Skip to content

Computer use CLI for AI agents

fix(macos): resolve native menus and verify lifecycle transitions (#376)

Lahfir5e0491ae9cfe
diff --git a/AGENTS.md b/AGENTS.md
index 608c87a60..21b6223d1 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -7,6 +7,15 @@ accessibility trees and returns structured JSON with ref-based element ids. The
calling agent. It never embeds an LLM and has no GUI or interactive prompt. It does not automate web pages (use
agent-browser). It cannot see UIs that expose no accessibility tree.
+## Critical: fixes must be application-agnostic
+
+Every fix must work through the platform's shared accessibility and lifecycle contracts across applications.
+Never add app-specific branches keyed by app names, bundle IDs, executables, window titles, or a known app's UI layout.
+Use observed capabilities, roles, ownership, and process identity in the shared platform adapter. Preserve safe failure
+when the platform cannot establish the required identity or capability. Verify changed behavior against multiple real
+apps and relevant UI toolkits; one app passing does not establish platform-wide correctness. App-specific names belong
+in examples and verification scenarios, never in runtime special cases.
+
## Commands
Each platform adapter compiles only on its own OS and the workspace names all three, so an unscoped `cargo build`,
@@ -209,6 +218,7 @@ Every command prints one envelope. `docs/json-output.md` holds the full contract
```
- Omit `None` fields and empty arrays. Compact mode omits bounds. `ref_count` and `tree` live inside `data`.
+- Snapshot `data.window` is present for window-owned surfaces. macOS `menu` and `menubar` snapshots are application-owned and omit it.
- Every snapshot carries `data.complete`. A snapshot that runs out of observation budget succeeds with
`"complete": false`, `"truncated": true`, `"nodes_observed"` and the tree it saw; each cut node carries
`"subtree_truncated": true`. A `--root` drill-down returns `TIMEOUT` instead of a partial tree.
diff --git a/CONCEPTS.md b/CONCEPTS.md
index e68f22eed..4b3b17955 100644
--- a/CONCEPTS.md
+++ b/CONCEPTS.md
@@ -75,7 +75,7 @@ Windows supplies UIA's `AutomationId`, macOS `AXIdentifier` or `AXDOMIdentifier`
### Window Identity
The durable identity of a window, used when observation resolves a snapshot root or a stored ref.
-Window handles can be recycled: after a window is destroyed, the OS may hand its handle to a different window. A handle alone therefore names the wrong window after churn. Identity is the handle corroborated by a process-generation token (a value derived from the owning process's creation time), so a recycled handle whose process generation no longer matches fails closed rather than resolving to the new occupant. The corroboration is strict for a window freshly listed in the same invocation, and tolerant of title drift for a stored ref (titles legitimately change under a live window), per platform: Windows pairs the HWND with a creation-time token, macOS the window number with a process start-time token, Linux the X11 client id with a boot-id-qualified process start-time token.
+Window handles can be recycled: after a window is destroyed, the OS may hand its handle to a different window. A handle alone therefore names the wrong window after churn. Identity is the handle corroborated by a process-generation token (a value derived from the owning process's creation time), so a recycled handle whose process generation no longer matches fails closed rather than resolving to the new occupant. The title is descriptive and may change under a live window, so it is not part of the shared identity contract. macOS and Linux ignore title drift when resolving either a fresh listing or a stored ref. Windows may require a matching nonempty title for fresh-list verification, while stored-ref resolution tolerates drift. The platform tokens are: Windows pairs the HWND with a creation-time token, macOS the window number with a process start-time token, Linux the X11 client id with a boot-id-qualified process start-time token.
A handle's identity can be invalidated at any point between an observation and a later action on it, and checking it once at the start of that gap only proves it was valid then. Where the check and the act cannot be a single atomic operation, the corroboration has to be repeated immediately before each write the action performs, and the action's own success check must itself be identity-qualified, confirming the responding resource is still the expected occupant and not merely that some resource at the expected handle responded, or a recycle occurring late in the gap reports success over the wrong resource.
@@ -225,7 +225,7 @@ Each adapter maps native primitives into this shared vocabulary before core eval
### 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. The CLI exposes two: **headless** (the default; accessibility-only, no cursor, fails closed when the semantic path is unavailable) and **headed** (opt-in via the global `--headed` flag; authorizes the action's declared focus and cursor preconditions). A third, **focus fallback**, sits between them: it permits focus but not cursor movement. It is not reachable from the CLI flag. It is the base policy of an explicit key press, and language bindings may select it directly.
-Core owns the precondition each action declares: a focused window for keyboard or focus-sensitive work, a focused window plus a verified cursor target for pointer delivery. Core satisfies it before dispatch. For ref actions core focuses the exact source window, not merely the owning application; the platform adapter owns the OS-specific focus primitive and delivery mechanism. Raw coordinate input has no ref identity, so it never infers or focuses a window. Which actions a headed policy makes physical rather than semantic is per-action and per-platform, and is settled by that action's own chain rather than by the policy. On Windows, `type` has no semantic headless path, because UIA offers no insert-at-selection write. Strict-headless `type` therefore fails at policy, and `set-value` is the headless text path. Headed `type` synthesizes keys physically (A4-1).
+Core owns the precondition each action declares: a focused window for keyboard or focus-sensitive work, a focused window plus a verified cursor target for pointer delivery. Core satisfies it before dispatch. For a window-owned ref action, core focuses the exact source window, not merely the owning application. For an application-owned target, core can focus the app and still verify any pointer target. macOS native application-menu items use that application-level path for click, right-click, double-click, and triple-click. `hover` and `drag` remain window-owned and fail when the ref has no source window. The platform adapter owns the OS-specific focus primitive and delivery mechanism. Raw coordinate input has no ref identity, so it never infers or focuses a window. Which actions a headed policy makes physical rather than semantic is per-action and per-platform, and is settled by that action's own chain rather than by the policy. On Windows, `type` has no semantic headless path, because UIA offers no insert-at-selection write. Strict-headless `type` therefore fails at policy, and `set-value` is the headless text path. Headed `type` synthesizes keys physically (A4-1).
### Agent Cursor Overlay
An optional presentation-only cursor driven by verified action destinations. Its whole configuration (label, colours, size, and click effects) is set once per session with `session start --cursor` or `cursor-overlay enable`; action and batch commands inherit it and take no cursor flags. Motion models a human hand and the cursor never rotates or resizes. The renderer acknowledges arrival before the action dispatches, under a bounded timeout, so the picture and the real effect stay in step. A click plays a ripple and flashes an outline around the element. A `--headed` mutating command hides the overlay before it dispatches and shows it again afterwards; on Windows the renderer stays suppressed for headed input and draws only for headless semantic actions. It never moves or replaces the OS pointer and never changes Interaction Policy, action delivery, or response semantics. Configuration, motion, and effect timing live in `agent-desktop-core`; macOS, Windows and Linux (X11 only) supply native renderers, and an adapter that does not override `update_cursor_overlay` refuses with `PLATFORM_NOT_SUPPORTED`, which dispatch treats as `rendered: false`.
diff --git a/README.md b/README.md
index 17bd6e781..32dee9630 100644
--- a/README.md
+++ b/README.md
@@ -61,11 +61,21 @@ Each command prints one JSON envelope. A trimmed snapshot:
}
```
-- Refs carry their snapshot id. A bare `@e8` fails with `INVALID_ARGS`.
-- If the UI changed, an action returns `STALE_REF` or `AMBIGUOUS_TARGET`. Take a new snapshot and use its refs.
-- Actions are headless by default: no pointer movement, no focus change. Pass `--headed` for physical input.
+- **Refs belong to their snapshot.** A bare `@e8` is rejected with `INVALID_ARGS`. When the UI changes, an action
+ returns `STALE_REF` or `AMBIGUOUS_TARGET`: take a new snapshot and use its refs.
+- **Several windows** give `AMBIGUOUS_TARGET`; `snapshot` lists the candidate window ids in `error.details`. Pass one
+ with `--window-id`.
+- **Dense apps:** map first with `snapshot --skeleton --app Slack -i --compact`, then drill into one region with
+ `snapshot --root @s8f3k2p9:e3 -i --compact`.
+- **Headless by default.** Ref actions use the accessibility API without moving the pointer or taking focus. The global
+ `--headed` flag allows physical input.
+- **Post-action waits** observe the ref's original process. Window-owned refs stay pinned to their original window,
+ including refs captured from a sheet, alert, popover, focused view, or Linux menu. macOS application menus keep
+ their application-owned surface and need no document window. The wait reads the whole pinned window, so overlay
+ selectors share its scope. [Wait scope and results](https://agent-browser.dev/desktop/configuration#post-action-wait-flags)
+ describe the selector limits.
- `type`, `set-value`, and `clipboard-set` accept `--stdin` for piped text, keeping it out of process arguments. Run secret steps as separate commands; batch JSON text appears in process arguments.
-- In PowerShell, quote every ref (`'@s8f3k2p9:e8'`), because a bare `@token` is the splatting operator.
+- **PowerShell.** Quote every ref (`'@s8f3k2p9:e8'`), because a bare `@token` is the splatting operator.
The full walkthrough is in the [quick start](https://agent-browser.dev/desktop/quick-start).
diff --git a/apps/docs/content/docs/commands/observation.mdx b/apps/docs/content/docs/commands/observation.mdx
index b143a32b1..d70e4f3ae 100644
--- a/apps/docs/content/docs/commands/observation.mdx
+++ b/apps/docs/content/docs/commands/observation.mdx
@@ -10,7 +10,7 @@ Concepts behind the flags are explained in [Skeleton and drill-down](/desktop/sk
## snapshot
-Captures an app window's accessibility tree as JSON. Interactive elements get qualified refs that later commands accept.
+Captures an application's accessibility tree as JSON. Window-owned surfaces are read from a window; on macOS, `menu` and `menubar` are application-owned and need no document window. Interactive elements get qualified refs that later commands accept.
```bash
agent-desktop snapshot [--app NAME] [--window-id ID] [-i] [--compact] [--skeleton] \
@@ -23,8 +23,8 @@ agent-desktop snapshot [--app NAME] [--window-id ID] [-i] [--compact] [--skeleto
<tr><th>Flag</th><th>Default</th><th>Meaning</th></tr>
</thead>
<tbody>
- <tr><td><code>--app NAME</code></td><td>focused window</td><td>Application to read. See <a href="/desktop/snapshots-and-refs#choose-the-window">Choose the window</a>.</td></tr>
- <tr><td><code>--window-id ID</code></td><td>none</td><td>Read one window by id from <code>list-windows</code>.</td></tr>
+ <tr><td><code>--app NAME</code></td><td>focused app or window</td><td>Application to read. The selected surface determines whether a window is required. See <a href="/desktop/snapshots-and-refs#choose-the-window">Choose the window</a>.</td></tr>
+ <tr><td><code>--window-id ID</code></td><td>none</td><td>Read one window by id from <code>list-windows</code>. For macOS <code>menu</code> and <code>menubar</code>, it selects the owning app.</td></tr>
<tr><td><code>-i</code>, <code>--interactive-only</code></td><td>off</td><td>Drop leaves without a ref. See <a href="/desktop/snapshots-and-refs#what-a-snapshot-contains">What a snapshot contains</a>.</td></tr>
<tr><td><code>--compact</code></td><td>off</td><td>Collapse single-child unnamed wrappers.</td></tr>
<tr><td><code>--include-bounds</code></td><td>off</td><td>Add <code>bounds</code> to each node.</td></tr>
@@ -32,15 +32,14 @@ agent-desktop snapshot [--app NAME] [--window-id ID] [-i] [--compact] [--skeleto
<tr><td><code>--root REF</code></td><td>none</td><td>Drill into one ref's subtree and replace that region's refs. Cannot combine with <code>--surface</code> or <code>--wait-for</code>. See <a href="/desktop/skeleton-and-drill-down#drill-into-a-region">Drill into a region</a>.</td></tr>
<tr><td><code>--max-depth N</code></td><td><code>10</code></td><td>Maximum depth, up to 50. See <a href="/desktop/skeleton-and-drill-down#depth-with-max-depth">Depth with max-depth</a>.</td></tr>
<tr><td><code>--timeout-ms MS</code></td><td><code>3000</code></td><td>Observation deadline. A full snapshot that runs out succeeds with <code>complete: false</code>. See <a href="/desktop/skeleton-and-drill-down#partial-observations">Partial observations</a>.</td></tr>
- <tr><td><code>--surface KIND</code></td><td><code>window</code></td><td>Read an overlay instead of the window. See <a href="/desktop/surfaces#surface-kinds">Surface kinds</a>.</td></tr>
+ <tr><td><code>--surface KIND</code></td><td><code>window</code></td><td>Read the selected UI surface. On macOS, <code>menu</code> and <code>menubar</code> are application-owned. See <a href="/desktop/surfaces#surface-kinds">Surface kinds</a>.</td></tr>
<tr><td><code>--force-electron-a11y</code></td><td>off</td><td>Assume Chromium renderer accessibility is already forced, which skips the activation guidance.</td></tr>
</tbody>
</table>
-`data` carries `app`, `window` (left out when macOS reads a windowless app through its process, see [Surfaces](/desktop/surfaces)), `snapshot_id`, `ref_count`, `complete`, and `tree`; [Snapshots and refs](/desktop/snapshots-and-refs) shows a full example. With a post-action `--wait-for` ([Configuration](/desktop/configuration#post-action-wait-flags)), the result adds `elapsed_ms` and `matched_selector`.
-
-Errors specific to `snapshot`: `INVALID_ARGS` for `--root` with `--surface` or `--wait-for`, a bare ref, or `--max-depth` above 50; `WINDOW_NOT_FOUND` when there is no window to read; `AMBIGUOUS_TARGET` when the app has several candidate windows; `INVALID_ARGS` for a `--surface` kind this OS does not have; `STALE_REF`, `SNAPSHOT_NOT_FOUND`, or `TIMEOUT` for a `--root` drill. See [What a drill refuses](/desktop/skeleton-and-drill-down#what-a-drill-refuses).
+`data` carries `app`, `snapshot_id`, `ref_count`, `complete`, and `tree`. Window-owned snapshots also carry `window`; macOS application-owned `menu` and `menubar` snapshots, and process-owned snapshots of a background app with no window, omit it. [Snapshots and refs](/desktop/snapshots-and-refs) shows the window-owned shape. With a post-action `--wait-for` ([Configuration](/desktop/configuration#post-action-wait-flags)), a successful snapshot adds `elapsed_ms` and `matched_selector`.
+Errors specific to `snapshot`: `INVALID_ARGS` for `--root` with `--surface` or `--wait-for`, a bare ref, `--max-depth` above 50, or an unsupported `--surface` when the platform supports other surfaces; `PLATFORM_NOT_SUPPORTED` when the adapter supports no surfaces; `WINDOW_NOT_FOUND` when a window-owned surface has no window; `APP_NOT_FOUND` when an application-owned surface has no matching app; `AMBIGUOUS_TARGET` when a window-owned lookup has several candidate windows; `ELEMENT_NOT_FOUND` when a macOS application-owned menu surface is absent; `STALE_REF`, `SNAPSHOT_NOT_FOUND`, or `TIMEOUT` for a `--root` drill. See [What a drill refuses](/desktop/skeleton-and-drill-down#what-a-drill-refuses).
Platform limits: supported surfaces and Chromium settle time differ by OS. See [macOS](/desktop/platforms/macos), [Windows](/desktop/platforms/windows), and [Linux](/desktop/platforms/linux).
## find
@@ -59,7 +58,7 @@ agent-desktop find [--app NAME] [--window-id ID] [--role ROLE] [--name TEXT] [--
<tr><th>Flag</th><th>Default</th><th>Meaning</th></tr>
</thead>
<tbody>
- <tr><td><code>--app NAME</code>, <code>--window-id ID</code></td><td>focused window</td><td>Which window to search, with the same rules as <code>snapshot</code>.</td></tr>
+ <tr><td><code>--app NAME</code>, <code>--window-id ID</code></td><td>focused app or window</td><td>Which owner to search, with the same rules as <code>snapshot</code>.</td></tr>
<tr><td><code>--role ROLE</code></td><td>none</td><td>Accessibility role, case-insensitive. <code>textarea</code>, <code>textbox</code>, and <code>searchfield</code> fold to <code>textfield</code>.</td></tr>
<tr><td><code>--name TEXT</code></td><td>none</td><td>Accessible name. Fuzzy unless <code>--exact</code>.</td></tr>
<tr><td><code>--value TEXT</code></td><td>none</td><td>Current value. Unnamed elements carry their content here.</td></tr>
diff --git a/apps/docs/content/docs/configuration.mdx b/apps/docs/content/docs/configuration.mdx
index 08535f9a7..abfbaf76c 100644
--- a/apps/docs/content/docs/configuration.mdx
+++ b/apps/docs/content/docs/configuration.mdx
@@ -37,13 +37,15 @@ Global flags work before or after the command name, so `agent-desktop --headed c
**Commands that accept them.** `snapshot`, `press`, `hover`, `drag`, and every ref action (`click`, `double-click`, `triple-click`, `right-click`, `type`, `set-value`, `clear`, `focus`, `select`, `toggle`, `check`, `uncheck`, `expand`, `collapse`, `scroll`, `scroll-to`). Every other command returns `INVALID_ARGS`. `snapshot --root` cannot combine with them, and a `batch` entry never inherits them.
-**Which window is polled.** For `snapshot`, the window it reads. For a ref action, the window of the element you acted on. For `press`, the `--app` or `--window-id` window, else the focused one. For `drag`, the destination window, or the source with `--wait-for-scope from`.
+**Which owner is polled.** For `snapshot`, the selected surface owner. For a ref action, the original process. Application-owned refs keep their source surface; a macOS `menu` or `menubar` ref is observed through its application without requiring a document window. Window-owned refs observe their original pinned window, even when captured from `sheet`, `alert`, `popover`, `focused`, or a window-owned `menu` such as a Linux menu. The wait reads the whole window, so a selector elsewhere in the parent can satisfy `--wait-for` early or keep `--wait-for-gone` from succeeding. On Linux, GTK3 context menus and Chromium popups can be exposed outside that window tree, so a gone wait cannot establish that a popup outside the observed scope was dismissed. To observe the overlay itself, run a separate `snapshot` with the desired `--surface` and wait selector. For `press`, the `--app` or `--window-id` window, else the focused one. For `drag`, the destination window, or the source with `--wait-for-scope from`.
**Results.**
- `--wait-for` succeeds with snapshot data (`snapshot_id`, `ref_count`, `tree`, and so on) plus `elapsed_ms` and `matched_selector`. For an action, the action's own report moves under `data.after_action`.
- `--wait-for-gone` succeeds with `matched_selector`, `gone: true`, `target_absent: true`, and `elapsed_ms`, with the action's report under `after_action`.
- On expiry the command fails with `TIMEOUT`, `details.kind: "wait_timeout"`, `details.selector`, and `details.timeout_ms`. After an action, `details.after_action` holds its report, and the error keeps the action's own delivery disposition, so a timeout does not make the action safe to repeat.
+- If a ref action returns `delivery_uncertain`, `error.details.post_action_observation` records read-only evidence from the original process and its application-owned source surface or pinned window. Its [fields and outcomes](/desktop/json-output#post-action-observation) do not change the original error or unsafe retry disposition. The wait uses `--wait-timeout` separately from the action timeout.
+- A temporary `ACTION_NOT_SUPPORTED` error with `details.kind: "window_without_accessibility_element"` is retried during wait polling. For `--wait-for-gone`, that error does not count as absence; the wait succeeds only after a complete selector read finds no match or the app/window lookup confirms the target is gone.
```bash
agent-desktop click @s8f3k2p9:e5 --wait-for ":Saved" --wait-timeout 5000
diff --git a/apps/docs/content/docs/errors-and-recovery.mdx b/apps/docs/content/docs/errors-and-recovery.mdx
index afef75503..6f5704a3b 100644
--- a/apps/docs/content/docs/errors-and-recovery.mdx
+++ b/apps/docs/content/docs/errors-and-recovery.mdx
@@ -38,7 +38,7 @@ A failed command prints an envelope with `ok: false` and exits `1` (or `2` for a
<tr><td><code>suggestion</code></td><td>when set</td><td>A hint for a person or an agent. Check any command it names before you run it.</td></tr>
<tr><td><code>recovery</code></td><td>only when retry is safe</td><td>A declared recovery plan. See <a href="#recovery-strategies">Recovery strategies</a>.</td></tr>
<tr><td><code>platform_detail</code></td><td>when set</td><td>The native platform's own error text.</td></tr>
- <tr><td><code>details</code></td><td>when set</td><td>Structured context. <code>details.kind</code> names the cause for many codes, for example <code>actionability_timeout</code>, <code>wait_timeout</code>, <code>session_ended</code>, or <code>post_action_verification</code>.</td></tr>
+ <tr><td><code>details</code></td><td>when set</td><td>Structured context. <code>details.kind</code> names the cause for many codes, for example <code>actionability_timeout</code>, <code>focus_verification</code>, <code>surface_absent</code>, <code>wait_timeout</code>, <code>session_ended</code>, or <code>post_action_verification</code>.</td></tr>
</tbody>
</table>
@@ -50,8 +50,8 @@ A failed command prints an envelope with `ok: false` and exits `1` (or `2` for a
</thead>
<tbody>
<tr><td><code>PERM_DENIED</code></td><td>A required operating system permission is missing, such as Accessibility or Screen Recording.</td><td>Run <code>agent-desktop permissions</code> and grant it. See the <a href="/desktop/platforms/macos">macOS</a>, <a href="/desktop/platforms/windows">Windows</a>, and <a href="/desktop/platforms/linux">Linux</a> pages.</td></tr>
- <tr><td><code>ELEMENT_NOT_FOUND</code></td><td>No element matched the ref or query.</td><td>Take a fresh snapshot or run <code>find</code> again, then use the new ref.</td></tr>
- <tr><td><code>APP_NOT_FOUND</code></td><td>The application is not running, or it has no windows.</td><td>Check the name with <code>list-apps</code>. Run <code>launch</code> if it is not running.</td></tr>
+ <tr><td><code>ELEMENT_NOT_FOUND</code></td><td>No element matched the ref or query, or a requested surface is absent.</td><td>Read <code>details.kind</code> and <code>details.surface</code>. For an absent menu, open the menu first; otherwise check the UI before refreshing a ref.</td></tr>
+ <tr><td><code>APP_NOT_FOUND</code></td><td>No matching application process exists.</td><td>Check the name with <code>list-apps</code>. Run <code>launch</code> if it is not running.</td></tr>
<tr><td><code>ACTION_FAILED</code></td><td>The action was rejected or blocked, or its observed result contradicted the request.</td><td>Read <code>details</code> and <code>disposition.retry</code>. It never carries <code>recovery</code>.</td></tr>
<tr><td><code>ACTION_NOT_SUPPORTED</code></td><td>The target, or this platform for this input, does not expose the requested action.</td><td>Use a different command or element. Repeating it fails the same way.</td></tr>
<tr><td><code>STALE_REF</code></td><td>The ref no longer matches a live element.</td><td>Take a fresh snapshot and use the new ref. See <a href="/desktop/snapshots-and-refs">Snapshots and refs</a>.</td></tr>
@@ -68,6 +68,10 @@ A failed command prints an envelope with `ok: false` and exits `1` (or `2` for a
</tbody>
</table>
+For <code>ELEMENT_NOT_FOUND</code>, read <code>details.kind</code>, <code>details.surface</code>, and <code>details.complete</code>. A macOS lookup with <code>kind: "surface_absent"</code> and <code>complete: true</code> has confirmed that the requested surface is absent. An absent <code>menubar</code> can mean the app exposes no menu bar. For <code>surface: "menu"</code>, open the application menu first: snapshot <code>menubar</code> when it exists, click its menu-bar item without <code>--headed</code>, then snapshot <code>--surface menu</code>. Missing <code>complete</code>, <code>complete: false</code>, a timeout, or an incomplete read is unknown. If the command followed an action with <code>disposition.retry: unsafe</code>, inspect the current UI before another action; do not repeat the action because the snapshot failed.
+
+A macOS <code>TIMEOUT</code> with <code>details.kind: "focus_verification"</code> means the app never reported <code>AXFrontmost</code>, or the target window never reported <code>AXMain</code>, before the bounded focus readback ended. <code>details.physical_delivery_started: false</code> means target input had not started; it does not mean a prior focus or window-raise request was never dispatched. Read <code>disposition</code>, which can still be <code>delivered_unverified</code>.
+
## Disposition
`disposition` says whether input reached the application, and from that, whether repeating the command is safe. Every error carries it. Commands that act on a target also carry it on success, as `data.disposition`.
diff --git a/apps/docs/content/docs/ffi/api.mdx b/apps/docs/content/docs/ffi/api.mdx
index e7b8a6990..f13e02848 100644
--- a/apps/docs/content/docs/ffi/api.mdx
+++ b/apps/docs/content/docs/ffi/api.mdx
@@ -69,7 +69,7 @@ AdResult ad_check_permissions(const struct AdAdapter *adapter);
Each writes an owned JSON envelope into `*out`; free it with `ad_free_string`, including an `"ok": false` envelope. `*out` is null only on an argument or infrastructure failure.
```c
-// Snapshots an app's focused window; surface is an AdSnapshotSurface.
+// Snapshots the app surface selected by AdSnapshotSurface.
AdResult ad_snapshot(const struct AdAdapter *adapter,
const char *app,
int32_t surface,
diff --git a/apps/docs/content/docs/ffi/build-and-link.mdx b/apps/docs/content/docs/ffi/build-and-link.mdx
index fd8a10ae8..383503728 100644
--- a/apps/docs/content/docs/ffi/build-and-link.mdx
+++ b/apps/docs/content/docs/ffi/build-and-link.mdx
@@ -83,11 +83,10 @@ cc -std=c11 -I crates/ffi/include main.c \
./snapshot_demo gnome-calculator
```
-On Linux against GNOME Calculator it printed this envelope, shown here with `tree` elided:
+On Linux against GNOME Calculator it printed this envelope, shown here with the window metadata and `tree` elided:
```json
-{"version":"2.6","ok":true,"command":"snapshot","data":{"app":"gnome-calculator","complete":true,"ref_count":2,"snapshot_id":"s18ekeexjf5trb","tree":{"...":"..."}}}
-```
+{"version":"2.6","ok":true,"command":"snapshot","data":{"app":"gnome-calculator","complete":true,"ref_count":2,"snapshot_id":"s18ekeexjf5trb","window":{"id":"...","title":"..."},"tree":{"...":"..."}}}```
The macOS install name is `@rpath/libagent_desktop_ffi.dylib`, so a program that links the library needs an rpath to its directory; `dlopen` and `ctypes` callers load by path and need nothing. On Windows, an MSVC program links `agent_desktop_ffi.dll.lib` and loads the DLL at run time. On Linux the program must run inside the user's graphical session to see apps; see [Linux](/desktop/platforms/linux).
diff --git a/apps/docs/content/docs/ffi/index.mdx b/apps/docs/content/docs/ffi/index.mdx
index a75cdb5bf..f791ac29b 100644
--- a/apps/docs/content/docs/ffi/index.mdx
+++ b/apps/docs/content/docs/ffi/index.mdx
@@ -29,7 +29,7 @@ The library and the CLI run the same core and the same platform adapter; the `ag
## What the library does not expose
-- `ad_snapshot` always reads the focused window of the app you name. It has no window id, skeleton mode, or `--root` drill-down; use the CLI for those.
+- `ad_snapshot` reads the owner selected by `surface`. On macOS, `menu` and `menubar` are application-owned and need no document window; window-owned snapshots include `data.window`. The ABI has no window id, skeleton mode, or `--root` drill-down; use the CLI for those.
- `ad_wait` does not expose `wait --event` or `--window-id`.
- The library carries no skills. Read the FFI guide with `agent-desktop skills get ffi` from the CLI.
diff --git a/apps/docs/content/docs/guides/headed-mode.mdx b/apps/docs/content/docs/guides/headed-mode.mdx
index a6d601988..476487781 100644
--- a/apps/docs/content/docs/guides/headed-mode.mdx
+++ b/apps/docs/content/docs/guides/headed-mode.mdx
@@ -16,8 +16,8 @@ A result shows which mechanism ran: in `data.steps`, `semantic_api` is an access
`--headed` authorizes the focus and cursor side effects an action declares:
-- For a ref, core focuses the exact source window first, and pointer actions need a verified target point. On macOS, a ref from a background app (a menu bar app, the Dock, a system panel) or a status item has no window to focus; the click still needs a verified target point.
-- Raw coordinates (`--xy`) carry no window identity, so they never focus anything.
+- For a ref, core focuses the exact source window before headed pointer input and verifies the target point before delivery. A process-owned ref has no window to focus, but physical input still requires a verified point.
+- On macOS, clicking a native menu-bar item uses `AXPress`; it works headless and does not move the pointer under `--headed`. A headless `right-click` can use `AXShowMenu` when the target provides it.- Raw coordinates (`--xy`) carry no window identity, so they never focus anything.
- It applies to every entry of a [batch](/desktop/guides/batch).
- It permits physical input; it does not force it. Each platform decides per action whether to use a physical or a semantic path, and `check`, `set-value`, and `expand` stay semantic under `--headed` everywhere.
- It does not lift other guards. A blocked key combo still needs `--force`, and a platform that cannot deliver physical input, such as pointer input on Wayland, still refuses.
diff --git a/apps/docs/content/docs/guides/waiting.mdx b/apps/docs/content/docs/guides/waiting.mdx
index e8beb5c13..1a335adc9 100644
--- a/apps/docs/content/docs/guides/waiting.mdx
+++ b/apps/docs/content/docs/guides/waiting.mdx
@@ -27,7 +27,7 @@ A fixed sleep either wastes time or races the app. agent-desktop gives you two w
## Wait inside the action
-`--wait-for` polls the acted-on window until the selector matches, then returns a fresh snapshot with the action's own report under `after_action`, so you can act on the new refs at once:
+`--wait-for` polls the ref's original process until the selector matches, then returns a fresh snapshot with the action's own report under `after_action`, so you can act on the new refs at once. Application-owned refs keep their source surface. Window-owned refs stay pinned to their original window, including refs captured from a sheet, alert, popover, focused view, or window-owned Linux menu:
```bash
agent-desktop click @s8f3k2p9:e5 --wait-for "button:Done" --wait-timeout 10000
diff --git a/apps/docs/content/docs/json-output.mdx b/apps/docs/content/docs/json-output.mdx
index 3f7cc7b04..104dc7b6f 100644
--- a/apps/docs/content/docs/json-output.mdx
+++ b/apps/docs/content/docs/json-output.mdx
@@ -57,10 +57,15 @@ An error envelope has `error` and no `data`:
- Snapshot node bounds are omitted unless you pass `--include-bounds`.
- Some commands build their `data` by hand and write `null` or `[]` for an absent value. `session list` writes `"ended_at": null` for an open session, and `find` matches write `"value": null` and `"states": []`. Treat a missing key, `null`, and an empty array the same way.
- Ignore keys you do not know. New optional fields can appear without a version change.
+- Snapshot `data.window` appears when a window owns the observation. On macOS, application-owned `menu` and `menubar` snapshots omit it.
+
+## Application-owned snapshots
+
+On macOS, `menu` and `menubar` snapshots belong to the application, so `data.app` identifies the owner and `data.window` is absent. This remains true when a `--window-id` selects which app to observe or when `--root` drills into a ref from that surface. Window-owned snapshots keep `data.window`.
## Where data lives
-`ref_count` and `tree` sit inside `data`, never at the top level. This snapshot of GNOME Calculator is trimmed to one branch:
+`ref_count` and `tree` sit inside `data`, never at the top level. This window-owned snapshot of GNOME Calculator is trimmed to one branch:
```json
{
@@ -72,6 +77,7 @@ An error envelope has `error` and no `data`:
"complete": true,
"ref_count": 7,
"snapshot_id": "s1vylk49fulgx4",
+ "window": { "id": "w-calculator", "title": "Calculator" },
"tree": {
"role": "window",
"name": "Calculator",
@@ -96,6 +102,39 @@ A snapshot that runs out of budget still returns `ok: true`, with `"complete": f
A ref action such as `click`, `type`, or `toggle` returns `data.action` and `data.disposition`, and can add `steps` (each mechanism tried), `post_state`, `surfaces` (surfaces open once the action settled), and `details`. `disposition` has two fields, `delivery` and `retry`; on success, `delivery` is `delivered_verified`, `delivered_unverified`, or `not_delivered` (already satisfied). What each value proves, and when a retry is safe, is in [Errors and recovery](/desktop/errors-and-recovery#disposition).
+### Post-action observation
+
+When a ref action returns `delivery_uncertain` with a post-action wait selector, `error.details.post_action_observation` records a read-only observation of the original process. Application-owned refs keep their source surface. Window-owned refs observe their original pinned window, including refs captured from `sheet`, `alert`, `popover`, `focused`, or a window-owned `menu` such as a Linux menu. This lets a closed overlay be observed without treating the parent window as absent. The action is never repeated, and its original error and unsafe retry disposition stay unchanged. Even `expected_state_observed` does not prove that the action caused the state. Observation uses `--wait-timeout` separately from the action timeout.
+
+<table>
+ <thead><tr><th>Field</th><th>Meaning</th></tr></thead>
+ <tbody>
+ <tr><td><code>kind</code></td><td>Always <code>post_action_observation</code>.</td></tr>
+ <tr><td><code>selector, expected</code></td><td>Requested selector and <code>present</code> or <code>absent</code>.</td></tr>
+ <tr><td><code>surface</code></td><td>The observed scope: the application-owned source surface, or <code>window</code> for a window-owned ref.</td></tr>
+ <tr><td><code>process_identity</code></td><td>Original <code>pid</code> and <code>process_instance</code>; the instance can be null for <code>identity_unavailable</code>.</td></tr>
+ <tr><td><code>elapsed_ms</code></td><td>Time spent observing after the action returned.</td></tr>
+ <tr><td><code>source_window_id</code></td><td>Original window ID, when the ref has one.</td></tr>
+ <tr><td><code>selector_matches</code></td><td>Observed selector result, when available; absence requires a complete read.</td></tr>
+ <tr><td><code>process_state</code></td><td>Last observed <code>unresponsive</code>, <code>exited</code>, or <code>crashed</code> state. <code>running</code> is never emitted.</td></tr>
+ <tr><td><code>last_observation_error</code></td><td>Last observation error's <code>code</code> and <code>message</code>, when available.</td></tr>
+ <tr><td><code>outcome</code></td><td>One of the outcomes below.</td></tr>
+ </tbody>
+</table>
+
+<table>
+ <thead><tr><th>Outcome</th><th>Meaning</th></tr></thead>
+ <tbody>
+ <tr><td><code>expected_state_observed</code></td><td>The expected selector state was observed, or the original window or surface was confirmed absent for an absence wait.</td></tr>
+ <tr><td><code>process_exited</code></td><td>The original process exited; this does not establish the action's effect.</td></tr>
+ <tr><td><code>process_crashed</code></td><td>The platform reported that the original process crashed.</td></tr>
+ <tr><td><code>owner_unavailable</code></td><td>The original surface owner remained unavailable without confirmed process exit.</td></tr>
+ <tr><td><code>observation_failed</code></td><td>A terminal read error stopped observation; inspect <code>last_observation_error</code>.</td></tr>
+ <tr><td><code>timed_out</code></td><td>The wait budget expired without observing the expected state, including when transient read errors persisted through the last poll. <code>last_observation_error</code> may hold the last error.</td></tr>
+ <tr><td><code>identity_unavailable</code></td><td>The ref has no usable process generation, so observation was skipped.</td></tr>
+ </tbody>
+</table>
+
## OperationReport
Thirteen commands return the adapter's own report as `data`: `mouse-click`, `mouse-move`, `mouse-wheel`, `hover`, `drag`, `clipboard-set`, `clipboard-clear`, `close-app`, `move-window`, `resize-window`, `minimize`, `maximize`, and `restore`. The report is the action result fields (`action`, `disposition`, and `steps`, `post_state`, `surfaces`, or `details` when present) plus a `target`. The command then adds the echoed request fields, such as `from` and `to` for `drag`, without overwriting any field the report already has.
@@ -189,7 +228,7 @@ An argument the parser accepts but the command rejects, such as a bare `@e1`, ex
## Contract versions
-Check `version` before you parse. A consumer written for 2.0 or later can treat a higher minor version as the same shape plus the changes below.
+Check `version` before you parse. Apply the migrations below when your parser supports an older contract version.
<table>
<thead>
@@ -201,7 +240,7 @@ Check `version` before you parse. A consumer written for 2.0 or later can treat
<tr><td>2.3</td><td><code>launch</code> returns <code>app</code>, <code>pid</code>, <code>process_instance</code>, and an optional <code>window</code> instead of a bare window object. An application that shows no window is <code>ok: true</code> with <code>window</code> omitted, not <code>WINDOW_NOT_FOUND</code>.</td></tr>
<tr><td>2.4</td><td>Stateful ref actions (<code>set-value</code>, <code>type</code>, <code>clear</code>, <code>check</code>, <code>uncheck</code>, <code>toggle</code>, <code>expand</code>, <code>collapse</code>) read the state back after one delivery attempt and reject an observed contradiction. A readback failure keeps the adapter's code and adds <code>details.kind: "post_action_verification"</code>. Missing evidence stays a successful <code>delivered_unverified</code> with <code>details.verification_scope: "unavailable"</code>.</td></tr>
<tr><td>2.5</td><td>Breaking for the thirteen <a href="#operationreport">OperationReport</a> commands. The success flags <code>clicked</code>, <code>moved</code>, <code>scrolled</code>, <code>hovered</code>, <code>dragged</code>, <code>resized</code>, <code>minimized</code>, <code>maximized</code>, <code>restored</code>, <code>closed</code>, <code>cleared</code>, <code>requested</code> (<code>close-app</code>), and the inner <code>ok</code> of <code>clipboard-set</code> are removed. <code>data</code> is the adapter's report with <code>disposition</code>, <code>steps</code>, and <code>target</code>.</td></tr>
- <tr><td>2.6</td><td>On Windows and Linux, and on macOS for an element with no address, a ref resolves only when one complete read of its window proved it unique at capture and exactly one live element matches it now. A ref to one of two identical controls, a ref from a window that could not be read whole, and every ref in a refmap written before 2.6 fail <code>AMBIGUOUS_TARGET</code> with <code>details.kind: "identity_not_unique"</code>. A twin that appears after capture fails with <code>saved_ref_ambiguous</code>. Both carry <code>details.retryable: false</code>.</td></tr>
+ <tr><td>2.6</td><td>On Windows and Linux, and on macOS for an element without a native address, a ref resolves only when a complete window read proved its role and stable fields unique at capture and exactly one live element matches now. An identity that was not unique at capture fails with <code>details.kind: "identity_not_unique"</code>; a twin that appears later fails with <code>details.kind: "saved_ref_ambiguous"</code>. A snapshot that could not prove identity can include <code>data.identity_unproven</code>. On macOS, application-owned <code>menu</code> and <code>menubar</code> snapshots omit <code>data.window</code>; <code>data.app</code> identifies the owner, and <code>--window-id</code> selects that app.</td></tr>
</tbody>
</table>
diff --git a/apps/docs/content/docs/platforms/macos.mdx b/apps/docs/content/docs/platforms/macos.mdx
index aec1b909d..2c5a5d4ba 100644
--- a/apps/docs/content/docs/platforms/macos.mdx
+++ b/apps/docs/content/docs/platforms/macos.mdx
@@ -39,7 +39,7 @@ The grant belongs to the app that launched agent-desktop, not to the shell. A di
## What works headless
-Ref actions are headless by default. Under `--headed`, `click`, `right-click`, `type`, `clear`, and `scroll` become physical first: core focuses the exact window, then a real click, key, or wheel event goes to the verified point. `expand`, `collapse`, `set-value`, `select`, `toggle`, `check`, `uncheck`, `focus`, and `scroll-to` stay semantic. See [Headed mode](/desktop/guides/headed-mode).
+Ref actions are headless by default. Under `--headed`, `click`, `right-click`, `type`, `clear`, and `scroll` use physical paths first, except a click on an item in the application's native menu bar hierarchy: agent-desktop activates the owning app and calls `AXPress` without moving the cursor. A headless click on these menu items calls `AXPress` without activating the app. `right-click` can use `AXShowMenu` headless when the item provides it. Under `--headed`, right-click, double-click, and triple-click support windowless native menu items by focusing the app and keeping pointer verification. `hover` and `drag` still require the ref's source window and fail with `ACTION_NOT_SUPPORTED` when it has none. Other ref-target pointer actions focus the exact owning window and verify the hit target before delivery. A window-backed popup uses its live owning window even when its snapshot is application-owned. `expand`, `collapse`, `set-value`, `select`, `toggle`, `check`, `uncheck`, `focus`, and `scroll-to` stay semantic. See [Headed mode](/desktop/guides/headed-mode).
<table>
<thead>
@@ -69,8 +69,7 @@ Judge delivery by observation. AX return codes do not prove an effect: an app ca
## Surfaces
-`supported_surfaces` lists `window`, `focused`, `menu`, `menubar`, `sheet`, `popover`, `alert`, `dock`, and `menu-bar-extras`. Use `--surface menubar` for an app's File, Edit, and View menus. Use `--surface menu-bar-extras` for status items: without `--app` it reads the system items (Wi-Fi, Battery, Clock), and with `--app` it reads that app's own item. `--surface dock` reads the Dock. A background app with no window, such as the Control Center panel after you click its status item, is read through its process with `snapshot --app "Control Center"`; [Surfaces](/desktop/surfaces) has the rules. Notification Center is reached through the notification commands. See [Surfaces](/desktop/surfaces).
-
+`supported_surfaces` lists `window`, `focused`, `menu`, `menubar`, `sheet`, `popover`, `alert`, `dock`, and `menu-bar-extras`. Use `--surface menubar` for an app's File, Edit, and View menus. Use `--surface menu-bar-extras` for status items: without `--app` it reads system items such as Wi-Fi, Battery, and Clock; with `--app` it reads that app's own item. Use `--surface dock` for the Dock. These shell surfaces are available headless through `open-system-surface`. A background app with no window, such as a menu-bar app or Control Center, can be read through its process. This applies to `window`, `menubar`, and `menu-bar-extras`, not `focused`; a regular app that has not shown a window returns `WINDOW_NOT_FOUND`. While a menu, sheet, alert, or popover is open, refs from the window tree behind it are the wrong target. See [Surfaces](/desktop/surfaces).
## Keys and notifications
- The primary modifier is `cmd`: `press cmd+c`. Punctuation keys work as the symbol or by name (`comma`, `period`, `slash`).
@@ -94,7 +93,7 @@ agent-desktop turns on web accessibility in a Chromium renderer when it needs it
<tr><td><code>complete: false</code> or a slow snapshot</td><td>A deep tree ran out of budget</td><td>Use <code>find</code>, or a skeleton and <code>--root</code>. See <a href="/desktop/skeleton-and-drill-down">Skeleton and drill-down</a></td></tr>
<tr><td><code>APP_UNRESPONSIVE</code> after <code>right-click</code> with <code>retry: unsafe</code></td><td><code>AXShowMenu</code> entered modal menu tracking after the menu opened</td><td>Do not retry. Run <code>snapshot --surface menu</code>; for a combo box or menu button, use <code>select</code></td></tr>
<tr><td><code>select</code> cannot confirm the choice</td><td>It needs a closed-to-open menu change, and a menu was already open</td><td>Dismiss the open menu, then run <code>select</code> again</td></tr>
- <tr><td><code>WINDOW_NOT_FOUND</code></td><td>The app has no open window</td><td><code>launch "App"</code> with <code>--activate</code>, then <code>list-windows --app "App"</code></td></tr>
+ <tr><td><code>WINDOW_NOT_FOUND</code></td><td>A window-owned surface has no open window</td><td><code>launch "App"</code> with <code>--activate</code>, then <code>list-windows --app "App"</code></td></tr>
<tr><td>A shortcut does nothing</td><td><code>ctrl</code> used where macOS uses <code>cmd</code>, or the keys went to another app</td><td>Use <code>cmd+...</code>, or scope with <code>--app</code></td></tr>
</tbody>
</table>
diff --git a/apps/docs/content/docs/snapshots-and-refs.mdx b/apps/docs/content/docs/snapshots-and-refs.mdx
index a7b17a91c..aaf11260c 100644
--- a/apps/docs/content/docs/snapshots-and-refs.mdx
+++ b/apps/docs/content/docs/snapshots-and-refs.mdx
@@ -4,7 +4,7 @@ navTitle: Snapshots and refs
description: What a snapshot contains, how refs are allocated and stored, and how a ref resolves back to a live element or goes stale.
---
-A snapshot is one observation of an application window's accessibility tree. agent-desktop saves it with a ref map and gives every actionable element a ref that you pass to later commands.
+A snapshot is one observation of an application's accessibility tree. Window-owned surfaces read a window; macOS `menu` and `menubar` surfaces belong to the application and need no document window. agent-desktop saves the observation with a ref map and gives every actionable element a ref that you pass to later commands.
```bash
agent-desktop snapshot --app gnome-calculator -i --compact
@@ -52,7 +52,7 @@ The tree above is trimmed to one button. The real tree nests it under several un
<tr><th>Field</th><th>Meaning</th></tr>
</thead>
<tbody>
- <tr><td><code>data.app</code>, <code>data.window</code></td><td>The application and the window that was read (<code>id</code>, <code>title</code>). <code>data.window</code> is omitted when macOS reads a background app with no window through its process; see <a href="/desktop/surfaces">Surfaces</a>.</td></tr>
+ <tr><td><code>data.app</code>, <code>data.window</code></td><td>The application and, for window-owned observations, the window that was read (<code>id</code>, <code>title</code>). <code>data.window</code> is omitted for macOS application-owned menu surfaces and process-owned snapshots of a background app with no window.</td></tr>
<tr><td><code>data.snapshot_id</code></td><td>The id of the saved snapshot. It is part of every ref.</td></tr>
<tr><td><code>data.ref_count</code></td><td>The number of refs the snapshot holds. After a <code>--root</code> drill it counts the whole snapshot, not only the drilled region.</td></tr>
<tr><td><code>data.complete</code></td><td>Present on every snapshot. <code>false</code> means the observation ran out of budget. See <a href="/desktop/skeleton-and-drill-down#partial-observations">Partial observations</a>.</td></tr>
@@ -83,7 +83,7 @@ A node always carries `role` and, when they exist, `ref_id`, `name`, `value`, `d
## Choose the window
-`snapshot` and `find` read one window. Without `--app` they read the focused window, and `WINDOW_NOT_FOUND` means there is none. With `--app` and no `--window-id`, agent-desktop narrows the app's windows in this order and stops at the first step that leaves exactly one:
+For window-owned surfaces, `snapshot` and `find` read one window. Without `--app` they use the focused window, and `WINDOW_NOT_FOUND` means there is none. With `--app` and no `--window-id`, agent-desktop narrows the app's windows in this order and stops at the first step that leaves exactly one:
1. If the app has only one window, use it.
2. Keep only visible windows.
@@ -92,6 +92,8 @@ A node always carries `role` and, when they exist, `ref_id`, `name`, `value`, `d
If several windows are still left, the command fails with `AMBIGUOUS_TARGET`, and `details.candidates` lists up to 10 of them. Run `list-windows --app <name>` and pass `--window-id`.
+On macOS, `menu` and `menubar` surfaces are application-owned. They can be observed without a document window. If you pass `--window-id`, it selects the app that owns the surface; the returned snapshot remains application-owned and omits `data.window`.
+
## Refs
A ref is an element id with its snapshot id inside it:
diff --git a/apps/docs/content/docs/surfaces.mdx b/apps/docs/content/docs/surfaces.mdx
index 1e45d641f..588120f11 100644
--- a/apps/docs/content/docs/surfaces.mdx
+++ b/apps/docs/content/docs/surfaces.mdx
@@ -1,10 +1,10 @@
---
title: Surfaces
navTitle: Surfaces
-description: Observe menus, sheets, alerts, popovers, and OS shell areas separately from the window with --surface, list-surfaces, and open-system-surface.
+description: Observe menus, sheets, alerts, popovers, and OS shell areas separately from a window or application with --surface, list-surfaces, and open-system-surface.
---
-A surface is a UI layer that you observe separately from the whole window: an open menu, a sheet, a popover, an alert, or an OS shell area such as the taskbar. While an overlay is open, the refs from the window behind it are the wrong target, so read the overlay itself.
+A surface is a UI layer that you observe separately from a window or application's full accessibility tree: an open menu, a sheet, a popover, an alert, or an OS shell area such as the taskbar. While an overlay is open, the refs from the window behind it are the wrong target, so read the overlay itself.
```bash
agent-desktop snapshot --app gtk3-widget-factory --surface menu -i --compact
@@ -20,7 +20,7 @@ agent-desktop find --app gtk3-widget-factory --surface menu --name "Dark Theme"
<tr><th>Group</th><th>Kinds</th></tr>
</thead>
<tbody>
- <tr><td>The window and its layers</td><td><code>window</code>, <code>focused</code>, <code>menu</code>, <code>menubar</code>, <code>sheet</code>, <code>popover</code>, <code>alert</code></td></tr>
+ <tr><td>The app or window and its layers</td><td><code>window</code>, <code>focused</code>, <code>menu</code>, <code>menubar</code>, <code>sheet</code>, <code>popover</code>, <code>alert</code></td></tr>
<tr><td>OS shell</td><td><code>desktop</code>, <code>taskbar</code>, <code>system-tray</code>, <code>system-tray-overflow</code>, <code>quick-settings</code>, <code>notification-center</code>, <code>toolbar</code>, <code>dock</code>, <code>spotlight</code>, <code>menu-bar-extras</code>, <code>start-menu</code>, <code>action-center</code></td></tr>
</tbody>
</table>
@@ -106,13 +106,17 @@ To reach one item, `find --surface` is cheaper than a dump:
}
```
-Which window agent-desktop reads depends on the kind:
+How agent-desktop selects an owner depends on the kind and platform:
- `sheet`, `popover`, and `alert`: the app's accessible windows in order, focused first and then visible, and the first that presents one wins. With no `--app`, the frontmost process.
-- `menu`, `menubar`, and `focused`: any window of the app identifies the process, so several open windows are never ambiguous. On macOS, `window`, `menubar` and `menu-bar-extras` read a background app (a menu bar app, the Dock, Control Center, Notification Center) through its process when it has no window; the result then has no `window` field. A regular app that has not shown its window yet returns `WINDOW_NOT_FOUND`: wait for the window. `focused` always needs a focused window.
-- A shell kind needs no `--app`, because no application owns it. On macOS, `menu-bar-extras` with `--app` reads that app's own status item instead.
-- `--window-id` pins the read to one window.
+- `sheet`, `popover`, and `alert`: the app's accessible windows in order, focused first and then visible, and the first that presents one wins. With no `--app`, the frontmost process.
+- On macOS, `menu` and `menubar` are application-owned and do not require a document window. If you pass `--window-id`, it selects the app that owns the surface. Snapshot data includes `app` and omits `window`. A complete lookup with no open menu or menu bar returns `ELEMENT_NOT_FOUND` with `details.kind: "surface_absent"` and `details.complete: true`. To read an application menu, snapshot `menubar` when it exists, click its item without `--headed`, then snapshot `--surface menu`. An absent menu bar can mean the app exposes none.
+- On implementations where `menu`, `menubar`, and `focused` are window-owned, any app window identifies the process, so several open windows are not ambiguous.
+- On macOS, `window`, `menubar`, and `menu-bar-extras` can read a background app with no window through its process. The result omits `window`. A regular app that has not shown a window returns `WINDOW_NOT_FOUND`; `focused` requires a focused window.
+- A shell kind needs no `--app`, because no application owns it. On macOS, `menu-bar-extras` with `--app` reads that app's own status item.
+- For window-owned surfaces, `--window-id` pins the read to that window.
+A missing `complete`, `complete: false`, a timeout, or an incomplete accessibility read leaves menu absence unknown. After a delivery with `retry: unsafe`, inspect the current UI before taking another action.
A surface that is not open returns an error. On Linux, a closed menu returns `ELEMENT_NOT_FOUND`:
```json
diff --git a/crates/core/examples/locator_benchmark/adapter.rs b/crates/core/examples/locator_benchmark/adapter.rs
index ad438b9b9..dcf69a3bd 100644
--- a/crates/core/examples/locator_benchmark/adapter.rs
+++ b/crates/core/examples/locator_benchmark/adapter.rs
@@ -31,6 +31,9 @@ impl ObservationOps for FixtureAdapter<'_> {
request: &ObservationRequest,
) -> Result<ObservedTree, AdapterError> {
match &root {
+ ObservationRoot::Application { .. } => {
+ Err(AdapterError::not_supported("application observation root"))
+ }
ObservationRoot::Window(_) => {
live_tree(self.fixture, request.evidence_for_raw_depth(0))
}
diff --git a/crates/core/src/actionability/actionability_nonspatial_tests.rs b/crates/core/src/actionability/actionability_nonspatial_tests.rs
index 63c54d84f..3a06e5d5c 100644
--- a/crates/core/src/actionability/actionability_nonspatial_tests.rs
+++ b/crates/core/src/actionability/actionability_nonspatial_tests.rs
@@ -115,3 +115,67 @@ fn nonspatial_semantic_targets_need_live_state_but_not_screen_bounds() {
hover.message
);
}
+
+struct ClassifiedTarget(ProtocolTarget, Result<bool, AdapterError>);
+
+impl ObservationOps for ClassifiedTarget {
+ fn is_nonspatial_target_with_deadline(
+ &self,
+ _: &NativeHandle,
+ deadline: crate::Deadline,
+ ) -> Result<bool, AdapterError> {
+ deadline.ensure_remaining()?;
+ self.1.clone()
+ }
+
+ fn get_live_element(
+ &self,
+ handle: &NativeHandle,
+ deadline: crate::Deadline,
+ ) -> Result<LiveElement, AdapterError> {
+ self.0.get_live_element(handle, deadline)
+ }
+}
+impl ActionOps for ClassifiedTarget {}
+impl InputOps for ClassifiedTarget {}
+impl SystemOps for ClassifiedTarget {}
+
+#[test]
+fn semantic_geometry_exemption_requires_successful_native_provenance() {
+ let (entry, adapter) = target("menuitem", &[capability::CLICK]);
+ let mut live = adapter.0;
+ live.bounds = None;
+ live.state.hidden = Some(false);
+ live.state.offscreen = None;
+ for classified in [true, false] {
+ let adapter = ClassifiedTarget(ProtocolTarget(live.clone()), Ok(classified));
+ let result = check_live(
+ &entry,
+ &NativeHandle::null(),
+ &adapter,
+ &ActionRequest::headless(Action::Click),
+ );
+ assert_eq!(result.is_ok(), classified);
+ }
+ for code in [
+ crate::ErrorCode::PermDenied,
+ crate::ErrorCode::Timeout,
+ crate::ErrorCode::StaleRef,
+ ] {
+ let adapter = ClassifiedTarget(
+ ProtocolTarget(live.clone()),
+ Err(AdapterError::new(
+ code.clone(),
+ "Native provenance read failed",
+ )),
+ );
+ let error = check_live(
+ &entry,
+ &NativeHandle::null(),
+ &adapter,
+ &ActionRequest::headless(Action::Click),
+ )
+ .unwrap_err();
+ assert_eq!(error.code, code);
+ }
+}
diff --git a/crates/core/src/actionability/evaluate.rs b/crates/core/src/actionability/evaluate.rs
index bf3398cd5..79dc9b7e9 100644
--- a/crates/core/src/actionability/evaluate.rs
+++ b/crates/core/src/actionability/evaluate.rs
@@ -85,15 +85,8 @@ pub(super) fn check_with_stability(
finish(evidence, request, report)
}
-/// Like [`check_with_stability`], but a report whose only unmet requirement
-/// is `stable` is returned as `Ok` instead of converted to a terminal `Err`.
-///
-/// `stable_preflight` (`ref_action.rs`) samples live bounds to let a target
-/// settle before deciding stability is truly unreachable; it can only make
-/// that call by seeing the report, and `finish` below has already discarded
-/// it into an error by the time a normal caller sees anything. Every other
-/// gap - disabled, hidden, policy-denied, unsupported - still converts here,
-/// unchanged, because no amount of sampling resolves those.
+/// Preserves stability gaps and positive-timeout application-pointer geometry gaps for sampling.
+/// Other unmet requirements remain errors.
pub(super) fn check_with_stability_or_gap(
stability: StabilityExpectation,
evidence: &ActionabilityEvidence,
@@ -101,10 +94,29 @@ pub(super) fn check_with_stability_or_gap(
hit_test: Option<(&NativeHandle, &dyn PlatformAdapter)>,
deadline: crate::Deadline,
) -> Result<ActionabilityReport, AdapterError> {
- let report = build_report(stability, evidence, request, hit_test, deadline)?;
+ let (report, requirement) =
+ build_report_with_requirement(stability, evidence, request, hit_test, deadline)?;
if !report.actionable && report.only_blocking_check_is_stability() {
return Ok(report);
}
+ if evidence.can_wait_for_geometry(request, &report, requirement) {
+ return Ok(report);
+ }
+ finish(evidence, request, report)
+}
+
+pub(super) fn check_before_focus(
+ stability: StabilityExpectation,
+ evidence: &ActionabilityEvidence,
+ request: &ActionRequest,
+ hit_test: Option<(&NativeHandle, &dyn PlatformAdapter)>,
+ deadline: crate::Deadline,
+) -> Result<ActionabilityReport, AdapterError> {
+ let (report, requirement) =
+ build_report_with_requirement(stability, evidence, request, hit_test, deadline)?;
+ if evidence.can_wait_for_geometry(request, &report, requirement) {
+ return Ok(report);
+ }
finish(evidence, request, report)
}
@@ -115,6 +127,32 @@ pub(super) fn build_report(
hit_test: Option<(&NativeHandle, &dyn PlatformAdapter)>,
deadline: crate::Deadline,
) -> Result<ActionabilityReport, AdapterError> {
+ build_report_with_requirement(stability, evidence, request, hit_test, deadline)
+ .map(|(report, _)| report)
+}
+
+fn build_report_with_requirement(
+ stability: StabilityExpectation,
+ evidence: &ActionabilityEvidence,
+ request: &ActionRequest,
+ hit_test: Option<(&NativeHandle, &dyn PlatformAdapter)>,
+ deadline: crate::Deadline,
+) -> Result<(ActionabilityReport, Option<crate::HeadedRequirement>), AdapterError> {
+ let requirement = if request.policy.is_headed() {
+ hit_test
+ .map(|(handle, adapter)| adapter.headed_requirement(handle, request, deadline))
+ .transpose()?
+ } else {
+ None
+ };
+ let mut semantic_request;
+ let request = if requirement == Some(crate::HeadedRequirement::FocusedApplication) {
+ semantic_request = request.clone();
+ semantic_request.policy = crate::InteractionPolicy::headless();
+ &semantic_request
+ } else {
+ request
+ };
let requirements = ActionabilityRequirements::for_action(&request.action);
let pointer_delivery =
requirements.pointer_delivery(&request.action, &evidence.available_actions, request.policy);
@@ -162,12 +200,15 @@ pub(super) fn build_report(
.iter()
.any(|check| !matches!(check.status, super::status::ActionabilityStatus::Pass))
{
- return Ok(ActionabilityReport::from_checks(
- checks,
- verified_point,
- presentation_point,
- evidence.bounds,
- pointer_delivery,
+ return Ok((
+ ActionabilityReport::from_checks(
+ checks,
+ verified_point,
+ presentation_point,
+ evidence.bounds,
+ pointer_delivery,
+ ),
+ requirement,
));
}
if matches!(pointer_delivery, super::PointerDelivery::Physical) {
@@ -184,12 +225,15 @@ pub(super) fn build_report(
)),
}
}
- Ok(ActionabilityReport::from_checks(
- checks,
- verified_point,
- presentation_point,
- evidence.bounds,
- pointer_delivery,
+ Ok((
+ ActionabilityReport::from_checks(
+ checks,
+ verified_point,
+ presentation_point,
+ evidence.bounds,
+ pointer_delivery,
+ ),
+ requirement,
))
}
@@ -342,3 +386,7 @@ mod tests {
assert!(suggestion.contains("available_actions"));
}
}
+
+#[cfg(test)]
+#[path = "evaluate_geometry_tests.rs"]
+mod geometry_tests;
diff --git a/crates/core/src/actionability/evaluate_geometry_tests.rs b/crates/core/src/actionability/evaluate_geometry_tests.rs
new file mode 100644
index 000000000..caed53479
--- /dev/null
+++ b/crates/core/src/actionability/evaluate_geometry_tests.rs
@@ -0,0 +1,142 @@
+use super::*;
+use crate::{Action, ActionOps, HeadedRequirement, InputOps, ObservationOps, SystemOps};
+
+struct GeometryAdapter(HeadedRequirement);
+
+impl ActionOps for GeometryAdapter {
+ fn headed_requirement(
+ &self,
+ _: &NativeHandle,
+ _: &ActionRequest,
+ _: crate::Deadline,
+ ) -> Result<HeadedRequirement, AdapterError> {
+ Ok(self.0)
+ }
+}
+impl ObservationOps for GeometryAdapter {}
+impl InputOps for GeometryAdapter {}
+impl SystemOps for GeometryAdapter {}
+
+fn evidence() -> ActionabilityEvidence {
+ ActionabilityEvidence {
+ nonspatial: false,
+ state: crate::ElementState {
+ role: "menuitem".into(),
+ states: vec![],
+ value: None,
+ enabled: Some(true),
+ hidden: Some(false),
+ offscreen: Some(false),
+ },
+ states_complete: true,
+ bounds: None,
+ available_actions: vec!["Click".into()],
+ }
+}
+
+fn check_gap(
+ evidence: &ActionabilityEvidence,
+ timeout: u64,
+ requirement: HeadedRequirement,
+) -> Result<ActionabilityReport, AdapterError> {
+ let adapter = GeometryAdapter(requirement);
+ check_with_stability_or_gap(
+ StabilityExpectation::permissive(None),
+ evidence,
+ &ActionRequest::headed(Action::DoubleClick).with_timeout_ms(Some(timeout)),
+ Some((&NativeHandle::null(), &adapter)),
+ crate::Deadline::standard().unwrap(),
+ )
+}
+
+#[test]
+fn only_positive_timeout_application_pointers_preserve_a_geometry_gap() {
+ let mut evidence = evidence();
+ for bounds in [
+ None,
+ Some(crate::Rect {
+ x: 0.0,
+ y: 0.0,
+ width: 0.0,
+ height: 0.0,
+ }),
+ ] {
+ evidence.bounds = bounds;
+ let report = check_gap(
+ &evidence,
+ 500,
+ HeadedRequirement::FocusedApplicationAndCursor,
+ )
+ .unwrap();
+ assert!(!report.actionable);
+ assert!(report.verified_point.is_none());
+ assert_eq!(
+ report.pointer_delivery,
+ super::super::PointerDelivery::Physical
+ );
+ assert!(check_gap(&evidence, 0, HeadedRequirement::FocusedApplicationAndCursor).is_err());
+ assert!(check_gap(&evidence, 500, HeadedRequirement::FocusedWindowAndCursor).is_err());
+ let adapter = GeometryAdapter(HeadedRequirement::FocusedApplicationAndCursor);
+ assert!(
+ check_with_stability(
+ StabilityExpectation::permissive(None),
+ &evidence,
+ &ActionRequest::headed(Action::DoubleClick).with_timeout_ms(Some(500)),
+ Some((&NativeHandle::null(), &adapter)),
+ crate::Deadline::standard().unwrap()
+ )
+ .is_err()
+ );
+ }
+}
+
+#[test]
+fn geometry_gap_never_masks_hidden_disabled_or_incomplete_state() {
+ for variant in 0..5 {
+ let mut evidence = evidence();
+ match variant {
+ 0 => evidence.state.hidden = Some(true),
+ 1 => evidence.state.offscreen = Some(true),
+ 2 => evidence.state.enabled = Some(false),
+ 3 => evidence.states_complete = false,
+ _ => evidence
+ .state
+ .states
+ .push(crate::tree::state::OFFSCREEN.into()),
+ }
+ assert!(
+ check_gap(
+ &evidence,
+ 500,
+ HeadedRequirement::FocusedApplicationAndCursor
+ )
+ .is_err(),
+ "variant {variant}"
+ );
+ }
+}
+
+#[test]
+fn geometry_gap_preserves_permanent_action_and_policy_refusals() {
+ let adapter = GeometryAdapter(HeadedRequirement::FocusedApplicationAndCursor);
+ for (request, code) in [
+ (
+ ActionRequest::headed(Action::SetValue("text".into())),
+ ErrorCode::ActionNotSupported,
+ ),
+ (
+ ActionRequest::headless(Action::DoubleClick),
+ ErrorCode::PolicyDenied,
+ ),
+ ] {
+ let error = check_with_stability_or_gap(
+ StabilityExpectation::permissive(None),
+ &evidence(),
+ &request.with_timeout_ms(Some(500)),
+ Some((&NativeHandle::null(), &adapter)),
+ crate::Deadline::standard().unwrap(),
+ )
+ .unwrap_err();
+ assert_eq!(error.code, code);
+ }
+}
diff --git a/crates/core/src/actionability/evidence.rs b/crates/core/src/actionability/evidence.rs
index e8b5af822..f835c9fe6 100644
--- a/crates/core/src/actionability/evidence.rs
+++ b/crates/core/src/actionability/evidence.rs
@@ -7,3 +7,30 @@ pub(super) struct ActionabilityEvidence {
pub(super) bounds: Option<Rect>,
pub(super) available_actions: Vec<String>,
}
+
+impl ActionabilityEvidence {
+ pub(super) fn can_wait_for_geometry(
+ &self,
+ request: &crate::ActionRequest,
+ report: &super::report::ActionabilityReport,
+ requirement: Option<crate::HeadedRequirement>,
+ ) -> bool {
+ !report.actionable
+ && request.policy.is_headed()
+ && request.timeout_ms.is_some_and(|timeout| timeout > 0)
+ && self.states_complete
+ && self.state.hidden != Some(true)
+ && self.state.offscreen != Some(true)
+ && !crate::tree::state::has_state(&self.state.states, crate::tree::state::HIDDEN)
+ && !crate::tree::state::has_state(&self.state.states, crate::tree::state::OFFSCREEN)
+ && self.bounds.is_none_or(|bounds| {
+ bounds.validate().is_ok() && (bounds.width == 0.0 || bounds.height == 0.0)
+ })
+ && report.checks.iter().all(|check| {
+ check.status == super::status::ActionabilityStatus::Pass
+ || (check.terminal_code.is_none()
+ && matches!(check.check, "visible" | "stable"))
+ })
+ && requirement == Some(crate::HeadedRequirement::FocusedApplicationAndCursor)
+ }
+}
diff --git a/crates/core/src/actionability/live.rs b/crates/core/src/actionability/live.rs
index 9edc1089d..467f1896c 100644
--- a/crates/core/src/actionability/live.rs
+++ b/crates/core/src/actionability/live.rs
@@ -81,6 +81,23 @@ pub(crate) fn check_live_with_stability_or_gap(
)
}
+pub(crate) fn check_live_before_focus(
+ target: &LiveCheckTarget<'_>,
+ request: &ActionRequest,
+ stability: StabilityExpectation,
+) -> Result<ActionabilityReport, AdapterError> {
+ let evidence =
+ observe(target).map_err(crate::ref_action::mark_pre_dispatch_resolution_failure)?;
+ super::evaluate::check_before_focus(
+ stability,
+ &evidence,
+ request,
+ Some((target.handle, target.adapter)),
+ target.deadline,
+ )
+ .map_err(crate::ref_action::mark_pre_dispatch_resolution_failure)
+}
+
fn observe(target: &LiveCheckTarget<'_>) -> Result<ActionabilityEvidence, AdapterError> {
let live = match target
.adapter
@@ -104,7 +121,10 @@ fn observe(target: &LiveCheckTarget<'_>) -> Result<ActionabilityEvidence, Adapte
};
validate_live_identity(target.entry, &live)?;
Ok(ActionabilityEvidence {
- nonspatial: target.adapter.is_nonspatial_target(target.handle),
+ nonspatial: live.bounds.is_none()
+ && target
+ .adapter
+ .is_nonspatial_target_with_deadline(target.handle, target.deadline)?,
state: live.state,
states_complete: live.states_complete,
bounds: live.bounds,
diff --git a/crates/core/src/actionability/mod.rs b/crates/core/src/actionability/mod.rs
index 7030458b6..09c36218e 100644
--- a/crates/core/src/actionability/mod.rs
+++ b/crates/core/src/actionability/mod.rs
@@ -26,7 +26,8 @@ pub(crate) use gates::states_are_enabled;
#[cfg(test)]
pub(crate) use live::check_live;
pub(crate) use live::{
- LiveCheckTarget, check_live_with_stability, check_live_with_stability_or_gap,
+ LiveCheckTarget, check_live_before_focus, check_live_with_stability,
+ check_live_with_stability_or_gap,
};
pub(crate) use pointer_delivery::PointerDelivery;
pub(crate) use receives_events::require_receives_events;
diff --git a/crates/core/src/actions/headed_focus.rs b/crates/core/src/actions/headed_focus.rs
index 38dce8834..16d7537fc 100644
--- a/crates/core/src/actions/headed_focus.rs
+++ b/crates/core/src/actions/headed_focus.rs
@@ -11,27 +11,41 @@ pub(crate) fn focus_entry_window(
context: &crate::CommandContext,
lease: &crate::InteractionLease,
) -> Result<bool, AppError> {
- let process_instance = required_text(
- entry.process.process_instance.as_deref(),
- "Headed input requires target process-instance identity",
- )?;
+ entry.process.identity().ok_or_else(|| {
+ AdapterError::new(
+ ErrorCode::ActionNotSupported,
+ "Headed input requires target process-instance identity",
+ )
+ .with_details(json!({ "physical_delivery_started": false }))
+ })?;
if entry.source.is_process_owned() {
return Ok(false);
}
+ let expected = adapter.resolve_ref_focus_window(entry, lease.deadline())?;
+ focus_exact_window(&expected, adapter, context, lease).map(|_| true)
+}
+
+pub fn saved_ref_focus_window(entry: &crate::RefEntry) -> Result<WindowInfo, AdapterError> {
+ let process = entry.process.identity().ok_or_else(|| {
+ AdapterError::new(
+ ErrorCode::ActionNotSupported,
+ "Headed input requires target process-instance identity",
+ )
+ .with_details(json!({ "physical_delivery_started": false }))
+ })?;
let window_id = required_text(
entry.source.source_window_id.as_deref(),
"Headed input requires an exact source window id",
)?;
- let expected = WindowInfo {
+ Ok(WindowInfo {
id: window_id.to_string(),
title: entry.source.source_window_title.clone().unwrap_or_default(),
app: entry.source.source_app.clone().unwrap_or_default(),
- pid: entry.process.pid,
- process_instance: Some(process_instance.to_string()),
+ pid: process.pid,
+ process_instance: Some(process.instance),
bounds: None,
state: crate::WindowState::default(),
- };
- focus_exact_window(&expected, adapter, context, lease).map(|_| true)
+ })
}
pub(crate) fn focus_process_window(
@@ -69,10 +83,13 @@ pub(crate) fn focus_exact_window(
Ok(live)
}
-fn required_text<'a>(value: Option<&'a str>, message: &str) -> Result<&'a str, AppError> {
+fn required_text<'a>(value: Option<&'a str>, message: &str) -> Result<&'a str, AdapterError> {
value.filter(|value| !value.is_empty()).ok_or_else(|| {
AdapterError::new(ErrorCode::ActionNotSupported, message)
.with_details(json!({ "physical_delivery_started": false }))
- .into()
})
}
+
+#[cfg(test)]
+#[path = "headed_focus_tests.rs"]
+mod tests;
diff --git a/crates/core/src/actions/headed_focus_tests.rs b/crates/core/src/actions/headed_focus_tests.rs
new file mode 100644
index 000000000..deac0e12c
--- /dev/null
+++ b/crates/core/src/actions/headed_focus_tests.rs
@@ -0,0 +1,79 @@
+use super::*;
+use std::sync::Mutex;
+
+struct RefWindowAdapter {
+ events: Mutex<Vec<&'static str>>,
+ mismatch: bool,
+}
+
+impl crate::ObservationOps for RefWindowAdapter {}
+impl crate::ActionOps for RefWindowAdapter {}
+impl crate::InputOps for RefWindowAdapter {}
+impl crate::SystemOps for RefWindowAdapter {
+ fn resolve_ref_focus_window(
+ &self,
+ entry: &crate::RefEntry,
+ _: crate::Deadline,
+ ) -> Result<WindowInfo, AdapterError> {
+ self.events.lock().unwrap().push("ref_window");
+ assert!(entry.source.source_window_id.is_none());
+ let mut evidence = entry.clone();
+ evidence.source.source_window_id = Some("exact-live-owner".into());
+ crate::saved_ref_focus_window(&evidence)
+ }
+
+ fn resolve_window_strict(
+ &self,
+ expected: &WindowInfo,
+ _: crate::Deadline,
+ ) -> Result<WindowInfo, AdapterError> {
+ self.events.lock().unwrap().push("strict_window");
+ assert_eq!(expected.id, "exact-live-owner");
+ let mut live = expected.clone();
+ if self.mismatch {
+ live.process_instance = Some("different-generation".into());
+ }
+ Ok(live)
+ }
+
+ fn focus_window(
+ &self,
+ window: &WindowInfo,
+ _: &crate::InteractionLease,
+ ) -> Result<(), AdapterError> {
+ self.events.lock().unwrap().push("focus");
+ assert_eq!(window.id, "exact-live-owner");
+ Ok(())
+ }
+}
+
+#[test]
+fn recovered_ref_window_is_strictly_verified_before_focus_without_rewriting_source() {
+ for mismatch in [false, true] {
+ let adapter = RefWindowAdapter {
+ events: Mutex::new(Vec::new()),
+ mismatch,
+ };
+ let mut entry = crate::adapter::minimal_ref_entry("menuitem", None);
+ entry.source.source_surface = crate::SnapshotSurface::Menu;
+ let original = entry.clone();
+ let lease =
+ crate::InteractionLease::guarded(crate::Deadline::standard().unwrap(), ()).unwrap();
+ let result =
+ focus_entry_window(&entry, &adapter, &crate::CommandContext::default(), &lease);
+ assert_eq!(entry, original);
+ if mismatch {
+ assert_eq!(result.unwrap_err().code(), "STALE_REF");
+ assert_eq!(
+ *adapter.events.lock().unwrap(),
+ ["ref_window", "strict_window"]
+ );
+ } else {
+ assert!(result.unwrap());
+ assert_eq!(
+ *adapter.events.lock().unwrap(),
+ ["ref_window", "strict_window", "focus"]
+ );
+ }
+ }
+}
diff --git a/crates/core/src/actions/headed_requirement.rs b/crates/core/src/actions/headed_requirement.rs
index da1e42c6a..add52e8e0 100644
--- a/crates/core/src/actions/headed_requirement.rs
+++ b/crates/core/src/actions/headed_requirement.rs
@@ -4,6 +4,8 @@ use serde::{Deserialize, Serialize};
#[serde(rename_all = "snake_case")]
pub enum HeadedRequirement {
None,
+ FocusedApplication,
+ FocusedApplicationAndCursor,
FocusedWindow,
FocusedWindowAndCursor,
}
@@ -14,6 +16,9 @@ impl HeadedRequirement {
}
pub fn requires_cursor(self) -> bool {
- matches!(self, Self::FocusedWindowAndCursor)
+ matches!(
+ self,
+ Self::FocusedApplicationAndCursor | Self::FocusedWindowAndCursor
+ )
}
}
diff --git a/crates/core/src/adapter/actions.rs b/crates/core/src/adapter/actions.rs
index fb4669f06..979e78c7b 100644
--- a/crates/core/src/adapter/actions.rs
+++ b/crates/core/src/adapter/actions.rs
@@ -4,6 +4,24 @@ use crate::{
};
pub trait ActionOps: Send + Sync {
+ fn headed_requirement_for_ref(
+ &self,
+ _entry: &crate::RefEntry,
+ request: &ActionRequest,
+ _deadline: crate::Deadline,
+ ) -> Result<crate::HeadedRequirement, AdapterError> {
+ Ok(request.headed_requirement())
+ }
+
+ fn headed_requirement(
+ &self,
+ _handle: &NativeHandle,
+ request: &ActionRequest,
+ _deadline: crate::Deadline,
+ ) -> Result<crate::HeadedRequirement, AdapterError> {
+ Ok(request.headed_requirement())
+ }
+
fn execute_action(
&self,
_handle: &NativeHandle,
diff --git a/crates/core/src/adapter/observation.rs b/crates/core/src/adapter/observation.rs
index 671282f11..a64fb7a3d 100644
--- a/crates/core/src/adapter/observation.rs
+++ b/crates/core/src/adapter/observation.rs
@@ -28,14 +28,29 @@ fn is_live_read_unsupported(err: &AdapterError) -> bool {
}
pub trait ObservationOps: Send + Sync {
- /// Whether this resolved handle denotes a protocol object with no screen
- /// position, rather than a native control whose geometry is unreadable.
- /// Only headless semantic delivery can use this fact; fresh identity,
- /// complete state and action capability are still required.
+ fn is_application_surface(&self, _surface: SnapshotSurface) -> bool {
+ false
+ }
+
+ fn focused_app(&self, _deadline: Deadline) -> Result<Option<AppInfo>, AdapterError> {
+ Err(AdapterError::not_supported("focused_app"))
+ }
+
+ /// Reports protocol targets that have no screen position without requiring a native read.
fn is_nonspatial_target(&self, _handle: &NativeHandle) -> bool {
false
}
+ /// Reports proven nonspatial targets, including native menus, within the observation deadline.
+ /// Semantic delivery still requires fresh identity, complete live state and action capability.
+ fn is_nonspatial_target_with_deadline(
+ &self,
+ handle: &NativeHandle,
+ _deadline: Deadline,
+ ) -> Result<bool, AdapterError> {
+ Ok(self.is_nonspatial_target(handle))
+ }
+
fn observe_tree(
&self,
_root: ObservationRoot<'_>,
diff --git a/crates/core/src/adapter/system.rs b/crates/core/src/adapter/system.rs
index 5a1925041..98e99604d 100644
--- a/crates/core/src/adapter/system.rs
+++ b/crates/core/src/adapter/system.rs
@@ -76,6 +76,22 @@ pub trait SystemOps: Send + Sync {
Err(AdapterError::not_supported("focus_window"))
}
+ fn resolve_ref_focus_window(
+ &self,
+ entry: &crate::RefEntry,
+ _deadline: Deadline,
+ ) -> Result<WindowInfo, AdapterError> {
+ crate::saved_ref_focus_window(entry)
+ }
+
+ fn focus_app(
+ &self,
+ _process: ProcessIdentity,
+ _lease: &InteractionLease,
+ ) -> Result<(), AdapterError> {
+ Err(AdapterError::not_supported("focus_app"))
+ }
+
fn launch_app(
&self,
_id: &str,
@@ -303,9 +319,8 @@ pub trait SystemOps: Send + Sync {
Err(AdapterError::not_supported("window_op"))
}
- /// Resolves a live window by `WindowInfo.id`, corroborating the match against
- /// `pid` and, when present, `title`. Opaque ids must not be parsed as numeric
- /// outside the adapter; macOS uses `w-<kCGWindowNumber>`.
+ /// Resolves the exact window id against its stored pid and process instance.
+ /// Titles and bounds may change; opaque ids are interpreted only by the adapter.
fn resolve_window_strict(
&self,
_win: &WindowInfo,
diff --git a/crates/core/src/adapter/system_tests.rs b/crates/core/src/adapter/system_tests.rs
index e4e60e8e4..7b7b2d678 100644
--- a/crates/core/src/adapter/system_tests.rs
+++ b/crates/core/src/adapter/system_tests.rs
@@ -59,3 +59,43 @@ fn default_open_session_is_explicitly_unsupported() {
assert_eq!(error.code, crate::ErrorCode::PlatformNotSupported);
assert!(error.message.contains("open_session"));
}
+
+#[test]
+fn default_ref_focus_window_preserves_saved_evidence_without_native_reads() {
+ let mut entry = crate::adapter::minimal_ref_entry("menuitem", Some("Choice"));
+ entry.source.source_window_id = Some("opaque-window".into());
+ entry.source.source_window_title = Some("Owner".into());
+ entry.source.source_app = Some("Application".into());
+ let before = entry.clone();
+ let window = DefaultOnly
+ .resolve_ref_focus_window(&entry, Deadline::standard().unwrap())
+ .unwrap();
+ assert_eq!(window.id, "opaque-window");
+ assert_eq!(window.title, "Owner");
+ assert_eq!(window.app, "Application");
+ assert_eq!(window.pid, entry.process.pid);
+ assert_eq!(window.process_instance, entry.process.process_instance);
+ assert_eq!(entry, before);
+}
+
+#[test]
+fn default_ref_focus_window_refuses_missing_window_or_generation() {
+ let mut entry = crate::adapter::minimal_ref_entry("menuitem", None);
+ let deadline = Deadline::standard().unwrap();
+ assert_eq!(
+ DefaultOnly
+ .resolve_ref_focus_window(&entry, deadline)
+ .unwrap_err()
+ .code,
+ crate::ErrorCode::ActionNotSupported
+ );
+ entry.source.source_window_id = Some("exact".into());
+ entry.process.process_instance = None;
+ assert_eq!(
+ DefaultOnly
+ .resolve_ref_focus_window(&entry, deadline)
+ .unwrap_err()
+ .code,
+ crate::ErrorCode::ActionNotSupported
+ );
+}
diff --git a/crates/core/src/commands/application_surface_tests.rs b/crates/core/src/commands/application_surface_tests.rs
new file mode 100644
index 000000000..ba0bfbf87
--- /dev/null
+++ b/crates/core/src/commands/application_surface_tests.rs
@@ -0,0 +1,313 @@
+use crate::{
+ AppInfo, CommandContext, Deadline, ErrorCode, NativeHandle, ObservationRoot, RefEntry,
+ SnapshotOwner, SnapshotSurface, TreeOptions, WindowFilter, WindowInfo,
+ adapter::{ActionOps, InputOps, ObservationOps, SystemOps, minimal_accessibility_node},
+ commands::{find, wait_selector},
+ refs::refs_test_support::HomeGuard,
+};
+
+struct MenuAdapter {
+ apps: Vec<AppInfo>,
+ windows: Vec<WindowInfo>,
+}
+
+impl MenuAdapter {
+ fn windowless() -> Self {
+ Self {
+ apps: vec![app(42)],
+ windows: vec![],
+ }
+ }
+}
+
+impl ObservationOps for MenuAdapter {
+ fn is_application_surface(&self, surface: SnapshotSurface) -> bool {
+ matches!(surface, SnapshotSurface::Menubar | SnapshotSurface::Menu)
+ }
+
+ fn focused_app(&self, _deadline: Deadline) -> Result<Option<AppInfo>, crate::AdapterError> {
+ Ok(self.apps.first().cloned())
+ }
+
+ fn list_apps(&self, _deadline: Deadline) -> Result<Vec<AppInfo>, crate::AdapterError> {
+ Ok(self.apps.clone())
+ }
+
+ fn list_windows(
+ &self,
+ _filter: &WindowFilter,
+ _deadline: Deadline,
+ ) -> Result<Vec<WindowInfo>, crate::AdapterError> {
+ Ok(self.windows.clone())
+ }
+
+ fn observe_tree(
+ &self,
+ root: ObservationRoot<'_>,
+ request: &crate::ObservationRequest,
+ ) -> Result<crate::ObservedTree, crate::AdapterError> {
+ assert_eq!(root.surface(), request.surface);
+ let mut item = minimal_accessibility_node("menuitem", "Help");
+ item.presentation.available_actions = vec!["AXPress".into()];
+ item.presentation.bounds = Some(crate::Rect {
+ x: 300.0,
+ y: 10.0,
+ width: 40.0,
+ height: 20.0,
+ });
+ crate::adapter::observed_tree(&root, item)
+ }
+
+ fn resolve_element_strict(
+ &self,
+ entry: &RefEntry,
+ _deadline: Deadline,
+ ) -> Result<NativeHandle, crate::AdapterError> {
+ if !self.apps.iter().any(|app| {
+ app.pid == entry.process.pid && app.process_instance == entry.process.process_instance
+ }) {
+ return Err(crate::AdapterError::stale_ref_because("process changed"));
+ }
+ Ok(NativeHandle::null())
+ }
+}
+
+impl ActionOps for MenuAdapter {}
+impl InputOps for MenuAdapter {}
+impl SystemOps for MenuAdapter {
+ fn supported_surfaces(&self) -> Vec<SnapshotSurface> {
+ vec![SnapshotSurface::Menubar, SnapshotSurface::Menu]
+ }
+}
+
+fn app(pid: u32) -> AppInfo {
+ AppInfo {
+ name: "MenuApp".into(),
+ pid: crate::ProcessId::new(pid),
+ bundle_id: Some("org.example.menu".into()),
+ process_instance: Some(format!("instance-{pid}")),
+ presentation: None,
+ }
+}
+
+fn options(surface: SnapshotSurface) -> TreeOptions {
+ TreeOptions {
+ surface,
+ ..Default::default()
+ }
+}
+
+fn assert_application_ref(entry: &RefEntry, surface: SnapshotSurface) {
+ assert_eq!(entry.process.pid, crate::ProcessId::new(42));
+ assert_eq!(
+ entry.process.process_instance.as_deref(),
+ Some("instance-42")
+ );
+ assert_eq!(entry.source.source_app.as_deref(), Some("MenuApp"));
+ assert_eq!(entry.source.source_surface, surface);
+ assert!(entry.source.source_window_id.is_none());
+ assert_eq!(entry.source.source_window_title.as_deref(), Some(""));
+ assert!(entry.source.is_process_owned());
+ assert!(entry.source.source_window_bounds_hash.is_none());
+ assert_ne!(
+ entry.geometry.bounds_space,
+ Some(crate::BoundsSpace::Window)
+ );
+}
+
+#[test]
+fn application_surface_snapshot_and_drill_do_not_require_a_document_window() {
+ let _guard = HomeGuard::new();
+ let adapter = MenuAdapter::windowless();
+ let context = CommandContext::default();
+ for surface in [SnapshotSurface::Menubar, SnapshotSurface::Menu] {
+ for app_name in [Some("MenuApp"), None] {
+ let snapshot = crate::snapshot::run_with_context(
+ &adapter,
+ &options(surface),
+ &crate::snapshot::SnapshotTarget {
+ app_name,
+ window_id: None,
+ },
+ &context,
+ 1_000,
+ )
+ .unwrap();
+ assert!(matches!(snapshot.owner, SnapshotOwner::Application(_)));
+ let data =
+ crate::commands::snapshot::format_snapshot_fields(&snapshot, None, None).unwrap();
+ assert_eq!(data["app"], "MenuApp");
+ assert!(data.get("window").is_none());
+ assert_application_ref(snapshot.refmap.get("@e1").unwrap(), surface);
+ let root = snapshot.tree.ref_id.as_deref().unwrap();
+ let drilled = crate::snapshot::snapshot_ref::run_from_ref_with_context(
+ &adapter,
+ &TreeOptions::default(),
+ root,
+ &context,
+ 1_000,
+ )
+ .unwrap();
+ assert!(drilled.owner.window().is_none());
+ let local =
+ crate::refs::ref_token::resolve_ref_target(drilled.tree.ref_id.as_deref().unwrap())
+ .unwrap()
+ .1;
+ assert_application_ref(drilled.refmap.get(&local).unwrap(), surface);
+ }
+ }
+}
+
+#[test]
+fn find_materializes_refs_from_the_application_surface() {
+ let _guard = HomeGuard::new();
+ let adapter = MenuAdapter::windowless();
+ let context = CommandContext::default();
+ let result = find::execute(
+ find::FindArgs {
+ app: Some("MenuApp".into()),
+ window_id: None,
+ root: None,
+ surface: SnapshotSurface::Menubar,
+ filter: find::FindFilterArgs {
+ role: Some("menuitem".into()),
+ name: Some("Help".into()),
+ description: None,
+ native_id: None,
+ value: None,
+ text: None,
+ exact: true,
+ },
+ selection: find::FindSelectionArgs {
+ count: false,
+ first: true,
+ last: false,
+ nth: None,
+ limit: None,
+ },
+ states: vec![],
+ timeout_ms: Some(1_000),
+ },
+ &adapter,
+ &context,
+ )
+ .unwrap();
+ let entry = crate::commands::helpers::load_ref_entry(
+ result["match"]["ref_id"].as_str().unwrap(),
+ &context,
+ )
+ .unwrap();
+ assert_application_ref(&entry, SnapshotSurface::Menubar);
+}
+
+#[test]
+fn a_missing_document_window_does_not_satisfy_a_menu_disappearance_wait() {
+ let _guard = HomeGuard::new();
+ let adapter = MenuAdapter::windowless();
+ for gone in [false, true] {
+ let result = wait_selector::execute(
+ wait_selector::WaitSelectorInput {
+ query_raw: "menuitem:Help".into(),
+ gone,
+ app: Some("MenuApp".into()),
+ window_id: None,
+ opts: options(SnapshotSurface::Menubar),
+ timeout_ms: 30,
+ },
+ &adapter,
+ &CommandContext::default(),
+ );
+ if gone {
+ assert_eq!(result.unwrap_err().code(), "TIMEOUT");
+ } else {
+ let data = result.unwrap();
+ assert_eq!(data["matched_selector"], "menuitem:Help");
+ assert!(data.get("window").is_none());
+ }
+ }
+}
+
+#[test]
+fn an_explicit_window_selects_its_exact_application_without_becoming_the_menu_owner() {
+ let mut adapter = MenuAdapter::windowless();
+ adapter.apps.push(app(99));
+ let duplicate = crate::snapshot::build(
+ &adapter,
+ &options(SnapshotSurface::Menubar),
+ Some("MenuApp"),
+ None,
+ Deadline::standard().unwrap(),
+ );
+ assert_eq!(duplicate.err().unwrap().code(), "AMBIGUOUS_TARGET");
+ adapter.windows.push(WindowInfo {
+ id: "w-99".into(),
+ title: "Document".into(),
+ app: "MenuApp".into(),
+ pid: crate::ProcessId::new(99),
+ process_instance: Some("instance-99".into()),
+ bounds: None,
+ state: Default::default(),
+ });
+ let snapshot = crate::snapshot::build(
+ &adapter,
+ &options(SnapshotSurface::Menubar),
+ Some("MenuApp"),
+ Some("w-99"),
+ Deadline::standard().unwrap(),
+ )
+ .unwrap();
+ let SnapshotOwner::Application(owner) = snapshot.owner else {
+ panic!("menu must be application-owned")
+ };
+ assert_eq!(owner.pid, crate::ProcessId::new(99));
+ assert!(
+ snapshot
+ .refmap
+ .get("@e1")
+ .unwrap()
+ .source
+ .source_window_id
+ .is_none()
+ );
+ let missing = crate::snapshot::build(
+ &adapter,
+ &options(SnapshotSurface::Menubar),
+ Some("MenuApp"),
+ Some("w-missing"),
+ Deadline::standard().unwrap(),
+ );
+ assert_eq!(missing.err().unwrap().code(), "WINDOW_NOT_FOUND");
+}
+
+#[test]
+fn drilling_an_application_ref_rejects_a_restarted_process_without_writing_refs() {
+ let _guard = HomeGuard::new();
+ let mut adapter = MenuAdapter::windowless();
+ let snapshot = crate::snapshot::run_with_context(
+ &adapter,
+ &options(SnapshotSurface::Menubar),
+ &crate::snapshot::SnapshotTarget {
+ app_name: Some("MenuApp"),
+ window_id: None,
+ },
+ &CommandContext::default(),
+ 1_000,
+ )
+ .unwrap();
+ adapter.apps[0].process_instance = Some("replacement".into());
+ let error = crate::snapshot::snapshot_ref::run_from_ref_with_context(
+ &adapter,
+ &TreeOptions::default(),
+ snapshot.tree.ref_id.as_deref().unwrap(),
+ &CommandContext::default(),
+ 1_000,
+ )
+ .err()
+ .unwrap();
+ assert_eq!(error.code(), ErrorCode::StaleRef.as_str());
+ let saved = crate::RefStore::new()
+ .unwrap()
+ .load_snapshot(snapshot.snapshot_id.as_deref().unwrap())
+ .unwrap();
+ assert_eq!(saved.len(), snapshot.refmap.len());
+}
diff --git a/crates/core/src/commands/find_live.rs b/crates/core/src/commands/find_live.rs
index 0cc9abea4..3a241575b 100644
--- a/crates/core/src/commands/find_live.rs
+++ b/crates/core/src/commands/find_live.rs
@@ -41,15 +41,20 @@ pub(super) fn execute(
let mut resolution = match args.root.as_deref() {
Some(root_ref) => rooted_resolution(adapter, query, root_ref, &request, context)?,
None => {
- let windows = snapshot::surface_windows(
+ let owners = snapshot::surface_target::resolve_owners(
adapter,
args.app.as_deref(),
args.window_id.as_deref(),
args.surface,
deadline,
)?;
- snapshot::window_capture::first_surface_owner(windows, |window| {
- resolve_query(adapter, query, ObservationRoot::Window(window), &request)
+ snapshot::window_capture::first_surface_owner(owners, |owner| {
+ resolve_query(
+ adapter,
+ query,
+ owner.observation_root(args.surface),
+ &request,
+ )
})?
.1
}
diff --git a/crates/core/src/commands/helpers.rs b/crates/core/src/commands/helpers.rs
index 25eed7870..b54dd3a08 100644
--- a/crates/core/src/commands/helpers.rs
+++ b/crates/core/src/commands/helpers.rs
@@ -7,10 +7,12 @@ use crate::{
ref_action::ref_action_wait_context::RefActionWaitContext,
refs::RefEntry,
refs::refs_store::RefStore,
- system::window_lookup,
};
use serde_json::{Value, json};
+#[path = "post_action_observation.rs"]
+mod post_action_observation;
+
pub(crate) use crate::system::app_lookup::{
process_identity, resolve_app, revalidate_app_for_mutation,
};
@@ -116,18 +118,28 @@ pub(crate) fn execute_ref_action_dispatching(
super::point_resolve::require_pointer_capability(adapter)?;
}
let entry = load_ref_entry(&args.ref_id, context)?;
- let (result, lease, pre, deadline, lease_started) =
- crate::ref_action::ref_action_wait::execute_with_auto_wait_and_lease(
- RefActionWaitContext {
- adapter,
- entry: &entry,
- ref_id: &args.ref_id,
- context,
- },
- request,
- dispatch,
- )
- .map_err(AppError::Adapter)?;
+ let action_result = crate::ref_action::ref_action_wait::execute_with_auto_wait_and_lease(
+ RefActionWaitContext {
+ adapter,
+ entry: &entry,
+ ref_id: &args.ref_id,
+ context,
+ },
+ request,
+ dispatch,
+ );
+ let (result, lease, pre, deadline, lease_started) = match action_result {
+ Ok(result) => result,
+ Err(mut error) => {
+ if error.disposition.delivery() == crate::DeliveryDisposition::DeliveryUncertain
+ && let Some(wait) = context.wait_selector()
+ {
+ let observation = post_action_observation::observe(wait, &entry, adapter);
+ error = post_action_observation::attach(error, observation);
+ }
+ return Err(AppError::Adapter(error));
+ }
+ };
let value = serde_json::to_value(result).map_err(|error| {
post_delivery_error(AppError::Json(error), json!({ "action": "delivered" }))
})?;
@@ -150,34 +162,29 @@ pub(crate) fn execute_ref_action_dispatching(
outcome
}
-pub(crate) fn probe_app_name(adapter: &dyn PlatformAdapter, entry: &RefEntry) -> Option<String> {
- if entry.source.source_app.is_some() {
- return entry.source.source_app.clone();
- }
- let identity = crate::ProcessIdentity::new(
- entry.process.pid,
- entry.process.process_instance.as_deref()?,
- );
- window_lookup::find_window_for_process(identity, adapter, crate::Deadline::standard().ok()?)
- .ok()
- .map(|window| window.app)
-}
-
pub(crate) fn apply_post_action_wait(
result: Value,
entry: Option<&RefEntry>,
adapter: &dyn PlatformAdapter,
context: &CommandContext,
) -> Result<Value, AppError> {
- if context.wait_selector().is_none() {
+ let Some(wait) = context.wait_selector() else {
return Ok(result);
- }
- apply_scoped_post_action_wait(
+ };
+ let Some(entry) = entry else {
+ return apply_scoped_post_action_wait(result, None, None, adapter, context);
+ };
+ let input = WaitSelectorInput {
+ query_raw: wait.query_raw.clone(),
+ gone: wait.gone,
+ app: entry.source.source_app.clone(),
+ window_id: entry.source.source_window_id.clone(),
+ opts: TreeOptions::default(),
+ timeout_ms: wait.timeout_ms,
+ };
+ finish_post_action_wait(
result,
- entry.and_then(|entry| probe_app_name(adapter, entry)),
- entry.and_then(|entry| entry.source.source_window_id.clone()),
- adapter,
- context,
+ wait_selector::execute_with_ref(input, Some(entry), adapter, context),
)
}
@@ -191,7 +198,7 @@ pub(crate) fn apply_scoped_post_action_wait(
let Some(wait) = context.wait_selector() else {
return Ok(result);
};
- match wait_selector::execute(
+ let outcome = wait_selector::execute(
WaitSelectorInput {
query_raw: wait.query_raw.clone(),
gone: wait.gone,
@@ -202,7 +209,15 @@ pub(crate) fn apply_scoped_post_action_wait(
},
adapter,
context,
- ) {
+ );
+ finish_post_action_wait(result, outcome)
+}
+
+fn finish_post_action_wait(
+ result: Value,
+ outcome: Result<Value, AppError>,
+) -> Result<Value, AppError> {
+ match outcome {
Ok(mut snapshot) => {
if let Some(body) = snapshot.as_object_mut() {
body.insert("after_action".into(), result);
diff --git a/crates/core/src/commands/helpers_ref_action_wait_result_tests.rs b/crates/core/src/commands/helpers_ref_action_wait_result_tests.rs
index a7ba64949..f0c343cd6 100644
--- a/crates/core/src/commands/helpers_ref_action_wait_result_tests.rs
+++ b/crates/core/src/commands/helpers_ref_action_wait_result_tests.rs
@@ -30,6 +30,7 @@ fn post_action_wait_timeout_embeds_action_result_in_details() {
let mut refmap = RefMap::new();
let mut entry = entry();
entry.source.source_app = Some("TargetApp".into());
+ entry.source.source_window_id = Some("w-1".into());
refmap.allocate(entry);
let snapshot_id = RefStore::new().unwrap().save_new_snapshot(&refmap).unwrap();
let adapter = ScopedWaitAdapter::new();
@@ -114,3 +115,50 @@ fn failed_wait_after_unverified_delivery_stays_unsafe_to_retry() {
crate::DeliverySemantics::delivered_unverified()
);
}
+
+#[test]
+fn close_action_gone_wait_preserves_success_or_uncertain_delivery() {
+ let _home = HomeGuard::new();
+ let mut refmap = RefMap::new();
+ let mut entry = entry();
+ entry.source.source_window_id = Some("w-1".into());
+ refmap.allocate(entry);
+ let snapshot_id = RefStore::new().unwrap().save_new_snapshot(&refmap).unwrap();
+ for uncertain in [false, true] {
+ let mut adapter = ScopedWaitAdapter::new();
+ adapter.closes_window = true;
+ adapter.uncertain = uncertain;
+ let context = CommandContext::default().with_wait_selector(Some(WaitSelector {
+ query_raw: ":Close".into(),
+ gone: true,
+ timeout_ms: 250,
+ }));
+ let result = execute_ref_action_with_context(
+ RefArgs {
+ ref_id: format!("@{snapshot_id}:e1"),
+ timeout_ms: None,
+ },
+ &adapter,
+ ActionRequest::headless(Action::Click),
+ &context,
+ );
+ if uncertain {
+ let AppError::Adapter(error) = result.unwrap_err() else {
+ panic!("expected adapter error")
+ };
+ assert_eq!(error.disposition, crate::DeliverySemantics::uncertain());
+ let observation = &error.details.unwrap()["post_action_observation"];
+ assert_eq!(observation["outcome"], "expected_state_observed");
+ assert_eq!(observation["selector_matches"], false);
+ } else {
+ let value = result.unwrap();
+ assert_eq!(value["target_absent"], true);
+ assert_eq!(
+ value["after_action"]["disposition"]["delivery"],
+ "delivered_unverified"
+ );
+ }
+ assert_eq!(adapter.dispatches.load(Ordering::SeqCst), 1);
+ assert_eq!(adapter.lease_free_polls.load(Ordering::SeqCst), 0);
+ }
+}
diff --git a/crates/core/src/commands/helpers_ref_action_wait_tests.rs b/crates/core/src/commands/helpers_ref_action_wait_tests.rs
index 6c6e66f26..def8876e4 100644
--- a/crates/core/src/commands/helpers_ref_action_wait_tests.rs
+++ b/crates/core/src/commands/helpers_ref_action_wait_tests.rs
@@ -25,6 +25,9 @@ struct ScopedWaitAdapter {
polled_app: Mutex<Option<String>>,
lease_held: Arc<AtomicBool>,
lease_free_polls: AtomicU32,
+ dispatches: AtomicU32,
+ uncertain: bool,
+ closes_window: bool,
}
impl ScopedWaitAdapter {
@@ -34,15 +37,22 @@ impl ScopedWaitAdapter {
polled_app: Mutex::new(None),
lease_held: Arc::new(AtomicBool::new(false)),
lease_free_polls: AtomicU32::new(0),
+ dispatches: AtomicU32::new(0),
+ uncertain: false,
+ closes_window: false,
}
}
}
impl ObservationOps for ScopedWaitAdapter {
+ fn is_application_surface(&self, surface: crate::SnapshotSurface) -> bool {
+ surface == crate::SnapshotSurface::Menubar
+ }
+
fn observe_tree(
&self,
root: crate::locator::live_locator::ObservationRoot<'_>,
- _request: &crate::locator::live_locator::ObservationRequest,
+ request: &crate::locator::live_locator::ObservationRequest,
) -> Result<crate::locator::live_locator::ObservedTree, AdapterError> {
if matches!(
root,
@@ -50,7 +60,20 @@ impl ObservationOps for ScopedWaitAdapter {
) {
return crate::adapter::saved_ref_element_tree(root);
}
- if !self.lease_held.load(Ordering::SeqCst) {
+ if request.surface == crate::SnapshotSurface::Menubar {
+ let crate::locator::live_locator::ObservationRoot::Application { app, .. } = root
+ else {
+ return Err(AdapterError::internal("expected application root"));
+ };
+ *self.polled_app.lock().unwrap() = Some(app.name.clone());
+ }
+ let post_action = self.dispatches.load(Ordering::SeqCst) > 0;
+ if post_action && self.lease_held.load(Ordering::SeqCst) {
+ return Err(AdapterError::internal(
+ "post-action wait must poll with the interaction lease released",
+ ));
+ }
+ if post_action {
self.lease_free_polls.fetch_add(1, Ordering::SeqCst);
}
crate::adapter::observed_tree(
@@ -85,6 +108,9 @@ impl ObservationOps for ScopedWaitAdapter {
_deadline: crate::Deadline,
) -> Result<Vec<WindowInfo>, AdapterError> {
*self.polled_app.lock().unwrap() = filter.app.clone();
+ if self.closes_window && self.dispatches.load(Ordering::SeqCst) > 0 {
+ return Ok(Vec::new());
+ }
Ok(vec![WindowInfo {
id: "w-1".into(),
title: "Doc".into(),
@@ -99,27 +125,6 @@ impl ObservationOps for ScopedWaitAdapter {
}])
}
- fn get_tree(
- &self,
- _win: &WindowInfo,
- _opts: &crate::adapter::TreeOptions,
- _deadline: crate::Deadline,
- ) -> Result<AccessibilityNode, AdapterError> {
- Ok(AccessibilityNode {
- ref_id: None,
- role: "window".into(),
- identity: crate::NodeIdentity {
- retained_object: None,
- name: Some("Saved!".into()),
- ..Default::default()
- },
- presentation: Default::default(),
- children_count: None,
- subtree_truncated: false,
- children: vec![],
- })
- }
-
crate::adapter::complete_live_observation!("button", "OK", [crate::actions::capability::CLICK]);
crate::adapter::saved_ref_anchor!();
}
@@ -133,6 +138,12 @@ impl ActionOps for ScopedWaitAdapter {
) -> Result<ActionResult, AdapterError> {
assert!(self.lease_held.load(Ordering::SeqCst));
*self.request.lock().unwrap() = Some(request);
+ self.dispatches.fetch_add(1, Ordering::SeqCst);
+ if self.uncertain {
+ return Err(AdapterError::app_unresponsive("TargetApp")
+ .with_details(json!({ "ax_error": -25204 }))
+ .with_disposition(crate::DeliverySemantics::uncertain()));
+ }
Ok(ActionResult::delivered_unverified("ok"))
}
}
@@ -140,6 +151,35 @@ impl ActionOps for ScopedWaitAdapter {
impl InputOps for ScopedWaitAdapter {}
impl SystemOps for ScopedWaitAdapter {
+ fn resolve_window_strict(
+ &self,
+ expected: &WindowInfo,
+ _deadline: crate::Deadline,
+ ) -> Result<WindowInfo, AdapterError> {
+ assert_eq!(expected.id, "w-1");
+ assert_eq!(expected.pid, crate::ProcessId::new(1));
+ assert_eq!(expected.process_instance.as_deref(), Some("test-instance"));
+ if self.closes_window && self.dispatches.load(Ordering::SeqCst) > 0 {
+ return Err(AdapterError::new(
+ crate::ErrorCode::WindowNotFound,
+ "Original window closed",
+ ));
+ }
+ Ok(expected.clone())
+ }
+
+ fn process_state(
+ &self,
+ process: crate::ProcessIdentity,
+ _deadline: crate::Deadline,
+ ) -> Result<crate::system::process_state::ProcessState, AdapterError> {
+ assert_eq!(
+ process,
+ crate::ProcessIdentity::new(crate::ProcessId::new(1), "test-instance")
+ );
+ Ok(crate::system::process_state::ProcessState::Running)
+ }
+
fn acquire_interaction_lease(
&self,
deadline: crate::Deadline,
@@ -152,40 +192,57 @@ impl SystemOps for ScopedWaitAdapter {
}
#[test]
-fn post_action_wait_scopes_to_source_app_and_merges_action_result() {
+fn post_action_wait_scopes_and_reconciles_without_redispatch_or_held_lease() {
let _guard = HomeGuard::new();
- let mut refmap = RefMap::new();
- let mut entry = entry();
- entry.source.source_app = Some("TargetApp".into());
- refmap.allocate(entry);
- let snapshot_id = RefStore::new().unwrap().save_new_snapshot(&refmap).unwrap();
- let adapter = ScopedWaitAdapter::new();
- let context = CommandContext::default().with_wait_selector(Some(WaitSelector {
- query_raw: ":saved!".into(),
- gone: false,
- timeout_ms: 5_000,
- }));
- let args = RefArgs {
- ref_id: format!("@{}:e1", snapshot_id),
- timeout_ms: None,
- };
-
- let value = execute_ref_action_with_context(
- args,
- &adapter,
- ActionRequest::headless(Action::Click),
- &context,
- )
- .unwrap();
-
- assert_eq!(
- adapter.polled_app.lock().unwrap().as_deref(),
- Some("TargetApp")
- );
- assert!(!adapter.lease_held.load(Ordering::SeqCst));
- assert!(adapter.lease_free_polls.load(Ordering::SeqCst) >= 1);
- assert_eq!(value["after_action"]["action"], "ok");
- assert_eq!(value["matched_selector"], ":saved!");
+ for uncertain in [false, true] {
+ let mut refmap = RefMap::new();
+ let mut entry = entry();
+ entry.source.source_app = Some("TargetApp".into());
+ entry.source.source_surface = crate::SnapshotSurface::Menubar;
+ assert!(entry.source.source_window_id.is_none());
+ refmap.allocate(entry);
+ let snapshot_id = RefStore::new().unwrap().save_new_snapshot(&refmap).unwrap();
+ let mut adapter = ScopedWaitAdapter::new();
+ adapter.uncertain = uncertain;
+ let context = CommandContext::default().with_wait_selector(Some(WaitSelector {
+ query_raw: ":saved!".into(),
+ gone: false,
+ timeout_ms: 500,
+ }));
+ let result = execute_ref_action_with_context(
+ RefArgs {
+ ref_id: format!("@{snapshot_id}:e1"),
+ timeout_ms: None,
+ },
+ &adapter,
+ ActionRequest::headless(Action::Click),
+ &context,
+ );
+ assert_eq!(adapter.dispatches.load(Ordering::SeqCst), 1);
+ assert_eq!(
+ adapter.polled_app.lock().unwrap().as_deref(),
+ Some("TargetApp")
+ );
+ assert!(!adapter.lease_held.load(Ordering::SeqCst));
+ assert!(adapter.lease_free_polls.load(Ordering::SeqCst) >= 1);
+ if uncertain {
+ let AppError::Adapter(error) = result.unwrap_err() else {
+ panic!("expected adapter error")
+ };
+ assert_eq!(error.code, crate::ErrorCode::AppUnresponsive);
+ assert_eq!(error.disposition, crate::DeliverySemantics::uncertain());
+ let details = error.details.unwrap();
+ assert_eq!(details["ax_error"], -25204);
+ assert_eq!(
+ details["post_action_observation"]["outcome"],
+ "expected_state_observed"
+ );
+ } else {
+ let value = result.unwrap();
+ assert_eq!(value["after_action"]["action"], "ok");
+ assert_eq!(value["matched_selector"], ":saved!");
+ }
+ }
}
struct MultiWindowAdapter;
@@ -272,44 +329,6 @@ impl ObservationOps for MultiWindowAdapter {
])
}
- fn get_tree(
- &self,
- win: &WindowInfo,
- _opts: &crate::adapter::TreeOptions,
- _deadline: crate::Deadline,
- ) -> Result<AccessibilityNode, AdapterError> {
- let children = if win.id == "w-target" {
- vec![AccessibilityNode {
- ref_id: None,
- role: "button".into(),
- identity: crate::NodeIdentity {
- retained_object: None,
- name: Some("Saved!".into()),
- ..Default::default()
- },
- presentation: Default::default(),
- children_count: None,
- subtree_truncated: false,
- children: vec![],
- }]
- } else {
- vec![]
- };
- Ok(AccessibilityNode {
- ref_id: None,
- role: "window".into(),
- identity: crate::NodeIdentity {
- retained_object: None,
- name: Some(win.title.clone()),
- ..Default::default()
- },
- presentation: Default::default(),
- children_count: None,
- subtree_truncated: false,
- children,
- })
- }
-
crate::adapter::complete_live_observation!("button", "OK", [crate::actions::capability::CLICK]);
crate::adapter::saved_ref_anchor!();
}
@@ -328,6 +347,17 @@ impl ActionOps for MultiWindowAdapter {
impl InputOps for MultiWindowAdapter {}
impl SystemOps for MultiWindowAdapter {
+ fn resolve_window_strict(
+ &self,
+ expected: &WindowInfo,
+ _deadline: crate::Deadline,
+ ) -> Result<WindowInfo, AdapterError> {
+ assert_eq!(expected.id, "w-target");
+ assert_eq!(expected.pid, crate::ProcessId::new(1));
+ assert_eq!(expected.process_instance.as_deref(), Some("test-instance"));
+ Ok(expected.clone())
+ }
+
crate::adapter::guarded_interaction_lease!();
}
diff --git a/crates/core/src/commands/mod.rs b/crates/core/src/commands/mod.rs
index b6964f835..1c13048ee 100644
--- a/crates/core/src/commands/mod.rs
+++ b/crates/core/src/commands/mod.rs
@@ -60,6 +60,7 @@ mod screenshot_tests;
pub mod scroll;
pub mod scroll_to;
pub mod select;
+pub(crate) mod selector_observation;
pub mod session;
pub mod set_value;
pub mod skills;
@@ -103,3 +104,6 @@ mod stale_retry_test_support;
#[cfg(test)]
mod operation_passthrough_tests;
+
+#[cfg(test)]
+mod application_surface_tests;
diff --git a/crates/core/src/commands/post_action_observation.rs b/crates/core/src/commands/post_action_observation.rs
new file mode 100644
index 000000000..432c8596b
--- /dev/null
+++ b/crates/core/src/commands/post_action_observation.rs
@@ -0,0 +1,201 @@
+use crate::{
+ AdapterError, AppError, Deadline, RefEntry, SignalFilter, adapter::PlatformAdapter,
+ commands::selector_observation::SelectorObservation, context::WaitSelector,
+ system::process_state::ProcessState,
+};
+use serde_json::{Value, json};
+use std::time::Instant;
+
+#[derive(Clone)]
+struct Probe {
+ outcome: &'static str,
+ selector_matches: Option<bool>,
+ process_state: Option<ProcessState>,
+ last_error: Option<Value>,
+}
+
+pub(crate) fn observe(
+ wait: &WaitSelector,
+ entry: &RefEntry,
+ adapter: &dyn PlatformAdapter,
+) -> Value {
+ let started = Instant::now();
+ let surface = crate::snapshot::surface_target::ref_observation_surface(adapter, entry);
+ let Some(process) = entry.process.identity() else {
+ return evidence(
+ wait,
+ entry,
+ surface,
+ &Probe::new("identity_unavailable"),
+ started,
+ );
+ };
+ let query = match crate::commands::query::validate_selector(&wait.query_raw) {
+ Ok(query) => query,
+ Err(error) => return failed_evidence(wait, entry, surface, error, started),
+ };
+ let deadline = match Deadline::after(wait.timeout_ms) {
+ Ok(deadline) => deadline,
+ Err(error) => return failed_evidence(wait, entry, surface, error.into(), started),
+ };
+ let mut latest = Probe::new("timed_out");
+ let result = crate::commands::wait_selector::poll_selector(
+ adapter,
+ SignalFilter {
+ app: entry.source.source_app.clone(),
+ process: Some(process),
+ },
+ deadline,
+ |poll_deadline| {
+ let observed = SelectorObservation::observe_ref(adapter, entry, &query, poll_deadline);
+ if matches!(&observed, Err(error)
+ if error.code() == crate::ErrorCode::Timeout.as_str() && poll_deadline.is_expired())
+ {
+ return Ok(None);
+ }
+ latest = Probe::new("timed_out");
+ Ok(match observed {
+ Ok(SelectorObservation::Selector { matches, complete }) if matches || complete => {
+ latest.selector_matches = Some(matches);
+ if matches != wait.gone {
+ latest.outcome = "expected_state_observed";
+ Some(latest.clone())
+ } else {
+ None
+ }
+ }
+ Ok(SelectorObservation::Selector { .. }) => {
+ latest.last_error = Some(error_value(
+ &AdapterError::new(
+ crate::ErrorCode::Timeout,
+ "Selector observation was incomplete",
+ )
+ .into(),
+ ));
+ None
+ }
+ Ok(SelectorObservation::OwnerUnavailable(state)) => {
+ latest.process_state = Some(state);
+ latest.outcome = match state {
+ ProcessState::Exited { .. } => "process_exited",
+ ProcessState::Crashed { .. } => "process_crashed",
+ _ => "owner_unavailable",
+ };
+ matches!(
+ state,
+ ProcessState::Exited { .. } | ProcessState::Crashed { .. }
+ )
+ .then(|| latest.clone())
+ }
+ Err(error) => {
+ let transient = is_transient(&error, entry.source.source_window_id.as_deref());
+ latest.outcome = if transient {
+ "timed_out"
+ } else {
+ "observation_failed"
+ };
+ latest.last_error = Some(error_value(&error));
+ (deadline.is_expired() || !transient).then(|| latest.clone())
+ }
+ })
+ },
+ );
+
+ match result {
+ Ok(Some(probe)) => evidence(wait, entry, surface, &probe, started),
+ Ok(None) => {
+ if latest.outcome != "owner_unavailable" {
+ latest.outcome = "timed_out";
+ }
+ evidence(wait, entry, surface, &latest, started)
+ }
+ Err(error) => failed_evidence(wait, entry, surface, error, started),
+ }
+}
+
+impl Probe {
+ fn new(outcome: &'static str) -> Self {
+ Self {
+ outcome,
+ selector_matches: None,
+ process_state: None,
+ last_error: None,
+ }
+ }
+}
+
+fn is_transient(error: &AppError, window_id: Option<&str>) -> bool {
+ error.code() == crate::ErrorCode::Timeout.as_str()
+ || crate::commands::wait_selector::is_transient_poll_error(error, window_id)
+}
+
+fn error_value(error: &AppError) -> Value {
+ json!({ "code": error.code(), "message": error.to_string() })
+}
+
+fn failed_evidence(
+ wait: &WaitSelector,
+ entry: &RefEntry,
+ surface: crate::SnapshotSurface,
+ error: AppError,
+ started: Instant,
+) -> Value {
+ let mut probe = Probe::new(
+ if is_transient(&error, entry.source.source_window_id.as_deref()) {
+ "timed_out"
+ } else {
+ "observation_failed"
+ },
+ );
+ probe.last_error = Some(error_value(&error));
+ evidence(wait, entry, surface, &probe, started)
+}
+
+fn evidence(
+ wait: &WaitSelector,
+ entry: &RefEntry,
+ surface: crate::SnapshotSurface,
+ probe: &Probe,
+ started: Instant,
+) -> Value {
+ let mut value = json!({
+ "kind": "post_action_observation",
+ "selector": wait.query_raw,
+ "expected": if wait.gone { "absent" } else { "present" },
+ "outcome": probe.outcome,
+ "surface": surface.as_str(),
+ "process_identity": {
+ "pid": entry.process.pid,
+ "process_instance": entry.process.process_instance,
+ },
+ "elapsed_ms": started.elapsed().as_millis(),
+ });
+ if let Some(window_id) = &entry.source.source_window_id {
+ value["source_window_id"] = json!(window_id);
+ }
+ if let Some(matches) = probe.selector_matches {
+ value["selector_matches"] = json!(matches);
+ }
+ if let Some(state) = probe.process_state {
+ value["process_state"] = json!(state.label());
+ }
+ if let Some(error) = &probe.last_error {
+ value["last_observation_error"] = error.clone();
+ }
+ value
+}
+
+pub(crate) fn attach(mut error: AdapterError, observation: Value) -> AdapterError {
+ let mut details = match error.details.take() {
+ Some(Value::Object(details)) => details,
+ Some(other) => serde_json::Map::from_iter([("adapter_details".into(), other)]),
+ None => serde_json::Map::new(),
+ };
+ details.insert("post_action_observation".into(), observation);
+ error.details = Some(Value::Object(details));
+ error
+}
+
+#[cfg(test)]
+#[path = "post_action_observation_tests.rs"]
+mod tests;
diff --git a/crates/core/src/commands/post_action_observation_lifecycle_tests.rs b/crates/core/src/commands/post_action_observation_lifecycle_tests.rs
new file mode 100644
index 000000000..9310c4971
--- /dev/null
+++ b/crates/core/src/commands/post_action_observation_lifecycle_tests.rs
@@ -0,0 +1,325 @@
+use super::*;
+
+#[test]
+fn unresponsive_original_process_does_not_prove_selector_absence() {
+ let mut adapter = windowless_adapter();
+ adapter.process_state = ProcessState::Unresponsive;
+ for gone in [false, true] {
+ assert_eq!(
+ delivered_wait(&adapter, &menu_entry(), gone)
+ .unwrap_err()
+ .code(),
+ "TIMEOUT"
+ );
+ let result = observe(&wait_for_ready(gone), &menu_entry(), &adapter);
+ assert_eq!(result["outcome"], "owner_unavailable");
+ assert_eq!(result["process_state"], "unresponsive");
+ assert!(result.get("selector_matches").is_none());
+ }
+ assert!(adapter.process_checks.load(Ordering::SeqCst) > 4);
+ assert_eq!(adapter.inventory_queries.load(Ordering::SeqCst), 0);
+ assert!(adapter.observed.lock().unwrap().is_empty());
+}
+
+#[test]
+fn exited_original_application_satisfies_only_a_gone_wait() {
+ for state in [
+ ProcessState::Exited { code: None },
+ ProcessState::Crashed { signal_or_code: 9 },
+ ] {
+ let mut adapter = windowless_adapter();
+ adapter.process_state = state;
+ assert_eq!(
+ delivered_wait(&adapter, &menu_entry(), true).unwrap()["target_absent"],
+ true
+ );
+ assert_eq!(
+ delivered_wait(&adapter, &menu_entry(), false)
+ .unwrap_err()
+ .code(),
+ "TIMEOUT"
+ );
+ let result = observe(&wait_for_ready(true), &menu_entry(), &adapter);
+ assert_eq!(
+ result["outcome"],
+ if matches!(state, ProcessState::Crashed { .. }) {
+ "process_crashed"
+ } else {
+ "process_exited"
+ }
+ );
+ assert!(result.get("selector_matches").is_none());
+ assert!(adapter.observed.lock().unwrap().is_empty());
+ }
+}
+
+#[test]
+fn replacement_window_cannot_satisfy_positive_wait_for_original_generation() {
+ let mut adapter = windowless_adapter();
+ adapter.windows = vec![window(1, "replacement")];
+ assert_eq!(
+ delivered_wait(&adapter, &entry(), false)
+ .unwrap_err()
+ .code(),
+ "TIMEOUT"
+ );
+ assert_eq!(
+ delivered_wait(&adapter, &entry(), true).unwrap()["target_absent"],
+ true
+ );
+ assert!(adapter.observed.lock().unwrap().is_empty());
+}
+
+#[test]
+fn incomplete_window_identity_cannot_prove_original_window_absence() {
+ let mut adapter = windowless_adapter();
+ let mut original = window(1, "test-instance");
+ original.process_instance = None;
+ adapter.windows = vec![original];
+ assert_eq!(
+ delivered_wait(&adapter, &entry(), true).unwrap_err().code(),
+ "ACTION_NOT_SUPPORTED"
+ );
+ assert!(adapter.observed.lock().unwrap().is_empty());
+}
+
+#[test]
+fn application_owner_requires_saved_label_and_nonempty_generation() {
+ let adapter = windowless_adapter();
+ let mut missing_label = menu_entry();
+ missing_label.source.source_app = None;
+ assert_eq!(
+ delivered_wait(&adapter, &missing_label, true)
+ .unwrap_err()
+ .code(),
+ "STALE_REF"
+ );
+ for generation in [None, Some(String::new())] {
+ let mut entry = menu_entry();
+ entry.process.process_instance = generation;
+ assert_eq!(
+ delivered_wait(&adapter, &entry, true).unwrap_err().code(),
+ "ACTION_NOT_SUPPORTED"
+ );
+ }
+ assert_eq!(adapter.process_checks.load(Ordering::SeqCst), 1);
+ assert_eq!(adapter.inventory_queries.load(Ordering::SeqCst), 0);
+}
+
+#[test]
+fn process_owned_wait_uses_process_window_and_refuses_unmarked_missing_window() {
+ let _home = crate::refs::refs_test_support::HomeGuard::new();
+ for surface in [
+ crate::SnapshotSurface::Window,
+ crate::SnapshotSurface::MenuBarExtras,
+ ] {
+ let adapter = windowless_adapter();
+ let mut entry = menu_entry();
+ entry.source.source_surface = surface;
+ entry.source.source_window_title = Some(String::new());
+
+ let result = delivered_wait(&adapter, &entry, false).unwrap();
+ assert_eq!(result["app"], "TargetApp");
+ let observed = adapter.observed.lock().unwrap();
+ assert!(!observed.is_empty());
+ assert!(observed.iter().all(|(pid, observed_surface)| {
+ *pid == crate::ProcessId::new(1) && *observed_surface == surface
+ }));
+ }
+
+ for surface in [
+ crate::SnapshotSurface::Window,
+ crate::SnapshotSurface::MenuBarExtras,
+ ] {
+ let adapter = windowless_adapter();
+ let mut malformed = menu_entry();
+ malformed.source.source_surface = surface;
+ assert_eq!(
+ delivered_wait(&adapter, &malformed, false)
+ .unwrap_err()
+ .code(),
+ "ACTION_NOT_SUPPORTED"
+ );
+ assert!(adapter.observed.lock().unwrap().is_empty());
+ }
+}
+
+struct StrictReadAdapter {
+ deadline: Deadline,
+ code: ErrorCode,
+}
+
+impl ObservationOps for StrictReadAdapter {
+ fn is_application_surface(&self, surface: crate::SnapshotSurface) -> bool {
+ surface == crate::SnapshotSurface::Menubar
+ }
+}
+impl ActionOps for StrictReadAdapter {}
+impl InputOps for StrictReadAdapter {}
+impl SystemOps for StrictReadAdapter {
+ fn resolve_window_strict(
+ &self,
+ expected: &WindowInfo,
+ deadline: Deadline,
+ ) -> Result<WindowInfo, AdapterError> {
+ assert_eq!(deadline, self.deadline);
+ assert_eq!(expected.id, "source-window");
+ assert_eq!(expected.pid, crate::ProcessId::new(1));
+ assert_eq!(expected.process_instance.as_deref(), Some("test-instance"));
+ assert_eq!(expected.app, "Saved label");
+ assert_eq!(expected.title, "Saved title");
+ Err(
+ AdapterError::new(self.code.clone(), "Exact window read failed")
+ .with_details(json!({"original": true})),
+ )
+ }
+
+ fn process_state(
+ &self,
+ process: ProcessIdentity,
+ deadline: Deadline,
+ ) -> Result<ProcessState, AdapterError> {
+ assert_eq!(deadline, self.deadline);
+ assert_eq!(
+ process,
+ ProcessIdentity::new(crate::ProcessId::new(1), "test-instance")
+ );
+ if self.code == ErrorCode::WindowNotFound {
+ return Ok(ProcessState::Running);
+ }
+ Err(
+ AdapterError::new(self.code.clone(), "Exact process read failed")
+ .with_details(json!({"original": true})),
+ )
+ }
+}
+
+#[test]
+fn strict_window_lookup_uses_saved_identity_and_only_not_found_proves_absence() {
+ use crate::snapshot::{
+ ref_owner_observation::RefOwnerObservation, surface_target::resolve_ref_owner,
+ };
+ let mut entry = entry();
+ entry.source.source_app = Some("Saved label".into());
+ entry.source.source_window_title = Some("Saved title".into());
+ for code in [
+ ErrorCode::WindowNotFound,
+ ErrorCode::Timeout,
+ ErrorCode::AppUnresponsive,
+ ErrorCode::PermDenied,
+ ErrorCode::ActionNotSupported,
+ ErrorCode::StaleRef,
+ ] {
+ let adapter = StrictReadAdapter {
+ deadline: Deadline::after(250).unwrap(),
+ code: code.clone(),
+ };
+ let result = resolve_ref_owner(&adapter, &entry, adapter.deadline);
+ if code == ErrorCode::WindowNotFound {
+ assert!(matches!(result, Ok(RefOwnerObservation::Absent(None))));
+ } else {
+ let AppError::Adapter(error) = result.err().unwrap() else {
+ panic!("expected adapter error")
+ };
+ assert_eq!(error.code, code);
+ assert_eq!(error.message, "Exact window read failed");
+ assert_eq!(error.details.unwrap()["original"], true);
+ }
+ }
+}
+
+#[test]
+fn process_liveness_errors_preserve_deadline_and_original_error() {
+ use crate::snapshot::surface_target::resolve_ref_owner;
+ let adapter = StrictReadAdapter {
+ deadline: Deadline::after(250).unwrap(),
+ code: ErrorCode::PermDenied,
+ };
+ let error = resolve_ref_owner(&adapter, &menu_entry(), adapter.deadline)
+ .err()
+ .unwrap();
+ let AppError::Adapter(error) = error else {
+ panic!("expected adapter error")
+ };
+ assert_eq!(error.code, ErrorCode::PermDenied);
+ assert_eq!(error.message, "Exact process read failed");
+ assert_eq!(error.details.unwrap()["original"], true);
+}
+
+#[test]
+fn absent_window_reconciliation_preserves_original_process_exit_and_crash() {
+ for state in [
+ ProcessState::Exited { code: None },
+ ProcessState::Crashed { signal_or_code: 9 },
+ ] {
+ let mut adapter = windowless_adapter();
+ adapter.process_state = state;
+ for gone in [false, true] {
+ let result = observe(&wait_for_ready(gone), &entry(), &adapter);
+ assert_eq!(
+ result["outcome"],
+ if matches!(state, ProcessState::Crashed { .. }) {
+ "process_crashed"
+ } else {
+ "process_exited"
+ }
+ );
+ assert_eq!(result["process_state"], state.label());
+ assert!(result.get("selector_matches").is_none());
+ }
+ assert_eq!(
+ delivered_wait(&adapter, &entry(), true).unwrap()["target_absent"],
+ true
+ );
+ assert_eq!(
+ delivered_wait(&adapter, &entry(), false)
+ .unwrap_err()
+ .code(),
+ "TIMEOUT"
+ );
+ assert!(adapter.observed.lock().unwrap().is_empty());
+ assert_eq!(adapter.inventory_queries.load(Ordering::SeqCst), 0);
+ }
+}
+
+#[test]
+fn incomplete_zero_match_reads_never_prove_presence_or_absence() {
+ let _home = crate::refs::refs_test_support::HomeGuard::new();
+ let mut adapter = ProbeAdapter {
+ windows: vec![window(1, "test-instance")],
+ matching_pid: None,
+ incomplete: true,
+ ..windowless_adapter()
+ };
+ for gone in [false, true] {
+ assert_eq!(
+ delivered_wait(&adapter, &entry(), gone).unwrap_err().code(),
+ "TIMEOUT"
+ );
+ let result = observe(&wait_for_ready(gone), &entry(), &adapter);
+ assert_eq!(result["outcome"], "timed_out");
+ assert!(result.get("selector_matches").is_none());
+ }
+ assert!(!adapter.observed.lock().unwrap().is_empty());
+ adapter.incomplete = false;
+ assert_eq!(
+ delivered_wait(&adapter, &entry(), true).unwrap()["target_absent"],
+ true
+ );
+ assert_eq!(
+ observe(&wait_for_ready(true), &entry(), &adapter)["outcome"],
+ "expected_state_observed"
+ );
+}
+
+#[test]
+fn successful_menu_materialization_rechecks_original_process_liveness() {
+ let adapter = ProbeAdapter {
+ exits_after_observation: true,
+ ..windowless_adapter()
+ };
+ let error = delivered_wait(&adapter, &menu_entry(), false).unwrap_err();
+ assert_eq!(error.code(), "TIMEOUT");
+ assert_eq!(adapter.observed.lock().unwrap().len(), 1);
+ assert!(adapter.process_checks.load(Ordering::SeqCst) >= 2);
+}
diff --git a/crates/core/src/commands/post_action_observation_surface_tests.rs b/crates/core/src/commands/post_action_observation_surface_tests.rs
new file mode 100644
index 000000000..1e30d4d27
--- /dev/null
+++ b/crates/core/src/commands/post_action_observation_surface_tests.rs
@@ -0,0 +1,143 @@
+use super::*;
+
+struct SurfaceAbsenceAdapter {
+ inner: ProbeAdapter,
+ error: AdapterError,
+ fail_after_observations: usize,
+}
+
+impl ObservationOps for SurfaceAbsenceAdapter {
+ fn is_application_surface(&self, surface: crate::SnapshotSurface) -> bool {
+ surface == crate::SnapshotSurface::Menu
+ }
+
+ fn observe_tree(
+ &self,
+ root: ObservationRoot<'_>,
+ request: &ObservationRequest,
+ ) -> Result<ObservedTree, AdapterError> {
+ assert_eq!(request.surface, crate::SnapshotSurface::Menu);
+ if self.inner.observed.lock().unwrap().len() >= self.fail_after_observations {
+ return Err(self.error.clone());
+ }
+ self.inner.observe_tree(root, request)
+ }
+}
+
+impl ActionOps for SurfaceAbsenceAdapter {}
+impl InputOps for SurfaceAbsenceAdapter {}
+impl SystemOps for SurfaceAbsenceAdapter {
+ fn resolve_window_strict(
+ &self,
+ expected: &WindowInfo,
+ deadline: Deadline,
+ ) -> Result<WindowInfo, AdapterError> {
+ self.inner.resolve_window_strict(expected, deadline)
+ }
+
+ fn process_state(
+ &self,
+ process: ProcessIdentity,
+ deadline: Deadline,
+ ) -> Result<ProcessState, AdapterError> {
+ self.inner.process_state(process, deadline)
+ }
+}
+
+fn absence_error() -> AdapterError {
+ AdapterError::surface_absent(crate::SnapshotSurface::Menu, "No open menu")
+}
+
+fn menu_source() -> RefEntry {
+ let mut entry = menu_entry();
+ entry.source.source_surface = crate::SnapshotSurface::Menu;
+ entry
+}
+
+fn adapter() -> SurfaceAbsenceAdapter {
+ SurfaceAbsenceAdapter {
+ inner: windowless_adapter(),
+ error: absence_error(),
+ fail_after_observations: 0,
+ }
+}
+
+fn wait(adapter: &SurfaceAbsenceAdapter, gone: bool) -> Result<Value, AppError> {
+ let context = crate::CommandContext::default().with_wait_selector(Some(wait_for_ready(gone)));
+ super::super::super::apply_post_action_wait(
+ serde_json::to_value(crate::ActionResult::delivered_unverified("click")).unwrap(),
+ Some(&menu_source()),
+ adapter,
+ &context,
+ )
+}
+
+#[test]
+fn complete_menu_absence_satisfies_only_gone_for_application_owner() {
+ let adapter = adapter();
+ assert_eq!(wait(&adapter, true).unwrap()["target_absent"], true);
+ assert_eq!(wait(&adapter, false).unwrap_err().code(), "TIMEOUT");
+ let result = observe(&wait_for_ready(true), &menu_source(), &adapter);
+ assert_eq!(result["outcome"], "expected_state_observed");
+ assert_eq!(result["selector_matches"], false);
+ assert_eq!(result["surface"], "menu");
+}
+
+#[test]
+fn incomplete_or_different_surface_errors_do_not_prove_menu_absence() {
+ for details in [
+ json!({}),
+ json!({"kind": "surface_absent", "surface": "menu", "complete": false}),
+ json!({"kind": "surface_absent", "surface": "menu"}),
+ json!({"kind": "surface_absent", "surface": "menubar", "complete": true}),
+ ] {
+ let adapter = SurfaceAbsenceAdapter {
+ error: AdapterError::new(ErrorCode::ElementNotFound, "Menu read failed")
+ .with_details(details),
+ ..adapter()
+ };
+ assert_eq!(
+ wait(&adapter, true).unwrap_err().code(),
+ "ELEMENT_NOT_FOUND"
+ );
+ let result = observe(&wait_for_ready(true), &menu_source(), &adapter);
+ assert_eq!(result["outcome"], "observation_failed");
+ assert!(result.get("selector_matches").is_none());
+ }
+}
+
+#[test]
+fn menu_dismissal_between_poll_and_materialization_cannot_satisfy_presence() {
+ let adapter = SurfaceAbsenceAdapter {
+ fail_after_observations: 1,
+ ..adapter()
+ };
+ let error = wait(&adapter, false).unwrap_err();
+ let AppError::Adapter(error) = error else {
+ panic!("expected adapter timeout")
+ };
+ assert_eq!(error.code, ErrorCode::Timeout);
+ assert_eq!(
+ error.disposition,
+ crate::DeliverySemantics::delivered_unverified()
+ );
+ assert!(error.details.unwrap().get("snapshot_id").is_none());
+ assert_eq!(adapter.inner.observed.lock().unwrap().len(), 1);
+}
+
+#[test]
+fn transient_observation_exhaustion_reports_timeout_and_keeps_last_error() {
+ for error in [
+ AdapterError::timeout("Read budget exhausted"),
+ AdapterError::app_unresponsive("Owner").with_details(json!({"retryable": true})),
+ ] {
+ let adapter = SurfaceAbsenceAdapter { error, ..adapter() };
+ let result = observe(&wait_for_ready(true), &menu_source(), &adapter);
+ assert_eq!(result["outcome"], "timed_out");
+ assert_eq!(
+ result["last_observation_error"]["code"],
+ adapter.error.code.as_str()
+ );
+ assert!(result.get("selector_matches").is_none());
+ }
+}
diff --git a/crates/core/src/commands/post_action_observation_tests.rs b/crates/core/src/commands/post_action_observation_tests.rs
new file mode 100644
index 000000000..d24798f8f
--- /dev/null
+++ b/crates/core/src/commands/post_action_observation_tests.rs
@@ -0,0 +1,398 @@
+use super::*;
+use crate::{
+ AccessibilityNode, DeliverySemantics, ErrorCode, ProcessIdentity, WindowInfo,
+ adapter::{ActionOps, InputOps, ObservationOps, SystemOps},
+ locator::live_locator::{ObservationRequest, ObservationRoot, ObservedTree},
+};
+use std::sync::{
+ Mutex,
+ atomic::{AtomicUsize, Ordering},
+};
+
+struct ProbeAdapter {
+ windows: Vec<WindowInfo>,
+ matching_pid: Option<crate::ProcessId>,
+ observed: Mutex<Vec<(crate::ProcessId, crate::SnapshotSurface)>>,
+ process_state: ProcessState,
+ exits_after_observation: bool,
+ incomplete: bool,
+ process_checks: AtomicUsize,
+ inventory_queries: AtomicUsize,
+}
+
+impl ObservationOps for ProbeAdapter {
+ fn is_application_surface(&self, surface: crate::SnapshotSurface) -> bool {
+ surface == crate::SnapshotSurface::Menubar
+ }
+
+ fn query_app_inventory(
+ &self,
+ _query: crate::AppInventoryQuery<'_>,
+ _deadline: Deadline,
+ ) -> Result<crate::AppInventory, AdapterError> {
+ self.inventory_queries.fetch_add(1, Ordering::SeqCst);
+ Err(AdapterError::new(
+ ErrorCode::PermDenied,
+ "Unrelated process denies application inventory",
+ ))
+ }
+
+ fn list_windows(
+ &self,
+ _filter: &crate::WindowFilter,
+ _deadline: Deadline,
+ ) -> Result<Vec<WindowInfo>, AdapterError> {
+ Err(AdapterError::new(
+ ErrorCode::PermDenied,
+ "Global window listing denied",
+ ))
+ }
+
+ fn observe_tree(
+ &self,
+ root: ObservationRoot<'_>,
+ request: &ObservationRequest,
+ ) -> Result<ObservedTree, AdapterError> {
+ let pid = match root {
+ ObservationRoot::Application { app, .. } => {
+ assert!(matches!(
+ request.surface,
+ crate::SnapshotSurface::Menu | crate::SnapshotSurface::Menubar
+ ));
+ assert_eq!(app.pid, crate::ProcessId::new(1));
+ assert_eq!(app.process_instance.as_deref(), Some("test-instance"));
+ app.pid
+ }
+ ObservationRoot::Window(window) => {
+ assert_eq!(window.pid, crate::ProcessId::new(1));
+ assert_eq!(window.process_instance.as_deref(), Some("test-instance"));
+ let supported = if window.is_process_owner() {
+ matches!(
+ request.surface,
+ crate::SnapshotSurface::Window | crate::SnapshotSurface::MenuBarExtras
+ )
+ } else {
+ request.surface == crate::SnapshotSurface::Window
+ };
+ if !supported {
+ return Err(AdapterError::new(
+ ErrorCode::ElementNotFound,
+ "Unsupported observation surface for window owner",
+ ));
+ }
+ window.pid
+ }
+ ObservationRoot::Element { .. } => {
+ return Err(AdapterError::internal("unexpected element root"));
+ }
+ };
+ self.observed.lock().unwrap().push((pid, request.surface));
+ let children = (self.matching_pid == Some(pid))
+ .then(|| AccessibilityNode {
+ ref_id: None,
+ role: "button".into(),
+ identity: crate::NodeIdentity {
+ name: Some("Ready".into()),
+ ..Default::default()
+ },
+ presentation: Default::default(),
+ children_count: None,
+ subtree_truncated: false,
+ children: vec![],
+ })
+ .into_iter()
+ .collect();
+ crate::adapter::observed_tree(
+ &root,
+ AccessibilityNode {
+ ref_id: None,
+ role: "application".into(),
+ identity: Default::default(),
+ presentation: Default::default(),
+ children_count: None,
+ subtree_truncated: self.incomplete,
+ children,
+ },
+ )
+ }
+}
+
+impl ActionOps for ProbeAdapter {}
+impl InputOps for ProbeAdapter {}
+impl SystemOps for ProbeAdapter {
+ fn resolve_window_strict(
+ &self,
+ expected: &WindowInfo,
+ _deadline: Deadline,
+ ) -> Result<WindowInfo, AdapterError> {
+ assert_eq!(expected.id, "source-window");
+ assert_eq!(expected.pid, crate::ProcessId::new(1));
+ assert_eq!(expected.process_instance.as_deref(), Some("test-instance"));
+ let candidate = self
+ .windows
+ .iter()
+ .find(|window| window.id == expected.id && window.pid == expected.pid);
+ if candidate.is_some_and(|window| window.process_instance.is_none()) {
+ return Err(AdapterError::new(
+ ErrorCode::ActionNotSupported,
+ "Incomplete window process identity",
+ ));
+ }
+ candidate
+ .filter(|window| window.process_instance == expected.process_instance)
+ .cloned()
+ .ok_or_else(|| {
+ AdapterError::new(ErrorCode::WindowNotFound, "Original window is absent")
+ })
+ }
+
+ fn process_state(
+ &self,
+ process: ProcessIdentity,
+ _deadline: Deadline,
+ ) -> Result<ProcessState, AdapterError> {
+ assert_eq!(
+ process,
+ ProcessIdentity::new(crate::ProcessId::new(1), "test-instance")
+ );
+ self.process_checks.fetch_add(1, Ordering::SeqCst);
+ if self.exits_after_observation && !self.observed.lock().unwrap().is_empty() {
+ return Ok(ProcessState::Exited { code: None });
+ }
+ Ok(self.process_state)
+ }
+}
+
+fn window(pid: u32, instance: &str) -> WindowInfo {
+ WindowInfo {
+ app: "TargetApp".into(),
+ pid: crate::ProcessId::new(pid),
+ process_instance: Some(instance.into()),
+ id: "source-window".into(),
+ title: "Target window".into(),
+ bounds: None,
+ state: Default::default(),
+ }
+}
+
+fn entry() -> RefEntry {
+ let mut entry = crate::adapter::minimal_ref_entry("button", None);
+ entry.source.source_app = Some("TargetApp".into());
+ entry.source.source_surface = crate::SnapshotSurface::Window;
+ entry.source.source_window_id = Some("source-window".into());
+ entry
+}
+
+fn wait_for_ready(gone: bool) -> WaitSelector {
+ WaitSelector {
+ query_raw: ":Ready".into(),
+ gone,
+ timeout_ms: 250,
+ }
+}
+
+#[test]
+fn selector_observation_uses_the_pinned_process_and_post_action_window_scope() {
+ let adapter = ProbeAdapter {
+ windows: vec![window(1, "test-instance")],
+ matching_pid: Some(crate::ProcessId::new(1)),
+ observed: Mutex::new(Vec::new()),
+ process_state: ProcessState::Running,
+ exits_after_observation: false,
+ incomplete: false,
+ process_checks: AtomicUsize::new(0),
+ inventory_queries: AtomicUsize::new(0),
+ };
+ let result = observe(&wait_for_ready(false), &entry(), &adapter);
+
+ assert_eq!(result["outcome"], "expected_state_observed");
+ assert_eq!(result["selector_matches"], true);
+ assert_eq!(result["surface"], "window");
+ assert_eq!(
+ *adapter.observed.lock().unwrap(),
+ vec![(crate::ProcessId::new(1), crate::SnapshotSurface::Window)]
+ );
+}
+
+#[test]
+fn attaching_observation_preserves_the_original_action_error() {
+ let error = AdapterError::new(ErrorCode::AppUnresponsive, "AXPress timed out")
+ .with_suggestion("Inspect state")
+ .with_platform_detail("kAXErrorCannotComplete")
+ .with_details(json!({ "ax_error": -25204 }))
+ .with_disposition(DeliverySemantics::uncertain());
+ let original = error.clone();
+ let attached = attach(error, json!({ "outcome": "expected_state_observed" }));
+
+ assert_eq!(attached.code, original.code);
+ assert_eq!(attached.message, original.message);
+ assert_eq!(attached.suggestion, original.suggestion);
+ assert_eq!(attached.platform_detail, original.platform_detail);
+ assert_eq!(attached.disposition, original.disposition);
+ let details = attached.details.unwrap();
+ assert_eq!(details["ax_error"], -25204);
+ assert_eq!(
+ details["post_action_observation"]["outcome"],
+ "expected_state_observed"
+ );
+}
+
+fn windowless_adapter() -> ProbeAdapter {
+ ProbeAdapter {
+ windows: vec![],
+ matching_pid: Some(crate::ProcessId::new(1)),
+ observed: Mutex::new(Vec::new()),
+ process_state: ProcessState::Running,
+ exits_after_observation: false,
+ incomplete: false,
+ process_checks: AtomicUsize::new(0),
+ inventory_queries: AtomicUsize::new(0),
+ }
+}
+
+fn menu_entry() -> RefEntry {
+ let mut entry = entry();
+ entry.source.source_surface = crate::SnapshotSurface::Menubar;
+ entry.source.source_window_id = None;
+ entry
+}
+
+fn delivered_wait(adapter: &ProbeAdapter, entry: &RefEntry, gone: bool) -> Result<Value, AppError> {
+ let context = crate::CommandContext::default().with_wait_selector(Some(wait_for_ready(gone)));
+ super::super::apply_post_action_wait(
+ serde_json::to_value(crate::ActionResult::delivered_unverified("click")).unwrap(),
+ Some(entry),
+ adapter,
+ &context,
+ )
+}
+
+#[test]
+fn windowless_menubar_waits_read_application_for_presence_and_absence() {
+ let _home = crate::refs::refs_test_support::HomeGuard::new();
+ for gone in [false, true] {
+ let mut adapter = windowless_adapter();
+ adapter.matching_pid = (!gone).then_some(crate::ProcessId::new(1));
+ let mut entry = menu_entry();
+ entry.source.source_app = Some("Saved label".into());
+ let reconciled = observe(&wait_for_ready(gone), &entry, &adapter);
+ assert_eq!(reconciled["outcome"], "expected_state_observed");
+ assert_eq!(reconciled["surface"], "menubar");
+ assert_eq!(reconciled["selector_matches"], !gone);
+ let result = delivered_wait(&adapter, &entry, gone).unwrap();
+ if gone {
+ assert_eq!(result["target_absent"], true);
+ } else {
+ assert_eq!(result["app"], "Saved label");
+ }
+ assert_eq!(adapter.inventory_queries.load(Ordering::SeqCst), 0);
+ assert!(
+ adapter
+ .observed
+ .lock()
+ .unwrap()
+ .iter()
+ .all(|(pid, surface)| *pid == crate::ProcessId::new(1)
+ && *surface == crate::SnapshotSurface::Menubar)
+ );
+ }
+}
+
+#[test]
+fn original_window_is_required_even_when_same_process_has_another_window() {
+ let mut adapter = windowless_adapter();
+ let mut other = window(1, "test-instance");
+ other.id = "other-window".into();
+ adapter.windows = vec![other];
+ assert_eq!(
+ delivered_wait(&adapter, &entry(), true).unwrap()["target_absent"],
+ true
+ );
+ assert_eq!(
+ delivered_wait(&adapter, &entry(), false)
+ .unwrap_err()
+ .code(),
+ "TIMEOUT"
+ );
+ let result = observe(&wait_for_ready(true), &entry(), &adapter);
+ assert_eq!(result["outcome"], "expected_state_observed");
+ assert_eq!(result["selector_matches"], false);
+ assert!(adapter.observed.lock().unwrap().is_empty());
+}
+
+#[test]
+fn present_menu_times_out_gone_wait_with_source_surface_diagnostic() {
+ let _home = crate::refs::refs_test_support::HomeGuard::new();
+ let adapter = windowless_adapter();
+ let error = delivered_wait(&adapter, &menu_entry(), true).unwrap_err();
+ let AppError::Adapter(error) = error else {
+ panic!("expected adapter timeout")
+ };
+ assert_eq!(error.code, ErrorCode::Timeout);
+ assert_eq!(
+ error.disposition,
+ crate::DeliverySemantics::delivered_unverified()
+ );
+ let details = error.details.unwrap();
+ let snapshot_id = details["snapshot_id"].as_str().unwrap();
+ let refmap = crate::refs::refs_store::RefStore::new()
+ .unwrap()
+ .load_snapshot(snapshot_id)
+ .unwrap();
+ let saved = refmap.get("@e1").unwrap();
+ assert_eq!(saved.source.source_surface, crate::SnapshotSurface::Menubar);
+ assert!(saved.source.source_window_id.is_none());
+ assert_eq!(
+ saved.process.process_instance.as_deref(),
+ Some("test-instance")
+ );
+ assert!(
+ adapter
+ .observed
+ .lock()
+ .unwrap()
+ .iter()
+ .all(|(_, surface)| *surface == crate::SnapshotSurface::Menubar)
+ );
+}
+
+#[path = "post_action_observation_lifecycle_tests.rs"]
+mod lifecycle_tests;
+
+#[path = "post_action_observation_surface_tests.rs"]
+mod surface_tests;
+
+#[test]
+fn sheet_ref_waits_observe_window_presence_and_confirm_absence() {
+ let _home = crate::refs::refs_test_support::HomeGuard::new();
+ let mut source = entry();
+ source.source.source_surface = crate::SnapshotSurface::Sheet;
+ let mut adapter = windowless_adapter();
+ adapter.windows = vec![window(1, "test-instance")];
+ assert!(
+ delivered_wait(&adapter, &source, false)
+ .unwrap()
+ .get("snapshot_id")
+ .is_some()
+ );
+ assert_eq!(
+ delivered_wait(&adapter, &source, true).unwrap_err().code(),
+ "TIMEOUT"
+ );
+ adapter.matching_pid = None;
+ assert_eq!(
+ delivered_wait(&adapter, &source, true).unwrap()["target_absent"],
+ true
+ );
+ let result = observe(&wait_for_ready(true), &source, &adapter);
+ assert_eq!(result["outcome"], "expected_state_observed");
+ assert_eq!(result["surface"], "window");
+ assert!(
+ adapter
+ .observed
+ .lock()
+ .unwrap()
+ .iter()
+ .all(|(_, surface)| *surface == crate::SnapshotSurface::Window)
+ );
+}
diff --git a/crates/core/src/commands/selector_observation.rs b/crates/core/src/commands/selector_observation.rs
new file mode 100644
index 000000000..2f717706c
--- /dev/null
+++ b/crates/core/src/commands/selector_observation.rs
@@ -0,0 +1,76 @@
+use crate::{
+ AppError, Deadline, LocatorQuery, PlatformAdapter, RefEntry, SnapshotOwner, SnapshotSurface,
+ locator::live_locator::{
+ LocatorMaterialization, LocatorResolveRequest, LocatorSelection, resolve_query,
+ },
+ snapshot::{ref_owner_observation::RefOwnerObservation, surface_target, window_capture},
+ system::process_state::ProcessState,
+};
+
+pub(crate) enum SelectorObservation {
+ Selector { matches: bool, complete: bool },
+ OwnerUnavailable(ProcessState),
+}
+
+impl SelectorObservation {
+ pub(crate) fn observe_ref(
+ adapter: &dyn PlatformAdapter,
+ entry: &RefEntry,
+ query: &LocatorQuery,
+ deadline: Deadline,
+ ) -> Result<Self, AppError> {
+ match surface_target::resolve_ref_owner(adapter, entry, deadline)? {
+ RefOwnerObservation::Present(owner) => Self::observe_owners(
+ adapter,
+ vec![owner],
+ surface_target::ref_observation_surface(adapter, entry),
+ query,
+ deadline,
+ ),
+ RefOwnerObservation::Absent(None) => Ok(Self::Selector {
+ matches: false,
+ complete: true,
+ }),
+ RefOwnerObservation::Absent(Some(state)) | RefOwnerObservation::Unavailable(state) => {
+ Ok(Self::OwnerUnavailable(state))
+ }
+ }
+ }
+
+ pub(crate) fn observe_owners(
+ adapter: &dyn PlatformAdapter,
+ owners: Vec<SnapshotOwner>,
+ surface: SnapshotSurface,
+ query: &LocatorQuery,
+ deadline: Deadline,
+ ) -> Result<Self, AppError> {
+ if owners.is_empty() {
+ return Ok(Self::Selector {
+ matches: false,
+ complete: true,
+ });
+ }
+ let request = LocatorResolveRequest {
+ selection: LocatorSelection::First,
+ deadline,
+ max_raw_depth: 50,
+ surface: (surface != SnapshotSurface::Window).then_some(surface),
+ materialization: LocatorMaterialization::None,
+ };
+ match window_capture::first_surface_owner(owners, |owner| {
+ resolve_query(adapter, query, owner.observation_root(surface), &request)
+ }) {
+ Ok((_, resolution)) => Ok(Self::Selector {
+ matches: resolution.meta.total_matches > 0,
+ complete: resolution.meta.selection_complete,
+ }),
+ Err(error) if surface_target::is_confirmed_surface_absence(&error, surface) => {
+ Ok(Self::Selector {
+ matches: false,
+ complete: true,
+ })
+ }
+ Err(error) => Err(error),
+ }
+ }
+}
diff --git a/crates/core/src/commands/snapshot.rs b/crates/core/src/commands/snapshot.rs
index 0599006ad..abef9e964 100644
--- a/crates/core/src/commands/snapshot.rs
+++ b/crates/core/src/commands/snapshot.rs
@@ -129,19 +129,18 @@ pub(crate) fn format_snapshot_fields(
) -> Result<Value, AppError> {
let ref_count = result.refmap.len();
let tree = serde_json::to_value(&result.tree)?;
- let win = &result.window;
tracing::debug!(refs = ref_count, "tree: snapshot complete");
let mut body = json!({
- "app": win.app,
+ "app": result.owner.app_name(),
"ref_count": ref_count,
"snapshot_id": result.snapshot_id,
"complete": result.complete,
"tree": tree
});
- if !win.is_process_owner() {
- body["window"] = json!({ "id": win.id, "title": win.title });
+ if let Some(window) = result.owner.window() {
+ body["window"] = json!({ "id": window.id, "title": window.title });
}
if !result.complete {
body["truncated"] = json!(true);
diff --git a/crates/core/src/commands/snapshot_log_tests.rs b/crates/core/src/commands/snapshot_log_tests.rs
index fa2466498..d6e2ba6e2 100644
--- a/crates/core/src/commands/snapshot_log_tests.rs
+++ b/crates/core/src/commands/snapshot_log_tests.rs
@@ -54,8 +54,11 @@ fn snapshot_completion_log_omits_private_app_and_window_names() {
crate::Deadline::standard().unwrap(),
)
.unwrap();
- result.window.app = "PrivateApp-7391".into();
- result.window.title = "PrivateWindow-1842".into();
+ let crate::SnapshotOwner::Window(window) = &mut result.owner else {
+ panic!("expected a window snapshot");
+ };
+ window.app = "PrivateApp-7391".into();
+ window.title = "PrivateWindow-1842".into();
let events = Arc::new(Mutex::new(Vec::new()));
let subscriber = LogCapture(events.clone());
diff --git a/crates/core/src/commands/snapshot_tests.rs b/crates/core/src/commands/snapshot_tests.rs
index 7d15cf267..3b237a083 100644
--- a/crates/core/src/commands/snapshot_tests.rs
+++ b/crates/core/src/commands/snapshot_tests.rs
@@ -359,7 +359,7 @@ fn an_unproven_capture_is_flagged_in_the_payload() {
let mut result = crate::snapshot::SnapshotResult {
tree: crate::adapter::minimal_accessibility_node("window", "Fixture"),
refmap: crate::RefMap::new(),
- window: WindowInfo {
+ owner: crate::SnapshotOwner::Window(WindowInfo {
id: "w-1".into(),
title: "Fixture".into(),
app: "Fixture".into(),
@@ -367,7 +367,7 @@ fn an_unproven_capture_is_flagged_in_the_payload() {
process_instance: None,
bounds: None,
state: crate::WindowState::default(),
- },
+ }),
snapshot_id: None,
complete: true,
nodes_observed: 1,
@@ -376,7 +376,10 @@ fn an_unproven_capture_is_flagged_in_the_payload() {
let proven = format_snapshot_fields(&result, None, None).unwrap();
assert!(proven.get("identity_unproven").is_none());
assert_eq!(proven["window"]["id"], "w-1");
- result.window.id.clear();
+ let crate::SnapshotOwner::Window(window) = &mut result.owner else {
+ panic!("expected a window owner");
+ };
+ window.id.clear();
assert!(
format_snapshot_fields(&result, None, None)
.unwrap()
diff --git a/crates/core/src/commands/type_text_interval_wait_tests.rs b/crates/core/src/commands/type_text_interval_wait_tests.rs
index a2434b88c..d635af9bf 100644
--- a/crates/core/src/commands/type_text_interval_wait_tests.rs
+++ b/crates/core/src/commands/type_text_interval_wait_tests.rs
@@ -119,6 +119,17 @@ impl ActionOps for TitledField {
impl InputOps for TitledField {}
impl SystemOps for TitledField {
+ fn resolve_window_strict(
+ &self,
+ expected: &WindowInfo,
+ _deadline: crate::Deadline,
+ ) -> Result<WindowInfo, AdapterError> {
+ assert_eq!(expected.id, "w-1");
+ assert_eq!(expected.pid, crate::ProcessId::new(1));
+ assert_eq!(expected.process_instance.as_deref(), Some("test-instance"));
+ Ok(expected.clone())
+ }
+
crate::adapter::guarded_interaction_lease!();
}
@@ -127,8 +138,15 @@ impl SystemOps for TitledField {
#[test]
fn a_wait_for_runs_once_after_the_last_keystroke() {
let _guard = HomeGuard::new();
- let snapshot_id =
- crate::commands::helpers::test_support::save_one_ref_snapshot("textfield", "SetValue");
+ let mut entry = crate::adapter::minimal_ref_entry("textfield", Some("Target"));
+ entry.source.source_window_id = Some("w-1".into());
+ entry.capabilities.available_actions = vec!["SetValue".into()];
+ let mut refmap = crate::RefMap::new();
+ refmap.allocate(entry);
+ let snapshot_id = crate::RefStore::new()
+ .unwrap()
+ .save_new_snapshot(&refmap)
+ .unwrap();
let adapter = TitledField::default();
let context = CommandContext::default().with_wait_selector(Some(WaitSelector {
query_raw: ":abc".into(),
diff --git a/crates/core/src/commands/wait_selector.rs b/crates/core/src/commands/wait_selector.rs
index 0e2e4d298..c318921f5 100644
--- a/crates/core/src/commands/wait_selector.rs
+++ b/crates/core/src/commands/wait_selector.rs
@@ -1,14 +1,12 @@
use crate::{
AppError, ErrorCode,
adapter::{PlatformAdapter, TreeOptions},
+ commands::selector_observation::SelectorObservation,
commands::{query, snapshot as snapshot_cmd, wait_timeout},
context::CommandContext,
- locator::live_locator::{
- LocatorMaterialization, LocatorResolveRequest, LocatorSelection, ObservationRoot,
- resolve_query,
- },
refs::refs_store::RefStore,
snapshot::{self, emit_snapshot_saved},
+ system::process_state::ProcessState,
trace::trace_artifacts,
};
use serde_json::{Value, json};
@@ -29,126 +27,160 @@ pub fn execute(
input: WaitSelectorInput,
adapter: &dyn PlatformAdapter,
context: &CommandContext,
+) -> Result<Value, AppError> {
+ execute_with_ref(input, None, adapter, context)
+}
+
+pub(crate) fn execute_with_ref(
+ mut input: WaitSelectorInput,
+ entry: Option<&crate::RefEntry>,
+ adapter: &dyn PlatformAdapter,
+ context: &CommandContext,
) -> Result<Value, AppError> {
let query = query::validate_selector(&input.query_raw)?;
+ if let Some(entry) = entry {
+ input.opts.surface = snapshot::surface_target::ref_observation_surface(adapter, entry);
+ }
let start = Instant::now();
let deadline = crate::Deadline::at(start, input.timeout_ms)?;
- let mut scheduler = super::wait_scheduler::WaitScheduler::new(
+ let mut last_error = None;
+ let mut last_built = None;
+ let result = poll_selector(
adapter,
- &crate::SignalFilter {
+ crate::SignalFilter {
app: input.app.clone(),
- process: None,
+ process: entry.and_then(|entry| entry.process.identity()),
},
deadline,
- );
- let mut last_error = None;
- let mut last_built = None;
-
- loop {
- match observe_selector(adapter, &input, &query, deadline) {
- Ok(Some(true)) if input.gone => {}
- Ok(Some(true)) => match build_materialization(adapter, &input, &query, deadline) {
- Ok((true, result)) => {
- return materialized_response(
- result,
- context,
- &input,
- start.elapsed().as_millis(),
- );
+ |poll_deadline| {
+ let completion = match observe_selector(adapter, &input, entry, &query, poll_deadline) {
+ Ok(Some(true)) if input.gone => None,
+ Ok(Some(true)) => {
+ match build_materialization(adapter, &input, entry, &query, poll_deadline) {
+ Ok((true, result)) => {
+ Some(Ok(SelectorCompletion::Matched(Box::new(result))))
+ }
+ Ok((false, result)) => {
+ last_built = Some(result);
+ None
+ }
+ Err(err)
+ if err.code() == ErrorCode::Timeout.as_str()
+ || is_transient_poll_error(&err, input.window_id.as_deref())
+ || is_target_gone_error(&err)
+ || snapshot::surface_target::is_confirmed_surface_absence(
+ &err,
+ input.opts.surface,
+ ) =>
+ {
+ last_error = Some(poll_error_json(&err));
+ None
+ }
+ Err(err) => Some(Err(err)),
+ }
}
- Ok((false, result)) => last_built = Some(result),
- Err(err) if err.code() == ErrorCode::Timeout.as_str() && deadline.is_expired() => {
- return timeout_response(
- adapter,
- &input,
- context,
- last_built,
- Some(poll_error_json(&err)),
- );
+ Ok(Some(false)) if input.gone => Some(Ok(SelectorCompletion::Absent)),
+ Ok(Some(false)) => None,
+ Ok(None) => {
+ last_error = Some(json!({ "kind": "locator_incomplete" }));
+ None
+ }
+ Err(err) if is_target_gone_error(&err) && input.gone && entry.is_none() => {
+ Some(Ok(SelectorCompletion::Absent))
+ }
+ Err(err)
+ if err.code() == ErrorCode::Timeout.as_str() && poll_deadline.is_expired() =>
+ {
+ return Ok(None);
}
Err(err)
if err.code() == ErrorCode::Timeout.as_str()
- || is_transient_poll_error(&err)
+ || is_transient_poll_error(&err, input.window_id.as_deref())
|| is_target_gone_error(&err) =>
{
last_error = Some(poll_error_json(&err));
+ None
}
- Err(err) => return Err(err),
- },
- Ok(Some(false)) if input.gone => {
- return Ok(target_absent_response(
- &input.query_raw,
- start.elapsed().as_millis(),
- ));
+ Err(err) => Some(Err(err)),
+ };
+ if let Some(completion) = completion {
+ return completion.map(Some);
}
- Ok(Some(false)) => {}
- Ok(None) => {
- last_error = Some(json!({ "kind": "locator_incomplete" }));
- }
- Err(err) if is_target_gone_error(&err) => {
- if input.gone {
- return Ok(target_absent_response(
- &input.query_raw,
- start.elapsed().as_millis(),
- ));
+
+ let remaining = deadline.remaining();
+ if !remaining.is_zero()
+ && remaining <= super::wait_scheduler::POLL_INTERVAL
+ && last_built.is_none()
+ {
+ match build_snapshot(adapter, &input, entry, poll_deadline) {
+ Ok(result) => last_built = Some(result),
+ Err(error) => last_error = Some(poll_error_json(&error)),
}
- last_error = Some(poll_error_json(&err));
- }
- Err(err) if err.code() == ErrorCode::Timeout.as_str() && deadline.is_expired() => {
- return timeout_response(adapter, &input, context, last_built, last_error);
- }
- Err(err) if err.code() == ErrorCode::Timeout.as_str() => {
- last_error = Some(poll_error_json(&err));
- }
- Err(err) if is_transient_poll_error(&err) => {
- last_error = Some(poll_error_json(&err));
}
- Err(err) => return Err(err),
+ Ok(None)
+ },
+ );
+ match result {
+ Ok(Some(SelectorCompletion::Matched(result))) => {
+ materialized_response(*result, context, &input, start.elapsed().as_millis())
}
-
- let mut remaining = deadline.remaining();
- if !remaining.is_zero()
- && remaining <= super::wait_scheduler::POLL_INTERVAL
- && last_built.is_none()
- {
- match snapshot::build(
+ Ok(Some(SelectorCompletion::Absent)) => Ok(target_absent_response(
+ &input.query_raw,
+ start.elapsed().as_millis(),
+ )),
+ Ok(None) => timeout_response(adapter, &input, entry, context, (last_built, last_error)),
+ Err(err) if err.code() == ErrorCode::Timeout.as_str() && deadline.is_expired() => {
+ timeout_response(
adapter,
- &input.opts,
- input.app.as_deref(),
- input.window_id.as_deref(),
- deadline,
- ) {
- Ok(result) => last_built = Some(result),
- Err(error) => last_error = Some(poll_error_json(&error)),
- }
- remaining = deadline.remaining();
- }
- if remaining.is_zero() {
- return timeout_response(adapter, &input, context, last_built, last_error);
+ &input,
+ entry,
+ context,
+ (last_built, Some(poll_error_json(&err))),
+ )
}
+ Err(err) => Err(err),
+ }
+}
+
+enum SelectorCompletion {
+ Matched(Box<snapshot::SnapshotResult>),
+ Absent,
+}
+pub(crate) fn poll_selector<T>(
+ adapter: &dyn PlatformAdapter,
+ filter: crate::SignalFilter,
+ deadline: crate::Deadline,
+ mut observe: impl FnMut(crate::Deadline) -> Result<Option<T>, AppError>,
+) -> Result<Option<T>, AppError> {
+ let mut scheduler = super::wait_scheduler::WaitScheduler::new(adapter, &filter, deadline);
+ loop {
+ if let Some(result) = observe(deadline)? {
+ return Ok(Some(result));
+ }
+ if deadline.is_expired() {
+ return Ok(None);
+ }
scheduler.wait(deadline);
+ if deadline.is_expired() {
+ return Ok(None);
+ }
}
}
fn timeout_response(
adapter: &dyn PlatformAdapter,
input: &WaitSelectorInput,
+ entry: Option<&crate::RefEntry>,
context: &CommandContext,
- mut last_built: Option<snapshot::SnapshotResult>,
- mut last_error: Option<Value>,
+ previous: (Option<snapshot::SnapshotResult>, Option<Value>),
) -> Result<Value, AppError> {
+ let (mut last_built, mut last_error) = previous;
if last_built.is_none() {
let diagnostic_deadline =
crate::Deadline::detached_after(DIAGNOSTIC_SNAPSHOT_BUDGET.as_millis() as u64)?;
- match snapshot::build(
- adapter,
- &input.opts,
- input.app.as_deref(),
- input.window_id.as_deref(),
- diagnostic_deadline,
- ) {
+ match build_snapshot(adapter, input, entry, diagnostic_deadline) {
Ok(result) => last_built = Some(result),
Err(error) if last_error.is_none() => last_error = Some(poll_error_json(&error)),
Err(_) => {}
@@ -180,50 +212,83 @@ fn persist_last_built(
fn observe_selector(
adapter: &dyn PlatformAdapter,
input: &WaitSelectorInput,
+ entry: Option<&crate::RefEntry>,
query: &crate::LocatorQuery,
deadline: crate::Deadline,
) -> Result<Option<bool>, AppError> {
- let window = snapshot::resolve_window_for_surface(
- adapter,
- input.app.as_deref(),
- input.window_id.as_deref(),
- input.opts.surface,
- deadline,
- )?;
- let resolution = resolve_query(
- adapter,
- query,
- ObservationRoot::Window(&window),
- &LocatorResolveRequest {
- selection: LocatorSelection::First,
+ let observation = if let Some(entry) = entry {
+ SelectorObservation::observe_ref(adapter, entry, query, deadline)?
+ } else {
+ SelectorObservation::observe_owners(
+ adapter,
+ resolve_owners(adapter, input, None, deadline)?,
+ input.opts.surface,
+ query,
deadline,
- max_raw_depth: 50,
- surface: (input.opts.surface != crate::SnapshotSurface::Window)
- .then_some(input.opts.surface),
- materialization: LocatorMaterialization::None,
- },
- )?;
- if !resolution.meta.selection_complete {
- return Ok(None);
+ )?
+ };
+ match observation {
+ SelectorObservation::Selector { matches, complete } => Ok(complete.then_some(matches)),
+ SelectorObservation::OwnerUnavailable(
+ ProcessState::Exited { .. } | ProcessState::Crashed { .. },
+ ) => Ok(Some(false)),
+ SelectorObservation::OwnerUnavailable(state) => Err(owner_unavailable(state)),
}
- Ok(Some(resolution.meta.total_matches > 0))
}
fn build_materialization(
adapter: &dyn PlatformAdapter,
input: &WaitSelectorInput,
+ entry: Option<&crate::RefEntry>,
query: &crate::LocatorQuery,
deadline: crate::Deadline,
) -> Result<(bool, snapshot::SnapshotResult), AppError> {
- let result = snapshot::build(
+ let result = build_snapshot(adapter, input, entry, deadline)?;
+ let matched = query::tree_has_match(&result.tree, query);
+ Ok((matched, result))
+}
+
+fn resolve_owners(
+ adapter: &dyn PlatformAdapter,
+ input: &WaitSelectorInput,
+ entry: Option<&crate::RefEntry>,
+ deadline: crate::Deadline,
+) -> Result<Vec<crate::SnapshotOwner>, AppError> {
+ if let Some(entry) = entry {
+ use snapshot::ref_owner_observation::RefOwnerObservation;
+ return match snapshot::surface_target::resolve_ref_owner(adapter, entry, deadline)? {
+ RefOwnerObservation::Present(owner) => Ok(vec![owner]),
+ RefOwnerObservation::Absent(_) => Ok(Vec::new()),
+ RefOwnerObservation::Unavailable(state) => Err(owner_unavailable(state)),
+ };
+ }
+ snapshot::surface_target::resolve_owners(
adapter,
- &input.opts,
input.app.as_deref(),
input.window_id.as_deref(),
+ input.opts.surface,
deadline,
- )?;
- let matched = query::tree_has_match(&result.tree, query);
- Ok((matched, result))
+ )
+}
+
+fn owner_unavailable(state: ProcessState) -> AppError {
+ crate::AdapterError::app_unresponsive("Ref owner")
+ .with_details(json!({
+ "kind": "ref_owner_unavailable",
+ "retryable": true,
+ "process_state": state.label(),
+ }))
+ .into()
+}
+
+fn build_snapshot(
+ adapter: &dyn PlatformAdapter,
+ input: &WaitSelectorInput,
+ entry: Option<&crate::RefEntry>,
+ deadline: crate::Deadline,
+) -> Result<snapshot::SnapshotResult, AppError> {
+ let owners = resolve_owners(adapter, input, entry, deadline)?;
+ snapshot::build_for_owners(adapter, &input.opts, owners, deadline)
}
fn materialized_response(
@@ -261,8 +326,16 @@ fn is_target_gone_error(err: &AppError) -> bool {
)
}
-fn is_transient_poll_error(err: &AppError) -> bool {
- matches!(err, AppError::Adapter(error) if error.is_explicitly_retryable())
+pub(crate) fn is_transient_poll_error(err: &AppError, window_id: Option<&str>) -> bool {
+ let AppError::Adapter(error) = err else {
+ return false;
+ };
+ error.is_explicitly_retryable()
+ || (error.code == ErrorCode::ActionNotSupported
+ && error.details.as_ref().is_some_and(|details| {
+ details["kind"] == "window_without_accessibility_element"
+ && window_id.is_none_or(|id| details["window_id"].as_str() == Some(id))
+ }))
}
#[cfg(test)]
diff --git a/crates/core/src/commands/wait_selector_ref_owner_tests.rs b/crates/core/src/commands/wait_selector_ref_owner_tests.rs
new file mode 100644
index 000000000..c63584765
--- /dev/null
+++ b/crates/core/src/commands/wait_selector_ref_owner_tests.rs
@@ -0,0 +1,88 @@
+use super::*;
+
+struct StrictDiagnosticAdapter;
+
+impl ObservationOps for StrictDiagnosticAdapter {}
+impl ActionOps for StrictDiagnosticAdapter {}
+impl InputOps for StrictDiagnosticAdapter {}
+impl SystemOps for StrictDiagnosticAdapter {
+ fn resolve_window_strict(
+ &self,
+ expected: &WindowInfo,
+ _deadline: crate::Deadline,
+ ) -> Result<WindowInfo, AdapterError> {
+ if expected.id == "w-1"
+ && expected.pid == crate::ProcessId::new(1)
+ && expected.process_instance.as_deref() == Some("test-instance")
+ {
+ Ok(expected.clone())
+ } else {
+ Err(AdapterError::new(
+ ErrorCode::WindowNotFound,
+ "Original window is absent",
+ ))
+ }
+ }
+}
+
+#[test]
+fn ref_wait_timeout_diagnostics_reject_other_windows_and_process_generations() {
+ let _home = HomeGuard::new();
+ let adapter = StrictDiagnosticAdapter;
+ for (window_id, generation) in [("other-window", "test-instance"), ("w-1", "old-instance")] {
+ let mut entry = crate::adapter::minimal_ref_entry("button", None);
+ entry.source.source_window_id = Some(window_id.into());
+ entry.process.process_instance = Some(generation.into());
+ let error = timeout_response(
+ &adapter,
+ &base_input("button:saved", false),
+ Some(&entry),
+ &CommandContext::default(),
+ (None, None),
+ )
+ .unwrap_err();
+ let AppError::Adapter(error) = error else {
+ panic!("expected adapter error")
+ };
+ assert_eq!(error.code, ErrorCode::Timeout);
+ let details = error.details.unwrap();
+ assert!(details.get("snapshot_id").is_none());
+ assert_eq!(details["last_error"]["code"], "WINDOW_NOT_FOUND");
+ }
+}
+
+#[test]
+fn unsupported_strict_resolution_does_not_fall_back_to_window_listing() {
+ let _home = HomeGuard::new();
+ let mut entry = crate::adapter::minimal_ref_entry("button", None);
+ entry.source.source_window_id = Some("w-1".into());
+ let error = execute_with_ref(
+ WaitSelectorInput {
+ timeout_ms: 30,
+ ..base_input("button:Close", true)
+ },
+ Some(&entry),
+ &CodeErrorAdapter {
+ code: ErrorCode::WindowNotFound,
+ },
+ &CommandContext::default(),
+ )
+ .unwrap_err();
+ assert_eq!(error.code(), "PLATFORM_NOT_SUPPORTED");
+ assert!(error.to_string().contains("resolve_window_strict"));
+}
+
+#[test]
+fn confirmed_window_absence_survives_default_process_state_capability() {
+ let _home = HomeGuard::new();
+ let mut entry = crate::adapter::minimal_ref_entry("button", None);
+ entry.source.source_window_id = Some("closed-window".into());
+ let result = execute_with_ref(
+ base_input("button:Close", true),
+ Some(&entry),
+ &StrictDiagnosticAdapter,
+ &CommandContext::default(),
+ )
+ .unwrap();
+ assert_eq!(result["target_absent"], true);
+}
diff --git a/crates/core/src/commands/wait_selector_retry_tests.rs b/crates/core/src/commands/wait_selector_retry_tests.rs
index ee42fe825..980e85447 100644
--- a/crates/core/src/commands/wait_selector_retry_tests.rs
+++ b/crates/core/src/commands/wait_selector_retry_tests.rs
@@ -227,3 +227,76 @@ fn materialization_miss_retains_its_fresh_snapshot_for_timeout() {
Some("newest")
);
}
+
+struct DisappearingWindowAdapter {
+ inventories: AtomicUsize,
+ unavailable_kind: &'static str,
+ disappears: bool,
+}
+
+impl ObservationOps for DisappearingWindowAdapter {
+ fn list_windows(
+ &self,
+ filter: &WindowFilter,
+ deadline: crate::Deadline,
+ ) -> Result<Vec<WindowInfo>, AdapterError> {
+ if self.inventories.fetch_add(1, Ordering::SeqCst) > 0 && self.disappears {
+ return Ok(Vec::new());
+ }
+ StaticTreeAdapter {
+ tree: window_node(Vec::new()),
+ }
+ .list_windows(filter, deadline)
+ }
+
+ fn observe_tree(
+ &self,
+ _root: crate::ObservationRoot<'_>,
+ _request: &crate::ObservationRequest,
+ ) -> Result<crate::ObservedTree, AdapterError> {
+ Err(AdapterError::new(
+ ErrorCode::ActionNotSupported,
+ "Window has no accessibility element",
+ )
+ .with_details(json!({ "kind": self.unavailable_kind, "window_id": "w-1" })))
+ }
+}
+
+impl ActionOps for DisappearingWindowAdapter {}
+impl InputOps for DisappearingWindowAdapter {}
+impl SystemOps for DisappearingWindowAdapter {}
+
+#[test]
+fn gone_wait_requires_window_absence_after_accessibility_disappears() {
+ let _guard = HomeGuard::new();
+ for (kind, disappears, expected) in [
+ ("window_without_accessibility_element", true, None),
+ (
+ "window_without_accessibility_element",
+ false,
+ Some("TIMEOUT"),
+ ),
+ ("unsupported_surface", true, Some("ACTION_NOT_SUPPORTED")),
+ ] {
+ let adapter = DisappearingWindowAdapter {
+ inventories: AtomicUsize::new(0),
+ unavailable_kind: kind,
+ disappears,
+ };
+ let result = execute(
+ WaitSelectorInput {
+ window_id: Some("w-1".into()),
+ timeout_ms: 250,
+ ..base_input("button:Close", true)
+ },
+ &adapter,
+ &CommandContext::default(),
+ );
+ if let Some(code) = expected {
+ assert_eq!(result.unwrap_err().code(), code);
+ } else {
+ assert_eq!(result.unwrap()["target_absent"], true);
+ assert!(adapter.inventories.load(Ordering::SeqCst) >= 2);
+ }
+ }
+}
diff --git a/crates/core/src/commands/wait_selector_tests.rs b/crates/core/src/commands/wait_selector_tests.rs
index ee50337d6..bd8f98721 100644
--- a/crates/core/src/commands/wait_selector_tests.rs
+++ b/crates/core/src/commands/wait_selector_tests.rs
@@ -377,3 +377,6 @@ fn gone_true_with_window_not_found_returns_immediately() {
#[path = "wait_selector_retry_tests.rs"]
mod retry_tests;
+
+#[path = "wait_selector_ref_owner_tests.rs"]
+mod ref_owner_tests;
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
index bdfecfb29..c88d0e79b 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -26,6 +26,7 @@ pub use actions::action_result::ActionResult;
pub use actions::action_step::ActionStep;
pub use actions::action_step_outcome::ActionStepOutcome;
pub use actions::delivery_semantics::DeliverySemantics;
+pub use actions::headed_focus::saved_ref_focus_window;
pub use actions::headed_requirement::HeadedRequirement;
pub use actions::interaction_policy::InteractionPolicy;
pub use actions::post_action::execute_verified_action;
@@ -111,6 +112,7 @@ pub use session::interaction_lease::{
};
pub use session::process_lease_guard::ProcessLeaseGuard;
pub use session::session_affinity::SessionAffinity;
+pub use snapshot::snapshot_owner::SnapshotOwner;
pub use snapshot::snapshot_surface::SnapshotSurface;
pub use storage::file_lock::FileLock;
pub use storage::private_file_ops::{
diff --git a/crates/core/src/locator/live_locator/materialize.rs b/crates/core/src/locator/live_locator/materialize.rs
index d15d6c6b8..af7501e92 100644
--- a/crates/core/src/locator/live_locator/materialize.rs
+++ b/crates/core/src/locator/live_locator/materialize.rs
@@ -147,6 +147,13 @@ pub(crate) fn ref_entry(
fn apply_source(entry: &mut RefEntry, source: &ObservationSource, node_path: &RefPath) {
match source {
+ ObservationSource::Application { app, surface } => {
+ entry.process.pid = app.pid;
+ entry.process.process_instance = app.process_instance.clone();
+ entry.source.source_app = Some(app.name.clone());
+ entry.source.source_window_title = Some(String::new());
+ entry.source.source_surface = *surface;
+ }
ObservationSource::Window {
window,
surface,
@@ -155,7 +162,11 @@ fn apply_source(entry: &mut RefEntry, source: &ObservationSource, node_path: &Re
entry.process.pid = window.pid;
entry.source.source_app = Some(window.app.clone());
entry.source.source_window_id = (!window.is_process_owner()).then(|| window.id.clone());
- entry.source.source_window_title = Some(window.title.clone());
+ entry.source.source_window_title = Some(if window.is_process_owner() {
+ String::new()
+ } else {
+ window.title.clone()
+ });
entry.source.source_window_bounds_hash =
window.bounds.as_ref().and_then(crate::Rect::bounds_hash);
entry.source.source_surface = *surface;
diff --git a/crates/core/src/locator/live_locator/observation_root.rs b/crates/core/src/locator/live_locator/observation_root.rs
index 2ac329116..b3a0ce9bf 100644
--- a/crates/core/src/locator/live_locator/observation_root.rs
+++ b/crates/core/src/locator/live_locator/observation_root.rs
@@ -1,7 +1,11 @@
-use crate::{WindowInfo, adapter::native_handle::NativeHandle, refs::RefEntry};
+use crate::{AppInfo, WindowInfo, adapter::native_handle::NativeHandle, refs::RefEntry};
#[derive(Clone, Copy)]
pub enum ObservationRoot<'a> {
+ Application {
+ app: &'a AppInfo,
+ surface: crate::SnapshotSurface,
+ },
Window(&'a WindowInfo),
Element {
handle: &'a NativeHandle,
@@ -13,6 +17,7 @@ pub enum ObservationRoot<'a> {
impl ObservationRoot<'_> {
pub fn surface(self) -> crate::SnapshotSurface {
match self {
+ Self::Application { surface, .. } => surface,
Self::Window(_) => crate::SnapshotSurface::Window,
Self::Element { entry, .. } => entry.source.source_surface,
}
diff --git a/crates/core/src/locator/live_locator/observation_source.rs b/crates/core/src/locator/live_locator/observation_source.rs
index a4ad8fcda..f31a72060 100644
--- a/crates/core/src/locator/live_locator/observation_source.rs
+++ b/crates/core/src/locator/live_locator/observation_source.rs
@@ -1,9 +1,13 @@
-use crate::{WindowInfo, refs::RefEntry};
+use crate::{AppInfo, WindowInfo, refs::RefEntry};
use super::ObservationRoot;
#[derive(Debug, Clone)]
pub enum ObservationSource {
+ Application {
+ app: AppInfo,
+ surface: crate::SnapshotSurface,
+ },
Window {
window: WindowInfo,
/// The surface actually walked. A ref that was found on the menu bar
@@ -23,6 +27,10 @@ pub enum ObservationSource {
impl ObservationSource {
pub fn from_root(root: &ObservationRoot<'_>, surface: crate::SnapshotSurface) -> Self {
match root {
+ ObservationRoot::Application { app, .. } => Self::Application {
+ app: (*app).clone(),
+ surface,
+ },
ObservationRoot::Window(window) => Self::Window {
window: (*window).clone(),
surface,
diff --git a/crates/core/src/locator/live_locator/resolve_query_hydration_tests.rs b/crates/core/src/locator/live_locator/resolve_query_hydration_tests.rs
index 3a2c15a71..7628e3c6f 100644
--- a/crates/core/src/locator/live_locator/resolve_query_hydration_tests.rs
+++ b/crates/core/src/locator/live_locator/resolve_query_hydration_tests.rs
@@ -22,6 +22,7 @@ impl ObservationOps for HydrationRetryAdapter {
_request: &ObservationRequest,
) -> Result<ObservedTree, AdapterError> {
match root {
+ ObservationRoot::Application { .. } => panic!("expected a window or element root"),
ObservationRoot::Window(_) => {
self.window_observations.fetch_add(1, Ordering::SeqCst);
Ok(lean_button_tree())
@@ -260,6 +261,7 @@ impl ObservationOps for ReadAgainAdapter {
_request: &ObservationRequest,
) -> Result<ObservedTree, AdapterError> {
Ok(match root {
+ ObservationRoot::Application { .. } => panic!("expected a window or element root"),
ObservationRoot::Window(_) => framed_label_tree(Some(self.first_screen), true),
ObservationRoot::Element { .. } => framed_label_tree(self.again_screen, false),
})
diff --git a/crates/core/src/locator/live_locator/selected_hydration_churn_tests.rs b/crates/core/src/locator/live_locator/selected_hydration_churn_tests.rs
index 822bb5c69..224ac79ff 100644
--- a/crates/core/src/locator/live_locator/selected_hydration_churn_tests.rs
+++ b/crates/core/src/locator/live_locator/selected_hydration_churn_tests.rs
@@ -28,6 +28,7 @@ impl ObservationOps for SingleAnchorAdapter {
request: &ObservationRequest,
) -> Result<ObservedTree, AdapterError> {
match root {
+ ObservationRoot::Application { .. } => panic!("expected a window or element root"),
ObservationRoot::Window(_) => {
self.window_observations.fetch_add(1, Ordering::SeqCst);
let evidence = request.descendant_evidence();
diff --git a/crates/core/src/locator/live_locator/selected_hydration_contract_tests.rs b/crates/core/src/locator/live_locator/selected_hydration_contract_tests.rs
index 662d67bbf..7924a8786 100644
--- a/crates/core/src/locator/live_locator/selected_hydration_contract_tests.rs
+++ b/crates/core/src/locator/live_locator/selected_hydration_contract_tests.rs
@@ -35,6 +35,7 @@ impl ObservationOps for HydrationContractAdapter {
request: &ObservationRequest,
) -> Result<ObservedTree, AdapterError> {
match root {
+ ObservationRoot::Application { .. } => panic!("expected a window or element root"),
ObservationRoot::Window(_) => {
self.window_observations.fetch_add(1, Ordering::SeqCst);
Ok(initial_tree(self.mode))
diff --git a/crates/core/src/locator/live_locator/selected_hydration_subtree_tests.rs b/crates/core/src/locator/live_locator/selected_hydration_subtree_tests.rs
index 3471676db..3492850b8 100644
--- a/crates/core/src/locator/live_locator/selected_hydration_subtree_tests.rs
+++ b/crates/core/src/locator/live_locator/selected_hydration_subtree_tests.rs
@@ -33,6 +33,7 @@ impl ObservationOps for SubtreeHydrationAdapter {
request: &ObservationRequest,
) -> Result<ObservedTree, AdapterError> {
match root {
+ ObservationRoot::Application { .. } => panic!("expected a window or element root"),
ObservationRoot::Window(_) => {
self.window_observations.fetch_add(1, Ordering::SeqCst);
let evidence = request.descendant_evidence();
diff --git a/crates/core/src/locator/live_locator/selected_hydration_tests.rs b/crates/core/src/locator/live_locator/selected_hydration_tests.rs
index d42891658..c5b2b93d0 100644
--- a/crates/core/src/locator/live_locator/selected_hydration_tests.rs
+++ b/crates/core/src/locator/live_locator/selected_hydration_tests.rs
@@ -31,6 +31,7 @@ impl ObservationOps for RoleOnlyHydrationAdapter {
request: &ObservationRequest,
) -> Result<ObservedTree, AdapterError> {
match root {
+ ObservationRoot::Application { .. } => panic!("expected a window or element root"),
ObservationRoot::Window(_) => {
self.window_observations.fetch_add(1, Ordering::SeqCst);
crate::wait::deadline::sleep(Duration::from_millis(10));
diff --git a/crates/core/src/ref_action/mod.rs b/crates/core/src/ref_action/mod.rs
index 5358369bc..85d0d5f3e 100644
--- a/crates/core/src/ref_action/mod.rs
+++ b/crates/core/src/ref_action/mod.rs
@@ -4,8 +4,7 @@ use crate::adapter::{NativeHandle, PlatformAdapter};
use crate::context::CommandContext;
use crate::ref_action::ref_action_context::RefActionContext;
use crate::ref_action::ref_action_wait_support::{after_scroll, trace_scroll_error};
-use crate::refs::RefEntry;
-use crate::refs::resolve_saved_ref::resolve_saved_ref;
+use crate::refs::{RefEntry, resolve_saved_ref::resolve_saved_ref};
use crate::{AdapterError, AppError, actionability};
use serde_json::json;
@@ -55,7 +54,13 @@ pub(crate) fn preflight_resolved(
request: &ActionRequest,
stability: actionability::StabilityExpectation,
) -> Result<ActionabilityPreflight, AppError> {
- check_actionability_with_trace(target, request, stability)
+ let report = ref_action_actionability::check_report_with_trace(
+ target,
+ request,
+ stability,
+ actionability::check_live_before_focus,
+ )?;
+ Ok(ref_action_actionability::preflight_from_report(&report))
}
/// Dispatches the action and also returns the handle it landed on.
@@ -253,13 +258,8 @@ fn pre_trace_capture_deadline(parent: crate::Deadline) -> Option<crate::Deadline
Some(parent.capped(capture_budget))
}
-/// The permissive check compares live bounds against the ref's
-/// snapshot-time evidence, which a caller's own preceding `scroll-to` on
-/// this same ref legitimately moved - so a report whose only gap is
-/// `stable` is not yet a verdict, it is the reason to sample. Anything else
-/// unmet (disabled, hidden, policy) is terminal immediately: no amount of
-/// waiting changes it, and `check_live_with_stability_or_gap` already
-/// converts those to `Err` for us.
+/// Samples stability and eligible application-pointer geometry gaps within the action deadline.
+/// Dispatch still requires a complete live actionability check after sampling.
fn stable_preflight(
target: &ResolvedRefAction<'_>,
request: &ActionRequest,
@@ -275,6 +275,7 @@ fn stable_preflight(
if report.actionable {
return Ok(ref_action_actionability::preflight_from_report(&report));
}
+ let geometry_pending = !report.only_blocking_check_is_stability();
let started = crate::wait::deadline::now();
let mut sampler = actionability::stability_sampler::StabilitySampler::new();
loop {
@@ -282,6 +283,10 @@ fn stable_preflight(
.adapter
.get_element_bounds(target.handle, target.deadline)?;
let elapsed = crate::wait::deadline::now().saturating_duration_since(started);
+ let bounds = bounds.filter(|bounds| {
+ !geometry_pending
+ || (bounds.validate().is_ok() && bounds.width > 0.0 && bounds.height > 0.0)
+ });
if sampler.observe(bounds, elapsed) {
let stability = actionability::StabilityExpectation::strict(
sampler.bounds(),
diff --git a/crates/core/src/ref_action/ref_action_focus_order_tests.rs b/crates/core/src/ref_action/ref_action_focus_order_tests.rs
index 92de9c8f7..ac218952d 100644
--- a/crates/core/src/ref_action/ref_action_focus_order_tests.rs
+++ b/crates/core/src/ref_action/ref_action_focus_order_tests.rs
@@ -7,8 +7,11 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
struct FocusAdapter {
focused: AtomicBool,
dispatched: AtomicUsize,
+ resolved: AtomicUsize,
persistent_occlusion: bool,
enabled: bool,
+ application_menu: bool,
+ pointer_menu: Option<AtomicUsize>,
}
fn bounds() -> crate::Rect {
@@ -22,6 +25,17 @@ fn bounds() -> crate::Rect {
impl FocusAdapter {
fn live_bounds(&self) -> crate::Rect {
+ if self
+ .pointer_menu
+ .as_ref()
+ .is_some_and(|remaining| remaining.load(Ordering::SeqCst) > 0)
+ {
+ return crate::Rect {
+ width: 0.0,
+ height: 0.0,
+ ..bounds()
+ };
+ }
crate::Rect {
x: if self.focused.load(Ordering::SeqCst) {
100.0
@@ -39,6 +53,7 @@ impl ObservationOps for FocusAdapter {
_: &RefEntry,
_: Deadline,
) -> Result<NativeHandle, AdapterError> {
+ self.resolved.fetch_add(1, Ordering::SeqCst);
Ok(NativeHandle::null())
}
@@ -46,15 +61,28 @@ impl ObservationOps for FocusAdapter {
Ok(LiveElement {
identity: crate::adapter::live_identity("Run"),
state: ElementState {
- role: "button".into(),
+ role: if self.application_menu {
+ "menuitem"
+ } else {
+ "button"
+ }
+ .into(),
states: vec![],
value: None,
enabled: Some(self.enabled),
hidden: Some(false),
- offscreen: Some(false),
+ offscreen: (!self.application_menu).then_some(false),
},
states_complete: true,
- bounds: Some(self.live_bounds()),
+ bounds: Some(if self.application_menu && self.pointer_menu.is_none() {
+ crate::Rect {
+ width: 0.0,
+ height: 0.0,
+ ..bounds()
+ }
+ } else {
+ self.live_bounds()
+ }),
available_actions: vec![crate::actions::capability::CLICK.into()],
})
}
@@ -64,7 +92,13 @@ impl ObservationOps for FocusAdapter {
_: &NativeHandle,
_: Deadline,
) -> Result<Option<crate::Rect>, AdapterError> {
- Ok(Some(self.live_bounds()))
+ let bounds = self.live_bounds();
+ if let Some(remaining) = &self.pointer_menu {
+ let _ = remaining.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |value| {
+ value.checked_sub(1)
+ });
+ }
+ Ok(Some(bounds))
}
fn hit_test(
@@ -73,6 +107,10 @@ impl ObservationOps for FocusAdapter {
_: crate::Point,
_: Deadline,
) -> Result<crate::HitTestResult, AdapterError> {
+ assert!(
+ !self.application_menu || self.pointer_menu.is_some(),
+ "semantic menus must not hit-test a pointer"
+ );
Ok(
if self.focused.load(Ordering::SeqCst) && !self.persistent_occlusion {
crate::HitTestResult::ReachesTarget
@@ -85,10 +123,50 @@ impl ObservationOps for FocusAdapter {
},
)
}
- crate::adapter::saved_ref_scope!("button", Some("Run"));
+ fn observe_tree(
+ &self,
+ root: crate::ObservationRoot<'_>,
+ _request: &crate::ObservationRequest,
+ ) -> Result<crate::ObservedTree, AdapterError> {
+ let role = if self.application_menu {
+ "menuitem"
+ } else {
+ "button"
+ };
+ crate::adapter::saved_ref_tree(root, role, Some("Run"))
+ }
+
+ crate::adapter::saved_ref_scope!(@inventory);
+ crate::adapter::saved_ref_anchor!();
}
impl ActionOps for FocusAdapter {
+ fn headed_requirement_for_ref(
+ &self,
+ _: &RefEntry,
+ request: &ActionRequest,
+ deadline: Deadline,
+ ) -> Result<crate::HeadedRequirement, AdapterError> {
+ self.headed_requirement(&NativeHandle::null(), request, deadline)
+ }
+
+ fn headed_requirement(
+ &self,
+ _: &NativeHandle,
+ request: &ActionRequest,
+ _: Deadline,
+ ) -> Result<crate::HeadedRequirement, AdapterError> {
+ Ok(if self.application_menu && request.policy.is_headed() {
+ if self.pointer_menu.is_some() {
+ crate::HeadedRequirement::FocusedApplicationAndCursor
+ } else {
+ crate::HeadedRequirement::FocusedApplication
+ }
+ } else {
+ request.headed_requirement()
+ })
+ }
+
fn execute_action(
&self,
_: &NativeHandle,
@@ -99,6 +177,10 @@ impl ActionOps for FocusAdapter {
assert!(self.focused.load(Ordering::SeqCst));
assert_eq!(request.verified_point().map(|point| point.x), Some(110.0));
}
+ if self.application_menu && self.pointer_menu.is_none() {
+ assert_eq!(request.policy, crate::InteractionPolicy::headless());
+ assert!(request.verified_point().is_none());
+ }
self.dispatched.fetch_add(1, Ordering::SeqCst);
Ok(ActionResult::delivered_unverified("click"))
}
@@ -114,7 +196,22 @@ impl SystemOps for FocusAdapter {
) -> Result<WindowInfo, AdapterError> {
Ok(window.clone())
}
+ fn focus_app(
+ &self,
+ process: crate::ProcessIdentity,
+ _: &InteractionLease,
+ ) -> Result<(), AdapterError> {
+ assert!(self.application_menu);
+ assert_eq!(process, crate::ProcessIdentity::new(1, "test-instance"));
+ self.focused.store(true, Ordering::SeqCst);
+ Ok(())
+ }
+
fn focus_window(&self, _: &WindowInfo, _: &InteractionLease) -> Result<(), AdapterError> {
+ assert!(
+ !self.application_menu,
+ "application menus have no document window"
+ );
self.focused.store(true, Ordering::SeqCst);
Ok(())
}
@@ -128,18 +225,34 @@ fn execute_within(
adapter: &FocusAdapter,
headed: bool,
timeout_ms: u64,
+) -> Result<ActionResult, AdapterError> {
+ execute_action_within(adapter, headed, timeout_ms, Action::Click)
+}
+
+fn execute_action_within(
+ adapter: &FocusAdapter,
+ headed: bool,
+ timeout_ms: u64,
+ action: Action,
) -> Result<ActionResult, AdapterError> {
let _clock = crate::wait::deadline::VirtualClock::freeze();
- let entry: RefEntry = serde_json::from_value(serde_json::json!({
+ let mut entry: RefEntry = serde_json::from_value(serde_json::json!({
"pid": 1, "process_instance": "test-instance", "role": "button", "name": "Run",
"source_window_id": "w-1", "source_surface": "window", "path": [0],
"unique_at_capture": true,
"bounds": bounds(), "bounds_hash": bounds().bounds_hash(), "available_actions": ["Click"], "states": []
})).unwrap();
+ if adapter.application_menu {
+ entry.identity.role = "menuitem".into();
+ entry.source.source_window_id = None;
+ entry.source.source_surface = crate::SnapshotSurface::Menubar;
+ entry.geometry.bounds_hash = None;
+ entry.geometry.bounds = Some(adapter.live_bounds());
+ }
let request = if headed {
- ActionRequest::headed(Action::Click)
+ ActionRequest::headed(action)
} else {
- ActionRequest::headless(Action::Click)
+ ActionRequest::headless(action)
};
crate::ref_action::execute_entry(adapter, &entry, request.with_timeout_ms(Some(timeout_ms)))
}
@@ -148,8 +261,11 @@ fn adapter(persistent_occlusion: bool, enabled: bool) -> FocusAdapter {
FocusAdapter {
focused: AtomicBool::new(false),
dispatched: AtomicUsize::new(0),
+ resolved: AtomicUsize::new(0),
persistent_occlusion,
enabled,
+ application_menu: false,
+ pointer_menu: None,
}
}
@@ -184,3 +300,83 @@ fn headless_semantic_action_never_raises_the_window() {
assert!(!adapter.focused.load(Ordering::SeqCst));
assert_eq!(adapter.dispatched.load(Ordering::SeqCst), 1);
}
+
+#[test]
+fn headed_application_menu_uses_semantic_actionability_before_application_focus() {
+ let mut adapter = adapter(true, true);
+ adapter.application_menu = true;
+ execute(&adapter, true).unwrap();
+ assert!(adapter.focused.load(Ordering::SeqCst));
+ assert_eq!(adapter.dispatched.load(Ordering::SeqCst), 1);
+}
+
+#[test]
+fn headless_application_menu_never_activates_the_application() {
+ let mut adapter = adapter(true, true);
+ adapter.application_menu = true;
+ execute(&adapter, false).unwrap();
+ assert!(!adapter.focused.load(Ordering::SeqCst));
+ assert_eq!(adapter.dispatched.load(Ordering::SeqCst), 1);
+}
+
+#[test]
+fn headed_click_does_not_resolve_before_window_focus_and_dispatch() {
+ struct DefaultRequirementAdapter(FocusAdapter);
+ impl ActionOps for DefaultRequirementAdapter {}
+ impl InputOps for DefaultRequirementAdapter {}
+ impl ObservationOps for DefaultRequirementAdapter {
+ fn resolve_element_strict(
+ &self,
+ entry: &RefEntry,
+ deadline: Deadline,
+ ) -> Result<NativeHandle, AdapterError> {
+ self.0.resolve_element_strict(entry, deadline)
+ }
+ }
+ impl SystemOps for DefaultRequirementAdapter {
+ fn resolve_window_strict(
+ &self,
+ window: &WindowInfo,
+ deadline: Deadline,
+ ) -> Result<WindowInfo, AdapterError> {
+ self.0.resolve_window_strict(window, deadline)
+ }
+ fn focus_window(
+ &self,
+ window: &WindowInfo,
+ lease: &InteractionLease,
+ ) -> Result<(), AdapterError> {
+ self.0.focus_window(window, lease)
+ }
+ }
+ let adapter = DefaultRequirementAdapter(adapter(false, true));
+ let entry: RefEntry = serde_json::from_value(serde_json::json!({
+ "pid": 1, "process_instance": "test-instance", "role": "button", "name": "Run",
+ "source_window_id": "w-test", "source_surface": "window", "path": [0],
+ "bounds": bounds(), "available_actions": ["Click"], "states": []
+ }))
+ .unwrap();
+ let context = crate::CommandContext::default();
+ let deadline = Deadline::standard().unwrap();
+ let lease = InteractionLease::guarded(deadline, ()).unwrap();
+ crate::ref_action::ref_action_single::execute_single_shot(
+ crate::ref_action::ref_action_wait_context::RefActionWaitContext {
+ adapter: &adapter,
+ entry: &entry,
+ ref_id: "@test:e1",
+ context: &context,
+ },
+ ActionRequest::headed(Action::Click),
+ deadline,
+ &lease,
+ |_, _, _| {
+ assert!(adapter.0.focused.load(Ordering::SeqCst));
+ assert_eq!(adapter.0.resolved.load(Ordering::SeqCst), 0);
+ Ok(ActionResult::delivered_unverified("click"))
+ },
+ )
+ .unwrap();
+}
+
+#[path = "ref_action_menu_pointer_tests.rs"]
+mod menu_pointer_tests;
diff --git a/crates/core/src/ref_action/ref_action_menu_pointer_tests.rs b/crates/core/src/ref_action/ref_action_menu_pointer_tests.rs
new file mode 100644
index 000000000..cbc01af34
--- /dev/null
+++ b/crates/core/src/ref_action/ref_action_menu_pointer_tests.rs
@@ -0,0 +1,91 @@
+use super::*;
+
+#[test]
+fn application_menu_gestures_focus_the_process_and_keep_pointer_verification() {
+ for action in [Action::RightClick, Action::DoubleClick, Action::TripleClick] {
+ let mut adapter = adapter(false, true);
+ adapter.application_menu = true;
+ adapter.pointer_menu = Some(AtomicUsize::new(0));
+ execute_action_within(&adapter, true, 2_000, action).unwrap();
+ assert!(adapter.focused.load(Ordering::SeqCst));
+ assert_eq!(adapter.dispatched.load(Ordering::SeqCst), 1);
+ }
+}
+
+#[test]
+fn application_menu_gestures_never_dispatch_through_an_occluder() {
+ for action in [Action::RightClick, Action::DoubleClick, Action::TripleClick] {
+ let mut adapter = adapter(true, true);
+ adapter.application_menu = true;
+ adapter.pointer_menu = Some(AtomicUsize::new(0));
+ execute_action_within(&adapter, true, 150, action).unwrap_err();
+ assert!(adapter.focused.load(Ordering::SeqCst));
+ assert_eq!(adapter.dispatched.load(Ordering::SeqCst), 0);
+ }
+}
+
+#[test]
+fn disabled_application_menu_gestures_do_not_focus_or_dispatch() {
+ let mut adapter = adapter(false, false);
+ adapter.application_menu = true;
+ adapter.pointer_menu = Some(AtomicUsize::new(0));
+ execute_action_within(&adapter, true, 150, Action::DoubleClick).unwrap_err();
+ assert!(!adapter.focused.load(Ordering::SeqCst));
+ assert_eq!(adapter.dispatched.load(Ordering::SeqCst), 0);
+}
+
+#[test]
+fn positive_timeout_menu_gestures_wait_through_three_zero_geometry_samples() {
+ for action in [Action::RightClick, Action::DoubleClick, Action::TripleClick] {
+ let mut adapter = adapter(false, true);
+ adapter.application_menu = true;
+ adapter.pointer_menu = Some(AtomicUsize::new(3));
+ execute_action_within(&adapter, true, 500, action).unwrap();
+ assert_eq!(adapter.dispatched.load(Ordering::SeqCst), 1);
+ }
+}
+
+#[test]
+fn single_shot_menu_gesture_does_not_sample_zero_geometry() {
+ let mut adapter = adapter(false, true);
+ adapter.application_menu = true;
+ adapter.pointer_menu = Some(AtomicUsize::new(3));
+ let error = execute_action_within(&adapter, true, 0, Action::RightClick).unwrap_err();
+ assert_eq!(error.code, crate::ErrorCode::ActionFailed);
+ assert_eq!(
+ adapter
+ .pointer_menu
+ .as_ref()
+ .unwrap()
+ .load(Ordering::SeqCst),
+ 3
+ );
+ assert_eq!(adapter.dispatched.load(Ordering::SeqCst), 0);
+}
+
+#[test]
+fn permanently_zero_geometry_uses_only_the_existing_deadline() {
+ let mut adapter = adapter(false, true);
+ adapter.application_menu = true;
+ adapter.pointer_menu = Some(AtomicUsize::new(usize::MAX));
+ let error = execute_action_within(&adapter, true, 100, Action::DoubleClick).unwrap_err();
+ assert_eq!(error.code, crate::ErrorCode::Timeout);
+ assert_eq!(adapter.dispatched.load(Ordering::SeqCst), 0);
+}
+
+#[test]
+fn geometry_settling_does_not_bypass_the_final_hit_test() {
+ let mut adapter = adapter(true, true);
+ adapter.application_menu = true;
+ adapter.pointer_menu = Some(AtomicUsize::new(3));
+ execute_action_within(&adapter, true, 500, Action::TripleClick).unwrap_err();
+ assert_eq!(
+ adapter
+ .pointer_menu
+ .as_ref()
+ .unwrap()
+ .load(Ordering::SeqCst),
+ 0
+ );
+ assert_eq!(adapter.dispatched.load(Ordering::SeqCst), 0);
+}
diff --git a/crates/core/src/ref_action/ref_action_single.rs b/crates/core/src/ref_action/ref_action_single.rs
index b64f237a9..d6e64eba9 100644
--- a/crates/core/src/ref_action/ref_action_single.rs
+++ b/crates/core/src/ref_action/ref_action_single.rs
@@ -27,13 +27,28 @@ pub(crate) fn execute_single_shot(
let keyboard_is_aimed_at_the_element = request.action.delivered_by_keyboard()
&& !context.adapter.keyboard_needs_window_activation();
if request.headed_requirement().requires_focus() && !keyboard_is_aimed_at_the_element {
- crate::actions::headed_focus::focus_entry_window(
- context.entry,
- context.adapter,
- context.context,
- lease,
- )
- .map_err(crate::ref_action::into_adapter_error)?;
+ let requirement = context
+ .adapter
+ .headed_requirement_for_ref(context.entry, &request, deadline)
+ .map_err(crate::ref_action::mark_pre_dispatch_resolution_failure)?;
+ if matches!(
+ requirement,
+ crate::HeadedRequirement::FocusedApplication
+ | crate::HeadedRequirement::FocusedApplicationAndCursor
+ ) {
+ let process = context.entry.process.identity().ok_or_else(|| {
+ AdapterError::stale_ref_because("Target process identity is unavailable")
+ })?;
+ context.adapter.focus_app(process, lease)?;
+ } else if requirement.requires_focus() {
+ crate::actions::headed_focus::focus_entry_window(
+ context.entry,
+ context.adapter,
+ context.context,
+ lease,
+ )
+ .map_err(crate::ref_action::into_adapter_error)?;
+ }
}
dispatch(RefActionContext::new(context, deadline), request, lease).map_err(into_adapter_error)
}
diff --git a/crates/core/src/ref_action/ref_action_wait_support.rs b/crates/core/src/ref_action/ref_action_wait_support.rs
index 08fd41755..c3c52d05a 100644
--- a/crates/core/src/ref_action/ref_action_wait_support.rs
+++ b/crates/core/src/ref_action/ref_action_wait_support.rs
@@ -12,18 +12,10 @@ pub(crate) fn enrich_with_process_state(
if !matches!(err.code, ErrorCode::StaleRef | ErrorCode::AppNotFound) {
return err;
}
- let Some(instance) = entry
- .process
- .process_instance
- .as_deref()
- .filter(|value| !value.is_empty())
- else {
+ let Some(process) = entry.process.identity() else {
return err;
};
- let Ok(state) = adapter.process_state(
- crate::ProcessIdentity::new(entry.process.pid, instance),
- deadline,
- ) else {
+ let Ok(state) = adapter.process_state(process, deadline) else {
return err;
};
if state == crate::system::process_state::ProcessState::Unresponsive {
@@ -63,24 +55,19 @@ fn process_identity_matches(
else {
return false;
};
- let Some(expected_instance) = entry
- .process
- .process_instance
- .as_deref()
- .filter(|instance| !instance.is_empty())
- else {
+ let Some(process) = entry.process.identity() else {
return false;
};
let Ok(apps) = adapter.list_apps(deadline) else {
return false;
};
- let mut same_pid = apps.iter().filter(|app| app.pid == entry.process.pid);
+ let mut same_pid = apps.iter().filter(|app| app.pid == process.pid);
let Some(app) = same_pid.next() else {
return false;
};
same_pid.next().is_none()
&& app.name == expected_name
- && app.process_instance.as_deref() == Some(expected_instance)
+ && app.process_instance.as_deref() == Some(process.instance.as_str())
}
fn attach_process_state_detail(
diff --git a/crates/core/src/refs/ref_capture_proof.rs b/crates/core/src/refs/ref_capture_proof.rs
index 659363748..9d99fc51e 100644
--- a/crates/core/src/refs/ref_capture_proof.rs
+++ b/crates/core/src/refs/ref_capture_proof.rs
@@ -31,8 +31,10 @@ pub(crate) struct CaptureProof<'a> {
impl<'a> CaptureProof<'a> {
pub(crate) fn new(observed: &'a ObservedTree) -> Self {
- let whole_window =
- matches!(observed.source, ObservationSource::Window { .. }) && observed.is_exhaustive();
+ let whole_window = matches!(
+ observed.source,
+ ObservationSource::Window { .. } | ObservationSource::Application { .. }
+ ) && observed.is_exhaustive();
Self {
observed,
whole_window,
diff --git a/crates/core/src/refs/ref_process.rs b/crates/core/src/refs/ref_process.rs
index 8ff1b41f7..192b50307 100644
--- a/crates/core/src/refs/ref_process.rs
+++ b/crates/core/src/refs/ref_process.rs
@@ -8,3 +8,13 @@ pub struct RefProcess {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub process_instance: Option<String>,
}
+
+impl RefProcess {
+ /// Returns the saved process identity when its generation is nonempty.
+ pub fn identity(&self) -> Option<crate::ProcessIdentity> {
+ self.process_instance
+ .as_deref()
+ .filter(|instance| !instance.is_empty())
+ .map(|instance| crate::ProcessIdentity::new(self.pid, instance))
+ }
+}
diff --git a/crates/core/src/refs/resolve_errors.rs b/crates/core/src/refs/resolve_errors.rs
index 00d7ea172..735e2f2ca 100644
--- a/crates/core/src/refs/resolve_errors.rs
+++ b/crates/core/src/refs/resolve_errors.rs
@@ -61,6 +61,33 @@ pub fn mark_deadline_elapsed(mut error: AdapterError) -> AdapterError {
error.with_details(details)
}
+pub(crate) fn ambiguous_live_match(entry: &RefEntry) -> AdapterError {
+ AdapterError::ambiguous_target(
+ "Two or more live elements match the saved ref's recorded role and stable identity",
+ )
+ .with_suggestion(
+ "An element identical to the captured one appeared, so neither can be picked by ref and \
+ a new snapshot refuses both as twins. Act on a control that is unique in the window, or, \
+ where headed pointer input is available, use an explicit --headed coordinate click.",
+ )
+ .with_details(json!({
+ "kind": "saved_ref_ambiguous",
+ "retryable": false,
+ "complete": true,
+ "role": entry.identity.role,
+ }))
+}
+
+pub(crate) fn absent(entry: &RefEntry) -> AdapterError {
+ AdapterError::stale_ref_because("No live element matches the saved ref's recorded identity")
+ .with_details(json!({
+ "kind": "saved_ref_absent",
+ "retryable": false,
+ "complete": true,
+ "role": entry.identity.role,
+ }))
+}
+
#[cfg(test)]
#[path = "resolve_errors_tests.rs"]
mod tests;
diff --git a/crates/core/src/refs/resolve_saved_ref.rs b/crates/core/src/refs/resolve_saved_ref.rs
index 731e4c1e8..634109054 100644
--- a/crates/core/src/refs/resolve_saved_ref.rs
+++ b/crates/core/src/refs/resolve_saved_ref.rs
@@ -1,7 +1,6 @@
-use serde_json::json;
-
use crate::{
- AdapterError, AppError, Deadline, IdentityMatch, PlatformAdapter, RefEntry, WindowInfo,
+ AdapterError, AppError, AppInfo, Deadline, IdentityMatch, PlatformAdapter, RefEntry,
+ WindowInfo,
adapter::{NativeHandle, TreeOptions},
locator::live_locator::{
ObservationRequest, ObservationRoot, ObservedTree, materialize_ref_entry,
@@ -9,7 +8,9 @@ use crate::{
refs::ref_full_predicate::FullPredicate,
refs::ref_identity::element_token,
refs::ref_live_predicate::LivePredicate,
- refs::resolve_errors::{identity_not_unique, identity_unknown_error},
+ refs::resolve_errors::{
+ absent, ambiguous_live_match, identity_not_unique, identity_unknown_error,
+ },
};
/// The depth a whole-window observation reaches: the limit a snapshot walk
@@ -268,13 +269,25 @@ fn observe_window(
window: &WindowInfo,
lease: Option<&crate::InteractionLease>,
) -> Result<ObservedTree, AdapterError> {
- let mut observed = crate::tree::renderer_accessibility::observe_tree(
- adapter,
- ObservationRoot::Window(window),
- request,
- lease,
- )
- .map_err(adapter_error)?;
+ let process_instance = window.process_instance.clone();
+ let app = AppInfo {
+ name: window.app.clone(),
+ pid: window.pid,
+ process_instance,
+ bundle_id: None,
+ presentation: None,
+ };
+ let root = if adapter.is_application_surface(request.surface) {
+ ObservationRoot::Application {
+ app: &app,
+ surface: request.surface,
+ }
+ } else {
+ ObservationRoot::Window(window)
+ };
+ let mut observed =
+ crate::tree::renderer_accessibility::observe_tree(adapter, root, request, lease)
+ .map_err(adapter_error)?;
if let crate::locator::live_locator::ObservationSource::Window {
renderer_accessibility_forced,
..
@@ -348,33 +361,6 @@ fn positional_anchor(
Ok(anchor)
}
-fn ambiguous_live_match(entry: &RefEntry) -> AdapterError {
- AdapterError::ambiguous_target(
- "Two or more live elements match the saved ref's recorded role and stable identity",
- )
- .with_suggestion(
- "An element identical to the captured one appeared, so neither can be picked by ref and \
- a new snapshot refuses both as twins. Act on a control that is unique in the window, or, \
- where headed pointer input is available, use an explicit --headed coordinate click.",
- )
- .with_details(json!({
- "kind": "saved_ref_ambiguous",
- "retryable": false,
- "complete": true,
- "role": entry.identity.role,
- }))
-}
-
-fn absent(entry: &RefEntry) -> AdapterError {
- AdapterError::stale_ref_because("No live element matches the saved ref's recorded identity")
- .with_details(json!({
- "kind": "saved_ref_absent",
- "retryable": false,
- "complete": true,
- "role": entry.identity.role,
- }))
-}
-
fn adapter_error(error: AppError) -> AdapterError {
match error {
AppError::Adapter(error) => error,
diff --git a/crates/core/src/response/mod.rs b/crates/core/src/response/mod.rs
index e8af7c445..ed81d842e 100644
--- a/crates/core/src/response/mod.rs
+++ b/crates/core/src/response/mod.rs
@@ -6,3 +6,4 @@ pub mod output;
pub(crate) mod recovery_hint;
pub(crate) mod retry_disposition;
pub(crate) mod retryability;
+pub(crate) mod surface_absence;
diff --git a/crates/core/src/response/surface_absence.rs b/crates/core/src/response/surface_absence.rs
new file mode 100644
index 000000000..e25af6272
--- /dev/null
+++ b/crates/core/src/response/surface_absence.rs
@@ -0,0 +1,32 @@
+use crate::{AdapterError, ErrorCode, SnapshotSurface};
+
+impl AdapterError {
+ /// Records a complete lookup that proved the requested surface absent.
+ pub fn surface_absent(surface: SnapshotSurface, message: &str) -> Self {
+ let suggestion = if surface == SnapshotSurface::Menu {
+ "Open the menu, then take a fresh snapshot with --surface menu".to_owned()
+ } else {
+ format!(
+ "Ensure the application exposes the {} surface, then take a fresh snapshot with --surface {}",
+ surface.as_str(),
+ surface.as_str(),
+ )
+ };
+ Self::new(ErrorCode::ElementNotFound, message)
+ .with_suggestion(suggestion)
+ .with_details(serde_json::json!({
+ "kind": "surface_absent",
+ "complete": true,
+ "surface": surface.as_str(),
+ }))
+ }
+
+ pub fn is_confirmed_surface_absence(&self, surface: SnapshotSurface) -> bool {
+ self.code == ErrorCode::ElementNotFound
+ && self.details.as_ref().is_some_and(|details| {
+ details["kind"] == "surface_absent"
+ && details["complete"] == true
+ && details["surface"] == surface.as_str()
+ })
+ }
+}
diff --git a/crates/core/src/snapshot/mod.rs b/crates/core/src/snapshot/mod.rs
index dd5f744d9..5cf27be60 100644
--- a/crates/core/src/snapshot/mod.rs
+++ b/crates/core/src/snapshot/mod.rs
@@ -1,12 +1,11 @@
use crate::{
- AccessibilityNode, AppError, WindowInfo,
- adapter::{PlatformAdapter, TreeOptions, WindowFilter},
+ AccessibilityNode, AppError, SnapshotOwner, WindowInfo,
+ adapter::{PlatformAdapter, TreeOptions},
context::CommandContext,
refs::RefMap,
refs::ref_alloc::{self, RefAllocConfig},
refs::ref_alloc_options::RefAllocOptions,
refs::ref_alloc_scope::RefAllocScope,
- refs::ref_alloc_source::RefAllocSource,
refs::refs_store::RefStore,
trace::trace_artifacts,
};
@@ -16,7 +15,7 @@ use serde_json::json;
pub struct SnapshotResult {
pub tree: AccessibilityNode,
pub refmap: RefMap,
- pub window: WindowInfo,
+ pub owner: SnapshotOwner,
pub snapshot_id: Option<String>,
pub complete: bool,
pub nodes_observed: usize,
@@ -47,9 +46,24 @@ pub fn build(
window_id: Option<&str>,
deadline: crate::Deadline,
) -> Result<SnapshotResult, AppError> {
- let windows = surface_windows(adapter, app_name, window_id, opts.surface, deadline)?;
- let (window, capture) = window_capture::first_surface_owner(windows, |window| {
- window_capture::capture_window(adapter, opts, window, deadline)
+ let owners =
+ surface_target::resolve_owners(adapter, app_name, window_id, opts.surface, deadline)?;
+ build_for_owners(adapter, opts, owners, deadline)
+}
+
+pub(crate) fn build_for_owners(
+ adapter: &dyn PlatformAdapter,
+ opts: &TreeOptions,
+ owners: Vec<SnapshotOwner>,
+ deadline: crate::Deadline,
+) -> Result<SnapshotResult, AppError> {
+ let (owner, capture) = window_capture::first_surface_owner(owners, |owner| match owner {
+ SnapshotOwner::Application(app) => {
+ window_capture::capture_application(adapter, opts, app, opts.surface, deadline)
+ }
+ SnapshotOwner::Window(window) => {
+ window_capture::capture_window(adapter, opts, window, deadline)
+ }
})?;
let identity_unproven = capture.identity_unproven.clone();
let (raw_tree, complete, nodes_observed, observed) = capture.into_parts()?;
@@ -63,15 +77,7 @@ pub fn build(
compact: opts.compact,
force_renderer_accessibility: opts.force_renderer_accessibility,
},
- source: RefAllocSource {
- pid: window.pid,
- app: Some(window.app.as_str()),
- window_id: (!window.is_process_owner()).then_some(window.id.as_str()),
- window_title: Some(window.title.as_str()),
- window_bounds_hash: window.bounds.as_ref().and_then(crate::Rect::bounds_hash),
- process_instance: window.process_instance.as_deref(),
- surface: opts.surface,
- },
+ source: owner.ref_source(opts.surface),
scope: RefAllocScope {
root_ref_id: None,
path_prefix: &[],
@@ -85,7 +91,7 @@ pub fn build(
Ok(SnapshotResult {
tree,
refmap,
- window,
+ owner,
snapshot_id: None,
complete,
nodes_observed,
@@ -93,22 +99,6 @@ pub fn build(
})
}
-/// Resolves the window that identifies the process to observe. An app-level
-/// surface is not owned by a single window, so several open windows must not be
-/// reported as ambiguous when one is requested.
-///
-/// Kinds naming OS chrome rather than a window's own sub-surface are routed to
-/// the adapter's `resolve_shell_surface` seam ahead of the application path,
-/// because no application owns them and the window inventory cannot identify
-/// them - not even a recorded or requested window id, which a shell container
-/// carries too. An adapter that answers with the trait default falls through to
-/// the application path, so an adapter's shape never changes by upgrading; every
-/// other answer - a missing surface, a build refusal, a timeout - is returned
-/// as the adapter supplied it, and a surface that answers with another window
-/// leaves the id to the application path.
-///
-/// `menu-bar-extras` with an app name is that app's own status item and takes the
-/// application path, where a background app that lists no window is read through its process.
pub(crate) fn resolve_window_for_surface(
adapter: &dyn PlatformAdapter,
app_name: Option<&str>,
@@ -116,77 +106,7 @@ pub(crate) fn resolve_window_for_surface(
surface: crate::SnapshotSurface,
deadline: crate::Deadline,
) -> Result<WindowInfo, AppError> {
- let app_status_item = app_name.is_some() && surface == crate::SnapshotSurface::MenuBarExtras;
- if is_shell_surface(surface) && !app_status_item {
- match adapter.resolve_shell_surface(surface, deadline) {
- Ok(window) if window_id.is_none_or(|id| window.id == id) => return Ok(window),
- Ok(_) => {}
- Err(error)
- if window_id.is_none()
- && !error.is_default_not_supported("resolve_shell_surface") =>
- {
- return Err(error.into());
- }
- Err(_) => {}
- }
- }
- if window_id.is_some() || (surface == crate::SnapshotSurface::Window && app_name.is_none()) {
- return resolve_window(adapter, app_name, window_id, deadline);
- }
- let windows = windows_for_app(adapter, app_name, deadline)?;
- if let (true, Some(app)) = (windows.is_empty() && is_process_surface(surface), app_name) {
- return crate::system::app_lookup::windowless_app_owner(adapter, app, deadline);
- }
- if let (crate::SnapshotSurface::Window, Some(app)) = (surface, app_name) {
- return select_app_window(windows, app);
- }
- crate::system::window_lookup::select_surface_owner(
- windows,
- crate::AdapterError::new(
- crate::ErrorCode::WindowNotFound,
- format!(
- "No window found to identify the application owning surface '{}'",
- surface.as_str()
- ),
- ),
- )
-}
-
-/// Whether the surface names OS chrome rather than a window's own sub-surface:
-/// the kinds an adapter may resolve directly, with no owning application and
-/// no window in the inventory. Derived from the [`SnapshotSurface`] variant
-/// alone - never from a platform check - so the seam stays platform-neutral.
-fn is_shell_surface(surface: crate::SnapshotSurface) -> bool {
- matches!(
- surface,
- crate::SnapshotSurface::StartMenu
- | crate::SnapshotSurface::Taskbar
- | crate::SnapshotSurface::SystemTray
- | crate::SnapshotSurface::SystemTrayOverflow
- | crate::SnapshotSurface::ActionCenter
- | crate::SnapshotSurface::QuickSettings
- | crate::SnapshotSurface::Dock
- | crate::SnapshotSurface::MenuBarExtras
- )
-}
-
-/// Surfaces a background app with no window still presents, read from its
-/// process; the owner then carries an empty window id.
-fn is_process_surface(surface: crate::SnapshotSurface) -> bool {
- matches!(
- surface,
- crate::SnapshotSurface::Window
- | crate::SnapshotSurface::Menubar
- | crate::SnapshotSurface::MenuBarExtras
- )
-}
-
-fn select_app_window(windows: Vec<WindowInfo>, app: &str) -> Result<WindowInfo, AppError> {
- crate::system::window_lookup::select_window(
- windows,
- crate::AdapterError::app_has_no_window(app),
- "More than one window matches the target",
- )
+ surface_target::resolve_window_for_surface(adapter, app_name, window_id, surface, deadline)
}
pub(crate) fn surface_windows(
@@ -196,47 +116,7 @@ pub(crate) fn surface_windows(
surface: crate::SnapshotSurface,
deadline: crate::Deadline,
) -> Result<Vec<WindowInfo>, AppError> {
- use crate::SnapshotSurface::{Alert, Popover, Sheet};
- if window_id.is_none() && matches!(surface, Sheet | Popover | Alert) {
- let mut windows = match app_name {
- Some(_) => windows_for_app(adapter, app_name, deadline)?,
- None => frontmost_process_windows(adapter, surface, deadline)?,
- };
- windows.retain(|window| window.state.accessible);
- let windows = crate::system::window_lookup::surface_owner_order(windows);
- if !windows.is_empty() {
- return Ok(windows);
- }
- }
- Ok(vec![resolve_window_for_surface(
- adapter, app_name, window_id, surface, deadline,
- )?])
-}
-
-fn frontmost_process_windows(
- adapter: &dyn PlatformAdapter,
- surface: crate::SnapshotSurface,
- deadline: crate::Deadline,
-) -> Result<Vec<WindowInfo>, AppError> {
- let owner = resolve_window_for_surface(adapter, None, None, surface, deadline)?;
- let mut windows = windows_for_app(adapter, Some(owner.app.as_str()), deadline)?;
- windows.retain(|window| window.pid == owner.pid);
- if windows.is_empty() {
- windows.push(owner);
- }
- Ok(windows)
-}
-
-fn windows_for_app(
- adapter: &dyn PlatformAdapter,
- app_name: Option<&str>,
- deadline: crate::Deadline,
-) -> Result<Vec<WindowInfo>, AppError> {
- let filter = WindowFilter {
- focused_only: app_name.is_none(),
- app: app_name.map(str::to_string),
- };
- Ok(adapter.list_windows(&filter, deadline)?)
+ surface_target::surface_windows(adapter, app_name, window_id, surface, deadline)
}
pub(crate) fn resolve_window(
@@ -245,42 +125,7 @@ pub(crate) fn resolve_window(
window_id: Option<&str>,
deadline: crate::Deadline,
) -> Result<WindowInfo, AppError> {
- let filter = WindowFilter {
- focused_only: app_name.is_none() && window_id.is_none(),
- app: app_name.map(str::to_string),
- };
-
- let windows = adapter.list_windows(&filter, deadline)?;
-
- if let Some(wid) = window_id {
- windows.into_iter().find(|w| w.id == wid).ok_or_else(|| {
- AppError::Adapter(
- crate::AdapterError::new(
- crate::ErrorCode::WindowNotFound,
- format!("No window with id {wid}"),
- )
- .with_suggestion("Run 'list-windows' to see available window IDs.")
- .unsent(),
- )
- })
- } else if let Some(app) = app_name {
- if windows.is_empty() {
- if let Err(AppError::Adapter(error)) =
- crate::system::app_lookup::resolve_app(Some(app), adapter, deadline)
- {
- if error.code == crate::ErrorCode::AppNotFound {
- return Err(AppError::Adapter(error));
- }
- }
- }
- select_app_window(windows, app)
- } else {
- crate::system::window_lookup::select_window(
- windows,
- crate::AdapterError::new(crate::ErrorCode::WindowNotFound, "No focused window found"),
- "More than one window matches the target",
- )
- }
+ surface_target::resolve_window(adapter, app_name, window_id, deadline)
}
#[cfg(test)]
@@ -350,8 +195,8 @@ pub(crate) fn emit_snapshot_saved(
"snapshot_id": result.snapshot_id,
"ref_count": result.refmap.len(),
});
- if !result.window.app.is_empty() {
- fields["app"] = json!(result.window.app);
+ if !result.owner.app_name().is_empty() {
+ fields["app"] = json!(result.owner.app_name());
}
if let Some(reason) = &result.identity_unproven {
fields["identity_unproven"] = json!(reason);
@@ -361,8 +206,11 @@ pub(crate) fn emit_snapshot_saved(
}
pub mod hints;
-pub mod snapshot_ref;
+pub(crate) mod ref_owner_observation;
+pub(crate) mod snapshot_owner;
+pub(crate) mod snapshot_ref;
pub mod snapshot_surface;
+pub(crate) mod surface_target;
#[cfg(test)]
#[path = "snapshot_tests.rs"]
mod tests;
diff --git a/crates/core/src/snapshot/ref_owner_observation.rs b/crates/core/src/snapshot/ref_owner_observation.rs
new file mode 100644
index 000000000..21f8431ef
--- /dev/null
+++ b/crates/core/src/snapshot/ref_owner_observation.rs
@@ -0,0 +1,7 @@
+use crate::{SnapshotOwner, system::process_state::ProcessState};
+
+pub(crate) enum RefOwnerObservation {
+ Present(SnapshotOwner),
+ Absent(Option<ProcessState>),
+ Unavailable(ProcessState),
+}
diff --git a/crates/core/src/snapshot/snapshot_owner.rs b/crates/core/src/snapshot/snapshot_owner.rs
new file mode 100644
index 000000000..5a9c808f1
--- /dev/null
+++ b/crates/core/src/snapshot/snapshot_owner.rs
@@ -0,0 +1,62 @@
+use crate::{AppInfo, ObservationRoot, SnapshotSurface, WindowInfo};
+
+#[derive(Debug, Clone)]
+pub enum SnapshotOwner {
+ Application(AppInfo),
+ Window(WindowInfo),
+}
+
+impl SnapshotOwner {
+ pub fn app_name(&self) -> &str {
+ match self {
+ Self::Application(app) => &app.name,
+ Self::Window(window) => &window.app,
+ }
+ }
+
+ pub fn window(&self) -> Option<&WindowInfo> {
+ match self {
+ Self::Application(_) => None,
+ Self::Window(window) if !window.is_process_owner() => Some(window),
+ Self::Window(_) => None,
+ }
+ }
+
+ pub fn observation_root(&self, surface: SnapshotSurface) -> ObservationRoot<'_> {
+ match self {
+ Self::Application(app) => ObservationRoot::Application { app, surface },
+ Self::Window(window) => ObservationRoot::Window(window),
+ }
+ }
+
+ pub(crate) fn ref_source(
+ &self,
+ surface: SnapshotSurface,
+ ) -> crate::refs::ref_alloc_source::RefAllocSource<'_> {
+ use crate::refs::ref_alloc_source::RefAllocSource;
+ match self {
+ Self::Application(app) => RefAllocSource {
+ pid: app.pid,
+ app: Some(&app.name),
+ process_instance: app.process_instance.as_deref(),
+ window_id: None,
+ window_title: Some(""),
+ window_bounds_hash: None,
+ surface,
+ },
+ Self::Window(window) => RefAllocSource {
+ pid: window.pid,
+ app: Some(&window.app),
+ process_instance: window.process_instance.as_deref(),
+ window_id: (!window.is_process_owner()).then_some(window.id.as_str()),
+ window_title: Some(if window.is_process_owner() {
+ ""
+ } else {
+ &window.title
+ }),
+ window_bounds_hash: window.bounds.as_ref().and_then(crate::Rect::bounds_hash),
+ surface,
+ },
+ }
+ }
+}
diff --git a/crates/core/src/snapshot/snapshot_ref.rs b/crates/core/src/snapshot/snapshot_ref.rs
index 2791cd464..e30cad3d9 100644
--- a/crates/core/src/snapshot/snapshot_ref.rs
+++ b/crates/core/src/snapshot/snapshot_ref.rs
@@ -1,5 +1,5 @@
use crate::{
- AccessibilityNode, AppError, WindowInfo,
+ AccessibilityNode, AppError, SnapshotOwner, WindowInfo,
adapter::{PlatformAdapter, TreeOptions},
context::CommandContext,
locator::live_locator::{ObservationRequest, ObservationRoot},
@@ -83,10 +83,7 @@ pub fn run_from_ref_with_context(
} = capture;
let capture_proof =
crate::refs::ref_capture_proof::CaptureProof::new(&observed).rooted_at(&path_prefix);
-
- let source_app = entry.source.source_app.as_deref();
- let source_window_id = entry.source.source_window_id.as_deref();
- let source_window_title = entry.source.source_window_title.as_deref();
+ let owner = resolve_result_owner(&entry, &window, adapter)?;
let config = RefAllocConfig {
options: RefAllocOptions {
include_bounds: opts.include_bounds,
@@ -96,9 +93,9 @@ pub fn run_from_ref_with_context(
},
source: RefAllocSource {
pid: entry.process.pid,
- app: source_app,
- window_id: source_window_id,
- window_title: source_window_title,
+ app: entry.source.source_app.as_deref(),
+ window_id: entry.source.source_window_id.as_deref(),
+ window_title: entry.source.source_window_title.as_deref(),
window_bounds_hash: entry.source.source_window_bounds_hash,
process_instance: entry.process.process_instance.as_deref(),
surface: entry.source.source_surface,
@@ -139,7 +136,7 @@ pub fn run_from_ref_with_context(
Ok(SnapshotResult {
tree,
refmap,
- window,
+ owner,
snapshot_id: Some(active_snapshot_id),
complete: true,
nodes_observed,
@@ -147,6 +144,20 @@ pub fn run_from_ref_with_context(
})
}
+fn resolve_result_owner(
+ entry: &crate::refs::RefEntry,
+ window: &WindowInfo,
+ adapter: &dyn PlatformAdapter,
+) -> Result<SnapshotOwner, AppError> {
+ if adapter.is_application_surface(entry.source.source_surface) {
+ let app = super::surface_target::application_from_ref(entry)?;
+ crate::system::app_lookup::process_identity(&app)?;
+ Ok(SnapshotOwner::Application(app))
+ } else {
+ Ok(SnapshotOwner::Window(window.clone()))
+ }
+}
+
fn drill_capture(
adapter: &dyn PlatformAdapter,
opts: &TreeOptions,
diff --git a/crates/core/src/snapshot/snapshot_ref_window_tests.rs b/crates/core/src/snapshot/snapshot_ref_window_tests.rs
index e57cb89fc..d112246de 100644
--- a/crates/core/src/snapshot/snapshot_ref_window_tests.rs
+++ b/crates/core/src/snapshot/snapshot_ref_window_tests.rs
@@ -27,7 +27,7 @@ fn test_run_from_ref_resolves_source_window_among_same_process_windows() {
let result = run_from_ref(&adapter, &drill_opts(), "@e1", Some(&snapshot_id))
.expect("drill must resolve its own source window, not the process");
- assert_eq!(result.window.id, "w-467");
+ assert_eq!(result.owner.window().unwrap().id, "w-467");
}
#[test]
@@ -72,11 +72,11 @@ fn test_run_from_ref_drills_a_ref_captured_from_a_windowless_app() {
let deadline = crate::Deadline::after(1000).unwrap();
let captured =
crate::snapshot::build(&windowless, &opts, Some("TestApp"), None, deadline).unwrap();
- assert!(captured.window.is_process_owner(), "{surface:?}");
+ assert!(captured.owner.window().is_none(), "{surface:?}");
let snapshot_id = save_latest(captured.refmap);
let adapter =
StubAdapter::with_windows(named("button", "Dock"), vec![window_info("w-9", true)]);
let result = run_from_ref(&adapter, &drill_opts(), "@e1", Some(&snapshot_id)).unwrap();
- assert!(result.window.is_process_owner(), "{surface:?}");
+ assert!(result.owner.window().is_none(), "{surface:?}");
}
}
diff --git a/crates/core/src/snapshot/snapshot_surface_window_tests.rs b/crates/core/src/snapshot/snapshot_surface_window_tests.rs
index b3d8f37d8..fb7857674 100644
--- a/crates/core/src/snapshot/snapshot_surface_window_tests.rs
+++ b/crates/core/src/snapshot/snapshot_surface_window_tests.rs
@@ -1,4 +1,5 @@
use super::*;
+use crate::WindowFilter;
use crate::adapter::{ActionOps, InputOps, ObservationOps, SystemOps};
use crate::locator::live_locator::{ObservationRequest, ObservationRoot};
@@ -109,7 +110,7 @@ fn an_unpinned_alert_is_found_on_whichever_window_holds_it() {
)
.unwrap();
- assert_eq!(result.window.id, "w-2");
+ assert_eq!(result.owner.window().unwrap().id, "w-2");
}
#[test]
@@ -154,7 +155,7 @@ fn an_alert_without_app_is_found_on_another_window_of_the_frontmost_app() {
)
.unwrap();
- assert_eq!(result.window.id, "w-2");
+ assert_eq!(result.owner.window().unwrap().id, "w-2");
}
#[test]
@@ -178,7 +179,7 @@ fn find_and_snapshot_reach_the_same_sheet_and_respect_an_explicit_window() {
crate::Deadline::standard().unwrap(),
)
.expect("snapshot reaches the sheet window");
- assert_eq!(snapshot.window.id, "w-sheet");
+ assert_eq!(snapshot.owner.window().unwrap().id, "w-sheet");
for window in [None, Some("w-main")] {
let result = crate::commands::find::execute(
FindArgs {
diff --git a/crates/core/src/snapshot/snapshot_window_tests.rs b/crates/core/src/snapshot/snapshot_window_tests.rs
index fae51e379..b9d9205dc 100644
--- a/crates/core/src/snapshot/snapshot_window_tests.rs
+++ b/crates/core/src/snapshot/snapshot_window_tests.rs
@@ -1,4 +1,5 @@
use super::*;
+use crate::WindowFilter;
use crate::adapter::{ActionOps, InputOps, ObservationOps, SystemOps};
struct WindowAdapter {
diff --git a/crates/core/src/snapshot/surface_target.rs b/crates/core/src/snapshot/surface_target.rs
new file mode 100644
index 000000000..3cc24cb9e
--- /dev/null
+++ b/crates/core/src/snapshot/surface_target.rs
@@ -0,0 +1,328 @@
+use super::ref_owner_observation::RefOwnerObservation;
+use crate::system::process_state::ProcessState;
+use crate::{
+ AdapterError, AppError, Deadline, PlatformAdapter, SnapshotOwner, SnapshotSurface, WindowInfo,
+ adapter::WindowFilter,
+};
+
+/// Resolves the window that identifies the process to observe. An app-level
+/// surface is not owned by a single window, so several open windows must not be
+/// reported as ambiguous when one is requested.
+///
+/// Kinds naming OS chrome rather than a window's own sub-surface are routed to
+/// the adapter's `resolve_shell_surface` seam ahead of the application path,
+/// because no application owns them and the window inventory cannot identify
+/// them - not even a recorded or requested window id, which a shell container
+/// carries too. An adapter that answers with the trait default falls through to
+/// the application path, so an adapter's shape never changes by upgrading; every
+/// other answer - a missing surface, a build refusal, a timeout - is returned
+/// as the adapter supplied it, and a surface that answers with another window
+/// leaves the id to the application path.
+///
+/// `menu-bar-extras` with an app name is that app's own status item and takes the
+/// application path, where a background app that lists no window is read through its process.
+pub(crate) fn resolve_window_for_surface(
+ adapter: &dyn PlatformAdapter,
+ app_name: Option<&str>,
+ window_id: Option<&str>,
+ surface: crate::SnapshotSurface,
+ deadline: crate::Deadline,
+) -> Result<WindowInfo, AppError> {
+ let app_status_item = app_name.is_some() && surface == crate::SnapshotSurface::MenuBarExtras;
+ if is_shell_surface(surface) && !app_status_item {
+ match adapter.resolve_shell_surface(surface, deadline) {
+ Ok(window) if window_id.is_none_or(|id| window.id == id) => return Ok(window),
+ Ok(_) => {}
+ Err(error)
+ if window_id.is_none()
+ && !error.is_default_not_supported("resolve_shell_surface") =>
+ {
+ return Err(error.into());
+ }
+ Err(_) => {}
+ }
+ }
+ if window_id.is_some() || (surface == crate::SnapshotSurface::Window && app_name.is_none()) {
+ return resolve_window(adapter, app_name, window_id, deadline);
+ }
+ let windows = windows_for_app(adapter, app_name, deadline)?;
+ if let (true, Some(app)) = (windows.is_empty() && is_process_surface(surface), app_name) {
+ return crate::system::app_lookup::windowless_app_owner(adapter, app, deadline);
+ }
+ if let (crate::SnapshotSurface::Window, Some(app)) = (surface, app_name) {
+ return select_app_window(windows, app);
+ }
+ crate::system::window_lookup::select_surface_owner(
+ windows,
+ crate::AdapterError::new(
+ crate::ErrorCode::WindowNotFound,
+ format!(
+ "No window found to identify the application owning surface '{}'",
+ surface.as_str()
+ ),
+ ),
+ )
+}
+
+/// Whether the surface names OS chrome rather than a window's own sub-surface:
+/// the kinds an adapter may resolve directly, with no owning application and
+/// no window in the inventory. Derived from the [`SnapshotSurface`] variant
+/// alone - never from a platform check - so the seam stays platform-neutral.
+fn is_shell_surface(surface: crate::SnapshotSurface) -> bool {
+ matches!(
+ surface,
+ crate::SnapshotSurface::StartMenu
+ | crate::SnapshotSurface::Taskbar
+ | crate::SnapshotSurface::SystemTray
+ | crate::SnapshotSurface::SystemTrayOverflow
+ | crate::SnapshotSurface::ActionCenter
+ | crate::SnapshotSurface::QuickSettings
+ | crate::SnapshotSurface::Dock
+ | crate::SnapshotSurface::MenuBarExtras
+ )
+}
+
+/// Surfaces a background app with no window still presents, read from its
+/// process; the owner then carries an empty window id.
+fn is_process_surface(surface: crate::SnapshotSurface) -> bool {
+ matches!(
+ surface,
+ crate::SnapshotSurface::Window
+ | crate::SnapshotSurface::Menubar
+ | crate::SnapshotSurface::MenuBarExtras
+ )
+}
+
+fn select_app_window(windows: Vec<WindowInfo>, app: &str) -> Result<WindowInfo, AppError> {
+ crate::system::window_lookup::select_window(
+ windows,
+ crate::AdapterError::app_has_no_window(app),
+ "More than one window matches the target",
+ )
+}
+
+pub(crate) fn surface_windows(
+ adapter: &dyn PlatformAdapter,
+ app_name: Option<&str>,
+ window_id: Option<&str>,
+ surface: crate::SnapshotSurface,
+ deadline: crate::Deadline,
+) -> Result<Vec<WindowInfo>, AppError> {
+ use crate::SnapshotSurface::{Alert, Popover, Sheet};
+ if window_id.is_none() && matches!(surface, Sheet | Popover | Alert) {
+ let mut windows = match app_name {
+ Some(_) => windows_for_app(adapter, app_name, deadline)?,
+ None => frontmost_process_windows(adapter, surface, deadline)?,
+ };
+ windows.retain(|window| window.state.accessible);
+ let windows = crate::system::window_lookup::surface_owner_order(windows);
+ if !windows.is_empty() {
+ return Ok(windows);
+ }
+ }
+ Ok(vec![resolve_window_for_surface(
+ adapter, app_name, window_id, surface, deadline,
+ )?])
+}
+
+fn frontmost_process_windows(
+ adapter: &dyn PlatformAdapter,
+ surface: crate::SnapshotSurface,
+ deadline: crate::Deadline,
+) -> Result<Vec<WindowInfo>, AppError> {
+ let owner = resolve_window_for_surface(adapter, None, None, surface, deadline)?;
+ let mut windows = windows_for_app(adapter, Some(owner.app.as_str()), deadline)?;
+ windows.retain(|window| window.pid == owner.pid);
+ if windows.is_empty() {
+ windows.push(owner);
+ }
+ Ok(windows)
+}
+
+fn windows_for_app(
+ adapter: &dyn PlatformAdapter,
+ app_name: Option<&str>,
+ deadline: crate::Deadline,
+) -> Result<Vec<WindowInfo>, AppError> {
+ let filter = WindowFilter {
+ focused_only: app_name.is_none(),
+ app: app_name.map(str::to_string),
+ };
+ Ok(adapter.list_windows(&filter, deadline)?)
+}
+
+pub(crate) fn resolve_window(
+ adapter: &dyn PlatformAdapter,
+ app_name: Option<&str>,
+ window_id: Option<&str>,
+ deadline: crate::Deadline,
+) -> Result<WindowInfo, AppError> {
+ let filter = WindowFilter {
+ focused_only: app_name.is_none() && window_id.is_none(),
+ app: app_name.map(str::to_string),
+ };
+
+ let windows = adapter.list_windows(&filter, deadline)?;
+
+ if let Some(wid) = window_id {
+ windows.into_iter().find(|w| w.id == wid).ok_or_else(|| {
+ AppError::Adapter(
+ crate::AdapterError::new(
+ crate::ErrorCode::WindowNotFound,
+ format!("No window with id {wid}"),
+ )
+ .with_suggestion("Run 'list-windows' to see available window IDs.")
+ .unsent(),
+ )
+ })
+ } else if let Some(app) = app_name {
+ if windows.is_empty() {
+ if let Err(AppError::Adapter(error)) =
+ crate::system::app_lookup::resolve_app(Some(app), adapter, deadline)
+ {
+ if error.code == crate::ErrorCode::AppNotFound {
+ return Err(AppError::Adapter(error));
+ }
+ }
+ }
+ select_app_window(windows, app)
+ } else {
+ crate::system::window_lookup::select_window(
+ windows,
+ crate::AdapterError::new(crate::ErrorCode::WindowNotFound, "No focused window found"),
+ "More than one window matches the target",
+ )
+ }
+}
+pub(crate) fn resolve_owners(
+ adapter: &dyn PlatformAdapter,
+ app_name: Option<&str>,
+ window_id: Option<&str>,
+ surface: SnapshotSurface,
+ deadline: Deadline,
+) -> Result<Vec<SnapshotOwner>, AppError> {
+ if !adapter.is_application_surface(surface) {
+ return super::surface_windows(adapter, app_name, window_id, surface, deadline)
+ .map(|windows| windows.into_iter().map(SnapshotOwner::Window).collect());
+ }
+ let app = if window_id.is_some() {
+ let window = super::resolve_window(adapter, app_name, window_id, deadline)?;
+ crate::system::app_lookup::resolve_app_owning(&window, adapter, deadline)?
+ } else if app_name.is_some() {
+ crate::system::app_lookup::resolve_app(app_name, adapter, deadline)?
+ } else {
+ adapter.focused_app(deadline)?.ok_or_else(|| {
+ AdapterError::new(
+ crate::ErrorCode::AppNotFound,
+ "No focused application was found when --app was omitted",
+ )
+ .unsent()
+ })?
+ };
+ crate::system::app_lookup::process_identity(&app)?;
+ Ok(vec![SnapshotOwner::Application(app)])
+}
+
+pub(crate) fn resolve_ref_owner(
+ adapter: &dyn PlatformAdapter,
+ entry: &crate::RefEntry,
+ deadline: Deadline,
+) -> Result<RefOwnerObservation, AppError> {
+ let process = entry.process.identity().ok_or_else(|| {
+ AdapterError::new(
+ crate::ErrorCode::ActionNotSupported,
+ "Ref has no process-instance identity for post-action observation",
+ )
+ })?;
+ let application_surface = adapter.is_application_surface(entry.source.source_surface);
+ if application_surface || entry.source.is_process_owned() {
+ return Ok(match adapter.process_state(process, deadline)? {
+ ProcessState::Running => {
+ let app = application_from_ref(entry)?;
+ let owner = if application_surface {
+ SnapshotOwner::Application(app)
+ } else {
+ SnapshotOwner::Window(crate::WindowInfo::for_process(&app))
+ };
+ RefOwnerObservation::Present(owner)
+ }
+ state @ (ProcessState::Exited { .. } | ProcessState::Crashed { .. }) => {
+ RefOwnerObservation::Absent(Some(state))
+ }
+ ProcessState::Unresponsive => {
+ RefOwnerObservation::Unavailable(ProcessState::Unresponsive)
+ }
+ });
+ }
+ let expected = crate::WindowInfo {
+ id: entry.source.source_window_id.clone().ok_or_else(|| {
+ AdapterError::new(
+ crate::ErrorCode::ActionNotSupported,
+ "Ref has no source window for post-action observation",
+ )
+ })?,
+ title: entry.source.source_window_title.clone().unwrap_or_default(),
+ app: entry.source.source_app.clone().unwrap_or_default(),
+ pid: entry.process.pid,
+ process_instance: Some(process.instance.clone()),
+ bounds: None,
+ state: Default::default(),
+ };
+ match adapter.resolve_window_strict(&expected, deadline) {
+ Ok(window) => {
+ if window.id != expected.id
+ || window.pid != expected.pid
+ || window.process_instance != expected.process_instance
+ {
+ return Err(AdapterError::stale_ref_because(
+ "Original window identity changed during observation",
+ )
+ .into());
+ }
+ Ok(RefOwnerObservation::Present(SnapshotOwner::Window(window)))
+ }
+ Err(error) if error.code == crate::ErrorCode::WindowNotFound => {
+ let state = match adapter.process_state(process, deadline) {
+ Ok(state) => state,
+ Err(error) if error.is_default_not_supported("process_state") => {
+ return Ok(RefOwnerObservation::Absent(None));
+ }
+ Err(error) => return Err(error.into()),
+ };
+ Ok(RefOwnerObservation::Absent(match state {
+ ProcessState::Exited { .. } | ProcessState::Crashed { .. } => Some(state),
+ ProcessState::Running | ProcessState::Unresponsive => None,
+ }))
+ }
+ Err(error) => Err(error.into()),
+ }
+}
+
+pub(crate) fn application_from_ref(entry: &crate::RefEntry) -> Result<crate::AppInfo, AppError> {
+ Ok(crate::AppInfo {
+ name: entry.source.source_app.clone().ok_or_else(|| {
+ AdapterError::stale_ref_because("root ref has no application identity")
+ })?,
+ pid: entry.process.pid,
+ process_instance: entry.process.process_instance.clone(),
+ bundle_id: None,
+ presentation: None,
+ })
+}
+
+pub(crate) fn ref_observation_surface(
+ adapter: &dyn PlatformAdapter,
+ entry: &crate::RefEntry,
+) -> SnapshotSurface {
+ if adapter.is_application_surface(entry.source.source_surface)
+ || entry.source.is_process_owned()
+ {
+ entry.source.source_surface
+ } else {
+ SnapshotSurface::Window
+ }
+}
+
+pub(crate) fn is_confirmed_surface_absence(error: &AppError, surface: SnapshotSurface) -> bool {
+ matches!(error, AppError::Adapter(error) if error.is_confirmed_surface_absence(surface))
+}
diff --git a/crates/core/src/snapshot/tokenless_capture_support.rs b/crates/core/src/snapshot/tokenless_capture_support.rs
index d3fe6c9ee..5efd9bf9f 100644
--- a/crates/core/src/snapshot/tokenless_capture_support.rs
+++ b/crates/core/src/snapshot/tokenless_capture_support.rs
@@ -72,7 +72,7 @@ impl ObservationOps for CaptureAdapter {
request: &ObservationRequest,
) -> Result<ObservedTree, AdapterError> {
match root {
- ObservationRoot::Window(_) => {
+ ObservationRoot::Window(_) | ObservationRoot::Application { .. } => {
self.captures.fetch_add(1, Ordering::SeqCst);
let tree = self.tree.lock().expect("the fixture tree locks").clone();
let tree = cut(tree, 0, request.max_logical_depth);
diff --git a/crates/core/src/snapshot/window_capture.rs b/crates/core/src/snapshot/window_capture.rs
index a5a0fceca..c7d3b0f7d 100644
--- a/crates/core/src/snapshot/window_capture.rs
+++ b/crates/core/src/snapshot/window_capture.rs
@@ -1,5 +1,5 @@
use crate::{
- AppError, WindowInfo,
+ AppError, AppInfo, SnapshotOwner, WindowInfo,
adapter::{PlatformAdapter, TreeOptions},
locator::live_locator::{ObservationRequest, ObservationRoot, ObservedTree},
};
@@ -95,24 +95,121 @@ pub(crate) fn capture_window(
}
pub(crate) fn first_surface_owner<T>(
- windows: Vec<WindowInfo>,
- mut observe: impl FnMut(&WindowInfo) -> Result<T, AppError>,
-) -> Result<(WindowInfo, T), AppError> {
- let mut windows = windows.into_iter().peekable();
- while let Some(window) = windows.next() {
- match observe(&window) {
+ owners: Vec<SnapshotOwner>,
+ mut observe: impl FnMut(&SnapshotOwner) -> Result<T, AppError>,
+) -> Result<(SnapshotOwner, T), AppError> {
+ let mut owners = owners.into_iter().peekable();
+ while let Some(owner) = owners.next() {
+ match observe(&owner) {
Err(AppError::Adapter(error))
- if error.code == crate::ErrorCode::ElementNotFound && windows.peek().is_some() => {}
- result => return result.map(|observed| (window, observed)),
+ if error.code == crate::ErrorCode::ElementNotFound && owners.peek().is_some() => {}
+ result => return result.map(|observed| (owner, observed)),
}
}
Err(
- crate::AdapterError::new(crate::ErrorCode::WindowNotFound, "No window to observe")
+ crate::AdapterError::new(crate::ErrorCode::WindowNotFound, "No owner to observe")
.unsent()
.into(),
)
}
+pub(crate) fn capture_application(
+ adapter: &dyn PlatformAdapter,
+ opts: &TreeOptions,
+ app: &AppInfo,
+ surface: crate::SnapshotSurface,
+ deadline: crate::Deadline,
+) -> Result<WindowCapture, AppError> {
+ let depth = ObservationRequest::snapshot_logical_depth(opts);
+ let shallow = depth < crate::refs::resolve_saved_ref::WHOLE_WINDOW_DEPTH;
+ let mut unproven = None;
+ if shallow && !adapter.retains_element_tokens() {
+ let attempt = deadline.capped(deadline.remaining() * 3 / 4);
+ match whole_application(adapter, opts, app, surface, attempt) {
+ Ok(observed) => {
+ return Ok(WindowCapture {
+ observed,
+ presentation_depth: Some(depth),
+ identity_unproven: None,
+ });
+ }
+ Err(reason) => unproven = Some(reason),
+ }
+ }
+ let observed = observe_application(adapter, opts, app, surface, deadline)?;
+ if !needs_whole_window(&observed) {
+ return Ok(WindowCapture {
+ observed,
+ presentation_depth: None,
+ identity_unproven: None,
+ });
+ }
+ let unproven = match unproven {
+ Some(reason) => reason,
+ None if !shallow => "the application read was cut short".to_owned(),
+ None => match whole_application(adapter, opts, app, surface, deadline) {
+ Ok(whole) => {
+ return Ok(WindowCapture {
+ observed: whole,
+ presentation_depth: Some(depth),
+ identity_unproven: None,
+ });
+ }
+ Err(reason) => reason,
+ },
+ };
+ Ok(WindowCapture {
+ observed,
+ presentation_depth: None,
+ identity_unproven: Some(unproven),
+ })
+}
+
+fn whole_application(
+ adapter: &dyn PlatformAdapter,
+ opts: &TreeOptions,
+ app: &AppInfo,
+ surface: crate::SnapshotSurface,
+ deadline: crate::Deadline,
+) -> Result<ObservedTree, String> {
+ let options = TreeOptions {
+ max_depth: crate::refs::resolve_saved_ref::WHOLE_WINDOW_DEPTH,
+ skeleton: false,
+ ..*opts
+ }
+ .with_ref_identity_bounds();
+ let request = ObservationRequest::snapshot(&options, deadline)
+ .validate()
+ .map_err(|error| error.message)?;
+ match crate::tree::renderer_accessibility::observe_tree(
+ adapter,
+ ObservationRoot::Application { app, surface },
+ &request,
+ None,
+ ) {
+ Ok(observed) if observed.is_exhaustive() => Ok(observed),
+ Ok(_) => Err("the whole-application read was cut short".to_owned()),
+ Err(error) => Err(error.to_string()),
+ }
+}
+
+fn observe_application(
+ adapter: &dyn PlatformAdapter,
+ opts: &TreeOptions,
+ app: &AppInfo,
+ surface: crate::SnapshotSurface,
+ deadline: crate::Deadline,
+) -> Result<ObservedTree, AppError> {
+ let options = opts.with_ref_identity_bounds();
+ let request = ObservationRequest::snapshot(&options, deadline).validate()?;
+ crate::tree::renderer_accessibility::observe_tree(
+ adapter,
+ ObservationRoot::Application { app, surface },
+ &request,
+ None,
+ )
+}
+
/// The whole-window read that proves tokenless refs, or why it cannot.
fn whole_window(
adapter: &dyn PlatformAdapter,
diff --git a/crates/core/src/trace/trace_artifacts.rs b/crates/core/src/trace/trace_artifacts.rs
index 05ea36c2c..55145fe27 100644
--- a/crates/core/src/trace/trace_artifacts.rs
+++ b/crates/core/src/trace/trace_artifacts.rs
@@ -82,12 +82,7 @@ pub(crate) fn capture_action_screenshot(
else {
return ArtifactOutcome::Skipped("exact_target_unavailable".into());
};
- let Some(process_instance) = entry
- .process
- .process_instance
- .as_deref()
- .filter(|instance| !instance.is_empty())
- else {
+ let Some(process) = entry.process.identity() else {
return ArtifactOutcome::Skipped("exact_target_unavailable".into());
};
let Some(trace_dir) = session_trace_dir(context) else {
@@ -102,8 +97,8 @@ pub(crate) fn capture_action_screenshot(
id: window_id.into(),
title: entry.source.source_window_title.clone().unwrap_or_default(),
app: entry.source.source_app.clone().unwrap_or_default(),
- pid: entry.process.pid,
- process_instance: Some(process_instance.into()),
+ pid: process.pid,
+ process_instance: Some(process.instance),
bounds: None,
state: crate::WindowState {
is_focused: false,
diff --git a/crates/core/src/tree/renderer_accessibility.rs b/crates/core/src/tree/renderer_accessibility.rs
index a3a99b463..ff75a1a81 100644
--- a/crates/core/src/tree/renderer_accessibility.rs
+++ b/crates/core/src/tree/renderer_accessibility.rs
@@ -80,15 +80,15 @@ fn switch_on(
fn root_process(root: ObservationRoot<'_>) -> Result<crate::ProcessIdentity, AppError> {
match root {
- ObservationRoot::Window(window) => window
+ ObservationRoot::Application { app, .. } => app
.process_instance
.as_deref()
- .map(|instance| crate::ProcessIdentity::new(window.pid, instance)),
- ObservationRoot::Element { entry, .. } => entry
- .process
+ .map(|instance| crate::ProcessIdentity::new(app.pid, instance)),
+ ObservationRoot::Window(window) => window
.process_instance
.as_deref()
- .map(|instance| crate::ProcessIdentity::new(entry.process.pid, instance)),
+ .map(|instance| crate::ProcessIdentity::new(window.pid, instance)),
+ ObservationRoot::Element { entry, .. } => entry.process.identity(),
}
.ok_or_else(|| {
crate::AdapterError::stale_ref_because("renderer process instance is unavailable").into()
diff --git a/crates/ffi/include/agent_desktop.h b/crates/ffi/include/agent_desktop.h
index 6bb5f171a..fccc48471 100644
--- a/crates/ffi/include/agent_desktop.h
+++ b/crates/ffi/include/agent_desktop.h
@@ -1368,14 +1368,14 @@ AdResult ad_execute_by_ref_timeout(const struct AdAdapter *adapter,
char **out);
/**
- * Takes a full CLI-format snapshot of the target application window,
+ * Takes a full CLI-format snapshot of the target application surface,
* allocates snapshot-qualified refs (`@<snapshot_id>:eN`) for all
* interactive elements, persists the refmap to disk, and writes the JSON envelope into `*out`.
*
* The JSON shape matches `agent-desktop snapshot`:
* `{"version":"2.6","ok":true,"command":"snapshot","data":{"app":"...","window":{...},"ref_count":N,"snapshot_id":"...","complete":true,"tree":{...}}}`.
- * On macOS, `window` is omitted when a background app with no window is read
- * through its process.
+ * On macOS, `window` is omitted for application-owned menu and menubar surfaces
+ * and when a background app with no window is read through its process.
*
* `data.complete` is always present. A snapshot that exhausts its observation
* budget still succeeds with `"complete":false` and the tree it did observe,
@@ -1396,18 +1396,17 @@ AdResult ad_execute_by_ref_timeout(const struct AdAdapter *adapter,
* allocation is made. Only the last-error slot is set.
*
* `app` is tri-state:
- * - null — snapshot the currently focused window (same as running the command with no `--app`).
- * - valid UTF-8 string — snapshot the named application's focused window.
+ * - null — use the focused owner selected by `surface`.
+ * - valid UTF-8 string — use the named app's owner selected by `surface`.
* - non-null but invalid UTF-8 or exceeding `AD_MAX_STRING_BYTES` — returns `ErrInvalidArgs`.
*
- * `surface` is an `AdSnapshotSurface` discriminant (0 = Window, 1 = Focused, …).
+ * `surface` is an `AdSnapshotSurface` discriminant (0 = Window, 1 = Focused, …). On macOS,
+ * `Menu` and `Menubar` are application-owned surfaces and do not require an open window.
* An out-of-range value returns `ErrInvalidArgs`.
*
- * This entrypoint always targets the active focused window of the requested
- * application; explicit window targeting (`window_id`) is not yet exposed
- * over the ABI. Progressive traversal (skeleton mode and `--root` drill-down)
- * is likewise not exposed here. Both are planned fast-follows to this
- * entrypoint — agents needing them should use the CLI in the meantime.
+ * Window-owned snapshots include `data.window`; application-owned menu and menubar snapshots omit it.
+ * Explicit window targeting (`window_id`), skeleton mode and `--root` drill-down are not exposed
+ * over the ABI. Use the CLI when you need those options.
*
* **Dispatch-before-serialize ordering**: the snapshot and refmap persistence
* occur before the result JSON is serialised. In the near-impossible event
diff --git a/crates/ffi/src/commands/snapshot.rs b/crates/ffi/src/commands/snapshot.rs
index 1af33f1f6..ea0da0799 100644
--- a/crates/ffi/src/commands/snapshot.rs
+++ b/crates/ffi/src/commands/snapshot.rs
@@ -10,14 +10,14 @@ use agent_desktop_core::commands::snapshot::SnapshotArgs;
use std::ffi::c_char;
use std::ptr;
-/// Takes a full CLI-format snapshot of the target application window,
+/// Takes a full CLI-format snapshot of the target application surface,
/// allocates snapshot-qualified refs (`@<snapshot_id>:eN`) for all
/// interactive elements, persists the refmap to disk, and writes the JSON envelope into `*out`.
///
/// The JSON shape matches `agent-desktop snapshot`:
/// `{"version":"2.6","ok":true,"command":"snapshot","data":{"app":"...","window":{...},"ref_count":N,"snapshot_id":"...","complete":true,"tree":{...}}}`.
-/// On macOS, `window` is omitted when a background app with no window is read
-/// through its process.
+/// On macOS, `window` is omitted for application-owned menu and menubar surfaces
+/// and when a background app with no window is read through its process.
///
/// `data.complete` is always present. A snapshot that exhausts its observation
/// budget still succeeds with `"complete":false` and the tree it did observe,
@@ -38,18 +38,17 @@ use std::ptr;
/// allocation is made. Only the last-error slot is set.
///
/// `app` is tri-state:
-/// - null — snapshot the currently focused window (same as running the command with no `--app`).
-/// - valid UTF-8 string — snapshot the named application's focused window.
+/// - null — use the focused owner selected by `surface`.
+/// - valid UTF-8 string — use the named app's owner selected by `surface`.
/// - non-null but invalid UTF-8 or exceeding `AD_MAX_STRING_BYTES` — returns `ErrInvalidArgs`.
///
-/// `surface` is an `AdSnapshotSurface` discriminant (0 = Window, 1 = Focused, …).
+/// `surface` is an `AdSnapshotSurface` discriminant (0 = Window, 1 = Focused, …). On macOS,
+/// `Menu` and `Menubar` are application-owned surfaces and do not require an open window.
/// An out-of-range value returns `ErrInvalidArgs`.
///
-/// This entrypoint always targets the active focused window of the requested
-/// application; explicit window targeting (`window_id`) is not yet exposed
-/// over the ABI. Progressive traversal (skeleton mode and `--root` drill-down)
-/// is likewise not exposed here. Both are planned fast-follows to this
-/// entrypoint — agents needing them should use the CLI in the meantime.
+/// Window-owned snapshots include `data.window`; application-owned menu and menubar snapshots omit it.
+/// Explicit window targeting (`window_id`), skeleton mode and `--root` drill-down are not exposed
+/// over the ABI. Use the CLI when you need those options.
///
/// **Dispatch-before-serialize ordering**: the snapshot and refmap persistence
/// occur before the result JSON is serialised. In the near-impossible event
diff --git a/crates/linux/src/system/focus/key_dispatch.rs b/crates/linux/src/system/focus/key_dispatch.rs
index 0c76db2bf..015c3fa44 100644
--- a/crates/linux/src/system/focus/key_dispatch.rs
+++ b/crates/linux/src/system/focus/key_dispatch.rs
@@ -8,7 +8,7 @@ use crate::input::backend::Backend;
use crate::input::physical::target_keyboard::press_for_process;
use crate::input::physical::target_world::{LiveWorld, PhysicalWorld};
use crate::system::process::process_lookup::Lookup;
-use crate::system::window::window_ops::windows_of_process;
+use crate::system::window::window_ops::{require_complete_frames, windows_of_process};
use crate::system::x11::stacking::stacking_source::StackingSource;
use crate::system::x11::{DisplayReader, X11State};
use crate::system::{
@@ -47,9 +47,12 @@ impl KeyWorld for LiveKeys<'_> {
pid: u32,
deadline: Deadline,
) -> Result<Option<WindowInfo>, AdapterError> {
- Ok(windows_of_process(self.bus, pid, deadline)?
- .into_iter()
- .find(|window| window.state.is_focused))
+ let (windows, read) = windows_of_process(self.bus, pid, deadline)?;
+ let focused = windows.into_iter().find(|window| window.state.is_focused);
+ if focused.is_none() {
+ require_complete_frames(read)?;
+ }
+ Ok(focused)
}
fn active_client_pid(&self, deadline: Deadline) -> Option<u32> {
diff --git a/crates/linux/src/system/launch/launch_resident_live_tests.rs b/crates/linux/src/system/launch/launch_resident_live_tests.rs
index 8cc9badb9..e07686578 100644
--- a/crates/linux/src/system/launch/launch_resident_live_tests.rs
+++ b/crates/linux/src/system/launch/launch_resident_live_tests.rs
@@ -107,7 +107,7 @@ fn live_a_forwarded_launch_without_matching_argv_reports_the_residents_new_windo
wait_until("the initial native window", || x_windows_of(pid).len() == 1);
let before = x_windows_of(pid);
assert_eq!(before.len(), 1);
- let known = crate::system::window::window_ops::windows_of_process(
+ let (known, _) = crate::system::window::window_ops::windows_of_process(
&SharedBus::default(),
pid,
deadline(8_000),
diff --git a/crates/linux/src/system/launch/launch_tests.rs b/crates/linux/src/system/launch/launch_tests.rs
index 600658535..f115d2b51 100644
--- a/crates/linux/src/system/launch/launch_tests.rs
+++ b/crates/linux/src/system/launch/launch_tests.rs
@@ -316,8 +316,40 @@ fn the_window_read_after_an_activation_is_the_one_the_launch_chose() {
let mut chosen = window();
chosen.id = "w-chosen".to_owned();
chosen.state.is_focused = true;
- let reread = same_window(vec![first.clone(), chosen.clone()], "w-chosen").expect("chosen");
+ let reread = same_window(
+ Ok((vec![first.clone(), chosen.clone()], RootRead::Read)),
+ &chosen,
+ )
+ .expect("chosen");
assert_eq!(reread.id, "w-chosen");
assert!(reread.state.is_focused);
- assert!(same_window(vec![first], "w-chosen").is_none());
+ assert!(same_window(Ok((vec![first], RootRead::Read)), &chosen).is_none());
+}
+
+#[test]
+fn successful_focus_keeps_its_window_without_a_failure_note_when_refresh_is_unavailable() {
+ let original = window();
+ let mut reused = original.clone();
+ reused.process_instance = Some("another-generation".to_owned());
+ for observation in [
+ Ok((Vec::new(), RootRead::TimedOut)),
+ Ok((vec![original.clone()], RootRead::TimedOut)),
+ Err(AdapterError::timeout("refresh expired")),
+ Ok((vec![reused], RootRead::Read)),
+ ] {
+ let result = conclude(
+ &owner(),
+ Some(original.clone()),
+ &LaunchOptions {
+ activate: true,
+ ..options()
+ },
+ true,
+ |target| Ok(same_window(observation, target)),
+ );
+ let retained = result.window.unwrap();
+ assert_eq!(retained.id, original.id);
+ assert_eq!(retained.process_instance, original.process_instance);
+ assert!(result.suggestion.is_none());
+ }
}
diff --git a/crates/linux/src/system/launch/launch_window_tests.rs b/crates/linux/src/system/launch/launch_window_tests.rs
index 4b63b9d68..be5a1bce0 100644
--- a/crates/linux/src/system/launch/launch_window_tests.rs
+++ b/crates/linux/src/system/launch/launch_window_tests.rs
@@ -148,8 +148,10 @@ fn launch_window_lookup_never_enriches_an_unrelated_process() {
fn a_window_read_the_display_could_not_prove_is_read_again_and_the_window_is_reported() {
let calls = Cell::new(0);
let found = waiting_for_window(5_000, |launch, owner| {
- let mut reads =
- VecDeque::from([Err(unproven(owner.pid)), Ok(vec![window_of_owner(owner)])]);
+ let mut reads = VecDeque::from([
+ Err(unproven(owner.pid)),
+ Ok((vec![window_of_owner(owner)], RootRead::Read)),
+ ]);
launch
.wait_for_window(owner, true, &HashSet::new(), || {
calls.set(calls.get() + 1);
@@ -161,6 +163,74 @@ fn a_window_read_the_display_could_not_prove_is_read_again_and_the_window_is_rep
assert_eq!(calls.get(), 2);
}
+#[test]
+fn partial_process_windows_attach_when_present_and_never_report_unknown_absence() {
+ waiting_for_window(1_000, |launch, owner| {
+ let found = launch
+ .wait_for_window(owner, false, &HashSet::new(), || {
+ Ok((vec![window_of_owner(owner)], RootRead::TimedOut))
+ })
+ .expect("a returned target can be attached despite an unread sibling");
+ assert_eq!(found.unwrap().id, "w-proven");
+ });
+ for started in [false, true] {
+ let calls = Cell::new(0);
+ let error = waiting_for_window(100, |launch, owner| {
+ let known = HashSet::from(["w-proven".to_owned()]);
+ launch
+ .wait_for_window(owner, started, &known, || {
+ calls.set(calls.get() + 1);
+ Ok((vec![window_of_owner(owner)], RootRead::TimedOut))
+ })
+ .expect_err("an unread new window must not become None and authorize another spawn")
+ });
+ assert_eq!(error.code, ErrorCode::Timeout);
+ assert_eq!(error.details.unwrap()["kind"], "frames_unanswered");
+ assert_eq!(
+ error.disposition,
+ if started {
+ DeliverySemantics::delivered_unverified()
+ } else {
+ DeliverySemantics::not_delivered()
+ }
+ );
+ assert!(calls.get() > 1);
+ }
+ waiting_for_window(1_000, |launch, owner| {
+ assert!(
+ launch
+ .wait_for_window(owner, false, &HashSet::new(), || {
+ Ok((Vec::new(), RootRead::Read))
+ })
+ .unwrap()
+ .is_none()
+ );
+ });
+}
+
+#[test]
+fn transient_process_read_errors_cannot_authorize_another_launch() {
+ for code in [
+ ErrorCode::Timeout,
+ ErrorCode::AppUnresponsive,
+ ErrorCode::AppNotFound,
+ ErrorCode::WindowNotFound,
+ ] {
+ let error = waiting_for_window(100, |launch, owner| {
+ launch
+ .wait_for_window(owner, false, &HashSet::new(), || {
+ Err(AdapterError::new(
+ code.clone(),
+ "unavailable process windows",
+ ))
+ })
+ .expect_err("failed reads are not confirmed window absence")
+ });
+ assert_eq!(error.code, code);
+ assert_eq!(error.disposition, DeliverySemantics::not_delivered());
+ }
+}
+
#[test]
fn a_window_never_proven_ends_in_its_refusal_with_the_report_of_how_far_the_launch_went() {
for (started, delivery) in [
diff --git a/crates/linux/src/system/launch/mod.rs b/crates/linux/src/system/launch/mod.rs
index 4c6ac8664..63a0ce767 100644
--- a/crates/linux/src/system/launch/mod.rs
+++ b/crates/linux/src/system/launch/mod.rs
@@ -20,8 +20,9 @@ use crate::system::process::liveness::{Liveness, liveness};
use crate::system::process::process_facts;
use crate::system::process::running_app::Running;
use crate::system::process::web_family::WebFamily;
+use crate::system::registry::registry_frames::RootRead;
use crate::system::window::native_group::is_unproven;
-use crate::system::window::window_ops::windows_of_process;
+use crate::system::window::window_ops::{require_complete_frames, windows_of_process};
#[path = "launch_baseline.rs"]
mod baseline;
@@ -46,10 +47,20 @@ fn chromium_renderer(bus: &SharedBus, pid: u32, deadline: Deadline) -> Option<Re
.then_some(RendererKind::Chromium)
}
-/// The window with `id` among a fresh read of the owner's windows, so a result
-/// keeps the window the launch chose and focused, not the first one listed.
-fn same_window(windows: Vec<WindowInfo>, id: &str) -> Option<WindowInfo> {
- windows.into_iter().find(|window| window.id == id)
+/// Refreshes the same process-owned window after successful focus when a complete read is available.
+fn same_window(
+ observation: Result<(Vec<WindowInfo>, RootRead), AdapterError>,
+ expected: &WindowInfo,
+) -> Option<WindowInfo> {
+ let (windows, read) = observation.ok()?;
+ if read != RootRead::Read {
+ return None;
+ }
+ windows.into_iter().find(|window| {
+ window.id == expected.id
+ && window.pid == expected.pid
+ && window.process_instance == expected.process_instance
+ })
}
/// The result for an owner and its window. A window is brought forward once,
@@ -170,39 +181,43 @@ impl Launch<'_> {
owner: &Running,
waits: bool,
known: &HashSet<String>,
- mut read: impl FnMut() -> Result<Vec<WindowInfo>, AdapterError>,
+ mut read: impl FnMut() -> Result<(Vec<WindowInfo>, RootRead), AdapterError>,
) -> Result<Option<WindowInfo>, AdapterError> {
let limit = self.wait_limit(known);
- let mut unproven = None;
loop {
- match read() {
- Ok(windows) => {
- unproven = None;
- let own: Vec<WindowInfo> = windows
- .into_iter()
- .filter(|window| {
- window.pid.get() == owner.pid
- && window.process_instance.as_deref()
- == Some(owner.instance.as_str())
- })
- .collect();
- if let Some(window) = choose_window(own, known) {
- return Ok(Some(window));
- }
+ let observed = read().and_then(|(windows, status)| {
+ let own: Vec<WindowInfo> = windows
+ .into_iter()
+ .filter(|window| {
+ window.pid.get() == owner.pid
+ && window.process_instance.as_deref() == Some(owner.instance.as_str())
+ })
+ .collect();
+ let window = choose_window(own, known);
+ if window.is_none() {
+ require_complete_frames(status)?;
}
- Err(error) if is_unproven(&error) => unproven = Some(error),
+ Ok(window)
+ });
+ let unproven = match observed {
+ Ok(Some(window)) => return Ok(Some(window)),
+ Ok(None) => None,
Err(error)
- if matches!(
- error.code,
- ErrorCode::Timeout
- | ErrorCode::AppUnresponsive
- | ErrorCode::AppNotFound
- | ErrorCode::WindowNotFound
- ) => {}
+ if is_unproven(&error)
+ || matches!(
+ error.code,
+ ErrorCode::Timeout
+ | ErrorCode::AppUnresponsive
+ | ErrorCode::AppNotFound
+ | ErrorCode::WindowNotFound
+ ) =>
+ {
+ Some(error)
+ }
Err(error) => {
return Err(error.with_disposition(DeliverySemantics::delivered_unverified()));
}
- }
+ };
if waits {
exited_early(owner, liveness(owner.pid, &owner.instance))?;
}
@@ -240,9 +255,10 @@ impl Launch<'_> {
renderer: chromium_renderer(self.bus, owner.pid, self.deadline),
..conclude(owner, window, self.options, created, |window| {
focus_window(self.bus, window, self.lease)?;
- Ok(windows_of_process(self.bus, owner.pid, self.deadline)
- .ok()
- .and_then(|windows| same_window(windows, &window.id)))
+ Ok(same_window(
+ windows_of_process(self.bus, owner.pid, self.deadline),
+ window,
+ ))
})
}
}
diff --git a/crates/linux/src/system/window/window_ops.rs b/crates/linux/src/system/window/window_ops.rs
index 9aceeb552..2565fc52d 100644
--- a/crates/linux/src/system/window/window_ops.rs
+++ b/crates/linux/src/system/window/window_ops.rs
@@ -47,17 +47,26 @@ pub(crate) fn require_answered(
outcomes: &[AppOutcome],
named: bool,
) -> Result<Vec<ListedWindow>, AdapterError> {
- let unanswered = outcomes
- .iter()
- .any(|outcome| outcome.read == RootRead::TimedOut);
- if named && windows.is_empty() && unanswered {
+ if named
+ && windows.is_empty()
+ && outcomes
+ .iter()
+ .any(|outcome| outcome.read == RootRead::TimedOut)
+ {
+ require_complete_frames(RootRead::TimedOut)?;
+ }
+ Ok(windows)
+}
+
+pub(crate) fn require_complete_frames(read: RootRead) -> Result<(), AdapterError> {
+ if read == RootRead::TimedOut {
return Err(AdapterError::timeout(
"The application did not answer in time, so its windows could not be listed",
)
.with_details(json!({ "kind": "frames_unanswered" }))
.with_disposition(DeliverySemantics::not_delivered()));
}
- Ok(windows)
+ Ok(())
}
/// Lists top-level windows, marking the one the sources agree is focused.
@@ -112,19 +121,43 @@ pub(crate) fn windows_of_process(
bus: &SharedBus,
pid: u32,
deadline: Deadline,
-) -> Result<Vec<WindowInfo>, AdapterError> {
+) -> Result<(Vec<WindowInfo>, RootRead), AdapterError> {
let pending = x11::start(|| DisplayReader.read());
let desktops = x11::start(desktops::read);
let registry = read_registry_for(bus, Some(pid), deadline)?;
let select = |app: &RegistryApp| app.root.pid() == pid;
let finish = |deadline| pending.finish(deadline).unwrap_or(X11State::Unavailable);
let (mut pass, state) = run_pass_with(bus, &registry, select, finish, deadline)?;
- finish_listing(
- &mut pass,
+ pass.windows = settle_scoped(
+ pass.windows,
+ stopped_target(&registry, select, proc_stat::is_stopped),
+ )?;
+ Ok(finish_process_listing(
+ pass,
&state,
desktops.finish(deadline).flatten().as_ref(),
- );
- Ok(pass.windows.into_iter().map(|window| window.info).collect())
+ ))
+}
+
+fn finish_process_listing(
+ mut pass: Pass,
+ state: &X11State,
+ desktops: Option<&Desktops>,
+) -> (Vec<WindowInfo>, RootRead) {
+ let read = if pass
+ .outcomes
+ .iter()
+ .any(|outcome| outcome.read == RootRead::TimedOut)
+ {
+ RootRead::TimedOut
+ } else {
+ RootRead::Read
+ };
+ finish_listing(&mut pass, state, desktops);
+ (
+ pass.windows.into_iter().map(|window| window.info).collect(),
+ read,
+ )
}
/// The focused window, or none when the available sources do not agree.
diff --git a/crates/linux/src/system/window/window_ops_tests.rs b/crates/linux/src/system/window/window_ops_tests.rs
index 13ee252a7..bf7281199 100644
--- a/crates/linux/src/system/window/window_ops_tests.rs
+++ b/crates/linux/src/system/window/window_ops_tests.rs
@@ -1,6 +1,6 @@
use agent_desktop_core::{ErrorCode, WindowInfo, WindowState};
-use super::require_answered;
+use super::{finish_process_listing, require_answered};
use crate::system::registry::app_outcome::AppOutcome;
use crate::system::registry::listed_window::ListedWindow;
use crate::system::registry::registry_frames::RootRead;
@@ -139,3 +139,35 @@ fn the_windows_that_did_answer_are_listed_beside_an_unanswered_frame() {
.expect("the answered windows are kept");
assert_eq!(kept.len(), 1);
}
+
+#[test]
+fn process_inventory_keeps_windows_and_reports_any_unanswered_frames() {
+ for reads in [
+ vec![RootRead::Read, RootRead::Read],
+ vec![RootRead::Read, RootRead::TimedOut],
+ vec![RootRead::TimedOut, RootRead::Read],
+ ] {
+ for listed in [Vec::new(), vec![window("main", false, false)]] {
+ let expected_count = listed.len();
+ let outcomes = reads
+ .iter()
+ .enumerate()
+ .map(|(app, read)| AppOutcome { app, read: *read })
+ .collect();
+ let pass = pass_over_with_menu(
+ listed,
+ outcomes,
+ Vec::new(),
+ &X11State::Unavailable,
+ |_| Ok(false),
+ |_| false,
+ );
+ let (windows, read) = finish_process_listing(pass, &X11State::Unavailable, None);
+ assert_eq!(windows.len(), expected_count);
+ assert_eq!(
+ read == RootRead::TimedOut,
+ reads.contains(&RootRead::TimedOut)
+ );
+ }
+ }
+}
diff --git a/crates/linux/src/system/window/window_resolve.rs b/crates/linux/src/system/window/window_resolve.rs
index f057cb7a2..901765ad8 100644
--- a/crates/linux/src/system/window/window_resolve.rs
+++ b/crates/linux/src/system/window/window_resolve.rs
@@ -1,8 +1,9 @@
use agent_desktop_core::{AdapterError, Deadline, ErrorCode, WindowInfo};
use super::window_id;
-use super::window_ops::windows_of_process;
+use super::window_ops::{require_complete_frames, windows_of_process};
use crate::system::process::liveness::{Liveness, liveness};
+use crate::system::registry::registry_frames::RootRead;
use crate::system::{SharedBus, shell};
fn not_found(detail: &str) -> AdapterError {
@@ -18,7 +19,7 @@ fn not_found(detail: &str) -> AdapterError {
/// `APP_UNRESPONSIVE` for its application either way, never a closed window.
pub(crate) fn verify(
expected: &WindowInfo,
- live: Vec<WindowInfo>,
+ (live, read): (Vec<WindowInfo>, RootRead),
process: Liveness,
) -> Result<WindowInfo, AdapterError> {
if process == Liveness::Stopped {
@@ -35,6 +36,7 @@ pub(crate) fn verify(
));
};
let Some(found) = live.into_iter().find(|window| window.id == expected.id) else {
+ require_complete_frames(read)?;
return Err(not_found("The window is no longer open"));
};
if found.pid != expected.pid || found.process_instance.as_deref() != Some(instance) {
diff --git a/crates/linux/src/system/window/window_resolve_tests.rs b/crates/linux/src/system/window/window_resolve_tests.rs
index 0e03b8b6b..ef3b39596 100644
--- a/crates/linux/src/system/window/window_resolve_tests.rs
+++ b/crates/linux/src/system/window/window_resolve_tests.rs
@@ -1,6 +1,6 @@
use agent_desktop_core::{ErrorCode, WindowInfo, WindowState};
-use super::{Liveness, verify};
+use super::{Liveness, RootRead, verify};
fn window(id: &str, pid: u32, instance: Option<&str>, title: &str) -> WindowInfo {
WindowInfo {
@@ -19,7 +19,7 @@ fn a_live_window_with_the_same_process_resolves_even_when_retitled() {
let stored = window("w-1.2-a", 5, Some("b:1"), "Old title");
let live = vec![window("w-1.2-a", 5, Some("b:1"), "New title")];
assert_eq!(
- verify(&stored, live, Liveness::Alive)
+ verify(&stored, (live, RootRead::Read), Liveness::Alive)
.expect("resolves")
.title,
"New title"
@@ -31,7 +31,7 @@ fn a_different_pid_is_window_not_found() {
let stored = window("w-1.2-a", 5, Some("b:1"), "t");
let live = vec![window("w-1.2-a", 6, Some("b:1"), "t")];
assert_eq!(
- verify(&stored, live, Liveness::Alive)
+ verify(&stored, (live, RootRead::Read), Liveness::Alive)
.expect_err("refused")
.code,
ErrorCode::WindowNotFound
@@ -43,7 +43,7 @@ fn a_stored_window_without_a_process_instance_is_refused() {
let stored = window("w-1.2-a", 5, None, "t");
let live = vec![window("w-1.2-a", 5, Some("b:1"), "t")];
assert_eq!(
- verify(&stored, live, Liveness::Alive)
+ verify(&stored, (live, RootRead::Read), Liveness::Alive)
.expect_err("refused")
.code,
ErrorCode::StaleRef
@@ -54,7 +54,8 @@ fn a_stored_window_without_a_process_instance_is_refused() {
fn a_stopped_process_is_unresponsive_with_or_without_a_listed_window() {
let stored = window("w-1.2-a", 5, Some("b:1"), "t");
for live in [Vec::new(), vec![stored.clone()]] {
- let error = verify(&stored, live, Liveness::Stopped).expect_err("stopped");
+ let error =
+ verify(&stored, (live, RootRead::Read), Liveness::Stopped).expect_err("stopped");
assert_eq!(error.code, ErrorCode::AppUnresponsive);
assert!(error.message.contains("'a'"));
}
@@ -63,7 +64,7 @@ fn a_stopped_process_is_unresponsive_with_or_without_a_listed_window() {
#[test]
fn an_absent_window_of_a_gone_process_is_window_not_found() {
let stored = window("w-1.2-a", 5, Some("b:1"), "t");
- let error = verify(&stored, Vec::new(), Liveness::Gone).expect_err("gone");
+ let error = verify(&stored, (Vec::new(), RootRead::Read), Liveness::Gone).expect_err("gone");
assert_eq!(error.code, ErrorCode::WindowNotFound);
assert!(error.message.contains("no longer open"));
}
@@ -73,8 +74,34 @@ fn a_reused_process_id_keeps_the_different_process_refusal_while_the_process_ans
let stored = window("w-1.2-a", 5, Some("b:1"), "t");
for process in [Liveness::Alive, Liveness::Gone] {
let live = vec![window("w-1.2-a", 5, Some("b:2"), "t")];
- let error = verify(&stored, live, process).expect_err("refused");
+ let error = verify(&stored, (live, RootRead::Read), process).expect_err("refused");
assert_eq!(error.code, ErrorCode::WindowNotFound);
assert!(error.message.contains("different process"));
}
}
+
+#[test]
+fn an_unanswered_sibling_does_not_hide_a_verified_target_or_prove_its_absence() {
+ let stored = window("target", 5, Some("b:1"), "target");
+ let sibling = window("sibling", 5, Some("b:1"), "sibling");
+ let found = verify(
+ &stored,
+ (vec![stored.clone(), sibling.clone()], RootRead::TimedOut),
+ Liveness::Alive,
+ )
+ .expect("the observed target remains usable");
+ assert_eq!(found.id, stored.id);
+ for live in [Vec::new(), vec![sibling]] {
+ let unknown = verify(&stored, (live.clone(), RootRead::TimedOut), Liveness::Alive)
+ .expect_err("an unread frame cannot prove absence");
+ assert_eq!(unknown.code, ErrorCode::Timeout);
+ assert_eq!(unknown.details.unwrap()["kind"], "frames_unanswered");
+ assert_eq!(
+ unknown.disposition,
+ agent_desktop_core::DeliverySemantics::not_delivered()
+ );
+ let absent = verify(&stored, (live, RootRead::Read), Liveness::Alive)
+ .expect_err("the complete read proves absence");
+ assert_eq!(absent.code, ErrorCode::WindowNotFound);
+ }
+}
diff --git a/crates/linux/src/tree/observe/mod.rs b/crates/linux/src/tree/observe/mod.rs
index 9bfdbbe2b..21feed003 100644
--- a/crates/linux/src/tree/observe/mod.rs
+++ b/crates/linux/src/tree/observe/mod.rs
@@ -34,6 +34,9 @@ fn refuse_stopped(
fn root_element(root: &ObservationRoot<'_>) -> Result<AtspiElement, AdapterError> {
match root {
+ ObservationRoot::Application { .. } => {
+ Err(AdapterError::not_supported("application observation root"))
+ }
ObservationRoot::Window(window) if window.is_process_owner() => {
Err(AdapterError::app_has_no_window(&window.app))
}
diff --git a/crates/macos/src/actions/adapter.rs b/crates/macos/src/actions/adapter.rs
index 111e263c5..53b7421ff 100644
--- a/crates/macos/src/actions/adapter.rs
+++ b/crates/macos/src/actions/adapter.rs
@@ -1,11 +1,34 @@
use agent_desktop_core::{
Action, ActionOps, ActionResult, ActionStep, AdapterError, InteractionLease, NativeHandle,
- StepMechanism, actions::action_request::ActionRequest,
+ ObservationOps, StepMechanism, actions::action_request::ActionRequest,
};
use crate::adapter::{MacOSAdapter, ax_element};
impl ActionOps for MacOSAdapter {
+ fn headed_requirement_for_ref(
+ &self,
+ entry: &agent_desktop_core::RefEntry,
+ request: &ActionRequest,
+ deadline: agent_desktop_core::Deadline,
+ ) -> Result<agent_desktop_core::HeadedRequirement, AdapterError> {
+ crate::actions::native_menu::headed_requirement(request, || {
+ let handle = self.resolve_element_strict(entry, deadline)?;
+ crate::tree::native_menu::is_native_menu(ax_element(&handle)?, deadline)
+ })
+ }
+
+ fn headed_requirement(
+ &self,
+ handle: &NativeHandle,
+ request: &ActionRequest,
+ deadline: agent_desktop_core::Deadline,
+ ) -> Result<agent_desktop_core::HeadedRequirement, AdapterError> {
+ crate::actions::native_menu::headed_requirement(request, || {
+ crate::tree::native_menu::is_native_menu(ax_element(handle)?, deadline)
+ })
+ }
+
fn execute_action(
&self,
handle: &NativeHandle,
diff --git a/crates/macos/src/actions/chain/chain_defs.rs b/crates/macos/src/actions/chain/chain_defs.rs
index 0c44c8996..d60d8e86a 100644
--- a/crates/macos/src/actions/chain/chain_defs.rs
+++ b/crates/macos/src/actions/chain/chain_defs.rs
@@ -34,15 +34,15 @@ mod imp {
continue_after_unverified_delivery: false,
};
- static MENUBAR_CLICK_CHAIN: ChainDef = ChainDef {
+ static MENU_CLICK_CHAIN: ChainDef = ChainDef {
steps: &[ChainStep::Action("AXPress")],
- suggestion: "Refresh the menu-bar snapshot and target an item that supports AXPress.",
+ suggestion: "Refresh the menu snapshot and target an item that supports AXPress.",
continue_after_unverified_delivery: false,
};
- pub(crate) fn click_chain(native_role: Option<&str>) -> &'static ChainDef {
- if native_role == Some("AXMenuBarItem") {
- &MENUBAR_CLICK_CHAIN
+ pub(crate) fn click_chain(native_menu: bool) -> &'static ChainDef {
+ if native_menu {
+ &MENU_CLICK_CHAIN
} else {
&CLICK_CHAIN
}
diff --git a/crates/macos/src/actions/chain/chain_tests.rs b/crates/macos/src/actions/chain/chain_tests.rs
index 786841c59..c8f039df3 100644
--- a/crates/macos/src/actions/chain/chain_tests.rs
+++ b/crates/macos/src/actions/chain/chain_tests.rs
@@ -32,7 +32,7 @@ fn right_click_prefers_physical_input_before_semantic_fallbacks() {
#[test]
fn click_and_clear_prefer_physical_delivery_when_policy_allows_it() {
assert!(matches!(
- crate::actions::chain::chain_defs::click_chain(None)
+ crate::actions::chain::chain_defs::click_chain(false)
.steps
.first(),
Some(ChainStep::CGClick {
@@ -81,7 +81,7 @@ fn headless_chains_omit_physical_steps_before_reporting() {
#[test]
fn headed_menubar_click_uses_only_semantic_press_and_keeps_other_clicks_physical() {
- let menu = crate::actions::chain::chain_defs::click_chain(Some("AXMenuBarItem"));
+ let menu = crate::actions::chain::chain_defs::click_chain(true);
assert!(matches!(menu.steps, [ChainStep::Action("AXPress")]));
assert!(!menu.continue_after_unverified_delivery);
let mut steps = Vec::new();
@@ -104,24 +104,17 @@ fn headed_menubar_click_uses_only_semantic_press_and_keeps_other_clicks_physical
exhaustion_disposition(&unsupported),
agent_desktop_core::DeliverySemantics::not_delivered()
);
- for role in [
- None,
- Some("AXButton"),
- Some("AXMenuItem"),
- Some("AXMenuBar"),
- ] {
- assert!(matches!(
- crate::actions::chain::chain_defs::click_chain(role)
- .steps
- .first(),
- Some(ChainStep::CGClick { .. })
- ));
- }
+ assert!(matches!(
+ crate::actions::chain::chain_defs::click_chain(false)
+ .steps
+ .first(),
+ Some(ChainStep::CGClick { .. })
+ ));
}
#[test]
-fn click_role_probe_failure_falls_back_to_default_chain() {
- let fallback = crate::actions::chain::chain_defs::click_chain(None);
+fn targets_without_native_menu_provenance_keep_the_default_chain() {
+ let fallback = crate::actions::chain::chain_defs::click_chain(false);
assert!(matches!(
fallback.steps.first(),
Some(ChainStep::CGClick {
@@ -129,21 +122,15 @@ fn click_role_probe_failure_falls_back_to_default_chain() {
count: 1
})
));
- for unknown in [Some("AXUnknown"), Some(""), Some("AXButton")] {
- assert!(std::ptr::eq(
- fallback,
- crate::actions::chain::chain_defs::click_chain(unknown)
- ));
- }
assert!(!std::ptr::eq(
fallback,
- crate::actions::chain::chain_defs::click_chain(Some("AXMenuBarItem"))
+ crate::actions::chain::chain_defs::click_chain(true)
));
}
#[test]
fn the_click_chain_verifies_its_press_before_writing_a_selection() {
- let labels: Vec<&str> = crate::actions::chain::chain_defs::click_chain(None)
+ let labels: Vec<&str> = crate::actions::chain::chain_defs::click_chain(false)
.steps
.iter()
.map(|step| match step {
diff --git a/crates/macos/src/actions/dispatch.rs b/crates/macos/src/actions/dispatch.rs
index c1a09f409..6255f60cb 100644
--- a/crates/macos/src/actions/dispatch.rs
+++ b/crates/macos/src/actions/dispatch.rs
@@ -31,14 +31,12 @@ mod imp {
tracing::debug!("action: perform {label}");
match action {
Action::Click => {
- let role = if request.policy.is_headed() {
- probe_click_role(el, deadline)?
- } else {
- None
- };
+ let native_menu = crate::tree::native_menu::is_native_menu(el, deadline)?
+ || (request.policy.is_headed()
+ && probe_click_role(el, deadline)?.as_deref() == Some("AXMenuBarItem"));
steps.extend(run_chain(
el,
- chain_defs::click_chain(role.as_deref()),
+ chain_defs::click_chain(native_menu),
None,
request,
deadline,
diff --git a/crates/macos/src/actions/mod.rs b/crates/macos/src/actions/mod.rs
index d03382d39..366e7df89 100644
--- a/crates/macos/src/actions/mod.rs
+++ b/crates/macos/src/actions/mod.rs
@@ -8,6 +8,7 @@ pub(crate) mod chain;
pub(crate) mod delivery_tracker;
pub(crate) mod dispatch;
pub(crate) mod extras;
+mod native_menu;
mod physical_click;
mod physical_keyboard;
mod physical_target;
diff --git a/crates/macos/src/actions/native_menu.rs b/crates/macos/src/actions/native_menu.rs
new file mode 100644
index 000000000..9d4c1046d
--- /dev/null
+++ b/crates/macos/src/actions/native_menu.rs
@@ -0,0 +1,26 @@
+use agent_desktop_core::AdapterError;
+
+pub(crate) fn headed_requirement(
+ request: &agent_desktop_core::ActionRequest,
+ classify: impl FnOnce() -> Result<bool, AdapterError>,
+) -> Result<agent_desktop_core::HeadedRequirement, AdapterError> {
+ use agent_desktop_core::{Action, HeadedRequirement};
+ if request.policy.is_headed()
+ && matches!(
+ request.action,
+ Action::Click | Action::RightClick | Action::DoubleClick | Action::TripleClick
+ )
+ && classify()?
+ {
+ return Ok(if matches!(request.action, Action::Click) {
+ HeadedRequirement::FocusedApplication
+ } else {
+ HeadedRequirement::FocusedApplicationAndCursor
+ });
+ }
+ Ok(request.headed_requirement())
+}
+
+#[cfg(test)]
+#[path = "native_menu_tests.rs"]
+mod tests;
diff --git a/crates/macos/src/actions/native_menu_tests.rs b/crates/macos/src/actions/native_menu_tests.rs
new file mode 100644
index 000000000..abfcbb55d
--- /dev/null
+++ b/crates/macos/src/actions/native_menu_tests.rs
@@ -0,0 +1,51 @@
+use super::*;
+use agent_desktop_core::ErrorCode;
+
+#[test]
+fn headed_requirements_share_provenance_and_preserve_pointer_checks_for_gestures() {
+ use agent_desktop_core::{Action, ActionRequest, HeadedRequirement};
+ for action in [
+ Action::Click,
+ Action::RightClick,
+ Action::DoubleClick,
+ Action::TripleClick,
+ ] {
+ let request = ActionRequest::headed(action.clone());
+ let native = headed_requirement(&request, || Ok(true)).unwrap();
+ assert_eq!(
+ native,
+ if matches!(action, Action::Click) {
+ HeadedRequirement::FocusedApplication
+ } else {
+ HeadedRequirement::FocusedApplicationAndCursor
+ }
+ );
+ assert_eq!(native.requires_cursor(), !matches!(action, Action::Click));
+ assert_eq!(
+ headed_requirement(&request, || Ok(false)).unwrap(),
+ HeadedRequirement::FocusedWindowAndCursor
+ );
+ let error = headed_requirement(&request, || {
+ Err(AdapterError::stale_ref_because("identity changed"))
+ })
+ .unwrap_err();
+ assert_eq!(error.code, ErrorCode::StaleRef);
+ let headless = ActionRequest::headless(action);
+ assert_eq!(
+ headed_requirement(&headless, || panic!(
+ "headless requirement must not resolve"
+ ))
+ .unwrap(),
+ HeadedRequirement::None
+ );
+ }
+}
+
+#[test]
+fn non_pointer_headed_actions_do_not_probe_menu_ancestry() {
+ let request = agent_desktop_core::ActionRequest::headed(agent_desktop_core::Action::SetFocus);
+ assert_eq!(
+ headed_requirement(&request, || panic!("not a menu gesture")).unwrap(),
+ agent_desktop_core::HeadedRequirement::FocusedWindow
+ );
+}
diff --git a/crates/macos/src/actions/physical_target.rs b/crates/macos/src/actions/physical_target.rs
index 6d2719352..c9590ed25 100644
--- a/crates/macos/src/actions/physical_target.rs
+++ b/crates/macos/src/actions/physical_target.rs
@@ -5,6 +5,7 @@ use crate::tree::AXElement;
pub(crate) struct PreparedPhysicalTarget {
identity: crate::system::process::process_identity::ProcessIdentity,
window: Option<AXElement>,
+ focus_required: bool,
}
impl PreparedPhysicalTarget {
@@ -23,8 +24,18 @@ impl PreparedPhysicalTarget {
"Physical input target process exited before input preparation",
)
})?;
- let window = target_window(element, pid, deadline)?;
- let prepared = Self { identity, window };
+ let native_menu = crate::tree::native_menu::is_native_menu(element, deadline)?;
+ let window = if native_menu {
+ None
+ } else {
+ target_window(element, pid, deadline)?
+ };
+ let focus_required = native_menu || window.is_some();
+ let prepared = Self {
+ identity,
+ window,
+ focus_required,
+ };
prepared.verify_focus(deadline)?;
Ok(prepared)
}
@@ -32,11 +43,14 @@ impl PreparedPhysicalTarget {
/// Requires the app to be frontmost and the window main whenever the
/// target has a window that focus applies to.
fn verify_focus(&self, deadline: Deadline) -> Result<(), AdapterError> {
- let Some(window) = &self.window else {
+ if !self.focus_required {
return Ok(());
- };
+ }
crate::system::focus::verify_app_focused(self.identity.pid(), deadline)?;
- crate::system::focus::verify_window_main(window, deadline)
+ if let Some(window) = &self.window {
+ crate::system::focus::verify_window_main(window, deadline)?;
+ }
+ Ok(())
}
pub(crate) fn verify_pointer(
@@ -46,39 +60,10 @@ impl PreparedPhysicalTarget {
deadline: Deadline,
) -> Result<(), AdapterError> {
self.verify_focus(deadline)?;
- match crate::tree::hit_test::hit_test_ax_element(element, point.clone(), deadline)? {
- agent_desktop_core::adapter::hit_test::HitTestResult::ReachesTarget => {}
- agent_desktop_core::adapter::hit_test::HitTestResult::InterceptedBy {
- role,
- name,
- ..
- } => {
- return Err(AdapterError::new(
- ErrorCode::ActionFailed,
- "Physical input point is intercepted by another accessibility element",
- )
- .with_details(serde_json::json!({
- "physical_delivery_started": false,
- "occluder_role": role,
- "occluder_name": name,
- })));
- }
- agent_desktop_core::adapter::hit_test::HitTestResult::Unknown => {
- return Err(AdapterError::new(
- ErrorCode::ActionFailed,
- "Physical input target could not be proven at the final input point",
- )
- .with_details(serde_json::json!({ "physical_delivery_started": false })));
- }
- }
- if !self.identity.still_matches()? {
- return Err(AdapterError::new(
- ErrorCode::StaleRef,
- "Physical input target process instance changed at input delivery",
- )
- .with_details(serde_json::json!({ "physical_delivery_started": false })));
- }
- Ok(())
+ verify_pointer_identity(
+ crate::tree::hit_test::hit_test_ax_element(element, point.clone(), deadline),
+ || self.identity.still_matches(),
+ )
}
}
@@ -130,3 +115,44 @@ fn is_background_app(pid: i32, deadline: std::time::Instant) -> bool {
})
})
}
+
+fn verify_pointer_identity(
+ hit: Result<agent_desktop_core::HitTestResult, AdapterError>,
+ same_instance: impl FnOnce() -> Result<bool, AdapterError>,
+) -> Result<(), AdapterError> {
+ match hit? {
+ agent_desktop_core::adapter::hit_test::HitTestResult::ReachesTarget => {}
+ agent_desktop_core::adapter::hit_test::HitTestResult::InterceptedBy {
+ role, name, ..
+ } => {
+ return Err(AdapterError::new(
+ ErrorCode::ActionFailed,
+ "Physical input point is intercepted by another accessibility element",
+ )
+ .with_details(serde_json::json!({
+ "physical_delivery_started": false,
+ "occluder_role": role,
+ "occluder_name": name,
+ })));
+ }
+ agent_desktop_core::adapter::hit_test::HitTestResult::Unknown => {
+ return Err(AdapterError::new(
+ ErrorCode::ActionFailed,
+ "Physical input target could not be proven at the final input point",
+ )
+ .with_details(serde_json::json!({ "physical_delivery_started": false })));
+ }
+ }
+ if !same_instance()? {
+ return Err(AdapterError::new(
+ ErrorCode::StaleRef,
+ "Physical input target process instance changed at input delivery",
+ )
+ .with_details(serde_json::json!({ "physical_delivery_started": false })));
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+#[path = "physical_target_tests.rs"]
+mod tests;
diff --git a/crates/macos/src/actions/physical_target_tests.rs b/crates/macos/src/actions/physical_target_tests.rs
new file mode 100644
index 000000000..4d0daaaac
--- /dev/null
+++ b/crates/macos/src/actions/physical_target_tests.rs
@@ -0,0 +1,46 @@
+use super::*;
+use agent_desktop_core::HitTestResult;
+
+#[test]
+fn final_pointer_guard_requires_both_hit_target_and_same_generation() {
+ verify_pointer_identity(Ok(HitTestResult::ReachesTarget), || Ok(true)).unwrap();
+ let error =
+ verify_pointer_identity(Ok(HitTestResult::ReachesTarget), || Ok(false)).unwrap_err();
+ assert_eq!(error.code, ErrorCode::StaleRef);
+ assert_eq!(error.details.unwrap()["physical_delivery_started"], false);
+}
+
+#[test]
+fn final_pointer_guard_refuses_occluded_and_unknown_points() {
+ for hit in [
+ HitTestResult::Unknown,
+ HitTestResult::InterceptedBy {
+ role: Some("window".into()),
+ name: Some("occluder".into()),
+ bounds: None,
+ },
+ ] {
+ let error =
+ verify_pointer_identity(Ok(hit), || panic!("hit did not reach target")).unwrap_err();
+ assert_eq!(error.code, ErrorCode::ActionFailed);
+ assert_eq!(error.details.unwrap()["physical_delivery_started"], false);
+ }
+}
+
+#[test]
+fn final_pointer_guard_preserves_hit_test_and_identity_read_errors() {
+ for code in [
+ ErrorCode::PermDenied,
+ ErrorCode::Timeout,
+ ErrorCode::StaleRef,
+ ] {
+ let failure = AdapterError::new(code.clone(), "native read failed");
+ let error = verify_pointer_identity(Err(failure.clone()), || panic!("hit test failed"))
+ .unwrap_err();
+ assert_eq!(error.code, code);
+ let error =
+ verify_pointer_identity(Ok(HitTestResult::ReachesTarget), || Err(failure.clone()))
+ .unwrap_err();
+ assert_eq!(error.code, code);
+ }
+}
diff --git a/crates/macos/src/system/adapter.rs b/crates/macos/src/system/adapter.rs
index b36e1b0f6..a1a8d01d8 100644
--- a/crates/macos/src/system/adapter.rs
+++ b/crates/macos/src/system/adapter.rs
@@ -84,6 +84,22 @@ impl SystemOps for MacOSAdapter {
crate::system::focus::focus_window_impl(win, lease.deadline())
}
+ fn resolve_ref_focus_window(
+ &self,
+ entry: &agent_desktop_core::RefEntry,
+ deadline: Deadline,
+ ) -> Result<WindowInfo, AdapterError> {
+ crate::system::ref_focus_window::resolve(self, entry, deadline)
+ }
+
+ fn focus_app(
+ &self,
+ process: ProcessIdentity,
+ lease: &InteractionLease,
+ ) -> Result<(), AdapterError> {
+ crate::system::focus::focus_process(&process, lease.deadline())
+ }
+
fn launch_app(
&self,
id: &str,
diff --git a/crates/macos/src/system/app/workspace_apps.rs b/crates/macos/src/system/app/workspace_apps.rs
index ac7611f23..636c16f2d 100644
--- a/crates/macos/src/system/app/workspace_apps.rs
+++ b/crates/macos/src/system/app/workspace_apps.rs
@@ -1,10 +1,8 @@
use agent_desktop_core::{AdapterError, AppInfo, AppInventory, ErrorCode};
use serde::Deserialize;
use std::time::Instant;
-
const MAX_SNAPSHOT_BYTES: usize = 1024 * 1024;
const MAX_FIELD_BYTES: usize = 16 * 1024;
-
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub(crate) enum ActivationPolicy {
@@ -159,6 +157,16 @@ fn has_alias(bundle_id: &Option<String>, executable: &Option<String>, identifier
.any(|alias| alias.eq_ignore_ascii_case(identifier))
}
+pub(crate) fn focused_owner_until(deadline: Instant) -> Result<Option<WindowOwner>, AdapterError> {
+ ensure_before_deadline(deadline)?;
+ crate::system::cocoa_runtime::ensure_cocoa_multithreaded()?;
+ let bytes = crate::system::appkit_bridge::focused_snapshot_json()?;
+ ensure_before_deadline(deadline)?;
+ let snapshot = window_owner_snapshot_from_json(&bytes, deadline)?;
+ require_complete(&snapshot.skipped)?;
+ Ok(snapshot.frontmost().cloned())
+}
+
pub(crate) fn window_owner_snapshot_until(
deadline: Instant,
) -> Result<WindowOwnerSnapshot, AdapterError> {
diff --git a/crates/macos/src/system/appkit_bridge.m b/crates/macos/src/system/appkit_bridge.m
index d512200dd..b995cd841 100644
--- a/crates/macos/src/system/appkit_bridge.m
+++ b/crates/macos/src/system/appkit_bridge.m
@@ -123,7 +123,7 @@ static NSString *agent_desktop_application_name(NSRunningApplication *app) {
return name;
}
-AgentDesktopBytesResult agent_desktop_copy_workspace_snapshot_json(void) {
+AgentDesktopBytesResult agent_desktop_copy_workspace_snapshot_json(uint8_t frontmostOnly) {
AgentDesktopBytesResult result = {
.status = 5, .failureField = NULL, .failureIndex = -1,
.failurePID = 0, .bytes = NULL, .length = 0
@@ -131,8 +131,13 @@ AgentDesktopBytesResult agent_desktop_copy_workspace_snapshot_json(void) {
@try {
@autoreleasepool {
NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
- CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.001, false);
- NSArray<NSRunningApplication *> *running = workspace.runningApplications;
+ if ([NSThread isMainThread]) {
+ CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.001, false);
+ }
+ NSRunningApplication *observedFrontmost = workspace.frontmostApplication;
+ NSArray<NSRunningApplication *> *running = frontmostOnly == 0
+ ? workspace.runningApplications
+ : (observedFrontmost == nil ? @[] : @[observedFrontmost]);
if (running == nil || running.count > 8192) {
result.status = 1;
return result;
@@ -140,7 +145,7 @@ AgentDesktopBytesResult agent_desktop_copy_workspace_snapshot_json(void) {
NSMutableArray<NSDictionary *> *skipped = [NSMutableArray array];
int32_t frontmostPID = 0;
id frontmostLaunchTime = [NSNull null];
- NSRunningApplication *frontmost = workspace.frontmostApplication;
+ NSRunningApplication *frontmost = observedFrontmost;
if (frontmost != nil) {
if (![frontmost isKindOfClass:[NSRunningApplication class]]) {
[skipped addObject:@{@"pid": @0, @"field": @"frontmost_class"}];
@@ -272,3 +277,33 @@ AgentDesktopBytesResult agent_desktop_copy_workspace_snapshot_json(void) {
void agent_desktop_free_bridge_bytes(uint8_t *bytes) {
free(bytes);
}
+
+AgentDesktopTerminateResult agent_desktop_activate_application(
+ int32_t pid,
+ bool (*verifyIdentity)(void *),
+ void *context
+) {
+ AgentDesktopTerminateResult result = { .status = 4, .deliveryStarted = 0 };
+ @try {
+ @autoreleasepool {
+ NSRunningApplication *app =
+ [NSRunningApplication runningApplicationWithProcessIdentifier:pid];
+ if (app == nil || app.isTerminated) {
+ result.status = 1;
+ return result;
+ }
+ if (verifyIdentity == NULL || !verifyIdentity(context)) {
+ result.status = 5;
+ return result;
+ }
+ result.deliveryStarted = 1;
+ BOOL accepted = [app activateWithOptions:0];
+ result.status = accepted ? 0 : 2;
+ return result;
+ }
+ } @catch (NSException *exception) {
+ (void)exception;
+ result.status = 3;
+ return result;
+ }
+}
diff --git a/crates/macos/src/system/appkit_bridge.rs b/crates/macos/src/system/appkit_bridge.rs
index a53b278ce..d6090d104 100644
--- a/crates/macos/src/system/appkit_bridge.rs
+++ b/crates/macos/src/system/appkit_bridge.rs
@@ -96,7 +96,17 @@ pub(crate) fn ensure_cocoa_multithreaded() -> Result<(), String> {
#[cfg(target_os = "macos")]
pub(crate) fn workspace_snapshot_json() -> Result<Vec<u8>, AdapterError> {
- let result = unsafe { agent_desktop_copy_workspace_snapshot_json() };
+ copy_workspace_snapshot_json(0)
+}
+
+#[cfg(target_os = "macos")]
+pub(crate) fn focused_snapshot_json() -> Result<Vec<u8>, AdapterError> {
+ copy_workspace_snapshot_json(1)
+}
+
+#[cfg(target_os = "macos")]
+fn copy_workspace_snapshot_json(frontmost_only: u8) -> Result<Vec<u8>, AdapterError> {
+ let result = unsafe { agent_desktop_copy_workspace_snapshot_json(frontmost_only) };
let bytes = BridgeBytes(result.bytes);
if result.status != 0 {
return Err(workspace_snapshot_error(&result));
@@ -204,7 +214,7 @@ unsafe extern "C" {
) -> TerminateResult;
fn agent_desktop_app_finished_launching(pid: i32) -> i32;
fn agent_desktop_ensure_cocoa_multithreaded() -> u8;
- fn agent_desktop_copy_workspace_snapshot_json() -> BytesResult;
+ fn agent_desktop_copy_workspace_snapshot_json(frontmost_only: u8) -> BytesResult;
fn agent_desktop_free_bridge_bytes(bytes: *mut u8);
}
diff --git a/crates/macos/src/system/focus.rs b/crates/macos/src/system/focus.rs
index 2b078a355..b6a7d13aa 100644
--- a/crates/macos/src/system/focus.rs
+++ b/crates/macos/src/system/focus.rs
@@ -6,53 +6,174 @@ use std::time::{Duration, Instant};
#[cfg(target_os = "macos")]
const VERIFY_LIMIT: Duration = Duration::from_millis(500);
+#[cfg(target_os = "macos")]
+pub(crate) fn focused_app(
+ deadline: Deadline,
+) -> Result<Option<agent_desktop_core::AppInfo>, AdapterError> {
+ let Some(owner) = crate::system::app::workspace_apps::focused_owner_until(
+ crate::tree::locator_deadline::from_operation(deadline)?,
+ )?
+ else {
+ return Ok(None);
+ };
+ let identity = capture_identity(owner.pid)?;
+ if owner
+ .launch_time
+ .is_some_and(|time| identity.conflicts_with_launch_time(time))
+ {
+ return Err(AdapterError::stale_ref_because(
+ "Frontmost application changed process instance",
+ ));
+ }
+ if !is_frontmost(identity, deadline)? {
+ return Err(AdapterError::new(
+ ErrorCode::AppUnresponsive,
+ "Frontmost application changed during observation",
+ ));
+ }
+ Ok(Some(agent_desktop_core::AppInfo {
+ name: owner.name,
+ pid: crate::system::process::process_identity::from_pid_t(owner.pid)?,
+ bundle_id: owner.bundle_id,
+ process_instance: Some(identity.token()),
+ presentation: Some(match owner.activation_policy {
+ crate::system::app::workspace_apps::ActivationPolicy::Regular => {
+ agent_desktop_core::AppPresentation::Foreground
+ }
+ _ => agent_desktop_core::AppPresentation::Background,
+ }),
+ }))
+}
+
+#[cfg(target_os = "macos")]
+pub(crate) fn focus_process(
+ process: &agent_desktop_core::ProcessIdentity,
+ deadline: Deadline,
+) -> Result<(), AdapterError> {
+ let identity = crate::system::process::process_identity::require_core(process)
+ .map_err(before_activation)?;
+ focus_identity(identity, deadline).map(|_| ())
+}
+
#[cfg(target_os = "macos")]
pub(crate) fn ensure_app_focused(pid: i32, deadline: Deadline) -> Result<(), AdapterError> {
- focus_app(pid, deadline).map(|_| ())
+ focus_identity(capture_identity(pid)?, deadline).map(|_| ())
}
#[cfg(target_os = "macos")]
-fn focus_app(pid: i32, deadline: Deadline) -> Result<bool, AdapterError> {
- use core_foundation::{base::TCFType, boolean::CFBoolean, string::CFString};
+fn capture_identity(
+ pid: i32,
+) -> Result<crate::system::process::process_identity::ProcessIdentity, AdapterError> {
+ crate::system::process::process_identity::ProcessIdentity::capture(pid)?
+ .ok_or_else(|| AdapterError::stale_ref_because("Target application process exited"))
+}
- tracing::debug!("system: ensure app focused pid={pid}");
- let app = crate::tree::element_for_pid(pid);
- if read_frontmost(&app, deadline)? {
- return Ok(false);
+#[cfg(target_os = "macos")]
+fn is_frontmost(
+ identity: crate::system::process::process_identity::ProcessIdentity,
+ deadline: Deadline,
+) -> Result<bool, AdapterError> {
+ deadline.ensure_remaining()?;
+ require_same_process(identity)?;
+ let app = crate::tree::properties::element::element_for_pid(identity.pid());
+ let focused = read_boolean(&app, "AXFrontmost", deadline)?;
+ require_same_process(identity)?;
+ Ok(focused)
+}
+
+#[cfg(target_os = "macos")]
+fn require_same_process(
+ identity: crate::system::process::process_identity::ProcessIdentity,
+) -> Result<(), AdapterError> {
+ if identity.still_matches()? {
+ Ok(())
+ } else {
+ Err(AdapterError::stale_ref_because(
+ "Target process instance changed during focus verification",
+ ))
}
- prepare(&app, deadline)?;
- let attribute = CFString::new("AXFrontmost");
- let error = crate::tree::properties::ax_ipc::set_attribute_value(
- &app,
- attribute.as_concrete_TypeRef(),
- CFBoolean::true_value().as_CFTypeRef(),
- deadline,
- )?;
- finish_mutation(&app, error, "focus application", deadline)?;
- wait_until(
- &app,
- "AXFrontmost",
+}
+
+#[cfg(target_os = "macos")]
+fn focus_identity(
+ identity: crate::system::process::process_identity::ProcessIdentity,
+ deadline: Deadline,
+) -> Result<bool, AdapterError> {
+ focus_until(
deadline,
- "application did not become frontmost",
+ || is_frontmost(identity, deadline),
+ || {
+ crate::system::cocoa_runtime::ensure_cocoa_multithreaded()
+ .map_err(before_activation)?;
+ deadline.ensure_remaining().map_err(before_activation)?;
+ crate::system::focus_bridge::activate(identity)
+ },
)
- .map(|()| true)
- .map_err(after_delivery)
+}
+
+#[cfg(target_os = "macos")]
+fn focus_until(
+ deadline: Deadline,
+ mut is_frontmost: impl FnMut() -> Result<bool, AdapterError>,
+ activate: impl FnOnce() -> Result<bool, AdapterError>,
+) -> Result<bool, AdapterError> {
+ if is_frontmost().map_err(before_activation)? {
+ return Ok(false);
+ }
+ let delivered = activate()?;
+ let local_deadline = Instant::now() + VERIFY_LIMIT;
+ loop {
+ match is_frontmost() {
+ Ok(true) => return Ok(delivered),
+ Ok(false) => {}
+ Err(error) => {
+ return Err(if delivered {
+ after_delivery(error)
+ } else {
+ error
+ });
+ }
+ }
+ if Instant::now() >= local_deadline || deadline.is_expired() {
+ let error = AdapterError::timeout("Application did not become frontmost")
+ .with_details(serde_json::json!({ "kind": "focus_verification", "physical_delivery_started": false }));
+ return Err(if delivered {
+ after_delivery(error)
+ } else {
+ error
+ });
+ }
+ std::thread::sleep(deadline.remaining_slice(Duration::from_millis(5)).map_err(
+ |error| {
+ if delivered {
+ after_delivery(error)
+ } else {
+ error
+ }
+ },
+ )?);
+ }
}
#[cfg(target_os = "macos")]
pub(crate) fn verify_app_focused(pid: i32, deadline: Deadline) -> Result<(), AdapterError> {
- let app = crate::tree::element_for_pid(pid);
- if read_frontmost(&app, deadline)? {
+ verify_identity_focused(capture_identity(pid)?, deadline)
+}
+
+#[cfg(target_os = "macos")]
+fn verify_identity_focused(
+ identity: crate::system::process::process_identity::ProcessIdentity,
+ deadline: Deadline,
+) -> Result<(), AdapterError> {
+ let pid = identity.pid();
+ if is_frontmost(identity, deadline)? {
Ok(())
} else {
Err(AdapterError::new(
ErrorCode::ActionFailed,
"Target application lost focus before physical input delivery",
)
- .with_details(serde_json::json!({
- "pid": pid,
- "physical_delivery_started": false,
- }))
+ .with_details(serde_json::json!({ "pid": pid, "physical_delivery_started": false }))
.with_suggestion("Retry after ensuring the target application remains frontmost"))
}
}
@@ -62,14 +183,23 @@ pub(crate) fn focus_window_impl(
window: &WindowInfo,
deadline: Deadline,
) -> Result<(), AdapterError> {
- tracing::debug!("system: focus window");
- let pid = crate::system::process::process_identity::to_pid_t(window.pid)?;
+ let instance = window.process_instance.as_deref().ok_or_else(|| {
+ AdapterError::stale_ref_because("Window has no process-instance identity")
+ })?;
+ let identity = crate::system::process::process_identity::require_core(
+ &agent_desktop_core::ProcessIdentity::new(window.pid, instance),
+ )?;
let element = crate::system::window::window_resolve::window_element_for_info(window, deadline)?;
- let focused = focus_app(pid, deadline)?;
+ let focused = focus_identity(identity, deadline)?;
crate::system::window::window_ops::raise_window(&element, deadline).map_err(|error| {
crate::actions::DeliveryTracker::from_delivered_units(usize::from(focused)).annotate(error)
})?;
- verify_app_focused(pid, deadline).map_err(after_delivery)
+ if !identity.still_matches().map_err(after_delivery)? {
+ return Err(after_delivery(AdapterError::stale_ref_because(
+ "Target window process instance changed while focusing",
+ )));
+ }
+ verify_identity_focused(identity, deadline).map_err(after_delivery)
}
#[cfg(target_os = "macos")]
@@ -97,11 +227,6 @@ pub(crate) fn verify_window_main(
}
}
-#[cfg(target_os = "macos")]
-fn read_frontmost(app: &crate::tree::AXElement, deadline: Deadline) -> Result<bool, AdapterError> {
- read_boolean(app, "AXFrontmost", deadline)
-}
-
#[cfg(target_os = "macos")]
fn read_boolean(
element: &crate::tree::AXElement,
@@ -203,6 +328,11 @@ pub(crate) fn map_ax_read_error(error: i32, operation: &str) -> AdapterError {
.with_disposition(DeliverySemantics::not_delivered())
}
+#[cfg(target_os = "macos")]
+fn before_activation(error: AdapterError) -> AdapterError {
+ error.with_disposition(DeliverySemantics::not_delivered())
+}
+
#[cfg(target_os = "macos")]
fn after_delivery(error: AdapterError) -> AdapterError {
error.with_disposition(DeliverySemantics::delivered_unverified())
@@ -220,3 +350,7 @@ pub(crate) fn focus_window_impl(
) -> Result<(), AdapterError> {
Err(AdapterError::not_supported("focus_window"))
}
+
+#[cfg(test)]
+#[path = "focus_tests.rs"]
+mod tests;
diff --git a/crates/macos/src/system/focus_bridge.rs b/crates/macos/src/system/focus_bridge.rs
new file mode 100644
index 000000000..ba9884c75
--- /dev/null
+++ b/crates/macos/src/system/focus_bridge.rs
@@ -0,0 +1,98 @@
+use agent_desktop_core::{AdapterError, DeliverySemantics, ErrorCode};
+
+use crate::system::process::process_identity::ProcessIdentity;
+
+#[repr(C)]
+struct ActivationResult {
+ status: u8,
+ delivery_started: u8,
+}
+
+struct ActivationContext {
+ identity: ProcessIdentity,
+ failure: Option<AdapterError>,
+}
+
+#[cfg(target_os = "macos")]
+extern "C" fn verify_identity(context: *mut std::ffi::c_void) -> bool {
+ let context = unsafe { &mut *context.cast::<ActivationContext>() };
+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ match context.identity.still_matches() {
+ Ok(true) => true,
+ Ok(false) => {
+ context.failure = Some(AdapterError::stale_ref_because(
+ "Target process instance changed before activation",
+ ));
+ false
+ }
+ Err(error) => {
+ context.failure = Some(error);
+ false
+ }
+ }
+ }))
+ .unwrap_or(false)
+}
+
+#[cfg(target_os = "macos")]
+pub(crate) fn activate(identity: ProcessIdentity) -> Result<bool, AdapterError> {
+ let mut context = ActivationContext {
+ identity,
+ failure: None,
+ };
+ let result = unsafe {
+ agent_desktop_activate_application(
+ identity.pid(),
+ verify_identity,
+ (&mut context as *mut ActivationContext).cast(),
+ )
+ };
+ finish_activation(result, context.failure)
+}
+
+fn finish_activation(
+ result: ActivationResult,
+ failure: Option<AdapterError>,
+) -> Result<bool, AdapterError> {
+ if let Some(error) = failure {
+ return Err(error.with_disposition(DeliverySemantics::not_delivered()));
+ }
+ let disposition = if result.delivery_started != 0 {
+ DeliverySemantics::uncertain()
+ } else {
+ DeliverySemantics::not_delivered()
+ };
+ match result.status {
+ 0 => Ok(result.delivery_started != 0),
+ 1 | 5 => Err(AdapterError::stale_ref_because(
+ "Target application changed before activation",
+ )
+ .with_disposition(disposition)),
+ 2 => Err(AdapterError::new(
+ ErrorCode::ActionFailed,
+ "macOS did not accept the application activation request",
+ )
+ .with_disposition(DeliverySemantics::not_delivered())),
+ status => Err(AdapterError::new(
+ ErrorCode::AppUnresponsive,
+ "The macOS AppKit bridge failed during application activation",
+ )
+ .with_details(serde_json::json!({
+ "kind": "appkit_bridge", "operation": "activation", "status": status,
+ }))
+ .with_disposition(disposition)),
+ }
+}
+
+#[cfg(target_os = "macos")]
+unsafe extern "C" {
+ fn agent_desktop_activate_application(
+ pid: i32,
+ verify_identity: extern "C" fn(*mut std::ffi::c_void) -> bool,
+ context: *mut std::ffi::c_void,
+ ) -> ActivationResult;
+}
+
+#[cfg(test)]
+#[path = "focus_bridge_tests.rs"]
+mod tests;
diff --git a/crates/macos/src/system/focus_bridge_tests.rs b/crates/macos/src/system/focus_bridge_tests.rs
new file mode 100644
index 000000000..4b339da96
--- /dev/null
+++ b/crates/macos/src/system/focus_bridge_tests.rs
@@ -0,0 +1,50 @@
+use super::*;
+
+fn result(status: u8, started: bool) -> ActivationResult {
+ ActivationResult {
+ status,
+ delivery_started: u8::from(started),
+ }
+}
+
+#[test]
+fn bridge_maps_native_status_and_delivery_evidence() {
+ for started in [false, true] {
+ assert_eq!(
+ finish_activation(result(0, started), None).unwrap(),
+ started
+ );
+ for (status, code) in [
+ (1, ErrorCode::StaleRef),
+ (5, ErrorCode::StaleRef),
+ (2, ErrorCode::ActionFailed),
+ (3, ErrorCode::AppUnresponsive),
+ (4, ErrorCode::AppUnresponsive),
+ (255, ErrorCode::AppUnresponsive),
+ ] {
+ let error = finish_activation(result(status, started), None).unwrap_err();
+ assert_eq!(error.code, code);
+ assert_eq!(
+ error.disposition,
+ if started && status != 2 {
+ DeliverySemantics::uncertain()
+ } else {
+ DeliverySemantics::not_delivered()
+ }
+ );
+ if code == ErrorCode::AppUnresponsive {
+ assert_eq!(error.details.unwrap()["status"], status);
+ }
+ }
+ }
+}
+
+#[test]
+fn identity_callback_error_overrides_bridge_status_without_losing_details() {
+ let failure = AdapterError::new(ErrorCode::PermDenied, "process identity unavailable")
+ .with_details(serde_json::json!({ "identity": "unreadable" }));
+ let error = finish_activation(result(5, false), Some(failure.clone())).unwrap_err();
+ assert_eq!(error.code, failure.code);
+ assert_eq!(error.details, failure.details);
+ assert_eq!(error.disposition, DeliverySemantics::not_delivered());
+}
diff --git a/crates/macos/src/system/focus_tests.rs b/crates/macos/src/system/focus_tests.rs
new file mode 100644
index 000000000..a7a92b262
--- /dev/null
+++ b/crates/macos/src/system/focus_tests.rs
@@ -0,0 +1,115 @@
+use super::*;
+use std::cell::Cell;
+
+#[test]
+fn already_frontmost_does_not_activate() {
+ assert!(
+ !focus_until(
+ Deadline::standard().unwrap(),
+ || Ok(true),
+ || panic!("already focused")
+ )
+ .unwrap()
+ );
+}
+
+#[test]
+fn activation_requires_frontmost_readback() {
+ let activated = Cell::new(false);
+ let reads = Cell::new(0);
+ let delivered = focus_until(
+ Deadline::standard().unwrap(),
+ || {
+ reads.set(reads.get() + 1);
+ Ok(activated.get())
+ },
+ || {
+ activated.set(true);
+ Ok(true)
+ },
+ )
+ .unwrap();
+ assert!(delivered);
+ assert_eq!(reads.get(), 2);
+}
+
+#[test]
+fn identity_and_permission_errors_before_activation_prevent_delivery() {
+ for code in [
+ ErrorCode::StaleRef,
+ ErrorCode::PermDenied,
+ ErrorCode::Timeout,
+ ] {
+ let error = focus_until(
+ Deadline::standard().unwrap(),
+ || Err(AdapterError::new(code.clone(), "read failed")),
+ || panic!("must not activate"),
+ )
+ .unwrap_err();
+ assert_eq!(error.code, code);
+ assert_eq!(error.disposition, DeliverySemantics::not_delivered());
+ }
+}
+
+#[test]
+fn failed_verification_preserves_delivery_and_original_error() {
+ for delivered in [false, true] {
+ let reads = Cell::new(0);
+ let error = focus_until(
+ Deadline::standard().unwrap(),
+ || {
+ reads.set(reads.get() + 1);
+ if reads.get() == 1 {
+ Ok(false)
+ } else {
+ Err(AdapterError::stale_ref_because("process restarted"))
+ }
+ },
+ || Ok(delivered),
+ )
+ .unwrap_err();
+ assert_eq!(error.code, ErrorCode::StaleRef);
+ assert_eq!(
+ error.disposition,
+ if delivered {
+ DeliverySemantics::delivered_unverified()
+ } else {
+ AdapterError::stale_ref_because("process restarted").disposition
+ }
+ );
+ }
+}
+
+#[test]
+fn frontmost_verification_timeout_preserves_activation_delivery() {
+ for delivered in [false, true] {
+ let deadline = Deadline::after(100).unwrap();
+ let reads = Cell::new(0);
+ let error = focus_until(
+ deadline,
+ || {
+ reads.set(reads.get() + 1);
+ Ok(false)
+ },
+ || {
+ std::thread::sleep(deadline.remaining());
+ Ok(delivered)
+ },
+ )
+ .unwrap_err();
+ assert_eq!(reads.get(), 2);
+ assert_eq!(error.code, ErrorCode::Timeout);
+ assert_eq!(
+ error.details.as_ref().unwrap()["kind"],
+ "focus_verification"
+ );
+ assert_eq!(
+ error.disposition,
+ if delivered {
+ DeliverySemantics::delivered_unverified()
+ } else {
+ AdapterError::timeout("").disposition
+ }
+ );
+ }
+}
diff --git a/crates/macos/src/system/mod.rs b/crates/macos/src/system/mod.rs
index 17ef849c7..2861ce972 100644
--- a/crates/macos/src/system/mod.rs
+++ b/crates/macos/src/system/mod.rs
@@ -6,6 +6,7 @@ pub(crate) mod cursor_overlay;
pub(crate) mod display;
pub(crate) mod display_work_area;
pub(crate) mod focus;
+pub(crate) mod focus_bridge;
pub(crate) mod key_dispatch;
pub(crate) mod launch;
pub(crate) mod launch_callback_result;
@@ -13,6 +14,7 @@ pub(crate) mod launch_completion;
pub(crate) mod launch_workspace;
pub(crate) mod permissions;
pub(crate) mod process;
+pub(crate) mod ref_focus_window;
pub(crate) mod renderer_activation;
pub(crate) mod renderer_kind;
pub(crate) mod screenshot;
diff --git a/crates/macos/src/system/ref_focus_window.rs b/crates/macos/src/system/ref_focus_window.rs
new file mode 100644
index 000000000..8c3b6d8b3
--- /dev/null
+++ b/crates/macos/src/system/ref_focus_window.rs
@@ -0,0 +1,120 @@
+use agent_desktop_core::{
+ AdapterError, Deadline, ErrorCode, ObservationOps, RefEntry, SnapshotSurface, WindowInfo,
+};
+
+use crate::adapter::MacOSAdapter;
+
+pub(crate) fn resolve(
+ adapter: &MacOSAdapter,
+ entry: &RefEntry,
+ deadline: Deadline,
+) -> Result<WindowInfo, AdapterError> {
+ if entry.source.source_window_id.is_some()
+ || entry.source.source_surface != SnapshotSurface::Menu
+ {
+ return agent_desktop_core::saved_ref_focus_window(entry);
+ }
+ let instance = entry
+ .process
+ .process_instance
+ .as_deref()
+ .filter(|value| !value.is_empty())
+ .ok_or_else(missing_owner)?;
+ let identity = crate::system::process::process_identity::require_core(
+ &agent_desktop_core::ProcessIdentity::new(entry.process.pid, instance),
+ )?;
+ let handle = adapter.resolve_element_strict(entry, deadline)?;
+ let target = crate::adapter::ax_element(&handle)?;
+ let instant = crate::tree::locator_deadline::from_operation(deadline)?;
+ let window = owning_window(target, identity.pid(), deadline)?;
+ let number =
+ crate::system::window::window_resolve::ax_window_id_with_deadline(&window, instant)?
+ .filter(|number| *number > 0)
+ .ok_or_else(missing_owner)?;
+ let expected = WindowInfo {
+ id: format!("w-{number}"),
+ title: String::new(),
+ app: String::new(),
+ pid: entry.process.pid,
+ process_instance: Some(instance.to_string()),
+ bounds: None,
+ state: Default::default(),
+ };
+ if !identity.still_matches()? {
+ return Err(AdapterError::stale_ref_because(
+ "Ref focus window identity changed",
+ ));
+ }
+ Ok(expected)
+}
+
+pub(crate) fn owning_window(
+ target: &crate::tree::AXElement,
+ expected_pid: i32,
+ deadline: Deadline,
+) -> Result<crate::tree::AXElement, AdapterError> {
+ let instant = crate::tree::locator_deadline::from_operation(deadline)?;
+ let window = find_window(
+ target.clone(),
+ |element| crate::tree::surface_read::string(element, "AXRole", instant),
+ |element, attribute| crate::tree::surface_read::element(element, attribute, instant),
+ )?
+ .ok_or_else(missing_owner)?;
+ let pid = crate::tree::properties::ax_ipc::pid(&window, instant).map_err(pid_read_error)?;
+ if pid != expected_pid {
+ return Err(AdapterError::stale_ref_because(
+ "Input target window belongs to another process",
+ ));
+ }
+ Ok(window)
+}
+
+fn find_window<T>(
+ target: T,
+ mut role: impl FnMut(&T) -> Result<Option<String>, AdapterError>,
+ mut read: impl FnMut(&T, &str) -> Result<Option<T>, AdapterError>,
+) -> Result<Option<T>, AdapterError> {
+ let mut current = Some(target);
+ for _ in 0..32 {
+ let Some(element) = current else {
+ return Ok(None);
+ };
+ if role(&element)?.as_deref() == Some("AXWindow") {
+ return Ok(Some(element));
+ }
+ if let Some(window) = read(&element, "AXWindow")? {
+ if role(&window)?.as_deref() != Some("AXWindow") {
+ return Err(missing_owner());
+ }
+ return Ok(Some(window));
+ }
+ current = read(&element, "AXParent")?;
+ }
+ Err(AdapterError::new(
+ ErrorCode::ActionNotSupported,
+ "Ref focus window ancestry exceeded its bounded search",
+ ))
+}
+
+fn pid_read_error(error: i32) -> AdapterError {
+ let code = match error {
+ accessibility_sys::kAXErrorAPIDisabled => ErrorCode::PermDenied,
+ accessibility_sys::kAXErrorCannotComplete => ErrorCode::Timeout,
+ accessibility_sys::kAXErrorInvalidUIElement => ErrorCode::StaleRef,
+ _ => ErrorCode::ActionFailed,
+ };
+ AdapterError::new(code, "Could not verify ref focus window process")
+ .with_details(serde_json::json!({ "ax_error": error, "physical_delivery_started": false }))
+}
+
+fn missing_owner() -> AdapterError {
+ AdapterError::new(
+ ErrorCode::ActionNotSupported,
+ "Headed input requires a verified live owning AXWindow",
+ )
+ .with_details(serde_json::json!({ "physical_delivery_started": false }))
+}
+
+#[cfg(test)]
+#[path = "ref_focus_window_tests.rs"]
+mod tests;
diff --git a/crates/macos/src/system/ref_focus_window_tests.rs b/crates/macos/src/system/ref_focus_window_tests.rs
new file mode 100644
index 000000000..214f7087a
--- /dev/null
+++ b/crates/macos/src/system/ref_focus_window_tests.rs
@@ -0,0 +1,56 @@
+use super::*;
+
+#[test]
+fn live_window_recovery_uses_exact_attribute_or_ancestor() {
+ for direct in [true, false] {
+ let window = find_window(
+ 0,
+ |node| {
+ Ok(Some(
+ if *node == 2 { "AXWindow" } else { "AXMenuItem" }.into(),
+ ))
+ },
+ |node, attr| {
+ Ok(match (*node, attr, direct) {
+ (0, "AXWindow", true) => Some(2),
+ (0, "AXParent", false) => Some(1),
+ (1, "AXWindow", false) => Some(2),
+ _ => None,
+ })
+ },
+ )
+ .unwrap();
+ assert_eq!(window, Some(2));
+ }
+}
+
+#[test]
+fn missing_unknown_or_cyclic_ownership_cannot_select_a_window() {
+ assert_eq!(find_window(0, |_| Ok(None), |_, _| Ok(None)).unwrap(), None);
+ assert!(find_window(0, |_| Ok(Some("AXMenu".into())), |_, _| Ok(Some(1))).is_err());
+ assert!(
+ find_window(
+ 0,
+ |_| Ok(None),
+ |_, attr| Ok((attr == "AXParent").then_some(0))
+ )
+ .is_err()
+ );
+}
+
+#[test]
+fn ownership_reads_preserve_native_failures() {
+ for code in [
+ ErrorCode::PermDenied,
+ ErrorCode::Timeout,
+ ErrorCode::StaleRef,
+ ] {
+ let error = find_window(
+ 0,
+ |_| Ok(None),
+ |_, _| Err(AdapterError::new(code.clone(), "read failed")),
+ )
+ .unwrap_err();
+ assert_eq!(error.code, code);
+ }
+}
diff --git a/crates/macos/src/system/signals.rs b/crates/macos/src/system/signals.rs
index 52c17d0ea..14b2ee805 100644
--- a/crates/macos/src/system/signals.rs
+++ b/crates/macos/src/system/signals.rs
@@ -125,24 +125,19 @@ fn surfaces_for_apps(
let mut surfaces = Vec::new();
for app in apps {
ensure_before_deadline(deadline)?;
- let pid = crate::system::process::process_identity::to_pid_t(app.pid)?;
- for info in crate::tree::surface_inventory::list_surfaces_for_pid(pid, deadline)? {
+ let instance = app.process_instance.as_deref().ok_or_else(|| {
+ AdapterError::stale_ref_because("Surface owner lacks a process instance")
+ })?;
+ let identity = crate::system::process::process_identity::require_core(
+ &agent_desktop_core::ProcessIdentity::new(app.pid, instance),
+ )?;
+ for info in crate::tree::surface_inventory::list_surfaces_for_process(identity, deadline)? {
if let Some(kind) = map_surface_kind(&info.kind) {
- let process_instance = app.process_instance.clone().ok_or_else(|| {
- AdapterError::new(
- agent_desktop_core::ErrorCode::AppUnresponsive,
- "Surface owner lacks a verified process instance",
- )
- .with_details(serde_json::json!({
- "pid": app.pid,
- "complete": false,
- }))
- })?;
surfaces.push(SurfaceSignal {
kind,
app: app.name.clone(),
pid: app.pid,
- process_instance,
+ process_instance: instance.to_owned(),
id: info.id,
title: info.title,
});
diff --git a/crates/macos/src/system/window/window_resolve.rs b/crates/macos/src/system/window/window_resolve.rs
index 81dc00316..aadd63779 100644
--- a/crates/macos/src/system/window/window_resolve.rs
+++ b/crates/macos/src/system/window/window_resolve.rs
@@ -151,26 +151,22 @@ pub(crate) fn parse_window_number(id: &str) -> Option<i64> {
fn verify_window_record(win: &WindowInfo, record: &WindowRecord) -> Result<(), AdapterError> {
let pid = crate::system::process::process_identity::to_pid_t(win.pid)?;
- if record.pid != pid {
+ let evidence = WindowIdentityEvidence {
+ pid,
+ app: Some(&win.app),
+ process_instance: win.process_instance.as_deref(),
+ title: Some(&win.title),
+ bounds_hash: None,
+ };
+ if !window_record_matches_source(record, &evidence) {
return Err(window_identity_mismatch(&win.id));
}
- let Some(instance) = win.process_instance.as_deref() else {
+ let Some(instance) = evidence.process_instance else {
return Err(window_identity_mismatch(&win.id));
};
- if record.process_instance.as_deref() != Some(instance)
- || !crate::system::process::process_identity::matches_instance(pid, instance)?
- {
- return Err(window_identity_mismatch(&win.id));
- }
- if !win.app.is_empty() && record.app_name != win.app {
+ if !crate::system::process::process_identity::matches_instance(pid, instance)? {
return Err(window_identity_mismatch(&win.id));
}
- if !win.title.is_empty() {
- let record_title = record.title.as_deref().unwrap_or(record.app_name.as_str());
- if record_title != win.title {
- return Err(window_identity_mismatch(&win.id));
- }
- }
Ok(())
}
diff --git a/crates/macos/src/system/window/window_resolve_tests.rs b/crates/macos/src/system/window/window_resolve_tests.rs
index c8c2cf760..07c0ccb54 100644
--- a/crates/macos/src/system/window/window_resolve_tests.rs
+++ b/crates/macos/src/system/window/window_resolve_tests.rs
@@ -69,11 +69,15 @@ fn verify_rejects_recycled_pid_with_wrong_application_identity() {
}
#[test]
-fn verify_rejects_title_mismatch_when_title_provided() {
+fn verify_accepts_changed_title_but_rejects_replaced_process_generation() {
let pid = current_pid();
let requested = win("w-100", pid, "Doc A");
- let live = record("TextEdit", pid, "Doc B", 100);
- assert!(verify_window_record(&requested, &live).is_err());
+ let mut live = record("TextEdit", pid, "Doc B", 100);
+ assert!(verify_window_record(&requested, &live).is_ok());
+ for generation in [None, Some("replacement-generation".into())] {
+ live.process_instance = generation;
+ assert!(verify_window_record(&requested, &live).is_err());
+ }
}
#[test]
diff --git a/crates/macos/src/tree/adapter.rs b/crates/macos/src/tree/adapter.rs
index 0918f7a59..9159ada4c 100644
--- a/crates/macos/src/tree/adapter.rs
+++ b/crates/macos/src/tree/adapter.rs
@@ -6,6 +6,26 @@ use agent_desktop_core::{
};
impl ObservationOps for MacOSAdapter {
+ fn is_application_surface(&self, surface: agent_desktop_core::SnapshotSurface) -> bool {
+ matches!(
+ surface,
+ agent_desktop_core::SnapshotSurface::Menu
+ | agent_desktop_core::SnapshotSurface::Menubar
+ )
+ }
+
+ fn is_nonspatial_target_with_deadline(
+ &self,
+ handle: &NativeHandle,
+ deadline: Deadline,
+ ) -> Result<bool, AdapterError> {
+ crate::tree::native_menu::is_native_menu(ax_element(handle)?, deadline)
+ }
+
+ fn focused_app(&self, deadline: Deadline) -> Result<Option<AppInfo>, AdapterError> {
+ crate::system::focus::focused_app(deadline)
+ }
+
fn observe_tree(
&self,
root: ObservationRoot<'_>,
@@ -103,12 +123,10 @@ impl ObservationOps for MacOSAdapter {
deadline: Deadline,
) -> Result<Vec<SurfaceInfo>, AdapterError> {
let identity = crate::system::process::process_identity::require_core(&process)?;
- let surfaces = crate::tree::surface_inventory::list_surfaces_for_pid(
- identity.pid(),
+ crate::tree::surface_inventory::list_surfaces_for_process(
+ identity,
crate::tree::locator_deadline::from_operation(deadline)?,
- )?;
- crate::system::process::process_identity::require_core(&process)?;
- Ok(surfaces)
+ )
}
fn hit_test(
diff --git a/crates/macos/src/tree/app_menu.rs b/crates/macos/src/tree/app_menu.rs
new file mode 100644
index 000000000..97b314ef6
--- /dev/null
+++ b/crates/macos/src/tree/app_menu.rs
@@ -0,0 +1,293 @@
+use super::{AXElement, properties::element::element_for_pid, surface_read};
+use agent_desktop_core::{AdapterError, ErrorCode, SnapshotSurface};
+use std::time::Instant;
+
+const MAX_SURFACE_NODES: usize = 2_048;
+
+pub(crate) fn observe<T>(
+ identity: crate::system::process::process_identity::ProcessIdentity,
+ deadline: Instant,
+ mut operation: impl FnMut() -> Result<T, AdapterError>,
+) -> Result<T, AdapterError> {
+ surface_read::ensure_before_deadline(deadline)?;
+ let mut reacquired = false;
+ super::resolve::retry_incomplete_until(deadline, || {
+ reacquire_once(deadline, &mut reacquired, || {
+ require_generation(identity)?;
+ let result = operation();
+ require_generation(identity)?;
+ result
+ })
+ })
+}
+
+fn require_generation(
+ identity: crate::system::process::process_identity::ProcessIdentity,
+) -> Result<(), AdapterError> {
+ if identity.still_matches()? {
+ Ok(())
+ } else {
+ Err(AdapterError::stale_ref_because(
+ "Application process instance changed during observation",
+ ))
+ }
+}
+
+fn reacquire_once<T>(
+ deadline: Instant,
+ reacquired: &mut bool,
+ mut operation: impl FnMut() -> Result<T, AdapterError>,
+) -> Result<T, AdapterError> {
+ loop {
+ surface_read::ensure_before_deadline(deadline)?;
+ match operation() {
+ Err(mut error) if invalidated(&error) => {
+ if !*reacquired {
+ *reacquired = true;
+ continue;
+ }
+ error.code = ErrorCode::AppUnresponsive;
+ let mut details = error
+ .details
+ .take()
+ .unwrap_or_else(|| serde_json::json!({}));
+ if let Some(fields) = details.as_object_mut() {
+ fields.insert("complete".into(), false.into());
+ fields.insert("retryable".into(), false.into());
+ fields.insert("menu_root_reacquired".into(), true.into());
+ }
+ return Err(error.with_details(details));
+ }
+ result => return result,
+ }
+ }
+}
+
+fn invalidated(error: &AdapterError) -> bool {
+ error
+ .details
+ .as_ref()
+ .and_then(|details| details["ax_error"].as_i64())
+ == Some(i64::from(accessibility_sys::kAXErrorInvalidUIElement))
+}
+
+pub(crate) fn root_for_pid(
+ pid: i32,
+ surface: SnapshotSurface,
+ deadline: Instant,
+) -> Result<Option<AXElement>, AdapterError> {
+ match surface {
+ SnapshotSurface::Menubar => menubar_for_pid(pid, deadline),
+ SnapshotSurface::Menu => menu_element_for_pid(pid, deadline),
+ _ => Err(AdapterError::not_supported("native menu surface")),
+ }
+}
+
+pub(super) fn require_root<T>(
+ read: Result<Option<T>, AdapterError>,
+ surface: SnapshotSurface,
+ message: &str,
+) -> Result<T, AdapterError> {
+ read?.ok_or_else(|| AdapterError::surface_absent(surface, message))
+}
+
+#[cfg(target_os = "macos")]
+fn menubar_for_pid(pid: i32, deadline: Instant) -> Result<Option<AXElement>, AdapterError> {
+ let app = element_for_pid(pid);
+ let Some(menubar) = surface_read::element(&app, "AXMenuBar", deadline)? else {
+ return Ok(None);
+ };
+ if !has_role(&menubar, "AXMenuBar", deadline)? {
+ return Err(invalid_root_error());
+ }
+ Ok(Some(menubar))
+}
+
+#[cfg(target_os = "macos")]
+fn menu_element_for_pid(pid: i32, deadline: Instant) -> Result<Option<AXElement>, AdapterError> {
+ Ok(open_menus_for_pid(pid, deadline)?
+ .into_iter()
+ .next()
+ .map(|(_, _, menu)| menu))
+}
+
+pub(crate) fn open_menus_for_pid(
+ pid: i32,
+ deadline: Instant,
+) -> Result<Vec<(&'static str, String, AXElement)>, AdapterError> {
+ let mut menus = Vec::new();
+ if let Some(menubar) = menubar_for_pid(pid, deadline)? {
+ menus.extend(
+ open_menubar_menus_with(
+ &menubar,
+ |element| surface_read::elements(element, "AXChildren", deadline),
+ |element| {
+ Ok(has_role(element, "AXMenuBarItem", deadline)?
+ && surface_read::boolean(element, "AXSelected", deadline)? == Some(true))
+ },
+ |element| has_role(element, "AXMenu", deadline),
+ )?
+ .into_iter()
+ .map(|(id, menu)| ("menu", id, menu)),
+ );
+ }
+ if menus.is_empty()
+ && let Some((id, menu)) = context_menu_from_app(pid, deadline)?
+ {
+ menus.push(("context_menu", id, menu));
+ }
+ Ok(menus)
+}
+
+fn open_menubar_menus_with<T>(
+ menubar: &T,
+ mut children: impl FnMut(&T) -> Result<Vec<T>, AdapterError>,
+ mut selected: impl FnMut(&T) -> Result<bool, AdapterError>,
+ mut is_menu: impl FnMut(&T) -> Result<bool, AdapterError>,
+) -> Result<Vec<(String, T)>, AdapterError> {
+ let mut menus = Vec::new();
+ for (item_index, item) in children(menubar)?.into_iter().enumerate() {
+ if !selected(&item)? {
+ continue;
+ }
+ for (child_index, child) in children(&item)?.into_iter().enumerate() {
+ if is_menu(&child)? {
+ menus.push((
+ format!("app/menubar/children/{item_index}/children/{child_index}"),
+ child,
+ ));
+ }
+ }
+ }
+ Ok(menus)
+}
+
+#[cfg(target_os = "macos")]
+fn context_menu_from_app(
+ pid: i32,
+ deadline: Instant,
+) -> Result<Option<(String, AXElement)>, AdapterError> {
+ let app = element_for_pid(pid);
+ for (index, menu) in surface_read::elements(&app, "AXMenus", deadline)?
+ .into_iter()
+ .enumerate()
+ {
+ if displayed_menu(&menu, deadline)? {
+ return Ok(Some((format!("app/menus/{index}"), menu)));
+ }
+ }
+ if let Some(focused) = surface_read::element(&app, "AXFocusedUIElement", deadline)?
+ && let Some(menu) = find_menu_descendant(focused, "app/focused-element".into(), deadline)?
+ {
+ return Ok(Some(menu));
+ }
+ for (index, child) in surface_read::elements(&app, "AXChildren", deadline)?
+ .into_iter()
+ .enumerate()
+ {
+ if let Some(menu) = find_menu_descendant(child, format!("app/children/{index}"), deadline)?
+ {
+ return Ok(Some(menu));
+ }
+ }
+ Ok(None)
+}
+
+#[cfg(target_os = "macos")]
+fn find_menu_descendant(
+ root: AXElement,
+ source: String,
+ deadline: Instant,
+) -> Result<Option<(String, AXElement)>, AdapterError> {
+ find_menu_descendant_with(root, source, deadline, |element| {
+ let role = surface_read::string(element, "AXRole", deadline)?;
+ if role.as_deref() == Some("AXMenuBar") {
+ return Ok((false, Vec::new()));
+ }
+ if role.as_deref() == Some("AXMenu")
+ && surface_read::boolean(element, "AXVisible", deadline)? != Some(false)
+ {
+ return Ok((true, Vec::new()));
+ }
+ Ok((
+ false,
+ surface_read::elements(element, "AXChildren", deadline)?,
+ ))
+ })
+}
+
+fn find_menu_descendant_with<T>(
+ root: T,
+ source: String,
+ deadline: Instant,
+ mut inspect: impl FnMut(&T) -> Result<(bool, Vec<T>), AdapterError>,
+) -> Result<Option<(String, T)>, AdapterError> {
+ let mut pending = std::collections::VecDeque::from([(source, root)]);
+ let mut incomplete = None;
+ let mut visited = 0_usize;
+ while let Some((path, element)) = pending.pop_front() {
+ surface_read::ensure_before_deadline(deadline)?;
+ visited += 1;
+ if visited > MAX_SURFACE_NODES {
+ return Err(surface_limit_error());
+ }
+ let (is_menu, children) = match inspect(&element) {
+ Ok(observed) => observed,
+ Err(error) if error.code == ErrorCode::AppUnresponsive && !invalidated(&error) => {
+ incomplete.get_or_insert(error);
+ continue;
+ }
+ Err(error) => return Err(error),
+ };
+ if is_menu {
+ return Ok(Some((path, element)));
+ }
+ pending.extend(
+ children
+ .into_iter()
+ .enumerate()
+ .map(|(index, child)| (format!("{path}/children/{index}"), child)),
+ );
+ }
+ incomplete.map_or(Ok(None), Err)
+}
+
+#[cfg(target_os = "macos")]
+fn displayed_menu(element: &AXElement, deadline: Instant) -> Result<bool, AdapterError> {
+ Ok(has_role(element, "AXMenu", deadline)?
+ && surface_read::boolean(element, "AXVisible", deadline)? != Some(false))
+}
+
+#[cfg(target_os = "macos")]
+fn has_role(element: &AXElement, expected: &str, deadline: Instant) -> Result<bool, AdapterError> {
+ Ok(surface_read::string(element, "AXRole", deadline)?.as_deref() == Some(expected))
+}
+
+fn invalid_root_error() -> AdapterError {
+ AdapterError::new(
+ ErrorCode::AppUnresponsive,
+ "Application returned an invalid menu bar root",
+ )
+ .with_details(serde_json::json!({
+ "kind": "surface_root_invalid", "surface": "menubar", "complete": false,
+ "retryable": false,
+ }))
+}
+
+fn surface_limit_error() -> AdapterError {
+ AdapterError::new(
+ ErrorCode::AppUnresponsive,
+ "Accessibility surface search exceeded its node budget",
+ )
+ .with_details(serde_json::json!({
+ "kind": "surface_search_limit",
+ "limit": MAX_SURFACE_NODES,
+ "complete": false,
+ "retryable": false,
+ }))
+ .with_suggestion("Retry with the target application in a more stable UI state")
+}
+
+#[cfg(test)]
+#[path = "app_menu_tests.rs"]
+mod tests;
diff --git a/crates/macos/src/tree/app_menu_tests.rs b/crates/macos/src/tree/app_menu_tests.rs
new file mode 100644
index 000000000..841b1cdb6
--- /dev/null
+++ b/crates/macos/src/tree/app_menu_tests.rs
@@ -0,0 +1,374 @@
+use super::*;
+use std::time::Duration;
+
+#[test]
+fn only_complete_menu_root_absence_gets_a_typed_surface_error() {
+ for (surface, message) in [
+ (SnapshotSurface::Menu, "No open menu"),
+ (SnapshotSurface::Menu, "No open context menu"),
+ (SnapshotSurface::Menubar, "No menu bar found"),
+ ] {
+ let error = require_root::<u8>(Ok(None), surface, message).unwrap_err();
+ assert_eq!(error.code, ErrorCode::ElementNotFound);
+ assert_eq!(error.message, message);
+ assert_eq!(
+ error.suggestion.as_deref(),
+ Some(if surface == SnapshotSurface::Menu {
+ "Open the menu, then take a fresh snapshot with --surface menu"
+ } else {
+ "Ensure the application exposes the menubar surface, then take a fresh snapshot with --surface menubar"
+ })
+ );
+ assert_eq!(
+ error.details.unwrap(),
+ serde_json::json!({
+ "kind": "surface_absent",
+ "complete": true,
+ "surface": surface.as_str(),
+ })
+ );
+ assert_eq!(require_root(Ok(Some(7)), surface, message).unwrap(), 7);
+ let invalidated = AdapterError::new(ErrorCode::AppUnresponsive, "invalidated root")
+ .with_details(serde_json::json!({
+ "ax_error": accessibility_sys::kAXErrorInvalidUIElement,
+ "complete": false,
+ }));
+ let error = require_root::<u8>(Err(invalidated), surface, message).unwrap_err();
+ assert_eq!(error.code, ErrorCode::AppUnresponsive);
+ assert_eq!(error.message, "invalidated root");
+ assert_eq!(
+ error.details.unwrap(),
+ serde_json::json!({
+ "ax_error": accessibility_sys::kAXErrorInvalidUIElement,
+ "complete": false,
+ })
+ );
+ }
+}
+
+fn current_identity() -> crate::system::process::process_identity::ProcessIdentity {
+ crate::system::process::process_identity::ProcessIdentity::capture(
+ i32::try_from(std::process::id()).unwrap(),
+ )
+ .unwrap()
+ .unwrap()
+}
+
+#[test]
+fn menu_observation_retries_native_transience_but_not_deterministic_incompleteness() {
+ let mut reads = 0;
+ let result = observe(
+ current_identity(),
+ Instant::now() + Duration::from_secs(1),
+ || {
+ reads += 1;
+ if reads == 1 {
+ Err(surface_read::map_error(
+ "AXRole",
+ accessibility_sys::kAXErrorCannotComplete,
+ ))
+ } else {
+ Ok("fresh menu")
+ }
+ },
+ );
+ assert_eq!(result.unwrap(), "fresh menu");
+ assert_eq!(reads, 2);
+ let mut reads = 0;
+ let error = observe(
+ current_identity(),
+ Instant::now() + Duration::from_secs(1),
+ || {
+ reads += 1;
+ match reads {
+ 1 | 3 => Err(surface_read::map_error(
+ "AXRole",
+ accessibility_sys::kAXErrorInvalidUIElement,
+ )),
+ 2 => Err(surface_read::map_error(
+ "AXRole",
+ accessibility_sys::kAXErrorCannotComplete,
+ )),
+ _ => Ok("must not reacquire again"),
+ }
+ },
+ )
+ .unwrap_err();
+ assert_eq!(reads, 3);
+ assert!(!error.permits_retry_by_default());
+ assert_eq!(error.details.unwrap()["menu_root_reacquired"], true);
+ for expected in [surface_limit_error(), invalid_root_error()] {
+ let mut attempts = 0;
+ let error = observe::<()>(
+ current_identity(),
+ Instant::now() + Duration::from_secs(1),
+ || {
+ attempts += 1;
+ assert_eq!(attempts, 1);
+ Err(expected.clone())
+ },
+ )
+ .unwrap_err();
+ assert_eq!(error.details, expected.details);
+ assert!(!error.permits_retry_by_default());
+ }
+ let error = observe::<()>(current_identity(), Instant::now(), || {
+ panic!("expired observation must not read a menu")
+ })
+ .unwrap_err();
+ assert_eq!(error.code, ErrorCode::Timeout);
+}
+
+#[test]
+fn terminal_menu_errors_are_not_retried() {
+ for (code, details) in [
+ (
+ ErrorCode::PermDenied,
+ serde_json::json!({ "complete": false }),
+ ),
+ (
+ ErrorCode::StaleRef,
+ serde_json::json!({ "complete": false }),
+ ),
+ (
+ ErrorCode::AmbiguousTarget,
+ serde_json::json!({ "complete": true }),
+ ),
+ (
+ ErrorCode::ElementNotFound,
+ serde_json::json!({ "complete": true }),
+ ),
+ (
+ ErrorCode::AppUnresponsive,
+ serde_json::json!({ "complete": false, "retryable": false }),
+ ),
+ ] {
+ let mut reads = 0;
+ let error = observe::<()>(
+ current_identity(),
+ Instant::now() + Duration::from_secs(1),
+ || {
+ reads += 1;
+ assert_eq!(reads, 1);
+ Err(AdapterError::new(code.clone(), "terminal").with_details(details.clone()))
+ },
+ )
+ .unwrap_err();
+ assert_eq!(error.code, code);
+ assert_eq!(reads, 1);
+ }
+}
+
+#[test]
+fn process_exit_rejects_menu_reads_before_and_after_observation() {
+ for phase in ["before", "success", "incomplete", "absent"] {
+ let mut child = std::process::Command::new("/bin/sleep")
+ .arg("30")
+ .spawn()
+ .unwrap();
+ let identity = crate::system::process::process_identity::ProcessIdentity::capture(
+ i32::try_from(child.id()).unwrap(),
+ )
+ .unwrap()
+ .unwrap();
+ if phase == "before" {
+ child.kill().unwrap();
+ child.wait().unwrap();
+ }
+ let mut reads = 0;
+ let error = observe(identity, Instant::now() + Duration::from_secs(1), || {
+ reads += 1;
+ assert_ne!(phase, "before");
+ child.kill().unwrap();
+ child.wait().unwrap();
+ if phase == "incomplete" {
+ Err(surface_limit_error())
+ } else if phase == "absent" {
+ require_root(Ok(None), SnapshotSurface::Menu, "No open menu")
+ } else {
+ Ok("read from exited process")
+ }
+ })
+ .unwrap_err();
+ assert_eq!(error.code, ErrorCode::StaleRef);
+ assert_eq!(reads, usize::from(phase != "before"));
+ }
+}
+
+#[test]
+fn open_menu_ids_follow_unfiltered_menubar_provenance() {
+ let discover = |selected: &[u8]| {
+ open_menubar_menus_with(
+ &0_u8,
+ |node| {
+ Ok(match node {
+ 0 => vec![10, 20, 30],
+ 10 => vec![11, 12],
+ 20 => vec![21, 22],
+ 30 => vec![31, 32],
+ _ => unreachable!(),
+ })
+ },
+ |node| Ok(selected.contains(node)),
+ |node| Ok(node % 10 == 2),
+ )
+ .unwrap()
+ };
+ let file = discover(&[10]);
+ let edit = discover(&[20]);
+ let both = discover(&[10, 20]);
+ assert_eq!(file, [("app/menubar/children/0/children/1".into(), 12)]);
+ assert_eq!(edit, [("app/menubar/children/1/children/1".into(), 22)]);
+ assert_eq!(both, [file[0].clone(), edit[0].clone()]);
+}
+
+#[test]
+fn incomplete_selected_menu_children_cannot_produce_an_empty_or_partial_inventory() {
+ let error = open_menubar_menus_with(
+ &0_u8,
+ |node| match node {
+ 0 => Ok(vec![1, 2]),
+ 1 => Ok(vec![3]),
+ _ => Err(surface_limit_error()),
+ },
+ |_| Ok(true),
+ |_| Ok(true),
+ )
+ .unwrap_err();
+ assert_eq!(error.details.unwrap()["complete"], false);
+}
+
+#[test]
+fn surface_node_limit_is_explicitly_incomplete() {
+ let error = surface_limit_error();
+
+ assert_eq!(error.code, ErrorCode::AppUnresponsive);
+ assert_eq!(error.details.expect("limit details")["complete"], false);
+}
+
+#[test]
+fn menus_beyond_eight_wrappers_remain_discoverable() {
+ let deadline = Instant::now() + std::time::Duration::from_secs(5);
+ for target_depth in [9, 11, 30] {
+ let found = find_menu_descendant_with(0, "app".into(), deadline, |depth| {
+ Ok((*depth == target_depth, vec![depth + 1]))
+ })
+ .unwrap();
+ assert_eq!(found.map(|(_, node)| node), Some(target_depth));
+ }
+}
+
+#[test]
+fn cyclic_menu_search_remains_bounded_and_explicitly_incomplete() {
+ let mut reads = 0;
+ let error = find_menu_descendant_with(
+ 0,
+ "app".into(),
+ Instant::now() + std::time::Duration::from_secs(5),
+ |node| {
+ reads += 1;
+ Ok((false, vec![*node]))
+ },
+ )
+ .unwrap_err();
+ assert_eq!(reads, MAX_SURFACE_NODES);
+ assert_eq!(error.details.unwrap()["complete"], false);
+}
+
+#[test]
+fn expired_menu_search_never_reads_a_node() {
+ let result = find_menu_descendant_with::<()>((), "app".into(), Instant::now(), |_| {
+ panic!("expired search must not call AX")
+ });
+ assert_eq!(result.unwrap_err().code, ErrorCode::Timeout);
+}
+
+#[test]
+fn incomplete_content_branch_does_not_hide_a_menu_in_a_sibling() {
+ let result = find_menu_descendant_with(
+ 0,
+ "app".into(),
+ Instant::now() + std::time::Duration::from_secs(5),
+ |node| match node {
+ 0 => Ok((false, vec![1, 2])),
+ 1 => Err(surface_limit_error()),
+ 2 => Ok((true, vec![])),
+ _ => unreachable!(),
+ },
+ );
+ assert_eq!(result.unwrap(), Some(("app/children/1".into(), 2)));
+}
+
+#[test]
+fn an_incomplete_branch_cannot_prove_menu_absence() {
+ let result = find_menu_descendant_with(
+ 0,
+ "app".into(),
+ Instant::now() + std::time::Duration::from_secs(5),
+ |node| match node {
+ 0 => Ok((false, vec![1, 2])),
+ 1 => Err(surface_limit_error()),
+ _ => Ok((false, vec![])),
+ },
+ );
+ assert_eq!(result.unwrap_err().details.unwrap()["complete"], false);
+}
+
+#[test]
+fn shallow_menu_precedes_unbounded_content_and_permission_errors_stay_terminal() {
+ let deadline = Instant::now() + std::time::Duration::from_secs(5);
+ let found = find_menu_descendant_with(0, "app".into(), deadline, |node| match node {
+ 0 => Ok((false, vec![1, 2])),
+ 1 => Ok((false, vec![1])),
+ _ => Ok((true, vec![])),
+ });
+ assert_eq!(found.unwrap(), Some(("app/children/1".into(), 2)));
+ let denied = find_menu_descendant_with(0, "app".into(), deadline, |node| match node {
+ 0 => Ok((false, vec![1, 2])),
+ 1 => Err(AdapterError::new(ErrorCode::PermDenied, "denied")),
+ _ => panic!("permission failure must stop all further AX reads"),
+ });
+ assert_eq!(denied.unwrap_err().code, ErrorCode::PermDenied);
+}
+
+#[test]
+fn invalidated_menu_roots_are_reacquired_once_and_permission_errors_are_terminal() {
+ use accessibility_sys::{kAXErrorAPIDisabled, kAXErrorInvalidUIElement};
+ for (ax_error, failures) in [
+ (kAXErrorInvalidUIElement, 1),
+ (kAXErrorInvalidUIElement, 2),
+ (kAXErrorAPIDisabled, 1),
+ ] {
+ let mut reads = 0;
+ let result = reacquire_once(
+ Instant::now() + std::time::Duration::from_secs(1),
+ &mut false,
+ || {
+ reads += 1;
+ if reads <= failures {
+ Err(AdapterError::new(ErrorCode::PermDenied, "read failed")
+ .with_details(serde_json::json!({ "ax_error": ax_error })))
+ } else {
+ Ok("fresh root")
+ }
+ },
+ );
+ if ax_error == kAXErrorAPIDisabled {
+ assert_eq!(reads, 1);
+ assert_eq!(result.unwrap_err().code, ErrorCode::PermDenied);
+ } else {
+ assert_eq!(reads, 2);
+ if failures == 1 {
+ assert_eq!(result.unwrap(), "fresh root");
+ } else {
+ let error = result.unwrap_err();
+ assert_eq!(error.code, ErrorCode::AppUnresponsive);
+ let details = error.details.unwrap();
+ assert_eq!(details["complete"], false);
+ assert_eq!(details["menu_root_reacquired"], true);
+ assert_eq!(details["retryable"], false);
+ assert_eq!(details["ax_error"], kAXErrorInvalidUIElement);
+ }
+ }
+ }
+}
diff --git a/crates/macos/src/tree/element_bounds.rs b/crates/macos/src/tree/element_bounds.rs
index ed704dc4e..d8c05ff7d 100644
--- a/crates/macos/src/tree/element_bounds.rs
+++ b/crates/macos/src/tree/element_bounds.rs
@@ -7,19 +7,14 @@ 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 {
+ Rect {
x: point.x,
y: point.y,
width: size.width,
height: size.height,
- })
+ }
+ .validate()
+ .ok()
}
#[cfg(target_os = "macos")]
@@ -169,6 +164,27 @@ fn read_error(attribute: &str, error: i32) -> AdapterError {
mod tests {
use super::*;
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn native_bounds_decoder_rejects_invalid_geometry_before_live_or_snapshot_use() {
+ use core_graphics::geometry::{CGPoint, CGSize};
+ for (point, size) in [
+ (CGPoint::new(0.0, 33.0), CGSize::new(-1.0, 0.0)),
+ (CGPoint::new(0.0, 0.0), CGSize::new(10.0, -0.5)),
+ (CGPoint::new(f64::NAN, 0.0), CGSize::new(10.0, 10.0)),
+ (CGPoint::new(0.0, 0.0), CGSize::new(f64::INFINITY, 10.0)),
+ (CGPoint::new(0.0, 0.0), CGSize::new(f64::MAX, 10.0)),
+ ] {
+ assert_eq!(rect_from_parts(point, size), None);
+ }
+ for size in [CGSize::new(0.0, 0.0), CGSize::new(20.0, 10.0)] {
+ let bounds = rect_from_parts(CGPoint::new(-20.0, 33.0), size).unwrap();
+ assert_eq!(bounds.x, -20.0);
+ assert_eq!(bounds.width, size.width);
+ assert_eq!(bounds.height, size.height);
+ }
+ }
+
fn rect(x: f64, width: f64) -> Rect {
Rect {
x,
diff --git a/crates/macos/src/tree/mod.rs b/crates/macos/src/tree/mod.rs
index 9abc6f053..4809c51e7 100644
--- a/crates/macos/src/tree/mod.rs
+++ b/crates/macos/src/tree/mod.rs
@@ -1,4 +1,5 @@
mod adapter;
+pub(crate) mod app_menu;
pub(crate) mod ax_element;
pub(crate) mod build_context;
pub(crate) mod child_labels;
@@ -7,6 +8,7 @@ pub(crate) mod element_dedupe;
pub(crate) mod element_name;
pub(crate) mod hit_test;
pub(crate) mod locator_deadline;
+pub(crate) mod native_menu;
pub(crate) mod observation_usage;
pub(crate) mod properties;
pub(crate) mod query;
diff --git a/crates/macos/src/tree/native_menu.rs b/crates/macos/src/tree/native_menu.rs
new file mode 100644
index 000000000..d07b9e9c7
--- /dev/null
+++ b/crates/macos/src/tree/native_menu.rs
@@ -0,0 +1,58 @@
+use agent_desktop_core::{AdapterError, Deadline, ErrorCode};
+
+use crate::tree::{AXElement, surface_read};
+
+pub(crate) fn is_native_menu(
+ element: &AXElement,
+ deadline: Deadline,
+) -> Result<bool, AdapterError> {
+ let end = crate::tree::locator_deadline::from_operation(deadline)?;
+ classify(
+ element.clone(),
+ deadline,
+ |element| surface_read::string(element, "AXRole", end),
+ |element| surface_read::element(element, "AXParent", end),
+ |application, menubar| {
+ Ok(surface_read::element(application, "AXMenuBar", end)?
+ .is_some_and(|owned| crate::tree::same_element(&owned, menubar)))
+ },
+ )
+}
+
+fn classify<T: Clone>(
+ mut element: T,
+ deadline: Deadline,
+ mut role: impl FnMut(&T) -> Result<Option<String>, AdapterError>,
+ mut parent: impl FnMut(&T) -> Result<Option<T>, AdapterError>,
+ mut owns_menubar: impl FnMut(&T, &T) -> Result<bool, AdapterError>,
+) -> Result<bool, AdapterError> {
+ let mut menubar = None;
+ for depth in 0..64 {
+ deadline.ensure_remaining()?;
+ let role = role(&element)?;
+ match role.as_deref() {
+ Some("AXMenuItem" | "AXMenuBarItem") => {}
+ Some("AXMenu") if depth > 0 => {}
+ Some("AXMenuBar") if depth > 0 => menubar = Some(element.clone()),
+ Some("AXApplication") => {
+ return menubar
+ .as_ref()
+ .map_or(Ok(false), |menubar| owns_menubar(&element, menubar));
+ }
+ _ => return Ok(false),
+ }
+ let Some(next) = parent(&element)? else {
+ return Ok(false);
+ };
+ element = next;
+ }
+ Err(AdapterError::new(
+ ErrorCode::AppUnresponsive,
+ "Native menu ancestry exceeded its observation budget",
+ )
+ .with_details(serde_json::json!({ "complete": false, "kind": "menu_ancestry_limit" })))
+}
+
+#[cfg(test)]
+#[path = "native_menu_tests.rs"]
+mod tests;
diff --git a/crates/macos/src/tree/native_menu_tests.rs b/crates/macos/src/tree/native_menu_tests.rs
new file mode 100644
index 000000000..e28934dab
--- /dev/null
+++ b/crates/macos/src/tree/native_menu_tests.rs
@@ -0,0 +1,147 @@
+use super::*;
+
+fn classify_roles(roles: &[Option<&str>]) -> Result<bool, AdapterError> {
+ classify(
+ 0,
+ Deadline::standard().unwrap(),
+ |index| Ok(roles[*index].map(str::to_owned)),
+ |index| Ok((index + 1 < roles.len()).then_some(index + 1)),
+ |application, menubar| {
+ assert_eq!(roles[*application], Some("AXApplication"));
+ assert_eq!(roles[*menubar], Some("AXMenuBar"));
+ Ok(true)
+ },
+ )
+}
+
+#[test]
+fn only_application_menu_ancestry_selects_the_press_only_chain() {
+ for roles in [
+ vec![
+ Some("AXMenuItem"),
+ Some("AXMenu"),
+ Some("AXMenuBarItem"),
+ Some("AXMenuBar"),
+ Some("AXApplication"),
+ ],
+ vec![
+ Some("AXMenuBarItem"),
+ Some("AXMenuBar"),
+ Some("AXApplication"),
+ ],
+ ] {
+ let native = classify_roles(&roles).unwrap();
+ assert!(native);
+ }
+ for roles in [
+ vec![Some("AXMenuItem"), Some("AXMenu"), Some("AXWebArea")],
+ vec![
+ Some("AXMenuItem"),
+ Some("AXMenu"),
+ Some("AXMenuBar"),
+ Some("AXWebArea"),
+ Some("AXApplication"),
+ ],
+ vec![Some("AXMenuItem"), Some("AXMenu"), Some("AXWindow")],
+ vec![Some("AXMenuItem"), Some("AXApplication")],
+ vec![Some("AXMenuItem"), Some("AXMenu"), Some("AXApplication")],
+ vec![Some("AXMenuItem")],
+ vec![Some("AXButton")],
+ vec![Some("")],
+ vec![None],
+ vec![Some("AXMenuItem"), None],
+ ] {
+ let native = classify_roles(&roles).unwrap();
+ assert!(!native, "{roles:?}");
+ }
+}
+
+#[test]
+fn role_and_parent_failures_are_never_downgraded_to_ordinary_clicks() {
+ for code in [
+ ErrorCode::PermDenied,
+ ErrorCode::Timeout,
+ ErrorCode::StaleRef,
+ ErrorCode::AppUnresponsive,
+ ] {
+ let error = AdapterError::new(code.clone(), "native read failed")
+ .with_details(serde_json::json!({ "ax_error": -25202 }));
+ let role_error = classify(
+ 0,
+ Deadline::standard().unwrap(),
+ |_| Err(error.clone()),
+ |_| Ok(None),
+ |_, _| panic!("no menubar"),
+ )
+ .unwrap_err();
+ assert_eq!(role_error.code, code);
+ assert_eq!(role_error.details, error.details);
+ let parent_error = classify(
+ 0,
+ Deadline::standard().unwrap(),
+ |_| Ok(Some("AXMenuItem".into())),
+ |_| Err(error.clone()),
+ |_, _| panic!("no menubar"),
+ )
+ .unwrap_err();
+ assert_eq!(parent_error.code, code);
+ assert_eq!(parent_error.details, error.details);
+ }
+}
+
+#[test]
+fn ancestry_cycles_exhaust_the_budget_instead_of_enabling_fallbacks() {
+ let error = classify(
+ 0,
+ Deadline::standard().unwrap(),
+ |_| Ok(Some("AXMenuItem".into())),
+ |_| Ok(Some(0)),
+ |_, _| panic!("cycle has no app"),
+ )
+ .unwrap_err();
+ assert_eq!(error.code, ErrorCode::AppUnresponsive);
+ assert_eq!(error.details.unwrap()["complete"], false);
+}
+
+#[test]
+fn exhausted_deadline_never_reads_or_selects_a_click_chain() {
+ let deadline = Deadline::after(1).unwrap();
+ std::thread::sleep(std::time::Duration::from_millis(2));
+ let error = classify(
+ 0,
+ deadline,
+ |_| panic!("role read after deadline"),
+ |_| panic!("parent read after deadline"),
+ |_, _| panic!("provenance read after deadline"),
+ )
+ .unwrap_err();
+ assert_eq!(error.code, ErrorCode::Timeout);
+}
+
+#[test]
+fn menu_roles_cannot_substitute_for_the_applications_actual_menubar() {
+ for ownership in [
+ Ok(false),
+ Err(AdapterError::new(
+ ErrorCode::PermDenied,
+ "cannot read application menubar",
+ )),
+ ] {
+ let result = classify(
+ 0,
+ Deadline::standard().unwrap(),
+ |index| {
+ Ok(Some(
+ ["AXMenuBarItem", "AXMenuBar", "AXApplication"][*index].into(),
+ ))
+ },
+ |index| Ok(Some(index + 1)),
+ |_, _| ownership.clone(),
+ );
+ match ownership {
+ Ok(false) => assert!(!result.unwrap()),
+ Err(error) => assert_eq!(result.unwrap_err().code, error.code),
+ _ => unreachable!(),
+ }
+ }
+}
diff --git a/crates/macos/src/tree/query/child_source.rs b/crates/macos/src/tree/query/child_source.rs
index 46bb504f7..adf40cffe 100644
--- a/crates/macos/src/tree/query/child_source.rs
+++ b/crates/macos/src/tree/query/child_source.rs
@@ -41,10 +41,12 @@ pub(super) fn read_first_nonempty(
let mut status = ChildReadStatus::default();
let mut prefix_certain = true;
let mut any_available = false;
+ let mut total_count = 0;
for attribute in attributes {
let mut read = read_attribute(attribute);
let terminal = read.status.invalid_element || read.status.api_disabled;
any_available |= read.source_availability == ChildSourceAvailability::Available;
+ total_count = total_count.max(read.total_count);
status.merge(read.status);
let source_selected = read.source_availability == ChildSourceAvailability::Available
&& (read.total_count > 0 || *attribute == CANONICAL_CHILDREN);
@@ -61,7 +63,7 @@ pub(super) fn read_first_nonempty(
}
ChildRead {
elements: Vec::new(),
- total_count: 0,
+ total_count,
complete: prefix_certain,
source_availability: if any_available {
ChildSourceAvailability::Available
diff --git a/crates/macos/src/tree/query/mod.rs b/crates/macos/src/tree/query/mod.rs
index 4fae0bfc0..0fe1ac95d 100644
--- a/crates/macos/src/tree/query/mod.rs
+++ b/crates/macos/src/tree/query/mod.rs
@@ -51,12 +51,47 @@ pub(crate) fn observe_tree(
) -> Result<ObservedTree, AdapterError> {
let request = (*request).validate()?;
let deadline = crate::tree::locator_deadline::from_operation(request.deadline)?;
- let resolved = resolve_root(root, &request, deadline)?;
+ let process_owner_surface = matches!(
+ request.surface,
+ SnapshotSurface::Window | SnapshotSurface::MenuBarExtras
+ ) && matches!(root, ObservationRoot::Window(window) if window.is_process_owner());
+ if (matches!(
+ request.surface,
+ SnapshotSurface::Menu | SnapshotSurface::Menubar
+ ) && !matches!(root, ObservationRoot::Element { .. }))
+ || process_owner_surface
+ {
+ let (pid, instance) = match root {
+ ObservationRoot::Application { app, .. } => (app.pid, app.process_instance.as_deref()),
+ ObservationRoot::Window(window) => (window.pid, window.process_instance.as_deref()),
+ ObservationRoot::Element { .. } => {
+ return Err(AdapterError::internal("Invalid menu observation root"));
+ }
+ };
+ let instance = instance.ok_or_else(|| {
+ AdapterError::stale_ref_because("Application has no process instance identity")
+ })?;
+ let identity = crate::system::process::process_identity::require_core(
+ &agent_desktop_core::ProcessIdentity::new(pid, instance),
+ )?;
+ return crate::tree::app_menu::observe(identity, deadline, || {
+ observe_tree_once(root, &request, deadline)
+ });
+ }
+ observe_tree_once(root, &request, deadline)
+}
+
+fn observe_tree_once(
+ root: ObservationRoot<'_>,
+ request: &ObservationRequest,
+ deadline: std::time::Instant,
+) -> Result<ObservedTree, AdapterError> {
+ let resolved = resolve_root(root, request, deadline)?;
let (tree, renderer_ready, stats) =
- traversal::LocatorTraversal::new(&request, resolved.context, deadline)
+ traversal::LocatorTraversal::new(request, resolved.context, deadline)
.build(resolved.element, resolved.source)?;
tracing::debug!(?stats, "tree: native observation completed");
- let looked_deep_enough = observation_reached_tree_end(&stats, &request);
+ let looked_deep_enough = observation_reached_tree_end(&stats, request);
if renderer_ready || (resolved.activation_eligible && tree.is_complete()) {
if let Some(instance) = resolved.process_instance.as_deref() {
if crate::tree::renderer_probe::activation_required(
@@ -97,6 +132,32 @@ fn resolve_root(
) -> Result<ResolvedRoot, AdapterError> {
let source = ObservationSource::from_root(&root, request.surface);
match root {
+ ObservationRoot::Application { app, .. } => {
+ let pid = crate::system::process::process_identity::to_pid_t(app.pid)?;
+ let element = match request.surface {
+ SnapshotSurface::Menu => crate::tree::app_menu::require_root(
+ crate::tree::app_menu::root_for_pid(pid, SnapshotSurface::Menu, deadline),
+ SnapshotSurface::Menu,
+ "No open menu",
+ )?,
+ SnapshotSurface::Menubar => crate::tree::app_menu::require_root(
+ crate::tree::app_menu::root_for_pid(pid, SnapshotSurface::Menubar, deadline),
+ SnapshotSurface::Menubar,
+ "No menu bar found",
+ )?,
+ _ => return Err(AdapterError::not_supported("application snapshot surface")),
+ };
+ let context =
+ crate::tree::TreeBuildContext::for_pid_with_deadline(pid, true, deadline)?;
+ Ok(ResolvedRoot {
+ element,
+ source,
+ context,
+ pid,
+ process_instance: app.process_instance.clone(),
+ activation_eligible: false,
+ })
+ }
ObservationRoot::Window(window) => {
let pid = crate::system::process::process_identity::to_pid_t(window.pid)?;
let element = resolve_window_surface(window, request.surface, deadline)?;
@@ -117,7 +178,7 @@ fn resolve_root(
entry,
root_ref,
} => {
- verify_entry_process(entry)?;
+ verify_process(entry.process.pid, entry.process.process_instance.as_deref())?;
let pid = crate::system::process::process_identity::to_pid_t(entry.process.pid)?;
let element = handle.downcast_ref::<AXElement>().cloned().ok_or_else(|| {
AdapterError::new(
@@ -148,11 +209,14 @@ fn resolve_root(
}
}
-fn verify_entry_process(entry: &agent_desktop_core::RefEntry) -> Result<(), AdapterError> {
- let instance = entry.process.process_instance.as_deref().ok_or_else(|| {
+fn verify_process(
+ process: agent_desktop_core::ProcessId,
+ instance: Option<&str>,
+) -> Result<(), AdapterError> {
+ let instance = instance.ok_or_else(|| {
AdapterError::stale_ref_because("Live locator root has no process instance identity")
})?;
- let pid = crate::system::process::process_identity::to_pid_t(entry.process.pid)?;
+ let pid = crate::system::process::process_identity::to_pid_t(process)?;
match crate::system::process::process_identity::matches_instance(pid, instance) {
Ok(true) => Ok(()),
Ok(false) => Err(AdapterError::stale_ref_because(
@@ -193,10 +257,16 @@ fn resolve_window_surface(
}
SnapshotSurface::Focused => crate::tree::surfaces::focused_surface_for_pid(pid, deadline)?
.ok_or_else(|| AdapterError::element_not_found("No focused surface found"))?,
- SnapshotSurface::Menu => crate::tree::surfaces::menu_element_for_pid(pid, deadline)?
- .ok_or_else(|| AdapterError::element_not_found("No open context menu"))?,
- SnapshotSurface::Menubar => crate::tree::surfaces::menubar_for_pid(pid, deadline)?
- .ok_or_else(|| AdapterError::element_not_found("No menu bar found"))?,
+ SnapshotSurface::Menu => crate::tree::app_menu::require_root(
+ crate::tree::app_menu::root_for_pid(pid, SnapshotSurface::Menu, deadline),
+ SnapshotSurface::Menu,
+ "No open context menu",
+ )?,
+ SnapshotSurface::Menubar => crate::tree::app_menu::require_root(
+ crate::tree::app_menu::root_for_pid(pid, SnapshotSurface::Menubar, deadline),
+ SnapshotSurface::Menubar,
+ "No menu bar found",
+ )?,
SnapshotSurface::MenuBarExtras => {
crate::tree::shell_surface::extras_menu_bar(pid, deadline)?
.ok_or_else(|| AdapterError::element_not_found("No menu bar extras found"))?
@@ -320,3 +390,7 @@ mod tests {
assert_eq!(error.details.unwrap()["kind"], "locator_root_invalid");
}
}
+
+#[cfg(test)]
+#[path = "process_owner_tests.rs"]
+mod process_owner_tests;
diff --git a/crates/macos/src/tree/query/process_owner_tests.rs b/crates/macos/src/tree/query/process_owner_tests.rs
new file mode 100644
index 000000000..7149b0a30
--- /dev/null
+++ b/crates/macos/src/tree/query/process_owner_tests.rs
@@ -0,0 +1,31 @@
+use super::*;
+
+#[test]
+fn process_owner_surfaces_require_saved_process_identity_before_tree_read() {
+ let pid = i32::try_from(std::process::id()).expect("test pid fits macOS pid_t");
+ let window = agent_desktop_core::WindowInfo {
+ id: String::new(),
+ title: String::new(),
+ app: "Fixture".into(),
+ pid: agent_desktop_core::ProcessId::try_from(pid).expect("test pid is positive"),
+ process_instance: None,
+ bounds: None,
+ state: agent_desktop_core::WindowState::default(),
+ };
+
+ for surface in [SnapshotSurface::Window, SnapshotSurface::MenuBarExtras] {
+ let mut request = ObservationRequest::snapshot(
+ &agent_desktop_core::TreeOptions::default(),
+ agent_desktop_core::Deadline::after(1_000).unwrap(),
+ );
+ request.surface = surface;
+ let error = observe_tree(ObservationRoot::Window(&window), &request)
+ .expect_err("process-owner observation without saved identity must fail closed");
+
+ assert_eq!(error.code, ErrorCode::StaleRef);
+ assert_eq!(
+ error.message,
+ "Application has no process instance identity"
+ );
+ }
+}
diff --git a/crates/macos/src/tree/query/traversal.rs b/crates/macos/src/tree/query/traversal.rs
index daf4810d2..e0c315c67 100644
--- a/crates/macos/src/tree/query/traversal.rs
+++ b/crates/macos/src/tree/query/traversal.rs
@@ -120,7 +120,7 @@ impl LocatorTraversal {
"Live locator root is no longer a valid accessibility element",
)
.with_suggestion("Refresh the source snapshot and retry the locator")
- .with_details(json!({ "kind": "locator_root_invalid" })));
+ .with_details(json!({ "kind": "locator_root_invalid", "ax_error": accessibility_sys::kAXErrorInvalidUIElement, "complete": false })));
}
self.arena.mark_incomplete();
return Ok(None);
diff --git a/crates/macos/src/tree/resolve/mod.rs b/crates/macos/src/tree/resolve/mod.rs
index f114890e3..a7fc4da1f 100644
--- a/crates/macos/src/tree/resolve/mod.rs
+++ b/crates/macos/src/tree/resolve/mod.rs
@@ -22,12 +22,14 @@ pub(crate) fn resolve_element_with_deadline(
entry: &RefEntry,
operation_deadline: agent_desktop_core::Deadline,
) -> Result<NativeHandle, AdapterError> {
- verify_process_instance(entry)?;
+ let identity = verify_process_instance(entry)?;
if element_token(entry).is_none() {
return Err(element_token_required(entry));
}
let deadline = crate::tree::locator_deadline::from_operation(operation_deadline)?;
- let result = retry_incomplete_until(deadline, || resolve_token_once(entry, deadline));
+ let result = resolve_with_recovery(entry, identity, deadline, || {
+ resolve_token_once(entry, deadline)
+ });
match result {
Err(error) if error.code == ErrorCode::ElementNotFound => {
Err(stale_ref_error(entry, &error))
@@ -41,9 +43,11 @@ pub(crate) fn resolve_locator_anchor_with_deadline(
entry: &RefEntry,
operation_deadline: agent_desktop_core::Deadline,
) -> Result<NativeHandle, AdapterError> {
- verify_process_instance(entry)?;
+ let identity = verify_process_instance(entry)?;
let deadline = crate::tree::locator_deadline::from_operation(operation_deadline)?;
- let result = retry_incomplete_until(deadline, || resolve_locator_anchor_once(entry, deadline));
+ let result = resolve_with_recovery(entry, identity, deadline, || {
+ resolve_locator_anchor_once(entry, deadline)
+ });
match result {
Err(error) if error.code == ErrorCode::ElementNotFound => {
Err(stale_ref_error(entry, &error))
@@ -53,7 +57,9 @@ pub(crate) fn resolve_locator_anchor_with_deadline(
}
#[cfg(target_os = "macos")]
-fn verify_process_instance(entry: &RefEntry) -> Result<(), AdapterError> {
+fn verify_process_instance(
+ entry: &RefEntry,
+) -> Result<crate::system::process::process_identity::ProcessIdentity, AdapterError> {
let Some(instance) = entry.process.process_instance.as_deref() else {
return Err(AdapterError::stale_ref_because(
"Saved target has no process instance identity",
@@ -61,7 +67,13 @@ fn verify_process_instance(entry: &RefEntry) -> Result<(), AdapterError> {
};
let pid = crate::system::process::process_identity::to_pid_t(entry.process.pid)?;
match crate::system::process::process_identity::matches_instance(pid, instance) {
- Ok(true) => Ok(()),
+ Ok(true) => crate::system::process::process_identity::ProcessIdentity::capture(pid)?
+ .filter(|identity| identity.token() == instance)
+ .ok_or_else(|| {
+ AdapterError::stale_ref_because(
+ "Saved target process instance changed during resolution",
+ )
+ }),
Ok(false) => Err(AdapterError::stale_ref_because(
"Saved target belongs to a process instance that is no longer running",
)),
@@ -72,6 +84,36 @@ fn verify_process_instance(entry: &RefEntry) -> Result<(), AdapterError> {
}
}
+#[cfg(target_os = "macos")]
+fn resolve_with_recovery<T>(
+ entry: &RefEntry,
+ identity: crate::system::process::process_identity::ProcessIdentity,
+ deadline: Instant,
+ mut operation: impl FnMut() -> Result<T, AdapterError>,
+) -> Result<T, AdapterError> {
+ if matches!(
+ entry.source.source_surface,
+ SnapshotSurface::Menu | SnapshotSurface::Menubar
+ ) {
+ crate::tree::app_menu::observe(identity, deadline, operation)
+ } else {
+ retry_incomplete_until(deadline, || {
+ if !identity.still_matches()? {
+ return Err(AdapterError::stale_ref_because(
+ "Saved target process instance changed during resolution",
+ ));
+ }
+ let result = operation();
+ if !identity.still_matches()? {
+ return Err(AdapterError::stale_ref_because(
+ "Saved target process instance changed during resolution",
+ ));
+ }
+ result
+ })
+ }
+}
+
#[cfg(target_os = "macos")]
fn resolve_token_once(entry: &RefEntry, deadline: Instant) -> Result<NativeHandle, AdapterError> {
let started = Instant::now();
@@ -185,7 +227,7 @@ fn finish_resolution<T>(
}
#[cfg(target_os = "macos")]
-fn retry_incomplete_until<T>(
+pub(super) fn retry_incomplete_until<T>(
deadline: Instant,
mut operation: impl FnMut() -> Result<T, AdapterError>,
) -> Result<T, AdapterError> {
diff --git a/crates/macos/src/tree/resolve/resolve_roots.rs b/crates/macos/src/tree/resolve/resolve_roots.rs
index c30a146c4..5aa04e23a 100644
--- a/crates/macos/src/tree/resolve/resolve_roots.rs
+++ b/crates/macos/src/tree/resolve/resolve_roots.rs
@@ -99,8 +99,12 @@ fn source_surface_scoped_roots(
}
}
SnapshotSurface::Focused => crate::tree::surfaces::focused_surface_for_pid(pid, deadline)?,
- SnapshotSurface::Menu => crate::tree::surfaces::menu_element_for_pid(pid, deadline)?,
- SnapshotSurface::Menubar => crate::tree::surfaces::menubar_for_pid(pid, deadline)?,
+ SnapshotSurface::Menu => {
+ crate::tree::app_menu::root_for_pid(pid, SnapshotSurface::Menu, deadline)?
+ }
+ SnapshotSurface::Menubar => {
+ crate::tree::app_menu::root_for_pid(pid, SnapshotSurface::Menubar, deadline)?
+ }
SnapshotSurface::Sheet => crate::tree::surfaces::sheet_for_pid(pid, deadline)?,
SnapshotSurface::Popover => crate::tree::surfaces::popover_for_pid(pid, deadline)?,
SnapshotSurface::Alert => crate::tree::surfaces::alert_for_pid(pid, deadline)?,
diff --git a/crates/macos/src/tree/resolve/resolve_tests_more.rs b/crates/macos/src/tree/resolve/resolve_tests_more.rs
index 5a4dd6232..45640a36b 100644
--- a/crates/macos/src/tree/resolve/resolve_tests_more.rs
+++ b/crates/macos/src/tree/resolve/resolve_tests_more.rs
@@ -1,6 +1,47 @@
use super::tests::entry;
use super::*;
+#[test]
+fn application_menu_resolution_reacquires_invalid_roots_once_without_window_fallback() {
+ let pid = i32::try_from(std::process::id()).unwrap();
+ let identity = crate::system::process::process_identity::ProcessIdentity::capture(pid)
+ .unwrap()
+ .unwrap();
+ for surface in [SnapshotSurface::Menu, SnapshotSurface::Menubar] {
+ let mut stored = entry(None, None, None, None);
+ stored.process.pid = agent_desktop_core::ProcessId::try_from(pid).unwrap();
+ stored.process.process_instance = Some(identity.token());
+ stored.source.source_surface = surface;
+ for failures in [1, 2] {
+ let mut reads = 0;
+ let result = resolve_with_recovery(
+ &stored,
+ identity,
+ Instant::now() + Duration::from_secs(1),
+ || {
+ reads += 1;
+ if reads <= failures {
+ Err(crate::tree::surface_read::map_error(
+ "AXRole",
+ accessibility_sys::kAXErrorInvalidUIElement,
+ ))
+ } else {
+ Ok("resolved menu")
+ }
+ },
+ );
+ assert_eq!(reads, 2);
+ if failures == 1 {
+ assert_eq!(result.unwrap(), "resolved menu");
+ } else {
+ let error = result.unwrap_err();
+ assert!(!error.permits_retry_by_default());
+ assert_eq!(error.details.unwrap()["menu_root_reacquired"], true);
+ }
+ }
+ }
+}
+
#[test]
fn ax_read_errors_distinguish_absent_unknown_and_permission_denied() {
use accessibility_sys::{
diff --git a/crates/macos/src/tree/surface_inventory.rs b/crates/macos/src/tree/surface_inventory.rs
index cb17f519b..634c4cbd2 100644
--- a/crates/macos/src/tree/surface_inventory.rs
+++ b/crates/macos/src/tree/surface_inventory.rs
@@ -2,123 +2,46 @@ use crate::tree::{AXElement, properties::element::element_for_pid};
use agent_desktop_core::{AdapterError, SurfaceInfo};
use std::time::Instant;
-pub(crate) fn list_surfaces_for_pid(
- pid: i32,
+pub(crate) fn list_surfaces_for_process(
+ identity: crate::system::process::process_identity::ProcessIdentity,
deadline: Instant,
) -> Result<Vec<SurfaceInfo>, AdapterError> {
- ensure_before_deadline(deadline)?;
- let app = element_for_pid(pid);
- let mut surfaces = Vec::new();
-
- if let Some(children) = read_array(&app, "AXChildren", deadline)? {
- collect_app_surfaces(&children, deadline, &mut surfaces)?;
- }
- if let Some(focused) = read_element(&app, "AXFocusedUIElement", deadline)? {
- collect_context_menus(&focused, deadline, &mut surfaces)?;
- }
- if let Some(window) = read_element(&app, "AXFocusedWindow", deadline)? {
- collect_window_surfaces(&window, "focused-window", deadline, &mut surfaces)?;
- }
-
- complete_menu_inventory(&mut surfaces, |surfaces| {
- if let Some(menu) = super::surfaces::menu_element_for_pid(pid, deadline)? {
- push_menu_surface(
- &menu,
- "context_menu",
- "resolved/menu".into(),
- deadline,
- surfaces,
- )?;
- }
- Ok(())
- })?;
-
- ensure_before_deadline(deadline)?;
- Ok(surfaces)
-}
-
-fn complete_menu_inventory(
- surfaces: &mut Vec<SurfaceInfo>,
- discover: impl FnOnce(&mut Vec<SurfaceInfo>) -> Result<(), AdapterError>,
-) -> Result<(), AdapterError> {
- if !surfaces
- .iter()
- .any(|surface| matches!(surface.kind.as_str(), "menu" | "context_menu"))
- {
- discover(surfaces)?;
- }
- Ok(())
-}
-
-fn collect_app_surfaces(
- children: &[AXElement],
- deadline: Instant,
- surfaces: &mut Vec<SurfaceInfo>,
-) -> Result<(), AdapterError> {
- for (index, child) in children.iter().enumerate() {
- let id = format!("app/children/{index}");
- match read_string(child, "AXRole", deadline)?.as_deref() {
- Some("AXMenuBar") => collect_menubar_surfaces(child, &id, deadline, surfaces)?,
- Some("AXMenu") => push_menu_surface(child, "context_menu", id, deadline, surfaces)?,
- _ => {}
- }
- }
- Ok(())
+ super::app_menu::observe(identity, deadline, || {
+ list_surfaces_once(identity.pid(), deadline)
+ })
}
-fn collect_menubar_surfaces(
- menubar: &AXElement,
- menubar_id: &str,
- deadline: Instant,
- surfaces: &mut Vec<SurfaceInfo>,
-) -> Result<(), AdapterError> {
- let Some(items) = read_array(menubar, "AXChildren", deadline)? else {
- return Ok(());
- };
- for (item_index, item) in items.iter().enumerate() {
- if read_string(item, "AXRole", deadline)?.as_deref() != Some("AXMenuBarItem")
- || read_bool(item, "AXSelected", deadline)? != Some(true)
- {
- continue;
- }
- let Some(children) = read_array(item, "AXChildren", deadline)? else {
- continue;
- };
- for (menu_index, menu) in children.iter().enumerate() {
- if read_string(menu, "AXRole", deadline)?.as_deref() == Some("AXMenu") {
- push_menu_surface(
- menu,
- "menu",
- format!("{menubar_id}/items/{item_index}/children/{menu_index}"),
- deadline,
- surfaces,
- )?;
+fn list_surfaces_once(pid: i32, deadline: Instant) -> Result<Vec<SurfaceInfo>, AdapterError> {
+ let app = element_for_pid(pid);
+ list_surfaces_with(
+ deadline,
+ || {
+ let mut surfaces = Vec::new();
+ if let Some(window) = read_element(&app, "AXFocusedWindow", deadline)? {
+ collect_window_surfaces(&window, "focused-window", deadline, &mut surfaces)?;
}
- }
- }
- Ok(())
+ Ok(surfaces)
+ },
+ || {
+ let mut surfaces = Vec::new();
+ for (kind, id, menu) in super::app_menu::open_menus_for_pid(pid, deadline)? {
+ push_menu_surface(&menu, kind, id, deadline, &mut surfaces)?;
+ }
+ Ok(surfaces)
+ },
+ )
}
-fn collect_context_menus(
- element: &AXElement,
+fn list_surfaces_with(
deadline: Instant,
- surfaces: &mut Vec<SurfaceInfo>,
-) -> Result<(), AdapterError> {
- let Some(children) = read_array(element, "AXChildren", deadline)? else {
- return Ok(());
- };
- for (index, child) in children.iter().enumerate() {
- if read_string(child, "AXRole", deadline)?.as_deref() == Some("AXMenu") {
- push_menu_surface(
- child,
- "context_menu",
- format!("focused/children/{index}"),
- deadline,
- surfaces,
- )?;
- }
- }
- Ok(())
+ window_surfaces: impl FnOnce() -> Result<Vec<SurfaceInfo>, AdapterError>,
+ menu_surfaces: impl FnOnce() -> Result<Vec<SurfaceInfo>, AdapterError>,
+) -> Result<Vec<SurfaceInfo>, AdapterError> {
+ ensure_before_deadline(deadline)?;
+ let mut surfaces = menu_surfaces()?;
+ surfaces.extend(window_surfaces()?);
+ ensure_before_deadline(deadline)?;
+ Ok(surfaces)
}
fn push_menu_surface(
@@ -205,14 +128,6 @@ fn read_string(
crate::tree::surface_read::string(element, attribute, deadline)
}
-fn read_bool(
- element: &AXElement,
- attribute: &str,
- deadline: Instant,
-) -> Result<Option<bool>, AdapterError> {
- crate::tree::surface_read::boolean(element, attribute, deadline)
-}
-
fn read_array(
element: &AXElement,
attribute: &str,
diff --git a/crates/macos/src/tree/surface_inventory_tests.rs b/crates/macos/src/tree/surface_inventory_tests.rs
index 9ad353493..82b833df8 100644
--- a/crates/macos/src/tree/surface_inventory_tests.rs
+++ b/crates/macos/src/tree/surface_inventory_tests.rs
@@ -1,52 +1,77 @@
use super::*;
use std::time::Duration;
-#[test]
-fn expired_deadline_fails_before_accessibility_inventory() {
- let deadline = Instant::now() - Duration::from_millis(1);
-
- let pid = i32::try_from(std::process::id()).expect("test pid fits macOS pid_t");
- let error = list_surfaces_for_pid(pid, deadline)
- .expect_err("an expired surface inventory must time out");
-
- assert_eq!(error.code.as_str(), "TIMEOUT");
-}
-
-fn surface(kind: &str) -> SurfaceInfo {
+fn surface(id: &str, kind: &str) -> SurfaceInfo {
SurfaceInfo {
- id: kind.into(),
+ id: id.into(),
kind: kind.into(),
- title: None,
- item_count: None,
+ title: Some(format!("{kind} title")),
+ item_count: Some(3),
unclassified: Vec::new(),
}
}
#[test]
fn shared_menu_discovery_preserves_other_surfaces_and_existing_menu_ids() {
- let mut surfaces = vec![surface("sheet")];
- complete_menu_inventory(&mut surfaces, |surfaces| {
- surfaces.push(surface("context_menu"));
- Ok(())
- })
- .unwrap();
- assert_eq!(surfaces.len(), 2);
- assert_eq!(surfaces[0].kind, "sheet");
- assert_eq!(surfaces[1].kind, "context_menu");
-
- for kind in ["menu", "context_menu"] {
- let mut surfaces = vec![surface(kind)];
- complete_menu_inventory(&mut surfaces, |_| panic!("must not duplicate menus")).unwrap();
- assert_eq!(surfaces.len(), 1);
- assert_eq!(surfaces[0].id, kind);
+ let window_surfaces = vec![
+ surface("focused-window", "sheet"),
+ surface("focused-window/children/2", "popover"),
+ surface("focused-window/children/4", "alert"),
+ ];
+ for menus in [
+ vec![],
+ vec![surface("app/menubar/children/1/children/0", "menu")],
+ ] {
+ let mut expected = menus.clone();
+ expected.extend(window_surfaces.clone());
+ let actual = list_surfaces_with(
+ Instant::now() + Duration::from_secs(1),
+ || Ok(window_surfaces.clone()),
+ || Ok(menus),
+ )
+ .unwrap();
+ assert_eq!(
+ serde_json::to_value(actual).unwrap(),
+ serde_json::to_value(expected).unwrap()
+ );
}
}
#[test]
fn incomplete_shared_discovery_is_not_reported_as_an_empty_inventory() {
- let mut surfaces = Vec::new();
- let error = complete_menu_inventory(&mut surfaces, |_| Err(AdapterError::permission_denied()))
+ for failed_menu in [true, false] {
+ let read = |fail| {
+ if fail {
+ Err(
+ AdapterError::new(agent_desktop_core::ErrorCode::AppUnresponsive, "incomplete")
+ .with_details(
+ serde_json::json!({ "complete": false, "attribute": "AXChildren" }),
+ ),
+ )
+ } else {
+ Ok(vec![surface("observed", "sheet")])
+ }
+ };
+ let error = list_surfaces_with(
+ Instant::now() + Duration::from_secs(1),
+ || read(!failed_menu),
+ || read(failed_menu),
+ )
.unwrap_err();
- assert_eq!(error.code.as_str(), "PERM_DENIED");
- assert!(surfaces.is_empty());
+ let details = error.details.unwrap();
+ assert_eq!(details["complete"], false);
+ assert_eq!(details["attribute"], "AXChildren");
+ }
+}
+
+#[test]
+fn expired_deadline_fails_before_accessibility_inventory() {
+ let deadline = Instant::now() - Duration::from_millis(1);
+ let pid = i32::try_from(std::process::id()).expect("test pid fits macOS pid_t");
+ let identity = crate::system::process::process_identity::ProcessIdentity::capture(pid)
+ .unwrap()
+ .unwrap();
+ let error =
+ list_surfaces_for_process(identity, deadline).expect_err("expired surface inventory");
+ assert_eq!(error.code.as_str(), "TIMEOUT");
}
diff --git a/crates/macos/src/tree/surface_read.rs b/crates/macos/src/tree/surface_read.rs
index bd5d17886..afd0b8fe8 100644
--- a/crates/macos/src/tree/surface_read.rs
+++ b/crates/macos/src/tree/surface_read.rs
@@ -22,10 +22,10 @@ fn elements_with_reader(
read_attribute: impl FnMut(&str) -> super::query::child_read::ChildRead,
) -> Result<Vec<super::AXElement>, AdapterError> {
let read = super::query::child_source::read_resilient(&[attribute], deadline, read_attribute);
- ensure_before_deadline(deadline)?;
if read.status.api_disabled {
return Err(map_error(attribute, accessibility_sys::kAXErrorAPIDisabled));
}
+ ensure_before_deadline(deadline)?;
if read.status.invalid_element {
return Err(map_error(
attribute,
@@ -39,6 +39,9 @@ fn elements_with_reader(
)
.with_details(serde_json::json!({
"kind": "surface_array_incomplete",
+ "retryable": !read.complete
+ && read.total_count <= agent_desktop_core::ObservationBudget::default().max_children_per_node
+ && (read.status.count_changed || read.status.health.cannot_complete > 0),
"attribute": attribute,
"complete": false,
"total_count": read.total_count,
@@ -126,6 +129,12 @@ fn finish<T>(
attribute: &str,
deadline: Instant,
) -> Result<Option<T>, AdapterError> {
+ if result
+ .as_ref()
+ .is_err_and(|error| *error == accessibility_sys::kAXErrorAPIDisabled)
+ {
+ return Err(map_error(attribute, accessibility_sys::kAXErrorAPIDisabled));
+ }
ensure_before_deadline(deadline)?;
result.map_err(|error| map_error(attribute, error))
}
@@ -140,7 +149,7 @@ pub(crate) fn map_error(attribute: &str, error: i32) -> AdapterError {
} else if error == kAXErrorCannotComplete {
ErrorCode::Timeout
} else if error == kAXErrorInvalidUIElement {
- ErrorCode::ElementNotFound
+ ErrorCode::AppUnresponsive
} else {
ErrorCode::ActionFailed
};
@@ -152,6 +161,7 @@ pub(crate) fn map_error(attribute: &str, error: i32) -> AdapterError {
"attribute": attribute,
"ax_error": error,
"kind": "surface_read",
+ "complete": false,
"retryable": error == kAXErrorCannotComplete,
}))
.with_suggestion("Retry after the application finishes updating its accessibility surfaces")
@@ -169,7 +179,7 @@ mod tests {
};
#[test]
- fn classifier_preserves_permission_timeout_and_stale_states() {
+ fn classifier_preserves_permission_timeout_and_incomplete_observation() {
assert_eq!(
map_error("AXRole", kAXErrorAPIDisabled).code,
ErrorCode::PermDenied
@@ -180,7 +190,40 @@ mod tests {
);
assert_eq!(
map_error("AXRole", kAXErrorInvalidUIElement).code,
- ErrorCode::ElementNotFound
+ ErrorCode::AppUnresponsive
+ );
+ let stale = map_error("AXRole", kAXErrorInvalidUIElement);
+ let details = stale.details.unwrap();
+ assert_eq!(details["complete"], false);
+ assert_eq!(details["retryable"], false);
+ assert_eq!(details["ax_error"], kAXErrorInvalidUIElement);
+ }
+
+ #[test]
+ fn permission_failure_survives_expiry_but_success_never_does() {
+ let expired = Instant::now();
+ let permission = finish::<()>(Err(kAXErrorAPIDisabled), "AXRole", expired).unwrap_err();
+ assert_eq!(permission.code, ErrorCode::PermDenied);
+ assert_eq!(
+ finish(Ok(Some(())), "AXRole", expired).unwrap_err().code,
+ ErrorCode::Timeout
+ );
+ let permission = elements_with_reader("AXChildren", expired, |_| {
+ let mut read = super::super::query::child_read::ChildRead::empty(false);
+ read.status.api_disabled = true;
+ read
+ })
+ .err()
+ .expect("permission failure must reject the array read");
+ assert_eq!(permission.code, ErrorCode::PermDenied);
+ assert_eq!(
+ elements_with_reader("AXChildren", expired, |_| {
+ super::super::query::child_read::ChildRead::empty(true)
+ })
+ .err()
+ .expect("expired deadline must reject the successful array read")
+ .code,
+ ErrorCode::Timeout
);
}
@@ -188,6 +231,7 @@ mod tests {
fn a_busy_read_is_retryable_while_a_terminal_one_is_not() {
assert!(map_error("AXRole", kAXErrorCannotComplete).is_transient_incomplete_read());
assert!(!map_error("AXRole", kAXErrorAPIDisabled).is_transient_incomplete_read());
+ assert!(!map_error("AXRole", kAXErrorInvalidUIElement).is_transient_incomplete_read());
}
#[test]
@@ -215,6 +259,44 @@ mod tests {
assert_eq!(native_ax_error(false, false, 0), None);
}
+ #[test]
+ fn array_retryability_comes_from_native_transience_not_truncation() {
+ for variant in 0..6 {
+ let error = elements_with_reader(
+ "AXChildren",
+ Instant::now() + std::time::Duration::from_secs(1),
+ |_| {
+ let mut read =
+ super::super::query::child_read::ChildRead::empty(matches!(variant, 2 | 5));
+ match variant {
+ 0 => read.status.health.cannot_complete = 1,
+ 1 => read.status.count_changed = true,
+ 2 | 4 | 5 => {
+ read.total_count = agent_desktop_core::ObservationBudget::default()
+ .max_children_per_node
+ + 1;
+ if variant >= 4 {
+ read.status.health.cannot_complete = 1;
+ read.status.count_changed = true;
+ }
+ }
+ _ => read.status.health.native_read_failures = 1,
+ }
+ if variant == 5 {
+ read.complete = false;
+ read.prefix_certain = false;
+ }
+ read
+ },
+ )
+ .err()
+ .expect("incomplete array read must fail");
+ assert_eq!(error.code, ErrorCode::AppUnresponsive);
+ assert_eq!(error.is_transient_incomplete_read(), variant < 2);
+ assert_eq!(error.permits_retry_by_default(), variant < 2);
+ }
+ }
+
#[test]
fn surface_read_recovers_transient_failure_before_reporting_missing_windows() {
let mut calls = 0;
diff --git a/crates/macos/src/tree/surfaces.rs b/crates/macos/src/tree/surfaces.rs
index be25e8e13..b87ce8c71 100644
--- a/crates/macos/src/tree/surfaces.rs
+++ b/crates/macos/src/tree/surfaces.rs
@@ -1,9 +1,7 @@
use super::{AXElement, properties::element::element_for_pid, surface_read};
-use agent_desktop_core::{AdapterError, ErrorCode, SnapshotSurface};
+use agent_desktop_core::{AdapterError, SnapshotSurface};
use std::time::Instant;
-const MAX_SURFACE_NODES: usize = 2_048;
-
#[cfg(target_os = "macos")]
pub(crate) fn focused_surface_for_pid(
pid: i32,
@@ -13,135 +11,18 @@ pub(crate) fn focused_surface_for_pid(
surface_read::element(&app, "AXFocusedWindow", deadline)
}
-#[cfg(target_os = "macos")]
-pub(crate) fn menubar_for_pid(
- pid: i32,
- deadline: Instant,
-) -> Result<Option<AXElement>, AdapterError> {
- let app = element_for_pid(pid);
- for child in surface_read::elements(&app, "AXChildren", deadline)? {
- if has_role(&child, "AXMenuBar", deadline)? {
- return Ok(Some(child));
- }
- }
- Ok(None)
-}
-
#[cfg(target_os = "macos")]
pub(crate) fn menu_element_for_pid(
pid: i32,
deadline: Instant,
) -> Result<Option<AXElement>, AdapterError> {
- if let Some(menu) = open_menubar_menu(pid, deadline)? {
- return Ok(Some(menu));
- }
- context_menu_from_app(pid, deadline)
-}
-
-#[cfg(target_os = "macos")]
-fn open_menubar_menu(pid: i32, deadline: Instant) -> Result<Option<AXElement>, AdapterError> {
- let Some(menubar) = menubar_for_pid(pid, deadline)? else {
- return Ok(None);
- };
- for item in surface_read::elements(&menubar, "AXChildren", deadline)? {
- if !has_role(&item, "AXMenuBarItem", deadline)?
- || surface_read::boolean(&item, "AXSelected", deadline)? != Some(true)
- {
- continue;
- }
- for child in surface_read::elements(&item, "AXChildren", deadline)? {
- if has_role(&child, "AXMenu", deadline)? {
- return Ok(Some(child));
- }
- }
- }
- Ok(None)
-}
-
-#[cfg(target_os = "macos")]
-fn context_menu_from_app(pid: i32, deadline: Instant) -> Result<Option<AXElement>, AdapterError> {
- let app = element_for_pid(pid);
- for menu in surface_read::elements(&app, "AXMenus", deadline)? {
- if displayed_menu(&menu, deadline)? {
- return Ok(Some(menu));
- }
- }
- if let Some(focused) = surface_read::element(&app, "AXFocusedUIElement", deadline)?
- && let Some(menu) = find_menu_descendant(focused, deadline)?
- {
- return Ok(Some(menu));
- }
- for child in surface_read::elements(&app, "AXChildren", deadline)? {
- if let Some(menu) = find_menu_descendant(child, deadline)? {
- return Ok(Some(menu));
- }
- }
- Ok(None)
-}
-
-#[cfg(target_os = "macos")]
-fn find_menu_descendant(
- root: AXElement,
- deadline: Instant,
-) -> Result<Option<AXElement>, AdapterError> {
- find_menu_descendant_with(root, deadline, |element| {
- let role = surface_read::string(element, "AXRole", deadline)?;
- if role.as_deref() == Some("AXMenuBar") {
- return Ok((false, Vec::new()));
- }
- if role.as_deref() == Some("AXMenu")
- && surface_read::boolean(element, "AXVisible", deadline)? != Some(false)
- {
- return Ok((true, Vec::new()));
- }
- Ok((
- false,
- surface_read::elements(element, "AXChildren", deadline)?,
- ))
+ let identity = crate::system::process::process_identity::ProcessIdentity::capture(pid)?
+ .ok_or_else(|| AdapterError::stale_ref_because("Menu application exited"))?;
+ super::app_menu::observe(identity, deadline, || {
+ super::app_menu::root_for_pid(pid, SnapshotSurface::Menu, deadline)
})
}
-fn find_menu_descendant_with<T>(
- root: T,
- deadline: Instant,
- mut inspect: impl FnMut(&T) -> Result<(bool, Vec<T>), AdapterError>,
-) -> Result<Option<T>, AdapterError> {
- let mut pending = std::collections::VecDeque::from([root]);
- let mut incomplete = None;
- let mut visited = 0_usize;
- while let Some(element) = pending.pop_front() {
- surface_read::ensure_before_deadline(deadline)?;
- visited += 1;
- if visited > MAX_SURFACE_NODES {
- return Err(surface_limit_error());
- }
- let (is_menu, children) = match inspect(&element) {
- Ok(observed) => observed,
- Err(error) if error.code == ErrorCode::AppUnresponsive => {
- incomplete.get_or_insert(error);
- continue;
- }
- Err(error) => return Err(error),
- };
- if is_menu {
- return Ok(Some(element));
- }
- pending.extend(children);
- }
- incomplete.map_or(Ok(None), Err)
-}
-
-#[cfg(target_os = "macos")]
-fn displayed_menu(element: &AXElement, deadline: Instant) -> Result<bool, AdapterError> {
- Ok(has_role(element, "AXMenu", deadline)?
- && surface_read::boolean(element, "AXVisible", deadline)? != Some(false))
-}
-
-#[cfg(target_os = "macos")]
-fn has_role(element: &AXElement, expected: &str, deadline: Instant) -> Result<bool, AdapterError> {
- Ok(surface_read::string(element, "AXRole", deadline)?.as_deref() == Some(expected))
-}
-
#[cfg(target_os = "macos")]
fn first_child_with_role_or_subrole(
pid: i32,
@@ -260,19 +141,6 @@ pub(crate) fn is_menu_open(pid: i32, deadline: Instant) -> Result<bool, AdapterE
Ok(menu_element_for_pid(pid, deadline)?.is_some())
}
-fn surface_limit_error() -> AdapterError {
- AdapterError::new(
- ErrorCode::AppUnresponsive,
- "Accessibility surface search exceeded its node budget",
- )
- .with_details(serde_json::json!({
- "kind": "surface_search_limit",
- "limit": MAX_SURFACE_NODES,
- "complete": false,
- }))
- .with_suggestion("Retry with the target application in a more stable UI state")
-}
-
#[cfg(not(target_os = "macos"))]
macro_rules! unsupported_surface {
($name:ident) => {
@@ -288,8 +156,6 @@ macro_rules! unsupported_surface {
#[cfg(not(target_os = "macos"))]
unsupported_surface!(focused_surface_for_pid);
#[cfg(not(target_os = "macos"))]
-unsupported_surface!(menubar_for_pid);
-#[cfg(not(target_os = "macos"))]
unsupported_surface!(menu_element_for_pid);
#[cfg(not(target_os = "macos"))]
unsupported_surface!(sheet_for_pid);
@@ -302,98 +168,3 @@ unsupported_surface!(alert_for_pid);
pub(crate) fn is_menu_open(_pid: i32, _deadline: Instant) -> Result<bool, AdapterError> {
Ok(false)
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn surface_node_limit_is_explicitly_incomplete() {
- let error = surface_limit_error();
-
- assert_eq!(error.code, ErrorCode::AppUnresponsive);
- assert_eq!(error.details.expect("limit details")["complete"], false);
- }
-
- #[test]
- fn menus_beyond_eight_wrappers_remain_discoverable() {
- let deadline = Instant::now() + std::time::Duration::from_secs(5);
- for target_depth in [9, 11, 30] {
- let found = find_menu_descendant_with(0, deadline, |depth| {
- Ok((*depth == target_depth, vec![depth + 1]))
- })
- .unwrap();
- assert_eq!(found, Some(target_depth));
- }
- }
-
- #[test]
- fn cyclic_menu_search_remains_bounded_and_explicitly_incomplete() {
- let mut reads = 0;
- let error = find_menu_descendant_with(
- 0,
- Instant::now() + std::time::Duration::from_secs(5),
- |node| {
- reads += 1;
- Ok((false, vec![*node]))
- },
- )
- .unwrap_err();
- assert_eq!(reads, MAX_SURFACE_NODES);
- assert_eq!(error.details.unwrap()["complete"], false);
- }
-
- #[test]
- fn expired_menu_search_never_reads_a_node() {
- let result = find_menu_descendant_with::<()>((), Instant::now(), |_| {
- panic!("expired search must not call AX")
- });
- assert_eq!(result.unwrap_err().code, ErrorCode::Timeout);
- }
-
- #[test]
- fn incomplete_content_branch_does_not_hide_a_menu_in_a_sibling() {
- let result = find_menu_descendant_with(
- 0,
- Instant::now() + std::time::Duration::from_secs(5),
- |node| match node {
- 0 => Ok((false, vec![1, 2])),
- 1 => Err(surface_limit_error()),
- 2 => Ok((true, vec![])),
- _ => unreachable!(),
- },
- );
- assert_eq!(result.unwrap(), Some(2));
- }
-
- #[test]
- fn an_incomplete_branch_cannot_prove_menu_absence() {
- let result = find_menu_descendant_with(
- 0,
- Instant::now() + std::time::Duration::from_secs(5),
- |node| match node {
- 0 => Ok((false, vec![1, 2])),
- 1 => Err(surface_limit_error()),
- _ => Ok((false, vec![])),
- },
- );
- assert_eq!(result.unwrap_err().details.unwrap()["complete"], false);
- }
-
- #[test]
- fn shallow_menu_precedes_unbounded_content_and_permission_errors_stay_terminal() {
- let deadline = Instant::now() + std::time::Duration::from_secs(5);
- let found = find_menu_descendant_with(0, deadline, |node| match node {
- 0 => Ok((false, vec![1, 2])),
- 1 => Ok((false, vec![1])),
- _ => Ok((true, vec![])),
- });
- assert_eq!(found.unwrap(), Some(2));
- let denied = find_menu_descendant_with(0, deadline, |node| match node {
- 0 => Ok((false, vec![1, 2])),
- 1 => Err(AdapterError::new(ErrorCode::PermDenied, "denied")),
- _ => panic!("permission failure must stop all further AX reads"),
- });
- assert_eq!(denied.unwrap_err().code, ErrorCode::PermDenied);
- }
-}
diff --git a/crates/windows/src/tree/observe.rs b/crates/windows/src/tree/observe.rs
index e4a6985be..d83138d1f 100644
--- a/crates/windows/src/tree/observe.rs
+++ b/crates/windows/src/tree/observe.rs
@@ -140,6 +140,9 @@ fn has_room_for_another_walk(deadline: Deadline, last_walk: Duration) -> bool {
/// so a recycled pid never inherits another process's settle state.
fn root_process_identity(root: ObservationRoot<'_>) -> ProcessIdentity {
match root {
+ ObservationRoot::Application { app, .. } => {
+ ProcessIdentity::new(app.pid, app.process_instance.clone().unwrap_or_default())
+ }
ObservationRoot::Window(window) => ProcessIdentity::new(
window.pid,
window.process_instance.clone().unwrap_or_default(),
@@ -166,6 +169,9 @@ fn still_thin_after_settle() -> AdapterError {
/// Rechecks stored ownership and generation evidence after the UIA read.
fn re_verify_root(root: ObservationRoot<'_>) -> Result<(), AdapterError> {
match root {
+ ObservationRoot::Application { .. } => {
+ Err(AdapterError::not_supported("application observation root"))
+ }
ObservationRoot::Window(window) => {
let handle = hwnd_of(&window.id)?;
let evidence =
diff --git a/crates/windows/src/tree/surfaces.rs b/crates/windows/src/tree/surfaces.rs
index c70e18d1b..2791f1c3a 100644
--- a/crates/windows/src/tree/surfaces.rs
+++ b/crates/windows/src/tree/surfaces.rs
@@ -23,6 +23,9 @@ pub(crate) fn surface_root(
deadline: Deadline,
) -> Result<UIAElement, AdapterError> {
match (root, surface) {
+ (ObservationRoot::Application { .. }, _) => {
+ Err(AdapterError::not_supported("application observation root"))
+ }
(ObservationRoot::Window(window), _) if window.is_process_owner() => {
Err(AdapterError::app_has_no_window(&window.app))
}
diff --git a/docs/json-output.md b/docs/json-output.md
index 2b0a90e78..03fadda8c 100644
--- a/docs/json-output.md
+++ b/docs/json-output.md
@@ -121,19 +121,47 @@ Version 2.6 changes which refs resolve on Windows and Linux, and on macOS for an
- When a ref action's full resolution under the lease is refused in a way that may clear, the action waits again within its `--timeout-ms`. If that budget then runs out, the error carries the refusal in `details.refusal`: its `code`, `message`, and `details` when the refusal had any.
- A surface kind the OS does not have now returns `INVALID_ARGS` instead of `PLATFORM_NOT_SUPPORTED`, with the disposition `not_delivered` and `retry: "safe"`. FFI callers see the matching `AdResult` code change. An adapter with no surfaces at all still returns `PLATFORM_NOT_SUPPORTED`.
- On macOS, `open-system-surface --surface dock` and `--surface menu-bar-extras` now succeed headless. Their `data` has no `window`; check for the field before reading it. Windows and Linux still return `window` and need `--headed`.
-- On macOS, a snapshot of a background app that lists no window (a menu bar app, the Dock, Control Center), and `--surface dock` or `--surface menu-bar-extras`, now succeed and read the app through its process. Earlier they failed `WINDOW_NOT_FOUND`. `data.window` is omitted from such a snapshot and `data.app` names the process; check for the field before reading `data.window.id`.
+- On macOS, a snapshot of a background app that lists no window (a menu-bar app, the Dock, Control Center), and `--surface dock` or `--surface menu-bar-extras`, now succeed and read the app through its process. Earlier they failed `WINDOW_NOT_FOUND`. `data.window` is omitted from such a snapshot and `data.app` names the process; check for the field before reading `data.window.id`.
A snapshot that needed one complete read of its window to prove its refs, and could not get it, says so with `"identity_unproven": true` in `data`. `complete` still describes the presented tree. On Windows and Linux, and on macOS for an element with no address, every ref of that snapshot fails `AMBIGUOUS_TARGET` with `details.kind: "identity_not_unique"`; retake the snapshot with a larger `--timeout-ms`. The field is omitted otherwise.
-## Headed action verification
+On macOS, application-owned `menu` and `menubar` snapshots omit `data.window`. `data.app` identifies the owner, including for a `--root` drill into a ref from one of these surfaces. Window-owned snapshots retain `data.window`. When `--window-id` is supplied for an application-owned surface, it selects the owning app while the observed surface remains application-owned.
+
+A complete macOS menu lookup with no surface returns `ELEMENT_NOT_FOUND` with `details.kind: "surface_absent"`, `details.surface: "menu"` or `"menubar"`, and `details.complete: true`. That is completed absence evidence. An absent `menubar` can mean the application exposes no menu bar. A `menu` lookup requires an open menu: snapshot `menubar` when it exists, click its owning item without `--headed`, then snapshot `--surface menu`. Missing `complete`, `complete: false`, a timeout, or an incomplete AX read leaves the result unknown, not absent. If a prior action has `delivery_uncertain` and `retry: unsafe`, inspect the current UI before any action; do not repeat the action.
-- Headed ref interactions activate the exact source app/window before final pointer hit testing. Read-only readiness polling must not prevent a background target from reaching that focus phase; final hit testing remains mandatory before delivery.
-- On macOS, a ref read through a background app's process has no window to activate, and a target in a background app (a menu bar app, the Dock, a system panel) or a status item skips the frontmost-app and main-window checks, because such an app never becomes frontmost. Final hit testing still gates delivery. Any other target without a verified owning window is refused.
- Focus and preparatory scrolling can change coordinates. Stability is verified against fresh live observations, not by requiring coordinates to remain equal to the original snapshot.
-- On macOS, post-activation focus confirmation uses fresh system-wide `AXFocusedApplication` and exact-window evidence with process-generation checks. A cached `NSWorkspace` foreground snapshot is not sufficient in a process that just activated another app.
+- On macOS, clicking an item in the native menu bar uses `AXPress`. It works headless, and under `--headed` it does not move the pointer. A headless `right-click` can use `AXShowMenu` when the target provides it.
+
- Focusing an inactive text field can change its selection. A pre-focus range cannot establish the expected insertion into a nonempty field; such a result is explicitly unverified rather than falsely contradicted.
- A settle-loop pacing budget does not replace the caller's deadline for native reads. Tests assert deadline identity rather than arbitrary remaining-time thresholds.
+### Post-action observation
+
+When a ref action returns `delivery_uncertain` with a post-action wait selector, `error.details.post_action_observation` records a read-only observation of the original process. Application-owned refs keep their source surface. Window-owned refs observe their original pinned window, including refs captured from `sheet`, `alert`, `popover`, `focused`, or a window-owned `menu` such as a Linux menu. This lets a closed overlay be observed without treating the parent window as absent. The action is never repeated, and its original error and unsafe retry disposition stay unchanged. Even `expected_state_observed` does not prove that the action caused the state. Observation uses `--wait-timeout` separately from the action timeout.
+
+| Field | Meaning |
+| --- | --- |
+| `kind` | Always `post_action_observation`. |
+| `selector, expected` | Requested selector and `present` or `absent`. |
+| `surface` | The observed scope: the application-owned source surface, or `window` for a window-owned ref. |
+| `process_identity` | Original `pid` and `process_instance`; the instance can be null for `identity_unavailable`. |
+| `elapsed_ms` | Time spent observing after the action returned. |
+| `source_window_id` | Original window ID, when the ref has one. |
+| `selector_matches` | Observed selector result, when available; absence requires a complete read. |
+| `process_state` | Last observed `unresponsive`, `exited`, or `crashed` state. `running` is never emitted. |
+| `last_observation_error` | Last observation error's `code` and `message`, when available. |
+| `outcome` | One of the outcomes below. |
+
+| Outcome | Meaning |
+| --- | --- |
+| `expected_state_observed` | The expected selector state was observed, or the original window or surface was confirmed absent for an absence wait. |
+| `process_exited` | The original process exited; this does not establish the action's effect. |
+| `process_crashed` | The platform reported that the original process crashed. |
+| `owner_unavailable` | The original surface owner remained unavailable without confirmed process exit. |
+| `observation_failed` | A terminal read error stopped observation; inspect `last_observation_error`. |
+| `timed_out` | The wait budget expired without observing the expected state, including when transient read errors persisted through the last poll. `last_observation_error` may hold the last error. |
+| `identity_unavailable` | The ref has no usable process generation, so observation was skipped. |
+
## Find result shape
`find` match objects report the element's actual accessibility `name`. Elements
@@ -164,7 +192,7 @@ After the core resolver chooses the element, the platform adapter lands it, and
|------|---------|
| `PERM_DENIED` | Accessibility permission not granted |
| `ELEMENT_NOT_FOUND` | No element matched the ref or query |
-| `APP_NOT_FOUND` | Application not running or no windows; the lookup failed before anything was sent, so the disposition is `not_delivered` |
+| `APP_NOT_FOUND` | No matching application process; the lookup failed before anything was sent, so the disposition is `not_delivered` |
| `STALE_REF` | Ref could not be re-identified in the live UI |
| `AMBIGUOUS_TARGET` | Ref recovery matched multiple plausible targets |
| `SNAPSHOT_NOT_FOUND` | Snapshot ID is missing or expired |
diff --git a/skills/agent-desktop-ffi/SKILL.md b/skills/agent-desktop-ffi/SKILL.md
index 15407b94c..5ec5fad9c 100644
--- a/skills/agent-desktop-ffi/SKILL.md
+++ b/skills/agent-desktop-ffi/SKILL.md
@@ -58,9 +58,11 @@ ad_adapter_destroy(adapter)
`ad_snapshot` returns the CLI envelope `{version, ok, command, data}`.
`data.tree` carries snapshot-qualified refs for interactive elements. Read
`data.complete` before trusting a tree: `false` means the observation budget ran
-out and the tree is partial, not an error. `ad_snapshot` always targets the
-focused window of `app`; window targeting, skeleton mode and `--root` drill-down
-are not exposed over the ABI. A bare `@eN` ref returns
+out and the tree is partial, not an error. `ad_snapshot` reads the owner selected
+by `surface`. On macOS, `menu` and `menubar` are application-owned, need no
+document window, and omit `data.window`; window-owned snapshots include it.
+Window targeting, skeleton mode and `--root` drill-down are not exposed over the
+ABI. A bare `@eN` ref returns
`AD_RESULT_ERR_INVALID_ARGS`.
## Core constraints
diff --git a/skills/agent-desktop-macos/SKILL.md b/skills/agent-desktop-macos/SKILL.md
index 560523e40..c69933f19 100644
--- a/skills/agent-desktop-macos/SKILL.md
+++ b/skills/agent-desktop-macos/SKILL.md
@@ -36,13 +36,12 @@ Read the core skill first (`agent-desktop skills get desktop`) for the observe,
## What differs on macOS
-**Headed is physical first** for `click`, `right-click`, `type`, `clear` and `scroll`. Core focuses the exact window of the ref; a ref from a background app (menu bar app, Dock, system panel) or a status item has no window and is not focused. The adapter then sends a real click, key or wheel event to the verified point. `expand`, `collapse`, `set-value`, `select`, `toggle`, `check`, `uncheck`, `focus` and `scroll-to` stay semantic under `--headed`. Double-click, triple-click, `hover` and `drag` need `--headed`. Raw `--xy` input never changes focus.
+**Headed actions.** `click`, `right-click`, `type`, `clear` and `scroll` use physical paths first, except a click on an item in the application's native menu bar hierarchy, which calls `AXPress` without moving the pointer. A headless click on these menu items also calls `AXPress`. Process-owned refs have no window to focus; other ref-target pointer actions focus the exact owning window and verify the hit target before delivery. A headless `right-click` can use `AXShowMenu` when the target provides it. `expand`, `collapse`, `set-value`, `select`, `toggle`, `check`, `uncheck`, `focus` and `scroll-to` stay semantic under `--headed`. `double-click`, `triple-click`, `hover` and `drag` need `--headed`. Raw `--xy` input never changes focus.
**Judge delivery by observation.** AX return codes do not prove an effect. Finder returns success from an `AXConfirm` that does nothing. Snapshot again or use `get` and `is` to check the result.
-**Surfaces.** Use `--surface menubar` for an app's File, Edit and View menus. Use `--surface menu-bar-extras` for status items: with no `--app` it reads the system items (Wi-Fi, Battery, Clock), and with `--app` it reads that app's own item. Both work for menu bar apps with no window. Use `--surface dock` for the Dock. Both are always on screen, so `open-system-surface` returns them at once, headless, with no `--headed`; `action-center` and `start-menu` are Windows kinds. A background app with no ordinary window (menu bar apps, the Dock, the Control Center and Notification Center panels) is observed through its process: `snapshot --app "Control Center"` after clicking its status item. This applies to `window`, `menubar` and `menu-bar-extras`, not to `focused`, and not to a regular app that has not shown its window yet, which returns `WINDOW_NOT_FOUND`: wait for the window. Control Center rebuilds its tree right after a tile is clicked, so drill in with `snapshot --app "Control Center" --wait-for "<role>:<name>"` rather than an immediate snapshot. Its refs work headless and `--headed`. While a menu, sheet, alert or popover is open, refs from the window tree behind it are the wrong target.
-
-**Menus.** `right-click` headless uses `AXShowMenu`. If the menu opened but the app returned `APP_UNRESPONSIVE` with `retry: unsafe`, do not retry. Inspect the menu with `--surface menu`. For combo boxes and menu buttons, use `select @ref "Option"`. `select` needs a closed-to-open menu transition, so dismiss any open menu first.
+**Surfaces.** Use `--surface menubar` for an app's File, Edit, and View menus. Use `--surface menu-bar-extras` for status items: with no `--app` it reads system items such as Wi-Fi, Battery, and Clock; with `--app` it reads that app's own item. Use `--surface dock` for the Dock. These shell surfaces are available headless through `open-system-surface`. A background app with no ordinary window, such as a menu-bar app or Control Center, can be observed through its process with `snapshot --app "Control Center"`. This applies to `window`, `menubar`, and `menu-bar-extras`, not `focused`; a regular app that has not shown its window returns `WINDOW_NOT_FOUND`. While a menu, sheet, alert, or popover is open, refs from the window tree behind it are the wrong target.
+**Menus.** `right-click` headless uses `AXShowMenu`. If the menu opened but the app returned `APP_UNRESPONSIVE` with `retry: unsafe`, do not retry. Inspect the menu with `--surface menu`. `menu` requires an open menu: if `snapshot --surface menu` returns `surface_absent` with `complete: true`, snapshot `menubar` when it exists, click its item without `--headed`, then snapshot `--surface menu`. An absent `menubar` can mean the app exposes no menu bar. A missing `complete`, `complete: false`, timeout or incomplete read is unknown, not absent. For combo boxes and menu buttons, use `select @ref "Option"`. `select` needs a closed-to-open menu transition, so dismiss any open menu first.
**Notification Center.** The notification commands drive Notification Center through accessibility, with the rules in the core `commands-system` reference. When agent-desktop opens the center, it closes it afterwards and restores the previous app focus. Pass both `--expected-app` and `--expected-title` on a single dismiss or action, because the stack shifts. Use `wait --notification --app "App"` for banners that vanish before you list them.
@@ -50,7 +49,7 @@ Read the core skill first (`agent-desktop skills get desktop`) for the observe,
**Identity.** `launch` accepts a display name (`"System Settings"`) or a bundle ID (`com.apple.systempreferences`). Other commands take the display name through `--app`, or the bundle ID or executable name (`ControlCenter`) when no running app has that display name. Window IDs such as `w-4521` stay valid for the life of the window. Find them with `list-windows`.
-**Refs carry each element's own address.** A ref turns back into the exact element it was captured from, so identical twins, such as several identical `Delete` buttons, each act on their own row. If the element was removed or the app restarted, the ref is `STALE_REF`, `details.kind: retained_object_stale`, and it never falls back to a search for a look-alike. When an app yields no address for an element, that ref follows the cross-platform rule instead and must have been the only element in its window with its role, native id, name and description. Take a fresh snapshot after a list changes.
+**Refs use native addresses when available.** A ref turns back into the exact element it was captured from, so identical twins, such as several identical `Delete` buttons, each act on their own row. If the element was removed or the app restarted, the ref is `STALE_REF`, `details.kind: retained_object_stale`, and it never falls back to a search for a look-alike. When an app yields no address for an element, that ref follows the cross-platform rule instead and must have been the only element in its window with its role, native id, name and description. Take a fresh snapshot after a list changes.
**Keys.** The primary modifier is `cmd`: `press cmd+c`, `press cmd+s`. Quit shortcuts such as `cmd+q`, `cmd+shift+q`, `cmd+alt+esc`, `ctrl+cmd+q` and `cmd+shift+delete` return `POLICY_DENIED` unless you pass `--force`. To quit an app, use `close-app`. Punctuation keys work in combos, as the symbol (`,` `.` `/` `;` `'` `[` `]` `\` `-` `=` `` ` ``) or by name (`comma`, `period`, `slash`, `semicolon`, `quote`, `leftbracket`, `rightbracket`, `backslash`, `minus`, `equal`, `grave`). Each one is sent with the key that types it in the active keyboard layout, so `press cmd+,` opens Settings on ANSI and JIS keyboards alike.
diff --git a/skills/agent-desktop/references/commands-interaction.md b/skills/agent-desktop/references/commands-interaction.md
index 01e6b70c9..983d62159 100644
--- a/skills/agent-desktop/references/commands-interaction.md
+++ b/skills/agent-desktop/references/commands-interaction.md
@@ -42,7 +42,7 @@ Exit codes: `0` success, `1` structured error, `2` argument error. The `error` o
| Code | Meaning | Recovery |
|------|---------|----------|
| `PERM_DENIED` | A required OS permission is missing | Read the platform skill |
-| `ELEMENT_NOT_FOUND` | Ref cannot be resolved in the live UI | Snapshot again |
+| `ELEMENT_NOT_FOUND` | Ref is absent, or the requested surface is absent | Read `details.kind` and `details.surface`; open an absent menu or refresh only after checking the UI |
| `STALE_REF` | Ref no longer matches the live UI | Snapshot again, use the new ref |
| `AMBIGUOUS_TARGET` | Several live elements match the ref's identity, or it was not proven unique at capture | Act on a control unique in the window; identical twins need `--headed mouse-click --xy` (see `commands-observation.md`) |
| `SNAPSHOT_NOT_FOUND` | Snapshot id missing or expired | Snapshot again |
@@ -58,7 +58,9 @@ Exit codes: `0` success, `1` structured error, `2` argument error. The `error` o
| `NOTIFICATION_NOT_FOUND` | Notification index or fingerprint no longer matches | List again |
| `INTERNAL` | Unexpected OS failure | Read `message`. Retry once only if `disposition.retry` is `safe` |
-`TIMEOUT` `details.kind` values: `actionability_timeout` (the target never became actionable), `wait_timeout` (a `wait` condition; carries `predicate`, `timeout_ms`, `last_observed` or `last_error`), `chain_deadline` (an activation chain ran out of time; carries `value_before`, `value_at_timeout`, `target`, `mutated`). With `chain_deadline`, `mutated: true` or an unknown expanded state means re-read before you retry. `mutated: false` means a direct retry is safe.
+`ELEMENT_NOT_FOUND` with `details.kind: "surface_absent"` and `details.complete: true` is complete absence evidence. An absent `menubar` can mean the app exposes no menu bar. For `surface: menu`, snapshot `menubar` when it exists, click its item without `--headed`, then snapshot `--surface menu`. Missing `complete`, `complete: false`, a timeout or an incomplete read is unknown, not absent. If the earlier action has `delivery_uncertain` and `retry: unsafe`, inspect the current UI before any action; do not repeat it.
+
+`TIMEOUT` `details.kind` values: `actionability_timeout` (the target never became actionable), `wait_timeout` (a `wait` condition; carries `predicate`, `timeout_ms`, `last_observed` or `last_error`), `chain_deadline` (an activation chain ran out of time; carries `value_before`, `value_at_timeout`, `target`, `mutated`), and `focus_verification` (macOS did not observe `AXFrontmost` for the app or `AXMain` for the window before the bounded focus readback ended). With `chain_deadline`, `mutated: true` or an unknown expanded state means re-read before you retry. `mutated: false` means a direct retry is safe. With `focus_verification`, `physical_delivery_started: false` means target input had not started; read `disposition` because a dispatched activation can still be `delivered_unverified`.
## Actionability
@@ -168,7 +170,8 @@ agent-desktop click @s8f3k2p9:e5 --wait-for-gone "progressindicator" --wait-time
- The selector is `role:text`, split on the first `:`. `"button"` is role only. `":Saved!"` is text only. Text searches name, value and description.
- They work on `snapshot`, `press` and every ref action. Other commands (`find`, `launch`, ...) return `INVALID_ARGS`. `--root` cannot combine with them. Batch entries never inherit an outer `-w`.
- `--wait-timeout` defaults to 30000. On expiry: exit `1`, `TIMEOUT`, `details.kind: "wait_timeout"`, `details.snapshot_id` of the last tree. A post-action timeout also embeds `details.after_action`.
-- A ref action polls the acted-on ref's window. The action result is kept under `after_action`.
+- A ref action polls its original process. Application-owned refs keep their source surface, including macOS `menu` and `menubar` without a window. Window-owned refs observe their original pinned window, even when captured from `sheet`, `alert`, `popover`, `focused`, or a window-owned `menu` such as a Linux menu. This reads the whole window: a selector elsewhere in the parent can satisfy `--wait-for` early or keep `--wait-for-gone` from succeeding. On Linux, GTK3 context menus and Chromium popups can be exposed outside that window tree, so a gone wait cannot establish that a popup outside the observed scope was dismissed. To observe the overlay itself, use a separate `snapshot` with the desired `--surface` and wait selector. The action result is kept under `after_action`.
+- After `delivery_uncertain`, `error.details.post_action_observation` reports read-only evidence with `outcome`, `selector`, `expected`, `surface`, `process_identity`, and `elapsed_ms`; optional fields are `source_window_id`, `selector_matches`, `process_state`, and `last_observation_error`. `surface` names the observed scope. `process_state` is `unresponsive`, `exited` or `crashed`; `running` is never emitted. Outcomes are `expected_state_observed`, `process_exited`, `process_crashed`, `owner_unavailable`, `observation_failed`, `timed_out`, and `identity_unavailable`. Transient read errors that persist to the deadline end as `timed_out` with the last error; `observation_failed` means a terminal error stopped observation. The original error and unsafe retry disposition remain unchanged, even when the expected state is observed. The wait has its own `--wait-timeout` budget.
- `--wait-for-gone` succeeds with `{ "gone": true, "target_absent": true }` when the app or window itself closed.
- For `drag`, `--wait-for-scope to|from` picks which endpoint window to poll (default `to`).
diff --git a/skills/agent-desktop/references/commands-observation.md b/skills/agent-desktop/references/commands-observation.md
index 2274c2c27..9afed7ab3 100644
--- a/skills/agent-desktop/references/commands-observation.md
+++ b/skills/agent-desktop/references/commands-observation.md
@@ -24,7 +24,7 @@ Output shape:
{ "ref_id": "@s8f3k2p9:e1", "role": "button", "name": "About", "states": ["focused"] } ] } } }
```
-`data.window` is left out when macOS reads a windowless app through its process. On Windows and Linux the same app returns `WINDOW_NOT_FOUND`.
+On macOS, `menu` and `menubar` snapshots are application-owned. They need no document window, include `data.app`, and omit `data.window`. A process-owned snapshot of a background app with no window also omits `data.window`. If you pass `--window-id` for an application-owned menu, it selects the app that owns the surface.
Each ref names the snapshot that owns it, so a ref keeps resolving against its own snapshot when you interleave several apps or windows.
@@ -37,6 +37,7 @@ Choose the scope:
- `--max-depth` (default 10) limits depth. Reach deeper subtrees with `--root`.
- Use `--include-bounds` only when you need coordinates.
- With `--app` and no `--window-id`, `snapshot` and `find` take the app's only visible window, else its only focused window, and answer `AMBIGUOUS_TARGET` with the candidates when neither settles it. Pass `--window-id` when an app has several windows.
+- On macOS, `menu` and `menubar` are application-owned and skip window selection. If you pass `--window-id`, it selects the owning app for that surface.
### Partial trees
@@ -52,7 +53,7 @@ An element gets a ref when its role is interactive or it advertises a primary ac
### Ref re-identification
-A command re-identifies the element from the ref before it acts. On macOS the ref carries the element's own address, so identical twins each keep their ref. On Windows and Linux a ref resolves only when it was the only element in the window its snapshot captured with its role, native id, name and description, and exactly one live element still matches. A skeleton, depth-limited or drilled capture counts against the whole window, so a shallow tree proves the same thing a full one does. Values and bounds never count as identity.
+A command re-identifies the element from the ref before it acts. On macOS, a ref carries the element's native address when available, so identical twins each keep their ref. On Windows and Linux, and on macOS when an element has no address, a ref resolves only when a complete read proved it was the only element in the window with its role, native id, name and description, and exactly one live element still matches. A skeleton, depth-limited or drilled capture counts against the whole window, so a shallow tree proves the same thing a full one does. Values and bounds never count as identity.
- `STALE_REF`, `details.kind: saved_ref_absent`: no live element matches the stored identity. Take a fresh snapshot. On macOS `retained_object_stale` means the recorded address is dead or no longer matches.
- `AMBIGUOUS_TARGET`, `details.kind: saved_ref_ambiguous`: an identical element appeared, so two live elements match. `identity_not_unique`: the ref was not proven unique at capture, so nothing was searched. That is an identical twin, which every snapshot refuses again, or a window the snapshot could not read whole in time, which a new snapshot with a larger `--timeout-ms` fixes.
@@ -62,7 +63,7 @@ Off macOS, identical twins have no ref path: only `--headed mouse-click --xy X,Y
### Surfaces
-Surfaces are overlays: `menu`, `menubar`, `sheet`, `popover`, `alert`, `focused`, plus OS shell kinds on some platforms. Read `supported_surfaces` from `status` before you ask for one. A kind this OS does not have returns `INVALID_ARGS` with the supported list in `details`. A shell surface needs no `--app`; on macOS, `menu-bar-extras` with `--app` reads that app's own status item. When it is closed you get `WINDOW_NOT_FOUND`; raise it with `open-system-surface`.
+Surfaces include `menu`, `menubar`, `sheet`, `popover`, `alert`, `focused`, and OS shell kinds supported on each platform. On macOS, `menu` and `menubar` are application-owned. A kind this OS does not have returns `INVALID_ARGS` with the supported list in `details`; an adapter with no supported surfaces returns `PLATFORM_NOT_SUPPORTED`. A shell surface needs no `--app`, except that macOS `menu-bar-extras` with `--app` reads that app's own status item. A closed shell surface returns `WINDOW_NOT_FOUND`; a complete lookup of an absent macOS menu returns `ELEMENT_NOT_FOUND` with `details.kind: "surface_absent"`. Raise a shell surface with `open-system-surface`.
Use a surface snapshot for dialogs and menus, not a window snapshot. To reach one item inside an overlay, use `find --surface` instead of a full dump.
diff --git a/skills/agent-desktop/references/commands-system.md b/skills/agent-desktop/references/commands-system.md
index 8df47af06..e3b916b1c 100644
--- a/skills/agent-desktop/references/commands-system.md
+++ b/skills/agent-desktop/references/commands-system.md
@@ -79,7 +79,7 @@ agent-desktop minimize --app "TextEdit" # maximize, restore likewise
```
- `list-windows` returns `{ id, title, app_name, pid, bounds, is_focused, accessible }`. Use a `w-<id>` with `--window-id` when an app has several windows.
-- `accessible: false` means semantic commands cannot reach that window. Targeting it returns `ACTION_NOT_SUPPORTED` with `kind: "window_without_accessibility_element"`. It still accepts screenshots and coordinate input. Choose another window.
+- `accessible: false` means semantic commands cannot reach that window. Targeting it returns `ACTION_NOT_SUPPORTED` with `kind: "window_without_accessibility_element"`. It still accepts screenshots and coordinate input. Choose another window. Wait polling treats this error as transient. In particular, `--wait-for-gone` does not count it as absence; it keeps polling until the window disappears from the inventory or the wait times out.
- `focus-window` needs at least one identifier. It confirms the OS reports that window as focused. Otherwise it returns `ACTION_FAILED`.
- `restore` undoes a minimize and returns the window to its earlier placement. It does not promise to un-maximize.
diff --git a/src/cli/contract_command_surface_tests.rs b/src/cli/contract_command_surface_tests.rs
index 0ea311683..6b8d71ecd 100644
--- a/src/cli/contract_command_surface_tests.rs
+++ b/src/cli/contract_command_surface_tests.rs
@@ -17,8 +17,10 @@ const NON_COMMAND_MODULES: &[&str] = &[
"operation_response",
"point_resolve",
"pointer_action",
+ "post_action_observation",
"query",
"find_live_test_support",
+ "selector_observation",
"surface_scope",
"type_text_interval",
"type_text_interval_verify",
diff --git a/tests/conformance/window_identity_contract.rs b/tests/conformance/window_identity_contract.rs
index 0c3079549..1fa8b2468 100644
--- a/tests/conformance/window_identity_contract.rs
+++ b/tests/conformance/window_identity_contract.rs
@@ -39,12 +39,6 @@ impl SystemOps for WindowIdentityAdapter {
format!("Window '{}' identity mismatch", win.id),
));
}
- if !win.title.is_empty() && live.title != win.title {
- return Err(AdapterError::new(
- ErrorCode::WindowNotFound,
- format!("Window '{}' identity mismatch", win.id),
- ));
- }
Ok(live)
}
}
@@ -85,3 +79,20 @@ fn resolve_window_strict_default_is_not_supported() {
assert_eq!(err.code, ErrorCode::PlatformNotSupported);
}
+
+#[test]
+fn renamed_window_retains_its_identity() {
+ let mut target = untitled("w-100", 10);
+ target.title = "Unsaved document".into();
+ let mut live = target.clone();
+ live.title = "Saved document".into();
+ let adapter = WindowIdentityAdapter {
+ windows: vec![live.clone()],
+ };
+ let resolved = adapter
+ .resolve_window_strict(&target, Deadline::standard().unwrap())
+ .unwrap();
+ assert_eq!(resolved.title, live.title);
+ assert_eq!(resolved.id, target.id);
+ assert_eq!(resolved.process_instance, target.process_instance);
+}
diff --git a/tests/e2e/README.md b/tests/e2e/README.md
index 8adc8c34b..d3e7c46ed 100644
--- a/tests/e2e/README.md
+++ b/tests/e2e/README.md
@@ -56,6 +56,16 @@ exclusivity acknowledgement and calls `run.sh`; it refuses to run unless
`AGENT_DESKTOP_NATIVE_E2E_RUNNER=1` is set. The `native-e2e.yml` workflow is
`workflow_dispatch` only.
+## Native menu regression
+
+Run this manually on macOS with a built binary. Close TextEdit first. Grant the terminal Accessibility and System Events automation access; if macOS lists `agent-desktop` separately, grant it access too. The script launches TextEdit without activating it, closes its verified blank document, and checks the menubar with zero AX windows. It leaves TextEdit running if another document appears or changes.
+
+This script is not part of `run.sh`.
+
+```bash
+python3 tests/e2e/native-menus.py --bin /absolute/path/to/agent-desktop
+```
+
## Exact ref namespaces
Every non-count `find` returns two inseparable values:
diff --git a/tests/e2e/native-menus.py b/tests/e2e/native-menus.py
new file mode 100755
index 000000000..ea66d65de
--- /dev/null
+++ b/tests/e2e/native-menus.py
@@ -0,0 +1,325 @@
+#!/usr/bin/env python3
+"""Check native TextEdit menu behavior with no document window open."""
+
+import argparse
+import json
+import os
+import platform
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+
+class Failure(RuntimeError):
+ pass
+
+
+def need(condition, message):
+ if not condition:
+ raise Failure(message)
+
+
+def osa(source):
+ result = subprocess.run(
+ ["/usr/bin/osascript", "-e", source], capture_output=True, text=True, timeout=15
+ )
+ if result.returncode:
+ raise Failure(result.stderr.strip() or "AppleScript failed")
+ return result.stdout.strip()
+
+
+def textedit_running():
+ result = subprocess.run(["/usr/bin/pgrep", "-x", "TextEdit"], capture_output=True)
+ need(result.returncode in (0, 1), "could not check whether TextEdit is running")
+ return result.returncode == 0
+
+
+def process_name(pid):
+ return osa(f'''tell application "System Events"
+set matches to every process whose unix id is {pid}
+if (count of matches) is 0 then return ""
+return name of item 1 of matches as text
+end tell''')
+
+
+def require_owned(pid):
+ need(process_name(pid) == "TextEdit", "task-created TextEdit process changed")
+
+
+def frontmost():
+ value = osa('''tell application "System Events"
+set matches to every process whose frontmost is true
+if (count of matches) is 0 then return ""
+set p to item 1 of matches
+return (name of p as text) & tab & (unix id of p as text)
+end tell''')
+ if not value:
+ return None
+ name, pid = value.split("\t", 1)
+ return name, int(pid)
+
+
+def documents():
+ value = osa('''tell application id "com.apple.TextEdit"
+set docs to every document
+set resultText to count of docs as text
+repeat with d in docs
+set resultText to resultText & linefeed & (name of d as text) & tab & ((modified of d) as text) & tab & ((length of (text of d as text)) as text)
+end repeat
+return resultText
+end tell''')
+ lines = value.splitlines()
+ need(bool(lines), "TextEdit document state was empty")
+ result = [tuple((parts[0], parts[1].lower() == "true", int(parts[2])))
+ for parts in (line.split("\t", 2) for line in lines[1:])]
+ need(int(lines[0]) == len(result), "TextEdit document inventory was inconsistent")
+ return result
+
+
+def ax_windows(pid):
+ return int(osa(f'''tell application "System Events"
+set matches to every process whose unix id is {pid}
+if (count of matches) is 0 then return "0"
+return count of windows of item 1 of matches as text
+end tell'''))
+
+
+def require_windowless(pid):
+ require_owned(pid)
+ need(ax_windows(pid) == 0, "TextEdit acquired an AX window during the regression")
+
+
+def menu_state(pid):
+ value = osa(f'''tell application "System Events"
+set p to first process whose unix id is {pid}
+set menuItems to every menu bar item of menu bar 1 of p
+set names to {{}}
+set selectedNames to {{}}
+repeat with menuItem in menuItems
+set end of names to name of menuItem as text
+try
+if selected of menuItem then set end of selectedNames to name of menuItem as text
+end try
+end repeat
+set AppleScript's text item delimiters to linefeed
+return (names as text) & tab & (selectedNames as text)
+end tell''')
+ names, _, selected = value.partition("\t")
+ return names.splitlines(), selected.splitlines() if selected else []
+
+
+def cancel_open_menus(pid):
+ value = osa(f'''tell application "System Events"
+set p to first process whose unix id is {pid}
+set selectedItems to every menu bar item of menu bar 1 of p whose selected is true
+set cancelCount to 0
+repeat with selectedItem in selectedItems
+set openMenu to menu 1 of selectedItem
+set actionNames to name of every action of openMenu
+if actionNames contains "AXCancel" then
+set ignoredResult to perform action "AXCancel" of openMenu
+set cancelCount to cancelCount + 1
+end if
+end repeat
+set selectedItems to every menu bar item of menu bar 1 of p whose selected is true
+return (cancelCount as text) & tab & (count of selectedItems as text)
+end tell''')
+ _, remaining = value.split("\t", 1)
+ need(int(remaining) == 0, "a native menu remains selected after AXCancel")
+
+
+def cli(binary, env, *args):
+ try:
+ result = subprocess.run(
+ [str(binary), *args], capture_output=True, text=True, timeout=60, env=env
+ )
+ except subprocess.TimeoutExpired as error:
+ raise Failure(f"agent-desktop timed out: {' '.join(args)}") from error
+ try:
+ return result.returncode, json.loads(result.stdout)
+ except json.JSONDecodeError as error:
+ raise Failure(result.stderr.strip() or "agent-desktop returned non-JSON output") from error
+
+
+def ok(result, label):
+ code, value = result
+ need(code == 0 and value.get("ok") is True, f"{label} failed: {value}")
+ return value
+
+
+def walk(node):
+ yield node
+ for child in node.get("children", []):
+ yield from walk(child)
+
+
+def refs_from(snapshot):
+ data = snapshot.get("data", {})
+ need(data.get("app") == "TextEdit" and "window" not in data, "menubar snapshot was not app-owned")
+ need(data.get("complete") is True, "menubar snapshot was incomplete")
+ found = {name: [] for name in ("File", "Edit", "Help")}
+ for node in walk(data.get("tree", {})):
+ if node.get("role") == "menuitem" and node.get("name") in found:
+ found[node["name"]].append(node.get("ref_id"))
+ refs = {}
+ for name, matches in found.items():
+ need(len(matches) == 1 and isinstance(matches[0], str)
+ and matches[0].startswith("@") and ":" in matches[0], f"missing qualified {name} ref")
+ refs[name] = matches[0]
+ need(len({ref.split(":", 1)[0] for ref in refs.values()}) == 1, "menu refs came from different snapshots")
+ return refs
+
+
+def menu_id(binary, env):
+ value = ok(cli(binary, env, "list-surfaces", "--app", "TextEdit"), "list-surfaces")
+ menus = [item for item in value.get("data", {}).get("surfaces", []) if item.get("type") == "menu"]
+ need(len(menus) == 1 and isinstance(menus[0].get("id"), str), "expected one native menu surface")
+ return menus[0]["id"]
+
+
+def close_blank_document(pid):
+ require_owned(pid)
+ value = osa('''tell application id "com.apple.TextEdit"
+if (count of documents) is not 1 then error "document count changed"
+set d to first document
+if (name of d as text) is not "Untitled" then error "document is not the new untitled document"
+if modified of d then error "document was modified"
+if (length of (text of d as text)) is not 0 then error "document is not blank"
+close d saving no
+return "closed"
+end tell''')
+ need(value == "closed", "TextEdit did not confirm closing the blank document")
+
+
+def cleanup(binary, env, pid, close_attempted):
+ require_owned(pid)
+ cancel_open_menus(pid)
+ name = process_name(pid)
+ if name:
+ need(name == "TextEdit", "task-created TextEdit process changed")
+ docs = documents()
+ if docs:
+ if close_attempted or docs != [("Untitled", False, 0)]:
+ raise Failure("TextEdit left running because a document was added, changed, or was not blank")
+ close_blank_document(pid)
+ if process_name(pid):
+ require_owned(pid)
+ need(documents() == [], "new blank document remained open after close")
+ need(ax_windows(pid) == 0, "TextEdit still has AX windows")
+ if process_name(pid):
+ require_owned(pid)
+ need(documents() == [], "TextEdit opened a document before graceful quit")
+ need(ax_windows(pid) == 0, "TextEdit gained an AX window before graceful quit")
+ code, value = cli(binary, env, "close-app", "TextEdit")
+ need(code == 0 and value.get("ok") is True, f"graceful close-app failed: {value}")
+ need(process_name(pid) == "", "task-created TextEdit did not quit")
+ return "task-created TextEdit quit after the zero-window check"
+
+
+def foreground_unchanged(previous, where):
+ need(frontmost() == previous, f"foreground changed after {where}; no restoration was attempted")
+
+
+def run(binary):
+ need(platform.system() == "Darwin", "this regression runs only on macOS")
+ need(binary.is_absolute() and binary.is_file() and os.access(binary, os.X_OK), "--bin must be an executable absolute path")
+ need(textedit_running() is False, "TextEdit is already running; close it before this manual regression")
+ previous = frontmost()
+ failures = []
+ pid = None
+ close_attempted = False
+
+ with tempfile.TemporaryDirectory(prefix="agent-desktop-native-menus-") as state_home:
+ env = os.environ.copy()
+ env["AGENT_DESKTOP_HOME"] = state_home
+ env.pop("AGENT_DESKTOP_SESSION", None)
+ env.pop("AGENT_DESKTOP_AGENT_ID", None)
+ try:
+ need(textedit_running() is False, "TextEdit started during preflight; no app action was attempted")
+ launch = ok(cli(binary, env, "launch", "TextEdit"), "quiet TextEdit launch")
+ pid = int(launch.get("data", {}).get("pid"))
+ require_owned(pid)
+ foreground_unchanged(previous, "launch")
+
+ need(documents() == [("Untitled", False, 0)], "expected only TextEdit's new blank unmodified document")
+ close_attempted = True
+ close_blank_document(pid)
+ if process_name(pid):
+ require_owned(pid)
+ need(documents() == [], "TextEdit still has a document after the guarded close")
+ need(ax_windows(pid) == 0, "TextEdit did not reach zero AX windows")
+ foreground_unchanged(previous, "blank-document close")
+
+ require_windowless(pid)
+ snapshot = ok(cli(binary, env, "snapshot", "--app", "TextEdit", "--surface", "menubar"), "menubar snapshot")
+ refs = refs_from(snapshot)
+ require_windowless(pid)
+ help_result = ok(cli(binary, env, "--wait-for", "menuitem:TextEdit Help", "--wait-timeout", "2000", "click", refs["Help"]), "headless Help click")
+ help_data = help_result.get("data", {})
+ need("window" not in help_data, "Help click returned data.window")
+ need(any(node.get("role") == "menuitem" and node.get("name") == "TextEdit Help" for node in walk(help_data.get("tree", {}))), "Help wait returned without the open submenu item")
+ names, selected = menu_state(pid)
+ need("Help" in names and selected == ["Help"], f"native AX did not show Help selected: {names}, {selected}")
+ foreground_unchanged(previous, "Help click")
+
+ require_windowless(pid)
+ code, result = cli(binary, env, "--wait-for-gone", "menuitem:File", "--wait-timeout", "600", "click", refs["File"])
+ error = result.get("error", {})
+ need(code != 0 and result.get("ok") is False and error.get("code") == "TIMEOUT", f"File wait did not time out: {result}")
+ need(error.get("disposition", {}).get("retry") == "unsafe", f"File click was not marked unsafe: {result}")
+ need(not result.get("data", {}).get("gone"), "File wait reported false absence")
+ names, _ = menu_state(pid)
+ need("File" in names, "native AX no longer lists File")
+ foreground_unchanged(previous, "File wait")
+
+ require_windowless(pid)
+ ok(cli(binary, env, "click", refs["Edit"]), "fresh Edit menu action")
+ names, selected = menu_state(pid)
+ need("Edit" in names and selected == ["Edit"], f"native AX did not select Edit: {names}, {selected}")
+ edit_id = menu_id(binary, env)
+ need(menu_id(binary, env) == edit_id, "Edit surface ID changed between reads")
+
+ require_windowless(pid)
+ ok(cli(binary, env, "click", refs["File"]), "File menu switch from Edit")
+ names, selected = menu_state(pid)
+ need("File" in names and selected == ["File"], f"native AX did not select File: {names}, {selected}")
+ file_id = menu_id(binary, env)
+ need(menu_id(binary, env) == file_id, "File surface ID changed between reads")
+ need(file_id != edit_id, f"File and Edit reused surface ID {file_id}")
+ foreground_unchanged(previous, "menu inventory")
+ except Exception as error:
+ failures.append(str(error))
+ finally:
+ if pid is None:
+ failures.append("launch returned no safe process ID; app cleanup was not attempted")
+ else:
+ try:
+ print(cleanup(binary, env, pid, close_attempted))
+ except Exception as error:
+ failures.append(f"cleanup: {error}")
+ try:
+ foreground_unchanged(previous, "cleanup")
+ except Exception as error:
+ failures.append(str(error))
+
+ for failure in failures:
+ print(f"FAIL: {failure}", file=sys.stderr)
+ if failures:
+ return 1
+ print("PASS: native TextEdit menu regression passed")
+ return 0
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--bin", required=True, help="absolute path to the built agent-desktop binary")
+ return run(Path(parser.parse_args().bin))
+
+
+if __name__ == "__main__":
+ try:
+ sys.exit(main())
+ except Exception as error:
+ print(f"FAIL: {error}", file=sys.stderr)
+ sys.exit(2)
diff --git a/tests/native/appkit_workspace_name_test.m b/tests/native/appkit_workspace_name_test.m
index f0f720305..1141c9ec2 100644
--- a/tests/native/appkit_workspace_name_test.m
+++ b/tests/native/appkit_workspace_name_test.m
@@ -51,7 +51,7 @@ static InventoryTestApplication *application(NSString *name, NSString *executabl
}
static NSDictionary *snapshot(void) {
- AgentDesktopBytesResult result = agent_desktop_copy_workspace_snapshot_json();
+ AgentDesktopBytesResult result = agent_desktop_copy_workspace_snapshot_json(0);
require(result.status == 0, "snapshot status");
NSData *data = [NSData dataWithBytes:result.bytes length:result.length];
agent_desktop_free_bridge_bytes(result.bytes);
@@ -128,7 +128,7 @@ int main(void) {
require([frontmostSnapshot[@"skipped"][0][@"field"] isEqualToString:@"frontmost_launch_time"], "frontmost skip field");
testFrontmost = nil;
testApplications = nil;
- AgentDesktopBytesResult missing = agent_desktop_copy_workspace_snapshot_json();
+ AgentDesktopBytesResult missing = agent_desktop_copy_workspace_snapshot_json(0);
require(missing.status == 1, "missing snapshot remains failure");
require(missing.bytes == NULL, "missing snapshot has no bytes");
puts("AppKit inventory name regression tests passed");