Computer use CLI for AI agents
Rust accessibilityaccessibility-apiai-agentsautomationclicomputer-usecomputer-use-agentcomputer-use-agentsdesktop-automationmacosmcprust
fix(macos): reach the Dock, menu bar status items and system panels (#480)
Lahfir31b757a990a1
diff --git a/README.md b/README.mdindex df48d2a3d..640963561 100644--- a/README.md+++ b/README.md@@ -132,7 +132,7 @@ It ships 60 command names, 56 operational commands. The other four (`key-down`,| Clipboard | Yes | Yes | Yes; Wayland needs `wl-clipboard` || App & window management | Yes | Yes | Launch/list; X11 window control || Notifications | Yes | Yes | GNOME Shell |-| Shell surfaces (`open-system-surface`) | Planned | Yes | GNOME tray, Action Center |+| Shell surfaces (`open-system-surface`) | Dock, menu bar extras | Yes | GNOME tray, Action Center |The Windows surface and `launch` notes and the Linux X11 and Wayland notes are in [docs/install.md](docs/install.md#platform-notes).diff --git a/apps/docs/content/docs/commands/observation.mdx b/apps/docs/content/docs/commands/observation.mdxindex f93023839..b143a32b1 100644--- a/apps/docs/content/docs/commands/observation.mdx+++ b/apps/docs/content/docs/commands/observation.mdx@@ -37,9 +37,9 @@ agent-desktop snapshot [--app NAME] [--window-id ID] [-i] [--compact] [--skeleto</tbody></table>-`data` carries `app`, `window`, `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`.+`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; `PLATFORM_NOT_SUPPORTED` for an unsupported `--surface`; `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).+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).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).@@ -259,11 +259,11 @@ agent-desktop --headed open-system-surface --surface KIND<tr><th>Flag</th><th>Default</th><th>Meaning</th></tr></thead><tbody>- <tr><td><code>--surface KIND</code></td><td>required</td><td>The shell surface: <code>start-menu</code>, <code>taskbar</code>, <code>system-tray</code>, <code>system-tray-overflow</code>, or <code>action-center</code>.</td></tr>+ <tr><td><code>--surface KIND</code></td><td>required</td><td>The shell surface: <code>start-menu</code>, <code>taskbar</code>, <code>system-tray</code>, <code>system-tray-overflow</code>, <code>action-center</code>, <code>dock</code>, or <code>menu-bar-extras</code>. <code>dock</code> and <code>menu-bar-extras</code> are the macOS kinds.</td></tr></tbody></table>-`data` is `surface` and `window`, with the same fields as a [`list-windows`](/desktop/commands/app-window#list-windows) entry. This shape comes from the command's unit test:+`data` is `surface` and, on Windows and Linux, `window`, with the same fields as a [`list-windows`](/desktop/commands/app-window#list-windows) entry. On macOS no window owns the surface, so `data` is only `{"surface": "dock"}` and `window` is left out. This shape comes from the command's unit test:```json{@@ -277,4 +277,4 @@ agent-desktop --headed open-system-surface --surface KIND}```-The command takes the foreground, so headless mode refuses it with `POLICY_DENIED` before anything is raised; pass `--headed`. A kind the OS does not expose returns `PLATFORM_NOT_SUPPORTED`, with the alternative in `platform_detail` where one exists. macOS has no shell surfaces, so every call there returns `PLATFORM_NOT_SUPPORTED`. Which kinds open on Windows and Linux is on their platform pages.+The command takes the foreground, so on Windows and Linux headless mode refuses it with `POLICY_DENIED` before anything is raised; pass `--headed`. A kind the OS does not expose returns `INVALID_ARGS`, with the kinds to use in `suggestion` and the alternative in `platform_detail` where one exists. On macOS, `dock` and `menu-bar-extras` are always on screen, so the command returns them at once, headless, with no `--headed`; open Control Center or Notification Center by clicking its `menu-bar-extras` item. Which kinds open on Windows and Linux is on their platform pages.diff --git a/apps/docs/content/docs/errors-and-recovery.mdx b/apps/docs/content/docs/errors-and-recovery.mdxindex 75d7a990a..afef75503 100644--- a/apps/docs/content/docs/errors-and-recovery.mdx+++ b/apps/docs/content/docs/errors-and-recovery.mdx@@ -57,7 +57,7 @@ A failed command prints an envelope with `ok: false` and exits `1` (or `2` for a<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><tr><td><code>AMBIGUOUS_TARGET</code></td><td>Several live elements, windows, or app instances match, or the ref was not unique when it was captured, and the command refuses to guess.</td><td>Take a fresh snapshot. When the matches are different elements, narrow the target with <code>find</code>, <code>--root</code>, or <code>--window-id</code>; off macOS, identical twins have no ref path. It never carries <code>recovery</code>.</td></tr><tr><td><code>WINDOW_NOT_FOUND</code></td><td>The requested window does not exist, including a <code>--window-id</code> that matches no window or a closed shell surface.</td><td>Run <code>list-windows --app <name></code> and use an id it reports.</td></tr>- <tr><td><code>PLATFORM_NOT_SUPPORTED</code></td><td>This platform's adapter does not implement the method or surface kind.</td><td>Use another approach. The platform pages list what each OS supports.</td></tr>+ <tr><td><code>PLATFORM_NOT_SUPPORTED</code></td><td>This platform's adapter does not implement the method. A surface kind this OS does not have is <code>INVALID_ARGS</code>.</td><td>Use another approach. The platform pages list what each OS supports.</td></tr><tr><td><code>TIMEOUT</code></td><td>A wait expired, the target never became actionable, or a read stayed incomplete until the deadline.</td><td>Read <code>details.kind</code>. Retry only when <code>disposition.retry</code> is <code>safe</code>.</td></tr><tr><td><code>INVALID_ARGS</code></td><td>An argument is invalid. Also returned for a bare <code>@eN</code> ref and an ended session.</td><td>Fix the input. Repeating the same arguments fails the same way.</td></tr><tr><td><code>NOTIFICATION_NOT_FOUND</code></td><td>The notification index or identity no longer matches.</td><td>Run <code>list-notifications</code> again.</td></tr>diff --git a/apps/docs/content/docs/guides/headed-mode.mdx b/apps/docs/content/docs/guides/headed-mode.mdxindex 304cdf7b2..a6d601988 100644--- a/apps/docs/content/docs/guides/headed-mode.mdx+++ b/apps/docs/content/docs/guides/headed-mode.mdx@@ -16,7 +16,7 @@ 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.+- 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.- 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.@@ -45,7 +45,7 @@ Depending on the OS:<tr><td><code>scroll</code></td><td>Headless</td><td>Headless</td><td><code>--headed</code>, X11 only</td></tr><tr><td>Listing notifications</td><td>Headless while the surface is open</td><td>Headless while the surface is open</td><td>Headless</td></tr><tr><td>Notification mutations</td><td><code>--headed</code></td><td><code>--headed</code></td><td><code>--headed</code>, X11 only</td></tr>- <tr><td><code>open-system-surface</code></td><td>Not supported</td><td><code>--headed</code></td><td><code>--headed</code></td></tr>+ <tr><td><code>open-system-surface</code></td><td>Headless</td><td><code>--headed</code></td><td><code>--headed</code></td></tr></tbody></table>diff --git a/apps/docs/content/docs/platforms/macos.mdx b/apps/docs/content/docs/platforms/macos.mdxindex af9916b06..aec1b909d 100644--- a/apps/docs/content/docs/platforms/macos.mdx+++ b/apps/docs/content/docs/platforms/macos.mdx@@ -56,7 +56,7 @@ Ref actions are headless by default. Under `--headed`, `click`, `right-click`, `<tr><td>Clipboard</td><td><code>clipboard-get</code>, <code>clipboard-set</code> (read back: <code>delivered_verified</code>), <code>clipboard-clear</code></td><td></td><td></td></tr><tr><td>Wait</td><td>All modes. <code>wait --notification</code> sees only an already-open Notification Center</td><td></td><td></td></tr><tr><td>Notifications</td><td><code>list-notifications</code> while Notification Center is open</td><td>Listing while it is closed, and every dismiss and action</td><td>Headless listing with the center closed: <code>POLICY_DENIED</code></td></tr>- <tr><td>Shell surfaces</td><td></td><td></td><td><code>open-system-surface</code>: <code>PLATFORM_NOT_SUPPORTED</code></td></tr>+ <tr><td>Shell surfaces</td><td><code>open-system-surface</code> for <code>dock</code> and <code>menu-bar-extras</code>, returned at once because they are always on screen</td><td></td><td><code>start-menu</code>, <code>taskbar</code>, <code>system-tray</code>, <code>system-tray-overflow</code>, <code>action-center</code>: <code>INVALID_ARGS</code></td></tr><tr><td>System</td><td><code>status</code>, <code>permissions</code>, <code>version</code>, <code>batch</code>, <code>skills</code>, <code>session</code>, <code>cursor-overlay</code>, <code>trace</code></td><td></td><td></td></tr></tbody></table>@@ -65,11 +65,11 @@ Judge delivery by observation. AX return codes do not prove an effect: an app ca## App naming-`--app` takes the display name `list-apps` prints, such as `"System Settings"` or `"TextEdit"`. `launch` also accepts a bundle ID such as `com.apple.TextEdit`. Window ids such as `w-4521` stay valid for the life of the window; find them with `list-windows`.+`--app` takes the display name `list-apps` prints, such as `"System Settings"` or `"TextEdit"`. When no running app has that display name, it also matches a bundle ID or an executable name, such as `ControlCenter` for Control Center. `launch` also accepts a bundle ID such as `com.apple.TextEdit`. Window ids such as `w-4521` stay valid for the life of the window; find them with `list-windows`.## Surfaces-`supported_surfaces` lists `window`, `focused`, `menu`, `menubar`, `sheet`, `popover`, and `alert`. Use `--surface menubar` for the File, Edit, and View menus and for menu bar status items. macOS has no shell surfaces; 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 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).## Keys and notificationsdiff --git a/apps/docs/content/docs/platforms/windows.mdx b/apps/docs/content/docs/platforms/windows.mdxindex f7a22af51..20f5c8618 100644--- a/apps/docs/content/docs/platforms/windows.mdx+++ b/apps/docs/content/docs/platforms/windows.mdx@@ -38,7 +38,7 @@ Ref actions are semantic UIA calls headless and under `--headed`, except the one<tr><td>Clipboard</td><td><code>clipboard-get</code>, <code>clipboard-set</code>, <code>clipboard-clear</code> (text and images)</td><td></td><td></td></tr><tr><td>Wait</td><td>All modes except notifications with the Action Center closed</td><td><code>--notification</code> when the Action Center is closed</td><td></td></tr><tr><td>Notifications</td><td><code>list-notifications</code> while the Action Center is open</td><td>Listing while it is closed, and every dismiss and action</td><td>Headless on a closed center: <code>POLICY_DENIED</code></td></tr>- <tr><td>Shell surfaces</td><td><code>snapshot --surface KIND</code> on a surface that is already present</td><td><code>open-system-surface</code> for <code>start-menu</code>, <code>taskbar</code>, <code>system-tray</code>, <code>system-tray-overflow</code>, <code>action-center</code></td><td><code>quick-settings</code>: <code>PLATFORM_NOT_SUPPORTED</code>, naming <code>action-center</code></td></tr>+ <tr><td>Shell surfaces</td><td><code>snapshot --surface KIND</code> on a surface that is already present</td><td><code>open-system-surface</code> for <code>start-menu</code>, <code>taskbar</code>, <code>system-tray</code>, <code>system-tray-overflow</code>, <code>action-center</code></td><td><code>quick-settings</code>: <code>INVALID_ARGS</code>, naming <code>action-center</code></td></tr><tr><td>System</td><td><code>status</code>, <code>permissions</code>, <code>version</code>, <code>batch</code>, <code>skills</code>, <code>session</code>, <code>cursor-overlay</code>, <code>trace</code></td><td></td><td></td></tr></tbody></table>diff --git a/apps/docs/content/docs/snapshots-and-refs.mdx b/apps/docs/content/docs/snapshots-and-refs.mdxindex 254fcd155..a7b17a91c 100644--- a/apps/docs/content/docs/snapshots-and-refs.mdx+++ b/apps/docs/content/docs/snapshots-and-refs.mdx@@ -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>).</td></tr>+ <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.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>diff --git a/apps/docs/content/docs/surfaces.mdx b/apps/docs/content/docs/surfaces.mdxindex 260275038..1e45d641f 100644--- a/apps/docs/content/docs/surfaces.mdx+++ b/apps/docs/content/docs/surfaces.mdx@@ -32,7 +32,7 @@ Each platform supports a subset:<tr><th>Platform</th><th>Supported surfaces</th></tr></thead><tbody>- <tr><td>macOS</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>macOS</td><td><code>window</code>, <code>focused</code>, <code>menu</code>, <code>menubar</code>, <code>sheet</code>, <code>popover</code>, <code>alert</code>, <code>dock</code>, <code>menu-bar-extras</code></td></tr><tr><td>Windows</td><td><code>window</code>, <code>focused</code>, <code>sheet</code>, <code>menu</code>, <code>start-menu</code>, <code>taskbar</code>, <code>system-tray</code>, <code>system-tray-overflow</code>, <code>action-center</code></td></tr><tr><td>Linux</td><td><code>window</code>, <code>sheet</code>, <code>alert</code>, <code>menu</code>, plus GNOME Shell kinds the session can resolve</td></tr></tbody>@@ -48,7 +48,7 @@ Per-kind limits are on the platform pages: [macOS](/desktop/platforms/macos), [W{ "supported_surfaces": ["window", "sheet", "alert", "menu"] }```-Read it before you ask for a surface. An unsupported kind fails with `PLATFORM_NOT_SUPPORTED`, with the supported list in `details.supported_surfaces` and your request in `details.requested_surface`. On Linux, an empty `supported_surfaces` means the accessibility bus did not answer, not that the desktop is empty.+Read it before you ask for a surface. A kind this OS does not have fails with `INVALID_ARGS`, with the supported list in `details.supported_surfaces` and your request in `details.requested_surface`. On Linux, an empty `supported_surfaces` means the accessibility bus did not answer, not that the desktop is empty.## Know when a surface opened@@ -109,8 +109,8 @@ To reach one item, `find --surface` is cheaper than a dump:Which window agent-desktop reads depends on the kind:- `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.-- A shell kind needs no `--app`, because no application owns it.+- `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.A surface that is not open returns an error. On Linux, a closed menu returns `ELEMENT_NOT_FOUND`:@@ -150,11 +150,11 @@ agent-desktop list-surfaces --app gtk3-widget-factory## Open an OS shell surface-`open-system-surface` raises a shell surface and returns the window it presents, in the `w-<id>` form that `list-windows` uses:+`open-system-surface` raises a shell surface. On Windows and Linux it returns the window it presents, in the `w-<id>` form that `list-windows` uses. On macOS it returns only `{"surface": "dock"}`, because no window owns these surfaces:```bashagent-desktop --headed open-system-surface --surface action-centeragent-desktop snapshot --surface action-center -i --compact```-It takes the foreground, so headless mode refuses it with `POLICY_DENIED`; pass `--headed` (see [Headed mode](/desktop/guides/headed-mode)). An already-present surface returns without being raised again. A kind the OS does not expose returns `PLATFORM_NOT_SUPPORTED`, and `platform_detail` names the alternative. macOS has no shell surfaces; which kinds open on Windows and Linux is on their platform pages.+It takes the foreground, so on Windows and Linux headless mode refuses it with `POLICY_DENIED`; pass `--headed` (see [Headed mode](/desktop/guides/headed-mode)). An already-present surface returns without being raised again. A kind the OS does not expose returns `INVALID_ARGS`, and the suggestion or `platform_detail` names the kinds to use instead. On macOS, `dock` and `menu-bar-extras` are always on screen, so the command returns them at once, headless, with no `--headed`; open Control Center or Notification Center by clicking its `menu-bar-extras` item. Which kinds open on Windows and Linux is on their platform pages.diff --git a/crates/core/src/actions/headed_focus.rs b/crates/core/src/actions/headed_focus.rsindex 327984811..38dce8834 100644--- a/crates/core/src/actions/headed_focus.rs+++ b/crates/core/src/actions/headed_focus.rs@@ -2,16 +2,22 @@ use serde_json::json;use crate::{AdapterError, AppError, ErrorCode, PlatformAdapter, ProcessIdentity, WindowInfo};+/// Focuses the window a ref came from and returns whether it did. A ref+/// captured through a process owner has no window to raise, so it returns+/// `false`; any other ref without a window id is refused.pub(crate) fn focus_entry_window(entry: &crate::RefEntry,adapter: &dyn PlatformAdapter,context: &crate::CommandContext,lease: &crate::InteractionLease,-) -> Result<WindowInfo, AppError> {+) -> Result<bool, AppError> {let process_instance = required_text(entry.process.process_instance.as_deref(),"Headed input requires target process-instance identity",)?;+ if entry.source.is_process_owned() {+ return Ok(false);+ }let window_id = required_text(entry.source.source_window_id.as_deref(),"Headed input requires an exact source window id",@@ -25,7 +31,7 @@ pub(crate) fn focus_entry_window(bounds: None,state: crate::WindowState::default(),};- focus_exact_window(&expected, adapter, context, lease)+ focus_exact_window(&expected, adapter, context, lease).map(|_| true)}pub(crate) fn focus_process_window(diff --git a/crates/core/src/adapter/system.rs b/crates/core/src/adapter/system.rsindex 2901a1cd1..5a1925041 100644--- a/crates/core/src/adapter/system.rs+++ b/crates/core/src/adapter/system.rs@@ -111,15 +111,7 @@ pub trait SystemOps: Send + Sync {if supported.contains(&requested) {return Ok(());}- Err(AdapterError::new(- crate::ErrorCode::PlatformNotSupported,- format!("Snapshot surface '{}' is not supported on this platform", requested.as_str()),- )- .with_details(serde_json::json!({- "requested_surface": requested.as_str(),- "supported_surfaces": supported.into_iter().map(crate::SnapshotSurface::as_str).collect::<Vec<_>>()- }))- .with_suggestion("Choose one of the supported snapshot surfaces"))+ Err(requested.unavailable_error(&supported))}/// Registers caller-scoped wake hints before the initial predicate read.@@ -137,9 +129,9 @@ pub trait SystemOps: Send + Sync {/// presents, in the same shape the window observation stack consumes. It/// takes the lease because it mutates OS chrome and takes the foreground;/// the policy travels separately because the lease carries no- /// focus-steal refusal. Implementations must refuse with `POLICY_DENIED`- /// before anything is raised when `policy.allow_focus_steal` is false,- /// must return an already-present surface without raising it again, and+ /// focus-steal refusal. Implementations that raise anything must refuse with+ /// `POLICY_DENIED` first when `policy.allow_focus_steal` is false, must+ /// return an already-present surface without raising it again, and/// must answer a kind their platform does not expose with a refusal that/// names what a caller should ask for instead - never with this default.fn open_system_surface(diff --git a/crates/core/src/commands/open_system_surface.rs b/crates/core/src/commands/open_system_surface.rsindex d6b64043e..38425e6ba 100644--- a/crates/core/src/commands/open_system_surface.rs+++ b/crates/core/src/commands/open_system_surface.rs@@ -10,7 +10,8 @@ pub struct OpenSystemSurfaceArgs {}/// Opens a shell surface and answers with the identity of the window the-/// surface actually presents: the same `w-<hwnd>` identity the observation+/// surface actually presents, left out when a process with no window presents+/// it: the same `w-<hwnd>` identity the observation/// stack roots, so `snapshot --surface <kind>` consumes it with no second/// lookup. The answer comes from the adapter's kind/// table, never from `supported_surfaces()`: that list says which kinds a@@ -33,10 +34,11 @@ pub fn execute(let policy = context.physical_input_policy();let lease = adapter.acquire_interaction_lease(deadline)?;let window = adapter.open_system_surface(args.surface, policy, &lease)?;- Ok(json!({- "surface": args.surface.as_str(),- "window": window,- }))+ let mut data = json!({ "surface": args.surface.as_str() });+ if !window.is_process_owner() {+ data["window"] = json!(window);+ }+ Ok(data)}#[cfg(test)]diff --git a/crates/core/src/commands/open_system_surface_tests.rs b/crates/core/src/commands/open_system_surface_tests.rsindex a5a4ae86a..97c85ef7c 100644--- a/crates/core/src/commands/open_system_surface_tests.rs+++ b/crates/core/src/commands/open_system_surface_tests.rs@@ -28,12 +28,21 @@ impl SystemOps for SurfaceAdapter {_lease: &InteractionLease,) -> Result<WindowInfo, AdapterError> {self.opens.lock().unwrap().push((surface, policy));+ if surface == SnapshotSurface::Dock {+ return Ok(WindowInfo::for_process(&crate::AppInfo {+ name: "Dock".into(),+ pid: crate::ProcessId::new(7),+ bundle_id: None,+ process_instance: Some("instance-7".into()),+ presentation: None,+ }));+ }Ok(shell_window())}}-/// An adapter that keeps the trait default for the open seam - the macOS-/// shape today - but still grants the lease, so the `not_supported` the+/// An adapter that keeps the trait default for the open seam, as an adapter+/// without the seam does, but still grants the lease, so the `not_supported` the/// command surfaces is provably the open seam's own answer and not the/// lease acquisition failing.struct LeaseOnlyAdapter {@@ -195,3 +204,17 @@ fn the_trait_default_answers_not_supported_for_adapters_without_the_surface() {assert!(inner.is_default_not_supported("open_system_surface"));assert_eq!(error.code(), "PLATFORM_NOT_SUPPORTED");}++#[test]+fn a_surface_no_window_presents_leaves_the_window_out() {+ let value = execute(+ OpenSystemSurfaceArgs {+ surface: SnapshotSurface::Dock,+ },+ &adapter(),+ &headed(),+ )+ .unwrap();++ assert_eq!(value, serde_json::json!({ "surface": "dock" }));+}diff --git a/crates/core/src/commands/point_resolve.rs b/crates/core/src/commands/point_resolve.rsindex dce1fb550..47c38af05 100644--- a/crates/core/src/commands/point_resolve.rs+++ b/crates/core/src/commands/point_resolve.rs@@ -90,8 +90,7 @@ pub(crate) fn focus_for_physical_input(if !context.physical_input_policy().allow_focus_steal {return Ok(false);}- crate::actions::headed_focus::focus_entry_window(entry, adapter, context, lease)?;- Ok(true)+ crate::actions::headed_focus::focus_entry_window(entry, adapter, context, lease)}#[cfg(test)]diff --git a/crates/core/src/commands/point_resolve_tests.rs b/crates/core/src/commands/point_resolve_tests.rsindex 33c2985fa..0457ed1d9 100644--- a/crates/core/src/commands/point_resolve_tests.rs+++ b/crates/core/src/commands/point_resolve_tests.rs@@ -283,6 +283,7 @@ fn focus_ref_entry() -> RefEntry {}}+#[derive(Default)]struct FocusFailureAdapter {resolve_error: Option<AdapterError>,focus_error: Option<AdapterError>,@@ -326,8 +327,7 @@ fn focus_test_lease() -> crate::InteractionLease {fn transient_window_resolution_failure_blocks_headed_input() {let adapter = FocusFailureAdapter {resolve_error: Some(AdapterError::app_unresponsive("Fixture")),- focus_error: None,- focus_calls: AtomicU32::new(0),+ ..Default::default()};let error = focus_for_physical_input(@@ -342,15 +342,30 @@ fn transient_window_resolution_failure_blocks_headed_input() {assert_eq!(adapter.focus_calls.load(Ordering::SeqCst), 0);}+#[test]+fn windowless_ref_skips_focus_only_when_process_owned() {+ let adapter = FocusFailureAdapter::default();+ let context = CommandContext::default().with_headed(true);+ let lease = focus_test_lease();+ let mut entry = focus_ref_entry();+ entry.source.source_window_id = None;+ entry.source.source_window_title = Some(String::new());+ let skipped = focus_for_physical_input(Some(&entry), &adapter, &context, &lease);+ assert_eq!(skipped.ok(), Some(false));+ entry.source.source_window_title = Some("Fixture".into());+ let refused = focus_for_physical_input(Some(&entry), &adapter, &context, &lease);+ assert_eq!(refused.unwrap_err().code(), "ACTION_NOT_SUPPORTED");+ assert_eq!(adapter.focus_calls.load(Ordering::SeqCst), 0);+}+#[test]fn transient_focus_failure_blocks_headed_input() {let adapter = FocusFailureAdapter {- resolve_error: None,focus_error: Some(AdapterError::new(ErrorCode::ActionFailed,"window could not be raised",)),- focus_calls: AtomicU32::new(0),+ ..Default::default()};let error = focus_for_physical_input(@@ -368,9 +383,8 @@ fn transient_focus_failure_blocks_headed_input() {#[test]fn permission_failure_during_focus_is_preserved() {let adapter = FocusFailureAdapter {- resolve_error: None,focus_error: Some(AdapterError::permission_denied()),- focus_calls: AtomicU32::new(0),+ ..Default::default()};let err = focus_for_physical_input(diff --git a/crates/core/src/commands/snapshot.rs b/crates/core/src/commands/snapshot.rsindex 186c36f2d..0599006ad 100644--- a/crates/core/src/commands/snapshot.rs+++ b/crates/core/src/commands/snapshot.rs@@ -135,15 +135,14 @@ pub(crate) fn format_snapshot_fields(let mut body = json!({"app": win.app,- "window": {- "id": win.id,- "title": win.title- },"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 !result.complete {body["truncated"] = json!(true);body["nodes_observed"] = json!(result.nodes_observed);diff --git a/crates/core/src/commands/snapshot_tests.rs b/crates/core/src/commands/snapshot_tests.rsindex 0b81b2277..7d15cf267 100644--- a/crates/core/src/commands/snapshot_tests.rs+++ b/crates/core/src/commands/snapshot_tests.rs@@ -260,31 +260,23 @@ fn test_root_with_window_surface_does_not_short_circuit_validation() {#[test]fn unsupported_surface_fails_before_adapter_traversal() {- let args = SnapshotArgs {+ let sheet = || SnapshotArgs {surface: SnapshotSurface::Sheet,..base_args()};-- let err = execute(args, &DefaultSurfaceAdapter, &CommandContext::default()).unwrap_err();+ assert!(matches!(+ execute(sheet(), &NoopAdapter, &CommandContext::default()),+ Err(AppError::Adapter(error)) if error.code == ErrorCode::InvalidArgs+ ));+ let err = execute(sheet(), &DefaultSurfaceAdapter, &CommandContext::default()).unwrap_err();let AppError::Adapter(adapter_error) = err else {panic!("expected adapter error")};assert_eq!(adapter_error.code, ErrorCode::PlatformNotSupported);assert_eq!(- adapter_error- .details- .as_ref()- .and_then(|details| details.get("requested_surface")),- Some(&serde_json::json!("sheet"))- );- assert!(- adapter_error- .details- .as_ref()- .and_then(|details| details.get("supported_surfaces"))- .and_then(serde_json::Value::as_array)- .is_some_and(Vec::is_empty)+ adapter_error.details,+ Some(serde_json::json!({ "requested_surface": "sheet", "supported_surfaces": [] })));}@@ -383,6 +375,14 @@ 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();+ assert!(+ format_snapshot_fields(&result, None, None)+ .unwrap()+ .get("window")+ .is_none()+ );result.identity_unproven = Some("the whole-window read was cut short".into());let unproven = format_snapshot_fields(&result, None, None).unwrap();diff --git a/crates/core/src/locator/live_locator/materialize.rs b/crates/core/src/locator/live_locator/materialize.rsindex 9052f74b4..d15d6c6b8 100644--- a/crates/core/src/locator/live_locator/materialize.rs+++ b/crates/core/src/locator/live_locator/materialize.rs@@ -154,7 +154,7 @@ 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 = Some(window.id.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_bounds_hash =window.bounds.as_ref().and_then(crate::Rect::bounds_hash);diff --git a/crates/core/src/locator/live_locator/materialize_tests.rs b/crates/core/src/locator/live_locator/materialize_tests.rsindex ffcc6cfb7..f8b8e780e 100644--- a/crates/core/src/locator/live_locator/materialize_tests.rs+++ b/crates/core/src/locator/live_locator/materialize_tests.rs@@ -238,6 +238,30 @@ fn window_source_materialization_preserves_geometry_generation_evidence() {assert_eq!(saved.source.source_window_bounds_hash, bounds.bounds_hash());}+#[test]+fn a_process_owner_source_materializes_a_process_owned_ref() {+ let mut observed = tree(+ vec![node(0, evidence("button", Some("Save")), vec![], &[])],+ vec![0],+ true,+ );+ let ObservationSource::Window { window, .. } = &mut observed.source else {+ panic!("fixture must use a window source");+ };+ *window = crate::WindowInfo::for_process(&crate::AppInfo {+ name: window.app.clone(),+ pid: window.pid,+ bundle_id: None,+ process_instance: window.process_instance.clone(),+ presentation: None,+ });++ let resolution = evaluate_locator_tree(observed, &LocatorQuery::default(), &request()).unwrap();+ let saved = resolution.refmap.unwrap().get("@e1").unwrap().clone();++ assert!(saved.source.is_process_owned());+}+#[test]fn ref_entry_prefers_the_window_rectangle_and_tags_its_space() {let window_bounds = crate::Rect {diff --git a/crates/core/src/refs/ref_source.rs b/crates/core/src/refs/ref_source.rsindex 43465df36..ad0348d52 100644--- a/crates/core/src/refs/ref_source.rs+++ b/crates/core/src/refs/ref_source.rs@@ -16,3 +16,17 @@ pub struct RefSource {#[serde(default, skip_serializing_if = "std::ops::Not::not")]pub renderer_accessibility_forced: bool,}++impl RefSource {+ /// Whether the ref was captured through a process owner (see+ /// [`crate::WindowInfo::for_process`]) rather than a window, on any surface.+ pub fn is_process_owned(&self) -> bool {+ self.source_window_id.is_none() && self.source_window_title.as_deref() == Some("")+ }++ /// Whether the ref was observed from a process owner's application root,+ /// so its path starts there.+ pub fn is_process_rooted(&self) -> bool {+ self.source_surface == crate::SnapshotSurface::Window && self.is_process_owned()+ }+}diff --git a/crates/core/src/refs/resolve_saved_ref.rs b/crates/core/src/refs/resolve_saved_ref.rsindex 4d15f8340..731e4c1e8 100644--- a/crates/core/src/refs/resolve_saved_ref.rs+++ b/crates/core/src/refs/resolve_saved_ref.rs@@ -163,19 +163,20 @@ fn confirm_landed(}}-/// The window the ref was captured from, never any other window of the-/// process: resolution re-searches the scope the capture proved unique.-///-/// The surface lookup owns shell surfaces and the focused-window case, and it-/// already resolves a recorded window id by that id; `belongs_to_entry` checks-/// the process and its generation on that answer. Only an entry that records no-/// window id falls back to enumerating the process's windows, where the-/// generation alone still says which one it was.+/// The window the ref was captured from, never another window of the process;+/// a process-owned ref's owner is its live process, whatever windows it opens.+/// The surface lookup resolves shell surfaces, the focused window and a recorded+/// window id; an entry with no window id falls back to the process's windows,+/// where the generation says which one it was.pub(crate) fn recorded_window(adapter: &dyn PlatformAdapter,entry: &RefEntry,deadline: Deadline,) -> Result<WindowInfo, AdapterError> {+ if entry.source.is_process_owned() {+ return crate::system::app_lookup::live_process_owner(adapter, entry, deadline)+ .map_err(adapter_error);+ }let resolved = crate::snapshot::resolve_window_for_surface(adapter,entry.source.source_app.as_deref(),@@ -209,12 +210,12 @@ fn gone() -> AdapterError {AdapterError::stale_ref_because("The window the ref was captured from is gone")}-/// Whether a live window is the one the entry was captured from. Pid and a-/// recorded window id must agree. Process generations must agree when both-/// sides carry one; a window listing that cannot read the generation leaves-/// the pid and window id to decide, since some macOS window records omit it.+/// Whether a live window is the one the entry was captured from: the owner kind,+/// pid and a recorded window id must agree, and process generations must agree+/// when both sides carry one, since some macOS window records omit it.fn belongs_to_entry(window: &WindowInfo, entry: &RefEntry) -> bool {- window.pid == entry.process.pid+ window.is_process_owner() == entry.source.is_process_owned()+ && window.pid == entry.process.pid&& entry.source.source_window_iddiff --git a/crates/core/src/refs/resolve_saved_ref_test_support.rs b/crates/core/src/refs/resolve_saved_ref_test_support.rsindex 70173b037..ba267c01b 100644--- a/crates/core/src/refs/resolve_saved_ref_test_support.rs+++ b/crates/core/src/refs/resolve_saved_ref_test_support.rs@@ -53,6 +53,21 @@ impl RuleAdapter {}impl ObservationOps for RuleAdapter {+ fn list_apps_scoped(+ &self,+ _name: &str,+ _bundle_id: Option<&str>,+ _deadline: Deadline,+ ) -> Result<Vec<crate::AppInfo>, AdapterError> {+ Ok(vec![crate::AppInfo {+ name: "Fixture".into(),+ pid: crate::ProcessId::new(1),+ bundle_id: None,+ process_instance: Some("test-instance".into()),+ presentation: None,+ }])+ }+fn list_windows(&self,_filter: &crate::adapter::WindowFilter,diff --git a/crates/core/src/refs/resolve_saved_ref_tests.rs b/crates/core/src/refs/resolve_saved_ref_tests.rsindex dcf264c99..82d7c8ab3 100644--- a/crates/core/src/refs/resolve_saved_ref_tests.rs+++ b/crates/core/src/refs/resolve_saved_ref_tests.rs@@ -79,6 +79,27 @@ fn a_shell_surface_ref_reaches_its_container_without_the_window_inventory() {assert_eq!(adapter.windows_listed.load(Ordering::SeqCst), 0);}+/// A windowless app's ref resolves from its live process even after the app+/// opens a window, and a relaunched process makes it stale.+#[test]+fn a_process_owned_ref_follows_its_process_not_a_window() {+ let _guard = HomeGuard::new();+ let adapter = RuleAdapter::new(tree_with(vec![node("button", "Run")]));+ let mut entry = entry();+ entry.source.source_window_id = None;+ entry.source.source_window_title = Some(String::new());+ entry.process.process_instance = Some("test-instance".into());++ assert!(resolve(&adapter, &entry).is_ok());+ assert_eq!(adapter.windows_listed.load(Ordering::SeqCst), 0);++ entry.process.process_instance = Some("relaunched".into());+ let Err(error) = resolve(&adapter, &entry) else {+ panic!("a replaced process cannot answer for the ref");+ };+ assert_eq!(error.code, ErrorCode::StaleRef);+}+#[test]fn a_removed_target_is_stale() {let _guard = HomeGuard::new();diff --git a/crates/core/src/response/adapter_error.rs b/crates/core/src/response/adapter_error.rsindex 5f24244f9..e285d1b69 100644--- a/crates/core/src/response/adapter_error.rs+++ b/crates/core/src/response/adapter_error.rs@@ -184,6 +184,15 @@ impl AdapterError {.with_disposition(DeliverySemantics::not_delivered())}+ /// A named app is running but presents no window this command can read.+ pub fn app_has_no_window(app: &str) -> Self {+ Self::new(+ ErrorCode::WindowNotFound,+ format!("Application '{app}' is running but has no matching window"),+ )+ .with_suggestion("Wait for the app to present a window, or run 'list-windows --app'.")+ }+pub fn timeout(message: impl Into<String>) -> Self {Self::new(ErrorCode::Timeout, message).with_suggestion("The target application may be busy or unresponsive")diff --git a/crates/core/src/snapshot/mod.rs b/crates/core/src/snapshot/mod.rsindex f0ed1ebff..0e40ed6a3 100644--- a/crates/core/src/snapshot/mod.rs+++ b/crates/core/src/snapshot/mod.rs@@ -58,7 +58,7 @@ pub fn build(source: RefAllocSource {pid: window.pid,app: Some(window.app.as_str()),- window_id: Some(window.id.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(),@@ -98,6 +98,9 @@ pub fn build(/// 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>,@@ -105,7 +108,8 @@ pub(crate) fn resolve_window_for_surface(surface: crate::SnapshotSurface,deadline: crate::Deadline,) -> Result<WindowInfo, AppError> {- if is_shell_surface(surface) {+ 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(_) => {}@@ -118,11 +122,18 @@ pub(crate) fn resolve_window_for_surface(Err(_) => {}}}- if window_id.is_some() || matches!(surface, crate::SnapshotSurface::Window) {+ 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_for_app(adapter, app_name, deadline)?,+ windows,crate::AdapterError::new(crate::ErrorCode::WindowNotFound,format!(@@ -146,6 +157,27 @@ fn is_shell_surface(surface: crate::SnapshotSurface) -> bool {| 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",)}@@ -252,15 +284,7 @@ pub(crate) fn resolve_window(}}}- crate::system::window_lookup::select_window(- windows,- crate::AdapterError::new(- crate::ErrorCode::WindowNotFound,- format!("Application '{app}' is running but has no matching window"),- )- .with_suggestion("Wait for the app to present a window, or run 'list-windows --app'."),- "More than one window matches the target",- )+ select_app_window(windows, app)} else {crate::system::window_lookup::select_window(windows,diff --git a/crates/core/src/snapshot/snapshot_ref_tests.rs b/crates/core/src/snapshot/snapshot_ref_tests.rsindex a472bd5c7..4cf371f96 100644--- a/crates/core/src/snapshot/snapshot_ref_tests.rs+++ b/crates/core/src/snapshot/snapshot_ref_tests.rs@@ -116,6 +116,16 @@ impl ObservationOps for StubAdapter {crate::adapter::observed_tree(&root, window)}+ fn list_apps(&self, _deadline: crate::Deadline) -> Result<Vec<crate::AppInfo>, AdapterError> {+ Ok(vec![crate::AppInfo {+ name: "TestApp".into(),+ pid: crate::ProcessId::new(42),+ bundle_id: None,+ process_instance: Some("test-instance".into()),+ presentation: Some(crate::AppPresentation::Background),+ }])+ }+fn list_windows(&self,filter: &crate::adapter::WindowFilter,diff --git a/crates/core/src/snapshot/snapshot_ref_window_tests.rs b/crates/core/src/snapshot/snapshot_ref_window_tests.rsindex 6e311c0e6..e57cb89fc 100644--- a/crates/core/src/snapshot/snapshot_ref_window_tests.rs+++ b/crates/core/src/snapshot/snapshot_ref_window_tests.rs@@ -56,3 +56,27 @@ fn test_run_from_ref_does_not_persist_refs_when_source_window_is_gone() {"seed refs only; a failed drill must not persist refs");}++#[test]+fn test_run_from_ref_drills_a_ref_captured_from_a_windowless_app() {+ for surface in [+ crate::SnapshotSurface::Window,+ crate::SnapshotSurface::Menubar,+ ] {+ let _guard = HomeGuard::new();+ let opts = TreeOptions {+ surface,+ ..drill_opts()+ };+ let windowless = StubAdapter::with_windows(named("button", "Dock"), vec![]);+ 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:?}");+ 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:?}");+ }+}diff --git a/crates/core/src/snapshot/snapshot_surface.rs b/crates/core/src/snapshot/snapshot_surface.rsindex 0450b8309..fbeec9500 100644--- a/crates/core/src/snapshot/snapshot_surface.rs+++ b/crates/core/src/snapshot/snapshot_surface.rs@@ -32,6 +32,25 @@ pub enum SnapshotSurface {}impl SnapshotSurface {+ /// The refusal for a surface an adapter does not root: a wrong argument+ /// when the platform roots other kinds, a platform limit when it roots none.+ pub fn unavailable_error(self, supported: &[Self]) -> crate::AdapterError {+ crate::AdapterError::new(+ if supported.is_empty() {+ crate::ErrorCode::PlatformNotSupported+ } else {+ crate::ErrorCode::InvalidArgs+ },+ format!("Snapshot surface '{}' is not available on this platform", self.as_str()),+ )+ .with_details(serde_json::json!({+ "requested_surface": self.as_str(),+ "supported_surfaces": supported.iter().map(|surface| surface.as_str()).collect::<Vec<_>>()+ }))+ .with_suggestion("Choose one of the supported snapshot surfaces")+ .with_disposition(crate::DeliverySemantics::not_delivered())+ }+pub fn is_window(surface: &Self) -> bool {matches!(surface, Self::Window)}diff --git a/crates/core/src/snapshot/snapshot_window_tests.rs b/crates/core/src/snapshot/snapshot_window_tests.rsindex 196a4212d..fae51e379 100644--- a/crates/core/src/snapshot/snapshot_window_tests.rs+++ b/crates/core/src/snapshot/snapshot_window_tests.rs@@ -173,6 +173,33 @@ fn app_name_resolution_discriminates_absent_from_windowless() {assert_eq!(windowless.code(), "WINDOW_NOT_FOUND");}+#[test]+fn a_windowless_app_is_a_process_owner_only_when_it_is_background() {+ use crate::AppPresentation::{Background, Foreground};+ use crate::SnapshotSurface::{MenuBarExtras, Menubar, Window};+ let app = |presentation| crate::AppInfo {+ presentation: Some(presentation),+ ..running_app("Helper")+ };+ let cases = [+ (vec![app(Background)], Window, None),+ (vec![app(Background)], Menubar, None),+ (vec![app(Background)], MenuBarExtras, None),+ (vec![app(Foreground)], Window, Some("WINDOW_NOT_FOUND")),+ (vec![app(Foreground)], Menubar, Some("WINDOW_NOT_FOUND")),+ (vec![app(Background); 2], Window, Some("AMBIGUOUS_TARGET")),+ ];+ for (running_apps, surface, error_code) in cases {+ let adapter = AppInventoryAdapter { running_apps };+ let deadline = crate::Deadline::after(100).unwrap();+ let result = resolve_window_for_surface(&adapter, Some("Helper"), None, surface, deadline);+ match error_code {+ None => assert!(result.unwrap().is_process_owner()),+ Some(code) => assert_eq!(result.unwrap_err().code(), code),+ }+ }+}+/// An adapter whose `resolve_shell_surface` answers with the trait default -/// the exact shape `AdapterError::not_supported` builds - falls through to/// the application path for a routed shell kind, so upgrading an adapter in@@ -285,9 +312,9 @@ fn the_seams_window_not_found_passes_through_with_its_suggestion() {);}-/// A window-owned sub-surface is never routed to the seam, even when the-/// adapter implements it: the application path stays the answer for kinds-/// some application owns.+/// A window-owned sub-surface, or an app's own status item, is never routed to+/// the seam, even when the adapter implements it: the application path stays+/// the answer for kinds some application owns.#[test]fn a_window_owned_surface_kind_is_not_routed_to_the_seam() {let adapter = ShellSurfaceAdapter {@@ -295,14 +322,18 @@ fn a_window_owned_surface_kind_is_not_routed_to_the_seam() {resolution: Ok(shell_window()),};- let resolved = resolve_window_for_surface(- &adapter,- Some("WhatsApp"),- None,+ for surface in [crate::SnapshotSurface::Sheet,- crate::Deadline::after(100).unwrap(),- )- .unwrap();-- assert_eq!(resolved.id, "w-1");+ crate::SnapshotSurface::MenuBarExtras,+ ] {+ let resolved = resolve_window_for_surface(+ &adapter,+ Some("WhatsApp"),+ None,+ surface,+ crate::Deadline::after(100).unwrap(),+ )+ .unwrap();+ assert_eq!(resolved.id, "w-1");+ }}diff --git a/crates/core/src/system/app_lookup.rs b/crates/core/src/system/app_lookup.rsindex 1449518e2..d799a62d3 100644--- a/crates/core/src/system/app_lookup.rs+++ b/crates/core/src/system/app_lookup.rs@@ -5,6 +5,27 @@ use crate::{adapter::{PlatformAdapter, WindowFilter},};+/// Owner for a named app that lists no window. A background app is observed+/// through its process; any other app has not presented a window yet. Failures+/// of the app lookup propagate, except an adapter without an app inventory,+/// which keeps the window error.+pub(crate) fn windowless_app_owner(+ adapter: &dyn PlatformAdapter,+ app: &str,+ deadline: Deadline,+) -> Result<WindowInfo, AppError> {+ match resolve_app(Some(app), adapter, deadline) {+ Ok(info) if info.presentation == Some(crate::AppPresentation::Background) => {+ Ok(WindowInfo::for_process(&info))+ }+ Ok(_) => Err(AdapterError::app_has_no_window(app).into()),+ Err(AppError::Adapter(error)) if error.code == ErrorCode::PlatformNotSupported => {+ Err(AdapterError::app_has_no_window(app).into())+ }+ Err(error) => Err(error),+ }+}+pub(crate) fn resolve_app(app: Option<&str>,adapter: &dyn PlatformAdapter,@@ -148,6 +169,36 @@ pub(crate) fn process_identity(app: &AppInfo) -> Result<ProcessIdentity, AppErroOk(ProcessIdentity::new(app.pid, instance))}+/// The live process a process-owned ref was captured from, revalidated by pid,+/// process instance and name; a replaced or exited process is stale.+pub(crate) fn live_process_owner(+ adapter: &dyn PlatformAdapter,+ entry: &crate::RefEntry,+ deadline: Deadline,+) -> Result<WindowInfo, AppError> {+ let stale = |reason| AppError::Adapter(AdapterError::stale_ref_because(reason));+ let expected = AppInfo {+ name: entry+ .source+ .source_app+ .clone()+ .ok_or_else(|| stale("ref has no source app"))?,+ pid: entry.process.pid,+ bundle_id: None,+ process_instance: Some(+ entry+ .process+ .process_instance+ .clone()+ .ok_or_else(|| stale("ref has no process instance"))?,+ ),+ presentation: None,+ };+ Ok(WindowInfo::for_process(&revalidate_app_for_mutation(+ adapter, &expected, deadline,+ )?))+}+pub(crate) fn revalidate_app_for_mutation(adapter: &dyn PlatformAdapter,expected: &AppInfo,diff --git a/crates/core/src/system/window_info.rs b/crates/core/src/system/window_info.rsindex aafc54cec..83551cfac 100644--- a/crates/core/src/system/window_info.rs+++ b/crates/core/src/system/window_info.rs@@ -17,6 +17,28 @@ pub struct WindowInfo {pub state: WindowState,}+impl WindowInfo {+ /// Identifies an app's process instead of one of its windows, for an app+ /// observed from its application root because it has no window.+ pub fn for_process(app: &crate::AppInfo) -> Self {+ Self {+ id: String::new(),+ title: String::new(),+ app: app.name.clone(),+ pid: app.pid,+ process_instance: app.process_instance.clone(),+ bounds: None,+ state: WindowState::default(),+ }+ }++ /// Whether this names a process built by [`WindowInfo::for_process`]+ /// rather than a window.+ pub fn is_process_owner(&self) -> bool {+ self.id.is_empty()+ }+}+#[cfg(test)]#[path = "window_info_tests.rs"]mod tests;diff --git a/crates/ffi/include/agent_desktop.h b/crates/ffi/include/agent_desktop.hindex b56987013..6bb5f171a 100644--- a/crates/ffi/include/agent_desktop.h+++ b/crates/ffi/include/agent_desktop.h@@ -1374,6 +1374,8 @@ AdResult ad_execute_by_ref_timeout(const struct AdAdapter *adapter,** 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.** `data.complete` is always present. A snapshot that exhausts its observation* budget still succeeds with `"complete":false` and the tree it did observe,diff --git a/crates/ffi/src/commands/snapshot.rs b/crates/ffi/src/commands/snapshot.rsindex 271d41a54..1af33f1f6 100644--- a/crates/ffi/src/commands/snapshot.rs+++ b/crates/ffi/src/commands/snapshot.rs@@ -16,6 +16,8 @@ use std::ptr;////// 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.////// `data.complete` is always present. A snapshot that exhausts its observation/// budget still succeeds with `"complete":false` and the tree it did observe,diff --git a/crates/linux/src/system/adapter.rs b/crates/linux/src/system/adapter.rsindex 667b395c4..4e7a60816 100644--- a/crates/linux/src/system/adapter.rs+++ b/crates/linux/src/system/adapter.rs@@ -3,10 +3,10 @@ use agent_desktop_core::system::launch_result::LaunchResult;use agent_desktop_core::system::process_state::ProcessState;use agent_desktop_core::{ActionResult, AdapterError, AdapterSession, AppInfo, Deadline, DismissAllNotificationsRequest,- DismissNotificationRequest, DisplayInfo, ErrorCode, ImageBuffer, InteractionLease,- InteractionPolicy, KeyCombo, NotificationActionRequest, NotificationFilter, NotificationInfo,- OperationReport, PermissionReport, ProcessIdentity, ScreenshotTarget, SessionAffinity,- SignalBaseline, SignalFilter, SnapshotSurface, SystemOps, WindowInfo, WindowOp,+ DismissNotificationRequest, DisplayInfo, ImageBuffer, InteractionLease, InteractionPolicy,+ KeyCombo, NotificationActionRequest, NotificationFilter, NotificationInfo, OperationReport,+ PermissionReport, ProcessIdentity, ScreenshotTarget, SessionAffinity, SignalBaseline,+ SignalFilter, SnapshotSurface, SystemOps, WindowInfo, WindowOp,};use crate::adapter::LinuxAdapter;@@ -212,15 +212,7 @@ impl SystemOps for LinuxAdapter {if supported.contains(&requested) {return Ok(());}- Err(AdapterError::new(- ErrorCode::PlatformNotSupported,- format!("Snapshot surface '{}' is not supported on this platform", requested.as_str()),- )- .with_details(serde_json::json!({- "requested_surface": requested.as_str(),- "supported_surfaces": supported.into_iter().map(SnapshotSurface::as_str).collect::<Vec<_>>()- }))- .with_suggestion("Choose one of the supported snapshot surfaces"))+ Err(requested.unavailable_error(&supported))}fn open_session(diff --git a/crates/linux/src/system/shell/kinds_tests.rs b/crates/linux/src/system/shell/kinds_tests.rsindex 32391d122..193456bc5 100644--- a/crates/linux/src/system/shell/kinds_tests.rs+++ b/crates/linux/src/system/shell/kinds_tests.rs@@ -26,6 +26,6 @@ fn taskbar_open_is_refused_before_any_bus_access() {&lease,).expect_err("the shell does not present a taskbar");- assert_eq!(error.code, ErrorCode::PlatformNotSupported);+ assert_eq!(error.code, ErrorCode::InvalidArgs);assert!(error.message.contains("no stock shell shows a dock"));}diff --git a/crates/linux/src/system/shell/mod.rs b/crates/linux/src/system/shell/mod.rsindex 95cba62b0..6eeeb4426 100644--- a/crates/linux/src/system/shell/mod.rs+++ b/crates/linux/src/system/shell/mod.rs@@ -2,8 +2,8 @@ pub(crate) mod anchor;pub(crate) mod call_failure;pub(crate) mod located;use agent_desktop_core::{- AdapterError, Deadline, ErrorCode, InteractionLease, InteractionPolicy, ObservationRequest,- ObservationRoot, ObservedTree, SnapshotSurface, WindowInfo,+ AdapterError, Deadline, DeliverySemantics, ErrorCode, InteractionLease, InteractionPolicy,+ ObservationRequest, ObservationRoot, ObservedTree, SnapshotSurface, WindowInfo,};use crate::system::{SharedBus, window::window_id};@@ -67,13 +67,25 @@ pub(crate) fn is_shell_window(window: &WindowInfo) -> bool {.is_ok_and(|(bus_name, _)| identity::is_shell_owner(&bus_name, window.pid.get()))}+fn unknown_kind_error(surface: SnapshotSurface) -> AdapterError {+ AdapterError::new(+ ErrorCode::InvalidArgs,+ format!(+ "'{}' is not a shell surface this desktop has",+ surface.as_str()+ ),+ )+ .with_suggestion("Use system-tray, action-center or quick-settings")+ .with_disposition(DeliverySemantics::not_delivered())+}+pub(crate) fn resolve_surface(bus: &SharedBus,surface: SnapshotSurface,deadline: Deadline,) -> Result<WindowInfo, AdapterError> {let Some(kind) = kinds::kind_of(surface) else {- return Err(AdapterError::not_supported("resolve_shell_surface"));+ return Err(unknown_kind_error(surface));};let root = identity::find_root(bus, deadline)?;let landmark = open::container_landmark(kind);@@ -93,14 +105,15 @@ pub(crate) fn open_surface(lease: &InteractionLease,) -> Result<WindowInfo, AdapterError> {let Some(kind) = kinds::kind_of(surface) else {- return Err(AdapterError::not_supported("open_system_surface"));+ return Err(unknown_kind_error(surface));};if kind == kinds::ShellKind::Dock {return Err(AdapterError::new(- ErrorCode::PlatformNotSupported,+ ErrorCode::InvalidArgs,"The taskbar surface is not offered: no stock shell shows a dock",)- .with_suggestion("Open system-tray, action-center or quick-settings instead"));+ .with_suggestion("Open system-tray, action-center or quick-settings instead")+ .with_disposition(DeliverySemantics::not_delivered()));}open::open(bus, kind, policy, lease).map(|(window, _)| window)}diff --git a/crates/linux/src/tree/observe/mod.rs b/crates/linux/src/tree/observe/mod.rsindex b4f64749e..9bfdbbe2b 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::Window(window) if window.is_process_owner() => {+ Err(AdapterError::app_has_no_window(&window.app))+ }ObservationRoot::Window(window) => {refuse_stopped(window, proc_stat::is_stopped)?;let (bus, path) = window_id::decode(&window.id)?;diff --git a/crates/macos/src/actions/activation_effect.rs b/crates/macos/src/actions/activation_effect.rsindex 632d83f6e..67bff7127 100644--- a/crates/macos/src/actions/activation_effect.rs+++ b/crates/macos/src/actions/activation_effect.rs@@ -13,10 +13,12 @@ mod imp {/// unsupported code to the action that navigates it, and moves its/// selection rather than the focus. Selection is therefore read as well,/// on every element, because an attribute an element does not publish reads- /// as absent and the rule simply never fires for it.+ /// as absent and the rule simply never fires for it. The focused editor's+ /// value is read because a press can replace what that editor shows.#[derive(Default)]pub(crate) struct FocusState {focused_element: Option<AXElement>,+ focused_value: Option<String>,selected: Option<bool>,menu_open: Option<bool>,}@@ -44,13 +46,17 @@ mod imp {pub(crate) fn focus_state(element: &AXElement, deadline: Deadline) -> Option<FocusState> {let app = crate::system::app::app_ops::pid_from_element(element, deadline).map(crate::tree::element_for_pid)?;+ let focused_element = crate::tree::properties::attributes::copy_element_attr_result(+ &app,+ "AXFocusedUIElement",+ deadline,+ )+ .ok()?;Some(FocusState {- focused_element: crate::tree::properties::attributes::copy_element_attr_result(- &app,- "AXFocusedUIElement",- deadline,- )- .ok()?,+ focused_value: focused_element+ .as_ref()+ .and_then(|focused| crate::tree::copy_value_typed(focused, deadline)),+ focused_element,selected: crate::tree::properties::attributes::copy_bool_attr_result(element,crate::actions::select::container_select::SELECTED,@@ -111,11 +117,15 @@ mod imp {deadline: Deadline,) -> bool {let after = focus_state(element, deadline);- let target_focused = after+ let focused = after.as_ref()- .and_then(|state| state.focused_element.as_ref())- .is_some_and(|focused| focus_reached(focused, element, deadline));+ .and_then(|state| state.focused_element.as_ref());+ let target_focused =+ focused.is_some_and(|focused| focus_reached(focused, element, deadline));observed_change(before, &after, target_focused)+ || focus_changed_in_target_window(before, &after, || {+ focused.and_then(|focused| shares_window(focused, element, deadline)) == Some(true)+ })}/// A control that owns an editor hands focus to the editor, not to itself:@@ -184,6 +194,28 @@ mod imp {)}+ /// Focus moved, or the focused element shows new content, in the target's window.+ fn focus_changed_in_target_window(+ before: &Option<FocusState>,+ after: &Option<FocusState>,+ focused_in_target_window: impl FnOnce() -> bool,+ ) -> bool {+ matches!((before, after), (Some(before), Some(after))+ if after.focused_element.is_some() && (before != after+ || matches!((&before.focused_value, &after.focused_value), (Some(old), Some(new)) if old != new)))+ && focused_in_target_window()+ }++ fn shares_window(focused: &AXElement, element: &AXElement, deadline: Deadline) -> Option<bool> {+ let window = |el| {+ crate::tree::properties::attributes::copy_element_attr_result(el, "AXWindow", deadline)+ };+ Some(crate::tree::same_element(+ &window(focused).ok()??,+ &window(element).ok()??,+ ))+ }+/// An element that was not selected and now is has been acted on, whatever/// return code the application chose. The reverse is not evidence: a/// selection that was already true says nothing about this action.@@ -204,19 +236,35 @@ mod imp {fn focused(pid: i32) -> Option<FocusState> {Some(FocusState {focused_element: Some(crate::tree::element_for_pid(pid)),- selected: None,- menu_open: None,+ ..FocusState::default()})}fn selected(value: Option<bool>) -> Option<FocusState> {Some(FocusState {- focused_element: None,selected: value,- menu_open: None,+ ..FocusState::default()})}+ #[test]+ fn a_focus_change_counts_only_inside_the_pressed_elements_window() {+ let editor = |pid, value: &str| {+ Some(FocusState {+ focused_value: Some(value.into()),+ ..focused(pid).unwrap_or_default()+ })+ };+ let changed =+ |old, new, in_window| focus_changed_in_target_window(&old, &new, || in_window);+ assert!(changed(editor(1, "old note"), editor(1, ""), true));+ assert!(changed(focused(1), editor(2, ""), true));+ assert!(!changed(editor(1, "old note"), editor(1, ""), false));+ assert!(!changed(focused(1), editor(2, ""), false));+ assert!(!changed(editor(1, "same"), editor(1, "same"), true));+ assert!(!changed(editor(1, "old note"), focused(1), true));+ }+#[test]fn focus_changes_must_correlate_with_the_target() {let before = focused(1);diff --git a/crates/macos/src/actions/chain/chain_value_write.rs b/crates/macos/src/actions/chain/chain_value_write.rsindex 860c48874..1fff7b978 100644--- a/crates/macos/src/actions/chain/chain_value_write.rs+++ b/crates/macos/src/actions/chain/chain_value_write.rs@@ -93,17 +93,22 @@ mod imp {}delivered = true;delivery.mark_delivered();- match read_number(element, deadline).map_err(|error| delivery.annotate(error))? {+ match read_after_step(element, ¤t_text, deadline)+ .map_err(|error| delivery.annotate(error))?+ {Some((next, text)) => {- let progressed = increment_progressed(¤t_text, &text, requested);+ if !increment_progressed(¤t_text, &text, requested) {+ return Err(delivery.annotate(+ AdapterError::new(+ agent_desktop_core::ErrorCode::ActionFailed,+ format!("Native steps cannot reach {requested}: the last step moved the value from {current_text} to {text}"),+ )+ .with_suggestion("Read the current value and set one the control's steps reach.")+ .with_details(serde_json::json!({ "before_step": current_text, "after_step": text })),+ ));+ }current = next;current_text = text;- if !progressed {- return Err(delivery.annotate(AdapterError::new(- agent_desktop_core::ErrorCode::ActionFailed,- "Native increments stopped progressing toward the requested value",- ).with_suggestion("Read the current value; choose a target supported by the control's native step size.")));- }}_ => break,}@@ -197,6 +202,23 @@ mod imp {&& increment_action(after, target) == direction)}+ /// An increment is applied asynchronously by some controls, so the value+ /// read right after the action can still be the previous one.+ fn read_after_step(+ element: &AXElement,+ previous: &str,+ deadline: Deadline,+ ) -> Result<Option<(f64, String)>, AdapterError> {+ let settle = deadline.capped(std::time::Duration::from_millis(400));+ loop {+ let read = read_number(element, deadline)?;+ if settle.is_expired() || read.as_ref().is_none_or(|(_, text)| text != previous) {+ return Ok(read);+ }+ std::thread::sleep(settle.remaining().min(std::time::Duration::from_millis(20)));+ }+ }+pub(crate) fn increment_target_reached(current: &str, target: &str) -> bool {agent_desktop_core::value_matches("incrementor", target, Some(current))}diff --git a/crates/macos/src/actions/dispatch.rs b/crates/macos/src/actions/dispatch.rsindex 920d34cff..c1a09f409 100644--- a/crates/macos/src/actions/dispatch.rs+++ b/crates/macos/src/actions/dispatch.rs@@ -231,6 +231,12 @@ mod imp {"AXRole",operation_deadline,) {+ Ok(Some(role))+ if role == "AXMenuBarItem"+ && crate::tree::shell_surface::is_status_item(element, operation_deadline) =>+ {+ Ok(None)+ }Err(error) if error.code == ErrorCode::AppUnresponsive => Ok(None),result => result,}diff --git a/crates/macos/src/actions/physical_target.rs b/crates/macos/src/actions/physical_target.rsindex ff01b41eb..6d2719352 100644--- a/crates/macos/src/actions/physical_target.rs+++ b/crates/macos/src/actions/physical_target.rs@@ -4,7 +4,7 @@ use crate::tree::AXElement;pub(crate) struct PreparedPhysicalTarget {identity: crate::system::process::process_identity::ProcessIdentity,- window: AXElement,+ window: Option<AXElement>,}impl PreparedPhysicalTarget {@@ -23,10 +23,20 @@ impl PreparedPhysicalTarget {"Physical input target process exited before input preparation",)})?;- let window = target_window(element, deadline)?;- crate::system::focus::verify_app_focused(pid, deadline)?;- crate::system::focus::verify_window_main(&window, deadline)?;- Ok(Self { identity, window })+ let window = target_window(element, pid, deadline)?;+ let prepared = Self { identity, window };+ prepared.verify_focus(deadline)?;+ Ok(prepared)+ }++ /// 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 {+ return Ok(());+ };+ crate::system::focus::verify_app_focused(self.identity.pid(), deadline)?;+ crate::system::focus::verify_window_main(window, deadline)}pub(crate) fn verify_pointer(@@ -35,8 +45,7 @@ impl PreparedPhysicalTarget {point: &Point,deadline: Deadline,) -> Result<(), AdapterError> {- crate::system::focus::verify_app_focused(self.identity.pid(), deadline)?;- crate::system::focus::verify_window_main(&self.window, deadline)?;+ 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 {@@ -73,7 +82,19 @@ impl PreparedPhysicalTarget {}}-fn target_window(element: &AXElement, deadline: Deadline) -> Result<AXElement, AdapterError> {+/// The window that must stay main during input, or `None` when focus cannot+/// apply: a background app (a menu bar app, the Dock, a system panel) never+/// becomes frontmost, and a status item has no window. The hit test still+/// gates delivery. Any other target without a verified window is refused.+fn target_window(+ element: &AXElement,+ pid: i32,+ deadline: Deadline,+) -> Result<Option<AXElement>, AdapterError> {+ let instant = crate::tree::locator_deadline::from_operation(deadline)?;+ if is_background_app(pid, instant) {+ return Ok(None);+ }crate::tree::properties::attributes::set_messaging_timeout(element, deadline)?;let result = crate::tree::properties::attributes::copy_element_attr_result(element, "AXWindow", deadline,@@ -82,7 +103,8 @@ fn target_window(element: &AXElement, deadline: Deadline) -> Result<AXElement, Areturn Err(deadline.timeout_error());}match result {- Ok(Some(window)) => Ok(window),+ Ok(Some(window)) => Ok(Some(window)),+ Ok(None) if crate::tree::shell_surface::is_status_item(element, instant) => Ok(None),Ok(None) => Err(AdapterError::new(ErrorCode::ActionFailed,"Physical input target has no verified owning window",@@ -98,3 +120,13 @@ fn target_window(element: &AXElement, deadline: Deadline) -> Result<AXElement, A}))),}}++/// Whether `pid` is an app AppKit runs without a regular activation policy. A+/// failed inventory read answers false, which keeps every focus check.+fn is_background_app(pid: i32, deadline: std::time::Instant) -> bool {+ crate::system::app::workspace_apps::window_owner_snapshot_until(deadline).is_ok_and(|owners| {+ owners.owner(pid).is_some_and(|owner| {+ owner.activation_policy != crate::system::app::workspace_apps::ActivationPolicy::Regular+ })+ })+}diff --git a/crates/macos/src/system/adapter.rs b/crates/macos/src/system/adapter.rsindex 10f953e17..b36e1b0f6 100644--- a/crates/macos/src/system/adapter.rs+++ b/crates/macos/src/system/adapter.rs@@ -114,6 +114,21 @@ impl SystemOps for MacOSAdapter {crate::system::signals::supported_surfaces_impl()}+ /// The Dock and the menu bar extras are always presented, so opening one+ /// returns it without raising anything or moving the foreground, which is+ /// why no policy floor applies.+ fn open_system_surface(+ &self,+ surface: SnapshotSurface,+ _policy: agent_desktop_core::InteractionPolicy,+ lease: &InteractionLease,+ ) -> Result<WindowInfo, AdapterError> {+ crate::tree::shell_surface::resolve_surface(+ surface,+ crate::tree::locator_deadline::from_operation(lease.deadline())?,+ )+ }+fn capture_signal_baseline(&self,filter: &SignalFilter,diff --git a/crates/macos/src/system/app/workspace_apps.rs b/crates/macos/src/system/app/workspace_apps.rsindex 43bdf5974..1fefa62e3 100644--- a/crates/macos/src/system/app/workspace_apps.rs+++ b/crates/macos/src/system/app/workspace_apps.rs@@ -19,6 +19,7 @@ struct BridgedApplication {pid: i32,#[serde(default)]bundle_id: Option<String>,+ executable: Option<String>,launch_time: NullableLaunchTime,activation_policy: ActivationPolicy,}@@ -51,6 +52,7 @@ pub(crate) struct WindowOwner {pub(crate) pid: i32,pub(crate) name: String,pub(crate) bundle_id: Option<String>,+ pub(crate) executable: Option<String>,pub(crate) launch_time: Option<f64>,pub(crate) activation_policy: ActivationPolicy,}@@ -67,15 +69,17 @@ impl WindowOwnerSnapshot {self.owners.iter().map(|owner| owner.pid).collect()}+ /// Pids of the apps `identifier` names. A bundle ID or executable name counts+ /// only when no app has that display name, so an alias never merges two apps.pub(crate) fn matching_pids(&self, identifier: &str) -> rustc_hash::FxHashSet<i32> {+ let named =+ |owner: &WindowOwner| agent_desktop_core::app_name_matches(&owner.name, identifier);+ let by_alias = !self.owners.iter().any(named);self.owners.iter().filter(|owner| {- agent_desktop_core::app_name_matches(&owner.name, identifier)- || owner- .bundle_id- .as_deref()- .is_some_and(|bundle_id| bundle_id.eq_ignore_ascii_case(identifier))+ named(owner)+ || (by_alias && has_alias(&owner.bundle_id, &owner.executable, identifier))}).map(|owner| owner.pid).collect()@@ -120,20 +124,18 @@ pub(crate) fn require_complete(skipped: &[serde_json::Value]) -> Result<(), Adap))}+/// Apps named `name`, optionally pinned to `bundle_id`. Without one, a bundle+/// ID or executable name matches only when no app has that display name.pub(crate) fn list_apps_scoped_until(name: &str,bundle_id: Option<&str>,deadline: Instant,) -> Result<AppInventory, AdapterError> {- list_apps_with(+ let mut inventory = list_apps_with(deadline,|app| {(agent_desktop_core::app_name_matches(&app.name, name)- || (bundle_id.is_none()- && app- .bundle_id- .as_deref()- .is_some_and(|candidate| candidate.eq_ignore_ascii_case(name))))+ || (bundle_id.is_none() && has_alias(&app.bundle_id, &app.executable, name)))&& bundle_id.is_none_or(|bundle| {app.bundle_id.as_deref()@@ -141,7 +143,20 @@ pub(crate) fn list_apps_scoped_until(})},false,- )+ )?;+ let named = |app: &AppInfo| agent_desktop_core::app_name_matches(&app.name, name);+ if inventory.apps.iter().any(named) {+ inventory.apps.retain(named);+ }+ Ok(inventory)+}++/// Whether `identifier` is the app's bundle ID or executable name.+fn has_alias(bundle_id: &Option<String>, executable: &Option<String>, identifier: &str) -> bool {+ [bundle_id, executable]+ .into_iter()+ .flatten()+ .any(|alias| alias.eq_ignore_ascii_case(identifier))}pub(crate) fn window_owner_snapshot_until(@@ -276,6 +291,7 @@ fn window_owner_snapshot_from_json(pid: app.pid,name: app.name,bundle_id: app.bundle_id,+ executable: app.executable,launch_time,activation_policy: app.activation_policy,});diff --git a/crates/macos/src/system/app/workspace_apps_tests.rs b/crates/macos/src/system/app/workspace_apps_tests.rsindex ed135a6ea..5187a5cc9 100644--- a/crates/macos/src/system/app/workspace_apps_tests.rs+++ b/crates/macos/src/system/app/workspace_apps_tests.rs@@ -50,27 +50,23 @@ fn owner_snapshot_includes_regular_and_accessory_but_excludes_prohibited() {fn owner_snapshot_matches_visible_app_name_and_bundle_id() {let bytes = br#"{"applications":[- {"name":"\u200eWhatsApp","pid":10,"bundle_id":"net.whatsapp.WhatsApp","launch_time":100.25,"activation_policy":"regular"}+ {"name":"\u200eWhatsApp","executable":"WhatsAppDesktop","pid":10,"bundle_id":"net.whatsapp.WhatsApp","launch_time":100.25,"activation_policy":"regular"},+ {"name":"Helper","executable":"WhatsApp","pid":11,"launch_time":100.5,"activation_policy":"accessory"}],"frontmost_pid":10,"frontmost_launch_time":100.25}"#;let snapshot = window_owner_snapshot_from_json(bytes, deadline()).unwrap();- assert_eq!(- snapshot- .matching_pids("WhatsApp")- .into_iter()- .collect::<Vec<_>>(),- [10]- );- assert_eq!(- snapshot- .matching_pids("net.whatsapp.WhatsApp")- .into_iter()- .collect::<Vec<_>>(),- [10]- );+ for identifier in ["WhatsApp", "net.whatsapp.WhatsApp", "WhatsAppDesktop"] {+ assert_eq!(+ snapshot+ .matching_pids(identifier)+ .into_iter()+ .collect::<Vec<_>>(),+ [10]+ );+ }}#[test]diff --git a/crates/macos/src/system/appkit_bridge.m b/crates/macos/src/system/appkit_bridge.mindex 19b9699a9..d512200dd 100644--- a/crates/macos/src/system/appkit_bridge.m+++ b/crates/macos/src/system/appkit_bridge.m@@ -225,6 +225,10 @@ AgentDesktopBytesResult agent_desktop_copy_workspace_snapshot_json(void) {}record[@"bundle_id"] = bundle;}+ NSString *executable = agent_desktop_non_blank(app.executableURL.lastPathComponent);+ if (executable != nil && [executable lengthOfBytesUsingEncoding:NSUTF8StringEncoding] <= 16384) {+ record[@"executable"] = executable;+ }[records addObject:record];}NSMutableDictionary *snapshot = [@{diff --git a/crates/macos/src/system/signals.rs b/crates/macos/src/system/signals.rsindex b7e8074a2..52c17d0ea 100644--- a/crates/macos/src/system/signals.rs+++ b/crates/macos/src/system/signals.rs@@ -14,6 +14,8 @@ pub(crate) fn supported_surfaces_impl() -> Vec<SnapshotSurface> {SnapshotSurface::Sheet,SnapshotSurface::Popover,SnapshotSurface::Alert,+ SnapshotSurface::Dock,+ SnapshotSurface::MenuBarExtras,]}diff --git a/crates/macos/src/system/signals_tests.rs b/crates/macos/src/system/signals_tests.rsindex 53bf5af21..6358d2646 100644--- a/crates/macos/src/system/signals_tests.rs+++ b/crates/macos/src/system/signals_tests.rs@@ -12,6 +12,8 @@ fn supported_surfaces_are_only_the_implemented_macos_contract() {SnapshotSurface::Sheet,SnapshotSurface::Popover,SnapshotSurface::Alert,+ SnapshotSurface::Dock,+ SnapshotSurface::MenuBarExtras,]);}diff --git a/crates/macos/src/system/window/window_resolve.rs b/crates/macos/src/system/window/window_resolve.rsindex 55235770a..81dc00316 100644--- a/crates/macos/src/system/window/window_resolve.rs+++ b/crates/macos/src/system/window/window_resolve.rs@@ -27,6 +27,9 @@ pub(crate) fn window_element_for_info_with_deadline(win: &WindowInfo,deadline: std::time::Instant,) -> Result<AXElement, AdapterError> {+ if win.is_process_owner() && win.title.is_empty() {+ return Err(AdapterError::app_has_no_window(&win.app));+ }if win.id.is_empty() {let pid = crate::system::process::process_identity::to_pid_t(win.pid)?;return window_element_by_title(pid, &win.title, deadline);diff --git a/crates/macos/src/tree/adapter.rs b/crates/macos/src/tree/adapter.rsindex c273ad8ea..0918f7a59 100644--- a/crates/macos/src/tree/adapter.rs+++ b/crates/macos/src/tree/adapter.rs@@ -86,6 +86,17 @@ impl ObservationOps for MacOSAdapter {)}+ fn resolve_shell_surface(+ &self,+ surface: agent_desktop_core::SnapshotSurface,+ deadline: Deadline,+ ) -> Result<WindowInfo, AdapterError> {+ crate::tree::shell_surface::resolve_surface(+ surface,+ crate::tree::locator_deadline::from_operation(deadline)?,+ )+ }+fn list_surfaces(&self,process: agent_desktop_core::ProcessIdentity,diff --git a/crates/macos/src/tree/mod.rs b/crates/macos/src/tree/mod.rsindex 78251e536..9abc6f053 100644--- a/crates/macos/src/tree/mod.rs+++ b/crates/macos/src/tree/mod.rs@@ -15,6 +15,7 @@ pub(crate) mod read_recovery;pub(crate) mod renderer_probe;pub(crate) mod resolve;pub(crate) mod roles;+pub(crate) mod shell_surface;pub(crate) mod state_reader;pub(crate) mod surface_inventory;pub(crate) mod surface_read;diff --git a/crates/macos/src/tree/query/mod.rs b/crates/macos/src/tree/query/mod.rsindex 2e33c361f..4fae0bfc0 100644--- a/crates/macos/src/tree/query/mod.rs+++ b/crates/macos/src/tree/query/mod.rs@@ -183,6 +183,9 @@ fn resolve_window_surface(},)?}+ SnapshotSurface::Window | SnapshotSurface::Dock if window.is_process_owner() => {+ crate::tree::properties::element::element_for_pid(pid)+ }SnapshotSurface::Window => {crate::system::window::window_resolve::window_element_for_info_with_deadline(window, deadline,@@ -194,6 +197,10 @@ fn resolve_window_surface(.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::MenuBarExtras => {+ crate::tree::shell_surface::extras_menu_bar(pid, deadline)?+ .ok_or_else(|| AdapterError::element_not_found("No menu bar extras found"))?+ }_ => return Err(AdapterError::not_supported("snapshot surface")),};crate::tree::locator_deadline::remaining(deadline)?;diff --git a/crates/macos/src/tree/resolve/mod.rs b/crates/macos/src/tree/resolve/mod.rsindex 4461ea553..f114890e3 100644--- a/crates/macos/src/tree/resolve/mod.rs+++ b/crates/macos/src/tree/resolve/mod.rs@@ -251,7 +251,7 @@ fn is_retryable_resolution_error(error: &AdapterError) -> bool {#[cfg(target_os = "macos")]fn can_use_locator_anchor_path(entry: &RefEntry) -> bool {let source_scoped = if entry.source.source_surface == SnapshotSurface::Window {- source_window_scope_required(entry)+ source_window_scope_required(entry) || entry.source.is_process_rooted()} else {true};diff --git a/crates/macos/src/tree/resolve/resolve_roots.rs b/crates/macos/src/tree/resolve/resolve_roots.rsindex 8e3cd0c40..c30a146c4 100644--- a/crates/macos/src/tree/resolve/resolve_roots.rs+++ b/crates/macos/src/tree/resolve/resolve_roots.rs@@ -1,9 +1,9 @@use agent_desktop_core::{AdapterError, RefEntry, SnapshotSurface};use super::resolve_read_context::ResolveReadContext;-use crate::tree::AXElement;use crate::tree::element_dedupe::push_unique;use crate::tree::properties::element::element_for_pid;+use crate::tree::{AXElement, shell_surface::extras_menu_bar};#[cfg(target_os = "macos")]pub(in crate::tree) fn candidate_roots(@@ -25,6 +25,9 @@ pub(in crate::tree) fn candidate_roots(if source_window_scope_required(entry) {return source_window_scoped_roots(&application, entry, context);}+ if entry.source.is_process_rooted() {+ return Ok(vec![application]);+ }let mut roots = Vec::new();let windows = read_root_array(&application, "AXWindows", context)?;@@ -101,7 +104,8 @@ fn source_surface_scoped_roots(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)?,- SnapshotSurface::Window => None,+ SnapshotSurface::Dock => Some(application.clone()),+ SnapshotSurface::MenuBarExtras => extras_menu_bar(pid, deadline)?,_ => None,};let Some(root) = root else {diff --git a/crates/macos/src/tree/resolve/resolve_source_app.rs b/crates/macos/src/tree/resolve/resolve_source_app.rsindex 5035a5465..8c8e3ecde 100644--- a/crates/macos/src/tree/resolve/resolve_source_app.rs+++ b/crates/macos/src/tree/resolve/resolve_source_app.rs@@ -3,12 +3,17 @@ use agent_desktop_core::{AdapterError, RefEntry};use crate::tree::AXElement;use crate::tree::resolve::resolve_read_context::ResolveReadContext;+/// Window-owned sources are checked by application name. A process-owned source is already+/// identified by its saved pid and process instance, which resolution verifies first.#[cfg(target_os = "macos")]pub(in crate::tree) fn verify_source_application(application: &AXElement,entry: &RefEntry,context: &mut ResolveReadContext,) -> Result<(), AdapterError> {+ if entry.source.is_process_owned() {+ return Ok(());+ }let Some(expected) = entry.source.source_appdiff --git a/crates/macos/src/tree/shell_surface.rs b/crates/macos/src/tree/shell_surface.rsnew file mode 100644index 000000000..3837befd0--- /dev/null+++ b/crates/macos/src/tree/shell_surface.rs@@ -0,0 +1,77 @@+//! The Dock and the system menu bar extras: surfaces no window owns, found by+//! the process that presents them.++use super::{AXElement, properties::element::element_for_pid, surface_read};+use agent_desktop_core::{AdapterError, ErrorCode, SnapshotSurface, WindowInfo};+use std::time::Instant;++/// MenuBarAgent hosts the system status items on current macOS; Control Center+/// and SystemUIServer hosted them on earlier releases.+const MENU_BAR_EXTRAS_HOSTS: [&str; 3] = [+ "com.apple.MenuBarAgent",+ "com.apple.controlcenter",+ "com.apple.systemuiserver",+];++/// The system menu bar extras root in `pid`, or `None` when it presents none.+pub(crate) fn extras_menu_bar(+ pid: i32,+ deadline: Instant,+) -> Result<Option<AXElement>, AdapterError> {+ surface_read::element(&element_for_pid(pid), "AXExtrasMenuBar", deadline)+}++/// Whether `element` is a status item: a child of its app's extras menu bar,+/// which has no window and takes a click wherever the app is. A failed read+/// answers false.+pub(crate) fn is_status_item(element: &AXElement, deadline: Instant) -> bool {+ use super::properties::attributes::copy_element_attr_result;+ let parent = copy_element_attr_result(element, "AXParent", deadline);+ let pid = super::properties::ax_ipc::pid(element, deadline);+ match (parent, pid) {+ (Ok(Some(parent)), Ok(pid)) => matches!(+ extras_menu_bar(pid, deadline),+ Ok(Some(extras)) if super::same_element(&parent, &extras)+ ),+ _ => false,+ }+}++pub(crate) fn resolve_surface(+ surface: SnapshotSurface,+ deadline: Instant,+) -> Result<WindowInfo, AdapterError> {+ let hosts: &[&str] = match surface {+ SnapshotSurface::Dock => &["com.apple.dock"],+ SnapshotSurface::MenuBarExtras => &MENU_BAR_EXTRAS_HOSTS,+ _ => {+ return Err(AdapterError::new(+ ErrorCode::InvalidArgs,+ format!("'{}' is not a macOS shell surface", surface.as_str()),+ )+ .with_suggestion("Use dock or menu-bar-extras; open Control Center or Notification Center by clicking its menu-bar-extras item")+ .with_disposition(agent_desktop_core::DeliverySemantics::not_delivered()));+ }+ };+ let inventory = crate::system::app::workspace_apps::list_apps_inventory_until(deadline)?;+ for host in hosts {+ for app in inventory+ .apps+ .iter()+ .filter(|app| app.bundle_id.as_deref() == Some(*host))+ {+ let pid = crate::system::process::process_identity::to_pid_t(app.pid)?;+ if surface == SnapshotSurface::Dock || extras_menu_bar(pid, deadline)?.is_some() {+ return Ok(WindowInfo::for_process(app));+ }+ }+ }+ crate::system::app::workspace_apps::require_complete(&inventory.skipped)?;+ Err(AdapterError::new(+ ErrorCode::WindowNotFound,+ format!(+ "No running process presents the '{}' surface",+ surface.as_str()+ ),+ ))+}diff --git a/crates/windows/src/system/shell/shell_surface.rs b/crates/windows/src/system/shell/shell_surface.rsindex 7a865c841..ddc61f21c 100644--- a/crates/windows/src/system/shell/shell_surface.rs+++ b/crates/windows/src/system/shell/shell_surface.rs@@ -35,12 +35,13 @@ pub(in crate::system) fn resolve_row(pub(crate) fn unknown_surface_error(kind: SnapshotSurface) -> AdapterError {AdapterError::new(- ErrorCode::PlatformNotSupported,+ ErrorCode::InvalidArgs,format!("'{}' is not a shell surface this adapter resolves",kebab(kind)),)+ .with_suggestion("Use taskbar, system-tray, system-tray-overflow, start-menu or action-center").with_disposition(DeliverySemantics::not_delivered())}@@ -71,7 +72,7 @@ pub(crate) fn not_open_error(kind: SnapshotSurface) -> AdapterError {pub(crate) fn refusal_error(row: &SurfaceKindRow) -> AdapterError {let holder = row.capability_holder.unwrap_or("an equivalent surface");AdapterError::new(- ErrorCode::PlatformNotSupported,+ ErrorCode::InvalidArgs,format!("the running build does not expose the '{}' shell surface",kebab(row.kind)diff --git a/crates/windows/src/system/shell/shell_surface_kinds_tests.rs b/crates/windows/src/system/shell/shell_surface_kinds_tests.rsindex 6cbbcd2c4..fe8388152 100644--- a/crates/windows/src/system/shell/shell_surface_kinds_tests.rs+++ b/crates/windows/src/system/shell/shell_surface_kinds_tests.rs@@ -16,7 +16,7 @@ fn quick_settings_refusal_names_build_and_capability_holder() {let error = open_surface(SnapshotSurface::QuickSettings, headed(), deadline(5_000)).expect_err("quick-settings is absent on this build");- assert_eq!(error.code, ErrorCode::PlatformNotSupported);+ assert_eq!(error.code, ErrorCode::InvalidArgs);let build = build_number();assert!(build > 0, "the build number must be read, not guessed");let detail = error.platform_detail.expect("the refusal carries a detail");diff --git a/crates/windows/src/tree/surfaces.rs b/crates/windows/src/tree/surfaces.rsindex c4b458d85..c70e18d1b 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::Window(window), _) if window.is_process_owner() => {+ Err(AdapterError::app_has_no_window(&window.app))+ }(ObservationRoot::Window(window), SnapshotSurface::Window) => {let handle = parse_window_id(&window.id)?;root_from_hwnd(handle, deadline)diff --git a/docs/install.md b/docs/install.mdindex 367e875af..d1b45e7a4 100644--- a/docs/install.md+++ b/docs/install.md@@ -81,7 +81,7 @@ the rest: `agent-desktop skills get linux`.**Windows.** `list-surfaces` lists each process's `window`, `focused`, `sheet` and `menu` surfaces. `snapshot--surface` also reads `taskbar`, `system-tray`, `system-tray-overflow`, `start-menu` and `action-center` without-`--app`. `quick-settings` returns `PLATFORM_NOT_SUPPORTED` and names `action-center`, which carries those controls.+`--app`. `quick-settings` returns `INVALID_ARGS` and names `action-center`, which carries those controls.`launch` on Windows takes an absolute path, or a bare name under System32 or the Windows directory, with orwithout `.exe`. It cannot resolve a display name such as "Google Chrome".diff --git a/docs/json-output.md b/docs/json-output.mdindex 665541be6..2b0a90e78 100644--- a/docs/json-output.md+++ b/docs/json-output.md@@ -119,12 +119,16 @@ Version 2.6 changes which refs resolve on Windows and Linux, and on macOS for an- An identical twin that appears after capture fails `AMBIGUOUS_TARGET` with `details.kind: "saved_ref_ambiguous"`.- All of these carry `details.retryable: false` and a `not_delivered` disposition. `disposition.retry` stays `safe` because nothing was sent, but repeating the same ref returns the same refusal.- 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`.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- 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.- 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.diff --git a/skills/agent-desktop-linux/references/shell-tray-and-notifications.md b/skills/agent-desktop-linux/references/shell-tray-and-notifications.mdindex a022b8115..9f36c0777 100644--- a/skills/agent-desktop-linux/references/shell-tray-and-notifications.md+++ b/skills/agent-desktop-linux/references/shell-tray-and-notifications.md@@ -271,8 +271,8 @@ two can work:| `system-tray` | Needs `org.kde.StatusNotifierWatcher`. Without it: `PLATFORM_NOT_SUPPORTED`, `watcher: absent`, the same refusal as `snapshot --surface system-tray`. No window is returned || `action-center` | Opens the GNOME message list when its container and opener are proven; otherwise `ACTION_NOT_SUPPORTED`, `shell_container_unproven` || `quick-settings` | `ACTION_NOT_SUPPORTED`, `shell_container_unproven`, before any input |-| `taskbar` | `PLATFORM_NOT_SUPPORTED`: no stock shell shows a dock |-| `start-menu`, `system-tray-overflow`, other values | `PLATFORM_NOT_SUPPORTED`, not supported on this platform |+| `taskbar` | `INVALID_ARGS`: no stock shell shows a dock |+| `start-menu`, `system-tray-overflow`, other values | `INVALID_ARGS`, naming `system-tray`, `action-center` and `quick-settings` |Retrying an unsupported value gives the same refusal.diff --git a/skills/agent-desktop-linux/references/troubleshooting.md b/skills/agent-desktop-linux/references/troubleshooting.mdindex a51075a6f..1783785eb 100644--- a/skills/agent-desktop-linux/references/troubleshooting.md+++ b/skills/agent-desktop-linux/references/troubleshooting.md@@ -184,7 +184,7 @@ D-Bus or X11 error.modifiers and `drag`.- `cursor-overlay` on Wayland: succeeds as a setting only. `enable` returns`data.rendered: false` and no overlay is drawn, so do not wait for one.-- `open-system-surface --surface taskbar`: `PLATFORM_NOT_SUPPORTED`. Use the+- `open-system-surface --surface taskbar`: `INVALID_ARGS`. Use theadvertised GNOME surfaces; see `references/shell-tray-and-notifications.md`.- Ordinary app pointer commands and window screenshots on Wayland. Shell refclicks also refuse on Wayland, and on X11 unless the shell's own tree proves thediff --git a/skills/agent-desktop-macos/SKILL.md b/skills/agent-desktop-macos/SKILL.mdindex 8047b3a61..2d88b6c97 100644--- a/skills/agent-desktop-macos/SKILL.md+++ b/skills/agent-desktop-macos/SKILL.md@@ -7,7 +7,8 @@ description: >macOS platform guide for the agent-desktop CLI. Use for desktop automationon macOS: granting Accessibility and Screen Recording permission (TCC),what headed mode does on macOS (physical-first click, type and scroll),- surfaces (menu, menubar, sheet, popover, alert), Notification Center,+ surfaces (menu, menubar, sheet, popover, alert, dock, menu-bar-extras),+ menu bar apps and system panels with no window, Notification Center,Chromium and Electron apps including launch --cdp, and fixing PERM_DENIED,empty accessibility trees, ACTION_FAILED and APP_UNRESPONSIVE.---@@ -35,11 +36,11 @@ 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. 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 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.**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 File, Edit and View menus and for menu bar apps (status items). While a menu, sheet, alert or popover is open, refs from the window tree behind it are the wrong target.+**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.@@ -47,7 +48,7 @@ Read the core skill first (`agent-desktop skills get desktop`) for the observe,**Chromium and Electron.** agent-desktop switches on the web accessibility of a Chromium renderer automatically when it needs it. For a dense running app, use `snapshot --skeleton -i --compact`, then drill with `--root @ref`.-**Identity.** `launch` accepts a display name (`"System Settings"`) or a bundle ID (`com.apple.systempreferences`). Other commands take the display name through `--app`. Window IDs such as `w-4521` stay valid for the life of the window. Find them with `list-windows`.+**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.diff --git a/skills/agent-desktop-windows/SKILL.md b/skills/agent-desktop-windows/SKILL.mdindex 947c629df..e93d2a730 100644--- a/skills/agent-desktop-windows/SKILL.md+++ b/skills/agent-desktop-windows/SKILL.md@@ -31,7 +31,7 @@ observation, actions and capture there fail or return nothing.|-------|----------|-------------------|| Observation | `snapshot`, `find`, `get`, `is`, `screenshot` | Works. Surfaces are `window`, `focused`, a Chromium modal as `sheet`, and an open application menu as `menu` || Surfaces | `list-surfaces` | Works. Lists `window`, `focused` and `sheet` per process, plus `menu` with `item_count` while a menu is open |-| Shell surfaces | `open-system-surface` | Works for `start-menu`, `taskbar`, `system-tray`, `system-tray-overflow` and `action-center`, and returns the window `snapshot --surface <kind>` reads. `quick-settings` returns `PLATFORM_NOT_SUPPORTED` naming `action-center` |+| Shell surfaces | `open-system-surface` | Works for `start-menu`, `taskbar`, `system-tray`, `system-tray-overflow` and `action-center`, and returns the window `snapshot --surface <kind>` reads. `quick-settings` returns `INVALID_ARGS` naming `action-center` || Ref interaction | `click`, `right-click`, `type`, `set-value`, `clear`, `select`, `toggle`, `check`, `uncheck`, `expand`, `collapse`, `scroll`, `scroll-to` | Works, semantic in headless and `--headed` mode. `right-click` and `type` need `--headed` and return `POLICY_DENIED` headless || Multi-click and focus | `double-click`, `triple-click`, `focus` | Works with global `--headed` only || Keyboard and mouse | `press`, `hover`, `drag`, `mouse-click`, `mouse-move`, `mouse-wheel` | Works. Cursor-moving input needs `--headed`. First Contact covers `press --app` |diff --git a/skills/agent-desktop-windows/references/shell-and-overlay.md b/skills/agent-desktop-windows/references/shell-and-overlay.mdindex a974f4eee..bdbfb3e95 100644--- a/skills/agent-desktop-windows/references/shell-and-overlay.md+++ b/skills/agent-desktop-windows/references/shell-and-overlay.md@@ -17,7 +17,7 @@ windows.- **`snapshot --surface <kind>` needs no `--app` and works headless.** A closedsurface returns `WINDOW_NOT_FOUND` with a suggestion that names`open-system-surface`.-- **`quick-settings` returns `PLATFORM_NOT_SUPPORTED`** and names+- **`quick-settings` returns `INVALID_ARGS`** and names`action-center`, where the quick actions live.- **`start-menu` is whatever the Win key raises.** Before Windows 11 that is asearch overlay whose root holds a `SearchTextBox`, not a tile grid. Drive itdiff --git a/skills/agent-desktop/references/commands-interaction.md b/skills/agent-desktop/references/commands-interaction.mdindex a5c3dc983..49fb2a4a2 100644--- a/skills/agent-desktop/references/commands-interaction.md+++ b/skills/agent-desktop/references/commands-interaction.md@@ -54,7 +54,7 @@ Exit codes: `0` success, `1` structured error, `2` argument error. The `error` o| `APP_UNRESPONSIVE` | A liveness probe also failed after an uncertain mutation | Take a fresh snapshot. Wait for recovery before you retry || `TIMEOUT` | Wait or actionability condition not met | Read `error.details.kind` || `INVALID_ARGS` | Bad arguments, or a protected system process was targeted for close | Check syntax |-| `PLATFORM_NOT_SUPPORTED` | The adapter lacks this method or surface | Use another approach |+| `PLATFORM_NOT_SUPPORTED` | The adapter lacks this method | Use another approach || `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` |diff --git a/skills/agent-desktop/references/commands-observation.md b/skills/agent-desktop/references/commands-observation.mdindex 877654583..2274c2c27 100644--- a/skills/agent-desktop/references/commands-observation.md+++ b/skills/agent-desktop/references/commands-observation.md@@ -24,6 +24,8 @@ 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`.+Each ref names the snapshot that owns it, so a ref keeps resolving against its own snapshot when you interleave several apps or windows.Choose the scope:@@ -60,7 +62,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. An unsupported kind returns `PLATFORM_NOT_SUPPORTED` with the supported list in `details`. A shell surface needs no `--app`. When it is closed you get `WINDOW_NOT_FOUND`; raise it with `open-system-surface`.+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`.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.@@ -132,7 +134,7 @@ Lists the overlay surfaces an app presents now, the values `snapshot --surface`agent-desktop --headed open-system-surface --surface action-center```-Raises an OS shell surface and returns the window it presents, in the `w-<id>` form that `list-windows` uses. It takes the foreground, so strict headless is refused with `POLICY_DENIED`; pass `--headed`. An already-present surface returns without being raised again. A kind the OS does not expose returns `PLATFORM_NOT_SUPPORTED` with a `platform_detail` that names the alternative. See the platform skill for the kinds.+Raises an OS shell surface. On Windows and Linux it returns the window it presents, in the `w-<id>` form that `list-windows` uses; on macOS `data` is only `{"surface": "dock"}` and `window` is left out, because no window owns these surfaces. It takes the foreground, so on Windows and Linux strict headless is refused with `POLICY_DENIED`; pass `--headed`. On macOS, `dock` and `menu-bar-extras` are always on screen, so they return headless with no `--headed`. An already-present surface returns without being raised again. A kind the OS does not expose returns `INVALID_ARGS` naming the kinds to use instead. `start-menu` is a Windows kind and `action-center` exists on Windows and Linux (GNOME); neither is a macOS kind. On macOS use `dock` or `menu-bar-extras`, and open Control Center or Notification Center by clicking its `menu-bar-extras` item. See the platform skill for the kinds.## Chromium and Electron appsdiff --git a/src/cli/mod.rs b/src/cli/mod.rsindex eb61abe0d..2dd7cf023 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -129,7 +129,7 @@ pub(crate) enum Commands {#[command(about = "List accessibility surfaces for an app (window, menu, sheet ...)")]ListSurfaces(ListSurfacesArgs),#[command(- about = "Open a shell surface (start-menu, taskbar, action-center ...) and return the window it presents"+ about = "Open a shell surface (start-menu, taskbar, dock, menu-bar-extras ...) and return the window it presents, if any")]OpenSystemSurface(OpenSystemSurfaceArgs),#[command(about = "List notifications from Notification Center")]diff --git a/src/cli/windows_capability_claims_tests.rs b/src/cli/windows_capability_claims_tests.rsindex 840004c4e..05fe365bb 100644--- a/src/cli/windows_capability_claims_tests.rs+++ b/src/cli/windows_capability_claims_tests.rs@@ -94,7 +94,7 @@ fn windows_adapter_still_refuses_what_the_skill_marks_unavailable() {);assert_eq!(quick_settings.code,- ErrorCode::PlatformNotSupported,+ ErrorCode::InvalidArgs,"quick-settings changed behaviour; update the Windows skill's capability table");let detail = quick_settings.platform_detail.expect(diff --git a/src/cli_args/system.rs b/src/cli_args/system.rsindex ded3fb4b1..996743d18 100644--- a/src/cli_args/system.rs+++ b/src/cli_args/system.rs@@ -306,7 +306,7 @@ pub(crate) struct OpenSystemSurfaceArgs {#[arg(long,value_enum,- help = "Shell surface to open: start-menu, taskbar, system-tray, system-tray-overflow, action-center"+ help = "Shell surface to open: start-menu, taskbar, system-tray, system-tray-overflow, action-center, dock, menu-bar-extras")]pub surface: Surface,}diff --git a/tests/e2e-windows/scenarios/ShellSurfaces.ps1 b/tests/e2e-windows/scenarios/ShellSurfaces.ps1index 1955fa033..aacb2be94 100644--- a/tests/e2e-windows/scenarios/ShellSurfaces.ps1+++ b/tests/e2e-windows/scenarios/ShellSurfaces.ps1@@ -103,7 +103,7 @@ function Invoke-ShellActionCenterOpenLeg {}$open = Invoke-ShellActionCenterOpenWithRetry -Surface 'action-center'if (-not $open.Opened) {- if ($open.ErrorCode -eq 'PLATFORM_NOT_SUPPORTED') {+ if ($open.ErrorCode -eq 'INVALID_ARGS') {$script:ShellSurfacesSkippedLeg = $legAdd-Skip -Leg $leg -Token 'shell-surface-absent' -Reason "open-system-surface refused with $($open.ErrorCode); this runner does not expose the surface"return@@ -150,7 +150,7 @@ function Invoke-ShellActionCenterCloseLeg {if (-not $pre.Opened) {$open = Invoke-ShellActionCenterOpenWithRetry -Surface 'action-center'if (-not $open.Opened) {- if ($open.ErrorCode -eq 'PLATFORM_NOT_SUPPORTED') {+ if ($open.ErrorCode -eq 'INVALID_ARGS') {$script:ShellSurfacesSkippedLeg = $legAdd-Skip -Leg $leg -Token 'shell-surface-absent' -Reason "open-system-surface refused with $($open.ErrorCode); this runner does not expose the surface"returndiff --git a/tests/e2e-windows/skip-allowlist.psd1 b/tests/e2e-windows/skip-allowlist.psd1index ab13dd022..0df6e07d5 100644--- a/tests/e2e-windows/skip-allowlist.psd1+++ b/tests/e2e-windows/skip-allowlist.psd1@@ -1,5 +1,5 @@@{'chromium-target-absent' = 'No Electron/Chromium target is guaranteed on an arbitrary runner; Edge is absent under this grounding (G5). Declared for the Chromium/renderer scenario so a target-less host reports a visible skip rather than a silent pass.''foreground-grant-declined' = 'A raw SetForegroundWindow (AttachThreadInput + AllowSetForegroundWindow) staged from the long-lived harness process itself can be declined by this desktop even after every documented workaround, the same escape hatch crates/windows/src/system/signal/wait_event_live_tests.rs already takes for focus_changed ("this desktop declines foreground even to a raw SetForegroundWindow"). Declared for the contended focus-steal control (R17b(c)) so an unstageable host reports a visible skip rather than a silent pass; the N-trial rate leg is never reached when the control cannot be established.'- 'shell-surface-absent' = 'A runner whose shell does not expose the surface a leg drives: open-system-surface answers PLATFORM_NOT_SUPPORTED (the informative build refusal) instead of an identity. Declared for the Action Center legs of the shell-surfaces scenario so a surface-less host reports a visible skip rather than a silent pass or a fake failure; the tray/taskbar legs have no skip path because their Win32-class kinds exist on every build the adapter resolves.'+ 'shell-surface-absent' = 'A runner whose shell does not expose the surface a leg drives: open-system-surface answers INVALID_ARGS (the informative build refusal) instead of an identity. Declared for the Action Center legs of the shell-surfaces scenario so a surface-less host reports a visible skip rather than a silent pass or a fake failure; the tray/taskbar legs have no skip path because their Win32-class kinds exist on every build the adapter resolves.'}diff --git a/tests/e2e/README.md b/tests/e2e/README.mdindex 82f7b8cb2..8adc8c34b 100644--- a/tests/e2e/README.md+++ b/tests/e2e/README.md@@ -88,6 +88,7 @@ helper that returns a bare `@eN`.| `scenarios/trace_performance.sh` | Trace artifacts, redaction, timings, cleanup || `scenarios/ref_churn.sh` | `STALE_REF` after the UI really changes, on a dedicated fixture process (`AGENT_DESKTOP_FIXTURE_REF_CHURN=1`) || `scenarios/notifications.sh` | Real Notification Center lifecycle |+| `scenarios/os_surfaces.sh` | Dock launch, Control Center panel and volume slider, `--app` by executable name || `permission-contract.sh` | Deterministic AE5 mapping tests without mutating TCC || `electron-live.sh`, `electron_metrics*.py` | Opt-in installed Electron/Chromium app measurement || `json_tool.py`, `bounded_process.py`, `guard-command.sh` | JSON field extraction and the timeout/output-capped, process-group-isolated command runner |diff --git a/tests/e2e/run.sh b/tests/e2e/run.shindex 2107f01f2..3d0a4a2e6 100755--- a/tests/e2e/run.sh+++ b/tests/e2e/run.sh@@ -141,6 +141,9 @@ check_fixture_contention || { finish; exit 1; }source "$here/scenarios/trace_performance.sh"# shellcheck source=tests/e2e/scenarios/notifications.shsource "$here/scenarios/notifications.sh"+check_fixture_contention || { finish; exit 1; }+# shellcheck source=tests/e2e/scenarios/os_surfaces.sh+source "$here/scenarios/os_surfaces.sh"note "Multi-agent cursor probe"if [ "$fixture_owned" -eq 0 ] || "$bin" close-app "$app" --force >/dev/null 2>&1; thendiff --git a/tests/e2e/scenarios/os_surfaces.sh b/tests/e2e/scenarios/os_surfaces.shnew file mode 100644index 000000000..a1075a372--- /dev/null+++ b/tests/e2e/scenarios/os_surfaces.sh@@ -0,0 +1,137 @@+os_volume() { osascript -e "output volume of (get volume settings)" 2>/dev/null; }+os_ref() { printf '%s' "$1" | python3 "$json_tool" tree "$2" ref 2>/dev/null; }++os_wait_volume() {+ local value=""+ for _ in $(seq 1 25); do+ value="$(os_volume)"+ case "$value" in+ ''|*[!0-9]*) ;;+ *) if [ "$value" -ge 45 ] && [ "$value" -le 55 ]; then printf '%s' "$value"; return 0; fi ;;+ esac+ sleep 0.2+ done+ printf '%s' "$value"+ return 1+}++os_panel_open=0+os_cc_ref=""++os_wait_panel() {+ local want="$1" seen+ for _ in $(seq 1 15); do+ seen=closed+ [ -n "$(os_ref "$("$bin" snapshot --app "Control Center" -i 2>/dev/null)" Sound)" ] && seen=open+ [ "$seen" = "$want" ] && return 0+ sleep 0.2+ done+ return 1+}++os_close_panel() {+ [ "$os_panel_open" = 1 ] || return 0+ os_panel_open=0+ os_wait_panel closed && return 0+ "$bin" click "$os_cc_ref" >/dev/null 2>&1+ os_wait_panel closed+}++os_restore_volume() {+ os_close_panel || badmsg "the Control Center panel stayed open after its item was clicked again"+ osascript -e "set volume output volume $volume_original" >/dev/null 2>&1+}++os_control_center_volume() {+ local extras panel sound_ref detail slider_ref set_output volume volume_moved=0+ extras="$("$bin" snapshot --surface menu-bar-extras -i 2>/dev/null)"+ os_cc_ref="$(os_ref "$extras" "Control Center")"+ if [ -z "$os_cc_ref" ]; then+ badmsg "menu-bar-extras snapshot lists no Control Center item ref [ok=$(json_field "$extras" ok)]"+ return+ fi+ okmsg "menu-bar-extras snapshot lists the Control Center item [$os_cc_ref]"+ os_panel_open=1+ panel="$("$bin" click "$os_cc_ref" --wait-for "button:Sound" 2>/dev/null)"+ sound_ref="$(os_ref "$panel" Sound)"+ if [ -z "$sound_ref" ]; then+ badmsg "clicking Control Center did not return a panel snapshot with a Sound button [ok=$(json_field "$panel" ok) error=$(json_field "$panel" error.code)]"+ return+ fi+ detail="$("$bin" click "$sound_ref" --wait-for "slider:sound volume" 2>/dev/null)"+ slider_ref="$(os_ref "$detail" "sound volume")"+ if [ -z "$slider_ref" ]; then+ badmsg "clicking Sound did not return a snapshot with the sound volume slider [ok=$(json_field "$detail" ok) error=$(json_field "$detail" error.code)]"+ return+ fi+ set_output="$("$bin" set-value "$slider_ref" 0.5 2>/dev/null)"+ volume="$(os_wait_volume)" && volume_moved=1+ assert "set-value on the Control Center slider moves the system volume to about 50" \+ "$([ "$(json_field "$set_output" ok)" = "True" ] && [ "$volume_moved" = "1" ] && echo 1 || echo 0)" \+ "ok=$(json_field "$set_output" ok) error=$(json_field "$set_output" error.code) volume=$volume"+ os_close_panel || badmsg "clicking the Control Center item again did not close its panel"+ os_panel_open=1+ panel="$("$bin" --headed click "$os_cc_ref" 2>/dev/null)"+ assert "--headed click on the Control Center item opens its panel" \+ "$(os_wait_panel open && echo 1 || echo 0)" \+ "ok=$(json_field "$panel" ok) error=$(json_field "$panel" error.code)"+}++note "OS surfaces: process-name app, Dock, menu bar extras"+control_center_process="$("$bin" snapshot --app ControlCenter -i 2>/dev/null)"+assert "--app accepts the executable name ControlCenter without a window" \+ "$([ "$(json_field "$control_center_process" ok)" = "True" ] && \+ [ "$(json_field "$control_center_process" data.app)" = "Control Center" ] && \+ [ -z "$(json_field "$control_center_process" data.window)" ] && echo 1 || echo 0)" \+ "ok=$(json_field "$control_center_process" ok) app=$(json_field "$control_center_process" data.app) window=$(json_field "$control_center_process" data.window) error=$(json_field "$control_center_process" error.code)"++dock_surface="$("$bin" snapshot --surface dock -i 2>/dev/null)"+dock_process="$("$bin" snapshot --app Dock -i 2>/dev/null)"+assert "snapshot --surface dock lists the Dock items" \+ "$([ -n "$(os_ref "$dock_surface" Finder)" ] && echo 1 || echo 0)" \+ "ok=$(json_field "$dock_surface" ok) error=$(json_field "$dock_surface" error.code)"+assert "snapshot --app Dock lists the Dock items" \+ "$([ -n "$(os_ref "$dock_process" Finder)" ] && echo 1 || echo 0)" \+ "ok=$(json_field "$dock_process" ok) error=$(json_field "$dock_process" error.code)"++dock_launch=""+for candidate in TextEdit Calculator Notes; do+ if ! pgrep -x "$candidate" >/dev/null 2>&1 && [ -n "$(os_ref "$dock_surface" "$candidate")" ]; then+ dock_launch="$candidate"+ break+ fi+done+if [ -z "$dock_launch" ]; then+ skipmsg "Dock launch of a stopped app unavailable: no stopped TextEdit, Calculator or Notes item is pinned in the Dock"+else+ dock_click="$("$bin" click "$(os_ref "$dock_surface" "$dock_launch")" 2>/dev/null)"+ dock_launched=0+ for _ in $(seq 1 50); do+ if pgrep -x "$dock_launch" >/dev/null 2>&1; then dock_launched=1; break; fi+ sleep 0.2+ done+ assert "clicking the Dock item of a stopped app launches it" \+ "$([ "$(json_field "$dock_click" ok)" = "True" ] && [ "$dock_launched" = "1" ] && echo 1 || echo 0)" \+ "app=$dock_launch ok=$(json_field "$dock_click" ok) error=$(json_field "$dock_click" error.code) running=$dock_launched"+ "$bin" close-app "$dock_launch" --force >/dev/null 2>&1+fi++volume_original="$(os_volume)"+case "$volume_original" in+ ''|*[!0-9]*)+ badmsg "system output volume is not readable through osascript [volume='$volume_original']"+ ;;+ *)+ trap 'os_restore_volume; cleanup' EXIT+ trap 'exit 130' INT TERM HUP+ osascript -e "set volume output volume 20" >/dev/null 2>&1+ os_control_center_volume+ os_restore_volume+ volume_restored="$(os_volume)"+ assert "the system output volume is restored after the scenario" \+ "$([ "$volume_restored" = "$volume_original" ] && echo 1 || echo 0)" \+ "volume=$volume_restored expected=$volume_original"+ trap cleanup EXIT+ trap - INT TERM HUP+ ;;+esac