Computer use CLI for AI agents
Rust accessibilityaccessibility-apiai-agentsautomationclicomputer-usecomputer-use-agentcomputer-use-agentsdesktop-automationmacosmcprust
docs: add platform crate folder structure convention and track plans
Lahfir775892ee8e6d
diff --git a/.gitignore b/.gitignoreindex 24c23ada4..524be7ace 100644--- a/.gitignore+++ b/.gitignore@@ -62,7 +62,9 @@ dist/*.rpm*.snap-# Compound Engineering-docs/+# Compound Engineering (ignore auto-generated, keep plans/brainstorms)+docs/*+!docs/plans/+!docs/brainstorms/todos/.cursor/\ No newline at end of filediff --git a/CLAUDE.md b/CLAUDE.mdindex cd78d4ef3..948bd7ad0 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -145,6 +145,48 @@ PLATFORM_NOT_SUPPORTED, TIMEOUT, INVALID_ARGS, INTERNAL| CLI flags | kebab-case | `--max-depth`, `--include-bounds` || Ref IDs | `@e{n}` sequential | `@e1`, `@e2`, `@e14` |+### Platform Crate Folder Structure++All platform crates (`macos`, `windows`, `linux`) follow an identical subfolder layout. New files must be placed in the correct subfolder.++```+crates/{macos,windows,linux}/src/+├── lib.rs # mod declarations + re-exports only+├── adapter.rs # PlatformAdapter trait impl (~175 LOC)+├── tree/ # Reading & understanding the UI+│ ├── mod.rs # re-exports+│ ├── element.rs # AXElement struct + attribute readers+│ ├── builder.rs # build_subtree, tree traversal+│ ├── roles.rs # Role mapping+│ ├── resolve.rs # Element re-identification+│ └── surfaces.rs # Surface detection+├── actions/ # Interacting with elements+│ ├── mod.rs # re-exports+│ ├── dispatch.rs # perform_action match arms+│ ├── activate.rs # Smart AX-first activation chain+│ └── extras.rs # select_value, ax_scroll+├── input/ # Low-level OS input synthesis+│ ├── mod.rs # re-exports+│ ├── keyboard.rs # Key synthesis, text typing+│ ├── mouse.rs # Mouse events+│ └── clipboard.rs # Clipboard get/set+└── system/ # App lifecycle, windows, permissions+ ├── mod.rs # re-exports+ ├── app_ops.rs # launch, close, focus+ ├── window_ops.rs # window operations+ ├── key_dispatch.rs # app-targeted key press+ ├── permissions.rs # permission checks+ ├── screenshot.rs # screen capture+ └── wait.rs # wait utilities+```++**Placement rules:**+- Tree reading/traversal/resolution → `tree/`+- Element interaction/activation → `actions/`+- Raw OS input (keyboard, mouse, clipboard) → `input/`+- App lifecycle, windows, permissions, screenshots → `system/`+- `adapter.rs` stays at root — it's the PlatformAdapter impl that wires everything together+### Extensibility PatternAdding a new command requires exactly these steps:@@ -243,9 +285,9 @@ pub trait PlatformAdapter: Send + Sync {### Tree Traversal- Entry: `AXUIElementCreateApplication(pid)` for app root-- Children: `kAXChildrenAttribute` recursively with visited-set to prevent cycles+- Children: `kAXChildrenAttribute` recursively with **ancestor-path set** (not global visited set — macOS reuses AXUIElementRef pointers across sibling branches)- **Use `AXUIElementCopyMultipleAttributeValues`** for batch attribute fetch (3-5x faster)-- Role mapping: AXRole strings → unified role enum in `roles.rs`+- Role mapping: AXRole strings → unified role enum in `tree/roles.rs`- Max depth default: 10. Configurable via `--max-depth`### Action Executiondiff --git a/docs/brainstorms/2026-02-19-ax-tree-accuracy-speed-brainstorm.md b/docs/brainstorms/2026-02-19-ax-tree-accuracy-speed-brainstorm.mdnew file mode 100644index 000000000..083cd4408--- /dev/null+++ b/docs/brainstorms/2026-02-19-ax-tree-accuracy-speed-brainstorm.md@@ -0,0 +1,176 @@+---+date: 2026-02-19+topic: ax-tree-accuracy-speed+---++# AX Tree Accuracy & Speed: First-Principles Fix++## What We're Building++A corrected, fast accessibility tree traversal engine that returns complete, readable node data+on every call. The current implementation has two compounding bugs that make the tool nearly+useless in practice: node names are missing for most elements, and traversal is 4–5 seconds+for a medium-sized UI.++---++## Root Cause Diagnosis++### Bug 1 — Empty names++`fetch_node_attrs` tries `kAXTitleAttribute` then `kAXDescriptionAttribute` and calls it done.++The macOS AX tree does **not** guarantee that either attribute carries the visible label text.+For the vast majority of real-world controls:++| Element type | Where the label actually lives |+|---|---|+| `AXOutlineRow` (Finder sidebar) | `kAXTitleAttribute` ← **should work**, but our batch parse drops it |+| `AXRow` (Finder column browser) | child `AXCell` → child `AXStaticText` → `kAXValueAttribute` |+| `AXButton` with image only | `kAXDescriptionAttribute` |+| `AXTextField` | `kAXPlaceholderValueAttribute` if empty, else `kAXValueAttribute` |+| `AXStaticText` | `kAXValueAttribute` (not title!) |+| `AXMenuItem` | `kAXTitleAttribute` |++The batch fetch uses `AXUIElementCopyMultipleAttributeValues`. The result is a `CFArray` of+`CFType` values. Our parsing calls `item.downcast::<CFString>()`. This is correct for string+attrs — but **boolean attrs** (`kAXEnabledAttribute`, `kAXFocusedAttribute`) are `CFBoolean`,+so they downcast to `None`. That's fine because we re-fetch them individually. But the real+problem is more subtle: **some elements return their string attrs as `CFString` subclasses+or as `AXTextMarker` types** that do not downcast to plain `CFString`. In those cases we get+`None` even when data is present.++The fix requires a multi-attribute fallback chain **plus** a child-text fallback.++### Bug 2 — Unknown roles++`roles.rs` maps ~22 role strings but the AX API has ~55. Anything not mapped becomes+`"unknown"`. In Finder's column browser, most elements are `AXBrowser`, `AXColumn`, `AXRow`+(table row variant), `AXLayoutItem` — all currently `"unknown"`. This makes the tree+unreadable and prevents `find --role` from working.++Unmapped roles in the existing codebase:+`AXBrowser`, `AXColumn`, `AXRow` (table row), `AXGrid`, `AXHandle`, `AXPopover`,+`AXDockItem`, `AXRuler`, `AXRulerMarker`, `AXTimeField`, `AXDateField`, `AXHelpTag`,+`AXMatte`, `AXDrawer`, `AXLayoutArea`, `AXLayoutItem`, `AXLevelIndicator`,+`AXRelevanceIndicator`, `AXSearchField` (already covered by textfield but missing as alias),+`AXSwitch`, `AXMenuButton`.++### Bug 3 — Speed++Every node requires 2–4 round-trips across the Mach IPC boundary:+1. `AXUIElementCopyMultipleAttributeValues` — 1 call for 6 attrs+2. `copy_children` tries up to 3 attr fetches (`kAXChildren`, `kAXContents`,+ `AXChildrenInNavigationOrder`) even when the first one succeeds++Each Mach IPC call costs ~1–5 ms. A 150-node tree = 300–600 round-trips = 2–5 seconds.++The fix is: stop on first successful children attribute, and batch-fetch **more** useful attrs+in the single `AXUIElementCopyMultipleAttributeValues` call so we never need per-attr fallback+calls for the common case.++### Non-bug: `-i` flag++Already implemented. `#[arg(long, short = 'i')]` on `interactive_only`. Works as+`agent-desktop snapshot -i`. The long form is `--interactive-only`, not `--interactive`.+We should add an alias `--interactive` to match user expectation.++---++## Approach A: Fix name resolution with fallback chain (Recommended)++**What it is:** Extend `fetch_node_attrs` to try 5 name sources in order, including+reading the first `AXStaticText` child. Expand `roles.rs` to cover all standard AX roles.+Stop `copy_children` on first non-empty result. Add `--interactive` as alias.++**Pros:**+- Targets the exact root cause. Minimal code change.+- No architecture change — same `build_subtree` recursion.+- Risk is low. Every change is additive.++**Cons:**+- The child-text fallback adds 1 extra IPC call per node that has no direct name.+ For nodes that DO have `kAXTitleAttribute`, this extra call is skipped.++**Speed estimate:** ~2x improvement from stopping children fetch early.+Name accuracy: ~95% of real apps will have readable names.++---++## Approach B: Batch all attrs including children in one call++**What it is:** Use `AXUIElementCopyMultipleAttributeValues` to fetch role, subrole, title,+description, value, placeholder, help, enabled, focused, selected, expanded, children — all+in a single call. Parse `CFBoolean` and `CFArray` correctly alongside `CFString`.++**Pros:**+- Reduces per-node IPC calls from 2–4 down to 1.+- Could bring 150-node tree from 4s down to <1s.++**Cons:**+- Requires correctly parsing mixed-type `CFArray` results (CFString, CFBoolean, CFArray).+- `AXUIElementCopyMultipleAttributeValues` doesn't support fetching array attrs+ (kAXChildren) — children still need a separate call.+- Higher implementation risk; the CF type introspection is fragile.++---++## Approach C: AXUIElementCopyAttributeNames + full dynamic attribute dump++**What it is:** For each node, first call `AXUIElementCopyAttributeNames` to get the list of+all attributes the element supports, then batch-fetch only those. This is what macOS+Accessibility Inspector does internally.++**Pros:**+- Most complete and accurate — never misses a custom attribute.+- Would fully expose Electron app data, web areas, custom controls.++**Cons:**+- Doubles the IPC calls per node (one for names, one for values).+- Much slower than Approach A or B for the common case.+- Over-engineered for Phase 1.++---++## Why Approach A, then B incrementally++Start with A because it fixes the accuracy problem with minimal risk and gives us a working,+readable tree. Then layer in B's batch parsing improvements as a separate optimization pass+once the output is verified correct.++The correctness of the tree is more valuable right now than raw speed. A 2-second tree with+readable names beats a 0.5-second tree of `"unknown"` nodes.++---++## Key Decisions++- **Name fallback chain**: `kAXTitleAttribute` → `kAXDescriptionAttribute` →+ `kAXValueAttribute` → first AXStaticText child's `kAXValueAttribute` →+ `kAXPlaceholderValueAttribute`+- **Expand roles.rs**: Add all ~33 missing role mappings from `role_constants.rs`+- **Add subrole field**: Include `kAXSubroleAttribute` in output so agents can distinguish+ `AXOutlineRow` vs `AXTableRow` vs plain `AXRow`+- **children fetch**: Break on first non-empty result (already partially there, needs+ confirmation that `kAXChildrenAttribute` wins 99% of the time and others are rarely needed)+- **`--interactive` alias**: Add alongside existing `--interactive-only` and `-i`+- **Test harness**: Write a Rust integration test that snapshots Finder and asserts:+ - ≥10 nodes have non-empty names+ - Zero nodes have role `"unknown"`+ - Total time < 3 seconds++---++## Open Questions++- Do we want to include `kAXSubrole` in the JSON output, or keep the schema flat?+- Should we emit a `label` field (the human-readable role description) separately from `role`?+- For Finder's column browser specifically: are file rows exposed as `AXRow` children of+ `AXColumn` children of `AXBrowser`? Need to confirm with a debug attr-dump.+- Should `find` command also search `value` field, not just `name`?++---++## Next Steps++→ `/workflows:plan` to break this into implementation tasksdiff --git a/docs/plans/2026-02-19-feat-context-menu-popup-ax-handling-plan.md b/docs/plans/2026-02-19-feat-context-menu-popup-ax-handling-plan.mdnew file mode 100644index 000000000..4ad80e3df--- /dev/null+++ b/docs/plans/2026-02-19-feat-context-menu-popup-ax-handling-plan.md@@ -0,0 +1,260 @@+---+title: "feat: Context Menu, Popup, and Overlay Handling via Accessibility APIs"+type: feat+date: 2026-02-19+---++# feat: Context Menu, Popup, and Overlay Handling via Accessibility APIs++## Overview++Context menus, sheets, dialogs, and popovers are transient surfaces that appear and disappear outside the normal window hierarchy. The current `snapshot` command misses them entirely because `list_windows` filters `kCGWindowLayer != 0` and `window_element_for` only queries `kAXWindowsAttribute`. This plan introduces targeted surface commands that read exactly the live transient surface — no full-tree traversal required.++## Problem Statement++1. **Context menus are invisible to snapshot.** Right-clicking in any app opens a menu at CG layer 8. `list_windows` rejects all `layer != 0` entries. `AXWindowsAttribute` does not include menus. An agent cannot read what is in the menu.++2. **Sheets and dialogs are not distinguished.** Save dialogs, alert panels, and popovers appear as children of windows but are not surfaced as distinct snapshot targets. An agent cannot tell if a modal is blocking interaction.++3. **No way to wait for a menu or popup.** `wait --element` polls the ref tree. There is no primitive to block until a context menu opens or a sheet appears.++4. **Comment noise.** Inline comments throughout the macOS crate explain implementation details that should be self-evident from names.++## Key Research Findings++### How macOS exposes transient surfaces via AX++| Surface | AX API | Notes |+|---------|--------|-------|+| Context menu (open) | `AXUIElementCopyAttributeValue(app, "AXMenus", …)` | Returns array of open `AXMenu` elements. Empty when closed. O(1) — no tree scan. |+| Context menu (notification) | `kAXMenuOpenedNotification` on the app element | Delivers the menu AXElement directly. |+| Focused window's sheet/dialog | `kAXFocusedWindowAttribute` on app element | Returns whatever window (or sheet) currently has focus. |+| Sheet attached to a window | Child with `AXSubrole == "AXSheet"` | Always a child of the parent window. |+| Alert/dialog | `kAXSubrole == "AXDialog"` or `kAXModalAttribute == true` | System alerts use subrole; app dialogs may use modal attribute. |+| Popover | `kAXSubrole == "AXPopover"` | Floats above the window hierarchy. |++### CG window layers (for reference, not for menu detection)++| Layer | Surface |+|-------|---------|+| 0 | Normal windows |+| 3 | Panels / popovers |+| 8 | Context menus |+| 20 | Alerts |++Using CG layers to find menus requires cross-referencing PID and is slower than reading `"AXMenus"` directly.++### `AXUIElementCreateSystemWide()`++Returns the system-wide accessibility element. `kAXFocusedApplicationAttribute` on it yields the currently focused app element. Useful when the caller has not already identified the target PID.++## Proposed Solution++### Phase 1 — `snapshot --surface` flag (new surface targeting)++Extend `SnapshotArgs` with `--surface <surface>` (default: `window`).++| `--surface` value | What is captured | Implementation |+|-------------------|-----------------|----------------|+| `window` | Current focused window (existing behavior) | unchanged |+| `focused` | Whatever `kAXFocusedWindowAttribute` returns (window, sheet, or dialog) | single AX attribute read, then build_subtree on result |+| `menu` | Open context menu on the target app | read `"AXMenus"` attribute on app element; error if no open menu |+| `sheet` | Sheet attached to focused window | walk `kAXChildrenAttribute` of focused window, find first `AXSubrole == "AXSheet"` |+| `popover` | Floating popover | walk children for `AXSubrole == "AXPopover"` |+| `alert` | Modal alert/dialog | walk children for `kAXModalAttribute == true` or `AXSubrole == "AXDialog"` |++All surfaces build their subtree with the existing `build_subtree` function. No new traversal logic needed.++### Phase 2 — `wait --menu` and `wait --popup`++Extend the `wait` command with surface-aware variants that use `AXObserver` notifications rather than polling:++| Flag | Notification | Timeout behavior |+|------|-------------|-----------------|+| `wait --menu` | `kAXMenuOpenedNotification` on app element | error `TIMEOUT` if menu does not appear within `--timeout` ms |+| `wait --menu-closed` | `kAXMenuClosedNotification` | waits until menu dismisses |+| `wait --popup` | poll `"AXMenus"` or watch for `AXSubrole==AXPopover` child | polling fallback (250ms interval) |++`AXObserver` requires a `CFRunLoop`. The implementation spins a dedicated thread, runs the loop for the duration of the timeout, then shuts it down. This is safe for single-shot CLI use — no persistent daemon needed in Phase 1.++### Phase 3 — `list-surfaces` command++Enumerate all currently visible transient surfaces for a given app:++```json+{+ "surfaces": [+ { "type": "menu", "title": "Edit", "item_count": 12 },+ { "type": "sheet", "title": "Save", "ref": "@e1" }+ ]+}+```++Implemented by reading `"AXMenus"`, inspecting `kAXFocusedWindowAttribute` children for sheets/popovers/dialogs, and returning a flat list. No tree traversal.++### Phase 4 — Comment cleanup++Remove all inline `//` comments from macOS crate files. Retain `///` doc-comments on public items where the function name alone is insufficient.++Files to clean: `tree.rs`, `adapter.rs`, `actions.rs`, `screenshot.rs`, `app_ops.rs`, `input.rs`, `roles.rs`, `permissions.rs`.++## Implementation Plan++### Step 1: Add `--surface` to `SnapshotArgs`++**File:** `src/cli.rs`++```rust+#[derive(clap::ValueEnum, Clone, Debug, Default)]+pub enum Surface {+ #[default]+ Window,+ Focused,+ Menu,+ Sheet,+ Popover,+ Alert,+}++// In SnapshotArgs:+#[arg(long, value_enum, default_value_t = Surface::Window)]+pub surface: Surface,+```++**File:** `crates/core/src/adapter.rs` — extend `ScreenshotTarget` analog with a `SnapshotSurface` enum mirroring the CLI enum.++### Step 2: Surface resolution in macOS adapter++**File:** `crates/macos/src/tree.rs` — add `menu_element_for_pid`, `focused_surface_for_pid`, `sheet_for_window`:++```rust+/// Returns the first open context menu element for the given PID, if any.+pub fn menu_element_for_pid(pid: i32) -> Option<AXElement> { … }++/// Returns whatever kAXFocusedWindowAttribute points to (window, sheet, or dialog).+pub fn focused_surface_for_pid(pid: i32) -> Option<AXElement> { … }++/// Returns the first AXSheet child of the given window element.+pub fn sheet_for_window(win: &AXElement) -> Option<AXElement> { … }+```++These are all single attribute reads — O(1) AX calls before any tree traversal begins.++**File:** `crates/macos/src/adapter.rs` — update `get_tree` to dispatch on `SnapshotSurface`:++```rust+fn get_tree(&self, win: &WindowInfo, opts: &TreeOptions) -> Result<AccessibilityNode, AdapterError> {+ let el = match opts.surface {+ SnapshotSurface::Window => crate::tree::window_element_for(win.pid, &win.title),+ SnapshotSurface::Focused => crate::tree::focused_surface_for_pid(win.pid)+ .ok_or_else(|| AdapterError::internal("no focused surface"))?,+ SnapshotSurface::Menu => crate::tree::menu_element_for_pid(win.pid)+ .ok_or_else(|| AdapterError::not_found("no open context menu"))?,+ SnapshotSurface::Sheet => { … }+ SnapshotSurface::Popover => { … }+ SnapshotSurface::Alert => { … }+ };+ let mut visited = FxHashSet::default();+ crate::tree::build_subtree(&el, 0, opts.max_depth, opts.include_bounds, &mut visited)+ .ok_or_else(|| AdapterError::internal("empty tree"))+}+```++### Step 3: `wait --menu` via AXObserver++**File:** `crates/macos/src/wait.rs` (new file, ≤ 150 LOC)++```rust+/// Blocks until a context menu opens on the given PID or the timeout elapses.+pub fn wait_for_menu(pid: i32, timeout_ms: u64) -> Result<(), AdapterError> { … }++/// Blocks until the context menu on the given PID closes or the timeout elapses.+pub fn wait_for_menu_closed(pid: i32, timeout_ms: u64) -> Result<(), AdapterError> { … }+```++Implementation uses `AXObserverCreate`, `AXObserverAddNotification` with `kAXMenuOpenedNotification`/`kAXMenuClosedNotification`, then runs a `CFRunLoop` with a deadline timer on a dedicated thread. The main thread joins with the specified timeout.++**File:** `crates/macos/src/lib.rs` — `pub mod wait;`++### Step 4: Extend `WaitArgs` in CLI++**File:** `src/cli.rs`++```rust+/// Wait for a context menu to open (--menu) or close (--menu-closed)+#[arg(long)]+pub menu: bool,+#[arg(long)]+pub menu_closed: bool,+```++**File:** `crates/core/src/commands/wait.rs` — dispatch to `adapter.wait_for_surface(…)` with new `WaitSurface` enum.++### Step 5: `list-surfaces` command++**File:** `crates/core/src/commands/list_surfaces.rs`++```rust+pub struct ListSurfacesArgs {+ #[arg(long)]+ pub app: Option<String>,+}+```++Output:+```json+{+ "version": "1.0",+ "ok": true,+ "command": "list-surfaces",+ "data": {+ "surfaces": [+ { "type": "menu", "item_count": 8 },+ { "type": "sheet", "title": "Save" }+ ]+ }+}+```++### Step 6: Comment cleanup++Remove all inline `//` comments from `crates/macos/src/*.rs`. Rules:+- Delete comments that restate what the code does+- Delete comments that explain macOS constant values (constants are named)+- Keep `///` doc-comments on `pub` functions where the name alone is insufficient+- Keep `// SAFETY:` and `// kAX...` references where they provide non-obvious AX API context++## Acceptance Criteria++- [ ] `agent-desktop snapshot --app WhatsApp --surface menu` returns the open context menu tree within 0.5s (no full tree traversal)+- [ ] `agent-desktop snapshot --app Finder --surface sheet` returns the save sheet when one is open+- [ ] `agent-desktop snapshot --app Finder --surface focused` returns a focused dialog, sheet, or window — whichever has focus+- [ ] `agent-desktop wait --app TextEdit --menu --timeout 5000` blocks until a context menu opens and exits 0; exits with `TIMEOUT` error if none appears in 5s+- [ ] `agent-desktop list-surfaces --app Finder` lists all currently visible transient surfaces+- [ ] All existing 30 commands continue to pass+- [ ] No inline `//` comments remain in `crates/macos/src/`+- [ ] Snapshot of a context menu does NOT traverse the full app tree first+- [ ] `--surface menu` returns `APP_NOT_FOUND`-equivalent error (`ELEMENT_NOT_FOUND`) when no menu is open++## File Checklist++| File | Change |+|------|--------|+| `src/cli.rs` | Add `--surface`, `--menu`, `--menu-closed` args |+| `crates/core/src/adapter.rs` | Add `SnapshotSurface` enum to `TreeOptions`; add `wait_for_surface` trait method |+| `crates/core/src/commands/snapshot.rs` | Pass `surface` from args to `TreeOptions` |+| `crates/core/src/commands/wait.rs` | Add `WaitSurface` dispatch |+| `crates/core/src/commands/list_surfaces.rs` | New file |+| `crates/core/src/commands/mod.rs` | Register `list_surfaces` |+| `crates/macos/src/tree.rs` | Add `menu_element_for_pid`, `focused_surface_for_pid`, `sheet_for_window` |+| `crates/macos/src/adapter.rs` | Dispatch on `SnapshotSurface` in `get_tree`; implement `wait_for_surface` |+| `crates/macos/src/wait.rs` | New file — AXObserver-based surface waiting |+| `crates/macos/src/lib.rs` | `pub mod wait` |+| `crates/macos/src/*.rs` | Remove inline comments |++## Non-Goals++- Does NOT use `CGWindowListCreateImage` for menu capture (screenshot of a menu is separate from its AX tree)+- Does NOT implement persistent AXObserver across invocations (Phase 4 daemon scope)+- Does NOT handle Electron/custom-rendered menus that bypass the AX API+- Does NOT add Windows or Linux surface detection (Phase 2)diff --git a/docs/plans/2026-02-19-fix-bugs-add-missing-commands-plan.md b/docs/plans/2026-02-19-fix-bugs-add-missing-commands-plan.mdnew file mode 100644index 000000000..41c5470ea--- /dev/null+++ b/docs/plans/2026-02-19-fix-bugs-add-missing-commands-plan.md@@ -0,0 +1,987 @@+---+title: "fix: Phase 1 bug fixes, AX-first execution, missing commands, adapter-ready architecture"+type: fix+date: 2026-02-19+deepened: 2026-02-19+---++# fix: Phase 1 Bug Fixes + AX-First Execution + Missing Commands + Adapter-Ready Architecture++## Enhancement Summary++**Deepened on:** 2026-02-19+**Plans merged:** `fix-bugs-add-missing-commands-plan.md` + `fix-subtree-traversal-error-dedup-ax-only-plan.md`+**Research agents used:** AX-only execution, select semantics, agent-browser gap analysis, sub-window tree traversal, stderr duplication, cross-platform adapter design, drag-and-drop feasibility++### Key Improvements Over Original Plan+1. **AX-first philosophy**: Every command uses Accessibility API as primary execution path. CGEvent/osascript kept ONLY for operations with no AX equivalent (drag, hover, modified key combos without menu bar entries)+2. **Corrected root causes**: Stderr duplication is NOT a code bug (removed from plan). Sub-window tree fix is a ONE-LINE change in `list_windows_impl`, not `window_element_for`+3. **Role-aware `select`**: Branches by AX role — AXPopUpButton (press→menu→press item), AXComboBox (set kAXValueAttribute), AXList/AXTable (set kAXSelectedChildrenAttribute)+4. **New commands from agent-browser gap analysis**: `check`/`uncheck` (idempotent), `scroll-to`, `wait --text`, `find` enhancements (`--count`, `--first`, `--nth`), `hover`, `drag`+5. **Adapter extensibility**: Flat `#[non_exhaustive]` Action enum, WindowOp enum, MouseEvent struct, single `mouse_event` method++### AX-First Principle++> Every command MUST use the Accessibility API as its primary execution mechanism. CGEvent mouse/keyboard synthesis and osascript are NEVER the primary path. They are kept ONLY as documented fallbacks for operations that have no AX equivalent (drag, hover, arbitrary screen-coordinate clicks, modified key combos not in any menu bar).++**AX-Only Commands** (no CGEvent/osascript at all):+- `click`, `right-click`, `toggle`, `select`, `expand`, `collapse`, `set-value`, `focus`, `type` (via kAXValueAttribute)+- `focus-window` (via kAXMainAttribute + kAXRaiseAction)+- `close-app` graceful (via AX menu bar "Quit" item or kAXCloseButtonAttribute)+- `press` for Return/Escape/Space (via kAXConfirmAction/kAXCancelAction/kAXPressAction)+- `press` for cmd+shortcuts (via AX menu bar traversal matching kAXMenuItemCmdChar)+- `scroll` (via AXScrollBar kAXIncrementAction/kAXDecrementAction)+- `check`/`uncheck` (via kAXValueAttribute set on checkbox/switch)+- Window geometry: `resize-window`, `move-window`, `minimize`, `maximize`, `restore`++**Hybrid Commands** (AX resolve coordinates → CGEvent execute):+- `drag` — AX resolves element bounds, CGEvent performs LeftMouseDown→Dragged→Up+- `hover` — AX resolves bounds, CGEvent MouseMoved (tooltips require real cursor movement)+- `mouse-move`, `mouse-click`, `mouse-down`, `mouse-up` — coordinate-based, CGEvent only++**CGEvent-Only Commands** (no AX equivalent exists):+- `key-down`/`key-up` — holding modifier keys has no AX equivalent+- `press` for arbitrary key combos not in menu bar (e.g., `f5`, `ctrl+left`) — falls back to `AXUIElementPostKeyboardEvent`, then returns `ACTION_NOT_SUPPORTED` if both fail++---++## Phase A: Critical Bug Fixes (P0 + P1)++### A1. Fix sub-window tree missing elements++**Problem:** `snapshot --app "System Settings"` only captures the sidebar; the content pane is never reached.++**Root Cause (CORRECTED from original plan):** The bug is NOT in `window_element_for` or `build_subtree`. It's in `list_windows_impl` in `crates/macos/src/adapter.rs`. The CGWindow enumeration filters out windows with empty `kCGWindowName` via a `_ => continue` match arm. System Settings has a window whose CGWindow title is empty, so it's silently skipped. The content pane is NOT a separate AXWindow — it's inside a single AXSplitGroup within the one AXWindow, and `build_subtree` already recurses `kAXChildrenAttribute`, so it would find the content pane IF the window weren't filtered out.++**Files:** `crates/macos/src/adapter.rs`++**Fix:** ONE-LINE change in `list_windows_impl`:+```rust+// BEFORE (adapter.rs, inside the CGWindow title match):+_ => continue,++// AFTER:+_ => app_name.clone(),+```++When `kCGWindowName` is empty or missing, use the application name as fallback instead of skipping the window entirely. This ensures System Settings' content pane window (and similar empty-titled windows in other apps) appears in the window list and gets traversed.++**Verification:** `agent-desktop snapshot --app "System Settings"` returns both sidebar AND content pane elements (AXOutline + content controls like AXCheckBox, AXPopUpButton, etc.)++### A2. Fix `select` false success (P0)++**Problem:** `select @e4 "Courier"` returns `ok:true` but value stays "Helvetica".++**Root cause:** `actions.rs` maps `Action::Select` to a bare `kAXPressAction` click — it just clicks the element instead of performing role-aware selection.++**Files:** `crates/macos/src/actions.rs`++**Critical insight from research:** Popup menu children DON'T EXIST in the AX tree until the menu is physically opened. You cannot query kAXChildrenAttribute on a closed AXPopUpButton to enumerate its options. The `select` command's purpose is to SET a value when the caller already knows what value they want. Option DISCOVERY uses a different workflow: `click @popup` → `snapshot` → see menu items → `click @menuitem`.++**Fix — role-aware branching:**++1. **AXPopUpButton** (dropdown menus):+ - `AXUIElementPerformAction(kAXPressAction)` to open the menu+ - Wait up to 500ms for menu to appear (poll kAXChildrenAttribute on the popup)+ - Walk menu children, find `AXMenuItem` whose `kAXTitleAttribute` matches the target value (case-insensitive, trimmed)+ - `AXUIElementPerformAction(kAXPressAction)` on the matched menu item+ - If no match found: press Escape to close menu, return `ELEMENT_NOT_FOUND` with suggestion listing available options+ - Read back `kAXValueAttribute` to confirm change, include in `post_state`++2. **AXComboBox** (editable dropdowns):+ - `AXUIElementSetAttributeValue(kAXValueAttribute, value)` directly+ - Read back to confirm, include in `post_state`++3. **AXList / AXTable** (list selections):+ - Find child element matching `value` by name+ - `AXUIElementSetAttributeValue(kAXSelectedChildrenAttribute, [matched_child])`+ - Read back to confirm++4. **Any other role**: Return `ACTION_NOT_SUPPORTED` with suggestion: "Element role '{role}' doesn't support select. Use 'click' or 'set-value' instead."++### A3. Fix `toggle` false success (P0)++**Problem:** `toggle @e1` on a textfield returns `ok:true` with no effect.++**Root cause:** `actions.rs` maps `Action::Toggle` to `kAXPressAction` unconditionally — no role check.++**Files:** `crates/macos/src/actions.rs`, `crates/core/src/commands/toggle.rs`++**Fix:**+- Before executing, check element role from RefEntry+- Supported roles: `checkbox`, `switch`, `radiobutton`, `togglebutton`, `menuitemcheckbox`, `menuitemradio`+- For supported roles: `AXUIElementPerformAction(kAXPressAction)`, then read back `kAXValueAttribute` to confirm state changed+- For unsupported roles: return `ACTION_NOT_SUPPORTED` with suggestion: "Toggle only works on checkboxes, switches, and radio buttons. Use 'click' for other elements."++### A4. Fix `launch` window detection (P1)++**Problem:** `launch Calculator` returns error "no window found" even though the app launched fine.++**Root cause:** `app_ops.rs::launch_app_impl` non-wait path only sleeps 500ms. Many apps need 2-5s for window.++**Files:** `crates/macos/src/app_ops.rs`++**Fix:**+- Default behavior: poll `list_windows()` every 200ms for up to 5s (matching the wait path's pattern)+- When the app process exists but no window: return success with `"window": null` and `"note": "App launched but no window detected yet. Use 'wait --window' to poll."`+- Only return error if the `open -a` command itself fails (non-zero exit code)++### A5. Fix `close-app` not actually closing (P1)++**Problem:** `close-app Calculator` returns `ok:true` but app keeps running.++**Root cause:** The graceful quit via osascript doesn't verify termination.++**Files:** `crates/macos/src/app_ops.rs`++**Fix (AX-first):**+- **Primary:** Find "Quit" menu item via AX menu bar traversal (`kAXMenuBarAttribute` → last `AXMenuBarItem` → walk `AXMenuItem` children → find item with title containing "Quit"), then `kAXPressAction` on it+- **Fallback:** If no menu bar accessible, use `AXUIElementSetAttributeValue(kAXHiddenAttribute)` or the existing osascript quit+- After sending quit, poll `list_apps()` every 200ms for up to 3s to verify app exited+- If still running after timeout: return `{ "ok": true, "data": { "closed": false, "note": "Quit requested but app may still be running. Use --force to kill." } }`++### A6. Fix `expand`/`collapse` wrong error code (P1)++**Problem:** Returns `ACTION_FAILED` with raw AX error code (-25205) instead of `ACTION_NOT_SUPPORTED`.++**Files:** `crates/macos/src/actions.rs`++**Fix:**+- Before attempting `AXExpand`/`AXCollapse`, call `AXUIElementCopyActionNames` and check if the action string exists+- If not present: return `AdapterError::new(ErrorCode::ActionNotSupported, "This element doesn't support expand/collapse").with_suggestion("Try 'click' to open it instead.")`+- If present but fails: keep `ACTION_FAILED` with the AX error detail++### A7. Fix `get --property bounds` returning null++**Problem:** `get @e1 --property bounds` returns `null` even though element has screen position.++**Files:** `crates/core/src/commands/get.rs`, `crates/macos/src/adapter.rs`++**Fix:**+- `get bounds` should resolve the element handle via `resolve_element`, then query `kAXPositionAttribute` + `kAXSizeAttribute` LIVE from the AX tree+- Don't rely on RefEntry's cached bounds — query the adapter directly+- Add `get_element_bounds(handle: &NativeHandle) -> Result<Option<Rect>>` to PlatformAdapter trait (with default `not_supported()`)+- macOS impl queries `AXUIElementCopyAttributeValue` for position and size++### A8. Fix `focus-window` to use AX instead of osascript++**Problem:** `focus_window_impl` uses `osascript` → `tell application X to activate`.++**Files:** `crates/macos/src/app_ops.rs`++**Fix (AX-first):**+- Get AXApplication element for the target PID+- `AXUIElementSetAttributeValue(appEl, kAXFrontmostAttribute, kCFBooleanTrue)` to bring app to front+- Get the target window element+- `AXUIElementSetAttributeValue(winEl, kAXMainAttribute, kCFBooleanTrue)` to make it the main window+- `AXUIElementPerformAction(winEl, kAXRaiseAction)` to raise it+- Remove osascript path entirely++### A9. Replace CGEvent fallbacks in action execution++**Problem:** `click`, `right-click`, `toggle`, `select` all fall back to `cg_mouse_click` CGEvent synthesis when AX action fails.++**Files:** `crates/macos/src/actions.rs`++**Fix:**+- **`Action::Click`**: `kAXPressAction` only. If AX error, propagate `ACTION_FAILED` (no CGEvent fallback)+- **`Action::RightClick`**: `AXShowMenu` only. Remove CGEvent fallback. Already implemented correctly; just delete the fallback branch+- **`Action::DoubleClick`**: Try `AXOpen` first. If unsupported, `kAXPressAction` twice with 50ms sleep between. If still fails, return `ACTION_FAILED`+- **`Action::Toggle`**: `kAXPressAction` only after role validation (A3). Remove CGEvent fallback+- **`Action::Select`**: Role-aware AX implementation (A2). Remove CGEvent fallback+- **`Action::Scroll`**: Replace `CGEvent::new_scroll_event` with AX scroll (see A10)+- Remove `cg_mouse_click` helper function entirely from `actions.rs`+- Remove CGEvent mouse imports from `actions.rs`++### A10. Replace CGEvent scroll with AX scroll++**Problem:** `Action::Scroll` uses `CGEvent::new_scroll_event` (HID injection).++**Files:** `crates/macos/src/actions.rs`++**Fix:**+- Find the `AXScrollArea` or `AXScrollBar` associated with the target element+- For vertical scroll: find the vertical `AXScrollBar` child, then:+ - Scroll down: `AXUIElementPerformAction(scrollBar, kAXIncrementAction)` repeated `amount` times+ - Scroll up: `AXUIElementPerformAction(scrollBar, kAXDecrementAction)` repeated `amount` times+- For horizontal: same with horizontal `AXScrollBar` and corresponding actions+- If no scroll bar found: return `ACTION_NOT_SUPPORTED` with suggestion "Element is not scrollable"+- Remove `CGEvent::new_scroll_event` import and usage++### A11. Replace CGEvent keyboard input with AX equivalents++**Problem:** `Action::TypeText` uses `synthesize_text` (CGEvent keyboard per character). `Action::PressKey` uses `synthesize_key` (CGEvent keyboard).++**Files:** `crates/macos/src/actions.rs`, `crates/macos/src/input.rs`++**Fix for TypeText (AX-first):**+- Set `kAXFocusedAttribute = true` on target element+- Read current `kAXValueAttribute`+- `AXUIElementSetAttributeValue(kAXValueAttribute, newText)` — this replaces the full value+- For append semantics: read current value, concatenate, set combined value+- The `type` command already has this distinction: if ref provided, set value on ref. If no ref, this is a "type into focused element" which still needs kAXValueAttribute set on the focused element++**Fix for PressKey (AX-first, multi-strategy):**+1. **Simple keys → AX actions on focused element:**+ - `return`/`enter` → `kAXConfirmAction`+ - `escape`/`esc` → `kAXCancelAction`+ - `space` → `kAXPressAction`+ - `tab` → `kAXNextContentsAction` or move focus+ - Arrow keys on sliders → `kAXIncrementAction` / `kAXDecrementAction`++2. **Modifier combos → AX menu bar traversal:**+ - Get `kAXMenuBarAttribute` from app element+ - Walk `AXMenuBarItem` → expand each → walk `AXMenuItem` children+ - Match `kAXMenuItemCmdChar` (e.g., "C" for Cmd+C) and `kAXMenuItemCmdModifiers`+ - `kAXPressAction` on matched `AXMenuItem`++3. **Fallback for keys with no AX equivalent:**+ - `AXUIElementPostKeyboardEvent(appEl, 0, keyCode, true/false)` — this is technically AX API (not CGEvent), available in accessibility-sys+ - If that also fails: return `ACTION_NOT_SUPPORTED` with message: "No AX equivalent for key combo '{combo}'. This combo has no menu-bar action."++4. **Remove `synthesize_key` and `synthesize_text` from `input.rs`**+ - If `input.rs` becomes empty, delete it and remove from `lib.rs`++### A12. Replace osascript in `press_for_app_impl`++**Problem:** `press --app TextEdit "cmd+c"` uses osascript System Events `keystroke`/`key code`.++**Files:** `crates/macos/src/app_ops.rs`++**Fix (AX-first):**+- Activate target app via AX: `AXUIElementSetAttributeValue(appEl, kAXFrontmostAttribute, kCFBooleanTrue)`+- Use the same AX menu bar traversal strategy from A11 step 2+- If menu bar match found: `kAXPressAction` on the `AXMenuItem`+- If no match: `AXUIElementPostKeyboardEvent` fallback+- Remove osascript `keystroke`/`key code` path entirely++---++## Phase B: Improvements++### B1. Fix `list-apps` data shape + bundle_id++**Files:** `crates/core/src/commands/list_apps.rs`, `crates/macos/src/adapter.rs`++**Fix:**+- Wrap `data` in `{"apps": [...]}` instead of bare array+- Populate `bundle_id` using `kAXBundleIdentifierAttribute` on the AXApplication element (pure AX, no osascript)+- Add `bundle_id: Option<String>` to `AppInfo` struct if not already present++### B2. Fix `is` returning `false` vs "not applicable"++**Files:** `crates/core/src/commands/is_check.rs`++**Fix:**+- Return `{ "result": false, "applicable": false }` when querying a property that doesn't apply to the element's role+- Applicability rules:+ - `checked` → applies to: checkbox, switch, radiobutton, menuitemcheckbox+ - `expanded` → applies to: treeitem, combobox, disclosure, outlinerow+ - `focused` → applies to: ALL interactive roles+ - `visible` → applies to: ALL roles+ - `enabled` → applies to: ALL interactive roles++### B3. Add `--help` descriptions to all commands and flags++**Files:** `src/cli.rs`++**Fix:**+- Add `#[command(about = "...")]` to every `Commands` variant+- Add `#[arg(help = "...")]` to every flag+- Descriptions should be one-line, imperative mood, agent-oriented++### B4. Improve `find` output for unnamed elements++**Files:** `crates/core/src/commands/find.rs`++**Fix:**+- When `name` is null, fall back to `description`, then `title`, then `"(unnamed {role})"`+- Include `description` field in find results when available++### B5. Filter stale menu items from window snapshots++**Files:** `crates/macos/src/adapter.rs` or snapshot engine++**Fix:**+- In `snapshot --surface window`: filter out nodes with role `menuitem` or `menu` that are direct children of the app/window root (not nested inside actual window content)+- This handles the race condition where pressing escape doesn't immediately remove menu items from the AX tree++---++## Phase C: New Commands — Idempotent State Control++These commands address a critical gap: agents need idempotent state-setting, not just toggling.++### C1. `check` / `uncheck` commands++**Problem:** `toggle` is non-idempotent — calling it twice returns to original state. An agent that wants a checkbox ON must first query state, then conditionally toggle. `check` and `uncheck` are idempotent: `check` is always a no-op if already checked.++**CLI:**+```+agent-desktop check @e5+agent-desktop uncheck @e5+```++**Files:** `crates/core/src/commands/check.rs`, `crates/core/src/commands/uncheck.rs`++**New Action variants:** `Action::Check`, `Action::Uncheck`++**Implementation (macOS, AX-only):**+1. Resolve element, verify role is checkbox/switch/radiobutton/menuitemcheckbox+2. Read current `kAXValueAttribute` (0 = unchecked, 1 = checked)+3. For `check`: if already 1, return success with `"already_checked": true`. If 0, `kAXPressAction`+4. For `uncheck`: if already 0, return success with `"already_unchecked": true`. If 1, `kAXPressAction`+5. Read back value to confirm state change+6. For unsupported roles: return `ACTION_NOT_SUPPORTED`++**Cross-platform:** All platforms support querying checkbox state and pressing — this is pure AX.++### C2. `scroll-to` command (scroll element into view)++**CLI:**+```+agent-desktop scroll-to @e15+agent-desktop scroll-to @e15 --align top+```++**File:** `crates/core/src/commands/scroll_to.rs`++**Implementation (macOS, AX-only):**+1. Resolve target element+2. Query `kAXVisibleCharacterRangeAttribute` or check if element bounds are within scroll area visible rect+3. If not visible: find parent scroll area, use `AXUIElementPerformAction(kAXScrollToVisibleAction)` on the target element (this is a native AX action that scrolls the element into view)+4. If `kAXScrollToVisibleAction` not available: incrementally `kAXIncrementAction`/`kAXDecrementAction` on the scroll bar until element bounds are within viewport++**Cross-platform:** `kAXScrollToVisibleAction` is macOS. Windows has `IUIAutomationScrollItemPattern.ScrollIntoView()`. Linux AT-SPI has `scroll_to` in Component interface.++### C3. `wait --text` variant++**CLI:**+```+agent-desktop wait --text "Loading complete" --app TextEdit --timeout 5000+```++**File:** `crates/core/src/commands/wait.rs` (extend existing)++**Implementation:**+- Poll the app's AX tree every 200ms+- Search for any element whose `kAXValueAttribute` or `kAXTitleAttribute` or `kAXDescriptionAttribute` contains the target text (case-insensitive substring match)+- Return the matching element's ref when found+- Return `TIMEOUT` if not found within timeout++---++## Phase D: Enhanced `find` Command++### D1. `find --count` — return count only++**CLI:** `agent-desktop find --app TextEdit --role button --count`++**Output:** `{ "count": 3 }` instead of the full element list.++**File:** `crates/core/src/commands/find.rs`++### D2. `find --first` / `find --last` / `find --nth N`++**CLI:**+```+agent-desktop find --app TextEdit --role button --first+agent-desktop find --app TextEdit --role button --last+agent-desktop find --app TextEdit --role button --nth 2+```++**Output:** Single element instead of array.++**File:** `crates/core/src/commands/find.rs`++### D3. `find --text` — search by text content++**CLI:** `agent-desktop find --app TextEdit --text "Save"`++**Implementation:** Match against `name`, `value`, `title`, `description` attributes (any match counts).++**File:** `crates/core/src/commands/find.rs`++---++## Phase E: New Commands — Mouse & Coordinate Control++These commands require CGEvent synthesis because the Accessibility API has no concept of cursor movement or raw mouse events. They are the documented exceptions to the AX-first principle.++### New Supporting Types++```rust+pub struct Point {+ pub x: f64,+ pub y: f64,+}++pub enum MouseButton {+ Left,+ Right,+ Middle,+}++pub struct DragParams {+ pub from: Point,+ pub to: Point,+ pub duration_ms: Option<u64>,+ pub steps: Option<u32>,+}+```++### E1. `drag` command++**CLI:**+```+agent-desktop drag --from @e5 --to @e12+agent-desktop drag --from @e5 --to-xy 500,300+agent-desktop drag --from-xy 100,200 --to-xy 500,300+agent-desktop drag --from @e5 --to @e12 --duration 500+```++**File:** `crates/core/src/commands/drag.rs`++**Why CGEvent is required:** Pure AX drag is impossible on ALL three platforms. macOS has no `AXDragAction`. Windows `IDragPattern` is read-only (describes draggable state, doesn't perform drags). Linux AT-SPI has no drag interface.++**Implementation (macOS — hybrid AX+CGEvent):**+1. **AX phase:** Resolve source/target coordinates from refs (via `get_element_bounds`) or use raw `--xy` coordinates+2. **CGEvent phase:**+ - `CGEvent::new_mouse_event(LeftMouseDown, source_point)` → post+ - Sleep 50ms (initial hold for drag registration)+ - 10 intermediate `CGEvent::new_mouse_event(LeftMouseDragged, interpolated_point)` events, 8ms apart+ - `CGEvent::new_mouse_event(LeftMouseUp, target_point)` → post+ - Sleep 50ms (settle time for app to process drop)+3. **Total duration:** ~230ms default, configurable via `--duration`++**Cross-platform mapping:**+- macOS: CGEvent `LeftMouseDown` → `LeftMouseDragged` (N steps) → `LeftMouseUp`+- Windows: `SendInput` with `MOUSEEVENTF_LEFTDOWN` → `MOUSEEVENTF_MOVE` (N steps) → `MOUSEEVENTF_LEFTUP`+- Linux: `atspi_generate_mouse_event` with `b1p` → `abs` (N steps) → `b1r`++### E2. `hover` command++**CLI:**+```+agent-desktop hover @e5+agent-desktop hover --xy 500,300+agent-desktop hover @e5 --duration 1000+```++**File:** `crates/core/src/commands/hover.rs`++**Why CGEvent:** Tooltips and hover states require real cursor movement. `CGWarpMouseCursorPosition` is silent and won't trigger tooltips — must use `CGEvent::new_mouse_event(MouseMoved)`.++**Implementation (macOS):**+- Resolve target point (from ref bounds center or `--xy`)+- `CGEvent::new_mouse_event(MouseMoved, target_point)` → post+- If `--duration` specified, hold position for that time (cursor stays put naturally)++### E3. `mouse-down` / `mouse-up` commands++**CLI:**+```+agent-desktop mouse-down @e5 --button left+agent-desktop mouse-up --xy 500,300 --button left+```++**Files:** `crates/core/src/commands/mouse_down.rs`, `crates/core/src/commands/mouse_up.rs`++**Implementation:** Individual CGEvent mouseDown/mouseUp events. Essential for custom drag sequences and long-press patterns.++### E4. `mouse-move` command++**CLI:**+```+agent-desktop mouse-move --xy 500,300+agent-desktop mouse-move --relative -10,20+```++**File:** `crates/core/src/commands/mouse_move.rs`++**Implementation:** `CGEvent::new_mouse_event(MouseMoved)`. `--relative` uses delta from current cursor position (query via `CGEvent::location()`).++### E5. `mouse-click` command++**CLI:**+```+agent-desktop mouse-click --xy 500,300+agent-desktop mouse-click --xy 500,300 --button right --count 2+```++**File:** `crates/core/src/commands/mouse_click.rs`++**Implementation:** Click at absolute coordinates, bypassing ref system. Useful when AX tree doesn't expose an element (e.g., Calculator display, game UIs, custom-rendered views).++### E6. `triple-click` command++**CLI:** `agent-desktop triple-click @e1`++**File:** `crates/core/src/commands/triple_click.rs`++**Implementation:** AX-first attempt: three rapid `kAXPressAction` calls with 30ms sleep between. If that doesn't trigger line/paragraph selection, fall back to CGEvent triple-click at element center.++---++## Phase F: New Commands — Window Geometry++All window geometry commands are **pure AX** — no CGEvent or osascript needed.++### F1. `resize-window`++**CLI:** `agent-desktop resize-window --app TextEdit --width 800 --height 600`++**File:** `crates/core/src/commands/resize_window.rs`++**Implementation (macOS, AX-only):**+- Get window element for app+- `AXUIElementSetAttributeValue(winEl, kAXSizeAttribute, AXValueCreate(kAXValueCGSizeType, &CGSize { width, height }))`++### F2. `move-window`++**CLI:** `agent-desktop move-window --app TextEdit --x 100 --y 100`++**File:** `crates/core/src/commands/move_window.rs`++**Implementation (macOS, AX-only):**+- `AXUIElementSetAttributeValue(winEl, kAXPositionAttribute, AXValueCreate(kAXValueCGPointType, &CGPoint { x, y }))`++### F3. `minimize` / `maximize` / `restore`++**CLI:**+```+agent-desktop minimize --app TextEdit+agent-desktop maximize --app TextEdit+agent-desktop restore --app TextEdit+```++**Files:** `crates/core/src/commands/minimize.rs`, `crates/core/src/commands/maximize.rs`, `crates/core/src/commands/restore.rs`++**Implementation (macOS, AX-only):**+- Minimize: `AXUIElementSetAttributeValue(winEl, kAXMinimizedAttribute, kCFBooleanTrue)`+- Maximize: `AXUIElementPerformAction(zoomButton, kAXPressAction)` where zoomButton is from `kAXZoomButtonAttribute`+- Restore: `AXUIElementSetAttributeValue(winEl, kAXMinimizedAttribute, kCFBooleanFalse)` for minimized windows, `AXUIElementPerformAction(zoomButton, kAXPressAction)` for fullscreen++**Cross-platform:**+- Windows: `IUIAutomationTransformPattern.Move/Resize`, `IUIAutomationWindowPattern.SetWindowVisualState`+- Linux: `atspi_component_set_extents`, window manager D-Bus calls++---++## Phase G: New Commands — Keyboard++### G1. `key-down` / `key-up`++**CLI:**+```+agent-desktop key-down shift+agent-desktop key-up shift+```++**Files:** `crates/core/src/commands/key_down.rs`, `crates/core/src/commands/key_up.rs`++**Implementation:** `AXUIElementPostKeyboardEvent` with only the down or up flag. If that doesn't work for the key, fall back to `CGEventCreateKeyboardEvent` with only key-down or key-up. Essential for modifier-hold sequences (hold Shift while clicking multiple items).++### G2. `clear` command++**CLI:** `agent-desktop clear @e1`++**File:** `crates/core/src/commands/clear.rs`++**Implementation (AX-only):** `AXUIElementSetAttributeValue(el, kAXValueAttribute, "")`. Simple set-value to empty string.++### G3. `clipboard-clear`++**CLI:** `agent-desktop clipboard-clear`++**File:** `crates/core/src/commands/clipboard_clear.rs`++**Implementation (macOS):** `NSPasteboard.generalPasteboard.clearContents()` via Cocoa FFI.++---++## Phase H: Architecture — Adapter Extensibility++### H1. Make Action enum `#[non_exhaustive]`++**File:** `crates/core/src/action.rs`++```rust+#[non_exhaustive]+#[derive(Debug, Clone, Serialize, Deserialize)]+pub enum Action {+ Click,+ DoubleClick,+ RightClick,+ SetValue(String),+ SetFocus,+ Expand,+ Collapse,+ Select(String),+ Toggle,+ Scroll(Direction, u32),+ PressKey(KeyCombo),+ TypeText(String),+ Check,+ Uncheck,+ ScrollTo,+ Drag(DragParams),+ Hover,+}+```++Adding `#[non_exhaustive]` means platform adapters must have a `_ => Err(not_supported())` catch-all, which naturally handles new actions added in future phases.++### H2. WindowOp enum for window geometry++**File:** `crates/core/src/action.rs` (or new `crates/core/src/window_op.rs` if action.rs grows)++```rust+pub enum WindowOp {+ Resize { width: f64, height: f64 },+ Move { x: f64, y: f64 },+ Minimize,+ Maximize,+ Restore,+}+```++Single `window_op(&self, win: &WindowInfo, op: WindowOp)` method on PlatformAdapter instead of 5 separate methods.++### H3. MouseEvent struct for raw mouse control++**File:** `crates/core/src/action.rs` (or new `crates/core/src/mouse.rs`)++```rust+pub struct MouseEvent {+ pub kind: MouseEventKind,+ pub point: Point,+ pub button: MouseButton,+}++pub enum MouseEventKind {+ Move,+ Down,+ Up,+ Click { count: u32 },+}+```++Single `mouse_event(&self, event: MouseEvent)` method on PlatformAdapter. Handles `mouse-move`, `mouse-down`, `mouse-up`, `mouse-click`, and `hover` through one trait method.++### H4. Coordinate Resolution Helper++**File:** `crates/core/src/commands/coords.rs`++```rust+pub enum CoordSource {+ Ref(String),+ Absolute(Point),+}++pub fn resolve_coords(+ source: &CoordSource,+ adapter: &dyn PlatformAdapter,+) -> Result<Point, AppError> {+ match source {+ CoordSource::Ref(ref_id) => {+ let (entry, handle) = resolve_ref(ref_id, adapter)?;+ let bounds = adapter.get_element_bounds(&handle)?+ .ok_or(AppError::internal("Element has no bounds"))?;+ Ok(Point {+ x: bounds.x + bounds.width / 2.0,+ y: bounds.y + bounds.height / 2.0,+ })+ }+ CoordSource::Absolute(p) => Ok(p.clone()),+ }+}+```++Used by `drag`, `hover`, `mouse-move`, `mouse-click`, `mouse-down`, `mouse-up`. All coordinate-based commands resolve through the same path.++### H5. Action Pre-Check Pattern++**File:** `crates/core/src/commands/action_check.rs`++```rust+pub fn check_action_supported(+ entry: &RefEntry,+ required_roles: &[&str],+ action_name: &str,+ suggestion: &str,+) -> Result<(), AppError> {+ if !required_roles.contains(&entry.role.as_str()) {+ return Err(AppError::Adapter(AdapterError::new(+ ErrorCode::ActionNotSupported,+ format!("'{}' is not supported on role '{}'", action_name, entry.role),+ ).with_suggestion(suggestion)));+ }+ Ok(())+}+```++Used by `toggle`, `check`, `uncheck`, `expand`, `collapse`, `select` to validate role before attempting action.++### H6. Extended PlatformAdapter Trait++**File:** `crates/core/src/adapter.rs`++```rust+pub trait PlatformAdapter: Send + Sync {+ // --- Discovery ---+ fn list_windows(&self, filter: &WindowFilter) -> Result<Vec<WindowInfo>, AdapterError> { not_supported() }+ fn list_apps(&self) -> Result<Vec<AppInfo>, AdapterError> { not_supported() }+ fn get_tree(&self, win: &WindowInfo, opts: &TreeOptions) -> Result<AccessibilityNode, AdapterError> { not_supported() }+ fn resolve_element(&self, entry: &RefEntry) -> Result<NativeHandle, AdapterError> { not_supported() }+ fn check_permissions(&self) -> PermissionStatus { PermissionStatus::Unknown }++ // --- AX Actions (primary execution path) ---+ fn execute_action(&self, handle: &NativeHandle, action: Action) -> Result<ActionResult, AdapterError> { not_supported() }+ fn get_element_bounds(&self, handle: &NativeHandle) -> Result<Option<Rect>, AdapterError> { not_supported() }++ // --- Window Management ---+ fn focus_window(&self, win: &WindowInfo) -> Result<(), AdapterError> { not_supported() }+ fn window_op(&self, win: &WindowInfo, op: WindowOp) -> Result<(), AdapterError> { not_supported() }+ fn launch_app(&self, id: &str, wait: bool) -> Result<WindowInfo, AdapterError> { not_supported() }+ fn close_app(&self, id: &str, force: bool) -> Result<(), AdapterError> { not_supported() }++ // --- Mouse/Coordinate (CGEvent-based, documented exceptions) ---+ fn mouse_event(&self, event: MouseEvent) -> Result<(), AdapterError> { not_supported() }+ fn drag(&self, params: DragParams) -> Result<(), AdapterError> { not_supported() }++ // --- Media ---+ fn screenshot(&self, target: ScreenshotTarget) -> Result<ImageBuffer, AdapterError> { not_supported() }+ fn get_clipboard(&self) -> Result<String, AdapterError> { not_supported() }+ fn set_clipboard(&self, text: &str) -> Result<(), AdapterError> { not_supported() }+ fn clear_clipboard(&self) -> Result<(), AdapterError> { not_supported() }++ // --- App-Level Keyboard ---+ fn press_key_for_app(&self, app: &str, combo: &KeyCombo) -> Result<ActionResult, AdapterError> { not_supported() }+ fn focused_window(&self) -> Result<Option<WindowInfo>, AdapterError> { not_supported() }++ // --- Surface Management ---+ fn wait_for_menu(&self, pid: i32, open: bool, timeout: u64) -> Result<(), AdapterError> { not_supported() }+ fn list_surfaces(&self, pid: i32) -> Result<Vec<SurfaceInfo>, AdapterError> { not_supported() }+}+```++All methods default to `not_supported()`. Phase 2 Windows/Linux adapters implement what they can — everything else gracefully fails with `PLATFORM_NOT_SUPPORTED`.++---++## Implementation Order++### Sprint 1: Critical Bug Fixes — AX-First Foundation (2-3 days)++Priority: Stop commands from lying about success, fix the tree traversal.++1. **A1** — Sub-window tree fix (ONE LINE in `list_windows_impl`)+2. **A9** — Remove CGEvent fallbacks from click/right-click/toggle/select in `actions.rs`+3. **A2** — Role-aware `select` implementation+4. **A3** — Toggle role validation+5. **A6** — Expand/collapse error codes+6. **A10** — Replace CGEvent scroll with AX scroll bar increment/decrement+7. **B3** — Help descriptions (touches `cli.rs` only, low risk, high value)++**Verify:** `cargo clippy --all-targets -- -D warnings && cargo test --workspace`++### Sprint 2: AX-First Keyboard & Window (2-3 days)++Priority: Eliminate remaining osascript and CGEvent keyboard paths.++8. **A11** — Replace CGEvent keyboard with AX (TypeText via kAXValueAttribute, PressKey via menu bar traversal + AXUIElementPostKeyboardEvent)+9. **A12** — Replace osascript in `press_for_app_impl`+10. **A8** — Replace osascript in `focus_window_impl`+11. **A5** — Fix close-app with AX menu bar "Quit" + verification+12. **A4** — Fix launch window detection polling+13. **A7** — Fix get bounds returning null++**After this sprint:** `input.rs` functions `synthesize_key` and `synthesize_text` should be dead code. Remove them and potentially the file.++### Sprint 3: Improvements + New Idempotent Commands (1-2 days)++14. **B1** — list-apps data shape + bundle_id+15. **B2** — is false vs not-applicable+16. **B4** — find unnamed elements+17. **B5** — stale menu items in snapshots+18. **C1** — `check` / `uncheck` commands (AX-only)+19. **C2** — `scroll-to` command (AX-only)+20. **C3** — `wait --text` variant++### Sprint 4: Architecture + Find Enhancements (1-2 days)++21. **H1** — Make Action enum `#[non_exhaustive]`, add new variants+22. **H2** — WindowOp enum+23. **H3** — MouseEvent struct+24. **H4** — Coordinate resolution helper+25. **H5** — Action pre-check pattern+26. **H6** — Extend PlatformAdapter trait+27. **D1-D3** — find --count, --first/--last/--nth, --text++### Sprint 5: Mouse/Coordinate Commands (2-3 days)++28. **E4** — mouse-move+29. **E2** — hover+30. **E5** — mouse-click+31. **E3** — mouse-down / mouse-up+32. **E6** — triple-click+33. **E1** — drag (most complex, depends on mouse-down/up being solid)++### Sprint 6: Window Geometry + Misc (1-2 days)++34. **F1** — resize-window (AX-only)+35. **F2** — move-window (AX-only)+36. **F3** — minimize / maximize / restore (AX-only)+37. **G1** — key-down / key-up+38. **G2** — clear (AX-only)+39. **G3** — clipboard-clear++### Sprint 7: Testing & Polish (1 day)++40. Full agentic test re-run (same task as original test in `tests/agentic_test_notes.md`)+41. Verify all 7 original bugs are fixed+42. Test all new commands end-to-end+43. Test cross-app drag (Finder → TextEdit file drag)+44. Verify no CGEvent imports remain in `actions.rs`+45. Verify no osascript calls remain in `app_ops.rs` except `launch_app_impl` (`open -a`) and `close_app_impl --force` (`pkill`)++---++## Command Count After Implementation++| Category | Phase 1 (existing) | New | Total |+|----------|-------------------|-----|-------|+| App/Window | 5 | 5 (resize, move, minimize, maximize, restore) | 10 |+| Observation | 7 | 3 (find --count/--first/--nth/--text via flags) | 7* |+| Interaction | 11 | 5 (check, uncheck, triple-click, scroll-to, clear) | 16 |+| Mouse/Coord | 0 | 5 (drag, hover, mouse-move, mouse-click, mouse-down/up) | 5 |+| Keyboard | 1 | 2 (key-down, key-up) | 3 |+| Clipboard | 2 | 1 (clipboard-clear) | 3 |+| Wait | 1 | 1 (wait --text via flag) | 1* |+| System | 3 | 0 | 3 |+| Batch | 1 | 0 | 1 |+| **Total** | **31** | **19** | **49** |++*find enhancements and wait --text are flags on existing commands, not new command files++---++## Cross-Platform Adapter Contract++| Pattern | Commands | macOS | Windows | Linux |+|---------|----------|-------|---------|-------|+| **AX Action** | click, toggle, expand, collapse, select, set-value, focus, check, uncheck, scroll, scroll-to, clear | AXUIElementPerformAction / SetAttributeValue | IUIAutomationElement.Invoke/Toggle/ScrollIntoView | atspi_component_do_action |+| **AX Value Set** | type, set-value, clear | AXUIElementSetAttributeValue(kAXValueAttribute) | IUIAutomationValuePattern.SetValue | atspi_editable_text_set_text_contents |+| **AX Menu Traverse** | press (cmd+shortcuts), close-app (graceful) | kAXMenuBarAttribute → walk → kAXPressAction | IUIAutomationElement.FindAll for menu items | atspi_accessible_get_child_at_index |+| **AX Key Post** | press (fallback for non-menu keys) | AXUIElementPostKeyboardEvent | IUIAutomationElement.SendKeys | atspi_generate_keyboard_event |+| **AX Window Prop** | resize, move, minimize, maximize, restore, focus-window | AXUIElementSetAttributeValue (Position/Size/Minimized/Main) | IUIAutomationTransformPattern / WindowPattern | atspi_component_set_extents |+| **CGEvent Mouse** | drag, hover, mouse-move/click/down/up, triple-click | CGEvent sequences | SendInput sequences | atspi_generate_mouse_event |+| **CGEvent Keyboard** | key-down, key-up | CGEvent / AXUIElementPostKeyboardEvent | SendInput VK_ codes | atspi_generate_keyboard_event |+| **AX Attribute Get** | get, is, snapshot, find, wait --text | AXUIElementCopyAttributeValue | IUIAutomationElement.GetPropertyValue | atspi_accessible_get_* |+| **OS Shell** | launch, close-app --force | `open -a` / `pkill` | CreateProcess / TerminateProcess | xdg-open / kill |+| **OS Clipboard** | clipboard-* | NSPasteboard | Win32 Clipboard API | wl-copy / xclip |++---++## Removed / Downgraded Items++### Stderr Duplication (was A1 in original plan — REMOVED)++**Research finding:** There is NO stderr duplication bug in the code. `emit_json()` writes exactly once to stdout via `BufWriter`. `Cli::try_parse()` does NOT write to stderr on its own. The reported "duplication" was most likely `cargo run` output noise (rustc warnings, build progress) or shell stream merging (`2>&1`). The release binary does NOT exhibit this behavior.++**Action:** No code change needed. Verified by reading `main.rs` error paths — all produce exactly 1 JSON object on stdout. If this resurfaces, the diagnostic is: run `./target/release/agent-desktop click @invalid 2>/dev/null | wc -l` and verify it outputs exactly 1 line.++### Commands NOT Added (from agent-browser gap analysis)++These agent-browser commands were evaluated and intentionally excluded:++| Command | Reason for exclusion |+|---------|---------------------|+| `navigate`, `go_back`, `go_forward`, `reload`, `wait_for_page` | Browser-only, no desktop equivalent |+| `evaluate`, `console`, `network` | Browser DevTools, no desktop equivalent |+| `pdf`, `snapshot_html`, `save_html` | Browser DOM, no desktop equivalent |+| `get_cookies`, `set_cookies`, `clear_cookies` | Browser storage, no desktop equivalent |+| `file_upload`, `file_download` | Browser file dialogs — desktop equivalent would be AX file picker interaction, deferred to Phase 2 |+| `dialog_accept`, `dialog_dismiss` | Browser dialogs — desktop alert/dialog handling is possible via AX but complex; deferred to Phase 2 |++---++## Acceptance Criteria++### Bug Fixes+- [ ] `agent-desktop snapshot --app "System Settings"` returns both sidebar AND content pane elements+- [ ] `agent-desktop select @popup "Courier"` actually changes the value and reports new value in response+- [ ] `agent-desktop toggle @textfield` returns `ACTION_NOT_SUPPORTED` (not false success)+- [ ] `agent-desktop launch Calculator` succeeds and returns window info (with polling)+- [ ] `agent-desktop close-app Calculator` reports actual close status, not premature success+- [ ] `agent-desktop expand @combobox` returns `ACTION_NOT_SUPPORTED` with suggestion (not raw AX error)+- [ ] `agent-desktop get @e1 --property bounds` returns actual coordinates (not null)++### AX-First Execution+- [ ] `actions.rs` contains ZERO `cg_mouse_click` calls or CGEvent mouse imports+- [ ] `actions.rs` Click/RightClick/Toggle/Select use only AXUIElementPerformAction+- [ ] `actions.rs` Scroll uses AXScrollBar increment/decrement (no CGEvent::new_scroll_event)+- [ ] `actions.rs` TypeText uses kAXValueAttribute set (no synthesize_text)+- [ ] `app_ops.rs` focus_window uses AX (no osascript)+- [ ] `app_ops.rs` close_app graceful uses AX menu bar (no osascript quit)+- [ ] `app_ops.rs` press_for_app uses AX menu bar traversal (no osascript keystroke)+- [ ] `input.rs` synthesize_key and synthesize_text removed or only used by CGEvent-based commands (drag, hover, mouse-*, key-down/up)++### New Commands+- [ ] `agent-desktop check @checkbox` sets checked state idempotently+- [ ] `agent-desktop uncheck @checkbox` sets unchecked state idempotently+- [ ] `agent-desktop scroll-to @e15` scrolls element into view+- [ ] `agent-desktop wait --text "Done" --app TextEdit --timeout 3000` waits for text appearance+- [ ] `agent-desktop find --app TextEdit --role button --count` returns count+- [ ] `agent-desktop find --app TextEdit --role button --first` returns single element+- [ ] `agent-desktop drag --from @e1 --to @e5` performs drag via CGEvent+- [ ] `agent-desktop hover @e5` moves cursor to element+- [ ] `agent-desktop minimize --app TextEdit` minimizes window via AX+- [ ] `agent-desktop resize-window --app TextEdit --width 800 --height 600` resizes via AX+- [ ] `agent-desktop mouse-click --xy 500,300` clicks at coordinates+- [ ] `agent-desktop key-down shift` holds shift modifier++### Quality+- [ ] `cargo clippy --all-targets -- -D warnings` passes+- [ ] `cargo test --workspace` passes+- [ ] No file exceeds 400 LOC+- [ ] `agent-desktop --help` shows descriptions for all commands+- [ ] Error JSON appears exactly once on stdout for all error cases+- [ ] Full agentic test re-run shows 0 bugs, 0 false successes++---++## Files to Change (Summary)++| File | Change |+|------|--------|+| `crates/macos/src/adapter.rs` | ONE-LINE fix for sub-window tree; add `get_element_bounds`; populate `bundle_id` in list_apps |+| `crates/macos/src/actions.rs` | Remove ALL CGEvent mouse fallbacks; rewrite select (role-aware), toggle (role check), scroll (AX scroll bar), type (kAXValueAttribute), press (menu traverse + AXUIElementPostKeyboardEvent) |+| `crates/macos/src/input.rs` | Remove `synthesize_key`, `synthesize_text`; keep file only if CGEvent mouse commands need keyboard helpers, otherwise delete |+| `crates/macos/src/app_ops.rs` | Replace osascript in focus_window, close_app, press_for_app with AX equivalents |+| `crates/core/src/adapter.rs` | Extend PlatformAdapter with `get_element_bounds`, `window_op`, `mouse_event`, `drag`, `clear_clipboard`; add `#[non_exhaustive]` consideration |+| `crates/core/src/action.rs` | Add `#[non_exhaustive]`, new variants: Check, Uncheck, ScrollTo, Drag, Hover; add Point, MouseButton, DragParams, WindowOp, MouseEvent types |+| `src/cli.rs` | Add `#[command(about)]` to all variants; add new command structs for all Phase C-G commands |+| `src/dispatch.rs` | Add match arms for all new commands |+| `crates/core/src/commands/` | New files: `check.rs`, `uncheck.rs`, `scroll_to.rs`, `drag.rs`, `hover.rs`, `mouse_down.rs`, `mouse_up.rs`, `mouse_move.rs`, `mouse_click.rs`, `triple_click.rs`, `resize_window.rs`, `move_window.rs`, `minimize.rs`, `maximize.rs`, `restore.rs`, `key_down.rs`, `key_up.rs`, `clear.rs`, `clipboard_clear.rs`, `coords.rs`, `action_check.rs` |+| `crates/core/src/commands/find.rs` | Add `--count`, `--first`, `--last`, `--nth`, `--text` flags |+| `crates/core/src/commands/wait.rs` | Add `--text` flag |+| `crates/core/src/commands/get.rs` | Fix bounds to query live from AX tree |+| `crates/core/src/commands/is_check.rs` | Add `applicable` field based on role |+| `crates/core/src/commands/toggle.rs` | Add role validation |+| `crates/core/src/commands/list_apps.rs` | Wrap data in `{"apps": [...]}` |++---++## References++- Agentic test notes: `tests/agentic_test_notes.md`+- PRD v2.0: `docs/agent_desktop_prd_v2.pdf`+- Architecture brainstorm: `docs/brainstorms/2026-02-19-architecture-validation-brainstorm.md`+- Agent-browser command inventory: `github.com/vercel-labs/agent-browser` (used for gap analysis)+- macOS AX API: `AXUIElementPerformAction`, `AXUIElementSetAttributeValue`, `AXUIElementCopyActionNames`, `AXUIElementPostKeyboardEvent`+- macOS AX menu traversal: `kAXMenuBarAttribute` → `AXMenuBarItem` → `AXMenu` → `AXMenuItem` → `kAXMenuItemCmdChar` + `kAXMenuItemCmdModifiers`+- macOS AX scroll: `kAXScrollBarAttribute` → `kAXIncrementAction` / `kAXDecrementAction`+- Pure AX drag is impossible on all 3 platforms — CGEvent mouse synthesis required+- `accessibility-sys` crate: provides all kAX constants and AXUIElement FFI bindingsdiff --git a/docs/plans/2026-02-19-fix-subtree-traversal-error-dedup-ax-only-plan.md b/docs/plans/2026-02-19-fix-subtree-traversal-error-dedup-ax-only-plan.mdnew file mode 100644index 000000000..356f454bd--- /dev/null+++ b/docs/plans/2026-02-19-fix-subtree-traversal-error-dedup-ax-only-plan.md@@ -0,0 +1,178 @@+---+title: "fix: Sub-window tree, duplicate error output, AX-only commands"+type: fix+date: 2026-02-19+---++# fix: Sub-window tree traversal, duplicate error output, and AX-only command execution++## Overview++Three bugs identified during live testing against macOS System Settings:++1. **Sub-window tree missing** — `snapshot` only captures the sidebar; the content pane (a child AXWindow) is never reached because `window_element_for` queries only `kAXWindowsAttribute`, which excludes embedded sub-windows.+2. **Error emitted twice** — An invalid-argument error JSON appears twice in combined stdout+stderr output. Clap may write its own formatted output to stderr while `main.rs` independently emits the JSON to stdout.+3. **CGEvent and osascript in command paths** — `press`, `type`, `click` (fallback), `double-click`, `right-click` (fallback), `scroll`, `toggle` (fallback), `select` (fallback), `close-app` (graceful), `focus-window` all use CGEvent mouse/keyboard injection or osascript System Events. Every command must be AX-API-only; no CGEvent, no HID injection, no osascript for input delivery.++---++## Problem Analysis++### 1 — Sub-window tree (`crates/macos/src/tree.rs:53–75`)++`window_element_for` walks `kAXWindowsAttribute` to find a matching AXWindow, falling back to the first window or the application element. On macOS, `kAXWindowsAttribute` returns only the **primary top-level windows** registered with the window server.++Apps like System Settings expose their content pane as a **separate AXWindow** accessible via `kAXChildrenAttribute` on the app element (or on the main window). This child window never appears in `kAXWindowsAttribute`, so the tree traversal starts from the sidebar window and never crosses into the content pane.++Concrete evidence: snapshotting System Settings shows `AXOutline (Sidebar)` with 40+ tree items but no content-pane elements. Taking a screenshot confirms the content pane (Appearance options) is present but invisible to the AX tree walk.++**Root cause:** `window_element_for` stops after `kAXWindowsAttribute`; it does not consult `kAXChildrenAttribute` on either the app element or on the matched window.++### 2 — Duplicate error output (`src/main.rs:10–30`)++`emit_json` writes exactly once to stdout (`src/main.rs:122–130`). However, the Claude Bash tool (and any caller that merges stdout + stderr) sees two copies of the error. Clap v4's error type, when converted via `.to_string()` or when the process exits via `std::process::exit`, may flush a buffered internal writer to stderr that contains the same message text. Independently, `BufWriter` wrapping stdout's lock means our JSON flushes to stdout. Together both streams appear in a combined capture.++Fix: configure the clap command to redirect its own error output to a null sink so our JSON is the sole output on any stream.++### 3 — CGEvent and osascript usage++| File | Location | Non-AX mechanism |+|------|----------|-----------------|+| `crates/macos/src/actions.rs` | `Action::Click` fallback | `cg_mouse_click` → `CGEvent::new_mouse_event` |+| `crates/macos/src/actions.rs` | `Action::DoubleClick` | `cg_mouse_click` → `CGEvent::new_mouse_event` |+| `crates/macos/src/actions.rs` | `Action::RightClick` fallback | `cg_mouse_click` → `CGEvent::new_mouse_event` |+| `crates/macos/src/actions.rs` | `Action::Toggle` fallback | `cg_mouse_click` → `CGEvent::new_mouse_event` |+| `crates/macos/src/actions.rs` | `Action::Select` fallback | `cg_mouse_click` → `CGEvent::new_mouse_event` |+| `crates/macos/src/actions.rs` | `Action::Scroll` | `CGEvent::new_scroll_event` → HID |+| `crates/macos/src/actions.rs` | `Action::TypeText` | `synthesize_text` → `CGEvent::new_keyboard_event` |+| `crates/macos/src/actions.rs` | `Action::PressKey` | `synthesize_key` → `CGEvent::new_keyboard_event` |+| `crates/macos/src/input.rs` | `synthesize_key` | `CGEvent::new_keyboard_event` + HID post |+| `crates/macos/src/input.rs` | `synthesize_text` | `CGEvent::new_keyboard_event` + HID post |+| `crates/macos/src/app_ops.rs:27–39` | `press_for_app_impl` | `osascript` → System Events `keystroke`/`key code` |+| `crates/macos/src/app_ops.rs:9–18` | `focus_window_impl` | `osascript` → `tell application X to activate` |+| `crates/macos/src/app_ops.rs:150–173` | `close_app_impl` | `osascript` → quit / `pkill` |++**AX replacements available on macOS:**++| Replaced mechanism | AX replacement |+|-------------------|----------------|+| Mouse click (CGEvent) | `AXUIElementPerformAction(kAXPressAction)` |+| Double-click (CGEvent) | `AXUIElementPerformAction("AXOpen")` or two sequential `kAXPressAction` calls |+| Right-click (CGEvent) | `AXUIElementPerformAction("AXShowMenu")` (already implemented; just remove fallback) |+| Scroll (CGEvent) | `AXUIElementPerformAction(kAXScrollDownAction / kAXScrollUpAction / kAXScrollLeftAction / kAXScrollRightAction)` |+| Text input (CGEvent keyboard) | `AXUIElementSetAttributeValue(kAXValueAttribute, newText)` after `kAXFocusedAttribute = true` |+| Key press for Return/Escape/Space | `AXUIElementPerformAction(kAXConfirmAction / kAXCancelAction / kAXPressAction)` on focused element |+| Key combo shortcuts (cmd+c etc.) | Traverse menu bar AX tree: find `AXMenuItem` where `AXMenuItemCmdChar` + `AXMenuItemCmdModifiers` match, then `kAXPressAction` |+| Window activation (osascript) | `AXUIElementSetAttributeValue(windowEl, kAXMainAttribute, kCFBooleanTrue)` |+| Window close (osascript) | `AXUIElementPerformAction(kAXCloseButtonAttribute child, kAXPressAction)` |++**Limitation:** Arbitrary key combos with no menu-bar equivalent (e.g., `f5`, custom shortcuts not in any menu) cannot be delivered via pure AX API. These should return `ACTION_NOT_SUPPORTED` with a clear suggestion rather than silently falling back to HID injection.++---++## Proposed Solution++### Fix 1 — Expand sub-window discovery (`crates/macos/src/tree.rs`)++After exhausting `kAXWindowsAttribute`, `window_element_for` must also:+1. Query `kAXChildrenAttribute` on the **application element** and collect any child whose role is `AXWindow`, `AXPanel`, `AXSheet`, or `AXDrawer`.+2. Attempt title-exact, then title-fuzzy match on those children.+3. If the matched window has **itself** an `AXSplitGroup` or secondary `AXWindow` child visible via `kAXChildrenAttribute`, include those in the subtree — `build_subtree` already recurses `kAXChildrenAttribute` so this comes for free once the root is correct.++No changes to `build_subtree` are required; only `window_element_for` needs expanding.++### Fix 2 — Silence clap's stderr (`src/main.rs`)++Replace bare `Cli::try_parse()` with an explicit command build that redirects clap's error writer to stderr (discarded via a custom `Write` impl that no-ops), OR use clap's `override_usage` to suppress the automatic error echo.++Concrete approach: configure the `Command` to use a null stderr writer before calling `try_get_matches_from`. In clap 4.x this is done by building the command with `.error_format(clap::ErrorFormat::Plain)` combined with `stderr_fn` override so our `emit_json` path is the only output.++Simplest viable fix: add an unconditional `eprintln!` suppression by redirecting stderr on the command, or simply verify with `2>/dev/null` that only one copy appears on stdout (confirming stderr is the source). If confirmed, wrap the `Cli::command()` call to set the error writer to `std::io::sink()` before `try_get_matches_from`.++### Fix 3 — AX-only command execution++**`crates/macos/src/actions.rs`** — Remove all CGEvent imports and `cg_mouse_click`. Update each action:++- `Action::Click` → `kAXPressAction` only; if it returns error, propagate `ACTION_FAILED` (no CGEvent fallback).+- `Action::DoubleClick` → `AXUIElementPerformAction("AXOpen")` first; if unsupported, `kAXPressAction` twice with a short sleep; if still unsupported, return `ACTION_NOT_SUPPORTED`.+- `Action::RightClick` → `AXUIElementPerformAction("AXShowMenu")` only; remove CGEvent fallback.+- `Action::Toggle` → `kAXPressAction` only; remove CGEvent fallback.+- `Action::Select` → `kAXPressAction` only; remove CGEvent fallback.+- `Action::Scroll` → Use `kAXScrollDownAction` / `kAXScrollUpAction` / `kAXScrollLeftAction` / `kAXScrollRightAction` from `accessibility_sys`; apply `amount` times. Remove `CGEvent::new_scroll_event`.+- `Action::TypeText` → `kAXFocusedAttribute = true` then `kAXValueAttribute = newText`. For append semantics, read current value first and concatenate. Remove `synthesize_text`.+- `Action::PressKey` → Implement `ax_press_key` (see below); remove `synthesize_key`.++**`crates/macos/src/input.rs`** — Remove `synthesize_key` and `synthesize_text` entirely. File may become empty/deleted; if so, remove from `lib.rs` too.++**`crates/macos/src/app_ops.rs`** — Replace:++- `press_for_app_impl` → Activate target app via AX (`kAXMainAttribute`), then call `ax_press_key`.+- `focus_window_impl` → `AXUIElementSetAttributeValue(windowEl, kAXMainAttribute, kCFBooleanTrue)`.+- `close_app_impl` (graceful) → Query `kAXCloseButtonAttribute` on the main window element, then `kAXPressAction` on the close button.+- `close_app_impl --force` → Keep `pkill` (explicit process termination is not an AX concern).+- `launch_app_impl` → Keep `open -a` (launching an app has no AX equivalent).++**New: `ax_press_key` function** (`crates/macos/src/actions.rs` or new `crates/macos/src/ax_key.rs`)++```+ax_press_key(app_pid: Option<i32>, combo: &KeyCombo) -> Result<ActionResult, AdapterError>+```++Strategy:+1. Get the focused element via `kAXFocusedUIElement` on the app (or system-wide element if no app given).+2. Map simple keys to AX actions:+ - `return` / `enter` → `kAXConfirmAction`+ - `escape` / `esc` → `kAXCancelAction`+ - `space` → `kAXPressAction`+ - `up` / `down` / `left` / `right` on sliders → `kAXDecrementAction` / `kAXIncrementAction`+3. For modifier combos (cmd+c, cmd+v, etc.) with no focused-element AX action:+ - Enumerate the menu bar: `kAXMenuBarAttribute` → iterate `AXMenuBarItem` → expand each → walk `AXMenuItem` children+ - Match against `AXMenuItemCmdChar` and `AXMenuItemCmdModifiers`+ - `kAXPressAction` on the matched `AXMenuItem`+4. If no match in steps 2–3: return `Err(AdapterError::new(ErrorCode::ActionNotSupported, "No AX equivalent for key combo '...'; this combo has no menu-bar action and no AX direct action"))`++---++## Acceptance Criteria++- [ ] `agent-desktop snapshot --app "System Settings"` returns both sidebar **and** content pane elements in a single tree+- [ ] Any invalid-argument invocation emits exactly **one** JSON error object on stdout; stderr is silent+- [ ] `agent-desktop press return` (focused text field active) succeeds without CGEvent+- [ ] `agent-desktop press cmd+z` finds and activates the Undo menu item via AX, returns success+- [ ] `agent-desktop press f5` returns `{"ok":false,"error":{"code":"ACTION_NOT_SUPPORTED",...}}` with a descriptive message+- [ ] `agent-desktop click @e1` uses only `kAXPressAction`; no CGEvent in the code path+- [ ] `agent-desktop scroll @e1 --direction down` uses `kAXScrollDownAction`+- [ ] `agent-desktop type @e1 "hello"` sets value via `kAXValueAttribute`+- [ ] `cargo clippy --all-targets -- -D warnings` passes+- [ ] `cargo test --workspace` passes++---++## Files to Change++| File | Change |+|------|--------|+| `crates/macos/src/tree.rs` | Expand `window_element_for` to include `kAXChildrenAttribute` discovery of sub-windows |+| `src/main.rs` | Redirect clap's stderr error writer to suppress duplicate output |+| `crates/macos/src/actions.rs` | Remove all `cg_mouse_click` / `CGEvent` usage; rewrite each action with AX equivalents |+| `crates/macos/src/input.rs` | Remove `synthesize_key`, `synthesize_text`; delete file if empty |+| `crates/macos/src/app_ops.rs` | Replace `press_for_app_impl` and `focus_window_impl` with AX; update `close_app_impl` graceful path |+| `crates/macos/src/lib.rs` | Remove `input` module export if file deleted |++New file (optional, if `ax_press_key` grows beyond ~80 LOC and would push `actions.rs` over 400 LOC):++| File | Purpose |+|------|---------|+| `crates/macos/src/ax_key.rs` | `ax_press_key` — focused-element action dispatch + menu-bar shortcut traversal |++---++## References++- `kAXScrollDownAction` / `kAXScrollUpAction` / `kAXScrollLeftAction` / `kAXScrollRightAction` — standard AX scroll actions in `accessibility_sys`+- `kAXConfirmAction`, `kAXCancelAction` — `accessibility_sys` constants for Return / Escape on focused elements+- `kAXMenuBarAttribute`, `AXMenuItemCmdChar`, `AXMenuItemCmdModifiers` — AX menu traversal attributes+- `kAXCloseButtonAttribute` — AX attribute for window close button element+- `kAXMainAttribute` — AX attribute to make a window the main window+- `kAXFocusedUIElementAttribute` — system-wide or app-level focused element query+- Clap v4 `Command::error_format` / null error writer — suppress stderr echo of parse errorsdiff --git a/docs/plans/2026-02-20-feat-smart-ax-click-chain-plan.md b/docs/plans/2026-02-20-feat-smart-ax-click-chain-plan.mdnew file mode 100644index 000000000..88cffca24--- /dev/null+++ b/docs/plans/2026-02-20-feat-smart-ax-click-chain-plan.md@@ -0,0 +1,329 @@+---+title: "feat: Smart AX-First Click Chain — Universal Element Activation Without CGEvent"+type: feat+date: 2026-02-20+---++# Smart AX-First Click Chain++## Overview++Replace hardcoded `AXPress -> AXConfirm -> CGEvent` fallbacks with a **dynamic, discovery-based activation chain** that queries each element's capabilities at runtime and exhausts every pure-AX strategy before touching the cursor. The goal: any interactive element in any app activates without moving the mouse.++## Problem Statement++The current click implementation tries 2 hardcoded AX actions, then falls back to CGEvent mouse synthesis. CGEvent:+- **Moves the visible cursor** — disruptive to the user+- **Requires the window to be frontmost** — blocks background operation+- **Fails on multi-monitor setups** where bounds are in different coordinate spaces+- **Is non-deterministic by nature** — relies on screen geometry, not semantic interaction++Meanwhile, macOS exposes multiple pure-AX strategies (selection attributes, hierarchy walking, focus+confirm) that would work silently in the background. We just never try them.++## Proposed Solution++A `smart_activate()` function that dynamically discovers and attempts every available AX strategy in priority order, falling through to CGEvent only as absolute last resort.++### The 10-Step Activation Chain++```+1. AXPress on element (if in action list)+2. AXConfirm on element (if in action list)+3. AXOpen on element (if in action list — Finder tree items)+4. AXPick on element (if in action list — menu items)+5. Set AXSelected=true (if attribute is writable on element)+6. Set AXSelectedRows=[el] (on parent table/outline/list)+7. Focus + AXConfirm/AXPress (set AXFocused, wait, retry)+8. Walk DOWN: try child actions (first child, then grandchild)+9. Walk UP: try parent actions (parent, then grandparent)+10. CGEvent click at center (absolute last resort)+```++Steps 1-9 are pure AX. Step 10 is the existing CGEvent fallback. The chain is **non-deterministic** — it queries `AXUIElementCopyActionNames()` and `AXUIElementIsAttributeSettable()` at runtime for each element, never assuming what an app supports.++## Technical Approach++### Prerequisite: Folder Restructure++Before implementing the activation chain, the macOS crate must be restructured from flat files into the standard subfolder layout (see CLAUDE.md "Platform Crate Folder Structure"). This is a prerequisite because:+- `tree.rs` (512 LOC) and `adapter.rs` (438 LOC) exceed the 400 LOC limit+- The new `activate.rs` file belongs in `actions/`, not at the root++The restructure splits files into `tree/`, `actions/`, `input/`, and `system/` subfolders. All `mod` paths and `crate::` imports update accordingly.++### Architecture++#### New file: `crates/macos/src/actions/activate.rs` (~180 LOC)++Contains the smart activation logic. Lives in the `actions/` subfolder alongside `dispatch.rs` and `extras.rs`.++**Public API:**++```rust+pub fn smart_activate(el: &AXElement) -> Result<(), AdapterError>+pub fn smart_double_activate(el: &AXElement) -> Result<(), AdapterError>+pub fn smart_right_activate(el: &AXElement) -> Result<(), AdapterError>+```++**Internal helpers:**++```rust+fn list_ax_actions(el: &AXElement) -> Vec<String>+fn try_action_from_list(el: &AXElement, actions: &[String], targets: &[&str]) -> bool+fn try_set_selected(el: &AXElement) -> bool+fn try_select_via_parent(el: &AXElement) -> bool+fn try_focus_then_activate(el: &AXElement) -> bool+fn try_child_activation(el: &AXElement) -> bool+fn try_parent_activation(el: &AXElement) -> bool+fn is_attr_settable(el: &AXElement, attr: &str) -> bool+```++#### Modified file: `crates/macos/src/actions/dispatch.rs` (~350 LOC, net decrease)++Replace inline fallback logic with calls to `activate::smart_activate()`:++```rust+Action::Click => {+ crate::actions::activate::smart_activate(el)?;+}+Action::DoubleClick => {+ crate::actions::activate::smart_double_activate(el)?;+}+Action::RightClick => {+ crate::actions::activate::smart_right_activate(el)?;+}+Action::Toggle => {+ crate::actions::activate::smart_activate(el)?;+}+Action::TripleClick => {+ crate::actions::activate::smart_triple_activate(el)?;+}+```++`check_uncheck()` also delegates to `smart_activate()` after its role/value checks.++#### Modified file: `crates/macos/src/actions/mod.rs`++Add `pub mod activate;` registration.++### Implementation Phases++#### Phase 0: Folder Restructure (prerequisite, no behavior change)++Split the flat macOS crate into the standard subfolder layout:++```+crates/macos/src/+├── lib.rs # mod declarations only+├── adapter.rs # PlatformAdapter impl (~175 LOC)+├── tree/+│ ├── mod.rs+│ ├── element.rs # AXElement struct + attribute readers (~180)+│ ├── builder.rs # build_subtree, tree traversal (~250)+│ ├── roles.rs # Role mapping (75)+│ ├── resolve.rs # Element re-identification (~100)+│ └── surfaces.rs # Surface detection (252)+├── actions/+│ ├── mod.rs+│ ├── dispatch.rs # perform_action match arms (~350)+│ ├── activate.rs # NEW — smart AX-first chain (~180)+│ └── extras.rs # select_value, ax_scroll (182)+├── input/+│ ├── mod.rs+│ ├── keyboard.rs # Key synthesis (281)+│ ├── mouse.rs # Mouse events (147)+│ └── clipboard.rs # Clipboard get/set (55)+└── system/+ ├── mod.rs+ ├── app_ops.rs # launch, close, focus (165)+ ├── window_ops.rs # window operations (113)+ ├── key_dispatch.rs # app-targeted key press (105)+ ├── permissions.rs # permission checks (19)+ ├── screenshot.rs # screen capture (79)+ └── wait.rs # wait utilities (77)+```++**Verification:** `cargo build && cargo test --workspace && cargo clippy --all-targets -- -D warnings` — zero behavior change, only file moves and import path updates.++#### Phase 1: Core Smart Activate (~130 LOC in `actions/activate.rs`)++**`list_ax_actions()`** — Query element's action list dynamically:+```+AXUIElementCopyActionNames → iterate CFArray → collect Vec<String>+```+This is the foundation — every decision is based on what the element actually reports.++**`is_attr_settable()`** — Check if a writable attribute exists:+```+AXUIElementIsAttributeSettable(el, attr) → bool+```+Required import from `accessibility_sys`: `AXUIElementIsAttributeSettable`.++**`smart_activate()`** — The 10-step chain:++```+Step 1-4: Query actions once, try matching activation actions in order+Step 5: is_attr_settable("AXSelected") → set true+Step 6: copy_element_attr(el, "AXParent") → check parent role →+ is_attr_settable(parent, "AXSelectedRows") → set [el]+Step 7: set AXFocused=true → sleep(50ms) → retry AXConfirm/AXPress+Step 8: copy_ax_array(el, "AXChildren") → take(3) → try actions on each+Step 9: copy_element_attr(el, "AXParent") → try actions, then grandparent+Step 10: click_via_bounds(el, Left, 1) — existing CGEvent fallback+```++**Key design decisions:**++- **Query actions ONCE per activate call** — store in a local Vec, don't re-query per step+- **Parent role check for step 6** — only try AXSelectedRows on AXTable/AXOutline/AXList roles+ (prevents setting selection attributes on random groups)+- **Child walk limit** — try first 3 children only (avoid expensive deep traversal)+- **Parent walk limit** — 2 levels max (parent + grandparent)+- **Focus settle delay** — 50ms between AXFocused set and retry (matches existing codebase pattern)++#### Phase 2: Specialized Variants (~50 LOC in `actions/activate.rs`)++**`smart_double_activate()`:**+```+1. AXOpen (if in action list)+2. smart_activate() twice with 50ms gap+3. CGEvent double-click fallback+```++**`smart_right_activate()`:**+```+1. AXShowMenu (if in action list)+2. CGEvent right-click fallback (no AX alternative for context menus)+```++**`smart_triple_activate()`:**+```+1. smart_activate() three times with 30ms gaps+2. CGEvent triple-click fallback+```++Right-click has fewer AX alternatives — `AXShowMenu` is the only pure-AX option. CGEvent is a reasonable fallback here since context menus are inherently visual.++#### Phase 3: Wire Into actions/dispatch.rs (net LOC decrease)++Replace the inline `try_ax_action` + `click_via_bounds` chains in `perform_action()` with single-line calls to `activate.rs`. This will **reduce** `dispatch.rs` LOC since the complex fallback logic moves out.++The `try_ax_action()`, `click_via_bounds()`, and `has_ax_action()` functions stay in `dispatch.rs` as they're used by other code paths. But they also get `pub(crate)` visibility for `activate.rs` to call `click_via_bounds()` as the final fallback.++#### Phase 4: Expand/Collapse AXDisclosing Fallback (~15 LOC in actions/dispatch.rs)++For `Action::Expand` and `Action::Collapse`, add `AXDisclosing` attribute as fallback:++```+Expand: AXExpand action → set AXDisclosing=true → error+Collapse: AXCollapse action → set AXDisclosing=false → error+```++This uses `is_attr_settable()` from `actions/activate.rs`. Small addition, stays in `actions/dispatch.rs`.++### Selection via Parent: Building the CFArray++For step 6 (set AXSelectedRows on parent), we need to build a CFArray containing the target element. The pattern from tree.rs:++```rust+// Retain the element, build a single-element array+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]);+AXUIElementSetAttributeValue(parent.0, attr, arr.as_CFTypeRef())+```++**Important:** The element must be CFRetained before wrapping, since `from_CFTypes` does its own retain, and `wrap_under_create_rule` takes ownership.++## File Changes Summary++### Phase 0: Folder Restructure (move only, no behavior change)++| Old Path | New Path |+|----------|----------|+| `crates/macos/src/tree.rs` | Split → `tree/element.rs`, `tree/builder.rs` |+| `crates/macos/src/actions.rs` | → `actions/dispatch.rs` |+| `crates/macos/src/action_extras.rs` | → `actions/extras.rs` |+| `crates/macos/src/keyboard.rs` | → `input/keyboard.rs` |+| `crates/macos/src/mouse.rs` | → `input/mouse.rs` |+| `crates/macos/src/clipboard.rs` | → `input/clipboard.rs` |+| `crates/macos/src/roles.rs` | → `tree/roles.rs` |+| `crates/macos/src/surfaces.rs` | → `tree/surfaces.rs` |+| `crates/macos/src/app_ops.rs` | → `system/app_ops.rs` |+| `crates/macos/src/window_ops.rs` | → `system/window_ops.rs` |+| `crates/macos/src/key_dispatch.rs` | → `system/key_dispatch.rs` |+| `crates/macos/src/permissions.rs` | → `system/permissions.rs` |+| `crates/macos/src/screenshot.rs` | → `system/screenshot.rs` |+| `crates/macos/src/wait.rs` | → `system/wait.rs` |++Plus extract `tree/resolve.rs` from `adapter.rs` (element re-identification logic).++### Phases 1-4: Smart Activation Chain++| File | Action | LOC Change |+|------|--------|------------|+| `crates/macos/src/actions/activate.rs` | **Create** | +180 |+| `crates/macos/src/actions/dispatch.rs` | Modify (simplify) | -30 (~350 LOC) |+| `crates/macos/src/actions/mod.rs` | Add `pub mod activate` | +1 |++**Net:** +151 LOC. No file exceeds 400 LOC.++## Acceptance Criteria++### Functional Requirements++- [ ] `click @ref` on System Settings treeitems works without moving cursor (AXSelected or AXSelectedRows)+- [ ] `click @ref` on standard buttons still works via AXPress (no regression)+- [ ] `click @ref` on Finder sidebar items works (AXOpen or AXSelected)+- [ ] `click @ref` on custom SwiftUI controls works (hierarchy walking or focus+confirm)+- [ ] `double-click @ref` works via AXOpen or repeated activation+- [ ] `right-click @ref` works via AXShowMenu where possible+- [ ] `toggle`, `check`, `uncheck` use smart activation+- [ ] `expand`/`collapse` falls back to AXDisclosing attribute++### Non-Functional Requirements++- [ ] No app-specific code — all behavior is discovered at runtime via `AXUIElementCopyActionNames` and `AXUIElementIsAttributeSettable`+- [ ] CGEvent is only reached when ALL pure-AX strategies fail+- [ ] No file exceeds 400 LOC+- [ ] `cargo clippy --all-targets -- -D warnings` passes+- [ ] `cargo test --workspace` passes++### Quality Gates++- [ ] Smoke test on 5+ apps: System Settings, Finder, TextEdit, Safari, Xcode+- [ ] Verify cursor does NOT move during activation on at least 3 test cases++## Verification Plan++```bash+cargo build+cargo clippy --all-targets -- -D warnings+cargo fmt --all+cargo test --workspace++# Smoke tests+cargo run -- launch "System Settings"+cargo run -- snapshot --app "System Settings" -i+cargo run -- click @eN # Appearance treeitem — should NOT move cursor+cargo run -- click @eN # Light button — should activate++cargo run -- launch "Finder"+cargo run -- snapshot --app "Finder" -i+cargo run -- click @eN # Sidebar item++cargo run -- launch "TextEdit"+cargo run -- snapshot --app "TextEdit" -i+cargo run -- click @eN # Toolbar button++wc -l crates/macos/src/actions/activate.rs # must be <= 400+wc -l crates/macos/src/actions/dispatch.rs # must be <= 400+```++## References++- Brainstorm research: AX action catalog (11 documented + app-specific custom actions)+- `AXUIElementIsAttributeSettable` available in `accessibility-sys 0.2.0`+- Existing parent-walking pattern: `actions/extras.rs` (`find_scroll_area`)+- Existing action list query: `actions/dispatch.rs` (`has_ax_action`)+- `copy_element_attr` supports "AXParent": `tree/element.rs`