Computer use CLI for AI agents
Rust accessibilityaccessibility-apiai-agentsautomationclicomputer-usecomputer-use-agentcomputer-use-agentsdesktop-automationmacosmcprust
fix: harden agent-desktop reliability (#54)
Lahfir0c0a5b8dbc4c
diff --git a/.githooks/pre-commit b/.githooks/pre-commitindex bebbd8cdc..bdebcd07b 100755--- a/.githooks/pre-commit+++ b/.githooks/pre-commit@@ -45,6 +45,22 @@ run() {fi}+run "inline comment ban" bash -c '+ mapfile -t files < <(git diff --cached --name-only --diff-filter=ACMR -- "*.rs")+ if ((${#files[@]} == 0)); then+ exit 0+ fi+ if grep -En "^\s*//[^/!]" "${files[@]}" 2>/dev/null; then+ echo "" >&2+ echo "pre-commit: inline // comments are forbidden; use /// or //! docstrings only." >&2+ exit 1+ fi+ if grep -En "[^:\"'\''\`]\s+//[^/!]" "${files[@]}" 2>/dev/null; then+ echo "" >&2+ echo "pre-commit: end-of-line // comments are forbidden; use /// or //! docstrings only." >&2+ exit 1+ fi+'run "cargo fmt --all -- --check" cargo fmt --all -- --checkrun "cargo clippy --all-targets -- -D warnings" cargo clippy --all-targets -- -D warningsrun "cargo test --lib --workspace" cargo test --lib --workspacediff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 4f7ff3ffc..8f7538ce2 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -49,16 +49,16 @@ jobs:~/.cargo/registry/index/~/.cargo/registry/cache/~/.cargo/git/db/- key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.toml', 'Cargo.lock') }}+ key: ${{ runner.os }}-cargo-${{ hashFiles('Cargo.lock', 'Cargo.toml', 'crates/**/Cargo.toml', 'src/Cargo.toml') }}restore-keys: ${{ runner.os }}-cargo-- name: Cache build artifactsuses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5with:path: target/- key: ${{ runner.os }}-build-ci-${{ hashFiles('**/Cargo.toml', 'Cargo.lock') }}-${{ hashFiles('**/*.rs') }}+ key: ${{ runner.os }}-build-ci-${{ hashFiles('Cargo.lock', 'Cargo.toml', 'crates/**/Cargo.toml', 'src/Cargo.toml') }}-${{ hashFiles('crates/**/*.rs', 'src/**/*.rs', 'tests/**/*.rs') }}restore-keys: |- ${{ runner.os }}-build-ci-${{ hashFiles('**/Cargo.toml', 'Cargo.lock') }}-+ ${{ runner.os }}-build-ci-${{ hashFiles('Cargo.lock', 'Cargo.toml', 'crates/**/Cargo.toml', 'src/Cargo.toml') }}-${{ runner.os }}-build-ci-- name: Check dependency isolationdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 692f2c6af..99bbca94f 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -152,7 +152,7 @@ jobs:~/.cargo/registry/index/~/.cargo/registry/cache/~/.cargo/git/db/- key: ${{ runner.os }}-${{ matrix.target }}-cargo-${{ hashFiles('**/Cargo.toml', 'Cargo.lock') }}+ key: ${{ runner.os }}-${{ matrix.target }}-cargo-${{ hashFiles('Cargo.lock', 'Cargo.toml', 'crates/**/Cargo.toml', 'src/Cargo.toml') }}restore-keys: ${{ runner.os }}-${{ matrix.target }}-cargo-- name: Build release binary@@ -236,7 +236,7 @@ jobs:~/.cargo/registry/index/~/.cargo/registry/cache/~/.cargo/git/db/- key: ${{ runner.os }}-${{ matrix.target }}-ffi-cargo-${{ hashFiles('**/Cargo.toml', 'Cargo.lock') }}+ key: ${{ runner.os }}-${{ matrix.target }}-ffi-cargo-${{ hashFiles('Cargo.lock', 'Cargo.toml', 'crates/**/Cargo.toml', 'src/Cargo.toml') }}restore-keys: ${{ runner.os }}-${{ matrix.target }}-ffi-cargo-- name: Build FFI cdylib (release-ffi profile)diff --git a/.gitignore b/.gitignoreindex 3900c96d1..01dd3aebc 100644--- a/.gitignore+++ b/.gitignore@@ -2,6 +2,9 @@/target/**/*.rs.bk+# E2E fixture build artifact (compiled by tests/fixture-app/build.sh on demand)+/tests/fixture-app/build/+# Cargo!Cargo.lockdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex e9829eb4c..cdf2d35a5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,11 @@# Changelog+## Unreleased++### Notes++* **ffi:** `AdRefEntry` carries additional reliability metadata in this branch; C ABI consumers must rebuild against the updated `agent_desktop.h` header.+## [0.2.3](https://github.com/lahfir/agent-desktop/compare/v0.2.2...v0.2.3) (2026-06-06)diff --git a/CLAUDE.md b/CLAUDE.mdindex 50971e5d1..1021a5eda 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -15,10 +15,13 @@ cargo clippy --all-targets -- -D warnings # Lint (must pass, zero warnings)cargo fmt --all -- --check # Format checkcargo fmt --all # Auto-formatcargo tree -p agent-desktop-core # Verify no platform crate leaks (CI enforces)+bash tests/e2e/run.sh # E2E: real binary vs fixture app, verify by observation (needs --release + AX permission)```Run the binary: `./target/release/agent-desktop snapshot --app Finder -i`+The E2E harness drives the release binary against a real SwiftUI/AppKit fixture and asserts every effect by independent observation (never the command's own `ok:true`), covering every ref action in **both** headless and `--headed` mode. See `tests/e2e/README.md`.+## Pre-commit HookThe repo ships a pre-commit hook at `.githooks/pre-commit` that runs `cargo fmt --check`, `cargo clippy --all-targets -- -D warnings`, and `cargo test --lib --workspace` against staged Rust changes. Wire it up once after cloning:@@ -45,12 +48,14 @@ Cross-platform Rust CLI + MCP server enabling AI agents to observe and control d- `docs:` — documentation only- `style:` — formatting, no code change- `refactor:` — code change that neither fixes a bug nor adds a feature+ - `perf:` — performance improvement with no behavior change- `chore:` — maintenance tasks, dependencies- `ci:` — CI/CD changes- `test:` — adding or fixing tests- Format: `type: concise imperative description` (lowercase type, no capital after colon)- Focus on "why" not "what"- Examples: `feat: add scroll-to command`, `fix: prevent stale ref on window resize`, `ci: add binary size check`+- **Pre-1.0 versioning policy** (release-please `bump-minor-pre-major` + `bump-patch-for-minor-pre-major`): while the version is 0.x, a `BREAKING CHANGE` cuts a **minor** (0.2 → 0.3) and a `feat:` cuts a **patch**. Do not expect a major release before 1.0.## Core Principle@@ -63,6 +68,7 @@ agent-desktop is NOT an AI agent. It is a tool that AI agents invoke. It outputs```agent-desktop/├── Cargo.toml # workspace: members, shared deps+├── CONCEPTS.md # shared domain vocabulary for refs, snapshots, sessions, actionability, and related concepts├── rust-toolchain.toml # pinned Rust version├── clippy.toml # project-wide lint config├── crates/@@ -77,12 +83,12 @@ agent-desktop/│ └── ffi/ # agent-desktop-ffi (cdylib + committed C ABI header)├── src/ # agent-desktop binary (entry point)│ ├── main.rs # entry point, permission check, JSON envelope-│ ├── cli.rs # clap derive enum (Commands)-│ ├── cli_args.rs # all command argument structs-│ ├── batch.rs # batch JSON → typed Commands-│ ├── command_policy.rs # command permission/ref/side-effect policy-│ ├── dispatch.rs # command dispatcher + parse helpers-│ └── dispatch_notifications.rs+│ ├── batch/ # batch JSON → typed Commands+│ ├── cli/ # clap derive enum, help text, CLI contract tests+│ ├── cli_args/ # command argument structs by domain+│ ├── command_policy/ # permission/ref/side-effect policy+│ ├── dispatch/ # command dispatcher, parse helpers, notifications+│ └── tests/ # binary-level conformance tests├── docs/│ └── solutions/ # documented solutions to past problems (bugs, best practices, workflow patterns), organized by category with YAML frontmatter (module, tags, problem_type); relevant when implementing or debugging in documented areas└── tests/@@ -150,7 +156,7 @@ pub fn dispatch(}```-Batch is not a second dispatcher. `src/batch.rs` deserializes JSON entries into the same typed `Commands` enum, runs the same `CommandPolicy` preflight, and calls the same `dispatch()` path as CLI.+Batch is not a second dispatcher. `src/batch/mod.rs` deserializes JSON entries into the same typed `Commands` enum, runs the same `CommandPolicy` preflight, and calls the same `dispatch()` path as CLI.### Additive Phase Model@@ -184,8 +190,9 @@ Phases 2–4 add adapters, transports, and production readiness work. Nothing in```PERM_DENIED, ELEMENT_NOT_FOUND, APP_NOT_FOUND, ACTION_FAILED,-ACTION_NOT_SUPPORTED, STALE_REF, WINDOW_NOT_FOUND,-PLATFORM_NOT_SUPPORTED, TIMEOUT, INVALID_ARGS, INTERNAL+ACTION_NOT_SUPPORTED, STALE_REF, AMBIGUOUS_TARGET, WINDOW_NOT_FOUND,+PLATFORM_NOT_SUPPORTED, TIMEOUT, INVALID_ARGS, NOTIFICATION_NOT_FOUND,+SNAPSHOT_NOT_FOUND, POLICY_DENIED, INTERNAL```### Exit Codes@@ -258,7 +265,7 @@ crates/{macos,windows,linux}/src/Adding a new command requires exactly these steps:1. Create `crates/core/src/commands/{name}.rs` with an `execute()` function2. Register it in `crates/core/src/commands/mod.rs`-3. Add the CLI subcommand variant to `src/cli.rs` (clap derive enum)+3. Add the CLI subcommand variant to `src/cli/mod.rs` and arguments under `src/cli_args/`4. Add a match arm in `dispatch()` in the binary crate5. If new `Action` variant needed, add to `crates/core/src/action.rs`6. If new adapter method needed, add to `PlatformAdapter` trait with a default returning `Err(AdapterError::not_supported())`@@ -271,7 +278,7 @@ Every command produces a response envelope:```json{- "version": "1.0",+ "version": "2.0","ok": true,"command": "snapshot","data": {@@ -287,7 +294,7 @@ Error responses:```json{- "version": "1.0",+ "version": "2.0","ok": false,"command": "click","error": {@@ -298,6 +305,8 @@ Error responses:}```+The `error` object may also carry an optional `details` object (e.g. the actionability report on an actionability failure, candidate summaries on `AMBIGUOUS_TARGET`, or the last observed state on a `wait` `TIMEOUT`).+### Serialization Rules- Omit null/None fields (`#[serde(skip_serializing_if = "Option::is_none")]`)@@ -308,8 +317,9 @@ Error responses:## Ref System- Refs allocated in depth-first document order: `@e1`, `@e2`, etc.-- Only interactive roles receive refs: `button`, `textfield`, `checkbox`, `link`, `menuitem`, `tab`, `slider`, `combobox`, `treeitem`, `cell`-- Static text, groups, containers do NOT get refs (they remain in tree for context)+- An element receives a ref when it is **addressable for an action**: its role is interactive (`button`, `textfield`, `checkbox`, `link`, `menuitem`, `tab`, `slider`, `combobox`, `treeitem`, `cell`, `radiobutton`, `switch`, `colorwell`, `menubutton`, `incrementor`, `dockitem`), **or** it advertises an available action regardless of role. Container roles such as `scrollarea` (Scroll) and `disclosure` (Expand/Collapse/Click) are not interactive by role but are genuinely actionable, so they are ref-able — `scroll` / `expand` / `collapse` need a ref to target them+- A bare `SetFocus` affordance does not qualify on its own (focusability is not a primary action), so inert focusable containers stay ref-less+- Static text and non-actionable groups/containers do NOT get refs (they remain in tree for context)- Refs are deterministic within a snapshot but NOT stable across snapshots if UI changed- Snapshot refs are stored by snapshot ID under `~/.agent-desktop/snapshots/{snapshot_id}/refmap.json`, with a `latest_snapshot_id` pointer for commands that omit `--snapshot`- `~/.agent-desktop/last_refmap.json` is written only as a latest-snapshot inspection artifact; command code must use `RefStore`@@ -320,120 +330,32 @@ Error responses:## PlatformAdapter Trait-Platform-facing methods default to `not_supported()` unless implemented by an adapter:--```rust-pub trait PlatformAdapter {- fn list_windows(&self, filter: &WindowFilter) -> Result<Vec<WindowInfo>, AdapterError>;- fn list_apps(&self) -> Result<Vec<AppInfo>, AdapterError>;- fn get_tree(&self, win: &WindowInfo, opts: &TreeOptions) -> Result<AccessibilityNode, AdapterError>;- fn get_subtree(&self, handle: &NativeHandle, opts: &TreeOptions) -> Result<AccessibilityNode, AdapterError>;- fn execute_action(&self, handle: &NativeHandle, request: ActionRequest) -> Result<ActionResult, AdapterError>;- fn resolve_element(&self, entry: &RefEntry) -> Result<NativeHandle, AdapterError>;- fn permission_report(&self) -> PermissionReport;- fn request_permissions(&self) -> PermissionReport;- fn focus_window(&self, win: &WindowInfo) -> Result<(), AdapterError>;- fn launch_app(&self, id: &str, wait: bool) -> Result<WindowInfo, AdapterError>;- fn close_app(&self, id: &str, force: bool) -> Result<(), AdapterError>;- fn screenshot(&self, target: ScreenshotTarget) -> Result<ImageBuffer, AdapterError>;- fn get_clipboard(&self) -> Result<String, AdapterError>;- fn set_clipboard(&self, text: &str) -> Result<(), AdapterError>;-}-```--## Key Types--- `AccessibilityNode` — platform-agnostic tree node: `ref`, `role`, `name`, `value`, `description`, `states`, `available_actions`, `bounds`, `children`-- `Action` — Click, DoubleClick, RightClick, SetValue(String), SetFocus, Expand, Collapse, Select(String), Toggle, Scroll(Direction, Amount), PressKey(KeyCombo)-- `ActionRequest` — `{ action, policy }`, where the default `InteractionPolicy` forbids focus stealing and cursor movement-- `NativeHandle` — opaque platform pointer with `PhantomData<*const ()>` to prevent auto-Send/Sync. Inner field is `pub(crate)`.-- `RefEntry` — `{ pid, role, name, bounds_hash, available_actions }`-- `WindowInfo` — `{ id, title, app_name, pid, bounds }`-- `PermissionReport` — `{ accessibility, screen_recording, automation }`, each `{ "state": "granted" }`, `{ "state": "denied", "suggestion": "..." }`, or `{ "state": "unknown" }`-- `ErrorCode` — machine-readable enum with `#[serde(rename_all = "SCREAMING_SNAKE_CASE")]`-- `AdapterError` — struct with `code`, `message`, `suggestion`, `platform_detail`-- `AppError` — enum with `#[from]` impls for `AdapterError`, `std::io::Error`, `serde_json::Error`--## macOS Adapter (Phase 1)--### Tree Traversal-- Entry: `AXUIElementCreateApplication(pid)` for app root-- 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 `tree/roles.rs`-- Max depth default: 10. Configurable via `--max-depth`--### Action Execution-- Click: `AXUIElementPerformAction(kAXPressAction)`-- SetValue: `AXUIElementSetAttributeValue(kAXValueAttribute, value)`-- SetFocus: `AXUIElementSetAttributeValue(kAXFocusedAttribute, true)`-- Keyboard/Mouse: `CGEventCreateKeyboardEvent` / `CGEventCreateMouseEvent`-- Clipboard: `NSPasteboard.generalPasteboard` via Cocoa FFI-- Screenshot: `ScreenshotBackend` boundary with secure `screencapture` temp files--### Permission Detection-- Call `AXIsProcessTrusted()` on startup-- If false, return `PERM_DENIED` with guidance: "Open System Settings > Privacy > Accessibility and add your terminal"-- Optionally call `AXIsProcessTrustedWithOptions(prompt: true)` to trigger system dialog--### AXElement Safety-- Inner field: `pub(crate)` not `pub` (prevents double-free via raw pointer extraction)-- `Clone` impl must call `CFRetain`-- `Drop` impl must call `CFRelease`--## Testing Strategy--### Unit Tests (core)-- `AccessibilityNode` ser/de roundtrips-- Ref allocator only assigns interactive roles-- `SnapshotEngine` filtering-- Error serialization-- MockAdapter: in-memory `PlatformAdapter` returning hardcoded trees--### Golden Fixtures (`tests/fixtures/`)-- Real snapshots from Finder, TextEdit, etc. checked into repo-- Regression-test serialization format changes--### Integration Tests (macOS CI)-- Snapshot Finder, TextEdit, System Settings — non-empty trees with refs-- Click button in test app — verify action succeeded-- Type text into TextEdit via ref — verify content changed-- Clipboard get/set roundtrip-- Permission denied scenario — correct error code and guidance-- Large tree (Xcode) snapshot in under 2 seconds--## Dependencies (Phase 1)--| Crate | Version | Purpose |-|-------|---------|---------|-| clap | 4.x | CLI parsing with derive macros |-| serde + serde_json | 1.x | JSON serialization |-| thiserror | 2.x | Error derive macros |-| tracing | 0.1+ | Structured logging |-| base64 | 0.22+ | Screenshot encoding |-| accessibility-sys | 0.1+ | macOS AXUIElement FFI |-| core-foundation | 0.10+ | macOS CF types |-| core-graphics | 0.24+ | macOS CG types |--### Deferred Dependencies-- `tokio` — Phase 2/3 (all Phase 1 ops are synchronous)-- `rmcp` (0.15.0) — Phase 3 (MCP server)-- `schemars` — Phase 3 (JSON Schema generation)-- `uiautomation` (0.24+) — Phase 2 (Windows)-- `atspi` (0.28+) + `zbus` (5.x) — Phase 2 (Linux)--## Build Configuration--```toml-[profile.release]-opt-level = "z"-lto = true-codegen-units = 1-strip = true-panic = "abort"-```--Target binary size: <15MB per platform.+Core defines `PlatformAdapter`; platform crates implement it. Methods default to+`not_supported()`, so an adapter only implements what it supports. Read the+current signatures in `crates/core/src/adapter.rs` — notably strict resolution+(`resolve_element_strict*` → STALE_REF on 0, AMBIGUOUS_TARGET on 2+), live reads+for the actionability preflight (`get_live_*`), and `is_protected_process`+(keeps platform-specific process names out of core).++## macOS Adapter Gotchas++- **Ancestor-path set, not a global visited set** — macOS reuses+ `AXUIElementRef` pointers across sibling branches, so a global visited set+ would prune real subtrees.+- **`AXElement` memory safety** — inner field is `pub(crate)` (prevents+ double-free via raw pointer extraction); `Clone` must `CFRetain`, `Drop` must+ `CFRelease`.+- **Batch attribute reads** — use `AXUIElementCopyMultipleAttributeValues`+ (3-5x faster than per-attribute fetches).++## Testing++- Unit tests use an in-memory `MockAdapter`; golden fixtures in `tests/fixtures/`+ regression-test serialization.+- macOS CI integration tests drive real apps (Finder, TextEdit, System Settings).+- `tests/e2e/run.sh` drives the release binary against the SwiftUI fixture and+ verifies every effect by independent observation in both headless and+ `--headed` mode (see `tests/e2e/README.md`).## CI Requirements@@ -443,23 +365,13 @@ Target binary size: <15MB per platform.- `cargo test --workspace`- Binary size check: fail if release binary exceeds 15MB-## Implemented Commands (54)--> **Platform note:** All 54 commands are implemented on macOS (Phase 1). Windows and Linux adapters are planned (Phase 2/3) and will support the same command surface; notification commands depend on platform-specific notification APIs.--| Category | Commands |-|----------|----------|-| App/Window (10) | `launch`, `close-app`, `list-windows`, `list-apps`, `focus-window`, `resize-window`, `move-window`, `minimize`, `maximize`, `restore` |-| Observation (6) | `snapshot`, `screenshot`, `find`, `get`, `is`, `list-surfaces` |-| Interaction (14) | `click`, `double-click`, `triple-click`, `right-click`, `type`, `set-value`, `clear`, `focus`, `select`, `toggle`, `check`, `uncheck`, `expand`, `collapse` |-| Scroll (2) | `scroll`, `scroll-to` |-| Keyboard (3) | `press`, `key-down`, `key-up` |-| Mouse (6) | `hover`, `drag`, `mouse-move`, `mouse-click`, `mouse-down`, `mouse-up` |-| Notifications (4) *(macOS)* | `list-notifications`, `dismiss-notification`, `dismiss-all-notifications`, `notification-action` |-| Clipboard (3) | `clipboard-get`, `clipboard-set`, `clipboard-clear` |-| Wait (1) | `wait` (with `--element`, `--window`, `--text`, `--menu`, `--notification` flags) |-| System (4) | `status`, `permissions`, `version`, `skills` |-| Batch (1) | `batch` |+## Commands++54 commands spanning App/Window, Observation, Interaction, Scroll, Keyboard,+Mouse, Notifications (macOS), Clipboard, Wait, System, and Batch. The full+surface and per-command reference live in `skills/agent-desktop/`. All 54 are+implemented on macOS (Phase 1); Windows/Linux (Phase 2/3) target the same+surface. Adding a command: see the Extensibility Pattern above.## Non-Goalsdiff --git a/CONCEPTS.md b/CONCEPTS.mdnew file mode 100644index 000000000..1c9e583fa--- /dev/null+++ b/CONCEPTS.md@@ -0,0 +1,91 @@+# Concepts++Shared domain vocabulary for this project -- entities, named processes, and status concepts with project-specific meaning. Seeded with core domain vocabulary, then accretes as ce-compound and ce-compound-refresh process learnings; direct edits are fine. Glossary only, not a spec or catch-all.++## Desktop Observation++### Accessibility Tree+A structured representation of an application's user interface exposed by the operating system accessibility APIs and used by agent-desktop as the source of truth for observation and semantic interaction.++### Snapshot+An observation of an accessibility tree at a point in time, persisted with the element refs allocated from that observation.++### Snapshot ID+A compact identifier for one persisted snapshot. Explicit snapshot IDs are direct handles; callers do not need the original session when they pass the ID.++### Surface+A scoped UI layer that can be observed separately from the whole window, such as an open menu, sheet, popover, alert, or focused area.++### Drill-down+A snapshot operation that starts from an existing ref to observe that element's subtree instead of re-reading the entire window.++## Refs And Identity++### Ref+A short element identifier assigned by agent-desktop to an actionable or drillable node in a snapshot.++Refs are deterministic inside one snapshot but are not stable across UI changes. Callers either pass the snapshot ID that produced the ref or intentionally use the session's latest snapshot pointer.++### RefMap+The persisted mapping from refs to the identity evidence needed to re-identify elements later.++### Stale Ref+A ref whose stored identity no longer matches a live element strongly enough to act safely.++### Strict Ref Resolution+The fail-closed process of re-identifying a ref from stored identity evidence before a command acts on it.++Strict ref resolution rejects missing, stale, and ambiguous matches instead of guessing. It is the boundary between an old observation and a live desktop mutation.++## Coordination++### Session+A coordination key for one agent or a coordinated group of agents that share a latest-snapshot pointer.++Use sessions when callers intentionally omit `--snapshot` and want a shared latest observation. Explicit snapshot IDs remain the deterministic path for pinned actions and can be resolved without also passing the session.++### Protected Process+A session-critical operating-system process that agent-desktop refuses to close on every surface, because terminating it would break the user's desktop session.++The refusal is enforced where the close happens, so CLI, FFI, and any future consumer behave identically. Matching is exact — a process name or a bundle-identifier component, never a substring — so lookalike applications that merely contain a protected name stay closable.++## Action Reliability++### Actionability+The pre-dispatch judgement that a resolved element is safe to act on, based on native evidence such as visibility, stability, enabled state, supported action, policy, and editability.++### Capability Vocabulary+The platform-neutral set of supported action names that core uses to compare command intent with native adapter evidence.++Each adapter maps native primitives into this shared vocabulary before core evaluates actionability. New commands should extend the central vocabulary first, then reuse it from actionability, ref allocation, predicates, FFI tests, and platform adapters.++### Interaction Policy+The side-effect contract attached to an action request, controlling whether the command may steal focus, move the cursor, or use physical input fallbacks. Ref commands expose exactly two modes: **headless** (the default — accessibility-only, no cursor, fails closed when the AX path is unavailable) and **headed** (opt-in via the global `--headed` flag — permits focus stealing and cursor movement so the action chain's physical fallbacks can complete). The AX path is always tried first, so headed never regresses headless-capable elements. The `headed` upgrade applies uniformly to every ref command; each command still declares its own headless base policy (most are pure-AX; `type` uses a focus-fallback base because typing requires focus but never moves the cursor).++### Headless Ref Action+A ref-based action that uses semantic accessibility operations without implicit focus stealing, cursor movement, synthetic keyboard input, or pasteboard use. This is the default mode.++Headless ref actions may still fail when the native accessibility API cannot perform the requested semantic operation; they fail closed with structured actionability or policy errors rather than silently substituting physical input. The broader **headed** policy must be selected explicitly with `--headed`.++### Action Chain+The ordered ladder of strategies a ref action walks to perform one intent — semantic accessibility actions first, then settable attributes, then policy-gated physical input — with each step verified against the element's observed state before it counts as success.++The chain pins one execution deadline at its start (distinct from the Resolver Deadline, which budgets re-identification) and every step observes it. Expiry while a step may have partially mutated the element surfaces as a structured timeout carrying the observed state, never as a plain step failure — the caller must be able to tell "nothing happened" from "something may have happened".++### Wait Predicate+The condition a wait command polls for before returning, such as element actionability, text presence, window appearance, menu state, or notification arrival.++### Resolver Deadline+The remaining time budget carried through strict ref resolution so every native read can fail with a structured timeout instead of using an unrelated platform default timeout.++### Coordinate Fallback+An explicit opt-in path that uses screen coordinates or physical input when semantic accessibility operations cannot perform the requested action.++Physical input lands on the topmost window at the target point, so the fallback first ensures the target element's own window is frontmost — the app being frontmost is not sufficient when the element lives in a background window of that app.++### FFI Ref-Action Parity+The requirement that language bindings using refs follow the same strict resolution, actionability, and interaction-policy semantics as CLI ref commands.++## Relationships++A session owns one latest-snapshot pointer. A snapshot persists a ref map and can be selected directly by snapshot ID. A ref resolves through strict ref resolution into live native evidence, then actionability decides whether a headless ref action can safely dispatch, and the action chain executes that dispatch under its own deadline with the interaction policy gating its physical steps. FFI ref-action parity keeps that same relationship true for language bindings.diff --git a/Cargo.lock b/Cargo.lockindex 62f11e68f..94ea4ff7a 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -50,6 +50,7 @@ dependencies = ["agent-desktop-macos","agent-desktop-windows","libc",+ "serde_json","smallvec",]diff --git a/README.md b/README.mdindex f4d50febf..0bcfb6edb 100644--- a/README.md+++ b/README.md@@ -71,7 +71,7 @@ cargo build --releasecp target/release/agent-desktop /usr/local/bin/```-Requires Rust 1.78+ and macOS 13.0+.+Requires Rust 1.85+ and macOS 13.0+.### Permissions@@ -156,6 +156,27 @@ agent-desktop snapshot -i # re-observe after UI changesAgent loop: snapshot → decide → act → snapshot → decide → act → ...```+### Shared sessions for multi-agent workflows++Use the same `--session <id>` when multiple agents coordinate on one desktop task. A session owns a latest-snapshot pointer, not a security boundary. Each snapshot gets its own `snapshot_id`; pass `--snapshot <id>` when an agent must act on a specific observation. Explicit snapshot IDs can be used without repeating `--session`; keep `--session` when you omit `--snapshot` and want that session's latest snapshot.++```mermaid+flowchart LR+ S["--session release-fix"] --> A["snapshot -> s1"]+ S --> B["snapshot -> s2"]+ A --> C["Agent A: click @e4 --snapshot s1"]+ B --> D["Agent B: wait --element @e9 --predicate actionable"]+ S --> E["latest_snapshot_id points at newest snapshot"]+ C --> F["Explicit snapshot id works outside session too"]+```++```bash+agent-desktop --session release-fix snapshot --app Xcode -i --compact+agent-desktop --session release-fix wait --element @e9 --predicate actionable --timeout 5000+agent-desktop --session release-fix click @e9+agent-desktop click @e9 --snapshot s2+```+## Commands### Observation@@ -170,11 +191,13 @@ agent-desktop is @e7 --snapshot s8f3k2p9 --property checked # check boolean statagent-desktop list-surfaces --app Notes # list menus, sheets, popovers, alerts```+`get` and `is` resolve the ref once, prefer live platform reads when available, and fall back only when that live read is unsupported by the adapter.+### Interaction```bashagent-desktop click @e3 # semantic AX-first click-agent-desktop double-click @e3 # AXOpen; physical double-click uses mouse-click --count 2+agent-desktop double-click @e3 # AXOpen; physical double-click uses --headed mouse-click --count 2agent-desktop triple-click @e3 # POLICY_DENIED if physical input is disabledagent-desktop right-click @e3 # open verified context menuagent-desktop type @e5 "hello world" # insert text into element@@ -191,6 +214,8 @@ agent-desktop scroll @e1 --direction down --amount 3 # scroll (AX-first)agent-desktop scroll-to @e20 # scroll element into view```+> **(macOS, Phase 1)** Pure cursor gestures have no accessibility equivalent, so `triple-click`, `hover`, and `drag` are always physical; `double-click` is headless via `AXOpen` and only needs `--headed` for gesture-only targets. Windows (UIA) and Linux (AT-SPI) adapters may expose different capabilities. See `skills/agent-desktop/references/commands-interaction.md`.+### Keyboard```bash@@ -204,13 +229,13 @@ agent-desktop key-up shift # release key### Mouse```bash-agent-desktop hover @e3 # move cursor to element-agent-desktop hover --xy 500,300 # move cursor to coordinates-agent-desktop drag @e3 --to @e8 # drag between elements-agent-desktop drag --xy 100,200 --to-xy 400,200 # drag between coordinates-agent-desktop mouse-click --xy 500,300 # click at coordinates-agent-desktop mouse-down --xy 500,300 # press at coordinates-agent-desktop mouse-up --xy 500,300 # release at coordinates+agent-desktop --headed hover @e3 # move cursor to element+agent-desktop --headed hover --xy 500,300 # move cursor to coordinates+agent-desktop --headed drag --from @e3 --to @e8 # drag between elements+agent-desktop --headed drag --from-xy 100,200 --to-xy 400,200 # drag between coordinates+agent-desktop --headed mouse-click --xy 500,300 # click at coordinates+agent-desktop --headed mouse-down --xy 500,300 # press at coordinates+agent-desktop --headed mouse-up --xy 500,300 # release at coordinates```### App & Window Management@@ -219,7 +244,7 @@ agent-desktop mouse-up --xy 500,300 # release at coordinatesagent-desktop launch Safari # launch app by nameagent-desktop launch com.apple.Safari # launch by bundle IDagent-desktop close-app Safari # quit app-agent-desktop close-app Safari --force # force quit (SIGKILL)+agent-desktop close-app Safari --force # force quit (SIGTERM, then SIGKILL if needed)agent-desktop list-apps # list running GUI appsagent-desktop list-windows # list visible windowsagent-desktop list-windows --app Finder # windows for specific app@@ -256,8 +281,12 @@ agent-desktop clipboard-clear # clear clipboard```bashagent-desktop wait 500 # sleep 500msagent-desktop wait --element @e3 --timeout 5000 # wait for element+agent-desktop wait --element @e3 --predicate actionable # wait until safe to act+agent-desktop wait --element @e5 --predicate value --value readyagent-desktop wait --window "Save" --timeout 10000 # wait for windowagent-desktop wait --text "Loading complete" --app Safari # wait for text+agent-desktop wait --text "Done" --count 1 --app Xcode # wait for exact match count+agent-desktop wait --notification --text "Build Succeeded" # wait for new matching notificationagent-desktop wait --menu --timeout 3000 # wait for menu```@@ -269,6 +298,11 @@ agent-desktop batch '[{"command": "type", "args": {"ref_id": "@e5", "snapshot": "<snapshot_id>", "text": "hello"}},{"command": "press", "args": {"combo": "return"}}]' --stop-on-error++agent-desktop --session run-a batch '[+ {"command": "snapshot", "args": {"app": "Finder", "interactive_only": true}},+ {"command": "status", "session": "run-b", "args": {}}+]'```### System@@ -335,6 +369,7 @@ Errors include machine-readable codes and recovery hints:| `ELEMENT_NOT_FOUND` | No element matched the ref or query || `APP_NOT_FOUND` | Application not running or no windows || `STALE_REF` | Ref is from a previous snapshot |+| `AMBIGUOUS_TARGET` | Ref recovery matched multiple plausible targets || `SNAPSHOT_NOT_FOUND` | Snapshot ID is missing or expired || `POLICY_DENIED` | Physical/headed path blocked by policy || `ACTION_FAILED` | The OS rejected the action |@@ -348,16 +383,25 @@ Errors include machine-readable codes and recovery hints:## Ref System-`snapshot` assigns refs to interactive elements in depth-first order: `@e1`, `@e2`, `@e3`, etc. Refs are scoped to a compact `snapshot_id` such as `s8f3k2p9`. Commands can omit `--snapshot` to use the latest snapshot pointer, but passing the ID is more deterministic in multi-step flows.+`snapshot` assigns refs to interactive elements in depth-first order: `@e1`, `@e2`, `@e3`, etc. Refs are scoped to a compact `snapshot_id` such as `s8f3k2p9`. Commands can omit `--snapshot` to use the active session's latest snapshot pointer, but passing the ID is more deterministic in multi-step flows and does not require also passing `--session`.Interactive roles that receive refs: `button`, `textfield`, `checkbox`, `link`, `menuitem`, `tab`, `slider`, `combobox`, `treeitem`, `cell`, `radiobutton`, `incrementor`, `menubutton`, `switch`, `colorwell`, `dockitem`.Static elements (labels, groups, containers) appear in the tree for context but have no ref.+Reliability contract:++- `--session <id>` scopes the latest snapshot pointer to one caller or agent team; explicit `--snapshot <id>` resolves the saved snapshot directly.+- Ref actions re-identify targets at action time: a moved unique target can proceed, while missing or changed identity returns `STALE_REF`.+- Multiple plausible targets return `AMBIGUOUS_TARGET` instead of choosing arbitrarily.+- Actions run an actionability preflight before dispatch: visibility, stability, enabled state, supported action, policy, and editability.+- `wait --element @e3 --predicate actionable` polls until the target can be acted on.+- `--trace <path>` appends JSONL diagnostics outside stdout; `--trace-strict` fails on trace setup and pre-action trace writes, while post-action success traces are best-effort after the desktop mutation has already happened.+Stale ref recovery:```-snapshot → act → STALE_REF? → snapshot again → retry+snapshot → act → STALE_REF or AMBIGUOUS_TARGET? → wait/snapshot again → retry with the new ref```## Platform Support@@ -441,7 +485,7 @@ cargo build --release### What is the ref system?-`snapshot` assigns refs to interactive elements in depth-first order: `@e1`, `@e2`, `@e3`, etc. Refs are scoped to a compact `snapshot_id` such as `s8f3k2p9`.+`snapshot` assigns refs to interactive elements in depth-first order: `@e1`, `@e2`, `@e3`, etc. Refs are scoped to a compact `snapshot_id` such as `s8f3k2p9`. Commands can omit `--snapshot` to use the active session's latest snapshot pointer, but explicit snapshot IDs are the deterministic path and do not require also passing `--session`.Interactive roles that receive refs:diff --git a/crates/core/src/action.rs b/crates/core/src/action.rsindex a5ea37547..91a3c7b2b 100644--- a/crates/core/src/action.rs+++ b/crates/core/src/action.rs@@ -1,6 +1,5 @@use serde::{Deserialize, Serialize};-#[non_exhaustive]#[derive(Debug, Clone, Serialize, Deserialize)]pub enum Action {Click,@@ -26,92 +25,39 @@ pub enum Action {Drag(DragParams),}-#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct ActionRequest {- pub action: Action,- pub policy: InteractionPolicy,-}--#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]-pub struct InteractionPolicy {- pub allow_focus_steal: bool,- pub allow_cursor_move: bool,-}--impl ActionRequest {- pub fn headless(action: Action) -> Self {- Self {- action,- policy: InteractionPolicy::headless(),+impl Action {+ pub fn name(&self) -> &'static str {+ match self {+ Self::Click => "click",+ Self::DoubleClick => "double-click",+ Self::RightClick => "right-click",+ Self::TripleClick => "triple-click",+ Self::SetValue(_) => "set-value",+ Self::SetFocus => "focus",+ Self::Expand => "expand",+ Self::Collapse => "collapse",+ Self::Select(_) => "select",+ Self::Toggle => "toggle",+ Self::Check => "check",+ Self::Uncheck => "uncheck",+ Self::Scroll(_, _) => "scroll",+ Self::ScrollTo => "scroll-to",+ Self::PressKey(_) => "press",+ Self::KeyDown(_) => "key-down",+ Self::KeyUp(_) => "key-up",+ Self::TypeText(_) => "type",+ Self::Clear => "clear",+ Self::Hover => "hover",+ Self::Drag(_) => "drag",}}- pub fn focus_fallback(action: Action) -> Self {- Self {- action,- policy: InteractionPolicy::focus_fallback(),- }+ pub fn requires_cursor_policy(&self) -> bool {+ matches!(self, Self::Hover | Self::Drag(_))}- pub fn physical(action: Action) -> Self {- Self {- action,- policy: InteractionPolicy::physical(),- }- }-}--impl InteractionPolicy {- pub fn headless() -> Self {- Self {- allow_focus_steal: false,- allow_cursor_move: false,- }- }-- pub fn focus_fallback() -> Self {- Self {- allow_focus_steal: true,- allow_cursor_move: false,- }- }-- pub fn physical() -> Self {- Self {- allow_focus_steal: true,- allow_cursor_move: true,- }- }-}--impl Default for InteractionPolicy {- fn default() -> Self {- Self::headless()- }-}--#[cfg(test)]-mod policy_tests {- use super::*;-- #[test]- fn default_policy_is_headless() {- let policy = InteractionPolicy::default();- assert!(!policy.allow_focus_steal);- assert!(!policy.allow_cursor_move);- }-- #[test]- fn headless_request_blocks_physical_side_effects() {- let request = ActionRequest::headless(Action::Click);- assert_eq!(request.policy, InteractionPolicy::headless());- }-- #[test]- fn focus_fallback_policy_never_moves_cursor() {- let request = ActionRequest::focus_fallback(Action::Scroll(Direction::Down, 1));- assert!(request.policy.allow_focus_steal);- assert!(!request.policy.allow_cursor_move);+ pub fn may_use_focus_fallback(&self) -> bool {+ matches!(self, Self::TypeText(_) | Self::PressKey(_))}}@@ -142,6 +88,12 @@ pub struct DragParams {pub to: Point,#[serde(skip_serializing_if = "Option::is_none")]pub duration_ms: Option<u64>,+ /// Time to hold the dragged item over the destination before releasing.+ /// macOS drop targets often need the drag to dwell over them before they+ /// register as the drop destination; too short and the gesture lands as a+ /// drag with no drop. `None` uses the adapter default.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub drop_delay_ms: Option<u64>,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -182,40 +134,27 @@ pub enum Modifier {Shift,}-#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct ActionResult {- pub action: String,- #[serde(skip_serializing_if = "Option::is_none")]- pub ref_id: Option<String>,- #[serde(skip_serializing_if = "Option::is_none")]- pub post_state: Option<ElementState>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct ElementState {- pub role: String,- #[serde(skip_serializing_if = "Vec::is_empty", default)]- pub states: Vec<String>,- #[serde(skip_serializing_if = "Option::is_none")]- pub value: Option<String>,-}+#[cfg(test)]+mod tests {+ use super::*;-impl ActionResult {- pub fn new(action: impl Into<String>) -> Self {- Self {- action: action.into(),- ref_id: None,- post_state: None,+ #[test]+ fn action_names_do_not_include_payloads() {+ let cases = [+ (Action::SetValue("private".into()), "set-value"),+ (Action::Select("private".into()), "select"),+ (Action::TypeText("private".into()), "type"),+ (+ Action::PressKey(KeyCombo {+ key: "A".into(),+ modifiers: vec![Modifier::Cmd],+ }),+ "press",+ ),+ ];++ for (action, expected) in cases {+ assert_eq!(action.name(), expected);}}-- pub fn with_ref(mut self, ref_id: impl Into<String>) -> Self {- self.ref_id = Some(ref_id.into());- self- }-- pub fn with_state(mut self, state: ElementState) -> Self {- self.post_state = Some(state);- self- }}diff --git a/crates/core/src/action_request.rs b/crates/core/src/action_request.rsnew file mode 100644index 000000000..b5f4155b0--- /dev/null+++ b/crates/core/src/action_request.rs@@ -0,0 +1,58 @@+use crate::action::Action;+use crate::interaction_policy::InteractionPolicy;+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ActionRequest {+ pub action: Action,+ pub policy: InteractionPolicy,+}++impl ActionRequest {+ pub fn headless(action: Action) -> Self {+ Self {+ action,+ policy: InteractionPolicy::headless(),+ }+ }++ pub fn focus_fallback(action: Action) -> Self {+ Self {+ action,+ policy: InteractionPolicy::focus_fallback(),+ }+ }++ pub fn headed(action: Action) -> Self {+ Self {+ action,+ policy: InteractionPolicy::headed(),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::action::{Action, Direction};++ #[test]+ fn default_policy_is_headless() {+ let policy = InteractionPolicy::default();+ assert!(!policy.allow_focus_steal);+ assert!(!policy.allow_cursor_move);+ }++ #[test]+ fn headless_request_blocks_physical_side_effects() {+ let request = ActionRequest::headless(Action::Click);+ assert_eq!(request.policy, InteractionPolicy::headless());+ }++ #[test]+ fn focus_fallback_policy_never_moves_cursor() {+ let request = ActionRequest::focus_fallback(Action::Scroll(Direction::Down, 1));+ assert!(request.policy.allow_focus_steal);+ assert!(!request.policy.allow_cursor_move);+ }+}diff --git a/crates/core/src/action_result.rs b/crates/core/src/action_result.rsnew file mode 100644index 000000000..287db095e--- /dev/null+++ b/crates/core/src/action_result.rs@@ -0,0 +1,31 @@+use crate::{action_step::ActionStep, element_state::ElementState};+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ActionResult {+ pub action: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub post_state: Option<ElementState>,+ #[serde(skip_serializing_if = "Vec::is_empty", default)]+ pub steps: Vec<ActionStep>,+}++impl ActionResult {+ pub fn new(action: impl Into<String>) -> Self {+ Self {+ action: action.into(),+ post_state: None,+ steps: Vec::new(),+ }+ }++ pub fn with_state(mut self, state: ElementState) -> Self {+ self.post_state = Some(state);+ self+ }++ pub fn with_steps(mut self, steps: Vec<ActionStep>) -> Self {+ self.steps = steps;+ self+ }+}diff --git a/crates/core/src/action_step.rs b/crates/core/src/action_step.rsnew file mode 100644index 000000000..f2c22490c--- /dev/null+++ b/crates/core/src/action_step.rs@@ -0,0 +1,35 @@+use crate::action_step_outcome::ActionStepOutcome;+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ActionStep {+ label: String,+ pub outcome: ActionStepOutcome,+}++impl ActionStep {+ pub fn attempted(label: &'static str) -> Self {+ Self {+ label: label.to_string(),+ outcome: ActionStepOutcome::Attempted,+ }+ }++ pub fn skipped(label: &'static str) -> Self {+ Self {+ label: label.to_string(),+ outcome: ActionStepOutcome::Skipped,+ }+ }++ pub fn succeeded(label: &'static str) -> Self {+ Self {+ label: label.to_string(),+ outcome: ActionStepOutcome::Succeeded,+ }+ }++ pub fn label(&self) -> &str {+ &self.label+ }+}diff --git a/crates/core/src/action_step_outcome.rs b/crates/core/src/action_step_outcome.rsnew file mode 100644index 000000000..fa63d84e6--- /dev/null+++ b/crates/core/src/action_step_outcome.rs@@ -0,0 +1,9 @@+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum ActionStepOutcome {+ Attempted,+ Skipped,+ Succeeded,+}diff --git a/crates/core/src/actionability/check.rs b/crates/core/src/actionability/check.rsnew file mode 100644index 000000000..42b0c5003--- /dev/null+++ b/crates/core/src/actionability/check.rs@@ -0,0 +1,10 @@+use super::ActionabilityStatus;+use serde::Serialize;++#[derive(Debug, Clone, Serialize, PartialEq, Eq)]+pub struct ActionabilityCheck {+ pub name: &'static str,+ pub status: ActionabilityStatus,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub reason: Option<String>,+}diff --git a/crates/core/src/actionability/mod.rs b/crates/core/src/actionability/mod.rsnew file mode 100644index 000000000..f557a50c2--- /dev/null+++ b/crates/core/src/actionability/mod.rs@@ -0,0 +1,242 @@+use crate::capability;+use crate::{+ action::Action,+ action_request::ActionRequest,+ adapter::{NativeHandle, PlatformAdapter},+ error::{AdapterError, ErrorCode},+ node::Rect,+ refs::RefEntry,+};+use serde_json::json;++mod check;+mod report;+mod status;++pub use check::ActionabilityCheck;+pub use report::ActionabilityReport;+pub use status::ActionabilityStatus;++#[cfg(test)]+pub fn check(+ entry: &RefEntry,+ request: &ActionRequest,+) -> Result<ActionabilityReport, AdapterError> {+ check_with_stability(entry.bounds_hash, entry, request)+}++pub fn check_live(+ entry: &RefEntry,+ handle: &NativeHandle,+ adapter: &dyn PlatformAdapter,+ request: &ActionRequest,+) -> Result<ActionabilityReport, AdapterError> {+ let mut observed = entry.clone();+ let live = match adapter.get_live_element(handle) {+ Ok(live) => live,+ Err(err)+ if matches!(+ err.code,+ ErrorCode::PlatformNotSupported | ErrorCode::ActionNotSupported+ ) =>+ {+ return check_with_stability(entry.bounds_hash, &observed, request);+ }+ Err(err) => return Err(err),+ };+ if live_element_is_stale(&live) {+ return Err(AdapterError::new(+ ErrorCode::StaleRef,+ "Resolved element no longer exposes live accessibility state",+ )+ .with_suggestion("Run 'snapshot' again and retry with the refreshed ref"));+ }+ if let Some(state) = live.state {+ observed.role = state.role;+ observed.states = state.states;+ observed.value = state.value.or(observed.value);+ }+ observed.bounds = live.bounds;+ if let Some(actions) = live.available_actions+ && !actions.is_empty()+ {+ observed.available_actions = actions;+ }+ check_with_stability(entry.bounds_hash, &observed, request)+}++fn live_element_is_stale(live: &crate::adapter::LiveElement) -> bool {+ let role_unknown = live+ .state+ .as_ref()+ .is_none_or(|state| state.role == "unknown");+ let actions_empty = live.available_actions.as_ref().is_none_or(Vec::is_empty);+ role_unknown && live.bounds.is_none() && actions_empty+}++fn check_with_stability(+ expected_bounds_hash: Option<u64>,+ entry: &RefEntry,+ request: &ActionRequest,+) -> Result<ActionabilityReport, AdapterError> {+ let checks = vec![+ visibility_check(entry),+ stability_check(expected_bounds_hash, entry.bounds),+ enabled_check(entry),+ action_supported_check(entry, request),+ policy_check(request),+ editable_check(entry, &request.action),+ ];++ let actionable = checks+ .iter()+ .all(|check| !matches!(check.status, ActionabilityStatus::Fail));+ let report = ActionabilityReport { actionable, checks };+ if report.actionable {+ return Ok(report);+ }+ Err(AdapterError::new(+ ErrorCode::ActionFailed,+ format!("Target is not actionable: {}", failure_reasons(&report)),+ )+ .with_details(json!(report))+ .with_suggestion(+ "Wait for the target to become actionable, refresh the snapshot, or use an explicit physical/focus command if intended.",+ ))+}++fn visibility_check(entry: &RefEntry) -> ActionabilityCheck {+ let Some(bounds) = entry.bounds else {+ return unknown("visible", "bounds unavailable");+ };+ if !bounds_are_visible(Some(bounds)) {+ return fail("visible", "bounds are zero-sized");+ }+ pass("visible")+}++fn stability_check(expected_bounds_hash: Option<u64>, bounds: Option<Rect>) -> ActionabilityCheck {+ let Some(expected) = expected_bounds_hash else {+ return unknown("stable", "snapshot bounds hash unavailable");+ };+ let Some(bounds) = bounds else {+ return unknown("stable", "live bounds unavailable");+ };+ if bounds.bounds_hash() != expected {+ return unknown("stable", "bounds changed since snapshot");+ }+ pass("stable")+}++fn enabled_check(entry: &RefEntry) -> ActionabilityCheck {+ if !states_are_enabled(&entry.states) {+ return fail("enabled", "entry state contains disabled");+ }+ pass("enabled")+}++pub fn states_are_enabled(states: &[String]) -> bool {+ !states.iter().any(|state| state == "disabled")+}++pub fn bounds_are_visible(bounds: Option<Rect>) -> bool {+ bounds.is_some_and(|bounds| bounds.width > 0.0 && bounds.height > 0.0)+}++fn action_supported_check(entry: &RefEntry, request: &ActionRequest) -> ActionabilityCheck {+ if request.action.requires_cursor_policy() {+ return pass("supported_action");+ }+ if capability::contains_any(+ &entry.available_actions,+ capability::for_action(&request.action),+ ) {+ return pass("supported_action");+ }+ if may_use_fallback(&request.action, request) {+ return unknown(+ "supported_action",+ "semantic action unavailable but fallback policy allows attempt",+ );+ }+ let expected = capability::for_action(&request.action).join(" or ");+ fail("supported_action", format!("{expected} is not available"))+}++fn policy_check(request: &ActionRequest) -> ActionabilityCheck {+ if request.action.requires_cursor_policy() && !request.policy.allow_cursor_move {+ return fail(+ "policy",+ "action requires cursor movement but policy denies it",+ );+ }+ if request.action.may_use_focus_fallback() && !request.policy.allow_focus_steal {+ return fail("policy", "action requires focus but policy denies it");+ }+ pass("policy")+}++fn editable_check(entry: &RefEntry, action: &Action) -> ActionabilityCheck {+ if !matches!(+ action,+ Action::SetValue(_) | Action::TypeText(_) | Action::Clear+ ) {+ return pass("editable");+ }+ if entry.role == "textfield" || entry.role == "combobox" {+ return pass("editable");+ }+ if capability::contains(&entry.available_actions, capability::SET_VALUE) {+ return pass("editable");+ }+ fail("editable", format!("role {} is not editable", entry.role))+}++fn failure_reasons(report: &ActionabilityReport) -> String {+ report+ .checks+ .iter()+ .filter(|check| matches!(check.status, ActionabilityStatus::Fail))+ .map(|check| {+ let reason = check.reason.as_deref().unwrap_or("failed");+ format!("{} ({reason})", check.name)+ })+ .collect::<Vec<_>>()+ .join(", ")+}++fn may_use_fallback(action: &Action, request: &ActionRequest) -> bool {+ action.may_use_focus_fallback() && request.policy.allow_focus_steal+}++fn pass(name: &'static str) -> ActionabilityCheck {+ ActionabilityCheck {+ name,+ status: ActionabilityStatus::Pass,+ reason: None,+ }+}++fn fail(name: &'static str, reason: impl Into<String>) -> ActionabilityCheck {+ ActionabilityCheck {+ name,+ status: ActionabilityStatus::Fail,+ reason: Some(reason.into()),+ }+}++fn unknown(name: &'static str, reason: impl Into<String>) -> ActionabilityCheck {+ ActionabilityCheck {+ name,+ status: ActionabilityStatus::Unknown,+ reason: Some(reason.into()),+ }+}++#[cfg(test)]+#[path = "../actionability_tests.rs"]+mod tests;++#[cfg(test)]+#[path = "../actionability_live_tests.rs"]+mod live_tests;diff --git a/crates/core/src/actionability/report.rs b/crates/core/src/actionability/report.rsnew file mode 100644index 000000000..2d0df4037--- /dev/null+++ b/crates/core/src/actionability/report.rs@@ -0,0 +1,8 @@+use super::ActionabilityCheck;+use serde::Serialize;++#[derive(Debug, Clone, Serialize, PartialEq, Eq)]+pub struct ActionabilityReport {+ pub actionable: bool,+ pub checks: Vec<ActionabilityCheck>,+}diff --git a/crates/core/src/actionability/status.rs b/crates/core/src/actionability/status.rsnew file mode 100644index 000000000..9ff4cf8e9--- /dev/null+++ b/crates/core/src/actionability/status.rs@@ -0,0 +1,9 @@+use serde::Serialize;++#[derive(Debug, Clone, Serialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum ActionabilityStatus {+ Pass,+ Fail,+ Unknown,+}diff --git a/crates/core/src/actionability_live_tests.rs b/crates/core/src/actionability_live_tests.rsnew file mode 100644index 000000000..5666d29df--- /dev/null+++ b/crates/core/src/actionability_live_tests.rs@@ -0,0 +1,305 @@+use super::*;+use crate::{+ action::Action,+ action_request::ActionRequest,+ adapter::{LiveElement, NativeHandle, PlatformAdapter, SnapshotSurface},+ capability,+ element_state::ElementState,+ node::Rect,+ refs::RefEntry,+};++struct LiveAdapter {+ state: Option<ElementState>,+ bounds: Option<Rect>,+ actions: Option<Vec<String>>,+}++impl PlatformAdapter for LiveAdapter {+ fn get_live_state(&self, _handle: &NativeHandle) -> Result<Option<ElementState>, AdapterError> {+ Ok(self.state.clone())+ }++ fn get_element_bounds(&self, _handle: &NativeHandle) -> Result<Option<Rect>, AdapterError> {+ Ok(self.bounds)+ }++ fn get_live_actions(+ &self,+ _handle: &NativeHandle,+ ) -> Result<Option<Vec<String>>, AdapterError> {+ Ok(self.actions.clone())+ }+}++struct CombinedLiveAdapter;++impl PlatformAdapter for CombinedLiveAdapter {+ fn get_live_element(&self, _handle: &NativeHandle) -> Result<LiveElement, AdapterError> {+ Ok(LiveElement {+ state: Some(ElementState {+ role: "button".into(),+ states: vec![],+ value: None,+ }),+ bounds: Some(Rect {+ x: 1.0,+ y: 1.0,+ width: 20.0,+ height: 20.0,+ }),+ available_actions: Some(vec![capability::CLICK.into()]),+ })+ }++ fn get_live_state(&self, _handle: &NativeHandle) -> Result<Option<ElementState>, AdapterError> {+ panic!("check_live should use get_live_element")+ }++ fn get_element_bounds(&self, _handle: &NativeHandle) -> Result<Option<Rect>, AdapterError> {+ panic!("check_live should use get_live_element")+ }++ fn get_live_actions(+ &self,+ _handle: &NativeHandle,+ ) -> Result<Option<Vec<String>>, AdapterError> {+ panic!("check_live should use get_live_element")+ }+}++struct LiveReadErrorAdapter;++impl PlatformAdapter for LiveReadErrorAdapter {+ fn get_live_state(&self, _handle: &NativeHandle) -> Result<Option<ElementState>, AdapterError> {+ Err(AdapterError::permission_denied())+ }+}++struct UnsupportedLiveAdapter;++impl PlatformAdapter for UnsupportedLiveAdapter {}++struct DeadLiveElementAdapter;++impl PlatformAdapter for DeadLiveElementAdapter {+ fn get_live_element(&self, _handle: &NativeHandle) -> Result<LiveElement, AdapterError> {+ Ok(LiveElement {+ state: Some(ElementState {+ role: "unknown".into(),+ states: vec![],+ value: None,+ }),+ bounds: None,+ available_actions: Some(vec![]),+ })+ }+}++fn entry() -> RefEntry {+ let bounds = Rect {+ x: 1.0,+ y: 1.0,+ width: 20.0,+ height: 20.0,+ };+ RefEntry {+ pid: 1,+ role: "button".into(),+ name: Some("OK".into()),+ value: None,+ description: None,+ states: vec![],+ bounds: Some(bounds),+ bounds_hash: Some(bounds.bounds_hash()),+ available_actions: vec![capability::CLICK.into()],+ source_app: None,+ source_window_id: None,+ source_window_title: None,+ source_surface: SnapshotSurface::Window,+ root_ref: None,+ path_is_absolute: true,+ path: smallvec::SmallVec::new(),+ }+}++#[test]+fn live_actionability_overrides_stale_snapshot_state() {+ let mut stale = entry();+ stale.states.push("disabled".into());+ let adapter = LiveAdapter {+ state: Some(ElementState {+ role: "button".into(),+ states: vec![],+ value: None,+ }),+ bounds: stale.bounds,+ actions: Some(vec![capability::CLICK.into()]),+ };++ let report = check_live(+ &stale,+ &NativeHandle::null(),+ &adapter,+ &ActionRequest::headless(Action::Click),+ )+ .unwrap();++ assert!(report.actionable);+}++#[test]+fn live_actionability_uses_combined_live_element_read() {+ let mut stale = entry();+ stale.states.push("disabled".into());+ stale.bounds = Some(Rect {+ x: 1.0,+ y: 1.0,+ width: 0.0,+ height: 20.0,+ });+ stale.available_actions = vec![];++ let report = check_live(+ &stale,+ &NativeHandle::null(),+ &CombinedLiveAdapter,+ &ActionRequest::headless(Action::Click),+ )+ .unwrap();++ assert!(report.actionable);+}++#[test]+fn live_actionability_uses_actions_gained_after_snapshot() {+ let mut stale = entry();+ stale.available_actions = vec![];+ let adapter = LiveAdapter {+ state: None,+ bounds: stale.bounds,+ actions: Some(vec![capability::CLICK.into()]),+ };++ let report = check_live(+ &stale,+ &NativeHandle::null(),+ &adapter,+ &ActionRequest::headless(Action::Click),+ )+ .unwrap();++ assert!(report.actionable);+}++#[test]+fn live_actionability_fails_when_action_disappears_after_snapshot() {+ let stale = entry();+ let adapter = LiveAdapter {+ state: None,+ bounds: stale.bounds,+ actions: Some(vec![capability::SET_VALUE.into()]),+ };++ let err = check_live(+ &stale,+ &NativeHandle::null(),+ &adapter,+ &ActionRequest::headless(Action::Click),+ )+ .unwrap_err();++ assert_eq!(err.code, ErrorCode::ActionFailed);+ assert!(err.message.contains("supported_action"));+}++#[test]+fn live_actionability_allows_identity_resolved_bounds_change() {+ let stale = entry();+ let adapter = LiveAdapter {+ state: None,+ bounds: Some(Rect {+ x: 100.0,+ y: 100.0,+ width: 20.0,+ height: 20.0,+ }),+ actions: Some(vec![capability::CLICK.into()]),+ };++ let report = check_live(+ &stale,+ &NativeHandle::null(),+ &adapter,+ &ActionRequest::headless(Action::Click),+ )+ .unwrap();++ assert!(report.actionable);+ let stable = report+ .checks+ .iter()+ .find(|check| check.name == "stable")+ .unwrap();+ assert_eq!(stable.status, ActionabilityStatus::Unknown);+}++#[test]+fn empty_live_actions_do_not_erase_snapshot_capabilities() {+ let stale = entry();+ let adapter = LiveAdapter {+ state: None,+ bounds: stale.bounds,+ actions: Some(vec![]),+ };++ let report = check_live(+ &stale,+ &NativeHandle::null(),+ &adapter,+ &ActionRequest::headless(Action::Click),+ )+ .unwrap();++ assert!(report.actionable);+}++#[test]+fn unsupported_live_reads_fall_back_to_snapshot_entry() {+ let report = check_live(+ &entry(),+ &NativeHandle::null(),+ &UnsupportedLiveAdapter,+ &ActionRequest::headless(Action::Click),+ )+ .unwrap();++ assert!(report.actionable);+}++#[test]+fn empty_live_element_fails_as_stale_before_dispatch() {+ let err = check_live(+ &entry(),+ &NativeHandle::null(),+ &DeadLiveElementAdapter,+ &ActionRequest::headless(Action::Click),+ )+ .unwrap_err();++ assert_eq!(err.code, ErrorCode::StaleRef);+ assert!(err.message.contains("no longer exposes live"));+}++#[test]+fn live_read_errors_are_not_silently_downgraded_to_snapshot_data() {+ let err = check_live(+ &entry(),+ &NativeHandle::null(),+ &LiveReadErrorAdapter,+ &ActionRequest::headless(Action::Click),+ )+ .unwrap_err();++ assert_eq!(err.code, ErrorCode::PermDenied);+}diff --git a/crates/core/src/actionability_tests.rs b/crates/core/src/actionability_tests.rsnew file mode 100644index 000000000..dd4cad0e5--- /dev/null+++ b/crates/core/src/actionability_tests.rs@@ -0,0 +1,149 @@+use super::*;+use crate::{+ action::{Action, Direction},+ action_request::ActionRequest,+ adapter::SnapshotSurface,+ capability,+ node::Rect,+ refs::RefEntry,+};++fn entry() -> RefEntry {+ let bounds = Rect {+ x: 1.0,+ y: 1.0,+ width: 20.0,+ height: 20.0,+ };+ RefEntry {+ pid: 1,+ role: "button".into(),+ name: Some("OK".into()),+ value: None,+ description: None,+ states: vec![],+ bounds: Some(bounds),+ bounds_hash: Some(bounds.bounds_hash()),+ available_actions: vec![capability::CLICK.into()],+ source_app: None,+ source_window_id: None,+ source_window_title: None,+ source_surface: SnapshotSurface::Window,+ root_ref: None,+ path_is_absolute: true,+ path: smallvec::SmallVec::new(),+ }+}++#[test]+fn click_passes_when_target_is_enabled_visible_and_supported() {+ let report = check(&entry(), &ActionRequest::headless(Action::Click)).unwrap();++ assert!(report.actionable);+}++#[test]+fn disabled_entry_fails_before_action_dispatch() {+ let mut entry = entry();+ entry.states.push("disabled".into());++ let err = check(&entry, &ActionRequest::headless(Action::Click)).unwrap_err();++ assert_eq!(err.code, ErrorCode::ActionFailed);+ assert!(err.message.contains("enabled"));+ assert_eq!(err.details.as_ref().unwrap()["actionable"], false);+}++#[test]+fn zero_sized_bounds_fail_visibility() {+ let mut entry = entry();+ let bounds = Rect {+ x: 1.0,+ y: 1.0,+ width: 0.0,+ height: 20.0,+ };+ entry.bounds = Some(bounds);+ entry.bounds_hash = Some(bounds.bounds_hash());++ let err = check(&entry, &ActionRequest::headless(Action::Click)).unwrap_err();++ assert!(err.message.contains("visible"));+}++#[test]+fn text_input_requires_editable_target() {+ let err = check(+ &entry(),+ &ActionRequest::focus_fallback(Action::TypeText("hello".into())),+ )+ .unwrap_err();++ assert!(err.message.contains("editable"));+}++#[test]+fn cursor_movement_requires_physical_policy() {+ let err = check(&entry(), &ActionRequest::headless(Action::Hover)).unwrap_err();++ assert!(err.message.contains("policy"));+}++#[test]+fn headless_type_text_fails_policy_before_dispatch() {+ let mut target = entry();+ target.role = "textfield".into();+ target.available_actions = vec![capability::SET_VALUE.into()];++ let err = check(+ &target,+ &ActionRequest::headless(Action::TypeText("x".into())),+ )+ .unwrap_err();++ assert!(err.message.contains("policy"));+ assert!(err.message.contains("focus"));+}++#[test]+fn right_click_requires_right_click_capability_before_dispatch() {+ let err = check(&entry(), &ActionRequest::headless(Action::RightClick)).unwrap_err();++ assert_eq!(err.code, ErrorCode::ActionFailed);+ assert!(err.message.contains("supported_action"));+}++#[test]+fn command_aliases_match_platform_capabilities() {+ let click_entry = entry();+ assert!(check(&click_entry, &ActionRequest::headless(Action::DoubleClick)).is_ok());+ assert!(check(&click_entry, &ActionRequest::headless(Action::TripleClick)).is_ok());+ assert!(check(&click_entry, &ActionRequest::headless(Action::Check)).is_ok());+ assert!(check(&click_entry, &ActionRequest::headless(Action::Uncheck)).is_ok());++ let mut editable = entry();+ editable.role = "textfield".into();+ editable.available_actions = vec![capability::SET_VALUE.into()];+ assert!(check(&editable, &ActionRequest::headless(Action::Clear)).is_ok());++ let mut scrollable = entry();+ scrollable.available_actions = vec![capability::SCROLL.into()];+ assert!(+ check(+ &scrollable,+ &ActionRequest::headless(Action::Scroll(Direction::Down, 1))+ )+ .is_ok()+ );+ assert!(check(&scrollable, &ActionRequest::headless(Action::ScrollTo)).is_err());++ scrollable.available_actions = vec![capability::SCROLL_TO.into()];+ assert!(+ check(+ &scrollable,+ &ActionRequest::headless(Action::Scroll(Direction::Down, 1))+ )+ .is_ok()+ );+ assert!(check(&scrollable, &ActionRequest::headless(Action::ScrollTo)).is_ok());+}diff --git a/crates/core/src/adapter.rs b/crates/core/src/adapter.rsindex fee7a7b69..a5056a2c3 100644--- a/crates/core/src/adapter.rs+++ b/crates/core/src/adapter.rs@@ -1,9 +1,10 @@use crate::{PermissionReport, PermissionState,- action::{- ActionRequest, ActionResult, DragParams, ElementState, KeyCombo, MouseEvent, WindowOp,- },- error::AdapterError,+ action::{DragParams, KeyCombo, MouseEvent, WindowOp},+ action_request::ActionRequest,+ action_result::ActionResult,+ element_state::ElementState,+ error::{AdapterError, ErrorCode},node::{AccessibilityNode, AppInfo, Rect, SurfaceInfo, WindowInfo},notification::{NotificationFilter, NotificationIdentity, NotificationInfo},refs::RefEntry,@@ -34,6 +35,7 @@ impl SnapshotSurface {}}+#[derive(Clone, Copy)]pub struct TreeOptions {pub max_depth: u8,pub include_bounds: bool,@@ -56,6 +58,37 @@ impl Default for TreeOptions {}}+impl TreeOptions {+ pub(crate) fn with_ref_identity_bounds(mut self) -> Self {+ self.include_bounds = true;+ self+ }+}++#[derive(Debug, Clone, Default)]+pub struct LiveElement {+ pub state: Option<ElementState>,+ pub bounds: Option<Rect>,+ pub available_actions: Option<Vec<String>>,+}++pub(crate) fn optional_live_read<T>(+ result: Result<Option<T>, AdapterError>,+) -> Result<Option<T>, AdapterError> {+ match result {+ Ok(value) => Ok(value),+ Err(err) if is_live_read_unsupported(&err) => Ok(None),+ Err(err) => Err(err),+ }+}++fn is_live_read_unsupported(err: &AdapterError) -> bool {+ matches!(+ err.code,+ ErrorCode::PlatformNotSupported | ErrorCode::ActionNotSupported+ )+}+pub enum ScreenshotTarget {Screen(usize),/// Capture the frontmost window owned by this process ID.@@ -143,8 +176,24 @@ pub trait PlatformAdapter: Send + Sync {Err(AdapterError::not_supported("execute_action"))}- fn resolve_element(&self, _entry: &RefEntry) -> Result<NativeHandle, AdapterError> {- Err(AdapterError::not_supported("resolve_element"))+ fn resolve_element_strict(&self, _entry: &RefEntry) -> Result<NativeHandle, AdapterError> {+ Err(AdapterError::not_supported("resolve_element_strict"))+ }++ /// Resolves an element under a caller deadline. Defaults to delegating+ /// to [`PlatformAdapter::resolve_element_strict`], ignoring the timeout,+ /// so adapters that implement only the un-timed variant still support+ /// `wait --element`. Override to honor the remaining budget.+ fn resolve_element_strict_with_timeout(+ &self,+ entry: &RefEntry,+ timeout: std::time::Duration,+ ) -> Result<NativeHandle, AdapterError> {+ tracing::trace!(+ ?timeout,+ "resolve_element_strict_with_timeout: default impl does not enforce the deadline; override to honor it"+ );+ self.resolve_element_strict(entry)}/// Releases a platform-specific element handle returned from@@ -179,6 +228,14 @@ pub trait PlatformAdapter: Send + Sync {Err(AdapterError::not_supported("focus_window"))}+ /// Brings the application owning `pid` to the foreground. Best-effort guard+ /// invoked before physical (cursor/keyboard) input that targets a known+ /// element, so synthetic events land on the intended window rather than+ /// whatever happens to be frontmost.+ fn focus_app(&self, _pid: i32) -> Result<(), AdapterError> {+ Err(AdapterError::not_supported("focus_app"))+ }+fn launch_app(&self, _id: &str, _timeout_ms: u64) -> Result<WindowInfo, AdapterError> {Err(AdapterError::not_supported("launch_app"))}@@ -187,6 +244,14 @@ pub trait PlatformAdapter: Send + Sync {Err(AdapterError::not_supported("close_app"))}+ /// Reports whether closing `identifier` would terminate a process the OS+ /// depends on (window server, login session, shell). The set is+ /// inherently platform-specific, so each adapter owns its own list;+ /// core only asks. The default denies nothing.+ fn is_protected_process(&self, _identifier: &str) -> bool {+ false+ }+fn screenshot(&self, _target: ScreenshotTarget) -> Result<ImageBuffer, AdapterError> {Err(AdapterError::not_supported("screenshot"))}@@ -211,11 +276,30 @@ pub trait PlatformAdapter: Send + Sync {Err(AdapterError::not_supported("get_live_state"))}+ fn get_live_actions(+ &self,+ _handle: &NativeHandle,+ ) -> Result<Option<Vec<String>>, AdapterError> {+ Err(AdapterError::not_supported("get_live_actions"))+ }++ fn get_live_element(&self, handle: &NativeHandle) -> Result<LiveElement, AdapterError> {+ let live = LiveElement {+ state: optional_live_read(self.get_live_state(handle))?,+ bounds: optional_live_read(self.get_element_bounds(handle))?,+ available_actions: optional_live_read(self.get_live_actions(handle))?,+ };+ if live.state.is_none() && live.bounds.is_none() && live.available_actions.is_none() {+ return Err(AdapterError::not_supported("get_live_element"));+ }+ Ok(live)+ }+fn press_key_for_app(&self,_app_name: &str,_combo: &crate::action::KeyCombo,- ) -> Result<crate::action::ActionResult, AdapterError> {+ ) -> Result<crate::action_result::ActionResult, AdapterError> {Err(AdapterError::not_supported("press_key_for_app"))}diff --git a/crates/core/src/capability.rs b/crates/core/src/capability.rsnew file mode 100644index 000000000..a1ad11e43--- /dev/null+++ b/crates/core/src/capability.rs@@ -0,0 +1,114 @@+use crate::action::Action;++pub const CLICK: &str = "Click";+pub const RIGHT_CLICK: &str = "RightClick";+pub const SET_VALUE: &str = "SetValue";+pub const SET_FOCUS: &str = "SetFocus";+pub const EXPAND: &str = "Expand";+pub const COLLAPSE: &str = "Collapse";+pub const SELECT: &str = "Select";+pub const TOGGLE: &str = "Toggle";+pub const SCROLL: &str = "Scroll";+pub const SCROLL_TO: &str = "ScrollTo";+pub const PRESS_KEY: &str = "PressKey";+pub const KEY_DOWN: &str = "KeyDown";+pub const KEY_UP: &str = "KeyUp";+pub const TYPE_TEXT: &str = "TypeText";+pub const HOVER: &str = "Hover";+pub const DRAG: &str = "Drag";+pub const CHECK: &str = "Check";+pub const UNCHECK: &str = "Uncheck";++pub const CHECKED_APPLICABILITY: &[&str] = &[TOGGLE, CHECK, UNCHECK];+pub const EXPANDED_APPLICABILITY: &[&str] = &[EXPAND, COLLAPSE];++pub fn for_action(action: &Action) -> &'static [&'static str] {+ match action {+ Action::Click | Action::DoubleClick | Action::TripleClick => &[CLICK],+ Action::RightClick => &[RIGHT_CLICK],+ Action::SetValue(_) | Action::Clear => &[SET_VALUE],+ Action::SetFocus => &[SET_FOCUS],+ Action::Expand => &[EXPAND],+ Action::Collapse => &[COLLAPSE],+ Action::Select(_) => &[SELECT, CLICK],+ Action::Toggle => &[TOGGLE, CLICK],+ Action::Check | Action::Uncheck => &[TOGGLE, CLICK],+ Action::Scroll(_, _) => &[SCROLL, SCROLL_TO],+ Action::ScrollTo => &[SCROLL_TO],+ Action::PressKey(_) => &[PRESS_KEY],+ Action::KeyDown(_) => &[KEY_DOWN],+ Action::KeyUp(_) => &[KEY_UP],+ Action::TypeText(_) => &[TYPE_TEXT, SET_VALUE],+ Action::Hover => &[HOVER],+ Action::Drag(_) => &[DRAG],+ }+}++pub fn defaults_for_role(role: &str) -> Vec<String> {+ let capabilities: &[&str] = match role {+ "button" | "link" | "menuitem" | "tab" | "radiobutton" => &[CLICK],+ "textfield" | "incrementor" => &[CLICK, SET_VALUE, SET_FOCUS],+ "checkbox" => &[CLICK, TOGGLE],+ "combobox" => &[CLICK, SELECT],+ "treeitem" => &[CLICK, EXPAND, COLLAPSE],+ "slider" => &[SET_VALUE],+ "cell" => &[CLICK],+ _ => &[CLICK],+ };+ capabilities+ .iter()+ .map(|capability| (*capability).to_string())+ .collect()+}++pub fn contains(actions: &[String], capability: &str) -> bool {+ actions.iter().any(|action| action == capability)+}++pub fn contains_any(actions: &[String], capabilities: &[&str]) -> bool {+ capabilities+ .iter()+ .any(|capability| contains(actions, capability))+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::action::{Direction, KeyCombo};++ #[test]+ fn action_capabilities_are_declared_in_one_place() {+ assert_eq!(for_action(&Action::Click), &[CLICK]);+ assert_eq!(for_action(&Action::RightClick), &[RIGHT_CLICK]);+ assert_eq!(for_action(&Action::SetValue("x".into())), &[SET_VALUE]);+ assert_eq!(for_action(&Action::Clear), &[SET_VALUE]);+ assert_eq!(+ for_action(&Action::Scroll(Direction::Down, 1)),+ &[SCROLL, SCROLL_TO]+ );+ assert_eq!(+ for_action(&Action::PressKey(KeyCombo {+ key: "A".into(),+ modifiers: vec![],+ })),+ &[PRESS_KEY]+ );+ }++ #[test]+ fn role_defaults_are_declared_in_one_place() {+ assert_eq!(defaults_for_role("button"), strings(&[CLICK]));+ assert_eq!(+ defaults_for_role("textfield"),+ strings(&[CLICK, SET_VALUE, SET_FOCUS])+ );+ assert_eq!(+ defaults_for_role("treeitem"),+ strings(&[CLICK, EXPAND, COLLAPSE])+ );+ }++ fn strings(values: &[&str]) -> Vec<String> {+ values.iter().map(|value| (*value).to_string()).collect()+ }+}diff --git a/crates/core/src/commands/batch.rs b/crates/core/src/commands/batch.rsindex c778e4b76..3a792ece6 100644--- a/crates/core/src/commands/batch.rs+++ b/crates/core/src/commands/batch.rs@@ -10,6 +10,7 @@ pub struct BatchArgs {#[derive(Debug, Deserialize)]pub struct BatchCommand {pub command: String,+ pub session: Option<String>,#[serde(default)]pub args: Value,}diff --git a/crates/core/src/commands/check.rs b/crates/core/src/commands/check.rsindex e682d6b92..f05435df0 100644--- a/crates/core/src/commands/check.rs+++ b/crates/core/src/commands/check.rs@@ -1,11 +1,22 @@use crate::{- action::{Action, ActionRequest},+ action::Action,adapter::PlatformAdapter,- commands::helpers::{RefArgs, execute_ref_action},+ commands::helpers::{RefArgs, execute_ref_action_with_context},+ context::CommandContext,error::AppError,+ interaction_policy::InteractionPolicy,};use serde_json::Value;-pub fn execute(args: RefArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- execute_ref_action(args, adapter, ActionRequest::headless(Action::Check))+pub fn execute(+ args: RefArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ execute_ref_action_with_context(+ args,+ adapter,+ context.request(Action::Check, InteractionPolicy::headless()),+ context,+ )}diff --git a/crates/core/src/commands/clear.rs b/crates/core/src/commands/clear.rsindex dee80ee8e..60de3a77d 100644--- a/crates/core/src/commands/clear.rs+++ b/crates/core/src/commands/clear.rs@@ -1,11 +1,22 @@use crate::{- action::{Action, ActionRequest},+ action::Action,adapter::PlatformAdapter,- commands::helpers::{RefArgs, execute_ref_action},+ commands::helpers::{RefArgs, execute_ref_action_with_context},+ context::CommandContext,error::AppError,+ interaction_policy::InteractionPolicy,};use serde_json::Value;-pub fn execute(args: RefArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- execute_ref_action(args, adapter, ActionRequest::headless(Action::Clear))+pub fn execute(+ args: RefArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ execute_ref_action_with_context(+ args,+ adapter,+ context.request(Action::Clear, InteractionPolicy::headless()),+ context,+ )}diff --git a/crates/core/src/commands/click.rs b/crates/core/src/commands/click.rsindex 7e26f3c30..61f3c7846 100644--- a/crates/core/src/commands/click.rs+++ b/crates/core/src/commands/click.rs@@ -1,11 +1,22 @@use crate::{- action::{Action, ActionRequest},+ action::Action,adapter::PlatformAdapter,- commands::helpers::{RefArgs, execute_ref_action},+ commands::helpers::{RefArgs, execute_ref_action_with_context},+ context::CommandContext,error::AppError,+ interaction_policy::InteractionPolicy,};use serde_json::Value;-pub fn execute(args: RefArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- execute_ref_action(args, adapter, ActionRequest::headless(Action::Click))+pub fn execute(+ args: RefArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ execute_ref_action_with_context(+ args,+ adapter,+ context.request(Action::Click, InteractionPolicy::headless()),+ context,+ )}diff --git a/crates/core/src/commands/close_app.rs b/crates/core/src/commands/close_app.rsindex ef28932f2..3d6cdd763 100644--- a/crates/core/src/commands/close_app.rs+++ b/crates/core/src/commands/close_app.rs@@ -1,21 +1,30 @@use crate::{adapter::PlatformAdapter, error::AppError};use serde_json::{Value, json};-const PROTECTED_PROCESSES: &[&str] = &["loginwindow", "windowserver", "dock", "launchd", "finder"];-pub struct CloseAppArgs {pub app: String,pub force: bool,}pub fn execute(args: CloseAppArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- let lower = args.app.to_lowercase();- if PROTECTED_PROCESSES.iter().any(|p| lower.contains(p)) {- return Err(AppError::invalid_input(format!(- "'{}' is a protected system process and cannot be closed",- args.app- )));+ if adapter.is_protected_process(&args.app) {+ return Err(AppError::invalid_input_with_suggestion(+ format!(+ "'{}' is a protected system process and cannot be closed",+ args.app+ ),+ "Target a regular application; session-critical processes (loginwindow, WindowServer, Dock, Finder, launchd) are never closed.",+ ));}adapter.close_app(&args.app, args.force)?;- Ok(json!({ "app": args.app, "closed": true }))+ Ok(json!({+ "app": args.app,+ "method": if args.force { "force" } else { "graceful" },+ "requested": true,+ "closed": args.force+ }))}++#[cfg(test)]+#[path = "close_app_tests.rs"]+mod tests;diff --git a/crates/core/src/commands/close_app_tests.rs b/crates/core/src/commands/close_app_tests.rsnew file mode 100644index 000000000..d9ae2b712--- /dev/null+++ b/crates/core/src/commands/close_app_tests.rs@@ -0,0 +1,96 @@+use super::*;+use crate::adapter::PlatformAdapter;+use crate::error::{AdapterError, ErrorCode};++struct ProtectiveAdapter;++impl PlatformAdapter for ProtectiveAdapter {+ fn is_protected_process(&self, identifier: &str) -> bool {+ identifier.eq_ignore_ascii_case("CriticalThing")+ }++ fn close_app(&self, _id: &str, _force: bool) -> Result<(), crate::error::AdapterError> {+ Ok(())+ }+}++struct FailingAdapter;++impl PlatformAdapter for FailingAdapter {+ fn close_app(&self, _id: &str, _force: bool) -> Result<(), AdapterError> {+ Err(AdapterError::new(ErrorCode::AppNotFound, "no such app"))+ }+}++#[test]+fn close_app_blocks_adapter_protected_process() {+ let err = execute(+ CloseAppArgs {+ app: "CriticalThing".into(),+ force: false,+ },+ &ProtectiveAdapter,+ )+ .unwrap_err();++ assert_eq!(err.code(), "INVALID_ARGS");+ assert!(err.to_string().contains("protected"));+ let suggestion = err+ .suggestion()+ .expect("protected-process error must carry a suggestion");+ assert!(+ suggestion.contains("session-critical"),+ "suggestion should name session-critical processes, got: {suggestion}"+ );+}++#[test]+fn graceful_close_reports_request_without_claiming_termination() {+ let value = execute(+ CloseAppArgs {+ app: "TextEdit".into(),+ force: false,+ },+ &ProtectiveAdapter,+ )+ .unwrap();++ assert_eq!(value["app"], "TextEdit");+ assert_eq!(value["method"], "graceful");+ assert_eq!(value["requested"], true);+ assert_eq!(+ value["closed"], false,+ "graceful close must not claim a termination it cannot confirm"+ );+}++#[test]+fn close_app_propagates_adapter_errors() {+ let err = execute(+ CloseAppArgs {+ app: "Ghost".into(),+ force: true,+ },+ &FailingAdapter,+ )+ .unwrap_err();++ assert_eq!(err.code(), "APP_NOT_FOUND");+}++#[test]+fn forced_close_confirms_termination() {+ let value = execute(+ CloseAppArgs {+ app: "TextEdit".into(),+ force: true,+ },+ &ProtectiveAdapter,+ )+ .unwrap();++ assert_eq!(value["app"], "TextEdit");+ assert_eq!(value["method"], "force");+ assert_eq!(value["requested"], true);+ assert_eq!(value["closed"], true);+}diff --git a/crates/core/src/commands/collapse.rs b/crates/core/src/commands/collapse.rsindex e0a231886..b904cbbf3 100644--- a/crates/core/src/commands/collapse.rs+++ b/crates/core/src/commands/collapse.rs@@ -1,11 +1,22 @@use crate::{- action::{Action, ActionRequest},+ action::Action,adapter::PlatformAdapter,- commands::helpers::{RefArgs, execute_ref_action},+ commands::helpers::{RefArgs, execute_ref_action_with_context},+ context::CommandContext,error::AppError,+ interaction_policy::InteractionPolicy,};use serde_json::Value;-pub fn execute(args: RefArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- execute_ref_action(args, adapter, ActionRequest::headless(Action::Collapse))+pub fn execute(+ args: RefArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ execute_ref_action_with_context(+ args,+ adapter,+ context.request(Action::Collapse, InteractionPolicy::headless()),+ context,+ )}diff --git a/crates/core/src/commands/double_click.rs b/crates/core/src/commands/double_click.rsindex 1e70bad73..2344aacfa 100644--- a/crates/core/src/commands/double_click.rs+++ b/crates/core/src/commands/double_click.rs@@ -1,11 +1,25 @@use crate::{- action::{Action, ActionRequest},+ action::Action,adapter::PlatformAdapter,- commands::helpers::{RefArgs, execute_ref_action},+ commands::helpers::{RefArgs, execute_ref_action_with_context},+ context::CommandContext,error::AppError,+ interaction_policy::InteractionPolicy,};use serde_json::Value;-pub fn execute(args: RefArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- execute_ref_action(args, adapter, ActionRequest::headless(Action::DoubleClick))+/// Double-click tries AXOpen (headless) first. Without `--headed` and no+/// AXOpen it fails closed; with `--headed` the chain may perform a physical+/// double-click.+pub fn execute(+ args: RefArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ execute_ref_action_with_context(+ args,+ adapter,+ context.request(Action::DoubleClick, InteractionPolicy::headless()),+ context,+ )}diff --git a/crates/core/src/commands/drag.rs b/crates/core/src/commands/drag.rsindex 718f242c4..3e6a7df69 100644--- a/crates/core/src/commands/drag.rs+++ b/crates/core/src/commands/drag.rs@@ -1,7 +1,11 @@use crate::{- action::{DragParams, Point},+ action::DragParams,adapter::PlatformAdapter,- commands::helpers::resolve_point_from_ref_or_xy,+ commands::point_resolve::{+ PointResolveArgs, focus_for_physical_input, require_cursor_policy,+ resolve_point_from_ref_or_xy_with_context,+ },+ context::CommandContext,error::AppError,};use serde_json::{Value, json};@@ -13,48 +17,57 @@ pub struct DragArgs {pub to_xy: Option<(f64, f64)>,pub snapshot_id: Option<String>,pub duration_ms: Option<u64>,+ pub drop_delay_ms: Option<u64>,}-pub fn execute(args: DragArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- let from = resolve_point(- &args.from_ref,- args.from_xy,- "from",- args.snapshot_id.as_deref(),+pub fn execute(+ args: DragArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ require_cursor_policy(context, "drag")?;+ let from = resolve_point_from_ref_or_xy_with_context(+ PointResolveArgs {+ ref_id: args.from_ref.as_deref(),+ xy: args.from_xy,+ snapshot_id: args.snapshot_id.as_deref(),+ missing_input_message: "Provide --from <ref> or --from-xy x,y",+ },adapter,+ context,)?;- let to = resolve_point(- &args.to_ref,- args.to_xy,- "to",- args.snapshot_id.as_deref(),+ let to = resolve_point_from_ref_or_xy_with_context(+ PointResolveArgs {+ ref_id: args.to_ref.as_deref(),+ xy: args.to_xy,+ snapshot_id: args.snapshot_id.as_deref(),+ missing_input_message: "Provide --to <ref> or --to-xy x,y",+ },adapter,+ context,)?;+ let focused = focus_for_physical_input(from.pid, adapter, context)?;let params = DragParams {- from: from.clone(),- to: to.clone(),+ from: from.point.clone(),+ to: to.point.clone(),duration_ms: args.duration_ms,+ drop_delay_ms: args.drop_delay_ms,};adapter.drag(params)?;- Ok(json!({+ let mut response = json!({"dragged": true,- "from": { "x": from.x, "y": from.y },- "to": { "x": to.x, "y": to.y }- }))+ "from": { "x": from.point.x, "y": from.point.y },+ "to": { "x": to.point.x, "y": to.point.y }+ });+ if let Some(drop_delay_ms) = args.drop_delay_ms {+ response["drop_delay_ms"] = json!(drop_delay_ms);+ }+ if focused {+ response["focused"] = json!(true);+ }+ Ok(response)}-fn resolve_point(- ref_id: &Option<String>,- xy: Option<(f64, f64)>,- label: &str,- snapshot_id: Option<&str>,- adapter: &dyn PlatformAdapter,-) -> Result<Point, AppError> {- resolve_point_from_ref_or_xy(- ref_id.as_deref(),- xy,- snapshot_id,- adapter,- format!("Provide --{label} <ref> or --{label}-xy x,y"),- )-}+#[cfg(test)]+#[path = "drag_tests.rs"]+mod tests;diff --git a/crates/core/src/commands/drag_tests.rs b/crates/core/src/commands/drag_tests.rsnew file mode 100644index 000000000..70ff9e2ac--- /dev/null+++ b/crates/core/src/commands/drag_tests.rs@@ -0,0 +1,213 @@+use super::*;+use crate::{+ action::DragParams,+ adapter::{NativeHandle, PlatformAdapter},+ capability,+ error::AdapterError,+ node::Rect,+ refs::{RefEntry, RefMap},+ refs_store::RefStore,+ refs_test_support::HomeGuard,+};+use std::sync::Mutex;++struct DragCaptureAdapter {+ captured: Mutex<Option<DragParams>>,+ focused_pids: Mutex<Vec<i32>>,+}++impl DragCaptureAdapter {+ fn new() -> Self {+ Self {+ captured: Mutex::new(None),+ focused_pids: Mutex::new(Vec::new()),+ }+ }+}++impl PlatformAdapter for DragCaptureAdapter {+ fn resolve_element_strict(&self, _entry: &RefEntry) -> Result<NativeHandle, AdapterError> {+ Ok(NativeHandle::null())+ }++ fn get_element_bounds(&self, _handle: &NativeHandle) -> Result<Option<Rect>, AdapterError> {+ Ok(Some(Rect {+ x: 10.0,+ y: 20.0,+ width: 40.0,+ height: 60.0,+ }))+ }++ fn focus_app(&self, pid: i32) -> Result<(), AdapterError> {+ self.focused_pids.lock().unwrap().push(pid);+ Ok(())+ }++ fn drag(&self, params: DragParams) -> Result<(), AdapterError> {+ *self.captured.lock().unwrap() = Some(params);+ Ok(())+ }+}++fn xy_args(drop_delay_ms: Option<u64>) -> DragArgs {+ DragArgs {+ from_ref: None,+ from_xy: Some((1.0, 2.0)),+ to_ref: None,+ to_xy: Some((3.0, 4.0)),+ snapshot_id: None,+ duration_ms: None,+ drop_delay_ms,+ }+}++#[test]+fn drop_delay_is_threaded_into_drag_params_and_response() {+ let adapter = DragCaptureAdapter::new();++ let value = execute(+ xy_args(Some(750)),+ &adapter,+ &CommandContext::default().with_headed(true),+ )+ .unwrap();++ assert_eq!(value["dragged"], true);+ assert_eq!(value["drop_delay_ms"], 750);+ let captured = adapter.captured.lock().unwrap().clone().unwrap();+ assert_eq!(captured.drop_delay_ms, Some(750));+ assert_eq!((captured.from.x, captured.from.y), (1.0, 2.0));+ assert_eq!((captured.to.x, captured.to.y), (3.0, 4.0));+}++#[test]+fn drop_delay_omitted_uses_adapter_default_and_no_response_field() {+ let adapter = DragCaptureAdapter::new();++ let value = execute(+ xy_args(None),+ &adapter,+ &CommandContext::default().with_headed(true),+ )+ .unwrap();++ assert!(value.get("drop_delay_ms").is_none());+ let captured = adapter.captured.lock().unwrap().clone().unwrap();+ assert_eq!(captured.drop_delay_ms, None);+}++fn ref_entry(pid: i32) -> RefEntry {+ RefEntry {+ pid,+ role: "button".into(),+ name: Some("Item".into()),+ value: None,+ description: None,+ states: vec![],+ bounds: None,+ bounds_hash: None,+ available_actions: vec![capability::CLICK.into()],+ source_app: None,+ source_window_id: None,+ source_window_title: None,+ source_surface: crate::adapter::SnapshotSurface::Window,+ root_ref: None,+ path_is_absolute: false,+ path: smallvec::SmallVec::new(),+ }+}++fn cross_app_snapshot() -> String {+ let store = RefStore::new().unwrap();+ let mut refmap = RefMap::new();+ refmap.allocate(ref_entry(1));+ refmap.allocate(ref_entry(2));+ store.save_new_snapshot(&refmap).unwrap()+}++fn cross_app_args(snapshot_id: String) -> DragArgs {+ DragArgs {+ from_ref: Some("@e1".into()),+ from_xy: None,+ to_ref: Some("@e2".into()),+ to_xy: None,+ snapshot_id: Some(snapshot_id),+ duration_ms: None,+ drop_delay_ms: None,+ }+}++#[test]+fn drag_resolves_ref_bounds_to_center_point() {+ let _guard = HomeGuard::new();+ let store = RefStore::new().unwrap();+ let mut refmap = RefMap::new();+ refmap.allocate(ref_entry(1));+ let snapshot_id = store.save_new_snapshot(&refmap).unwrap();+ let adapter = DragCaptureAdapter::new();++ let args = DragArgs {+ from_ref: Some("@e1".into()),+ from_xy: None,+ to_ref: None,+ to_xy: Some((100.0, 200.0)),+ snapshot_id: Some(snapshot_id),+ duration_ms: None,+ drop_delay_ms: Some(300),+ };+ execute(args, &adapter, &CommandContext::default().with_headed(true)).unwrap();++ let captured = adapter.captured.lock().unwrap().clone().unwrap();+ assert_eq!((captured.from.x, captured.from.y), (30.0, 50.0));+}++#[test]+fn headless_ref_drag_is_policy_denied_before_cursor_move() {+ let _guard = HomeGuard::new();+ let snapshot_id = cross_app_snapshot();+ let adapter = DragCaptureAdapter::new();++ let err = execute(+ cross_app_args(snapshot_id),+ &adapter,+ &CommandContext::default(),+ )+ .unwrap_err();++ assert_eq!(err.code(), "POLICY_DENIED");+ assert!(adapter.focused_pids.lock().unwrap().is_empty());+ assert!(adapter.captured.lock().unwrap().is_none());+}++#[test]+fn headed_ref_drag_focuses_only_the_from_app_once() {+ let _guard = HomeGuard::new();+ let snapshot_id = cross_app_snapshot();+ let adapter = DragCaptureAdapter::new();++ let value = execute(+ cross_app_args(snapshot_id),+ &adapter,+ &CommandContext::default().with_headed(true),+ )+ .unwrap();++ assert_eq!(*adapter.focused_pids.lock().unwrap(), vec![1]);+ assert_eq!(value["focused"], true);+}++#[test]+fn headed_xy_drag_never_steals_focus() {+ let adapter = DragCaptureAdapter::new();++ let value = execute(+ xy_args(None),+ &adapter,+ &CommandContext::default().with_headed(true),+ )+ .unwrap();++ assert!(adapter.focused_pids.lock().unwrap().is_empty());+ assert!(value.get("focused").is_none());+}diff --git a/crates/core/src/commands/expand.rs b/crates/core/src/commands/expand.rsindex 4d4a65f47..f3d2fbc98 100644--- a/crates/core/src/commands/expand.rs+++ b/crates/core/src/commands/expand.rs@@ -1,11 +1,22 @@use crate::{- action::{Action, ActionRequest},+ action::Action,adapter::PlatformAdapter,- commands::helpers::{RefArgs, execute_ref_action},+ commands::helpers::{RefArgs, execute_ref_action_with_context},+ context::CommandContext,error::AppError,+ interaction_policy::InteractionPolicy,};use serde_json::Value;-pub fn execute(args: RefArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- execute_ref_action(args, adapter, ActionRequest::headless(Action::Expand))+pub fn execute(+ args: RefArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ execute_ref_action_with_context(+ args,+ adapter,+ context.request(Action::Expand, InteractionPolicy::headless()),+ context,+ )}diff --git a/crates/core/src/commands/find.rs b/crates/core/src/commands/find.rsindex 4102ea33b..90ffe91eb 100644--- a/crates/core/src/commands/find.rs+++ b/crates/core/src/commands/find.rs@@ -1,7 +1,9 @@use crate::{- adapter::PlatformAdapter, error::AppError, node::AccessibilityNode, search_text, snapshot,+ adapter::PlatformAdapter, context::CommandContext, error::AppError, node::AccessibilityNode,+ roles, search_text, snapshot,};use serde_json::{Value, json};+use std::collections::BTreeSet;const DEFAULT_LIMIT: usize = 50;@@ -18,15 +20,19 @@ pub struct FindArgs {pub limit: Option<usize>,}-pub fn execute(args: FindArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {+pub fn execute(+ args: FindArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {validate_find_mode(&args)?;+ let query = FindQuery::from_args(&args);let opts = crate::adapter::TreeOptions::default();let result = if args.count {snapshot::build(adapter, &opts, args.app.as_deref(), None)?} else {- snapshot::run(adapter, &opts, args.app.as_deref(), None)?+ snapshot::run_with_context(adapter, &opts, args.app.as_deref(), None, context)?};- let query = FindQuery::from_args(&args);if args.count {return Ok(json!({ "count": count_matches(&result.tree, &query) }));@@ -43,18 +49,74 @@ pub fn execute(args: FindArgs, adapter: &dyn PlatformAdapter) -> Result<Value, A);if args.first {- return Ok(json!({ "match": matches.into_iter().next() }));+ return Ok(single_match_response(+ matches.into_iter().next(),+ &query,+ &result.tree,+ ));}if args.last {- return Ok(json!({ "match": matches.into_iter().last() }));+ return Ok(single_match_response(+ matches.into_iter().last(),+ &query,+ &result.tree,+ ));}if let Some(n) = args.nth {- return Ok(json!({ "match": matches.into_iter().nth(n) }));+ return Ok(single_match_response(+ matches.into_iter().nth(n),+ &query,+ &result.tree,+ ));}- Ok(json!({ "matches": matches }))+ let mut response = json!({ "matches": matches });+ attach_roles_present_hint(&mut response, matches.is_empty(), &query, &result.tree);+ Ok(response)+}++/// When a role-filtered search returns nothing, the caller cannot tell+/// "no elements of this role are on screen" from "this role name does not+/// exist." Listing the roles actually present in the searched tree answers+/// that from live data — no hardcoded vocabulary, so a role any adapter+/// newly emits shows up here automatically.+fn attach_roles_present_hint(+ response: &mut Value,+ is_empty: bool,+ query: &FindQuery,+ tree: &AccessibilityNode,+) {+ if !is_empty || query.role.is_none() {+ return;+ }+ let mut present = BTreeSet::new();+ collect_roles(tree, &mut present);+ if let Some(obj) = response.as_object_mut() {+ obj.insert(+ "roles_present".into(),+ json!(present.into_iter().collect::<Vec<_>>()),+ );+ }+}++fn single_match_response(+ found: Option<Value>,+ query: &FindQuery,+ tree: &AccessibilityNode,+) -> Value {+ let is_empty = found.is_none();+ let mut response = json!({ "match": found });+ attach_roles_present_hint(&mut response, is_empty, query, tree);+ response+}++fn collect_roles(node: &AccessibilityNode, roles: &mut BTreeSet<String>) {+ roles.insert(node.role.clone());+ for child in &node.children {+ collect_roles(child, roles);+ }}fn max_matches_for_args(args: &FindArgs) -> Option<usize> {@@ -87,17 +149,18 @@ fn validate_find_mode(args: &FindArgs) -> Result<(), AppError> {Ok(())}-struct FindQuery<'a> {- role: Option<&'a str>,+#[derive(Debug)]+struct FindQuery {+ role: Option<String>,name: Option<String>,value: Option<String>,text: Option<String>,}-impl<'a> FindQuery<'a> {- fn from_args(args: &'a FindArgs) -> Self {+impl FindQuery {+ fn from_args(args: &FindArgs) -> Self {Self {- role: args.role.as_deref(),+ role: args.role.as_deref().map(roles::normalize_role_query),name: args.name.as_deref().map(search_text::normalize),value: args.value.as_deref().map(search_text::normalize),text: args.text.as_deref().map(search_text::normalize),@@ -125,10 +188,11 @@ fn search_tree(.map(String::from).unwrap_or_else(|| format!("(unnamed {})", node.role));matches.push(json!({- "ref": node.ref_id,+ "ref_id": node.ref_id,"role": node.role,"name": display_name,"value": node.value,+ "states": node.states,"interactive": interactive,"path": path.clone()}));@@ -166,7 +230,7 @@ fn count_matches(node: &AccessibilityNode, query: &FindQuery) -> usize {}fn node_matches(node: &AccessibilityNode, query: &FindQuery) -> bool {- let role_match = query.role.is_none_or(|r| node.role == r);+ let role_match = query.role.as_deref().is_none_or(|r| node.role == r);let name_match = query.name.as_deref().is_none_or(|n| {node.name.as_deref()diff --git a/crates/core/src/commands/find_tests.rs b/crates/core/src/commands/find_tests.rsindex 69c2438f3..a0930e2f9 100644--- a/crates/core/src/commands/find_tests.rs+++ b/crates/core/src/commands/find_tests.rs@@ -32,6 +32,25 @@ fn display_name_prefers_value_before_description() {assert_eq!(matches[0]["name"], "current value");}+#[test]+fn search_tree_match_uses_ref_id_contract_and_includes_states() {+ let mut root = node(Some("Save"), None, None);+ root.states = vec!["enabled".into()];+ let query = FindQuery {+ role: None,+ name: None,+ value: None,+ text: None,+ };+ let mut matches = Vec::new();++ search_tree(&root, &query, &mut Vec::new(), &mut matches, None);++ assert_eq!(matches[0]["ref_id"], "@e1");+ assert!(matches[0].get("ref").is_none());+ assert_eq!(matches[0]["states"], serde_json::json!(["enabled"]));+}+#[test]fn search_tree_matches_text_across_fields() {let root = node(None, Some("Primary"), Some("Secondary"));@@ -130,3 +149,110 @@ fn count_matches_does_not_build_result_json() {assert_eq!(count_matches(&root, &query), 2);}++fn role_node(role: &str, name: Option<&str>) -> AccessibilityNode {+ let mut n = node(name, None, None);+ n.role = role.into();+ n+}++#[test]+fn textarea_alias_resolves_to_textfield_query() {+ let query = FindQuery::from_args(&FindArgs {+ app: None,+ role: Some("textarea".into()),+ name: None,+ value: None,+ text: None,+ count: false,+ first: false,+ last: false,+ nth: None,+ limit: None,+ });++ assert_eq!(query.role.as_deref(), Some("textfield"));++ let root = node(None, Some("doc body"), None);+ let mut matches = Vec::new();+ search_tree(&root, &query, &mut Vec::new(), &mut matches, None);+ assert_eq!(matches.len(), 1);+}++#[test]+fn unknown_role_passes_through_and_matches_nothing() {+ let query = FindQuery::from_args(&FindArgs {+ app: None,+ role: Some("navbar".into()),+ name: None,+ value: None,+ text: None,+ count: false,+ first: false,+ last: false,+ nth: None,+ limit: None,+ });++ assert_eq!(query.role.as_deref(), Some("navbar"));++ let root = role_node("textfield", Some("body"));+ let mut matches = Vec::new();+ search_tree(&root, &query, &mut Vec::new(), &mut matches, None);+ assert!(matches.is_empty());+}++#[test]+fn empty_role_filtered_result_reports_roles_present_from_tree() {+ let mut root = role_node("window", Some("Save"));+ root.children = vec![+ role_node("button", Some("OK")),+ role_node("textfield", None),+ ];++ let query = FindQuery::from_args(&FindArgs {+ app: None,+ role: Some("navbar".into()),+ name: None,+ value: None,+ text: None,+ count: false,+ first: false,+ last: false,+ nth: None,+ limit: None,+ });+ let response = single_match_response(None, &query, &root);++ let present = response["roles_present"].as_array().unwrap();+ let names: Vec<&str> = present.iter().filter_map(|v| v.as_str()).collect();+ assert!(names.contains(&"button"));+ assert!(names.contains(&"textfield"));+ assert!(names.contains(&"window"));+ assert!(!names.contains(&"navbar"));+}++#[test]+fn roles_present_hint_is_omitted_when_a_match_is_found() {+ let root = role_node("textfield", Some("body"));+ let query = FindQuery::from_args(&FindArgs {+ app: None,+ role: Some("textfield".into()),+ name: None,+ value: None,+ text: None,+ count: false,+ first: false,+ last: false,+ nth: None,+ limit: None,+ });++ let mut matches = Vec::new();+ search_tree(&root, &query, &mut Vec::new(), &mut matches, None);+ let mut response = json!({ "matches": matches });+ let is_empty = response["matches"].as_array().unwrap().is_empty();+ attach_roles_present_hint(&mut response, is_empty, &query, &root);++ assert!(response.get("roles_present").is_none());+}diff --git a/crates/core/src/commands/focus.rs b/crates/core/src/commands/focus.rsindex d4c59d771..cdda016c6 100644--- a/crates/core/src/commands/focus.rs+++ b/crates/core/src/commands/focus.rs@@ -1,11 +1,22 @@use crate::{- action::{Action, ActionRequest},+ action::Action,adapter::PlatformAdapter,- commands::helpers::{RefArgs, execute_ref_action},+ commands::helpers::{RefArgs, execute_ref_action_with_context},+ context::CommandContext,error::AppError,+ interaction_policy::InteractionPolicy,};use serde_json::Value;-pub fn execute(args: RefArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- execute_ref_action(args, adapter, ActionRequest::headless(Action::SetFocus))+pub fn execute(+ args: RefArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ execute_ref_action_with_context(+ args,+ adapter,+ context.request(Action::SetFocus, InteractionPolicy::headless()),+ context,+ )}diff --git a/crates/core/src/commands/get.rs b/crates/core/src/commands/get.rsindex f3aec97ae..d5f02b1b5 100644--- a/crates/core/src/commands/get.rs+++ b/crates/core/src/commands/get.rs@@ -1,4 +1,9 @@-use crate::{adapter::PlatformAdapter, commands::helpers::resolve_ref, error::AppError};+use crate::{+ adapter::{PlatformAdapter, optional_live_read},+ commands::helpers::resolve_ref_with_context,+ context::CommandContext,+ error::AppError,+};use serde_json::{Value, json};pub struct GetArgs {@@ -16,27 +21,27 @@ pub enum GetProperty {States,}-pub fn execute(args: GetArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- let (entry, handle) = resolve_ref(&args.ref_id, args.snapshot_id.as_deref(), adapter)?;+pub fn execute(+ args: GetArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ let (entry, handle) =+ resolve_ref_with_context(&args.ref_id, args.snapshot_id.as_deref(), adapter, context)?;- let value = match args.property {- GetProperty::Role => json!(entry.role),- GetProperty::Title => json!(entry.name),- GetProperty::Text | GetProperty::Value => {- let live = adapter.get_live_value(handle.handle()).ok().flatten();- json!(live.or(entry.value))+ let (prop_name, value) = match args.property {+ GetProperty::Role => ("role", json!(entry.role)),+ GetProperty::Title => ("title", json!(entry.name)),+ GetProperty::Text => {+ let live = optional_live_read(adapter.get_live_value(handle.handle()))?;+ ("text", json!(live.or(entry.value)))}- GetProperty::Bounds => json!(entry.bounds),- GetProperty::States => json!(entry.states),- };-- let prop_name = match args.property {- GetProperty::Text => "text",- GetProperty::Value => "value",- GetProperty::Title => "title",- GetProperty::Bounds => "bounds",- GetProperty::Role => "role",- GetProperty::States => "states",+ GetProperty::Value => {+ let live = optional_live_read(adapter.get_live_value(handle.handle()))?;+ ("value", json!(live.or(entry.value)))+ }+ GetProperty::Bounds => ("bounds", json!(entry.bounds)),+ GetProperty::States => ("states", json!(entry.states)),};Ok(json!({ "property": prop_name, "ref": args.ref_id, "value": value }))diff --git a/crates/core/src/commands/helpers.rs b/crates/core/src/commands/helpers.rsindex 5ec33034c..ee675fdb1 100644--- a/crates/core/src/commands/helpers.rs+++ b/crates/core/src/commands/helpers.rs@@ -1,6 +1,9 @@use crate::{- action::{ActionRequest, Point, WindowOp},+ action::WindowOp,+ action_request::ActionRequest,+ action_result::ActionResult,adapter::{PlatformAdapter, WindowFilter},+ context::CommandContext,error::AppError,node::WindowInfo,refs::{RefEntry, validate_ref_id},@@ -19,30 +22,71 @@ pub struct RefArgs {pub snapshot_id: Option<String>,}-pub(crate) fn resolve_ref<'a>(+pub(crate) fn resolve_ref_with_context<'a>(ref_id: &str,snapshot_id: Option<&str>,adapter: &'a dyn PlatformAdapter,+ context: &CommandContext,) -> Result<(RefEntry, ResolvedElement<'a>), AppError> {validate_ref_id(ref_id)?;- let store = RefStore::new()?;- let refmap = store.load(snapshot_id).map_err(|e| {+ let store = RefStore::for_session(context.session_id())?;+ context.trace_lazy(+ "ref.resolve.start",+ || json!({ "ref": ref_id, "snapshot_id": snapshot_id }),+ )?;+ let refmap = store.load(snapshot_id).inspect_err(|e| {tracing::debug!("refmap load failed: {e}");- AppError::stale_ref(ref_id)+ let _ = context.trace_lazy("ref.resolve.error", || {+ json!({+ "ref": ref_id,+ "snapshot_id": snapshot_id,+ "code": e.code(),+ "message": e.to_string()+ })+ });})?;- let entry = refmap- .get(ref_id)- .ok_or_else(|| AppError::stale_ref(ref_id))?- .clone();+ let entry = match refmap.get(ref_id) {+ Some(entry) => entry.clone(),+ None => {+ context.trace_lazy("ref.resolve.error", || {+ json!({+ "ref": ref_id,+ "snapshot_id": snapshot_id,+ "code": "STALE_REF",+ "message": "ref not found in current RefMap"+ })+ })?;+ return Err(AppError::stale_ref(ref_id));+ }+ };tracing::debug!(- "resolve: {} -> pid={} role={} name={:?}",+ "resolve: {} -> pid={} role={} name_chars={:?}",ref_id,entry.pid,entry.role,- entry.name.as_deref().unwrap_or("(none)")+ entry.name.as_deref().map(|name| name.chars().count()));- let handle = adapter.resolve_element(&entry)?;+ context.trace_lazy("ref.resolve.entry", || {+ json!({+ "ref": ref_id,+ "pid": entry.pid,+ "role": entry.role,+ "name": entry.name+ })+ })?;+ let handle = adapter.resolve_element_strict(&entry).inspect_err(|err| {+ let _ = context.trace_lazy("ref.resolve.error", || {+ json!({+ "ref": ref_id,+ "snapshot_id": snapshot_id,+ "code": err.code.as_str(),+ "message": err.message.clone(),+ "details": err.details.clone()+ })+ });+ })?;tracing::debug!("resolve: {} resolved successfully", ref_id);+ context.trace_lazy("ref.resolve.ok", || json!({ "ref": ref_id }))?;Ok((entry, ResolvedElement::new(adapter, handle)))}@@ -69,37 +113,41 @@ pub(crate) fn resolve_app_pid(}}-pub(crate) fn execute_ref_action(+pub(crate) fn execute_ref_action_with_context(args: RefArgs,adapter: &dyn PlatformAdapter,request: ActionRequest,+ context: &CommandContext,) -> Result<Value, AppError> {- let (_entry, handle) = resolve_ref(&args.ref_id, args.snapshot_id.as_deref(), adapter)?;- let result = adapter.execute_action(handle.handle(), request)?;+ let (_entry, result) = execute_ref_action_result_with_context(+ &args.ref_id,+ args.snapshot_id.as_deref(),+ adapter,+ request,+ context,+ )?;Ok(serde_json::to_value(result)?)}-pub(crate) fn resolve_point_from_ref_or_xy(- ref_id: Option<&str>,- xy: Option<(f64, f64)>,+pub(crate) fn execute_ref_action_result_with_context(+ ref_id: &str,snapshot_id: Option<&str>,adapter: &dyn PlatformAdapter,- missing_input_message: impl Into<String>,-) -> Result<Point, AppError> {- if let Some(ref_id) = ref_id {- let (_entry, handle) = resolve_ref(ref_id, snapshot_id, adapter)?;- let bounds = adapter- .get_element_bounds(handle.handle())?- .ok_or_else(|| AppError::invalid_input(format!("Element {ref_id} has no bounds")))?;- return Ok(Point {- x: bounds.x + bounds.width / 2.0,- y: bounds.y + bounds.height / 2.0,- });- }- if let Some((x, y)) = xy {- return Ok(Point { x, y });- }- Err(AppError::invalid_input(missing_input_message.into()))+ request: ActionRequest,+ context: &CommandContext,+) -> Result<(RefEntry, ActionResult), AppError> {+ let (entry, handle) = resolve_ref_with_context(ref_id, snapshot_id, adapter, context)?;+ let result = crate::ref_action::execute_resolved(+ crate::ref_action::ResolvedRefAction {+ adapter,+ entry: &entry,+ handle: handle.handle(),+ ref_id,+ context,+ },+ request,+ )?;+ Ok((entry, result))}pub(crate) fn window_op_command(@@ -140,6 +188,14 @@ pub(crate) fn resolve_window_for_app(find_window_for_pid(pid, adapter)}+#[cfg(test)]+#[path = "helpers_test_support.rs"]+mod test_support;+#[cfg(test)]#[path = "helpers_tests.rs"]mod tests;++#[cfg(test)]+#[path = "helpers_ref_action_tests.rs"]+mod ref_action_tests;diff --git a/crates/core/src/commands/helpers_ref_action_tests.rs b/crates/core/src/commands/helpers_ref_action_tests.rsnew file mode 100644index 000000000..bf8041140--- /dev/null+++ b/crates/core/src/commands/helpers_ref_action_tests.rs@@ -0,0 +1,193 @@+use super::test_support::{entry, text_entry};+use super::*;+use crate::adapter::NativeHandle;+use crate::error::AdapterError;+use crate::refs::RefMap;+use crate::refs_test_support::HomeGuard;+use crate::{+ action::Action, action_result::ActionResult, action_step::ActionStep,+ element_state::ElementState, interaction_policy::InteractionPolicy,+};+use std::sync::Mutex;+use std::sync::atomic::{AtomicU32, Ordering};++struct RecordingAdapter {+ request: Mutex<Option<ActionRequest>>,+}++impl PlatformAdapter for RecordingAdapter {+ fn resolve_element_strict(&self, _entry: &RefEntry) -> Result<NativeHandle, AdapterError> {+ Ok(NativeHandle::null())+ }++ fn execute_action(+ &self,+ _handle: &NativeHandle,+ request: ActionRequest,+ ) -> Result<ActionResult, AdapterError> {+ *self.request.lock().unwrap() = Some(request);+ Ok(ActionResult::new("ok")+ .with_state(ElementState {+ role: "textfield".into(),+ states: vec!["focused".into()],+ value: Some("updated".into()),+ })+ .with_steps(vec![ActionStep::succeeded("AXPress")]))+ }+}++struct AmbiguousAdapter {+ executed: AtomicU32,+}++impl PlatformAdapter for AmbiguousAdapter {+ fn resolve_element_strict(&self, _entry: &RefEntry) -> Result<NativeHandle, AdapterError> {+ Err(+ AdapterError::ambiguous_target("2 candidates matched").with_details(+ serde_json::json!({+ "candidate_count": 2,+ "candidates": [{ "name": "Private OK" }]+ }),+ ),+ )+ }++ fn execute_action(+ &self,+ _handle: &NativeHandle,+ _request: ActionRequest,+ ) -> Result<ActionResult, AdapterError> {+ self.executed.fetch_add(1, Ordering::SeqCst);+ Ok(ActionResult::new("unexpected"))+ }+}++#[test]+fn execute_ref_action_preserves_action_and_policy() {+ let _guard = HomeGuard::new();+ let mut refmap = RefMap::new();+ refmap.allocate(entry());+ let snapshot_id = RefStore::new().unwrap().save_new_snapshot(&refmap).unwrap();+ let adapter = RecordingAdapter {+ request: Mutex::new(None),+ };+ let args = RefArgs {+ ref_id: "@e1".into(),+ snapshot_id: Some(snapshot_id),+ };++ execute_ref_action_with_context(+ args,+ &adapter,+ ActionRequest::headless(Action::Click),+ &CommandContext::default(),+ )+ .unwrap();++ let request = adapter.request.lock().unwrap().clone().unwrap();+ assert!(matches!(request.action, Action::Click));+ assert_eq!(request.policy, InteractionPolicy::headless());+}++#[test]+fn execute_ref_action_does_not_dispatch_ambiguous_target() {+ let _guard = HomeGuard::new();+ let mut refmap = RefMap::new();+ refmap.allocate(entry());+ let snapshot_id = RefStore::new().unwrap().save_new_snapshot(&refmap).unwrap();+ let adapter = AmbiguousAdapter {+ executed: AtomicU32::new(0),+ };+ let args = RefArgs {+ ref_id: "@e1".into(),+ snapshot_id: Some(snapshot_id),+ };++ let err = execute_ref_action_with_context(+ args,+ &adapter,+ ActionRequest::headless(Action::Click),+ &CommandContext::default(),+ )+ .expect_err("ambiguous targets fail before action dispatch");++ assert_eq!(err.code(), "AMBIGUOUS_TARGET");+ assert_eq!(adapter.executed.load(Ordering::SeqCst), 0);+}++#[test]+fn ref_action_trace_includes_ambiguous_details_without_candidate_names() {+ let _guard = HomeGuard::new();+ let mut refmap = RefMap::new();+ refmap.allocate(entry());+ let snapshot_id = RefStore::new().unwrap().save_new_snapshot(&refmap).unwrap();+ let adapter = AmbiguousAdapter {+ executed: AtomicU32::new(0),+ };+ let trace_path = std::env::temp_dir().join(format!(+ "agent-desktop-ambiguous-trace-{}.jsonl",+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ let context = CommandContext::new(None, Some(trace_path.clone()), true).unwrap();+ let args = RefArgs {+ ref_id: "@e1".into(),+ snapshot_id: Some(snapshot_id),+ };++ let err = execute_ref_action_with_context(+ args,+ &adapter,+ ActionRequest::headless(Action::Click),+ &context,+ )+ .expect_err("ambiguous targets fail before action dispatch");++ assert_eq!(err.code(), "AMBIGUOUS_TARGET");+ let trace = std::fs::read_to_string(&trace_path).unwrap();+ assert!(trace.contains("\"candidate_count\":2"));+ assert!(!trace.contains("Private OK"));+ let _ = std::fs::remove_file(trace_path);+}++#[test]+fn ref_action_trace_does_not_include_typed_text_payload() {+ let _guard = HomeGuard::new();+ let mut refmap = RefMap::new();+ refmap.allocate(text_entry());+ let snapshot_id = RefStore::new().unwrap().save_new_snapshot(&refmap).unwrap();+ let adapter = RecordingAdapter {+ request: Mutex::new(None),+ };+ let trace_path = std::env::temp_dir().join(format!(+ "agent-desktop-type-trace-{}.jsonl",+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ let context = CommandContext::new(None, Some(trace_path.clone()), true).unwrap();+ let args = RefArgs {+ ref_id: "@e1".into(),+ snapshot_id: Some(snapshot_id),+ };++ execute_ref_action_with_context(+ args,+ &adapter,+ ActionRequest::focus_fallback(Action::TypeText("super-secret".into())),+ &context,+ )+ .unwrap();++ let trace = std::fs::read_to_string(&trace_path).unwrap();+ assert!(trace.contains("\"action\":\"type\""));+ assert!(trace.contains("\"event\":\"action.dispatch.start\""));+ assert!(trace.contains("\"event\":\"action.dispatch.ok\""));+ assert!(trace.contains("\"post_state\""));+ assert!(trace.contains("\"steps\""));+ assert!(!trace.contains("super-secret"));+ let _ = std::fs::remove_file(trace_path);+}diff --git a/crates/core/src/commands/helpers_test_support.rs b/crates/core/src/commands/helpers_test_support.rsnew file mode 100644index 000000000..dec4e528d--- /dev/null+++ b/crates/core/src/commands/helpers_test_support.rs@@ -0,0 +1,29 @@+use crate::refs::RefEntry;++pub(super) fn entry() -> RefEntry {+ RefEntry {+ pid: 1,+ role: "button".into(),+ name: Some("OK".into()),+ value: None,+ description: None,+ states: vec![],+ bounds: None,+ bounds_hash: None,+ available_actions: vec!["Clear".into(), "Click".into()],+ source_app: None,+ source_window_id: None,+ source_window_title: None,+ source_surface: crate::adapter::SnapshotSurface::Window,+ root_ref: None,+ path_is_absolute: false,+ path: smallvec::SmallVec::new(),+ }+}++pub(super) fn text_entry() -> RefEntry {+ let mut entry = entry();+ entry.role = "textfield".into();+ entry.available_actions = vec!["SetValue".into()];+ entry+}diff --git a/crates/core/src/commands/helpers_tests.rs b/crates/core/src/commands/helpers_tests.rsindex 6fb569260..894e9d40c 100644--- a/crates/core/src/commands/helpers_tests.rs+++ b/crates/core/src/commands/helpers_tests.rs@@ -1,11 +1,12 @@+use super::test_support::entry;use super::*;-use crate::action::{Action, ActionResult, InteractionPolicy};+use crate::action::Action;use crate::adapter::NativeHandle;+use crate::capability;use crate::error::{AdapterError, ErrorCode};use crate::node::AppInfo;use crate::refs::RefMap;use crate::refs_test_support::HomeGuard;-use std::sync::Mutex;use std::sync::atomic::{AtomicU32, Ordering};struct ReleaseCountingAdapter {@@ -13,7 +14,7 @@ struct ReleaseCountingAdapter {}impl PlatformAdapter for ReleaseCountingAdapter {- fn resolve_element(&self, _entry: &RefEntry) -> Result<NativeHandle, AdapterError> {+ fn resolve_element_strict(&self, _entry: &RefEntry) -> Result<NativeHandle, AdapterError> {Ok(NativeHandle::null())}@@ -23,25 +24,6 @@ impl PlatformAdapter for ReleaseCountingAdapter {}}-struct RecordingAdapter {- request: Mutex<Option<ActionRequest>>,-}--impl PlatformAdapter for RecordingAdapter {- fn resolve_element(&self, _entry: &RefEntry) -> Result<NativeHandle, AdapterError> {- Ok(NativeHandle::null())- }-- fn execute_action(- &self,- _handle: &NativeHandle,- request: ActionRequest,- ) -> Result<ActionResult, AdapterError> {- *self.request.lock().unwrap() = Some(request);- Ok(ActionResult::new("ok"))- }-}-struct RestoreWithoutWindowAdapter {op_count: AtomicU32,}@@ -70,27 +52,6 @@ impl PlatformAdapter for RestoreWithoutWindowAdapter {}}-fn entry() -> RefEntry {- RefEntry {- pid: 1,- role: "button".into(),- name: Some("OK".into()),- value: None,- description: None,- states: vec![],- bounds: None,- bounds_hash: None,- available_actions: vec!["Click".into()],- source_app: None,- source_window_id: None,- source_window_title: None,- source_surface: crate::adapter::SnapshotSurface::Window,- root_ref: None,- path_is_absolute: false,- path: smallvec::SmallVec::new(),- }-}-#[test]fn resolved_element_releases_handle_once_on_drop() {let _guard = HomeGuard::new();@@ -102,7 +63,13 @@ fn resolved_element_releases_handle_once_on_drop() {};{- let (_entry, resolved) = resolve_ref("@e1", Some(&snapshot_id), &adapter).unwrap();+ let (_entry, resolved) = resolve_ref_with_context(+ "@e1",+ Some(&snapshot_id),+ &adapter,+ &CommandContext::default(),+ )+ .unwrap();let _handle = resolved.handle();assert_eq!(adapter.releases.load(Ordering::SeqCst), 0);}@@ -111,24 +78,49 @@ fn resolved_element_releases_handle_once_on_drop() {}#[test]-fn execute_ref_action_preserves_action_and_policy() {+fn explicit_session_snapshot_resolves_without_session_context() {let _guard = HomeGuard::new();let mut refmap = RefMap::new();refmap.allocate(entry());- let snapshot_id = RefStore::new().unwrap().save_new_snapshot(&refmap).unwrap();- let adapter = RecordingAdapter {- request: Mutex::new(None),+ let snapshot_id = RefStore::for_session(Some("agent-a"))+ .unwrap()+ .save_new_snapshot(&refmap)+ .unwrap();+ let adapter = ReleaseCountingAdapter {+ releases: AtomicU32::new(0),};- let args = RefArgs {- ref_id: "@e1".into(),- snapshot_id: Some(snapshot_id),++ let (_entry, resolved) = resolve_ref_with_context(+ "@e1",+ Some(&snapshot_id),+ &adapter,+ &CommandContext::default(),+ )+ .unwrap();+ let _handle = resolved.handle();++ assert_eq!(adapter.releases.load(Ordering::SeqCst), 0);+}++#[test]+fn missing_snapshot_keeps_snapshot_not_found_error() {+ let _guard = HomeGuard::new();+ let adapter = ReleaseCountingAdapter {+ releases: AtomicU32::new(0),};- execute_ref_action(args, &adapter, ActionRequest::headless(Action::Clear)).unwrap();+ let err = match resolve_ref_with_context(+ "@e1",+ Some("smissing"),+ &adapter,+ &CommandContext::default(),+ ) {+ Ok(_) => panic!("expected missing snapshot to fail"),+ Err(err) => err,+ };- let request = adapter.request.lock().unwrap().clone().unwrap();- assert!(matches!(request.action, Action::Clear));- assert_eq!(request.policy, InteractionPolicy::headless());+ assert_eq!(err.code(), "SNAPSHOT_NOT_FOUND");+ assert!(err.suggestion().unwrap().contains("snapshot_id"));}#[test]@@ -150,3 +142,82 @@ fn restore_can_run_when_no_window_is_currently_listed() {assert_eq!(value["restored"], true);assert_eq!(adapter.op_count.load(Ordering::SeqCst), 1);}++struct CountingPipelineAdapter {+ resolves: AtomicU32,+ live_reads: AtomicU32,+ executes: AtomicU32,+ releases: AtomicU32,+}++impl CountingPipelineAdapter {+ fn new() -> Self {+ Self {+ resolves: AtomicU32::new(0),+ live_reads: AtomicU32::new(0),+ executes: AtomicU32::new(0),+ releases: AtomicU32::new(0),+ }+ }+}++impl PlatformAdapter for CountingPipelineAdapter {+ fn resolve_element_strict(&self, _entry: &RefEntry) -> Result<NativeHandle, AdapterError> {+ self.resolves.fetch_add(1, Ordering::SeqCst);+ Ok(NativeHandle::null())+ }++ fn get_live_element(+ &self,+ _handle: &NativeHandle,+ ) -> Result<crate::adapter::LiveElement, AdapterError> {+ self.live_reads.fetch_add(1, Ordering::SeqCst);+ Ok(crate::adapter::LiveElement {+ state: Some(crate::element_state::ElementState {+ role: "button".into(),+ states: vec![],+ value: None,+ }),+ bounds: None,+ available_actions: Some(vec![capability::CLICK.into()]),+ })+ }++ fn execute_action(+ &self,+ _handle: &NativeHandle,+ _request: ActionRequest,+ ) -> Result<crate::action_result::ActionResult, AdapterError> {+ self.executes.fetch_add(1, Ordering::SeqCst);+ Ok(crate::action_result::ActionResult::new("click"))+ }++ fn release_handle(&self, _handle: &NativeHandle) -> Result<(), AdapterError> {+ self.releases.fetch_add(1, Ordering::SeqCst);+ Ok(())+ }+}++#[test]+fn ref_action_pipeline_makes_one_resolve_one_preflight_one_dispatch() {+ let _guard = HomeGuard::new();+ let store = crate::refs_store::RefStore::new().unwrap();+ let mut refmap = RefMap::new();+ refmap.allocate(entry());+ let snapshot_id = store.save_new_snapshot(&refmap).unwrap();+ let adapter = CountingPipelineAdapter::new();++ execute_ref_action_result_with_context(+ "@e1",+ Some(&snapshot_id),+ &adapter,+ ActionRequest::headless(Action::Click),+ &CommandContext::default(),+ )+ .unwrap();++ assert_eq!(adapter.resolves.load(Ordering::SeqCst), 1);+ assert_eq!(adapter.live_reads.load(Ordering::SeqCst), 1);+ assert_eq!(adapter.executes.load(Ordering::SeqCst), 1);+ assert_eq!(adapter.releases.load(Ordering::SeqCst), 1);+}diff --git a/crates/core/src/commands/hover.rs b/crates/core/src/commands/hover.rsindex 8d0d3879c..7d11c5003 100644--- a/crates/core/src/commands/hover.rs+++ b/crates/core/src/commands/hover.rs@@ -1,7 +1,11 @@use crate::{- action::{MouseButton, MouseEvent, MouseEventKind, Point},+ action::{MouseButton, MouseEvent, MouseEventKind},adapter::PlatformAdapter,- commands::helpers::resolve_point_from_ref_or_xy,+ commands::point_resolve::{+ PointResolveArgs, focus_for_physical_input, require_cursor_policy,+ resolve_point_from_ref_or_xy_with_context,+ },+ context::CommandContext,error::AppError,};use serde_json::{Value, json};@@ -13,25 +17,38 @@ pub struct HoverArgs {pub duration_ms: Option<u64>,}-pub fn execute(args: HoverArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- let point = resolve_hover_point(&args, adapter)?;+pub fn execute(+ args: HoverArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ require_cursor_policy(context, "hover")?;+ let resolved = resolve_point_from_ref_or_xy_with_context(+ PointResolveArgs {+ ref_id: args.ref_id.as_deref(),+ xy: args.xy,+ snapshot_id: args.snapshot_id.as_deref(),+ missing_input_message: "Provide a ref (@e1) or --xy x,y",+ },+ adapter,+ context,+ )?;+ let focused = focus_for_physical_input(resolved.pid, adapter, context)?;adapter.mouse_event(MouseEvent {kind: MouseEventKind::Move,- point: point.clone(),+ point: resolved.point.clone(),button: MouseButton::Left,})?;if let Some(ms) = args.duration_ms {std::thread::sleep(std::time::Duration::from_millis(ms));}- Ok(json!({ "hovered": true, "x": point.x, "y": point.y }))+ let mut response = json!({ "hovered": true, "x": resolved.point.x, "y": resolved.point.y });+ if focused {+ response["focused"] = json!(true);+ }+ Ok(response)}-fn resolve_hover_point(args: &HoverArgs, adapter: &dyn PlatformAdapter) -> Result<Point, AppError> {- resolve_point_from_ref_or_xy(- args.ref_id.as_deref(),- args.xy,- args.snapshot_id.as_deref(),- adapter,- "Provide a ref (@e1) or --xy x,y",- )-}+#[cfg(test)]+#[path = "hover_tests.rs"]+mod tests;diff --git a/crates/core/src/commands/hover_tests.rs b/crates/core/src/commands/hover_tests.rsnew file mode 100644index 000000000..033166672--- /dev/null+++ b/crates/core/src/commands/hover_tests.rs@@ -0,0 +1,135 @@+use super::*;+use crate::{+ adapter::NativeHandle,+ capability,+ error::AdapterError,+ node::Rect,+ refs::{RefEntry, RefMap},+ refs_store::RefStore,+ refs_test_support::HomeGuard,+};+use std::sync::Mutex;++struct HoverCaptureAdapter {+ moved_to: Mutex<Option<MouseEvent>>,+ focused_pids: Mutex<Vec<i32>>,+}++impl HoverCaptureAdapter {+ fn new() -> Self {+ Self {+ moved_to: Mutex::new(None),+ focused_pids: Mutex::new(Vec::new()),+ }+ }+}++impl PlatformAdapter for HoverCaptureAdapter {+ fn resolve_element_strict(&self, _entry: &RefEntry) -> Result<NativeHandle, AdapterError> {+ Ok(NativeHandle::null())+ }++ fn get_element_bounds(&self, _handle: &NativeHandle) -> Result<Option<Rect>, AdapterError> {+ Ok(Some(Rect {+ x: 100.0,+ y: 200.0,+ width: 20.0,+ height: 10.0,+ }))+ }++ fn focus_app(&self, pid: i32) -> Result<(), AdapterError> {+ self.focused_pids.lock().unwrap().push(pid);+ Ok(())+ }++ fn mouse_event(&self, event: MouseEvent) -> Result<(), AdapterError> {+ *self.moved_to.lock().unwrap() = Some(event);+ Ok(())+ }+}++fn ref_snapshot(pid: i32) -> String {+ let store = RefStore::new().unwrap();+ let mut refmap = RefMap::new();+ refmap.allocate(RefEntry {+ pid,+ role: "button".into(),+ name: Some("Target".into()),+ value: None,+ description: None,+ states: vec![],+ bounds: None,+ bounds_hash: None,+ available_actions: vec![capability::CLICK.into()],+ source_app: None,+ source_window_id: None,+ source_window_title: None,+ source_surface: crate::adapter::SnapshotSurface::Window,+ root_ref: None,+ path_is_absolute: false,+ path: smallvec::SmallVec::new(),+ });+ store.save_new_snapshot(&refmap).unwrap()+}++fn ref_args(snapshot_id: String) -> HoverArgs {+ HoverArgs {+ ref_id: Some("@e1".into()),+ snapshot_id: Some(snapshot_id),+ xy: None,+ duration_ms: None,+ }+}++#[test]+fn headless_ref_hover_is_policy_denied_before_cursor_move() {+ let _guard = HomeGuard::new();+ let snapshot_id = ref_snapshot(42);+ let adapter = HoverCaptureAdapter::new();++ let err = execute(ref_args(snapshot_id), &adapter, &CommandContext::default()).unwrap_err();++ assert_eq!(err.code(), "POLICY_DENIED");+ assert!(adapter.focused_pids.lock().unwrap().is_empty());+ assert!(adapter.moved_to.lock().unwrap().is_none());+}++#[test]+fn headed_ref_hover_focuses_target_app_once() {+ let _guard = HomeGuard::new();+ let snapshot_id = ref_snapshot(42);+ let adapter = HoverCaptureAdapter::new();++ let value = execute(+ ref_args(snapshot_id),+ &adapter,+ &CommandContext::default().with_headed(true),+ )+ .unwrap();++ assert_eq!(*adapter.focused_pids.lock().unwrap(), vec![42]);+ assert_eq!(value["focused"], true);+ assert_eq!(value["x"], 110.0);+ assert_eq!(value["y"], 205.0);+}++#[test]+fn headed_xy_hover_never_steals_focus() {+ let adapter = HoverCaptureAdapter::new();++ let value = execute(+ HoverArgs {+ ref_id: None,+ snapshot_id: None,+ xy: Some((5.0, 6.0)),+ duration_ms: None,+ },+ &adapter,+ &CommandContext::default().with_headed(true),+ )+ .unwrap();++ assert!(adapter.focused_pids.lock().unwrap().is_empty());+ assert!(value.get("focused").is_none());+}diff --git a/crates/core/src/commands/is_check.rs b/crates/core/src/commands/is_check.rsindex 0b7bc6ed5..55d44961e 100644--- a/crates/core/src/commands/is_check.rs+++ b/crates/core/src/commands/is_check.rs@@ -1,6 +1,10 @@use crate::{- action::ElementState, adapter::PlatformAdapter, commands::helpers::resolve_ref,- error::AppError, refs::RefEntry,+ adapter::{PlatformAdapter, optional_live_read},+ commands::helpers::resolve_ref_with_context,+ context::CommandContext,+ element_state::ElementState,+ error::AppError,+ refs::RefEntry,};use serde_json::{Value, json};@@ -19,12 +23,14 @@ pub enum IsProperty {}/// State is read live when the platform supports it, then falls back to snapshot state.-pub fn execute(args: IsArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- let (entry, handle) = resolve_ref(&args.ref_id, args.snapshot_id.as_deref(), adapter)?;- let state = adapter- .get_live_state(handle.handle())- .ok()- .flatten()+pub fn execute(+ args: IsArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ let (entry, handle) =+ resolve_ref_with_context(&args.ref_id, args.snapshot_id.as_deref(), adapter, context)?;+ let state = optional_live_read(adapter.get_live_state(handle.handle()))?.unwrap_or_else(|| state_from_ref_entry(&entry));let prop_name = match args.property {@@ -68,23 +74,22 @@ fn is_applicable(property: &IsProperty, entry: &RefEntry, state: &ElementState)IsProperty::Checked => {crate::roles::is_toggleable_role(&entry.role)|| has_state(state, "checked")- || has_available_action(entry, "Toggle")- || has_available_action(entry, "Check")- || has_available_action(entry, "Uncheck")+ || crate::capability::contains_any(+ &entry.available_actions,+ crate::capability::CHECKED_APPLICABILITY,+ )}IsProperty::Expanded => {crate::roles::is_expandable_role(&entry.role)|| has_state(state, "expanded")- || has_available_action(entry, "Expand")- || has_available_action(entry, "Collapse")+ || crate::capability::contains_any(+ &entry.available_actions,+ crate::capability::EXPANDED_APPLICABILITY,+ )}}}-fn has_available_action(entry: &RefEntry, action: &str) -> bool {- entry.available_actions.iter().any(|a| a == action)-}-#[cfg(test)]#[path = "is_check_tests.rs"]mod tests;diff --git a/crates/core/src/commands/is_check_tests.rs b/crates/core/src/commands/is_check_tests.rsindex 042f18396..22220bbbd 100644--- a/crates/core/src/commands/is_check_tests.rs+++ b/crates/core/src/commands/is_check_tests.rs@@ -10,7 +10,7 @@ struct LiveStateAdapter {}impl PlatformAdapter for LiveStateAdapter {- fn resolve_element(&self, _entry: &RefEntry) -> Result<NativeHandle, AdapterError> {+ fn resolve_element_strict(&self, _entry: &RefEntry) -> Result<NativeHandle, AdapterError> {Ok(NativeHandle::null())}@@ -65,6 +65,7 @@ fn checked_uses_live_canonical_state() {property: IsProperty::Checked,},&adapter,+ &CommandContext::default(),).unwrap();@@ -87,6 +88,7 @@ fn checked_does_not_infer_platform_values_in_core() {property: IsProperty::Checked,},&adapter,+ &CommandContext::default(),).unwrap();@@ -109,6 +111,7 @@ fn checked_falls_back_to_snapshot_state_when_live_state_is_missing() {property: IsProperty::Checked,},&adapter,+ &CommandContext::default(),).unwrap();@@ -141,6 +144,7 @@ fn basic_state_properties_use_live_state() {property,},&adapter,+ &CommandContext::default(),).unwrap();@@ -182,6 +186,7 @@ fn action_availability_makes_toggle_and_expand_applicable() {property,},&adapter,+ &CommandContext::default(),).unwrap();diff --git a/crates/core/src/commands/mod.rs b/crates/core/src/commands/mod.rsindex cc59257ef..45c151257 100644--- a/crates/core/src/commands/mod.rs+++ b/crates/core/src/commands/mod.rs@@ -35,6 +35,7 @@ pub mod mouse_up;pub mod move_window;pub mod notification_action;pub mod permissions;+pub(crate) mod point_resolve;pub mod press;pub mod resize_window;pub mod restore;@@ -53,6 +54,12 @@ pub mod type_text;pub mod uncheck;pub mod version;pub mod wait;+pub(crate) mod wait_element;+pub(crate) mod wait_latest_ref_cache;+pub(crate) mod wait_mode;+pub(crate) mod wait_predicate;+pub(crate) mod wait_text_match;+pub(crate) mod wait_timeout;#[cfg(test)]mod ref_policy_tests;diff --git a/crates/core/src/commands/mouse_click.rs b/crates/core/src/commands/mouse_click.rsindex 06f410782..507ea13b6 100644--- a/crates/core/src/commands/mouse_click.rs+++ b/crates/core/src/commands/mouse_click.rs@@ -1,6 +1,8 @@use crate::{action::{MouseButton, MouseEvent, MouseEventKind, Point},adapter::PlatformAdapter,+ commands::point_resolve::require_cursor_policy,+ context::CommandContext,error::AppError,};use serde_json::{Value, json};@@ -12,7 +14,12 @@ pub struct MouseClickArgs {pub count: u32,}-pub fn execute(args: MouseClickArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {+pub fn execute(+ args: MouseClickArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ require_cursor_policy(context, "mouse-click")?;adapter.mouse_event(MouseEvent {kind: MouseEventKind::Click { count: args.count },point: Point {diff --git a/crates/core/src/commands/mouse_down.rs b/crates/core/src/commands/mouse_down.rsindex 7af3fc5ca..8e8607a77 100644--- a/crates/core/src/commands/mouse_down.rs+++ b/crates/core/src/commands/mouse_down.rs@@ -1,6 +1,8 @@use crate::{action::{MouseButton, MouseEvent, MouseEventKind, Point},adapter::PlatformAdapter,+ commands::point_resolve::require_cursor_policy,+ context::CommandContext,error::AppError,};use serde_json::{Value, json};@@ -11,7 +13,12 @@ pub struct MouseDownArgs {pub button: MouseButton,}-pub fn execute(args: MouseDownArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {+pub fn execute(+ args: MouseDownArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ require_cursor_policy(context, "mouse-down")?;adapter.mouse_event(MouseEvent {kind: MouseEventKind::Down,point: Point {diff --git a/crates/core/src/commands/mouse_move.rs b/crates/core/src/commands/mouse_move.rsindex 90f462a2d..bccb010c0 100644--- a/crates/core/src/commands/mouse_move.rs+++ b/crates/core/src/commands/mouse_move.rs@@ -1,6 +1,8 @@use crate::{action::{MouseButton, MouseEvent, MouseEventKind, Point},adapter::PlatformAdapter,+ commands::point_resolve::require_cursor_policy,+ context::CommandContext,error::AppError,};use serde_json::{Value, json};@@ -10,7 +12,12 @@ pub struct MouseMoveArgs {pub y: f64,}-pub fn execute(args: MouseMoveArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {+pub fn execute(+ args: MouseMoveArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ require_cursor_policy(context, "mouse-move")?;adapter.mouse_event(MouseEvent {kind: MouseEventKind::Move,point: Point {diff --git a/crates/core/src/commands/mouse_up.rs b/crates/core/src/commands/mouse_up.rsindex feae46ed3..4a9c5ed7b 100644--- a/crates/core/src/commands/mouse_up.rs+++ b/crates/core/src/commands/mouse_up.rs@@ -1,6 +1,8 @@use crate::{action::{MouseButton, MouseEvent, MouseEventKind, Point},adapter::PlatformAdapter,+ commands::point_resolve::require_cursor_policy,+ context::CommandContext,error::AppError,};use serde_json::{Value, json};@@ -11,7 +13,12 @@ pub struct MouseUpArgs {pub button: MouseButton,}-pub fn execute(args: MouseUpArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {+pub fn execute(+ args: MouseUpArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ require_cursor_policy(context, "mouse-up")?;adapter.mouse_event(MouseEvent {kind: MouseEventKind::Up,point: Point {diff --git a/crates/core/src/commands/point_resolve.rs b/crates/core/src/commands/point_resolve.rsnew file mode 100644index 000000000..99f21082e--- /dev/null+++ b/crates/core/src/commands/point_resolve.rs@@ -0,0 +1,104 @@+use crate::{+ action::Point,+ adapter::PlatformAdapter,+ commands::helpers::resolve_ref_with_context,+ context::CommandContext,+ error::{AdapterError, AppError},+};+use serde_json::json;++pub(crate) struct PointResolveArgs<'a> {+ pub ref_id: Option<&'a str>,+ pub xy: Option<(f64, f64)>,+ pub snapshot_id: Option<&'a str>,+ pub missing_input_message: &'a str,+}++pub(crate) struct ResolvedPoint {+ pub point: Point,+ pub pid: Option<i32>,+}++pub(crate) fn require_cursor_policy(+ context: &CommandContext,+ command: &str,+) -> Result<(), AppError> {+ let policy = context.physical_input_policy();+ if policy.allow_cursor_move {+ return Ok(());+ }+ Err(AdapterError::policy_denied_for_policy(+ format!("{command} moves the cursor and is disabled in headless mode"),+ policy,+ )+ .into())+}++pub(crate) fn resolve_point_from_ref_or_xy_with_context(+ args: PointResolveArgs<'_>,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<ResolvedPoint, AppError> {+ if let Some(ref_id) = args.ref_id {+ let (entry, handle) = resolve_ref_with_context(ref_id, args.snapshot_id, adapter, context)?;+ let bounds = adapter+ .get_element_bounds(handle.handle())?+ .ok_or_else(|| AppError::invalid_input(format!("Element {ref_id} has no bounds")))?;+ return Ok(ResolvedPoint {+ point: Point {+ x: bounds.x + bounds.width / 2.0,+ y: bounds.y + bounds.height / 2.0,+ },+ pid: Some(entry.pid),+ });+ }+ if let Some((x, y)) = args.xy {+ return Ok(ResolvedPoint {+ point: Point { x, y },+ pid: None,+ });+ }+ Err(AppError::invalid_input(args.missing_input_message))+}++/// Ensures the app that owns a ref-resolved point is frontmost before+/// physical input is synthesized, so the events land on its window instead+/// of whatever happens to be frontmost. Headless never steals focus+/// (`--headed` opts in), and a raise failure downgrades to un-focused input+/// rather than erroring.+pub(crate) fn focus_for_physical_input(+ pid: Option<i32>,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<bool, AppError> {+ let Some(pid) = pid else { return Ok(false) };+ if !context.physical_input_policy().allow_focus_steal {+ return Ok(false);+ }+ let focused = match adapter.focus_app(pid) {+ Ok(()) => true,+ Err(err) => {+ tracing::debug!("focus before physical input failed for pid {pid}: {err}");+ false+ }+ };+ context.trace_lazy("input.focus_app", || json!({ "pid": pid, "ok": focused }))?;+ Ok(focused)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn physical_input_requires_headed_context() {+ let err = require_cursor_policy(&CommandContext::default(), "mouse-move").unwrap_err();++ assert_eq!(err.code(), "POLICY_DENIED");+ }++ #[test]+ fn headed_context_allows_physical_input() {+ require_cursor_policy(&CommandContext::default().with_headed(true), "mouse-move").unwrap();+ }+}diff --git a/crates/core/src/commands/press.rs b/crates/core/src/commands/press.rsindex 665e30976..48dfe6a57 100644--- a/crates/core/src/commands/press.rs+++ b/crates/core/src/commands/press.rs@@ -1,5 +1,6 @@use crate::{- action::{Action, ActionRequest, KeyCombo, Modifier},+ action::{Action, KeyCombo, Modifier},+ action_request::ActionRequest,adapter::PlatformAdapter,error::AppError,};@@ -35,8 +36,7 @@ pub fn execute(args: PressArgs, adapter: &dyn PlatformAdapter) -> Result<Value,}let handle = crate::adapter::NativeHandle::null();- let result =- adapter.execute_action(&handle, ActionRequest::physical(Action::PressKey(combo)))?;+ let result = adapter.execute_action(&handle, ActionRequest::headed(Action::PressKey(combo)))?;Ok(serde_json::to_value(result)?)}diff --git a/crates/core/src/commands/ref_policy_tests.rs b/crates/core/src/commands/ref_policy_tests.rsindex 131ab98fe..09cdab600 100644--- a/crates/core/src/commands/ref_policy_tests.rs+++ b/crates/core/src/commands/ref_policy_tests.rs@@ -1,17 +1,43 @@use crate::{- action::{Action, ActionRequest, ActionResult, Direction, InteractionPolicy},+ action::{Action, Direction},+ action_request::ActionRequest,+ action_result::ActionResult,adapter::{NativeHandle, PlatformAdapter},commands::{check, clear, click, collapse, double_click, expand, focus, helpers::RefArgs, right_click,scroll, scroll_to, select, set_value, toggle, triple_click, type_text, uncheck,},+ context::CommandContext,error::AdapterError,+ interaction_policy::InteractionPolicy,refs::{RefEntry, RefMap},refs_store::RefStore,refs_test_support::HomeGuard,};use std::sync::Mutex;+/// Every command module stem whose execute function calls `context.request(`.+/// Adding a new ref-action command requires adding its stem here; the+/// `all_context_request_callers_are_policy_tested` guard enforces this.+const POLICY_TESTED_COMMANDS: &[&str] = &[+ "check",+ "clear",+ "click",+ "collapse",+ "double_click",+ "expand",+ "focus",+ "right_click",+ "scroll",+ "scroll_to",+ "select",+ "set_value",+ "toggle",+ "triple_click",+ "type_text",+ "uncheck",+];+struct RecordingAdapter {requests: Mutex<Vec<ActionRequest>>,}@@ -29,7 +55,7 @@ impl RecordingAdapter {}impl PlatformAdapter for RecordingAdapter {- fn resolve_element(&self, _entry: &RefEntry) -> Result<NativeHandle, AdapterError> {+ fn resolve_element_strict(&self, _entry: &RefEntry) -> Result<NativeHandle, AdapterError> {Ok(NativeHandle::null())}@@ -54,7 +80,23 @@ fn snapshot_id() -> String {states: vec![],bounds: None,bounds_hash: None,- available_actions: vec!["Click".into()],+ available_actions: vec![+ "Check".into(),+ "Clear".into(),+ "Click".into(),+ "Collapse".into(),+ "DoubleClick".into(),+ "Expand".into(),+ "RightClick".into(),+ "ScrollTo".into(),+ "Select".into(),+ "SetFocus".into(),+ "SetValue".into(),+ "Toggle".into(),+ "TripleClick".into(),+ "TypeText".into(),+ "Uncheck".into(),+ ],source_app: None,source_window_id: None,source_window_title: None,@@ -82,23 +124,24 @@ fn default_ref_commands_are_headless() {let _guard = HomeGuard::new();let snapshot_id = snapshot_id();let adapter = RecordingAdapter::new();+ let context = CommandContext::default();- click::execute(ref_args(&snapshot_id), &adapter).unwrap();- double_click::execute(ref_args(&snapshot_id), &adapter).unwrap();- triple_click::execute(ref_args(&snapshot_id), &adapter).unwrap();+ click::execute(ref_args(&snapshot_id), &adapter, &context).unwrap();+ double_click::execute(ref_args(&snapshot_id), &adapter, &context).unwrap();+ triple_click::execute(ref_args(&snapshot_id), &adapter, &context).unwrap();let before_right_click = adapter.requests.lock().unwrap().len();- let _ = right_click::execute(ref_args(&snapshot_id), &adapter);+ let _ = right_click::execute(ref_args(&snapshot_id), &adapter, &context);assert_eq!(adapter.requests.lock().unwrap().len(),before_right_click + 1);- clear::execute(ref_args(&snapshot_id), &adapter).unwrap();- toggle::execute(ref_args(&snapshot_id), &adapter).unwrap();- check::execute(ref_args(&snapshot_id), &adapter).unwrap();- uncheck::execute(ref_args(&snapshot_id), &adapter).unwrap();- expand::execute(ref_args(&snapshot_id), &adapter).unwrap();- collapse::execute(ref_args(&snapshot_id), &adapter).unwrap();- scroll_to::execute(ref_args(&snapshot_id), &adapter).unwrap();+ clear::execute(ref_args(&snapshot_id), &adapter, &context).unwrap();+ toggle::execute(ref_args(&snapshot_id), &adapter, &context).unwrap();+ check::execute(ref_args(&snapshot_id), &adapter, &context).unwrap();+ uncheck::execute(ref_args(&snapshot_id), &adapter, &context).unwrap();+ expand::execute(ref_args(&snapshot_id), &adapter, &context).unwrap();+ collapse::execute(ref_args(&snapshot_id), &adapter, &context).unwrap();+ scroll_to::execute(ref_args(&snapshot_id), &adapter, &context).unwrap();set_value::execute(set_value::SetValueArgs {ref_id: "@e1".into(),@@ -106,6 +149,7 @@ fn default_ref_commands_are_headless() {value: "value".into(),},&adapter,+ &context,).unwrap();select::execute(@@ -115,6 +159,7 @@ fn default_ref_commands_are_headless() {value: "choice".into(),},&adapter,+ &context,).unwrap();let before_type = adapter.requests.lock().unwrap().len();@@ -125,6 +170,7 @@ fn default_ref_commands_are_headless() {text: "text".into(),},&adapter,+ &context,).unwrap();let type_request = adapter.requests.lock().unwrap()[before_type].clone();@@ -137,6 +183,7 @@ fn default_ref_commands_are_headless() {amount: 1,},&adapter,+ &context,).unwrap();@@ -154,9 +201,118 @@ fn focus_command_is_explicit_headless_policy() {let snapshot_id = snapshot_id();let adapter = RecordingAdapter::new();- focus::execute(ref_args(&snapshot_id), &adapter).unwrap();+ focus::execute(ref_args(&snapshot_id), &adapter, &CommandContext::default()).unwrap();let request = adapter.last_request();assert!(matches!(request.action, Action::SetFocus));assert_eq!(request.policy, InteractionPolicy::headless());}++#[test]+fn headed_context_upgrades_every_ref_command_to_headed() {+ let _guard = HomeGuard::new();+ let snapshot_id = snapshot_id();+ let adapter = RecordingAdapter::new();+ let context = CommandContext::default().with_headed(true);++ click::execute(ref_args(&snapshot_id), &adapter, &context).unwrap();+ double_click::execute(ref_args(&snapshot_id), &adapter, &context).unwrap();+ triple_click::execute(ref_args(&snapshot_id), &adapter, &context).unwrap();+ let _ = right_click::execute(ref_args(&snapshot_id), &adapter, &context);+ clear::execute(ref_args(&snapshot_id), &adapter, &context).unwrap();+ toggle::execute(ref_args(&snapshot_id), &adapter, &context).unwrap();+ check::execute(ref_args(&snapshot_id), &adapter, &context).unwrap();+ uncheck::execute(ref_args(&snapshot_id), &adapter, &context).unwrap();+ expand::execute(ref_args(&snapshot_id), &adapter, &context).unwrap();+ collapse::execute(ref_args(&snapshot_id), &adapter, &context).unwrap();+ scroll_to::execute(ref_args(&snapshot_id), &adapter, &context).unwrap();+ focus::execute(ref_args(&snapshot_id), &adapter, &context).unwrap();+ set_value::execute(+ set_value::SetValueArgs {+ ref_id: "@e1".into(),+ snapshot_id: Some(snapshot_id.clone()),+ value: "value".into(),+ },+ &adapter,+ &context,+ )+ .unwrap();+ select::execute(+ select::SelectArgs {+ ref_id: "@e1".into(),+ snapshot_id: Some(snapshot_id.clone()),+ value: "choice".into(),+ },+ &adapter,+ &context,+ )+ .unwrap();+ type_text::execute(+ type_text::TypeArgs {+ ref_id: "@e1".into(),+ snapshot_id: Some(snapshot_id.clone()),+ text: "text".into(),+ },+ &adapter,+ &context,+ )+ .unwrap();+ scroll::execute(+ scroll::ScrollArgs {+ ref_id: "@e1".into(),+ snapshot_id: Some(snapshot_id),+ direction: Direction::Down,+ amount: 1,+ },+ &adapter,+ &context,+ )+ .unwrap();++ for request in adapter.requests.lock().unwrap().iter() {+ assert_eq!(+ request.policy,+ InteractionPolicy::headed(),+ "{:?} must be headed under --headed",+ request.action+ );+ }+}++#[test]+fn all_context_request_callers_are_policy_tested() {+ let commands_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/commands");+ let covered: std::collections::BTreeSet<&str> =+ POLICY_TESTED_COMMANDS.iter().copied().collect();++ let mut uncovered: Vec<String> = std::fs::read_dir(&commands_dir)+ .expect("commands directory must be readable")+ .filter_map(|entry| entry.ok())+ .filter_map(|entry| {+ let path = entry.path();+ if path.extension().is_some_and(|e| e == "rs") {+ path.file_stem()+ .and_then(|s| s.to_str())+ .map(ToOwned::to_owned)+ } else {+ None+ }+ })+ .filter(|stem| !stem.ends_with("_tests"))+ .filter(|stem| {+ if covered.contains(stem.as_str()) {+ return false;+ }+ let path = commands_dir.join(format!("{stem}.rs"));+ let source = std::fs::read_to_string(&path).unwrap_or_default();+ source.contains("context.request(")+ })+ .collect();++ uncovered.sort();+ assert!(+ uncovered.is_empty(),+ "new ref-action command(s) call context.request( but are not in POLICY_TESTED_COMMANDS: {uncovered:?}\n\+ Add each stem to POLICY_TESTED_COMMANDS and write a matching policy assertion."+ );+}diff --git a/crates/core/src/commands/right_click.rs b/crates/core/src/commands/right_click.rsindex 95ff1f4cd..10abf77ed 100644--- a/crates/core/src/commands/right_click.rs+++ b/crates/core/src/commands/right_click.rs@@ -1,17 +1,28 @@use crate::{- action::{Action, ActionRequest},+ action::Action,adapter::{PlatformAdapter, SnapshotSurface, TreeOptions},- commands::helpers::{RefArgs, find_window_for_pid, resolve_ref},+ commands::helpers::{RefArgs, execute_ref_action_result_with_context, find_window_for_pid},+ context::CommandContext,error::AppError,+ interaction_policy::InteractionPolicy,refs::RefEntry,snapshot,};use serde_json::{Value, json};-pub fn execute(args: RefArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- let (entry, handle) = resolve_ref(&args.ref_id, args.snapshot_id.as_deref(), adapter)?;- let result =- adapter.execute_action(handle.handle(), ActionRequest::headless(Action::RightClick))?;+pub fn execute(+ args: RefArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ let request = context.request(Action::RightClick, InteractionPolicy::headless());+ let (entry, result) = execute_ref_action_result_with_context(+ &args.ref_id,+ args.snapshot_id.as_deref(),+ adapter,+ request,+ context,+ )?;let mut response = serde_json::to_value(&result)?;std::thread::sleep(std::time::Duration::from_millis(200));@@ -22,7 +33,7 @@ pub fn execute(args: RefArgs, adapter: &dyn PlatformAdapter) -> Result<Value, Ap..Default::default()};let probe_app = probe_app_name(adapter, &entry);- match snapshot::run(adapter, &opts, probe_app.as_deref(), None) {+ match snapshot::run_with_context(adapter, &opts, probe_app.as_deref(), None, context) {Ok(snap) => match serde_json::to_value(&snap.tree) {Ok(menu_json) => {response["menu"] = menu_json;diff --git a/crates/core/src/commands/right_click_tests.rs b/crates/core/src/commands/right_click_tests.rsindex d4aa1b8f7..701dda24b 100644--- a/crates/core/src/commands/right_click_tests.rs+++ b/crates/core/src/commands/right_click_tests.rs@@ -1,6 +1,7 @@use super::*;use crate::{- action::ActionResult,+ action_request::ActionRequest,+ action_result::ActionResult,adapter::{NativeHandle, WindowFilter},error::{AdapterError, ErrorCode},node::WindowInfo,@@ -14,7 +15,7 @@ struct ProbeFailingAdapter {}impl PlatformAdapter for ProbeFailingAdapter {- fn resolve_element(&self, _entry: &RefEntry) -> Result<NativeHandle, AdapterError> {+ fn resolve_element_strict(&self, _entry: &RefEntry) -> Result<NativeHandle, AdapterError> {Ok(NativeHandle::null())}@@ -107,6 +108,7 @@ fn returns_action_success_when_menu_probe_fails() {snapshot_id: Some(snapshot_id),},&ProbeFailingAdapter { tree_error: None },+ &CommandContext::default(),).unwrap();@@ -128,6 +130,7 @@ fn element_not_found_menu_probe_uses_right_click_specific_guidance() {&ProbeFailingAdapter {tree_error: Some(ErrorCode::ElementNotFound),},+ &CommandContext::default(),).unwrap();diff --git a/crates/core/src/commands/scroll.rs b/crates/core/src/commands/scroll.rsindex 5c65ef9c1..ace5f00d3 100644--- a/crates/core/src/commands/scroll.rs+++ b/crates/core/src/commands/scroll.rs@@ -1,8 +1,10 @@use crate::{- action::{Action, ActionRequest, Direction},+ action::{Action, Direction},adapter::PlatformAdapter,- commands::helpers::resolve_ref,+ commands::helpers::execute_ref_action_result_with_context,+ context::CommandContext,error::AppError,+ interaction_policy::InteractionPolicy,};use serde_json::Value;@@ -13,11 +15,21 @@ pub struct ScrollArgs {pub amount: u32,}-pub fn execute(args: ScrollArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- let (_entry, handle) = resolve_ref(&args.ref_id, args.snapshot_id.as_deref(), adapter)?;- let result = adapter.execute_action(- handle.handle(),- ActionRequest::headless(Action::Scroll(args.direction, args.amount)),+pub fn execute(+ args: ScrollArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ let request = context.request(+ Action::Scroll(args.direction, args.amount),+ InteractionPolicy::headless(),+ );+ let (_entry, result) = execute_ref_action_result_with_context(+ &args.ref_id,+ args.snapshot_id.as_deref(),+ adapter,+ request,+ context,)?;Ok(serde_json::to_value(result)?)}diff --git a/crates/core/src/commands/scroll_to.rs b/crates/core/src/commands/scroll_to.rsindex 38823edeb..3d32c07e9 100644--- a/crates/core/src/commands/scroll_to.rs+++ b/crates/core/src/commands/scroll_to.rs@@ -1,11 +1,22 @@use crate::{- action::{Action, ActionRequest},+ action::Action,adapter::PlatformAdapter,- commands::helpers::{RefArgs, execute_ref_action},+ commands::helpers::{RefArgs, execute_ref_action_with_context},+ context::CommandContext,error::AppError,+ interaction_policy::InteractionPolicy,};use serde_json::Value;-pub fn execute(args: RefArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- execute_ref_action(args, adapter, ActionRequest::headless(Action::ScrollTo))+pub fn execute(+ args: RefArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ execute_ref_action_with_context(+ args,+ adapter,+ context.request(Action::ScrollTo, InteractionPolicy::headless()),+ context,+ )}diff --git a/crates/core/src/commands/select.rs b/crates/core/src/commands/select.rsindex 6765c6669..f396d1516 100644--- a/crates/core/src/commands/select.rs+++ b/crates/core/src/commands/select.rs@@ -1,8 +1,7 @@use crate::{- action::{Action, ActionRequest},- adapter::PlatformAdapter,- commands::helpers::resolve_ref,- error::AppError,+ action::Action, adapter::PlatformAdapter,+ commands::helpers::execute_ref_action_result_with_context, context::CommandContext,+ error::AppError, interaction_policy::InteractionPolicy,};use serde_json::Value;@@ -12,11 +11,18 @@ pub struct SelectArgs {pub value: String,}-pub fn execute(args: SelectArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- let (_entry, handle) = resolve_ref(&args.ref_id, args.snapshot_id.as_deref(), adapter)?;- let result = adapter.execute_action(- handle.handle(),- ActionRequest::headless(Action::Select(args.value)),+pub fn execute(+ args: SelectArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ let request = context.request(Action::Select(args.value), InteractionPolicy::headless());+ let (_entry, result) = execute_ref_action_result_with_context(+ &args.ref_id,+ args.snapshot_id.as_deref(),+ adapter,+ request,+ context,)?;Ok(serde_json::to_value(result)?)}diff --git a/crates/core/src/commands/set_value.rs b/crates/core/src/commands/set_value.rsindex 493751298..dc67d2ad6 100644--- a/crates/core/src/commands/set_value.rs+++ b/crates/core/src/commands/set_value.rs@@ -1,8 +1,7 @@use crate::{- action::{Action, ActionRequest},- adapter::PlatformAdapter,- commands::helpers::resolve_ref,- error::AppError,+ action::Action, adapter::PlatformAdapter,+ commands::helpers::execute_ref_action_result_with_context, context::CommandContext,+ error::AppError, interaction_policy::InteractionPolicy,};use serde_json::Value;@@ -12,11 +11,18 @@ pub struct SetValueArgs {pub value: String,}-pub fn execute(args: SetValueArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- let (_entry, handle) = resolve_ref(&args.ref_id, args.snapshot_id.as_deref(), adapter)?;- let result = adapter.execute_action(- handle.handle(),- ActionRequest::headless(Action::SetValue(args.value)),+pub fn execute(+ args: SetValueArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ let request = context.request(Action::SetValue(args.value), InteractionPolicy::headless());+ let (_entry, result) = execute_ref_action_result_with_context(+ &args.ref_id,+ args.snapshot_id.as_deref(),+ adapter,+ request,+ context,)?;Ok(serde_json::to_value(result)?)}diff --git a/crates/core/src/commands/snapshot.rs b/crates/core/src/commands/snapshot.rsindex 0a7b23b01..ffb0b30e3 100644--- a/crates/core/src/commands/snapshot.rs+++ b/crates/core/src/commands/snapshot.rs@@ -1,5 +1,6 @@use crate::{adapter::{PlatformAdapter, SnapshotSurface},+ context::CommandContext,error::AppError,refs::validate_ref_id,snapshot, snapshot_ref,@@ -37,7 +38,11 @@ fn tree_options(args: &SnapshotArgs) -> crate::adapter::TreeOptions {}}-pub fn execute(args: SnapshotArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {+pub fn execute(+ args: SnapshotArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {tracing::debug!("tree: snapshot app={:?} window_id={:?} max_depth={} interactive_only={} compact={}",args.app.as_deref().unwrap_or("(focused)"),@@ -56,19 +61,21 @@ pub fn execute(args: SnapshotArgs, adapter: &dyn PlatformAdapter) -> Result<Valu));}validate_ref_id(root)?;- return format_result(snapshot_ref::run_from_ref(+ return format_result(snapshot_ref::run_from_ref_with_context(adapter,&opts,root,args.snapshot_id.as_deref(),+ context,)?);}- let result = snapshot::run(+ let result = snapshot::run_with_context(adapter,&opts,args.app.as_deref(),args.window_id.as_deref(),+ context,)?;format_result(result)diff --git a/crates/core/src/commands/snapshot_tests.rs b/crates/core/src/commands/snapshot_tests.rsindex 307397000..24972e79c 100644--- a/crates/core/src/commands/snapshot_tests.rs+++ b/crates/core/src/commands/snapshot_tests.rs@@ -63,7 +63,8 @@ fn test_tree_options_suppresses_skeleton_for_drill_down() {#[test]fn test_root_with_menu_surface_rejected() {let args = args_with_surface(SnapshotSurface::Menu);- let err = execute(args, &NoopAdapter).expect_err("should reject --root + --surface");+ let err = execute(args, &NoopAdapter, &CommandContext::default())+ .expect_err("should reject --root + --surface");match err {AppError::Adapter(adapter_err) => {assert_eq!(adapter_err.code, ErrorCode::InvalidArgs);@@ -80,7 +81,7 @@ fn test_root_with_menu_surface_rejected() {#[test]fn test_root_with_window_surface_does_not_short_circuit_validation() {let args = args_with_surface(SnapshotSurface::Window);- let result = execute(args, &NoopAdapter);+ let result = execute(args, &NoopAdapter, &CommandContext::default());assert!(result.is_err(),"NoopAdapter cannot satisfy run_from_ref so this must error"@@ -100,7 +101,8 @@ fn test_invalid_root_ref_format_returns_invalid_args() {root_ref: Some("not-a-ref".into()),..base_args()};- let err = execute(args, &NoopAdapter).expect_err("malformed --root should fail");+ let err = execute(args, &NoopAdapter, &CommandContext::default())+ .expect_err("malformed --root should fail");match err {AppError::Adapter(adapter_err) => {assert_eq!(@@ -119,7 +121,8 @@ fn test_valid_root_ref_format_does_not_trigger_invalid_args() {root_ref: Some("@e42".into()),..base_args()};- let err = execute(args, &NoopAdapter).expect_err("NoopAdapter cannot resolve ref");+ let err = execute(args, &NoopAdapter, &CommandContext::default())+ .expect_err("NoopAdapter cannot resolve ref");if let AppError::Adapter(adapter_err) = err {assert_ne!(adapter_err.code,diff --git a/crates/core/src/commands/status.rs b/crates/core/src/commands/status.rsindex 41f43e894..2436d7e2b 100644--- a/crates/core/src/commands/status.rs+++ b/crates/core/src/commands/status.rs@@ -2,24 +2,21 @@ use crate::{PermissionReport,adapter::PlatformAdapter,commands::permissions::{self, PermissionsArgs},+ context::CommandContext,error::AppError,refs_store::RefStore,};use serde_json::{Value, json};-pub fn execute(adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- let report = adapter.permission_report();- execute_with_report(adapter, &report)-}--pub fn execute_with_report(+pub fn execute_with_report_with_context(adapter: &dyn PlatformAdapter,report: &PermissionReport,+ context: &CommandContext,) -> Result<Value, AppError> {let permissions =permissions::execute_with_report(PermissionsArgs { request: false }, adapter, report)?;- let store = RefStore::new().ok();+ let store = RefStore::for_session(context.session_id()).ok();let ref_count = store.as_ref().and_then(|s| s.load_latest().ok())diff --git a/crates/core/src/commands/status_tests.rs b/crates/core/src/commands/status_tests.rsindex 955102b26..82fa73881 100644--- a/crates/core/src/commands/status_tests.rs+++ b/crates/core/src/commands/status_tests.rs@@ -25,7 +25,9 @@ fn status_uses_precomputed_permission_report() {automation: PermissionState::NotRequired,};- let value = execute_with_report(&DeniedAdapter, &report).unwrap();+ let value =+ execute_with_report_with_context(&DeniedAdapter, &report, &CommandContext::default())+ .unwrap();let permissions = value.get("permissions").unwrap();assert_eq!(permissions["accessibility"]["state"], "granted");diff --git a/crates/core/src/commands/toggle.rs b/crates/core/src/commands/toggle.rsindex 531375b3a..c55c8c0b8 100644--- a/crates/core/src/commands/toggle.rs+++ b/crates/core/src/commands/toggle.rs@@ -1,11 +1,22 @@use crate::{- action::{Action, ActionRequest},+ action::Action,adapter::PlatformAdapter,- commands::helpers::{RefArgs, execute_ref_action},+ commands::helpers::{RefArgs, execute_ref_action_with_context},+ context::CommandContext,error::AppError,+ interaction_policy::InteractionPolicy,};use serde_json::Value;-pub fn execute(args: RefArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- execute_ref_action(args, adapter, ActionRequest::headless(Action::Toggle))+pub fn execute(+ args: RefArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ execute_ref_action_with_context(+ args,+ adapter,+ context.request(Action::Toggle, InteractionPolicy::headless()),+ context,+ )}diff --git a/crates/core/src/commands/triple_click.rs b/crates/core/src/commands/triple_click.rsindex 88ccc4155..35ff65578 100644--- a/crates/core/src/commands/triple_click.rs+++ b/crates/core/src/commands/triple_click.rs@@ -1,11 +1,22 @@use crate::{- action::{Action, ActionRequest},+ action::Action,adapter::PlatformAdapter,- commands::helpers::{RefArgs, execute_ref_action},+ commands::helpers::{RefArgs, execute_ref_action_with_context},+ context::CommandContext,error::AppError,+ interaction_policy::InteractionPolicy,};use serde_json::Value;-pub fn execute(args: RefArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- execute_ref_action(args, adapter, ActionRequest::headless(Action::TripleClick))+pub fn execute(+ args: RefArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ execute_ref_action_with_context(+ args,+ adapter,+ context.request(Action::TripleClick, InteractionPolicy::headless()),+ context,+ )}diff --git a/crates/core/src/commands/type_text.rs b/crates/core/src/commands/type_text.rsindex a605fe3c5..7855d8432 100644--- a/crates/core/src/commands/type_text.rs+++ b/crates/core/src/commands/type_text.rs@@ -1,8 +1,7 @@use crate::{- action::{Action, ActionRequest},- adapter::PlatformAdapter,- commands::helpers::resolve_ref,- error::AppError,+ action::Action, adapter::PlatformAdapter,+ commands::helpers::execute_ref_action_result_with_context, context::CommandContext,+ error::AppError, interaction_policy::InteractionPolicy,};use serde_json::Value;@@ -14,17 +13,27 @@ pub struct TypeArgs {pub text: String,}-pub fn execute(args: TypeArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {+pub fn execute(+ args: TypeArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {if args.text.len() > MAX_TEXT_LEN {return Err(AppError::invalid_input(format!("Text exceeds maximum length of {MAX_TEXT_LEN} characters")));}- let (_entry, handle) = resolve_ref(&args.ref_id, args.snapshot_id.as_deref(), adapter)?;- let result = adapter.execute_action(- handle.handle(),- ActionRequest::focus_fallback(Action::TypeText(args.text)),+ let request = context.request(+ Action::TypeText(args.text),+ InteractionPolicy::focus_fallback(),+ );+ let (_entry, result) = execute_ref_action_result_with_context(+ &args.ref_id,+ args.snapshot_id.as_deref(),+ adapter,+ request,+ context,)?;Ok(serde_json::to_value(result)?)}diff --git a/crates/core/src/commands/uncheck.rs b/crates/core/src/commands/uncheck.rsindex 44c85b251..58e6ed860 100644--- a/crates/core/src/commands/uncheck.rs+++ b/crates/core/src/commands/uncheck.rs@@ -1,11 +1,22 @@use crate::{- action::{Action, ActionRequest},+ action::Action,adapter::PlatformAdapter,- commands::helpers::{RefArgs, execute_ref_action},+ commands::helpers::{RefArgs, execute_ref_action_with_context},+ context::CommandContext,error::AppError,+ interaction_policy::InteractionPolicy,};use serde_json::Value;-pub fn execute(args: RefArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- execute_ref_action(args, adapter, ActionRequest::headless(Action::Uncheck))+pub fn execute(+ args: RefArgs,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ execute_ref_action_with_context(+ args,+ adapter,+ context.request(Action::Uncheck, InteractionPolicy::headless()),+ context,+ )}diff --git a/crates/core/src/commands/wait.rs b/crates/core/src/commands/wait.rsindex 297730bf8..9ed024134 100644--- a/crates/core/src/commands/wait.rs+++ b/crates/core/src/commands/wait.rs@@ -1,198 +1,107 @@use crate::{adapter::{PlatformAdapter, WindowFilter},- commands::helpers::resolve_app_pid,+ commands::{+ helpers::resolve_app_pid,+ wait_element::{ElementWaitInput, wait_for_element},+ wait_mode::WaitMode,+ wait_text_match, wait_timeout,+ },+ context::CommandContext,error::{AppError, ErrorCode},- node::AccessibilityNode,- notification::NotificationFilter,- refs::{RefMap, validate_ref_id},+ notification::{NotificationFilter, NotificationInfo},refs_store::RefStore,search_text, snapshot,};use serde_json::{Value, json};use std::time::{Duration, Instant};+#[cfg(test)]+use crate::commands::wait_mode::validate_wait_mode;++#[derive(Clone)]pub struct WaitArgs {+ pub mode: WaitModeArgs,+ pub predicate: WaitPredicateArgs,+ pub timeout_ms: u64,+ pub app: Option<String>,+}++#[derive(Clone)]+pub struct WaitModeArgs {pub ms: Option<u64>,pub element: Option<String>,- pub snapshot_id: Option<String>,pub window: Option<String>,pub text: Option<String>,- pub timeout_ms: u64,pub menu: bool,pub menu_closed: bool,pub notification: bool,- pub app: Option<String>,-}--pub fn execute(args: WaitArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- validate_wait_mode(&args)?;-- if let Some(ms) = args.ms {- std::thread::sleep(Duration::from_millis(ms));- return Ok(json!({ "waited_ms": ms }));- }-- if args.menu || args.menu_closed {- let pid = resolve_app_pid(args.app.as_deref(), adapter)?;- let start = Instant::now();- adapter- .wait_for_menu(pid, args.menu, args.timeout_ms)- .map_err(AppError::Adapter)?;- let elapsed = start.elapsed().as_millis();- return Ok(json!({ "found": true, "elapsed_ms": elapsed }));- }-- if args.notification {- return wait_for_notification(&args, adapter);- }-- if let Some(ref_id) = args.element {- validate_ref_id(&ref_id)?;- return wait_for_element(ref_id, args.snapshot_id, args.timeout_ms, adapter);- }-- if let Some(title) = args.window {- return wait_for_window(title, args.timeout_ms, adapter);- }-- if let Some(text) = args.text {- return wait_for_text(text, args.app, args.timeout_ms, adapter);- }-- Err(AppError::invalid_input(- "Provide a duration (ms), --menu, --notification, --element <ref>, --window <title>, or --text <text>",- ))}-fn validate_wait_mode(args: &WaitArgs) -> Result<(), AppError> {- let selected = [- args.ms.is_some(),- args.element.is_some(),- args.window.is_some(),- args.text.is_some() && !args.notification,- args.menu,- args.menu_closed,- args.notification,- ]- .into_iter()- .filter(|selected| *selected)- .count();- if selected <= 1 {- return Ok(());- }- Err(AppError::invalid_input_with_suggestion(- "wait accepts exactly one mode",- "Use one of: ms, --element, --window, --text, --menu, --menu-closed, or --notification.",- ))+#[derive(Clone)]+pub struct WaitPredicateArgs {+ pub snapshot_id: Option<String>,+ pub predicate: Option<String>,+ pub value: Option<String>,+ pub action: Option<String>,+ pub count: Option<usize>,}-fn wait_for_element(- ref_id: String,- snapshot_id: Option<String>,- timeout_ms: u64,+pub fn execute(+ args: WaitArgs,adapter: &dyn PlatformAdapter,+ context: &CommandContext,) -> Result<Value, AppError> {- let start = Instant::now();- let timeout = Duration::from_millis(timeout_ms);- let store = RefStore::new()?;- let fixed_refmap = match snapshot_id.as_deref() {- Some(id) => Some(store.load_snapshot(id)?),- None => None,- };- let mut latest_cache = if fixed_refmap.is_none() {- Some(LatestRefCache::new(&store)?)- } else {- None- };-- if fixed_refmap- .as_ref()- .is_some_and(|refmap| refmap.get(&ref_id).is_none())- {- return Err(AppError::invalid_input_with_suggestion(- format!("Ref {ref_id} is not present in the requested snapshot"),- "Use a ref returned by that snapshot_id, or omit --snapshot to wait against the latest refmap.",- ));- }-- loop {- let entry = fixed_refmap- .as_ref()- .and_then(|r| r.get(&ref_id).cloned())- .or_else(|| latest_cache.as_ref().and_then(|c| c.entry(&ref_id)));- if let Some(entry) = entry {- match adapter.resolve_element(&entry) {- Ok(handle) => {- let _ = adapter.release_handle(&handle);- let elapsed = start.elapsed().as_millis();- return Ok(json!({ "found": true, "ref": ref_id, "elapsed_ms": elapsed }));- }- Err(err) if fixed_refmap.is_none() && err.code == ErrorCode::StaleRef => {- if let Some(cache) = latest_cache.as_mut() {- cache.refresh_if_due();- }- }- Err(_) => {}- }- } else if let Some(cache) = latest_cache.as_mut() {- cache.refresh_if_due();+ let timeout_ms = args.timeout_ms;+ match WaitMode::from_args(args)? {+ WaitMode::Sleep(ms) => {+ std::thread::sleep(Duration::from_millis(ms));+ Ok(json!({ "waited_ms": ms }))}-- let remaining = timeout.saturating_sub(start.elapsed());- if remaining.is_zero() {- return Err(AppError::Adapter(crate::error::AdapterError::timeout(- format!("Element {ref_id} not found within {timeout_ms}ms"),- )));+ WaitMode::Menu { app, open } => wait_for_menu(app, open, timeout_ms, adapter),+ WaitMode::Notification { app, text } => {+ wait_for_notification(app, text, timeout_ms, adapter)}- std::thread::sleep(remaining.min(Duration::from_millis(100)));- }-}--struct LatestRefCache<'a> {- store: &'a RefStore,- snapshot_id: Option<String>,- refmap: RefMap,- last_refresh: Instant,-}--impl<'a> LatestRefCache<'a> {- fn new(store: &'a RefStore) -> Result<Self, AppError> {- let snapshot_id = store.latest_snapshot_id();- let refmap = if let Some(id) = snapshot_id.as_deref() {- store.load_snapshot(id)?- } else {- store.load_latest()?- };- Ok(Self {- store,+ WaitMode::Element {+ ref_id,snapshot_id,- refmap,- last_refresh: Instant::now() - Duration::from_millis(500),- })- }-- fn entry(&self, ref_id: &str) -> Option<crate::refs::RefEntry> {- self.refmap.get(ref_id).cloned()+ predicate,+ } => wait_for_element(+ ElementWaitInput {+ ref_id,+ snapshot_id,+ predicate,+ timeout_ms,+ },+ adapter,+ context,+ ),+ WaitMode::Window(title) => wait_for_window(title, timeout_ms, adapter),+ WaitMode::Text { text, count, app } => wait_for_text(+ TextWaitInput {+ text,+ expected_count: count,+ app,+ timeout_ms,+ },+ adapter,+ context,+ ),}+}- fn refresh_if_due(&mut self) {- if self.last_refresh.elapsed() < Duration::from_millis(500) {- return;- }- self.last_refresh = Instant::now();- if let Some(snapshot_id) = self.store.latest_snapshot_id() {- if self.snapshot_id.as_deref() == Some(snapshot_id.as_str()) {- return;- }- if let Ok(refmap) = self.store.load_snapshot(&snapshot_id) {- self.snapshot_id = Some(snapshot_id);- self.refmap = refmap;- }- } else if let Ok(refmap) = self.store.load_latest() {- self.refmap = refmap;- self.snapshot_id = self.store.latest_snapshot_id();- }- }+fn wait_for_menu(+ app: Option<String>,+ open: bool,+ timeout_ms: u64,+ adapter: &dyn PlatformAdapter,+) -> Result<Value, AppError> {+ let pid = resolve_app_pid(app.as_deref(), adapter)?;+ let start = Instant::now();+ adapter+ .wait_for_menu(pid, open, timeout_ms)+ .map_err(AppError::Adapter)?;+ let elapsed = start.elapsed().as_millis();+ Ok(json!({ "found": true, "elapsed_ms": elapsed }))}fn wait_for_window(@@ -206,58 +115,97 @@ fn wait_for_window(focused_only: false,app: None,};+ let mut last_error = None;loop {- if let Ok(windows) = adapter.list_windows(&filter) {- if let Some(win) = windows.into_iter().find(|w| w.title.contains(&title)) {- let elapsed = start.elapsed().as_millis();- return Ok(json!({ "found": true, "window": win, "elapsed_ms": elapsed }));+ match adapter.list_windows(&filter) {+ Ok(windows) => {+ if let Some(win) = windows.into_iter().find(|w| w.title.contains(&title)) {+ let elapsed = start.elapsed().as_millis();+ return Ok(json!({ "found": true, "window": win, "elapsed_ms": elapsed }));+ }}+ Err(err) if is_retryable_wait_poll_error(&err.code) => {+ last_error = Some(json!({+ "code": err.code.as_str(),+ "message": err.message+ }));+ }+ Err(err) => return Err(AppError::Adapter(err)),}- if start.elapsed() >= timeout {- return Err(AppError::Adapter(crate::error::AdapterError::timeout(- format!("Window with title '{title}' not found within {timeout_ms}ms"),- )));+ let remaining = timeout.saturating_sub(start.elapsed());+ if remaining.is_zero() {+ return wait_timeout::window(&title, timeout_ms, last_error);}- std::thread::sleep(Duration::from_millis(100));+ std::thread::sleep(remaining.min(Duration::from_millis(100)));}}-fn wait_for_text(+struct TextWaitInput {text: String,+ expected_count: Option<usize>,app: Option<String>,timeout_ms: u64,+}++fn wait_for_text(+ input: TextWaitInput,adapter: &dyn PlatformAdapter,+ context: &CommandContext,) -> Result<Value, AppError> {+ let TextWaitInput {+ text,+ expected_count,+ app,+ timeout_ms,+ } = input;let start = Instant::now();let timeout = Duration::from_millis(timeout_ms);let opts = crate::adapter::TreeOptions::default();let normalized_text = search_text::normalize(&text);let mut interval = Duration::from_millis(200);+ let mut last_error = None;loop {- if let Ok(result) = snapshot::build(adapter, &opts, app.as_deref(), None) {- if let Some(found) = find_text_in_tree(&result.tree, &normalized_text) {- let snapshot_id = RefStore::new()?.save_new_snapshot(&result.refmap)?;- let elapsed = start.elapsed().as_millis();- return Ok(json!({- "found": true,- "text": text,- "ref": found.ref_id,- "role": found.role,- "snapshot_id": snapshot_id,- "elapsed_ms": elapsed+ match snapshot::build(adapter, &opts, app.as_deref(), None) {+ Ok(result) => {+ let matches = wait_text_match::find(&result.tree, &normalized_text, expected_count);+ let matched = expected_count+ .map(|expected| matches.len() == expected)+ .unwrap_or_else(|| !matches.is_empty());+ if matched {+ let snapshot_id = RefStore::for_session(context.session_id())?+ .save_new_snapshot(&result.refmap)?;+ let elapsed = start.elapsed().as_millis();+ let found = matches.first();+ let mut body = json!({+ "found": true,+ "text": text,+ "ref": found.and_then(|found| found.ref_id.clone()),+ "role": found.map(|found| found.role.clone()),+ "snapshot_id": snapshot_id,+ "elapsed_ms": elapsed+ });+ if expected_count.is_some() {+ body["count"] = json!(matches.len());+ }+ return Ok(body);+ }+ }+ Err(err) if is_retryable_wait_app_error(&err) => {+ last_error = Some(json!({+ "code": err.code(),+ "message": err.to_string()}));}+ Err(err) => return Err(err),}let remaining = timeout.saturating_sub(start.elapsed());if remaining.is_zero() {- return Err(AppError::Adapter(crate::error::AdapterError::timeout(- format!("Text '{text}' not found within {timeout_ms}ms"),- )));+ return wait_timeout::text(&text, timeout_ms, expected_count, last_error);}std::thread::sleep(remaining.min(interval));@@ -265,71 +213,128 @@ fn wait_for_text(}}-struct TextMatch {- ref_id: Option<String>,- role: String,+fn is_retryable_wait_poll_error(code: &ErrorCode) -> bool {+ matches!(code, ErrorCode::Timeout | ErrorCode::ElementNotFound)+}++fn is_retryable_wait_app_error(err: &AppError) -> bool {+ matches!(err, AppError::Adapter(err) if is_retryable_wait_poll_error(&err.code))}fn wait_for_notification(- args: &WaitArgs,+ app: Option<String>,+ text: Option<String>,+ timeout_ms: u64,adapter: &dyn PlatformAdapter,) -> Result<Value, AppError> {let filter = NotificationFilter {- app: args.app.clone(),- text: args.text.clone(),+ app: app.clone(),+ text: text.clone(),..Default::default()};- let baseline = adapter- .list_notifications(&filter)- .map_err(AppError::Adapter)?;- let baseline_indices: std::collections::HashSet<usize> =- baseline.iter().map(|n| n.index).collect();- let interval = Duration::from_millis(500);- let deadline = Instant::now() + Duration::from_millis(args.timeout_ms);let start = Instant::now();+ let timeout = Duration::from_millis(timeout_ms);+ let mut baseline: Option<std::collections::HashMap<NotificationFingerprint, usize>> = None;+ let mut last_error = None;loop {- if Instant::now() > deadline {- return Err(AppError::Adapter(crate::error::AdapterError::timeout(- format!("No new notification within {}ms", args.timeout_ms),- )));+ match adapter.list_notifications(&filter) {+ Ok(current) => match &baseline {+ None => {+ baseline = Some(notification_counts(¤t));+ }+ Some(baseline) => {+ if let Some(notif) = first_new_notification(¤t, baseline) {+ let elapsed = start.elapsed().as_millis();+ return Ok(json!({+ "condition": "notification",+ "matched": true,+ "notification": notif,+ "elapsed_ms": elapsed,+ }));+ }+ }+ },+ Err(err) if is_retryable_wait_poll_error(&err.code) => {+ last_error = Some(json!({+ "code": err.code.as_str(),+ "message": err.message+ }));+ }+ Err(err) => return Err(AppError::Adapter(err)),}- let current = adapter- .list_notifications(&filter)- .map_err(AppError::Adapter)?;- let Some(notif) = current- .iter()- .find(|n| !baseline_indices.contains(&n.index))- else {- std::thread::sleep(interval);- continue;- };- let elapsed = start.elapsed().as_millis();- return Ok(json!({- "condition": "notification",- "matched": true,- "notification": notif,- "elapsed_ms": elapsed,- }));++ let remaining = timeout.saturating_sub(start.elapsed());+ if remaining.is_zero() {+ return wait_timeout::notification(app.as_ref(), text.as_ref(), timeout_ms, last_error);+ }+ std::thread::sleep(remaining.min(Duration::from_millis(500)));}}-fn find_text_in_tree(node: &AccessibilityNode, text_lower: &str) -> Option<TextMatch> {- if search_text::node_contains(node, text_lower) {- return Some(TextMatch {- ref_id: node.ref_id.clone(),- role: node.role.clone(),- });+#[derive(Clone, Eq, Hash, PartialEq)]+struct NotificationFingerprint {+ app_name: String,+ title: String,+ body: Option<String>,+ actions: Vec<String>,+}++impl From<&NotificationInfo> for NotificationFingerprint {+ fn from(info: &NotificationInfo) -> Self {+ Self {+ app_name: info.app_name.clone(),+ title: info.title.clone(),+ body: info.body.clone(),+ actions: info.actions.clone(),+ }}+}- for child in &node.children {- if let Some(found) = find_text_in_tree(child, text_lower) {- return Some(found);+fn notification_counts(+ notifications: &[NotificationInfo],+) -> std::collections::HashMap<NotificationFingerprint, usize> {+ let mut counts = std::collections::HashMap::new();+ for notification in notifications {+ *counts+ .entry(NotificationFingerprint::from(notification))+ .or_insert(0) += 1;+ }+ counts+}++fn first_new_notification<'a>(+ current: &'a [NotificationInfo],+ baseline: &std::collections::HashMap<NotificationFingerprint, usize>,+) -> Option<&'a NotificationInfo> {+ let mut seen = std::collections::HashMap::new();+ for notification in current {+ let fingerprint = NotificationFingerprint::from(notification);+ let current_count = seen.entry(fingerprint.clone()).or_insert(0);+ *current_count += 1;+ if *current_count > baseline.get(&fingerprint).copied().unwrap_or(0) {+ return Some(notification);}}None}+#[cfg(test)]+#[path = "wait_test_support.rs"]+mod test_support;+#[cfg(test)]#[path = "wait_tests.rs"]mod tests;++#[cfg(test)]+#[path = "wait_element_tests.rs"]+mod element_tests;++#[cfg(test)]+#[path = "wait_predicate_tests.rs"]+mod predicate_tests;++#[cfg(test)]+#[path = "wait_resolution_tests.rs"]+mod resolution_tests;diff --git a/crates/core/src/commands/wait_element.rs b/crates/core/src/commands/wait_element.rsnew file mode 100644index 000000000..e13d627d7--- /dev/null+++ b/crates/core/src/commands/wait_element.rs@@ -0,0 +1,118 @@+use crate::{+ adapter::PlatformAdapter,+ commands::{wait_latest_ref_cache::LatestRefCache, wait_predicate, wait_timeout},+ context::CommandContext,+ error::{AppError, ErrorCode},+ refs_store::RefStore,+};+use serde_json::{Value, json};+use std::time::{Duration, Instant};++/// Per-attempt cap on ref resolution inside a wait loop, so a slow resolve+/// cannot consume the whole wait budget on the first poll; the predicate is+/// re-checked every attempt across the full timeout.+const WAIT_RESOLVE_ATTEMPT: Duration = Duration::from_millis(750);++pub(crate) struct ElementWaitInput {+ pub(crate) ref_id: String,+ pub(crate) snapshot_id: Option<String>,+ pub(crate) predicate: wait_predicate::ElementPredicate,+ pub(crate) timeout_ms: u64,+}++pub(crate) fn wait_for_element(+ input: ElementWaitInput,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ let ElementWaitInput {+ ref_id,+ snapshot_id,+ predicate,+ timeout_ms,+ } = input;+ let start = Instant::now();+ let timeout = Duration::from_millis(timeout_ms);+ let store = RefStore::for_session(context.session_id())?;+ let fixed_refmap = match snapshot_id.as_deref() {+ Some(id) => Some(store.load_snapshot(id)?),+ None => None,+ };+ let mut latest_cache = if fixed_refmap.is_none() {+ Some(LatestRefCache::new(&store)?)+ } else {+ None+ };++ if fixed_refmap+ .as_ref()+ .is_some_and(|refmap| refmap.get(&ref_id).is_none())+ {+ return Err(AppError::invalid_input_with_suggestion(+ format!("Ref {ref_id} is not present in the requested snapshot"),+ "Use a ref returned by that snapshot_id, or omit --snapshot to wait against the latest refmap.",+ ));+ }++ let mut last_observed = json!(null);+ loop {+ let entry = fixed_refmap+ .as_ref()+ .and_then(|r| r.get(&ref_id).cloned())+ .or_else(|| latest_cache.as_ref().and_then(|c| c.entry(&ref_id)));+ if let Some(entry) = entry {+ let remaining = timeout.saturating_sub(start.elapsed());+ if remaining.is_zero() {+ return wait_timeout::element(ref_id, predicate, timeout_ms, last_observed);+ }+ let attempt = remaining.min(WAIT_RESOLVE_ATTEMPT);+ match adapter.resolve_element_strict_with_timeout(&entry, attempt) {+ Ok(handle) => {+ let observed = wait_predicate::observe(&entry, &handle, &predicate, adapter);+ let _ = adapter.release_handle(&handle);+ last_observed = observed.map_err(AppError::Adapter)?;+ if wait_predicate::satisfied(&predicate, &last_observed) {+ let elapsed = start.elapsed().as_millis();+ return Ok(json!({+ "found": true,+ "ref": ref_id,+ "predicate": predicate.name(),+ "observed": last_observed,+ "elapsed_ms": elapsed+ }));+ }+ }+ Err(err) if is_retryable_wait_resolution_error(&err.code) => {+ last_observed = json!({+ "error": err.code.as_str(),+ "message": err.message+ });+ if fixed_refmap.is_none() {+ if let Some(cache) = latest_cache.as_mut() {+ cache.refresh_if_due()?;+ }+ }+ }+ Err(err) => return Err(AppError::Adapter(err)),+ }+ } else if let Some(cache) = latest_cache.as_mut() {+ cache.refresh_if_due()?;+ }++ let remaining = timeout.saturating_sub(start.elapsed());+ if remaining.is_zero() {+ return wait_timeout::element(ref_id, predicate, timeout_ms, last_observed);+ }+ std::thread::sleep(remaining.min(Duration::from_millis(100)));+ }+}++fn is_retryable_wait_resolution_error(code: &ErrorCode) -> bool {+ matches!(+ code,+ ErrorCode::StaleRef+ | ErrorCode::ElementNotFound+ | ErrorCode::AmbiguousTarget+ | ErrorCode::Timeout+ )+}diff --git a/crates/core/src/commands/wait_element_tests.rs b/crates/core/src/commands/wait_element_tests.rsnew file mode 100644index 000000000..bb3a4f64b--- /dev/null+++ b/crates/core/src/commands/wait_element_tests.rs@@ -0,0 +1,132 @@+use super::test_support::{+ PredicateAdapter, save_ref_in_session, snapshot_with_one_ref, wait_for_element_test,+};+use super::*;+use crate::{+ adapter::{NativeHandle, PlatformAdapter},+ commands::wait_predicate,+ element_state::ElementState,+ error::AdapterError,+ refs::RefEntry,+ refs_test_support::HomeGuard,+};+use std::sync::atomic::{AtomicU32, Ordering};++struct NoopAdapter;++impl PlatformAdapter for NoopAdapter {}++struct LiveErrorPredicateAdapter {+ releases: AtomicU32,+}++impl PlatformAdapter for LiveErrorPredicateAdapter {+ fn resolve_element_strict_with_timeout(+ &self,+ _entry: &RefEntry,+ _timeout: std::time::Duration,+ ) -> Result<NativeHandle, AdapterError> {+ Ok(NativeHandle::null())+ }++ fn get_live_state(&self, _handle: &NativeHandle) -> Result<Option<ElementState>, AdapterError> {+ Err(AdapterError::permission_denied())+ }++ fn release_handle(&self, _handle: &NativeHandle) -> Result<(), AdapterError> {+ self.releases.fetch_add(1, Ordering::SeqCst);+ Ok(())+ }+}++#[test]+fn snapshot_pinned_missing_ref_is_invalid_args() {+ let _guard = HomeGuard::new();+ let snapshot_id = snapshot_with_one_ref();++ let err = wait_for_element_test(+ "@e2".into(),+ Some(snapshot_id),+ wait_predicate::ElementPredicate::Exists,+ 1,+ &NoopAdapter,+ &crate::context::CommandContext::default(),+ )+ .unwrap_err();++ assert_eq!(err.code(), "INVALID_ARGS");+ assert!(err.suggestion().is_some());+}++#[test]+fn element_wait_explicit_session_snapshot_without_session_context() {+ let _guard = HomeGuard::new();+ let snapshot_id = save_ref_in_session("agent-a", Vec::new());+ let adapter = PredicateAdapter {+ state: Some(ElementState {+ role: "button".into(),+ states: vec![],+ value: None,+ }),+ value: None,+ bounds: None,+ };++ let value = wait_for_element_test(+ "@e1".into(),+ Some(snapshot_id),+ wait_predicate::ElementPredicate::Exists,+ 50,+ &adapter,+ &crate::context::CommandContext::default(),+ )+ .unwrap();++ assert_eq!(value["found"], true);+ assert_eq!(value["predicate"], "exists");+}++#[test]+fn element_wait_propagates_live_read_errors_after_releasing_handle() {+ let _guard = HomeGuard::new();+ let snapshot_id = snapshot_with_one_ref();+ let adapter = LiveErrorPredicateAdapter {+ releases: AtomicU32::new(0),+ };++ let err = wait_for_element_test(+ "@e1".into(),+ Some(snapshot_id),+ wait_predicate::ElementPredicate::Enabled,+ 250,+ &adapter,+ &crate::context::CommandContext::default(),+ )+ .unwrap_err();++ assert_eq!(err.code(), "PERM_DENIED");+ assert_eq!(adapter.releases.load(Ordering::SeqCst), 1);+}++#[test]+fn zero_timeout_returns_timeout_before_any_resolution_attempt() {+ let _guard = HomeGuard::new();+ let snapshot_id = snapshot_with_one_ref();++ let err = wait_for_element_test(+ "@e1".into(),+ Some(snapshot_id),+ wait_predicate::ElementPredicate::Exists,+ 0,+ &NoopAdapter,+ &crate::context::CommandContext::default(),+ )+ .unwrap_err();++ let AppError::Adapter(adapter_err) = err else {+ panic!("expected adapter error");+ };+ assert_eq!(adapter_err.code, crate::error::ErrorCode::Timeout);+ let details = adapter_err.details.expect("timeout should carry details");+ assert!(details["last_observed"].is_null());+}diff --git a/crates/core/src/commands/wait_latest_ref_cache.rs b/crates/core/src/commands/wait_latest_ref_cache.rsnew file mode 100644index 000000000..3411b4699--- /dev/null+++ b/crates/core/src/commands/wait_latest_ref_cache.rs@@ -0,0 +1,69 @@+use crate::{error::AppError, refs::RefMap, refs_store::RefStore};+use std::time::{Duration, Instant};++pub(crate) struct LatestRefCache<'a> {+ store: &'a RefStore,+ snapshot_id: Option<String>,+ refmap: RefMap,+ last_refresh: Instant,+}++impl<'a> LatestRefCache<'a> {+ pub(crate) fn new(store: &'a RefStore) -> Result<Self, AppError> {+ let mut snapshot_id = store.latest_snapshot_id();+ let refmap = if let Some(id) = snapshot_id.as_deref() {+ store.load_snapshot(id)?+ } else {+ let refmap = store.load_latest()?;+ snapshot_id = store.latest_snapshot_id();+ refmap+ };+ Ok(Self {+ store,+ snapshot_id,+ refmap,+ last_refresh: Instant::now() - Duration::from_millis(500),+ })+ }++ pub(crate) fn entry(&self, ref_id: &str) -> Option<crate::refs::RefEntry> {+ self.refmap.get(ref_id).cloned()+ }++ pub(crate) fn refresh_if_due(&mut self) -> Result<(), AppError> {+ if self.last_refresh.elapsed() < Duration::from_millis(500) {+ return Ok(());+ }+ self.last_refresh = Instant::now();+ if let Some(snapshot_id) = self.snapshot_id.as_deref() {+ match self.store.load_snapshot(snapshot_id) {+ Ok(refmap) => {+ self.refmap = refmap;+ Ok(())+ }+ Err(err) => {+ tracing::warn!(+ "latest snapshot {snapshot_id} unreadable during wait refresh: {err}"+ );+ Ok(())+ }+ }+ } else {+ match self.store.load_latest() {+ Ok(refmap) => {+ self.refmap = refmap;+ self.snapshot_id = self.store.latest_snapshot_id();+ Ok(())+ }+ Err(err) => {+ tracing::warn!("latest refmap unreadable during wait refresh: {err}");+ Ok(())+ }+ }+ }+ }+}++#[cfg(test)]+#[path = "wait_latest_ref_cache_tests.rs"]+mod tests;diff --git a/crates/core/src/commands/wait_latest_ref_cache_tests.rs b/crates/core/src/commands/wait_latest_ref_cache_tests.rsnew file mode 100644index 000000000..84aa479a7--- /dev/null+++ b/crates/core/src/commands/wait_latest_ref_cache_tests.rs@@ -0,0 +1,135 @@+use super::*;+use crate::{+ adapter::SnapshotSurface,+ capability,+ refs::{RefEntry, RefMap},+ refs_test_support::HomeGuard,+};++fn save_ref(pid: i32, name: Option<&str>) -> String {+ RefStore::new()+ .unwrap()+ .save_new_snapshot(&refmap_with_ref(pid, name))+ .unwrap()+}++fn refmap_with_ref(pid: i32, name: Option<&str>) -> RefMap {+ let mut refmap = RefMap::new();+ refmap.allocate(RefEntry {+ pid,+ role: "button".into(),+ name: name.map(String::from),+ value: None,+ description: None,+ states: vec![],+ bounds: None,+ bounds_hash: None,+ available_actions: vec![capability::CLICK.into()],+ source_app: None,+ source_window_id: None,+ source_window_title: None,+ source_surface: SnapshotSurface::Window,+ root_ref: None,+ path_is_absolute: false,+ path: smallvec::SmallVec::new(),+ });+ refmap+}++#[test]+fn latest_ref_cache_pins_starting_snapshot_when_latest_advances() {+ let _guard = HomeGuard::new();+ let first_id = save_ref(1, Some("First"));+ let store = RefStore::new().unwrap();++ let mut cache = LatestRefCache::new(&store).unwrap();+ assert_eq!(cache.snapshot_id.as_deref(), Some(first_id.as_str()));++ let second_id = save_ref(99, Some("Second"));+ assert_ne!(first_id, second_id);++ cache.last_refresh = std::time::Instant::now() - std::time::Duration::from_secs(2);+ cache.refresh_if_due().unwrap();++ assert_eq!(cache.snapshot_id.as_deref(), Some(first_id.as_str()));+ assert_eq!(+ store.latest_snapshot_id().as_deref(),+ Some(second_id.as_str())+ );+ assert_eq!(cache.entry("@e1").unwrap().pid, 1);+}++#[test]+fn latest_ref_cache_debounces_consecutive_refreshes() {+ let _guard = HomeGuard::new();+ let _first_id = save_ref(1, Some("First"));+ let store = RefStore::new().unwrap();++ let mut cache = LatestRefCache::new(&store).unwrap();+ let pinned_snapshot_id = cache.snapshot_id.clone();++ let _ = save_ref(2, None);++ let debounced_refresh = std::time::Instant::now();+ cache.last_refresh = debounced_refresh;+ cache.refresh_if_due().unwrap();++ assert_eq!(cache.snapshot_id, pinned_snapshot_id);+ assert_eq!(cache.last_refresh, debounced_refresh);+}++#[test]+fn latest_ref_cache_keeps_last_good_map_when_pinned_snapshot_disappears() {+ let _guard = HomeGuard::new();+ let first_id = save_ref(1, Some("First"));+ let store = RefStore::new().unwrap();++ let mut cache = LatestRefCache::new(&store).unwrap();+ assert_eq!(cache.snapshot_id.as_deref(), Some(first_id.as_str()));++ let home = crate::refs::home_dir().unwrap();+ let snapshot_dir = home+ .join(".agent-desktop")+ .join("snapshots")+ .join(&first_id);+ std::fs::remove_dir_all(snapshot_dir).unwrap();++ cache.last_refresh = std::time::Instant::now() - std::time::Duration::from_secs(2);+ cache.refresh_if_due().unwrap();++ assert_eq!(cache.snapshot_id.as_deref(), Some(first_id.as_str()));+ assert_eq!(cache.entry("@e1").unwrap().pid, 1);+}++#[test]+fn latest_ref_cache_retries_unreadable_pinned_snapshot_after_refresh_error() {+ let _guard = HomeGuard::new();+ let first_id = save_ref(1, Some("First"));+ let store = RefStore::new().unwrap();++ let mut cache = LatestRefCache::new(&store).unwrap();+ assert_eq!(cache.snapshot_id.as_deref(), Some(first_id.as_str()));++ let refmap_path = crate::refs::home_dir()+ .unwrap()+ .join(".agent-desktop")+ .join("snapshots")+ .join(&first_id)+ .join("refmap.json");+ std::fs::write(&refmap_path, b"{not-json").unwrap();++ cache.last_refresh = std::time::Instant::now() - std::time::Duration::from_secs(2);+ cache.refresh_if_due().unwrap();++ assert_eq!(cache.snapshot_id.as_deref(), Some(first_id.as_str()));+ assert_eq!(cache.entry("@e1").unwrap().pid, 1);++ store+ .save_snapshot(&first_id, &refmap_with_ref(3, Some("Recovered")))+ .unwrap();+ cache.last_refresh = std::time::Instant::now() - std::time::Duration::from_secs(2);+ cache.refresh_if_due().unwrap();++ assert_eq!(cache.snapshot_id.as_deref(), Some(first_id.as_str()));+ assert_eq!(cache.entry("@e1").unwrap().pid, 3);+}diff --git a/crates/core/src/commands/wait_mode.rs b/crates/core/src/commands/wait_mode.rsnew file mode 100644index 000000000..a80b30b92--- /dev/null+++ b/crates/core/src/commands/wait_mode.rs@@ -0,0 +1,122 @@+use crate::{+ commands::{wait::WaitArgs, wait_predicate},+ error::AppError,+ refs::validate_ref_id,+};++pub(crate) enum WaitMode {+ Sleep(u64),+ Element {+ ref_id: String,+ snapshot_id: Option<String>,+ predicate: wait_predicate::ElementPredicate,+ },+ Window(String),+ Text {+ text: String,+ count: Option<usize>,+ app: Option<String>,+ },+ Menu {+ app: Option<String>,+ open: bool,+ },+ Notification {+ app: Option<String>,+ text: Option<String>,+ },+}++impl WaitMode {+ pub(crate) fn from_args(args: WaitArgs) -> Result<Self, AppError> {+ validate_wait_mode(&args)?;+ if let Some(ms) = args.mode.ms {+ return Ok(Self::Sleep(ms));+ }+ if args.mode.menu || args.mode.menu_closed {+ return Ok(Self::Menu {+ app: args.app,+ open: args.mode.menu,+ });+ }+ if args.mode.notification {+ return Ok(Self::Notification {+ app: args.app,+ text: args.mode.text,+ });+ }+ if let Some(ref_id) = args.mode.element {+ validate_ref_id(&ref_id)?;+ let predicate = wait_predicate::ElementPredicate::parse(+ args.predicate.predicate.as_deref(),+ args.predicate.value,+ args.predicate.action.as_deref(),+ )?;+ return Ok(Self::Element {+ ref_id,+ snapshot_id: args.predicate.snapshot_id,+ predicate,+ });+ }+ if let Some(title) = args.mode.window {+ return Ok(Self::Window(title));+ }+ if let Some(text) = args.mode.text {+ return Ok(Self::Text {+ text,+ count: args.predicate.count,+ app: args.app,+ });+ }+ Err(missing_wait_mode())+ }+}++pub(crate) fn validate_wait_mode(args: &WaitArgs) -> Result<(), AppError> {+ if args.predicate.predicate.is_some() && args.mode.element.is_none() {+ return Err(AppError::invalid_input_with_suggestion(+ "--predicate requires --element",+ "Use --element <ref> with --predicate, or remove --predicate.",+ ));+ }+ if args.predicate.value.is_some() && args.mode.element.is_none() {+ return Err(AppError::invalid_input_with_suggestion(+ "--value requires --element and --predicate value",+ "Use --element <ref> --predicate value --value <expected>.",+ ));+ }+ if args.predicate.count.is_some() && (args.mode.text.is_none() || args.mode.notification) {+ return Err(AppError::invalid_input_with_suggestion(+ "--count is only valid for --text waits",+ "Use --text <text> --count <expected> without --notification, or remove --count.",+ ));+ }+ let selected = [+ args.mode.ms.is_some(),+ args.mode.element.is_some(),+ args.mode.window.is_some(),+ args.mode.text.is_some() && !args.mode.notification,+ args.mode.menu,+ args.mode.menu_closed,+ args.mode.notification,+ ]+ .into_iter()+ .filter(|selected| *selected)+ .count();+ if selected == 1 {+ return Ok(());+ }+ if selected == 0 {+ return Err(missing_wait_mode());+ }+ Err(AppError::invalid_input_with_suggestion(+ "wait accepts exactly one mode",+ "Use one of: ms, --element, --window, --text, --menu, --menu-closed, or --notification.",+ ))+}++fn missing_wait_mode() -> AppError {+ AppError::invalid_input(+ "Provide a duration (ms), --menu, --notification, --element <ref>, --window <title>, or --text <text>",+ )+}diff --git a/crates/core/src/commands/wait_predicate.rs b/crates/core/src/commands/wait_predicate.rsnew file mode 100644index 000000000..952160b90--- /dev/null+++ b/crates/core/src/commands/wait_predicate.rs@@ -0,0 +1,187 @@+use crate::{+ action::Action,+ action_request::ActionRequest,+ actionability::{bounds_are_visible, states_are_enabled},+ adapter::{NativeHandle, PlatformAdapter, optional_live_read},+ error::{AdapterError, AppError, ErrorCode},+ refs::RefEntry,+};+use serde_json::{Value, json};++#[derive(Debug)]+pub(crate) enum ElementPredicate {+ Exists,+ Enabled,+ Visible,+ Actionable(ActionRequest),+ Value(String),+}++impl ElementPredicate {+ pub(crate) fn parse(+ predicate: Option<&str>,+ value: Option<String>,+ action: Option<&str>,+ ) -> Result<Self, AppError> {+ match predicate.unwrap_or("exists") {+ "exists" => {+ reject_unused_value(value)?;+ reject_unused_action(action)?;+ Ok(Self::Exists)+ }+ "enabled" => {+ reject_unused_value(value)?;+ reject_unused_action(action)?;+ Ok(Self::Enabled)+ }+ "visible" => {+ reject_unused_value(value)?;+ reject_unused_action(action)?;+ Ok(Self::Visible)+ }+ "actionable" => {+ reject_unused_value(value)?;+ Ok(Self::Actionable(parse_actionability_action(action)?))+ }+ "value" => {+ reject_unused_action(action)?;+ value.map(Self::Value).ok_or_else(|| {+ AppError::invalid_input_with_suggestion(+ "--predicate value requires --value",+ "Pass --value <expected> with --predicate value.",+ )+ })+ }+ other => Err(AppError::invalid_input_with_suggestion(+ format!("Unknown wait predicate '{other}'"),+ "Use one of: exists, enabled, visible, actionable, value.",+ )),+ }+ }++ pub(crate) fn name(&self) -> &'static str {+ match self {+ Self::Exists => "exists",+ Self::Enabled => "enabled",+ Self::Visible => "visible",+ Self::Actionable(_) => "actionable",+ Self::Value(_) => "value",+ }+ }+}++/// Maps each `--action` name to the exact request its real command would+/// run with — policy included — so the preflight answers "would this action+/// succeed". Every name is an explicit arm: a catch-all here would let a+/// new action silently inherit the wrong policy.+fn parse_actionability_action(action: Option<&str>) -> Result<ActionRequest, AppError> {+ match action.unwrap_or("click") {+ "click" => Ok(ActionRequest::headless(Action::Click)),+ "type" => Ok(ActionRequest::focus_fallback(Action::TypeText(+ String::new(),+ ))),+ "set-value" => Ok(ActionRequest::headless(Action::SetValue(String::new()))),+ "clear" => Ok(ActionRequest::headless(Action::Clear)),+ other => Err(AppError::invalid_input_with_suggestion(+ format!("Unknown actionability action '{other}'"),+ "Use one of: click, type, set-value, clear.",+ )),+ }+}++fn reject_unused_action(action: Option<&str>) -> Result<(), AppError> {+ if action.is_none() {+ return Ok(());+ }+ Err(AppError::invalid_input_with_suggestion(+ "--action is only valid with --predicate actionable",+ "Remove --action or use --predicate actionable.",+ ))+}++pub(crate) fn observe(+ entry: &RefEntry,+ handle: &NativeHandle,+ predicate: &ElementPredicate,+ adapter: &dyn PlatformAdapter,+) -> Result<Value, AdapterError> {+ match predicate {+ ElementPredicate::Exists => Ok(json!({ "exists": true })),+ ElementPredicate::Enabled => enabled(entry, handle, adapter),+ ElementPredicate::Visible => visible(entry, handle, adapter),+ ElementPredicate::Actionable(request) => actionable(entry, handle, request, adapter),+ ElementPredicate::Value(expected) => value(entry, handle, expected, adapter),+ }+}++pub(crate) fn satisfied(predicate: &ElementPredicate, observed: &Value) -> bool {+ match predicate {+ ElementPredicate::Exists => observed["exists"].as_bool() == Some(true),+ ElementPredicate::Enabled => observed["enabled"].as_bool() == Some(true),+ ElementPredicate::Visible => observed["visible"].as_bool() == Some(true),+ ElementPredicate::Actionable(_) => observed["actionable"].as_bool() == Some(true),+ ElementPredicate::Value(_) => observed["matched"].as_bool() == Some(true),+ }+}++fn reject_unused_value(value: Option<String>) -> Result<(), AppError> {+ if value.is_none() {+ return Ok(());+ }+ Err(AppError::invalid_input_with_suggestion(+ "--value is only valid with --predicate value",+ "Remove --value or use --predicate value.",+ ))+}++fn enabled(+ entry: &RefEntry,+ handle: &NativeHandle,+ adapter: &dyn PlatformAdapter,+) -> Result<Value, AdapterError> {+ let enabled = optional_live_read(adapter.get_live_state(handle))?+ .map(|state| states_are_enabled(&state.states))+ .unwrap_or_else(|| states_are_enabled(&entry.states));+ Ok(json!({ "enabled": enabled }))+}++fn visible(+ entry: &RefEntry,+ handle: &NativeHandle,+ adapter: &dyn PlatformAdapter,+) -> Result<Value, AdapterError> {+ let bounds = optional_live_read(adapter.get_element_bounds(handle))?.or(entry.bounds);+ Ok(json!({ "visible": bounds_are_visible(bounds) }))+}++fn actionable(+ entry: &RefEntry,+ handle: &NativeHandle,+ request: &ActionRequest,+ adapter: &dyn PlatformAdapter,+) -> Result<Value, AdapterError> {+ match crate::actionability::check_live(entry, handle, adapter, request) {+ Ok(report) => Ok(json!(report)),+ Err(err) if err.code == ErrorCode::ActionFailed => match err.details {+ Some(report) => Ok(report),+ None => Ok(json!({ "actionable": false, "error": err.message })),+ },+ Err(err) => Err(err),+ }+}++fn value(+ entry: &RefEntry,+ handle: &NativeHandle,+ expected: &str,+ adapter: &dyn PlatformAdapter,+) -> Result<Value, AdapterError> {+ let observed = optional_live_read(adapter.get_live_value(handle))?.or(entry.value.clone());+ let matched = observed.as_deref() == Some(expected);+ Ok(json!({+ "matched": matched,+ "value_present": observed.is_some(),+ "value_chars": observed.as_ref().map(|value| value.chars().count()),+ "expected_chars": expected.chars().count()+ }))+}diff --git a/crates/core/src/commands/wait_predicate_tests.rs b/crates/core/src/commands/wait_predicate_tests.rsnew file mode 100644index 000000000..f830626af--- /dev/null+++ b/crates/core/src/commands/wait_predicate_tests.rs@@ -0,0 +1,269 @@+use super::test_support::{+ PredicateAdapter, snapshot_with_disabled_ref, snapshot_with_one_ref, wait_for_element_test,+};+use super::*;+use crate::{+ adapter::{NativeHandle, PlatformAdapter},+ commands::wait_predicate,+ element_state::ElementState,+ error::AdapterError,+ refs::RefEntry,+ refs_test_support::HomeGuard,+};+use std::sync::Mutex;++struct FlippingPredicateAdapter {+ states: Mutex<Vec<Vec<String>>>,+}++impl PlatformAdapter for FlippingPredicateAdapter {+ fn resolve_element_strict_with_timeout(+ &self,+ _entry: &RefEntry,+ _timeout: std::time::Duration,+ ) -> Result<NativeHandle, AdapterError> {+ Ok(NativeHandle::null())+ }++ fn get_live_state(&self, _handle: &NativeHandle) -> Result<Option<ElementState>, AdapterError> {+ let states = self.states.lock().unwrap().pop().unwrap_or_default();+ Ok(Some(ElementState {+ role: "button".into(),+ states,+ value: None,+ }))+ }+}++#[test]+fn element_wait_enabled_predicate_uses_live_state() {+ let _guard = HomeGuard::new();+ let snapshot_id = snapshot_with_one_ref();+ let adapter = PredicateAdapter {+ state: Some(ElementState {+ role: "button".into(),+ states: vec![],+ value: None,+ }),+ value: None,+ bounds: None,+ };++ let value = wait_for_element_test(+ "@e1".into(),+ Some(snapshot_id),+ wait_predicate::ElementPredicate::Enabled,+ 50,+ &adapter,+ &crate::context::CommandContext::default(),+ )+ .unwrap();++ assert_eq!(value["predicate"], "enabled");+ assert_eq!(value["observed"]["enabled"], true);+}++#[test]+fn element_wait_value_predicate_matches_live_value_without_leaking_it() {+ let _guard = HomeGuard::new();+ let snapshot_id = snapshot_with_one_ref();+ let adapter = PredicateAdapter {+ state: None,+ value: Some("ready".into()),+ bounds: None,+ };++ let value = wait_for_element_test(+ "@e1".into(),+ Some(snapshot_id),+ wait_predicate::ElementPredicate::Value("ready".into()),+ 50,+ &adapter,+ &crate::context::CommandContext::default(),+ )+ .unwrap();++ assert_eq!(value["predicate"], "value");+ assert_eq!(value["observed"]["matched"], true);+ assert_eq!(value["observed"]["value_chars"], 5);+ assert!(value["observed"].get("value").is_none());+}++#[test]+fn element_wait_timeout_reports_last_actionability_observation() {+ let _guard = HomeGuard::new();+ let snapshot_id = snapshot_with_disabled_ref();+ let adapter = PredicateAdapter {+ state: Some(ElementState {+ role: "button".into(),+ states: vec!["disabled".into()],+ value: None,+ }),+ value: None,+ bounds: None,+ };++ let err = wait_for_element_test(+ "@e1".into(),+ Some(snapshot_id),+ wait_predicate::ElementPredicate::Actionable(+ crate::action_request::ActionRequest::headless(crate::action::Action::Click),+ ),+ 50,+ &adapter,+ &crate::context::CommandContext::default(),+ )+ .unwrap_err();++ assert_eq!(err.code(), "TIMEOUT");+ match err {+ AppError::Adapter(adapter_error) => {+ let details = adapter_error.details.unwrap();+ assert_eq!(details["predicate"], "actionable");+ assert_eq!(details["last_observed"]["actionable"], false);+ }+ _ => panic!("expected adapter error"),+ }+}++#[test]+fn element_wait_actionable_uses_live_state() {+ let _guard = HomeGuard::new();+ let snapshot_id = snapshot_with_disabled_ref();+ let adapter = PredicateAdapter {+ state: Some(ElementState {+ role: "button".into(),+ states: vec![],+ value: None,+ }),+ value: None,+ bounds: None,+ };++ let value = wait_for_element_test(+ "@e1".into(),+ Some(snapshot_id),+ wait_predicate::ElementPredicate::Actionable(+ crate::action_request::ActionRequest::headless(crate::action::Action::Click),+ ),+ 50,+ &adapter,+ &crate::context::CommandContext::default(),+ )+ .unwrap();++ assert_eq!(value["predicate"], "actionable");+ assert_eq!(value["observed"]["actionable"], true);+}++#[test]+fn element_wait_actionable_retries_until_live_state_converges() {+ let _guard = HomeGuard::new();+ let snapshot_id = snapshot_with_disabled_ref();+ let adapter = FlippingPredicateAdapter {+ states: Mutex::new(vec![vec![], vec!["disabled".into()]]),+ };++ let value = wait_for_element_test(+ "@e1".into(),+ Some(snapshot_id),+ wait_predicate::ElementPredicate::Actionable(+ crate::action_request::ActionRequest::headless(crate::action::Action::Click),+ ),+ 250,+ &adapter,+ &crate::context::CommandContext::default(),+ )+ .unwrap();++ assert_eq!(value["predicate"], "actionable");+ assert_eq!(value["observed"]["actionable"], true);+}++#[test]+fn element_wait_actionable_type_fails_on_uneditable_role() {+ let _guard = HomeGuard::new();+ let snapshot_id = snapshot_with_one_ref();+ let adapter = PredicateAdapter {+ state: Some(ElementState {+ role: "button".into(),+ states: vec![],+ value: None,+ }),+ value: None,+ bounds: None,+ };++ let err = wait_for_element_test(+ "@e1".into(),+ Some(snapshot_id),+ wait_predicate::ElementPredicate::Actionable(+ crate::action_request::ActionRequest::focus_fallback(crate::action::Action::TypeText(+ String::new(),+ )),+ ),+ 50,+ &adapter,+ &crate::context::CommandContext::default(),+ )+ .unwrap_err();++ assert_eq!(err.code(), "TIMEOUT");+ match err {+ AppError::Adapter(adapter_error) => {+ let details = adapter_error.details.unwrap();+ assert_eq!(details["last_observed"]["actionable"], false);+ }+ _ => panic!("expected adapter error"),+ }+}++#[test]+fn wait_action_flag_is_rejected_outside_actionable_predicate() {+ let err =+ wait_predicate::ElementPredicate::parse(Some("enabled"), None, Some("type")).unwrap_err();++ assert_eq!(err.code(), "INVALID_ARGS");+}++#[test]+fn wait_actionable_rejects_unknown_action() {+ let err = wait_predicate::ElementPredicate::parse(Some("actionable"), None, Some("hover"))+ .unwrap_err();++ assert_eq!(err.code(), "INVALID_ARGS");+}++#[test]+fn actionable_parse_mirrors_each_real_command_policy() {+ use crate::interaction_policy::InteractionPolicy;++ let request_for = |name: Option<&str>| match wait_predicate::ElementPredicate::parse(+ Some("actionable"),+ None,+ name,+ )+ .unwrap()+ {+ wait_predicate::ElementPredicate::Actionable(request) => request,+ other => panic!("expected actionable predicate, got {other:?}"),+ };++ assert_eq!(request_for(None).policy, InteractionPolicy::headless());+ assert_eq!(+ request_for(Some("click")).policy,+ InteractionPolicy::headless()+ );+ assert_eq!(+ request_for(Some("type")).policy,+ InteractionPolicy::focus_fallback()+ );+ assert_eq!(+ request_for(Some("set-value")).policy,+ InteractionPolicy::headless()+ );+ assert_eq!(+ request_for(Some("clear")).policy,+ InteractionPolicy::headless()+ );+}diff --git a/crates/core/src/commands/wait_resolution_tests.rs b/crates/core/src/commands/wait_resolution_tests.rsnew file mode 100644index 000000000..b187dc599--- /dev/null+++ b/crates/core/src/commands/wait_resolution_tests.rs@@ -0,0 +1,232 @@+use super::*;+use crate::{+ adapter::{NativeHandle, PlatformAdapter},+ capability,+ commands::wait_predicate,+ error::{AdapterError, ErrorCode},+ refs::{RefEntry, RefMap},+ refs_store::RefStore,+ refs_test_support::HomeGuard,+};+use std::sync::Mutex;+use std::time::Duration;++use super::test_support::wait_for_element_test;++struct AmbiguousResolveAdapter;++impl PlatformAdapter for AmbiguousResolveAdapter {+ fn resolve_element_strict_with_timeout(+ &self,+ _entry: &RefEntry,+ _timeout: Duration,+ ) -> Result<NativeHandle, AdapterError> {+ Err(AdapterError::ambiguous_target("2 candidates matched"))+ }+}++struct TransientResolveAdapter {+ errors: Mutex<Vec<ErrorCode>>,+}++impl PlatformAdapter for TransientResolveAdapter {+ fn resolve_element_strict_with_timeout(+ &self,+ _entry: &RefEntry,+ _timeout: Duration,+ ) -> Result<NativeHandle, AdapterError> {+ if let Some(code) = self.errors.lock().unwrap().pop() {+ return Err(AdapterError::new(code, "transient resolution failure"));+ }+ Ok(NativeHandle::null())+ }+}++struct PermissionResolveAdapter;++impl PlatformAdapter for PermissionResolveAdapter {+ fn resolve_element_strict_with_timeout(+ &self,+ _entry: &RefEntry,+ _timeout: Duration,+ ) -> Result<NativeHandle, AdapterError> {+ Err(AdapterError::permission_denied())+ }+}++struct StrictOnlyResolveAdapter;++impl PlatformAdapter for StrictOnlyResolveAdapter {+ fn resolve_element_strict(&self, _entry: &RefEntry) -> Result<NativeHandle, AdapterError> {+ Ok(NativeHandle::null())+ }+}++struct TimeoutCaptureAdapter {+ captured_ms: Mutex<Vec<u128>>,+}++impl PlatformAdapter for TimeoutCaptureAdapter {+ fn resolve_element_strict_with_timeout(+ &self,+ _entry: &RefEntry,+ timeout: Duration,+ ) -> Result<NativeHandle, AdapterError> {+ self.captured_ms.lock().unwrap().push(timeout.as_millis());+ Ok(NativeHandle::null())+ }+}++fn snapshot_with_one_ref() -> String {+ let mut refmap = RefMap::new();+ refmap.allocate(RefEntry {+ pid: 1,+ role: "button".into(),+ name: Some("Run".into()),+ value: None,+ description: None,+ states: vec![],+ bounds: None,+ bounds_hash: None,+ available_actions: vec![capability::CLICK.into()],+ source_app: None,+ source_window_id: None,+ source_window_title: None,+ source_surface: crate::adapter::SnapshotSurface::Window,+ root_ref: None,+ path_is_absolute: false,+ path: smallvec::SmallVec::new(),+ });+ RefStore::new().unwrap().save_new_snapshot(&refmap).unwrap()+}++#[test]+fn element_wait_retries_transient_ambiguous_resolution() {+ let _guard = HomeGuard::new();+ let snapshot_id = snapshot_with_one_ref();+ let adapter = TransientResolveAdapter {+ errors: Mutex::new(vec![ErrorCode::AmbiguousTarget]),+ };++ let value = wait_for_element_test(+ "@e1".into(),+ Some(snapshot_id),+ wait_predicate::ElementPredicate::Exists,+ 250,+ &adapter,+ &crate::context::CommandContext::default(),+ )+ .unwrap();++ assert_eq!(value["predicate"], "exists");+ assert_eq!(value["observed"]["exists"], true);+}++#[test]+fn element_wait_retries_transient_resolution_timeout() {+ let _guard = HomeGuard::new();+ let snapshot_id = snapshot_with_one_ref();+ let adapter = TransientResolveAdapter {+ errors: Mutex::new(vec![ErrorCode::Timeout]),+ };++ let value = wait_for_element_test(+ "@e1".into(),+ Some(snapshot_id),+ wait_predicate::ElementPredicate::Exists,+ 250,+ &adapter,+ &crate::context::CommandContext::default(),+ )+ .unwrap();++ assert_eq!(value["observed"]["exists"], true);+}++#[test]+fn element_wait_passes_remaining_budget_to_resolver() {+ let _guard = HomeGuard::new();+ let snapshot_id = snapshot_with_one_ref();+ let adapter = TimeoutCaptureAdapter {+ captured_ms: Mutex::new(vec![]),+ };++ let value = wait_for_element_test(+ "@e1".into(),+ Some(snapshot_id),+ wait_predicate::ElementPredicate::Exists,+ 500,+ &adapter,+ &crate::context::CommandContext::default(),+ )+ .unwrap();++ assert_eq!(value["observed"]["exists"], true);+ let captured = adapter.captured_ms.lock().unwrap();+ assert_eq!(captured.len(), 1);+ assert!(captured[0] <= 500);+}++#[test]+fn element_wait_delegates_to_strict_only_resolution() {+ let _guard = HomeGuard::new();+ let snapshot_id = snapshot_with_one_ref();++ let value = wait_for_element_test(+ "@e1".into(),+ Some(snapshot_id),+ wait_predicate::ElementPredicate::Exists,+ 250,+ &StrictOnlyResolveAdapter,+ &crate::context::CommandContext::default(),+ )+ .unwrap();++ assert_eq!(value["found"], true);+ assert_eq!(value["observed"]["exists"], true);+}++#[test]+fn element_wait_times_out_after_persistent_ambiguous_resolution() {+ let _guard = HomeGuard::new();+ let snapshot_id = snapshot_with_one_ref();++ let err = wait_for_element_test(+ "@e1".into(),+ Some(snapshot_id),+ wait_predicate::ElementPredicate::Exists,+ 50,+ &AmbiguousResolveAdapter,+ &crate::context::CommandContext::default(),+ )+ .unwrap_err();++ assert_eq!(err.code(), "TIMEOUT");+ match err {+ AppError::Adapter(adapter_error) => {+ assert_eq!(+ adapter_error.details.unwrap()["last_observed"]["error"],+ "AMBIGUOUS_TARGET"+ );+ }+ _ => panic!("expected adapter error"),+ }+}++#[test]+fn element_wait_aborts_terminal_permission_error() {+ let _guard = HomeGuard::new();+ let snapshot_id = snapshot_with_one_ref();++ let err = wait_for_element_test(+ "@e1".into(),+ Some(snapshot_id),+ wait_predicate::ElementPredicate::Exists,+ 250,+ &PermissionResolveAdapter,+ &crate::context::CommandContext::default(),+ )+ .unwrap_err();++ assert_eq!(err.code(), "PERM_DENIED");+}diff --git a/crates/core/src/commands/wait_test_support.rs b/crates/core/src/commands/wait_test_support.rsnew file mode 100644index 000000000..43b776769--- /dev/null+++ b/crates/core/src/commands/wait_test_support.rs@@ -0,0 +1,99 @@+use crate::commands::wait_element::{ElementWaitInput, wait_for_element};+use crate::commands::wait_predicate;+use crate::{+ adapter::{NativeHandle, PlatformAdapter},+ context::CommandContext,+ element_state::ElementState,+ error::{AdapterError, AppError},+ node::Rect,+ refs::{RefEntry, RefMap},+ refs_store::RefStore,+};+use serde_json::Value;++pub(super) fn wait_for_element_test(+ ref_id: String,+ snapshot_id: Option<String>,+ predicate: wait_predicate::ElementPredicate,+ timeout_ms: u64,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ wait_for_element(+ ElementWaitInput {+ ref_id,+ snapshot_id,+ predicate,+ timeout_ms,+ },+ adapter,+ context,+ )+}++pub(super) struct PredicateAdapter {+ pub(super) state: Option<ElementState>,+ pub(super) value: Option<String>,+ pub(super) bounds: Option<Rect>,+}++impl PlatformAdapter for PredicateAdapter {+ fn resolve_element_strict_with_timeout(+ &self,+ _entry: &RefEntry,+ _timeout: std::time::Duration,+ ) -> Result<NativeHandle, AdapterError> {+ Ok(NativeHandle::null())+ }++ fn get_live_state(&self, _handle: &NativeHandle) -> Result<Option<ElementState>, AdapterError> {+ Ok(self.state.clone())+ }++ fn get_live_value(&self, _handle: &NativeHandle) -> Result<Option<String>, AdapterError> {+ Ok(self.value.clone())+ }++ fn get_element_bounds(&self, _handle: &NativeHandle) -> Result<Option<Rect>, AdapterError> {+ Ok(self.bounds)+ }+}++pub(super) fn snapshot_with_one_ref() -> String {+ save_ref(Vec::new())+}++pub(super) fn snapshot_with_disabled_ref() -> String {+ save_ref(vec!["disabled".into()])+}++pub(super) fn save_ref(states: Vec<String>) -> String {+ save_ref_in_store(RefStore::new().unwrap(), states)+}++pub(super) fn save_ref_in_session(session_id: &str, states: Vec<String>) -> String {+ save_ref_in_store(RefStore::for_session(Some(session_id)).unwrap(), states)+}++fn save_ref_in_store(store: RefStore, states: Vec<String>) -> String {+ let mut refmap = RefMap::new();+ refmap.allocate(RefEntry {+ pid: 1,+ role: "button".into(),+ name: Some("Run".into()),+ value: None,+ description: None,+ states,+ bounds: None,+ bounds_hash: None,+ available_actions: vec!["Click".into()],+ source_app: None,+ source_window_id: None,+ source_window_title: None,+ source_surface: crate::adapter::SnapshotSurface::Window,+ root_ref: None,+ path_is_absolute: false,+ path: smallvec::SmallVec::new(),+ });+ store.save_new_snapshot(&refmap).unwrap()+}diff --git a/crates/core/src/commands/wait_tests.rs b/crates/core/src/commands/wait_tests.rsindex 4b9b19c8d..f4d57d872 100644--- a/crates/core/src/commands/wait_tests.rs+++ b/crates/core/src/commands/wait_tests.rs@@ -1,11 +1,9 @@use super::*;use crate::{- adapter::PlatformAdapter,+ adapter::{PlatformAdapter, WindowFilter},error::{AdapterError, ErrorCode},+ node::WindowInfo,notification::{NotificationFilter, NotificationInfo},- refs::{RefEntry, RefMap},- refs_store::RefStore,- refs_test_support::HomeGuard,};struct NoopAdapter;@@ -26,78 +24,172 @@ impl PlatformAdapter for NotificationErrorAdapter {}}-fn snapshot_with_one_ref() -> String {- let mut refmap = RefMap::new();- refmap.allocate(RefEntry {- pid: 1,- role: "button".into(),- name: Some("Run".into()),- value: None,- description: None,- states: Vec::new(),- bounds: None,- bounds_hash: None,- available_actions: vec!["Click".into()],- source_app: None,- source_window_id: None,- source_window_title: None,- source_surface: crate::adapter::SnapshotSurface::Window,- root_ref: None,- path_is_absolute: false,- path: smallvec::SmallVec::new(),- });- RefStore::new().unwrap().save_new_snapshot(&refmap).unwrap()+struct FlakyNotificationAdapter {+ responses: std::sync::Mutex<Vec<Result<Vec<NotificationInfo>, AdapterError>>>,}-#[test]-fn snapshot_pinned_missing_ref_is_invalid_args() {- let _guard = HomeGuard::new();- let snapshot_id = snapshot_with_one_ref();+impl FlakyNotificationAdapter {+ fn with_responses(in_order: Vec<Result<Vec<NotificationInfo>, AdapterError>>) -> Self {+ let mut responses = in_order;+ responses.reverse();+ Self {+ responses: std::sync::Mutex::new(responses),+ }+ }+}- let err = wait_for_element("@e2".into(), Some(snapshot_id), 1, &NoopAdapter).unwrap_err();+impl PlatformAdapter for FlakyNotificationAdapter {+ fn list_notifications(+ &self,+ _filter: &NotificationFilter,+ ) -> Result<Vec<NotificationInfo>, AdapterError> {+ self.responses+ .lock()+ .unwrap()+ .pop()+ .unwrap_or_else(|| Err(AdapterError::timeout("notification center unavailable")))+ }+}- assert_eq!(err.code(), "INVALID_ARGS");- assert!(err.suggestion().is_some());+fn notification(index: usize, title: &str) -> NotificationInfo {+ NotificationInfo {+ index,+ app_name: "Mail".into(),+ title: title.into(),+ body: None,+ actions: vec![],+ }}-#[test]-fn notification_wait_propagates_adapter_error() {- let err = execute(- WaitArgs {+fn notification_wait_args(timeout_ms: u64) -> WaitArgs {+ WaitArgs {+ mode: WaitModeArgs {+ notification: true,+ ..wait_args().mode+ },+ timeout_ms,+ ..wait_args()+ }+}++struct WindowErrorAdapter;++impl PlatformAdapter for WindowErrorAdapter {+ fn list_windows(&self, _filter: &WindowFilter) -> Result<Vec<WindowInfo>, AdapterError> {+ Err(AdapterError::permission_denied())+ }+}++fn wait_args() -> WaitArgs {+ WaitArgs {+ mode: WaitModeArgs {ms: None,element: None,- snapshot_id: None,window: None,text: None,- timeout_ms: 1,menu: false,menu_closed: false,- notification: true,- app: None,+ notification: false,+ },+ predicate: WaitPredicateArgs {+ snapshot_id: None,+ predicate: None,+ value: None,+ action: None,+ count: None,+ },+ timeout_ms: 1,+ app: None,+ }+}++#[test]+fn notification_wait_propagates_adapter_error() {+ let err = execute(+ WaitArgs {+ mode: WaitModeArgs {+ notification: true,+ ..wait_args().mode+ },+ ..wait_args()},&NotificationErrorAdapter,+ &CommandContext::default(),).unwrap_err();assert_eq!(err.code(), "PLATFORM_NOT_SUPPORTED");}+#[test]+fn notification_wait_retries_transient_baseline_errors() {+ let adapter = FlakyNotificationAdapter::with_responses(vec![+ Err(AdapterError::timeout("notification center starting")),+ Ok(vec![notification(0, "old")]),+ Ok(vec![notification(0, "old"), notification(1, "fresh")]),+ ]);++ let value = execute(+ notification_wait_args(5_000),+ &adapter,+ &CommandContext::default(),+ )+ .unwrap();++ assert_eq!(value["matched"], true);+ assert_eq!(value["notification"]["title"], "fresh");+}++#[test]+fn notification_wait_fingerprint_ignores_reindexed_existing_notification() {+ let baseline = notification_counts(&[notification(0, "old")]);+ let current = vec![notification(4, "old")];++ assert!(first_new_notification(¤t, &baseline).is_none());+}++#[test]+fn notification_wait_fingerprint_detects_duplicate_new_notification() {+ let baseline = notification_counts(&[notification(0, "same")]);+ let current = vec![notification(4, "same"), notification(5, "same")];++ let found = first_new_notification(¤t, &baseline).unwrap();++ assert_eq!(found.index, 5);+}++#[test]+fn notification_wait_times_out_with_last_error_after_transient_failures() {+ let adapter = FlakyNotificationAdapter::with_responses(vec![]);++ let err = execute(+ notification_wait_args(600),+ &adapter,+ &CommandContext::default(),+ )+ .unwrap_err();++ let AppError::Adapter(adapter_err) = err else {+ panic!("expected adapter error");+ };+ assert_eq!(adapter_err.code, ErrorCode::Timeout);+ let details = adapter_err.details.expect("timeout should carry details");+ assert_eq!(details["last_error"]["code"], "TIMEOUT");+}+#[test]fn rejects_multiple_wait_modes() {let err = execute(WaitArgs {- ms: Some(1),- element: Some("@e1".into()),- snapshot_id: None,- window: None,- text: None,- timeout_ms: 1,- menu: false,- menu_closed: false,- notification: false,- app: None,+ mode: WaitModeArgs {+ ms: Some(1),+ element: Some("@e1".into()),+ ..wait_args().mode+ },+ ..wait_args()},&NoopAdapter,+ &CommandContext::default(),).unwrap_err();@@ -105,99 +197,186 @@ fn rejects_multiple_wait_modes() {assert!(err.suggestion().is_some());}+#[test]+fn window_wait_propagates_permanent_adapter_error() {+ let err = execute(+ WaitArgs {+ mode: WaitModeArgs {+ window: Some("Document".into()),+ ..wait_args().mode+ },+ ..wait_args()+ },+ &WindowErrorAdapter,+ &CommandContext::default(),+ )+ .unwrap_err();++ assert_eq!(err.code(), "PERM_DENIED");+}++#[test]+fn text_wait_propagates_permanent_snapshot_error() {+ let err = execute(+ WaitArgs {+ mode: WaitModeArgs {+ text: Some("hello".into()),+ ..wait_args().mode+ },+ ..wait_args()+ },+ &WindowErrorAdapter,+ &CommandContext::default(),+ )+ .unwrap_err();++ assert_eq!(err.code(), "PERM_DENIED");+}++#[test]+fn app_retryability_uses_adapter_error_codes() {+ assert!(is_retryable_wait_app_error(&AppError::Adapter(+ AdapterError::timeout("busy")+ )));+ assert!(!is_retryable_wait_app_error(&AppError::Adapter(+ AdapterError::permission_denied()+ )));+ assert!(!is_retryable_wait_app_error(&AppError::Internal(+ "internal".into()+ )));+}+#[test]fn notification_wait_allows_text_filter() {let result = validate_wait_mode(&WaitArgs {- ms: None,- element: None,- snapshot_id: None,- window: None,- text: Some("done".into()),- timeout_ms: 1,- menu: false,- menu_closed: false,- notification: true,- app: None,+ mode: WaitModeArgs {+ text: Some("done".into()),+ notification: true,+ ..wait_args().mode+ },+ ..wait_args()});assert!(result.is_ok());}#[test]-fn latest_ref_cache_picks_up_newer_snapshot_after_refresh() {- let _guard = HomeGuard::new();- let _ = snapshot_with_one_ref();- let store = RefStore::new().unwrap();- let first_id = store.latest_snapshot_id().unwrap();-- let mut cache = LatestRefCache::new(&store).unwrap();- assert_eq!(cache.snapshot_id.as_deref(), Some(first_id.as_str()));-- let mut second = RefMap::new();- second.allocate(RefEntry {- pid: 99,- role: "button".into(),- name: Some("Second".into()),- value: None,- description: None,- states: vec![],- bounds: None,- bounds_hash: None,- available_actions: vec!["Click".into()],- source_app: None,- source_window_id: None,- source_window_title: None,- source_surface: crate::adapter::SnapshotSurface::Window,- root_ref: None,- path_is_absolute: false,- path: smallvec::SmallVec::new(),- });- let second_id = store.save_new_snapshot(&second).unwrap();- assert_ne!(first_id, second_id);+fn predicate_requires_element_mode() {+ let err = validate_wait_mode(&WaitArgs {+ predicate: WaitPredicateArgs {+ predicate: Some("enabled".into()),+ ..wait_args().predicate+ },+ ..wait_args()+ })+ .unwrap_err();++ assert_eq!(err.code(), "INVALID_ARGS");+}- cache.last_refresh = std::time::Instant::now() - std::time::Duration::from_secs(2);- cache.refresh_if_due();+struct TextlessTreeAdapter;- assert_eq!(cache.snapshot_id.as_deref(), Some(second_id.as_str()));- assert!(cache.entry("@e1").is_some());+impl PlatformAdapter for TextlessTreeAdapter {+ fn list_windows(&self, _filter: &WindowFilter) -> Result<Vec<WindowInfo>, AdapterError> {+ Ok(vec![WindowInfo {+ id: "w-1".into(),+ title: "Doc".into(),+ app: "TestApp".into(),+ pid: 1,+ bounds: None,+ is_focused: true,+ }])+ }++ fn get_tree(+ &self,+ _win: &WindowInfo,+ _opts: &crate::adapter::TreeOptions,+ ) -> Result<crate::node::AccessibilityNode, AdapterError> {+ Ok(crate::node::AccessibilityNode {+ ref_id: None,+ role: "window".into(),+ name: Some("Doc".into()),+ value: None,+ description: None,+ hint: None,+ states: vec![],+ available_actions: vec![],+ bounds: None,+ children_count: None,+ children: vec![],+ })+ }}#[test]-fn latest_ref_cache_debounces_consecutive_refreshes() {- let _guard = HomeGuard::new();- let _ = snapshot_with_one_ref();- let store = RefStore::new().unwrap();- let first_id = store.latest_snapshot_id().unwrap();-- let mut cache = LatestRefCache::new(&store).unwrap();- let pinned_snapshot_id = cache.snapshot_id.clone();- let pinned_refresh = cache.last_refresh;-- let mut other = RefMap::new();- other.allocate(RefEntry {- pid: 1,- role: "button".into(),- name: None,- value: None,- description: None,- states: vec![],- bounds: None,- bounds_hash: None,- available_actions: vec!["Click".into()],- source_app: None,- source_window_id: None,- source_window_title: None,- source_surface: crate::adapter::SnapshotSurface::Window,- root_ref: None,- path_is_absolute: false,- path: smallvec::SmallVec::new(),- });- let _ = store.save_new_snapshot(&other).unwrap();+fn text_wait_with_count_zero_detects_absence() {+ let _guard = crate::refs_test_support::HomeGuard::new();++ let value = execute(+ WaitArgs {+ mode: WaitModeArgs {+ text: Some("Gone".into()),+ ..wait_args().mode+ },+ predicate: WaitPredicateArgs {+ count: Some(0),+ ..wait_args().predicate+ },+ timeout_ms: 1_000,+ app: Some("TestApp".into()),+ },+ &TextlessTreeAdapter,+ &CommandContext::default(),+ )+ .unwrap();++ assert_eq!(value["found"], true);+ assert_eq!(value["count"], 0);+}++struct MenuWaitAdapter {+ open_seen: std::sync::Mutex<Option<bool>>,+}++impl PlatformAdapter for MenuWaitAdapter {+ fn list_apps(&self) -> Result<Vec<crate::node::AppInfo>, AdapterError> {+ Ok(vec![crate::node::AppInfo {+ name: "MenuApp".into(),+ pid: 42,+ bundle_id: None,+ }])+ }- cache.last_refresh = std::time::Instant::now();- cache.refresh_if_due();+ fn wait_for_menu(&self, _pid: i32, open: bool, _timeout_ms: u64) -> Result<(), AdapterError> {+ *self.open_seen.lock().unwrap() = Some(open);+ Ok(())+ }+}++#[test]+fn menu_closed_wait_requests_closed_state_and_reports_found() {+ let adapter = MenuWaitAdapter {+ open_seen: std::sync::Mutex::new(None),+ };+ let value = execute(+ WaitArgs {+ mode: WaitModeArgs {+ menu_closed: true,+ ..wait_args().mode+ },+ app: Some("MenuApp".into()),+ ..wait_args()+ },+ &adapter,+ &CommandContext::default(),+ )+ .unwrap();- assert_eq!(cache.snapshot_id, pinned_snapshot_id);- assert_eq!(cache.last_refresh, pinned_refresh.max(cache.last_refresh));- let _ = first_id;+ assert_eq!(value["found"], true);+ assert_eq!(+ *adapter.open_seen.lock().unwrap(),+ Some(false),+ "--menu-closed must wait for the menu to be closed (open=false)"+ );}diff --git a/crates/core/src/commands/wait_text_match.rs b/crates/core/src/commands/wait_text_match.rsnew file mode 100644index 000000000..6659bbf87--- /dev/null+++ b/crates/core/src/commands/wait_text_match.rs@@ -0,0 +1,94 @@+use crate::{node::AccessibilityNode, search_text};++pub(crate) struct TextMatch {+ pub ref_id: Option<String>,+ pub role: String,+}++pub(crate) fn find(+ node: &AccessibilityNode,+ text_lower: &str,+ expected_count: Option<usize>,+) -> Vec<TextMatch> {+ let mut matches = Vec::new();+ collect(node, text_lower, match_limit(expected_count), &mut matches);+ matches+}++fn match_limit(expected_count: Option<usize>) -> usize {+ expected_count+ .map(|expected| expected.saturating_add(1))+ .unwrap_or(1)+}++fn collect(node: &AccessibilityNode, text_lower: &str, limit: usize, matches: &mut Vec<TextMatch>) {+ if matches.len() >= limit {+ return;+ }+ if search_text::node_contains(node, text_lower) {+ matches.push(TextMatch {+ ref_id: node.ref_id.clone(),+ role: node.role.clone(),+ });+ }++ for child in &node.children {+ collect(child, text_lower, limit, matches);+ if matches.len() >= limit {+ return;+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn node(name: &str, children: Vec<AccessibilityNode>) -> AccessibilityNode {+ AccessibilityNode {+ ref_id: None,+ role: "group".into(),+ name: Some(name.into()),+ value: None,+ description: None,+ hint: None,+ states: vec![],+ available_actions: vec![],+ bounds: None,+ children_count: None,+ children,+ }+ }++ #[test]+ fn default_wait_text_stops_after_first_match() {+ let tree = node(+ "root",+ vec![+ node("ready one", vec![]),+ node("ready two", vec![]),+ node("ready three", vec![]),+ ],+ );++ let matches = find(&tree, "ready", None);++ assert_eq!(matches.len(), 1);+ }++ #[test]+ fn count_wait_text_collects_one_past_expected() {+ let tree = node(+ "root",+ vec![+ node("ready one", vec![]),+ node("ready two", vec![]),+ node("ready three", vec![]),+ ],+ );++ let matches = find(&tree, "ready", Some(2));++ assert_eq!(matches.len(), 3);+ }+}diff --git a/crates/core/src/commands/wait_timeout.rs b/crates/core/src/commands/wait_timeout.rsnew file mode 100644index 000000000..3b48255ff--- /dev/null+++ b/crates/core/src/commands/wait_timeout.rs@@ -0,0 +1,88 @@+use crate::{+ commands::wait_predicate,+ error::{AdapterError, AppError},+};+use serde_json::{Value, json};++/// Builds the wait-loop TIMEOUT error. Every payload carries+/// `kind: "wait_timeout"` so agents can discriminate it from the chain+/// deadline TIMEOUT schema (`kind: "chain_deadline"`) without sniffing+/// field names.+fn timeout_err(message: String, mut details: Value) -> Result<Value, AppError> {+ details["kind"] = json!("wait_timeout");+ Err(AppError::Adapter(+ AdapterError::timeout(message).with_details(details),+ ))+}++pub(crate) fn element(+ ref_id: String,+ predicate: wait_predicate::ElementPredicate,+ timeout_ms: u64,+ last_observed: Value,+) -> Result<Value, AppError> {+ timeout_err(+ format!(+ "Element {ref_id} did not satisfy predicate '{}' within {timeout_ms}ms; last_observed={last_observed}",+ predicate.name()+ ),+ json!({+ "ref": ref_id,+ "predicate": predicate.name(),+ "timeout_ms": timeout_ms,+ "last_observed": last_observed+ }),+ )+}++pub(crate) fn window(+ title: &str,+ timeout_ms: u64,+ last_error: Option<Value>,+) -> Result<Value, AppError> {+ timeout_err(+ format!("Window with title '{title}' not found within {timeout_ms}ms"),+ json!({+ "predicate": "window",+ "title": title,+ "timeout_ms": timeout_ms,+ "last_error": last_error+ }),+ )+}++pub(crate) fn text(+ text: &str,+ timeout_ms: u64,+ expected_count: Option<usize>,+ last_error: Option<Value>,+) -> Result<Value, AppError> {+ timeout_err(+ format!("Text '{text}' did not match within {timeout_ms}ms"),+ json!({+ "predicate": "text",+ "text_chars": text.chars().count(),+ "timeout_ms": timeout_ms,+ "expected_count": expected_count,+ "last_error": last_error+ }),+ )+}++pub(crate) fn notification(+ app: Option<&String>,+ text: Option<&String>,+ timeout_ms: u64,+ last_error: Option<Value>,+) -> Result<Value, AppError> {+ timeout_err(+ format!("No new notification within {timeout_ms}ms"),+ json!({+ "predicate": "notification",+ "timeout_ms": timeout_ms,+ "app": app,+ "text_chars": text.map(|text| text.chars().count()),+ "last_error": last_error+ }),+ )+}diff --git a/crates/core/src/context.rs b/crates/core/src/context.rsnew file mode 100644index 000000000..646d18701--- /dev/null+++ b/crates/core/src/context.rs@@ -0,0 +1,293 @@+use crate::{+ action::Action, action_request::ActionRequest, error::AppError,+ interaction_policy::InteractionPolicy, trace::TraceConfig,+};+use serde_json::Value;+use std::path::PathBuf;++#[derive(Debug, Clone, Default)]+pub struct CommandContext {+ session_id: Option<String>,+ trace: TraceConfig,+ headed: bool,+}++impl CommandContext {+ pub fn new(+ session_id: Option<String>,+ trace_path: Option<PathBuf>,+ trace_strict: bool,+ ) -> Result<Self, AppError> {+ if let Some(id) = session_id.as_deref() {+ validate_session_id(id)?;+ }+ Ok(Self {+ session_id,+ trace: TraceConfig::new(trace_path, trace_strict)?,+ headed: false,+ })+ }++ /// Selects headed interaction: ref actions may move the cursor and steal+ /// focus, unlocking the physical click/scroll/keypress fallbacks in the+ /// action chain. Off by default — the tool is headless-first (Playwright+ /// style: headless is the default, headed is opt-in via `--headed`).+ pub fn with_headed(mut self, headed: bool) -> Self {+ self.headed = headed;+ self+ }++ /// Builds the action request for a ref command. Headless (default) uses the+ /// command's own `base` policy — its minimum viable policy with no cursor+ /// movement (most commands are pure-AX `headless`; `type` is `focus_fallback`+ /// because typing requires focus). `--headed` upgrades any base to `headed`,+ /// unlocking the cursor/OS-input fallbacks instead of failing closed.+ pub fn request(&self, action: Action, base: InteractionPolicy) -> ActionRequest {+ ActionRequest {+ action,+ policy: self.policy_with_base(base),+ }+ }++ /// Policy for raw physical-input commands (hover, drag, mouse-*). They+ /// have no semantic action chain, so headless denies both focus stealing+ /// and cursor movement unless `--headed` opts in.+ pub fn physical_input_policy(&self) -> InteractionPolicy {+ self.policy_with_base(InteractionPolicy::headless())+ }++ fn policy_with_base(&self, base: InteractionPolicy) -> InteractionPolicy {+ if self.headed {+ InteractionPolicy::headed()+ } else {+ base+ }+ }++ pub fn for_batch_item(&self, session_id: Option<String>) -> Result<Self, AppError> {+ let session_id = session_id.or_else(|| self.session_id.clone());+ if let Some(id) = session_id.as_deref() {+ validate_session_id(id)?;+ }+ Ok(Self {+ session_id,+ trace: self.trace.clone(),+ headed: self.headed,+ })+ }++ pub fn trace(&self, event: &str, fields: Value) -> Result<(), AppError> {+ self.trace.emit(event, fields)+ }++ pub fn trace_lazy(&self, event: &str, fields: impl FnOnce() -> Value) -> Result<(), AppError> {+ self.trace.emit_lazy(event, fields)+ }++ pub fn session_id(&self) -> Option<&str> {+ self.session_id.as_deref()+ }+}++pub fn validate_session_id(id: &str) -> Result<(), AppError> {+ let valid = !id.is_empty()+ && id.len() <= 64+ && id+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_'));+ if valid {+ return Ok(());+ }+ Err(AppError::invalid_input_with_suggestion(+ "Session id must be 1-64 chars using letters, numbers, '-' or '_'",+ "Use a short filesystem-safe session id such as run_1 or agent-a.",+ ))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn accepts_filesystem_safe_session_ids() {+ assert!(validate_session_id("agent-1_A").is_ok());+ }++ #[test]+ fn rejects_path_like_session_ids() {+ assert!(validate_session_id("../agent").is_err());+ assert!(validate_session_id("agent/a").is_err());+ }++ #[test]+ fn trace_writes_jsonl_without_stdout_dependency() {+ let path = std::env::temp_dir().join(format!(+ "agent-desktop-trace-{}.jsonl",+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ let context = CommandContext::new(None, Some(path.clone()), false).unwrap();++ context+ .trace("ref.resolve.ok", serde_json::json!({ "ref": "@e1" }))+ .unwrap();++ let body = std::fs::read_to_string(&path).unwrap();+ let event: serde_json::Value = serde_json::from_str(body.trim()).unwrap();+ assert_eq!(event["event"], "ref.resolve.ok");+ assert_eq!(event["ref"], "@e1");+ assert!(event["ts_ms"].as_u64().is_some());+ let _ = std::fs::remove_file(path);+ }++ #[test]+ fn trace_write_failure_is_best_effort_unless_strict() {+ let missing = std::env::temp_dir()+ .join("agent-desktop-missing-dir")+ .join("trace.jsonl");++ let best_effort = CommandContext::new(None, Some(missing.clone()), false).unwrap();+ assert!(best_effort.trace("event", serde_json::json!({})).is_ok());++ assert!(CommandContext::new(None, Some(missing), true).is_err());+ }++ #[test]+ fn trace_lazy_does_not_build_fields_when_trace_is_disabled() {+ let context = CommandContext::default();+ let built = std::cell::Cell::new(false);++ context+ .trace_lazy("event", || {+ built.set(true);+ serde_json::json!({})+ })+ .unwrap();++ assert!(!built.get());+ }++ #[cfg(unix)]+ #[test]+ fn trace_file_is_private_on_create() {+ use std::os::unix::fs::PermissionsExt;++ let path = std::env::temp_dir().join(format!(+ "agent-desktop-private-trace-{}.jsonl",+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ let context = CommandContext::new(None, Some(path.clone()), true).unwrap();+ context.trace("event", serde_json::json!({})).unwrap();++ let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;+ assert_eq!(mode, 0o600);+ let _ = std::fs::remove_file(path);+ }++ #[cfg(unix)]+ #[test]+ fn trace_rejects_loose_existing_file_permissions() {+ use std::os::unix::fs::PermissionsExt;++ let path = std::env::temp_dir().join(format!(+ "agent-desktop-loose-trace-{}.jsonl",+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ std::fs::write(&path, "").unwrap();+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();++ let err = CommandContext::new(None, Some(path.clone()), false).unwrap_err();++ assert_eq!(err.code(), "INVALID_ARGS");+ let _ = std::fs::remove_file(path);+ }++ #[test]+ fn trace_redacts_sensitive_text_and_value_fields() {+ let path = std::env::temp_dir().join(format!(+ "agent-desktop-redacted-trace-{}.jsonl",+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ let context = CommandContext::new(None, Some(path.clone()), true).unwrap();+ context+ .trace(+ "event",+ serde_json::json!({+ "text": "secret",+ "value": "hidden",+ "name": "private label",+ "description": "private desc",+ "message": "diagnostic error",+ "post_state": { "value": "deep secret" },+ "target_label": "button secret",+ "nested": { "expected": "token" },+ "title": "private window title",+ "url": "https://internal.example/doc",+ "help": "private tooltip",+ "placeholder": "private placeholder"+ }),+ )+ .unwrap();++ let body = std::fs::read_to_string(&path).unwrap();+ let event: serde_json::Value = serde_json::from_str(body.trim()).unwrap();+ assert_eq!(event["text"]["redacted"], true);+ assert_eq!(event["value"]["redacted"], true);+ assert_eq!(event["name"]["redacted"], true);+ assert_eq!(event["description"]["redacted"], true);+ assert_eq!(event["message"], "diagnostic error");+ assert_eq!(event["post_state"]["value"]["redacted"], true);+ assert_eq!(event["target_label"]["redacted"], true);+ assert_eq!(event["nested"]["expected"]["redacted"], true);+ assert_eq!(event["title"]["redacted"], true);+ assert_eq!(event["url"]["redacted"], true);+ assert_eq!(event["help"]["redacted"], true);+ assert_eq!(event["placeholder"]["redacted"], true);+ assert!(!body.contains("secret"));+ assert!(!body.contains("hidden"));+ assert!(!body.contains("private label"));+ assert!(!body.contains("private desc"));+ assert!(!body.contains("token"));+ assert!(!body.contains("private window title"));+ assert!(!body.contains("internal.example"));+ assert!(!body.contains("private tooltip"));+ assert!(!body.contains("private placeholder"));+ let _ = std::fs::remove_file(path);+ }++ #[test]+ fn trace_strict_requires_trace_path() {+ let err = CommandContext::new(None, None, true).unwrap_err();+ assert_eq!(err.code(), "INVALID_ARGS");+ }++ #[test]+ fn batch_item_inherits_or_overrides_session_without_trace_loss() {+ let path = std::env::temp_dir().join("agent-desktop-context-test.jsonl");+ let _ = std::fs::remove_file(&path);+ let parent = CommandContext::new(Some("parent".into()), Some(path.clone()), false).unwrap();++ let inherited = parent.for_batch_item(None).unwrap();+ let overridden = parent.for_batch_item(Some("child".into())).unwrap();++ assert_eq!(inherited.session_id(), Some("parent"));+ assert_eq!(overridden.session_id(), Some("child"));+ overridden+ .trace("batch.child", serde_json::json!({ "ok": true }))+ .unwrap();+ let body = std::fs::read_to_string(&path).unwrap();+ assert!(body.contains("batch.child"));+ let _ = std::fs::remove_file(path);+ }+}diff --git a/crates/core/src/element_state.rs b/crates/core/src/element_state.rsnew file mode 100644index 000000000..64f57b5d7--- /dev/null+++ b/crates/core/src/element_state.rs@@ -0,0 +1,10 @@+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ElementState {+ pub role: String,+ #[serde(skip_serializing_if = "Vec::is_empty", default)]+ pub states: Vec<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub value: Option<String>,+}diff --git a/crates/core/src/error.rs b/crates/core/src/error.rsindex 056be0c40..e730ae706 100644--- a/crates/core/src/error.rs+++ b/crates/core/src/error.rs@@ -1,6 +1,9 @@use serde::Serialize;+use serde_json::Value;use thiserror::Error;+use crate::interaction_policy::InteractionPolicy;+#[derive(Debug, Clone, Serialize, PartialEq, Eq)]#[serde(rename_all = "SCREAMING_SNAKE_CASE")]pub enum ErrorCode {@@ -10,6 +13,7 @@ pub enum ErrorCode {ActionFailed,ActionNotSupported,StaleRef,+ AmbiguousTarget,WindowNotFound,PlatformNotSupported,Timeout,@@ -29,6 +33,7 @@ impl ErrorCode {ErrorCode::ActionFailed => "ACTION_FAILED",ErrorCode::ActionNotSupported => "ACTION_NOT_SUPPORTED",ErrorCode::StaleRef => "STALE_REF",+ ErrorCode::AmbiguousTarget => "AMBIGUOUS_TARGET",ErrorCode::WindowNotFound => "WINDOW_NOT_FOUND",ErrorCode::PlatformNotSupported => "PLATFORM_NOT_SUPPORTED",ErrorCode::Timeout => "TIMEOUT",@@ -50,6 +55,7 @@ pub struct AdapterError {pub source: Option<Box<SourceError>>,pub suggestion: Option<String>,pub platform_detail: Option<String>,+ pub details: Option<Value>,}#[derive(Debug, Error, Clone)]@@ -64,6 +70,7 @@ impl AdapterError {source: None,suggestion: None,platform_detail: None,+ details: None,}}@@ -77,16 +84,26 @@ impl AdapterError {self}+ pub fn with_details(mut self, details: Value) -> Self {+ self.details = Some(details);+ self+ }+pub fn stale_ref(ref_id: &str) -> Self {Self::new(ErrorCode::StaleRef,format!("{ref_id} not found in current RefMap"),).with_suggestion(- "Run 'snapshot' (or 'snapshot --skeleton') to refresh, then retry with updated ref",+ "Use the snapshot_id returned with this ref, or run 'snapshot' / 'snapshot --skeleton' again for fresh refs",)}+ pub fn ambiguous_target(message: impl Into<String>) -> Self {+ Self::new(ErrorCode::AmbiguousTarget, message)+ .with_suggestion("Run 'snapshot' to refresh, then retry with a more specific ref")+ }+pub fn not_supported(method: &str) -> Self {Self::new(ErrorCode::PlatformNotSupported,@@ -135,7 +152,7 @@ impl AdapterError {ErrorCode::SnapshotNotFound,format!("Snapshot '{snapshot_id}' not found"),)- .with_suggestion("Run 'snapshot' again and retry with the returned snapshot_id")+ .with_suggestion("Run 'snapshot' again and retry with the returned snapshot_id; if you omitted --snapshot, use the same --session as the snapshot")}pub fn policy_denied(message: impl Into<String>) -> Self {@@ -143,6 +160,21 @@ impl AdapterError {"Use an explicit mouse/focus command if physical interaction is intended",)}++ pub fn policy_denied_for_policy(message: impl Into<String>, policy: InteractionPolicy) -> Self {+ Self::new(ErrorCode::PolicyDenied, message)+ .with_suggestion(policy_denied_suggestion(policy))+ }+}++fn policy_denied_suggestion(policy: InteractionPolicy) -> &'static str {+ if policy.allow_focus_steal && !policy.allow_cursor_move {+ "Retry with --headed to permit cursor movement, or use an explicit mouse command if physical input is intended"+ } else if !policy.allow_focus_steal && !policy.allow_cursor_move {+ "Headless mode allows only accessibility-backed actions; retry with --headed only if physical cursor/focus interaction is intended, otherwise refresh the snapshot or target an element with the needed semantic action"+ } else {+ "Use an explicit mouse/focus command if physical interaction is intended"+ }}#[derive(Debug, Error)]@@ -226,4 +258,24 @@ mod tests {"stale-ref suggestion should mention skeleton refresh, got: {suggestion}");}++ #[test]+ fn ambiguous_target_error_has_machine_readable_code() {+ let err = AdapterError::ambiguous_target("2 candidates matched");++ assert_eq!(err.code, ErrorCode::AmbiguousTarget);+ assert_eq!(err.code.as_str(), "AMBIGUOUS_TARGET");+ assert!(err.suggestion.is_some());+ }++ #[test]+ fn policy_denied_suggestion_is_mode_aware() {+ let headless =+ AdapterError::policy_denied_for_policy("blocked", InteractionPolicy::headless());+ assert!(headless.suggestion.unwrap().contains("--headed"));++ let focus_fallback =+ AdapterError::policy_denied_for_policy("blocked", InteractionPolicy::focus_fallback());+ assert!(focus_fallback.suggestion.unwrap().contains("--headed"));+ }}diff --git a/crates/core/src/interaction_policy.rs b/crates/core/src/interaction_policy.rsnew file mode 100644index 000000000..d612de995--- /dev/null+++ b/crates/core/src/interaction_policy.rs@@ -0,0 +1,36 @@+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]+pub struct InteractionPolicy {+ pub allow_focus_steal: bool,+ pub allow_cursor_move: bool,+}++impl InteractionPolicy {+ pub fn headless() -> Self {+ Self {+ allow_focus_steal: false,+ allow_cursor_move: false,+ }+ }++ pub fn focus_fallback() -> Self {+ Self {+ allow_focus_steal: true,+ allow_cursor_move: false,+ }+ }++ pub fn headed() -> Self {+ Self {+ allow_focus_steal: true,+ allow_cursor_move: true,+ }+ }+}++impl Default for InteractionPolicy {+ fn default() -> Self {+ Self::headless()+ }+}diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rsindex dfa99b8c6..3a99faa8d 100644--- a/crates/core/src/lib.rs+++ b/crates/core/src/lib.rs@@ -1,13 +1,23 @@pub mod action;+pub mod action_request;+pub mod action_result;+pub mod action_step;+pub mod action_step_outcome;+pub(crate) mod actionability;pub mod adapter;+pub mod capability;pub mod commands;+pub mod context;+pub mod element_state;pub mod error;pub mod hints;+pub mod interaction_policy;pub mod node;pub mod notification;pub mod output;pub mod permission_report;pub mod permission_state;+pub mod ref_action;pub mod ref_alloc;pub mod refs;mod refs_lock;@@ -19,17 +29,25 @@ pub mod roles;pub(crate) mod search_text;pub mod snapshot;pub mod snapshot_ref;+pub(crate) mod trace;mod window_lookup;pub use action::{- Action, ActionRequest, ActionResult, Direction, DragParams, ElementState, InteractionPolicy,- KeyCombo, Modifier, MouseButton, MouseEvent, MouseEventKind, Point, WindowOp,+ Action, Direction, DragParams, KeyCombo, Modifier, MouseButton, MouseEvent, MouseEventKind,+ Point, WindowOp,};+pub use action_request::ActionRequest;+pub use action_result::ActionResult;+pub use action_step::ActionStep;+pub use action_step_outcome::ActionStepOutcome;pub use adapter::{ImageBuffer, ImageFormat, NativeHandle, PlatformAdapter, ScreenshotTarget, TreeOptions,WindowFilter,};+pub use context::CommandContext;+pub use element_state::ElementState;pub use error::{AdapterError, AppError, ErrorCode};+pub use interaction_policy::InteractionPolicy;pub use node::{AccessibilityNode, AppInfo, Rect, WindowInfo};pub use notification::{NotificationFilter, NotificationInfo};pub use output::{AppContext, ErrorPayload, Response, WindowContext};diff --git a/crates/core/src/output.rs b/crates/core/src/output.rsindex cd3ff1b04..a6a6ed78d 100644--- a/crates/core/src/output.rs+++ b/crates/core/src/output.rs@@ -1,11 +1,11 @@use serde::Serialize;use serde_json::Value;+use crate::error::AppError;+pub const ENVELOPE_VERSION: &str = "2.0";-/// Structured output envelope used by the Phase 3 MCP server transport layer.-/// CLI commands currently build responses via inline `serde_json::json!` calls in `main.rs`;-/// this type provides the typed equivalent for programmatic consumers.+/// Structured output envelope used by the CLI and future programmatic transports.#[derive(Debug, Serialize)]pub struct Response {pub version: &'static str,@@ -42,6 +42,8 @@ pub struct ErrorPayload {pub retry_command: Option<String>,#[serde(skip_serializing_if = "Option::is_none")]pub platform_detail: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub details: Option<Value>,}impl Response {@@ -74,6 +76,18 @@ impl Response {}impl ErrorPayload {+ pub fn from_app_error(err: &AppError) -> Self {+ let mut payload = Self::new(err.code(), err.to_string());+ if let Some(suggestion) = err.suggestion() {+ payload = payload.with_suggestion(suggestion);+ }+ if let AppError::Adapter(adapter_error) = err {+ payload.platform_detail = adapter_error.platform_detail.clone();+ payload.details = adapter_error.details.clone();+ }+ payload+ }+pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {Self {code: code.into(),@@ -81,6 +95,7 @@ impl ErrorPayload {suggestion: None,retry_command: None,platform_detail: None,+ details: None,}}@@ -94,3 +109,31 @@ impl ErrorPayload {self}}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::error::{AdapterError, ErrorCode};+ use serde_json::json;++ #[test]+ fn app_error_payload_preserves_adapter_recovery_fields() {+ let err = AppError::Adapter(+ AdapterError::new(ErrorCode::ActionFailed, "not actionable")+ .with_suggestion("wait and retry")+ .with_platform_detail("native press action failed")+ .with_details(json!({ "check": "visible" })),+ );++ let payload = ErrorPayload::from_app_error(&err);++ assert_eq!(payload.code, "ACTION_FAILED");+ assert_eq!(payload.message, "not actionable");+ assert_eq!(payload.suggestion.as_deref(), Some("wait and retry"));+ assert_eq!(+ payload.platform_detail.as_deref(),+ Some("native press action failed")+ );+ assert_eq!(payload.details, Some(json!({ "check": "visible" })));+ }+}diff --git a/crates/core/src/ref_action.rs b/crates/core/src/ref_action.rsnew file mode 100644index 000000000..c7b823d64--- /dev/null+++ b/crates/core/src/ref_action.rs@@ -0,0 +1,101 @@+use crate::{+ action_request::ActionRequest,+ action_result::ActionResult,+ actionability,+ adapter::{NativeHandle, PlatformAdapter},+ context::CommandContext,+ error::{AdapterError, AppError},+ refs::RefEntry,+ resolved_element::ResolvedElement,+};+use serde_json::json;++/// A strictly resolved ref-action target plus the tracing identity for it.+/// Both the CLI command path and the FFI entry path execute through+/// [`execute_resolved`], so actionability, dispatch, and trace semantics+/// live in exactly one place.+pub(crate) struct ResolvedRefAction<'a> {+ pub(crate) adapter: &'a dyn PlatformAdapter,+ pub(crate) entry: &'a RefEntry,+ pub(crate) handle: &'a NativeHandle,+ pub(crate) ref_id: &'a str,+ pub(crate) context: &'a CommandContext,+}++pub(crate) fn execute_resolved(+ target: ResolvedRefAction<'_>,+ request: ActionRequest,+) -> Result<ActionResult, AppError> {+ check_actionability_with_trace(&target, &request)?;+ target.context.trace_lazy(+ "action.dispatch.start",+ || json!({ "ref": target.ref_id, "action": request.action.name() }),+ )?;+ let action_name = request.action.name();+ let result = target.adapter.execute_action(target.handle, request)?;+ let _ = target.context.trace_lazy(+ "action.dispatch.ok",+ || json!({ "ref": target.ref_id, "action": action_name, "result": &result }),+ );+ Ok(result)+}++fn check_actionability_with_trace(+ target: &ResolvedRefAction<'_>,+ request: &ActionRequest,+) -> Result<(), AppError> {+ target.context.trace_lazy(+ "actionability.check.start",+ || json!({ "ref": target.ref_id, "action": request.action.name() }),+ )?;+ actionability::check_live(target.entry, target.handle, target.adapter, request).inspect_err(+ |err| {+ let _ = target.context.trace_lazy("actionability.check.error", || {+ json!({+ "ref": target.ref_id,+ "action": request.action.name(),+ "code": err.code.as_str(),+ "message": err.message.clone(),+ "details": err.details.clone()+ })+ });+ },+ )?;+ target.context.trace_lazy(+ "actionability.check.ok",+ || json!({ "ref": target.ref_id, "action": request.action.name() }),+ )?;+ Ok(())+}++pub fn execute_entry(+ adapter: &dyn PlatformAdapter,+ entry: &RefEntry,+ request: ActionRequest,+) -> Result<ActionResult, AdapterError> {+ let handle = adapter.resolve_element_strict(entry)?;+ let handle = ResolvedElement::new(adapter, handle);+ let context = CommandContext::default();+ let result = execute_resolved(+ ResolvedRefAction {+ adapter,+ entry,+ handle: handle.handle(),+ ref_id: "<ffi>",+ context: &context,+ },+ request,+ );+ result.map_err(into_adapter_error)+}++fn into_adapter_error(err: AppError) -> AdapterError {+ match err {+ AppError::Adapter(err) => err,+ other => AdapterError::internal(other.to_string()),+ }+}++#[cfg(test)]+#[path = "ref_action_tests.rs"]+mod tests;diff --git a/crates/core/src/ref_action_tests.rs b/crates/core/src/ref_action_tests.rsnew file mode 100644index 000000000..7013cd924--- /dev/null+++ b/crates/core/src/ref_action_tests.rs@@ -0,0 +1,97 @@+use super::*;+use crate::{+ action::Action,+ action_result::ActionResult,+ adapter::{NativeHandle, SnapshotSurface},+ capability,+};+use std::sync::atomic::{AtomicU32, Ordering};++struct ReleaseFailingAdapter;++impl PlatformAdapter for ReleaseFailingAdapter {+ fn resolve_element_strict(&self, _entry: &RefEntry) -> Result<NativeHandle, AdapterError> {+ Ok(NativeHandle::null())+ }++ fn execute_action(+ &self,+ _handle: &NativeHandle,+ _request: ActionRequest,+ ) -> Result<ActionResult, AdapterError> {+ Ok(ActionResult::new("click"))+ }++ fn release_handle(&self, _handle: &NativeHandle) -> Result<(), AdapterError> {+ Err(AdapterError::internal("release failed"))+ }+}++struct ErrorReleasingAdapter {+ releases: AtomicU32,+}++impl PlatformAdapter for ErrorReleasingAdapter {+ fn resolve_element_strict(&self, _entry: &RefEntry) -> Result<NativeHandle, AdapterError> {+ Ok(NativeHandle::null())+ }++ fn execute_action(+ &self,+ _handle: &NativeHandle,+ _request: ActionRequest,+ ) -> Result<ActionResult, AdapterError> {+ Err(AdapterError::internal("dispatch failed"))+ }++ fn release_handle(&self, _handle: &NativeHandle) -> Result<(), AdapterError> {+ self.releases.fetch_add(1, Ordering::SeqCst);+ Ok(())+ }+}++fn entry() -> RefEntry {+ RefEntry {+ pid: 1,+ role: "button".into(),+ name: Some("Run".into()),+ value: None,+ description: None,+ states: vec![],+ bounds: None,+ bounds_hash: None,+ available_actions: vec![capability::CLICK.into()],+ source_app: None,+ source_window_id: None,+ source_window_title: None,+ source_surface: SnapshotSurface::Window,+ root_ref: None,+ path_is_absolute: false,+ path: smallvec::SmallVec::new(),+ }+}++#[test]+fn successful_action_survives_release_failure() {+ let result = execute_entry(+ &ReleaseFailingAdapter,+ &entry(),+ ActionRequest::headless(Action::Click),+ )+ .unwrap();++ assert_eq!(result.action, "click");+}++#[test]+fn failed_action_still_releases_resolved_handle() {+ let adapter = ErrorReleasingAdapter {+ releases: AtomicU32::new(0),+ };++ let err =+ execute_entry(&adapter, &entry(), ActionRequest::headless(Action::Click)).unwrap_err();++ assert_eq!(err.code, crate::error::ErrorCode::Internal);+ assert_eq!(adapter.releases.load(Ordering::SeqCst), 1);+}diff --git a/crates/core/src/ref_alloc.rs b/crates/core/src/ref_alloc.rsindex 84f2f29eb..ec3fb2d72 100644--- a/crates/core/src/ref_alloc.rs+++ b/crates/core/src/ref_alloc.rs@@ -4,19 +4,6 @@ use crate::refs::{RefEntry, RefMap};pub(crate) use crate::roles::INTERACTIVE_ROLES;-pub(crate) fn actions_for_role(role: &str) -> Vec<String> {- match role {- "button" | "link" | "menuitem" | "tab" | "radiobutton" => vec!["Click".into()],- "textfield" | "incrementor" => vec!["Click".into(), "SetValue".into(), "SetFocus".into()],- "checkbox" => vec!["Click".into(), "Toggle".into()],- "combobox" => vec!["Click".into(), "Select".into()],- "treeitem" => vec!["Click".into(), "Expand".into(), "Collapse".into()],- "slider" => vec!["SetValue".into()],- "cell" => vec!["Click".into()],- _ => vec!["Click".into()],- }-}-pub(crate) fn ref_entry_from_node(node: &AccessibilityNode,pid: i32,@@ -36,7 +23,7 @@ pub(crate) fn ref_entry_from_node(bounds: node.bounds,bounds_hash: node.bounds.as_ref().map(|b| b.bounds_hash()),available_actions: if node.available_actions.is_empty() {- actions_for_role(&node.role)+ crate::capability::defaults_for_role(&node.role)} else {node.available_actions.clone()},@@ -50,6 +37,24 @@ pub(crate) fn ref_entry_from_node(}}+/// An element receives a ref when it is addressable for an action: either its+/// role is interactive, or it advertises an available action regardless of+/// role. Container roles like `scrollarea` (Scroll) and `disclosure`+/// (Expand/Collapse) are not "interactive" by role but are genuinely+/// actionable, and `scroll` / `expand` / `collapse` need a ref to target+/// them — so action-bearing elements must be ref-able. A bare `SetFocus`+/// affordance does not qualify on its own: focusability is not a primary+/// action and would ref-allocate large numbers of inert containers.+pub(crate) fn is_ref_able(node: &AccessibilityNode) -> bool {+ INTERACTIVE_ROLES.contains(&node.role.as_str()) || advertises_primary_action(node)+}++fn advertises_primary_action(node: &AccessibilityNode) -> bool {+ node.available_actions+ .iter()+ .any(|action| action != crate::capability::SET_FOCUS)+}+pub(crate) fn is_collapsible(node: &AccessibilityNode) -> bool {node.ref_id.is_none()&& node.name.as_deref().is_none_or(str::is_empty)@@ -131,9 +136,9 @@ fn allocate_refs_at_path(config: &RefAllocConfig,path: &mut Vec<usize>,) -> AccessibilityNode {- let is_interactive = INTERACTIVE_ROLES.contains(&node.role.as_str());+ let is_ref_able = is_ref_able(&node);- if is_interactive {+ if is_ref_able {let mut entry = ref_entry_from_node(&node,config.pid,@@ -151,10 +156,8 @@ fn allocate_refs_at_path(let has_label = node.name.as_deref().is_some_and(|n| !n.is_empty())|| node.description.as_deref().is_some_and(|d| !d.is_empty());- let is_skeleton_anchor = !is_interactive- && node.children_count.is_some()- && has_label- && config.root_ref_id.is_none();+ let is_skeleton_anchor =+ !is_ref_able && node.children_count.is_some() && has_label && config.root_ref_id.is_none();if is_skeleton_anchor {let mut entry = ref_entry_from_node(@@ -206,7 +209,6 @@ fn allocate_refs_at_path(fn strip_ref_bounds_when_hidden(entry: &mut RefEntry, include_bounds: bool) {if !include_bounds {entry.bounds = None;- entry.bounds_hash = None;}}diff --git a/crates/core/src/ref_alloc_tests.rs b/crates/core/src/ref_alloc_tests.rsindex c1e7b5a0b..4d8684de1 100644--- a/crates/core/src/ref_alloc_tests.rs+++ b/crates/core/src/ref_alloc_tests.rs@@ -115,6 +115,37 @@ fn ref_entry_preserves_meaningful_identity_text() {assert_eq!(entry.description.as_deref(), Some("Commits changes"));}+/// scrollarea/disclosure are not interactive roles, but they advertise real+/// actions and `scroll` / `expand` need a ref to target them.+#[test]+fn actionable_container_roles_receive_refs() {+ let mut scroll = node("scrollarea", Some("Log"));+ scroll.available_actions = vec!["Scroll".into()];+ assert!(is_ref_able(&scroll));++ let mut disclosure = node("disclosure", Some("Details"));+ disclosure.available_actions = vec!["Click".into()];+ assert!(is_ref_able(&disclosure));+}++/// A bare SetFocus affordance is not a primary action; ref-allocating every+/// focusable container would bloat the refmap.+#[test]+fn focus_only_container_does_not_receive_a_ref() {+ let mut group = node("group", Some("Panel"));+ group.available_actions = vec!["SetFocus".into()];+ assert!(!is_ref_able(&group));++ let inert = node("statictext", Some("Label"));+ assert!(!is_ref_able(&inert));+}++#[test]+fn interactive_role_is_ref_able_even_without_actions() {+ let button = node("button", Some("OK"));+ assert!(is_ref_able(&button));+}+#[test]fn allocate_refs_records_structural_paths() {let mut root = node("window", Some("w"));@@ -148,7 +179,7 @@ fn allocate_refs_records_structural_paths() {}#[test]-fn allocate_refs_hides_bounds_from_refmap_when_snapshot_hides_bounds() {+fn allocate_refs_keeps_bounds_hash_when_snapshot_hides_bounds() {let mut root = node("window", Some("w"));root.children = vec![node("button", Some("Open"))];let mut refmap = RefMap::new();@@ -171,12 +202,22 @@ fn allocate_refs_hides_bounds_from_refmap_when_snapshot_hides_bounds() {assert!(out.children[0].bounds.is_none());assert!(entry.bounds.is_none());- assert!(entry.bounds_hash.is_none());+ assert_eq!(entry.bounds_hash, Some(entry_hash()));assert_eq!(entry.path.as_slice(), [0]);assert_eq!(entry.source_window_id.as_deref(), Some("w-42"));assert_eq!(entry.source_window_title.as_deref(), Some("Documents"));}+fn entry_hash() -> u64 {+ Rect {+ x: 0.0,+ y: 0.0,+ width: 10.0,+ height: 10.0,+ }+ .bounds_hash()+}+#[test]fn allocate_refs_keeps_bounds_in_refmap_when_snapshot_includes_bounds() {let mut root = node("window", Some("w"));diff --git a/crates/core/src/refs.rs b/crates/core/src/refs.rsindex 97e903c35..08b22525a 100644--- a/crates/core/src/refs.rs+++ b/crates/core/src/refs.rs@@ -216,6 +216,14 @@ pub(crate) fn write_private_file(path: &Path, bytes: &[u8]) -> Result<(), AppErrstd::fs::create_dir_all(dir)?;let tmp = path.with_extension("tmp");+ let written = write_tmp_then_rename(&tmp, path, bytes);+ if written.is_err() {+ let _ = std::fs::remove_file(&tmp);+ }+ written+}++fn write_tmp_then_rename(tmp: &Path, path: &Path, bytes: &[u8]) -> Result<(), AppError> {#[cfg(unix)]{use std::io::Write;@@ -225,12 +233,13 @@ pub(crate) fn write_private_file(path: &Path, bytes: &[u8]) -> Result<(), AppErr.create(true).truncate(true).mode(0o600)- .open(&tmp)?;+ .custom_flags(libc::O_NOFOLLOW)+ .open(tmp)?;file.write_all(bytes)?;file.flush()?;}#[cfg(not(unix))]- std::fs::write(&tmp, bytes)?;+ std::fs::write(tmp, bytes)?;std::fs::rename(tmp, path)?;Ok(())diff --git a/crates/core/src/refs_store.rs b/crates/core/src/refs_store.rsindex fe4ea7d15..f2e832002 100644--- a/crates/core/src/refs_store.rs+++ b/crates/core/src/refs_store.rs@@ -1,25 +1,43 @@use crate::{+ context::validate_session_id,error::{AdapterError, AppError},refs::{RefMap, home_dir, new_snapshot_id, validate_snapshot_id, write_private_file},refs_lock::RefStoreLock,};-use std::io::Read;-use std::path::PathBuf;+use std::io::{ErrorKind, Read};+use std::path::{Path, PathBuf};const LATEST_SNAPSHOT_FILE: &str = "latest_snapshot_id";const MAX_SAVED_SNAPSHOTS: usize = 512;+const STALE_TMP_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(60);#[derive(Debug, Clone)]pub struct RefStore {base_dir: PathBuf,+ allow_legacy_migration: bool,}impl RefStore {pub fn new() -> Result<Self, AppError> {+ Self::for_session(None)+ }++ pub fn for_session(session_id: Option<&str>) -> Result<Self, AppError> {let home =home_dir().ok_or_else(|| AppError::Internal("HOME directory not found".into()))?;+ if let Some(session_id) = session_id {+ validate_session_id(session_id)?;+ return Ok(Self {+ base_dir: home+ .join(".agent-desktop")+ .join("sessions")+ .join(session_id),+ allow_legacy_migration: false,+ });+ }Ok(Self {base_dir: home.join(".agent-desktop"),+ allow_legacy_migration: true,})}@@ -42,12 +60,55 @@ impl RefStore {self.with_write_lock(|| self.save_snapshot_unlocked(snapshot_id, refmap))}+ /// Re-saves a snapshot to whichever store currently owns it. Ownership is+ /// re-verified inside the owning store's write lock, so a snapshot pruned+ /// or moved between discovery and locking is never written to a stale+ /// location; discovery retries once before deterministically recreating+ /// the snapshot in this store.pub fn save_existing_snapshot(&self,snapshot_id: &str,refmap: &RefMap,) -> Result<(), AppError> {- self.with_write_lock(|| self.save_snapshot_unlocked(snapshot_id, refmap))+ validate_snapshot_id(snapshot_id)?;+ for _ in 0..2 {+ let Some(owner) = self.snapshot_owner(snapshot_id)? else {+ break;+ };+ let saved = owner.with_write_lock(|| {+ if owner.snapshot_path(snapshot_id).is_file() {+ owner+ .save_snapshot_unlocked(snapshot_id, refmap)+ .map(|_| true)+ } else {+ Ok(false)+ }+ })?;+ if saved {+ return Ok(());+ }+ }+ let fallback = self.without_legacy_migration();+ fallback.with_write_lock(|| fallback.save_snapshot_unlocked(snapshot_id, refmap))+ }++ fn snapshot_owner(&self, snapshot_id: &str) -> Result<Option<Self>, AppError> {+ if self.snapshot_path(snapshot_id).is_file() {+ return Ok(Some(self.without_legacy_migration()));+ }+ Ok(self+ .discover_snapshot_base(snapshot_id)?+ .map(|base_dir| Self {+ base_dir,+ allow_legacy_migration: false,+ }))+ }++ fn without_legacy_migration(&self) -> Self {+ Self {+ base_dir: self.base_dir.clone(),+ allow_legacy_migration: false,+ }}pub fn load(&self, snapshot_id: Option<&str>) -> Result<RefMap, AppError> {@@ -58,11 +119,8 @@ impl RefStore {}pub fn load_latest(&self) -> Result<RefMap, AppError> {- if let Ok(id) = std::fs::read_to_string(self.latest_path()) {- let id = id.trim();- if !id.is_empty() {- return self.load_snapshot(id);- }+ if let Some(id) = self.read_latest_snapshot_id()? {+ return self.load_snapshot_from_base(&self.base_dir, &id);}if let Some(refmap) = self.migrate_legacy_latest()? {return Ok(refmap);@@ -74,9 +132,38 @@ impl RefStore {pub fn load_snapshot(&self, snapshot_id: &str) -> Result<RefMap, AppError> {validate_snapshot_id(snapshot_id)?;- let path = self.snapshot_path(snapshot_id);- let mut file = std::fs::File::open(&path)- .map_err(|_| AppError::Adapter(AdapterError::snapshot_not_found(snapshot_id)))?;+ if let Some(refmap) = self.read_snapshot_if_present(&self.base_dir, snapshot_id)? {+ return Ok(refmap);+ }+ match self.discover_snapshot_base(snapshot_id)? {+ Some(base_dir) => self.load_snapshot_from_base(&base_dir, snapshot_id),+ None => Err(AppError::Adapter(AdapterError::snapshot_not_found(+ snapshot_id,+ ))),+ }+ }++ fn load_snapshot_from_base(+ &self,+ base_dir: &Path,+ snapshot_id: &str,+ ) -> Result<RefMap, AppError> {+ validate_snapshot_id(snapshot_id)?;+ self.read_snapshot_if_present(base_dir, snapshot_id)?+ .ok_or_else(|| AppError::Adapter(AdapterError::snapshot_not_found(snapshot_id)))+ }++ fn read_snapshot_if_present(+ &self,+ base_dir: &Path,+ snapshot_id: &str,+ ) -> Result<Option<RefMap>, AppError> {+ let path = Self::snapshot_path_for_base(base_dir, snapshot_id);+ let mut file = match open_refstore_file(&path) {+ Ok(file) => file,+ Err(err) if err.kind() == ErrorKind::NotFound => return Ok(None),+ Err(err) => return Err(err.into()),+ };let metadata = file.metadata()?;if metadata.len() > crate::refs::MAX_REFMAP_BYTES {return Err(AppError::Internal(@@ -90,7 +177,7 @@ impl RefStore {"RefMap file exceeds 1MB size limit".into(),));}- Ok(serde_json::from_str(&json)?)+ Ok(Some(serde_json::from_str(&json)?))}pub fn set_latest(&self, snapshot_id: &str) -> Result<(), AppError> {@@ -98,10 +185,7 @@ impl RefStore {}pub fn latest_snapshot_id(&self) -> Option<String> {- std::fs::read_to_string(self.latest_path())- .ok()- .map(|s| s.trim().to_string())- .filter(|s| !s.is_empty())+ self.read_latest_snapshot_id().ok().flatten()}fn save_snapshot_unlocked(&self, snapshot_id: &str, refmap: &RefMap) -> Result<(), AppError> {@@ -120,8 +204,23 @@ impl RefStore {self.base_dir.join(LATEST_SNAPSHOT_FILE)}+ fn read_latest_snapshot_id(&self) -> Result<Option<String>, AppError> {+ let mut file = match open_refstore_file(&self.latest_path()) {+ Ok(file) => file,+ Err(err) if err.kind() == ErrorKind::NotFound => return Ok(None),+ Err(err) => return Err(err.into()),+ };+ let mut id = String::new();+ file.read_to_string(&mut id)?;+ Ok(Some(id.trim().to_string()).filter(|id| !id.is_empty()))+ }+fn snapshot_path(&self, snapshot_id: &str) -> PathBuf {- self.base_dir+ Self::snapshot_path_for_base(&self.base_dir, snapshot_id)+ }++ fn snapshot_path_for_base(base_dir: &Path, snapshot_id: &str) -> PathBuf {+ base_dir.join("snapshots").join(snapshot_id).join("refmap.json")@@ -131,44 +230,50 @@ impl RefStore {self.base_dir.join("snapshots")}- fn prune_old_snapshots_unlocked(&self, latest_id: &str) -> Result<(), AppError> {- let dir = self.snapshots_dir();- let Ok(entries) = std::fs::read_dir(&dir) else {- return Ok(());+ fn lock_path(&self) -> PathBuf {+ self.base_dir.join("refstore.lock")+ }++ fn discover_snapshot_base(&self, snapshot_id: &str) -> Result<Option<PathBuf>, AppError> {+ let home =+ home_dir().ok_or_else(|| AppError::Internal("HOME directory not found".into()))?;+ let agent_dir = home.join(".agent-desktop");+ let mut matches = Vec::new();+ if agent_dir != self.base_dir+ && Self::snapshot_path_for_base(&agent_dir, snapshot_id).is_file()+ {+ matches.push(agent_dir.clone());+ }+ let sessions_dir = agent_dir.join("sessions");+ let Ok(entries) = std::fs::read_dir(sessions_dir) else {+ return Ok(matches.into_iter().next());};- let mut snapshots = Vec::new();for entry in entries.flatten() {- let Ok(file_type) = entry.file_type() else {+ let path = entry.path();+ if path == self.base_dir {+ continue;+ }+ let name = entry.file_name();+ let Some(name) = name.to_str() else {continue;};- if !file_type.is_dir() {+ if validate_session_id(name).is_err() {continue;}- let id = entry.file_name().to_string_lossy().to_string();- if validate_snapshot_id(&id).is_err() {+ let Ok(file_type) = entry.file_type() else {continue;- }- let modified = entry- .metadata()- .and_then(|metadata| metadata.modified())- .unwrap_or(std::time::SystemTime::UNIX_EPOCH);- snapshots.push((modified, id, entry.path()));- }- if snapshots.len() <= MAX_SAVED_SNAPSHOTS {- return Ok(());- }- snapshots.sort_by_key(|(modified, id, _)| (*modified, id.clone()));- let remove_count = snapshots.len() - MAX_SAVED_SNAPSHOTS;- for (_, id, path) in snapshots.into_iter().take(remove_count) {- if id != latest_id {- let _ = std::fs::remove_dir_all(path);+ };+ if file_type.is_dir() && Self::snapshot_path_for_base(&path, snapshot_id).is_file() {+ matches.push(path);}}- Ok(())- }-- fn lock_path(&self) -> PathBuf {- self.base_dir.join("refstore.lock")+ if matches.len() > 1 {+ return Err(AppError::invalid_input_with_suggestion(+ format!("Snapshot '{snapshot_id}' exists in more than one session"),+ "Pass the matching --session for this rare snapshot id collision.",+ ));+ }+ Ok(matches.into_iter().next())}fn with_write_lock<T>(&self, f: impl FnOnce() -> Result<T, AppError>) -> Result<T, AppError> {@@ -177,12 +282,12 @@ impl RefStore {}fn migrate_legacy_latest(&self) -> Result<Option<RefMap>, AppError> {+ if !self.allow_legacy_migration {+ return Ok(None);+ }self.with_write_lock(|| {- if let Ok(id) = std::fs::read_to_string(self.latest_path()) {- let id = id.trim();- if !id.is_empty() {- return self.load_snapshot(id).map(Some);- }+ if let Some(id) = self.read_latest_snapshot_id()? {+ return self.load_snapshot_from_base(&self.base_dir, &id).map(Some);}let refmap = match RefMap::load() {Ok(refmap) => refmap,@@ -198,3 +303,35 @@ impl RefStore {})}}++fn open_refstore_file(path: &Path) -> std::io::Result<std::fs::File> {+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt;+ std::fs::OpenOptions::new()+ .read(true)+ .custom_flags(libc::O_NOFOLLOW)+ .open(path)+ }+ #[cfg(not(unix))]+ {+ if std::fs::symlink_metadata(path)?.file_type().is_symlink() {+ return Err(std::io::Error::new(+ ErrorKind::PermissionDenied,+ "refmap path must not be a symlink",+ ));+ }+ std::fs::File::open(path)+ }+}++/// Pruning logic is a sibling `#[path]` module rather than a separate crate+/// module so it can access `base_dir`/`snapshots_dir` directly. Exposing them+/// as `pub(crate)` would widen the visibility surface to every module in the+/// crate; the path declaration keeps them private to this module tree.+#[path = "refs_store_prune.rs"]+mod prune;++#[cfg(test)]+#[path = "refs_store_tests.rs"]+mod tests;diff --git a/crates/core/src/refs_store_prune.rs b/crates/core/src/refs_store_prune.rsnew file mode 100644index 000000000..263e5b658--- /dev/null+++ b/crates/core/src/refs_store_prune.rs@@ -0,0 +1,88 @@+use super::{MAX_SAVED_SNAPSHOTS, RefStore, STALE_TMP_MAX_AGE};+use crate::error::AppError;+use crate::refs::validate_snapshot_id;++impl RefStore {+ /// Removes orphaned `*.tmp` files left behind when a process died between+ /// the temp write and the atomic rename. Runs under the store write lock;+ /// the age threshold keeps any in-flight write from another process safe.+ pub(crate) fn remove_tmp_files_older_than(&self, max_age: std::time::Duration) {+ self.remove_tmp_files_in_dir(&self.base_dir, max_age);+ let snapshots_dir = self.snapshots_dir();+ self.remove_tmp_files_in_dir(&snapshots_dir, max_age);+ let Ok(entries) = std::fs::read_dir(snapshots_dir) else {+ return;+ };+ for entry in entries.flatten() {+ if entry.file_type().is_ok_and(|kind| kind.is_dir()) {+ self.remove_tmp_files_in_dir(&entry.path(), max_age);+ }+ }+ }++ fn remove_tmp_files_in_dir(&self, dir: &std::path::Path, max_age: std::time::Duration) {+ let Ok(entries) = std::fs::read_dir(dir) else {+ return;+ };+ for entry in entries.flatten() {+ let path = entry.path();+ if path.extension().is_none_or(|ext| ext != "tmp") {+ continue;+ }+ let is_plain_file = entry.file_type().is_ok_and(|kind| kind.is_file());+ if !is_plain_file {+ continue;+ }+ let stale = entry+ .metadata()+ .ok()+ .and_then(|metadata| metadata.modified().ok())+ .and_then(|modified| modified.elapsed().ok())+ .is_some_and(|age| age >= max_age);+ if stale {+ let _ = std::fs::remove_file(&path);+ }+ }+ }++ pub(super) fn prune_old_snapshots_unlocked(&self, latest_id: &str) -> Result<(), AppError> {+ self.remove_tmp_files_older_than(STALE_TMP_MAX_AGE);+ let dir = self.snapshots_dir();+ let Ok(entries) = std::fs::read_dir(&dir) else {+ return Ok(());+ };+ let mut snapshots = Vec::new();+ for entry in entries.flatten() {+ let Ok(file_type) = entry.file_type() else {+ continue;+ };+ if !file_type.is_dir() {+ continue;+ }+ let id = entry.file_name().to_string_lossy().to_string();+ if validate_snapshot_id(&id).is_err() {+ continue;+ }+ let modified = entry+ .metadata()+ .and_then(|metadata| metadata.modified())+ .unwrap_or(std::time::SystemTime::UNIX_EPOCH);+ snapshots.push((modified, id, entry.path()));+ }+ if snapshots.len() <= MAX_SAVED_SNAPSHOTS {+ return Ok(());+ }+ snapshots.sort_by_key(|(modified, id, _)| (*modified, id.clone()));+ let mut remove_count = snapshots.len() - MAX_SAVED_SNAPSHOTS;+ for (_, id, path) in snapshots {+ if remove_count == 0 {+ break;+ }+ if id != latest_id {+ let _ = std::fs::remove_dir_all(path);+ remove_count -= 1;+ }+ }+ Ok(())+ }+}diff --git a/crates/core/src/refs_store_tests.rs b/crates/core/src/refs_store_tests.rsnew file mode 100644index 000000000..78889205c--- /dev/null+++ b/crates/core/src/refs_store_tests.rs@@ -0,0 +1,369 @@+use super::*;+use crate::{+ adapter::SnapshotSurface,+ refs::{RefEntry, RefMap},+ refs_test_support::HomeGuard,+};++fn entry(name: &str) -> RefEntry {+ RefEntry {+ pid: 7,+ role: "button".into(),+ name: Some(name.into()),+ value: None,+ description: None,+ states: vec![],+ bounds: None,+ bounds_hash: Some(42),+ available_actions: vec![crate::capability::CLICK.into()],+ source_app: Some("TestApp".into()),+ source_window_id: None,+ source_window_title: Some("Test Window".into()),+ source_surface: SnapshotSurface::Window,+ root_ref: None,+ path_is_absolute: false,+ path: smallvec::SmallVec::new(),+ }+}++fn map_with(name: &str) -> RefMap {+ let mut map = RefMap::new();+ map.allocate(entry(name));+ map+}++fn ref_name(map: &RefMap) -> Option<&str> {+ map.get("@e1").and_then(|entry| entry.name.as_deref())+}++#[test]+fn snapshot_roundtrip_updates_latest_pointer() {+ let _guard = HomeGuard::new();+ let store = RefStore::new().unwrap();+ let map = map_with("Send");++ let snapshot_id = store.save_new_snapshot(&map).unwrap();++ assert_eq!(+ store.latest_snapshot_id().as_deref(),+ Some(snapshot_id.as_str())+ );+ assert_eq!(store.load(Some(&snapshot_id)).unwrap().len(), 1);+ assert_eq!(store.load(None).unwrap().len(), 1);+}++#[test]+fn concurrent_writers_preserve_all_snapshots() {+ let _guard = HomeGuard::new();+ let store = RefStore::new().unwrap();+ let mut handles = Vec::new();++ for i in 0..8 {+ let store = store.clone();+ handles.push(std::thread::spawn(move || {+ store+ .save_new_snapshot(&map_with(&format!("Snapshot {i}")))+ .unwrap()+ }));+ }++ let ids = handles+ .into_iter()+ .map(|handle| handle.join().unwrap())+ .collect::<Vec<_>>();++ for id in &ids {+ assert_eq!(store.load_snapshot(id).unwrap().len(), 1);+ }+ let latest = store.latest_snapshot_id().unwrap();+ assert!(ids.iter().any(|id| id == &latest));+}++#[test]+fn sessions_are_isolated_from_default_store() {+ let _guard = HomeGuard::new();+ let default_store = RefStore::new().unwrap();+ let session_a = RefStore::for_session(Some("agent-a")).unwrap();+ let session_b = RefStore::for_session(Some("agent-b")).unwrap();++ let default_id = default_store+ .save_new_snapshot(&map_with("Default"))+ .unwrap();+ let session_id = session_a.save_new_snapshot(&map_with("Session A")).unwrap();++ assert_eq!(default_store.load(None).unwrap().len(), 1);+ assert_eq!(+ ref_name(&default_store.load(Some(&default_id)).unwrap()),+ Some("Default")+ );+ assert_eq!(+ ref_name(&session_a.load(Some(&session_id)).unwrap()),+ Some("Session A")+ );+ assert!(session_b.load(None).is_err());+ assert_ne!(+ default_store.latest_snapshot_id(),+ session_a.latest_snapshot_id()+ );+}++#[test]+fn explicit_snapshot_id_loads_across_session_namespaces() {+ let _guard = HomeGuard::new();+ let default_store = RefStore::new().unwrap();+ let session_a = RefStore::for_session(Some("agent-a")).unwrap();+ let session_b = RefStore::for_session(Some("agent-b")).unwrap();++ let snapshot_id = session_a.save_new_snapshot(&map_with("Session A")).unwrap();++ assert_eq!(+ ref_name(&default_store.load(Some(&snapshot_id)).unwrap()),+ Some("Session A")+ );+ assert_eq!(+ ref_name(&session_b.load(Some(&snapshot_id)).unwrap()),+ Some("Session A")+ );+ assert!(default_store.load(None).is_err());+ assert!(session_b.load(None).is_err());+}++#[test]+fn save_existing_snapshot_updates_discovered_owner_without_promoting_latest() {+ let _guard = HomeGuard::new();+ let default_store = RefStore::new().unwrap();+ let session_a = RefStore::for_session(Some("agent-a")).unwrap();++ let snapshot_id = session_a.save_new_snapshot(&map_with("Session A")).unwrap();+ default_store+ .save_existing_snapshot(&snapshot_id, &map_with("Updated"))+ .unwrap();++ assert_eq!(+ ref_name(&session_a.load(Some(&snapshot_id)).unwrap()),+ Some("Updated")+ );+ assert!(default_store.latest_snapshot_id().is_none());+ assert_eq!(+ session_a.latest_snapshot_id().as_deref(),+ Some(snapshot_id.as_str())+ );+}++#[test]+fn duplicate_explicit_snapshot_id_requires_session() {+ let _guard = HomeGuard::new();+ let default_store = RefStore::new().unwrap();+ let session_a = RefStore::for_session(Some("agent-a")).unwrap();+ let session_b = RefStore::for_session(Some("agent-b")).unwrap();++ session_a+ .save_snapshot("sdup1", &map_with("Session A"))+ .unwrap();+ session_b+ .save_snapshot("sdup1", &map_with("Session B"))+ .unwrap();++ let err = default_store.load(Some("sdup1")).unwrap_err();++ assert_eq!(err.code(), "INVALID_ARGS");+ assert!(err.suggestion().unwrap().contains("--session"));+ assert_eq!(+ ref_name(&session_a.load(Some("sdup1")).unwrap()),+ Some("Session A")+ );+}++#[test]+fn discover_skips_invalid_session_names_when_detecting_collisions() {+ let _guard = HomeGuard::new();+ let default_store = RefStore::new().unwrap();+ let session_a = RefStore::for_session(Some("agent-a")).unwrap();++ session_a+ .save_snapshot("sdup2", &map_with("Session A"))+ .unwrap();+ let invalid_base = default_store.base_dir.join("sessions").join("bad.session");+ let invalid_path = RefStore::snapshot_path_for_base(&invalid_base, "sdup2");+ std::fs::create_dir_all(invalid_path.parent().unwrap()).unwrap();+ std::fs::write(+ invalid_path,+ map_with("Invalid").serialize_with_size_check().unwrap(),+ )+ .unwrap();++ assert_eq!(+ ref_name(&default_store.load(Some("sdup2")).unwrap()),+ Some("Session A")+ );+}++#[cfg(unix)]+#[test]+fn read_snapshot_rejects_symlinked_refmap() {+ let _guard = HomeGuard::new();+ let store = RefStore::new().unwrap();++ store.save_snapshot("ssym1", &map_with("Original")).unwrap();+ let path = store.snapshot_path("ssym1");+ let target = store.base_dir.join("symlink-target-refmap.json");+ std::fs::write(+ target.as_path(),+ map_with("Symlinked").serialize_with_size_check().unwrap(),+ )+ .unwrap();+ std::fs::remove_file(&path).unwrap();+ std::os::unix::fs::symlink(&target, &path).unwrap();++ let err = store.load(Some("ssym1")).unwrap_err();++ assert_eq!(err.code(), "INTERNAL");+}++#[cfg(unix)]+#[test]+fn read_latest_rejects_symlinked_pointer() {+ let _guard = HomeGuard::new();+ let store = RefStore::new().unwrap();++ let snapshot_id = store.save_new_snapshot(&map_with("Original")).unwrap();+ let latest = store.latest_path();+ let target = store.base_dir.join("latest-target");+ std::fs::write(&target, snapshot_id).unwrap();+ std::fs::remove_file(&latest).unwrap();+ std::os::unix::fs::symlink(&target, &latest).unwrap();++ let err = store.load_latest().unwrap_err();++ assert_eq!(err.code(), "INTERNAL");+ assert!(store.latest_snapshot_id().is_none());+}++#[test]+fn save_existing_snapshot_does_not_promote_latest_pointer() {+ let _guard = HomeGuard::new();+ let store = RefStore::new().unwrap();++ let mut first = map_with("First");+ let first_id = store.save_new_snapshot(&first).unwrap();+ let second_id = store.save_new_snapshot(&map_with("Second")).unwrap();++ first.allocate(entry("First Child"));+ store.save_existing_snapshot(&first_id, &first).unwrap();++ assert_eq!(+ store.latest_snapshot_id().as_deref(),+ Some(second_id.as_str())+ );+ assert_eq!(store.load(Some(&first_id)).unwrap().len(), 2);+}++#[test]+fn default_store_migrates_legacy_latest_refmap() {+ let _guard = HomeGuard::new();+ map_with("Legacy").save().unwrap();++ let store = RefStore::new().unwrap();+ let loaded = store.load_latest().unwrap();++ assert_eq!(loaded.len(), 1);+ assert!(store.latest_snapshot_id().is_some());+}++#[test]+fn session_store_does_not_migrate_global_legacy_refmap() {+ let _guard = HomeGuard::new();+ map_with("Legacy").save().unwrap();++ let store = RefStore::for_session(Some("fresh-agent")).unwrap();+ let err = store.load(None).unwrap_err();++ assert_eq!(err.code(), "SNAPSHOT_NOT_FOUND");+ assert!(store.latest_snapshot_id().is_none());+}++#[test]+fn stale_tmp_files_are_swept_and_fresh_ones_kept() {+ let _guard = HomeGuard::new();+ let store = RefStore::new().unwrap();+ let snapshot_id = store.save_new_snapshot(&map_with("Send")).unwrap();+ let base_tmp = store.base_dir.join("latest_snapshot_id.tmp");+ let snapshot_tmp = store.snapshots_dir().join("dead.tmp");+ let refmap_tmp = store.snapshots_dir().join(&snapshot_id).join("refmap.tmp");+ std::fs::write(&base_tmp, b"orphan").unwrap();+ std::fs::write(&snapshot_tmp, b"orphan").unwrap();+ std::fs::write(&refmap_tmp, b"orphan").unwrap();++ store.remove_tmp_files_older_than(std::time::Duration::ZERO);++ assert!(!base_tmp.exists());+ assert!(!snapshot_tmp.exists());+ assert!(!refmap_tmp.exists());+ assert!(store.snapshot_path(&snapshot_id).is_file());++ std::fs::write(&base_tmp, b"fresh").unwrap();+ store.remove_tmp_files_older_than(STALE_TMP_MAX_AGE);++ assert!(base_tmp.exists());+}++#[test]+fn save_new_snapshot_prunes_old_snapshots_without_removing_latest() {+ let _guard = HomeGuard::new();+ let store = RefStore::new().unwrap();+ let first_id = store.save_new_snapshot(&map_with("First")).unwrap();+ std::thread::sleep(std::time::Duration::from_millis(5));+ let mut latest_id = first_id.clone();++ for i in 0..=MAX_SAVED_SNAPSHOTS {+ latest_id = store+ .save_new_snapshot(&map_with(&format!("Snapshot {i}")))+ .unwrap();+ }++ let count = std::fs::read_dir(store.snapshots_dir())+ .unwrap()+ .filter_map(Result::ok)+ .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_dir()))+ .count();++ assert!(count <= MAX_SAVED_SNAPSHOTS);+ assert!(store.snapshot_path(&latest_id).is_file());+ assert!(!store.snapshot_path(&first_id).exists());+ assert_eq!(+ store.latest_snapshot_id().as_deref(),+ Some(latest_id.as_str())+ );+}++#[test]+fn save_existing_recreates_snapshot_pruned_from_every_store() {+ let _guard = HomeGuard::new();+ let store = RefStore::new().unwrap();+ let snapshot_id = store.save_new_snapshot(&map_with("Original")).unwrap();+ std::fs::remove_dir_all(store.snapshots_dir().join(&snapshot_id)).unwrap();++ store+ .save_existing_snapshot(&snapshot_id, &map_with("Recreated"))+ .unwrap();++ let reloaded = store.load_snapshot(&snapshot_id).unwrap();+ assert_eq!(ref_name(&reloaded), Some("Recreated"));+}++#[test]+fn duplicate_snapshot_id_across_sessions_is_rejected_on_load() {+ let _guard = HomeGuard::new();+ let store_a = RefStore::for_session(Some("agent-a")).unwrap();+ let store_b = RefStore::for_session(Some("agent-b")).unwrap();+ let snapshot_id = store_a.save_new_snapshot(&map_with("A")).unwrap();+ store_b.save_snapshot(&snapshot_id, &map_with("B")).unwrap();++ let err = RefStore::new()+ .unwrap()+ .load_snapshot(&snapshot_id)+ .unwrap_err();++ assert_eq!(err.code(), "INVALID_ARGS");+ assert!(err.to_string().contains("more than one session"));+}diff --git a/crates/core/src/refs_tests.rs b/crates/core/src/refs_tests.rsindex d32b906a5..35fed6509 100644--- a/crates/core/src/refs_tests.rs+++ b/crates/core/src/refs_tests.rs@@ -1,5 +1,5 @@use super::*;-use crate::{refs_store::RefStore, refs_test_support::HomeGuard};+use crate::refs_test_support::HomeGuard;fn entry(role: &str, name: Option<&str>) -> RefEntry {RefEntry {@@ -208,63 +208,6 @@ fn test_save_load_roundtrip_with_home_override() {assert_eq!(entry.name.as_deref(), Some("Send"));}-#[test]-fn test_refstore_snapshot_roundtrip_and_latest_pointer() {- let _guard = HomeGuard::new();- let store = RefStore::new().unwrap();- let mut map = RefMap::new();- map.allocate(RefEntry {- pid: 7,- role: "button".into(),- name: Some("Send".into()),- value: None,- description: None,- states: vec![],- bounds: None,- bounds_hash: Some(42),- available_actions: vec!["Click".into()],- source_app: Some("TestApp".into()),- source_window_id: None,- source_window_title: Some("Test Window".into()),- source_surface: crate::adapter::SnapshotSurface::Window,- root_ref: None,- path_is_absolute: false,- path: smallvec::SmallVec::new(),- });-- let snapshot_id = store.save_new_snapshot(&map).unwrap();-- assert_eq!(- store.latest_snapshot_id().as_deref(),- Some(snapshot_id.as_str())- );- assert_eq!(store.load(Some(&snapshot_id)).unwrap().len(), 1);- assert_eq!(store.load(None).unwrap().len(), 1);-}--#[test]-fn test_save_existing_snapshot_does_not_promote_latest_pointer() {- let _guard = HomeGuard::new();- let store = RefStore::new().unwrap();-- let mut first = RefMap::new();- first.allocate(entry("button", Some("First")));- let first_id = store.save_new_snapshot(&first).unwrap();-- let mut second = RefMap::new();- second.allocate(entry("button", Some("Second")));- let second_id = store.save_new_snapshot(&second).unwrap();-- first.allocate(entry("button", Some("First Child")));- store.save_existing_snapshot(&first_id, &first).unwrap();-- assert_eq!(- store.latest_snapshot_id().as_deref(),- Some(second_id.as_str())- );- assert_eq!(store.load(Some(&first_id)).unwrap().len(), 2);-}-#[test]fn test_snapshot_ids_are_compact_and_valid() {let id = new_snapshot_id();@@ -291,20 +234,6 @@ fn test_new_snapshot_id_passes_validation() {}}-#[test]-fn test_refstore_migrates_legacy_latest_refmap() {- let _guard = HomeGuard::new();- let mut map = RefMap::new();- map.allocate(entry("button", Some("Legacy")));- map.save().unwrap();-- let store = RefStore::new().unwrap();- let loaded = store.load_latest().unwrap();-- assert_eq!(loaded.len(), 1);- assert!(store.latest_snapshot_id().is_some());-}-#[test]fn test_validate_snapshot_id_rejects_bad_values() {assert!(validate_snapshot_id("").is_err());@@ -335,9 +264,52 @@ fn test_save_oversize_preserves_previous_file() {assert_eq!(entry.name.as_deref(), Some("Original"));}+#[cfg(unix)]+#[test]+fn test_write_private_file_rejects_tmp_symlink() {+ let dir = std::env::temp_dir().join(format!(+ "agent-desktop-ref-symlink-{}",+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("refmap.json");+ let target = dir.join("target.json");+ let tmp = path.with_extension("tmp");+ std::fs::write(&target, b"existing").unwrap();+ std::os::unix::fs::symlink(&target, &tmp).unwrap();++ let result = write_private_file(&path, b"new");++ assert!(result.is_err());+ assert_eq!(std::fs::read(&target).unwrap(), b"existing");+ let _ = std::fs::remove_dir_all(dir);+}+#[test]fn test_root_ref_none_omitted() {let entry = entry("button", None);let json = serde_json::to_string(&entry).unwrap();assert!(!json.contains("root_ref"));}++#[test]+fn test_write_private_file_cleans_tmp_when_rename_fails() {+ let dir = std::env::temp_dir().join(format!(+ "agent-desktop-ref-renamefail-{}",+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ let path = dir.join("blocked");+ std::fs::create_dir_all(path.join("child")).unwrap();++ let result = write_private_file(&path, b"new");++ assert!(result.is_err());+ assert!(!dir.join("blocked.tmp").exists());+ let _ = std::fs::remove_dir_all(dir);+}diff --git a/crates/core/src/roles.rs b/crates/core/src/roles.rsindex a2c6f5583..f209ceb6f 100644--- a/crates/core/src/roles.rs+++ b/crates/core/src/roles.rs@@ -22,6 +22,21 @@ pub const INTERACTIVE_ROLES: &[&str] = &["treeitem",];+/// Normalizes a caller-supplied role filter for comparison against tree+/// roles: trims, lowercases, and folds a few high-frequency web-automation+/// synonyms onto their canonical names so an agent's reflexive `textarea`+/// matches the `textfield` the adapters emit. This is an ergonomic shim,+/// not a vocabulary: it never rejects. Whether a role exists is answered+/// by the live tree (see `find`'s `roles_present`), so a new adapter role+/// works the instant the adapter emits it — nothing here to keep in sync.+pub fn normalize_role_query(role: &str) -> String {+ let normalized = role.trim().to_ascii_lowercase();+ match normalized.as_str() {+ "textarea" | "textbox" | "searchfield" => "textfield".to_string(),+ _ => normalized,+ }+}+/// Returns true when `role` is in [`INTERACTIVE_ROLES`].pub fn is_interactive_role(role: &str) -> bool {INTERACTIVE_ROLES.contains(&role)@@ -34,7 +49,13 @@ pub fn is_toggleable_role(role: &str) -> bool {/// Returns true for roles that carry an expanded/collapsed surface state.pub fn is_expandable_role(role: &str) -> bool {- matches!(role, "combobox" | "menubutton" | "treeitem")+ matches!(role, "combobox" | "menubutton" | "treeitem" | "disclosure")+}++/// Returns true for roles whose `value` changes during normal interaction and+/// must not be treated as stable ref identity.+pub fn is_mutable_value_role(role: &str) -> bool {+ matches!(role, "combobox" | "incrementor" | "slider" | "textfield")}#[cfg(test)]@@ -49,6 +70,25 @@ mod tests {assert_eq!(sorted.as_slice(), INTERACTIVE_ROLES);}+ #[test]+ fn normalize_role_query_folds_text_input_synonyms() {+ assert_eq!(normalize_role_query("textarea"), "textfield");+ assert_eq!(normalize_role_query("textbox"), "textfield");+ assert_eq!(normalize_role_query("searchfield"), "textfield");+ }++ #[test]+ fn normalize_role_query_is_case_insensitive_and_trimmed() {+ assert_eq!(normalize_role_query("Button"), "button");+ assert_eq!(normalize_role_query(" TEXTAREA "), "textfield");+ }++ #[test]+ fn normalize_role_query_passes_unknown_roles_through_untouched() {+ assert_eq!(normalize_role_query("navbar"), "navbar");+ assert_eq!(normalize_role_query("buttn"), "buttn");+ }+#[test]fn toggleable_roles_are_a_subset_of_interactive() {for role in ["checkbox", "switch", "radiobutton"] {@@ -60,18 +100,19 @@ mod tests {}#[test]- fn expandable_roles_are_a_subset_of_interactive() {+ fn interactive_expandable_roles_are_interactive() {for role in ["combobox", "menubutton", "treeitem"] {assert!(is_expandable_role(role));assert!(is_interactive_role(role));}+ assert!(is_expandable_role("disclosure"));+ assert!(!is_interactive_role("disclosure"));assert!(!is_expandable_role("button"));assert!(!is_expandable_role("checkbox"));- assert!(!is_expandable_role("disclosure"));}#[test]- fn every_expandable_role_is_interactive() {+ fn interactive_role_expandables_are_in_interactive_roles() {for role in ["combobox", "menubutton", "treeitem"] {assert!(is_expandable_role(role),@@ -101,4 +142,14 @@ mod tests {assert!(!is_interactive_role(role));}}++ #[test]+ fn mutable_value_roles_are_interactive() {+ for role in ["combobox", "incrementor", "slider", "textfield"] {+ assert!(is_mutable_value_role(role));+ assert!(is_interactive_role(role));+ }+ assert!(!is_mutable_value_role("cell"));+ assert!(!is_mutable_value_role("button"));+ }}diff --git a/crates/core/src/snapshot.rs b/crates/core/src/snapshot.rsindex a78af3f07..4efb54762 100644--- a/crates/core/src/snapshot.rs+++ b/crates/core/src/snapshot.rs@@ -1,5 +1,6 @@use crate::{adapter::{PlatformAdapter, SnapshotSurface, TreeOptions, WindowFilter},+ context::CommandContext,error::AppError,node::{AccessibilityNode, WindowInfo},ref_alloc::{self, RefAllocConfig},@@ -75,7 +76,7 @@ pub fn build(})?};- let raw_tree = adapter.get_tree(&window, opts)?;+ let raw_tree = adapter.get_tree(&window, &opts.with_ref_identity_bounds())?;let mut refmap = RefMap::new();let config = RefAllocConfig {@@ -102,16 +103,37 @@ pub fn build(})}+#[cfg(test)]pub fn run(adapter: &dyn PlatformAdapter,opts: &TreeOptions,app_name: Option<&str>,window_id: Option<&str>,+) -> Result<SnapshotResult, AppError> {+ run_with_context(+ adapter,+ opts,+ app_name,+ window_id,+ &CommandContext::default(),+ )+}++pub fn run_with_context(+ adapter: &dyn PlatformAdapter,+ opts: &TreeOptions,+ app_name: Option<&str>,+ window_id: Option<&str>,+ context: &CommandContext,) -> Result<SnapshotResult, AppError> {let mut result = build(adapter, opts, app_name, window_id)?;- let store = RefStore::new()?;+ let store = RefStore::for_session(context.session_id())?;let snapshot_id = store.save_new_snapshot(&result.refmap)?;result.snapshot_id = Some(snapshot_id);+ context.trace_lazy(+ "snapshot.saved",+ || serde_json::json!({ "snapshot_id": result.snapshot_id, "ref_count": result.refmap.len() }),+ )?;Ok(result)}@@ -120,6 +142,22 @@ pub fn append_surface_refs(pid: i32,source_app: Option<&str>,surface: SnapshotSurface,+) -> Result<Option<AccessibilityNode>, AppError> {+ append_surface_refs_with_context(+ adapter,+ pid,+ source_app,+ surface,+ &CommandContext::default(),+ )+}++pub fn append_surface_refs_with_context(+ adapter: &dyn PlatformAdapter,+ pid: i32,+ source_app: Option<&str>,+ surface: SnapshotSurface,+ context: &CommandContext,) -> Result<Option<AccessibilityNode>, AppError> {let filter = WindowFilter {focused_only: false,@@ -134,8 +172,8 @@ pub fn append_surface_refs(interactive_only: true,..Default::default()};- let raw_tree = adapter.get_tree(&window, &opts)?;- let store = RefStore::new()?;+ let raw_tree = adapter.get_tree(&window, &opts.with_ref_identity_bounds())?;+ let store = RefStore::for_session(context.session_id())?;let mut refmap = store.load_latest()?;let config = RefAllocConfig {include_bounds: false,diff --git a/crates/core/src/snapshot_ref.rs b/crates/core/src/snapshot_ref.rsindex dacef173e..71a0a4e93 100644--- a/crates/core/src/snapshot_ref.rs+++ b/crates/core/src/snapshot_ref.rs@@ -1,5 +1,6 @@use crate::{adapter::{PlatformAdapter, TreeOptions},+ context::CommandContext,error::AppError,node::WindowInfo,ref_alloc::{self, RefAllocConfig},@@ -8,13 +9,30 @@ use crate::{snapshot::SnapshotResult,};+#[cfg(test)]pub fn run_from_ref(adapter: &dyn PlatformAdapter,opts: &TreeOptions,root_ref_id: &str,snapshot_id: Option<&str>,) -> Result<SnapshotResult, AppError> {- let store = RefStore::new()?;+ run_from_ref_with_context(+ adapter,+ opts,+ root_ref_id,+ snapshot_id,+ &CommandContext::default(),+ )+}++pub fn run_from_ref_with_context(+ adapter: &dyn PlatformAdapter,+ opts: &TreeOptions,+ root_ref_id: &str,+ snapshot_id: Option<&str>,+ context: &CommandContext,+) -> Result<SnapshotResult, AppError> {+ let store = RefStore::for_session(context.session_id())?;let mut refmap = store.load(snapshot_id)?;let active_snapshot_id = snapshot_id.map(str::to_string)@@ -25,9 +43,9 @@ pub fn run_from_ref(.ok_or_else(|| AppError::stale_ref(root_ref_id))?.clone();- let handle = ResolvedElement::new(adapter, adapter.resolve_element(&entry)?);+ let handle = ResolvedElement::new(adapter, adapter.resolve_element_strict(&entry)?);- let raw_tree = adapter.get_subtree(handle.handle(), opts)?;+ let raw_tree = adapter.get_subtree(handle.handle(), &opts.with_ref_identity_bounds())?;refmap.remove_by_root_ref(root_ref_id);@@ -58,6 +76,13 @@ pub fn run_from_ref(} else {Some(store.save_new_snapshot(&refmap)?)};+ context.trace_lazy("snapshot.root.saved", || {+ serde_json::json!({+ "root_ref": root_ref_id,+ "snapshot_id": saved_snapshot_id,+ "ref_count": refmap.len()+ })+ })?;let window =crate::window_lookup::find_window_for_pid(entry.pid, adapter).unwrap_or(WindowInfo {diff --git a/crates/core/src/snapshot_ref_tests.rs b/crates/core/src/snapshot_ref_tests.rsindex 6ff917482..b0b267e6b 100644--- a/crates/core/src/snapshot_ref_tests.rs+++ b/crates/core/src/snapshot_ref_tests.rs@@ -1,5 +1,5 @@use super::*;-use crate::action::ActionRequest;+use crate::action_request::ActionRequest;use crate::adapter::{NativeHandle, PlatformAdapter};use crate::error::AdapterError;use crate::node::AccessibilityNode;@@ -58,7 +58,7 @@ impl StubAdapter {}impl PlatformAdapter for StubAdapter {- fn resolve_element(+ fn resolve_element_strict(&self,_entry: &crate::refs::RefEntry,) -> Result<NativeHandle, AdapterError> {@@ -86,7 +86,7 @@ impl PlatformAdapter for StubAdapter {&self,_handle: &NativeHandle,_request: ActionRequest,- ) -> Result<crate::action::ActionResult, AdapterError> {+ ) -> Result<crate::action_result::ActionResult, AdapterError> {Err(AdapterError::not_supported("execute_action"))}}@@ -98,6 +98,13 @@ fn save_latest(refmap: RefMap) -> String {.expect("snapshot refmap should save")}+fn save_session(session_id: &str, refmap: RefMap) -> String {+ RefStore::for_session(Some(session_id))+ .unwrap()+ .save_new_snapshot(&refmap)+ .expect("session snapshot refmap should save")+}+fn load_latest() -> RefMap {RefStore::new().unwrap()@@ -105,6 +112,13 @@ fn load_latest() -> RefMap {.expect("latest snapshot should load")}+fn load_session_snapshot(session_id: &str, snapshot_id: &str) -> RefMap {+ RefStore::for_session(Some(session_id))+ .unwrap()+ .load(Some(snapshot_id))+ .expect("session snapshot should load")+}+fn seed_skeleton_refmap() -> RefMap {let mut map = RefMap::new();let anchor = ref_entry_from_node(@@ -176,6 +190,24 @@ fn test_run_from_ref_returns_subtree_and_persists_refs() {assert_eq!(adapter.release_calls.load(Ordering::SeqCst), 1);}+#[test]+fn test_run_from_ref_explicit_session_snapshot_without_session_context() {+ let _guard = HomeGuard::new();+ let snapshot_id = save_session("agent-a", seed_skeleton_refmap());++ let adapter = StubAdapter::new(named("button", "Save"));+ let result = run_from_ref(&adapter, &drill_opts(), "@e1", Some(&snapshot_id))+ .expect("explicit snapshot should drill without repeating --session");++ assert_eq!(result.snapshot_id.as_deref(), Some(snapshot_id.as_str()));+ let on_disk = load_session_snapshot("agent-a", &snapshot_id);+ assert!(on_disk.get("@e1").is_some(), "skeleton anchor preserved");+ let drill_ref = result.tree.ref_id.as_deref().expect("drill ref");+ let drill_entry = on_disk.get(drill_ref).expect("drill ref persisted");+ assert_eq!(drill_entry.name.as_deref(), Some("Save"));+ assert!(RefStore::new().unwrap().latest_snapshot_id().is_none());+}+#[test]fn test_run_from_ref_releases_handle_when_subtree_read_fails() {let _guard = HomeGuard::new();diff --git a/crates/core/src/trace.rs b/crates/core/src/trace.rsnew file mode 100644index 000000000..8c586de65--- /dev/null+++ b/crates/core/src/trace.rs@@ -0,0 +1,300 @@+use crate::error::AppError;+use serde_json::{Map, Value, json};+use std::path::{Path, PathBuf};+use std::sync::{Arc, Mutex};++const MAX_TRACE_FILE_BYTES: u64 = 64 * 1024 * 1024;++#[derive(Debug, Clone, Default)]+pub struct TraceConfig {+ strict: bool,+ writer: Option<Arc<Mutex<std::fs::File>>>,+}++impl TraceConfig {+ pub fn new(path: Option<PathBuf>, strict: bool) -> Result<Self, AppError> {+ if strict && path.is_none() {+ return Err(AppError::invalid_input_with_suggestion(+ "--trace-strict requires --trace",+ "Provide --trace <path> or remove --trace-strict.",+ ));+ }+ let writer = match path.as_deref() {+ Some(path) => match open_trace_file(path) {+ Ok(file) => Some(Arc::new(Mutex::new(file))),+ Err(err) if err.code() == "INVALID_ARGS" => return Err(err),+ Err(err) if strict => return Err(err),+ Err(err) => {+ tracing::warn!("trace open failed: {err}");+ None+ }+ },+ None => None,+ };+ Ok(Self { strict, writer })+ }++ pub fn emit(&self, event: &str, fields: Value) -> Result<(), AppError> {+ self.emit_lazy(event, || fields)+ }++ pub fn emit_lazy(&self, event: &str, fields: impl FnOnce() -> Value) -> Result<(), AppError> {+ let Some(writer) = self.writer.as_ref() else {+ return Ok(());+ };+ match writer+ .lock()+ .map_err(|_| AppError::Internal("trace writer lock poisoned".into()))+ .and_then(|mut file| write_event(&mut file, event, fields()))+ {+ Ok(()) => Ok(()),+ Err(err) if self.strict => Err(err),+ Err(err) => {+ tracing::warn!("trace write failed: {err}");+ Ok(())+ }+ }+ }+}++fn open_trace_file(path: &Path) -> Result<std::fs::File, AppError> {+ let mut options = std::fs::OpenOptions::new();+ options.create(true).append(true);+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt;+ options.mode(0o600);+ options.custom_flags(libc::O_NOFOLLOW);+ }+ let file = options.open(path).map_err(AppError::from)?;+ reject_loose_trace_permissions(&file)?;+ Ok(file)+}++fn write_event(file: &mut std::fs::File, event: &str, fields: Value) -> Result<(), AppError> {+ reject_oversized_trace(file)?;+ let mut body = Map::new();+ body.insert("event".to_string(), json!(event));+ body.insert(+ "ts_ms".to_string(),+ json!(+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_err(|err| AppError::Internal(err.to_string()))?+ .as_millis()+ ),+ );+ if let Value::Object(fields) = sanitize_trace_value(fields) {+ for (key, value) in fields {+ body.insert(key, value);+ }+ }+ serde_json::to_writer(&mut *file, &Value::Object(body))?;+ use std::io::Write;+ file.write_all(b"\n").map_err(AppError::from)+}++fn reject_oversized_trace(file: &std::fs::File) -> Result<(), AppError> {+ let len = file.metadata()?.len();+ if len < MAX_TRACE_FILE_BYTES {+ return Ok(());+ }+ Err(AppError::invalid_input_with_suggestion(+ "Trace file reached the maximum supported size",+ "Start a new --trace file or rotate the existing trace before retrying.",+ ))+}++#[cfg(unix)]+fn reject_loose_trace_permissions(file: &std::fs::File) -> Result<(), AppError> {+ use std::os::unix::fs::PermissionsExt;++ let mode = file.metadata()?.permissions().mode() & 0o777;+ if mode & 0o077 == 0 {+ return Ok(());+ }+ Err(AppError::invalid_input_with_suggestion(+ "Trace file must not be readable or writable by group/other",+ "Use a new --trace path or run chmod 600 on the existing trace file.",+ ))+}++#[cfg(not(unix))]+fn reject_loose_trace_permissions(_file: &std::fs::File) -> Result<(), AppError> {+ Ok(())+}++fn sanitize_trace_value(value: Value) -> Value {+ match value {+ Value::Object(map) => Value::Object(+ map.into_iter()+ .map(|(key, value)| {+ if is_sensitive_trace_key(&key) {+ (key, redacted_value(value))+ } else {+ (key, sanitize_trace_value(value))+ }+ })+ .collect(),+ ),+ Value::Array(items) => Value::Array(items.into_iter().map(sanitize_trace_value).collect()),+ other => other,+ }+}++fn is_sensitive_trace_key(key: &str) -> bool {+ const SENSITIVE_KEYS: &[&str] = &[+ "text",+ "value",+ "expected",+ "name",+ "username",+ "description",+ "label",+ "query",+ "secret",+ "token",+ "password",+ "title",+ "url",+ "help",+ "placeholder",+ ];+ trace_key_tokens(key)+ .iter()+ .any(|part| SENSITIVE_KEYS.contains(&part.as_str()))+}++fn trace_key_tokens(key: &str) -> Vec<String> {+ let mut tokens = Vec::new();+ let mut current = String::new();+ let mut previous_was_lower_or_digit = false;++ for ch in key.chars() {+ if !ch.is_ascii_alphanumeric() {+ push_trace_key_token(&mut tokens, &mut current);+ previous_was_lower_or_digit = false;+ continue;+ }++ if ch.is_ascii_uppercase() && previous_was_lower_or_digit {+ push_trace_key_token(&mut tokens, &mut current);+ }++ current.push(ch.to_ascii_lowercase());+ previous_was_lower_or_digit = ch.is_ascii_lowercase() || ch.is_ascii_digit();+ }++ push_trace_key_token(&mut tokens, &mut current);+ tokens+}++fn push_trace_key_token(tokens: &mut Vec<String>, current: &mut String) {+ if !current.is_empty() {+ tokens.push(std::mem::take(current));+ }+}++fn redacted_value(value: Value) -> Value {+ match value {+ Value::Null => Value::Null,+ _ => json!({ "redacted": true }),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[cfg(unix)]+ #[test]+ fn trace_open_rejects_symlink_paths() {+ let base = std::env::temp_dir().join(format!(+ "agent-desktop-trace-symlink-{}",+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ let target = base.with_extension("target");+ let link = base.with_extension("link");+ std::fs::write(&target, b"existing").unwrap();+ std::os::unix::fs::symlink(&target, &link).unwrap();++ let result = open_trace_file(&link);++ assert!(result.is_err());+ let _ = std::fs::remove_file(&link);+ let _ = std::fs::remove_file(&target);+ }++ #[test]+ fn trace_redacts_sensitive_fields_but_preserves_messages() {+ let value = sanitize_trace_value(json!({+ "text": "secret",+ "message": "Target is not actionable: supported_action failed",+ "details": { "name": "Private Button" },+ "title": "Window"+ }));++ assert_eq!(value["text"]["redacted"], true);+ assert_eq!(value["details"]["name"]["redacted"], true);+ assert_eq!(value["title"]["redacted"], true);+ assert_eq!(+ value["message"],+ "Target is not actionable: supported_action failed"+ );+ }++ #[test]+ fn trace_redaction_covers_nested_shapes_and_substring_keys() {+ let value = sanitize_trace_value(json!({+ "action": {+ "typed_text": ["secret", "another"],+ "api_token": {"kind": "bearer"},+ "typedText": "secret",+ "apiToken": "secret",+ "targetLabel": "secret",+ "userName": "secret",+ "filename": "report.txt",+ "password": null,+ "counter": 3+ }+ }));++ assert_eq!(value["action"]["typed_text"]["redacted"], true);+ assert_eq!(value["action"]["api_token"]["redacted"], true);+ assert_eq!(value["action"]["typedText"]["redacted"], true);+ assert_eq!(value["action"]["apiToken"]["redacted"], true);+ assert_eq!(value["action"]["targetLabel"]["redacted"], true);+ assert_eq!(value["action"]["userName"]["redacted"], true);+ assert_eq!(value["action"]["filename"], "report.txt");+ assert!(value["action"]["password"].is_null());+ assert_eq!(value["action"]["counter"], 3);+ }++ #[test]+ fn trace_write_rejects_files_at_size_cap() {+ let path = std::env::temp_dir().join(format!(+ "agent-desktop-trace-cap-{}",+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ let file = std::fs::File::create(&path).unwrap();+ file.set_len(MAX_TRACE_FILE_BYTES).unwrap();+ drop(file);+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();+ }+ let mut file = open_trace_file(&path).unwrap();++ let err = write_event(&mut file, "event", json!({})).unwrap_err();++ assert_eq!(err.code(), "INVALID_ARGS");+ let _ = std::fs::remove_file(path);+ }+}diff --git a/crates/ffi/Cargo.toml b/crates/ffi/Cargo.tomlindex 397d6dbc7..df24d463b 100644--- a/crates/ffi/Cargo.toml+++ b/crates/ffi/Cargo.toml@@ -10,6 +10,7 @@ crate-type = ["cdylib", "rlib"][dependencies]smallvec.workspace = true+serde_json.workspace = trueagent-desktop-core.workspace = true[target.'cfg(target_os = "macos")'.dependencies]diff --git a/crates/ffi/build.rs b/crates/ffi/build.rsindex 25fd7629f..f154d8413 100644--- a/crates/ffi/build.rs+++ b/crates/ffi/build.rs@@ -1,7 +1,8 @@+//! Cargo's default install_name is the absolute build-machine path, which+//! breaks linking consumers (Swift/SPM, clang) once the dylib is extracted+//! from a release tarball. @rpath is the portable form.+fn main() {- // Cargo's default install_name is the absolute build-machine path,- // which breaks linking consumers (Swift/SPM, clang) once the dylib- // is extracted from a release tarball. @rpath is the portable form.if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") {println!("cargo:rustc-cdylib-link-arg=-Wl,-install_name,@rpath/libagent_desktop_ffi.dylib");}diff --git a/crates/ffi/include/agent_desktop.h b/crates/ffi/include/agent_desktop.hindex dd3416033..bd1034cd8 100644--- a/crates/ffi/include/agent_desktop.h+++ b/crates/ffi/include/agent_desktop.h@@ -5,6 +5,8 @@#include <stdbool.h>#include <stddef.h>+/* New result codes may be appended in future releases.+ * Always handle values outside this list. */enum AdResult {AD_RESULT_OK = 0,AD_RESULT_ERR_PERM_DENIED = -1,@@ -21,6 +23,7 @@ enum AdResult {AD_RESULT_ERR_INTERNAL = -12,AD_RESULT_ERR_SNAPSHOT_NOT_FOUND = -13,AD_RESULT_ERR_POLICY_DENIED = -14,+ AD_RESULT_ERR_AMBIGUOUS_TARGET = -15,};typedef int32_t AdResult;@@ -89,7 +92,7 @@ typedef int32_t AdMouseEventKind;enum AdPolicyKind {AD_POLICY_KIND_HEADLESS = 0,AD_POLICY_KIND_FOCUS_FALLBACK = 1,- AD_POLICY_KIND_PHYSICAL = 2,+ AD_POLICY_KIND_HEADED = 2,};typedef int32_t AdPolicyKind;@@ -193,12 +196,38 @@ typedef struct AdPoint {double y;} AdPoint;+/*+ * Caller-allocated drag parameters. Zero-initialize the whole struct before+ * setting fields: `duration_ms`/`drop_delay_ms` treat 0 as the adapter-default+ * sentinel, so stack garbage in an unset field would become a real delay.+ * Validate layout with `AD_DRAG_PARAMS_SIZE` / `ad_drag_params_size()`.+ *+ * Layout history (adjudicated pre-1.0 breaks; revalidate sizes on upgrade,+ * do not re-report): 0.x grew this struct 40 -> 48 bytes by adding+ * `drop_delay_ms` (which also grew the embedding `AdAction` — see+ * `AD_ACTION_SIZE`), `AdRefEntry` grew to 192 bytes (`AD_REF_ENTRY_SIZE`),+ * `AdActionStep` was added as a public 16-byte struct (`AD_ACTION_STEP_SIZE`),+ * `AdActionResult` grew to 40 bytes (`AD_ACTION_RESULT_SIZE`) to expose action+ * steps, and `AD_POLICY_KIND_PHYSICAL` was renamed to `AD_POLICY_KIND_HEADED`+ * with a stable discriminant and intentionally no compatibility alias.+ */typedef struct AdDragParams {struct AdPoint from;struct AdPoint to;uint64_t duration_ms;+ /* Milliseconds to hold over the destination before releasing, so the drop+ * target activates (macOS). Zero uses the adapter default (500ms). */+ uint64_t drop_delay_ms;} AdDragParams;+#define AD_DRAG_PARAMS_SIZE (sizeof(AdDragParams))+#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L+_Static_assert(sizeof(AdDragParams) == 48, "AdDragParams ABI size changed");+_Static_assert(_Alignof(AdDragParams) == 8, "AdDragParams ABI alignment changed");+#endif++uintptr_t ad_drag_params_size(void);+/*** Action dispatched by `ad_execute_action`.*@@ -207,6 +236,12 @@ typedef struct AdDragParams {* an out-of-range value is rejected with* `AD_RESULT_ERR_INVALID_ARGS` at the boundary. Valid values are the* discriminants of `AdActionKind`.+ *+ * `AdDragParams` is embedded by value, so any growth there grows this+ * struct too. Zero-initialize the whole struct before setting fields and+ * validate layout with `AD_ACTION_SIZE` / `ad_action_size()` — an+ * under-allocated action makes the library read past your buffer, and+ * stack garbage in the embedded `drag` fields becomes a live delay.*/typedef struct AdAction {int32_t kind;@@ -216,6 +251,14 @@ typedef struct AdAction {struct AdDragParams drag;} AdAction;+#define AD_ACTION_SIZE (sizeof(AdAction))+#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L+_Static_assert(sizeof(AdAction) == 96, "AdAction ABI size changed");+_Static_assert(_Alignof(AdAction) == 8, "AdAction ABI alignment changed");+#endif++uintptr_t ad_action_size(void);+typedef struct AdElementState {const char *role;char **states;@@ -223,27 +266,113 @@ typedef struct AdElementState {const char *value;} AdElementState;+#define AD_ELEMENT_STATE_SIZE (sizeof(AdElementState))+#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L+_Static_assert(sizeof(AdElementState) == 32, "AdElementState ABI size changed");+_Static_assert(_Alignof(AdElementState) == 8, "AdElementState ABI alignment changed");+#endif++uintptr_t ad_element_state_size(void);++typedef struct AdActionStep {+ const char *label;+ const char *outcome;+} AdActionStep;++#define AD_ACTION_STEP_SIZE (sizeof(AdActionStep))+#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L+_Static_assert(sizeof(AdActionStep) == 16, "AdActionStep ABI size changed");+_Static_assert(_Alignof(AdActionStep) == 8, "AdActionStep ABI alignment changed");+_Static_assert(offsetof(AdActionStep, label) == 0, "AdActionStep.label offset changed");+_Static_assert(offsetof(AdActionStep, outcome) == 8, "AdActionStep.outcome offset changed");+#endif++uintptr_t ad_action_step_size(void);++/*+ * Result for action calls. `post_state->states` contains `state_count` strings+ * when present. `steps` contains `step_count` activation-chain entries+ * (`label`, `outcome`) when the adapter recorded how the action was attempted.+ * Non-empty owned arrays are additionally null-sentinel terminated by Rust; C+ * callers should use the counts for reads and release the unmodified result via+ * `ad_free_action_result`.+ */typedef struct AdActionResult {const char *action;const char *ref_id;struct AdElementState *post_state;+ struct AdActionStep *steps;+ uint32_t step_count;} AdActionResult;+#define AD_ACTION_RESULT_SIZE (sizeof(AdActionResult))+#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L+_Static_assert(sizeof(AdActionResult) == 40, "AdActionResult ABI size changed");+_Static_assert(_Alignof(AdActionResult) == 8, "AdActionResult ABI alignment changed");+_Static_assert(offsetof(AdActionResult, action) == 0, "AdActionResult.action offset changed");+_Static_assert(offsetof(AdActionResult, ref_id) == 8, "AdActionResult.ref_id offset changed");+_Static_assert(offsetof(AdActionResult, post_state) == 16, "AdActionResult.post_state offset changed");+_Static_assert(offsetof(AdActionResult, steps) == 24, "AdActionResult.steps offset changed");+_Static_assert(offsetof(AdActionResult, step_count) == 32, "AdActionResult.step_count offset changed");+#endif++uintptr_t ad_action_result_size(void);++typedef struct AdRect {+ double x;+ double y;+ double width;+ double height;+} AdRect;+typedef struct AdRefEntry {int32_t pid;const char *role;const char *name;+ const char *value;const char *description;+ const char *const *states;+ uintptr_t state_count;+ const char *const *available_actions;+ uintptr_t available_action_count;+ struct AdRect bounds;+ bool has_bounds;uint64_t bounds_hash;bool has_bounds_hash;+ const char *source_app;+ const char *source_window_id;+ const char *source_window_title;+ int32_t source_surface;+ const char *root_ref;+ bool path_is_absolute;+ const uint32_t *path;+ uintptr_t path_count;} AdRefEntry;-typedef struct AdRect {- double x;- double y;- double width;- double height;-} AdRect;+#define AD_REF_ENTRY_SIZE (sizeof(AdRefEntry))+#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L+_Static_assert(sizeof(AdRefEntry) == 192, "AdRefEntry ABI size changed");+_Static_assert(_Alignof(AdRefEntry) == 8, "AdRefEntry ABI alignment changed");+#endif++/*+ * Per-field input caps enforced when an `AdRefEntry` crosses the boundary+ * (`ad_resolve_element`, `ad_execute_ref_action_with_policy`). Counts above+ * a cap are rejected with `AD_RESULT_ERR_INVALID_ARGS`.+ */+#define AD_MAX_REF_STATES 64+#define AD_MAX_REF_ACTIONS 32+#define AD_MAX_REF_PATH_DEPTH 128++/*+ * Maximum byte length (excluding the NUL terminator) accepted for any C+ * string field on any call. Longer or unterminated strings are rejected+ * with `AD_RESULT_ERR_INVALID_ARGS`. Sized to roughly match the CLI's argv+ * ceiling so payload-bearing calls (clipboard, type) keep CLI parity.+ */+#define AD_MAX_STRING_BYTES 1048576++uintptr_t ad_ref_entry_size(void);typedef struct AdWindowInfo {const char *id;@@ -373,10 +502,15 @@ typedef struct AdWindowOp {} AdWindowOp;/**+ * Low-level native-handle action. This does not perform strict ref+ * re-identification or actionability preflight; callers that want CLI parity+ * should use `ad_execute_ref_action_with_policy`.+ ** # Safety** `adapter` must be a non-null pointer returned by `ad_adapter_create`.- * `handle` must be a non-null pointer to a valid `AdNativeHandle`.+ * `handle` must be a non-null pointer to a valid `AdNativeHandle` produced by+ * the same live adapter. Free the handle before destroying that adapter.* `action` must be a non-null pointer to a valid `AdAction`.* `out` must be a non-null pointer to an `AdActionResult` to write the result into.*/@@ -386,10 +520,15 @@ AdResult ad_execute_action(const struct AdAdapter *adapter,struct AdActionResult *out);/**+ * Low-level native-handle action with explicit interaction policy. This does+ * not perform strict ref re-identification or actionability preflight; callers+ * that want CLI parity should use `ad_execute_ref_action_with_policy`.+ ** # Safety** `adapter` must be a non-null pointer returned by `ad_adapter_create`.- * `handle` must be a non-null pointer to a valid `AdNativeHandle`.+ * `handle` must be a non-null pointer to a valid `AdNativeHandle` produced by+ * the same live adapter. Free the handle before destroying that adapter.* `action` must be a non-null pointer to a valid `AdAction`.* `out` must be a non-null pointer to an `AdActionResult` to write the result into.*/@@ -399,6 +538,23 @@ AdResult ad_execute_action_with_policy(const struct AdAdapter *adapter,int32_t policy,struct AdActionResult *out);+/**+ * Strict ref action path matching CLI semantics: resolve the full ref identity,+ * run actionability preflight, then dispatch using the requested policy.+ *+ * # Safety+ *+ * `adapter` must be a non-null pointer returned by `ad_adapter_create`.+ * `entry` must be a non-null pointer to a valid `AdRefEntry`.+ * `action` must be a non-null pointer to a valid `AdAction`.+ * `out` must be a non-null pointer to an `AdActionResult` to write the result into.+ */+AdResult ad_execute_ref_action_with_policy(const struct AdAdapter *adapter,+ const struct AdRefEntry *entry,+ const struct AdAction *action,+ int32_t policy,+ struct AdActionResult *out);+/*** Releases a handle previously returned by `ad_resolve_element` and* zeroes the caller's struct so accidentally calling this twice is@@ -416,11 +572,13 @@ AdResult ad_execute_action_with_policy(const struct AdAdapter *adapter,* `ad_resolve_element` writes `ptr`. Copying the struct after that* point and calling `ad_free_handle` on either copy is undefined —* there is no way for the library to detect forged non-null pointers.- * Callers that legitimately need a "copy" should re-resolve.+ * Callers that legitimately need a "copy" should re-resolve. The adapter that+ * produced the handle must stay alive until the handle is freed.** # Safety*- * `adapter` must be a non-null pointer returned by `ad_adapter_create`.+ * `adapter` must be a non-null pointer returned by `ad_adapter_create`+ * and must be the same live adapter that produced `handle`.* `handle` must be null or a `*mut AdNativeHandle` previously* populated by `ad_resolve_element`. On return `(*handle).ptr` is* `NULL` so a double-call is a no-op instead of a double-free.@@ -441,8 +599,11 @@ AdResult ad_resolve_element(const struct AdAdapter *adapter,/*** # Safety*- * `result` must be a pointer to an `AdActionResult` previously written by `ad_execute_action`,- * or null. After this call all pointers inside the struct are invalid.+ * `result` must be null or a pointer to an `AdActionResult` previously written+ * by `ad_execute_action`, `ad_execute_action_with_policy`,+ * `ad_execute_ref_action_with_policy`, or `ad_notification_action`. This frees+ * `post_state`, `steps`, and all nested strings. After this call all pointers+ * inside the struct are invalid.*/void ad_free_action_result(struct AdActionResult *result);@@ -476,7 +637,8 @@ AdResult ad_check_permissions(const struct AdAdapter *adapter);/*** Closes the application identified by `id` (bundle id on macOS,* executable path on other platforms). `force = true` skips the- * graceful-shutdown path (equivalent to `kill -9`).+ * graceful-shutdown path, sends SIGTERM, escalates survivors to SIGKILL,+ * and returns success only after termination is verified.** # Safety* `adapter` must be non-null. `id` must be a non-null UTF-8 C string.@@ -580,6 +742,15 @@ const char *ad_last_error_suggestion(void);*/const char *ad_last_error_platform_detail(void);+/**+ * Returns a borrowed JSON string with structured details for the last+ * error, or null if the adapter didn't supply one. Same lifetime rules+ * as `ad_last_error_message`. Details may contain element names, values,+ * and window titles from the user's screen; treat as sensitive+ * diagnostics and avoid routing to shared log surfaces.+ */+const char *ad_last_error_details(void);+/*** Reads the current clipboard text and writes an owned C string into* `*out`. The caller must free the returned pointer with@@ -621,9 +792,12 @@ AdResult ad_clear_clipboard(const struct AdAdapter *adapter);void ad_free_string(char *s);/**- * Synthesizes a mouse drag from `params.from` to `params.to`. When- * `params.duration_ms` is zero the drag is instantaneous; a non-zero- * value asks the platform adapter to interpolate.+ * Synthesizes an explicit physical mouse drag from `params.from` to+ * `params.to`. When `params.duration_ms` is zero the drag is instantaneous;+ * a non-zero value asks the platform adapter to interpolate.+ * `params.drop_delay_ms` holds the item over the destination before releasing+ * so the drop target activates; zero uses the adapter default. Callers that+ * need headless policy enforcement should use ref actions with policy.** # Safety* `adapter` must be a non-null pointer returned by `ad_adapter_create`.@@ -632,9 +806,10 @@ void ad_free_string(char *s);AdResult ad_drag(const struct AdAdapter *adapter, const struct AdDragParams *params);/**- * Dispatches a mouse event (move / down / up / click) at the given- * screen point. Click count is only consulted when `event.kind` is- * `CLICK` (e.g., `click_count == 2` for a double-click).+ * Dispatches an explicit physical mouse event (move / down / up / click)+ * at the given screen point. Click count is only consulted when `event.kind`+ * is `CLICK` (e.g., `click_count == 2` for a double-click). Callers that need+ * headless policy enforcement should use ref actions with policy.** # Safety* `adapter` must be a non-null pointer returned by `ad_adapter_create`.@@ -799,7 +974,8 @@ AdResult ad_find(const struct AdAdapter *adapter,* The returned string must be freed with `ad_free_string`.** # Safety- * `adapter` must be valid. `handle` must be a non-null `AdNativeHandle`.+ * `adapter` must be valid. `handle` must be a non-null `AdNativeHandle`+ * produced by the same live adapter and freed before that adapter is destroyed.* `property` must be a non-null UTF-8 C string. `out` must be a valid* writable `*mut *mut c_char`; it is null-initialized on entry.*/diff --git a/crates/ffi/src/actions/conversion.rs b/crates/ffi/src/actions/conversion.rsindex e04cdccba..786fdc95d 100644--- a/crates/ffi/src/actions/conversion.rs+++ b/crates/ffi/src/actions/conversion.rs@@ -1,9 +1,6 @@use crate::convert::string::c_to_string;use crate::types::{AdAction, AdActionKind, AdDirection, AdKeyCombo, AdModifier};-use agent_desktop_core::action::{- Action, Direction, DragParams as CoreDragParams, KeyCombo as CoreKeyCombo, Modifier,- Point as CorePoint,-};+use agent_desktop_core::action::{Action, Direction, KeyCombo as CoreKeyCombo, Modifier};fn direction_from_c(d: AdDirection) -> Direction {match d {@@ -95,24 +92,7 @@ pub(crate) unsafe fn action_from_c(action: &AdAction) -> Result<Action, &'staticlet combo = key_combo_from_c(&action.key)?;Ok(Action::KeyUp(combo))}- AdActionKind::Drag => {- let params = CoreDragParams {- from: CorePoint {- x: action.drag.from.x,- y: action.drag.from.y,- },- to: CorePoint {- x: action.drag.to.x,- y: action.drag.to.y,- },- duration_ms: if action.drag.duration_ms == 0 {- None- } else {- Some(action.drag.duration_ms)- },- };- Ok(Action::Drag(params))- }+ AdActionKind::Drag => Ok(Action::Drag(action.drag.to_core())),}}}@@ -144,6 +124,7 @@ mod tests {from: AdPoint { x: 0.0, y: 0.0 },to: AdPoint { x: 0.0, y: 0.0 },duration_ms: 0,+ drop_delay_ms: 0,}}diff --git a/crates/ffi/src/actions/execute.rs b/crates/ffi/src/actions/execute.rsindex 1728a70cc..c3a2ee38b 100644--- a/crates/ffi/src/actions/execute.rs+++ b/crates/ffi/src/actions/execute.rs@@ -3,13 +3,14 @@ use crate::actions::conversion::action_from_c;use crate::actions::result::action_result_to_c;use crate::error::{self, AdResult};use crate::ffi_try::trap_panic;-use crate::types::{AdAction, AdActionResult, AdNativeHandle, AdPolicyKind};-use agent_desktop_core::{action::ActionRequest, adapter::NativeHandle};+use crate::types::{AdAction, AdActionResult, AdNativeHandle, AdPolicyKind, AdRefEntry};+use agent_desktop_core::{action::Action, action_request::ActionRequest, adapter::NativeHandle};/// # Safety////// `adapter` must be a non-null pointer returned by `ad_adapter_create`.-/// `handle` must be a non-null pointer to a valid `AdNativeHandle`.+/// `handle` must be a non-null pointer to a valid `AdNativeHandle` produced by+/// the same live adapter. Free the handle before destroying that adapter./// `action` must be a non-null pointer to a valid `AdAction`./// `out` must be a non-null pointer to an `AdActionResult` to write the result into.#[unsafe(no_mangle)]@@ -27,7 +28,8 @@ pub unsafe extern "C" fn ad_execute_action(/// # Safety////// `adapter` must be a non-null pointer returned by `ad_adapter_create`.-/// `handle` must be a non-null pointer to a valid `AdNativeHandle`.+/// `handle` must be a non-null pointer to a valid `AdNativeHandle` produced by+/// the same live adapter. Free the handle before destroying that adapter./// `action` must be a non-null pointer to a valid `AdAction`./// `out` must be a non-null pointer to an `AdActionResult` to write the result into.#[unsafe(no_mangle)]@@ -56,24 +58,14 @@ pub unsafe extern "C" fn ad_execute_action_with_policy());return AdResult::ErrInvalidArgs;}- let action_ref = &*action;- let core_action = match action_from_c(action_ref) {- Ok(a) => a,- Err(msg) => {- error::set_last_error(&agent_desktop_core::error::AdapterError::new(- agent_desktop_core::error::ErrorCode::InvalidArgs,- msg,- ));- return AdResult::ErrInvalidArgs;- }+ let core_action = match decode_action(&*action) {+ Ok(action) => action,+ Err(result) => return result,};let native_handle = NativeHandle::from_ptr(handle_ref.ptr);- let Some(policy) = AdPolicyKind::from_c(policy) else {- error::set_last_error(&agent_desktop_core::error::AdapterError::new(- agent_desktop_core::error::ErrorCode::InvalidArgs,- "invalid policy kind discriminant",- ));- return AdResult::ErrInvalidArgs;+ let policy = match decode_policy(policy) {+ Ok(policy) => policy,+ Err(result) => return result,};let request = action_request(policy, core_action);match adapter.inner.execute_action(&native_handle, request) {@@ -89,13 +81,110 @@ pub unsafe extern "C" fn ad_execute_action_with_policy(})}-fn action_request(- policy: AdPolicyKind,- action: agent_desktop_core::action::Action,-) -> ActionRequest {+/// # Safety+///+/// `adapter` must be a non-null pointer returned by `ad_adapter_create`.+/// `entry` must be a non-null pointer to a valid `AdRefEntry`.+/// `action` must be a non-null pointer to a valid `AdAction`.+/// `out` must be a non-null pointer to an `AdActionResult` to write the result into.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn ad_execute_ref_action_with_policy(+ adapter: *const AdAdapter,+ entry: *const AdRefEntry,+ action: *const AdAction,+ policy: i32,+ out: *mut AdActionResult,+) -> AdResult {+ trap_panic(|| unsafe {+ crate::pointer_guard::guard_non_null!(out, c"out is null");+ *out = std::mem::zeroed();+ if let Err(rc) = crate::main_thread::require_main_thread() {+ return rc;+ }+ crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");+ crate::pointer_guard::guard_non_null!(entry, c"entry is null");+ crate::pointer_guard::guard_non_null!(action, c"action is null");+ let adapter = &*adapter;+ let entry_ref = &*entry;+ let core_entry = match crate::actions::resolve::core_ref_entry_from_ffi(entry_ref) {+ Ok(entry) => entry,+ Err(err) => {+ error::set_last_error(&err);+ return error::last_error_code();+ }+ };+ let core_action = match decode_action(&*action) {+ Ok(action) => action,+ Err(result) => return result,+ };+ let policy = match decode_policy(policy) {+ Ok(policy) => policy,+ Err(result) => return result,+ };+ let request = action_request(policy, core_action);+ match agent_desktop_core::ref_action::execute_entry(+ adapter.inner.as_ref(),+ &core_entry,+ request,+ ) {+ Ok(result) => {+ *out = action_result_to_c(&result);+ AdResult::Ok+ }+ Err(err) => {+ error::set_last_error(&err);+ error::last_error_code()+ }+ }+ })+}++fn decode_action(action: &AdAction) -> Result<Action, AdResult> {+ unsafe { action_from_c(action) }.map_err(|msg| {+ error::set_last_error(&agent_desktop_core::error::AdapterError::new(+ agent_desktop_core::error::ErrorCode::InvalidArgs,+ msg,+ ));+ AdResult::ErrInvalidArgs+ })+}++fn decode_policy(policy: i32) -> Result<AdPolicyKind, AdResult> {+ AdPolicyKind::from_c(policy).ok_or_else(|| {+ error::set_last_error(&agent_desktop_core::error::AdapterError::new(+ agent_desktop_core::error::ErrorCode::InvalidArgs,+ "invalid policy kind discriminant",+ ));+ AdResult::ErrInvalidArgs+ })+}++fn action_request(policy: AdPolicyKind, action: Action) -> ActionRequest {match policy {AdPolicyKind::Headless => ActionRequest::headless(action),AdPolicyKind::FocusFallback => ActionRequest::focus_fallback(action),- AdPolicyKind::Physical => ActionRequest::physical(action),+ AdPolicyKind::Headed => ActionRequest::headed(action),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use agent_desktop_core::{action::Action, interaction_policy::InteractionPolicy};++ #[test]+ fn ffi_policy_kind_maps_to_core_interaction_policy() {+ assert_eq!(+ action_request(AdPolicyKind::Headless, Action::Click).policy,+ InteractionPolicy::headless()+ );+ assert_eq!(+ action_request(AdPolicyKind::FocusFallback, Action::Click).policy,+ InteractionPolicy::focus_fallback()+ );+ assert_eq!(+ action_request(AdPolicyKind::Headed, Action::Click).policy,+ InteractionPolicy::headed()+ );}}diff --git a/crates/ffi/src/actions/native_handle.rs b/crates/ffi/src/actions/native_handle.rsindex d69a331c9..7bf1ba2cd 100644--- a/crates/ffi/src/actions/native_handle.rs+++ b/crates/ffi/src/actions/native_handle.rs@@ -24,7 +24,8 @@ use agent_desktop_core::adapter::NativeHandle;////// # Safety///-/// `adapter` must be a non-null pointer returned by `ad_adapter_create`.+/// `adapter` must be a non-null pointer returned by `ad_adapter_create`+/// and must be the same live adapter that produced `handle`./// `handle` must be null or a `*mut AdNativeHandle` previously/// populated by `ad_resolve_element`. On return `(*handle).ptr` is/// `NULL` so a double-call is a no-op instead of a double-free.@@ -48,9 +49,6 @@ pub unsafe extern "C" fn ad_free_handle(if raw.is_null() {return AdResult::Ok;}- // Zero the caller-visible pointer *before* the platform release- // so a concurrent or accidental double-call through the same- // struct cannot re-enter CFRelease on the same underlying ref.(*handle).ptr = std::ptr::null();let adapter = &*adapter;let native = NativeHandle::from_ptr(raw);diff --git a/crates/ffi/src/actions/resolve.rs b/crates/ffi/src/actions/resolve.rsindex 295358c03..b9a11f6cd 100644--- a/crates/ffi/src/actions/resolve.rs+++ b/crates/ffi/src/actions/resolve.rs@@ -1,5 +1,6 @@use crate::AdAdapter;-use crate::convert::string::{c_to_string, try_c_to_string};+use crate::convert::string::optional_adapter_string;+use crate::convert::surface::snapshot_surface_from_c;use crate::error::{self, AdResult};use crate::ffi_try::trap_panic;use crate::types::{AdNativeHandle, AdRefEntry};@@ -34,7 +35,7 @@ pub unsafe extern "C" fn ad_resolve_element(if let Err(rc) = crate::main_thread::require_main_thread() {return rc;}- match adapter.inner.resolve_element(&core_entry) {+ match adapter.inner.resolve_element_strict(&core_entry) {Ok(handle) => {let handle = ManuallyDrop::new(handle);(*out).ptr = handle.as_raw();@@ -48,40 +49,73 @@ pub unsafe extern "C" fn ad_resolve_element(})}-unsafe fn core_ref_entry_from_ffi(+pub(crate) unsafe fn core_ref_entry_from_ffi(entry: &AdRefEntry,) -> Result<CoreRefEntry, agent_desktop_core::error::AdapterError> {- let role = unsafe { c_to_string(entry.role) }.ok_or_else(|| {+ let role = unsafe { optional_string(entry.role, "role") }?.ok_or_else(|| {agent_desktop_core::error::AdapterError::new(agent_desktop_core::error::ErrorCode::InvalidArgs,- "role is null or invalid UTF-8",+ "role is null",)})?;let name = unsafe { optional_string(entry.name, "name") }?;+ let value = unsafe { optional_string(entry.value, "value") }?;let description = unsafe { optional_string(entry.description, "description") }?;+ let states = unsafe {+ string_array(+ entry.states,+ entry.state_count,+ "states",+ "AD_MAX_REF_STATES",+ crate::types::ref_entry::AD_MAX_REF_STATES,+ )+ }?;+ let available_actions = unsafe {+ string_array(+ entry.available_actions,+ entry.available_action_count,+ "available_actions",+ "AD_MAX_REF_ACTIONS",+ crate::types::ref_entry::AD_MAX_REF_ACTIONS,+ )+ }?;+ let bounds = if entry.has_bounds {+ Some(agent_desktop_core::node::Rect {+ x: entry.bounds.x,+ y: entry.bounds.y,+ width: entry.bounds.width,+ height: entry.bounds.height,+ })+ } else {+ None+ };let bounds_hash = if entry.has_bounds_hash {Some(entry.bounds_hash)} else {None};+ let source_surface = snapshot_surface_from_c(entry.source_surface, "source_surface")?;+ let path = unsafe { ref_path(entry.path, entry.path_count)? };Ok(CoreRefEntry {pid: entry.pid,role,name,- value: None,+ value,description,- states: vec![],- bounds: None,+ states,+ bounds,bounds_hash,- available_actions: vec![],- source_app: None,- source_window_id: None,- source_window_title: None,- source_surface: agent_desktop_core::adapter::SnapshotSurface::Window,- root_ref: None,- path_is_absolute: false,- path: smallvec::SmallVec::new(),+ available_actions,+ source_app: unsafe { optional_string(entry.source_app, "source_app") }?,+ source_window_id: unsafe { optional_string(entry.source_window_id, "source_window_id") }?,+ source_window_title: unsafe {+ optional_string(entry.source_window_title, "source_window_title")+ }?,+ source_surface,+ root_ref: unsafe { optional_string(entry.root_ref, "root_ref") }?,+ path_is_absolute: entry.path_is_absolute,+ path,})}@@ -89,12 +123,79 @@ unsafe fn optional_string(ptr: *const std::os::raw::c_char,field: &str,) -> Result<Option<String>, agent_desktop_core::error::AdapterError> {- unsafe { try_c_to_string(ptr) }.map_err(|()| {- agent_desktop_core::error::AdapterError::new(+ optional_adapter_string(ptr, field)+}++fn check_array_len(+ len: usize,+ is_null: bool,+ field: &str,+ constant: &str,+ max: usize,+) -> Result<(), agent_desktop_core::error::AdapterError> {+ if len > max {+ return Err(agent_desktop_core::error::AdapterError::new(agent_desktop_core::error::ErrorCode::InvalidArgs,- format!("{field} is not valid UTF-8"),- )- })+ format!("{field} count {len} exceeds {constant} ({max})"),+ ));+ }+ if is_null {+ return Err(agent_desktop_core::error::AdapterError::new(+ agent_desktop_core::error::ErrorCode::InvalidArgs,+ format!("{field} count is nonzero but pointer is null"),+ ));+ }+ Ok(())+}++unsafe fn string_array(+ ptr: *const *const std::os::raw::c_char,+ len: usize,+ field: &str,+ constant: &str,+ max: usize,+) -> Result<Vec<String>, agent_desktop_core::error::AdapterError> {+ if len == 0 {+ return Ok(Vec::new());+ }+ check_array_len(len, ptr.is_null(), field, constant, max)?;+ let items = unsafe { std::slice::from_raw_parts(ptr, len) };+ items+ .iter()+ .enumerate()+ .map(|(index, item)| {+ let element = format!("{field}[{index}]");+ unsafe { optional_string(*item, &element) }?.ok_or_else(|| {+ agent_desktop_core::error::AdapterError::new(+ agent_desktop_core::error::ErrorCode::InvalidArgs,+ format!("{element} is null"),+ )+ })+ })+ .collect()+}++unsafe fn ref_path(+ ptr: *const u32,+ len: usize,+) -> Result<smallvec::SmallVec<[usize; 8]>, agent_desktop_core::error::AdapterError> {+ if len == 0 {+ return Ok(smallvec::SmallVec::new());+ }+ check_array_len(+ len,+ ptr.is_null(),+ "path",+ "AD_MAX_REF_PATH_DEPTH",+ crate::types::ref_entry::AD_MAX_REF_PATH_DEPTH,+ )?;+ let mut path = smallvec::SmallVec::new();+ path.extend(+ unsafe { std::slice::from_raw_parts(ptr, len) }+ .iter()+ .map(|item| *item as usize),+ );+ Ok(path)}#[cfg(test)]diff --git a/crates/ffi/src/actions/resolve_tests.rs b/crates/ffi/src/actions/resolve_tests.rsindex ef981ccc0..d96084835 100644--- a/crates/ffi/src/actions/resolve_tests.rs+++ b/crates/ffi/src/actions/resolve_tests.rs@@ -2,44 +2,207 @@ use super::*;use agent_desktop_core::error::ErrorCode;use std::ffi::CString;+fn test_ref_entry() -> AdRefEntry {+ AdRefEntry {+ pid: 0,+ role: std::ptr::null(),+ name: std::ptr::null(),+ value: std::ptr::null(),+ description: std::ptr::null(),+ states: std::ptr::null(),+ state_count: 0,+ available_actions: std::ptr::null(),+ available_action_count: 0,+ bounds: crate::types::AdRect {+ x: 0.0,+ y: 0.0,+ width: 0.0,+ height: 0.0,+ },+ has_bounds: false,+ bounds_hash: 0,+ has_bounds_hash: false,+ source_app: std::ptr::null(),+ source_window_id: std::ptr::null(),+ source_window_title: std::ptr::null(),+ source_surface: 0,+ root_ref: std::ptr::null(),+ path_is_absolute: false,+ path: std::ptr::null(),+ path_count: 0,+ }+}+#[test]fn ffi_ref_entry_preserves_description_identity() {let role = CString::new("button").unwrap();let name = CString::new("Primary").unwrap();+ let value = CString::new("On").unwrap();let description = CString::new("Insert Shape").unwrap();- let entry = AdRefEntry {- pid: 42,- role: role.as_ptr(),- name: name.as_ptr(),- description: description.as_ptr(),- bounds_hash: 123,- has_bounds_hash: true,+ let state = CString::new("focused").unwrap();+ let action = CString::new("Click").unwrap();+ let source_app = CString::new("Finder").unwrap();+ let window_id = CString::new("w-1").unwrap();+ let window_title = CString::new("Documents").unwrap();+ let root_ref = CString::new("@e1").unwrap();+ let states = [state.as_ptr()];+ let actions = [action.as_ptr()];+ let path = [1_u32, 2, 3];+ let mut entry = test_ref_entry();+ entry.pid = 42;+ entry.role = role.as_ptr();+ entry.name = name.as_ptr();+ entry.value = value.as_ptr();+ entry.description = description.as_ptr();+ entry.states = states.as_ptr();+ entry.state_count = states.len();+ entry.available_actions = actions.as_ptr();+ entry.available_action_count = actions.len();+ entry.bounds = crate::types::AdRect {+ x: 1.0,+ y: 2.0,+ width: 3.0,+ height: 4.0,};+ entry.has_bounds = true;+ entry.bounds_hash = 123;+ entry.has_bounds_hash = true;+ entry.source_app = source_app.as_ptr();+ entry.source_window_id = window_id.as_ptr();+ entry.source_window_title = window_title.as_ptr();+ entry.source_surface = 5;+ entry.root_ref = root_ref.as_ptr();+ entry.path_is_absolute = true;+ entry.path = path.as_ptr();+ entry.path_count = path.len();let core_entry = unsafe { core_ref_entry_from_ffi(&entry) }.unwrap();assert_eq!(core_entry.pid, 42);assert_eq!(core_entry.role, "button");assert_eq!(core_entry.name.as_deref(), Some("Primary"));+ assert_eq!(core_entry.value.as_deref(), Some("On"));assert_eq!(core_entry.description.as_deref(), Some("Insert Shape"));+ assert_eq!(core_entry.states, ["focused"]);+ assert_eq!(core_entry.available_actions, ["Click"]);+ assert_eq!(core_entry.bounds.unwrap().width, 3.0);assert_eq!(core_entry.bounds_hash, Some(123));+ assert_eq!(core_entry.source_app.as_deref(), Some("Finder"));+ assert_eq!(core_entry.source_window_id.as_deref(), Some("w-1"));+ assert_eq!(core_entry.source_window_title.as_deref(), Some("Documents"));+ assert_eq!(+ core_entry.source_surface,+ agent_desktop_core::adapter::SnapshotSurface::Popover+ );+ assert_eq!(core_entry.root_ref.as_deref(), Some("@e1"));+ assert!(core_entry.path_is_absolute);+ assert_eq!(core_entry.path.as_slice(), &[1, 2, 3]);}#[test]fn ffi_ref_entry_rejects_invalid_description_identity() {let role = CString::new("button").unwrap();let bad_description: [u8; 2] = [0xC3, 0x00];- let entry = AdRefEntry {- pid: 42,- role: role.as_ptr(),- name: std::ptr::null(),- description: bad_description.as_ptr().cast(),- bounds_hash: 0,- has_bounds_hash: false,- };+ let mut entry = test_ref_entry();+ entry.pid = 42;+ entry.role = role.as_ptr();+ entry.description = bad_description.as_ptr().cast();let err = unsafe { core_ref_entry_from_ffi(&entry) }.unwrap_err();assert_eq!(err.code, ErrorCode::InvalidArgs);assert_eq!(err.message, "description is not valid UTF-8");}++#[test]+fn ffi_ref_entry_rejects_invalid_array_pointer() {+ let role = CString::new("button").unwrap();+ let mut entry = test_ref_entry();+ entry.role = role.as_ptr();+ entry.state_count = 1;++ let err = unsafe { core_ref_entry_from_ffi(&entry) }.unwrap_err();++ assert_eq!(err.code, ErrorCode::InvalidArgs);+ assert_eq!(err.message, "states count is nonzero but pointer is null");+}++#[test]+fn ffi_ref_entry_rejects_unknown_surface() {+ let role = CString::new("button").unwrap();+ let mut entry = test_ref_entry();+ entry.role = role.as_ptr();+ entry.source_surface = 99;++ let err = unsafe { core_ref_entry_from_ffi(&entry) }.unwrap_err();++ assert_eq!(err.code, ErrorCode::InvalidArgs);+ assert_eq!(err.message, "invalid source_surface discriminant");+}++fn string_array_of(len: usize) -> (Vec<CString>, Vec<*const std::os::raw::c_char>) {+ let owned: Vec<CString> = (0..len)+ .map(|i| CString::new(format!("item-{i}")).unwrap())+ .collect();+ let ptrs = owned.iter().map(|s| s.as_ptr()).collect();+ (owned, ptrs)+}++#[test]+fn ffi_ref_entry_rejects_oversized_state_count() {+ let role = CString::new("button").unwrap();+ let (_owned, ptrs) = string_array_of(crate::types::ref_entry::AD_MAX_REF_STATES + 1);+ let mut entry = test_ref_entry();+ entry.role = role.as_ptr();+ entry.states = ptrs.as_ptr();+ entry.state_count = ptrs.len();++ let err = unsafe { core_ref_entry_from_ffi(&entry) }.unwrap_err();++ assert_eq!(err.code, ErrorCode::InvalidArgs);+ assert!(err.message.contains("AD_MAX_REF_STATES"));+}++#[test]+fn ffi_ref_entry_rejects_oversized_action_count() {+ let role = CString::new("button").unwrap();+ let (_owned, ptrs) = string_array_of(crate::types::ref_entry::AD_MAX_REF_ACTIONS + 1);+ let mut entry = test_ref_entry();+ entry.role = role.as_ptr();+ entry.available_actions = ptrs.as_ptr();+ entry.available_action_count = ptrs.len();++ let err = unsafe { core_ref_entry_from_ffi(&entry) }.unwrap_err();++ assert_eq!(err.code, ErrorCode::InvalidArgs);+ assert!(err.message.contains("AD_MAX_REF_ACTIONS"));+}++#[test]+fn ffi_ref_entry_rejects_oversized_path_count() {+ let role = CString::new("button").unwrap();+ let path: Vec<u32> = (0..(crate::types::ref_entry::AD_MAX_REF_PATH_DEPTH as u32 + 1)).collect();+ let mut entry = test_ref_entry();+ entry.role = role.as_ptr();+ entry.path = path.as_ptr();+ entry.path_count = path.len();++ let err = unsafe { core_ref_entry_from_ffi(&entry) }.unwrap_err();++ assert_eq!(err.code, ErrorCode::InvalidArgs);+ assert!(err.message.contains("AD_MAX_REF_PATH_DEPTH"));+}++#[test]+fn ffi_ref_entry_rejects_unterminated_name_within_byte_cap() {+ let role = CString::new("button").unwrap();+ let unterminated = vec![b'a'; crate::convert::string::MAX_C_STRING_BYTES + 1];+ let mut entry = test_ref_entry();+ entry.role = role.as_ptr();+ entry.name = unterminated.as_ptr().cast();++ let err = unsafe { core_ref_entry_from_ffi(&entry) }.unwrap_err();++ assert_eq!(err.code, ErrorCode::InvalidArgs);+ assert!(err.message.contains("name exceeds AD_MAX_STRING_BYTES"));+}diff --git a/crates/ffi/src/actions/result.rs b/crates/ffi/src/actions/result.rsindex a0e5e8b8d..1941b5eba 100644--- a/crates/ffi/src/actions/result.rs+++ b/crates/ffi/src/actions/result.rs@@ -1,11 +1,11 @@use crate::convert::string::{free_c_string, opt_string_to_c, string_to_c_lossy};-use crate::types::{AdActionResult, AdElementState};-use agent_desktop_core::action::ActionResult as CoreActionResult;+use crate::types::{AdActionResult, AdElementState, action_step::AdActionStep};+use agent_desktop_core::action_result::ActionResult as CoreActionResult;+use agent_desktop_core::action_step_outcome::ActionStepOutcome;use std::ptr;pub(crate) fn action_result_to_c(r: &CoreActionResult) -> AdActionResult {let action = string_to_c_lossy(&r.action);- let ref_id = opt_string_to_c(r.ref_id.as_deref());let post_state = match &r.post_state {None => ptr::null_mut(),Some(state) => {@@ -15,8 +15,9 @@ pub(crate) fn action_result_to_c(r: &CoreActionResult) -> AdActionResult {let states = if state.states.is_empty() {ptr::null_mut()} else {- let ptrs: Vec<*mut std::os::raw::c_char> =+ let mut ptrs: Vec<*mut std::os::raw::c_char> =state.states.iter().map(|s| string_to_c_lossy(s)).collect();+ ptrs.push(ptr::null_mut());let mut boxed = ptrs.into_boxed_slice();let raw = boxed.as_mut_ptr();std::mem::forget(boxed);@@ -33,15 +34,20 @@ pub(crate) fn action_result_to_c(r: &CoreActionResult) -> AdActionResult {};AdActionResult {action,- ref_id,+ ref_id: ptr::null(),post_state,+ steps: action_steps_to_c(r),+ step_count: r.steps.len() as u32,}}/// # Safety///-/// `result` must be a pointer to an `AdActionResult` previously written by `ad_execute_action`,-/// or null. After this call all pointers inside the struct are invalid.+/// `result` must be null or a pointer to an `AdActionResult` previously written+/// by `ad_execute_action`, `ad_execute_action_with_policy`,+/// `ad_execute_ref_action_with_policy`, or `ad_notification_action`. This frees+/// `post_state`, `steps`, and all nested strings. After this call all pointers+/// inside the struct are invalid.#[unsafe(no_mangle)]pub unsafe extern "C" fn ad_free_action_result(result: *mut AdActionResult) {crate::ffi_try::trap_panic_void(|| unsafe {@@ -51,51 +57,122 @@ pub unsafe extern "C" fn ad_free_action_result(result: *mut AdActionResult) {let r = &mut *result;free_c_string(r.action as *mut _);free_c_string(r.ref_id as *mut _);+ if !r.steps.is_null() {+ free_step_array(r.steps);+ }if !r.post_state.is_null() {let state = &mut *r.post_state;free_c_string(state.role as *mut _);free_c_string(state.value as *mut _);- if !state.states.is_null() && state.state_count > 0 {- let slice =- std::slice::from_raw_parts_mut(state.states, state.state_count as usize);- for ptr in slice.iter() {- free_c_string(*ptr);- }- drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut(- state.states,- state.state_count as usize,- )));+ if !state.states.is_null() {+ free_state_array(state.states);}drop(Box::from_raw(r.post_state));r.post_state = ptr::null_mut();}r.action = ptr::null();r.ref_id = ptr::null();+ r.steps = ptr::null_mut();+ r.step_count = 0;})}+fn action_steps_to_c(r: &CoreActionResult) -> *mut AdActionStep {+ if r.steps.is_empty() {+ return ptr::null_mut();+ }+ let mut steps = r+ .steps+ .iter()+ .map(|step| AdActionStep {+ label: string_to_c_lossy(step.label()),+ outcome: string_to_c_lossy(step_outcome_name(&step.outcome)),+ })+ .collect::<Vec<_>>();+ steps.push(step_sentinel());+ let mut boxed = steps.into_boxed_slice();+ let raw = boxed.as_mut_ptr();+ std::mem::forget(boxed);+ raw+}++fn step_outcome_name(outcome: &ActionStepOutcome) -> &'static str {+ match outcome {+ ActionStepOutcome::Attempted => "attempted",+ ActionStepOutcome::Skipped => "skipped",+ ActionStepOutcome::Succeeded => "succeeded",+ }+}++fn step_sentinel() -> AdActionStep {+ AdActionStep {+ label: ptr::null(),+ outcome: ptr::null(),+ }+}++unsafe fn free_state_array(states: *mut *mut std::os::raw::c_char) {+ unsafe {+ let mut len = 0;+ while !(*states.add(len)).is_null() {+ len += 1;+ }+ for index in 0..len {+ free_c_string(*states.add(index));+ }+ drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut(+ states,+ len + 1,+ )));+ }+}++unsafe fn free_step_array(steps: *mut AdActionStep) {+ unsafe {+ let mut len = 0;+ while !step_is_sentinel(&*steps.add(len)) {+ len += 1;+ }+ for index in 0..len {+ let step = &mut *steps.add(index);+ free_c_string(step.label as *mut _);+ free_c_string(step.outcome as *mut _);+ }+ drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut(+ steps,+ len + 1,+ )));+ }+}++fn step_is_sentinel(step: &AdActionStep) -> bool {+ step.label.is_null() && step.outcome.is_null()+}+#[cfg(test)]mod tests {use super::*;use crate::convert::string::c_to_string;- use agent_desktop_core::action::ElementState;+ use agent_desktop_core::element_state::ElementState;#[test]fn test_action_result_to_c_with_state() {let core_result = CoreActionResult {action: "click".to_owned(),- ref_id: Some("@e3".to_owned()),post_state: Some(ElementState {role: "button".to_owned(),states: vec!["focused".to_owned(), "enabled".to_owned()],value: Some("OK".to_owned()),}),+ steps: Vec::new(),};let c_result = action_result_to_c(&core_result);unsafe {assert_eq!(c_to_string(c_result.action).as_deref(), Some("click"));- assert_eq!(c_to_string(c_result.ref_id).as_deref(), Some("@e3"));+ assert!(c_result.ref_id.is_null());assert!(!c_result.post_state.is_null());+ assert!(c_result.steps.is_null());+ assert_eq!(c_result.step_count, 0);let state = &*c_result.post_state;assert_eq!(c_to_string(state.role).as_deref(), Some("button"));assert_eq!(c_to_string(state.value).as_deref(), Some("OK"));@@ -105,6 +182,84 @@ mod tests {unsafe { ad_free_action_result(&mut c_result) };}+ #[test]+ fn free_action_result_ignores_mutated_counts() {+ let post_state = Box::new(AdElementState {+ role: crate::convert::string::string_to_c_lossy("button"),+ states: state_array(&["focused"]),+ state_count: u32::MAX,+ value: ptr::null(),+ });+ let mut steps = vec![+ AdActionStep {+ label: crate::convert::string::string_to_c_lossy("AXPress"),+ outcome: crate::convert::string::string_to_c_lossy("succeeded"),+ },+ step_sentinel(),+ ]+ .into_boxed_slice();+ let mut c_result = AdActionResult {+ action: crate::convert::string::string_to_c_lossy("click"),+ ref_id: ptr::null(),+ post_state: Box::into_raw(post_state),+ steps: steps.as_mut_ptr(),+ step_count: u32::MAX,+ };+ std::mem::forget(steps);+ unsafe { ad_free_action_result(&mut c_result) };++ assert!(c_result.post_state.is_null());+ assert!(c_result.steps.is_null());+ assert_eq!(c_result.step_count, 0);+ }++ #[test]+ fn action_result_to_c_preserves_steps() {+ let core_result = CoreActionResult::new("click").with_steps(vec![+ agent_desktop_core::action_step::ActionStep::attempted("AXScrollToVisible"),+ agent_desktop_core::action_step::ActionStep::succeeded("AXPress"),+ ]);++ let mut c_result = action_result_to_c(&core_result);++ unsafe {+ assert_eq!(c_result.step_count, 2);+ assert!(!c_result.steps.is_null());+ assert_eq!(+ c_to_string((*c_result.steps.add(0)).label).as_deref(),+ Some("AXScrollToVisible")+ );+ assert_eq!(+ c_to_string((*c_result.steps.add(0)).outcome).as_deref(),+ Some("attempted")+ );+ assert_eq!(+ c_to_string((*c_result.steps.add(1)).label).as_deref(),+ Some("AXPress")+ );+ assert_eq!(+ c_to_string((*c_result.steps.add(1)).outcome).as_deref(),+ Some("succeeded")+ );+ }++ unsafe { ad_free_action_result(&mut c_result) };+ assert!(c_result.steps.is_null());+ assert_eq!(c_result.step_count, 0);+ }++ fn state_array(states: &[&str]) -> *mut *mut std::os::raw::c_char {+ let mut ptrs: Vec<*mut std::os::raw::c_char> = states+ .iter()+ .map(|state| crate::convert::string::string_to_c_lossy(state))+ .collect();+ ptrs.push(ptr::null_mut());+ let mut boxed = ptrs.into_boxed_slice();+ let raw = boxed.as_mut_ptr();+ std::mem::forget(boxed);+ raw+ }+#[test]fn test_free_null_action_result() {unsafe { ad_free_action_result(ptr::null_mut()) };diff --git a/crates/ffi/src/apps/close.rs b/crates/ffi/src/apps/close.rsindex 89fc76228..4cb0c6b2d 100644--- a/crates/ffi/src/apps/close.rs+++ b/crates/ffi/src/apps/close.rs@@ -1,12 +1,16 @@use crate::AdAdapter;-use crate::convert::string::c_to_string;use crate::error::{AdResult, set_last_error};use crate::ffi_try::trap_panic;use std::os::raw::c_char;/// Closes the application identified by `id` (bundle id on macOS,/// executable path on other platforms). `force = true` skips the-/// graceful-shutdown path (equivalent to `kill -9`).+/// graceful-shutdown path, terminates matching app processes, and escalates+/// survivors when the platform supports it. Session-critical+/// processes (loginwindow, WindowServer, Dock, Finder, launchd) are+/// refused with `AD_RESULT_ERR_INVALID_ARGS` — the protected-process+/// guard is enforced inside the adapter, so FFI and CLI behave+/// identically.////// # Safety/// `adapter` must be non-null. `id` must be a non-null UTF-8 C string.@@ -21,17 +25,14 @@ pub unsafe extern "C" fn ad_close_app(return rc;}crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");- let adapter = &*adapter;- let id_str = match c_to_string(id) {- Some(s) => s,- None => {- set_last_error(&agent_desktop_core::error::AdapterError::new(- agent_desktop_core::error::ErrorCode::InvalidArgs,- "app id is null or invalid UTF-8",- ));- return AdResult::ErrInvalidArgs;+ let id_str = match super::decode_app_id(id) {+ Ok(id) => id,+ Err(err) => {+ set_last_error(&err);+ return crate::error::last_error_code();}};+ let adapter = &*adapter;match adapter.inner.close_app(&id_str, force) {Ok(()) => AdResult::Ok,diff --git a/crates/ffi/src/apps/launch.rs b/crates/ffi/src/apps/launch.rsindex 7e03927f4..3977274a9 100644--- a/crates/ffi/src/apps/launch.rs+++ b/crates/ffi/src/apps/launch.rs@@ -1,5 +1,4 @@use crate::AdAdapter;-use crate::convert::string::c_to_string;use crate::convert::window::window_info_to_c;use crate::error::{AdResult, set_last_error};use crate::ffi_try::trap_panic;@@ -33,14 +32,11 @@ pub unsafe extern "C" fn ad_launch_app(return rc;}crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");- let id_str = match c_to_string(id) {- Some(s) => s,- None => {- set_last_error(&agent_desktop_core::error::AdapterError::new(- agent_desktop_core::error::ErrorCode::InvalidArgs,- "app id is null or invalid UTF-8",- ));- return AdResult::ErrInvalidArgs;+ let id_str = match super::decode_app_id(id) {+ Ok(id) => id,+ Err(err) => {+ set_last_error(&err);+ return crate::error::last_error_code();}};diff --git a/crates/ffi/src/apps/mod.rs b/crates/ffi/src/apps/mod.rsindex 34893d1ff..214338fbd 100644--- a/crates/ffi/src/apps/mod.rs+++ b/crates/ffi/src/apps/mod.rs@@ -1,3 +1,51 @@pub(crate) mod close;pub(crate) mod launch;pub(crate) mod list;++use agent_desktop_core::error::AdapterError;+use std::os::raw::c_char;++fn decode_app_id(id: *const c_char) -> Result<String, AdapterError> {+ crate::convert::string::required_adapter_string(id, "app id")+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::convert::string::{MAX_C_STRING_BYTES, string_to_c};++ #[test]+ fn app_id_rejects_null() {+ let err = decode_app_id(std::ptr::null()).unwrap_err();++ assert_eq!(err.message, "app id is null");+ }++ #[test]+ fn app_id_rejects_invalid_utf8() {+ let bad = [0xC3_u8, 0];+ let err = decode_app_id(bad.as_ptr().cast()).unwrap_err();++ assert_eq!(err.message, "app id is not valid UTF-8");+ }++ #[test]+ fn app_id_rejects_overlong_input() {+ let bytes = vec![b'a'; MAX_C_STRING_BYTES + 1];+ let err = decode_app_id(bytes.as_ptr().cast()).unwrap_err();++ assert!(+ err.message+ .starts_with("app id exceeds AD_MAX_STRING_BYTES")+ );+ }++ #[test]+ fn app_id_accepts_valid_utf8() {+ let c = string_to_c("TextEdit");+ let decoded = decode_app_id(c).unwrap();++ assert_eq!(decoded, "TextEdit");+ unsafe { crate::convert::string::free_c_string(c) };+ }+}diff --git a/crates/ffi/src/convert/string.rs b/crates/ffi/src/convert/string.rsindex b323d3170..73afacc0f 100644--- a/crates/ffi/src/convert/string.rs+++ b/crates/ffi/src/convert/string.rs@@ -1,7 +1,9 @@-use std::ffi::{CStr, CString};+use std::ffi::CString;use std::os::raw::c_char;use std::ptr;+use agent_desktop_core::error::{AdapterError, ErrorCode};+pub(crate) fn string_to_c(s: &str) -> *mut c_char {match CString::new(s) {Ok(cs) => cs.into_raw(),@@ -43,52 +45,101 @@ pub(crate) unsafe fn free_c_string(ptr: *mut c_char) {}}-pub(crate) unsafe fn c_to_string(ptr: *const c_char) -> Option<String> {- unsafe {- if ptr.is_null() {- return None;+/// Maximum byte length (excluding the NUL terminator) accepted for any+/// foreign C string. Bounds both the terminator scan and the resulting+/// allocation, so a missing NUL or a hostile caller cannot walk arbitrary+/// memory into a `String`. Sized to roughly match the CLI's argv ceiling so+/// payload-bearing calls (clipboard-set, type) keep CLI parity rather than+/// being cut off at a ref-field-sized cap. Mirrored in the header as+/// `AD_MAX_STRING_BYTES`.+pub const MAX_C_STRING_BYTES: usize = 1024 * 1024;++pub(crate) enum CStrDecodeError {+ NotUtf8,+ TooLong,+}++impl CStrDecodeError {+ pub(crate) fn describe(&self, field: &str) -> String {+ match self {+ Self::NotUtf8 => format!("{field} is not valid UTF-8"),+ Self::TooLong => {+ format!("{field} exceeds AD_MAX_STRING_BYTES ({MAX_C_STRING_BYTES} bytes)")+ }}- CStr::from_ptr(ptr).to_str().ok().map(str::to_owned)}}+unsafe fn bounded_c_bytes<'a>(ptr: *const c_char) -> Result<&'a [u8], CStrDecodeError> {+ for len in 0..=MAX_C_STRING_BYTES {+ if unsafe { *ptr.add(len) } == 0 {+ return Ok(unsafe { std::slice::from_raw_parts(ptr.cast::<u8>(), len) });+ }+ }+ Err(CStrDecodeError::TooLong)+}++pub(crate) unsafe fn c_to_string(ptr: *const c_char) -> Option<String> {+ unsafe { try_c_to_string(ptr) }.ok().flatten()+}+/// Tri-state decode of a foreign C string used for optional filter/// fields where conflating null with invalid UTF-8 would silently widen/// an operation (e.g. treat "bad bytes" as "no filter").////// - `Ok(None)` — pointer is null. Caller should treat as "filter/// absent".-/// - `Ok(Some(s))` — pointer is non-null and decodes as valid UTF-8.-/// - `Err(())` — pointer is non-null but the bytes are not UTF-8.-/// Caller should surface `AD_RESULT_ERR_INVALID_ARGS` instead of+/// - `Ok(Some(s))` — pointer is non-null, NUL-terminated within+/// `MAX_C_STRING_BYTES`, and decodes as valid UTF-8.+/// - `Err(e)` — pointer is non-null but the bytes are not UTF-8 or no+/// terminator was found within the byte cap. Caller should surface+/// `AD_RESULT_ERR_INVALID_ARGS` (via `e.describe(field)`) instead of/// treating this as missing.////// # Safety-/// `ptr` must be null or a NUL-terminated C string.-pub(crate) unsafe fn try_c_to_string(ptr: *const c_char) -> Result<Option<String>, ()> {- unsafe {- if ptr.is_null() {- return Ok(None);- }- match CStr::from_ptr(ptr).to_str() {- Ok(s) => Ok(Some(s.to_owned())),- Err(_) => Err(()),- }+/// `ptr` must be null or point to readable memory that is NUL-terminated+/// within `MAX_C_STRING_BYTES + 1` bytes.+pub(crate) unsafe fn try_c_to_string(+ ptr: *const c_char,+) -> Result<Option<String>, CStrDecodeError> {+ if ptr.is_null() {+ return Ok(None);}+ let bytes = unsafe { bounded_c_bytes(ptr) }?;+ std::str::from_utf8(bytes)+ .map(|s| Some(s.to_owned()))+ .map_err(|_| CStrDecodeError::NotUtf8)+}++pub(crate) fn optional_adapter_string(+ ptr: *const c_char,+ field: &str,+) -> Result<Option<String>, AdapterError> {+ unsafe { try_c_to_string(ptr) }+ .map_err(|err| AdapterError::new(ErrorCode::InvalidArgs, err.describe(field)))+}++pub(crate) fn required_adapter_string(+ ptr: *const c_char,+ field: &str,+) -> Result<String, AdapterError> {+ optional_adapter_string(ptr, field)?+ .ok_or_else(|| AdapterError::new(ErrorCode::InvalidArgs, format!("{field} is null")))}/// Decode an optional filter string, short-circuiting the enclosing/// `AdResult`-returning fn with `AD_RESULT_ERR_INVALID_ARGS` (and a-/// tailored last-error diagnostic) when the pointer is non-null but-/// the bytes are not UTF-8. Null → `None` (treated as "no filter").+/// tailored last-error diagnostic) when the pointer is non-null but the+/// bytes are not UTF-8 or exceed the byte cap. Null → `None` (treated as+/// "no filter").macro_rules! decode_optional_filter {($ptr:expr, $label:expr) => {{match $crate::convert::string::try_c_to_string($ptr) {Ok(value) => value,- Err(()) => {+ Err(err) => {$crate::error::set_last_error(&agent_desktop_core::error::AdapterError::new(agent_desktop_core::error::ErrorCode::InvalidArgs,- concat!($label, " is not valid UTF-8"),+ err.describe($label),));return $crate::error::AdResult::ErrInvalidArgs;}@@ -169,6 +220,37 @@ mod tests {fn try_c_to_string_invalid_utf8_is_err() {let bad: [u8; 3] = [0xC3, 0xFF, 0x00];let result = unsafe { try_c_to_string(bad.as_ptr() as *const c_char) };- assert!(matches!(result, Err(())));+ assert!(matches!(result, Err(CStrDecodeError::NotUtf8)));+ }++ #[test]+ fn try_c_to_string_caps_unterminated_input() {+ let unterminated = vec![b'a'; MAX_C_STRING_BYTES + 1];+ let result = unsafe { try_c_to_string(unterminated.as_ptr() as *const c_char) };+ assert!(matches!(result, Err(CStrDecodeError::TooLong)));+ }++ #[test]+ fn try_c_to_string_accepts_exact_cap_length() {+ let mut max_len = vec![b'a'; MAX_C_STRING_BYTES];+ max_len.push(0);+ let result = unsafe { try_c_to_string(max_len.as_ptr() as *const c_char) };+ assert_eq!(+ result.ok().flatten().map(|s| s.len()),+ Some(MAX_C_STRING_BYTES)+ );+ }++ #[test]+ fn decode_error_messages_name_the_field_and_cap() {+ assert_eq!(+ CStrDecodeError::NotUtf8.describe("role"),+ "role is not valid UTF-8"+ );+ assert!(+ CStrDecodeError::TooLong+ .describe("name")+ .starts_with("name exceeds AD_MAX_STRING_BYTES")+ );}}diff --git a/crates/ffi/src/convert/surface.rs b/crates/ffi/src/convert/surface.rsindex 6fe1855e2..a017cc441 100644--- a/crates/ffi/src/convert/surface.rs+++ b/crates/ffi/src/convert/surface.rs@@ -1,6 +1,10 @@use crate::convert::string::{free_c_string, opt_string_to_c, string_to_c_lossy};-use crate::types::AdSurfaceInfo;-use agent_desktop_core::node::SurfaceInfo;+use crate::types::{AdSnapshotSurface, AdSurfaceInfo};+use agent_desktop_core::{+ adapter::SnapshotSurface,+ error::{AdapterError, ErrorCode},+ node::SurfaceInfo,+};use std::os::raw::c_char;use std::ptr;@@ -12,6 +16,32 @@ pub(crate) fn surface_info_to_c(s: &SurfaceInfo) -> AdSurfaceInfo {}}+pub(crate) fn snapshot_surface_to_core(surface: AdSnapshotSurface) -> SnapshotSurface {+ match surface {+ AdSnapshotSurface::Window => SnapshotSurface::Window,+ AdSnapshotSurface::Focused => SnapshotSurface::Focused,+ AdSnapshotSurface::Menu => SnapshotSurface::Menu,+ AdSnapshotSurface::Menubar => SnapshotSurface::Menubar,+ AdSnapshotSurface::Sheet => SnapshotSurface::Sheet,+ AdSnapshotSurface::Popover => SnapshotSurface::Popover,+ AdSnapshotSurface::Alert => SnapshotSurface::Alert,+ }+}++pub(crate) fn snapshot_surface_from_c(+ raw: i32,+ field: &str,+) -> Result<SnapshotSurface, AdapterError> {+ AdSnapshotSurface::from_c(raw)+ .map(snapshot_surface_to_core)+ .ok_or_else(|| {+ AdapterError::new(+ ErrorCode::InvalidArgs,+ format!("invalid {field} discriminant"),+ )+ })+}+pub(crate) unsafe fn free_surface_info_fields(s: &mut AdSurfaceInfo) {unsafe {free_c_string(s.kind as *mut c_char);@@ -40,4 +70,16 @@ mod tests {let mut c = c;unsafe { free_surface_info_fields(&mut c) };}++ #[test]+ fn snapshot_surface_from_c_uses_shared_enum_validation() {+ assert_eq!(+ snapshot_surface_from_c(5, "source_surface").unwrap(),+ SnapshotSurface::Popover+ );++ let err = snapshot_surface_from_c(99, "source_surface").unwrap_err();+ assert_eq!(err.code, ErrorCode::InvalidArgs);+ assert_eq!(err.message, "invalid source_surface discriminant");+ }}diff --git a/crates/ffi/src/enum_validation.rs b/crates/ffi/src/enum_validation.rsindex 6491f0ade..9eca47259 100644--- a/crates/ffi/src/enum_validation.rs+++ b/crates/ffi/src/enum_validation.rs@@ -16,7 +16,8 @@ use crate::types::{macro_rules! try_from_c_enum {($ty:ty { $($variant:ident = $val:expr),+ $(,)? }) => {impl $ty {- #[allow(dead_code)] // not every enum is read from C today; keep the validator uniformly+ /// Converts a raw C discriminant; not every enum is read from C today.+ #[allow(dead_code)]pub(crate) fn from_c(raw: i32) -> Option<Self> {match raw {$($val => Some(<$ty>::$variant),)+@@ -39,7 +40,7 @@ try_from_c_enum! {try_from_c_enum! {AdPolicyKind {- Headless = 0, FocusFallback = 1, Physical = 2,+ Headless = 0, FocusFallback = 1, Headed = 2,}}diff --git a/crates/ffi/src/error.rs b/crates/ffi/src/error.rsindex bdbed6c1d..242a46ffd 100644--- a/crates/ffi/src/error.rs+++ b/crates/ffi/src/error.rs@@ -3,7 +3,6 @@ use std::cell::RefCell;use std::ffi::{CStr, CString, c_char};const fn error_code_variant_count() -> usize {- let mut count = 0;let variants = [ErrorCode::PermDenied,ErrorCode::ElementNotFound,@@ -11,6 +10,7 @@ const fn error_code_variant_count() -> usize {ErrorCode::ActionFailed,ErrorCode::ActionNotSupported,ErrorCode::StaleRef,+ ErrorCode::AmbiguousTarget,ErrorCode::WindowNotFound,ErrorCode::PlatformNotSupported,ErrorCode::Timeout,@@ -20,12 +20,7 @@ const fn error_code_variant_count() -> usize {ErrorCode::PolicyDenied,ErrorCode::Internal,];- let mut i = 0;- while i < variants.len() {- count += 1;- i += 1;- }- count+ variants.len()}const fn ad_result_error_variant_count() -> usize {@@ -36,6 +31,7 @@ const fn ad_result_error_variant_count() -> usize {AdResult::ErrActionFailed,AdResult::ErrActionNotSupported,AdResult::ErrStaleRef,+ AdResult::ErrAmbiguousTarget,AdResult::ErrWindowNotFound,AdResult::ErrPlatformNotSupported,AdResult::ErrTimeout,@@ -45,13 +41,7 @@ const fn ad_result_error_variant_count() -> usize {AdResult::ErrSnapshotNotFound,AdResult::ErrPolicyDenied,];- let mut count = 0;- let mut i = 0;- while i < variants.len() {- count += 1;- i += 1;- }- count+ variants.len()}const _: () = assert!(@@ -77,6 +67,7 @@ pub enum AdResult {ErrInternal = -12,ErrSnapshotNotFound = -13,ErrPolicyDenied = -14,+ ErrAmbiguousTarget = -15,}const _: () = assert!(AdResult::ErrPermDenied as i32 == -1);@@ -93,6 +84,7 @@ const _: () = assert!(AdResult::ErrNotificationNotFound as i32 == -11);const _: () = assert!(AdResult::ErrInternal as i32 == -12);const _: () = assert!(AdResult::ErrSnapshotNotFound as i32 == -13);const _: () = assert!(AdResult::ErrPolicyDenied as i32 == -14);+const _: () = assert!(AdResult::ErrAmbiguousTarget as i32 == -15);enum MessageSource {Owned(CString),@@ -121,6 +113,7 @@ struct StoredError {message: MessageSource,suggestion: Option<CString>,platform_detail: Option<CString>,+ details: Option<CString>,}static NUL_BYTE_FALLBACK: &CStr = c"(message contained null byte)";@@ -137,6 +130,7 @@ fn error_code_to_result(code: &ErrorCode) -> AdResult {ErrorCode::ActionFailed => AdResult::ErrActionFailed,ErrorCode::ActionNotSupported => AdResult::ErrActionNotSupported,ErrorCode::StaleRef => AdResult::ErrStaleRef,+ ErrorCode::AmbiguousTarget => AdResult::ErrAmbiguousTarget,ErrorCode::WindowNotFound => AdResult::ErrWindowNotFound,ErrorCode::PlatformNotSupported => AdResult::ErrPlatformNotSupported,ErrorCode::Timeout => AdResult::ErrTimeout,@@ -159,12 +153,18 @@ pub(crate) fn set_last_error(err: &AdapterError) {.platform_detail.as_deref().and_then(|s| CString::new(s).ok());+ let details = err+ .details+ .as_ref()+ .and_then(|details| serde_json::to_string(details).ok())+ .and_then(|details| CString::new(details).ok());LAST_ERROR.with(|cell| {*cell.borrow_mut() = Some(StoredError {code,message,suggestion,platform_detail,+ details,});});}@@ -185,6 +185,7 @@ pub(crate) fn set_last_error_static(code: AdResult, message: &'static CStr) {message: MessageSource::Static(message),suggestion: None,platform_detail: None,+ details: None,});});}@@ -267,6 +268,21 @@ pub extern "C" fn ad_last_error_platform_detail() -> *const c_char {})}+/// Returns a borrowed JSON string carrying structured details for the last+/// error, or null if the adapter didn't supply any. Same lifetime rules as+/// `ad_last_error_message`.+#[unsafe(no_mangle)]+pub extern "C" fn ad_last_error_details() -> *const c_char {+ crate::ffi_try::trap_panic_const_ptr(|| {+ LAST_ERROR.with(|cell| {+ cell.borrow()+ .as_ref()+ .and_then(|e| e.details.as_ref().map(|s| s.as_ptr()))+ .unwrap_or(std::ptr::null())+ })+ })+}+#[cfg(test)]#[path = "error_tests.rs"]mod tests;diff --git a/crates/ffi/src/error_tests.rs b/crates/ffi/src/error_tests.rsindex 806fe0796..f833b211e 100644--- a/crates/ffi/src/error_tests.rs+++ b/crates/ffi/src/error_tests.rs@@ -24,6 +24,14 @@ fn last_error_platform_detail_str() -> Option<String> {})}+fn last_error_details_str() -> Option<String> {+ LAST_ERROR.with(|cell| {+ cell.borrow()+ .as_ref()+ .and_then(|e| e.details.as_ref().map(|s| s.to_string_lossy().into_owned()))+ })+}+#[test]fn test_no_error_initially() {clear_last_error();@@ -35,6 +43,7 @@ fn result_discriminants_preserve_existing_abi_values() {assert_eq!(AdResult::ErrInternal as i32, -12);assert_eq!(AdResult::ErrSnapshotNotFound as i32, -13);assert_eq!(AdResult::ErrPolicyDenied as i32, -14);+ assert_eq!(AdResult::ErrAmbiguousTarget as i32, -15);}#[test]@@ -46,6 +55,24 @@ fn test_set_and_get_error() {assert_eq!(last_error_message_str().unwrap(), "element @e5 gone");assert_eq!(last_error_suggestion_str().unwrap(), "run snapshot");assert!(last_error_platform_detail_str().is_none());+ assert!(last_error_details_str().is_none());+}++#[test]+fn test_set_and_get_structured_details() {+ let err = AdapterError::new(ErrorCode::AmbiguousTarget, "ambiguous").with_details(+ serde_json::json!({+ "candidate_count": 2,+ "role": "button"+ }),+ );+ set_last_error(&err);++ assert_eq!(last_error_code(), AdResult::ErrAmbiguousTarget);+ let details: serde_json::Value =+ serde_json::from_str(&last_error_details_str().unwrap()).unwrap();+ assert_eq!(details["candidate_count"], 2);+ assert_eq!(details["role"], "button");}#[test]diff --git a/crates/ffi/src/input/drag.rs b/crates/ffi/src/input/drag.rsindex c6309e916..69f18b8ff 100644--- a/crates/ffi/src/input/drag.rs+++ b/crates/ffi/src/input/drag.rs@@ -2,11 +2,11 @@ use crate::AdAdapter;use crate::error::{self, AdResult};use crate::ffi_try::trap_panic;use crate::types::AdDragParams;-use agent_desktop_core::action::{DragParams as CoreDragParams, Point as CorePoint};-/// Synthesizes a mouse drag from `params.from` to `params.to`. When-/// `params.duration_ms` is zero the drag is instantaneous; a non-zero-/// value asks the platform adapter to interpolate.+/// Synthesizes an explicit physical mouse drag from `params.from` to+/// `params.to`. When `params.duration_ms` is zero the drag is instantaneous;+/// a non-zero value asks the platform adapter to interpolate. Callers that+/// need headless policy enforcement should use ref actions with policy.////// # Safety/// `adapter` must be a non-null pointer returned by `ad_adapter_create`.@@ -24,21 +24,7 @@ pub unsafe extern "C" fn ad_drag(crate::pointer_guard::guard_non_null!(params, c"params is null");let adapter = &*adapter;let p = &*params;- let core_params = CoreDragParams {- from: CorePoint {- x: p.from.x,- y: p.from.y,- },- to: CorePoint {- x: p.to.x,- y: p.to.y,- },- duration_ms: if p.duration_ms == 0 {- None- } else {- Some(p.duration_ms)- },- };+ let core_params = p.to_core();match adapter.inner.drag(core_params) {Ok(()) => AdResult::Ok,Err(e) => {@@ -55,53 +41,29 @@ mod tests {use crate::types::AdPoint;#[test]- fn test_drag_zero_duration_becomes_none() {+ fn test_drag_zero_duration_and_drop_delay_become_none() {let p = AdDragParams {from: AdPoint { x: 0.0, y: 0.0 },to: AdPoint { x: 100.0, y: 200.0 },duration_ms: 0,+ drop_delay_ms: 0,};- let core = CoreDragParams {- from: CorePoint {- x: p.from.x,- y: p.from.y,- },- to: CorePoint {- x: p.to.x,- y: p.to.y,- },- duration_ms: if p.duration_ms == 0 {- None- } else {- Some(p.duration_ms)- },- };+ let core = p.to_core();assert!(core.duration_ms.is_none());+ assert!(core.drop_delay_ms.is_none());assert_eq!(core.to.x, 100.0);}#[test]- fn test_drag_nonzero_duration() {+ fn test_drag_nonzero_duration_and_drop_delay_pass_through() {let p = AdDragParams {from: AdPoint { x: 0.0, y: 0.0 },to: AdPoint { x: 50.0, y: 50.0 },duration_ms: 500,+ drop_delay_ms: 750,};- let core = CoreDragParams {- from: CorePoint {- x: p.from.x,- y: p.from.y,- },- to: CorePoint {- x: p.to.x,- y: p.to.y,- },- duration_ms: if p.duration_ms == 0 {- None- } else {- Some(p.duration_ms)- },- };+ let core = p.to_core();assert_eq!(core.duration_ms, Some(500));+ assert_eq!(core.drop_delay_ms, Some(750));}}diff --git a/crates/ffi/src/input/mouse.rs b/crates/ffi/src/input/mouse.rsindex a87325bc0..273cf208f 100644--- a/crates/ffi/src/input/mouse.rs+++ b/crates/ffi/src/input/mouse.rs@@ -15,9 +15,10 @@ pub(crate) fn mouse_button_from_c(b: AdMouseButton) -> CoreMouseButton {}}-/// Dispatches a mouse event (move / down / up / click) at the given-/// screen point. Click count is only consulted when `event.kind` is-/// `CLICK` (e.g., `click_count == 2` for a double-click).+/// Dispatches an explicit physical mouse event (move / down / up / click)+/// at the given screen point. Click count is only consulted when `event.kind`+/// is `CLICK` (e.g., `click_count == 2` for a double-click). Callers that+/// need headless policy enforcement should use ref actions with policy.////// # Safety/// `adapter` must be a non-null pointer returned by `ad_adapter_create`.diff --git a/crates/ffi/src/lib.rs b/crates/ffi/src/lib.rsindex a22ccce53..4717153d7 100644--- a/crates/ffi/src/lib.rs+++ b/crates/ffi/src/lib.rs@@ -64,6 +64,7 @@ pub use error::AdResult;pub use types::action::AdAction;pub use types::action_kind::AdActionKind;pub use types::action_result::AdActionResult;+pub use types::action_step::AdActionStep;pub use types::app_info::AdAppInfo;pub use types::app_list::AdAppList;pub use types::direction::AdDirection;diff --git a/crates/ffi/src/notifications/filter.rs b/crates/ffi/src/notifications/filter.rsindex 6c3b72a0d..2d0a681bc 100644--- a/crates/ffi/src/notifications/filter.rs+++ b/crates/ffi/src/notifications/filter.rs@@ -23,10 +23,9 @@ pub(crate) unsafe fn filter_from_c(}let f: &AdNotificationFilter = unsafe { &*filter };let app = unsafe { try_c_to_string(f.app) }- .map_err(|()| AdapterError::new(ErrorCode::InvalidArgs, "filter.app is not valid UTF-8"))?;- let text = unsafe { try_c_to_string(f.text) }.map_err(|()| {- AdapterError::new(ErrorCode::InvalidArgs, "filter.text is not valid UTF-8")- })?;+ .map_err(|err| AdapterError::new(ErrorCode::InvalidArgs, err.describe("filter.app")))?;+ let text = unsafe { try_c_to_string(f.text) }+ .map_err(|err| AdapterError::new(ErrorCode::InvalidArgs, err.describe("filter.text")))?;Ok(NotificationFilter {app,text,diff --git a/crates/ffi/src/observation/find.rs b/crates/ffi/src/observation/find.rsindex 61c9e5cc0..1dabdbd7e 100644--- a/crates/ffi/src/observation/find.rs+++ b/crates/ffi/src/observation/find.rs@@ -19,6 +19,11 @@ use std::mem::ManuallyDrop;/// - `name_substring` against `AccessibilityNode.name`/// - `value_substring` against `AccessibilityNode.value`///+/// The internal tree fetch always sets `include_bounds: true` so+/// `resolve_element_strict` can disambiguate duplicate-label siblings via+/// `bounds_hash`; without bounds on the matched node the resolver falls+/// back to role+name alone and may pick the wrong element.+////// # Safety/// `adapter`, `win`, and `query` must be valid pointers. `out_handle`/// must be a valid writable `*mut AdNativeHandle`. On@@ -52,10 +57,6 @@ pub unsafe extern "C" fn ad_find(let name_filter = decode_optional_filter!(q.name_substring, "query.name_substring");let value_filter = decode_optional_filter!(q.value_substring, "query.value_substring");- // include_bounds must be true: the resolver disambiguates- // duplicate-label siblings using bounds_hash, and without the- // bounds field populated on the matched node we would fall- // back to role+name alone and drift to the wrong element.let tree = match adapter.inner.get_tree(&core_win,&TreeOptions {@@ -109,7 +110,7 @@ pub unsafe extern "C" fn ad_find(path_is_absolute: false,path: smallvec::SmallVec::new(),};- match adapter.inner.resolve_element(&ref_entry) {+ match adapter.inner.resolve_element_strict(&ref_entry) {Ok(handle) => {let handle = ManuallyDrop::new(handle);(*out_handle).ptr = handle.as_raw();diff --git a/crates/ffi/src/observation/get.rs b/crates/ffi/src/observation/get.rsindex b4f8920bf..b75c99d1e 100644--- a/crates/ffi/src/observation/get.rs+++ b/crates/ffi/src/observation/get.rs@@ -17,7 +17,8 @@ use std::os::raw::c_char;/// The returned string must be freed with `ad_free_string`.////// # Safety-/// `adapter` must be valid. `handle` must be a non-null `AdNativeHandle`.+/// `adapter` must be valid. `handle` must be a non-null `AdNativeHandle`+/// produced by the same live adapter and freed before that adapter is destroyed./// `property` must be a non-null UTF-8 C string. `out` must be a valid/// writable `*mut *mut c_char`; it is null-initialized on entry.#[unsafe(no_mangle)]diff --git a/crates/ffi/src/tree/flatten.rs b/crates/ffi/src/tree/flatten.rsindex ff1c70106..0a1907cd2 100644--- a/crates/ffi/src/tree/flatten.rs+++ b/crates/ffi/src/tree/flatten.rs@@ -44,6 +44,7 @@ pub(crate) fn flatten_tree(root: &AccessibilityNode) -> AdNodeTree {}let count = flat.len() as u32;+ flat.push(sentinel_node());let nodes = if flat.is_empty() {ptr::null_mut()} else {@@ -55,6 +56,29 @@ pub(crate) fn flatten_tree(root: &AccessibilityNode) -> AdNodeTree {AdNodeTree { nodes, count }}+fn sentinel_node() -> AdNode {+ AdNode {+ ref_id: ptr::null(),+ role: ptr::null(),+ name: ptr::null(),+ value: ptr::null(),+ description: ptr::null(),+ hint: ptr::null(),+ states: ptr::null_mut(),+ state_count: 0,+ bounds: AdRect {+ x: 0.0,+ y: 0.0,+ width: 0.0,+ height: 0.0,+ },+ has_bounds: false,+ parent_index: -1,+ child_start: 0,+ child_count: 0,+ }+}+fn count_nodes(node: &AccessibilityNode) -> usize {let mut total: usize = 0;let mut queue: VecDeque<&AccessibilityNode> = VecDeque::new();@@ -103,8 +127,9 @@ fn strings_to_c_array(strings: &[String]) -> (*mut *mut c_char, u32) {if strings.is_empty() {return (ptr::null_mut(), 0);}- let ptrs: Vec<*mut c_char> = strings.iter().map(|s| string_to_c_lossy(s)).collect();+ let mut ptrs: Vec<*mut c_char> = strings.iter().map(|s| string_to_c_lossy(s)).collect();let count = ptrs.len() as u32;+ ptrs.push(ptr::null_mut());let mut boxed = ptrs.into_boxed_slice();let ptr = boxed.as_mut_ptr();std::mem::forget(boxed);diff --git a/crates/ffi/src/tree/free.rs b/crates/ffi/src/tree/free.rsindex da92daf5b..132915faa 100644--- a/crates/ffi/src/tree/free.rs+++ b/crates/ffi/src/tree/free.rs@@ -3,18 +3,22 @@ use crate::types::{AdNode, AdNodeTree};use std::os::raw::c_char;use std::ptr;-unsafe fn free_c_string_array(arr: *mut *mut c_char, count: u32) {+const MAX_NODE_STATE_STRINGS_TO_FREE: usize = 1024;+const MAX_TREE_NODES_TO_FREE: usize = 1_000_000;++unsafe fn free_c_string_array(arr: *mut *mut c_char) {unsafe {if arr.is_null() {return;}- let slice = std::slice::from_raw_parts_mut(arr, count as usize);- for p in slice.iter_mut() {- free_c_string(*p);+ let mut len = 0;+ while len < MAX_NODE_STATE_STRINGS_TO_FREE && !(*arr.add(len)).is_null() {+ free_c_string(*arr.add(len));+ len += 1;}drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut(arr,- count as usize,+ len + 1,)));}}@@ -27,7 +31,7 @@ unsafe fn free_node_fields(node: &mut AdNode) {free_c_string(node.value as *mut c_char);free_c_string(node.description as *mut c_char);free_c_string(node.hint as *mut c_char);- free_c_string_array(node.states, node.state_count);+ free_c_string_array(node.states);node.ref_id = ptr::null();node.role = ptr::null();node.name = ptr::null();@@ -52,19 +56,30 @@ pub unsafe extern "C" fn ad_free_tree(tree: *mut AdNodeTree) {if tree.nodes.is_null() {return;}- let nodes = std::slice::from_raw_parts_mut(tree.nodes, tree.count as usize);+ let node_count = sentinel_node_count(tree.nodes);+ let nodes = std::slice::from_raw_parts_mut(tree.nodes, node_count);for node in nodes.iter_mut() {free_node_fields(node);}drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut(tree.nodes,- tree.count as usize,+ node_count + 1,)));tree.nodes = ptr::null_mut();tree.count = 0;})}+unsafe fn sentinel_node_count(nodes: *mut AdNode) -> usize {+ unsafe {+ let mut count = 0;+ while count < MAX_TREE_NODES_TO_FREE && !(*nodes.add(count)).role.is_null() {+ count += 1;+ }+ count+ }+}+#[cfg(test)]mod tests {use super::*;@@ -73,4 +88,103 @@ mod tests {fn test_free_null_tree_is_noop() {unsafe { ad_free_tree(std::ptr::null_mut()) };}++ #[test]+ fn free_tree_ignores_mutated_node_state_count() {+ let mut tree = tree_with_node(node_with_states(&["focused"], u32::MAX));+ unsafe { ad_free_tree(&mut tree) };++ assert!(tree.nodes.is_null());+ }++ fn tree_with_node(node: AdNode) -> AdNodeTree {+ let mut nodes = vec![node, sentinel_node()].into_boxed_slice();+ let raw = nodes.as_mut_ptr();+ std::mem::forget(nodes);+ AdNodeTree {+ nodes: raw,+ count: 1,+ }+ }++ fn node_with_states(states: &[&str], state_count: u32) -> AdNode {+ AdNode {+ ref_id: ptr::null(),+ role: crate::convert::string::string_to_c_lossy("button"),+ name: ptr::null(),+ value: ptr::null(),+ description: ptr::null(),+ hint: ptr::null(),+ states: state_array(states),+ state_count,+ bounds: crate::types::AdRect {+ x: 0.0,+ y: 0.0,+ width: 0.0,+ height: 0.0,+ },+ has_bounds: false,+ parent_index: -1,+ child_start: 0,+ child_count: 0,+ }+ }++ fn sentinel_node() -> AdNode {+ AdNode {+ ref_id: ptr::null(),+ role: ptr::null(),+ name: ptr::null(),+ value: ptr::null(),+ description: ptr::null(),+ hint: ptr::null(),+ states: ptr::null_mut(),+ state_count: 0,+ bounds: crate::types::AdRect {+ x: 0.0,+ y: 0.0,+ width: 0.0,+ height: 0.0,+ },+ has_bounds: false,+ parent_index: -1,+ child_start: 0,+ child_count: 0,+ }+ }++ fn state_array(states: &[&str]) -> *mut *mut c_char {+ let mut ptrs: Vec<*mut c_char> = states+ .iter()+ .map(|state| crate::convert::string::string_to_c_lossy(state))+ .collect();+ ptrs.push(ptr::null_mut());+ let mut boxed = ptrs.into_boxed_slice();+ let raw = boxed.as_mut_ptr();+ std::mem::forget(boxed);+ raw+ }++ #[test]+ fn free_tree_ignores_mutated_tree_count() {+ let root = agent_desktop_core::node::AccessibilityNode {+ ref_id: None,+ role: "button".into(),+ name: None,+ value: None,+ description: None,+ hint: None,+ states: vec![],+ available_actions: vec![],+ bounds: None,+ children: vec![],+ children_count: None,+ };+ let mut tree = crate::tree::flatten::flatten_tree(&root);+ tree.count = u32::MAX;+ unsafe { ad_free_tree(&mut tree) };++ assert!(tree.nodes.is_null());+ assert_eq!(tree.count, 0);+ }}diff --git a/crates/ffi/src/tree/get.rs b/crates/ffi/src/tree/get.rsindex 7d57ad7cd..a9c49e260 100644--- a/crates/ffi/src/tree/get.rs+++ b/crates/ffi/src/tree/get.rs@@ -1,23 +1,11 @@use crate::AdAdapter;+use crate::convert::surface::snapshot_surface_from_c;use crate::error::{AdResult, set_last_error};use crate::ffi_try::trap_panic;use crate::tree::flatten::flatten_tree;-use crate::types::{AdNodeTree, AdSnapshotSurface, AdTreeOptions, AdWindowInfo};-use agent_desktop_core::adapter::SnapshotSurface;+use crate::types::{AdNodeTree, AdTreeOptions, AdWindowInfo};use std::ptr;-fn core_surface(s: AdSnapshotSurface) -> SnapshotSurface {- match s {- AdSnapshotSurface::Window => SnapshotSurface::Window,- AdSnapshotSurface::Focused => SnapshotSurface::Focused,- AdSnapshotSurface::Menu => SnapshotSurface::Menu,- AdSnapshotSurface::Menubar => SnapshotSurface::Menubar,- AdSnapshotSurface::Sheet => SnapshotSurface::Sheet,- AdSnapshotSurface::Popover => SnapshotSurface::Popover,- AdSnapshotSurface::Alert => SnapshotSurface::Alert,- }-}-/// Snapshots `win`'s accessibility tree into the flat BFS layout/// described in the types module. The result is written into `*out`/// and must be freed with `ad_free_tree`. Direct children of any node@@ -87,13 +75,10 @@ pub unsafe extern "C" fn ad_get_tree(return crate::error::last_error_code();}};- let surface = match AdSnapshotSurface::from_c(opts_ref.surface) {- Some(s) => core_surface(s),- None => {- set_last_error(&agent_desktop_core::error::AdapterError::new(- agent_desktop_core::error::ErrorCode::InvalidArgs,- "invalid snapshot surface discriminant",- ));+ let surface = match snapshot_surface_from_c(opts_ref.surface, "snapshot surface") {+ Ok(surface) => surface,+ Err(e) => {+ set_last_error(&e);return AdResult::ErrInvalidArgs;}};@@ -108,13 +93,6 @@ pub unsafe extern "C" fn ad_get_tree(match adapter.inner.get_tree(&core_win, &core_opts) {Ok(tree) => {- // Adapters return a full raw tree; flags live on the core- // TreeOptions but the macOS adapter only consumes- // `max_depth` and `skeleton`. Apply shape transformations- // here so the FFI behavior matches what AdTreeOptions- // documents. ref_alloc::transform_tree is the ref-free- // variant of allocate_refs and matches its semantics for- // compact/interactive_only/include_bounds.let shaped = agent_desktop_core::ref_alloc::transform_tree(tree,core_opts.include_bounds,diff --git a/crates/ffi/src/types/action.rs b/crates/ffi/src/types/action.rsindex 5f2cc718f..8997a3e1c 100644--- a/crates/ffi/src/types/action.rs+++ b/crates/ffi/src/types/action.rs@@ -10,6 +10,12 @@ use std::os::raw::c_char;/// an out-of-range value is rejected with/// `AD_RESULT_ERR_INVALID_ARGS` at the boundary. Valid values are the/// discriminants of `AdActionKind`.+///+/// `AdDragParams` is embedded by value, so any growth there grows this+/// struct too. Callers must zero-initialize the whole struct and verify+/// layout against `AD_ACTION_SIZE` / `ad_action_size()` when binding from+/// a language whose struct layout may diverge — an under-allocated action+/// makes the library read past the caller's buffer.#[repr(C)]pub struct AdAction {pub kind: i32,@@ -18,3 +24,12 @@ pub struct AdAction {pub key: AdKeyCombo,pub drag: AdDragParams,}++pub const AD_ACTION_SIZE: usize = 96;++const _: () = assert!(std::mem::size_of::<AdAction>() == AD_ACTION_SIZE);++#[unsafe(no_mangle)]+pub extern "C" fn ad_action_size() -> usize {+ std::mem::size_of::<AdAction>()+}diff --git a/crates/ffi/src/types/action_result.rs b/crates/ffi/src/types/action_result.rsindex 3b0ccda60..6c8d772ba 100644--- a/crates/ffi/src/types/action_result.rs+++ b/crates/ffi/src/types/action_result.rs@@ -1,3 +1,4 @@+use crate::types::action_step::AdActionStep;use crate::types::element_state::AdElementState;use std::os::raw::c_char;@@ -6,4 +7,15 @@ pub struct AdActionResult {pub action: *const c_char,pub ref_id: *const c_char,pub post_state: *mut AdElementState,+ pub steps: *mut AdActionStep,+ pub step_count: u32,+}++pub const AD_ACTION_RESULT_SIZE: usize = 40;++const _: () = assert!(std::mem::size_of::<AdActionResult>() == AD_ACTION_RESULT_SIZE);++#[unsafe(no_mangle)]+pub extern "C" fn ad_action_result_size() -> usize {+ std::mem::size_of::<AdActionResult>()}diff --git a/crates/ffi/src/types/action_step.rs b/crates/ffi/src/types/action_step.rsnew file mode 100644index 000000000..d11dc90be--- /dev/null+++ b/crates/ffi/src/types/action_step.rs@@ -0,0 +1,16 @@+use std::os::raw::c_char;++#[repr(C)]+pub struct AdActionStep {+ pub label: *const c_char,+ pub outcome: *const c_char,+}++pub const AD_ACTION_STEP_SIZE: usize = 16;++const _: () = assert!(std::mem::size_of::<AdActionStep>() == AD_ACTION_STEP_SIZE);++#[unsafe(no_mangle)]+pub extern "C" fn ad_action_step_size() -> usize {+ std::mem::size_of::<AdActionStep>()+}diff --git a/crates/ffi/src/types/drag_params.rs b/crates/ffi/src/types/drag_params.rsindex 487f07466..4b63880d8 100644--- a/crates/ffi/src/types/drag_params.rs+++ b/crates/ffi/src/types/drag_params.rs@@ -1,8 +1,48 @@use crate::types::point::AdPoint;+use agent_desktop_core::action::{DragParams as CoreDragParams, Point as CorePoint};+/// Caller-allocated drag parameters. Callers must zero-initialize the whole+/// struct before setting fields so unset numeric fields read as the `0`+/// adapter-default sentinel rather than stack garbage. Verify layout against+/// `AD_DRAG_PARAMS_SIZE` / `ad_drag_params_size()` when binding from a language+/// whose struct layout may diverge.#[repr(C)]pub struct AdDragParams {pub from: AdPoint,pub to: AdPoint,pub duration_ms: u64,+ pub drop_delay_ms: u64,+}++pub const AD_DRAG_PARAMS_SIZE: usize = 48;++const _: () = assert!(std::mem::size_of::<AdDragParams>() == AD_DRAG_PARAMS_SIZE);++#[unsafe(no_mangle)]+pub extern "C" fn ad_drag_params_size() -> usize {+ std::mem::size_of::<AdDragParams>()+}++impl AdDragParams {+ /// Converts the C drag params into the core type. `duration_ms` and+ /// `drop_delay_ms` use `0` as the "adapter default" sentinel because the+ /// C ABI has no `Option`; any non-zero value is passed through.+ pub(crate) fn to_core(&self) -> CoreDragParams {+ CoreDragParams {+ from: CorePoint {+ x: self.from.x,+ y: self.from.y,+ },+ to: CorePoint {+ x: self.to.x,+ y: self.to.y,+ },+ duration_ms: zero_as_default(self.duration_ms),+ drop_delay_ms: zero_as_default(self.drop_delay_ms),+ }+ }+}++fn zero_as_default(value: u64) -> Option<u64> {+ (value != 0).then_some(value)}diff --git a/crates/ffi/src/types/element_state.rs b/crates/ffi/src/types/element_state.rsindex ca7560743..6a48bc733 100644--- a/crates/ffi/src/types/element_state.rs+++ b/crates/ffi/src/types/element_state.rs@@ -7,3 +7,12 @@ pub struct AdElementState {pub state_count: u32,pub value: *const c_char,}++pub const AD_ELEMENT_STATE_SIZE: usize = 32;++const _: () = assert!(std::mem::size_of::<AdElementState>() == AD_ELEMENT_STATE_SIZE);++#[unsafe(no_mangle)]+pub extern "C" fn ad_element_state_size() -> usize {+ std::mem::size_of::<AdElementState>()+}diff --git a/crates/ffi/src/types/mod.rs b/crates/ffi/src/types/mod.rsindex fc095e674..fd8b2cdcb 100644--- a/crates/ffi/src/types/mod.rs+++ b/crates/ffi/src/types/mod.rs@@ -1,6 +1,7 @@pub mod action;pub mod action_kind;pub mod action_result;+pub mod action_step;pub mod app_info;pub mod app_list;pub mod direction;@@ -39,6 +40,7 @@ pub mod window_op_kind;pub use action::AdAction;pub use action_kind::AdActionKind;pub use action_result::AdActionResult;+pub use action_step::AdActionStep;pub use app_info::AdAppInfo;pub use app_list::AdAppList;pub use direction::AdDirection;diff --git a/crates/ffi/src/types/notification_list.rs b/crates/ffi/src/types/notification_list.rsindex 14ba200f8..18e22d545 100644--- a/crates/ffi/src/types/notification_list.rs+++ b/crates/ffi/src/types/notification_list.rs@@ -1,6 +1,7 @@use crate::types::notification_info::AdNotificationInfo;+/// Opaque notification list returned by `ad_list_notifications`.pub struct AdNotificationList {- #[allow(dead_code)] // populated + read by the Unit 8 notifications module+ #[allow(dead_code)]pub(crate) items: Box<[AdNotificationInfo]>,}diff --git a/crates/ffi/src/types/policy_kind.rs b/crates/ffi/src/types/policy_kind.rsindex 94fecdaf0..7c0ab6a24 100644--- a/crates/ffi/src/types/policy_kind.rs+++ b/crates/ffi/src/types/policy_kind.rs@@ -3,7 +3,7 @@pub enum AdPolicyKind {Headless = 0,FocusFallback = 1,- Physical = 2,+ Headed = 2,}#[cfg(test)]@@ -14,6 +14,6 @@ mod tests {fn discriminants_are_abi_stable() {assert_eq!(AdPolicyKind::Headless as i32, 0);assert_eq!(AdPolicyKind::FocusFallback as i32, 1);- assert_eq!(AdPolicyKind::Physical as i32, 2);+ assert_eq!(AdPolicyKind::Headed as i32, 2);}}diff --git a/crates/ffi/src/types/ref_entry.rs b/crates/ffi/src/types/ref_entry.rsindex dd4d3be50..6d9bb4dfa 100644--- a/crates/ffi/src/types/ref_entry.rs+++ b/crates/ffi/src/types/ref_entry.rs@@ -1,3 +1,4 @@+use crate::types::AdRect;use std::os::raw::c_char;#[repr(C)]@@ -5,7 +6,39 @@ pub struct AdRefEntry {pub pid: i32,pub role: *const c_char,pub name: *const c_char,+ pub value: *const c_char,pub description: *const c_char,+ pub states: *const *const c_char,+ pub state_count: usize,+ pub available_actions: *const *const c_char,+ pub available_action_count: usize,+ pub bounds: AdRect,+ pub has_bounds: bool,pub bounds_hash: u64,pub has_bounds_hash: bool,+ pub source_app: *const c_char,+ pub source_window_id: *const c_char,+ pub source_window_title: *const c_char,+ pub source_surface: i32,+ pub root_ref: *const c_char,+ pub path_is_absolute: bool,+ pub path: *const u32,+ pub path_count: usize,+}++pub const AD_REF_ENTRY_SIZE: usize = 192;++/// Per-field input caps enforced when converting an `AdRefEntry` at the C+/// boundary, sized from what real accessibility trees produce (a handful of+/// states/actions, double-digit path depth) with generous headroom. Mirrored+/// in the header so callers can validate before calling.+pub const AD_MAX_REF_STATES: usize = 64;+pub const AD_MAX_REF_ACTIONS: usize = 32;+pub const AD_MAX_REF_PATH_DEPTH: usize = 128;++const _: () = assert!(std::mem::size_of::<AdRefEntry>() == AD_REF_ENTRY_SIZE);++#[unsafe(no_mangle)]+pub extern "C" fn ad_ref_entry_size() -> usize {+ std::mem::size_of::<AdRefEntry>()}diff --git a/crates/ffi/src/windows/to_core.rs b/crates/ffi/src/windows/to_core.rsindex d06670c76..9ae9428d0 100644--- a/crates/ffi/src/windows/to_core.rs+++ b/crates/ffi/src/windows/to_core.rs@@ -1,6 +1,6 @@-use crate::convert::string::c_to_string;+use crate::convert::string::{optional_adapter_string, required_adapter_string};use crate::types::AdWindowInfo;-use agent_desktop_core::error::{AdapterError, ErrorCode};+use agent_desktop_core::error::AdapterError;/// Converts an `AdWindowInfo` from C into the core `WindowInfo`.///@@ -14,16 +14,9 @@ use agent_desktop_core::error::{AdapterError, ErrorCode};pub(crate) fn ad_window_to_core(w: &AdWindowInfo,) -> Result<agent_desktop_core::node::WindowInfo, AdapterError> {- let id = unsafe { c_to_string(w.id) }.ok_or_else(|| {- AdapterError::new(ErrorCode::InvalidArgs, "window id is null or invalid UTF-8")- })?;- let title = unsafe { c_to_string(w.title) }.ok_or_else(|| {- AdapterError::new(- ErrorCode::InvalidArgs,- "window title is null or invalid UTF-8",- )- })?;- let app = unsafe { c_to_string(w.app_name) }.unwrap_or_default();+ let id = required_adapter_string(w.id, "window id")?;+ let title = required_adapter_string(w.title, "window title")?;+ let app = optional_adapter_string(w.app_name, "window app_name")?.unwrap_or_default();Ok(agent_desktop_core::node::WindowInfo {id,title,@@ -42,3 +35,60 @@ pub(crate) fn ad_window_to_core(is_focused: w.is_focused,})}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::convert::string::MAX_C_STRING_BYTES;+ use crate::types::AdRect;+ use agent_desktop_core::error::ErrorCode;+ use std::ffi::CString;++ #[test]+ fn window_app_name_rejects_oversized_string() {+ let id = CString::new("w-1").unwrap();+ let title = CString::new("Main").unwrap();+ let mut app = vec![b'a'; MAX_C_STRING_BYTES + 1];+ app.push(0);+ let win = window(id.as_ptr(), title.as_ptr(), app.as_ptr().cast());++ let err = ad_window_to_core(&win).unwrap_err();++ assert_eq!(err.code, ErrorCode::InvalidArgs);+ assert!(err.message.contains("window app_name exceeds"));+ }++ #[test]+ fn window_app_name_rejects_invalid_utf8() {+ let id = CString::new("w-1").unwrap();+ let title = CString::new("Main").unwrap();+ let app = [0xff_u8, 0x00];+ let win = window(id.as_ptr(), title.as_ptr(), app.as_ptr().cast());++ let err = ad_window_to_core(&win).unwrap_err();++ assert_eq!(err.code, ErrorCode::InvalidArgs);+ assert!(err.message.contains("window app_name is not valid UTF-8"));+ }++ fn window(+ id: *const std::os::raw::c_char,+ title: *const std::os::raw::c_char,+ app_name: *const std::os::raw::c_char,+ ) -> AdWindowInfo {+ AdWindowInfo {+ id,+ title,+ app_name,+ pid: 7,+ bounds: AdRect {+ x: 0.0,+ y: 0.0,+ width: 0.0,+ height: 0.0,+ },+ has_bounds: false,+ is_focused: false,+ }+ }+}diff --git a/crates/ffi/tests/c_abi_actions.rs b/crates/ffi/tests/c_abi_actions.rsindex 7f5a59dc9..19c125cb9 100644--- a/crates/ffi/tests/c_abi_actions.rs+++ b/crates/ffi/tests/c_abi_actions.rs@@ -1,9 +1,11 @@mod common;use common::{- AdActionResult, AdNativeHandle, AdPolicyKind, AdResult, ad_execute_action,- ad_execute_action_with_policy, default_action, with_adapter,+ AdActionResult, AdActionStep, AdNativeHandle, AdPolicyKind, AdResult, ad_execute_action,+ ad_execute_action_with_policy, ad_execute_ref_action_with_policy, ad_free_action_result,+ default_action, default_ref_entry, with_adapter,};+use std::ffi::CString;#[test]fn enum_fuzz_invalid_discriminant_rejected() {@@ -35,7 +37,7 @@ fn invalid_policy_discriminant_rejected_without_ub() {adapter,&handle,&action,- AdPolicyKind::Physical as i32 + 1,+ AdPolicyKind::Headed as i32 + 1,&mut out,);assert!(matches!(@@ -60,3 +62,85 @@ fn execute_action_rejects_null_handle_ptr() {));});}++#[test]+fn execute_ref_action_uses_strict_resolution_before_dispatch() {+ with_adapter(|adapter| unsafe {+ let role = std::ffi::CString::new("button").unwrap();+ let mut entry = default_ref_entry();+ entry.role = role.as_ptr();+ let action = default_action();+ let mut out: AdActionResult = std::mem::zeroed();++ let rc = ad_execute_ref_action_with_policy(+ adapter,+ &entry,+ &action,+ AdPolicyKind::Headless as i32,+ &mut out,+ );++ assert!(matches!(+ rc,+ AdResult::ErrStaleRef | AdResult::ErrElementNotFound | AdResult::ErrInternal+ ));+ });+}++#[test]+fn execute_action_policy_requires_main_thread_on_macos() {+ let rc = std::thread::spawn(|| unsafe {+ let action = default_action();+ let handle = AdNativeHandle {+ ptr: std::ptr::null(),+ };+ let mut out: AdActionResult = std::mem::zeroed();+ ad_execute_action_with_policy(+ std::ptr::null(),+ &handle,+ &action,+ AdPolicyKind::Headless as i32,+ &mut out,+ )+ })+ .join()+ .unwrap();++ #[cfg(target_os = "macos")]+ assert_eq!(rc, AdResult::ErrInternal);+ #[cfg(not(target_os = "macos"))]+ assert_eq!(rc, AdResult::ErrInvalidArgs);+}++#[test]+fn free_action_result_releases_non_empty_steps_array() {+ let mut steps = vec![+ AdActionStep {+ label: CString::new("AXScrollToVisible").unwrap().into_raw(),+ outcome: CString::new("attempted").unwrap().into_raw(),+ },+ AdActionStep {+ label: CString::new("AXPress").unwrap().into_raw(),+ outcome: CString::new("succeeded").unwrap().into_raw(),+ },+ AdActionStep {+ label: std::ptr::null(),+ outcome: std::ptr::null(),+ },+ ]+ .into_boxed_slice();+ let mut result = AdActionResult {+ action: CString::new("click").unwrap().into_raw(),+ ref_id: std::ptr::null(),+ post_state: std::ptr::null_mut(),+ steps: steps.as_mut_ptr(),+ step_count: 2,+ };+ std::mem::forget(steps);++ unsafe { ad_free_action_result(&mut result) };++ assert!(result.action.is_null());+ assert!(result.steps.is_null());+ assert_eq!(result.step_count, 0);+}diff --git a/crates/ffi/tests/c_abi_inputs.rs b/crates/ffi/tests/c_abi_inputs.rsindex aa8179187..0d4eaf78a 100644--- a/crates/ffi/tests/c_abi_inputs.rs+++ b/crates/ffi/tests/c_abi_inputs.rs@@ -1,8 +1,8 @@mod common;use common::{- AdNativeHandle, AdRefEntry, AdResult, AdWindowInfo, AdWindowList, ad_launch_app,- ad_list_windows, ad_resolve_element, c_char, with_adapter,+ AdNativeHandle, AdResult, AdWindowInfo, AdWindowList, ad_launch_app, ad_list_windows,+ ad_resolve_element, c_char, default_ref_entry, with_adapter,};#[test]@@ -33,19 +33,26 @@ fn invalid_utf8_app_id_rejected() {});}+#[test]+fn resolve_element_rejects_null_role() {+ with_adapter(|adapter| unsafe {+ let mut out = AdNativeHandle {+ ptr: std::ptr::null(),+ };+ let rc = ad_resolve_element(adapter, &default_ref_entry(), &mut out);+ assert_eq!(rc, AdResult::ErrInvalidArgs);+ assert!(out.ptr.is_null());+ });+}+#[test]fn resolve_element_rejects_invalid_utf8_name() {with_adapter(|adapter| unsafe {let role = std::ffi::CString::new("button").unwrap();let bad_name: [u8; 2] = [0xC3, 0x00];- let entry = AdRefEntry {- pid: 0,- role: role.as_ptr(),- name: bad_name.as_ptr() as *const c_char,- description: std::ptr::null(),- bounds_hash: 0,- has_bounds_hash: false,- };+ let mut entry = default_ref_entry();+ entry.role = role.as_ptr();+ entry.name = bad_name.as_ptr() as *const c_char;let mut out = AdNativeHandle {ptr: std::ptr::null(),};@@ -60,14 +67,9 @@ fn resolve_element_rejects_invalid_utf8_description() {with_adapter(|adapter| unsafe {let role = std::ffi::CString::new("button").unwrap();let bad_description: [u8; 2] = [0xC3, 0x00];- let entry = AdRefEntry {- pid: 0,- role: role.as_ptr(),- name: std::ptr::null(),- description: bad_description.as_ptr() as *const c_char,- bounds_hash: 0,- has_bounds_hash: false,- };+ let mut entry = default_ref_entry();+ entry.role = role.as_ptr();+ entry.description = bad_description.as_ptr() as *const c_char;let mut out = AdNativeHandle {ptr: std::ptr::null(),};diff --git a/crates/ffi/tests/c_abi_layout.rs b/crates/ffi/tests/c_abi_layout.rsindex d74d0b02e..14201eb80 100644--- a/crates/ffi/tests/c_abi_layout.rs+++ b/crates/ffi/tests/c_abi_layout.rs@@ -1,6 +1,84 @@mod common;-use common::{AdPoint, AdRect};+use common::{AdAction, AdActionResult, AdActionStep, AdElementState, AdPoint, AdRect, AdRefEntry};+use std::mem::{MaybeUninit, align_of, offset_of, size_of};++#[test]+fn action_layout_is_guarded_for_c_consumers() {+ assert_eq!(agent_desktop_ffi::types::action::AD_ACTION_SIZE, 96);+ assert_eq!(+ unsafe { common::ad_action_size() },+ agent_desktop_ffi::types::action::AD_ACTION_SIZE+ );+ assert_eq!(size_of::<AdAction>(), 96);+ assert_eq!(align_of::<AdAction>(), align_of::<usize>());++ let offsets = [+ offset_of!(AdAction, kind),+ offset_of!(AdAction, text),+ offset_of!(AdAction, scroll),+ offset_of!(AdAction, key),+ offset_of!(AdAction, drag),+ ];+ assert_eq!(offsets[0], 0);+ assert!(offsets.windows(2).all(|pair| pair[0] < pair[1]));++ let copied = unsafe {+ let action = MaybeUninit::<AdAction>::zeroed().assume_init();+ std::ptr::read(&action as *const AdAction)+ };+ assert_eq!(copied.kind, 0);+ assert_eq!(copied.drag.drop_delay_ms, 0);+}++#[test]+fn action_result_layout_is_guarded_for_c_consumers() {+ assert_eq!(+ agent_desktop_ffi::types::action_result::AD_ACTION_RESULT_SIZE,+ 40+ );+ assert_eq!(+ unsafe { common::ad_action_result_size() },+ agent_desktop_ffi::types::action_result::AD_ACTION_RESULT_SIZE+ );+ assert_eq!(+ agent_desktop_ffi::types::action_step::AD_ACTION_STEP_SIZE,+ 16+ );+ assert_eq!(+ unsafe { common::ad_action_step_size() },+ agent_desktop_ffi::types::action_step::AD_ACTION_STEP_SIZE+ );+ assert_eq!(+ size_of::<AdActionStep>(),+ agent_desktop_ffi::types::action_step::AD_ACTION_STEP_SIZE+ );+ assert_eq!(align_of::<AdActionStep>(), align_of::<usize>());+ assert_eq!(size_of::<AdActionResult>(), 40);+ assert_eq!(align_of::<AdActionResult>(), align_of::<usize>());+ assert_eq!(offset_of!(AdActionResult, action), 0);+ assert_eq!(offset_of!(AdActionResult, ref_id), 8);+ assert_eq!(offset_of!(AdActionResult, post_state), 16);+ assert_eq!(offset_of!(AdActionResult, steps), 24);+ assert_eq!(offset_of!(AdActionResult, step_count), 32);+ assert_eq!(offset_of!(AdActionStep, label), 0);+ assert_eq!(offset_of!(AdActionStep, outcome), 8);+}++#[test]+fn element_state_layout_is_guarded_for_c_consumers() {+ assert_eq!(+ agent_desktop_ffi::types::element_state::AD_ELEMENT_STATE_SIZE,+ 32+ );+ assert_eq!(+ unsafe { common::ad_element_state_size() },+ agent_desktop_ffi::types::element_state::AD_ELEMENT_STATE_SIZE+ );+ assert_eq!(size_of::<AdElementState>(), 32);+ assert_eq!(align_of::<AdElementState>(), align_of::<usize>());+ assert_eq!(offset_of!(AdElementState, role), 0);+}#[test]fn rect_and_point_layouts_are_memcpyable() {@@ -21,3 +99,57 @@ fn rect_and_point_layouts_are_memcpyable() {assert_eq!(copied.x, 3.0);assert_eq!(copied.y, 4.0);}++#[test]+fn ref_entry_input_caps_match_the_published_header_values() {+ assert_eq!(agent_desktop_ffi::types::ref_entry::AD_MAX_REF_STATES, 64);+ assert_eq!(agent_desktop_ffi::types::ref_entry::AD_MAX_REF_ACTIONS, 32);+ assert_eq!(+ agent_desktop_ffi::types::ref_entry::AD_MAX_REF_PATH_DEPTH,+ 128+ );+}++#[test]+fn ref_entry_layout_is_guarded_for_c_consumers() {+ assert_eq!(agent_desktop_ffi::types::ref_entry::AD_REF_ENTRY_SIZE, 192);+ assert_eq!(+ unsafe { common::ad_ref_entry_size() },+ agent_desktop_ffi::types::ref_entry::AD_REF_ENTRY_SIZE+ );+ assert_eq!(size_of::<AdRefEntry>(), 192);+ assert_eq!(align_of::<AdRefEntry>(), align_of::<usize>());+ assert_eq!(offset_of!(AdRefEntry, pid), 0);++ let offsets = [+ offset_of!(AdRefEntry, pid),+ offset_of!(AdRefEntry, role),+ offset_of!(AdRefEntry, name),+ offset_of!(AdRefEntry, value),+ offset_of!(AdRefEntry, description),+ offset_of!(AdRefEntry, states),+ offset_of!(AdRefEntry, state_count),+ offset_of!(AdRefEntry, available_actions),+ offset_of!(AdRefEntry, available_action_count),+ offset_of!(AdRefEntry, bounds),+ offset_of!(AdRefEntry, has_bounds),+ offset_of!(AdRefEntry, bounds_hash),+ offset_of!(AdRefEntry, has_bounds_hash),+ offset_of!(AdRefEntry, source_app),+ offset_of!(AdRefEntry, source_window_id),+ offset_of!(AdRefEntry, source_window_title),+ offset_of!(AdRefEntry, source_surface),+ offset_of!(AdRefEntry, root_ref),+ offset_of!(AdRefEntry, path_is_absolute),+ offset_of!(AdRefEntry, path),+ offset_of!(AdRefEntry, path_count),+ ];+ assert!(offsets.windows(2).all(|pair| pair[0] < pair[1]));++ let copied = unsafe {+ let entry = MaybeUninit::<AdRefEntry>::zeroed().assume_init();+ std::ptr::read(&entry as *const AdRefEntry)+ };+ assert_eq!(copied.pid, 0);+ assert_eq!(copied.path_count, 0);+}diff --git a/crates/ffi/tests/c_header_compile.rs b/crates/ffi/tests/c_header_compile.rsindex 5749d0614..2c8ded58d 100644--- a/crates/ffi/tests/c_header_compile.rs+++ b/crates/ffi/tests/c_header_compile.rs@@ -43,8 +43,6 @@ fn committed_header_compiles_with_every_public_enum_constant() {let tmp = std::env::temp_dir().join("agent_desktop_header_abi_test.c");let obj = std::env::temp_dir().join("agent_desktop_header_abi_test.o");- // Touch every named-constant family so a missing enum block in the header- // fails compilation with "undeclared identifier".let src = r#"#include <stdint.h>#include <stdbool.h>@@ -62,6 +60,19 @@ int main(void) {(void)AD_WINDOW_OP_KIND_RESIZE;(void)AD_IMAGE_FORMAT_PNG;(void)AD_RESULT_OK;+ _Static_assert(AD_ACTION_SIZE == sizeof(AdAction), "AdAction size macro drifted");+ _Static_assert(AD_DRAG_PARAMS_SIZE == sizeof(AdDragParams), "AdDragParams size macro drifted");+ _Static_assert(AD_ACTION_STEP_SIZE == sizeof(AdActionStep), "AdActionStep size macro drifted");+ _Static_assert(AD_ACTION_RESULT_SIZE == sizeof(AdActionResult), "AdActionResult size macro drifted");+ _Static_assert(offsetof(AdActionResult, steps) == 24, "AdActionResult.steps offset changed");+ _Static_assert(offsetof(AdActionResult, step_count) == 32, "AdActionResult.step_count offset changed");+ _Static_assert(offsetof(AdActionStep, outcome) == 8, "AdActionStep.outcome offset changed");+ _Static_assert(AD_ELEMENT_STATE_SIZE == sizeof(AdElementState), "AdElementState size macro drifted");+ (void)ad_action_step_size;+ (void)ad_ref_entry_size;+ (void)ad_last_error_details;+ _Static_assert(AD_REF_ENTRY_SIZE == sizeof(AdRefEntry), "AdRefEntry size macro drifted");+ _Static_assert(AD_REF_ENTRY_SIZE == 192, "AdRefEntry ABI size changed");return 0;}"#;diff --git a/crates/ffi/tests/common/mod.rs b/crates/ffi/tests/common/mod.rsindex 5892d2beb..521e0482a 100644--- a/crates/ffi/tests/common/mod.rs+++ b/crates/ffi/tests/common/mod.rs@@ -3,20 +3,27 @@pub use agent_desktop_ffi::error::AdResult;pub use agent_desktop_ffi::{- AdAction, AdActionResult, AdAdapter, AdAppList, AdDirection, AdDragParams, AdFindQuery,- AdKeyCombo, AdNativeHandle, AdPoint, AdPolicyKind, AdRect, AdRefEntry, AdScrollParams,- AdWindowInfo, AdWindowList,+ AdAction, AdActionResult, AdActionStep, AdAdapter, AdAppList, AdDirection, AdDragParams,+ AdElementState, AdFindQuery, AdKeyCombo, AdNativeHandle, AdPoint, AdPolicyKind, AdRect,+ AdRefEntry, AdScrollParams, AdWindowInfo, AdWindowList,};pub use std::ffi::CStr;pub use std::os::raw::c_char;unsafe extern "C" {+ pub fn ad_ref_entry_size() -> usize;+ pub fn ad_action_size() -> usize;+ pub fn ad_action_step_size() -> usize;+ pub fn ad_action_result_size() -> usize;+ pub fn ad_element_state_size() -> usize;+pub fn ad_adapter_create() -> *mut AdAdapter;pub fn ad_adapter_destroy(adapter: *mut AdAdapter);pub fn ad_check_permissions(adapter: *const AdAdapter) -> AdResult;pub fn ad_last_error_code() -> AdResult;pub fn ad_last_error_message() -> *const c_char;+ pub fn ad_last_error_details() -> *const c_char;pub fn ad_list_apps(adapter: *const AdAdapter, out: *mut *mut AdAppList) -> AdResult;pub fn ad_app_list_count(list: *const AdAppList) -> u32;@@ -52,6 +59,14 @@ unsafe extern "C" {policy: i32,out: *mut AdActionResult,) -> AdResult;+ pub fn ad_execute_ref_action_with_policy(+ adapter: *const AdAdapter,+ entry: *const AdRefEntry,+ action: *const AdAction,+ policy: i32,+ out: *mut AdActionResult,+ ) -> AdResult;+ pub fn ad_free_action_result(result: *mut AdActionResult);pub fn ad_find(adapter: *const AdAdapter,@@ -78,6 +93,37 @@ pub fn with_adapter<F: FnOnce(*mut AdAdapter)>(body: F) {}}+pub fn default_ref_entry() -> AdRefEntry {+ AdRefEntry {+ pid: 0,+ role: std::ptr::null(),+ name: std::ptr::null(),+ value: std::ptr::null(),+ description: std::ptr::null(),+ states: std::ptr::null(),+ state_count: 0,+ available_actions: std::ptr::null(),+ available_action_count: 0,+ bounds: AdRect {+ x: 0.0,+ y: 0.0,+ width: 0.0,+ height: 0.0,+ },+ has_bounds: false,+ bounds_hash: 0,+ has_bounds_hash: false,+ source_app: std::ptr::null(),+ source_window_id: std::ptr::null(),+ source_window_title: std::ptr::null(),+ source_surface: 0,+ root_ref: std::ptr::null(),+ path_is_absolute: false,+ path: std::ptr::null(),+ path_count: 0,+ }+}+pub fn default_action() -> AdAction {AdAction {kind: 0,@@ -95,6 +141,7 @@ pub fn default_action() -> AdAction {from: AdPoint { x: 0.0, y: 0.0 },to: AdPoint { x: 0.0, y: 0.0 },duration_ms: 0,+ drop_delay_ms: 0,},}}diff --git a/crates/ffi/tests/error_lifetime.rs b/crates/ffi/tests/error_lifetime.rsindex a03a7e9f5..5eb74779c 100644--- a/crates/ffi/tests/error_lifetime.rs+++ b/crates/ffi/tests/error_lifetime.rs@@ -12,9 +12,13 @@ unsafe extern "C" {out: *mut agent_desktop_ffi::AdWindowInfo,) -> AdResult;fn ad_last_error_message() -> *const std::os::raw::c_char;+ fn ad_last_error_details() -> *const std::os::raw::c_char;fn ad_last_error_code() -> AdResult;}+/// Worker-thread cargo tests hit the main-thread guard first (`ErrInternal`);+/// main-thread callers would see `ErrInvalidArgs`. The contract under test is+/// that any failure populates last-error and the pointer stays stable.#[test]fn last_error_pointer_survives_across_successful_calls() {unsafe {@@ -24,17 +28,15 @@ fn last_error_pointer_survives_across_successful_calls() {let bad_id = std::ptr::null();let mut out_win: agent_desktop_ffi::AdWindowInfo = std::mem::zeroed();let rc = ad_launch_app(adapter, bad_id, 0, &mut out_win);- // Worker-thread cargo tests hit the main-thread guard first- // (ErrInternal); main-thread callers would see ErrInvalidArgs.- // The contract we're testing here is that *some* failure- // populates last-error and the pointer stays stable.assert!(matches!(rc,AdResult::ErrInvalidArgs | AdResult::ErrInternal));let first_msg_ptr = ad_last_error_message();+ let first_details_ptr = ad_last_error_details();assert!(!first_msg_ptr.is_null());+ assert!(first_details_ptr.is_null());let first_msg = CStr::from_ptr(first_msg_ptr).to_string_lossy().into_owned();for _ in 0..10 {@@ -45,6 +47,7 @@ fn last_error_pointer_survives_across_successful_calls() {let later_msg_ptr = ad_last_error_message();assert_eq!(first_msg_ptr, later_msg_ptr);+ assert_eq!(first_details_ptr, ad_last_error_details());let later_msg = CStr::from_ptr(later_msg_ptr).to_string_lossy().into_owned();assert_eq!(first_msg, later_msg);assert_eq!(ad_last_error_code(), rc);diff --git a/crates/macos/examples/ax_probe.rs b/crates/macos/examples/ax_probe.rsindex 02c1c1dc3..d87d518fb 100644--- a/crates/macos/examples/ax_probe.rs+++ b/crates/macos/examples/ax_probe.rs@@ -36,14 +36,12 @@ fn probe_app(pid: i32) {let app = unsafe { AXUIElementCreateApplication(pid) };- // ── 1. What attributes does the app element expose? ──────────────────────println!("\n[1] App element attribute names:");let attr_names = get_attribute_names(app);for n in &attr_names {println!(" {n}");}- // ── 2. Get windows the right way ─────────────────────────────────────────println!("\n[2] Windows via kAXWindowsAttribute:");let windows = get_ax_children(app, kAXWindowsAttribute);println!(" count = {}", windows.len());@@ -57,7 +55,6 @@ fn probe_app(pid: i32) {role, title, pos, size);- // Children of this windowlet children = get_ax_children(*win, kAXChildrenAttribute);println!(" children = {}", children.len());for (ci, child) in children.iter().enumerate().take(8) {@@ -74,14 +71,12 @@ fn probe_app(pid: i32) {);println!(" pos={:?} size={:?}", cpos, csz);- // ── 3. Test kAXPressAction on each child ────────────────────────let ax_err = ax_press(*child);println!(" kAXPressAction → err={} (0=ok, -25200=fail, -25205=not_supported)",ax_err);- // ── 4. Test CGEvent click at element center ─────────────────────if let (Some(p), Some(s)) = (cpos, csz) {let cx = p.0 + s.0 / 2.0;let cy = p.1 + s.1 / 2.0;@@ -105,14 +100,12 @@ fn probe_app(pid: i32) {release_ax(*win);if i >= 1 {break;- } // only first 2 windows+ }}- // ── 5. Multi-attribute fetch speed comparison ─────────────────────────────println!("\n[5] AXUIElementCopyMultipleAttributeValues vs individual calls:");speed_test(app, pid);- // ── 6. Scroll event test ─────────────────────────────────────────────────println!("\n[6] CGEvent scroll at (400, 400):");let ok = cg_scroll(400.0, 400.0, 0, -3);println!(" result = {}", if ok { "OK" } else { "FAIL" });@@ -121,8 +114,6 @@ fn probe_app(pid: i32) {println!("\n=== Done ===");}-// ── Helpers ──────────────────────────────────────────────────────────────────-#[cfg(target_os = "macos")]fn get_attribute_names(el: accessibility_sys::AXUIElementRef) -> Vec<String> {use accessibility_sys::*;@@ -164,7 +155,6 @@ fn get_ax_children(if ptr.is_null() {return None;}- // Retain so the element lives past CFArray deallocunsafe { CFRetain(ptr as CFTypeRef) };Some(ptr)})@@ -320,7 +310,6 @@ fn speed_test(app: accessibility_sys::AXUIElementRef, _pid: i32) {};use std::time::Instant;- // Get a real window element to test onlet windows = get_ax_children(app, kAXWindowsAttribute);let el = if let Some(&w) = windows.first() {w@@ -340,7 +329,6 @@ fn speed_test(app: accessibility_sys::AXUIElementRef, _pid: i32) {let cf_refs: Vec<_> = cf_attrs.iter().map(|s| s.as_concrete_TypeRef()).collect();let names_arr = CFArray::from_copyable(&cf_refs);- // Multi-attrlet t = Instant::now();for _ in 0..100 {let mut res: CFTypeRef = std::ptr::null_mut();@@ -358,7 +346,6 @@ fn speed_test(app: accessibility_sys::AXUIElementRef, _pid: i32) {}let multi = t.elapsed();- // Individual attrslet t2 = Instant::now();for _ in 0..100 {for attr in &attrs {diff --git a/crates/macos/src/actions/ax_helpers.rs b/crates/macos/src/actions/ax_helpers.rsindex d4b654cb8..48989830f 100644--- a/crates/macos/src/actions/ax_helpers.rs+++ b/crates/macos/src/actions/ax_helpers.rs@@ -5,11 +5,16 @@ mod imp {use super::*;use crate::tree::AXElement;use accessibility_sys::{- AXUIElementIsAttributeSettable, AXUIElementPerformAction, AXUIElementSetAttributeValue,- AXUIElementSetMessagingTimeout, kAXErrorAPIDisabled, kAXErrorCannotComplete,- kAXErrorSuccess, kAXFocusedAttribute, kAXValueAttribute,+ AXUIElementCopyAttributeValue, AXUIElementIsAttributeSettable, AXUIElementPerformAction,+ AXUIElementSetAttributeValue, AXUIElementSetMessagingTimeout, kAXErrorAPIDisabled,+ kAXErrorCannotComplete, kAXErrorSuccess, kAXFocusedAttribute, kAXValueAttribute,+ };+ use core_foundation::{+ base::{CFType, CFTypeRef, TCFType},+ boolean::CFBoolean,+ number::CFNumber,+ string::CFString,};- use core_foundation::{base::TCFType, boolean::CFBoolean, string::CFString};use std::os::raw::c_uchar;pub(crate) fn try_ax_action(el: &AXElement, name: &str) -> bool {@@ -170,6 +175,69 @@ mod imp {set_ax_string_or_err(el, kAXValueAttribute, val)}+ /// Sets `AXValue` with a CoreFoundation type matching the element's+ /// current value: numeric controls (sliders, steppers, progress) hold a+ /// `CFNumber` and reject a `CFString`, so a typed write is required. Falls+ /// back to a string write when the current value is a string or absent.+ pub(crate) fn set_ax_value_coerced(el: &AXElement, value: &str) -> Result<(), AdapterError> {+ let cf_attr = CFString::new(kAXValueAttribute);+ let mut current: CFTypeRef = std::ptr::null_mut();+ let read = unsafe {+ AXUIElementCopyAttributeValue(el.0, cf_attr.as_concrete_TypeRef(), &mut current)+ };+ let coerced: Option<CFType> = if read == kAXErrorSuccess && !current.is_null() {+ let cur = unsafe { CFType::wrap_under_create_rule(current) };+ if cur.downcast::<CFNumber>().is_some() {+ Some(number_cf_from_str(value)?)+ } else if cur.downcast::<CFBoolean>().is_some() {+ let truthy = matches!(value, "1" | "true" | "True" | "on" | "yes");+ Some(CFBoolean::from(truthy).as_CFType())+ } else {+ None+ }+ } else {+ None+ };++ match coerced {+ Some(cf_value) => {+ let err = unsafe {+ AXUIElementSetAttributeValue(+ el.0,+ cf_attr.as_concrete_TypeRef(),+ cf_value.as_CFTypeRef(),+ )+ };+ if err != kAXErrorSuccess {+ ax_error_result(kAXValueAttribute, err)?;+ return Err(AdapterError::new(+ ErrorCode::ActionFailed,+ format!("AXSetAttributeValue(AXValue) failed (err={err})"),+ )+ .with_suggestion(+ "Value may be read-only or out of range. Try 'click' to focus then arrow keys.",+ ));+ }+ Ok(())+ }+ None => set_ax_string_or_err(el, kAXValueAttribute, value),+ }+ }++ fn number_cf_from_str(value: &str) -> Result<CFType, AdapterError> {+ if let Ok(i) = value.parse::<i64>() {+ return Ok(CFNumber::from(i).as_CFType());+ }+ if let Ok(f) = value.parse::<f64>() {+ return Ok(CFNumber::from(f).as_CFType());+ }+ Err(AdapterError::new(+ ErrorCode::InvalidArgs,+ format!("'{value}' is not a number; this control holds a numeric value"),+ )+ .with_suggestion("Pass a numeric value, e.g. set-value @e1 50"))+ }+pub(crate) fn ax_press(el: &AXElement) -> bool {try_ax_action(el, "AXPress")}@@ -253,6 +321,9 @@ mod imp {pub fn ax_set_value(_el: &AXElement, _val: &str) -> Result<(), AdapterError> {Err(AdapterError::not_supported("ax_set_value"))}+ pub fn set_ax_value_coerced(_el: &AXElement, _value: &str) -> Result<(), AdapterError> {+ Err(AdapterError::not_supported("set_ax_value_coerced"))+ }pub fn ax_press(_el: &AXElement) -> bool {false}@@ -264,6 +335,6 @@ mod imp {pub(crate) use imp::{ax_focus_or_err, ax_press, ax_set_value, element_role, ensure_visible, has_ax_action,is_attr_settable, list_ax_actions, set_ax_bool, set_ax_bool_or_err, set_ax_string_or_err,- set_messaging_timeout, try_action_from_list, try_ax_action, try_ax_action_retried,- try_ax_action_retried_or_err, try_each_ancestor, try_each_child,+ set_ax_value_coerced, set_messaging_timeout, try_action_from_list, try_ax_action,+ try_ax_action_retried, try_ax_action_retried_or_err, try_each_ancestor, try_each_child,};diff --git a/crates/macos/src/actions/chain.rs b/crates/macos/src/actions/chain.rsindex 13bb467bd..ebe33f529 100644--- a/crates/macos/src/actions/chain.rs+++ b/crates/macos/src/actions/chain.rs@@ -1,5 +1,5 @@-use agent_desktop_core::action::InteractionPolicy;use agent_desktop_core::error::{AdapterError, ErrorCode};+use agent_desktop_core::{action_step::ActionStep, interaction_policy::InteractionPolicy};use crate::actions::discovery::ElementCaps;use crate::tree::AXElement;@@ -11,7 +11,7 @@ pub(crate) use super::chain_step::ChainStep;#[cfg(target_os = "macos")]mod imp {use super::*;- use crate::actions::ax_helpers;+ use crate::actions::{ax_helpers, chain_verify};use std::time::{Duration, Instant};const DEFAULT_CHAIN_TIMEOUT: Duration = Duration::from_secs(10);@@ -23,11 +23,16 @@ mod imp {def: &ChainDef,ctx: &ChainContext,policy: InteractionPolicy,- ) -> Result<(), AdapterError> {+ ) -> Result<Vec<ActionStep>, AdapterError> {let deadline = ctx.deadline.unwrap_or_else(|| Instant::now() + chain_timeout());+ let ctx = ChainContext {+ dynamic_value: ctx.dynamic_value,+ deadline: Some(deadline),+ };let total = def.steps.len();+ let mut steps = Vec::new();if let Some(pid) = crate::system::app_ops::pid_from_element(el) {ax_helpers::set_messaging_timeout(&crate::tree::element_for_pid(pid), 1.0);@@ -37,6 +42,7 @@ mod imp {if def.pre_scroll {tracing::debug!("chain: pre-scroll AXScrollToVisible");ax_helpers::ensure_visible(el);+ steps.push(ActionStep::attempted("AXScrollToVisible"));}for (i, step) in def.steps.iter().enumerate() {@@ -47,10 +53,12 @@ mod imp {.iter().find(|s| matches!(s, ChainStep::CGClick { .. })){- if physical_click_permitted(policy) && execute_step(el, caps, cg, ctx, policy)?+ let label = step_label(cg);+ if physical_click_permitted(policy) && execute_step(el, caps, cg, &ctx, policy)?{tracing::debug!("chain: CGClick fallback succeeded");- return Ok(());+ steps.push(ActionStep::succeeded(label));+ return Ok(steps);}}return Err(@@ -60,16 +68,19 @@ mod imp {);}if matches!(step, ChainStep::CGClick { .. }) && !physical_click_permitted(policy) {- return Err(AdapterError::policy_denied(+ return Err(AdapterError::policy_denied_for_policy("Physical click fallback is disabled by the current interaction policy",+ policy,));}let label = step_label(step);- if execute_step(el, caps, step, ctx, policy)? {+ if execute_step(el, caps, step, &ctx, policy)? {tracing::debug!("chain: [{}/{}] {} -> success", i + 1, total, label);- return Ok(());+ steps.push(ActionStep::succeeded(label));+ return Ok(steps);}tracing::debug!("chain: [{}/{}] {} -> skip", i + 1, total, label);+ steps.push(ActionStep::skipped(label));}tracing::debug!("chain: all {total} steps exhausted");@@ -85,10 +96,12 @@ mod imp {ChainStep::SetBool { attr, .. } => attr,ChainStep::SetDynamic { attr } => attr,ChainStep::FocusThenSetDynamic { attr } => attr,+ ChainStep::IncrementToDynamic => "IncrementToDynamic",ChainStep::FocusThenClearByKeyboard => "FocusThenClearByKeyboard",ChainStep::ChildActions { .. } => "ChildActions",ChainStep::AncestorActions { .. } => "AncestorActions",ChainStep::Custom { label, .. } => label,+ ChainStep::CustomWithDeadline { label, .. } => label,ChainStep::CGClick { .. } => "CGClick",}}@@ -136,6 +149,11 @@ mod imp {set_dynamic_verified(el, attr, value)}+ ChainStep::IncrementToDynamic => match ctx.dynamic_value {+ Some(value) => increment_to_value(el, value, ctx.deadline),+ None => Ok(false),+ },+ChainStep::FocusThenClearByKeyboard => {if !policy.allow_focus_steal {return Ok(false);@@ -181,7 +199,9 @@ mod imp {*limit,)),- ChainStep::Custom { label: _, func } => func(el, caps),+ ChainStep::Custom { label: _, func } => func(el),++ ChainStep::CustomWithDeadline { label: _, func } => func(el, ctx.deadline),ChainStep::CGClick { button, count } => {Ok(@@ -207,8 +227,12 @@ mod imp {}fn set_dynamic_verified(el: &AXElement, attr: &str, value: &str) -> Result<bool, AdapterError> {- ax_helpers::set_ax_string_or_err(el, attr, value)?;- Ok(dynamic_write_had_effect(+ if attr == "AXValue" {+ ax_helpers::set_ax_value_coerced(el, value)?;+ } else {+ ax_helpers::set_ax_string_or_err(el, attr, value)?;+ }+ Ok(chain_verify::dynamic_write_had_effect(attr,ax_helpers::element_role(el).as_deref(),value,@@ -216,69 +240,93 @@ mod imp {))}- fn set_bool_verified(el: &AXElement, attr: &str, value: bool) -> Result<bool, AdapterError> {- Ok(ax_helpers::set_ax_bool_or_err(el, attr, value)?- && bool_write_had_effect(attr, value, crate::tree::copy_bool_attr(el, attr)))+ /// Drives AXIncrement/AXDecrement until the control reaches `target`.+ /// Steppers and some sliders expose no settable AXValue but step through+ /// these actions. Stops on reaching the target or on no observable+ /// progress (the action stopped moving the value). Deadline expiry is a+ /// hard error: the control may sit at a half-applied value, and silently+ /// reporting "step failed" would mask that mutation as ACTION_FAILED with+ /// recovery guidance pointing the wrong way.+ fn increment_to_value(+ el: &AXElement,+ target: &str,+ deadline: Option<Instant>,+ ) -> Result<bool, AdapterError> {+ const MAX_INCREMENT_STEPS: usize = 1024;++ let target = match finite_target(target) {+ Some(target) => target,+ None => return Ok(false),+ };+ let read = || crate::tree::copy_value_typed(el).and_then(|v| v.parse::<f64>().ok());+ let mut current = match read() {+ Some(c) => c,+ None => return Ok(false),+ };+ let actions = ax_helpers::list_ax_actions(el);+ if !actions.iter().any(|action| action == "AXIncrement")+ && !actions.iter().any(|action| action == "AXDecrement")+ {+ return Ok(false);+ }+ let start = current;+ for _ in 0..MAX_INCREMENT_STEPS {+ if (current - target).abs() < 0.5 {+ return Ok(true);+ }+ if deadline.is_some_and(|dl| Instant::now() > dl) {+ return Err(chain_verify::increment_deadline_error(+ start, current, target,+ ));+ }+ let action = if current < target {+ "AXIncrement"+ } else {+ "AXDecrement"+ };+ if !ax_helpers::try_ax_action(el, action) {+ break;+ }+ match read() {+ Some(next) if (next - current).abs() >= f64::EPSILON => current = next,+ _ => break,+ }+ }+ if (current - target).abs() < 0.5 {+ return Ok(true);+ }+ if (current - start).abs() >= f64::EPSILON {+ return Err(chain_verify::increment_step_limit_error(+ start, current, target,+ ));+ }+ Ok(false)}- fn bool_write_had_effect(attr: &str, expected: bool, observed: Option<bool>) -> bool {- !matches!(- attr,- "AXExpanded" | "AXDisclosing" | "AXSelected" | "AXFocused"- ) || observed == Some(expected)+ fn finite_target(target: &str) -> Option<f64> {+ target.parse::<f64>().ok().filter(|value| value.is_finite())}- fn dynamic_write_had_effect(- attr: &str,- role: Option<&str>,- expected: &str,- observed: Option<&str>,- ) -> bool {- attr != "AXValue" || role == Some("AXSecureTextField") || observed == Some(expected)+ fn set_bool_verified(el: &AXElement, attr: &str, value: bool) -> Result<bool, AdapterError> {+ Ok(ax_helpers::set_ax_bool_or_err(el, attr, value)?+ && chain_verify::bool_write_had_effect(+ attr,+ value,+ crate::tree::copy_bool_attr(el, attr),+ ))}#[cfg(test)]mod tests {- use super::{bool_write_had_effect, dynamic_write_had_effect};-- #[test]- fn ax_value_write_requires_readback_match() {- assert!(!dynamic_write_had_effect(- "AXValue",- Some("AXTextField"),- "",- Some("unchanged")- ));- assert!(dynamic_write_had_effect(- "AXValue",- Some("AXTextField"),- "",- Some("")- ));- }-- #[test]- fn non_value_and_secure_writes_trust_ax_success() {- assert!(dynamic_write_had_effect(- "AXSelected",- Some("AXCheckBox"),- "true",- None- ));- assert!(dynamic_write_had_effect(- "AXValue",- Some("AXSecureTextField"),- "secret",- None- ));- }+ use super::finite_target;#[test]- fn bool_state_writes_require_readback_match_for_stateful_attrs() {- assert!(bool_write_had_effect("AXExpanded", true, Some(true)));- assert!(!bool_write_had_effect("AXExpanded", true, Some(false)));- assert!(!bool_write_had_effect("AXExpanded", false, None));- assert!(bool_write_had_effect("AXFoo", true, None));+ fn finite_target_rejects_non_finite_numbers() {+ assert_eq!(finite_target("42.5"), Some(42.5));+ assert_eq!(finite_target("NaN"), None);+ assert_eq!(finite_target("inf"), None);+ assert_eq!(finite_target("-inf"), None);+ assert_eq!(finite_target("not-a-number"), None);}}}@@ -293,7 +341,7 @@ mod imp {def: &ChainDef,_ctx: &ChainContext,_policy: InteractionPolicy,- ) -> Result<(), AdapterError> {+ ) -> Result<Vec<ActionStep>, AdapterError> {Err(AdapterError::new(ErrorCode::ActionFailed,"Chain execution not supported on this platform",diff --git a/crates/macos/src/actions/chain_defs.rs b/crates/macos/src/actions/chain_defs.rsindex 92f41de34..f2f80fea2 100644--- a/crates/macos/src/actions/chain_defs.rs+++ b/crates/macos/src/actions/chain_defs.rs@@ -6,11 +6,10 @@ mod imp {use crate::actions::{ax_helpers,chain::{ChainDef, ChainStep},- chain_menu_steps, chain_steps,- discovery::ElementCaps,+ chain_disclosure_steps, chain_menu_steps, chain_steps,};use crate::tree::AXElement;- use agent_desktop_core::action::{InteractionPolicy, MouseButton};+ use agent_desktop_core::{action::MouseButton, interaction_policy::InteractionPolicy};pub(crate) static CLICK_CHAIN: ChainDef = ChainDef {pre_scroll: true,@@ -97,41 +96,33 @@ mod imp {suggestion: "Try 'mouse-click --button right --xy X,Y'.",};+ /// Every step is verified against the element's disclosed state: a bare+ /// `AXExpand`/`AXSetAttributeValue` can return success without changing the+ /// control (SwiftUI disclosures do this), so an unverified action must not+ /// count as success. `expand_verified` tries the semantic action, then a+ /// press, and only reports success when the state actually flipped.pub(crate) static EXPAND_CHAIN: ChainDef = ChainDef {pre_scroll: false,- steps: &[- ChainStep::Action("AXExpand"),- ChainStep::SetBool {- attr: "AXExpanded",- value: true,- },- ChainStep::SetBool {- attr: "AXDisclosing",- value: true,- },- ],- suggestion: "Try 'click' to open it instead.",+ steps: &[ChainStep::CustomWithDeadline {+ label: "expand_verified",+ func: chain_disclosure_steps::press_to_expand,+ }],+ suggestion: "This control cannot be expanded via accessibility; try a physical 'click' on its disclosure triangle.",};pub(crate) static COLLAPSE_CHAIN: ChainDef = ChainDef {pre_scroll: false,- steps: &[- ChainStep::Action("AXCollapse"),- ChainStep::SetBool {- attr: "AXExpanded",- value: false,- },- ChainStep::SetBool {- attr: "AXDisclosing",- value: false,- },- ],- suggestion: "Try 'click' to close it instead.",+ steps: &[ChainStep::CustomWithDeadline {+ label: "collapse_verified",+ func: chain_disclosure_steps::press_to_collapse,+ }],+ suggestion: "This control cannot be collapsed via accessibility; try a physical 'click' on its disclosure triangle.",};const VALUE_STEPS: &[ChainStep] = &[ChainStep::SetDynamic { attr: "AXValue" },ChainStep::FocusThenSetDynamic { attr: "AXValue" },+ ChainStep::IncrementToDynamic,];pub(crate) static SET_VALUE_CHAIN: ChainDef = ChainDef {@@ -183,12 +174,17 @@ mod imp {suggestion: "Element may not be in a scrollable container.",};+ /// Only treats AXOpen as a real double-click when the element actually+ /// advertises it: `AXUIElementPerformAction` returns success for an+ /// unsupported action on some controls, which would make double-click claim+ /// success while doing nothing. Elements without AXOpen (e.g. a button that+ /// only fires on a true mouse double-click) require the physical path, which+ /// fails closed under the headless policy.pub(crate) fn double_click(el: &AXElement,- _caps: &ElementCaps,policy: InteractionPolicy,) -> Result<(), AdapterError> {- if ax_helpers::try_ax_action(el, "AXOpen") {+ if ax_helpers::has_ax_action(el, "AXOpen") && ax_helpers::try_ax_action(el, "AXOpen") {return Ok(());}crate::actions::dispatch::click_via_bounds(el, MouseButton::Left, 2, policy)@@ -196,7 +192,6 @@ mod imp {pub(crate) fn triple_click(el: &AXElement,- _caps: &ElementCaps,policy: InteractionPolicy,) -> Result<(), AdapterError> {crate::actions::dispatch::click_via_bounds(el, MouseButton::Left, 3, policy)diff --git a/crates/macos/src/actions/chain_disclosure_steps.rs b/crates/macos/src/actions/chain_disclosure_steps.rsnew file mode 100644index 000000000..abd63b83b--- /dev/null+++ b/crates/macos/src/actions/chain_disclosure_steps.rs@@ -0,0 +1,120 @@+#[cfg(target_os = "macos")]+mod imp {+ use crate::actions::ax_helpers;+ use crate::tree::AXElement;+ use agent_desktop_core::error::AdapterError;++ /// Expands a disclosure that toggles via press (no settable `AXExpanded`).+ /// Idempotent: a no-op when already expanded; otherwise presses and+ /// confirms the disclosed state flipped.+ pub(crate) fn press_to_expand(+ el: &AXElement,+ chain_deadline: Option<std::time::Instant>,+ ) -> Result<bool, AdapterError> {+ press_toggle_disclosure(el, true, chain_deadline)+ }++ /// Collapses a press-toggled disclosure, mirroring [`press_to_expand`].+ pub(crate) fn press_to_collapse(+ el: &AXElement,+ chain_deadline: Option<std::time::Instant>,+ ) -> Result<bool, AdapterError> {+ press_toggle_disclosure(el, false, chain_deadline)+ }++ /// Tries the semantic action / settable attribute, then a press. Each is+ /// confirmed against the disclosed state; an action that succeeds at the AX+ /// layer but does not move the control is not counted. A settle wait that+ /// was truncated by the chain deadline is a hard TIMEOUT (mirroring the+ /// increment path): the press may still land after the truncated wait, so+ /// reporting a plain step failure would mask a possible mutation as+ /// ACTION_FAILED.+ fn press_toggle_disclosure(+ el: &AXElement,+ want_expanded: bool,+ chain_deadline: Option<std::time::Instant>,+ ) -> Result<bool, AdapterError> {+ if disclosed_state(el) == Some(want_expanded) {+ return Ok(true);+ }+ let action = if want_expanded {+ "AXExpand"+ } else {+ "AXCollapse"+ };+ if ax_helpers::has_ax_action(el, action) {+ let _ = ax_helpers::try_ax_action_retried_or_err(el, action)?;+ if disclosure_settled(el, want_expanded, chain_deadline)? {+ return Ok(true);+ }+ }+ if ax_helpers::is_attr_settable(el, "AXExpanded") {+ let _ = ax_helpers::set_ax_bool_or_err(el, "AXExpanded", want_expanded)?;+ if disclosure_settled(el, want_expanded, chain_deadline)? {+ return Ok(true);+ }+ }+ if ax_helpers::has_ax_action(el, "AXPress")+ && ax_helpers::try_ax_action_retried_or_err(el, "AXPress")?+ && disclosure_settled(el, want_expanded, chain_deadline)?+ {+ return Ok(true);+ }+ Ok(false)+ }++ /// Polls for the disclosed state instead of a fixed settle sleep: fast UIs+ /// confirm on the first read, while animated disclosures get up to the+ /// settle budget. The budget is capped to the chain's remaining deadline;+ /// an exit forced by that cap (rather than the full budget elapsing) is+ /// reported as `DeadlineExpired`, never as a plain failure. At least one+ /// state read always happens, even with the deadline already past.+ fn disclosure_settled(+ el: &AXElement,+ want_expanded: bool,+ chain_deadline: Option<std::time::Instant>,+ ) -> Result<bool, AdapterError> {+ use std::time::{Duration, Instant};++ const POLL_INTERVAL: Duration = Duration::from_millis(20);+ const SETTLE_BUDGET: Duration = Duration::from_millis(200);++ let budget_end = Instant::now() + SETTLE_BUDGET;+ let deadline = chain_deadline.map_or(budget_end, |dl| dl.min(budget_end));+ let truncated = deadline < budget_end;+ loop {+ if disclosed_state(el) == Some(want_expanded) {+ return Ok(true);+ }+ let now = Instant::now();+ if now >= deadline {+ return if truncated {+ Err(crate::actions::chain_verify::disclosure_deadline_error(+ want_expanded,+ disclosed_state(el),+ ))+ } else {+ Ok(false)+ };+ }+ std::thread::sleep(POLL_INTERVAL.min(deadline - now));+ }+ }++ fn disclosed_state(el: &AXElement) -> Option<bool> {+ crate::tree::copy_bool_attr(el, "AXExpanded")+ .or_else(|| crate::tree::copy_bool_attr(el, "AXDisclosing"))+ .or_else(|| value_as_bool(el))+ }++ fn value_as_bool(el: &AXElement) -> Option<bool> {+ match crate::tree::copy_value_typed(el).as_deref() {+ Some("1" | "true" | "True") => Some(true),+ Some("0" | "false" | "False") => Some(false),+ _ => None,+ }+ }+}++#[cfg(target_os = "macos")]+pub(crate) use imp::{press_to_collapse, press_to_expand};diff --git a/crates/macos/src/actions/chain_menu_steps.rs b/crates/macos/src/actions/chain_menu_steps.rsindex e62a7ec87..d59f731fb 100644--- a/crates/macos/src/actions/chain_menu_steps.rs+++ b/crates/macos/src/actions/chain_menu_steps.rs@@ -1,17 +1,14 @@#[cfg(target_os = "macos")]mod imp {- use crate::actions::{ax_helpers, discovery::ElementCaps};+ use crate::actions::ax_helpers;use crate::tree::AXElement;use agent_desktop_core::error::AdapterError;- pub(crate) fn show_menu(el: &AXElement, _caps: &ElementCaps) -> Result<bool, AdapterError> {+ pub(crate) fn show_menu(el: &AXElement) -> Result<bool, AdapterError> {show_menu_on_element(el)}- pub(crate) fn show_menu_on_ancestors(- el: &AXElement,- _caps: &ElementCaps,- ) -> Result<bool, AdapterError> {+ pub(crate) fn show_menu_on_ancestors(el: &AXElement) -> Result<bool, AdapterError> {let mut current = crate::tree::copy_element_attr(el, "AXParent");for _ in 0..3 {let Some(parent) = current else {@@ -25,10 +22,7 @@ mod imp {Ok(false)}- pub(crate) fn show_menu_on_children(- el: &AXElement,- _caps: &ElementCaps,- ) -> Result<bool, AdapterError> {+ pub(crate) fn show_menu_on_children(el: &AXElement) -> Result<bool, AdapterError> {for child in crate::tree::copy_ax_array(el, "AXChildren").unwrap_or_default().iter()@@ -41,10 +35,7 @@ mod imp {Ok(false)}- pub(crate) fn select_then_show_menu(- el: &AXElement,- _caps: &ElementCaps,- ) -> Result<bool, AdapterError> {+ pub(crate) fn select_then_show_menu(el: &AXElement) -> Result<bool, AdapterError> {if !select_containing_item(el)? {return Ok(false);}@@ -52,10 +43,7 @@ mod imp {show_menu_on_element(el)}- pub(crate) fn select_then_selected_items_menu(- el: &AXElement,- _caps: &ElementCaps,- ) -> Result<bool, AdapterError> {+ pub(crate) fn select_then_selected_items_menu(el: &AXElement) -> Result<bool, AdapterError> {if !select_containing_item(el)? {tracing::debug!("selected-items menu: could not select containing item");return Ok(false);@@ -135,29 +123,22 @@ mod imp {}fn element_text_contains(el: &AXElement, needle: &str, depth: usize) -> bool {- if depth > 8 {- return false;- }+ find_descendant_value(el, depth, &|candidate| {+ element_own_text_contains(candidate, needle).then_some(())+ })+ .is_some()+ }++ fn element_own_text_contains(el: &AXElement, needle: &str) -> bool {["AXTitle", "AXDescription", "AXValue", "AXHelp"].into_iter().filter_map(|attr| crate::tree::copy_string_attr(el, attr)).any(|value| value.contains(needle))- || crate::tree::copy_ax_array(el, "AXChildren")- .unwrap_or_default()- .iter()- .any(|child| element_text_contains(child, needle, depth + 1))}fn select_containing_item(el: &AXElement) -> Result<bool, AdapterError> {Ok(ax_helpers::set_ax_bool_or_err(el, "AXSelected", true)?- || crate::actions::chain_steps::try_select_containing_item(- el,- &ElementCaps {- settable_focus: false,- settable_selected: false,- settable_disclosing: false,- },- )?)+ || crate::actions::chain_steps::try_select_containing_item(el)?)}fn window_ancestor(el: &AXElement) -> Option<AXElement> {@@ -173,9 +154,10 @@ mod imp {}fn selected_items_menu_button(root: &AXElement) -> Option<AXElement> {- find_descendant(root, 0, &|el| {- crate::tree::copy_string_attr(el, "AXRole").as_deref() == Some("AXMenuButton")- && is_selected_items_control(el)+ find_descendant_value(root, 0, &|el| {+ (crate::tree::copy_string_attr(el, "AXRole").as_deref() == Some("AXMenuButton")+ && is_selected_items_control(el))+ .then(|| el.clone())})}@@ -186,7 +168,10 @@ mod imp {.any(|value| {let matches = selected_items_text(&value);if matches {- tracing::debug!("selected-items menu: matched control text {value:?}");+ tracing::debug!(+ text_chars = value.chars().count(),+ "selected-items menu: matched control text"+ );}matches})@@ -197,19 +182,19 @@ mod imp {value.contains("selected item")}- fn find_descendant(+ fn find_descendant_value<T>(el: &AXElement,depth: usize,- predicate: &impl Fn(&AXElement) -> bool,- ) -> Option<AXElement> {+ mapper: &impl Fn(&AXElement) -> Option<T>,+ ) -> Option<T> {if depth > 8 {return None;}- if predicate(el) {- return Some(el.clone());+ if let Some(value) = mapper(el) {+ return Some(value);}for child in crate::tree::copy_ax_array(el, "AXChildren").unwrap_or_default() {- if let Some(found) = find_descendant(&child, depth + 1, predicate) {+ if let Some(found) = find_descendant_value(&child, depth + 1, mapper) {return Some(found);}}@@ -219,27 +204,27 @@ mod imp {#[cfg(not(target_os = "macos"))]mod imp {- use crate::actions::discovery::ElementCaps;use crate::tree::AXElement;+ use agent_desktop_core::error::AdapterError;- pub fn show_menu(_el: &AXElement, _caps: &ElementCaps) -> bool {- false+ pub(crate) fn show_menu(_el: &AXElement) -> Result<bool, AdapterError> {+ Ok(false)}- pub fn show_menu_on_ancestors(_el: &AXElement, _caps: &ElementCaps) -> bool {- false+ pub(crate) fn show_menu_on_ancestors(_el: &AXElement) -> Result<bool, AdapterError> {+ Ok(false)}- pub fn show_menu_on_children(_el: &AXElement, _caps: &ElementCaps) -> bool {- false+ pub(crate) fn show_menu_on_children(_el: &AXElement) -> Result<bool, AdapterError> {+ Ok(false)}- pub fn select_then_show_menu(_el: &AXElement, _caps: &ElementCaps) -> bool {- false+ pub(crate) fn select_then_show_menu(_el: &AXElement) -> Result<bool, AdapterError> {+ Ok(false)}- pub fn select_then_selected_items_menu(_el: &AXElement, _caps: &ElementCaps) -> bool {- false+ pub(crate) fn select_then_selected_items_menu(_el: &AXElement) -> Result<bool, AdapterError> {+ Ok(false)}}diff --git a/crates/macos/src/actions/chain_step.rs b/crates/macos/src/actions/chain_step.rsindex 7a99c5ef4..40e1739cf 100644--- a/crates/macos/src/actions/chain_step.rs+++ b/crates/macos/src/actions/chain_step.rs@@ -1,6 +1,6 @@use agent_desktop_core::{action::MouseButton, error::AdapterError};-use crate::{actions::discovery::ElementCaps, tree::AXElement};+use crate::tree::AXElement;pub(crate) enum ChainStep {Action(&'static str),@@ -14,6 +14,10 @@ pub(crate) enum ChainStep {FocusThenSetDynamic {attr: &'static str,},+ /// Converges a stepper/slider to the dynamic target value via repeated+ /// AXIncrement/AXDecrement actions, for controls whose AXValue is not+ /// directly settable.+ IncrementToDynamic,FocusThenClearByKeyboard,ChildActions {actions: &'static [&'static str],@@ -25,7 +29,13 @@ pub(crate) enum ChainStep {},Custom {label: &'static str,- func: fn(&AXElement, &ElementCaps) -> Result<bool, AdapterError>,+ func: fn(&AXElement) -> Result<bool, AdapterError>,+ },+ /// Like `Custom`, for steps that poll for a settled state and must cap+ /// that settle wait to the chain's remaining deadline budget.+ CustomWithDeadline {+ label: &'static str,+ func: fn(&AXElement, Option<std::time::Instant>) -> Result<bool, AdapterError>,},CGClick {button: MouseButton,diff --git a/crates/macos/src/actions/chain_steps.rs b/crates/macos/src/actions/chain_steps.rsindex 2cdd98f53..7b35debd6 100644--- a/crates/macos/src/actions/chain_steps.rs+++ b/crates/macos/src/actions/chain_steps.rs@@ -1,21 +1,14 @@#[cfg(target_os = "macos")]mod imp {- use crate::actions::{ax_helpers, discovery::ElementCaps};+ use crate::actions::ax_helpers;use crate::tree::AXElement;use agent_desktop_core::error::AdapterError;- pub(crate) fn do_verified_press(- el: &AXElement,- caps: &ElementCaps,- ) -> Result<bool, AdapterError> {- dispatch_verified_press(el, caps, crate::actions::chain_web_steps::is_in_webarea(el))+ pub(crate) fn do_verified_press(el: &AXElement) -> Result<bool, AdapterError> {+ dispatch_verified_press(el, crate::actions::chain_web_steps::is_in_webarea(el))}- fn dispatch_verified_press(- el: &AXElement,- _caps: &ElementCaps,- in_web: bool,- ) -> Result<bool, AdapterError> {+ fn dispatch_verified_press(el: &AXElement, in_web: bool) -> Result<bool, AdapterError> {if !in_web {return verified_press_native(el);}@@ -36,7 +29,7 @@ mod imp {return ax_helpers::try_ax_action_retried_or_err(el, "AXPress");}tracing::debug!("verified_press: native element in container, using AXPress");- let selected_before = crate::tree::element::copy_bool_attr(el, "AXSelected");+ let selected_before = crate::tree::copy_bool_attr(el, "AXSelected");if !ax_helpers::try_ax_action_retried_or_err(el, "AXPress")? {return Ok(false);}@@ -44,7 +37,7 @@ mod imp {return Ok(true);}std::thread::sleep(std::time::Duration::from_millis(50));- let selected_after = crate::tree::element::copy_bool_attr(el, "AXSelected");+ let selected_after = crate::tree::copy_bool_attr(el, "AXSelected");if selected_after == Some(true) {return Ok(true);}@@ -55,10 +48,7 @@ mod imp {Ok(false)}- pub(crate) fn try_value_relay(- el: &AXElement,- _caps: &ElementCaps,- ) -> Result<bool, AdapterError> {+ pub(crate) fn try_value_relay(el: &AXElement) -> Result<bool, AdapterError> {if !ax_helpers::list_ax_actions(el).is_empty() {return Ok(false);}@@ -110,7 +100,11 @@ mod imp {std::thread::sleep(std::time::Duration::from_millis(150));let final_val = crate::tree::copy_string_attr(&owner, "AXValue");if final_val.as_deref() != Some(label.as_str()) {- tracing::debug!("value_relay: reverted to {final_val:?}, expected {label:?}");+ tracing::debug!(+ observed_chars = final_val.as_deref().map(|value| value.chars().count()),+ expected_chars = label.chars().count(),+ "value_relay: value reverted"+ );}Ok(final_val.as_deref() == Some(label.as_str()))}@@ -127,7 +121,6 @@ mod imp {pub(crate) fn element_is_visible_in_scroll_context(el: &AXElement,- _caps: &ElementCaps,) -> Result<bool, AdapterError> {use accessibility_sys::kAXRoleAttribute;let Some(bounds) = crate::tree::read_bounds(el) else {@@ -167,10 +160,7 @@ mod imp {x >= outer.x && x <= outer.x + outer.width && y >= outer.y && y <= outer.y + outer.height}- pub(crate) fn try_show_alternate_ui(- el: &AXElement,- _caps: &ElementCaps,- ) -> Result<bool, AdapterError> {+ pub(crate) fn try_show_alternate_ui(el: &AXElement) -> Result<bool, AdapterError> {if !ax_helpers::has_ax_action(el, "AXShowAlternateUI") {return Ok(false);}@@ -186,10 +176,7 @@ mod imp {))}- pub(crate) fn try_parent_row_select(- el: &AXElement,- _caps: &ElementCaps,- ) -> Result<bool, AdapterError> {+ pub(crate) fn try_parent_row_select(el: &AXElement) -> Result<bool, AdapterError> {use accessibility_sys::kAXRoleAttribute;let Some(parent) = crate::tree::copy_element_attr(el, "AXParent") else {return Ok(false);@@ -204,10 +191,7 @@ mod imp {ax_helpers::set_ax_bool_or_err(&parent, "AXSelected", true)}- pub(crate) fn try_select_containing_item(- el: &AXElement,- _caps: &ElementCaps,- ) -> Result<bool, AdapterError> {+ pub(crate) fn try_select_containing_item(el: &AXElement) -> Result<bool, AdapterError> {let mut current = Some(el.clone());for _ in 0..4 {let Some(candidate) = current else {@@ -244,30 +228,13 @@ mod imp {}fn set_container_selection(candidate: &AXElement, attr: &str) -> bool {- use accessibility_sys::{AXUIElementSetAttributeValue, kAXErrorSuccess};- use core_foundation::{- array::CFArray,- base::{CFRetain, CFType, CFTypeRef, TCFType},- string::CFString,- };let Some(container) = crate::tree::copy_element_attr(candidate, "AXParent") else {return false;};if !ax_helpers::is_attr_settable(&container, attr) {return false;}- unsafe { CFRetain(candidate.0 as CFTypeRef) };- let candidate_cf = unsafe { CFType::wrap_under_create_rule(candidate.0 as CFTypeRef) };- let selected = CFArray::from_CFTypes(&[candidate_cf]);- let cf_attr = CFString::new(attr);- let err = unsafe {- AXUIElementSetAttributeValue(- container.0,- cf_attr.as_concrete_TypeRef(),- selected.as_CFTypeRef(),- )- };- err == kAXErrorSuccess+ set_single_element_selection(&container, candidate, attr)}fn container_selection_contains(candidate: &AXElement, attr: &str) -> bool {@@ -281,16 +248,8 @@ mod imp {.any(|selected| crate::tree::same_element(selected, candidate))}- pub(crate) fn try_select_via_parent(- el: &AXElement,- _caps: &ElementCaps,- ) -> Result<bool, AdapterError> {- use accessibility_sys::{AXUIElementSetAttributeValue, kAXErrorSuccess, kAXRoleAttribute};- use core_foundation::{- array::CFArray,- base::{CFRetain, CFType, CFTypeRef, TCFType},- string::CFString,- };+ pub(crate) fn try_select_via_parent(el: &AXElement) -> Result<bool, AdapterError> {+ use accessibility_sys::kAXRoleAttribute;let Some(parent) = crate::tree::copy_element_attr(el, "AXParent") else {return Ok(false);};@@ -303,24 +262,35 @@ mod imp {if !ax_helpers::is_attr_settable(&parent, "AXSelectedRows") {return Ok(false);}- unsafe { CFRetain(el.0 as CFTypeRef) };- let el_cf = unsafe { CFType::wrap_under_create_rule(el.0 as CFTypeRef) };- let arr = CFArray::from_CFTypes(&[el_cf]);- let cf_attr = CFString::new("AXSelectedRows");+ Ok(set_single_element_selection(&parent, el, "AXSelectedRows"))+ }++ fn set_single_element_selection(+ container: &AXElement,+ element: &AXElement,+ attr: &str,+ ) -> bool {+ use accessibility_sys::{AXUIElementSetAttributeValue, kAXErrorSuccess};+ use core_foundation::{+ array::CFArray,+ base::{CFRetain, CFType, CFTypeRef, TCFType},+ string::CFString,+ };+ unsafe { CFRetain(element.0 as CFTypeRef) };+ let element_cf = unsafe { CFType::wrap_under_create_rule(element.0 as CFTypeRef) };+ let selected = CFArray::from_CFTypes(&[element_cf]);+ let cf_attr = CFString::new(attr);let err = unsafe {AXUIElementSetAttributeValue(- parent.0,+ container.0,cf_attr.as_concrete_TypeRef(),- arr.as_CFTypeRef(),+ selected.as_CFTypeRef(),)};- Ok(err == kAXErrorSuccess)+ err == kAXErrorSuccess}- pub(crate) fn try_custom_actions(- el: &AXElement,- _caps: &ElementCaps,- ) -> Result<bool, AdapterError> {+ pub(crate) fn try_custom_actions(el: &AXElement) -> Result<bool, AdapterError> {let has = !crate::tree::copy_ax_array(el, "AXCustomActions").unwrap_or_default().is_empty();@@ -329,4 +299,11 @@ mod imp {}#[cfg(target_os = "macos")]-pub(crate) use imp::*;+pub(crate) use imp::{+ do_verified_press, element_is_visible_in_scroll_context, try_custom_actions,+ try_parent_row_select, try_select_containing_item, try_select_via_parent,+ try_show_alternate_ui, try_value_relay,+};++#[cfg(all(test, target_os = "macos"))]+pub(crate) use imp::{center_is_inside, rect_has_area};diff --git a/crates/macos/src/actions/chain_verify.rs b/crates/macos/src/actions/chain_verify.rsnew file mode 100644index 000000000..336d10dd4--- /dev/null+++ b/crates/macos/src/actions/chain_verify.rs@@ -0,0 +1,219 @@+use agent_desktop_core::error::AdapterError;++/// Error for a chain deadline expiring mid-increment. Unlike a plain step+/// "skip", expiry can leave the control at a half-applied value, so the+/// error must be TIMEOUT (not ACTION_FAILED) and must carry the observed+/// state — the caller cannot read post-state on the error path. `kind`+/// discriminates this details schema from other TIMEOUT payloads.+pub(crate) fn increment_deadline_error(start: f64, current: f64, target: f64) -> AdapterError {+ AdapterError::timeout("Chain deadline expired while stepping the value toward the target")+ .with_suggestion(+ "Re-read the element value before retrying; increase the timeout or AGENT_DESKTOP_CHAIN_TIMEOUT_MS for slow controls.",+ )+ .with_details(serde_json::json!({+ "kind": "chain_deadline",+ "value_before": start,+ "value_at_timeout": current,+ "target": target,+ "mutated": (current - start).abs() >= f64::EPSILON,+ }))+}++pub(crate) fn increment_step_limit_error(start: f64, current: f64, target: f64) -> AdapterError {+ AdapterError::new(+ agent_desktop_core::error::ErrorCode::ActionFailed,+ "Chain step limit was reached while stepping the value toward the target",+ )+ .with_suggestion(+ "Re-read the element value before retrying; the control may expose a step size too small for the requested target.",+ )+ .with_details(serde_json::json!({+ "kind": "chain_step_limit",+ "value_before": start,+ "value_at_limit": current,+ "target": target,+ "mutated": (current - start).abs() >= f64::EPSILON,+ }))+}++/// Error for the chain deadline truncating a disclosure settle wait. The+/// triggering action may still land after the truncated wait, so the+/// outcome is unknown — TIMEOUT with the observed state, mirroring+/// [`increment_deadline_error`], never a plain step failure.+pub(crate) fn disclosure_deadline_error(+ want_expanded: bool,+ observed: Option<bool>,+) -> AdapterError {+ AdapterError::timeout("Chain deadline expired while waiting for the disclosure to settle")+ .with_suggestion(+ "Re-read the element's expanded state before retrying; increase the timeout or AGENT_DESKTOP_CHAIN_TIMEOUT_MS for slow apps.",+ )+ .with_details(serde_json::json!({+ "kind": "chain_deadline",+ "wanted_expanded": want_expanded,+ "observed_expanded": observed,+ }))+}++pub(crate) fn bool_write_had_effect(attr: &str, expected: bool, observed: Option<bool>) -> bool {+ !matches!(+ attr,+ "AXExpanded" | "AXDisclosing" | "AXSelected" | "AXFocused"+ ) || observed == Some(expected)+}++pub(crate) fn dynamic_write_had_effect(+ attr: &str,+ role: Option<&str>,+ expected: &str,+ observed: Option<&str>,+) -> bool {+ if attr != "AXValue" || role == Some("AXSecureTextField") {+ return true;+ }+ observed == Some(expected) || numbers_match(expected, observed)+}++/// Numeric controls report their value back in their own format (a slider+/// set to `50` reads back as `50.00`), so compare numerically when both+/// sides parse as numbers.+fn numbers_match(expected: &str, observed: Option<&str>) -> bool {+ match (+ expected.parse::<f64>(),+ observed.and_then(|o| o.parse::<f64>().ok()),+ ) {+ (Ok(a), Some(b)) => {+ let tolerance = 1e-6_f64.max(a.abs().max(b.abs()) * 1e-9);+ (a - b).abs() <= tolerance+ }+ _ => false,+ }+}++#[cfg(test)]+mod tests {+ use super::{+ bool_write_had_effect, dynamic_write_had_effect, increment_deadline_error,+ increment_step_limit_error,+ };++ #[test]+ fn increment_deadline_error_is_timeout_and_reports_partial_mutation() {+ let err = increment_deadline_error(0.0, 37.0, 80.0);++ assert_eq!(err.code, agent_desktop_core::error::ErrorCode::Timeout);+ let details = err.details.expect("details must carry the observed state");+ assert_eq!(details["value_before"], 0.0);+ assert_eq!(details["value_at_timeout"], 37.0);+ assert_eq!(details["target"], 80.0);+ assert_eq!(details["mutated"], true);+ assert!(err.suggestion.is_some());+ }++ #[test]+ fn increment_deadline_error_reports_unmutated_state() {+ let err = increment_deadline_error(5.0, 5.0, 9.0);++ let details = err.details.unwrap();+ assert_eq!(details["mutated"], false);+ assert_eq!(details["kind"], "chain_deadline");+ }++ #[test]+ fn increment_step_limit_error_reports_partial_mutation() {+ let err = increment_step_limit_error(0.0, 1024.0, 5000.0);++ assert_eq!(err.code, agent_desktop_core::error::ErrorCode::ActionFailed);+ let details = err.details.unwrap();+ assert_eq!(details["kind"], "chain_step_limit");+ assert_eq!(details["value_at_limit"], 1024.0);+ assert_eq!(details["mutated"], true);+ }++ #[test]+ fn disclosure_deadline_error_is_timeout_with_observed_state() {+ let err = super::disclosure_deadline_error(true, Some(false));++ assert_eq!(err.code, agent_desktop_core::error::ErrorCode::Timeout);+ let details = err.details.expect("details must carry the observed state");+ assert_eq!(details["kind"], "chain_deadline");+ assert_eq!(details["wanted_expanded"], true);+ assert_eq!(details["observed_expanded"], false);+ assert!(err.suggestion.is_some());+ }++ #[test]+ fn disclosure_deadline_error_reports_unreadable_state_as_null() {+ let err = super::disclosure_deadline_error(false, None);++ assert!(err.details.unwrap()["observed_expanded"].is_null());+ }++ #[test]+ fn ax_value_write_requires_readback_match() {+ assert!(!dynamic_write_had_effect(+ "AXValue",+ Some("AXTextField"),+ "",+ Some("unchanged")+ ));+ assert!(dynamic_write_had_effect(+ "AXValue",+ Some("AXTextField"),+ "",+ Some("")+ ));+ }++ #[test]+ fn non_value_and_secure_writes_trust_ax_success() {+ assert!(dynamic_write_had_effect(+ "AXSelected",+ Some("AXCheckBox"),+ "true",+ None+ ));+ assert!(dynamic_write_had_effect(+ "AXValue",+ Some("AXSecureTextField"),+ "secret",+ None+ ));+ }++ #[test]+ fn bool_state_writes_require_readback_match_for_stateful_attrs() {+ assert!(bool_write_had_effect("AXExpanded", true, Some(true)));+ assert!(!bool_write_had_effect("AXExpanded", true, Some(false)));+ assert!(!bool_write_had_effect("AXExpanded", false, None));+ assert!(bool_write_had_effect("AXFoo", true, None));+ }++ #[test]+ fn numeric_value_write_matches_reformatted_readback() {+ assert!(dynamic_write_had_effect(+ "AXValue",+ Some("AXSlider"),+ "50",+ Some("50.00")+ ));+ assert!(dynamic_write_had_effect(+ "AXValue",+ Some("AXIncrementor"),+ "3",+ Some("3")+ ));+ assert!(dynamic_write_had_effect(+ "AXValue",+ Some("AXSlider"),+ "50",+ Some("50.0000004")+ ));+ assert!(!dynamic_write_had_effect(+ "AXValue",+ Some("AXSlider"),+ "50",+ Some("12.00")+ ));+ }+}diff --git a/crates/macos/src/actions/chain_web_steps.rs b/crates/macos/src/actions/chain_web_steps.rsindex 39d68e683..9775c6d9b 100644--- a/crates/macos/src/actions/chain_web_steps.rs+++ b/crates/macos/src/actions/chain_web_steps.rs@@ -115,4 +115,4 @@ mod imp {mod imp {}#[cfg(target_os = "macos")]-pub(crate) use imp::*;+pub(crate) use imp::{activate_web_element, is_in_webarea};diff --git a/crates/macos/src/actions/dispatch.rs b/crates/macos/src/actions/dispatch.rsindex f50571f84..3767cb9ee 100644--- a/crates/macos/src/actions/dispatch.rs+++ b/crates/macos/src/actions/dispatch.rs@@ -1,9 +1,10 @@use agent_desktop_core::{- action::{- Action, ActionRequest, ActionResult, InteractionPolicy, MouseButton, MouseEvent,- MouseEventKind, Point,- },+ action::{Action, MouseButton, MouseEvent, MouseEventKind, Point},+ action_request::ActionRequest,+ action_result::ActionResult,+ element_state::ElementState,error::{AdapterError, ErrorCode},+ interaction_policy::InteractionPolicy,};#[cfg(target_os = "macos")]@@ -23,13 +24,17 @@ mod imp {policy: InteractionPolicy,) -> Result<(), AdapterError> {if !policy.allow_cursor_move || !policy.allow_focus_steal {- return Err(AdapterError::policy_denied(+ return Err(AdapterError::policy_denied_for_policy("Physical click fallback is disabled by the current interaction policy",+ policy,));}if let Some(pid) = crate::system::app_ops::pid_from_element(el) {let _ = crate::system::app_ops::ensure_app_focused(pid);}+ if let Some(window) = crate::tree::copy_element_attr(el, "AXWindow") {+ crate::system::window_ops::raise_window(&window);+ }let bounds = crate::tree::read_bounds(el).ok_or_else(|| {AdapterError::new(ErrorCode::ActionFailed, "Element has no readable bounds").with_suggestion("AX action failed and CGEvent fallback unavailable")@@ -63,7 +68,8 @@ mod imp {request: &ActionRequest,) -> Result<ActionResult, AdapterError> {let action = &request.action;- let label = action_label(action);+ let label = action.name();+ let mut steps = Vec::new();tracing::debug!("action: perform {label}");match action {Action::Click => {@@ -72,12 +78,17 @@ mod imp {dynamic_value: None,deadline: None,};- execute_chain(el, &caps, &chain_defs::CLICK_CHAIN, &ctx, request.policy)?;+ steps.extend(execute_chain(+ el,+ &caps,+ &chain_defs::CLICK_CHAIN,+ &ctx,+ request.policy,+ )?);}Action::DoubleClick => {- let caps = discovery::discover(el);- chain_defs::double_click(el, &caps, request.policy)?;+ chain_defs::double_click(el, request.policy)?;}Action::RightClick => {@@ -86,13 +97,13 @@ mod imp {dynamic_value: None,deadline: None,};- execute_chain(+ steps.extend(execute_chain(el,&caps,&chain_defs::RIGHT_CLICK_CHAIN,&ctx,request.policy,- )?;+ )?);}Action::Toggle => {@@ -102,16 +113,16 @@ mod imp {Action::SetValue(val) => {let caps = discovery::discover(el);let ctx = ChainContext {- dynamic_value: Some(val),+ dynamic_value: Some(val.as_str()),deadline: None,};- execute_chain(+ steps.extend(execute_chain(el,&caps,&chain_defs::SET_VALUE_CHAIN,&ctx,request.policy,- )?;+ )?);}Action::SetFocus => {@@ -120,11 +131,17 @@ mod imp {dynamic_value: None,deadline: None,};- execute_chain(el, &caps, &chain_defs::FOCUS_CHAIN, &ctx, request.policy)?;+ steps.extend(execute_chain(+ el,+ &caps,+ &chain_defs::FOCUS_CHAIN,+ &ctx,+ request.policy,+ )?);}Action::TypeText(text) => {- crate::actions::type_text::execute_type(el, text, request.policy)?;+ crate::actions::type_text::execute_type(el, text.as_str(), request.policy)?;}Action::PressKey(combo) => {@@ -137,7 +154,13 @@ mod imp {dynamic_value: None,deadline: None,};- execute_chain(el, &caps, &chain_defs::EXPAND_CHAIN, &ctx, request.policy)?;+ steps.extend(execute_chain(+ el,+ &caps,+ &chain_defs::EXPAND_CHAIN,+ &ctx,+ request.policy,+ )?);}Action::Collapse => {@@ -146,11 +169,17 @@ mod imp {dynamic_value: None,deadline: None,};- execute_chain(el, &caps, &chain_defs::COLLAPSE_CHAIN, &ctx, request.policy)?;+ steps.extend(execute_chain(+ el,+ &caps,+ &chain_defs::COLLAPSE_CHAIN,+ &ctx,+ request.policy,+ )?);}Action::Select(value) => {- crate::actions::extras::select_value(el, value)?;+ crate::actions::extras::select_value(el, value.as_str())?;}Action::Scroll(direction, amount) => {@@ -166,8 +195,7 @@ mod imp {}Action::TripleClick => {- let caps = discovery::discover(el);- chain_defs::triple_click(el, &caps, request.policy)?;+ chain_defs::triple_click(el, request.policy)?;}Action::ScrollTo => {@@ -176,13 +204,13 @@ mod imp {dynamic_value: None,deadline: None,};- execute_chain(+ steps.extend(execute_chain(el,&caps,&chain_defs::SCROLL_TO_CHAIN,&ctx,request.policy,- )?;+ )?);}Action::Clear => {@@ -191,7 +219,13 @@ mod imp {dynamic_value: Some(""),deadline: None,};- execute_chain(el, &caps, &chain_defs::CLEAR_CHAIN, &ctx, request.policy)?;+ steps.extend(execute_chain(+ el,+ &caps,+ &chain_defs::CLEAR_CHAIN,+ &ctx,+ request.policy,+ )?);}Action::KeyDown(_) | Action::KeyUp(_) | Action::Hover | Action::Drag(_) => {@@ -204,19 +238,32 @@ mod imp {).with_suggestion("Use the top-level command (e.g. 'hover', 'drag', 'key-down') instead of targeting an element."));}-- _ => {- return Err(AdapterError::not_supported(&label));- }}- let mut result = ActionResult::new(label);+ let mut result = ActionResult::new(label).with_steps(steps);if let Some(state) = crate::actions::post_state::read_post_state(el, action) {+ verify_post_state(action, &state)?;result = result.with_state(state);}Ok(result)}+ fn verify_post_state(action: &Action, state: &ElementState) -> Result<(), AdapterError> {+ if matches!(action, Action::Clear)+ && state+ .value+ .as_deref()+ .is_some_and(|value| !value.is_empty())+ {+ return Err(AdapterError::new(+ ErrorCode::ActionFailed,+ "Clear reported success but element value is still non-empty",+ )+ .with_suggestion("Retry 'clear', or use 'press cmd+a' then 'press delete'."));+ }+ Ok(())+ }+pub(crate) fn ax_press_or_fail(el: &AXElement, context: &str) -> Result<(), AdapterError> {if !ax_helpers::ax_press(el) {return Err(AdapterError::new(@@ -227,6 +274,40 @@ mod imp {}Ok(())}++ #[cfg(test)]+ mod tests {+ use super::*;+ use agent_desktop_core::element_state::ElementState;++ #[test]+ fn clear_post_state_fails_when_value_remains() {+ let err = verify_post_state(+ &Action::Clear,+ &ElementState {+ role: "textfield".into(),+ states: vec![],+ value: Some("still here".into()),+ },+ )+ .unwrap_err();++ assert_eq!(err.code, ErrorCode::ActionFailed);+ }++ #[test]+ fn clear_post_state_accepts_empty_value() {+ verify_post_state(+ &Action::Clear,+ &ElementState {+ role: "textfield".into(),+ states: vec![],+ value: Some(String::new()),+ },+ )+ .unwrap();+ }+ }}#[cfg(not(target_os = "macos"))]@@ -246,31 +327,3 @@ pub(crate) use imp::perform_action;#[cfg(target_os = "macos")]pub(crate) use imp::{ax_press_or_fail, click_via_bounds};--fn action_label(action: &Action) -> String {- match action {- Action::Click => "click",- Action::DoubleClick => "double_click",- Action::RightClick => "right_click",- Action::TripleClick => "triple_click",- Action::SetValue(_) => "set_value",- Action::SetFocus => "set_focus",- Action::Expand => "expand",- Action::Collapse => "collapse",- Action::Select(_) => "select",- Action::Toggle => "toggle",- Action::Check => "check",- Action::Uncheck => "uncheck",- Action::Scroll(_, _) => "scroll",- Action::ScrollTo => "scroll_to",- Action::PressKey(_) => "press_key",- Action::KeyDown(_) => "key_down",- Action::KeyUp(_) => "key_up",- Action::TypeText(_) => "type_text",- Action::Clear => "clear",- Action::Hover => "hover",- Action::Drag(_) => "drag",- _ => "unknown",- }- .to_string()-}diff --git a/crates/macos/src/actions/mod.rs b/crates/macos/src/actions/mod.rsindex 185f9a64b..036c00c0e 100644--- a/crates/macos/src/actions/mod.rs+++ b/crates/macos/src/actions/mod.rs@@ -3,9 +3,11 @@ pub(crate) mod chain;mod chain_context;mod chain_def;pub(crate) mod chain_defs;+pub(crate) mod chain_disclosure_steps;pub(crate) mod chain_menu_steps;mod chain_step;pub(crate) mod chain_steps;+pub(crate) mod chain_verify;pub(crate) mod chain_web_steps;pub(crate) mod discovery;pub(crate) mod dispatch;diff --git a/crates/macos/src/actions/post_state.rs b/crates/macos/src/actions/post_state.rsindex 7022383b9..4ef378136 100644--- a/crates/macos/src/actions/post_state.rs+++ b/crates/macos/src/actions/post_state.rs@@ -1,4 +1,4 @@-use agent_desktop_core::action::{Action, ElementState};+use agent_desktop_core::{action::Action, adapter::LiveElement, element_state::ElementState};#[cfg(target_os = "macos")]pub(crate) fn read_post_state(@@ -6,11 +6,26 @@ pub(crate) fn read_post_state(action: &Action,) -> Option<ElementState> {let delay_ms = match action {- Action::Click | Action::Toggle | Action::Check | Action::Uncheck | Action::TypeText(_) => {- 50- }- Action::SetValue(_) | Action::Clear | Action::Expand | Action::Collapse => 0,- _ => return None,+ Action::Click | Action::TypeText(_) => 50,+ Action::Toggle+ | Action::Check+ | Action::Uncheck+ | Action::SetValue(_)+ | Action::Clear+ | Action::Expand+ | Action::Collapse => 0,+ Action::DoubleClick+ | Action::RightClick+ | Action::TripleClick+ | Action::SetFocus+ | Action::Select(_)+ | Action::Scroll(_, _)+ | Action::ScrollTo+ | Action::PressKey(_)+ | Action::KeyDown(_)+ | Action::KeyUp(_)+ | Action::Hover+ | Action::Drag(_) => return None,};if delay_ms > 0 {std::thread::sleep(std::time::Duration::from_millis(delay_ms));@@ -19,18 +34,47 @@ pub(crate) fn read_post_state(}pub(crate) fn read_element_state(el: &crate::tree::AXElement) -> ElementState {- let value = crate::tree::copy_value_typed(el);- let role = crate::actions::ax_helpers::element_role(el).unwrap_or_default();- let focused = crate::tree::element::copy_bool_attr(el, "AXFocused").unwrap_or(false);- let enabled = crate::tree::element::copy_bool_attr(el, "AXEnabled").unwrap_or(true);- let expanded = crate::tree::element::copy_bool_attr(el, "AXExpanded")- .or_else(|| crate::tree::element::copy_bool_attr(el, "AXDisclosing"))+ let attrs = crate::tree::element::fetch_node_attrs(el);+ let role = normalized_role(attrs.role.as_deref());+ element_state_from_attrs(attrs, role)+}++pub(crate) fn read_live_element(el: &crate::tree::AXElement) -> LiveElement {+ let attrs = crate::tree::element::fetch_node_attrs(el);+ let role = normalized_role(attrs.role.as_deref());+ let bounds = attrs.bounds;+ let has_scrollbars = attrs.has_scrollbars;+ let state = element_state_from_attrs(attrs, role.clone());+ LiveElement {+ state: Some(state),+ bounds,+ available_actions: Some(crate::tree::action_list::platform_available_actions(+ el,+ &role,+ has_scrollbars,+ )),+ }+}++pub(crate) fn read_live_actions(el: &crate::tree::AXElement) -> Vec<String> {+ let attrs = crate::tree::element::fetch_node_attrs(el);+ let role = normalized_role(attrs.role.as_deref());+ crate::tree::action_list::platform_available_actions(el, &role, attrs.has_scrollbars)+}++fn element_state_from_attrs(attrs: crate::tree::NodeAttrs, role: String) -> ElementState {+ let value = attrs.value;+ let focused = attrs.states.focused.unwrap_or(false);+ let expanded = attrs+ .states+ .expanded+ .or(attrs.states.disclosing).unwrap_or(false);let mut states = Vec::new();if focused {states.push("focused".into());}- if !enabled {+ if !attrs.states.enabled {states.push("disabled".into());}if expanded {@@ -46,6 +90,13 @@ pub(crate) fn read_element_state(el: &crate::tree::AXElement) -> ElementState {}}+fn normalized_role(ax_role: Option<&str>) -> String {+ ax_role+ .map(crate::tree::roles::ax_role_to_str)+ .unwrap_or("unknown")+ .to_string()+}+fn value_is_checked(value: Option<&str>) -> bool {matches!(value, Some("1" | "true"))}diff --git a/crates/macos/src/actions/scroll.rs b/crates/macos/src/actions/scroll.rsindex 9d2934e4e..9b0a102ba 100644--- a/crates/macos/src/actions/scroll.rs+++ b/crates/macos/src/actions/scroll.rs@@ -1,5 +1,8 @@#[cfg(target_os = "macos")]-use agent_desktop_core::error::{AdapterError, ErrorCode};+use agent_desktop_core::{+ error::{AdapterError, ErrorCode},+ interaction_policy::InteractionPolicy,+};#[cfg(target_os = "macos")]use crate::tree::AXElement;@@ -9,7 +12,7 @@ pub(crate) fn ax_scroll(el: &AXElement,direction: &agent_desktop_core::action::Direction,amount: u32,- policy: agent_desktop_core::action::InteractionPolicy,+ policy: InteractionPolicy,) -> Result<(), AdapterError> {use accessibility_sys::{AXUIElementPerformAction, AXUIElementSetAttributeValue, kAXErrorSuccess,@@ -80,7 +83,7 @@ pub(crate) fn ax_scroll(if policy.allow_focus_steal && try_focus_child_in_direction(target, direction) {return Ok(());}- if try_select_row_in_direction(target, direction) {+ if policy.allow_focus_steal && try_select_row_in_direction(target, direction) {return Ok(());}@@ -125,8 +128,9 @@ pub(crate) fn ax_scroll(}if policy.allow_focus_steal && !policy.allow_cursor_move {- return Err(AdapterError::policy_denied(+ return Err(AdapterError::policy_denied_for_policy("Cursor-moving scroll fallback is disabled by the current interaction policy",+ policy,));}diff --git a/crates/macos/src/actions/toggle_state.rs b/crates/macos/src/actions/toggle_state.rsindex 25cc34610..07d2d618a 100644--- a/crates/macos/src/actions/toggle_state.rs+++ b/crates/macos/src/actions/toggle_state.rs@@ -1,6 +1,6 @@use agent_desktop_core::{- action::InteractionPolicy,error::{AdapterError, ErrorCode},+ interaction_policy::InteractionPolicy,};use crate::{diff --git a/crates/macos/src/actions/type_text.rs b/crates/macos/src/actions/type_text.rsindex ee08987ba..6c3f50439 100644--- a/crates/macos/src/actions/type_text.rs+++ b/crates/macos/src/actions/type_text.rs@@ -1,7 +1,7 @@#[cfg(target_os = "macos")]use agent_desktop_core::{- action::InteractionPolicy,error::{AdapterError, ErrorCode},+ interaction_policy::InteractionPolicy,};#[cfg(target_os = "macos")]@@ -30,21 +30,34 @@ pub(crate) fn execute_type(crate::input::keyboard::synthesize_text(text)}+/// Restores the user's clipboard on every scope exit — success, error, or+/// panic — so a failure or early return mid-paste cannot leave the pasted text+/// behind. (A SIGKILL between set and restore is unpreventable in any process.)+#[cfg(target_os = "macos")]+struct ClipboardRestore {+ previous: crate::input::clipboard::ClipboardSnapshot,+}++#[cfg(target_os = "macos")]+impl Drop for ClipboardRestore {+ fn drop(&mut self) {+ let _ = self.previous.restore();+ }+}+#[cfg(target_os = "macos")]fn type_via_clipboard_paste(el: &AXElement, text: &str) -> Result<(), AdapterError> {let before = readable_value(el);- let previous = crate::input::clipboard::get().unwrap_or_default();+ let previous = crate::input::clipboard::ClipboardSnapshot::capture()?;+ let _restore = ClipboardRestore { previous };crate::input::clipboard::set(text)?;std::thread::sleep(std::time::Duration::from_millis(50));let combo = agent_desktop_core::action::KeyCombo {key: "v".into(),modifiers: vec![agent_desktop_core::action::Modifier::Cmd],};- let paste_result = crate::input::keyboard::synthesize_key(&combo);+ crate::input::keyboard::synthesize_key(&combo)?;std::thread::sleep(std::time::Duration::from_millis(100));- let restore_result = crate::input::clipboard::set(&previous);- paste_result?;- restore_result?;verify_paste_effect(before.as_deref(), readable_value(el).as_deref())}@@ -83,7 +96,7 @@ fn type_via_ax_value(el: &AXElement, text: &str) -> Result<(), AdapterError> {pub(crate) fn execute_type(_el: &crate::tree::AXElement,_text: &str,- _policy: agent_desktop_core::action::InteractionPolicy,+ _policy: agent_desktop_core::interaction_policy::InteractionPolicy,) -> Result<(), agent_desktop_core::error::AdapterError> {Err(agent_desktop_core::error::AdapterError::new(agent_desktop_core::error::ErrorCode::PlatformNotSupported,diff --git a/crates/macos/src/adapter.rs b/crates/macos/src/adapter.rsindex f3e4757d5..f7e1716d1 100644--- a/crates/macos/src/adapter.rs+++ b/crates/macos/src/adapter.rs@@ -1,10 +1,13 @@use agent_desktop_core::{PermissionReport,- action::{ActionRequest, ActionResult, DragParams, ElementState, MouseEvent, WindowOp},+ action::{DragParams, MouseEvent, WindowOp},+ action_request::ActionRequest,+ action_result::ActionResult,adapter::{- ImageBuffer, NativeHandle, PlatformAdapter, ScreenshotTarget, SnapshotSurface, TreeOptions,- WindowFilter,+ ImageBuffer, LiveElement, NativeHandle, PlatformAdapter, ScreenshotTarget, SnapshotSurface,+ TreeOptions, WindowFilter,},+ element_state::ElementState,error::AdapterError,node::{AccessibilityNode, AppInfo, Rect, SurfaceInfo, WindowInfo},notification::{NotificationFilter, NotificationIdentity, NotificationInfo},@@ -81,10 +84,18 @@ impl PlatformAdapter for MacOSAdapter {execute_action_impl(handle, request)}- fn resolve_element(&self, entry: &RefEntry) -> Result<NativeHandle, AdapterError> {+ fn resolve_element_strict(&self, entry: &RefEntry) -> Result<NativeHandle, AdapterError> {crate::tree::resolve::resolve_element_impl(entry)}+ fn resolve_element_strict_with_timeout(+ &self,+ entry: &RefEntry,+ timeout: std::time::Duration,+ ) -> Result<NativeHandle, AdapterError> {+ crate::tree::resolve::resolve_element_with_timeout(entry, timeout)+ }+fn release_handle(&self, handle: &NativeHandle) -> Result<(), AdapterError> {let raw = handle.as_raw();if raw.is_null() {@@ -108,6 +119,10 @@ impl PlatformAdapter for MacOSAdapter {crate::system::app_ops::focus_window_impl(win)}+ fn focus_app(&self, pid: i32) -> Result<(), AdapterError> {+ crate::system::app_ops::ensure_app_focused(pid)+ }+fn launch_app(&self, id: &str, timeout_ms: u64) -> Result<WindowInfo, AdapterError> {crate::system::app_ops::launch_app_impl(id, timeout_ms)}@@ -116,6 +131,10 @@ impl PlatformAdapter for MacOSAdapter {crate::system::app_ops::close_app_impl(id, force)}+ fn is_protected_process(&self, identifier: &str) -> bool {+ crate::system::app_ops::is_protected_process(identifier)+ }+fn screenshot(&self, target: ScreenshotTarget) -> Result<ImageBuffer, AdapterError> {match target {ScreenshotTarget::Window(pid) => crate::system::screenshot::capture_app(pid),@@ -136,7 +155,7 @@ impl PlatformAdapter for MacOSAdapter {&self,app_name: &str,combo: &agent_desktop_core::action::KeyCombo,- ) -> Result<agent_desktop_core::action::ActionResult, AdapterError> {+ ) -> Result<ActionResult, AdapterError> {crate::system::key_dispatch::press_for_app_impl(app_name, combo)}@@ -160,12 +179,10 @@ impl PlatformAdapter for MacOSAdapter {fn get_live_value(&self, handle: &NativeHandle) -> Result<Option<String>, AdapterError> {#[cfg(target_os = "macos")]{- use crate::tree::AXElement;- use std::mem::ManuallyDrop;- let el = ManuallyDrop::new(AXElement(- handle.as_raw() as accessibility_sys::AXUIElementRef- ));- Ok(crate::tree::copy_value_typed(&el))+ Ok(with_borrowed_ax_element(+ handle,+ crate::tree::copy_value_typed,+ ))}#[cfg(not(target_os = "macos"))]Err(AdapterError::not_supported("get_live_value"))@@ -174,26 +191,43 @@ impl PlatformAdapter for MacOSAdapter {fn get_live_state(&self, handle: &NativeHandle) -> Result<Option<ElementState>, AdapterError> {#[cfg(target_os = "macos")]{- use crate::tree::AXElement;- use std::mem::ManuallyDrop;- let el = ManuallyDrop::new(AXElement(- handle.as_raw() as accessibility_sys::AXUIElementRef- ));- Ok(Some(crate::actions::post_state::read_element_state(&el)))+ Ok(Some(with_borrowed_ax_element(+ handle,+ crate::actions::post_state::read_element_state,+ )))}#[cfg(not(target_os = "macos"))]Err(AdapterError::not_supported("get_live_state"))}+ fn get_live_actions(&self, handle: &NativeHandle) -> Result<Option<Vec<String>>, AdapterError> {+ #[cfg(target_os = "macos")]+ {+ Ok(Some(with_borrowed_ax_element(+ handle,+ crate::actions::post_state::read_live_actions,+ )))+ }+ #[cfg(not(target_os = "macos"))]+ Err(AdapterError::not_supported("get_live_actions"))+ }++ fn get_live_element(&self, handle: &NativeHandle) -> Result<LiveElement, AdapterError> {+ #[cfg(target_os = "macos")]+ {+ Ok(with_borrowed_ax_element(+ handle,+ crate::actions::post_state::read_live_element,+ ))+ }+ #[cfg(not(target_os = "macos"))]+ Err(AdapterError::not_supported("get_live_element"))+ }+fn get_element_bounds(&self, handle: &NativeHandle) -> Result<Option<Rect>, AdapterError> {#[cfg(target_os = "macos")]{- use crate::tree::AXElement;- use std::mem::ManuallyDrop;- let el = ManuallyDrop::new(AXElement(- handle.as_raw() as accessibility_sys::AXUIElementRef- ));- Ok(crate::tree::read_bounds(&el))+ Ok(with_borrowed_ax_element(handle, crate::tree::read_bounds))}#[cfg(not(target_os = "macos"))]{@@ -262,29 +296,25 @@ impl PlatformAdapter for MacOSAdapter {handle: &NativeHandle,opts: &TreeOptions,) -> Result<AccessibilityNode, AdapterError> {- use crate::tree::AXElement;- use std::mem::ManuallyDrop;-- let el = ManuallyDrop::new(AXElement(- handle.as_raw() as accessibility_sys::AXUIElementRef- ));- let mut ancestors = FxHashSet::default();- let context = crate::tree::TreeBuildContext::empty(opts.include_bounds);- crate::tree::build_subtree(- &el,- 0,- 0,- opts.max_depth,- &mut ancestors,- opts.skeleton,- &context,- )- .ok_or_else(|| {- AdapterError::new(- agent_desktop_core::error::ErrorCode::ElementNotFound,- "Element no longer exists in accessibility tree",+ with_borrowed_ax_element(handle, |el| {+ let mut ancestors = FxHashSet::default();+ let context = crate::tree::TreeBuildContext::empty(opts.include_bounds);+ crate::tree::build_subtree(+ el,+ 0,+ 0,+ opts.max_depth,+ &mut ancestors,+ opts.skeleton,+ &context,)- .with_suggestion("Run 'snapshot' to refresh refs, then retry.")+ .ok_or_else(|| {+ AdapterError::new(+ agent_desktop_core::error::ErrorCode::ElementNotFound,+ "Element no longer exists in accessibility tree",+ )+ .with_suggestion("Run 'snapshot' to refresh refs, then retry.")+ })})}}@@ -293,11 +323,18 @@ fn execute_action_impl(handle: &NativeHandle,request: ActionRequest,) -> Result<ActionResult, AdapterError> {- use crate::tree::AXElement;+ with_borrowed_ax_element(handle, |el| crate::actions::perform_action(el, &request))+}++#[cfg(target_os = "macos")]+fn with_borrowed_ax_element<T>(+ handle: &NativeHandle,+ f: impl FnOnce(&crate::tree::AXElement) -> T,+) -> T {use std::mem::ManuallyDrop;- let el = ManuallyDrop::new(AXElement(+ let el = ManuallyDrop::new(crate::tree::AXElement(handle.as_raw() as accessibility_sys::AXUIElementRef));- crate::actions::perform_action(&el, &request)+ f(&el)}diff --git a/crates/macos/src/input/clipboard.rs b/crates/macos/src/input/clipboard.rsindex 2435f954e..c4fc89275 100644--- a/crates/macos/src/input/clipboard.rs+++ b/crates/macos/src/input/clipboard.rs@@ -17,6 +17,38 @@ mod imp {static NSPasteboardTypeString: Id;}+ pub(crate) struct ClipboardSnapshot {+ items: Id,+ }++ impl ClipboardSnapshot {+ pub(crate) fn capture() -> Result<Self, AdapterError> {+ unsafe {+ let pb = pasteboard()?;+ Ok(Self {+ items: retain_pasteboard_items(pb),+ })+ }+ }++ pub(crate) fn restore(&self) -> Result<(), AdapterError> {+ unsafe {+ let pb = pasteboard()?;+ clear_pasteboard(pb);+ if !self.items.is_null() && !write_objects(pb, self.items) {+ return Err(AdapterError::internal("NSPasteboard writeObjects: failed"));+ }+ Ok(())+ }+ }+ }++ impl Drop for ClipboardSnapshot {+ fn drop(&mut self) {+ unsafe { release_object(self.items) };+ }+ }+fn pasteboard() -> Result<Id, AdapterError> {unsafe {let cls = objc_getClass(c"NSPasteboard".as_ptr());@@ -38,56 +70,115 @@ mod imp {tracing::debug!("clipboard: get");unsafe {let pb = pasteboard()?;+ let Some(result) = read_string(pb) else {+ tracing::debug!("clipboard: get -> empty");+ return Ok(String::new());+ };+ tracing::debug!("clipboard: get -> {} chars", result.len());+ Ok(result)+ }+ }++ pub fn set(text: &str) -> Result<(), AdapterError> {+ tracing::debug!("clipboard: set {} chars", text.len());+ unsafe {+ let pb = pasteboard()?;+ let previous = ClipboardSnapshot::capture()?;+ clear_pasteboard(pb);+ if !write_string(pb, text) {+ let _ = previous.restore();+ return Err(AdapterError::internal(+ "NSPasteboard setString:forType: failed",+ ));+ }+ Ok(())+ }+ }++ pub fn clear() -> Result<(), AdapterError> {+ tracing::debug!("clipboard: clear");+ unsafe {+ let pb = pasteboard()?;+ clear_pasteboard(pb);+ Ok(())+ }+ }++ unsafe fn read_string(pb: Id) -> Option<String> {+ unsafe {let sel = sel_registerName(c"stringForType:".as_ptr());let send: unsafe extern "C" fn(Id, Sel, Id) -> Id =std::mem::transmute(objc_msgSend as *const c_void);let ns_string = send(pb, sel, NSPasteboardTypeString);if ns_string.is_null() {- tracing::debug!("clipboard: get -> empty");- return Ok(String::new());+ return None;}let cf_str = core_foundation::string::CFString::wrap_under_get_rule(ns_string as core_foundation_sys::string::CFStringRef,);- let result = cf_str.to_string();- tracing::debug!("clipboard: get -> {} chars", result.len());- Ok(result)+ Some(cf_str.to_string())}}- pub fn set(text: &str) -> Result<(), AdapterError> {- tracing::debug!("clipboard: set {} chars", text.len());+ unsafe fn retain_pasteboard_items(pb: Id) -> Id {+ unsafe {+ let items_sel = sel_registerName(c"pasteboardItems".as_ptr());+ let send: unsafe extern "C" fn(Id, Sel) -> Id =+ std::mem::transmute(objc_msgSend as *const c_void);+ retain_object(send(pb, items_sel))+ }+ }++ unsafe fn retain_object(object: Id) -> Id {+ if object.is_null() {+ return object;+ }+ unsafe {+ let sel = sel_registerName(c"retain".as_ptr());+ let send: unsafe extern "C" fn(Id, Sel) -> Id =+ std::mem::transmute(objc_msgSend as *const c_void);+ send(object, sel)+ }+ }++ unsafe fn release_object(object: Id) {+ if object.is_null() {+ return;+ }+ unsafe {+ let sel = sel_registerName(c"release".as_ptr());+ let send: unsafe extern "C" fn(Id, Sel) =+ std::mem::transmute(objc_msgSend as *const c_void);+ send(object, sel);+ }+ }++ unsafe fn clear_pasteboard(pb: Id) {unsafe {- let pb = pasteboard()?;let clear_sel = sel_registerName(c"clearContents".as_ptr());let send_void: unsafe extern "C" fn(Id, Sel) =std::mem::transmute(objc_msgSend as *const c_void);send_void(pb, clear_sel);+ }+ }+ unsafe fn write_string(pb: Id, text: &str) -> bool {+ unsafe {let cf_text = core_foundation::string::CFString::new(text);let ns_text = cf_text.as_concrete_TypeRef() as Id;let set_sel = sel_registerName(c"setString:forType:".as_ptr());let send_two: unsafe extern "C" fn(Id, Sel, Id, Id) -> bool =std::mem::transmute(objc_msgSend as *const c_void);- let ok = send_two(pb, set_sel, ns_text, NSPasteboardTypeString);- if !ok {- return Err(AdapterError::internal(- "NSPasteboard setString:forType: failed",- ));- }- Ok(())+ send_two(pb, set_sel, ns_text, NSPasteboardTypeString)}}- pub fn clear() -> Result<(), AdapterError> {- tracing::debug!("clipboard: clear");+ unsafe fn write_objects(pb: Id, objects: Id) -> bool {unsafe {- let pb = pasteboard()?;- let sel = sel_registerName(c"clearContents".as_ptr());- let send: unsafe extern "C" fn(Id, Sel) =+ let sel = sel_registerName(c"writeObjects:".as_ptr());+ let send: unsafe extern "C" fn(Id, Sel, Id) -> bool =std::mem::transmute(objc_msgSend as *const c_void);- send(pb, sel);- Ok(())+ send(pb, sel, objects)}}}@@ -107,6 +198,19 @@ mod imp {pub fn clear() -> Result<(), AdapterError> {Err(AdapterError::not_supported("clipboard_clear"))}++ pub(crate) struct ClipboardSnapshot;++ impl ClipboardSnapshot {+ pub(crate) fn capture() -> Result<Self, AdapterError> {+ Err(AdapterError::not_supported("clipboard_snapshot"))+ }++ pub(crate) fn restore(&self) -> Result<(), AdapterError> {+ Err(AdapterError::not_supported("clipboard_snapshot"))+ }+ }}+pub(crate) use imp::ClipboardSnapshot;pub use imp::{clear, get, set};diff --git a/crates/macos/src/input/mouse.rs b/crates/macos/src/input/mouse.rsindex eb0da8d34..42c25219b 100644--- a/crates/macos/src/input/mouse.rs+++ b/crates/macos/src/input/mouse.rs@@ -31,6 +31,17 @@ mod imp {}pub fn synthesize_drag(params: DragParams) -> Result<(), AdapterError> {+ drag_sequence(params).map_err(|err| {+ if err.suggestion.is_some() {+ return err;+ }+ err.with_suggestion(+ "The drag was aborted: the button was released back at the origin (best-effort) and no drop was committed at the destination. The cursor ends at the origin. Re-check the source state before retrying.",+ )+ })+ }++ fn drag_sequence(params: DragParams) -> Result<(), AdapterError> {tracing::debug!("mouse: drag ({:.0},{:.0}) -> ({:.0},{:.0}) duration={}ms",params.from.x,@@ -39,29 +50,131 @@ mod imp {params.to.y,params.duration_ms.unwrap_or(300));+ use std::thread::sleep;+ use std::time::Duration;++ const PICKUP_DELAY_MS: u64 = 200;+ const DEFAULT_DROP_DELAY_MS: u64 = 500;+ const DWELL_TICK_MS: u64 = 16;+let from = CGPoint::new(params.from.x, params.from.y);let to = CGPoint::new(params.to.x, params.to.y);let duration_ms = params.duration_ms.unwrap_or(300);- let steps = (duration_ms / 16).max(4) as usize;- let step_delay = std::time::Duration::from_millis(duration_ms / steps as u64);+ let steps = (duration_ms / DWELL_TICK_MS).max(4) as usize;+ let step_delay = Duration::from_millis(duration_ms / steps as u64);+ let source = event_source()?;- post_event(CGEventType::LeftMouseDown, from, CGMouseButton::Left)?;- std::thread::sleep(std::time::Duration::from_millis(200));+ post_event_with_source(+ &source,+ CGEventType::LeftMouseDown,+ from,+ CGMouseButton::Left,+ )?;+ let mut release = MouseUpGuard {+ source: &source,+ origin: from,+ armed: true,+ };+ sleep(Duration::from_millis(PICKUP_DELAY_MS));for i in 1..=steps {let t = i as f64 / steps as f64;let x = params.from.x + (params.to.x - params.from.x) * t;let y = params.from.y + (params.to.y - params.from.y) * t;- post_event(+ post_event_with_source(+ &source,CGEventType::LeftMouseDragged,CGPoint::new(x, y),CGMouseButton::Left,)?;- std::thread::sleep(step_delay);+ sleep(step_delay);}- std::thread::sleep(std::time::Duration::from_millis(500));- post_event(CGEventType::LeftMouseUp, to, CGMouseButton::Left)+ dwell_over_destination(+ &source,+ to,+ params.drop_delay_ms.unwrap_or(DEFAULT_DROP_DELAY_MS),+ DWELL_TICK_MS,+ )?;+ release.release_at(to)+ }++ /// Releases the left mouse button exactly once. Every fallible step between+ /// `LeftMouseDown` and the final `LeftMouseUp` would otherwise leave the+ /// button logically held down system-wide on error. The happy path calls+ /// `release_at(to)`, which disarms only after the up event actually posts.+ /// On any early return, `Drop` cancels the gesture by dragging back to the+ /// origin and releasing there — never at the unreached destination, where+ /// CGEvent's embedded coordinates would silently commit the aborted drag+ /// as a completed drop. The cancel is best-effort twice over: the+ /// corrective posts themselves can fail (typically the same systemic+ /// CGEventSource failure that aborted the drag, leaving the button held+ /// and the cursor wherever the last successful event put it), and a+ /// drop target under the origin still sees a self-drop, which most+ /// targets treat as a no-op.+ struct MouseUpGuard<'a> {+ source: &'a CGEventSource,+ origin: CGPoint,+ armed: bool,+ }++ impl MouseUpGuard<'_> {+ fn release_at(&mut self, point: CGPoint) -> Result<(), AdapterError> {+ post_event_with_source(+ self.source,+ CGEventType::LeftMouseUp,+ point,+ CGMouseButton::Left,+ )?;+ self.armed = false;+ Ok(())+ }+ }++ impl Drop for MouseUpGuard<'_> {+ fn drop(&mut self) {+ if self.armed {+ let _ = post_event_with_source(+ self.source,+ CGEventType::LeftMouseDragged,+ self.origin,+ CGMouseButton::Left,+ );+ let _ = post_event_with_source(+ self.source,+ CGEventType::LeftMouseUp,+ self.origin,+ CGMouseButton::Left,+ );+ }+ }+ }++ /// Holds the dragged item over the destination while the drop target+ /// activates. Posting `LeftMouseDragged` on each tick (instead of a dead+ /// sleep) keeps the destination engaged so the release registers as a+ /// drop rather than a bare drag — macOS targets can drop the highlight if+ /// no movement arrives. A zero delay still posts one settling event.+ fn dwell_over_destination(+ source: &CGEventSource,+ to: CGPoint,+ drop_delay_ms: u64,+ tick_ms: u64,+ ) -> Result<(), AdapterError> {+ use std::thread::sleep;+ use std::time::Duration;++ let ticks = drop_delay_ms.div_ceil(tick_ms).max(1);+ for _ in 0..ticks {+ post_event_with_source(+ source,+ CGEventType::LeftMouseDragged,+ to,+ CGMouseButton::Left,+ )?;+ sleep(Duration::from_millis(tick_ms));+ }+ Ok(())}fn synthesize_click(@@ -106,12 +219,25 @@ mod imp {point: CGPoint,button: CGMouseButton,) -> Result<CGEvent, AdapterError> {- let source = CGEventSource::new(CGEventSourceStateID::HIDSystemState)- .map_err(|()| AdapterError::internal("Failed to create CGEventSource"))?;- CGEvent::new_mouse_event(source, event_type, point, button)+ let source = event_source()?;+ create_event_with_source(&source, event_type, point, button)+ }++ fn create_event_with_source(+ source: &CGEventSource,+ event_type: CGEventType,+ point: CGPoint,+ button: CGMouseButton,+ ) -> Result<CGEvent, AdapterError> {+ CGEvent::new_mouse_event(source.clone(), event_type, point, button).map_err(|()| AdapterError::internal("CGEvent::new_mouse_event failed"))}+ fn event_source() -> Result<CGEventSource, AdapterError> {+ CGEventSource::new(CGEventSourceStateID::HIDSystemState)+ .map_err(|()| AdapterError::internal("Failed to create CGEventSource"))+ }+fn post_event(event_type: CGEventType,point: CGPoint,@@ -122,6 +248,17 @@ mod imp {Ok(())}+ fn post_event_with_source(+ source: &CGEventSource,+ event_type: CGEventType,+ point: CGPoint,+ button: CGMouseButton,+ ) -> Result<(), AdapterError> {+ let ev = create_event_with_source(source, event_type, point, button)?;+ ev.post(CGEventTapLocation::HID);+ Ok(())+ }+fn to_cg_button(button: &MouseButton) -> CGMouseButton {match button {MouseButton::Left => CGMouseButton::Left,diff --git a/crates/macos/src/notifications/actions.rs b/crates/macos/src/notifications/actions.rsindex 058999772..9fb55980c 100644--- a/crates/macos/src/notifications/actions.rs+++ b/crates/macos/src/notifications/actions.rs@@ -1,5 +1,5 @@use agent_desktop_core::{- action::ActionResult,+ action_result::ActionResult,error::{AdapterError, ErrorCode},notification::{NotificationFilter, NotificationIdentity, NotificationInfo},};@@ -12,8 +12,7 @@ pub fn dismiss_notification() -> Result<NotificationInfo, AdapterError> {let session = NcSession::open()?;let result = dismiss_impl(index, app_filter);- session.close()?;- result+ close_session(session, result)}pub fn dismiss_all(@@ -21,8 +20,7 @@ pub fn dismiss_all() -> Result<(Vec<NotificationInfo>, Vec<String>), AdapterError> {let session = NcSession::open()?;let result = dismiss_all_impl(app_filter);- session.close()?;- result+ close_session(session, result)}pub fn notification_action(@@ -32,8 +30,19 @@ pub fn notification_action() -> Result<ActionResult, AdapterError> {let session = NcSession::open()?;let result = action_impl(index, identity, action_name);- session.close()?;- result+ close_session(session, result)+}++fn close_session<T>(+ session: NcSession,+ result: Result<T, AdapterError>,+) -> Result<T, AdapterError> {+ let close_result = session.close();+ match (result, close_result) {+ (Ok(value), Ok(())) => Ok(value),+ (Ok(_), Err(err)) => Err(err),+ (Err(err), _) => Err(err),+ }}#[cfg(target_os = "macos")]@@ -120,6 +129,9 @@ fn try_dismiss_button(children: &[crate::tree::AXElement]) -> bool {close_btn.is_some_and(|btn| try_ax_action(btn, "AXPress"))}+/// Presses a named action button on the notification at `index`.+///+/// When `identity` is provided, rejects rows whose fingerprint no longer matches after NC reordering.#[cfg(target_os = "macos")]fn action_impl(index: usize,@@ -138,12 +150,6 @@ fn action_impl(.find(|e| e.info.index == index).ok_or_else(|| AdapterError::notification_not_found(index))?;- // Fingerprint check: NC may have reordered between the host's- // list_notifications call and now. When identity fields are- // provided, refuse to press an action on a row whose fingerprint- // doesn't match. Fail closed with NotificationNotFound so the host- // treats this exactly like "the notification disappeared" — which- // is precisely what happened from the host's perspective.if let Some(id) = identity {if !id.is_empty() && !id.matches(&entry.info) {return Err(AdapterError::new(diff --git a/crates/macos/src/system/app_inventory.rs b/crates/macos/src/system/app_inventory.rsindex 5e67d44ff..ec79cba23 100644--- a/crates/macos/src/system/app_inventory.rs+++ b/crates/macos/src/system/app_inventory.rs@@ -43,6 +43,10 @@ pub(crate) fn pid_for_app_name(app_name: &str) -> Option<i32> {app_for_name(app_name).map(|app| app.pid)}+pub(crate) fn pids_for_app_name(app_name: &str) -> Vec<i32> {+ matching_pids(&list_apps(), app_name)+}+pub(crate) fn app_for_name(app_name: &str) -> Option<AppInfo> {app_for_name_from_sources(app_name,@@ -118,6 +122,17 @@ fn find_app_in_apps(apps: &[AppInfo], app_name: &str) -> Option<AppInfo> {.cloned()}+fn matching_pids(apps: &[AppInfo], app_name: &str) -> Vec<i32> {+ let mut pids = apps+ .iter()+ .filter(|app| app.name.eq_ignore_ascii_case(app_name))+ .map(|app| app.pid)+ .collect::<Vec<_>>();+ pids.sort_unstable();+ pids.dedup();+ pids+}+#[cfg(test)]#[path = "app_inventory_tests.rs"]mod tests;diff --git a/crates/macos/src/system/app_inventory_tests.rs b/crates/macos/src/system/app_inventory_tests.rsindex 0b9d59ff7..e49afe671 100644--- a/crates/macos/src/system/app_inventory_tests.rs+++ b/crates/macos/src/system/app_inventory_tests.rs@@ -67,6 +67,18 @@ fn find_app_in_apps_rejects_contains_match() {assert!(find_app_in_apps(&apps, "Docker").is_none());}+#[test]+fn matching_pids_returns_all_exact_name_instances() {+ let apps = vec![+ app("Terminal", 3),+ app("Terminal Helper", 4),+ app("terminal", 2),+ app("Terminal", 3),+ ];++ assert_eq!(matching_pids(&apps, "Terminal"), vec![2, 3]);+}+#[test]fn find_app_with_process_fallback_uses_process_entries_after_primary_miss() {let primary = vec![app("Finder", 10)];diff --git a/crates/macos/src/system/app_list.rs b/crates/macos/src/system/app_list.rsindex 16412856f..f155f372a 100644--- a/crates/macos/src/system/app_list.rs+++ b/crates/macos/src/system/app_list.rs@@ -13,3 +13,8 @@ pub fn list_apps_impl() -> Result<Vec<AppInfo>, AdapterError> {pub(crate) fn pid_for_app_name(app_name: &str) -> Option<i32> {crate::system::app_inventory::pid_for_app_name(app_name)}++#[cfg(target_os = "macos")]+pub(crate) fn pids_for_app_name(app_name: &str) -> Vec<i32> {+ crate::system::app_inventory::pids_for_app_name(app_name)+}diff --git a/crates/macos/src/system/app_ops.rs b/crates/macos/src/system/app_ops.rsindex adc09af14..89520092f 100644--- a/crates/macos/src/system/app_ops.rs+++ b/crates/macos/src/system/app_ops.rs@@ -1,4 +1,9 @@-use agent_desktop_core::{adapter::WindowFilter, error::AdapterError, node::WindowInfo};+use agent_desktop_core::{+ adapter::WindowFilter,+ error::{AdapterError, ErrorCode},+ node::WindowInfo,+};+use std::time::Duration;#[cfg(target_os = "macos")]pub fn pid_from_element(el: &crate::tree::AXElement) -> Option<i32> {@@ -11,6 +16,10 @@ pub fn pid_from_element(el: &crate::tree::AXElement) -> Option<i32> {}}+/// Ensures the app is frontmost: a no-op when it already is, otherwise a+/// best-effort raise confirmed by polling. `Ok` therefore means "frontmost+/// ensured", not "a raise happened" — callers surfacing `focused:true` get+/// exactly that ensured semantics.#[cfg(target_os = "macos")]pub fn ensure_app_focused(pid: i32) -> Result<(), AdapterError> {tracing::debug!("system: ensure_app_focused pid={pid}");@@ -18,6 +27,9 @@ pub fn ensure_app_focused(pid: i32) -> Result<(), AdapterError> {use core_foundation::{base::TCFType, boolean::CFBoolean, string::CFString};let app_el = crate::tree::element_for_pid(pid);+ if crate::tree::copy_bool_attr(&app_el, "AXFrontmost") == Some(true) {+ return Ok(());+ }let frontmost_attr = CFString::new("AXFrontmost");let err = unsafe {AXUIElementSetAttributeValue(@@ -31,10 +43,33 @@ pub fn ensure_app_focused(pid: i32) -> Result<(), AdapterError> {"Failed to focus app pid={pid}")));}- std::thread::sleep(std::time::Duration::from_millis(50));+ wait_until_frontmost(&app_el);Ok(())}+/// Polls `AXFrontmost` until the app actually reports frontmost instead of a+/// fixed settle sleep, so an already-frontmost app costs one read and a slow+/// activation gets the full window. Best-effort: timing out just means the+/// caller proceeds as before the poll existed.+#[cfg(target_os = "macos")]+fn wait_until_frontmost(app_el: &crate::tree::AXElement) {+ use std::time::{Duration, Instant};++ const POLL_INTERVAL: Duration = Duration::from_millis(5);+ const FRONTMOST_DEADLINE: Duration = Duration::from_millis(50);++ let deadline = Instant::now() + FRONTMOST_DEADLINE;+ loop {+ if crate::tree::copy_bool_attr(app_el, "AXFrontmost") == Some(true) {+ return;+ }+ if Instant::now() >= deadline {+ return;+ }+ std::thread::sleep(POLL_INTERVAL);+ }+}+#[cfg(target_os = "macos")]pub fn focus_window_impl(win: &WindowInfo) -> Result<(), AdapterError> {tracing::debug!(@@ -42,45 +77,9 @@ pub fn focus_window_impl(win: &WindowInfo) -> Result<(), AdapterError> {win.app,win.title);- use accessibility_sys::{- AXUIElementCreateApplication, AXUIElementPerformAction, AXUIElementSetAttributeValue,- kAXErrorSuccess,- };- use core_foundation::{base::TCFType, boolean::CFBoolean, string::CFString};-- let app_el = crate::tree::AXElement(unsafe { AXUIElementCreateApplication(win.pid) });- if app_el.0.is_null() {- return Err(AdapterError::internal("Failed to create AX app element"));- }-- let frontmost_attr = CFString::new("AXFrontmost");- let err = unsafe {- AXUIElementSetAttributeValue(- app_el.0,- frontmost_attr.as_concrete_TypeRef(),- CFBoolean::true_value().as_CFTypeRef(),- )- };- if err != kAXErrorSuccess {- return Err(AdapterError::internal(format!(- "Failed to set AXFrontmost (err={err})"- )));- }-+ ensure_app_focused(win.pid)?;let main_win = crate::tree::window_element_for(win.pid, &win.title);- let raise_action = CFString::new("AXRaise");- let raise_err =- unsafe { AXUIElementPerformAction(main_win.0, raise_action.as_concrete_TypeRef()) };- if raise_err != kAXErrorSuccess {- let main_attr = CFString::new("AXMain");- unsafe {- AXUIElementSetAttributeValue(- main_win.0,- main_attr.as_concrete_TypeRef(),- CFBoolean::true_value().as_CFTypeRef(),- )- };- }+ crate::system::window_ops::raise_window(&main_win);Ok(())}@@ -159,22 +158,62 @@ pub fn launch_app_impl(_id: &str, _timeout_ms: u64) -> Result<WindowInfo, AdapteErr(AdapterError::not_supported("launch_app"))}+/// Processes whose termination would break the macOS session: the window+/// server, login session, launchd, the Dock, and Finder. Matched as an+/// exact lowercase name or an exact dot-separated bundle-id component, so+/// display names (`Dock`) and bundle ids (`com.apple.dock`) both resolve+/// while lookalikes (`Docker`, `FinderSync`) stay closable — a substring+/// match would permanently block them. Windows and Linux adapters define+/// their own equivalents (`csrss.exe`/`winlogon.exe`, `gnome-shell`/`Xorg`).+const PROTECTED_PROCESSES: &[&str] = &["loginwindow", "windowserver", "dock", "launchd", "finder"];++pub fn is_protected_process(identifier: &str) -> bool {+ let lower = identifier.to_lowercase();+ PROTECTED_PROCESSES+ .iter()+ .any(|p| lower == *p || lower.split('.').any(|component| component == *p))+}++fn ensure_not_protected(id: &str) -> Result<(), AdapterError> {+ if is_protected_process(id) {+ return Err(AdapterError::new(+ agent_desktop_core::error::ErrorCode::InvalidArgs,+ format!("'{id}' is a protected system process and cannot be closed"),+ )+ .with_suggestion(+ "Target a regular application; session-critical processes (loginwindow, WindowServer, Dock, Finder, launchd) are never closed.",+ ));+ }+ Ok(())+}+#[cfg(test)]#[path = "app_ops_tests.rs"]mod tests;+/// Closes an app after the protected-process guard. The guard runs here —+/// inside the adapter — so every consumer (CLI, FFI, future MCP) refuses+/// session-critical processes identically; the CLI command's own preflight+/// is an earlier check against the same predicate, not the enforcement+/// point. The error mirrors the CLI contract exactly (code and message).#[cfg(target_os = "macos")]pub fn close_app_impl(id: &str, force: bool) -> Result<(), AdapterError> {+ ensure_not_protected(id)?;tracing::debug!("system: close app={id:?} force={force}");use std::process::Command;- use std::time::Duration;const QUIT_TIMEOUT: Duration = Duration::from_secs(3);if force {- let mut command = Command::new("/usr/bin/pkill");- command.arg("-x").arg(id);- crate::system::process::run_with_timeout(&mut command, "pkill", QUIT_TIMEOUT)?;+ let pids = crate::system::app_list::pids_for_app_name(id);+ if pids.is_empty() {+ return Err(AdapterError::new(+ ErrorCode::AppNotFound,+ format!("App '{id}' was not running or could not be matched for force close"),+ )+ .with_suggestion("Use 'list-apps' to verify the running app name before retrying."));+ }+ crate::system::force_close::terminate_app(id, &pids, QUIT_TIMEOUT)?;} else {let pid = crate::system::key_dispatch::find_pid_by_name(id)?;let app_ax = crate::tree::element_for_pid(pid);@@ -198,7 +237,18 @@ end tell"#);let mut command = Command::new("/usr/bin/osascript");command.arg("-e").arg(script);- crate::system::process::run_with_timeout(&mut command, "osascript", QUIT_TIMEOUT)?;+ let output =+ crate::system::process::run_with_timeout(&mut command, "osascript", QUIT_TIMEOUT)?;+ if !output.status.success() {+ return Err(AdapterError::new(+ ErrorCode::ActionFailed,+ format!("Failed to request graceful quit for app '{id}'"),+ )+ .with_platform_detail(String::from_utf8_lossy(&output.stderr).trim().to_string())+ .with_suggestion(+ "Use 'list-apps' to verify the app name, or retry with --force.",+ ));+ }}}Ok(())diff --git a/crates/macos/src/system/app_ops_tests.rs b/crates/macos/src/system/app_ops_tests.rsindex ed598d6e8..b42a4840a 100644--- a/crates/macos/src/system/app_ops_tests.rs+++ b/crates/macos/src/system/app_ops_tests.rs@@ -4,3 +4,39 @@ use super::*;fn open_app_args_preserve_current_focus() {assert_eq!(open_app_args("Mail"), ["-g", "-a", "Mail"]);}++#[test]+fn protected_processes_match_display_and_bundle_forms() {+ assert!(is_protected_process("Finder"));+ assert!(is_protected_process("Dock"));+ assert!(is_protected_process("com.apple.dock"));+ assert!(is_protected_process("WindowServer"));+ assert!(is_protected_process("loginwindow"));+}++#[test]+fn ordinary_apps_are_not_protected() {+ assert!(!is_protected_process("TextEdit"));+ assert!(!is_protected_process("Safari"));+ assert!(!is_protected_process("com.company.MyApp"));+}++#[test]+fn lookalike_names_containing_protected_substrings_stay_closable() {+ assert!(!is_protected_process("Docker"));+ assert!(!is_protected_process("Docker Desktop"));+ assert!(!is_protected_process("com.docker.docker-desktop"));+ assert!(!is_protected_process("FinderSync"));+ assert!(!is_protected_process("PathFinder"));+ assert!(!is_protected_process("launchdarkly-agent"));+}++#[test]+fn adapter_guard_refuses_protected_processes_with_the_cli_contract() {+ let err = ensure_not_protected("loginwindow").unwrap_err();++ assert_eq!(err.code, agent_desktop_core::error::ErrorCode::InvalidArgs);+ assert!(err.message.contains("protected"));+ assert!(err.suggestion.is_some());+ assert!(ensure_not_protected("TextEdit").is_ok());+}diff --git a/crates/macos/src/system/force_close.rs b/crates/macos/src/system/force_close.rsnew file mode 100644index 000000000..d34f982b0--- /dev/null+++ b/crates/macos/src/system/force_close.rs@@ -0,0 +1,247 @@+use agent_desktop_core::error::AdapterError;+use std::time::{Duration, Instant};++const KILL_CONFIRM_FLOOR: Duration = Duration::from_millis(500);++pub(crate) fn terminate_app(id: &str, pids: &[i32], timeout: Duration) -> Result<(), AdapterError> {+ let start = Instant::now();+ let mut failures = signal_failures(pids, Signal::Term);+ let remaining = remaining_pids_after_wait(pids, timeout.saturating_sub(start.elapsed()));+ if remaining.is_empty() {+ return Ok(());+ }++ failures.extend(signal_failures(&remaining, Signal::Kill));+ let still_running = remaining_pids_after_wait(&remaining, kill_confirm_budget(timeout, start));+ if still_running.is_empty() {+ return Ok(());+ }++ let mut err = AdapterError::timeout(format!(+ "App '{id}' still has running pid(s) after force close: {}",+ format_pids(&still_running)+ ))+ .with_suggestion("Retry after checking for save dialogs or helper processes with 'list-apps'.");+ if !failures.is_empty() {+ err = err.with_platform_detail(failures.join("; "));+ }+ Err(err)+}++fn kill_confirm_budget(timeout: Duration, start: Instant) -> Duration {+ if timeout.is_zero() {+ return Duration::ZERO;+ }+ timeout+ .saturating_sub(start.elapsed())+ .max(KILL_CONFIRM_FLOOR)+}++fn signal_failures(pids: &[i32], signal: Signal) -> Vec<String> {+ collect_signal_failures(pids, signal, signal_result)+}++fn collect_signal_failures<F>(pids: &[i32], signal: Signal, mut signal_fn: F) -> Vec<String>+where+ F: FnMut(i32, Signal) -> Result<bool, String>,+{+ let mut failures = Vec::new();+ for &pid in pids {+ if let Err(detail) = signal_fn(pid, signal).map(|_| ()) {+ failures.push(format!("pid {pid} {}: {detail}", signal.verb()));+ }+ }+ failures+}++fn remaining_pids_after_wait(pids: &[i32], timeout: Duration) -> Vec<i32> {+ let start = Instant::now();+ while start.elapsed() < timeout {+ let remaining = running_pids(pids);+ if remaining.is_empty() {+ return remaining;+ }+ std::thread::sleep(Duration::from_millis(50));+ }+ running_pids(pids)+}++fn running_pids(pids: &[i32]) -> Vec<i32> {+ pids.iter()+ .copied()+ .filter(|pid| process_is_running(*pid))+ .collect()+}++fn process_is_running(pid: i32) -> bool {+ if let Some(running) = child_process_is_running(pid) {+ return running;+ }+ signal_result(pid, Signal::None).unwrap_or(true)+}++fn child_process_is_running(pid: i32) -> Option<bool> {+ const POSIX_ECHILD: i32 = 10;+ const WNOHANG: i32 = 1;++ unsafe extern "C" {+ fn waitpid(pid: i32, status: *mut i32, options: i32) -> i32;+ }+ let mut status = 0;+ match unsafe { waitpid(pid, &mut status, WNOHANG) } {+ child if child == pid => Some(false),+ 0 => Some(true),+ _ if std::io::Error::last_os_error().raw_os_error() == Some(POSIX_ECHILD) => None,+ _ => None,+ }+}++fn signal_result(pid: i32, signal: Signal) -> Result<bool, String> {+ const POSIX_ESRCH: i32 = 3;++ unsafe extern "C" {+ fn kill(pid: i32, sig: i32) -> i32;+ }+ if unsafe { kill(pid, signal.number()) } == 0 {+ return Ok(true);+ }+ let err = std::io::Error::last_os_error();+ if err.raw_os_error() == Some(POSIX_ESRCH) {+ return Ok(false);+ }+ Err(err.to_string())+}++fn format_pids(pids: &[i32]) -> String {+ pids.iter()+ .map(i32::to_string)+ .collect::<Vec<_>>()+ .join(", ")+}++#[derive(Clone, Copy)]+enum Signal {+ None,+ Term,+ Kill,+}++impl Signal {+ fn number(self) -> i32 {+ match self {+ Self::None => 0,+ Self::Term => 15,+ Self::Kill => 9,+ }+ }++ fn verb(self) -> &'static str {+ match self {+ Self::None => "inspect",+ Self::Term => "terminate",+ Self::Kill => "kill",+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::process::{Child, Command};++ struct ChildGuard(Child);++ impl ChildGuard {+ fn spawn_term_ignoring() -> Self {+ let child = Command::new("/bin/sh")+ .args(["-c", "trap '' TERM; while :; do sleep 1; done"])+ .spawn()+ .unwrap();+ Self(child)+ }++ fn pid(&self) -> i32 {+ self.0.id() as i32+ }++ fn has_exited(&mut self) -> bool {+ !process_is_running(self.pid())+ }+ }++ impl Drop for ChildGuard {+ fn drop(&mut self) {+ let _ = self.0.kill();+ let _ = self.0.wait();+ }+ }++ #[test]+ fn missing_pids_are_not_reported_as_running() {+ assert!(remaining_pids_after_wait(&[999_999], Duration::from_millis(1)).is_empty());+ }++ #[test]+ fn current_pid_remains_running_after_short_wait() {+ let pid = std::process::id() as i32;++ assert_eq!(+ remaining_pids_after_wait(&[999_999, pid], Duration::from_millis(1)),+ vec![pid]+ );+ }++ #[test]+ fn missing_pids_are_accepted_during_signal_race() {+ assert!(signal_failures(&[999_999], Signal::Term).is_empty());+ assert!(signal_failures(&[999_999], Signal::Kill).is_empty());+ }++ #[test]+ fn signal_collection_attempts_every_pid_after_failure() {+ let mut attempted = Vec::new();++ let failures = collect_signal_failures(&[11, 22, 33], Signal::Term, |pid, _signal| {+ attempted.push(pid);+ if pid == 11 {+ Err("operation not permitted".to_owned())+ } else {+ Ok(true)+ }+ });++ assert_eq!(attempted, vec![11, 22, 33]);+ assert_eq!(failures.len(), 1);+ assert!(failures[0].contains("pid 11 terminate"));+ }++ #[test]+ fn terminate_app_escalates_to_kill_for_all_remaining_pids() {+ let mut first = ChildGuard::spawn_term_ignoring();+ let mut second = ChildGuard::spawn_term_ignoring();+ let pids = [first.pid(), second.pid()];++ terminate_app("term-ignoring-test", &pids, Duration::from_millis(100)).unwrap();++ assert!(first.has_exited());+ assert!(second.has_exited());+ }++ #[test]+ fn kill_confirm_budget_keeps_a_small_floor_after_term_timeout() {+ let start = Instant::now() - Duration::from_secs(1);++ assert_eq!(+ kill_confirm_budget(Duration::from_millis(10), start),+ KILL_CONFIRM_FLOOR+ );+ }++ #[test]+ fn kill_confirm_budget_preserves_explicit_zero_timeout() {+ assert_eq!(+ kill_confirm_budget(Duration::ZERO, Instant::now()),+ Duration::ZERO+ );+ }+}diff --git a/crates/macos/src/system/key_dispatch.rs b/crates/macos/src/system/key_dispatch.rsindex ff28348a9..0a6e1ebda 100644--- a/crates/macos/src/system/key_dispatch.rs+++ b/crates/macos/src/system/key_dispatch.rs@@ -1,16 +1,10 @@-use agent_desktop_core::{- action::{ActionResult, KeyCombo},- error::AdapterError,-};+use agent_desktop_core::{action::KeyCombo, action_result::ActionResult, error::AdapterError};#[cfg(target_os = "macos")]use agent_desktop_core::{action::Modifier, adapter::WindowFilter};#[cfg(target_os = "macos")]pub fn press_for_app_impl(app_name: &str, combo: &KeyCombo) -> Result<ActionResult, AdapterError> {- use accessibility_sys::AXUIElementSetAttributeValue;- use core_foundation::{base::TCFType, boolean::CFBoolean, string::CFString};-tracing::debug!("system: press_for_app app={app_name:?} key={:?}", combo.key);let pid = find_pid_by_name(app_name)?;let app_el = crate::tree::element_for_pid(pid);@@ -18,15 +12,9 @@ pub fn press_for_app_impl(app_name: &str, combo: &KeyCombo) -> Result<ActionResureturn Err(AdapterError::internal("Failed to create AX app element"));}- let frontmost_attr = CFString::new("AXFrontmost");- unsafe {- AXUIElementSetAttributeValue(- app_el.0,- frontmost_attr.as_concrete_TypeRef(),- CFBoolean::true_value().as_CFTypeRef(),- )- };- std::thread::sleep(std::time::Duration::from_millis(50));+ if let Err(err) = crate::system::app_ops::ensure_app_focused(pid) {+ tracing::debug!("press_for_app: focus before key dispatch failed: {err}");+ }if !combo.modifiers.is_empty() {if let Some(result) = try_menu_bar_shortcut(&app_el, combo) {diff --git a/crates/macos/src/system/mod.rs b/crates/macos/src/system/mod.rsindex f0750b5e3..a0fcb0d04 100644--- a/crates/macos/src/system/mod.rs+++ b/crates/macos/src/system/mod.rs@@ -2,6 +2,7 @@ pub(crate) mod app_inventory;pub mod app_list;pub mod app_ops;pub(crate) mod cg_window;+pub(crate) mod force_close;pub mod key_dispatch;pub mod permissions;pub(crate) mod process;diff --git a/crates/macos/src/system/window_ops.rs b/crates/macos/src/system/window_ops.rsindex 4bc07ec8e..dde0c1aa2 100644--- a/crates/macos/src/system/window_ops.rs+++ b/crates/macos/src/system/window_ops.rs@@ -109,6 +109,56 @@ mod imp {}}+#[cfg(target_os = "macos")]+mod raise {+ use accessibility_sys::{+ AXUIElementPerformAction, AXUIElementSetAttributeValue, kAXErrorSuccess,+ };+ use core_foundation::{base::TCFType, boolean::CFBoolean, string::CFString};++ /// Raises a window element to the top of its app's window stack and+ /// confirms with a brief `AXMain` poll. CGEvents land on the topmost+ /// window at the click point, so a frontmost app is not enough when the+ /// target element lives in a background window. Best-effort: a window+ /// that refuses both `AXRaise` and a settable `AXMain` is left as-is.+ pub(crate) fn raise_window(window: &crate::tree::AXElement) {+ let raise = CFString::new("AXRaise");+ let raise_err = unsafe { AXUIElementPerformAction(window.0, raise.as_concrete_TypeRef()) };+ if raise_err != kAXErrorSuccess {+ let main_attr = CFString::new("AXMain");+ unsafe {+ AXUIElementSetAttributeValue(+ window.0,+ main_attr.as_concrete_TypeRef(),+ CFBoolean::true_value().as_CFTypeRef(),+ )+ };+ }+ wait_until_main(window);+ }++ fn wait_until_main(window: &crate::tree::AXElement) {+ use std::time::{Duration, Instant};++ const POLL_INTERVAL: Duration = Duration::from_millis(5);+ const MAIN_DEADLINE: Duration = Duration::from_millis(50);++ let deadline = Instant::now() + MAIN_DEADLINE;+ loop {+ if crate::tree::copy_bool_attr(window, "AXMain") == Some(true) {+ return;+ }+ if Instant::now() >= deadline {+ return;+ }+ std::thread::sleep(POLL_INTERVAL);+ }+ }+}++#[cfg(target_os = "macos")]+pub(crate) use raise::raise_window;+#[cfg(not(target_os = "macos"))]mod imp {use super::*;diff --git a/crates/macos/src/tree/action_list.rs b/crates/macos/src/tree/action_list.rsindex e67609cf6..88869fb93 100644--- a/crates/macos/src/tree/action_list.rs+++ b/crates/macos/src/tree/action_list.rs@@ -1,46 +1,116 @@use super::AXElement;use super::capabilities::{copy_action_names, is_attr_settable};+use agent_desktop_core::capability;#[cfg(target_os = "macos")]use accessibility_sys::{kAXFocusedAttribute, kAXValueAttribute};#[cfg(target_os = "macos")]-pub(crate) fn platform_available_actions(el: &AXElement, role: &str) -> Vec<String> {+pub(crate) fn platform_available_actions(+ el: &AXElement,+ role: &str,+ has_scrollbars: bool,+) -> Vec<String> {let ax_actions = copy_action_names(el);let has = |name: &str| ax_actions.iter().any(|a| a == name);let mut actions = Vec::new();if has("AXPress") {- push_unique(&mut actions, "Click");+ push_unique(&mut actions, capability::CLICK);if crate::tree::roles::is_toggleable_role(role) {- push_unique(&mut actions, "Toggle");+ push_unique(&mut actions, capability::TOGGLE);}if matches!(role, "combobox" | "menuitem" | "tab") {- push_unique(&mut actions, "Select");+ push_unique(&mut actions, capability::SELECT);}}if has("AXShowMenu") && role_allows_context_menu_action(role) {- push_unique(&mut actions, "RightClick");+ push_unique(&mut actions, capability::RIGHT_CLICK);}if has("AXScrollToVisible") {- push_unique(&mut actions, "ScrollTo");+ push_unique(&mut actions, capability::SCROLL);+ push_unique(&mut actions, capability::SCROLL_TO);}- if has("AXIncrement") || has("AXDecrement") || is_attr_settable(el, kAXValueAttribute) {- push_unique(&mut actions, "SetValue");+ if has_scroll_mechanism(role, &has, has_scrollbars) {+ push_unique(&mut actions, capability::SCROLL);}- if is_attr_settable(el, kAXFocusedAttribute) {- push_unique(&mut actions, "SetFocus");+ if has("AXIncrement")+ || has("AXDecrement")+ || (role_may_bear_value(role) && is_attr_settable(el, kAXValueAttribute))+ {+ push_unique(&mut actions, capability::SET_VALUE);}- if is_attr_settable(el, "AXExpanded") {- push_unique(&mut actions, "Expand");- push_unique(&mut actions, "Collapse");+ if role_may_accept_focus(role) && is_attr_settable(el, kAXFocusedAttribute) {+ push_unique(&mut actions, capability::SET_FOCUS);+ }+ if (role_may_expand(role) && is_attr_settable(el, "AXExpanded"))+ || (has("AXPress") && agent_desktop_core::roles::is_expandable_role(role))+ {+ push_unique(&mut actions, capability::EXPAND);+ push_unique(&mut actions, capability::COLLAPSE);}actions}+/// Whether a role could carry a settable `AXValue`, so the `is_settable` probe+/// is worth an IPC. Click/navigation-only roles never do; `unknown` always+/// probes so an unmapped role never loses a capability.+fn role_may_bear_value(role: &str) -> bool {+ matches!(+ role,+ "textfield"+ | "combobox"+ | "slider"+ | "incrementor"+ | "stepper"+ | "spinbutton"+ | "checkbox"+ | "radiobutton"+ | "switch"+ | "colorwell"+ | "scrollbar"+ | "valueindicator"+ | "unknown"+ )+}++/// Whether a role could carry a settable `AXFocused`, so the `is_settable`+/// probe is worth an IPC. Interactive controls and focus-holding containers+/// (tables, outlines, web areas) can; static/decorative roles never do.+/// `unknown` always probes so an unmapped role never loses a capability.+fn role_may_accept_focus(role: &str) -> bool {+ agent_desktop_core::roles::is_interactive_role(role)+ || matches!(+ role,+ "table"+ | "outline"+ | "list"+ | "browser"+ | "webarea"+ | "scrollarea"+ | "group"+ | "row"+ | "unknown"+ )+}++/// Whether a role could expose a settable `AXExpanded`. Leaf/interactive roles+/// never expand; `unknown` always probes.+fn role_may_expand(role: &str) -> bool {+ agent_desktop_core::roles::is_expandable_role(role)+ || matches!(+ role,+ "group" | "outline" | "row" | "browser" | "table" | "list" | "cell" | "unknown"+ )+}+#[cfg(not(target_os = "macos"))]-pub(crate) fn platform_available_actions(_el: &AXElement, _role: &str) -> Vec<String> {+pub(crate) fn platform_available_actions(+ _el: &AXElement,+ _role: &str,+ _has_scrollbars: bool,+) -> Vec<String> {Vec::new()}@@ -54,9 +124,52 @@ fn role_allows_context_menu_action(role: &str) -> bool {!matches!(role, "combobox" | "menubutton")}+fn has_scroll_mechanism(role: &str, has: &impl Fn(&str) -> bool, has_scrollbars: bool) -> bool {+ role_supports_scroll(role)+ || has("AXScrollDownByPage")+ || has("AXScrollUpByPage")+ || has("AXScrollLeftByPage")+ || has("AXScrollRightByPage")+ || (role_may_own_scrollbars(role) && has_scrollbars)+}++fn role_supports_scroll(role: &str) -> bool {+ matches!(+ role,+ "scrollarea" | "browser" | "table" | "outline" | "list"+ )+}++fn role_may_own_scrollbars(role: &str) -> bool {+ matches!(+ role,+ "application"+ | "window"+ | "sheet"+ | "dialog"+ | "group"+ | "splitter"+ | "webarea"+ | "grid"+ | "unknown"+ )+}+#[cfg(test)]mod tests {- use super::role_allows_context_menu_action;+ use super::{+ role_allows_context_menu_action, role_may_accept_focus, role_may_own_scrollbars,+ role_supports_scroll,+ };++ #[test]+ fn focus_probe_is_limited_to_focus_bearing_roles() {+ assert!(role_may_accept_focus("textfield"));+ assert!(role_may_accept_focus("webarea"));+ assert!(role_may_accept_focus("unknown"));+ assert!(!role_may_accept_focus("statictext"));+ assert!(!role_may_accept_focus("image"));+ }#[test]fn menu_opening_controls_do_not_advertise_right_click() {@@ -65,4 +178,19 @@ mod tests {assert!(role_allows_context_menu_action("textfield"));assert!(role_allows_context_menu_action("button"));}++ #[test]+ fn scroll_container_roles_advertise_scroll_without_scroll_to() {+ assert!(role_supports_scroll("scrollarea"));+ assert!(role_supports_scroll("browser"));+ assert!(!role_supports_scroll("button"));+ }++ #[test]+ fn scrollbar_probe_is_limited_to_container_like_roles() {+ assert!(role_may_own_scrollbars("group"));+ assert!(role_may_own_scrollbars("webarea"));+ assert!(!role_may_own_scrollbars("button"));+ assert!(!role_may_own_scrollbars("cell"));+ }}diff --git a/crates/macos/src/tree/attributes.rs b/crates/macos/src/tree/attributes.rsnew file mode 100644index 000000000..7314bd261--- /dev/null+++ b/crates/macos/src/tree/attributes.rs@@ -0,0 +1,228 @@+#[cfg(target_os = "macos")]+mod imp {+ use crate::{+ cf_type::created_cf_array,+ tree::{ax_element::AXElement, ax_value},+ };+ use accessibility_sys::{+ AXUIElementCopyAttributeValue, AXUIElementCopyAttributeValues,+ AXUIElementCopyMultipleAttributeValues, AXUIElementSetMessagingTimeout, kAXErrorSuccess,+ kAXValueAttribute,+ };+ use core_foundation::{+ array::CFArray,+ base::{CFType, CFTypeRef, TCFType},+ boolean::CFBoolean,+ number::CFNumber,+ string::CFString,+ };++ pub fn copy_string_attr(el: &AXElement, attr: &str) -> Option<String> {+ let cf_attr = CFString::new(attr);+ let mut value: CFTypeRef = std::ptr::null_mut();+ let err = unsafe {+ AXUIElementCopyAttributeValue(el.0, cf_attr.as_concrete_TypeRef(), &mut value)+ };+ if err != kAXErrorSuccess || value.is_null() {+ return None;+ }+ let cf_type = unsafe { CFType::wrap_under_create_rule(value) };+ cf_type.downcast::<CFString>().map(|s| s.to_string())+ }++ pub fn set_messaging_timeout(el: &AXElement, timeout: std::time::Duration) {+ if el.0.is_null() {+ return;+ }+ let seconds = timeout.as_secs_f32().clamp(0.001, 2.0);+ unsafe { AXUIElementSetMessagingTimeout(el.0, seconds) };+ }++ pub fn copy_value_typed(el: &AXElement) -> Option<String> {+ let cf_attr = CFString::new(kAXValueAttribute);+ let mut val_ref: CFTypeRef = std::ptr::null_mut();+ let err = unsafe {+ AXUIElementCopyAttributeValue(el.0, cf_attr.as_concrete_TypeRef(), &mut val_ref)+ };+ if err != kAXErrorSuccess || val_ref.is_null() {+ return None;+ }+ let cf = unsafe { CFType::wrap_under_create_rule(val_ref) };+ if let Some(s) = cf.downcast::<CFString>() {+ return Some(s.to_string());+ }+ if let Some(b) = cf.downcast::<CFBoolean>() {+ return Some(bool::from(b).to_string());+ }+ if let Some(n) = cf.downcast::<CFNumber>() {+ if let Some(i) = n.to_i64() {+ return Some(i.to_string());+ }+ if let Some(f) = n.to_f64() {+ return Some(format!("{:.2}", f));+ }+ }+ None+ }++ pub fn copy_bool_attr(el: &AXElement, attr: &str) -> Option<bool> {+ let cf_attr = CFString::new(attr);+ let mut value: CFTypeRef = std::ptr::null_mut();+ let err = unsafe {+ AXUIElementCopyAttributeValue(el.0, cf_attr.as_concrete_TypeRef(), &mut value)+ };+ if err != kAXErrorSuccess || value.is_null() {+ return None;+ }+ let cf_type = unsafe { CFType::wrap_under_create_rule(value) };+ cf_type.downcast::<CFBoolean>().map(|b| b.into())+ }++ pub fn copy_i64_attr(el: &AXElement, attr: &str) -> Option<i64> {+ let cf_attr = CFString::new(attr);+ let mut value: CFTypeRef = std::ptr::null_mut();+ let err = unsafe {+ AXUIElementCopyAttributeValue(el.0, cf_attr.as_concrete_TypeRef(), &mut value)+ };+ if err != kAXErrorSuccess || value.is_null() {+ return None;+ }+ let cf_type = unsafe { CFType::wrap_under_create_rule(value) };+ cf_type.downcast::<CFNumber>().and_then(|n| n.to_i64())+ }++ pub fn copy_ax_array(el: &AXElement, attr: &str) -> Option<Vec<AXElement>> {+ let cf_attr = CFString::new(attr);+ let mut value: CFTypeRef = std::ptr::null_mut();+ let err = unsafe {+ AXUIElementCopyAttributeValue(el.0, cf_attr.as_concrete_TypeRef(), &mut value)+ };+ if err != kAXErrorSuccess || value.is_null() {+ return None;+ }+ let arr = created_cf_array(value)?;+ Some(ax_array_items(arr))+ }++ pub fn copy_ax_array_prefix(+ el: &AXElement,+ attr: &str,+ max_values: usize,+ ) -> Option<Vec<AXElement>> {+ if max_values == 0 {+ return Some(Vec::new());+ }+ let cf_attr = CFString::new(attr);+ let mut value: core_foundation_sys::array::CFArrayRef = std::ptr::null();+ let err = unsafe {+ AXUIElementCopyAttributeValues(+ el.0,+ cf_attr.as_concrete_TypeRef(),+ 0,+ max_values as core_foundation_sys::base::CFIndex,+ &mut value,+ )+ };+ if err != kAXErrorSuccess || value.is_null() {+ return None;+ }+ let arr = created_cf_array(value as CFTypeRef)?;+ Some(ax_array_items(arr))+ }++ pub fn copy_element_attr(el: &AXElement, attr: &str) -> Option<AXElement> {+ let cf_attr = CFString::new(attr);+ let mut value: CFTypeRef = std::ptr::null_mut();+ let err = unsafe {+ AXUIElementCopyAttributeValue(el.0, cf_attr.as_concrete_TypeRef(), &mut value)+ };+ if err != kAXErrorSuccess || value.is_null() {+ return None;+ }+ ax_value::created_ax_element(value)+ }++ pub fn copy_first_element_attr(el: &AXElement, attrs: &[&str]) -> Option<AXElement> {+ if attrs.is_empty() {+ return None;+ }+ let cf_names: Vec<CFString> = attrs.iter().map(|attr| CFString::new(attr)).collect();+ let cf_refs: Vec<_> = cf_names.iter().map(|s| s.as_concrete_TypeRef()).collect();+ let names_arr = CFArray::from_copyable(&cf_refs);+ let mut result_ref: CFTypeRef = std::ptr::null_mut();+ let err = unsafe {+ AXUIElementCopyMultipleAttributeValues(+ el.0,+ names_arr.as_concrete_TypeRef(),+ 0,+ &mut result_ref as *mut _ as *mut _,+ )+ };+ if !result_ref.is_null() {+ let arr = created_cf_array(result_ref);+ if err == kAXErrorSuccess+ && let Some(arr) = arr+ {+ return arr+ .into_iter()+ .find_map(|item| ax_value::retained_ax_element(&item));+ }+ }+ attrs.iter().find_map(|attr| copy_element_attr(el, attr))+ }++ fn ax_array_items(arr: CFArray<CFType>) -> Vec<AXElement> {+ arr.into_iter()+ .filter_map(|item| ax_value::retained_ax_element(&item))+ .collect()+ }+}++#[cfg(not(target_os = "macos"))]+mod imp {+ use crate::tree::ax_element::AXElement;++ pub fn copy_ax_array(_el: &AXElement, _attr: &str) -> Option<Vec<AXElement>> {+ None+ }++ pub fn copy_ax_array_prefix(+ _el: &AXElement,+ _attr: &str,+ _max_values: usize,+ ) -> Option<Vec<AXElement>> {+ None+ }++ pub fn copy_string_attr(_el: &AXElement, _attr: &str) -> Option<String> {+ None+ }++ pub fn copy_bool_attr(_el: &AXElement, _attr: &str) -> Option<bool> {+ None+ }++ pub fn copy_i64_attr(_el: &AXElement, _attr: &str) -> Option<i64> {+ None+ }++ pub fn copy_element_attr(_el: &AXElement, _attr: &str) -> Option<AXElement> {+ None+ }++ pub fn copy_first_element_attr(_el: &AXElement, _attrs: &[&str]) -> Option<AXElement> {+ None+ }++ pub fn copy_value_typed(_el: &AXElement) -> Option<String> {+ None+ }++ pub fn set_messaging_timeout(_el: &AXElement, _timeout: std::time::Duration) {}+}++pub(crate) use imp::{+ copy_ax_array, copy_ax_array_prefix, copy_bool_attr, copy_element_attr,+ copy_first_element_attr, copy_i64_attr, copy_string_attr, copy_value_typed,+ set_messaging_timeout,+};diff --git a/crates/macos/src/tree/build_context.rs b/crates/macos/src/tree/build_context.rsindex 10e32a2f1..7640260a2 100644--- a/crates/macos/src/tree/build_context.rs+++ b/crates/macos/src/tree/build_context.rs@@ -21,11 +21,10 @@ impl TreeBuildContext {}}- pub(crate) fn read_bounds(&self, el: &AXElement) -> Option<agent_desktop_core::node::Rect> {- if self.include_bounds {- super::read_bounds(el)- } else {- None- }+ pub(crate) fn bounds_for(+ &self,+ bounds: Option<agent_desktop_core::node::Rect>,+ ) -> Option<agent_desktop_core::node::Rect> {+ if self.include_bounds { bounds } else { None }}}diff --git a/crates/macos/src/tree/builder.rs b/crates/macos/src/tree/builder.rsindex 162cdef07..a2ef91827 100644--- a/crates/macos/src/tree/builder.rs+++ b/crates/macos/src/tree/builder.rs@@ -1,13 +1,14 @@+use agent_desktop_core::capability;use agent_desktop_core::node::AccessibilityNode;use rustc_hash::FxHashSet;use super::AXElement;use super::action_list::platform_available_actions;+use super::attributes::{copy_ax_array, copy_ax_array_prefix, copy_bool_attr, copy_string_attr};use super::build_context::TreeBuildContext;use super::capabilities::same_element;use super::element::{- ABSOLUTE_MAX_DEPTH, child_attributes, copy_ax_array, copy_ax_array_prefix, copy_bool_attr,- copy_string_attr, count_children, element_for_pid, fetch_node_attrs,+ ABSOLUTE_MAX_DEPTH, child_attributes, count_children, element_for_pid, fetch_node_attrs,};#[cfg(target_os = "macos")]@@ -21,7 +22,14 @@ pub fn window_element_for(pid: i32, win_title: &str) -> AXElement {let app = element_for_pid(pid);if let Some(windows) = copy_ax_array(&app, kAXWindowsAttribute) {+ let mut first_candidate = None;+ let mut child_candidate = None;+ let mut partial_candidate = None;for win in &windows {+ if !is_window_candidate(win) {+ continue;+ }+ first_candidate.get_or_insert_with(|| win.clone());let title = copy_string_attr(win, kAXTitleAttribute);if title.as_deref()@@ -29,23 +37,18 @@ pub fn window_element_for(pid: i32, win_title: &str) -> AXElement {{return win.clone();}- }- for win in &windows {- let title = copy_string_attr(win, kAXTitleAttribute);if title.as_deref().is_some_and(|title| window_titles_are_partial_match(title, win_title)){- return win.clone();+ partial_candidate.get_or_insert_with(|| win.clone());}- }- for win in &windows {- if count_children(win, None) > 0 {- return win.clone();+ if child_candidate.is_none() && count_children(win, None) > 0 {+ child_candidate = Some(win.clone());}}- if let Some(first) = windows.into_iter().next() {- return first;+ if let Some(candidate) = partial_candidate.or(child_candidate).or(first_candidate) {+ return candidate;}}@@ -64,6 +67,11 @@ fn window_titles_are_partial_match(candidate_title: &str, requested_title: &str)&& (candidate_title.contains(requested_title) || requested_title.contains(candidate_title))}+#[cfg(target_os = "macos")]+fn is_window_candidate(el: &AXElement) -> bool {+ copy_string_attr(el, kAXRoleAttribute).as_deref() == Some("AXWindow")+}+#[cfg(target_os = "macos")]pub fn build_subtree(el: &AXElement,@@ -89,14 +97,14 @@ pub fn build_subtree(let value = redact_secure_value(attrs.role.as_deref(), attrs.value);let name = attrs.title.or(attrs.description);let child_count = count_children(el, attrs.role.as_deref());- let bounds = context.read_bounds(el);+ let bounds = context.bounds_for(attrs.bounds);let mut states = Vec::new();if is_secure_text {states.push("secure".into());}return Some(AccessibilityNode {ref_id: None,- available_actions: platform_available_actions(el, &role),+ available_actions: platform_available_actions(el, &role, attrs.has_scrollbars),name,value,description: None,@@ -125,9 +133,9 @@ pub fn build_subtree(let value = redact_secure_value(attrs.role.as_deref(), attrs.value);let is_promoted_item = promoted_label.is_some();let available_actions = if is_promoted_item {- vec!["Click".into(), "RightClick".into()]+ vec![capability::CLICK.into(), capability::RIGHT_CLICK.into()]} else {- platform_available_actions(el, &role)+ platform_available_actions(el, &role, attrs.has_scrollbars)};let name = promoted_label.or_else(|| attrs.title.clone().or_else(|| attrs.description.clone()));@@ -151,20 +159,25 @@ pub fn build_subtree({states.push("focused".into());}- if !attrs.enabled {+ if !attrs.states.enabled {states.push("disabled".into());}if is_secure_text {states.push("secure".into());}- if element_is_expanded(el) {+ if attrs+ .states+ .expanded+ .or(attrs.states.disclosing)+ .unwrap_or_else(|| element_is_expanded(el))+ {states.push("expanded".into());}if super::roles::is_toggleable_role(&role) && value_is_checked(value.as_deref()) {states.push("checked".into());}- let bounds = context.read_bounds(el);+ let bounds = context.bounds_for(attrs.bounds);let is_web_wrapper = matches!(attrs.role.as_deref(),diff --git a/crates/macos/src/tree/element.rs b/crates/macos/src/tree/element.rsindex 1a09ab248..69008c725 100644--- a/crates/macos/src/tree/element.rs+++ b/crates/macos/src/tree/element.rs@@ -15,14 +15,24 @@ mod imp {use super::*;use crate::{cf_type::created_cf_array,- tree::{NodeAttrs, ax_element::AXElement, ax_value, node_attrs::parse_enabled},+ tree::{+ NodeAttrs,+ attributes::{+ copy_ax_array, copy_bool_attr, copy_first_element_attr, copy_string_attr,+ copy_value_typed,+ },+ ax_element::AXElement,+ ax_value,+ element_bounds::{read_bounds, rect_from_parts},+ node_attrs::{NodeAttrStates, parse_bool_attr, parse_enabled},+ },};use accessibility_sys::{- AXUIElementCopyAttributeValue, AXUIElementCopyAttributeValues,AXUIElementCopyMultipleAttributeValues, AXUIElementCreateApplication,- AXUIElementGetAttributeValueCount, AXUIElementSetMessagingTimeout, kAXDescriptionAttribute,- kAXEnabledAttribute, kAXErrorSuccess, kAXRoleAttribute, kAXTitleAttribute,- kAXValueAttribute,+ AXUIElementGetAttributeValueCount, AXUIElementSetMessagingTimeout, AXValueGetValue,+ kAXDescriptionAttribute, kAXEnabledAttribute, kAXErrorSuccess, kAXPositionAttribute,+ kAXRoleAttribute, kAXSizeAttribute, kAXTitleAttribute, kAXValueAttribute,+ kAXValueTypeCGPoint, kAXValueTypeCGSize,};use core_foundation::{array::CFArray,@@ -31,6 +41,9 @@ mod imp {number::CFNumber,string::CFString,};+ use core_graphics::geometry::{CGPoint, CGSize};++ const SCROLLBAR_ATTRS: [&str; 2] = ["AXVerticalScrollBar", "AXHorizontalScrollBar"];pub fn element_for_pid(pid: i32) -> AXElement {let el = AXElement(unsafe { AXUIElementCreateApplication(pid) });@@ -47,6 +60,13 @@ mod imp {kAXDescriptionAttribute,kAXValueAttribute,kAXEnabledAttribute,+ "AXFocused",+ "AXExpanded",+ "AXDisclosing",+ kAXPositionAttribute,+ kAXSizeAttribute,+ SCROLLBAR_ATTRS[0],+ SCROLLBAR_ATTRS[1],];let cf_names: Vec<CFString> = attr_names.iter().map(|a| CFString::new(a)).collect();let cf_refs: Vec<_> = cf_names.iter().map(|s| s.as_concrete_TypeRef()).collect();@@ -69,46 +89,91 @@ mod imp {let Some(arr) = created_cf_array(result_ref) else {return fetch_node_attrs_slow(el);};- let items: Vec<Option<String>> = arr- .into_iter()- .enumerate()- .map(|(idx, item)| {- if let Some(s) = item.downcast::<CFString>() {- return Some(s.to_string());- }- match idx {- 3 => {- if let Some(b) = item.downcast::<CFBoolean>() {- return Some(bool::from(b).to_string());- }- if let Some(n) = item.downcast::<CFNumber>() {- if let Some(i) = n.to_i64() {- return Some(i.to_string());- }- if let Some(f) = n.to_f64() {- return Some(format!("{:.2}", f));- }- }- None- }- 4 => item- .downcast::<CFBoolean>()- .map(|b| bool::from(b).to_string()),- _ => None,++ let mut texts: [Option<String>; 8] = Default::default();+ let mut position: Option<CGPoint> = None;+ let mut size: Option<CGSize> = None;+ let mut has_scrollbars = false;+ for (idx, item) in arr.into_iter().enumerate() {+ match idx {+ 0..=7 => texts[idx] = decode_text_attr(idx, &item),+ 8 => position = decode_ax_point(&item),+ 9 => size = decode_ax_size(&item),+ 10 | 11 => {+ has_scrollbars =+ has_scrollbars || ax_value::retained_ax_element(&item).is_some();}- })- .collect();+ _ => {}+ }+ }- let get = |i: usize| items.get(i).and_then(|v| v.clone());+ let get = |i: usize| texts.get(i).and_then(|v| v.clone());NodeAttrs {role: get(0),title: get(1),description: get(2),value: get(3),- enabled: parse_enabled(get(4)),+ states: NodeAttrStates {+ enabled: parse_enabled(get(4)),+ focused: parse_bool_attr(get(5)),+ expanded: parse_bool_attr(get(6)),+ disclosing: parse_bool_attr(get(7)),+ },+ bounds: position.zip(size).and_then(|(p, s)| rect_from_parts(p, s)),+ has_scrollbars,+ }+ }++ fn decode_text_attr(idx: usize, item: &CFType) -> Option<String> {+ if let Some(s) = item.downcast::<CFString>() {+ return Some(s.to_string());+ }+ match idx {+ 3 => {+ if let Some(b) = item.downcast::<CFBoolean>() {+ return Some(bool::from(b).to_string());+ }+ if let Some(n) = item.downcast::<CFNumber>() {+ if let Some(i) = n.to_i64() {+ return Some(i.to_string());+ }+ if let Some(f) = n.to_f64() {+ return Some(format!("{:.2}", f));+ }+ }+ None+ }+ 4..=7 => item+ .downcast::<CFBoolean>()+ .map(|b| bool::from(b).to_string()),+ _ => None,}}+ fn decode_ax_point(item: &CFType) -> Option<CGPoint> {+ let mut point = CGPoint::new(0.0, 0.0);+ let decoded = unsafe {+ AXValueGetValue(+ item.as_CFTypeRef() as _,+ kAXValueTypeCGPoint,+ &mut point as *mut _ as *mut std::ffi::c_void,+ )+ };+ decoded.then_some(point)+ }++ fn decode_ax_size(item: &CFType) -> Option<CGSize> {+ let mut size = CGSize::new(0.0, 0.0);+ let decoded = unsafe {+ AXValueGetValue(+ item.as_CFTypeRef() as _,+ kAXValueTypeCGSize,+ &mut size as *mut _ as *mut std::ffi::c_void,+ )+ };+ decoded.then_some(size)+ }+fn fetch_node_attrs_slow(el: &AXElement) -> NodeAttrs {let role = copy_string_attr(el, kAXRoleAttribute);let title = copy_string_attr(el, kAXTitleAttribute);@@ -120,7 +185,14 @@ mod imp {title,description: desc,value: val,- enabled,+ states: NodeAttrStates {+ enabled,+ focused: copy_bool_attr(el, "AXFocused"),+ expanded: copy_bool_attr(el, "AXExpanded"),+ disclosing: copy_bool_attr(el, "AXDisclosing"),+ },+ bounds: read_bounds(el),+ has_scrollbars: copy_first_element_attr(el, &SCROLLBAR_ATTRS).is_some(),}}@@ -145,123 +217,6 @@ mod imp {})}- pub fn copy_string_attr(el: &AXElement, attr: &str) -> Option<String> {- let cf_attr = CFString::new(attr);- let mut value: CFTypeRef = std::ptr::null_mut();- let err = unsafe {- AXUIElementCopyAttributeValue(el.0, cf_attr.as_concrete_TypeRef(), &mut value)- };- if err != kAXErrorSuccess || value.is_null() {- return None;- }- let cf_type = unsafe { CFType::wrap_under_create_rule(value) };- cf_type.downcast::<CFString>().map(|s| s.to_string())- }-- pub fn copy_value_typed(el: &AXElement) -> Option<String> {- let cf_attr = CFString::new(kAXValueAttribute);- let mut val_ref: CFTypeRef = std::ptr::null_mut();- let err = unsafe {- AXUIElementCopyAttributeValue(el.0, cf_attr.as_concrete_TypeRef(), &mut val_ref)- };- if err != kAXErrorSuccess || val_ref.is_null() {- return None;- }- let cf = unsafe { CFType::wrap_under_create_rule(val_ref) };- if let Some(s) = cf.downcast::<CFString>() {- return Some(s.to_string());- }- if let Some(b) = cf.downcast::<CFBoolean>() {- return Some(bool::from(b).to_string());- }- if let Some(n) = cf.downcast::<CFNumber>() {- if let Some(i) = n.to_i64() {- return Some(i.to_string());- }- if let Some(f) = n.to_f64() {- return Some(format!("{:.2}", f));- }- }- None- }-- pub fn copy_bool_attr(el: &AXElement, attr: &str) -> Option<bool> {- let cf_attr = CFString::new(attr);- let mut value: CFTypeRef = std::ptr::null_mut();- let err = unsafe {- AXUIElementCopyAttributeValue(el.0, cf_attr.as_concrete_TypeRef(), &mut value)- };- if err != kAXErrorSuccess || value.is_null() {- return None;- }- let cf_type = unsafe { CFType::wrap_under_create_rule(value) };- cf_type.downcast::<CFBoolean>().map(|b| b.into())- }-- pub fn copy_i64_attr(el: &AXElement, attr: &str) -> Option<i64> {- let cf_attr = CFString::new(attr);- let mut value: CFTypeRef = std::ptr::null_mut();- let err = unsafe {- AXUIElementCopyAttributeValue(el.0, cf_attr.as_concrete_TypeRef(), &mut value)- };- if err != kAXErrorSuccess || value.is_null() {- return None;- }- let cf_type = unsafe { CFType::wrap_under_create_rule(value) };- cf_type.downcast::<CFNumber>().and_then(|n| n.to_i64())- }-- pub fn copy_ax_array(el: &AXElement, attr: &str) -> Option<Vec<AXElement>> {- let cf_attr = CFString::new(attr);- let mut value: CFTypeRef = std::ptr::null_mut();- let err = unsafe {- AXUIElementCopyAttributeValue(el.0, cf_attr.as_concrete_TypeRef(), &mut value)- };- if err != kAXErrorSuccess || value.is_null() {- return None;- }- let arr = created_cf_array(value)?;- Some(ax_array_items(arr))- }-- pub fn copy_ax_array_prefix(- el: &AXElement,- attr: &str,- max_values: usize,- ) -> Option<Vec<AXElement>> {- if max_values == 0 {- return Some(Vec::new());- }- let cf_attr = CFString::new(attr);- let mut value: core_foundation_sys::array::CFArrayRef = std::ptr::null();- let err = unsafe {- AXUIElementCopyAttributeValues(- el.0,- cf_attr.as_concrete_TypeRef(),- 0,- max_values as core_foundation_sys::base::CFIndex,- &mut value,- )- };- if err != kAXErrorSuccess || value.is_null() {- return None;- }- let arr = created_cf_array(value as CFTypeRef)?;- Some(ax_array_items(arr))- }-- pub fn copy_element_attr(el: &AXElement, attr: &str) -> Option<AXElement> {- let cf_attr = CFString::new(attr);- let mut value: CFTypeRef = std::ptr::null_mut();- let err = unsafe {- AXUIElementCopyAttributeValue(el.0, cf_attr.as_concrete_TypeRef(), &mut value)- };- if err != kAXErrorSuccess || value.is_null() {- return None;- }- ax_value::created_ax_element(value)- }-pub fn count_children(element: &AXElement, ax_role: Option<&str>) -> u32 {unsafe {for attr_name in child_attributes(ax_role) {@@ -282,12 +237,6 @@ mod imp {0}}-- fn ax_array_items(arr: CFArray<CFType>) -> Vec<AXElement> {- arr.into_iter()- .filter_map(|item| ax_value::retained_ax_element(&item))- .collect()- }}#[cfg(not(target_os = "macos"))]@@ -298,34 +247,6 @@ mod imp {AXElement(std::ptr::null())}- pub fn copy_ax_array(_el: &AXElement, _attr: &str) -> Option<Vec<AXElement>> {- None- }-- pub fn copy_ax_array_prefix(- _el: &AXElement,- _attr: &str,- _max_values: usize,- ) -> Option<Vec<AXElement>> {- None- }-- pub fn copy_string_attr(_el: &AXElement, _attr: &str) -> Option<String> {- None- }-- pub fn copy_bool_attr(_el: &AXElement, _attr: &str) -> Option<bool> {- None- }-- pub fn copy_i64_attr(_el: &AXElement, _attr: &str) -> Option<i64> {- None- }-- pub fn copy_element_attr(_el: &AXElement, _attr: &str) -> Option<AXElement> {- None- }-pub fn count_children(_element: &AXElement, _ax_role: Option<&str>) -> u32 {0}@@ -334,20 +255,9 @@ mod imp {None}- pub fn copy_value_typed(_el: &AXElement) -> Option<String> {- None- }-pub fn fetch_node_attrs(_el: &AXElement) -> NodeAttrs {- NodeAttrs {- enabled: true,- ..NodeAttrs::default()- }+ NodeAttrs::default()}}-pub use imp::{- copy_ax_array, copy_ax_array_prefix, copy_bool_attr, copy_element_attr, copy_i64_attr,- copy_string_attr, copy_value_typed, count_children, element_for_pid, fetch_node_attrs,- resolve_element_name,-};+pub use imp::{count_children, element_for_pid, fetch_node_attrs, resolve_element_name};diff --git a/crates/macos/src/tree/element_bounds.rs b/crates/macos/src/tree/element_bounds.rsindex deddc37bf..1fa4df873 100644--- a/crates/macos/src/tree/element_bounds.rs+++ b/crates/macos/src/tree/element_bounds.rs@@ -2,6 +2,26 @@ use agent_desktop_core::node::Rect;use super::AXElement;+#[cfg(target_os = "macos")]+pub(crate) fn rect_from_parts(+ point: core_graphics::geometry::CGPoint,+ size: core_graphics::geometry::CGSize,+) -> Option<Rect> {+ if !point.x.is_finite()+ || !point.y.is_finite()+ || !size.width.is_finite()+ || !size.height.is_finite()+ {+ return None;+ }+ Some(Rect {+ x: point.x,+ y: point.y,+ width: size.width,+ height: size.height,+ })+}+#[cfg(target_os = "macos")]pub fn read_bounds(el: &AXElement) -> Option<Rect> {use accessibility_sys::{@@ -58,20 +78,7 @@ pub fn read_bounds(el: &AXElement) -> Option<Rect> {return None;}- if !point.x.is_finite()- || !point.y.is_finite()- || !size.width.is_finite()- || !size.height.is_finite()- {- return None;- }-- Some(Rect {- x: point.x,- y: point.y,- width: size.width,- height: size.height,- })+ rect_from_parts(point, size)}#[cfg(not(target_os = "macos"))]diff --git a/crates/macos/src/tree/element_dedupe.rs b/crates/macos/src/tree/element_dedupe.rsnew file mode 100644index 000000000..7c47b9af8--- /dev/null+++ b/crates/macos/src/tree/element_dedupe.rs@@ -0,0 +1,74 @@+use super::{AXElement, same_element};++#[derive(Default)]+pub(crate) struct ElementDedupe;++impl ElementDedupe {+ pub(crate) fn push(&mut self, elements: &mut Vec<AXElement>, element: AXElement) -> bool {+ if elements+ .iter()+ .any(|existing| equivalent(existing, &element))+ {+ return false;+ }+ elements.push(element);+ true+ }++ pub(crate) fn push_clone(+ &mut self,+ elements: &mut Vec<AXElement>,+ element: &AXElement,+ ) -> bool {+ self.push(elements, element.clone())+ }+}++fn equivalent(existing: &AXElement, element: &AXElement) -> bool {+ existing.0 as usize != 0 && same_element(existing, element)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn null_elements_do_not_collapse_without_semantic_identity() {+ let mut dedupe = ElementDedupe;+ let mut elements = Vec::new();++ assert!(dedupe.push(&mut elements, null_element()));+ assert!(dedupe.push(&mut elements, null_element()));+ assert_eq!(elements.len(), 2);+ }++ #[cfg(target_os = "macos")]+ #[test]+ fn same_ax_element_collapses_to_one_candidate() {+ let mut dedupe = ElementDedupe;+ let mut elements = Vec::new();+ let element = current_process_element();+ let same = element.clone();++ assert!(dedupe.push(&mut elements, element));+ assert!(!dedupe.push(&mut elements, same));+ assert_eq!(elements.len(), 1);+ }++ #[cfg(target_os = "macos")]+ fn null_element() -> AXElement {+ AXElement(std::ptr::null_mut())+ }++ #[cfg(target_os = "macos")]+ fn current_process_element() -> AXElement {+ AXElement(unsafe {+ accessibility_sys::AXUIElementCreateApplication(std::process::id() as i32)+ })+ }++ #[cfg(not(target_os = "macos"))]+ fn null_element() -> AXElement {+ AXElement(std::ptr::null())+ }+}diff --git a/crates/macos/src/tree/mod.rs b/crates/macos/src/tree/mod.rsindex 536bd0aa8..a7cbce980 100644--- a/crates/macos/src/tree/mod.rs+++ b/crates/macos/src/tree/mod.rs@@ -1,4 +1,5 @@pub mod action_list;+pub(crate) mod attributes;pub mod ax_element;pub(crate) mod ax_value;pub mod build_context;@@ -6,21 +7,27 @@ pub mod builder;pub mod capabilities;pub mod element;pub mod element_bounds;+pub(crate) mod element_dedupe;pub(crate) mod node_attrs;pub mod resolve;mod resolve_bounds;+mod resolve_classify;+mod resolve_deadline;mod resolve_identity;+mod resolve_roots;+mod resolve_search;pub mod roles;pub mod surfaces;+pub(crate) use attributes::{+ copy_ax_array, copy_bool_attr, copy_element_attr, copy_i64_attr, copy_string_attr,+ copy_value_typed,+};pub use ax_element::AXElement;pub use build_context::TreeBuildContext;pub use builder::{build_subtree, window_element_for};pub use capabilities::same_element;-pub use element::{- copy_ax_array, copy_bool_attr, copy_element_attr, copy_i64_attr, copy_string_attr,- copy_value_typed, element_for_pid, resolve_element_name,-};+pub use element::{element_for_pid, resolve_element_name};pub use element_bounds::read_bounds;pub(crate) use node_attrs::NodeAttrs;pub use surfaces::{diff --git a/crates/macos/src/tree/node_attrs.rs b/crates/macos/src/tree/node_attrs.rsindex d946f3b22..92f94401a 100644--- a/crates/macos/src/tree/node_attrs.rs+++ b/crates/macos/src/tree/node_attrs.rs@@ -1,16 +1,43 @@-#[derive(Debug, Clone, Default, PartialEq, Eq)]+use agent_desktop_core::node::Rect;++#[derive(Debug, Clone, Default)]pub(crate) struct NodeAttrs {pub(crate) role: Option<String>,pub(crate) title: Option<String>,pub(crate) description: Option<String>,pub(crate) value: Option<String>,+ pub(crate) states: NodeAttrStates,+ pub(crate) bounds: Option<Rect>,+ pub(crate) has_scrollbars: bool,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct NodeAttrStates {pub(crate) enabled: bool,+ pub(crate) focused: Option<bool>,+ pub(crate) expanded: Option<bool>,+ pub(crate) disclosing: Option<bool>,+}++impl Default for NodeAttrStates {+ fn default() -> Self {+ Self {+ enabled: true,+ focused: None,+ expanded: None,+ disclosing: None,+ }+ }}pub(crate) fn parse_enabled(enabled: Option<String>) -> bool {enabled.map(|s| s == "true").unwrap_or(true)}+pub(crate) fn parse_bool_attr(value: Option<String>) -> Option<bool> {+ value.map(|s| s == "true")+}+#[cfg(test)]mod tests {use super::*;diff --git a/crates/macos/src/tree/resolve.rs b/crates/macos/src/tree/resolve.rsindex 7f4bb539b..4f1c4f1ef 100644--- a/crates/macos/src/tree/resolve.rs+++ b/crates/macos/src/tree/resolve.rs@@ -1,83 +1,119 @@use agent_desktop_core::{- adapter::{NativeHandle, SnapshotSurface},+ adapter::NativeHandle,error::{AdapterError, ErrorCode},refs::RefEntry,};-use rustc_hash::FxHashSet;+use std::time::{Duration, Instant};-use super::AXElement;-use super::builder::window_element_for;-use super::element::{- child_attributes, copy_ax_array, copy_element_attr, copy_i64_attr, copy_string_attr,- element_for_pid, resolve_element_name,+#[cfg(target_os = "macos")]+use super::resolve_classify::identity_summary_for_message;+#[cfg(target_os = "macos")]+use super::resolve_deadline::sleep_before_retry;+#[cfg(target_os = "macos")]+use super::resolve_identity::has_meaningful_identity;+#[cfg(target_os = "macos")]+use super::resolve_roots::{+ candidate_roots, path_candidate_roots, source_window_number, source_window_scope_required,};-use super::resolve_bounds::{bounds_match, should_prune_by_bounds};-use super::resolve_identity::{has_meaningful_identity, identity_matches};+#[cfg(target_os = "macos")]+use super::resolve_search::{find_entry_by_path, find_entry_in_roots};#[cfg(target_os = "macos")]pub fn resolve_element_impl(entry: &RefEntry) -> Result<NativeHandle, AdapterError> {- tracing::debug!(- "resolve: searching pid={} role={} name={:?} description={:?} bounds_hash={:?}",- entry.pid,- entry.role,- entry.name.as_deref().unwrap_or("(none)"),- entry.description.as_deref().unwrap_or("(none)"),- entry.bounds_hash- );- let resolve_depth: u8 = 50;- let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);- let attempts = 4;+ resolve_element_with_timeout(entry, Duration::from_secs(5))+}++/// Resolves a ref to a live handle, retrying until the deadline. Once any+/// complete search pass concludes the element is absent, a later attempt that+/// merely runs out of deadline budget is still a stale ref — not an+/// indeterminate timeout. Tracking `proved_absent` keeps STALE_REF+/// deterministic regardless of how big or slow the surrounding tree is.+#[cfg(target_os = "macos")]+pub fn resolve_element_with_timeout(+ entry: &RefEntry,+ timeout: Duration,+) -> Result<NativeHandle, AdapterError> {+ let (resolve_depth, attempts) = (50, 4);+ let deadline = Instant::now() + timeout;+ let mut proved_absent = false;for attempt in 0..attempts {if can_use_path_fast_path(entry) {- let path_roots = path_candidate_roots(entry);- if let Ok(handle) = find_entry_by_path(&path_roots, entry) {- tracing::debug!("resolve: found path match");- return Ok(handle);+ let path_roots = match path_candidate_roots(entry, deadline) {+ Ok(roots) => roots,+ Err(err) => return Err(downgrade_timeout(err, entry, proved_absent)),+ };+ let scope_verified = path_roots.scope_verified;+ match find_entry_by_path(&path_roots.roots, entry, scope_verified, deadline) {+ Ok(handle) => {+ return Ok(handle);+ }+ Err(err) if is_retryable_resolution_error(&err) => proved_absent = true,+ Err(err) => return Err(downgrade_timeout(err, entry, proved_absent)),}- if should_retry_scoped_path_resolution(entry) {- if attempt + 1 < attempts && std::time::Instant::now() < deadline {- std::thread::sleep(std::time::Duration::from_millis(75));+ if requires_scoped_path_resolution(entry) {+ if attempt + 1 < attempts {+ sleep_before_retry(deadline);}continue;}}if !can_use_broad_search(entry) {- if attempt + 1 < attempts && std::time::Instant::now() < deadline {- std::thread::sleep(std::time::Duration::from_millis(75));+ if attempt + 1 < attempts {+ sleep_before_retry(deadline);}continue;}- let roots = candidate_roots(entry);- if let Ok(handle) = find_entry_in_roots(&roots, entry, resolve_depth, deadline) {- tracing::debug!("resolve: found exact match");- return Ok(handle);+ let roots = match candidate_roots(entry, deadline) {+ Ok(roots) => roots,+ Err(err) => return Err(downgrade_timeout(err, entry, proved_absent)),+ };+ let scope_verified = roots.scope_verified;+ match find_entry_in_roots(&roots.roots, entry, resolve_depth, scope_verified, deadline) {+ Ok(handle) => {+ return Ok(handle);+ }+ Err(err) if is_retryable_resolution_error(&err) => proved_absent = true,+ Err(err) => return Err(downgrade_timeout(err, entry, proved_absent)),}- if attempt + 1 < attempts && std::time::Instant::now() < deadline {- std::thread::sleep(std::time::Duration::from_millis(75));+ if attempt + 1 < attempts {+ sleep_before_retry(deadline);}}- tracing::debug!("resolve: element not found");- Err(AdapterError::new(+ Err(stale_ref_error(entry))+}++#[cfg(target_os = "macos")]+fn stale_ref_error(entry: &RefEntry) -> AdapterError {+ AdapterError::new(ErrorCode::StaleRef,- format!(- "Element not found: role={}, name={:?}, description={:?}",- entry.role,- entry.name.as_deref().unwrap_or("(none)"),- entry.description.as_deref().unwrap_or("(none)")- ),+ format!("Element not found: {}", identity_summary_for_message(entry)),)- .with_suggestion("Run 'snapshot' to refresh, then retry with the updated ref."))+ .with_suggestion("Run 'snapshot' to refresh, then retry with the updated ref.")+}++/// A deadline `TIMEOUT` becomes `STALE_REF` once a prior complete pass proved+/// the element absent: the element is gone, the timeout is incidental.+#[cfg(target_os = "macos")]+fn downgrade_timeout(err: AdapterError, entry: &RefEntry, proved_absent: bool) -> AdapterError {+ if proved_absent && err.code == ErrorCode::Timeout {+ stale_ref_error(entry)+ } else {+ err+ }+}++#[cfg(target_os = "macos")]+fn is_retryable_resolution_error(err: &AdapterError) -> bool {+ err.code == ErrorCode::ElementNotFound}#[cfg(target_os = "macos")]fn can_use_path_fast_path(entry: &RefEntry) -> bool {(entry.root_ref.is_none() || entry.path_is_absolute)&& !entry.path.is_empty()- && (entry.bounds_hash.is_some()- || entry.source_window_id.is_some()- || entry.source_window_title.is_some())+ && (entry.bounds_hash.is_some() || source_window_number(entry).is_some())}#[cfg(target_os = "macos")]@@ -85,12 +121,7 @@ fn requires_scoped_path_resolution(entry: &RefEntry) -> bool {(entry.root_ref.is_none() || entry.path_is_absolute)&& entry.bounds_hash.is_none()&& !entry.path.is_empty()- && (entry.source_window_id.is_some() || entry.source_window_title.is_some())-}--#[cfg(target_os = "macos")]-fn should_retry_scoped_path_resolution(entry: &RefEntry) -> bool {- requires_scoped_path_resolution(entry)+ && source_window_scope_required(entry)}#[cfg(target_os = "macos")]@@ -98,234 +129,6 @@ fn can_use_broad_search(entry: &RefEntry) -> bool {entry.bounds_hash.is_some() || has_meaningful_identity(entry)}-#[cfg(target_os = "macos")]-fn path_candidate_roots(entry: &RefEntry) -> Vec<AXElement> {- if entry.bounds_hash.is_some() {- return candidate_roots(entry);- }- scoped_surface_root(entry).into_iter().collect()-}--#[cfg(target_os = "macos")]-fn scoped_surface_root(entry: &RefEntry) -> Option<AXElement> {- match entry.source_surface {- SnapshotSurface::Window => exact_source_window_root(entry),- SnapshotSurface::Focused => crate::tree::focused_surface_for_pid(entry.pid),- SnapshotSurface::Menu => crate::tree::menu_element_for_pid(entry.pid),- SnapshotSurface::Menubar => crate::tree::menubar_for_pid(entry.pid),- SnapshotSurface::Sheet => crate::tree::sheet_for_pid(entry.pid),- SnapshotSurface::Popover => crate::tree::popover_for_pid(entry.pid),- SnapshotSurface::Alert => crate::tree::alert_for_pid(entry.pid),- }-}--#[cfg(target_os = "macos")]-fn exact_source_window_root(entry: &RefEntry) -> Option<AXElement> {- let root = element_for_pid(entry.pid);- let windows = copy_ax_array(&root, "AXWindows")?;- if let Some(source_window_number) = source_window_number(entry) {- if let Some(window) = windows- .iter()- .find(|win| copy_i64_attr(win, "AXWindowNumber") == Some(source_window_number))- {- return Some(window.clone());- }- }- let source_window_title = entry.source_window_title.as_deref()?;- windows- .into_iter()- .find(|win| copy_string_attr(win, "AXTitle").as_deref() == Some(source_window_title))-}--#[cfg(target_os = "macos")]-fn source_window_number(entry: &RefEntry) -> Option<i64> {- entry- .source_window_id- .as_deref()?- .strip_prefix("w-")?- .parse()- .ok()-}--#[cfg(target_os = "macos")]-fn candidate_roots(entry: &RefEntry) -> Vec<AXElement> {- let root = element_for_pid(entry.pid);- let mut roots = Vec::new();- if let Some(source_window_title) = entry.source_window_title.as_deref() {- roots.push(window_element_for(entry.pid, source_window_title));- }- if let Some(focused) = copy_element_attr(&root, "AXFocusedWindow") {- roots.push(focused);- }- if let Some(main) = copy_element_attr(&root, "AXMainWindow") {- roots.push(main);- }- roots.extend(copy_ax_array(&root, "AXWindows").unwrap_or_default());- if let Some(menubar) = crate::tree::menubar_for_pid(entry.pid) {- roots.push(menubar);- }- if let Some(menu) = crate::tree::menu_element_for_pid(entry.pid) {- roots.push(menu);- }- if roots.is_empty() {- roots.push(root);- }- roots-}--#[cfg(target_os = "macos")]-fn find_entry_by_path(roots: &[AXElement], entry: &RefEntry) -> Result<NativeHandle, AdapterError> {- use core_foundation::base::{CFRetain, CFTypeRef};-- if entry.path.is_empty() {- return Err(AdapterError::element_not_found("element"));- }-- for root in roots {- let Some(candidate) = element_at_path(root, &entry.path) else {- continue;- };- if element_matches_entry(&candidate, entry) {- unsafe { CFRetain(candidate.0 as CFTypeRef) };- return Ok(unsafe { NativeHandle::from_ptr(candidate.0 as *const _) });- }- }-- Err(AdapterError::element_not_found("element"))-}--#[cfg(target_os = "macos")]-fn element_at_path(root: &AXElement, path: &[usize]) -> Option<AXElement> {- let mut current = root.clone();- for idx in path {- let ax_role = copy_string_attr(¤t, accessibility_sys::kAXRoleAttribute);- let children = resolve_children(¤t, ax_role.as_deref());- current = children.get(*idx)?.clone();- }- Some(current)-}--#[cfg(target_os = "macos")]-fn find_entry_in_roots(- roots: &[AXElement],- entry: &RefEntry,- resolve_depth: u8,- deadline: std::time::Instant,-) -> Result<NativeHandle, AdapterError> {- for root in roots {- let mut visited = FxHashSet::default();- if let Ok(handle) =- find_element_recursive(root, entry, 0, resolve_depth, &mut visited, deadline)- {- return Ok(handle);- }- }- Err(AdapterError::element_not_found("element"))-}--/// Depth-first search for a single element matching `entry`.-///-/// `deadline` is shared across retry attempts so the total wall-clock time is-/// bounded at five seconds.-#[cfg(target_os = "macos")]-pub fn find_element_recursive(- el: &AXElement,- entry: &RefEntry,- depth: u8,- max_depth: u8,- ancestors: &mut FxHashSet<usize>,- deadline: std::time::Instant,-) -> Result<NativeHandle, AdapterError> {- use accessibility_sys::kAXRoleAttribute;- use core_foundation::base::{CFRetain, CFTypeRef};-- if std::time::Instant::now() > deadline {- return Err(- AdapterError::new(ErrorCode::Timeout, "Element resolution timed out")- .with_suggestion("Retry the command, or run 'snapshot' if the UI changed."),- );- }-- let ptr_key = el.0 as usize;- if !ancestors.insert(ptr_key) {- return Err(AdapterError::element_not_found("element"));- }-- let ax_role = copy_string_attr(el, kAXRoleAttribute);- let normalized = crate::tree::roles::normalized_role_for_element(el, ax_role.as_deref());-- if normalized == entry.role && element_matches_entry(el, entry) {- ancestors.remove(&ptr_key);- unsafe { CFRetain(el.0 as CFTypeRef) };- return Ok(unsafe { NativeHandle::from_ptr(el.0 as *const _) });- }-- if depth >= max_depth {- ancestors.remove(&ptr_key);- return Err(AdapterError::element_not_found("element"));- }-- if should_prune_by_bounds(el, entry, depth) {- ancestors.remove(&ptr_key);- return Err(AdapterError::element_not_found("element"));- }-- let children = resolve_children(el, ax_role.as_deref());-- for child in &children {- if let Ok(handle) =- find_element_recursive(child, entry, depth + 1, max_depth, ancestors, deadline)- {- ancestors.remove(&ptr_key);- return Ok(handle);- }- }-- ancestors.remove(&ptr_key);- Err(AdapterError::element_not_found("element"))-}--#[cfg(target_os = "macos")]-fn element_matches_entry(el: &AXElement, entry: &RefEntry) -> bool {- element_matches_path_entry(el, entry) && bounds_match(el, entry)-}--#[cfg(target_os = "macos")]-fn element_matches_path_entry(el: &AXElement, entry: &RefEntry) -> bool {- let ax_role = copy_string_attr(el, accessibility_sys::kAXRoleAttribute);- let (normalized, promoted_label) =- crate::tree::roles::normalized_role_and_label(el, ax_role.as_deref());- if normalized != entry.role {- return false;- }-- let elem_name = promoted_label.or_else(|| resolve_element_name(el));- let elem_value = crate::tree::copy_value_typed(el);- let elem_description = copy_string_attr(el, accessibility_sys::kAXDescriptionAttribute);- identity_matches(- entry,- elem_name.as_deref(),- elem_value.as_deref(),- elem_description.as_deref(),- )-}--#[cfg(target_os = "macos")]-fn resolve_children(el: &AXElement, ax_role: Option<&str>) -> Vec<AXElement> {- let mut seen = FxHashSet::default();- let mut result = Vec::new();- for attr in child_attributes(ax_role) {- if let Some(children) = copy_ax_array(el, attr) {- for child in children {- if seen.insert(child.0 as usize) {- result.push(child);- }- }- }- }- result-}-#[cfg(test)]#[path = "resolve_tests.rs"]mod tests;@@ -334,15 +137,3 @@ mod tests;pub fn resolve_element_impl(_entry: &RefEntry) -> Result<NativeHandle, AdapterError> {Err(AdapterError::not_supported("resolve_element"))}--#[cfg(not(target_os = "macos"))]-pub fn find_element_recursive(- _el: &AXElement,- _entry: &RefEntry,- _depth: u8,- _max_depth: u8,- _ancestors: &mut FxHashSet<usize>,- _deadline: std::time::Instant,-) -> Result<NativeHandle, AdapterError> {- Err(AdapterError::not_supported("find_element_recursive"))-}diff --git a/crates/macos/src/tree/resolve_classify.rs b/crates/macos/src/tree/resolve_classify.rsnew file mode 100644index 000000000..46453bc1c--- /dev/null+++ b/crates/macos/src/tree/resolve_classify.rs@@ -0,0 +1,119 @@+use agent_desktop_core::{adapter::NativeHandle, error::AdapterError, refs::RefEntry};++use super::AXElement;+#[cfg(target_os = "macos")]+use super::attributes::copy_string_attr;+#[cfg(target_os = "macos")]+use super::element::resolve_element_name;+#[cfg(target_os = "macos")]+use super::resolve_bounds::bounds_match;++#[cfg(target_os = "macos")]+pub(super) fn classify_candidates(+ mut matches: Vec<AXElement>,+ entry: &RefEntry,+ source_window_verified: bool,+) -> Result<NativeHandle, AdapterError> {+ match matches.len() {+ 0 => Err(AdapterError::element_not_found("element")),+ 1 => {+ let candidate = matches.remove(0);+ if source_window_verified || verified_bounds_match(&candidate, entry) {+ retained_handle(candidate)+ } else {+ Err(AdapterError::element_not_found("element"))+ }+ }+ _ => classify_ambiguous_candidates(matches, entry),+ }+}++#[cfg(target_os = "macos")]+fn verified_bounds_match(candidate: &AXElement, entry: &RefEntry) -> bool {+ entry.bounds_hash.is_some() && bounds_match(candidate, entry)+}++#[cfg(target_os = "macos")]+fn classify_ambiguous_candidates(+ matches: Vec<AXElement>,+ entry: &RefEntry,+) -> Result<NativeHandle, AdapterError> {+ let mut bounds_matches: Vec<_> = matches+ .iter()+ .filter(|candidate| verified_bounds_match(candidate, entry))+ .cloned()+ .collect();+ if entry.bounds_hash.is_some() && bounds_matches.is_empty() {+ return Err(AdapterError::element_not_found("element"));+ }+ if bounds_matches.len() == 1 {+ return retained_handle(bounds_matches.remove(0));+ }+ let count = matches.len();+ Err(AdapterError::ambiguous_target(format!(+ "Ambiguous target: {count} candidates matched {}",+ identity_summary_for_message(entry)+ ))+ .with_details(serde_json::json!({+ "candidate_count": count,+ "role": entry.role,+ "name": entry.name,+ "description": entry.description,+ "source_app": entry.source_app,+ "source_window_id": entry.source_window_id,+ "source_window_title": entry.source_window_title,+ "candidates": candidate_summaries(&matches)+ })))+}++#[cfg(target_os = "macos")]+pub(super) fn identity_summary_for_message(entry: &RefEntry) -> String {+ format!(+ "role={}, name_chars={}, description_chars={}",+ entry.role,+ text_len(entry.name.as_deref()),+ text_len(entry.description.as_deref())+ )+}++#[cfg(target_os = "macos")]+fn text_len(value: Option<&str>) -> usize {+ value.unwrap_or("").chars().count()+}++#[cfg(target_os = "macos")]+fn retained_handle(candidate: AXElement) -> Result<NativeHandle, AdapterError> {+ use core_foundation::base::{CFRetain, CFTypeRef};+ #[cfg(test)]+ if candidate.0.is_null() {+ return Ok(NativeHandle::null());+ }+ unsafe { CFRetain(candidate.0 as CFTypeRef) };+ Ok(unsafe { NativeHandle::from_ptr(candidate.0 as *const _) })+}++#[cfg(target_os = "macos")]+fn candidate_summaries(matches: &[AXElement]) -> Vec<serde_json::Value> {+ matches+ .iter()+ .take(10)+ .enumerate()+ .map(|(index, element)| {+ let ax_role = copy_string_attr(element, accessibility_sys::kAXRoleAttribute);+ let role = crate::tree::roles::normalized_role_for_element(element, ax_role.as_deref());+ let name = crate::tree::roles::normalized_role_and_label(element, ax_role.as_deref())+ .1+ .or_else(|| resolve_element_name(element));+ let description = copy_string_attr(element, accessibility_sys::kAXDescriptionAttribute);+ let bounds = crate::tree::read_bounds(element);+ serde_json::json!({+ "index": index,+ "role": role,+ "name": name,+ "description": description,+ "bounds": bounds,+ "bounds_hash": bounds.as_ref().map(|bounds| bounds.bounds_hash())+ })+ })+ .collect()+}diff --git a/crates/macos/src/tree/resolve_deadline.rs b/crates/macos/src/tree/resolve_deadline.rsnew file mode 100644index 000000000..4895380a4--- /dev/null+++ b/crates/macos/src/tree/resolve_deadline.rs@@ -0,0 +1,29 @@+use agent_desktop_core::error::{AdapterError, ErrorCode};+use std::time::{Duration, Instant};++#[cfg(target_os = "macos")]+pub(super) fn remaining_before_deadline(deadline: Instant) -> Result<Duration, AdapterError> {+ let remaining = deadline.saturating_duration_since(Instant::now());+ if remaining.is_zero() {+ return Err(timeout_error());+ }+ Ok(remaining)+}++#[cfg(target_os = "macos")]+pub(super) fn ensure_before_deadline(deadline: Instant) -> Result<(), AdapterError> {+ remaining_before_deadline(deadline).map(|_| ())+}++#[cfg(target_os = "macos")]+pub(super) fn timeout_error() -> AdapterError {+ AdapterError::new(ErrorCode::Timeout, "Element resolution timed out")+ .with_suggestion("Retry the command, or run 'snapshot' if the UI changed.")+}++#[cfg(target_os = "macos")]+pub(super) fn sleep_before_retry(deadline: Instant) {+ if let Ok(remaining) = remaining_before_deadline(deadline) {+ std::thread::sleep(remaining.min(Duration::from_millis(75)));+ }+}diff --git a/crates/macos/src/tree/resolve_identity.rs b/crates/macos/src/tree/resolve_identity.rsindex ed7fbfa42..2a4200e79 100644--- a/crates/macos/src/tree/resolve_identity.rs+++ b/crates/macos/src/tree/resolve_identity.rs@@ -1,8 +1,8 @@-use agent_desktop_core::refs::RefEntry;+use agent_desktop_core::{refs::RefEntry, roles::is_mutable_value_role};pub(super) fn has_meaningful_identity(entry: &RefEntry) -> bool {meaningful_text(entry.name.as_deref()).is_some()- || meaningful_text(entry.value.as_deref()).is_some()+ || stable_value(entry.role.as_str(), entry.value.as_deref()).is_some()|| meaningful_text(entry.description.as_deref()).is_some()}@@ -13,10 +13,10 @@ pub(super) fn identity_matches(actual_description: Option<&str>,) -> bool {let expected_name = meaningful_text(entry.name.as_deref());- let expected_value = meaningful_text(entry.value.as_deref());+ let expected_value = stable_value(entry.role.as_str(), entry.value.as_deref());let expected_description = meaningful_text(entry.description.as_deref());let actual_name = meaningful_text(actual_name);- let actual_value = meaningful_text(actual_value);+ let actual_value = stable_value(entry.role.as_str(), actual_value);let actual_description = meaningful_text(actual_description);if let Some(expected) = expected_name {@@ -47,6 +47,12 @@ fn meaningful_text(value: Option<&str>) -> Option<&str> {value.filter(|text| !text.is_empty())}+fn stable_value<'a>(role: &str, value: Option<&'a str>) -> Option<&'a str> {+ (!is_mutable_value_role(role))+ .then(|| meaningful_text(value))+ .flatten()+}+#[cfg(test)]#[path = "resolve_identity_tests.rs"]mod tests;diff --git a/crates/macos/src/tree/resolve_identity_tests.rs b/crates/macos/src/tree/resolve_identity_tests.rsindex d9b58ccb7..09793480a 100644--- a/crates/macos/src/tree/resolve_identity_tests.rs+++ b/crates/macos/src/tree/resolve_identity_tests.rs@@ -87,3 +87,35 @@ fn value_identity_cannot_be_rescued_by_matching_name_when_value_mismatches() {assert!(identity_matches(&entry, Some("On"), None, None));assert!(!identity_matches(&entry, Some("On"), Some("Off"), None));}++#[test]+fn mutable_value_role_does_not_go_stale_when_value_changes() {+ let mut entry = entry();+ entry.role = "textfield".into();+ entry.value = Some("seed".into());++ assert!(!has_meaningful_identity(&entry));+ assert!(identity_matches(&entry, None, Some("changed"), None));+}++#[test]+fn named_mutable_value_role_still_uses_name_identity() {+ let mut entry = entry();+ entry.role = "textfield".into();+ entry.name = Some("Search".into());+ entry.value = Some("old query".into());++ assert!(has_meaningful_identity(&entry));+ assert!(identity_matches(+ &entry,+ Some("Search"),+ Some("new query"),+ None+ ));+ assert!(!identity_matches(+ &entry,+ Some("Replace"),+ Some("new query"),+ None+ ));+}diff --git a/crates/macos/src/tree/resolve_roots.rs b/crates/macos/src/tree/resolve_roots.rsnew file mode 100644index 000000000..c3cb244bc--- /dev/null+++ b/crates/macos/src/tree/resolve_roots.rs@@ -0,0 +1,272 @@+use agent_desktop_core::{adapter::SnapshotSurface, error::AdapterError, refs::RefEntry};+use std::time::Instant;++use super::AXElement;+use super::attributes::{+ copy_ax_array, copy_element_attr, copy_i64_attr, copy_string_attr, set_messaging_timeout,+};+use super::element::element_for_pid;+use super::element_dedupe::ElementDedupe;+use super::resolve_deadline::{ensure_before_deadline, remaining_before_deadline};++#[cfg(target_os = "macos")]+pub(super) struct CandidateRoots {+ pub roots: Vec<AXElement>,+ pub scope_verified: bool,+}++#[cfg(target_os = "macos")]+pub(super) fn path_candidate_roots(+ entry: &RefEntry,+ deadline: Instant,+) -> Result<CandidateRoots, AdapterError> {+ if entry.bounds_hash.is_some() {+ return candidate_roots(entry, deadline);+ }+ let roots: Vec<_> = scoped_surface_root(entry, deadline)?.into_iter().collect();+ Ok(CandidateRoots {+ scope_verified: source_window_scope_required(entry) && !roots.is_empty(),+ roots,+ })+}++#[cfg(target_os = "macos")]+pub(super) fn candidate_roots(+ entry: &RefEntry,+ deadline: Instant,+) -> Result<CandidateRoots, AdapterError> {+ if source_window_scope_required(entry) {+ return source_window_scoped_roots(entry, deadline);+ }++ let root = element_for_pid(entry.pid);+ prepare_for_read(&root, deadline)?;+ let mut roots = Vec::new();+ let mut dedupe = ElementDedupe;+ let windows = copy_ax_array(&root, "AXWindows").unwrap_or_default();+ if let Some(window) = exact_source_window_from_windows(&windows, entry, deadline) {+ dedupe.push(&mut roots, window);+ }+ prepare_for_read(&root, deadline)?;+ if let Some(focused) = copy_element_attr(&root, "AXFocusedWindow") {+ dedupe.push(&mut roots, focused);+ }+ prepare_for_read(&root, deadline)?;+ if let Some(main) = copy_element_attr(&root, "AXMainWindow") {+ dedupe.push(&mut roots, main);+ }+ for window in windows {+ dedupe.push(&mut roots, window);+ }+ ensure_before_deadline(deadline)?;+ if let Some(menubar) = crate::tree::menubar_for_pid(entry.pid) {+ dedupe.push(&mut roots, menubar);+ }+ ensure_before_deadline(deadline)?;+ if let Some(menu) = crate::tree::menu_element_for_pid(entry.pid) {+ dedupe.push(&mut roots, menu);+ }+ if roots.is_empty() {+ roots.push(root);+ }+ Ok(CandidateRoots {+ roots,+ scope_verified: false,+ })+}++#[cfg(target_os = "macos")]+fn source_window_scoped_roots(+ entry: &RefEntry,+ deadline: Instant,+) -> Result<CandidateRoots, AdapterError> {+ let Some(windows) = windows_for_pid(entry.pid, deadline)? else {+ return Ok(CandidateRoots {+ roots: Vec::new(),+ scope_verified: false,+ });+ };+ if let Some(window) = window_by_number(&windows, source_window_number(entry), deadline) {+ return Ok(CandidateRoots {+ roots: vec![window],+ scope_verified: true,+ });+ }+ if single_window_fallback_allowed(entry) {+ if let Some(window) = fallback_source_window_root(&windows, entry, deadline) {+ return Ok(CandidateRoots {+ roots: vec![window],+ scope_verified: false,+ });+ }+ }+ Ok(CandidateRoots {+ roots: Vec::new(),+ scope_verified: false,+ })+}++#[cfg(target_os = "macos")]+fn scoped_surface_root(+ entry: &RefEntry,+ deadline: Instant,+) -> Result<Option<AXElement>, AdapterError> {+ ensure_before_deadline(deadline)?;+ let root = match entry.source_surface {+ SnapshotSurface::Window if source_window_scope_required(entry) => {+ exact_source_window_number_root(entry, deadline)?+ }+ SnapshotSurface::Window => exact_source_window_root(entry, deadline)?,+ SnapshotSurface::Focused => crate::tree::focused_surface_for_pid(entry.pid),+ SnapshotSurface::Menu => crate::tree::menu_element_for_pid(entry.pid),+ SnapshotSurface::Menubar => crate::tree::menubar_for_pid(entry.pid),+ SnapshotSurface::Sheet => crate::tree::sheet_for_pid(entry.pid),+ SnapshotSurface::Popover => crate::tree::popover_for_pid(entry.pid),+ SnapshotSurface::Alert => crate::tree::alert_for_pid(entry.pid),+ };+ Ok(root)+}++#[cfg(target_os = "macos")]+fn exact_source_window_number_root(+ entry: &RefEntry,+ deadline: Instant,+) -> Result<Option<AXElement>, AdapterError> {+ let Some(windows) = windows_for_pid(entry.pid, deadline)? else {+ return Ok(None);+ };+ Ok(window_by_number(+ &windows,+ source_window_number(entry),+ deadline,+ ))+}++#[cfg(target_os = "macos")]+fn exact_source_window_root(+ entry: &RefEntry,+ deadline: Instant,+) -> Result<Option<AXElement>, AdapterError> {+ let Some(windows) = windows_for_pid(entry.pid, deadline)? else {+ return Ok(None);+ };+ Ok(exact_source_window_from_windows(&windows, entry, deadline))+}++#[cfg(target_os = "macos")]+fn exact_source_window_from_windows(+ windows: &[AXElement],+ entry: &RefEntry,+ deadline: Instant,+) -> Option<AXElement> {+ if let Some(window) = window_by_number(windows, source_window_number(entry), deadline) {+ return Some(window);+ }+ window_by_title(windows, entry.source_window_title.as_deref(), deadline)+}++#[cfg(target_os = "macos")]+fn windows_for_pid(pid: i32, deadline: Instant) -> Result<Option<Vec<AXElement>>, AdapterError> {+ let root = element_for_pid(pid);+ prepare_for_read(&root, deadline)?;+ Ok(copy_ax_array(&root, "AXWindows"))+}++#[cfg(target_os = "macos")]+fn window_by_number(+ windows: &[AXElement],+ source_window_number: Option<i64>,+ deadline: Instant,+) -> Option<AXElement> {+ let source_window_number = source_window_number?;+ windows+ .iter()+ .find(|win| {+ prepare_for_read(win, deadline).is_ok()+ && copy_i64_attr(win, "AXWindowNumber") == Some(source_window_number)+ })+ .cloned()+}++#[cfg(target_os = "macos")]+fn window_by_title(+ windows: &[AXElement],+ source_window_title: Option<&str>,+ deadline: Instant,+) -> Option<AXElement> {+ let source_window_title = source_window_title?;+ let index = unique_fallible_matching_index(windows, |win| {+ prepare_for_read(win, deadline)?;+ Ok::<bool, AdapterError>(+ copy_string_attr(win, "AXTitle").as_deref() == Some(source_window_title),+ )+ })?;+ windows.get(index).cloned()+}++#[cfg(target_os = "macos")]+fn fallback_source_window_root(+ windows: &[AXElement],+ entry: &RefEntry,+ deadline: Instant,+) -> Option<AXElement> {+ if let Some(window) = window_by_title(windows, entry.source_window_title.as_deref(), deadline) {+ return Some(window);+ }+ if !sole_source_window_fallback_allowed(entry) {+ return None;+ }+ let index = unique_fallible_matching_index(windows, |win| {+ prepare_for_read(win, deadline)?;+ Ok::<bool, AdapterError>(copy_string_attr(win, "AXRole").as_deref() == Some("AXWindow"))+ })?;+ windows.get(index).cloned()+}++#[cfg(target_os = "macos")]+pub(super) fn source_window_scope_required(entry: &RefEntry) -> bool {+ matches!(entry.source_surface, SnapshotSurface::Window) && source_window_number(entry).is_some()+}++#[cfg(target_os = "macos")]+pub(super) fn single_window_fallback_allowed(entry: &RefEntry) -> bool {+ source_window_scope_required(entry) && entry.bounds_hash.is_some()+}++#[cfg(target_os = "macos")]+pub(super) fn sole_source_window_fallback_allowed(entry: &RefEntry) -> bool {+ single_window_fallback_allowed(entry) && entry.source_window_title.is_none()+}++#[cfg(target_os = "macos")]+pub(super) fn source_window_number(entry: &RefEntry) -> Option<i64> {+ entry+ .source_window_id+ .as_deref()?+ .strip_prefix("w-")?+ .parse()+ .ok()+}++#[cfg(target_os = "macos")]+fn prepare_for_read(element: &AXElement, deadline: Instant) -> Result<(), AdapterError> {+ set_messaging_timeout(element, remaining_before_deadline(deadline)?);+ Ok(())+}++#[cfg(target_os = "macos")]+pub(super) fn unique_fallible_matching_index<T, E>(+ items: &[T],+ mut matches: impl FnMut(&T) -> Result<bool, E>,+) -> Option<usize> {+ let mut first = None;+ for (index, item) in items.iter().enumerate() {+ match matches(item) {+ Ok(true) if first.is_none() => first = Some(index),+ Ok(true) => return None,+ Ok(false) => {}+ Err(_) => return None,+ }+ }+ first+}diff --git a/crates/macos/src/tree/resolve_search.rs b/crates/macos/src/tree/resolve_search.rsnew file mode 100644index 000000000..3e28ed86c--- /dev/null+++ b/crates/macos/src/tree/resolve_search.rs@@ -0,0 +1,212 @@+use agent_desktop_core::{adapter::NativeHandle, error::AdapterError, refs::RefEntry};+use rustc_hash::FxHashSet;+use std::time::Instant;++use super::AXElement;+#[cfg(target_os = "macos")]+use super::attributes::{copy_ax_array, copy_string_attr, set_messaging_timeout};+#[cfg(target_os = "macos")]+use super::element::{child_attributes, resolve_element_name};+use super::element_dedupe::ElementDedupe;+use super::resolve_bounds::should_prune_by_bounds;+#[cfg(target_os = "macos")]+use super::resolve_classify::classify_candidates;+#[cfg(target_os = "macos")]+use super::resolve_deadline::{ensure_before_deadline, remaining_before_deadline};+use super::resolve_identity::has_meaningful_identity;+#[cfg(target_os = "macos")]+use super::resolve_identity::identity_matches;++#[cfg(target_os = "macos")]+pub(super) fn find_entry_by_path(+ roots: &[AXElement],+ entry: &RefEntry,+ source_window_verified: bool,+ deadline: Instant,+) -> Result<NativeHandle, AdapterError> {+ if entry.path.is_empty() {+ return Err(AdapterError::element_not_found("element"));+ }+ ensure_before_deadline(deadline)?;++ let mut matches = Vec::new();+ let mut dedupe = ElementDedupe;+ for root in roots {+ ensure_before_deadline(deadline)?;+ if should_stop_collecting(matches.len(), entry) {+ break;+ }+ let Some(candidate) = element_at_path(root, &entry.path, deadline)? else {+ continue;+ };+ if element_matches_entry(&candidate, entry) {+ dedupe.push(&mut matches, candidate);+ }+ }++ classify_candidates(matches, entry, source_window_verified)+}++#[cfg(target_os = "macos")]+fn element_at_path(+ root: &AXElement,+ path: &[usize],+ deadline: Instant,+) -> Result<Option<AXElement>, AdapterError> {+ let mut current = root.clone();+ let mut seen = FxHashSet::default();+ for idx in path {+ ensure_before_deadline(deadline)?;+ let ax_role = copy_string_attr(¤t, accessibility_sys::kAXRoleAttribute);+ let children = resolve_children(¤t, ax_role.as_deref(), deadline, &mut seen)?;+ let Some(child) = children.get(*idx) else {+ return Ok(None);+ };+ current = child.clone();+ }+ Ok(Some(current))+}++#[cfg(target_os = "macos")]+pub(super) fn find_entry_in_roots(+ roots: &[AXElement],+ entry: &RefEntry,+ resolve_depth: u8,+ source_window_verified: bool,+ deadline: Instant,+) -> Result<NativeHandle, AdapterError> {+ let mut matches = Vec::new();+ let mut seen_matches = ElementDedupe;+ let mut child_scratch = FxHashSet::default();+ for root in roots {+ if should_stop_collecting(matches.len(), entry) {+ break;+ }+ let mut visited = FxHashSet::default();+ let mut context = CollectContext {+ entry,+ max_depth: resolve_depth,+ ancestors: &mut visited,+ seen_matches: &mut seen_matches,+ matches: &mut matches,+ child_scratch: &mut child_scratch,+ deadline,+ };+ collect_elements_recursive(root, 0, &mut context)?;+ }+ classify_candidates(matches, entry, source_window_verified)+}++#[cfg(target_os = "macos")]+struct CollectContext<'a> {+ entry: &'a RefEntry,+ max_depth: u8,+ ancestors: &'a mut FxHashSet<usize>,+ seen_matches: &'a mut ElementDedupe,+ matches: &'a mut Vec<AXElement>,+ child_scratch: &'a mut FxHashSet<usize>,+ deadline: Instant,+}++#[cfg(target_os = "macos")]+fn collect_elements_recursive(+ el: &AXElement,+ depth: u8,+ context: &mut CollectContext<'_>,+) -> Result<(), AdapterError> {+ use accessibility_sys::kAXRoleAttribute;++ if should_stop_collecting(context.matches.len(), context.entry) {+ return Ok(());+ }+ ensure_before_deadline(context.deadline)?;++ let ptr_key = el.0 as usize;+ if !context.ancestors.insert(ptr_key) {+ return Ok(());+ }++ let ax_role = copy_string_attr(el, kAXRoleAttribute);+ let (normalized, promoted_label) =+ crate::tree::roles::normalized_role_and_label(el, ax_role.as_deref());++ if normalized == context.entry.role+ && element_identity_matches(el, context.entry, promoted_label)+ && context.seen_matches.push_clone(context.matches, el)+ && should_stop_collecting(context.matches.len(), context.entry)+ {+ context.ancestors.remove(&ptr_key);+ return Ok(());+ }++ if depth < context.max_depth && !should_prune_for_resolution(el, context.entry, depth) {+ let children = resolve_children(+ el,+ ax_role.as_deref(),+ context.deadline,+ context.child_scratch,+ )?;+ for child in &children {+ collect_elements_recursive(child, depth + 1, context)?;+ }+ }++ context.ancestors.remove(&ptr_key);+ Ok(())+}++#[cfg(target_os = "macos")]+fn element_matches_entry(el: &AXElement, entry: &RefEntry) -> bool {+ let ax_role = copy_string_attr(el, accessibility_sys::kAXRoleAttribute);+ let (normalized, promoted_label) =+ crate::tree::roles::normalized_role_and_label(el, ax_role.as_deref());+ normalized == entry.role && element_identity_matches(el, entry, promoted_label)+}++pub(super) fn should_stop_collecting(match_count: usize, entry: &RefEntry) -> bool {+ match_count > 1 && entry.bounds_hash.is_none()+}++fn should_prune_for_resolution(el: &AXElement, entry: &RefEntry, depth: u8) -> bool {+ !has_meaningful_identity(entry) && should_prune_by_bounds(el, entry, depth)+}++#[cfg(target_os = "macos")]+fn element_identity_matches(+ el: &AXElement,+ entry: &RefEntry,+ promoted_label: Option<String>,+) -> bool {+ let elem_name = promoted_label.or_else(|| resolve_element_name(el));+ let elem_value = crate::tree::copy_value_typed(el);+ let elem_description = copy_string_attr(el, accessibility_sys::kAXDescriptionAttribute);+ identity_matches(+ entry,+ elem_name.as_deref(),+ elem_value.as_deref(),+ elem_description.as_deref(),+ )+}++#[cfg(target_os = "macos")]+fn resolve_children(+ el: &AXElement,+ ax_role: Option<&str>,+ deadline: Instant,+ seen: &mut FxHashSet<usize>,+) -> Result<Vec<AXElement>, AdapterError> {+ seen.clear();+ set_messaging_timeout(el, remaining_before_deadline(deadline)?);+ let mut result = Vec::new();+ for attr in child_attributes(ax_role) {+ ensure_before_deadline(deadline)?;+ if let Some(children) = copy_ax_array(el, attr) {+ for child in children {+ if seen.insert(child.0 as usize) {+ result.push(child);+ }+ }+ }+ }+ Ok(result)+}diff --git a/crates/macos/src/tree/resolve_tests.rs b/crates/macos/src/tree/resolve_tests.rsindex b120328b5..934e1cbc6 100644--- a/crates/macos/src/tree/resolve_tests.rs+++ b/crates/macos/src/tree/resolve_tests.rs@@ -1,4 +1,12 @@use super::*;+use crate::tree::AXElement;+use crate::tree::resolve_classify::classify_candidates;+use crate::tree::resolve_roots::{+ single_window_fallback_allowed, sole_source_window_fallback_allowed, source_window_number,+ unique_fallible_matching_index,+};+use crate::tree::resolve_search::should_stop_collecting;+use agent_desktop_core::adapter::SnapshotSurface;fn entry(bounds_hash: Option<u64>,@@ -19,7 +27,7 @@ fn entry(source_app: None,source_window_id: source_window_id.map(String::from),source_window_title: source_window_title.map(String::from),- source_surface: agent_desktop_core::adapter::SnapshotSurface::Window,+ source_surface: SnapshotSurface::Window,root_ref: root_ref.map(String::from),path_is_absolute: false,path: smallvec::smallvec![0, 1],@@ -35,7 +43,7 @@ fn path_fast_path_accepts_bounds_or_source_window_identity() {None,None)));- assert!(can_use_path_fast_path(&entry(+ assert!(!can_use_path_fast_path(&entry(None,None,Some("Documents"),@@ -64,7 +72,7 @@ fn no_bounds_source_window_refs_require_scoped_path_resolution() {None,None)));- assert!(requires_scoped_path_resolution(&entry(+ assert!(!requires_scoped_path_resolution(&entry(None,None,Some("Documents"),@@ -91,9 +99,9 @@ fn no_bounds_source_window_refs_require_scoped_path_resolution() {fn scoped_path_retry_fails_closed_when_scope_is_unresolved() {let no_bounds_entry = entry(None, Some("w-10"), Some("Freeform"), None);- assert!(should_retry_scoped_path_resolution(&no_bounds_entry));- assert!(should_retry_scoped_path_resolution(&description_entry()));- assert!(!should_retry_scoped_path_resolution(&entry(+ assert!(requires_scoped_path_resolution(&no_bounds_entry));+ assert!(requires_scoped_path_resolution(&description_entry()));+ assert!(!requires_scoped_path_resolution(&entry(Some(42),Some("w-10"),Some("Freeform"),@@ -106,7 +114,7 @@ fn scoped_path_retry_fails_closed_for_blank_identity_without_bounds() {let mut blank = entry(None, Some("w-10"), Some("Freeform"), None);blank.name = None;- assert!(should_retry_scoped_path_resolution(&blank));+ assert!(requires_scoped_path_resolution(&blank));}#[test]@@ -135,6 +143,183 @@ fn source_window_number_parses_window_ids_only() {);}+#[test]+fn only_element_not_found_is_retryable_resolution_error() {+ assert!(is_retryable_resolution_error(+ &AdapterError::element_not_found("element")+ ));+ assert!(!is_retryable_resolution_error(+ &AdapterError::ambiguous_target("2 candidates matched")+ ));+ assert!(!is_retryable_resolution_error(&AdapterError::new(+ ErrorCode::Timeout,+ "resolution timed out"+ )));+}++#[test]+fn expired_deadline_fails_before_path_resolution_reads() {+ let err = match find_entry_by_path(+ &[],+ &entry(Some(42), Some("w-42"), Some("Documents"), None),+ false,+ std::time::Instant::now(),+ ) {+ Ok(_) => panic!("expected timeout"),+ Err(err) => err,+ };++ assert_eq!(err.code, ErrorCode::Timeout);+}++#[test]+fn ambiguous_candidate_classification_reports_structured_details() {+ let err = match classify_candidates(+ vec![+ AXElement(std::ptr::null_mut()),+ AXElement(std::ptr::null_mut()),+ ],+ &entry(None, Some("w-42"), Some("Documents"), None),+ true,+ ) {+ Ok(_) => panic!("expected ambiguous target"),+ Err(err) => err,+ };++ assert_eq!(err.code, ErrorCode::AmbiguousTarget);+ assert!(!err.message.contains("Investors"));+ assert!(err.message.contains("name_chars=9"));+ let details = err.details.unwrap();+ assert_eq!(details["candidate_count"], 2);+ assert_eq!(details["role"], "cell");+ assert_eq!(details["source_window_id"], "w-42");+}++#[test]+fn multiple_identity_candidates_without_bounds_match_are_stale_not_ambiguous() {+ let err = match classify_candidates(+ vec![+ AXElement(std::ptr::null_mut()),+ AXElement(std::ptr::null_mut()),+ ],+ &entry(Some(42), Some("w-42"), Some("Documents"), None),+ true,+ ) {+ Ok(_) => panic!("expected stale moved target"),+ Err(err) => err,+ };++ assert_eq!(err.code, ErrorCode::ElementNotFound);+}++#[test]+fn single_meaningful_identity_candidate_resolves_after_bounds_change() {+ let _handle = classify_candidates(+ vec![AXElement(std::ptr::null_mut())],+ &entry(None, Some("w-42"), Some("Documents"), None),+ true,+ )+ .expect("unique identity should resolve within the verified source window");+}++#[test]+fn cross_window_replacement_without_verified_source_window_fails_closed() {+ let err = match classify_candidates(+ vec![AXElement(std::ptr::null_mut())],+ &entry(None, Some("w-42"), Some("Documents"), None),+ false,+ ) {+ Ok(_) => panic!("expected stale candidate to fail closed"),+ Err(err) => err,+ };++ assert_eq!(err.code, ErrorCode::ElementNotFound);+}++#[test]+fn non_window_identity_candidate_without_bounds_fails_closed() {+ let mut menu_entry = entry(None, None, None, None);+ menu_entry.source_surface = SnapshotSurface::Menu;++ let err = match classify_candidates(vec![AXElement(std::ptr::null_mut())], &menu_entry, false) {+ Ok(_) => panic!("expected stale candidate to fail closed"),+ Err(err) => err,+ };++ assert_eq!(err.code, ErrorCode::ElementNotFound);+}++#[test]+fn single_window_fallback_requires_bounds_hash_not_title() {+ assert!(single_window_fallback_allowed(&entry(+ Some(42),+ Some("w-10"),+ None,+ None+ )));+ assert!(!single_window_fallback_allowed(&entry(+ None,+ Some("w-10"),+ Some("Documents"),+ None+ )));+ let mut menu_entry = entry(Some(42), Some("w-10"), Some("Documents"), None);+ menu_entry.source_surface = SnapshotSurface::Menu;+ assert!(!single_window_fallback_allowed(&menu_entry));+}++#[test]+fn sole_window_fallback_requires_missing_title() {+ assert!(sole_source_window_fallback_allowed(&entry(+ Some(42),+ Some("w-10"),+ None,+ None+ )));+ assert!(!sole_source_window_fallback_allowed(&entry(+ Some(42),+ Some("w-10"),+ Some("Documents"),+ None+ )));+}++#[test]+fn unique_fallible_matching_index_fails_closed_on_scan_error() {+ let values = [1, 2, 3];++ assert_eq!(+ unique_fallible_matching_index(&values, |value| Ok::<bool, ()>(*value == 2)),+ Some(1)+ );+ assert_eq!(+ unique_fallible_matching_index(&values, |value| Ok::<bool, ()>(*value > 1)),+ None+ );+ assert_eq!(+ unique_fallible_matching_index(&values, |value| Ok::<bool, ()>(*value == 4)),+ None+ );+ assert_eq!(+ unique_fallible_matching_index(&values, |value| {+ if *value == 3 {+ return Err(());+ }+ Ok(*value == 2)+ }),+ None+ );+}++#[test]+fn bounds_hash_keeps_collecting_to_disambiguate_identity_matches() {+ assert!(!should_stop_collecting(+ 2,+ &entry(Some(42), None, None, None)+ ));+ assert!(should_stop_collecting(2, &entry(None, None, None, None)));+}+fn description_entry() -> RefEntry {let mut entry = entry(None, Some("w-10"), Some("Freeform"), None);entry.role = "button".into();diff --git a/crates/macos/src/tree/surfaces.rs b/crates/macos/src/tree/surfaces.rsindex 718eb85ab..c60f31378 100644--- a/crates/macos/src/tree/surfaces.rs+++ b/crates/macos/src/tree/surfaces.rs@@ -1,7 +1,6 @@use super::AXElement;-use super::element::{- copy_ax_array, copy_bool_attr, copy_element_attr, copy_string_attr, element_for_pid,-};+use super::attributes::{copy_ax_array, copy_bool_attr, copy_element_attr, copy_string_attr};+use super::element::element_for_pid;use agent_desktop_core::node::SurfaceInfo;#[cfg(target_os = "macos")]@@ -62,10 +61,19 @@ mod imp {&& copy_bool_attr(el, "AXVisible").unwrap_or(true)}+ /// Searches for a *displayed* menu under `el`. The menu bar is skipped:+ /// every `AXMenuBarItem` carries a latent `AXMenu` child that exists even+ /// when the dropdown is closed, so descending into the menu bar would make+ /// `is_menu_open` permanently true for any app with a menu bar. Open+ /// menu-bar dropdowns are detected separately by `open_menubar_menu` via+ /// the `AXSelected` gate.fn find_menu_descendant(el: &AXElement, depth: usize) -> Option<AXElement> {if depth > 8 {return None;}+ if copy_string_attr(el, "AXRole").as_deref() == Some("AXMenuBar") {+ return None;+ }if is_menu(el) {return Some(el.clone());}@@ -93,9 +101,11 @@ mod imp {focused_window_element(pid)}+ /// Returns the focused window or its first child whose role or subrole matches `target`.+ ///+ /// The focused window itself may be the target (e.g. Electron sheets).fn first_child_with_role_or_subrole(pid: i32, target: &str) -> Option<AXElement> {let win = focused_window_element(pid)?;- // The focused window itself might be the target surface (e.g. Electron sheets).if copy_string_attr(&win, "AXRole").as_deref() == Some(target)|| copy_string_attr(&win, "AXSubrole").as_deref() == Some(target){@@ -160,6 +170,7 @@ mod imp {open_menubar_menu(pid).is_some() || context_menu_from_app(pid).is_some()}+ /// Lists open UI surfaces for the app. The focused window itself counts when its role/subrole matches (e.g. Electron sheets).pub fn list_surfaces_for_pid(pid: i32) -> Vec<SurfaceInfo> {let mut surfaces = Vec::new();let app = element_for_pid(pid);@@ -230,7 +241,6 @@ mod imp {}if let Some(win) = focused_window_element(pid) {- // The focused window itself might be a surface (e.g. Electron sheets).let win_role = copy_string_attr(&win, "AXRole");let win_subrole = copy_string_attr(&win, "AXSubrole");let win_kind = match win_subrole.as_deref() {diff --git a/docs/phases.md b/docs/phases.mdindex 359fbfc8a..21246f013 100644--- a/docs/phases.md+++ b/docs/phases.md@@ -10,6 +10,7 @@ Most recent shipments against this roadmap:| Version | Date | What shipped ||---------|------------|--------------|+| Unreleased | 2026-06 | Reliability hardening on the Phase 1 contracts: session-scoped latest snapshot pointers, explicit snapshot IDs usable across sessions, actionability checks, JSONL `--trace`, stale-ref diagnostics, and refstore symlink hardening || v0.1.14 | 2026-05 | Phase 1 unified core: typed batch/CLI path, `CommandPolicy`, `PermissionReport`, snapshot-scoped `RefStore`, headless `ActionRequest`, macOS screenshot backend boundary || v0.1.13 | 2026-04-17 | FFI cdylib on 5 platforms (aarch64/x86_64 macOS + Linux, x86_64 Windows MSVC), Sigstore build-provenance attestations, FFI review fixes (#26 — 50 commits) || v0.1.12 | 2026-03–04 | Progressive skeleton traversal + ref-rooted drill-down (#20) |@@ -19,6 +20,7 @@ Most recent shipments against this roadmap:| v0.1.7 | 2025-12 | Electron / web app accessibility-tree compatibility |- Phase 1 completion: incremental across v0.1.0 – v0.1.14 (macOS MVP, 54 commands, unified core engine).+- Current unreleased hardening extends Phase 1 contracts; it does not change the planned Windows/Linux adapter sequence.- Phase 1.5 completion: v0.1.13 (FFI cdylib on 5 platforms).- Phase 2: planned. Public scope is summarized in the Phase 2 section below.- Phase 3+: planned. See each phase section below for the additive platform work and trait defaults that later phases backfill.@@ -36,7 +38,7 @@ Most recent shipments against this roadmap:| 4 | MCP Server Mode | Planned | All || 5 | Production Readiness | Planned | All |-Future platform phases are additive against the Phase 1 contracts: typed command args, `CommandPolicy`, `PermissionReport`, snapshot-scoped refs, `ActionRequest`, and the `PlatformAdapter` boundary. Core can still gain explicitly planned additive trait methods, but Windows/Linux should not fork command semantics or duplicate transport dispatch.+Future platform phases are additive against the Phase 1 contracts: typed command args, `CommandPolicy`, `PermissionReport`, snapshot-scoped refs, session-scoped latest snapshot pointers, `ActionRequest`, JSONL reliability tracing, and the `PlatformAdapter` boundary. Core can still gain explicitly planned additive trait methods, but Windows/Linux should not fork command semantics or duplicate transport dispatch.---@@ -44,15 +46,17 @@ Future platform phases are additive against the Phase 1 contracts: typed commandEvery command in agent-desktop has one shared semantic path. CLI and batch both parse into the same typed `Commands` enum, run the same `CommandPolicy` preflight, and enter the same `dispatch()` match. Platform crates implement primitives through `PlatformAdapter`; they do not own command semantics.+Current shipped code uses explicit match arms, not a runtime command registry. Later sections that discuss descriptor/codegen work are planned future transport-generation work; they do not describe the current CLI/batch dispatch path.+### Current Layering| Layer | Scope | Invariant ||-------|-------|-----------|| `crates/core/src/commands/<name>.rs` | Platform-agnostic command behavior and args passed to `&dyn PlatformAdapter` | One command implementation |-| `src/cli.rs` / `src/cli_args*.rs` | Clap command enum and transport args | CLI shape only, no platform behavior |-| `src/command_policy.rs` | Permissions, ref usage, side-effect classification | One policy source of truth for CLI, batch, and tests |-| `src/batch.rs` | JSON batch parser and executor | Deserializes into `Commands`; no separate command interpretation |-| `src/dispatch.rs` | Direct command match | Shared CLI/batch execution path |+| `src/cli/` / `src/cli_args/` | Clap command enum and transport args | CLI shape only, no platform behavior |+| `src/command_policy/` | Permissions, ref usage, side-effect classification | One policy source of truth for CLI, batch, and tests |+| `src/batch/` | JSON batch parser and executor | Deserializes into `Commands`; no separate command interpretation |+| `src/dispatch/` | Direct command match plus parse helpers | Shared CLI/batch execution path || `crates/{macos,windows,linux}/` | Adapter method implementations | Same trait signatures across platforms || `crates/ffi/` | C ABI wrappers around adapter/core types | ABI marshaling only |@@ -60,12 +64,12 @@ Every command in agent-desktop has one shared semantic path. CLI and batch both1. Add `crates/core/src/commands/{name}.rs`.2. Register it in `crates/core/src/commands/mod.rs`.-3. Add the CLI args/variant in `src/cli_args*.rs` and `src/cli.rs`.-4. Add a single arm in `src/dispatch.rs`.+3. Add the CLI args/variant in `src/cli_args/` and `src/cli/mod.rs`.+4. Add a single arm in `src/dispatch/mod.rs`.5. Add a `CommandPolicy` arm.6. If needed, add one `PlatformAdapter` method with a `not_supported()` default, then implement it per adapter.-Batch receives the command automatically once `src/batch.rs::parse_command` maps the JSON command name to that same CLI enum variant. There is no separate batch-only behavior.+Batch receives the command automatically once `src/batch/mod.rs` maps the JSON command name to that same CLI enum variant. There is no separate batch-only behavior.### Headless Contract@@ -73,7 +77,7 @@ Ref actions use `ActionRequest { action, policy }`. The default `InteractionPoli- Semantic AX steps run first.- Physical fallbacks are explicit and policy-gated.-- Non-mouse ref commands must not silently focus apps or move the cursor.+- Raw cursor commands (`hover`, `drag`, `mouse-*`) require `--headed`; other commands must not silently focus apps or move the cursor.- Expected OS denials return specific error codes such as `PERM_DENIED`, `SNAPSHOT_NOT_FOUND`, or `POLICY_DENIED`, not generic `INTERNAL`.Windows and Linux should implement the same signatures rather than copying macOS-specific fallback decisions.@@ -94,9 +98,9 @@ Phase 1 is the load-bearing phase. It establishes the shared command path, trait| P1-O2 | Platform adapter trait | Trait compiles with mock adapter; macOS adapter satisfies all trait methods || P1-O3 | Ref-based interaction | `click @e3` successfully invokes AXPress on the resolved element || P1-O4 | Context efficiency | Typical Finder snapshot < 500 tokens (measured via tiktoken) |-| P1-O5 | Typed JSON contract | Output envelope carries `version: "1.0"`. **Partial**: dedicated `schemas/` JSON-Schema files were never delivered — deferred to Phase 5 quality gates. |+| P1-O5 | Typed JSON contract | Output envelope carries `version: "2.0"`. **Partial**: dedicated standalone JSON-Schema files were never delivered — deferred to later quality gates. || P1-O6 | Permission detection | Permission report covers Accessibility, Screen Recording, and Automation with recovery suggestions |-| P1-O7 | Command extensibility | Adding a new command is ~4 registration points: `commands/{name}.rs` + `commands/mod.rs` + `src/cli.rs` variant + `src/dispatch.rs` match arm |+| P1-O7 | Command extensibility | Adding a new command follows the current shared path: `commands/{name}.rs` + `commands/mod.rs` + `src/cli_args/` + `src/cli/mod.rs` + `src/dispatch/mod.rs` + `src/command_policy/mod.rs` || P1-O8 | 54 working commands | All commands pass integration tests || P1-O9 | CI pipeline | GitHub Actions macOS runner executes full test suite on every PR || P1-O10 | Progressive skeleton traversal | Skeleton + drill-down workflow achieves 78%+ token savings on Electron apps |@@ -115,13 +119,17 @@ agent-desktop/│ │ ├── lib.rs # public re-exports only│ │ ├── node.rs # AccessibilityNode, Rect, WindowInfo│ │ ├── adapter.rs # PlatformAdapter trait-│ │ ├── action.rs # Action enum, ActionRequest, ActionResult+│ │ ├── action.rs # Action enum+│ │ ├── action_request.rs / action_result.rs / action_step*.rs+│ │ ├── actionability/ # Live actionability checks and reports│ │ ├── refs.rs # RefMap and RefEntry-│ │ ├── refs_store.rs # Snapshot-scoped ref persistence+│ │ ├── refs_store.rs # Snapshot/session-scoped ref persistence+│ │ ├── refs_lock.rs # RefStore write lock│ │ ├── ref_alloc.rs # INTERACTIVE_ROLES, allocate_refs, is_collapsible, transform_tree│ │ ├── snapshot_ref.rs # Ref-rooted drill-down (run_from_ref)│ │ ├── snapshot.rs # SnapshotEngine (filter, allocate, serialize)-│ │ ├── error.rs # ErrorCode enum (12 variants), AdapterError, AppError+│ │ ├── trace.rs # JSONL reliability trace support+│ │ ├── error.rs # ErrorCode enum, AdapterError, AppError│ │ ├── notification.rs # NotificationInfo, NotificationFilter, NotificationIdentity│ │ └── commands/ # one file per command (direct match, no Command trait)│ ├── macos/ # agent-desktop-macos (Phase 1, shipped)@@ -130,14 +138,12 @@ agent-desktop/│ └── ffi/ # agent-desktop-ffi (cdylib, shipped v0.1.13; see Phase 1.5)├── src/ # agent-desktop binary (entry point)│ ├── main.rs-│ ├── cli.rs-│ ├── cli_args.rs-│ ├── cli_args_actions.rs-│ ├── cli_args_system.rs-│ ├── command_policy.rs-│ ├── batch.rs-│ ├── dispatch.rs-│ └── dispatch_parse.rs+│ ├── batch/ # JSON batch -> typed Commands+│ ├── cli/ # Clap enum, help text, contract tests+│ ├── cli_args/ # Command argument structs by domain+│ ├── command_policy/ # Permission/ref/side-effect policy+│ ├── dispatch/ # Command dispatcher and parse helpers+│ └── tests/ # Binary-level conformance tests└── tests/├── fixtures/└── integration/@@ -145,31 +151,36 @@ agent-desktop/### PlatformAdapter Trait-The single most important abstraction. Every platform-specific operation goes through this trait. Core never imports platform crates. The trait currently exposes ~27 methods with default implementations returning `not_supported()` — see `crates/core/src/adapter.rs` for the canonical definition. Key method shapes:+The single most important abstraction. Every platform-specific operation goes through this trait. Core never imports platform crates. The canonical definition is `crates/core/src/adapter.rs`; this roadmap lists representative method groups only, because the trait grows additively as reliability and platform parity work lands.```rustpub trait PlatformAdapter: Send + Sync {// Core observationfn list_windows(&self, filter: &WindowFilter) -> Result<Vec<WindowInfo>, AdapterError>;fn list_apps(&self) -> Result<Vec<AppInfo>, AdapterError>;+ fn focused_window(&self) -> Result<Option<WindowInfo>, AdapterError>;fn get_tree(&self, win: &WindowInfo, opts: &TreeOptions) -> Result<AccessibilityNode, AdapterError>;fn get_subtree(&self, handle: &NativeHandle, opts: &TreeOptions) -> Result<AccessibilityNode, AdapterError>;fn list_surfaces(&self, pid: i32) -> Result<Vec<SurfaceInfo>, AdapterError>;// Interactionfn execute_action(&self, handle: &NativeHandle, request: ActionRequest) -> Result<ActionResult, AdapterError>;- fn resolve_element(&self, entry: &RefEntry) -> Result<NativeHandle, AdapterError>;+ fn resolve_element_strict(&self, entry: &RefEntry) -> Result<NativeHandle, AdapterError>;+ fn resolve_element_strict_with_timeout(&self, entry: &RefEntry, timeout: Duration) -> Result<NativeHandle, AdapterError>;fn release_handle(&self, handle: &NativeHandle) -> Result<(), AdapterError>;fn mouse_event(&self, event: MouseEvent) -> Result<(), AdapterError>;fn drag(&self, params: DragParams) -> Result<(), AdapterError>;- fn press_key_for_app(&self, pid: i32, combo: KeyCombo) -> Result<(), AdapterError>;+ fn key_event(&self, combo: &KeyCombo, down: bool) -> Result<(), AdapterError>;+ fn press_key_for_app(&self, app_name: &str, combo: &KeyCombo) -> Result<ActionResult, AdapterError>;// Lifecycle + windowingfn permission_report(&self) -> PermissionReport;fn request_permissions(&self) -> PermissionReport;fn focus_window(&self, win: &WindowInfo) -> Result<(), AdapterError>;+ fn focus_app(&self, pid: i32) -> Result<(), AdapterError>;fn launch_app(&self, id: &str, timeout_ms: u64) -> Result<WindowInfo, AdapterError>;fn close_app(&self, id: &str, force: bool) -> Result<(), AdapterError>;+ fn is_protected_process(&self, identifier: &str) -> bool;fn window_op(&self, win: &WindowInfo, op: WindowOp) -> Result<(), AdapterError>;// Capture + clipboard@@ -184,21 +195,24 @@ pub trait PlatformAdapter: Send + Sync {fn dismiss_all_notifications(&self, app_filter: Option<&str>) -> Result<(Vec<NotificationInfo>, Vec<String>), AdapterError>;fn notification_action(&self, index: usize, identity: Option<&NotificationIdentity>, action_name: &str) -> Result<ActionResult, AdapterError>;- // Property probes+ // Live evidence and wait probesfn get_live_value(&self, handle: &NativeHandle) -> Result<Option<String>, AdapterError>;+ fn get_live_state(&self, handle: &NativeHandle) -> Result<Option<ElementState>, AdapterError>;+ fn get_live_actions(&self, handle: &NativeHandle) -> Result<Option<Vec<String>>, AdapterError>;+ fn get_live_element(&self, handle: &NativeHandle) -> Result<LiveElement, AdapterError>;fn get_element_bounds(&self, handle: &NativeHandle) -> Result<Option<Rect>, AdapterError>;- fn wait_for_menu(&self, pid: i32, open: bool, timeout_ms: u64) -> Result<bool, AdapterError>;+ fn wait_for_menu(&self, pid: i32, open: bool, timeout_ms: u64) -> Result<(), AdapterError>;}```### Key Supporting Types-- `Action` — `#[non_exhaustive]` enum. Current variants: Click, DoubleClick, TripleClick, RightClick, SetValue(String), SetFocus, Expand, Collapse, Select(String), Toggle, Check, Uncheck, Scroll(Direction, Amount), ScrollTo, PressKey(KeyCombo), KeyDown(KeyCombo), KeyUp(KeyCombo), TypeText(String), Clear, Hover, Drag(DragParams)+- `Action` — closed core enum whose platform dispatch arms must stay exhaustive. Current variants: Click, DoubleClick, TripleClick, RightClick, SetValue(String), SetFocus, Expand, Collapse, Select(String), Toggle, Check, Uncheck, Scroll(Direction, Amount), ScrollTo, PressKey(KeyCombo), KeyDown(KeyCombo), KeyUp(KeyCombo), TypeText(String), Clear, Hover, Drag(DragParams)- `ActionRequest` — `{ action, policy }`; default policy forbids focus stealing and cursor movement- `PermissionReport` — `{ accessibility, screen_recording, automation }`, each `{ "state": "granted" }`, `{ "state": "denied", "suggestion": "..." }`, `{ "state": "not_required" }`, or `{ "state": "unknown" }`- `MouseEvent`, `DragParams`, `KeyCombo` — dedicated types (not unified under an `InputEvent` enum)- `WindowOp` — Resize{w,h}, Move{x,y}, Minimize, Maximize, Restore, Close-- `ScreenshotTarget` — FullScreen, Window(WindowInfo), Element(NativeHandle)+- `ScreenshotTarget` — Screen(usize), Window(pid), FullScreen- `NotificationInfo` — index, app_name, title, body, actions: Vec<String>- `NotificationIdentity` — expected_app, expected_title (used for NC-reorder-safe `notification_action`)- `SurfaceInfo` — kind, label, bounds (for `list-surfaces` command)@@ -214,22 +228,27 @@ crates/macos/src/├── adapter.rs # MacOSAdapter: PlatformAdapter impl├── tree/│ ├── mod.rs # re-exports-│ ├── element.rs # AXElement struct + attribute readers+│ ├── ax_element.rs # AXElement ownership wrapper+│ ├── attributes.rs # Batched AX attribute reads│ ├── capabilities.rs # AX-supported actions and settable attributes│ ├── builder.rs # build_subtree, tree traversal-│ ├── roles.rs # AXRole string → unified role enum mapping-│ ├── resolve.rs # Element re-identification for ref resolution+│ ├── node_attrs.rs # Node metadata extraction+│ ├── roles.rs # AXRole string -> unified role enum mapping+│ ├── resolve*.rs # Element re-identification for ref resolution│ └── surfaces.rs # Surface detection (menu, sheet, alert, popover)├── actions/│ ├── mod.rs # re-exports│ ├── dispatch.rs # perform_action match arms-│ ├── chain.rs # policy-aware AX-first activation chain+│ ├── chain*.rs # policy-aware AX-first activation chain+│ ├── discovery.rs # Live capability discovery│ ├── extras.rs # select_value helpers+│ ├── post_state.rs # Post-action state reads│ ├── scroll.rs # scroll semantics and explicit physical policy paths-│ └── type_text.rs # headless AX text insertion and physical typing+│ └── type_text.rs # focus-fallback text insertion and physical typing├── input/│ ├── mod.rs # re-exports│ ├── keyboard.rs # CGEventCreateKeyboardEvent, key synthesis, text typing+│ ├── keyboard_map.rs # Key name mapping│ ├── mouse.rs # CGEventCreateMouseEvent, mouse events│ └── clipboard.rs # NSPasteboard.generalPasteboard read/write├── notifications/@@ -239,7 +258,9 @@ crates/macos/src/│ └── actions.rs # Click notification action buttons (identity-verified)└── system/├── mod.rs # re-exports- ├── app_ops.rs # launch, close, focus via NSWorkspace / AppleScript+ ├── app_ops.rs # launch, close, focus via NSWorkspace+ ├── app_list.rs # Running app inventory+ ├── window_list.rs # Window inventory├── window_ops.rs # window resize, move, minimize, maximize, restore├── key_dispatch.rs # app-targeted key press├── permissions.rs # PermissionReport probe/request@@ -260,7 +281,7 @@ crates/macos/src/- Ref actions take `ActionRequest`, not bare `Action`- Default policy forbids focus stealing and cursor movement- Click/right-click/scroll chains run semantic AX steps first and return structured errors instead of silently using physical/headed paths-- Type in headless mode mutates settable AX text values; physical keyboard typing is policy-gated+- Type uses the focus-fallback policy floor; SetValue/Clear are the pure headless AX value-mutation paths- SetValue/Clear: `AXUIElementSetAttributeValue(kAXValueAttribute, value)`- SetFocus/Press/Hover/Drag/Mouse: explicit focus/cursor/physical commands- Keyboard/Mouse: `CGEventCreateKeyboardEvent` / `CGEventCreateMouseEvent` via CoreGraphics@@ -284,9 +305,8 @@ crates/macos/src/**System tray / Menu bar extras:**- Menu bar extras (status items) live under the `SystemUIServer` process AX tree-- List items: traverse `AXMenuBarItem` children of the system menu bar-- Click: `AXPress` on the target menu bar extra element-- Expand menus: after clicking a tray item, traverse the resulting `AXMenu` as a surface+- Current support is through surface discovery/snapshotting (`menubar` / `menu`) where the AX tree exposes those items+- Dedicated `list-tray-items`, `click-tray-item`, and `open-tray-menu` commands are not shipped- Control Center items: accessible via the `ControlCenter` process (bundleId: `com.apple.controlcenter`)**AXElement safety:**@@ -304,7 +324,7 @@ Platform-agnostic, lives in `agent-desktop-core`:4. Serialize: Omit null fields. Omit empty arrays. Omit bounds in compact mode5. Estimate tokens: Optionally warn if exceeding threshold-Snapshot refs persist through `RefStore` under `~/.agent-desktop/snapshots/{snapshot_id}/refmap.json`, with a `latest_snapshot_id` pointer for commands that omit `--snapshot`. `~/.agent-desktop/last_refmap.json` remains only as a latest-snapshot inspection artifact. Action commands resolve through `RefStore` and use `ResolvedElement` RAII so native handles are released after ref-consuming commands. Return `STALE_REF` on live re-identification mismatch and `SNAPSHOT_NOT_FOUND` when the requested snapshot does not exist.+Snapshot refs persist through `RefStore`. The default namespace stores snapshots under `~/.agent-desktop/snapshots/{snapshot_id}/refmap.json`; `--session <id>` stores the same shape under `~/.agent-desktop/sessions/{id}/snapshots/{snapshot_id}/refmap.json`. Each namespace owns one `latest_snapshot_id` pointer for commands that omit `--snapshot`. Explicit `--snapshot <id>` is a direct snapshot handle and can be used without repeating `--session`; if the same snapshot ID appears in multiple sessions, callers pass the matching session to disambiguate. `~/.agent-desktop/last_refmap.json` remains only as a latest-snapshot inspection artifact. Action commands resolve through `RefStore` and use `ResolvedElement` RAII so native handles are released after ref-consuming commands. Return `STALE_REF` on live re-identification mismatch and `SNAPSHOT_NOT_FOUND` when the requested snapshot does not exist.**Progressive Skeleton Traversal:**- `--skeleton` flag clamps depth to `min(max_depth, 3)`, annotates truncated containers with `children_count` for agent discovery@@ -365,7 +385,7 @@ The `wait` command has been extended with notification and menu support:### JSON Output Contract-All commands produce a response envelope. Schema files versioned in `schemas/`.+All commands produce a response envelope with `version: "2.0"`. Standalone schema files are still deferred; the current contract is enforced by Rust serde types, CLI conformance tests, and documented examples.Success:```json@@ -410,13 +430,14 @@ The `ErrorCode` enum in `crates/core/src/error.rs` exposes these machine-readabl| `ACTION_FAILED` | Execution | AXPress returned error on disabled button | Element may be disabled. Check states before acting || `ACTION_NOT_SUPPORTED` | Execution | Expand on a button | This element does not support the requested action || `STALE_REF` | Ref | Element could not be re-identified from the requested snapshot | Run 'snapshot' (or `snapshot --skeleton`) to refresh |+| `AMBIGUOUS_TARGET` | Ref | Ref identity maps to more than one live candidate | Run 'snapshot' to refresh, then retry with a more specific ref || `WINDOW_NOT_FOUND` | Window | --window w-999 does not exist | Run 'list-windows' to see available windows || `PLATFORM_NOT_SUPPORTED` | Platform | Windows/Linux adapter not yet shipped | This platform ships in Phase 2/3 || `TIMEOUT` | Wait / Traversal | wait --element exceeded timeout | Increase --timeout or check app state || `INVALID_ARGS` | Input | Bad CLI argument or unknown ref format | Fix the argument per CLI help || `NOTIFICATION_NOT_FOUND` | Notification | Notification ID not found / NC reordered | Run 'list-notifications' to see current notifications || `SNAPSHOT_NOT_FOUND` | Ref | Requested snapshot ID is missing | Run 'snapshot' again and use the returned snapshot_id |-| `POLICY_DENIED` | Action policy | Physical fallback blocked by headless policy | Use an explicit focus/cursor/mouse command if physical interaction is intended |+| `POLICY_DENIED` | Action policy | Physical input blocked by headless policy | Retry with `--headed` for explicit cursor movement, or use a semantic AX action when available || `INTERNAL` | Internal | Unexpected error or caught panic | Re-run with verbose logging |Exit codes: `0` success, `1` structured error (JSON on stdout), `2` argument/parse error.@@ -430,7 +451,7 @@ Exit codes: `0` success, `1` structured error (JSON on stdout), `2` argument/par- Ref allocator only assigns interactive roles- SnapshotEngine filtering- Error serialization-- JSON schema validation+- JSON contract / output conformance coverage- MockAdapter: in-memory PlatformAdapter returning hardcoded trees**Unit tests (macos):**@@ -449,8 +470,7 @@ Exit codes: `0` success, `1` structured error (JSON on stdout), `2` argument/par- Large tree (Xcode) snapshot in under 2 seconds- List notifications — returns non-empty list when Notification Center has entries- Dismiss notification — verify notification removed from Notification Center AX tree-- List tray items — returns known menu bar extras (Wi-Fi, Bluetooth, Clock)-- Click tray item — verify menu bar extra menu opens+- Menu/menu-bar surface snapshot and wait behavior where the host exposes AX menu surfaces**Golden fixtures (`tests/fixtures/`):**- Real snapshots from Finder, TextEdit, etc. checked into repo@@ -473,16 +493,18 @@ Current `.github/workflows/ci.yml` on every PR:| Crate | Version | Purpose ||-------|---------|---------|-| `clap` | 4.x | CLI parsing with derive macros |+| `clap` | 4.6 | CLI parsing with derive macros || `serde` + `serde_json` | 1.x | JSON serialization |-| `thiserror` | 2.x | Error derive macros |+| `thiserror` | 2.0 | Error derive macros || `tracing` | 0.1+ | Structured logging || `tracing-subscriber` | 0.3 | env-filter log formatter || `rustc-hash` | 2.1 | Faster hashing for ref maps and visited sets |+| `smallvec` | 1.13 | Small fixed-size vectors in hot paths || `base64` | 0.22+ | Screenshot encoding |-| `accessibility-sys` | 0.1+ | macOS AXUIElement FFI |-| `core-foundation` | 0.10+ | macOS CF types |-| `core-graphics` | 0.24+ | macOS CG types |+| `accessibility-sys` | 0.2.0 | macOS AXUIElement FFI |+| `core-foundation` | 0.10.1 | macOS CF types |+| `core-foundation-sys` | 0.8.7 | macOS CF FFI |+| `core-graphics` | 0.25.0 | macOS CG types |### Documentation Delivered@@ -599,7 +621,7 @@ These items are tracked under P2-O16 below: registry migration via `build.rs` fi### Core invariants (research-driven — from Phase 2 plan §Headless-First Invariant)-1. **Headless-first inside the active desktop session.** Every command — existing and Phase 2 — must run without an agent-desktop GUI, foreground activation, focus steal, or physical cursor movement (except for explicit mouse commands). Windows, macOS, and Linux still require the target app to exist in the current user's interactive desktop/display session for accessibility and capture APIs. Session 0, Server Core, secure desktops, locked desktops, and other-user sessions return `PLATFORM_NOT_SUPPORTED`, `PERM_DENIED`, or `WINDOW_NOT_FOUND` with `platform_detail`, not silent best effort. The invariant is enforced by integration tests: target window is NOT focused at test entry; `list-windows --focused-only` returns the same window before/after; cursor position unchanged for non-mouse commands.+1. **Headless-first inside the active desktop session.** Every command — existing and Phase 2 — must run without an agent-desktop GUI, foreground activation, focus steal, or physical cursor movement unless `--headed` explicitly opts into cursor input. Windows, macOS, and Linux still require the target app to exist in the current user's interactive desktop/display session for accessibility and capture APIs. Session 0, Server Core, secure desktops, locked desktops, and other-user sessions return `PLATFORM_NOT_SUPPORTED`, `PERM_DENIED`, or `WINDOW_NOT_FOUND` with `platform_detail`, not silent best effort. The invariant is enforced by integration tests: target window is NOT focused at test entry; `list-windows --focused-only` returns the same window before/after; cursor position unchanged for headless commands.2. **Skeleton traversal is platform-agnostic.** The novel progressive skeleton pattern (depth-3 clamp + `children_count` annotation + drill-down via `--root @ref` + scoped invalidation via `RefMap::remove_by_root_ref`) lives entirely in `crates/core/src/snapshot_ref.rs`. Windows adapter contributes ~50 LOC glue: `ControlViewWalker` (NOT `RawViewWalker` or `ContentViewWalker`) + `FindAll(TreeScope_Children, TrueCondition)` for `children_count` + fresh `UICacheRequest` per drill-down.3. **Asymmetric event threading.** `watch_element` uses main-thread `AXObserver` on macOS (research-confirmed: Apple DTS says all AX is main-thread-only; AXSwift / Hammerspoon / Phoenix all do this); worker-thread MTA `IUIAutomation` event handler on Windows (Microsoft 2025 threading doc: UIA supports cross-thread event delivery).4. **No `inventory` / `linkme` command registry.** Research confirmed neither survives link-GC reliably across ld64, ld-prime, GNU ld, lld, MSVC for cdylib consumers. Phase 2 uses `build.rs` filesystem enumeration of `crates/core/src/commands/*.rs` — deterministic, cdylib-safe, zero linker magic. The repository's "one command per file" rule becomes the codegen contract.@@ -626,7 +648,7 @@ These items are tracked under P2-O16 below: registry migration via `build.rs` fiPhase 2 brings agent-desktop to Windows. It is also the phase that closes the cross-platform feature-parity gaps surfaced after the v0.1.13 FFI ship — shipping Windows meaningfully requires new core abstractions (stable identifiers, event subscriptions, text-range primitives, shell surfaces, and Windows-specific tray/taskbar affordances) that Windows UIA exposes natively and the macOS adapter currently does not surface. Every new trait method added here is implemented on both platforms in the same PR pair when there is a real cross-platform analogue. True Windows shell concepts return `PLATFORM_NOT_SUPPORTED` on other adapters through the same core command path, never through side-channel code. Linux (Phase 3) mirrors the portable parts against AT-SPI2.-Core engine, CLI parser, JSON contract invariants, and command-registration pattern are preserved. What Phase 2 legitimately changes: `AccessibilityNode` field set, `Action` enum variants, `ErrorCode` variants, `PlatformAdapter` trait size. Every change is additive (`#[non_exhaustive]` already guards the enums) and every macOS backfill lands atomically with the Windows implementation so the two platforms never drift.+Core engine, CLI parser, JSON contract invariants, and command-registration pattern are preserved. What Phase 2 legitimately changes: `AccessibilityNode` field set, `Action` enum variants, `ErrorCode` variants, `PlatformAdapter` trait size. Every new `Action` variant must update core actionability, capability maps, platform dispatch, CLI/FFI conversion, and contract tests in the same change; exhaustive compiler checks are the guard against adapter drift. Every macOS backfill lands atomically with the Windows implementation so the two platforms never drift.Per the [Command Surface Architecture](#command-surface-architecture-dry-invariant) invariant, every new command added in Phase 2 (`watch`, `text select-range`, `text get-selection`, `text insert-at-caret`, etc.) lives in **exactly one file** under `crates/core/src/commands/` and is wired through the shared typed command path. If Phase 2 adds codegen, it uses deterministic `build.rs` filesystem enumeration, not linker registries. The per-platform work is the three `PlatformAdapter` method implementations (one each in `crates/macos/`, `crates/windows/`, `crates/linux/`) — nothing repeats across transports.@@ -639,7 +661,7 @@ Core + Windows parity (original scope):| ID | Objective | Metric ||----|-----------|--------|| P2-O1 | Windows adapter | `snapshot` on Windows returns valid tree for Explorer, Notepad, Settings |-| P2-O2 | All existing commands cross-platform | Identical JSON schema output on macOS and Windows for every command |+| P2-O2 | All existing commands cross-platform | Identical JSON contract output on macOS and Windows for every command || P2-O3 | Windows input synthesis | `click`, `type`, `press`, all mouse commands working via UIA + SendInput || P2-O4 | Windows screenshot | `screenshot` produces PNG via `Windows.Graphics.Capture` API || P2-O5 | Windows clipboard | `clipboard-get` / `clipboard-set` / `clipboard-clear` working via Win32 Clipboard API |@@ -651,7 +673,7 @@ Cross-platform core extensions (new, landed alongside Windows):| ID | Objective | Metric ||----|-----------|--------|| P2-O8 | `AccessibilityNode` stable-selector fields | Nodes may carry `identifier`, `subrole`, `role_description`, `placeholder`, `dom_id`, `dom_classes` (all `Option<String>` / `Vec<String>` with `skip_serializing_if`). Populated where the platform/app exposes stable selectors: Windows UIA `AutomationId` / `LocalizedControlType` / `HelpText`; macOS `kAXIdentifierAttribute` / `kAXSubroleAttribute` / `kAXRoleDescriptionAttribute` / `kAXPlaceholderValueAttribute` / `kAXDOMIdentifierAttribute` / `kAXDOMClassListAttribute`. Resolver prefers stable selectors when present and falls back to the existing fingerprint; tests require known controls with explicit IDs to preserve them across re-drills, not every real-app node |-| P2-O9 | `Action` enum expansion for 2026 agent workloads | New variants: `LongPress { duration_ms }`, `ForceClick`, `ShowMenu`, `DeliverFiles(Vec<PathBuf>)` (renamed from `FileDrop` — the original name implied `NSDraggingSession` which is not headless-compatible on macOS; see Phase 2 plan §Headless-First Invariant and Unit 12), `WindowRaise`, `Cancel`, `SelectRange { start, len }`, `InsertAtCaret(String)`. `watch_element` is an adapter method, **not** an `Action` variant (plan §KD8 + origin brainstorm §D8). Each has a macOS AX API mapping (all AX calls on main thread per plan §KD9), a Windows UIA pattern mapping, and a new CLI subcommand. The `#[non_exhaustive]` attribute keeps this SemVer-safe; C-ABI consumers use `default:` / wildcard fallthrough plus the exported `AD_RESULT_UNKNOWN = -99` sentinel (plan §KD17) |+| P2-O9 | `Action` enum expansion for 2026 agent workloads | New variants: `LongPress { duration_ms }`, `ForceClick`, `ShowMenu`, `DeliverFiles(Vec<PathBuf>)` (renamed from `FileDrop` — the original name implied `NSDraggingSession` which is not headless-compatible on macOS; see Phase 2 plan §Headless-First Invariant and Unit 12), `WindowRaise`, `Cancel`, `SelectRange { start, len }`, `InsertAtCaret(String)`. `watch_element` is an adapter method, **not** an `Action` variant (plan §KD8 + origin brainstorm §D8). Each has a macOS AX API mapping (all AX calls on main thread per plan §KD9), a Windows UIA pattern mapping, a new CLI subcommand, FFI conversion coverage where applicable, and exhaustive platform-dispatch tests in the same change. || P2-O10 | `ErrorCode` expansion | Add `PermissionRevoked` (distinct from `PermDenied` — TCC yanked mid-session), `ResourceExhausted` (refmap >1 MB, tree node-count cap), `AxMessagingTimeout` (AX-specific timeout separate from orchestration `Timeout`), `AutomationPermissionDenied` (macOS `osascript` grant). Tri-state permission probe at startup distinguishes "never granted" from "revoked" || P2-O11 | Event-subscription primitive (push, not poll) | New trait method `watch_element(handle, events: &[EventKind], timeout_ms: u64) -> Result<Vec<ElementEvent>>`. macOS: `AXObserverCreate` + `AXObserverAddNotification` + `CFRunLoopSource` (no more polling in `system/wait.rs`). Windows: `IUIAutomation.AddAutomationEventHandler` + `AddFocusChangedEventHandler` + `AddPropertyChangedEventHandler`. New `wait --event value-changed --ref @e5 --timeout 3000` CLI flag. Linux mirrors in Phase 3 via AT-SPI2 D-Bus signals || P2-O12 | Text range primitives | Read caret, read selection, select a range by offsets, read text at range, insert at caret. macOS: `kAXSelectedTextRangeAttribute` (settable), `AXStringForRangeParameterizedAttribute`, `AXBoundsForRangeParameterizedAttribute`, `AXRangeForLineParameterizedAttribute`, `AXValueCreate(kAXValueCFRangeType, …)`. Windows: `TextPattern.GetSelection`, `TextPattern.DocumentRange`, `TextRange.Select`, `TextRange.Move`, `TextRange.GetText`, `TextRange.GetBoundingRectangles`. Commands: `text get-selection`, `text select-range <ref> <start> <len>`, `text insert-at-caret <ref> <string>`, `text at-offset <ref> <start> <len>` |@@ -1014,7 +1036,7 @@ Linux parity (original scope):| ID | Objective | Metric ||----|-----------|--------|| P3-O1 | Linux adapter | `snapshot` on Ubuntu GNOME returns valid tree for Files, Terminal, Settings |-| P3-O2 | All commands cross-platform | Identical JSON schema output on all 3 platforms for every command |+| P3-O2 | All commands cross-platform | Identical JSON contract output on all 3 platforms for every command || P3-O3 | Linux input synthesis | `click`, `type`, `press`, all mouse commands via AT-SPI actions + xdotool/ydotool || P3-O4 | Linux screenshot | `screenshot` produces PNG via PipeWire ScreenCast portal (Wayland) / XGetImage (X11) || P3-O5 | Linux clipboard | `clipboard-get` / `clipboard-set` / `clipboard-clear` via `wl-clipboard` (Wayland) / `xclip` (X11) |@@ -1312,7 +1334,7 @@ By Phase 4 the CLI already covers the shared command surface on three platforms,| ID | Objective | Metric ||----|-----------|--------|| P4-O1 | MCP server mode via `--mcp` | Responds to MCP `initialize` handshake, reports capabilities, per-host hello-world passes |-| P4-O2 | All commands as MCP tools | `tools/list` returns 53+ tools with JSON Schemas generated from the CLI arg structs via `schemars`; tool names prefixed `desktop_` |+| P4-O2 | All commands as MCP tools | `tools/list` returns 54+ tools with JSON Schemas generated from the CLI arg structs via `schemars`; tool names prefixed `desktop_` || P4-O3 | Claude Desktop + Cursor + VS Code + Gemini CLI + MS Agent Framework validated | Each host invokes tools to control a desktop app end-to-end on all three platforms; repo ships `mcp.json` / `claude_desktop_config.json` / `.cursor/mcp.json` examples per host || P4-O4 | Tool annotations | `readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint` on every tool; Claude Desktop surfaces destructive tools with a confirmation prompt || P4-O5 | Ref-based MCP tool shape (Playwright-MCP idiom) | Tools take `{ref: "e5"}` not raw `element_handle`, matching Playwright MCP so agents can swap between the two without relearning selectors. Tree snapshots return as MCP resources with refs inline |@@ -1470,7 +1492,7 @@ Each host gets a ~30-line config + a 60-second "hello agent" demo (launch Calcul- **Stdio (primary):** MCP host spawns `agent-desktop --mcp` as a child process. JSON-RPC over stdin/stdout. Required; validated against all hosts in the Framework Integration table.- **Streamable HTTP (P4-O12, required for MS Agent Framework):** Single HTTP endpoint at `POST /mcp` with chunked response streaming; replaces the pre-March-2025 SSE transport. Used when the host declares `transport: http` in its MCP config. Binds to `127.0.0.1` by default; `--mcp-bind <addr:port>` CLI flag overrides.- **SSE (legacy):** Retained for hosts that haven't migrated to Streamable HTTP. Gated on `--mcp-transport sse`.-- **Session:** On `initialize`, detect platform, probe permissions (AX + Screen Recording + Automation tri-state), report tool capabilities given current permissions. Each MCP session has its own in-memory RefMap keyed by `session_id` — never reads or writes the on-disk CLI refmap at `~/.agent-desktop/last_refmap.json`. Sessions are isolated so the same host can run multiple agent-desktop-mcp instances concurrently without cross-contamination.+- **Session:** On `initialize`, detect platform, probe permissions (AX + Screen Recording + Automation tri-state), report tool capabilities given current permissions. The current CLI already supports `--session <id>` as an on-disk latest-snapshot namespace. MCP adds per-host in-memory session state keyed by `session_id`; it must not use the legacy `~/.agent-desktop/last_refmap.json` artifact and should bridge to the same explicit snapshot semantics as the CLI.### Initialize Handler@@ -1485,16 +1507,16 @@ On receiving MCP `initialize`:| Crate | Version | Purpose | License ||-------|---------|---------|---------|| `rmcp` | 0.15.0+ | Official MCP Rust SDK — `#[tool]` macro, JSON-RPC handling, transport | MIT/Apache-2.0 |-| `schemars` | 0.8+ | JSON Schema generation for tool parameter definitions | MIT/Apache-2.0 |+| `schemars` | 1.2+ | JSON Schema generation for tool parameter definitions | MIT/Apache-2.0 || `tokio` | 1.x | Async runtime (required by rmcp for MCP server event loop) | MIT |Note: If `tokio` was already introduced in Phase 3 (Linux), it is already available. Otherwise, it is introduced here.### Binary Crate Changes-- `src/main.rs` — Add `--mcp` flag detection, route to MCP server mode+- `src/main.rs` / `src/cli/` — Add `--mcp` flag detection, route to MCP server mode- `Cargo.toml` — Add `agent-desktop-mcp` dependency (non-platform-gated, available on all platforms)-- No changes to `dispatch.rs`, `cli.rs`, or any command files — MCP tools call the same `execute()` functions+- No changes to `src/dispatch/` or command files — MCP tools call the same `execute()` functions### Testing@@ -1594,20 +1616,20 @@ Skill maintenance rules:**Status: Planned**-Phase 5 transforms agent-desktop from functional to enterprise-grade. Persistent daemon process, session isolation for concurrent agents, the safety trio required for enterprise and regulated deployments (dry-run + confirm + audit log), an OCR/vision fallback for custom-rendered UIs where the accessibility tree is empty, session tracing with OpenTelemetry-compatible event streams, and first-class distribution via native package managers.+Phase 5 transforms agent-desktop from functional to enterprise-grade. Persistent daemon process, in-memory session multiplexing for concurrent agents, the safety trio required for enterprise and regulated deployments (dry-run + confirm + audit log), an OCR/vision fallback for custom-rendered UIs where the accessibility tree is empty, OpenTelemetry-compatible trace export on top of the current JSONL reliability trace, and first-class distribution via native package managers.### Objectives| ID | Objective | Metric ||----|-----------|--------|| P5-O1 | Persistent daemon | Warm snapshot completes in <50ms (vs 200ms+ cold start) |-| P5-O2 | Session isolation | Two agents hold independent RefMaps without interference |+| P5-O2 | Daemon session multiplexing | Two agents hold independent in-memory RefMaps without interference; CLI `--session` remains the on-disk latest-snapshot namespace for non-daemon use || P5-O3 | Enterprise quality gates | All gates in quality gates table pass || P5-O4 | Package manager distribution | Available via brew (macOS), winget/scoop (Windows), snap/apt (Linux) with Sigstore attestation verification on install || P5-O5 | Safety trio: `--dry-run` / `--confirm` / append-only audit log | Every destructive command supports `--dry-run` (resolves ref, computes the action, emits the would-be JSON response, does not execute), `--confirm` (stderr prompt with configurable timeout), and `~/.agent-desktop/audit.jsonl` append-only log with trace_id, actor, tool, args, decision (allowed / dry-run / denied / confirmed), exit code, timestamp. Covers EU AI Act Article 14 and OWASP Agentic Top-10 (2026) requirements || P5-O6 | Policy allowlist / denylist | `~/.agent-desktop/policy.yaml` defines per-tool rules — e.g. "never call `desktop_close_app` for `com.apple.finder`", "require confirm for any action on bundle ID `com.apple.mail`". Loaded at daemon start, reload-on-SIGHUP. Policy decisions land in the audit log || P5-O7 | OCR / vision fallback (`find --visual`) | When the AX tree is empty or the target isn't exposed (Canvas apps, Flutter-desktop, games, remote desktop, Figma plugins), `find --visual "label"` falls back to a per-window screenshot + OCR to locate text. macOS: `Vision` framework `VNRecognizeTextRequest`. Windows: `Windows.Media.Ocr.OcrEngine`. Linux: Tesseract via `tesseract` crate. Returns a synthetic ref that routes to coordinate events; clearly marked `source: "visual"` in output to signal reduced reliability |-| P5-O8 | Session trace + OpenTelemetry-compatible event stream | `--trace-id <uuid>` on every CLI invocation; generated if not provided. Each command appends structured events (command start, adapter call, action dispatched, exit) to `~/.agent-desktop/traces/{trace_id}.jsonl`. Events are OpenTelemetry-compliant (`span_id`, `trace_id`, `parent_span_id`, `span_name`, `attributes`). New `agent-desktop trace view <uuid>` pretty-prints; `trace export <uuid>` emits OTLP JSON |+| P5-O8 | OpenTelemetry trace export | Current `--trace <path>` writes redacted JSONL reliability diagnostics. Phase 5 adds trace IDs, span structure, `agent-desktop trace view <uuid>`, and OTLP/HAR export without changing the existing stdout JSON contract || P5-O9 | Screencast / screenshot-per-action receipt | `--record-trace <path.mp4>` on long-running MCP sessions or CLI batches. Uses Phase 2 P2-O13 modern screenshot APIs at 2 Hz by default. Parity with Playwright 1.59 `page.screencast`. Mutually exclusive with `--dry-run` (nothing to record) || P5-O10 | Sigstore attestation verification at install time | `brew install` formula and `winget` manifest run `cosign verify-blob` / `gh attestation verify` against the downloaded tarball before installing. Prevents supply-chain tampering. apt/snap use distro-native signatures; the formula publishes both Sigstore bundle and the checksum |@@ -1626,10 +1648,10 @@ The daemon is a long-running process that maintains state between CLI/MCP invoca- Any new connection resets the idle timer**Session multiplexing:**-- Each CLI invocation or MCP session gets a unique session ID-- Each session has its own RefMap (held in memory by daemon, not on disk)-- Sessions are isolated: agent A's refs never collide with agent B's refs-- Session destroyed on disconnect or explicit `session kill`+- The current CLI `--session <id>` persists snapshots on disk and scopes only the latest-snapshot pointer.+- The daemon upgrades that model to warm, in-memory per-session RefMaps while preserving explicit snapshot IDs as deterministic handles.+- Sessions are isolated: agent A's latest pointer never collides with agent B's latest pointer.+- Session destroyed on disconnect or explicit `session kill`.**Health check:**- `agent-desktop status` returns: daemon PID, uptime, active session count, platform, permission status@@ -1648,7 +1670,7 @@ The daemon is a long-running process that maintains state between CLI/MCP invoca| `find --visual "<label>"` | OCR-based visual fallback when the AX tree has no match for `label` (P5-O7) || Every command gains `--dry-run` | Resolve ref, compute action, emit the would-be response, **do not execute** (P5-O5) || Every destructive command gains `--confirm [--confirm-timeout <ms>]` | Prompt on stderr before executing; defaults off for CLI, on for MCP `destructive` capability |-| Every command gains `--trace-id <uuid>` | Correlate events; auto-generated when not provided (P5-O8) |+| Every command gains `--trace-id <uuid>` | Correlate the existing `--trace` JSONL events and future daemon/MCP spans; auto-generated when not provided (P5-O8) || Every command gains `--record-trace <path.mp4>` | Screencast while the command runs (P5-O9) |### CLI-to-Daemon Migration@@ -1723,16 +1745,16 @@ Matchers: `tool` (glob), `bundle` (exact or glob), `pid`, `trace_mcp_host` (`cli`STALE_REF` semantics stay the same — a visual ref invalidates on the next snapshot. Visual refs never cache in the refmap persisted to disk.-### Session Trace + OpenTelemetry (P5-O8)+### Trace Export + OpenTelemetry (P5-O8)-Every command generates trace events written to `~/.agent-desktop/traces/{trace_id}.jsonl`:+Today, callers opt into a redacted reliability trace with `--trace <path>` and may add `--trace-strict` to fail on setup or pre-action trace write errors. Phase 5 layers trace IDs and span/export tooling on top of that existing JSONL event stream:```json{"ts":"…","trace_id":"9f3c…","span_id":"…","parent_span_id":"…","name":"cli.snapshot","kind":"internal","attributes":{"app":"Finder","skeleton":true,"ref_count":14,"duration_ms":87}}{"ts":"…","trace_id":"9f3c…","span_id":"…","parent_span_id":"<snapshot span>","name":"adapter.macos.get_tree","duration_ms":72,"attributes":{"surface":"window"}}```-Spans are OpenTelemetry-compliant so `agent-desktop trace export <uuid> --otlp` emits a valid OTLP JSON payload ingestable by Grafana Tempo / Jaeger / Honeycomb / Datadog. `--har` exports a HAR-like envelope for quick manual inspection. Screencasts from `--record-trace` attach as trace links.+Phase 5 spans are OpenTelemetry-compliant so `agent-desktop trace export <uuid> --otlp` emits a valid OTLP JSON payload ingestable by Grafana Tempo / Jaeger / Honeycomb / Datadog. `--har` exports a HAR-like envelope for quick manual inspection. Screencasts from `--record-trace` attach as trace links.### Enterprise Quality Gates@@ -1742,7 +1764,7 @@ Spans are OpenTelemetry-compliant so `agent-desktop trace export <uuid> --otlp`| Safety | Every destructive command supports `--dry-run`; every MCP destructive tool requires the `destructive` capability + audit log; the audit log is hash-chained and tamper-detectable; policy engine evaluated on every invocation. || Performance | Cold start <200ms. Warm snapshot <50ms via daemon. Tree traversal timeout 5s default, configurable. `watch --event` latency <500ms (push, not poll) per P2-O11. || Reliability | Zero panics in non-test code. Graceful daemon recovery on crash. Stale socket cleanup on startup. FFI panic boundary in release-ffi profile (already shipping). |-| Observability | Every command writes a trace file. Daemon exports `/metrics` Prometheus endpoint when `--metrics` flag is on. OpenTelemetry OTLP export via `trace export --otlp`. |+| Observability | Current commands can opt into redacted JSONL via `--trace`. Phase 5 adds daemon metrics, trace IDs, and OpenTelemetry OTLP export via `trace export --otlp`. || Compatibility | Tested against target app matrix: Finder, TextEdit, Xcode, VS Code, Chrome, Slack (macOS); Explorer, Notepad, Settings, VS Code, Edge (Windows); Nautilus, Terminal, Firefox, VS Code (Linux). || Distribution | Single binary per platform. No runtime dependencies for the CLI. FFI cdylib tarballs signed via Sigstore (already shipping as of Phase 1.5). Formula / manifest verify Sigstore attestation before installing (P5-O10). || Documentation | README, CLI reference, MCP reference, per-platform setup guides, troubleshooting, audit-log format reference, policy-file reference, OpenTelemetry trace schema. |@@ -1820,8 +1842,8 @@ Each package manager distribution includes:- Visual refs never persist to disk refmap- On Linux without Tesseract installed, `find --visual` returns `PlatformNotSupported` with the install command-**Session trace tests (P5-O8):**-- Every CLI invocation writes at least one span to `~/.agent-desktop/traces/{trace_id}.jsonl`+**Trace export tests (P5-O8):**+- Commands run with `--trace <path>` write at least one redacted JSONL reliability event- `trace export <uuid> --otlp` produces a valid OpenTelemetry JSON payload that passes `otel-cli validate`- A multi-command batch under a single `--trace-id` produces a single-rooted span tree (batch command is the parent)- MCP sessions propagate the `trace_id` from the host's `initialize` params if provided; otherwise generatediff --git a/docs/solutions/best-practices/abort-state-guidance-multi-step-physical-input.md b/docs/solutions/best-practices/abort-state-guidance-multi-step-physical-input.mdnew file mode 100644index 000000000..928c44b29--- /dev/null+++ b/docs/solutions/best-practices/abort-state-guidance-multi-step-physical-input.md@@ -0,0 +1,124 @@+---+title: Abort-state guidance on multi-step physical input errors+date: 2026-06-10+category: best-practices+module: crates/macos+problem_type: best_practice+component: macos-adapter+severity: high+applies_when:+ - Implementing a multi-step physical input sequence (drag, gesture, press-hold) using CGEvent synthesis+ - An early return or error exit can leave cursor or button state at an intermediate position+ - A Drop guard is introduced to cancel a partially committed OS operation+ - An error from a multi-phase input helper needs recovery guidance attached+ - The caller must distinguish "no drop committed" from "drop committed at the wrong target"+tags:+ - drag+ - cgevent+ - abort-state+ - error-recovery+ - mouse-input+ - headless-headed+ - macos+ - physical-fallback+---++# Abort-state guidance on multi-step physical input errors++## Context++A synthetic drag is a multi-step OS mutation: `LeftMouseDown` at the origin, interpolated `LeftMouseDragged` events, a dwell over the destination, then a final `LeftMouseUp`. Any step after the mouse-down can fail, and the original `MouseUpGuard` in `crates/macos/src/input/mouse.rs` had two bugs at once. The happy path disarmed the guard *before* posting the final `LeftMouseUp`, so a failure on that last post left the button logically held down system-wide — the exact defect the guard existed to prevent. And the guard's corrective release on `Drop` fired at the *destination*: CGEvents resolve at the coordinates embedded in the event, so a "corrective" up at the destination is indistinguishable from a successful drop. The file landed in the target folder while the command reported failure — the agent's perception (error) and the system's state (dropped) irreconcilably diverged.++## Guidance++The pattern has three coordinated legs.++**Leg 1 — the guard owns the release, and disarms only after the post succeeds.**++```rust+// crates/macos/src/input/mouse.rs+impl MouseUpGuard {+ fn release_at(&mut self, point: CGPoint) -> Result<(), AdapterError> {+ post_event(CGEventType::LeftMouseUp, point, CGMouseButton::Left)?;+ self.armed = false;+ Ok(())+ }+}+```++The happy path calls `release.release_at(to)` as its final statement. If that post fails, `armed` stays `true` and `Drop` still runs the abort path.++**Leg 2 — abort at the origin, never the unreached destination.**++```rust+impl Drop for MouseUpGuard {+ fn drop(&mut self) {+ if self.armed {+ let _ = post_event(CGEventType::LeftMouseDragged, self.origin, CGMouseButton::Left);+ let _ = post_event(CGEventType::LeftMouseUp, self.origin, CGMouseButton::Left);+ }+ }+}+```++`origin` is captured at `LeftMouseDown`. Releasing where the gesture picked up is a self-drop — a no-op to most drop targets — which gives the abort genuine cancel semantics. There is no "current cursor position" escape hatch: the coordinate in the event is where the OS resolves the release.++**Leg 3 — every error from the sequence carries the end state.**++```rust+pub fn synthesize_drag(params: DragParams) -> Result<(), AdapterError> {+ drag_sequence(params).map_err(|err| {+ if err.suggestion.is_some() {+ return err;+ }+ err.with_suggestion(+ "The drag was aborted: the button was released back at the origin (best-effort) and no drop was committed at the destination. The cursor ends at the origin. Re-check the source state before retrying.",+ )+ })+}+```++One `map_err` at the public boundary; inner errors that already carry a tailored suggestion pass through unchanged. The guard's doc comment also states the best-effort limits honestly: the corrective posts can themselves fail (typically the same systemic CGEventSource failure that aborted the drag), and a drop target sitting under the origin still sees a self-drop.++## Why This Matters++Without leg 1, a failure on the final post leaves the button logically held: the OS treats every subsequent cursor movement as a drag and every click target as a drop target, corrupting unrelated interactions until something releases the button.++Without leg 2, an aborted drag silently commits as a real drop. This is the worst failure class for an agent caller: the error says "retry", but the filesystem or UI already changed — retrying duplicates the operation.++Without leg 3, an agent holding `ACTION_FAILED`/`INTERNAL` cannot tell whether the world changed. With the suggestion, it knows: button released at origin, no drop committed, cursor at origin — and whether a re-snapshot is needed before retry.++## When to Apply++- A command posts a sequence of OS-level events where a later step can fail after an earlier irreversible step succeeded+- The abort path could itself mutate state (a corrective event at the wrong coordinates commits, not cancels)+- Errors must communicate post-failure system state, not just the failure cause, for callers to retry safely++Specifically necessary for anything backed by `CGEventPost`-style APIs that resolve coordinates at event-creation time.++## Examples++Before (both bugs, as originally shipped):++```rust+// happy path disarmed BEFORE the final fallible post+release.armed = false;+post_event(CGEventType::LeftMouseUp, to, CGMouseButton::Left)++// and Drop released at the DESTINATION, committing the aborted drop+impl Drop for MouseUpGuard {+ fn drop(&mut self) {+ if self.armed {+ let _ = post_event(CGEventType::LeftMouseUp, self.to, CGMouseButton::Left);+ }+ }+}+```++The fixed version is the Guidance section above. Verified by the E2E drag scenario observing the canvas effect, not the command's `ok:true`.++## Related++- `best-practices/macos-gesture-headless-capability-2026-06-10.md` — drag/hover/mouse-* are always physical and policy-gated; establishes when this multi-step path runs at all+- `best-practices/playwright-grade-desktop-reliability-2026-06-02.md` — the upstream principle that fallbacks must be explicit and failures honest; abort-state cleanup is that principle applied to mid-sequence failure+- `best-practices/preserve-command-policy-semantics-during-refactor-2026-05-12.md` — when the physical path is even entered (policy ownership) — context for why aborts are headed-mode territorydiff --git a/docs/solutions/best-practices/deduplicate-ref-allocator-via-config-struct-2026-04-14.md b/docs/solutions/best-practices/deduplicate-ref-allocator-via-config-struct-2026-04-14.mdindex d7bd066e2..3409615c7 100644--- a/docs/solutions/best-practices/deduplicate-ref-allocator-via-config-struct-2026-04-14.md+++ b/docs/solutions/best-practices/deduplicate-ref-allocator-via-config-struct-2026-04-14.md@@ -1,6 +1,7 @@---title: Deduplicate ref allocator via RefAllocConfig instead of a _with_X copydate: 2026-04-14+last_updated: 2026-06-10category: best-practicesmodule: crates/coreproblem_type: best_practice@@ -257,6 +258,10 @@ let mut tree = ref_alloc::allocate_refs(raw_tree, &mut refmap, &config);**Net diff** (`d06a6c2 refactor: unify allocate_refs across snapshot and drill-down paths`): +139 / −190 across `ref_alloc.rs`, `snapshot.rs`, `snapshot_ref.rs`. 51 net LOC removed. `grep allocate_refs_with_root` returns zero matches. The follow-up `7c7837a chore: drop with_root from drill test names after allocator unification` renamed the leftover `test_allocate_refs_with_root_*` helpers to `test_drill_alloc_*` so the name is gone from the codebase entirely.+### Current shape (as of 2026-06-10)++The code blocks above are the historical record of that refactor; the unified design has since absorbed further growth in exactly the way the pattern promised — all in one place. `RefAllocConfig` now carries ten fields (the originals plus `source_window_id`, `source_window_title`, `source_surface`, and `path_prefix` for element-identity evidence), ref eligibility generalized from `INTERACTIVE_ROLES.contains(...)` to `is_ref_able(node)` (interactive role **or** a non-`SetFocus` advertised action), the skeleton-anchor condition additionally requires `root_ref_id.is_none()`, and `allocate_refs` delegates to a private `allocate_refs_at_path` that threads tree-position tracking. Each of those changes touched the single shared body — none re-introduced a second copy. See `crates/core/src/ref_alloc.rs` for the current implementation.+## Related- `crates/core/src/ref_alloc.rs` — single source of truth for ref allocationdiff --git a/docs/solutions/best-practices/exhaustiveness-guards-over-catch-alls-in-policy-mirrors.md b/docs/solutions/best-practices/exhaustiveness-guards-over-catch-alls-in-policy-mirrors.mdnew file mode 100644index 000000000..3fdc7a56e--- /dev/null+++ b/docs/solutions/best-practices/exhaustiveness-guards-over-catch-alls-in-policy-mirrors.md@@ -0,0 +1,122 @@+---+title: Use named arms and exhaustiveness guard tests instead of catch-alls in policy and dispatch mirrors+date: 2026-06-10+category: best-practices+module: crates/core, src+problem_type: best_practice+component: command-policy+severity: high+applies_when:+ - A helper mirrors the per-case behavior of real command dispatch (a preflight reproducing each command's policy)+ - A new command or action name is added and a parallel mapping must stay in sync+ - A match over named semantic cases is tempted to use a catch-all arm+ - A registry or test list must provably cover everything the codebase actually contains+tags:+ - exhaustiveness+ - command-policy+ - dispatch+ - wait-predicate+ - regression-prevention+ - contract-tests+ - actionability+ - rust-patterns+---++# Use named arms and exhaustiveness guard tests instead of catch-alls in policy and dispatch mirrors++## Context++`wait --predicate actionable --action <name>` answers "would this action succeed" by running the same actionability preflight the real command runs — which means it must mirror each command's interaction policy exactly. The first implementation centralized that mirror behind a catch-all:++```rust+fn actionability_request(action: Action) -> ActionRequest {+ match action {+ Action::TypeText(_) => ActionRequest::focus_fallback(action),+ _ => ActionRequest::headless(action),+ }+}+```++Correct for the four actions that existed — and a trap for the fifth. Any future action would silently inherit headless policy, right or wrong, with no compiler complaint and no failing test. In a headless-first codebase where policy must flow explicitly from each command's declared base, a mirror that *infers* policy is exactly the drift the project's own learnings warn against. Code review flagged the catch-all as a silent-drift risk (auto memory [claude]: the repo treats policy inference as a standing hazard).++## Guidance++Three legs: explicit arms, a machine-derived universe guard, and per-case value pins.++**Leg 1 — one arm per name; the only "default" is an error.**++```rust+// crates/core/src/commands/wait_predicate.rs+/// Maps each `--action` name to the exact request its real command would+/// run with — policy included — so the preflight answers "would this action+/// succeed". Every name is an explicit arm: a catch-all here would let a+/// new action silently inherit the wrong policy.+fn parse_actionability_action(action: Option<&str>) -> Result<ActionRequest, AppError> {+ match action.unwrap_or("click") {+ "click" => Ok(ActionRequest::headless(Action::Click)),+ "type" => Ok(ActionRequest::focus_fallback(Action::TypeText(String::new()))),+ "set-value" => Ok(ActionRequest::headless(Action::SetValue(String::new()))),+ "clear" => Ok(ActionRequest::headless(Action::Clear)),+ other => Err(AppError::invalid_input_with_suggestion(+ format!("Unknown actionability action '{other}'"),+ "Use one of: click, type, set-value, clear.",+ )),+ }+}+```++The `other` arm rejects unrecognized input — it is input validation, not a semantic catch-all. Adding an action *requires* adding an arm; forgetting produces a user-visible error at this match, never a silent wrong-policy preflight.++**Leg 2 — a guard test that derives the case universe mechanically.**++```rust+// crates/core/src/commands/ref_policy_tests.rs+const POLICY_TESTED_COMMANDS: &[&str] = &[+ "check", "clear", "click", "collapse", "double_click", "expand",+ "focus", "right_click", "scroll", "scroll_to", "select", "set_value",+ "toggle", "triple_click", "type_text", "uncheck",+];++#[test]+fn all_context_request_callers_are_policy_tested() {+ // scans crates/core/src/commands/*.rs (excluding *_tests) for files+ // containing `context.request(` and fails, naming each stem, when one+ // is absent from POLICY_TESTED_COMMANDS+}+```++The universe is not hand-maintained: the test scans the filesystem for the call-site signature every ref-action command shares. A new command file that calls `context.request(` without a registered policy assertion fails CI with a message naming the stem and the required follow-up.++**Leg 3 — per-case value pins.**++Each listed case is pinned to its exact mirrored value, never covered by an "everything else" loop — `type` is asserted `focus_fallback` specifically, each remaining command asserted headless by name. The same shape guards CLI registration in `src/cli/contract_tests.rs`: `NON_COMMAND_MODULES` plus a filesystem scan asserts every command module is either a registered CLI subcommand or an explicitly declared helper.++## Why This Matters++Mirrors rot silently. When real dispatch gains a case but the mirror does not, nothing fails — the mirror's catch-all *answers confidently and wrongly*. Here that means a false "actionable: true" for an action whose real command would run a different policy: the agent's wait reports ready, the action then fails or behaves differently. The compiler cannot help across a string-keyed boundary, so the guard test substitutes for exhaustiveness checking by deriving the universe from the same source of truth the dispatcher uses (the files that exist, the call signature they share).++## When to Apply++- A function maps symbolic names to typed behavior where cases must genuinely differ (policy, routing, config)+- A test list or registry mirrors real per-case code and grows as the system grows+- The case universe is file-shaped or string-keyed, so `match` exhaustiveness cannot be compiler-enforced — derive it mechanically instead+- When the universe IS a closed enum, prefer matching on the enum directly and let the compiler enforce exhaustiveness; the guard-test pattern is for universes the compiler cannot see++## Examples++Before — the policy mirror with a catch-all (silently wrong for the next action):++```rust+match action {+ Action::TypeText(_) => ActionRequest::focus_fallback(action),+ _ => ActionRequest::headless(action),+}+```++After — the Guidance section above; the guard is `all_context_request_callers_are_policy_tested`, the value pin is `actionable_parse_mirrors_each_real_command_policy`.++## Related++- `best-practices/preserve-command-policy-semantics-during-refactor-2026-05-12.md` — the same risk class (per-case policy flattened by a structural abstraction) from the shared-helper angle; complementary defenses+- `best-practices/playwright-grade-desktop-reliability-2026-06-02.md` — the dispatch-correctness and test-ownership contract this pattern enforces at the match level+- `best-practices/macos-gesture-headless-capability-2026-06-10.md` — the per-gesture policy table whose explicitness named arms preservediff --git a/docs/solutions/best-practices/ffi-repr-c-struct-size-pinning.md b/docs/solutions/best-practices/ffi-repr-c-struct-size-pinning.mdnew file mode 100644index 000000000..f0e27b85e--- /dev/null+++ b/docs/solutions/best-practices/ffi-repr-c-struct-size-pinning.md@@ -0,0 +1,119 @@+---+title: Pin repr(C) struct sizes at every layer of the FFI boundary+date: 2026-06-10+category: best-practices+module: crates/ffi+problem_type: best_practice+component: ffi+severity: high+applies_when:+ - Adding or changing a public repr(C) struct in crates/ffi+ - A nested repr(C) struct is embedded by value inside another (size change propagates silently)+ - Writing or updating the committed C ABI header (include/agent_desktop.h)+ - Adding a new FFI integration test in crates/ffi/tests/+ - A C, Swift, Python, Go, or Node consumer allocates the struct on the stack or in a fixed buffer+tags:+ - ffi+ - abi+ - repr-c+ - struct-layout+ - static-assert+ - compile-time-pin+ - c-header+ - memory-safety+---++# Pin repr(C) struct sizes at every layer of the FFI boundary++## Context++`AdDragParams` grew from 40 to 48 bytes when `drop_delay_ms: u64` was added. Because `AdDragParams` is embedded **by value** inside `AdAction`, `AdAction` silently grew 88 → 96 bytes with no guard of any kind — the growth was declared nowhere near the `AdAction` definition. A C caller holding the old layout would under-allocate; the Rust side then reads 8 bytes past the caller's buffer, and that stack garbage becomes a live `drop_delay_ms` value. The growth was caught only because a reviewer noticed it manually — it passed CI because there were no pins.++## Guidance++Three synchronized layers guard every `repr(C)` struct that crosses the ABI. Each layer catches drift at a different consumer point.++**Layer 1 — Rust: published const + compile-time assert + extern size fn.**++```rust+// crates/ffi/src/types/action.rs+pub const AD_ACTION_SIZE: usize = 96;++const _: () = assert!(std::mem::size_of::<AdAction>() == AD_ACTION_SIZE);++#[unsafe(no_mangle)]+pub extern "C" fn ad_action_size() -> usize {+ std::mem::size_of::<AdAction>()+}+```++The anonymous const assert fails the Rust build the moment the layout drifts. The extern function lets any binding language query the true size at startup and compare it against its own layout computation.++**Layer 2 — C header: macro + C11-gated `_Static_assert` + layout history.**++```c+/* crates/ffi/include/agent_desktop.h */+#define AD_ACTION_SIZE (sizeof(AdAction))+#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L+_Static_assert(sizeof(AdAction) == 96, "AdAction ABI size changed");+#endif+```++C11 consumers fail at their own compile time when the header and the pinned literal diverge; pre-C11 consumers verify at runtime by comparing their own layout against `ad_action_size()` (the macro is a sizing shorthand, not a pin — `sizeof` always tracks the current struct). A layout-history comment in the header records past size changes (40→48, the AdAction propagation, renames) so fresh reviewers and upgrading callers stop re-discovering adjudicated breaks.++**Layer 3 — integration test: size, alignment, offset ordering, zeroed-read, const-vs-extern agreement.**++```rust+// crates/ffi/tests/c_abi_layout.rs+assert_eq!(agent_desktop_ffi::types::action::AD_ACTION_SIZE, 96);+assert_eq!(unsafe { common::ad_action_size() }, AD_ACTION_SIZE);+assert_eq!(size_of::<AdAction>(), 96);+assert_eq!(align_of::<AdAction>(), align_of::<usize>());++let offsets = [+ offset_of!(AdAction, kind),+ offset_of!(AdAction, text),+ offset_of!(AdAction, scroll),+ offset_of!(AdAction, key),+ offset_of!(AdAction, drag),+];+assert!(offsets.windows(2).all(|pair| pair[0] < pair[1]));++let copied = unsafe {+ let action = MaybeUninit::<AdAction>::zeroed().assume_init();+ std::ptr::read(&action as *const AdAction)+};+assert_eq!(copied.drag.drop_delay_ms, 0);+```++The zeroed-read assertion doubles as a sentinel check: every field must read as a safe default from zero-initialized memory, because the header tells callers to zero-initialize.++## Why This Matters++Embedded-by-value fields create a *transitive* size dependency: growing the inner struct grows every outer struct that embeds it, with no declaration at the outer definition. Without pins, that propagation is invisible until a caller under-allocates — undefined behavior in the best case, stack garbage promoted to live field values in the worst. The motivating incident proved this is not theoretical: the field addition passed CI cleanly.++Three layers because each guards a different party: the Rust assert guards this repo's own builds, the `_Static_assert` guards C consumers compiling against the committed header, and the integration test guards the cross-language agreement (const, extern fn, and real layout all matching).++## When to Apply++- Every `#[repr(C)]` struct passed by pointer or embedded by value across the FFI boundary+- Double-apply to the **outer** struct whenever a pinned struct is embedded by value in another+- The extern size fn is mandatory when consumers include runtime-layout languages (Python ctypes, Go cgo, Swift unsafe pointers)++## Examples++Adding a field to a pinned struct forces this sequence, and any step done wrong fails loudly:++1. Add the field to the Rust struct → the `const _` assert fails+2. Update the Rust const to the new size → build green+3. Update the header `_Static_assert` literal and the layout-history comment+4. Update the integration test size assertion and extend the zeroed-read check to the new field+5. The header-compile test and `c_abi_layout` test confirm both sides agree++The process is self-documenting: the failing assert names the struct and the expectation at every step.++## Related++- `best-practices/keep-ffi-action-policy-aligned-with-cli-2026-05-12.md` — the behavioral-parity companion; this doc is the structural-parity half of the same FFI review discipline+- `best-practices/playwright-grade-desktop-reliability-2026-06-02.md` — "FFI and CLI divergence makes language bindings less reliable" is the motivation the pins serve+- `best-practices/deterministic-build-artifact-marker-2026-04-16.md` — records that the header is a hand-committed ABI contract, the discipline these pins extenddiff --git a/docs/solutions/best-practices/identity-fingerprint-against-os-reorder-2026-04-16.md b/docs/solutions/best-practices/identity-fingerprint-against-os-reorder-2026-04-16.mdindex 31d93f140..30b13bfa3 100644--- a/docs/solutions/best-practices/identity-fingerprint-against-os-reorder-2026-04-16.md+++ b/docs/solutions/best-practices/identity-fingerprint-against-os-reorder-2026-04-16.md@@ -1,6 +1,7 @@---title: Guard OS-reordered resources with an identity fingerprint, not a raw indexdate: 2026-04-16+last_updated: 2026-06-10category: best-practicesmodule: crates/core, crates/macos, crates/ffiproblem_type: best_practice@@ -111,8 +112,10 @@ real behavioral difference.**Tri-state UTF-8 decoding at the FFI boundary.** The identity stringscome in as `*const c_char`. Null means "no fingerprint"; invalid UTF-8must NOT be silently coerced to "no fingerprint" (that would defeat-the guard). Use `try_c_to_string` which returns-`Ok(None)` / `Ok(Some(_))` / `Err(())` and map `Err` to+the guard). Use `try_c_to_string` (or the `decode_optional_filter!`+macro that wraps it) which returns+`Ok(None)` / `Ok(Some(_))` / `Err(CStrDecodeError)` — the error also+covers strings exceeding the byte cap — and map `Err` to`InvalidArgs`.## When NOT to use thisdiff --git a/docs/solutions/best-practices/keep-ffi-action-policy-aligned-with-cli-2026-05-12.md b/docs/solutions/best-practices/keep-ffi-action-policy-aligned-with-cli-2026-05-12.mdindex d673a8626..904db3856 100644--- a/docs/solutions/best-practices/keep-ffi-action-policy-aligned-with-cli-2026-05-12.md+++ b/docs/solutions/best-practices/keep-ffi-action-policy-aligned-with-cli-2026-05-12.md@@ -1,6 +1,7 @@---title: Keep FFI action policy aligned with CLI action policydate: 2026-05-12+last_updated: 2026-06-10category: best-practicesmodule: crates/ffiproblem_type: best_practice@@ -22,10 +23,10 @@ tags:## ContextThe CLI action path moved to `ActionRequest { action, policy }`, but the FFI-`ad_execute_action` wrapper initially constructed `ActionRequest::physical` for-every action. That meant C, Swift, Python, Go, and Node consumers received-focus-stealing and cursor-moving behavior for actions that the CLI treats as-headless by default.+`ad_execute_action` wrapper initially constructed the cursor/focus policy (then+named `physical`, since renamed `ActionRequest::headed`) for every action. That+meant C, Swift, Python, Go, and Node consumers received focus-stealing and+cursor-moving behavior for actions that the CLI treats as headless by default.## Guidance@@ -42,3 +43,13 @@ Any change to `ActionRequest`, `InteractionPolicy`, or command preflight mustinclude a pass over `crates/ffi/src/actions/`. If the CLI and FFI can perform thesame action, they must document the same default and expose any divergence as anexplicit parameter.++Behavioral parity is only half the FFI review: any structural change to a public+`repr(C)` type — adding, removing, or reordering fields, or growing a struct that+is embedded by value inside another — must also update the three-layer size pin+(Rust const assert, header `_Static_assert`, layout integration test). Size drift+in an embedded struct silently propagates to every outer struct that embeds it.++## Related++- `best-practices/ffi-repr-c-struct-size-pinning.md` — the structural-parity companion: the full three-layer pinning protocol and the AdAction silent-growth incident that motivated it.diff --git a/docs/solutions/best-practices/macos-gesture-headless-capability-2026-06-10.md b/docs/solutions/best-practices/macos-gesture-headless-capability-2026-06-10.mdnew file mode 100644index 000000000..4c9f67b03--- /dev/null+++ b/docs/solutions/best-practices/macos-gesture-headless-capability-2026-06-10.md@@ -0,0 +1,103 @@+---+title: Which desktop gestures have a headless path (macOS) and why the command never decides+date: 2026-06-10+category: best-practices+module: crates/macos+problem_type: best_practice+component: macos-adapter+severity: high+applies_when:+ - Implementing or using a ref-action command and deciding whether it needs --headed+ - A headless ref action returns POLICY_DENIED and you are unsure if that is correct+ - Adding a Windows (UIA) or Linux (AT-SPI) adapter and mapping gesture commands+ - Writing an E2E that drives a gesture and must assert the real effect, not ok:true+tags:+ - interaction-policy+ - headless-headed+ - accessibility+ - macos+ - platform-adapter+ - swiftui+---++# Which desktop gestures have a headless path (macOS) and why the command never decides++## Context++Ref actions run in two modes (Playwright-style): **headless** (default — accessibility-only, no cursor, fail closed with `POLICY_DENIED`) and **headed** (`--headed` — permits cursor movement and focus stealing so physical fallbacks can complete). A recurring question when using or extending the tool is: *which* interactions actually work headlessly, and which inherently need `--headed`? Getting this wrong leads to either surprise `POLICY_DENIED` errors or the false assumption that a command physically interacted when it only did an AX no-op.++The answer is **per-gesture and per-platform**, because a gesture is headless-capable only when the OS accessibility API exposes a semantic action for it. On macOS the reality is:++| Gesture / control | Headless path (macOS) | Notes |+|-------------------|-----------------------|-------|+| `click`, `set-value`, `type`, `check`, `select`, `scroll`, `expand`, `toggle`, … | yes | semantic AX actions; the default and most reliable surface |+| `double-click` | partial | `AXOpen` works headless on elements that advertise it (Finder/list/outline rows, table cells). Falls back to `--headed` only for gesture-only targets with no `AXOpen`. |+| `triple-click` | no | macOS exposes no triple-click action; it is purely 3 physical clicks → `--headed` only |+| `hover` | no | hovering *is* moving the cursor over an element; no AX equivalent |+| `drag` / drop | no | dragging *is* a cursor press-move-release; no general AX drag. Native cross-app drop needs the OS `NSDraggingSession`/pasteboard protocol that synthetic CGEvents cannot start (works for same-view source-tracked gestures and web/Electron mouse-DnD) |+| menu bar | enumerate / open | readable and openable via `snapshot --surface menubar`; **SwiftUI `CommandMenu` items accept AXPress but do not route to their action closure** (a SwiftUI limitation, like its `Slider`) — native AppKit menu items fire. `.contextMenu` item selection works. |+| SwiftUI `Slider` / `Stepper` / `DisclosureGroup` | no | not AX-actionable; the native AppKit `NSSlider`/`NSStepper` equivalents are (so `set-value`/`expand` work on those) |++## Guidance++1. **The command is platform-agnostic; the adapter owns headless-vs-physical.** A ref-action command builds an `Action` (e.g. `Action::TripleClick`) and calls `adapter.execute_action`. The macOS adapter's dispatch decides how to perform it (AX action vs policy-gated CGEvent). Core never encodes platform behavior — it cannot, because core may never import a platform crate (CI enforces this with `cargo tree -p agent-desktop-core`).++2. **A new platform that exposes a headless path lights it up automatically — adapter-only change.** If a future Windows (UIA) or Linux (AT-SPI) adapter has a headless action for `double-click`/`triple-click`, it maps the `Action` there and the command succeeds headlessly on that platform with **zero change to the command or core**. The `InteractionPolicy` flows through the request; each adapter honors it per its own capabilities. The agent just sees success (or `POLICY_DENIED` → retry `--headed`) — it never needs to know the platform.++3. **`hover`/`drag`/`mouse-*` are modeled as raw cursor gestures, not semantic `Action`s** (they call `adapter.mouse_event`/`adapter.drag` with coordinates). They stay physical on every platform by design, because hovering/dragging *are* cursor operations universally. A semantic drag (AX reorder) would be a *new* `Action`, not a change to `drag`. Headless gestures return `POLICY_DENIED` before resolving refs or moving the cursor. Under `--headed`, ref-addressed gestures first ensure the target app is frontmost (`focus_for_physical_input`, gated on `InteractionPolicy::allow_focus_steal`; the response reports `"focused": true` when confirmed — already-frontmost apps skip the raise). `--xy` input never focuses — the caller owns the target there. The chain's physical click fallback goes one step further than the gesture focus path: it also raises the target element's **own window** (AXRaise, AXMain fallback) before posting events, because CGEvents land on the topmost window at the click point and app-frontmost alone is not enough when the element lives in a background window of that app.++4. **`POLICY_DENIED` on a headless gesture is correct, not a bug** — it is the fail-closed signal that the headless AX path is unavailable and the caller must opt into `--headed`. Never widen the default policy to make it disappear.++5. **When verifying a gesture in a test, observe the real effect, never the command's `ok:true`.** An AX action can report `verified_press:succeeded` while the underlying control's handler never ran (SwiftUI `CommandMenu`, `Slider`). Re-read the target's state to confirm.++## Why This Matters++- It keeps the **headless-first reliability guarantee** honest: the tool only claims a headless effect when the OS actually provides one, and fails closed otherwise.+- It preserves **cross-platform extensibility**: the same 54-command surface works identically across macOS/Windows/Linux, and each adapter contributes whatever headless capability its platform has — without touching the command layer.+- It prevents the **vacuous-success trap**: assuming `ok:true` means the gesture happened, when an AX action succeeded at the API layer but the control ignored it.++## When to Apply++- Deciding whether a command needs `--headed` (consult the matrix; `POLICY_DENIED` headless = needs `--headed` or has no headless path).+- Implementing a new platform adapter: map each `Action` to the platform's best headless path first, gate physical fallbacks on the policy, and return `POLICY_DENIED` when only a physical gesture would work.+- Building fixtures/tests: use **native AppKit** controls (`NSSlider`/`NSStepper`) when you need a genuinely AX-actionable target; SwiftUI equivalents will not validate the AX path.++## Examples++Double-click is headless-capable only via `AXOpen`:++```bash+# Finder list row advertises AXOpen -> headless double-click opens it+agent-desktop double-click @e12++# A plain button with no AXOpen -> headless fails closed, needs --headed+agent-desktop double-click @e3 # POLICY_DENIED+agent-desktop --headed double-click @e3 # physical double-click completes+```++The macOS dispatch gates the physical path on the policy (so it is reachable only under `--headed`):++```rust+// crates/macos/src/actions/chain_defs.rs+pub(crate) fn double_click(el, _caps, policy) -> Result<(), AdapterError> {+ if ax_helpers::has_ax_action(el, "AXOpen") && ax_helpers::try_ax_action(el, "AXOpen") {+ return Ok(()); // headless AX path+ }+ crate::actions::dispatch::click_via_bounds(el, MouseButton::Left, 2, policy) // gated; POLICY_DENIED headless+}+```++The menu bar is readable/openable but SwiftUI `CommandMenu` items do not fire via AX:++```bash+agent-desktop snapshot --app MyApp --surface menubar # enumerates the full menu bar with refs+# clicking a SwiftUI CommandMenu item: verified_press:succeeded, but the action closure never runs+# native AppKit menu items DO fire; .contextMenu item selection DOES fire+```++## Related++- `best-practices/preserve-command-policy-semantics-during-refactor-2026-05-12.md` — why `type` keeps a `focus_fallback` base and the shared helper takes the caller's policy.+- `best-practices/keep-ffi-action-policy-aligned-with-cli-2026-05-12.md` — FFI and CLI run the same `ref_action::execute_resolved` ladder, so policy semantics stay identical.+- `best-practices/playwright-grade-desktop-reliability-2026-06-02.md` — strict late resolution, actionability preflight, and the headless-first contract this builds on.+- `best-practices/abort-state-guidance-multi-step-physical-input.md` — what happens when a physical drag sequence fails mid-flight: the button is released back at the origin (never the unreached destination) and the error describes the end state.diff --git a/docs/solutions/best-practices/playwright-grade-desktop-reliability-2026-06-02.md b/docs/solutions/best-practices/playwright-grade-desktop-reliability-2026-06-02.mdnew file mode 100644index 000000000..75f254515--- /dev/null+++ b/docs/solutions/best-practices/playwright-grade-desktop-reliability-2026-06-02.md@@ -0,0 +1,280 @@+---+title: Playwright-grade desktop reliability contract+date: 2026-06-02+last_updated: 2026-06-10+category: best-practices+module: crates/core, crates/macos, crates/ffi, src+problem_type: best_practice+component: tooling+severity: high+applies_when:+ - Ref resolution, action dispatch, wait semantics, session scope, trace output, or FFI ref-action paths change+ - Platform adapters add live state, bounds, action, or resolution behavior+ - CLI or FFI command paths are refactored around shared helpers+ - Adapter conformance tests are added or changed+tags:+ - reliability+ - ref-actions+ - strict-resolution+ - actionability+ - capabilities+ - wait+ - sessions+ - tracing+ - ffi-parity+---++# Playwright-grade desktop reliability contract++## Context++Playwright is reliable because actions flow through a consistent ladder:+resolve a locator, prove it is actionable, wait when the state is changing, and+fail with structured recovery when the target is stale or ambiguous. Desktop+automation cannot copy browser semantics directly, but it can use the same+engineering shape.++The reliability enhancement moved agent-desktop toward that model without+turning the CLI into a browser tool. Core owns the contract. Platform adapters+provide native evidence. CLI and FFI callers share the same ref-action semantics+unless a lower-level API explicitly documents that it bypasses the strict ref+path.++This learning updates the original contract doc with the implementation details+that matter for future changes.++## Guidance++### Keep Hidden Identity Evidence++Snapshot output may hide pixel bounds for compact, agent-friendly responses, but+the persisted ref identity still needs bounds evidence. The safe pattern is:++1. Ask the adapter for bounds when building a ref-bearing snapshot.+2. Allocate refs and store `bounds_hash` from that full internal tree.+3. Strip visible `bounds` only from the returned output when the caller did not+ request them.+4. Keep `bounds_hash` in the refmap so later actionability can detect stale refs.++Do not let presentation options erase identity evidence. Compact output is a+serialization concern, not a weaker ref contract.++### Centralize Strict Ref Actions++Ref actions must pass through the same ladder:++1. Load the refmap from the caller's session.+2. Resolve the ref with strict platform identity checks.+3. Return `STALE_REF` when the old element no longer matches.+4. Return `AMBIGUOUS_TARGET` when multiple candidates match.+5. Run live actionability checks before adapter dispatch.+6. Dispatch the adapter action chosen by the command's policy.+7. Release native handles through the adapter boundary.++The CLI path and FFI strict ref-action path should share this model. A lower+level native-handle FFI call may remain available, but it must be documented as+lower-level: it acts on a handle the caller already resolved and therefore does+not have ref identity evidence to re-check.++Command-specific policy still belongs at the command edge. Centralization should+remove duplicated mechanics; it should not flatten `ActionRequest` choices or+post-condition verification.++### Treat Actionability as a Core Contract++Actionability is not an adapter-specific convenience. Core decides whether a+resolved ref is safe to act on using native evidence supplied by the adapter:++- visibility from live bounds+- stability from live bounds hash versus snapshot bounds hash+- enabled state from live state+- supported action from live or snapshot actions+- interaction policy from the command request+- editability from role and supported actions++Unavailable native evidence should be `unknown`, not a false failure, when the+platform cannot provide it. A non-empty live action list can narrow capabilities;+an empty transient live action list should not erase snapshot capabilities.++### Own Capability Vocabulary in Core++Supported action names are part of the cross-platform contract, not incidental+strings. Put the canonical vocabulary, action-to-capability mapping, role+defaults, and membership helpers in one core module. Actionability, ref+allocation, `is` predicates, FFI tests, and platform adapters should refer to+that vocabulary instead of re-declaring string literals.++Platform adapters may discover capabilities differently. macOS maps AX actions+and settable attributes; Windows should map UIA patterns; Linux should map+AT-SPI actions and states. Those native differences must converge into the same+core capability names before core evaluates actionability.++Do not keep pass-through wrappers such as `Action::semantic_capabilities()` when+call sites can use the canonical capability helper directly. Thin wrappers make+future command additions touch multiple files without clarifying ownership.++### Keep Waits Bounded and Honest++Wait commands must not hide permanent adapter failures behind timeout polling.+The reliable split is:++- Retry transient resolution states such as stale, not found, ambiguous, or+ timeout while the caller's timeout budget remains.+- Propagate permanent adapter errors immediately.+- Preserve the last observed retryable state in timeout details. TIMEOUT+ details carry a `kind` discriminant: `"wait_timeout"` for wait-loop expiry+ (predicate, timeout_ms, last observed state) and `"chain_deadline"` for a+ chain step expiring mid-increment or mid-disclosure (observed value or+ expanded state, plus a `mutated` flag) — agents key on `kind` before+ inspecting other fields.+- For `wait --element` without `--snapshot`, refresh the latest-ref cache on a+ bounded cadence; for a fixed `--snapshot`, treat missing refs as invalid input+ instead of silently switching snapshots.+- `--predicate actionable` checks readiness for a specific action via+ `--action` (`click` default, `type`, `set-value`, `clear`); each name maps to+ the exact request its real command runs — policy included — through explicit+ per-name arms, so an unknown name errors instead of silently inheriting a+ default policy.++This keeps `wait` useful for changing desktop state without making it a blanket+error suppressor.++Resolver deadline checks should also have one owner. If both root selection and+tree traversal need the same timeout error and remaining-budget logic, share a+small resolver-deadline helper instead of copying the deadline branch into each+module. That keeps `wait --element` bounded through every native AX read without+growing resolver files toward the size limit.++### Make Tracing Diagnostic, Not Behavioral++Trace output belongs in the requested JSONL file and never in stdout. It must be+safe for agents to use with machine-readable command output:++- create private trace files+- reject symlink trace paths on Unix+- redact sensitive text/value/name/message fields+- let `--trace-strict` fail on setup and pre-action trace writes+- keep post-action success trace writes best-effort after the desktop mutation+ has already happened++Reporting a successful desktop mutation as failed because the final trace write+failed is worse than losing that final diagnostic event.++Do not describe the current trace as equivalent to Playwright Trace Viewer. It+is a JSONL diagnostic stream, not a bundled timeline artifact with before/after+snapshots, screenshots, source metadata, and an inspection UI. A Playwright-like+desktop trace should be introduced as a separate artifact format if needed.++### Keep the Foundation Cross-Platform++Core owns the contract; adapters own native evidence. Windows and Linux should+not fork CLI semantics. UIA and AT-SPI implementations must map their native+identity fields into the same `RefEntry` concepts: role, name, value,+description, state, bounds, supported actions, source surface, root ref, and+tree path.++Actionability should prefer one native live-state read that returns state,+bounds, and supported actions together. Platform adapters may fall back to+separate reads, but the CLI behavior must remain identical: empty transient+action reads do not erase snapshot capabilities, while a non-empty live action+set that lacks the required action can block dispatch.++Do not add macOS-only assumptions to core to solve a macOS bug. If a behavior is+part of the CLI or FFI contract, core should express the contract and each+adapter should provide native evidence or return a structured unsupported error.++### Triage Review Findings Against Project Constraints++Not every simplification suggested by a reviewer is a good simplification. In+this repo:++- One command per file is intentional; collapsing small command wrappers fights+ the project structure.+- Keeping helpers extracted is correct when inlining would push a file toward+ the 400 LOC limit or duplicate a shared contract.+- Centralizing strict ref-action behavior in core is better than moving it only+ into FFI because CLI and FFI parity is the invariant.+- Splitting tests by owner is better than letting one broad test file become the+ dumping ground for ref maps, ref stores, sessions, and legacy migration.+- Windows/Linux portability means platform-neutral contracts in core, not+ pretending current macOS AX evidence already exists on other platforms.++False positives should be marked as such. Do not add code only to satisfy a+review comment that contradicts the architecture.++## Why This Matters++The user-visible failure modes are severe:++- acting on a stale ref can mutate the wrong UI element+- hidden bounds in compact snapshots can accidentally weaken future stale-ref+ detection+- wait loops that swallow permanent errors waste time and obscure permissions or+ adapter failures+- FFI and CLI divergence makes language bindings less reliable than the command+ line+- trace failures after mutation can make successful desktop actions look failed++Playwright's reliability comes from a predictable action pipeline. agent-desktop+needs the same predictability across desktop platforms, even though native+accessibility APIs expose weaker and less uniform evidence than a browser DOM.++## When to Apply++Any change to ref resolution or action dispatch must include tests for:++- stale ref rejection+- ambiguous target rejection+- actionability failure before dispatch+- retrying waits that honor timeout and report last observed state+- session isolation+- FFI parity when the behavior is exposed through C ABI+- compact snapshot output preserving hidden identity evidence in the refmap+- capability mappings using the central vocabulary instead of copied strings+- resolver deadlines applied before native reads and shared by resolver modules+- trace strictness without post-mutation false failures++If a platform needs a coordinate fallback, the fallback must be explicit and+lower confidence. Do not silently replace a failed semantic action with a pixel+click.++## Examples++Snapshot construction should request identity bounds internally, then hide only+presentation bounds when needed:++```rust+let identity_opts = opts.with_ref_identity_bounds();+let tree = adapter.get_tree(&window, &identity_opts)?;+let (tree, refmap) = allocate_refs(tree, opts)?;+let tree = strip_ref_bounds_when_hidden(tree, opts);+```++Ref action execution should keep the command-selected policy while centralizing+the strict ladder:++```rust+let (entry, handle) = resolve_ref_with_context(ref_id, snapshot_id, adapter, context)?;+check_actionability_with_trace(ref_id, &entry, handle.handle(), adapter, &request, context)?;+let result = adapter.execute_action(handle.handle(), request)?;+```++The platform adapter should expose a single live element read when possible:++```rust+LiveElement {+ state: live_state,+ bounds: live_bounds,+ available_actions: live_actions,+}+```++Windows UIA and Linux AT-SPI adapters can fill those fields differently, but the+core actionability decision must stay the same.++## Related++- [Keep FFI action policy aligned with CLI action policy](keep-ffi-action-policy-aligned-with-cli-2026-05-12.md)+- [Preserve command policy semantics during shared ref-action refactors](preserve-command-policy-semantics-during-refactor-2026-05-12.md)+- [Guard OS-reordered resources with an identity fingerprint, not a raw index](identity-fingerprint-against-os-reorder-2026-04-16.md)+- [Progressive snapshot contract fixes after review](../logic-errors/progressive-snapshot-review-contract-2026-04-16.md)diff --git a/docs/solutions/best-practices/preserve-command-policy-semantics-during-refactor-2026-05-12.md b/docs/solutions/best-practices/preserve-command-policy-semantics-during-refactor-2026-05-12.mdindex 9fc5ca662..b86064e13 100644--- a/docs/solutions/best-practices/preserve-command-policy-semantics-during-refactor-2026-05-12.md+++ b/docs/solutions/best-practices/preserve-command-policy-semantics-during-refactor-2026-05-12.md@@ -1,6 +1,7 @@---title: Preserve command policy semantics during shared ref-action refactorsdate: 2026-05-12+last_updated: 2026-06-10category: best-practicesmodule: crates/core, crates/macosproblem_type: best_practice@@ -53,8 +54,14 @@ Each command owns its policy:- Use `ActionRequest::focus_fallback` only for APIs that have explicitly optedinto focus-changing behavior, such as CLI `type` after AXValue failure or FFIcallers selecting `AD_POLICY_KIND_FOCUS_FALLBACK`.-- Use `ActionRequest::physical` only for explicit physical interaction commands- or FFI callers selecting `AD_POLICY_KIND_PHYSICAL`.+- Use `ActionRequest::headed` (formerly `physical`) only for explicit physical+ interaction commands or FFI callers selecting `AD_POLICY_KIND_HEADED`. Ref+ commands no longer select it directly — the global `--headed` flag upgrades+ any command's base policy to headed via `CommandContext::request`. Note the+ headed physical path's side effects go beyond app-level focus stealing: the+ physical click fallback also raises the target element's own window (AXRaise,+ AXMain fallback) before posting events, gated on the same+ `allow_cursor_move && allow_focus_steal` policy as the rest of that path.Do not infer policy from the fact that a command consumes a ref. `click`,`check`, `expand`, `collapse`, `scroll-to`, `clear`, and `type` all consume refs,@@ -84,3 +91,8 @@ part of correctness:For AX value writes, treat "set returned success" as incomplete evidence onweb-backed controls. Read back the value when the field is not secure; amismatch must be a failed step so the next command-specific fallback can run.++## Related++- `best-practices/exhaustiveness-guards-over-catch-alls-in-policy-mirrors.md` — the same risk class (per-case policy flattened by a structural abstraction) from the string-keyed dispatch-mirror angle: named arms plus machine-derived guard tests where the compiler cannot enforce exhaustiveness.+- `best-practices/macos-gesture-headless-capability-2026-06-10.md` — the per-gesture policy table whose explicitness this guidance preserves.diff --git a/skills/agent-desktop-ffi/SKILL.md b/skills/agent-desktop-ffi/SKILL.mdindex 1769b4f03..8817fcd30 100644--- a/skills/agent-desktop-ffi/SKILL.md+++ b/skills/agent-desktop-ffi/SKILL.md@@ -59,19 +59,46 @@ Four reference topics, loaded as needed:- **Handle release.** Every `ad_resolve_element` result must bereleased with `ad_free_handle(adapter, handle)` on the same adapter- that produced it. On macOS this balances the internal `CFRetain`;- on Windows/Linux the call is a no-op but safe to issue.--- **Action policy.** `ad_execute_action` uses the headless policy by- default, matching CLI ref commands: no focus stealing and no cursor- movement. Use `ad_execute_action_with_policy(...,- AD_POLICY_KIND_FOCUS_FALLBACK, ...)` only when focus-changing behavior is- intended, and `AD_POLICY_KIND_PHYSICAL` only for explicit physical/headed- input semantics.--- **Text input privacy.** On macOS, explicit focus/physical policy can use the- clipboard briefly for non-ASCII text insertion. Keep the default headless- policy or set values directly for sensitive text when the target supports it.+ that produced it before that adapter is destroyed. On macOS this+ balances the internal `CFRetain`; on Windows/Linux the call is a no-op+ but safe to issue.++- **Action policy.** `ad_execute_action` uses headless policy by default.+ `ad_execute_ref_action_with_policy` should also use headless for semantic+ ref actions that must fail closed, except `AD_ACTION_KIND_TYPE_TEXT`: use+ `AD_POLICY_KIND_FOCUS_FALLBACK` for CLI `type` parity because typing needs+ focus but not cursor movement. Use `AD_POLICY_KIND_HEADED` only for explicit+ headed input semantics.++- **Ref-action preflight.** `ad_execute_ref_action_with_policy` resolves the+ ref strictly and runs the live actionability preflight (visible, stable,+ enabled, supported action, policy, editable) before dispatching — a disabled+ or unsupported target fails before any platform call. On+ `AD_RESULT_ERR_ACTION_FAILED`, the structured check report is available as+ JSON via `ad_last_error_details()`. Details may carry element names, values,+ and window titles from the user's screen — treat them as sensitive+ diagnostics and keep them out of shared log surfaces.++- **Action result steps.** `AdActionResult.steps` mirrors the CLI `steps`+ array for activation-chain actions. Each entry has `label` and `outcome`+ strings and is owned by the result; release it with+ `ad_free_action_result(&out)`.++- **Tracing.** CLI `--trace` is not inherited by the C ABI; FFI hosts should+ record `AdResult`, `ad_last_error_*`, action results, and host correlation IDs+ in their own logs.++- **No wait surface.** The CLI's `wait` command (element predicates including+ `--predicate actionable --action ...`, window/text/menu/notification waits)+ is not exposed over the C ABI. FFI hosts own their own polling loops; the+ actionability preflight inside `ad_execute_ref_action_with_policy` is the+ equivalent per-call readiness check.++- **Text input privacy.** On macOS, focus-fallback or headed text insertion may+ briefly use the clipboard for non-ASCII text. For sensitive text, prefer+ `AD_ACTION_KIND_SET_VALUE` with `AD_POLICY_KIND_HEADLESS` when the target+ supports settable values. Do not use headless `AD_ACTION_KIND_TYPE_TEXT` as+ CLI-parity ref input; actionability rejects it before dispatch.- **Enum discriminants.** Every `#[repr(i32)]` enum field is validatedat the C boundary — invalid discriminants returndiff --git a/skills/agent-desktop-ffi/references/ownership.md b/skills/agent-desktop-ffi/references/ownership.mdindex 09ca71a5d..81d0c01a6 100644--- a/skills/agent-desktop-ffi/references/ownership.md+++ b/skills/agent-desktop-ffi/references/ownership.md@@ -20,6 +20,8 @@ free function. Always call it; the allocator the FFI uses is Rust's| `ad_resolve_element(adapter, entry, &handle)` | `ad_free_handle(adapter, &handle)` — `*mut AdNativeHandle`; the call zeroes `handle.ptr` on success so a follow-up call is a no-op || `ad_find(adapter, win, query, &handle)` | same as `ad_resolve_element` || `ad_execute_action(adapter, handle, action, &out)` | `ad_free_action_result(&out)` |+| `ad_execute_action_with_policy(adapter, handle, action, policy, &out)` | `ad_free_action_result(&out)` |+| `ad_execute_ref_action_with_policy(adapter, entry, action, policy, &out)` | `ad_free_action_result(&out)` || `ad_notification_action(adapter, idx, expected_app, expected_title, name, &out)` | `ad_free_action_result(&out)` — pass the `app_name`/`title` you observed in `ad_list_notifications` (either may be null) so NC reorder between list and press is caught with `ERR_NOTIFICATION_NOT_FOUND` instead of pressing a different notification || `ad_screenshot(adapter, target, &buf)` | `ad_image_buffer_free(buf)` (buf is opaque; read via `ad_image_buffer_{data,size,width,height,format}`) || `ad_get_clipboard(adapter, &text)` | `ad_free_string(text)` |@@ -38,10 +40,18 @@ free function. Always call it; the allocator the FFI uses is Rust's- **`ad_free_handle` is safe to double-call** — it zeroes`handle.ptr` after the platform release, so a follow-up call sees`NULL` and returns `AD_RESULT_OK` without re-entering `CFRelease`.+- **Adapters must outlive their handles.** Free every handle with the+ same adapter that produced it before calling `ad_adapter_destroy`.+ Destroying the adapter first and later freeing its handles is+ undefined behavior for FFI hosts.- Pointers inside a struct (`.id`, `.title`, `.app_name`, each`AdNotificationInfo.body`, etc.) are freed by the struct's owningfree function (list_free / release_fields) — do not`ad_free_string()` them individually.+- `AdActionResult` owns `action`, `ref_id`, `post_state`, `post_state.states`,+ `steps`, and each `steps[i].label` / `steps[i].outcome`; free all of them+ only through `ad_free_action_result(&out)`. Treat the returned counts as+ read-only metadata; release the unmodified result struct.- Ownership does **not** transfer back to Rust after you free. Keep alocal `NULL` to prevent accidental reuse.diff --git a/skills/agent-desktop/SKILL.md b/skills/agent-desktop/SKILL.mdindex 8427a3c0d..d7d1e894c 100644--- a/skills/agent-desktop/SKILL.md+++ b/skills/agent-desktop/SKILL.md@@ -83,14 +83,20 @@ Use **progressive skeleton traversal** as the default approach. It reduces token## Ref System- Refs assigned depth-first: `@e1`, `@e2`, `@e3`...-- Only interactive elements get refs: button, textfield, checkbox, link, menuitem, tab, slider, combobox, treeitem, cell+- An element gets a ref when it is addressable for an action: an interactive role (button, textfield, checkbox, link, menuitem, tab, slider, combobox, treeitem, cell, radiobutton, switch, ...) **or** any element advertising an action — so `scrollarea` (Scroll) and `disclosure` (Expand/Collapse) are ref-able and `scroll`/`expand`/`collapse` can target them+- A `SetFocus`-only affordance does not earn a ref on its own- In skeleton mode, named/described containers at truncation boundary also get refs (drill-down targets with empty `available_actions`)-- Static text, groups, containers remain in tree for context but have no ref+- Static text and non-actionable groups/containers remain in tree for context but have no ref- Refs are deterministic within a snapshot but NOT stable across snapshots if UI changed-- Every snapshot returns `snapshot_id`; ref-consuming commands accept `--snapshot <snapshot_id>`+- Every snapshot returns `snapshot_id`; ref-consuming commands accept `--snapshot <snapshot_id>`, and explicit snapshot IDs do not require also passing `--session`- `last_refmap.json` is only a latest-snapshot inspection artifact. The command path uses snapshot-scoped storage.- After any action that changes UI, re-drill the affected region or re-snapshot- **Scoped invalidation:** re-drilling `--root @e3` only replaces refs from @e3's previous drill — refs from other regions and the skeleton itself are preserved+- **Strict resolution:** stale refs return `STALE_REF`; duplicate plausible targets return `AMBIGUOUS_TARGET` instead of choosing arbitrarily.+- **Actionability:** ref actions check live visibility, stability, enabled state, supported action, policy, and editability before dispatch.+- **Headless vs headed:** ref actions are headless by default (AX-only, no cursor) and fail closed when only a physical gesture would work. `type` uses a focus-fallback base policy because typing needs focus but never moves the cursor. Pass the global `--headed` flag to permit cursor movement and focus stealing so physical fallbacks can complete; the AX path is still tried first, so `--headed` never regresses headless-capable elements. Raw cursor commands (`hover`, `drag`, `mouse-*`) are physical and require `--headed`; keyboard commands (`press`, `key-down`, `key-up`) are explicit low-level input.+- **Sessions:** use `--session <id>` for concurrent or multi-agent runs that share a latest snapshot pointer; batch entries may override with `"session": "id"`.+- **Trace:** use `--trace <path>` for JSONL diagnostics outside stdout; `--trace-strict` fails on trace setup and pre-action writes. Post-action success traces are best-effort because the desktop mutation already happened. Trace fields with sensitive key tokens such as `text`, `value`, `expected`, `name`, `username`, `description`, `label`, `query`, `secret`, `token`, `password`, `title`, `url`, `help`, or `placeholder` are redacted to `{ "redacted": true }` at every nesting depth. Token matching handles snake_case, kebab-case, and camelCase keys (for example, `source_window_title`, `api_token`, and `typedText` redact, while `filename` stays readable). Top-level `--trace` is inherited by every `batch` entry, including entries with a `session` override.## JSON Output Contract@@ -99,6 +105,8 @@ Every command returns a JSON envelope on stdout:**Success:** `{ "version": "2.0", "ok": true, "command": "snapshot", "data": { ... } }`**Error:** `{ "version": "2.0", "ok": false, "command": "click", "error": { "code": "STALE_REF", "message": "...", "suggestion": "..." } }`+The `error` object may also carry an optional `details` object (e.g. the actionability report on an actionability failure, candidate summaries on `AMBIGUOUS_TARGET`, or the last observed state on a `wait` `TIMEOUT`). Parse errors leniently — `details` and future fields are additive, so do not reject responses with unknown keys.+Exit codes: `0` success, `1` structured error, `2` argument error.### Error Codes@@ -110,14 +118,18 @@ Exit codes: `0` success, `1` structured error, `2` argument error.| `APP_NOT_FOUND` | App not running | Launch it first || `ACTION_FAILED` | AX action rejected | Try an explicit alternative command || `ACTION_NOT_SUPPORTED` | Element can't do this | Use different command |-| `STALE_REF` | Ref from old snapshot | Re-run snapshot |+| `STALE_REF` | Ref from old snapshot | Use the `snapshot_id` returned with this ref, or re-run `snapshot` / `snapshot --skeleton` to get fresh refs |+| `AMBIGUOUS_TARGET` | Multiple elements matched the old ref identity | Re-run snapshot and choose a more specific ref || `SNAPSHOT_NOT_FOUND` | Snapshot ID is missing or expired | Run `snapshot` again and use the returned ID || `POLICY_DENIED` | A physical/headed path was blocked | Use an explicit mouse/focus/keyboard command if physical interaction is intended || `WINDOW_NOT_FOUND` | No matching window | Check app name, use list-windows || `PLATFORM_NOT_SUPPORTED` | Adapter method not implemented on this platform | Use a supported platform adapter |-| `TIMEOUT` | Wait condition not met | Increase --timeout |+| `TIMEOUT` | Wait condition not met | Increase `--timeout` for a predicate wait; for a chain deadline (`error.details.kind == "chain_deadline"`), increase `AGENT_DESKTOP_CHAIN_TIMEOUT_MS` — `--timeout` has no effect on chain deadlines || `INVALID_ARGS` | Bad arguments | Check command syntax || `NOTIFICATION_NOT_FOUND` | Notification index no longer exists | Re-run list-notifications |+| `INTERNAL` | Unexpected platform/OS failure (e.g. event synthesis failed) | Read `message`/`suggestion` for cleanup state, then retry once; persistent failures indicate an environment problem |++`TIMEOUT` errors carry a `details` object whose `kind` field selects the schema. `kind: "wait_timeout"` includes `predicate`, `timeout_ms`, and `last_observed` or `last_error`, plus `ref`/`title`/`text_chars` depending on the wait mode. `kind: "chain_deadline"` includes `value_before`, `value_at_timeout`, `target`, and `mutated` (increment waits) or `wanted_expanded`/`observed_expanded` (disclosure waits). `mutated: true` — or an unknown `observed_expanded` state — means re-read the element before retrying; `mutated: false` means the state did not change and retrying directly is safe.## Command Quick Reference (54 commands)@@ -137,7 +149,7 @@ agent-desktop list-surfaces --app "App" # Available surfaces### Interaction```agent-desktop click @e5 --snapshot <snapshot_id> # AX-first click, no cursor move by default-agent-desktop double-click @e3 # AXOpen; physical double-click uses mouse-click --count 2+agent-desktop double-click @e3 # AXOpen; physical double-click uses --headed mouse-click --count 2agent-desktop triple-click @e2 # Physical triple-click uses mouse-click --count 3agent-desktop right-click @e5 # Right-click; menu returned when verifiedagent-desktop type @e2 --snapshot <snapshot_id> "hello" # Headless AX text insertion when supported@@ -160,20 +172,20 @@ agent-desktop press cmd+c # Key comboagent-desktop press return --app "App" # Targeted key pressagent-desktop key-down shift # Hold keyagent-desktop key-up shift # Release key-agent-desktop hover @e5 # Explicit cursor movement-agent-desktop hover --xy 500,300 # Cursor to coordinates-agent-desktop drag --from @e1 --to @e5 # Drag between elements-agent-desktop mouse-click --xy 500,300 # Click at coordinates-agent-desktop mouse-move --xy 100,200 # Move cursor-agent-desktop mouse-down --xy 100,200 # Press mouse button-agent-desktop mouse-up --xy 300,400 # Release mouse button+agent-desktop --headed hover @e5 # Explicit cursor movement+agent-desktop --headed hover --xy 500,300 # Cursor to coordinates+agent-desktop --headed drag --from @e1 --to @e5 # Drag between elements+agent-desktop --headed mouse-click --xy 500,300 # Click at coordinates+agent-desktop --headed mouse-move --xy 100,200 # Move cursor+agent-desktop --headed mouse-down --xy 100,200 # Press mouse button+agent-desktop --headed mouse-up --xy 300,400 # Release mouse button```### App & Window```agent-desktop launch "System Settings" # Launch and waitagent-desktop close-app "TextEdit" # Quit gracefully-agent-desktop close-app "TextEdit" --force # Force kill+agent-desktop close-app "TextEdit" --force # Force quit; SIGKILL if SIGTERM does not exitagent-desktop list-windows --app "Finder" # List windowsagent-desktop list-apps # List running GUI appsagent-desktop focus-window --app "Finder" # Bring to front@@ -206,6 +218,8 @@ agent-desktop clipboard-clear # Clear clipboard```agent-desktop wait 1000 # Pause 1 secondagent-desktop wait --element @e5 --snapshot <snapshot_id> --timeout 5000 # Wait for element+agent-desktop wait --element @e5 --predicate actionable --timeout 5000 # Wait until actionable+agent-desktop wait --element @e5 --predicate value --value "Done" --timeout 5000 # Wait for valueagent-desktop wait --window "Title" # Wait for windowagent-desktop wait --text "Done" --app "App" # Wait for textagent-desktop wait --menu --app "App" # Wait for menu surface@@ -229,11 +243,13 @@ agent-desktop skills get desktop --full # Load this skill + all referenc1. **Skeleton first, drill second.** Start with `--skeleton -i --compact` for dense apps. Drill into regions with `--root @ref`. Full snapshot only for simple apps.2. **Use `-i --compact` flags.** Filters to interactive elements and collapses empty wrappers, minimizing tokens.3. **Refs are snapshot-scoped.** Keep `snapshot_id` for deterministic multi-step use; re-drill the affected region after any UI-changing action. Scoped invalidation keeps other refs intact.-4. **Prefer refs over coordinates.** `click @e5` > `mouse-click --xy 500,300`.+4. **Prefer refs over coordinates.** `click @e5` > `agent-desktop --headed mouse-click --xy 500,300`.5. **Use `wait` for async UI.** After launch/dialog triggers, wait for expected state.6. **Check permissions first.** Run `permissions` on first use; screenshots also need Screen Recording.-7. **Handle errors.** Parse `error.code` and follow `error.suggestion`.+7. **Handle errors.** Branch on `error.code` only — `error.message` and `error.suggestion` text is informational and may change between versions.8. **Use `find` for targeted searches.** Faster than any snapshot when you know role/name.9. **Use surfaces for overlays.** `snapshot --surface menu` for menus, `--surface sheet` for dialogs. Never `--skeleton` for surfaces — they're already focused.10. **Batch for performance.** Multiple commands in one invocation.11. **Headless by default.** Ref actions use semantic AX paths and block silent focus stealing, cursor movement, keyboard synthesis, and pasteboard insertion. Use explicit `focus`, `press`, `hover`, `drag`, or `mouse-*` commands only when physical/headed interaction is intended.+12. **Use sessions for parallel work.** Add `--session <id>` when multiple agents or batches can run at once.+13. **Trace hard failures.** Add `--trace /tmp/agent-desktop.jsonl` when diagnosing stale, ambiguous, or actionability failures.diff --git a/skills/agent-desktop/references/commands-interaction.md b/skills/agent-desktop/references/commands-interaction.mdindex 3bc268f41..d36e35d59 100644--- a/skills/agent-desktop/references/commands-interaction.md+++ b/skills/agent-desktop/references/commands-interaction.md@@ -2,13 +2,40 @@Commands for modifying UI state — clicking, typing, selecting, scrolling, and input synthesis.-Ref-based actions are headless by default. They try semantic accessibility operations and do not silently steal focus, move the cursor, synthesize keyboard input, or use the pasteboard. Physical/headed interaction is reserved for explicit `focus`, `press`, `hover`, `drag`, and `mouse-*` commands or an explicit FFI policy. The `type` command has an explicit focus-fallback tier for callers that opt into focus changes while still forbidding cursor movement; the default CLI path remains AX-value-first and headless.+### Headless (default) vs `--headed`-All ref-based interaction commands accept `--snapshot <snapshot_id>`. Omit it for the latest saved snapshot, or pass the `snapshot_id` returned by `snapshot` to keep scripts pinned to the exact ref map they observed.+Ref-based actions run in two modes, Playwright-style:++- **Headless (default).** Semantic accessibility operations only. The action never silently steals focus, moves the cursor, synthesizes keyboard input, or uses the pasteboard. When the AX path cannot perform the action it fails closed rather than reaching for OS input synthesis. (`type` is the one exception: its base tier may focus the target field — required for reliable typing — but still never moves the cursor.)+- **`--headed`.** A global flag (`agent-desktop --headed click @e5`) that upgrades every ref action to permit focus stealing **and** cursor movement, unlocking the physical click/double-click/scroll/keypress fallbacks in the action chain. The AX path is still tried first, so `--headed` never regresses elements that work headlessly — it only adds fallbacks for elements that need a real gesture (e.g. a gesture-only button with no `AXOpen`).++Raw-input commands (`press`, `hover`, `drag`, `mouse-*`, `key-down`, `key-up`) are physical by nature. Cursor-moving commands (`hover`, `drag`, `mouse-*`) require `--headed`; keyboard commands are explicit low-level input.++`--headed` is a global flag and also applies to every `batch` entry.++#### Which gestures have a headless path++The command surface is platform-agnostic: every ref action builds an `Action` and calls the platform adapter, which owns the headless-vs-physical implementation. The table below is the **macOS (Phase 1) adapter's** behavior — a gesture is headless-capable there only when macOS exposes an accessibility action for it. If a future Windows (UIA) or Linux (AT-SPI) adapter exposes a headless path for `double-click`/`triple-click`, that command lights up headlessly on that platform with **no change to the command or core** — only the adapter changes (`hover`/`drag` are modeled as raw cursor gestures, so they stay physical everywhere by design).++| Command | Headless path (macOS) | Notes |+|---------|---------------|-------|+| `click`, `set-value`, `check`, `select`, `scroll`, `expand`, … | yes | semantic AX actions; the default and most reliable surface |+| `type` | focus fallback | CLI `type` may focus the target field but never moves the cursor; use `set-value` for pure headless value mutation when supported |+| `double-click` | partial | `AXOpen` works headless on items that advertise it (Finder/list/outline rows, table cells). Falls back to `--headed` only for gesture-only targets with no `AXOpen`. |+| `triple-click` | no | macOS exposes no triple-click action; it is purely 3 physical clicks → `--headed` only |+| `hover` | no | hovering *is* moving the cursor over an element; no AX equivalent |+| `drag` / drop | no | dragging *is* a cursor press-move-release; no general AX drag. Native cross-app drop needs the OS dragging-session/pasteboard protocol that synthetic events cannot start (works for same-view source-tracked gestures and web/Electron mouse-DnD) |+| menu bar (`--surface menubar`) | enumerate/open | the app menu bar is readable and openable; SwiftUI `CommandMenu` items accept AXPress but do not route to their action closure (a SwiftUI limitation, like its Slider) — native AppKit menu items fire. `.contextMenu` item selection works. |++All ref-based interaction commands accept `--snapshot <snapshot_id>`. Omit it for the active session's latest saved snapshot, or pass the `snapshot_id` returned by `snapshot` to keep scripts pinned to the exact ref map they observed. Explicit snapshot IDs do not require also passing `--session`.++Success responses for ref actions include a `steps` array when the activation chain recorded attempts: each entry is `{ "label": "AXPress", "outcome": "attempted" | "skipped" | "succeeded" }` in execution order, showing which activation path produced the result.++When the actionability preflight blocks an action, the error envelope carries the full report in `error.details`: `{ "actionable": false, "checks": [ { "name": "...", "status": "...", "reason": "..." } ] }`. Check names are `visible`, `stable`, `enabled`, `supported_action`, `policy`, and `editable`; statuses are `pass`, `fail`, and `unknown`. Use the failing check's `reason` to pick recovery: `wait --element <ref> --predicate actionable`, a fresh snapshot, or `--headed` when a `policy` check failed and a physical gesture is intended.## Click Actions-Click commands use semantic AX activation first. In the default headless policy, coordinate click fallback is blocked; use `mouse-click` only when physical cursor movement is intended.+Click commands use semantic AX activation first. In the default headless mode, coordinate click fallback is blocked; pass `--headed` to allow the physical click fallback, or use `agent-desktop --headed mouse-click` for a raw coordinate click.### click```bash@@ -21,19 +48,19 @@ Primary activation. Tries verified AXPress > AXConfirm > AXOpen > AXPick > child```bashagent-desktop double-click @e3```-Tries AXOpen. Physical double-click fallback is blocked by default policy; use `mouse-click --xy X,Y --count 2` when a headed physical double-click is intended.+Tries AXOpen (headless). When the element advertises no `AXOpen`, the headless command fails closed with `POLICY_DENIED`; pass `--headed` to perform a real double-click (`agent-desktop --headed double-click @e3`), or use `agent-desktop --headed mouse-click --xy X,Y --count 2` for a raw coordinate double-click.### triple-click```bashagent-desktop triple-click @e2```-Physical triple-click requires cursor/focus side effects and is blocked by default policy; use `mouse-click --xy X,Y --count 3` when a headed physical triple-click is intended.+Triple-click requires cursor/focus side effects and is blocked in headless mode; pass `--headed` (`agent-desktop --headed triple-click @e2`), or use `agent-desktop --headed mouse-click --xy X,Y --count 3` for a raw coordinate triple-click.### right-click```bashagent-desktop right-click @e5```-Performs a semantic right-click/context-menu action and includes the menu tree when a menu surface can be verified. If the right-click action succeeds but menu probing fails, the command still returns the action result with `menu_probe.ok: false` so callers do not retry and double-open context menus. Combo boxes and menu buttons expose menu-opening actions for their primary dropdown; use `select` for those controls, not `right-click`. Focus-stealing and coordinate right-click fallback are blocked by default policy.+Performs a semantic right-click/context-menu action and includes `menu` plus `menu_snapshot_id` when a menu surface can be verified. If the right-click action succeeds but menu probing fails, the command still returns the action result with `menu_probe.ok: false` so callers do not retry and double-open context menus. Combo boxes and menu buttons expose menu-opening actions for their primary dropdown; use `select` for those controls, not `right-click`. Focus-stealing and coordinate right-click fallback are blocked in headless mode; pass `--headed` to allow them.## Text Input@@ -42,9 +69,9 @@ Performs a semantic right-click/context-menu action and includes the menu tree wagent-desktop type @e2 "[email protected]"agent-desktop type @e2 "multi line\ntext"```-In the default headless policy, inserts text by mutating the element's AX value when the target has a settable text value. If a target cannot be updated headlessly, the command returns a structured error instead of stealing focus. Physical keyboard synthesis and pasteboard-based insertion are reserved for explicit policy paths.+`type` uses the focus-fallback policy floor: it may focus the target field because typing requires focus, but it never moves the cursor. If the field cannot be updated and the focused-insert path is unavailable, it returns a structured error. Pass `--headed` to unlock physical keyboard synthesis and pasteboard-based insertion for fields that ignore AX value writes (common in web/Electron inputs).-When an explicit focus/physical policy is used for non-ASCII text on macOS, the adapter may briefly place the text on the clipboard to paste it. Do not use that path for secrets; prefer the default headless value path or `set-value` when the target supports it.+Under focus-fallback or `--headed`, non-ASCII text on macOS may be briefly placed on the clipboard to paste it. Do not use that path for secrets; prefer `set-value` when the target supports it.### set-value```bash@@ -164,18 +191,21 @@ Releases a held key or modifier.### hover```bash-agent-desktop hover @e5-agent-desktop hover --xy 500,300-agent-desktop hover @e5 --duration 2000+agent-desktop --headed hover @e5+agent-desktop --headed hover --xy 500,300+agent-desktop --headed hover @e5 --duration 2000```Moves cursor to element center or absolute coordinates. Optional `--duration` holds position for N ms.This is an explicit cursor-moving command.+With `--headed`, a ref-addressed hover ensures the target app is frontmost before moving the cursor (raising it if needed, best-effort), and the response includes `"focused": true` when that frontmost state was confirmed. The field is only ever present as `true`: absence means focus was never attempted (headless default, or `--xy` input — the caller owns the target there) or the best-effort raise could not be confirmed.+### drag```bash-agent-desktop drag --from @e1 --to @e5-agent-desktop drag --from-xy 100,200 --to-xy 400,500-agent-desktop drag --from @e1 --to-xy 400,500 --duration 500+agent-desktop --headed drag --from @e1 --to @e5+agent-desktop --headed drag --from-xy 100,200 --to-xy 400,500+agent-desktop --headed drag --from @e1 --to-xy 400,500 --duration 500+agent-desktop --headed drag --from @e1 --to @e5 --drop-delay 800```| Flag | Description |@@ -184,21 +214,26 @@ agent-desktop drag --from @e1 --to-xy 400,500 --duration 500| `--from-xy` | Source coordinates as `x,y` || `--to` | Destination element ref || `--to-xy` | Destination coordinates as `x,y` |-| `--duration` | Drag duration in milliseconds |+| `--duration` | Drag duration in milliseconds (movement from source to destination) |+| `--drop-delay` | Milliseconds to hold over the destination before releasing; default 500 |Can mix ref and coordinate sources (e.g., `--from @e1 --to-xy 400,500`).+With `--headed`, a ref-addressed `--from` ensures the source app is frontmost before the mouse-down (the destination app is never pre-focused — raising it could cover the source point), and the response includes `"focused": true` when that frontmost state was confirmed. The field is only ever present as `true`: absence means focus was never attempted (headless default, or coordinate-only drags) or the best-effort raise could not be confirmed. For cross-app two-ref drags, ensure the destination window is visible (not fully occluded) before dragging — only the source app is raised.++macOS drop targets often need the dragged item to dwell over them before they register as the drop destination — too short and the gesture lands as a drag with no drop. The default 500ms dwell suits most targets; raise `--drop-delay` (e.g. 800–1200) for sluggish destinations like list reorders or cross-window drops. The dwell posts continuous drag events over the destination so it stays highlighted, rather than a dead pause.+### mouse-move```bash-agent-desktop mouse-move --xy 500,300+agent-desktop --headed mouse-move --xy 500,300```Moves cursor to absolute screen coordinates.### mouse-click```bash-agent-desktop mouse-click --xy 500,300-agent-desktop mouse-click --xy 500,300 --button right-agent-desktop mouse-click --xy 500,300 --count 2+agent-desktop --headed mouse-click --xy 500,300+agent-desktop --headed mouse-click --xy 500,300 --button right+agent-desktop --headed mouse-click --xy 500,300 --count 2```| Flag | Default | Description |@@ -209,8 +244,8 @@ agent-desktop mouse-click --xy 500,300 --count 2### mouse-down / mouse-up```bash-agent-desktop mouse-down --xy 100,200-agent-desktop mouse-up --xy 300,400+agent-desktop --headed mouse-down --xy 100,200+agent-desktop --headed mouse-up --xy 300,400```Low-level press/release for custom drag or hold interactions.@@ -223,11 +258,11 @@ Low-level press/release for custom drag or hold interactions.| Goal | Preferred | Alternative ||------|-----------|-------------|-| Click a button | `click @ref` | `mouse-click --xy` if AX fails |+| Click a button | `click @ref` | `agent-desktop --headed mouse-click --xy X,Y` if physical interaction is intended || Fill a text field | `clear @ref` then `type @ref "text"` | `set-value @ref "text"` for direct replacement |-| Clear then type | `clear @ref` then `type @ref "new"` | `mouse-click --xy X,Y --count 3` only when physical selection is intended |+| Clear then type | `clear @ref` then `type @ref "new"` | `agent-desktop --headed mouse-click --xy X,Y --count 3` only when physical selection is intended || Toggle a checkbox | `check @ref` / `uncheck @ref` | `toggle @ref` if you don't know current state |-| Open context menu | `right-click @ref` | `mouse-click --xy --button right` when physical interaction is intended |+| Open context menu | `right-click @ref` | `agent-desktop --headed mouse-click --xy X,Y --button right` when physical interaction is intended || Select dropdown option | `select @ref "Option"` | `snapshot --surface menu` after an explicitly opened menu || Navigate a form | `press tab` between fields | `focus @ref` to jump directly || Copy text | `press cmd+c --app "App"` | `clipboard-set` to set directly |diff --git a/skills/agent-desktop/references/commands-observation.md b/skills/agent-desktop/references/commands-observation.mdindex 3a23f033a..6d42a1e24 100644--- a/skills/agent-desktop/references/commands-observation.md+++ b/skills/agent-desktop/references/commands-observation.md@@ -118,7 +118,7 @@ agent-desktop find --app "App" --role button --limit 20| Flag | Description ||------|-------------|| `--app` | Application name |-| `--role` | Accessibility role: button, textfield, checkbox, link, menuitem, tab, slider, combobox, treeitem, cell |+| `--role` | Role to match against the live tree (button, textfield, checkbox, scrollarea, window, ...). Case-insensitive; `textarea`/`textbox`/`searchfield` fold to `textfield`. When a role filter matches nothing, the response carries `roles_present` — the roles actually in the searched tree — so you can tell "none on screen" from a wrong role name and retry || `--name` | Accessible name or label || `--value` | Current value || `--text` | Fuzzy match across name, value, title, and description |@@ -140,6 +140,17 @@ agent-desktop find --app "App" --role button --limit 20}```+**Output (no match — `roles_present` hint):** when a `--role` filter matches nothing, `roles_present` lists the roles actually in the searched tree so you can tell a wrong role name from "none on screen"; this applies to all non-count selection modes — an empty match list, or a `--first`/`--last`/`--nth` miss — whenever a role filter was active, making it a role-vocabulary hint for retries.+```json+{+ "data": {+ "matches": [],+ "count": 0,+ "roles_present": ["button", "cell", "checkbox", "scrollarea", "statictext"]+ }+}+```+## getRead a specific property from an element.diff --git a/skills/agent-desktop/references/commands-system.md b/skills/agent-desktop/references/commands-system.mdindex 35577d0d9..08f9068c4 100644--- a/skills/agent-desktop/references/commands-system.md+++ b/skills/agent-desktop/references/commands-system.md@@ -20,7 +20,10 @@ Launches an application by name or bundle ID and waits until its window is visibagent-desktop close-app "TextEdit"agent-desktop close-app "TextEdit" --force```-Quits an application gracefully. Use `--force` to kill the process.+Requests an application quit. A graceful quit is asynchronous — the app may show an unsaved-changes dialog or refuse — so the response reports only what was guaranteed, never a termination it cannot confirm without blocking:++- Graceful: `{ "app": "TextEdit", "method": "graceful", "requested": true }`. The quit was sent. To confirm it actually closed, observe with `list-apps` or `wait --window`; if a save dialog appears, `snapshot` it and click the choice (`find --role button --name Delete`).+- `--force`: `{ "app": "TextEdit", "method": "force", "requested": true, "closed": true }`. Sends SIGTERM to matching app processes, escalates survivors to SIGKILL, and returns success only after termination is verified.### list-apps```bash@@ -138,7 +141,7 @@ index-only behavior for callers that reconcile themselves.agent-desktop wait --notification --app "App" --timeout 10000agent-desktop wait --notification --text "build passed" --timeout 15000```-Blocks until a new notification appears (detects index-diff from previous state). Supports `--app` and `--text` filters.+Blocks until a new notification appears (detects index-diff from a baseline captured at wait start). Supports `--app` and `--text` filters. Transient Notification Center errors (timeouts, element-not-found) are retried within the `--timeout` budget for both the baseline capture and polling; permanent errors (for example `PERM_DENIED`) fail immediately. Timeout errors include a `last_error` detail with the most recent transient failure.## Clipboard@@ -169,8 +172,14 @@ Pauses for N milliseconds. Use between actions that need time to settle.### wait (element)```bashagent-desktop wait --element @e5 --snapshot <snapshot_id> --timeout 5000 --app "App"+agent-desktop wait --element @e5 --predicate actionable --timeout 5000+agent-desktop wait --element @e5 --predicate actionable --action type --timeout 5000+agent-desktop wait --element @e5 --predicate value --value "Done" --timeout 5000```Blocks until the element ref appears in the accessibility tree. Useful after triggering UI changes.+When `--snapshot` is omitted, the command polls the caller's latest session refmap and refreshes it on the built-in debounce. When `--snapshot` is passed, it resolves that pinned refmap directly. Element resolution is capped by the remaining `--timeout`, and timeout errors include the last observed predicate/actionability state.++`--predicate actionable` checks readiness for a specific action via `--action` (`click` default, `type`, `set-value`, `clear`). Use `--action type` before a wait-then-type flow: the editability check only runs for the editing actions, so the default click check can report ready on a field that cannot accept text.### wait (window)```bash@@ -182,7 +191,7 @@ Blocks until a window with the given title appears.```bashagent-desktop wait --text "Loading complete" --app "Safari" --timeout 5000```-Blocks until the specified text appears anywhere in the app's accessibility tree.+Blocks until the specified text appears anywhere in the app's accessibility tree. The success body includes `count` only when `--count` is passed; without it, matching stops at the first hit and no count is reported.### wait (menu)```bash@@ -201,6 +210,10 @@ Blocks until the menu surface is dismissed.| (positional) | | Milliseconds to pause || `--element` | | Ref to wait for || `--snapshot` | latest | Snapshot ID for `--element` waits |+| `--predicate` | exists | Element predicate: `exists`, `enabled`, `visible`, `actionable`, `value` |+| `--value` | | Expected text for `--predicate value` |+| `--action` | click | Action checked by `--predicate actionable`: `click`, `type`, `set-value`, `clear` |+| `--count` | | Expected match count for `--text` waits || `--window` | | Window title to wait for || `--text` | | Text to wait for; with `--notification`, filters notification title/body || `--menu` | false | Wait for menu surface to open |@@ -215,11 +228,14 @@ Blocks until the menu surface is dismissed.```bashagent-desktop batch '[{"command":"click","args":{"ref_id":"@e1","snapshot":"<snapshot_id>"}},{"command":"wait","args":{"ms":500}},{"command":"click","args":{"ref_id":"@e2","snapshot":"<snapshot_id>"}}]'agent-desktop batch '[...]' --stop-on-error+agent-desktop --session run-a batch '[{"command":"status","session":"run-b","args":{}}]'```Execute multiple commands in sequence from a JSON array. Each entry has `command` (string) and `args` (object). Use `args`, not `params`. For ref-consuming commands, pass the output `snapshot_id` as the `snapshot` field.Batch uses the same typed `Commands` enum, command policy preflight, permission report, and dispatch path as the CLI. Unknown fields are rejected instead of being silently ignored. Nested `batch` is rejected.+Each entry may include `"session": "id"` beside `command` and `args`. If omitted, the entry inherits the top-level `--session`. Use per-entry sessions only when intentionally inspecting or coordinating separate agent runs. Top-level `--trace` is inherited by every entry — including entries with a `session` override — so one JSONL file captures the whole batch.+| Flag | Default | Description ||------|---------|-------------|| `--stop-on-error` | false | Halt on first failed command |@@ -229,7 +245,8 @@ Batch uses the same typed `Commands` enum, command policy preflight, permission[{ "command": "click", "args": { "ref_id": "@e1", "snapshot": "<snapshot_id>" } },{ "command": "wait", "args": { "ms": 500 } },- { "command": "type", "args": { "ref_id": "@e2", "snapshot": "<snapshot_id>", "text": "hello" } }+ { "command": "type", "args": { "ref_id": "@e2", "snapshot": "<snapshot_id>", "text": "hello" } },+ { "command": "status", "session": "other-agent", "args": {} }]```diff --git a/skills/agent-desktop/references/macos.md b/skills/agent-desktop/references/macos.mdindex 986c1e64f..99e5eca13 100644--- a/skills/agent-desktop/references/macos.md+++ b/skills/agent-desktop/references/macos.md@@ -80,10 +80,10 @@ The default activation-chain deadline is 10 seconds. Set `AGENT_DESKTOP_CHAIN_TIRef commands use `ActionRequest { action, policy }`. The default policy forbids focus stealing, cursor movement, keyboard synthesis, and pasteboard insertion. macOS actions split semantic AX steps from explicit physical/headed paths:- `click`, `right-click`, `scroll`, `set-value`, `clear`, `select`, `toggle`, `check`, `uncheck`, `expand`, `collapse`, and `scroll-to` try AX-first semantics and fail clearly when the headless path is unavailable.-- `type` mutates a settable AX text value in headless mode. It does not call `ensure_app_focused` or use the pasteboard in the default CLI path.+- `type` uses focus fallback in the CLI/ref-action path. It may focus the target field, never moves the cursor, and can use the pasteboard for non-ASCII insertion. Use `set-value` for pure headless value mutation when supported.- `focus`, `press`, `hover`, `drag`, and `mouse-*` are explicit physical/focus/cursor commands.-- FFI callers can opt into focus-only or physical policy explicitly; CLI ref commands do not do that implicitly.-- Explicit focus/physical policy can use the clipboard briefly for non-ASCII text insertion. Keep the default headless path or use `set-value` for sensitive text when possible.+- FFI ref-action callers should use focus fallback for `type` to match CLI behavior; direct-handle `ad_execute_action` is lower-level and defaults to headless.+- Explicit focus/physical policy can use the clipboard briefly for non-ASCII text insertion. Use `set-value` for sensitive text when possible.- If a command would need a forbidden physical path, it returns a structured error with a recovery hint.### Surfaces@@ -198,7 +198,7 @@ The UI changed between your snapshot and action, or the element could not be re-"code": "POLICY_DENIED"```-The semantic AX path could not complete and a physical/headed path was blocked by policy. Use an explicit physical command only when that is intended, for example `focus`, `press`, `hover`, `drag`, or `mouse-click`.+The semantic AX path could not complete and a physical/headed path was blocked by policy. Use `--headed` only when physical interaction is intended, for example `agent-desktop --headed hover @ref`, `agent-desktop --headed drag ...`, or `agent-desktop --headed mouse-click --xy x,y`.### ACTION_FAILED@@ -213,7 +213,7 @@ The accessibility action was rejected. This can happen when:**Try:**1. Check `is @ref --property enabled` first-2. If physical interaction is intended, get bounds with `get @ref --property bounds`, then use `mouse-click --xy x,y`+2. If physical interaction is intended, get bounds with `get @ref --property bounds`, then use `agent-desktop --headed mouse-click --xy x,y`3. Use keyboard explicitly: `focus @ref` then `press return`### APP_NOT_FOUND@@ -241,7 +241,7 @@ After `right-click @ref`, inspect `menu` first. If it is absent and `menu_probe.1. The element may not support context menus2. If the target is a combo box or menu button, use `select @ref "Option"` instead3. Run `list-surfaces --app "App"` to confirm whether a menu surface exists-4. If physical interaction is intended, try `mouse-click --xy x,y --button right` with coordinates from `get @ref --property bounds`+4. If physical interaction is intended, try `agent-desktop --headed mouse-click --xy x,y --button right` with coordinates from `get @ref --property bounds`## macOS-Specific Behaviordiff --git a/skills/agent-desktop/references/workflows.md b/skills/agent-desktop/references/workflows.mdindex 9b920add2..86faf0330 100644--- a/skills/agent-desktop/references/workflows.md+++ b/skills/agent-desktop/references/workflows.md@@ -186,13 +186,13 @@ agent-desktop clipboard-get```bash# Between elements (by ref)-agent-desktop drag --from @e3 --to @e8+agent-desktop --headed drag --from @e3 --to @e8# Between coordinates-agent-desktop drag --from-xy 100,200 --to-xy 500,400+agent-desktop --headed drag --from-xy 100,200 --to-xy 500,400# Mixed: element to coordinates-agent-desktop drag --from @e3 --to-xy 500,400 --duration 500+agent-desktop --headed drag --from @e3 --to-xy 500,400 --duration 500```## Pattern: Wait for Async UIdiff --git a/src/Cargo.toml b/src/Cargo.tomlindex e561265fa..6487fe5f8 100644--- a/src/Cargo.toml+++ b/src/Cargo.toml@@ -30,5 +30,9 @@ path = "main.rs"name = "snapshot_test"path = "tests/snapshot_test.rs"+[[test]]+name = "conformance"+path = "tests/conformance.rs"+[lints]workspace = truediff --git a/src/batch.rs b/src/batch/mod.rssimilarity index 93%rename from src/batch.rsrename to src/batch/mod.rsindex 7c55f2672..cf9a841c7 100644--- a/src/batch.rs+++ b/src/batch/mod.rs@@ -2,6 +2,7 @@ use agent_desktop_core::{PermissionReport,adapter::PlatformAdapter,commands::batch::BatchCommand,+ context::CommandContext,error::AppError,output::{ENVELOPE_VERSION, ErrorPayload},};@@ -11,23 +12,27 @@ use serde_json::{Map, Value, json};use crate::{cli::Commands,- cli_args_skills::{SkillsAction, SkillsArgs, SkillsGetArgs},- cli_args_system::BatchArgs,+ cli_args::{+ skills::{SkillsAction, SkillsArgs, SkillsGetArgs},+ system::BatchArgs,+ },};pub(crate) fn execute(args: BatchArgs,adapter: &dyn PlatformAdapter,permission_report: &PermissionReport,+ context: &CommandContext,) -> Result<Value, AppError> {let commands = agent_desktop_core::commands::batch::parse_commands(&args.commands_json)?;let mut results = Vec::new();for item in commands {let command = item.command.clone();+ let item_context = context.for_batch_item(item.session.clone())?;let result = parse_command(item).and_then(|typed| {crate::command_policy::preflight(&typed, permission_report)?;- crate::dispatch::dispatch(typed, adapter, permission_report)+ crate::dispatch::dispatch(typed, adapter, permission_report, &item_context)});let ok = result.is_ok();results.push(batch_entry(&command, result));@@ -113,22 +118,12 @@ fn batch_entry(command: &str, result: Result<Value, AppError>) -> Value {json!({ "version": ENVELOPE_VERSION, "ok": true, "command": command, "data": data })}Err(err) => {- json!({ "version": ENVELOPE_VERSION, "ok": false, "command": command, "error": error_payload(err) })+ let error = ErrorPayload::from_app_error(&err);+ json!({ "version": ENVELOPE_VERSION, "ok": false, "command": command, "error": error })}}}-fn error_payload(err: AppError) -> ErrorPayload {- let mut payload = ErrorPayload::new(err.code(), err.to_string());- if let Some(suggestion) = err.suggestion() {- payload = payload.with_suggestion(suggestion);- }- if let AppError::Adapter(adapter_error) = err {- payload.platform_detail = adapter_error.platform_detail;- }- payload-}-fn decode<T>(command: &str, args: Value) -> Result<T, AppError>whereT: DeserializeOwned,@@ -191,5 +186,4 @@ fn parse_skills(args: Value) -> Result<SkillsArgs, AppError> {}#[cfg(test)]-#[path = "batch_tests.rs"]mod tests;diff --git a/src/batch_tests.rs b/src/batch/tests.rssimilarity index 81%rename from src/batch_tests.rsrename to src/batch/tests.rsindex 2d6bbccae..348bc85a1 100644--- a/src/batch_tests.rs+++ b/src/batch/tests.rs@@ -9,10 +9,21 @@ impl PlatformAdapter for NoopAdapter {}fn item(command: &str, args: Value) -> BatchCommand {BatchCommand {command: command.to_string(),+ session: None,args,}}+#[test]+fn parses_optional_batch_session_scope() {+ let commands = agent_desktop_core::commands::batch::parse_commands(+ r#"[{"command":"status","session":"agent-a","args":{}}]"#,+ )+ .unwrap();++ assert_eq!(commands[0].session.as_deref(), Some("agent-a"));+}+#[test]fn parses_ref_command_into_cli_enum() {let command =@@ -52,6 +63,17 @@ fn rejects_unknown_batch_args() {assert_eq!(err.code(), "INVALID_ARGS");}+#[test]+fn rejects_unknown_wait_batch_args_after_flattening() {+ let err = parse_command(item(+ "wait",+ serde_json::json!({ "ms": 1, "unexpected": true }),+ ))+ .expect_err("unknown wait field is rejected");++ assert_eq!(err.code(), "INVALID_ARGS");+}+#[test]fn stop_on_error_halts_after_first_failure() {let args = BatchArgs {@@ -63,7 +85,13 @@ fn stop_on_error_halts_after_first_failure() {stop_on_error: true,};- let value = execute(args, &NoopAdapter, &PermissionReport::default()).unwrap();+ let value = execute(+ args,+ &NoopAdapter,+ &PermissionReport::default(),+ &agent_desktop_core::CommandContext::default(),+ )+ .unwrap();let results = value["results"].as_array().unwrap();assert_eq!(results.len(), 1);diff --git a/src/command_contract_tests.rs b/src/cli/contract_tests.rssimilarity index 94%rename from src/command_contract_tests.rsrename to src/cli/contract_tests.rsindex b12248e90..6bb5b2306 100644--- a/src/command_contract_tests.rs+++ b/src/cli/contract_tests.rs@@ -3,7 +3,19 @@ use clap::CommandFactory;use std::collections::BTreeSet;use std::path::{Path, PathBuf};-const NON_COMMAND_MODULES: &[&str] = &["helpers", "mod"];+const NON_COMMAND_MODULES: &[&str] = &[+ "helpers",+ "helpers_test_support",+ "mod",+ "point_resolve",+ "wait_element",+ "wait_latest_ref_cache",+ "wait_mode",+ "wait_predicate",+ "wait_test_support",+ "wait_text_match",+ "wait_timeout",+];const COMMAND_SPECIFIC_TESTS: &[&str] = &["find",diff --git a/src/help_after.txt b/src/cli/help_after.txtsimilarity index 68%rename from src/help_after.txtrename to src/cli/help_after.txtindex 73b6c8d74..32957ce11 100644--- a/src/help_after.txt+++ b/src/cli/help_after.txt@@ -30,16 +30,16 @@ KEYBOARDkey-up <combo> Release a held key or modifierMOUSE- hover <ref|--xy> Move cursor to element or coordinates- drag Drag from one element/point to another- mouse-move --xy x,y Move cursor to absolute coordinates- mouse-click --xy x,y Click at coordinates (--button, --count)- mouse-down --xy x,y Press mouse button at coordinates- mouse-up --xy x,y Release mouse button at coordinates+ hover <ref|--xy> Move cursor to element or coordinates (requires --headed)+ drag Drag from one element/point to another (requires --headed)+ mouse-move --xy x,y Move cursor to absolute coordinates (requires --headed)+ mouse-click --xy x,y Click at coordinates (--button, --count; requires --headed)+ mouse-down --xy x,y Press mouse button at coordinates (requires --headed)+ mouse-up --xy x,y Release mouse button at coordinates (requires --headed)APP & WINDOWlaunch <app> Launch app and wait until window is visible- close-app <app> Quit app gracefully (--force to kill)+ close-app <app> Quit app gracefully (--force to terminate)list-windows All visible windows (--app to filter)list-apps All running GUI applications (--app substring filter)focus-window Bring window to front and confirm focus@@ -63,6 +63,8 @@ CLIPBOARDWAITwait [ms] Pause for N millisecondswait --element <ref> Block until element appears (--timeout ms)+ wait --element <ref> --predicate actionable Block until element is actionable+ wait --element <ref> --predicate value --value <text> Block until value matcheswait --element <ref> --snapshot <snapshot_id> Wait against a specific snapshot refmapwait --window <title> Block until window appearswait --text <text> Block until text appears in app@@ -78,12 +80,21 @@ SYSTEMBATCHbatch <json> Run commands from a JSON array (--stop-on-error)+ batch items may set "session": "id" to override the inherited --sessionREF IDssnapshot assigns @e1, @e2, ... to interactive elements in depth-first order.Use a ref wherever <ref> appears. Refs are snapshot-scoped. Pass- --snapshot <snapshot_id> to pin a command to a known snapshot; when omitted,- ref commands use the latest saved snapshot. Run snapshot again after UI changes.+ --snapshot <snapshot_id> to pin a command to a known snapshot; explicit+ snapshot IDs do not require --session. When --snapshot is omitted, ref+ commands use the active session's latest saved snapshot. Run snapshot again+ after UI changes. Use --session <id> as a shared latest-snapshot namespace+ for concurrent agents.+ Ref actions use strict resolution: stale targets return STALE_REF; duplicate+ plausible targets return AMBIGUOUS_TARGET instead of choosing arbitrarily.+ Ref actions run actionability checks before dispatch. Use --trace <path> to+ write JSONL diagnostics outside stdout; --trace-strict fails on trace setup+ and pre-action writes. Post-action success traces are best-effort.KEY COMBOSSingle keys: return, escape, tab, space, delete, up, down, left, right@@ -93,17 +104,30 @@ KEY COMBOSEXAMPLESagent-desktop skills get desktop --full Load the primary skill (start here)- agent-desktop snapshot --app "System Settings" -i+ agent-desktop --session task-1 snapshot --app "System Settings" -iagent-desktop find --role button --name "OK"agent-desktop find --role button --limit 20- agent-desktop click @e5- agent-desktop check @e3- agent-desktop type @e2 "[email protected]"+ agent-desktop click @e5 --snapshot <snapshot_id>+ agent-desktop check @e3 --snapshot <snapshot_id>+ agent-desktop type @e2 --snapshot <snapshot_id> "[email protected]"agent-desktop press cmd+z- agent-desktop drag --from @e1 --to @e5- agent-desktop hover @e5+ agent-desktop --headed drag --from @e1 --to @e5+ agent-desktop --headed hover @e5agent-desktop minimize --app TextEditagent-desktop resize-window --app TextEdit --width 800 --height 600- agent-desktop mouse-click --xy 500,300+ agent-desktop --headed mouse-click --xy 500,300agent-desktop wait --text "Loading complete" --app Safari --timeout 5000+ agent-desktop wait --element @e5 --predicate actionable --timeout 5000+ agent-desktop --session run-a --trace /tmp/ad.jsonl click @e5agent-desktop batch '[{"command":"click","args":{"ref_id":"@e1","snapshot":"<snapshot_id>"}}]'+ agent-desktop --session run-a batch '[{"command":"status","session":"run-b","args":{}}]'++AGENT LOOP+ 1. Use `skills get desktop --full` when you need detailed guidance.+ 2. Use `--session <id>` when another agent or task may also run commands.+ 3. Observe with `snapshot -i` or `snapshot --skeleton -i --compact`.+ 4. Keep `snapshot_id`; pass it to every ref-consuming action.+ 5. Use `wait --predicate actionable`, `wait --text`, or `wait --window`+ instead of sleeping blindly.+ 6. On STALE_REF or AMBIGUOUS_TARGET, snapshot again and choose a fresh ref.+ 7. Add `--trace <path>` when diagnosing stale, ambiguous, or actionability failures.diff --git a/src/help_before.txt b/src/cli/help_before.txtsimilarity index 59%rename from src/help_before.txtrename to src/cli/help_before.txtindex e7b0f49a3..80d868dd7 100644--- a/src/help_before.txt+++ b/src/cli/help_before.txt@@ -2,11 +2,11 @@ For AI agents — read this first:agent-desktop skills get desktop --fullBundled skill docs travel with the binary, so they always match this- exact version. They cover the snapshot/ref loop, JSON envelope contract,- error codes with recovery hints, and copy-paste patterns for forms,- menus, dialogs, and async waits. Specialized skills go deeper on macOS- internals (TCC, AX API, surfaces, Notification Center) and on embedding- agent-desktop through its C ABI.+ exact version. They cover the snapshot-scoped ref loop, shared sessions,+ actionability, trace JSONL, error codes with recovery hints, and+ copy-paste patterns for forms, menus, dialogs, and async waits.+ Specialized skills go deeper on macOS internals (TCC, AX API, surfaces,+ Notification Center) and on embedding agent-desktop through its C ABI.skills List bundled skills with summariesskills get desktop Primary guide — overview + the observe-act loopdiff --git a/src/cli.rs b/src/cli/mod.rssimilarity index 83%rename from src/cli.rsrename to src/cli/mod.rsindex 223c5e0f1..c71aa8886 100644--- a/src/cli.rs+++ b/src/cli/mod.rs@@ -1,21 +1,22 @@use clap::{Parser, Subcommand};+use std::path::PathBuf;use crate::cli_args::{FindArgs, GetArgs, IsArgs, ListSurfacesArgs, RefArgs, ScreenshotArgs, SnapshotArgs,-};-use crate::cli_args_actions::{- DragCliArgs, HoverArgs, KeyComboArgs, MouseClickArgs, MouseMoveArgs, MousePointArgs, PressArgs,- ScrollArgs, SelectArgs, SetValueArgs, TypeArgs,-};-use crate::cli_args_notifications::{- DismissAllNotificationsCliArgs, DismissNotificationCliArgs, ListNotificationsCliArgs,- NotificationActionCliArgs,-};-use crate::cli_args_skills::SkillsArgs;-use crate::cli_args_system::{- AppRefArgs, BatchArgs, ClipboardSetArgs, CloseAppArgs, FocusWindowArgs, LaunchArgs,- ListAppsArgs, ListWindowsArgs, MoveWindowCliArgs, PermissionsArgs, ResizeWindowCliArgs,- VersionArgs, WaitArgs,+ actions::{+ DragCliArgs, HoverArgs, KeyComboArgs, MouseClickArgs, MouseMoveArgs, MousePointArgs,+ PressArgs, ScrollArgs, SelectArgs, SetValueArgs, TypeArgs,+ },+ notifications::{+ DismissAllNotificationsCliArgs, DismissNotificationCliArgs, ListNotificationsCliArgs,+ NotificationActionCliArgs,+ },+ skills::SkillsArgs,+ system::{+ AppRefArgs, BatchArgs, ClipboardSetArgs, CloseAppArgs, FocusWindowArgs, LaunchArgs,+ ListAppsArgs, ListWindowsArgs, MoveWindowCliArgs, PermissionsArgs, ResizeWindowCliArgs,+ VersionArgs, WaitArgs,+ },};const BEFORE_HELP: &str = include_str!("help_before.txt");@@ -38,6 +39,34 @@ pub(crate) struct Cli {)]pub verbose: bool,+ #[arg(+ long,+ global = true,+ help = "Select the latest-snapshot namespace; explicit --snapshot IDs do not require it"+ )]+ pub session: Option<String>,++ #[arg(+ long,+ global = true,+ help = "Append reliability trace JSONL to this path"+ )]+ pub trace: Option<PathBuf>,++ #[arg(+ long,+ global = true,+ help = "Fail on trace setup/pre-action write errors"+ )]+ pub trace_strict: bool,++ #[arg(+ long,+ global = true,+ help = "Permit cursor movement and focus stealing for physical input commands and fallbacks. Default is headless (AX-only, no cursor)."+ )]+ pub headed: bool,+#[command(subcommand)]pub command: Option<Commands>,}@@ -94,21 +123,21 @@ pub(crate) enum Commands {KeyDown(KeyComboArgs),#[command(about = "Release a held key or modifier")]KeyUp(KeyComboArgs),- #[command(about = "Move cursor to element center or coordinates")]+ #[command(about = "Move cursor to element center or coordinates (requires --headed)")]Hover(HoverArgs),- #[command(about = "Drag from one element or point to another")]+ #[command(about = "Drag from one element or point to another (requires --headed)")]Drag(DragCliArgs),- #[command(about = "Move cursor to absolute screen coordinates")]+ #[command(about = "Move cursor to absolute screen coordinates (requires --headed)")]MouseMove(MouseMoveArgs),- #[command(about = "Click at absolute screen coordinates")]+ #[command(about = "Click at absolute screen coordinates (requires --headed)")]MouseClick(MouseClickArgs),- #[command(about = "Press mouse button at coordinates (without releasing)")]+ #[command(about = "Press mouse button at coordinates (requires --headed)")]MouseDown(MousePointArgs),- #[command(about = "Release mouse button at coordinates")]+ #[command(about = "Release mouse button at coordinates (requires --headed)")]MouseUp(MousePointArgs),#[command(about = "Launch application and wait until its window is visible")]Launch(LaunchArgs),- #[command(about = "Quit an application gracefully (--force to kill)")]+ #[command(about = "Quit an application gracefully (--force to terminate)")]CloseApp(CloseAppArgs),#[command(about = "List all visible windows (--app to filter by application)")]ListWindows(ListWindowsArgs),@@ -218,3 +247,7 @@ impl Commands {}}}++#[cfg(test)]+#[path = "contract_tests.rs"]+mod contract_tests;diff --git a/src/cli_args_actions.rs b/src/cli_args/actions.rssimilarity index 74%rename from src/cli_args_actions.rsrename to src/cli_args/actions.rsindex c2f38b324..b18184087 100644--- a/src/cli_args_actions.rs+++ b/src/cli_args/actions.rs@@ -25,7 +25,7 @@ pub(crate) struct TypeArgs {#[arg(long,value_name = "SNAPSHOT_ID",- help = "Snapshot ID returned by snapshot; omit to use latest"+ help = "Snapshot ID returned by snapshot; omit to use active session latest")]pub snapshot: Option<String>,#[arg(value_name = "TEXT", allow_hyphen_values = true, help = "Text to type")]@@ -40,7 +40,7 @@ pub(crate) struct SetValueArgs {#[arg(long,value_name = "SNAPSHOT_ID",- help = "Snapshot ID returned by snapshot; omit to use latest"+ help = "Snapshot ID returned by snapshot; omit to use active session latest")]pub snapshot: Option<String>,#[arg(@@ -59,7 +59,7 @@ pub(crate) struct SelectArgs {#[arg(long,value_name = "SNAPSHOT_ID",- help = "Snapshot ID returned by snapshot; omit to use latest"+ help = "Snapshot ID returned by snapshot; omit to use active session latest")]pub snapshot: Option<String>,#[arg(value_name = "VALUE", help = "Option to select")]@@ -74,7 +74,7 @@ pub(crate) struct ScrollArgs {#[arg(long,value_name = "SNAPSHOT_ID",- help = "Snapshot ID returned by snapshot; omit to use latest"+ help = "Snapshot ID returned by snapshot; omit to use active session latest")]pub snapshot: Option<String>,#[arg(@@ -114,15 +114,18 @@ pub(crate) struct KeyComboArgs {#[derive(Parser, Debug, Deserialize)]#[serde(deny_unknown_fields)]pub(crate) struct HoverArgs {- #[arg(value_name = "REF", help = "Element ref to hover over")]+ #[arg(+ value_name = "REF",+ help = "Element ref to hover over; requires --headed"+ )]pub ref_id: Option<String>,#[arg(long,value_name = "SNAPSHOT_ID",- help = "Snapshot ID returned by snapshot; omit to use latest"+ help = "Snapshot ID returned by snapshot; omit to use active session latest")]pub snapshot: Option<String>,- #[arg(long, help = "Absolute coordinates as x,y")]+ #[arg(long, help = "Absolute coordinates as x,y; requires --headed")]pub xy: Option<String>,#[arg(long, help = "Hold hover position for N milliseconds")]pub duration: Option<u64>,@@ -131,35 +134,49 @@ pub(crate) struct HoverArgs {#[derive(Parser, Debug, Deserialize)]#[serde(deny_unknown_fields)]pub(crate) struct DragCliArgs {- #[arg(long, help = "Source element ref")]+ #[arg(long, help = "Source element ref; requires --headed")]pub from: Option<String>,- #[arg(long, name = "from-xy", help = "Source coordinates as x,y")]+ #[arg(+ long,+ name = "from-xy",+ help = "Source coordinates as x,y; requires --headed"+ )]pub from_xy: Option<String>,- #[arg(long, help = "Destination element ref")]+ #[arg(long, help = "Destination element ref; requires --headed")]pub to: Option<String>,- #[arg(long, name = "to-xy", help = "Destination coordinates as x,y")]+ #[arg(+ long,+ name = "to-xy",+ help = "Destination coordinates as x,y; requires --headed"+ )]pub to_xy: Option<String>,#[arg(long,value_name = "SNAPSHOT_ID",- help = "Snapshot ID returned by snapshot; omit to use latest"+ help = "Snapshot ID returned by snapshot; omit to use active session latest")]pub snapshot: Option<String>,#[arg(long, help = "Drag duration in milliseconds")]pub duration: Option<u64>,+ #[arg(+ long = "drop-delay",+ value_name = "MS",+ help = "Hold over the destination this many ms before releasing, so the drop target activates (macOS); default 500"+ )]+ pub drop_delay: Option<u64>,}#[derive(Parser, Debug, Deserialize)]#[serde(deny_unknown_fields)]pub(crate) struct MouseMoveArgs {- #[arg(long, help = "Absolute coordinates as x,y")]+ #[arg(long, help = "Absolute coordinates as x,y; requires --headed")]pub xy: String,}#[derive(Parser, Debug, Deserialize)]#[serde(deny_unknown_fields)]pub(crate) struct MouseClickArgs {- #[arg(long, help = "Absolute coordinates as x,y")]+ #[arg(long, help = "Absolute coordinates as x,y; requires --headed")]pub xy: String,#[arg(long,@@ -176,7 +193,7 @@ pub(crate) struct MouseClickArgs {#[derive(Parser, Debug, Deserialize)]#[serde(deny_unknown_fields)]pub(crate) struct MousePointArgs {- #[arg(long, help = "Absolute coordinates as x,y")]+ #[arg(long, help = "Absolute coordinates as x,y; requires --headed")]pub xy: String,#[arg(long,diff --git a/src/cli_args.rs b/src/cli_args/mod.rssimilarity index 94%rename from src/cli_args.rsrename to src/cli_args/mod.rsindex 2fcf1e10e..5b8b9717e 100644--- a/src/cli_args.rs+++ b/src/cli_args/mod.rs@@ -1,6 +1,11 @@use clap::{Parser, ValueEnum};use serde::Deserialize;+pub(crate) mod actions;+pub(crate) mod notifications;+pub(crate) mod skills;+pub(crate) mod system;+fn default_max_depth() -> u8 {10}@@ -165,7 +170,7 @@ pub(crate) struct GetArgs {#[arg(long,value_name = "SNAPSHOT_ID",- help = "Snapshot ID returned by snapshot; omit to use latest"+ help = "Snapshot ID returned by snapshot; omit to use active session latest")]pub snapshot: Option<String>,#[arg(@@ -185,7 +190,7 @@ pub(crate) struct IsArgs {#[arg(long,value_name = "SNAPSHOT_ID",- help = "Snapshot ID returned by snapshot; omit to use latest"+ help = "Snapshot ID returned by snapshot; omit to use active session latest")]pub snapshot: Option<String>,#[arg(@@ -205,7 +210,7 @@ pub(crate) struct RefArgs {#[arg(long = "snapshot",value_name = "SNAPSHOT_ID",- help = "Snapshot ID returned by snapshot; omit to use latest"+ help = "Snapshot ID returned by snapshot; omit to use active session latest")]#[serde(rename = "snapshot", alias = "snapshot_id")]pub snapshot_id: Option<String>,diff --git a/src/cli_args_notifications.rs b/src/cli_args/notifications.rssimilarity index 100%rename from src/cli_args_notifications.rsrename to src/cli_args/notifications.rsdiff --git a/src/cli_args_skills.rs b/src/cli_args/skills.rssimilarity index 100%rename from src/cli_args_skills.rsrename to src/cli_args/skills.rsdiff --git a/src/cli_args_system.rs b/src/cli_args/system.rssimilarity index 78%rename from src/cli_args_system.rsrename to src/cli_args/system.rsindex 8f8e19aa2..283f38bcf 100644--- a/src/cli_args_system.rs+++ b/src/cli_args/system.rs@@ -1,4 +1,4 @@-use clap::Parser;+use clap::{Args, Parser};use serde::Deserialize;fn default_launch_timeout() -> u64 {@@ -28,7 +28,10 @@ pub(crate) struct LaunchArgs {pub(crate) struct CloseAppArgs {#[arg(value_name = "APP", help = "Application name")]pub app: String,- #[arg(long, help = "Force-kill the process instead of quitting gracefully")]+ #[arg(+ long,+ help = "Terminate matching app processes instead of quitting gracefully"+ )]#[serde(default)]pub force: bool,}@@ -97,16 +100,30 @@ pub(crate) struct ClipboardSetArgs {#[derive(Parser, Debug, Deserialize)]#[serde(deny_unknown_fields)]pub(crate) struct WaitArgs {+ #[command(flatten)]+ #[serde(flatten)]+ pub mode: WaitModeArgs,+ #[command(flatten)]+ #[serde(flatten)]+ pub predicate: WaitPredicateArgs,+ #[arg(+ long,+ default_value = "30000",+ help = "Timeout in milliseconds for element/window/text waits"+ )]+ #[serde(default = "default_wait_timeout")]+ pub timeout: u64,+ #[arg(long, help = "Scope element, window, or text wait to this application")]+ pub app: Option<String>,+}++#[derive(Args, Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub(crate) struct WaitModeArgs {#[arg(value_name = "MS", help = "Milliseconds to pause")]pub ms: Option<u64>,#[arg(long, help = "Block until this element ref appears in the tree")]pub element: Option<String>,- #[arg(- long,- value_name = "SNAPSHOT_ID",- help = "Snapshot ID returned by snapshot for --element waits; omit to use latest"- )]- pub snapshot: Option<String>,#[arg(long, help = "Block until a window with this title appears")]pub window: Option<String>,#[arg(@@ -114,13 +131,6 @@ pub(crate) struct WaitArgs {help = "Block until text appears in the app's accessibility tree; with --notification, filter notification text")]pub text: Option<String>,- #[arg(- long,- default_value = "30000",- help = "Timeout in milliseconds for element/window/text waits"- )]- #[serde(default = "default_wait_timeout")]- pub timeout: u64,#[arg(long, help = "Block until a menu surface is open")]#[serde(default)]pub menu: bool,@@ -130,8 +140,41 @@ pub(crate) struct WaitArgs {#[arg(long, help = "Block until a new notification arrives")]#[serde(default)]pub notification: bool,- #[arg(long, help = "Scope element, window, or text wait to this application")]- pub app: Option<String>,+}++#[derive(Args, Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub(crate) struct WaitPredicateArgs {+ #[arg(+ long,+ value_name = "SNAPSHOT_ID",+ help = "Snapshot ID for --element waits; omit to use active session latest"+ )]+ pub snapshot: Option<String>,+ #[arg(+ long,+ value_name = "PREDICATE",+ help = "Element wait predicate: exists, enabled, visible, actionable, or value"+ )]+ pub predicate: Option<String>,+ #[arg(+ long,+ value_name = "VALUE",+ help = "Expected value for --predicate value"+ )]+ pub value: Option<String>,+ #[arg(+ long,+ value_name = "ACTION",+ help = "Action for --predicate actionable: click (default), type, set-value, or clear"+ )]+ pub action: Option<String>,+ #[arg(+ long,+ value_name = "COUNT",+ help = "Expected match count for --text waits"+ )]+ pub count: Option<usize>,}#[derive(Parser, Debug, Deserialize)]diff --git a/src/command_policy.rs b/src/command_policy/mod.rssimilarity index 98%rename from src/command_policy.rsrename to src/command_policy/mod.rsindex f484ed677..1136fecff 100644--- a/src/command_policy.rs+++ b/src/command_policy/mod.rs@@ -157,7 +157,7 @@ fn validate_args(cmd: &Commands) -> Result<(), AppError> {}}Commands::Wait(args) => {- if let Some(ref_id) = &args.element {+ if let Some(ref_id) = &args.mode.element {validate_ref_id(ref_id)?;}}@@ -212,5 +212,4 @@ fn requires_screen_recording(permission: PermissionNeed) -> bool {}#[cfg(test)]-#[path = "command_policy_tests.rs"]mod tests;diff --git a/src/command_policy_tests.rs b/src/command_policy/tests.rssimilarity index 100%rename from src/command_policy_tests.rsrename to src/command_policy/tests.rsdiff --git a/src/dispatch.rs b/src/dispatch/mod.rssimilarity index 85%rename from src/dispatch.rsrename to src/dispatch/mod.rsindex 82522c8c6..eb96027de 100644--- a/src/dispatch.rs+++ b/src/dispatch/mod.rs@@ -1,3 +1,6 @@+mod notifications;+mod parse;+use agent_desktop_core::{PermissionReport,adapter::PlatformAdapter,@@ -9,13 +12,14 @@ use agent_desktop_core::{resize_window, restore, right_click, screenshot, scroll, scroll_to, select, set_value,skills, snapshot, status, toggle, triple_click, type_text, uncheck, version, wait,},+ context::CommandContext,error::AppError,};use serde_json::Value;use crate::cli::Commands;-use crate::cli_args_skills::SkillsAction;-use crate::dispatch_parse::{+use crate::cli_args::skills::SkillsAction;+use parse::{parse_direction, parse_get_property, parse_is_property, parse_mouse_button, parse_xy,parse_xy_opt,};@@ -24,6 +28,7 @@ pub(crate) fn dispatch(cmd: Commands,adapter: &dyn PlatformAdapter,permission_report: &PermissionReport,+ context: &CommandContext,) -> Result<Value, AppError> {tracing::debug!("dispatch: {}", cmd.name());match cmd {@@ -41,6 +46,7 @@ pub(crate) fn dispatch(snapshot_id: a.snapshot,},adapter,+ context,),Commands::Find(a) => find::execute(@@ -57,6 +63,7 @@ pub(crate) fn dispatch(limit: a.limit,},adapter,+ context,),Commands::Screenshot(a) => screenshot::execute(@@ -75,6 +82,7 @@ pub(crate) fn dispatch(property: parse_get_property(&a.property)?,},adapter,+ context,),Commands::Is(a) => is_check::execute(@@ -84,12 +92,13 @@ pub(crate) fn dispatch(property: parse_is_property(&a.property)?,},adapter,+ context,),- Commands::Click(a) => click::execute(ref_args(a), adapter),- Commands::DoubleClick(a) => double_click::execute(ref_args(a), adapter),- Commands::TripleClick(a) => triple_click::execute(ref_args(a), adapter),- Commands::RightClick(a) => right_click::execute(ref_args(a), adapter),+ Commands::Click(a) => click::execute(ref_args(a), adapter, context),+ Commands::DoubleClick(a) => double_click::execute(ref_args(a), adapter, context),+ Commands::TripleClick(a) => triple_click::execute(ref_args(a), adapter, context),+ Commands::RightClick(a) => right_click::execute(ref_args(a), adapter, context),Commands::Type(a) => type_text::execute(type_text::TypeArgs {@@ -98,6 +107,7 @@ pub(crate) fn dispatch(text: a.text,},adapter,+ context,),Commands::SetValue(a) => set_value::execute(@@ -107,16 +117,17 @@ pub(crate) fn dispatch(value: a.value,},adapter,+ context,),- Commands::Clear(a) => clear::execute(ref_args(a), adapter),+ Commands::Clear(a) => clear::execute(ref_args(a), adapter, context),- Commands::Focus(a) => focus::execute(ref_args(a), adapter),- Commands::Toggle(a) => toggle::execute(ref_args(a), adapter),- Commands::Check(a) => check::execute(ref_args(a), adapter),- Commands::Uncheck(a) => uncheck::execute(ref_args(a), adapter),- Commands::Expand(a) => expand::execute(ref_args(a), adapter),- Commands::Collapse(a) => collapse::execute(ref_args(a), adapter),+ Commands::Focus(a) => focus::execute(ref_args(a), adapter, context),+ Commands::Toggle(a) => toggle::execute(ref_args(a), adapter, context),+ Commands::Check(a) => check::execute(ref_args(a), adapter, context),+ Commands::Uncheck(a) => uncheck::execute(ref_args(a), adapter, context),+ Commands::Expand(a) => expand::execute(ref_args(a), adapter, context),+ Commands::Collapse(a) => collapse::execute(ref_args(a), adapter, context),Commands::Select(a) => select::execute(select::SelectArgs {@@ -125,6 +136,7 @@ pub(crate) fn dispatch(value: a.value,},adapter,+ context,),Commands::Scroll(a) => scroll::execute(@@ -135,9 +147,10 @@ pub(crate) fn dispatch(amount: a.amount,},adapter,+ context,),- Commands::ScrollTo(a) => scroll_to::execute(ref_args(a), adapter),+ Commands::ScrollTo(a) => scroll_to::execute(ref_args(a), adapter, context),Commands::Press(a) => press::execute(press::PressArgs {@@ -161,6 +174,7 @@ pub(crate) fn dispatch(duration_ms: a.duration,},adapter,+ context,),Commands::Drag(a) => drag::execute(@@ -171,13 +185,15 @@ pub(crate) fn dispatch(to_xy: parse_xy_opt(a.to_xy.as_deref())?,snapshot_id: a.snapshot,duration_ms: a.duration,+ drop_delay_ms: a.drop_delay,},adapter,+ context,),Commands::MouseMove(a) => {let (x, y) = parse_xy(&a.xy)?;- mouse_move::execute(mouse_move::MouseMoveArgs { x, y }, adapter)+ mouse_move::execute(mouse_move::MouseMoveArgs { x, y }, adapter, context)}Commands::MouseClick(a) => {@@ -190,6 +206,7 @@ pub(crate) fn dispatch(count: a.count,},adapter,+ context,)}@@ -202,6 +219,7 @@ pub(crate) fn dispatch(button: parse_mouse_button(&a.button)?,},adapter,+ context,)}@@ -214,6 +232,7 @@ pub(crate) fn dispatch(button: parse_mouse_button(&a.button)?,},adapter,+ context,)}@@ -281,9 +300,7 @@ pub(crate) fn dispatch(Commands::ListNotifications(_)| Commands::DismissNotification(_)| Commands::DismissAllNotifications(_)- | Commands::NotificationAction(_) => {- crate::dispatch_notifications::dispatch_notification(cmd, adapter)- }+ | Commands::NotificationAction(_) => notifications::dispatch_notification(cmd, adapter),Commands::ClipboardGet => clipboard_get::execute(adapter),Commands::ClipboardSet(a) => clipboard_set::execute(a.text, adapter),@@ -291,21 +308,32 @@ pub(crate) fn dispatch(Commands::Wait(a) => wait::execute(wait::WaitArgs {- ms: a.ms,- element: a.element,- snapshot_id: a.snapshot,- window: a.window,- text: a.text,+ mode: wait::WaitModeArgs {+ ms: a.mode.ms,+ element: a.mode.element,+ window: a.mode.window,+ text: a.mode.text,+ menu: a.mode.menu,+ menu_closed: a.mode.menu_closed,+ notification: a.mode.notification,+ },+ predicate: wait::WaitPredicateArgs {+ snapshot_id: a.predicate.snapshot,+ predicate: a.predicate.predicate,+ value: a.predicate.value,+ action: a.predicate.action,+ count: a.predicate.count,+ },timeout_ms: a.timeout,- menu: a.menu,- menu_closed: a.menu_closed,- notification: a.notification,app: a.app,},adapter,+ context,),- Commands::Status => status::execute_with_report(adapter, permission_report),+ Commands::Status => {+ status::execute_with_report_with_context(adapter, permission_report, context)+ }Commands::Permissions(a) => permissions::execute_with_report(permissions::PermissionsArgs { request: a.request },@@ -325,7 +353,7 @@ pub(crate) fn dispatch(}),},- Commands::Batch(a) => crate::batch::execute(a, adapter, permission_report),+ Commands::Batch(a) => crate::batch::execute(a, adapter, permission_report, context),}}diff --git a/src/dispatch/notifications.rs b/src/dispatch/notifications.rsnew file mode 100644index 000000000..a7b913cbc--- /dev/null+++ b/src/dispatch/notifications.rs@@ -0,0 +1,101 @@+use agent_desktop_core::{+ adapter::PlatformAdapter,+ commands::{+ dismiss_all_notifications, dismiss_notification, list_notifications, notification_action,+ },+ error::{AppError, ErrorCode},+};+use serde_json::Value;++use crate::cli::Commands;++pub(crate) fn dispatch_notification(+ cmd: Commands,+ adapter: &dyn PlatformAdapter,+) -> Result<Value, AppError> {+ match cmd {+ Commands::ListNotifications(a) => list_notifications::execute(+ list_notifications::ListNotificationsArgs {+ app: a.app,+ text: a.text,+ limit: a.limit,+ },+ adapter,+ ),+ Commands::DismissNotification(a) => dismiss_notification::execute(+ dismiss_notification::DismissNotificationArgs {+ index: notification_index(a.index)?,+ app: a.app,+ },+ adapter,+ ),+ Commands::DismissAllNotifications(a) => dismiss_all_notifications::execute(+ dismiss_all_notifications::DismissAllNotificationsArgs { app: a.app },+ adapter,+ ),+ Commands::NotificationAction(a) => notification_action::execute(+ notification_action::NotificationActionArgs {+ index: notification_index(a.index)?,+ action: a.action,+ expected_app: a.expected_app,+ expected_title: a.expected_title,+ },+ adapter,+ ),+ _ => Err(AppError::Adapter(+ agent_desktop_core::error::AdapterError::new(+ ErrorCode::InvalidArgs,+ "dispatch_notification received a non-notification command",+ ),+ )),+ }+}++fn notification_index(index: u64) -> Result<usize, AppError> {+ if index == 0 {+ return Err(AppError::invalid_input(+ "Notification index is 1-based and must be greater than zero",+ ));+ }+ usize::try_from(index).map_err(|_| AppError::invalid_input("Notification index is too large"))+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::cli_args::notifications::{DismissNotificationCliArgs, NotificationActionCliArgs};++ struct NoopAdapter;++ impl PlatformAdapter for NoopAdapter {}++ #[test]+ fn dismiss_notification_rejects_zero_index_before_adapter() {+ let err = dispatch_notification(+ Commands::DismissNotification(DismissNotificationCliArgs {+ index: 0,+ app: None,+ }),+ &NoopAdapter,+ )+ .unwrap_err();++ assert_eq!(err.code(), "INVALID_ARGS");+ }++ #[test]+ fn notification_action_rejects_zero_index_before_adapter() {+ let err = dispatch_notification(+ Commands::NotificationAction(NotificationActionCliArgs {+ index: 0,+ action: "Reply".into(),+ expected_app: None,+ expected_title: None,+ }),+ &NoopAdapter,+ )+ .unwrap_err();++ assert_eq!(err.code(), "INVALID_ARGS");+ }+}diff --git a/src/dispatch_parse.rs b/src/dispatch/parse.rssimilarity index 98%rename from src/dispatch_parse.rsrename to src/dispatch/parse.rsindex 721f92f5f..2d17e6a4b 100644--- a/src/dispatch_parse.rs+++ b/src/dispatch/parse.rs@@ -80,5 +80,5 @@ pub(crate) fn parse_xy_opt(s: Option<&str>) -> Result<Option<(f64, f64)>, AppErr}#[cfg(test)]-#[path = "dispatch_parse_tests.rs"]+#[path = "parse_tests.rs"]mod tests;diff --git a/src/dispatch_parse_tests.rs b/src/dispatch/parse_tests.rssimilarity index 100%rename from src/dispatch_parse_tests.rsrename to src/dispatch/parse_tests.rsdiff --git a/src/dispatch_notifications.rs b/src/dispatch_notifications.rsdeleted file mode 100644index 781c97e2f..000000000--- a/src/dispatch_notifications.rs+++ /dev/null@@ -1,47 +0,0 @@-use agent_desktop_core::{- adapter::PlatformAdapter,- commands::{- dismiss_all_notifications, dismiss_notification, list_notifications, notification_action,- },- error::AppError,-};-use serde_json::Value;--use crate::cli::Commands;--pub(crate) fn dispatch_notification(- cmd: Commands,- adapter: &dyn PlatformAdapter,-) -> Result<Value, AppError> {- match cmd {- Commands::ListNotifications(a) => list_notifications::execute(- list_notifications::ListNotificationsArgs {- app: a.app,- text: a.text,- limit: a.limit,- },- adapter,- ),- Commands::DismissNotification(a) => dismiss_notification::execute(- dismiss_notification::DismissNotificationArgs {- index: a.index as usize,- app: a.app,- },- adapter,- ),- Commands::DismissAllNotifications(a) => dismiss_all_notifications::execute(- dismiss_all_notifications::DismissAllNotificationsArgs { app: a.app },- adapter,- ),- Commands::NotificationAction(a) => notification_action::execute(- notification_action::NotificationActionArgs {- index: a.index as usize,- action: a.action,- expected_app: a.expected_app,- expected_title: a.expected_title,- },- adapter,- ),- _ => unreachable!(),- }-}diff --git a/src/main.rs b/src/main.rsindex 693f4e462..1367be96c 100644--- a/src/main.rs+++ b/src/main.rs@@ -1,25 +1,17 @@mod batch;mod cli;mod cli_args;-mod cli_args_actions;-mod cli_args_notifications;-mod cli_args_skills;-mod cli_args_system;-#[cfg(test)]-mod command_contract_tests;mod command_policy;mod dispatch;-mod dispatch_notifications;-mod dispatch_parse;use agent_desktop_core::{adapter::PlatformAdapter,- error::AppError,+ context::CommandContext,output::{ENVELOPE_VERSION, ErrorPayload, Response},};use clap::{CommandFactory, Parser};use cli::{Cli, Commands};-use cli_args_skills::SkillsAction;+use cli_args::skills::SkillsAction;use std::io::{BufWriter, Write};fn main() {@@ -43,6 +35,13 @@ fn main() {};init_tracing(cli.verbose);+ let context = match CommandContext::new(cli.session, cli.trace, cli.trace_strict) {+ Ok(context) => context.with_headed(cli.headed),+ Err(err) => {+ finish("unknown", Err(err));+ return;+ }+ };let cmd = match cli.command {Some(c) => c,@@ -75,11 +74,11 @@ fn main() {};finish(cmd_name, result);}- cmd => run_with_adapter(cmd, cmd_name),+ cmd => run_with_adapter(cmd, cmd_name, &context),}}-fn run_with_adapter(cmd: Commands, cmd_name: &str) {+fn run_with_adapter(cmd: Commands, cmd_name: &str, context: &CommandContext) {let adapter = build_adapter();let report = adapter.permission_report();if let Err(err) = command_policy::preflight(&cmd, &report) {@@ -87,7 +86,7 @@ fn run_with_adapter(cmd: Commands, cmd_name: &str) {return;}- let result = dispatch::dispatch(cmd, &adapter, &report);+ let result = dispatch::dispatch(cmd, &adapter, &report, context);finish(cmd_name, result);}@@ -98,14 +97,10 @@ fn finish(cmd_name: &str, result: Result<serde_json::Value, agent_desktop_core::std::process::exit(0);}Err(e) => {- let mut payload = ErrorPayload::new(e.code(), e.to_string());- if let Some(s) = e.suggestion() {- payload = payload.with_suggestion(s);- }- if let AppError::Adapter(adapter_error) = &e {- payload.platform_detail = adapter_error.platform_detail.clone();- }- emit_response(&Response::err(cmd_name, payload));+ emit_response(&Response::err(+ cmd_name,+ agent_desktop_core::ErrorPayload::from_app_error(&e),+ ));std::process::exit(1);}}diff --git a/src/tests/conformance.rs b/src/tests/conformance.rsnew file mode 100644index 000000000..33aa7ef6b--- /dev/null+++ b/src/tests/conformance.rs@@ -0,0 +1,242 @@+use agent_desktop_core::{+ action_request::ActionRequest,+ action_result::ActionResult,+ adapter::{LiveElement, NativeHandle, PlatformAdapter, SnapshotSurface},+ capability,+ element_state::ElementState,+ error::{AdapterError, ErrorCode},+ node::Rect,+ refs::RefEntry,+};+use std::sync::atomic::{AtomicU32, Ordering};+use std::time::Duration;++#[path = "../../tests/conformance/ref_action_contract.rs"]+mod ref_action_contract;++struct ContractAdapter {+ resolve: ResolveMode,+ live_bounds: Option<Rect>,+ live_value: Option<String>,+ dispatches: AtomicU32,+}++#[derive(Clone, Copy)]+enum ResolveMode {+ Ok,+ Stale,+ Ambiguous,+}++impl PlatformAdapter for ContractAdapter {+ fn resolve_element_strict(&self, _entry: &RefEntry) -> Result<NativeHandle, AdapterError> {+ self.resolve()+ }++ fn resolve_element_strict_with_timeout(+ &self,+ _entry: &RefEntry,+ _timeout: Duration,+ ) -> Result<NativeHandle, AdapterError> {+ self.resolve()+ }++ fn get_live_element(&self, _handle: &NativeHandle) -> Result<LiveElement, AdapterError> {+ Ok(LiveElement {+ state: Some(ElementState {+ role: "button".into(),+ states: vec![],+ value: self.live_value.clone(),+ }),+ bounds: self.live_bounds,+ available_actions: Some(vec![capability::CLICK.into()]),+ })+ }++ fn get_live_state(&self, _handle: &NativeHandle) -> Result<Option<ElementState>, AdapterError> {+ Ok(Some(ElementState {+ role: "button".into(),+ states: vec![],+ value: self.live_value.clone(),+ }))+ }++ fn get_live_value(&self, _handle: &NativeHandle) -> Result<Option<String>, AdapterError> {+ Ok(self.live_value.clone())+ }++ fn execute_action(+ &self,+ _handle: &NativeHandle,+ _request: ActionRequest,+ ) -> Result<ActionResult, AdapterError> {+ self.dispatches.fetch_add(1, Ordering::SeqCst);+ Ok(ActionResult::new("click"))+ }+}++impl ContractAdapter {+ fn new(resolve: ResolveMode, live_bounds: Option<Rect>) -> Self {+ Self {+ resolve,+ live_bounds,+ live_value: None,+ dispatches: AtomicU32::new(0),+ }+ }++ fn with_live_value(mut self, value: &str) -> Self {+ self.live_value = Some(value.into());+ self+ }++ fn resolve(&self) -> Result<NativeHandle, AdapterError> {+ match self.resolve {+ ResolveMode::Ok => Ok(NativeHandle::null()),+ ResolveMode::Stale => Err(AdapterError::new(ErrorCode::StaleRef, "stale ref")),+ ResolveMode::Ambiguous => Err(AdapterError::ambiguous_target("2 candidates matched")),+ }+ }+}++fn entry(bounds: Rect) -> RefEntry {+ RefEntry {+ pid: 1,+ role: "button".into(),+ name: Some("OK".into()),+ value: None,+ description: None,+ states: vec![],+ bounds: Some(bounds),+ bounds_hash: Some(bounds.bounds_hash()),+ available_actions: vec![capability::CLICK.into()],+ source_app: None,+ source_window_id: None,+ source_window_title: None,+ source_surface: SnapshotSurface::Window,+ root_ref: None,+ path_is_absolute: true,+ path: Default::default(),+ }+}++#[test]+fn adapter_contract_dispatches_when_live_identity_moved() {+ let snapshot_bounds = Rect {+ x: 1.0,+ y: 1.0,+ width: 20.0,+ height: 20.0,+ };+ let adapter = ContractAdapter::new(+ ResolveMode::Ok,+ Some(Rect {+ x: 100.0,+ y: 100.0,+ width: 20.0,+ height: 20.0,+ }),+ );++ let result = ref_action_contract::run_click_command(&adapter, entry(snapshot_bounds)).unwrap();++ assert_eq!(result["action"], "click");+ assert_eq!(adapter.dispatches.load(Ordering::SeqCst), 1);+}++#[test]+fn adapter_contract_dispatches_when_live_identity_is_stable() {+ let bounds = Rect {+ x: 1.0,+ y: 1.0,+ width: 20.0,+ height: 20.0,+ };+ let adapter = ContractAdapter::new(ResolveMode::Ok, Some(bounds));++ let result = ref_action_contract::run_click_command(&adapter, entry(bounds)).unwrap();++ assert_eq!(result["action"], "click");+ assert_eq!(adapter.dispatches.load(Ordering::SeqCst), 1);+}++#[test]+fn adapter_contract_resolution_failures_stop_before_dispatch() {+ let bounds = Rect {+ x: 1.0,+ y: 1.0,+ width: 20.0,+ height: 20.0,+ };+ for (mode, code) in [+ (ResolveMode::Stale, "STALE_REF"),+ (ResolveMode::Ambiguous, "AMBIGUOUS_TARGET"),+ ] {+ let adapter = ContractAdapter::new(mode, Some(bounds));++ let err = ref_action_contract::run_click_command(&adapter, entry(bounds)).unwrap_err();++ assert_eq!(err.code(), code);+ assert_eq!(adapter.dispatches.load(Ordering::SeqCst), 0);+ }+}++#[test]+fn adapter_contract_wait_element_uses_session_snapshot() {+ let bounds = Rect {+ x: 1.0,+ y: 1.0,+ width: 20.0,+ height: 20.0,+ };+ let adapter = ContractAdapter::new(ResolveMode::Ok, Some(bounds));+ let context =+ agent_desktop_core::context::CommandContext::new(Some("shared-agent".into()), None, false)+ .unwrap();++ let result =+ ref_action_contract::run_wait_element_command(&adapter, entry(bounds), &context).unwrap();++ assert_eq!(result["found"], true);+ assert_eq!(result["ref"], "@e1");+ assert_eq!(result["predicate"], "exists");+}++#[test]+fn adapter_contract_wait_predicates_cover_live_state_paths() {+ let bounds = Rect {+ x: 1.0,+ y: 1.0,+ width: 20.0,+ height: 20.0,+ };+ let context =+ agent_desktop_core::context::CommandContext::new(Some("shared-agent".into()), None, false)+ .unwrap();++ let enabled = ref_action_contract::run_wait_element_command_with_predicate(+ &ContractAdapter::new(ResolveMode::Ok, Some(bounds)),+ entry(bounds),+ &context,+ ref_action_contract::WaitPredicate::new("enabled"),+ )+ .unwrap();+ let actionable = ref_action_contract::run_wait_element_command_with_predicate(+ &ContractAdapter::new(ResolveMode::Ok, Some(bounds)),+ entry(bounds),+ &context,+ ref_action_contract::WaitPredicate::new("actionable").with_action("click"),+ )+ .unwrap();+ let value = ref_action_contract::run_wait_element_command_with_predicate(+ &ContractAdapter::new(ResolveMode::Ok, Some(bounds)).with_live_value("ready"),+ entry(bounds),+ &context,+ ref_action_contract::WaitPredicate::new("value").with_value("ready"),+ )+ .unwrap();++ assert_eq!(enabled["observed"]["enabled"], true);+ assert_eq!(actionable["observed"]["actionable"], true);+ assert_eq!(value["observed"]["matched"], true);+}diff --git a/src/tests/snapshot_test.rs b/src/tests/snapshot_test.rsindex 9db3c2aa4..0de05111d 100644--- a/src/tests/snapshot_test.rs+++ b/src/tests/snapshot_test.rs@@ -54,7 +54,7 @@ mod tests {fn version_command_outputs_json() {let bin = agent_desktop_bin();if !bin.exists() {- return; // binary not built yet+ return;}let output = Command::new(&bin).args(["version", "--json"])diff --git a/tests/conformance/README.md b/tests/conformance/README.mdnew file mode 100644index 000000000..70d60e5f8--- /dev/null+++ b/tests/conformance/README.md@@ -0,0 +1,44 @@+# Adapter Reliability Conformance++Every platform adapter must satisfy the same ref/action contract. The macOS+adapter is the first implementation, but the tests are written against+`PlatformAdapter` semantics so Windows UIA and Linux AT-SPI can reuse the same+expectations.++The reusable command-path helper lives in `tests/conformance/ref_action_contract.rs`.+The executable smoke harness in `src/tests/conformance.rs` uses it with a mock+adapter; future Windows and Linux fixtures can call the same helper with real+adapter-provided refs.++## Required Gates++| Area | Required behavior |+|------|-------------------|+| Snapshot refs | Refs are depth-first, snapshot-scoped, and explicit snapshot IDs resolve directly |+| Strict resolve | A ref resolves only when identity still matches; stale refs return `STALE_REF` |+| Ambiguity | Multiple plausible matches return `AMBIGUOUS_TARGET`, never an arbitrary click |+| Actionability | Ref actions check live visibility, stability, enabled state, supported action, policy, and editability before dispatch |+| Wait recovery | `wait --element` can poll the latest session refmap when no snapshot is pinned, honors the caller timeout while resolving, and reports the last observed predicate state |+| Session latest scope | Commands that omit `--snapshot` read and write only the active session's latest refmap |+| Explicit snapshot scope | Passing `--snapshot <id>` resolves that pinned snapshot even when the caller omits the original session |+| Trace | `--trace <path>` writes JSONL diagnostics outside stdout and is best-effort unless strict |+| FFI parity | FFI ref actions use strict resolve and actionability checks before adapter dispatch |++## Platform Matrix++| Fixture | macOS AX | Windows UIA | Linux AT-SPI |+|---------|:--------:|:-----------:|:------------:|+| Two identical buttons produce ambiguity | Required | Required | Required |+| Ref disappears after snapshot | Required | Required | Required |+| Disabled button blocks click before dispatch | Required | Required | Required |+| Text field supports value/type actionability | Required | Required | Required |+| Session A latest refmap is invisible to Session B | Required | Required | Required |+| Batch item session overrides inherited session | Required | Required | Required |+| FFI `AdRefEntry` preserves full identity envelope | Required | Required | Required |++## Adding Windows or Linux++Add adapter-specific integration fixtures, but keep expected errors and JSON+shapes identical. Prefer semantic platform actions first (`AXPress`, UIA+Invoke/Value/Selection patterns, AT-SPI actions). Coordinate input is a lower+confidence fallback and must remain explicit in policy or command choice.diff --git a/tests/conformance/ref_action_contract.rs b/tests/conformance/ref_action_contract.rsnew file mode 100644index 000000000..ce13fbefa--- /dev/null+++ b/tests/conformance/ref_action_contract.rs@@ -0,0 +1,152 @@+use agent_desktop_core::{+ adapter::PlatformAdapter,+ commands::{click, helpers::RefArgs, wait},+ context::CommandContext,+ refs::{RefEntry, RefMap},+ refs_store::RefStore,+};+use std::sync::{Mutex, MutexGuard};++static HOME_LOCK: Mutex<()> = Mutex::new(());++pub fn run_click_command(+ adapter: &dyn PlatformAdapter,+ entry: RefEntry,+) -> Result<serde_json::Value, agent_desktop_core::AppError> {+ let context = CommandContext::default();+ with_saved_entry(entry, &context, |snapshot_id| {+ click::execute(+ RefArgs {+ ref_id: "@e1".into(),+ snapshot_id: Some(snapshot_id),+ },+ adapter,+ &context,+ )+ })+}++pub fn run_wait_element_command(+ adapter: &dyn PlatformAdapter,+ entry: RefEntry,+ context: &CommandContext,+) -> Result<serde_json::Value, agent_desktop_core::AppError> {+ run_wait_element_command_with_predicate(adapter, entry, context, WaitPredicate::new("exists"))+}++pub fn run_wait_element_command_with_predicate(+ adapter: &dyn PlatformAdapter,+ entry: RefEntry,+ context: &CommandContext,+ predicate: WaitPredicate<'_>,+) -> Result<serde_json::Value, agent_desktop_core::AppError> {+ with_saved_entry(entry, context, |_| {+ wait::execute(+ wait::WaitArgs {+ mode: wait::WaitModeArgs {+ ms: None,+ element: Some("@e1".into()),+ window: None,+ text: None,+ menu: false,+ menu_closed: false,+ notification: false,+ },+ predicate: wait::WaitPredicateArgs {+ snapshot_id: None,+ predicate: Some(predicate.name.into()),+ value: predicate.value.map(String::from),+ action: predicate.action.map(String::from),+ count: None,+ },+ timeout_ms: 100,+ app: None,+ },+ adapter,+ context,+ )+ })+}++pub struct WaitPredicate<'a> {+ name: &'a str,+ value: Option<&'a str>,+ action: Option<&'a str>,+}++impl<'a> WaitPredicate<'a> {+ pub fn new(name: &'a str) -> Self {+ Self {+ name,+ value: None,+ action: None,+ }+ }++ pub fn with_value(mut self, value: &'a str) -> Self {+ self.value = Some(value);+ self+ }++ pub fn with_action(mut self, action: &'a str) -> Self {+ self.action = Some(action);+ self+ }+}++fn with_saved_entry<T>(+ entry: RefEntry,+ context: &CommandContext,+ run: impl FnOnce(String) -> Result<T, agent_desktop_core::AppError>,+) -> Result<T, agent_desktop_core::AppError> {+ let _home = TestHome::new();+ let mut refmap = RefMap::new();+ refmap.allocate(entry);+ let snapshot_id = RefStore::for_session(context.session_id())?.save_new_snapshot(&refmap)?;+ run(snapshot_id)+}++struct TestHome {+ _lock: MutexGuard<'static, ()>,+ dir: std::path::PathBuf,+ prev: Option<std::ffi::OsString>,+}++impl TestHome {+ fn new() -> Self {+ let lock = HOME_LOCK.lock().unwrap();+ let dir = temp_path("home");+ std::fs::create_dir_all(&dir).unwrap();+ let prev = std::env::var_os("HOME");+ unsafe { std::env::set_var("HOME", &dir) };+ Self {+ _lock: lock,+ dir,+ prev,+ }+ }+}++impl Drop for TestHome {+ fn drop(&mut self) {+ match self.prev.as_ref() {+ Some(prev) => unsafe { std::env::set_var("HOME", prev) },+ None => unsafe { std::env::remove_var("HOME") },+ }+ let _ = std::fs::remove_dir_all(&self.dir);+ }+}++fn temp_path(label: &str) -> std::path::PathBuf {+ std::env::temp_dir().join(format!(+ "agent-desktop-conformance-{label}-{}",+ unique_suffix()+ ))+}++fn unique_suffix() -> u128 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+}diff --git a/tests/e2e/README.md b/tests/e2e/README.mdnew file mode 100644index 000000000..0d1949bac--- /dev/null+++ b/tests/e2e/README.md@@ -0,0 +1,87 @@+# End-to-End Tests (real binary vs. real app)++These tests drive the **release `agent-desktop` binary** against a **real macOS+application** and verify every effect by **independent observation** — never the+command's own `ok: true`. A command that returns success without producing the+effect is caught, because each check re-reads the UI (status label, element+value, scroll offset, `list-apps`, …) and asserts the observed `before`/`after`.++This is the layer that mock-adapter unit tests cannot cover: it exercises the+contract against the actual macOS Accessibility API.++## Layout++| Path | Role |+|------|------|+| `tests/fixture-app/AgentDeskFixture.swift` | SwiftUI + AppKit fixture exposing a fixed, diverse AX surface |+| `tests/fixture-app/build.sh` | Compiles the fixture into `build/AgentDeskFixture.app` |+| `tests/e2e/run.sh` | The harness: launches the fixture, runs the binary, asserts by observation |++The fixture is a **principal-engineer-grade slice of real UI**, not a target+tuned to make the CLI pass. It deliberately mixes AX-actionable native AppKit+controls (`NSSlider`, `NSStepper`) with gesture-only and ambiguous patterns. **A+failure here is a finding about the CLI or the harness — never a reason to edit+the fixture so the CLI passes.**++## Running++```bash+cargo build --release # the harness uses target/release/agent-desktop+bash tests/e2e/run.sh+```++Requirements:++- macOS with **Accessibility permission** granted to the terminal running the+ harness (System Settings → Privacy & Security → Accessibility).+- The harness builds the fixture `.app` automatically if it is missing.+- `--headed` checks move the real cursor; run on a machine where that is OK.++Exit code is `0` when every scenario passes, `1` on any failure (with the+observed values printed inline for each failing check), `2` on setup error.++## What it verifies++- **Observation:** snapshot role diversity, `find` vocabulary + `roles_present`+ hint, textarea→textfield alias.+- **Interaction in BOTH modes (the headless/headed contract):** every ref-action+ command (`click`, `type`, `set-value`, `clear`, `check`, `uncheck`, `select`,+ `set-value` on slider/stepper, `scroll`) is driven **twice** — default+ **headless**, then **`--headed`** — with mode-specific target values so a+ regression in either mode is caught by an independent `before`/`after`+ observation. Headed must not regress the AX path (it is tried first); it only+ adds cursor/physical fallbacks.+- **The headless/headed discriminator:** `double-click` on a gesture-only button+ (no `AXOpen`) **fails closed with `POLICY_DENIED` headless**, and **completes+ with `--headed`** (physical double-click). This is the crisp proof the two+ modes differ and that `--headed` unlocks the physical fallback.+- **Strict resolution:** ambiguous twins do not silently act; a removed element+ fails closed with `STALE_REF`.+- **Reliability core:** `wait` predicates (`enabled`, `actionable`, `visible`,+ `value`), `wait --text` async appearance, skeleton traversal + scoped+ drill-down, session isolation + session-independent explicit snapshots, trace+ JSONL with secret redaction.+- **Surfaces / drag / expand / close:** open a sheet and act inside it,+ source-tracked drag gesture verified by a tracking canvas, expand a+ press-toggled disclosure, `close-app --force` verified via `list-apps`.++## Documented limitations (tracked, not failures)++- **Cross-target native drag-and-drop (`onDrop`)** needs the OS dragging-session+ / pasteboard protocol. Synthetic mouse events route mouse-up to the drag+ origin, so they cannot drop onto a separate native target. Source-tracked+ gestures (and web/Electron mouse-DnD) work; the harness verifies the gesture+ via a tracking canvas.+- **SwiftUI `Slider`/`Stepper`/`DisclosureGroup` are not AX-actionable.** The+ fixture uses native AppKit `NSSlider`/`NSStepper` (which are), so `set-value`+ and `expand` are proven on controls that actually expose the capability.++## Adding a scenario++1. Expose the surface in `AgentDeskFixture.swift` with a stable+ `accessibilityLabel` and a `statictext` status readout that reflects the+ real state (so the harness can observe the effect, not the command's claim).+2. Add a check in `run.sh` using `verify <label> <status> <expected> <subcmd…>`+ (mode-injected) or an explicit `before`/`after` + `assert` block.+3. If the command is a ref action, add it to `interaction_suite` so it is+ covered in **both** headless and headed modes.diff --git a/tests/e2e/run.sh b/tests/e2e/run.shnew file mode 100755index 000000000..00d6874a7--- /dev/null+++ b/tests/e2e/run.sh@@ -0,0 +1,395 @@+#!/usr/bin/env bash+set -uo pipefail++repo="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+bin="$repo/target/release/agent-desktop"+fixture_app="$repo/tests/fixture-app/build/AgentDeskFixture.app"+app="AgentDeskFixture"++pass=0; skip_count=0; fail=0; declare -a failures+note() { printf '\n\033[1;34m== %s ==\033[0m\n' "$1"; }+okmsg() { printf ' \033[0;32mPASS\033[0m %s\n' "$1"; pass=$((pass+1)); }+badmsg(){ printf ' \033[0;31mFAIL\033[0m %s\n' "$1"; fail=$((fail+1)); failures+=("$1"); }+skip() { printf ' \033[0;33mNOTE\033[0m %s\n' "$1"; skip_count=$((skip_count+1)); }+assert() { if [ "$2" = "1" ]; then okmsg "$1 [$3]"; else badmsg "$1 [$3]"; fi; }++MODE_FLAG=""+act() { "$bin" $MODE_FLAG "$@"; }++PERF_FILE="$(mktemp -t agentdesk-perf.XXXXXX)"+timed() {+ python3 - "$PERF_FILE" "$@" <<'PY'+import sys, time, subprocess+perf, label, cmd = sys.argv[1], sys.argv[2], sys.argv[3:]+t = time.perf_counter()+r = subprocess.run(cmd, capture_output=True, text=True)+ms = (time.perf_counter() - t) * 1000+with open(perf, "a") as fh:+ fh.write(f"{label}\t{ms:.1f}\n")+sys.stdout.write(r.stdout)+PY+}++field() { python3 -c "import json,sys+try: d=json.load(sys.stdin)+except Exception: print(''); sys.exit()+try: print(eval('d'+sys.argv[1]))+except Exception: print('')" "$1" 2>/dev/null; }++resolve() { "$bin" find --app "$app" --role "$1" --name "$2" --first 2>/dev/null | field "['data']['match']['ref_id']"; }+read_value() { "$bin" find --app "$app" --role statictext --name "$1" --first 2>/dev/null | field "['data']['match']['value']"; }+running() { "$bin" list-apps 2>/dev/null | python3 -c "import json,sys;print(any(a['name']=='$app' for a in json.load(sys.stdin)['data']['apps']))" 2>/dev/null; }++verify() {+ local label="$1" status="$2" expected="$3"; shift 3+ local before after out cmd_ok err+ before="$(read_value "$status")"+ out="$(act "$@" 2>&1)"; sleep 0.35+ after="$(read_value "$status")"+ cmd_ok="$(echo "$out" | field "['ok']")"+ err="$(echo "$out" | field "['error']['code']")"+ assert "$label" "$([ "$after" = "$expected" ] && echo 1 || echo 0)" \+ "before='$before' after='$after' expected='$expected' cmd_ok=$cmd_ok${err:+ err=$err}"+}++interaction_suite() {+ local MODE="$1" MODE_FLAG="" sel sld stp dir+ if [ "$MODE" = headed ]; then MODE_FLAG="--headed"; sel=Gamma; sld=60; stp=6; dir=up+ else sel=Beta; sld=50; stp=4; dir=down; fi+ "$bin" focus-window --app "$app" >/dev/null 2>&1++ note "[$MODE] click / type / set-value / clear"+ # click-status is a counter ("click-N"); assert it INCREMENTS in this mode so+ # a no-op click cannot pass by inheriting a value the other mode already set.+ local cb ca nb na+ cb="$(read_value click-status)"+ act click "$(resolve button primary-button)" >/dev/null 2>&1; sleep 0.35+ ca="$(read_value click-status)"+ nb="$(printf '%s' "$cb" | grep -oE '[0-9]+$' || true)"; nb="${nb:-0}"+ na="$(printf '%s' "$ca" | grep -oE '[0-9]+$' || true)"; na="${na:-0}"+ assert "[$MODE] click incremented counter" "$([ "$na" -gt "$nb" ] && echo 1 || echo 0)" \+ "click-status before='$cb' after='$ca'"+ act clear "$(resolve textfield text-input)" >/dev/null 2>&1; sleep 0.2+ verify "type sets field" text-echo "typed-$MODE" type "$(resolve textfield text-input)" "typed-$MODE"+ verify "set-value sets field" text-echo "set-$MODE" set-value "$(resolve textfield text-input)" "set-$MODE"+ verify "clear empties field" text-echo "" clear "$(resolve textfield text-input)"++ note "[$MODE] check / uncheck (reset before each)"+ act uncheck "$(resolve checkbox toggle-box)" >/dev/null 2>&1; sleep 0.2+ verify "check turns toggle on" toggle-status on check "$(resolve checkbox toggle-box)"+ verify "uncheck turns toggle off" toggle-status off uncheck "$(resolve checkbox toggle-box)"++ note "[$MODE] select / slider / stepper (mode-specific targets)"+ verify "select combobox -> $sel" picker-status "$sel" select "$(resolve combobox option-picker)" "$sel"+ verify "set-value slider -> $sld" slider-status "$sld" set-value "$(resolve slider value-slider)" "$sld"+ verify "set-value stepper -> $stp" stepper-status "$stp" set-value "$(resolve incrementor value-stepper)" "$stp"++ note "[$MODE] scroll $dir (observed offset delta)"+ local so_b so_a+ so_b="$(read_value scroll-offset)"+ act scroll "$(resolve scrollarea scroll-area)" --direction "$dir" --amount 10 >/dev/null 2>&1; sleep 0.4+ so_a="$(read_value scroll-offset)"+ assert "[$MODE] scroll moved content" "$([ -n "$so_b" ] && [ "$so_b" != "$so_a" ] && echo 1 || echo 0)" \+ "offset before='$so_b' after='$so_a' dir=$dir"+}++cleanup() { "$bin" close-app "$app" --force >/dev/null 2>&1 || true; rm -f "$PERF_FILE"; }+trap cleanup EXIT++note "Setup"+[ -x "$bin" ] || { echo "release binary missing; run 'cargo build --release'"; exit 2; }+ax_state="$("$bin" permissions 2>/dev/null | field "['data']['accessibility']['state']")"+if [ "$ax_state" != "granted" ]; then+ echo "accessibility permission not granted (state='${ax_state:-unknown}')." >&2+ echo "Grant Accessibility trust to this terminal/runner in System Settings > Privacy & Security, then retry." >&2+ exit 2+fi+fixture_stale() {+ [ ! -d "$fixture_app" ] ||+ [ -n "$(find "$repo/tests/fixture-app" -maxdepth 1 -name '*.swift' -newer "$fixture_app" 2>/dev/null)" ]+}+if fixture_stale; then+ "$repo/tests/fixture-app/build.sh" >/dev/null || {+ echo "fixture build failed (swiftc output above); cannot run E2E" >&2+ exit 2+ }+fi+"$bin" close-app "$app" --force >/dev/null 2>&1 || true; sleep 1+open "$fixture_app"+ready=""; tries=0+for _ in $(seq 1 20); do+ tries=$((tries+1))+ "$bin" focus-window --app "$app" >/dev/null 2>&1 || true+ [ -n "$(resolve button primary-button)" ] && { ready=1; break; }+ sleep 0.5+done+assert "fixture launched and tree exposed" "$ready" "primary-button resolvable after $tries focus attempts"++note "snapshot role diversity (observed roles vs expected)"+snap="$("$bin" snapshot --app "$app" --max-depth 30 2>/dev/null)"+refc="$(echo "$snap" | field "['data']['ref_count']")"+for r in button textfield checkbox combobox slider incrementor radiobutton disclosure link tab treeitem scrollarea; do+ present="$(echo "$snap" | grep -qc "\"role\":\"$r\"" && echo 1 || echo 0)"+ assert "role $r" "$([ "$(echo "$snap" | grep -c "\"role\":\"$r\"")" -ge 1 ] && echo 1 || echo 0)" \+ "found=$([ "$(echo "$snap" | grep -c "\"role\":\"$r\"")" -ge 1 ] && echo yes || echo NO) ref_count=$refc"+done++note "find vocabulary (observed resolution)"+tf="$(resolve textfield text-input)"+assert "find textfield by name" "$([ -n "$tf" ] && echo 1 || echo 0)" "resolved ref='$tf'"+ta="$("$bin" find --app "$app" --role textarea --name text-input --first 2>/dev/null | field "['data']['match']['ref_id']")"+assert "textarea alias -> textfield" "$([ -n "$ta" ] && echo 1 || echo 0)" "alias resolved ref='$ta'"+hint="$("$bin" find --app "$app" --role navbar 2>/dev/null | field "['data']['roles_present']")"+assert "absent role returns roles_present hint" "$([ -n "$hint" ] && echo 1 || echo 0)" "roles_present=${hint:0:60}..."++interaction_suite headless+interaction_suite headed++note "radio (one-way, headless)"+verify "click radio option Two" radio-status Two click "$(resolve radiobutton Two)"++note "tab selection (TabView tabs are radiobuttons; observe tab-status switch)"+verify "select Tab Two switches body" tab-status 1 click "$(resolve radiobutton 'Tab Two')"+verify "select Tab One switches back" tab-status 0 click "$(resolve radiobutton 'Tab One')"++note "double-click: the headless/headed discriminator (gesture-only target, no AXOpen)"+dt="$(resolve button double-target)"+"$bin" focus-window --app "$app" >/dev/null 2>&1+dc_b="$(read_value double-status)"+hl_out="$("$bin" double-click "$dt" 2>&1)"; sleep 0.3+hl_a="$(read_value double-status)"; hl_code="$(echo "$hl_out" | field "['error']['code']")"+assert "headless double-click fails closed (no cursor)" \+ "$([ "$hl_a" = "$dc_b" ] && [ "$hl_code" = "POLICY_DENIED" ] && echo 1 || echo 0)" \+ "before='$dc_b' after='$hl_a' err=$hl_code"+"$bin" focus-window --app "$app" >/dev/null 2>&1+hd_out="$("$bin" --headed double-click "$dt" 2>&1)"; sleep 0.3+hd_a="$(read_value double-status)"; hd_ok="$(echo "$hd_out" | field "['ok']")"+assert "--headed double-click completes (physical fallback unlocked)" \+ "$([ "$hd_a" = "double-clicked" ] && echo 1 || echo 0)" \+ "before='$hl_a' after='$hd_a' cmd_ok=$hd_ok"++note "triple-click + hover (headed gestures, observed effect)"+"$bin" focus-window --app "$app" >/dev/null 2>&1+tp_b="$(read_value triple-status)"+"$bin" --headed triple-click "$(resolve button triple-target)" >/dev/null 2>&1; sleep 0.4+tp_a="$(read_value triple-status)"+assert "--headed triple-click fires 3-tap gesture" "$([ "$tp_a" = "triple-clicked" ] && echo 1 || echo 0)" \+ "triple-status before='$tp_b' after='$tp_a'"+hv_xy="$("$bin" snapshot --app "$app" --include-bounds --max-depth 30 2>/dev/null | python3 -c "import json,sys+d=json.load(sys.stdin)+def f(n):+ if n.get('name')=='hover-target' and n.get('bounds'):+ b=n['bounds']; return f\"{b['x']+b['width']/2},{b['y']+b['height']/2}\"+ for c in n.get('children',[]):+ r=f(c)+ if r: return r+print(f(d['data']['tree']) or '')" 2>/dev/null)"+hv_b="$(read_value hover-status)"+if [ -n "$hv_xy" ]; then+ "$bin" --headed hover --xy "$hv_xy" >/dev/null 2>&1; sleep 0.5+ hv_a="$(read_value hover-status)"+ assert "--headed hover triggers onHover" "$([ "$hv_a" = "hovered" ] && echo 1 || echo 0)" \+ "xy='$hv_xy' hover-status before='$hv_b' after='$hv_a'"+else+ assert "--headed hover triggers onHover" 0 "hover-target bounds not found in snapshot (no xy to hover)"+fi++note "strict resolution acts on the addressed twin, never the other"+"$bin" focus-window --app "$app" >/dev/null 2>&1+tw="$(resolve button twin-control)"+tw_b="$(read_value twin-status)"+out="$("$bin" click "$tw" 2>&1)"; sleep 0.3+tw_a="$(read_value twin-status)"+acode="$(echo "$out" | field "['error']['code']")"; aok="$(echo "$out" | field "['ok']")"+if [ "$aok" = "True" ]; then+ assert "addressed twin fired (not the other)" "$([ "$tw_a" = "twin-a" ] && echo 1 || echo 0)" \+ "ref='$tw' twin-status before='$tw_b' after='$tw_a' (must be twin-a)"+elif [ "$acode" = "AMBIGUOUS_TARGET" ]; then+ assert "twins fail closed on ambiguity" 1 "ref='$tw' code='$acode' (no silent pick)"+else+ assert "twin resolution honest" 0 "ref='$tw' code='$acode' ok=$aok after='$tw_a'"+fi++note "removed element fails closed"+sid="$("$bin" snapshot --app "$app" | field "['data']['snapshot_id']")"+stale="$(python3 -c "import json,subprocess+d=json.loads(subprocess.run(['$bin','snapshot','--app','$app','--snapshot','$sid','--max-depth','30'],capture_output=True,text=True).stdout)+def f(n):+ if n.get('name')=='removable-row' and n.get('ref_id'): return n['ref_id']+ for c in n.get('children',[]):+ r=f(c)+ if r: return r+print(f(d['data']['tree']) or '')" 2>/dev/null)"+"$bin" click "$(resolve button remove-row)" >/dev/null 2>&1; sleep 0.4+out="$("$bin" click "$stale" --snapshot "$sid" 2>&1)"; code="$(echo "$out" | field "['error']['code']")"; ok="$(echo "$out" | field "['ok']")"+case "$code" in+ STALE_REF) assert "removed -> STALE_REF" 1 "ref='$stale' code='$code' ok=$ok" ;;+ TIMEOUT|ELEMENT_NOT_FOUND|AMBIGUOUS_TARGET) assert "removed failed closed" 1 "ref='$stale' code='$code' (STALE_REF preferred)" ;;+ *) assert "removed failed closed" 0 "ref='$stale' code='$code' ok=$ok (acted on removed element!)" ;;+esac++note "wait predicates"+"$bin" click "$(resolve button enable-later)" >/dev/null 2>&1+we="$("$bin" wait --element "$(resolve button delayed-button)" --predicate enabled --timeout 5000 2>/dev/null)"+assert "wait enabled (async)" "$([ "$(echo "$we" | field "['data']['found']")" = "True" ] && echo 1 || echo 0)" \+ "found=$(echo "$we" | field "['data']['found']") elapsed_ms=$(echo "$we" | field "['data']['elapsed_ms']")"+pb="$(resolve button primary-button)"+wa="$("$bin" wait --element "$pb" --predicate actionable --timeout 3000 2>/dev/null)"+assert "predicate actionable" "$([ "$(echo "$wa" | field "['data']['found']")" = "True" ] && echo 1 || echo 0)" \+ "found=$(echo "$wa" | field "['data']['found']") actionable=$(echo "$wa" | field "['data']['observed']['actionable']")"+wv="$("$bin" wait --element "$pb" --predicate visible --timeout 3000 2>/dev/null)"+assert "predicate visible" "$([ "$(echo "$wv" | field "['data']['found']")" = "True" ] && echo 1 || echo 0)" "found=$(echo "$wv" | field "['data']['found']")"+"$bin" set-value "$(resolve textfield text-input)" "pred-val" >/dev/null 2>&1; sleep 0.3+wval="$("$bin" wait --element "$(resolve textfield text-input)" --predicate value --value pred-val --timeout 3000 2>/dev/null)"+assert "predicate value" "$([ "$(echo "$wval" | field "['data']['found']")" = "True" ] && echo 1 || echo 0)" \+ "found=$(echo "$wval" | field "['data']['found']") matched=$(echo "$wval" | field "['data']['observed']['matched']")"++note "wait --text (async appear)"+"$bin" click "$(resolve button appear-later)" >/dev/null 2>&1+wt="$("$bin" wait --text appeared-text --app "$app" --timeout 5000 2>/dev/null)"+assert "wait text resolved" "$([ "$(echo "$wt" | field "['data']['found']")" = "True" ] && echo 1 || echo 0)" \+ "found=$(echo "$wt" | field "['data']['found']") elapsed_ms=$(echo "$wt" | field "['data']['elapsed_ms']")"++note "skeleton traversal + scoped drill-down"+sk="$("$bin" snapshot --app "$app" --skeleton 2>/dev/null)"; sk_id="$(echo "$sk" | field "['data']['snapshot_id']")"+sk_refs="$(echo "$sk" | field "['data']['ref_count']")"+anchor="$(echo "$sk" | python3 -c "import json,sys+d=json.load(sys.stdin)+def f(n):+ if n.get('children_count') and n.get('ref_id'): return n['ref_id']+ for c in n.get('children',[]):+ r=f(c)+ if r: return r+print(f(d['data']['tree']) or '')" 2>/dev/null)"+drilled="$([ -n "$anchor" ] && "$bin" snapshot --app "$app" --root "$anchor" --snapshot "$sk_id" 2>/dev/null | field "['data']['ref_count']")"+assert "skeleton + drill-down" "$([ -n "$anchor" ] && [ -n "$drilled" ] && [ "$drilled" -gt 0 ] && echo 1 || echo 0)" \+ "skeleton_refs=$sk_refs anchor='$anchor' drilled_refs='$drilled'"++note "session isolation + session-independent explicit snapshot"+sa_out="$("$bin" --session run-a snapshot --app "$app" 2>/dev/null)"+sa="$(echo "$sa_out" | field "['data']['snapshot_id']")"+sb="$("$bin" --session run-b snapshot --app "$app" 2>/dev/null | field "['data']['snapshot_id']")"+assert "sessions keep distinct latest pointers" "$([ -n "$sa" ] && [ -n "$sb" ] && [ "$sa" != "$sb" ] && echo 1 || echo 0)" "run-a='$sa' run-b='$sb'"+ra="$(echo "$sa_out" | python3 -c "import json,sys+d=json.load(sys.stdin)+def f(n):+ if n.get('name')=='primary-button' and n.get('ref_id'): return n['ref_id']+ for c in n.get('children',[]):+ r=f(c)+ if r: return r+print(f(d['data']['tree']) or '')" 2>/dev/null)"+xok="$("$bin" get "$ra" --snapshot "$sa" 2>/dev/null | field "['ok']")"+assert "session-a snapshot resolves without --session" "$([ "$xok" = "True" ] && echo 1 || echo 0)" "ref='$ra' snapshot='$sa' get_ok=$xok"++note "trace JSONL + secret redaction"+trf="$(mktemp -t agentdesk-e2e-trace.XXXXXX)"+"$bin" --trace "$trf" type "$(resolve textfield text-input)" "sup3r-secret-trace" >/dev/null 2>&1; sleep 0.2+bytes="$(wc -c < "$trf" | tr -d ' ')"+has_events="$(grep -qc 'ref.resolve' "$trf" && echo 1 || echo 0)"+leaked="$(grep -qc 'sup3r-secret-trace' "$trf" && echo 1 || echo 0)"+redacted="$(grep -qc 'redacted' "$trf" && echo 1 || echo 0)"+assert "trace recorded resolver events" "$has_events" "bytes=$bytes resolver_events=$([ "$has_events" = 1 ] && echo yes || echo no)"+assert "typed secret NOT in trace" "$([ "$leaked" = "0" ] && echo 1 || echo 0)" "secret_present=$([ "$leaked" = 1 ] && echo YES || echo no) redaction_markers=$([ "$redacted" = 1 ] && echo yes || echo no)"+rm -f "$trf"++note "surface: open sheet, list-surfaces sees it, act inside"+sheet_b="$(read_value sheet-status)"+"$bin" click "$(resolve button open-sheet)" >/dev/null 2>&1; sleep 0.6+surf="$("$bin" list-surfaces --app "$app" 2>&1)"+surf_has_sheet="$(echo "$surf" | grep -qci sheet && echo 1 || echo 0)"+assert "list-surfaces reports the sheet" "$surf_has_sheet" "surfaces=$(echo "$surf" | field "['data']['surfaces']")"+"$bin" focus-window --app "$app" >/dev/null 2>&1+"$bin" click "$(resolve button confirm-sheet)" >/dev/null 2>&1; sleep 0.5+sheet_a="$(read_value sheet-status)"+assert "acted inside the sheet" "$([ "$sheet_a" = "confirmed" ] && echo 1 || echo 0)" "sheet-status before='$sheet_b' after='$sheet_a'"++note "context menu: right-click opens it, select an item, observe the effect"+"$bin" focus-window --app "$app" >/dev/null 2>&1+rc_b="$(read_value right-status)"+rc_out="$("$bin" right-click "$(resolve button context-target)" 2>&1)"; sleep 0.5+rc_menu="$(echo "$rc_out" | python3 -c "import json,sys;print(bool(json.load(sys.stdin).get('data',{}).get('menu')))" 2>/dev/null)"+cc="$(resolve menuitem context-choice)"+"$bin" click "$cc" >/dev/null 2>&1; sleep 0.4+rc_a="$(read_value right-status)"+assert "right-click opens a verifiable context menu" "$([ "$rc_menu" = "True" ] && echo 1 || echo 0)" "menu_in_response=$rc_menu"+assert "selecting a context-menu item fires it" "$([ "$rc_a" = "context-picked" ] && echo 1 || echo 0)" \+ "context-choice ref='$cc' right-status before='$rc_b' after='$rc_a'"++note "menu bar: the app menu bar is enumerable via --surface menubar"+mb_snap="$("$bin" snapshot --app "$app" --surface menubar --max-depth 5 2>/dev/null)"+mb_items="$(echo "$mb_snap" | grep -oc '"role":"menuitem"')"+has_fixture="$(echo "$mb_snap" | grep -qc '"name":"Fixture"' && echo 1 || echo 0)"+assert "menu bar exposes the custom 'Fixture' menu" "$has_fixture" \+ "menuitems=$mb_items custom_menu=$([ "$has_fixture" = 1 ] && echo found || echo MISSING)"++note "drag: source-tracked gesture across a single view (verified by canvas)"+dr_b="$(read_value drag-canvas-status)"+cxy="$("$bin" snapshot --app "$app" --include-bounds --max-depth 30 2>/dev/null | python3 -c "import json,sys+d=json.load(sys.stdin)+def f(n):+ if n.get('name')=='drag-canvas' and n.get('bounds'):+ b=n['bounds']; return b+ for c in n.get('children',[]):+ r=f(c)+ if r: return r+b=f(d['data']['tree'])+print(f\"{b['x']+20},{b['y']+b['height']/2} {b['x']+b['width']-20},{b['y']+b['height']/2}\" if b else '')" 2>/dev/null)"+from_xy="$(echo "$cxy" | awk '{print $1}')"; to_xy="$(echo "$cxy" | awk '{print $2}')"+"$bin" --headed drag --from-xy "$from_xy" --to-xy "$to_xy" --duration 400 --drop-delay 300 >/dev/null 2>&1; sleep 0.4+dr_a="$(read_value drag-canvas-status)"+assert "drag delivered a gesture" "$(echo "$dr_a" | grep -q '^dragged-' && echo 1 || echo 0)" "from='$from_xy' to='$to_xy' canvas before='$dr_b' after='$dr_a'"++note "expand a press-toggled disclosure (verified by disclosure value)"+"$bin" collapse "$(resolve disclosure disclosure-section)" >/dev/null 2>&1; sleep 0.4+exp_b="$("$bin" get "$(resolve disclosure disclosure-section)" 2>/dev/null | field "['data']['value']")"+eout="$("$bin" expand "$(resolve disclosure disclosure-section)" 2>&1)"; sleep 0.4+exp_a="$("$bin" get "$(resolve disclosure disclosure-section)" 2>/dev/null | field "['data']['value']")"+eok="$(echo "$eout" | field "['ok']")"+if [ "$exp_b" = "true" ]; then+ skip "expand unprovable: pre-collapse did not land, disclosure already expanded [value before='$exp_b' after='$exp_a' cmd_ok=$eok]"+elif [ "$exp_a" = "true" ]; then+ assert "expand flipped disclosure from collapsed to expanded" 1 "value before='$exp_b' after='$exp_a' cmd_ok=$eok"+elif [ "$eok" = "False" ]; then+ skip "expand honestly failed (disclosure not AX-actionable) [value before='$exp_b' after='$exp_a' cmd_ok=$eok]"+else+ assert "expand flipped disclosure from collapsed to expanded" 0 "claimed success but value before='$exp_b' after='$exp_a' cmd_ok=$eok"+fi++note "performance (CLI execution time per operation, ms)"+"$bin" focus-window --app "$app" >/dev/null 2>&1+pbref="$(resolve button primary-button)"; tfref="$(resolve textfield text-input)"+timed "snapshot (full, depth 30)" "$bin" snapshot --app "$app" --max-depth 30 >/dev/null+timed "snapshot (skeleton)" "$bin" snapshot --app "$app" --skeleton >/dev/null+timed "find (role+name)" "$bin" find --app "$app" --role button --name primary-button --first >/dev/null+timed "get (element value)" "$bin" get "$pbref" >/dev/null+timed "click (AX press)" "$bin" click "$pbref" >/dev/null+timed "set-value (textfield)" "$bin" set-value "$tfref" "perf-probe" >/dev/null+timed "type (textfield)" "$bin" type "$tfref" "perf" >/dev/null+if [ -s "$PERF_FILE" ]; then+ awk -F'\t' '{printf " %-26s %9.1f ms\n",$1,$2; n++; s+=$2}+ END{if(n) printf " %-26s %9.1f ms (mean of %d ops)\n","[mean]",s/n,n}' "$PERF_FILE"+ snapms="$(awk -F'\t' '/snapshot \(full/{print $2; exit}' "$PERF_FILE")"+ assert "full snapshot under 2s target" \+ "$(python3 -c "print(1 if float('${snapms:-99999}')<2000 else 0)")" \+ "snapshot=${snapms}ms (documented target <2000ms)"+fi++note "close-app --force terminates (observed via list-apps)"+run_b="$(running)"+"$bin" close-app "$app" --force >/dev/null 2>&1; sleep 1.5+run_a="$(running)"+assert "force close removed app" "$([ "$run_a" = "False" ] && echo 1 || echo 0)" "running before=$run_b after=$run_a"++note "Documented limitations (tracked separately, not failures)"+skip "cross-target native drag-and-drop (onDrop) needs the OS dragging-session/pasteboard protocol; synthetic mouse events route mouse-up to the drag origin, so they cannot drop onto a separate native target (works for source-tracked gestures, web/Electron mouse-DnD)"+skip "SwiftUI Slider/Stepper/DisclosureGroup are not AX-actionable; native AppKit equivalents are (set-value/expand work on those)"+skip "SwiftUI CommandMenu (menu-bar) items accept AXPress (verified_press succeeds) but do not route to their action closure, so firing a custom top-menu item has no effect; native AppKit menu items DO fire via AX. Menu-bar enumeration (--surface menubar), menu opening, and .contextMenu item selection all work."++note "Summary"+printf ' passed: %d skipped: %d failed: %d\n' "$pass" "$skip_count" "$fail"+if [ "$fail" -gt 0 ]; then+ printf '\n failures (observed values inline above):\n'+ for f in "${failures[@]}"; do printf ' - %s\n' "$f"; done+ exit 1+fi+echo " all asserted E2E scenarios passed"diff --git a/tests/fixture-app/AgentDeskFixture.swift b/tests/fixture-app/AgentDeskFixture.swiftnew file mode 100644index 000000000..b530fc1b6--- /dev/null+++ b/tests/fixture-app/AgentDeskFixture.swift@@ -0,0 +1,375 @@+import SwiftUI++// A deterministic, deliberately *diverse* accessibility surface for+// agent-desktop end-to-end tests. The goal is to mirror how real macOS apps+// vary — refs assigned to some elements and not others, state exposed as a+// value here and as content there, draggable things that are not buttons,+// nested tables and outlines, sheets and popovers and menus — so the CLI is+// exercised against the real spread, not a happy path. This fixture is never+// tuned to make a command pass; when a command fails against a realistic+// pattern here, that is a finding about the CLI.+//+// Verification principle: interactive controls write their result into a+// StatusReadout whose live state is the accessibility *value*, so the harness+// reads the real outcome instead of trusting a command's self-report.+++struct ContentView: View {+ // interaction+ @State private var clickStatus = "idle"+ @State private var clickCount = 0+ @State private var doubleStatus = "idle"+ @State private var tripleStatus = "idle"+ @State private var rightStatus = "idle"+ @State private var hoverStatus = "idle"+ @State private var twinStatus = "idle"+ // text+ @State private var textValue = ""+ @State private var secureValue = ""+ @State private var multilineValue = "line one\nline two"+ // state controls+ @State private var toggleOn = false+ @State private var pickerChoice = "Alpha"+ @State private var radioChoice = "One"+ @State private var disclosureExpanded = false+ @State private var tabSelection = 0+ // collections+ @State private var tableSelection: Int?+ // async / dynamic+ @State private var delayedEnabled = false+ @State private var delayedText = "waiting"+ @State private var removableVisible = true+ @State private var appearedText = ""+ // drag+ @State private var dropStatus = "empty"+ @State private var rowDropStatus = "empty"+ @State private var dragCanvasResult = "idle"+ // native AppKit controls (genuinely AX-settable, unlike SwiftUI's)+ @State private var nativeSliderValue = 0.0+ @State private var nativeStepperValue = 0.0+ // surfaces+ @State private var showSheet = false+ @State private var showPopover = false+ @State private var sheetStatus = "idle"+ @State private var sheetFieldValue = ""++ var body: some View {+ ScrollView([.vertical, .horizontal]) {+ VStack(alignment: .leading, spacing: 16) {+ Text("AgentDesk Fixture")+ .font(.title2)+ .accessibilityLabel("fixture-title")+ row1+ row2+ row3+ }+ .padding(20)+ }+ .frame(minWidth: 980, minHeight: 720)+ .sheet(isPresented: $showSheet) { sheetContent }+ }++ private var row1: some View {+ HStack(alignment: .top, spacing: 16) {+ clicksCard+ textCard+ stateCard+ }+ }++ private var row2: some View {+ HStack(alignment: .top, spacing: 16) {+ choiceCard+ collectionsCard+ asyncCard+ }+ }++ private var row3: some View {+ HStack(alignment: .top, spacing: 16) {+ dragCard+ surfacesCard+ ScrollCard()+ }+ }++ // MARK: clicks / mouse++ private var clicksCard: some View {+ Card(title: "Clicks & Mouse") {+ Button("Primary Action") { clickCount += 1; clickStatus = "click-\(clickCount)" }+ .accessibilityLabel("primary-button")+ StatusReadout(name: "click-status", value: clickStatus)++ Button("Double Target") { }+ .accessibilityLabel("double-target")+ .simultaneousGesture(TapGesture(count: 2).onEnded { doubleStatus = "double-clicked" })+ StatusReadout(name: "double-status", value: doubleStatus)++ Button("Triple Target") { }+ .accessibilityLabel("triple-target")+ .simultaneousGesture(TapGesture(count: 3).onEnded { tripleStatus = "triple-clicked" })+ StatusReadout(name: "triple-status", value: tripleStatus)++ Button("Context Target") { }+ .accessibilityLabel("context-target")+ .contextMenu {+ Button("Context Choice") { rightStatus = "context-picked" }+ .accessibilityLabel("context-choice")+ }+ StatusReadout(name: "right-status", value: rightStatus)++ Text("Hover Target")+ .padding(6)+ .background(hoverStatus == "hovered" ? Color.yellow.opacity(0.4) : Color.clear)+ .accessibilityLabel("hover-target")+ .onHover { inside in if inside { hoverStatus = "hovered" } }+ StatusReadout(name: "hover-status", value: hoverStatus)++ /// Two controls sharing role and name. Each records a distinct+ /// effect so the harness can prove strict resolution acts on the+ /// addressed twin, never silently the other.+ Button("Twin Control") { twinStatus = "twin-a" }.accessibilityLabel("twin-control")+ Button("Twin Control") { twinStatus = "twin-b" }.accessibilityLabel("twin-control")+ StatusReadout(name: "twin-status", value: twinStatus)+ }+ }++ // MARK: text input variety++ private var textCard: some View {+ Card(title: "Text Input") {+ TextField("Text Input", text: $textValue)+ .accessibilityLabel("text-input")+ StatusReadout(name: "text-echo", value: textValue)++ SecureField("Secure Input", text: $secureValue)+ .accessibilityLabel("secure-input")+ StatusReadout(name: "secure-echo", value: secureValue.isEmpty ? "empty" : "set")++ TextEditor(text: $multilineValue)+ .frame(height: 60)+ .accessibilityLabel("multiline-input")++ Link("Example Link", destination: URL(string: "https://example.com")!)+ .accessibilityLabel("example-link")+ }+ }++ // MARK: toggles / sliders / steppers / disclosure++ private var stateCard: some View {+ Card(title: "State Controls") {+ Toggle("Toggle Box", isOn: $toggleOn).accessibilityLabel("toggle-box")+ StatusReadout(name: "toggle-status", value: toggleOn ? "on" : "off")++ // Native AppKit slider and stepper: unlike SwiftUI's, these expose a+ // working AX value/increment interface, so set-value can drive them.+ // The harness-facing labels (value-slider/value-stepper) live on the+ // NSViews themselves — the AX-actionable elements — so exactly one+ // label source exists regardless of how SwiftUI wraps them.+ NativeSlider(value: $nativeSliderValue).frame(width: 180, height: 20)+ StatusReadout(name: "slider-status", value: String(Int(nativeSliderValue)))+ NativeStepper(value: $nativeStepperValue)+ StatusReadout(name: "stepper-status", value: String(Int(nativeStepperValue)))++ DisclosureGroup("Disclosure Section", isExpanded: $disclosureExpanded) {+ Text("Disclosed Content").accessibilityLabel("disclosed-content")+ }+ .accessibilityLabel("disclosure-section")+ }+ }++ // MARK: pickers / radios / tabs++ private var choiceCard: some View {+ Card(title: "Choices") {+ Picker("Option Picker", selection: $pickerChoice) {+ Text("Alpha").tag("Alpha")+ Text("Beta").tag("Beta")+ Text("Gamma").tag("Gamma")+ }+ .accessibilityLabel("option-picker")+ StatusReadout(name: "picker-status", value: pickerChoice)++ Picker("Radio Group", selection: $radioChoice) {+ Text("One").tag("One")+ Text("Two").tag("Two")+ Text("Three").tag("Three")+ }+ .pickerStyle(.radioGroup)+ .accessibilityLabel("radio-group")+ StatusReadout(name: "radio-status", value: radioChoice)++ TabView(selection: $tabSelection) {+ Text("Tab One Body").accessibilityLabel("tab-one-body").tabItem { Text("Tab One") }.tag(0)+ Text("Tab Two Body").accessibilityLabel("tab-two-body").tabItem { Text("Tab Two") }.tag(1)+ }+ .frame(height: 90)+ .accessibilityLabel("tab-view")+ StatusReadout(name: "tab-status", value: String(tabSelection))+ }+ }++ // MARK: table / outline++ private var collectionsCard: some View {+ Card(title: "Collections") {+ List(selection: $tableSelection) {+ ForEach(1...6, id: \.self) { i in+ Text("List Item \(i)").accessibilityLabel("list-item-\(i)").tag(i)+ }+ }+ .frame(height: 120)+ .accessibilityLabel("item-list")+ StatusReadout(name: "list-selection", value: tableSelection.map(String.init) ?? "none")++ DisclosureGroup("Outline Parent") {+ Text("Outline Child A").accessibilityLabel("outline-child-a")+ Text("Outline Child B").accessibilityLabel("outline-child-b")+ }+ .accessibilityLabel("outline-parent")+ }+ }++ // MARK: async / dynamic++ private var asyncCard: some View {+ Card(title: "Async & Dynamic") {+ Button("Enable Later") {+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {+ delayedEnabled = true+ delayedText = "ready"+ }+ }+ .accessibilityLabel("enable-later")+ Button("Delayed Button") { }+ .disabled(!delayedEnabled)+ .accessibilityLabel("delayed-button")+ StatusReadout(name: "delayed-text", value: delayedText)++ Button("Appear Later") {+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { appearedText = "appeared-text" }+ }+ .accessibilityLabel("appear-later")+ if !appearedText.isEmpty {+ Text(appearedText).accessibilityLabel("appeared-text")+ }++ if removableVisible {+ Button("Removable Row") { }.accessibilityLabel("removable-row")+ }+ Button("Remove Row") { removableVisible = false }.accessibilityLabel("remove-row")+ }+ }++ // MARK: drag (interactive row + non-interactive image)++ private var dragCard: some View {+ Card(title: "Drag & Drop") {+ // Drag the canvas from one point to another within itself: a+ // source-tracked gesture, which synthetic mouse events can drive.+ // Its harness label lives on the NSView itself (DragCanvasView),+ // keeping exactly one AX label source.+ DragCanvas(result: $dragCanvasResult)+ .frame(width: 200, height: 80)+ .background(Color.purple.opacity(0.12))+ StatusReadout(name: "drag-canvas-status", value: dragCanvasResult)+ // A non-interactive image drag source: realistic (file icons, custom+ // views) and intentionally NOT a button, so the CLI is tested on a+ // ref-less draggable.+ Image(systemName: "doc.fill")+ .resizable()+ .frame(width: 44, height: 44)+ .accessibilityLabel("image-drag-source")+ .onDrag { NSItemProvider(object: "image-item" as NSString) }++ // An interactive row drag source (ref-able), the common case.+ Text("Row Drag Source")+ .padding(6)+ .background(Color.blue.opacity(0.15))+ .accessibilityLabel("row-drag-source")+ .accessibilityAddTraits(.isButton)+ .onDrag { NSItemProvider(object: "row-item" as NSString) }++ // The drop-status readouts are siblings (not overlays) so the+ // accessibilityLabel on the drop rectangle does not absorb them and+ // the harness can read the drop result independently.+ RoundedRectangle(cornerRadius: 8)+ .stroke(dropStatus == "dropped" ? Color.green : Color.gray)+ .frame(width: 200, height: 60)+ .accessibilityLabel("drop-zone")+ .onDrop(of: ["public.text"], isTargeted: nil) { _ in dropStatus = "dropped"; return true }+ StatusReadout(name: "drop-status", value: dropStatus)++ RoundedRectangle(cornerRadius: 8)+ .stroke(rowDropStatus == "dropped" ? Color.green : Color.gray)+ .frame(width: 200, height: 60)+ .accessibilityLabel("row-drop-zone")+ .onDrop(of: ["public.text"], isTargeted: nil) { _ in rowDropStatus = "dropped"; return true }+ StatusReadout(name: "row-drop-status", value: rowDropStatus)+ }+ }++ // MARK: surfaces (sheet / popover)++ private var surfacesCard: some View {+ Card(title: "Surfaces") {+ Button("Open Sheet") { showSheet = true }.accessibilityLabel("open-sheet")+ StatusReadout(name: "sheet-status", value: sheetStatus)++ Button("Open Popover") { showPopover = true }+ .accessibilityLabel("open-popover")+ .popover(isPresented: $showPopover) {+ VStack {+ Text("Popover Body").accessibilityLabel("popover-body")+ Button("Close Popover") { showPopover = false }.accessibilityLabel("close-popover")+ }+ .padding()+ }+ }+ }++ private var sheetContent: some View {+ VStack(spacing: 12) {+ Text("Sheet Title").font(.headline).accessibilityLabel("sheet-title")+ TextField("Sheet Field", text: $sheetFieldValue).accessibilityLabel("sheet-field").frame(width: 200)+ Button("Confirm Sheet") { sheetStatus = "confirmed"; showSheet = false }+ .accessibilityLabel("confirm-sheet")+ Button("Cancel Sheet") { sheetStatus = "cancelled"; showSheet = false }+ .accessibilityLabel("cancel-sheet")+ }+ .padding(24)+ .frame(width: 320, height: 200)+ }++}++@main+struct AgentDeskFixtureApp: App {+ @NSApplicationDelegateAdaptor(AppDelegate.self) var delegate+ var body: some Scene {+ WindowGroup("AgentDesk Fixture") { ContentView() }+ .commands {+ // Custom top menu so the harness can verify the app menu bar is+ // enumerable via `snapshot --surface menubar`. (SwiftUI+ // CommandMenu items accept AXPress but do not route to their+ // action closure — a SwiftUI limitation, like its Slider; native+ // AppKit menu items fire via AX.)+ CommandMenu("Fixture") {+ Button("Fire Menu Item") {}.accessibilityLabel("menu-fire-item")+ }+ }+ }+}++final class AppDelegate: NSObject, NSApplicationDelegate {+ func applicationDidFinishLaunching(_ notification: Notification) {+ NSApp.setActivationPolicy(.regular)+ // Bring the window up without forcibly stealing focus from other apps:+ // the E2E harness drives focus explicitly via focus-window, and an+ // unconditional steal could mask headless-policy focus violations.+ NSApp.activate(ignoringOtherApps: false)+ }+ func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true }+}diff --git a/tests/fixture-app/FixtureCards.swift b/tests/fixture-app/FixtureCards.swiftnew file mode 100644index 000000000..76d9fb2b1--- /dev/null+++ b/tests/fixture-app/FixtureCards.swift@@ -0,0 +1,33 @@+import SwiftUI++// Overflow card extracted from AgentDeskFixture.swift to keep that file under+// the 400-LOC limit. All accessibility labels are preserved byte-for-byte so+// the E2E harness (tests/e2e/run.sh) continues to resolve them unchanged.+// The build compiles every .swift file in this directory as one module.++struct ScrollCard: View {+ @State private var scrollOffset = 0++ var body: some View {+ Card(title: "Scroll") {+ StatusReadout(name: "scroll-offset", value: String(scrollOffset))+ ScrollView {+ VStack(alignment: .leading) {+ GeometryReader { geo in+ Color.clear.preference(+ key: ScrollOffsetKey.self,+ value: geo.frame(in: .named("scroll-space")).minY)+ }+ .frame(height: 0)+ ForEach(1...60, id: \.self) { i in+ Text("Scroll Row \(i)").accessibilityLabel("scroll-row-\(i)")+ }+ }+ }+ .coordinateSpace(name: "scroll-space")+ .onPreferenceChange(ScrollOffsetKey.self) { scrollOffset = Int(-$0) }+ .frame(width: 220, height: 160)+ .accessibilityLabel("scroll-area")+ }+ }+}diff --git a/tests/fixture-app/FixtureComponents.swift b/tests/fixture-app/FixtureComponents.swiftnew file mode 100644index 000000000..4089745d9--- /dev/null+++ b/tests/fixture-app/FixtureComponents.swift@@ -0,0 +1,127 @@+import AppKit+import SwiftUI++// Reusable fixture components: status readout, native AppKit controls+// (genuinely AX-actionable, unlike SwiftUI's), drag canvas, and card chrome.+// Split from AgentDeskFixture.swift to keep each file under the 400-LOC limit;+// the build compiles every .swift file in this directory as one module.++struct StatusReadout: View {+ let name: String+ let value: String+ var body: some View {+ Text("\(name): \(value)")+ .accessibilityLabel(name)+ .accessibilityValue(value)+ }+}++// Exposes a ScrollView's live scroll offset as an accessibility value so the+// test harness can confirm `scroll` actually moved content, rather than+// trusting the command's ok:true.+struct ScrollOffsetKey: PreferenceKey {+ static var defaultValue: CGFloat = 0+ static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { value = nextValue() }+}++// Native AppKit controls embedded alongside the SwiftUI ones. SwiftUI sliders+// and steppers do not expose a settable AX value, so they cannot validate the+// numeric set-value path; their AppKit counterparts do, exercising the same+// command against a control that genuinely accepts a programmatic value.+struct NativeSlider: NSViewRepresentable {+ @Binding var value: Double+ func makeNSView(context: Context) -> NSSlider {+ let s = NSSlider(+ value: value, minValue: 0, maxValue: 100,+ target: context.coordinator, action: #selector(Coordinator.changed(_:)))+ s.setAccessibilityLabel("value-slider")+ return s+ }+ func updateNSView(_ view: NSSlider, context: Context) { view.doubleValue = value }+ func makeCoordinator() -> NativeControlCoordinator { NativeControlCoordinator { value = $0 } }+}++struct NativeStepper: NSViewRepresentable {+ @Binding var value: Double+ func makeNSView(context: Context) -> NSStepper {+ let s = NSStepper()+ s.minValue = 0+ s.maxValue = 10+ s.increment = 1+ s.valueWraps = false+ s.target = context.coordinator+ s.action = #selector(NativeControlCoordinator.changed(_:))+ s.setAccessibilityLabel("value-stepper")+ return s+ }+ func updateNSView(_ view: NSStepper, context: Context) { view.doubleValue = value }+ func makeCoordinator() -> NativeControlCoordinator { NativeControlCoordinator { value = $0 } }+}++// Shared target for native controls; NSControl exposes doubleValue for both+// NSSlider and NSStepper.+final class NativeControlCoordinator: NSObject {+ let onChange: (Double) -> Void+ init(_ onChange: @escaping (Double) -> Void) { self.onChange = onChange }+ @objc func changed(_ sender: NSControl) { onChange(sender.doubleValue) }+}++// A single view that tracks a mouse-drag gesture end to end (down, dragged,+// up). Synthetic mouse events route to whoever received the mouse-down, so a+// drag is observable when source and target are the same view — which is what+// `agent-desktop drag` can do. Cross-target native drag-and-drop uses the OS+// dragging-session/pasteboard protocol that synthetic events cannot start.+struct DragCanvas: NSViewRepresentable {+ @Binding var result: String+ func makeNSView(context: Context) -> DragCanvasView {+ let v = DragCanvasView()+ // The closure captures `result` by reference; DragCanvasView calls it+ // directly on each mouseUp, so updateNSView needs no re-sync.+ v.onDrag = { result = $0 }+ return v+ }+ func updateNSView(_ view: DragCanvasView, context: Context) {+ // Intentionally empty: gesture results flow *out* through the captured+ // binding (via onDrag), never *in* from SwiftUI state — nothing to sync.+ }+}++final class DragCanvasView: NSView {+ var onDrag: ((String) -> Void)?+ private var start: NSPoint?+ private var dragged = false+ override func viewDidMoveToWindow() {+ super.viewDidMoveToWindow()+ setAccessibilityElement(true)+ setAccessibilityRole(.group)+ setAccessibilityLabel("drag-canvas")+ }+ override func accessibilityFrame() -> NSRect {+ guard let window else { return .zero }+ return window.convertToScreen(convert(bounds, to: nil))+ }+ override func isAccessibilityElement() -> Bool { true }+ override func mouseDown(with e: NSEvent) { start = convert(e.locationInWindow, from: nil); dragged = false }+ override func mouseDragged(with e: NSEvent) { dragged = true }+ override func mouseUp(with e: NSEvent) {+ guard let s = start else { return }+ let end = convert(e.locationInWindow, from: nil)+ let dist = Int((hypot(end.x - s.x, end.y - s.y)).rounded())+ onDrag?(dragged ? "dragged-\(dist)" : "click")+ start = nil+ }+}++struct Card<Content: View>: View {+ let title: String+ @ViewBuilder var content: Content+ var body: some View {+ VStack(alignment: .leading, spacing: 8) {+ Text(title).font(.headline)+ content+ }+ .padding(10)+ .frame(width: 280, alignment: .leading)+ .background(RoundedRectangle(cornerRadius: 8).fill(Color.gray.opacity(0.08)))+ }+}diff --git a/tests/fixture-app/build.sh b/tests/fixture-app/build.shnew file mode 100755index 000000000..66c56672c--- /dev/null+++ b/tests/fixture-app/build.sh@@ -0,0 +1,46 @@+#!/usr/bin/env bash+# Builds the agent-desktop E2E fixture into a runnable .app bundle.+# Usage: tests/fixture-app/build.sh [output-dir]+# Output: <output-dir>/AgentDeskFixture.app (default: alongside this script)+set -euo pipefail++here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+out_dir="${1:-$here/build}"+app="$out_dir/AgentDeskFixture.app"+macos_dir="$app/Contents/MacOS"+bin="$macos_dir/AgentDeskFixture"++rm -rf "$app"+mkdir -p "$macos_dir"++# Pin the SDK and deployment target so the fixture builds reproducibly instead+# of inheriting whatever the host toolchain defaults to (matches the+# LSMinimumSystemVersion in the Info.plist below). Compile every .swift file in+# this directory as one module.+sdk="$(xcrun --show-sdk-path --sdk macosx)"+target="$(uname -m)-apple-macos13.0"+swiftc -O -parse-as-library \+ -target "$target" -sdk "$sdk" \+ -framework SwiftUI -framework AppKit \+ -o "$bin" \+ "$here"/*.swift++cat > "$app/Contents/Info.plist" <<'PLIST'+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleName</key><string>AgentDeskFixture</string>+ <key>CFBundleDisplayName</key><string>AgentDeskFixture</string>+ <key>CFBundleIdentifier</key><string>com.agentdesktop.fixture</string>+ <key>CFBundleVersion</key><string>1</string>+ <key>CFBundleShortVersionString</key><string>1.0</string>+ <key>CFBundlePackageType</key><string>APPL</string>+ <key>CFBundleExecutable</key><string>AgentDeskFixture</string>+ <key>LSMinimumSystemVersion</key><string>13.0</string>+ <key>NSHighResolutionCapable</key><true/>+</dict>+</plist>+PLIST++echo "Built: $app"