diff --git a/apps/docs/content/docs/commands/app-window.mdx b/apps/docs/content/docs/commands/app-window.mdx index 757c60aaab..0182b06318 100644 --- a/apps/docs/content/docs/commands/app-window.mdx +++ b/apps/docs/content/docs/commands/app-window.mdx @@ -139,7 +139,7 @@ agent-desktop close-app [--force] - `INVALID_ARGS` for a protected system process, with or without `--force`. - A save prompt keeps the app open. Read it with `snapshot --surface sheet`, answer it, then close again. - On macOS a graceful close returns `ACTION_FAILED` with `details.cause: modal_pending` and names the prompt when an alert or sheet is open before the request (`not_delivered`, nothing sent) or when the request raises one (`delivered_unverified`). Answer the prompt, or use `--force`. -- On Linux a headless graceful close runs. Where the focused window cannot be read (a Wayland session, or a focused window whose owner cannot be identified), it fails with `POLICY_DENIED` (`details.kind: focus_unreadable`) before any close request is sent. Report it to the user, or use `--force` (it discards unsaved work). If the app answers with a save prompt, the command fails with `ACTION_FAILED` (`details.cause: dialog_pending`), the app stays open, and the focus goes back to the window that had it (`details.focus_returned: true`). With `--headed` the focus is left where the prompt put it. Answer the prompt, or use `--force` (it discards unsaved work). +- On Linux a headless graceful close runs. On a native Wayland client it returns `ACTION_NOT_SUPPORTED` (`details.cause: wayland_session`), because the compositor has no close request for another client's window. Where the focused window cannot be read, it fails with `POLICY_DENIED` (`details.kind: focus_unreadable`) before any close request is sent. Report it to the user, or use `--force` (it discards unsaved work). If the app answers with a save prompt, the command fails with `ACTION_FAILED` (`details.cause: dialog_pending`), the app stays open, and the focus goes back to the window that had it (`details.focus_returned: true`). With `--headed` the focus is left where the prompt put it. Answer the prompt, or use `--force` (it discards unsaved work). On macOS a headless graceful close sends the quit request, and a save prompt opens in the app's own window behind the window in front. On Windows the close is posted to the app's windows, and if a window of the app takes the foreground, as a save prompt can, the command gives the foreground back to the window that had it. Linux checks focus first, as described above. diff --git a/apps/docs/content/docs/commands/batch.mdx b/apps/docs/content/docs/commands/batch.mdx index a40ba4df03..a84b96c15f 100644 --- a/apps/docs/content/docs/commands/batch.mdx +++ b/apps/docs/content/docs/commands/batch.mdx @@ -24,6 +24,15 @@ agent-desktop batch '[{"command":"version"},{"command":"wait","args":{"ms":100}} +In Windows PowerShell 5.1 the double quotes inside the JSON argument are dropped, and `batch` fails with `INVALID_ARGS` ("key must be a string"). Escape each quote with a backslash. `batch` has no stdin or file input. + +```powershell +$json = @' +[{"command":"version"},{"command":"wait","args":{"ms":100}}] +'@ +agent-desktop batch ($json -replace '"','\"') --stop-on-error +``` + ### Entry format diff --git a/apps/docs/content/docs/commands/interaction.mdx b/apps/docs/content/docs/commands/interaction.mdx index 16a0f1d298..133e844ea5 100644 --- a/apps/docs/content/docs/commands/interaction.mdx +++ b/apps/docs/content/docs/commands/interaction.mdx @@ -178,6 +178,8 @@ printf '%s' 'hello' | agent-desktop type @s8f3k2p9:e2 --stdin The action timeout starts after the input ends; it doesn't limit this wait. Empty input and all line breaks are kept, including a final newline. Use `printf '%s'` to avoid adding one. Input must be valid UTF-8 without NUL bytes (`\0`). The limits are 10,000 bytes for `type` and 128 KiB for `set-value`. +`--stdin` uses the bytes it receives, so a trailing newline becomes part of the text. `printf '%s'` sends none. PowerShell adds a line ending to a piped string; to send exact text on Windows, redirect a file in `cmd`: `cmd /c "agent-desktop set-value @s8f3k2p9:e2 --stdin < text.txt"`. + Provide either `--stdin` or a command-line value. To enter the text `--stdin`, put it after `--`: `agent-desktop type @s8f3k2p9:e2 -- --stdin`. Batch uses the JSON `text` or `value` field, which puts the text in process arguments. Run secret steps as separate `--stdin` commands. `--stdin` keeps text out of process arguments and omits observed `value` fields from JSON results, including `post_state.value`. Other app text and screenshot artifacts aren't redacted. diff --git a/apps/docs/content/docs/commands/wait.mdx b/apps/docs/content/docs/commands/wait.mdx index a9a28b53bd..88a87adcbe 100644 --- a/apps/docs/content/docs/commands/wait.mdx +++ b/apps/docs/content/docs/commands/wait.mdx @@ -16,6 +16,7 @@ agent-desktop wait --text TEXT [--count N] [--app NAME] agent-desktop wait --menu [--app NAME] agent-desktop wait --menu-closed [--app NAME] agent-desktop wait --notification [--text TEXT] [--app NAME] +agent-desktop wait --surface KIND [--app NAME] [--timeout MS] agent-desktop wait --event KIND [--app NAME] [--window TITLE] [--window-id ID] ``` @@ -34,9 +35,10 @@ agent-desktop wait --event KIND [--app NAME] [--window TITLE] [--window-id ID] + - +
--count NnoneFor --text: wait until exactly N nodes match.
--menu, --menu-closedoffWait until a menu surface is open, or dismissed.
--notificationoffWait until a new notification arrives.
--surface KINDnoneWait until a surface of this kind is open in the app: popover, sheet, alert, menu, or any. A surface that is already open matches at once.
--event KINDnoneWait for a lifecycle signal: window-opened, window-closed, app-launched, app-terminated, focus-changed, surface-appeared, or surface-dismissed.
--window-id IDnoneNarrow window-opened, window-closed, or focus-changed to one window.
--app NAMEnoneScope a window, text, menu, notification, or event wait to one application. Element and time waits ignore it.
--app NAMEnoneScope a window, text, menu, notification, surface, or event wait to one application. Element and time waits ignore it. A surface wait resolves the application once, at the start; without it the uniquely focused window's application is used, and a missing or ambiguous one is APP_NOT_FOUND or AMBIGUOUS_TARGET.
--timeout MS30000Timeout for every mode except MS, at most 86400000.
@@ -74,7 +76,7 @@ agent-desktop wait --element @s2txcl95uvubmn:e6 --predicate value --value 7 --ti ### Window -`--window TITLE` waits for any window whose title contains `TITLE`, focused or not. +`--window TITLE` waits for any window whose title contains `TITLE`, focused or not. When you do not know the title, wait for the event instead: `wait --event window-opened --app NAME`, in the same [batch](/desktop/commands/batch) as the action that opens the window. `--app` alone is not a wait mode. ```bash agent-desktop wait --window Calculator --app gnome-calculator --timeout 3000 @@ -105,6 +107,75 @@ agent-desktop wait --text Calculator --app gnome-calculator --timeout 3000 `--menu` waits until a menu surface is open, and `--menu-closed` until it is gone. Both return `{ "elapsed_ms", "found": true }`. On Linux, `--menu-closed` on a menu that never opened is true at once, so wait for `--menu` first. +### Surface + +`--surface KIND` polls the app's surface inventory until a surface of that kind is open: `popover`, `sheet`, `alert`, `menu`, or `any`. It waits for a state, not a change, so a surface that is already open matches immediately. Run it after the click that opens the surface: + +```bash +agent-desktop wait --surface sheet --app gedit --timeout 2000 +``` + +```json +{ + "version": "2.7", + "ok": true, + "command": "wait", + "data": { + "elapsed_ms": 87, + "found": true, + "surface": { + "id": "w-1.167-org-a11y-atspi-accessible-44", + "title": "Save As", + "type": "sheet" + } + } +} +``` + +The result is `{ "elapsed_ms", "found": true, "surface": SURFACE }`, where `SURFACE` has the fields `list-surfaces` returns. + +A kind the app's inventory could not read is never reported as one the app does not show. When the last inventory named the kind as unclassified, the timeout says the surface could not be read, sets `details.unread: true`, and lists what it did read in `last_observed`: + +```bash +agent-desktop wait --surface menu --app gedit --timeout 2000 +``` + +```json +{ + "version": "2.7", + "ok": false, + "command": "wait", + "error": { + "code": "TIMEOUT", + "message": "The menu surface could not be read within 2000ms", + "recovery": { + "strategy": "inspect_state_then_retry_original", + "retryable": true, + "requires_fresh_snapshot": true, + "retry_after_ms": 250 + }, + "details": { + "kind": "wait_timeout", + "last_observed": [ + { + "id": "w-1.167-org-a11y-atspi-accessible-12", + "title": "Untitled Document 1 - gedit", + "type": "window", + "unclassified": ["menu"] + } + ], + "predicate": "surface", + "surface": "menu", + "timeout_ms": 2000, + "unread": true + }, + "disposition": { "delivery": "not_delivered", "retry": "safe" } + } +} +``` + +A read of every window that shows no such surface is an observed absence: its timeout reads `No popover surface was open within 2000ms` and carries no `unread`. + ### Notification `--notification` takes a baseline of the notification list when it starts and returns the first notification not in it. `--text` and `--app` filter which notifications count. The result is `{ "condition": "notification", "matched": true, "notification": {...}, "elapsed_ms" }`. Headless limits on macOS and Windows are on the [notification commands](/desktop/commands/notifications) page. diff --git a/apps/docs/content/docs/guides/traces.mdx b/apps/docs/content/docs/guides/traces.mdx index 1bdb87f037..7b135fab4d 100644 --- a/apps/docs/content/docs/guides/traces.mdx +++ b/apps/docs/content/docs/guides/traces.mdx @@ -74,7 +74,7 @@ agent-desktop --trace /tmp/run.jsonl find --app gnome-calculator --role button - jq -c 'select(.event == "command.end")' /tmp/run.jsonl ``` -The file is created private. While `--trace` is set, the session's trace directory receives nothing. A trace write failure does not fail the command unless you add `--trace-strict`. +The file must be private: a regular file you own with one link. On Windows its folder must also exist and be private (only you, SYSTEM and Administrators); a folder that grants `Users` write is refused with `INVALID_ARGS`, so use a new folder under your profile. The file is created private. While `--trace` is set, the session's trace directory receives nothing. A trace write failure does not fail the command unless you add `--trace-strict`. ## Capture screenshots with a session diff --git a/apps/docs/content/docs/json-output.mdx b/apps/docs/content/docs/json-output.mdx index 104ffa3abb..788b376d72 100644 --- a/apps/docs/content/docs/json-output.mdx +++ b/apps/docs/content/docs/json-output.mdx @@ -100,7 +100,7 @@ A snapshot that runs out of budget still returns `ok: true`, with `"complete": f ## Action results and disposition -A ref action such as `click`, `type`, or `toggle` returns `data.action` and `data.disposition`, and can add `steps` (each mechanism tried), `post_state`, `surfaces` (surfaces open once the action settled), and `details`. `disposition` has two fields, `delivery` and `retry`; on success, `delivery` is `delivered_verified`, `delivered_unverified`, or `not_delivered` (already satisfied). What each value proves, and when a retry is safe, is in [Errors and recovery](/desktop/errors-and-recovery#disposition). +A ref action such as `click`, `type`, or `toggle` returns `data.action` and `data.disposition`, and can add `steps` (each mechanism tried), `post_state`, `surfaces` (surfaces open once the action settled), and `details`. When the read of `surfaces` fails, `details.surfaces` is `"not_read"`: an absent `surfaces` then does not mean that no overlay opened. `disposition` has two fields, `delivery` and `retry`; on success, `delivery` is `delivered_verified`, `delivered_unverified`, or `not_delivered` (already satisfied). What each value proves, and when a retry is safe, is in [Errors and recovery](/desktop/errors-and-recovery#disposition). ### Post-action observation diff --git a/apps/docs/content/docs/platforms/linux.mdx b/apps/docs/content/docs/platforms/linux.mdx index cbcde22e10..61c2a465c1 100644 --- a/apps/docs/content/docs/platforms/linux.mdx +++ b/apps/docs/content/docs/platforms/linux.mdx @@ -69,7 +69,7 @@ Ref actions are semantic AT-SPI calls that never move the pointer or change the Pointer gesturesdouble-click, triple-click, hover, drag, mouse-click, mouse-move, X11 onlyWayland: ACTION_NOT_SUPPORTED, cause wayland_session KeyboardScoped press (--app or --window-id) on X11 and Mutter Wayland. A scoped headless press needs the target window already activeUnscoped press; a scoped press to a background app (X11)Blocked combos such as alt+f4 without --force Held inputkey-down, key-up, mouse-down, mouse-up - App and windowlaunch, list-apps, list-windows on X11 and Wayland; window control and close-app --force on X11focus-window on X11; a graceful close-app of an app with unsaved work: the save prompt keeps the app open and is reported as dialog_pendingfocus-window and window control on Wayland: ACTION_NOT_SUPPORTED. A headless graceful close-app that cannot read the focused window (a Wayland session, or an owner it cannot identify) returns POLICY_DENIED with details.kind: focus_unreadable before any close request is sent. + App and windowlaunch, list-apps, list-windows on X11 and Wayland; window control and close-app --force on X11focus-window on X11; a graceful close-app of an app with unsaved work: the save prompt keeps the app open and is reported as dialog_pendingfocus-window and window control on Wayland: ACTION_NOT_SUPPORTED. A headless graceful close-app of a native Wayland client returns ACTION_NOT_SUPPORTED with details.cause: wayland_session. One that cannot read the focused window returns POLICY_DENIED with details.kind: focus_unreadable before any close request is sent. Capturescreenshot, list-displaysX11 under a compositing window manager (GNOME): display and --screen captures return PLATFORM_NOT_SUPPORTED (details.reason: "compositing"); capture one window instead. Wayland: portal consent on first use, and window targets are PLATFORM_NOT_SUPPORTED Clipboardclipboard-get (text, images, file lists)clipboard-set, clipboard-clear (text, images, file lists)Missing helper or wl-clipboard: PLATFORM_NOT_SUPPORTED WaitAll modes; --notification on GNOME @@ -91,7 +91,7 @@ Ref actions are semantic AT-SPI calls that never move the pointer or change the ## Surfaces -`supported_surfaces` lists `window`, `sheet`, `alert`, and `menu`, plus GNOME Shell kinds the session can resolve. After an opener, read `data.surfaces`. A GTK popover appears asynchronously, so if it is absent, run `wait --menu` before you assume the opener failed. A list-backed GTK4 dropdown is part of the window tree, not a menu surface. See [Surfaces](/desktop/surfaces). +`supported_surfaces` lists `window`, `sheet`, `alert`, and `menu`, plus GNOME Shell kinds the session can resolve. After an opener, read `data.surfaces`. A GTK popover appears asynchronously, so if it is absent, run `wait --menu` before you assume the opener failed. A list-backed GTK4 dropdown is part of the window tree, not a menu surface. A GTK4 list or grid view exposes its items without row nodes, so `select` and `click` cannot pick a row. See [Surfaces](/desktop/surfaces). ## Chromium, Qt, and Electron diff --git a/apps/docs/content/docs/platforms/macos.mdx b/apps/docs/content/docs/platforms/macos.mdx index 83659da436..77c10607fe 100644 --- a/apps/docs/content/docs/platforms/macos.mdx +++ b/apps/docs/content/docs/platforms/macos.mdx @@ -51,7 +51,7 @@ A text field that shows a file's name, such as a Finder name cell, does not rena Capturescreenshot, with Screen Recording permission Ref actionsclick, type, clear, scroll, expand, collapse, set-value, select on a list, table, outline or editable combo box, toggle, check, uncheck, scroll-to, focusright-click, select through a menu, click or expand on a pop-up button, menu button or combo box, click, toggle, check or uncheck on a label that ends in … or ...Headless: POLICY_DENIED Multi-click and pointerdouble-click when the element offers AXOpendouble-click, triple-click, hover, drag, mouse-move, mouse-click, mouse-wheelHeadless: POLICY_DENIED - KeyboardScoped press (--app or --window-id), always physical keyboard input; it never runs a menu item, so click the item insteadUnscoped pressQuit shortcuts such as cmd+q: POLICY_DENIED without --force + KeyboardScoped press (--app or --window-id), headless, return and escape run as accessibility actions on the focused element and every other key needs a focused element in the app (ACTION_FAILED, details.check: process_focus, not_delivered otherwise); a headless shortcut with a modifier never runs a menu item, so click the item insteadUnscoped pressQuit shortcuts such as cmd+q: POLICY_DENIED without --force Held inputkey-down, key-up, mouse-down, mouse-up App and windowlaunch, close-app, list-apps, list-windows, resize-window, move-window, minimize, maximize, restorefocus-window Clipboardclipboard-getclipboard-set (read back: delivered_verified), clipboard-clear @@ -76,6 +76,7 @@ Judge delivery by observation. AX return codes do not prove an effect: an app ca - The primary modifier is `cmd`: `press cmd+c --app "TextEdit"`. Punctuation keys work as the symbol or by name (`comma`, `period`, `slash`). - `cmd+q`, `cmd+shift+q`, `cmd+alt+esc`, `ctrl+cmd+q`, and `cmd+shift+delete` return `POLICY_DENIED` unless you pass `--force`. To quit an app, use `close-app`. - `press cmd+s --app "TextEdit"` sends the chord only when that app is frontmost. For a background app it returns `ACTION_FAILED` (`check: process_focus`) and sends nothing. +- A Save panel's name field takes a file name, never a path, and macOS shows a `/` typed there as `:`. Choose the folder with the panel's Where pop-up, which opens a menu and so needs `--headed`. Confirm the file on disk afterwards. - When agent-desktop opens Notification Center, it closes it afterward and restores the previous focus. Pass `--expected-app` and `--expected-title` on a single dismiss or action, because the stack shifts. Use `wait --notification --app "App"` for banners that vanish before you can list them. ## Chromium and Electron diff --git a/apps/docs/content/docs/platforms/windows.mdx b/apps/docs/content/docs/platforms/windows.mdx index b7a441dd95..f9cb04a28a 100644 --- a/apps/docs/content/docs/platforms/windows.mdx +++ b/apps/docs/content/docs/platforms/windows.mdx @@ -72,7 +72,7 @@ Use `$env:NAME = 'value'` instead of `export`, and `| ConvertFrom-Json` instead - `cmd` and `meta` are the Windows key, so `meta+c` is a shell shortcut. Write `ctrl+c` to copy. - `alt+f4`, `win+l`, `win+d`, `alt+tab`, `win+r`, `win+x`, `win+e`, `ctrl+shift+esc`, and their supersets are refused without `--force`. `ctrl+alt+delete` cannot be synthesized at all. - `type` is keystroke synthesis and needs `--headed`; use `set-value` headless. -- `press --app` writes to the foreground input queue and cannot target one background process. +- `press --app` writes to the foreground input queue and cannot target one background process. Headless, it works only when the target process owns the foreground window. Otherwise it returns `ACTION_FAILED` ("Windows SendInput cannot deliver to a background process", `details.check: process_focus`) with `not_delivered`, and sends nothing. ## Chromium and Electron diff --git a/apps/docs/content/docs/surfaces.mdx b/apps/docs/content/docs/surfaces.mdx index 01de27ea11..e4526c00d1 100644 --- a/apps/docs/content/docs/surfaces.mdx +++ b/apps/docs/content/docs/surfaces.mdx @@ -109,7 +109,7 @@ To reach one item, `find --surface` is cheaper than a dump: How agent-desktop selects an owner depends on the kind and platform: - `sheet`, `popover`, and `alert`: the app's accessible windows in order, focused first and then visible, and the first that presents one wins. With no `--app`, the frontmost process. -- `sheet`, `popover`, and `alert`: the app's accessible windows in order, focused first and then visible, and the first that presents one wins. With no `--app`, the frontmost process. +- On Windows, a popover is a window of its own that the window inventory leaves out: `list-surfaces` reports its `w-`, and `--window-id` with that id plus `--app` reads that exact popover. With several open and none named, the read is refused with `AMBIGUOUS_TARGET` and lists their ids rather than reading another popover. - On macOS, `menu` and `menubar` are application-owned and do not require a document window. If you pass `--window-id`, it selects the app that owns the surface. Snapshot data includes `app` and omits `window`. A complete lookup with no open menu or menu bar returns `ELEMENT_NOT_FOUND` with `details.kind: "surface_absent"` and `details.complete: true`. To read an application menu, snapshot `menubar` when it exists, click its item without `--headed`, then snapshot `--surface menu`. An absent menu bar can mean the app exposes none. - On implementations where `menu`, `menubar`, and `focused` are window-owned, any app window identifies the process, so several open windows are not ambiguous. - On macOS, `window`, `menubar`, and `menu-bar-extras` can read a background app with no window through its process. The result omits `window`. A regular app that has not shown a window returns `WINDOW_NOT_FOUND`; `focused` requires a focused window. @@ -150,7 +150,7 @@ agent-desktop list-surfaces --app gtk3-widget-factory } ``` -`list-surfaces` returns the overlays an app presents now, which are the kinds `snapshot --surface` accepts for it. Shell surfaces belong to the OS and never appear here. An entry can carry `"unclassified": ["sheet"]` or `["menu"]` when the check could not read that window, often because the app was busy. Treat the missing entry as unknown, not absent. +`list-surfaces` returns the overlays an app presents now, which are the kinds `snapshot --surface` accepts for it. Shell surfaces belong to the OS and never appear here. An entry can carry `"unclassified": ["sheet"]`, `["menu"]` or `["popover"]` when the check could not read that window, often because the app was busy or a search stopped at its bound. Treat the missing entry as unknown, not absent. ## Open an OS shell surface diff --git a/crates/core/src/actions/action_result.rs b/crates/core/src/actions/action_result.rs index a9efbd2ee4..55864cd936 100644 --- a/crates/core/src/actions/action_result.rs +++ b/crates/core/src/actions/action_result.rs @@ -94,6 +94,21 @@ impl ActionResult { self } + /// Records the overlays read once the action settled. A read that failed + /// is not "no overlay": it is reported as `details.surfaces: "not_read"`. + pub(crate) fn with_surfaces_read( + mut self, + read: Result, crate::AdapterError>, + ) -> Self { + match read { + Ok(surfaces) => { + self.surfaces = surfaces; + self + } + Err(_) => self.with_details(serde_json::json!({ "surfaces": "not_read" })), + } + } + pub fn with_verified_delivery(mut self) -> Self { if self.disposition == DeliverySemantics::delivered_unverified() { self.disposition = DeliverySemantics::delivered_verified(); diff --git a/crates/core/src/actions/action_result_tests.rs b/crates/core/src/actions/action_result_tests.rs index 3e560e7cc8..de35264276 100644 --- a/crates/core/src/actions/action_result_tests.rs +++ b/crates/core/src/actions/action_result_tests.rs @@ -185,3 +185,16 @@ fn an_annotation_keeps_the_details_an_inner_layer_set() { assert_eq!(details["pointer"], "verified"); assert_eq!(details["delivered_events"], 2); } + +#[test] +fn a_failed_surface_read_is_reported_and_not_shown_as_no_overlay() { + let result = ActionResult::delivered_unverified("click").with_surfaces_read(Err( + crate::AdapterError::new(crate::ErrorCode::Timeout, "surface read timed out"), + )); + + assert!(result.surfaces.is_empty()); + assert_eq!( + result.details, + Some(serde_json::json!({ "surfaces": "not_read" })) + ); +} diff --git a/crates/core/src/actions/headed_focus.rs b/crates/core/src/actions/headed_focus.rs index 985ff9c1fd..b4414f99d8 100644 --- a/crates/core/src/actions/headed_focus.rs +++ b/crates/core/src/actions/headed_focus.rs @@ -26,8 +26,9 @@ impl HeadedFocus { } /// 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. +/// captured through a process owner, or from a surface the platform presents +/// beside its windows rather than as one of them, has no census 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, @@ -41,7 +42,9 @@ pub(crate) fn focus_entry_window( ) .with_details(json!({ "physical_delivery_started": false })) })?; - if entry.source.is_process_owned() { + if entry.source.is_process_owned() + || adapter.is_application_surface(entry.source.source_surface) + { return Ok(false); } let expected = adapter.resolve_ref_focus_window(entry, lease.deadline())?; diff --git a/crates/core/src/adapter/observation.rs b/crates/core/src/adapter/observation.rs index f38e2f359d..3ada2bcd3d 100644 --- a/crates/core/src/adapter/observation.rs +++ b/crates/core/src/adapter/observation.rs @@ -32,10 +32,40 @@ pub trait ObservationOps: Send + Sync { false } + /// The window a surface is presented by, when the platform shows it in a + /// window of its own that the window inventory leaves out. A capture that + /// returns one records that window on every ref it allocates, so a later + /// resolve or observation lands on the window that was read rather than on + /// another one of the same kind. `None` keeps the surface + /// application-owned, which is the answer for a surface with no window. + fn surface_window( + &self, + _app: &AppInfo, + _surface: SnapshotSurface, + _deadline: Deadline, + ) -> Result, AdapterError> { + Ok(None) + } + fn focused_app(&self, _deadline: Deadline) -> Result, AdapterError> { Err(AdapterError::not_supported("focused_app")) } + /// The window a caller named for a surface the platform presents in a + /// window of its own: the id a stored ref recorded, or the `--window-id` + /// of a capture. The id must still name an open surface window of that + /// exact process instance, or this refuses; `None` keeps the window + /// inventory lookup, which is the answer for a surface with no window. + fn recorded_surface_window( + &self, + _process: crate::ProcessIdentity, + _window_id: &str, + _surface: SnapshotSurface, + _deadline: Deadline, + ) -> Result, AdapterError> { + Ok(None) + } + /// Reports protocol targets that have no screen position without requiring a native read. fn is_nonspatial_target(&self, _handle: &NativeHandle) -> bool { false diff --git a/crates/core/src/commands/application_surface_tests.rs b/crates/core/src/commands/application_surface_tests.rs index bed12e2038..5016fffa0a 100644 --- a/crates/core/src/commands/application_surface_tests.rs +++ b/crates/core/src/commands/application_surface_tests.rs @@ -6,23 +6,57 @@ use crate::{ refs::refs_test_support::HomeGuard, }; -struct MenuAdapter { - apps: Vec, - windows: Vec, +pub(super) struct MenuAdapter { + pub(super) apps: Vec, + pub(super) windows: Vec, + pub(super) surface_window: Option, } impl MenuAdapter { - fn windowless() -> Self { + pub(super) fn windowless() -> Self { Self { apps: vec![app(42)], windows: vec![], + surface_window: None, } } } impl ObservationOps for MenuAdapter { fn is_application_surface(&self, surface: SnapshotSurface) -> bool { - matches!(surface, SnapshotSurface::Menubar | SnapshotSurface::Menu) + matches!( + surface, + SnapshotSurface::Menubar | SnapshotSurface::Menu | SnapshotSurface::Popover + ) + } + + fn surface_window( + &self, + _app: &AppInfo, + surface: SnapshotSurface, + _deadline: Deadline, + ) -> Result, crate::AdapterError> { + if surface != SnapshotSurface::Popover { + return Ok(None); + } + Ok(self.surface_window.clone()) + } + + fn recorded_surface_window( + &self, + process: crate::ProcessIdentity, + window_id: &str, + surface: SnapshotSurface, + _deadline: Deadline, + ) -> Result, crate::AdapterError> { + if surface != SnapshotSurface::Popover { + return Ok(None); + } + Ok(self.surface_window.clone().filter(|window| { + window.id == window_id + && window.pid == process.pid + && window.process_instance.as_deref() == Some(process.instance.as_str()) + })) } fn focused_app(&self, _deadline: Deadline) -> Result, crate::AdapterError> { diff --git a/crates/core/src/commands/application_surface_window_tests.rs b/crates/core/src/commands/application_surface_window_tests.rs new file mode 100644 index 0000000000..53ced14595 --- /dev/null +++ b/crates/core/src/commands/application_surface_window_tests.rs @@ -0,0 +1,254 @@ +use super::application_surface_tests::MenuAdapter; +use crate::{Deadline, RefEntry, SnapshotOwner, SnapshotSurface, WindowInfo}; +fn popover_owner_surface_window() -> WindowInfo { + WindowInfo { + id: "w-77".into(), + title: "Filters".into(), + app: "MenuApp".into(), + pid: crate::ProcessId::new(42), + process_instance: Some("instance-42".into()), + bounds: None, + state: Default::default(), + } +} + +fn popover_owners(adapter: &MenuAdapter) -> Vec { + crate::snapshot::surface_target::resolve_owners( + adapter, + Some("MenuApp"), + None, + SnapshotSurface::Popover, + Deadline::standard().unwrap(), + ) + .unwrap() +} + +#[test] +fn a_surface_the_adapter_presents_in_its_own_window_is_owned_by_that_window() { + let mut adapter = MenuAdapter::windowless(); + adapter.surface_window = Some(popover_owner_surface_window()); + + let owners = popover_owners(&adapter); + + assert!( + matches!(&owners[..], [SnapshotOwner::Window(window)] if window.id == "w-77"), + "a surface presented by a window is captured at that window: {owners:?}" + ); +} + +#[test] +fn a_surface_with_no_window_of_its_own_stays_application_owned() { + let owners = popover_owners(&MenuAdapter::windowless()); + + assert!( + matches!(&owners[..], [SnapshotOwner::Application(_)]), + "a surface with no window stays application-owned: {owners:?}" + ); +} + +fn popover_entry(window_id: &str) -> RefEntry { + let mut entry = crate::adapter::minimal_ref_entry("button", None); + entry.process.pid = crate::ProcessId::new(42); + entry.process.process_instance = Some("instance-42".into()); + entry.source.source_app = Some("MenuApp".into()); + entry.source.source_surface = SnapshotSurface::Popover; + entry.source.source_window_id = Some(window_id.into()); + entry.source.source_window_title = Some("Filters".into()); + entry +} + +#[test] +fn a_recorded_popover_reference_resolves_to_the_popover_window_it_named() { + let mut adapter = MenuAdapter::windowless(); + adapter.surface_window = Some(popover_owner_surface_window()); + + let window = crate::refs::resolve_saved_ref::recorded_window( + &adapter, + &popover_entry("w-77"), + Deadline::standard().unwrap(), + ) + .unwrap(); + + assert_eq!(window.id, "w-77"); + assert_eq!(window.pid, crate::ProcessId::new(42)); + assert_eq!(window.process_instance.as_deref(), Some("instance-42")); +} + +#[test] +fn a_recorded_popover_reference_to_a_closed_popover_is_stale() { + let mut adapter = MenuAdapter::windowless(); + adapter.surface_window = Some(popover_owner_surface_window()); + + let error = crate::refs::resolve_saved_ref::recorded_window( + &adapter, + &popover_entry("w-99"), + Deadline::standard().unwrap(), + ) + .unwrap_err(); + + assert_eq!(error.code.as_str(), "STALE_REF"); +} + +#[test] +fn naming_the_surface_window_reads_it_even_though_it_is_not_a_listed_window() { + let mut adapter = MenuAdapter::windowless(); + adapter.surface_window = Some(popover_owner_surface_window()); + + let owners = crate::snapshot::surface_target::resolve_owners( + &adapter, + Some("MenuApp"), + Some("w-77"), + SnapshotSurface::Popover, + Deadline::standard().unwrap(), + ) + .unwrap(); + + assert!( + matches!(&owners[..], [SnapshotOwner::Window(window)] if window.id == "w-77"), + "the named surface window is captured at that window: {owners:?}" + ); +} + +/// An adapter whose popover surface behaves the way Windows does: the surface is +/// application-owned, two popovers are open, and an observation that starts at +/// the application root names neither, so it is refused as ambiguous. Only the +/// id a ref recorded can pick one popover out of the two. +#[derive(Default)] +struct TwoPopoverAdapter { + observed: std::sync::Mutex>, +} + +impl TwoPopoverAdapter { + fn popover(id: &str) -> WindowInfo { + WindowInfo { + id: id.into(), + ..popover_owner_surface_window() + } + } + + fn observed_roots(&self) -> Vec<(String, SnapshotSurface)> { + self.observed.lock().unwrap().clone() + } +} + +impl crate::adapter::ObservationOps for TwoPopoverAdapter { + fn is_application_surface(&self, surface: SnapshotSurface) -> bool { + surface == SnapshotSurface::Popover + } + + fn recorded_surface_window( + &self, + process: crate::ProcessIdentity, + window_id: &str, + surface: SnapshotSurface, + _deadline: Deadline, + ) -> Result, crate::AdapterError> { + let open = ["w-1", "w-2"]; + Ok(open + .contains(&window_id) + .then(|| Self::popover(window_id)) + .filter(|window| { + surface == SnapshotSurface::Popover + && window.pid == process.pid + && window.process_instance.as_deref() == Some(process.instance.as_str()) + })) + } + + fn list_windows( + &self, + _filter: &crate::adapter::WindowFilter, + _deadline: Deadline, + ) -> Result, crate::AdapterError> { + Ok(Vec::new()) + } + + fn observe_tree( + &self, + root: crate::ObservationRoot<'_>, + request: &crate::ObservationRequest, + ) -> Result { + match root { + crate::ObservationRoot::Application { .. } + if request.surface == SnapshotSurface::Popover => + { + Err(crate::AdapterError::new( + crate::ErrorCode::AmbiguousTarget, + "More than one popover is open in this application: w-1, w-2", + )) + } + crate::ObservationRoot::Window(window) => { + self.observed + .lock() + .unwrap() + .push((window.id.clone(), request.surface)); + crate::adapter::observed_tree(&root, popover_node()) + } + crate::ObservationRoot::Application { .. } | crate::ObservationRoot::Element { .. } => { + crate::adapter::observed_tree(&root, popover_node()) + } + } + } + + fn resolve_locator_anchor( + &self, + _entry: &RefEntry, + _base: Option<&crate::NativeHandle>, + _deadline: Deadline, + ) -> Result { + Ok(crate::NativeHandle::new("popover-anchor")) + } +} + +impl crate::adapter::ActionOps for TwoPopoverAdapter {} +impl crate::adapter::InputOps for TwoPopoverAdapter {} +impl crate::adapter::SystemOps for TwoPopoverAdapter {} + +fn popover_node() -> crate::AccessibilityNode { + crate::adapter::minimal_accessibility_node("button", "Run") +} + +#[test] +fn a_saved_popover_ref_is_observed_at_the_window_it_recorded() { + let adapter = TwoPopoverAdapter::default(); + let entry = popover_entry("w-1"); + + let (window, _, _) = crate::refs::resolve_saved_ref::observe_saved_ref( + &adapter, + &entry, + Deadline::standard().unwrap(), + None, + true, + ) + .expect("the recorded popover answers for its own ref while another popover is open"); + + assert_eq!(window.id, "w-1"); + assert_eq!( + adapter.observed_roots(), + vec![("w-1".to_string(), SnapshotSurface::Popover)], + "the observation names the popover the ref recorded" + ); +} + +#[test] +fn a_saved_popover_ref_resolves_while_a_second_popover_is_open() { + let adapter = TwoPopoverAdapter::default(); + let entry = popover_entry("w-2"); + + let handle = crate::refs::resolve_saved_ref::resolve_saved_ref( + &adapter, + &entry, + Deadline::standard().unwrap(), + None, + ) + .expect("a saved ref naming its popover is never ambiguous"); + + assert_eq!( + handle.downcast_ref::<&'static str>().copied(), + Some("popover-anchor") + ); + assert_eq!( + adapter.observed_roots().first().cloned(), + Some(("w-2".to_string(), SnapshotSurface::Popover)), + "resolution reads the popover the ref recorded" + ); +} diff --git a/crates/core/src/commands/mod.rs b/crates/core/src/commands/mod.rs index 5340c6ee9e..f2b96e3b78 100644 --- a/crates/core/src/commands/mod.rs +++ b/crates/core/src/commands/mod.rs @@ -113,5 +113,8 @@ mod operation_passthrough_tests; #[cfg(test)] mod application_surface_tests; +#[cfg(test)] +mod application_surface_window_tests; + #[cfg(test)] mod tests; diff --git a/crates/core/src/commands/post_action_observation_lifecycle_tests.rs b/crates/core/src/commands/post_action_observation_lifecycle_tests.rs index e539605453..3aa11f74bd 100644 --- a/crates/core/src/commands/post_action_observation_lifecycle_tests.rs +++ b/crates/core/src/commands/post_action_observation_lifecycle_tests.rs @@ -145,6 +145,54 @@ fn process_owned_wait_uses_process_window_and_refuses_unmarked_missing_window() } } +struct RecordedPopoverAdapter; + +impl ObservationOps for RecordedPopoverAdapter { + fn is_application_surface(&self, surface: crate::SnapshotSurface) -> bool { + surface == crate::SnapshotSurface::Popover + } +} + +impl ActionOps for RecordedPopoverAdapter {} +impl InputOps for RecordedPopoverAdapter {} +impl SystemOps for RecordedPopoverAdapter { + fn process_state( + &self, + _process: ProcessIdentity, + _deadline: Deadline, + ) -> Result { + Ok(ProcessState::Running) + } +} + +#[test] +fn a_surface_ref_that_recorded_its_window_observes_that_window() { + use crate::snapshot::{ + ref_owner_observation::RefOwnerObservation, surface_target::ref_observation_surface, + surface_target::resolve_ref_owner, + }; + let adapter = RecordedPopoverAdapter; + let mut entry = menu_entry(); + entry.source.source_surface = crate::SnapshotSurface::Popover; + entry.source.source_window_id = Some("w-99".into()); + entry.source.source_window_title = Some("Filters".into()); + + let owner = match resolve_ref_owner(&adapter, &entry, Deadline::after(250).unwrap()) { + Ok(RefOwnerObservation::Present(owner)) => owner, + Ok(_) => panic!("a running process is present"), + Err(error) => panic!("a running process resolves its owner: {error}"), + }; + let crate::SnapshotOwner::Window(window) = owner else { + panic!("a surface that recorded its window is observed at that window"); + }; + assert_eq!(window.id, "w-99"); + assert_eq!(window.title, "Filters"); + assert_eq!( + ref_observation_surface(&adapter, &entry), + crate::SnapshotSurface::Popover + ); +} + struct StrictReadAdapter { deadline: Deadline, code: ErrorCode, diff --git a/crates/core/src/commands/tests/waits/stub.rs b/crates/core/src/commands/tests/waits/stub.rs index 0fcc0e92d8..a537fab7b0 100644 --- a/crates/core/src/commands/tests/waits/stub.rs +++ b/crates/core/src/commands/tests/waits/stub.rs @@ -61,6 +61,8 @@ pub(super) fn signals(windows: Vec, apps: Vec) -> SignalBas #[derive(Default)] pub(super) struct Stub { pub(super) windows: Mutex, AdapterError>>>, + pub(super) surfaces: Mutex, AdapterError>>>, + pub(super) supported_surfaces: Vec, pub(super) tree: Option, pub(super) notifications: Mutex, AdapterError>>>, pub(super) menu_times_out: bool, @@ -68,6 +70,14 @@ pub(super) struct Stub { } impl ObservationOps for Stub { + fn list_surfaces( + &self, + _: ProcessIdentity, + _: Deadline, + ) -> Result, AdapterError> { + next(&self.surfaces).unwrap_or_else(|| Ok(Vec::new())) + } + fn observe_tree( &self, root: crate::locator::live_locator::ObservationRoot<'_>, @@ -94,6 +104,10 @@ impl ActionOps for Stub {} impl InputOps for Stub {} impl SystemOps for Stub { + fn supported_surfaces(&self) -> Vec { + self.supported_surfaces.clone() + } + fn wait_for_menu( &self, _: ProcessIdentity, diff --git a/crates/core/src/commands/tests/waits/success.rs b/crates/core/src/commands/tests/waits/success.rs index a0a135a019..0a1dc7ab74 100644 --- a/crates/core/src/commands/tests/waits/success.rs +++ b/crates/core/src/commands/tests/waits/success.rs @@ -1,9 +1,11 @@ -use super::stub::{Stub, app, args, build, golden, mode, run, script, selector, signals, stable}; +use super::stub::{ + Stub, app, args, build, golden, mode, payload, run, script, selector, signals, stable, +}; use super::stub::{window, with_buttons}; use crate::commands::wait::execute; use crate::commands::wait_surface::SurfaceWait; use crate::refs::refs_test_support::HomeGuard; -use crate::{CommandContext, NotificationInfo, SignalBaseline}; +use crate::{CommandContext, NotificationInfo, SignalBaseline, SurfaceInfo}; use serde_json::{Value, json}; #[test] @@ -107,3 +109,111 @@ fn event_wait_reports_the_window_and_app_events() { include_str!("../../../../../../tests/fixtures/contract/waits-event.json") ); } + +#[test] +fn a_surface_wait_polls_through_a_retryable_read_failure() { + let stub = Stub { + supported_surfaces: vec![crate::SnapshotSurface::Menu], + surfaces: script(vec![ + Err( + crate::AdapterError::new(crate::ErrorCode::AppUnresponsive, "busy") + .with_disposition(crate::DeliverySemantics::not_delivered()), + ), + Ok(vec![SurfaceInfo { + id: "menu-1".into(), + kind: "menu".into(), + title: None, + item_count: None, + unclassified: Vec::new(), + }]), + ]), + ..Default::default() + }; + + let data = run( + &stub, + mode!( + surface, + SurfaceWait::Open(Some(crate::SnapshotSurface::Menu)) + ), + Some("TextEdit"), + 2_000, + ) + .unwrap(); + + assert_eq!(data["found"], json!(true)); +} + +#[test] +fn a_surface_wait_that_never_read_the_surfaces_reports_the_error_and_no_observation() { + let retryable = || { + Err( + crate::AdapterError::new(crate::ErrorCode::AppUnresponsive, "busy") + .with_disposition(crate::DeliverySemantics::not_delivered()), + ) + }; + let stub = Stub { + supported_surfaces: vec![crate::SnapshotSurface::Menu], + surfaces: script(vec![retryable(); 6]), + ..Default::default() + }; + + let error = payload(run( + &stub, + mode!( + surface, + SurfaceWait::Open(Some(crate::SnapshotSurface::Menu)) + ), + Some("TextEdit"), + 250, + )); + + assert_eq!(error["code"], json!("TIMEOUT")); + assert_eq!( + error["details"]["last_error"]["code"], + json!("APP_UNRESPONSIVE") + ); + assert!(error["details"].get("last_observed").is_none()); +} + +#[test] +fn a_surface_wait_that_saw_no_such_surface_does_not_call_the_app_busy() { + let stub = Stub { + supported_surfaces: vec![crate::SnapshotSurface::Menu], + ..Default::default() + }; + + let error = payload(run( + &stub, + mode!( + surface, + SurfaceWait::Open(Some(crate::SnapshotSurface::Menu)) + ), + Some("TextEdit"), + 250, + )); + + assert_eq!(error["code"], json!("TIMEOUT")); + assert_eq!(error["details"]["last_observed"], json!([])); + let suggestion = error["suggestion"].as_str().unwrap_or_default(); + assert!(!suggestion.contains("busy"), "{suggestion}"); + assert!(suggestion.contains("last_observed"), "{suggestion}"); +} + +#[test] +fn a_surface_wait_for_a_kind_the_platform_cannot_show_is_refused_at_once() { + let started = std::time::Instant::now(); + let error = run( + &Stub::default(), + mode!( + surface, + SurfaceWait::Open(Some(crate::SnapshotSurface::Popover)) + ), + Some("TextEdit"), + 5_000, + ) + .unwrap_err(); + + assert_eq!(error.code(), "PLATFORM_NOT_SUPPORTED"); + assert!(started.elapsed() < std::time::Duration::from_secs(1)); +} diff --git a/crates/core/src/commands/wait.rs b/crates/core/src/commands/wait.rs index 311aa04f31..7f38d427b5 100644 --- a/crates/core/src/commands/wait.rs +++ b/crates/core/src/commands/wait.rs @@ -6,7 +6,7 @@ use crate::{ wait_element::{ElementWaitInput, wait_for_element}, wait_mode::WaitMode, wait_notification, - wait_surface::SurfaceWait, + wait_surface::{self, SurfaceWait}, wait_text_match, wait_timeout, }, context::CommandContext, @@ -64,6 +64,7 @@ pub fn execute( Ok(json!({ "waited_ms": ms })) } WaitMode::Menu { app, open } => wait_for_menu(app, open, timeout_ms, adapter), + WaitMode::Surface { app, kind } => wait_for_surface(app, kind, timeout_ms, adapter), WaitMode::Notification { app, text } => { wait_notification::wait_for_notification(app, text, timeout_ms, adapter, context) } @@ -133,6 +134,55 @@ fn wait_for_menu( Ok(json!({ "found": true, "elapsed_ms": elapsed })) } +/// Polls the application's surface list until one of the asked kind is open. +/// A kind the platform cannot show is refused before the wait starts. +fn wait_for_surface( + app: Option, + kind: Option, + timeout_ms: u64, + adapter: &dyn PlatformAdapter, +) -> Result { + if let Some(kind) = kind { + adapter.check_surface_support(kind)?; + } + let start = Instant::now(); + let deadline = crate::Deadline::at(start, timeout_ms)?; + let target = resolve_app(app.as_deref(), adapter, deadline)?; + let process = crate::commands::helpers::process_identity(&target)?; + let open = |surfaces: &[crate::SurfaceInfo]| { + surfaces + .iter() + .find(|surface| wait_surface::is_kind(surface, kind)) + .cloned() + }; + let mut last_observed = None; + let mut last_error = None; + loop { + match adapter.list_surfaces(process.clone(), deadline) { + Ok(surfaces) => { + if let Some(surface) = open(&surfaces) { + return Ok(json!({ + "found": true, + "surface": surface, + "elapsed_ms": start.elapsed().as_millis(), + })); + } + last_observed = Some(surfaces); + } + Err(error) if wait_timeout::is_deadline_expired(&error) => break, + Err(error) if error.is_retryable_poll_failure() => { + last_error = Some(json!({ "code": error.code.as_str(), "message": error.message })); + } + Err(error) => return Err(error.into()), + } + if deadline.is_expired() { + break; + } + deadline.pause(Duration::from_millis(100)); + } + wait_timeout::surface(kind, timeout_ms, last_observed.as_deref(), last_error) +} + fn wait_for_window( title: String, app: Option, @@ -312,6 +362,9 @@ mod scenario_menu_tests; #[cfg(test)] #[path = "wait_scenario_tests.rs"] mod scenario_tests; +#[cfg(test)] +#[path = "wait_surface_scenario_tests.rs"] +mod surface_scenario_tests; #[cfg(test)] #[path = "wait_element_tests.rs"] diff --git a/crates/core/src/commands/wait_mode.rs b/crates/core/src/commands/wait_mode.rs index e0b6c9d9ce..032907d6f2 100644 --- a/crates/core/src/commands/wait_mode.rs +++ b/crates/core/src/commands/wait_mode.rs @@ -27,6 +27,10 @@ pub(crate) enum WaitMode { app: Option, text: Option, }, + Surface { + app: Option, + kind: Option, + }, Event { event: String, app: Option, @@ -54,6 +58,12 @@ impl WaitMode { open: false, }); } + Some(SurfaceWait::Open(kind)) => { + return Ok(Self::Surface { + app: args.app, + kind, + }); + } Some(SurfaceWait::Notification) => { return Ok(Self::Notification { app: args.app, diff --git a/crates/core/src/commands/wait_surface.rs b/crates/core/src/commands/wait_surface.rs index 3d5032e655..02d5813792 100644 --- a/crates/core/src/commands/wait_surface.rs +++ b/crates/core/src/commands/wait_surface.rs @@ -1,13 +1,16 @@ -use crate::AppError; +use crate::{AppError, SnapshotSurface, SurfaceInfo}; -/// Which surface-lifecycle condition a `wait` targets: `--menu`, -/// `--menu-closed`, or `--notification`. One variant per flag makes the three +/// Which surface condition a `wait` targets: `--menu`, `--menu-closed`, +/// `--notification`, or `--surface `. One variant per flag makes the /// modes structurally mutually exclusive. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum SurfaceWait { Menu, MenuClosed, Notification, + /// A surface of this kind is open; `None` is any kind. Unlike an event + /// wait it is a state, so a surface that opened before the wait counts. + Open(Option), } impl SurfaceWait { @@ -15,17 +18,80 @@ impl SurfaceWait { menu: bool, menu_closed: bool, notification: bool, + open: Option<&str>, ) -> Result, AppError> { - match (menu, menu_closed, notification) { - (false, false, false) => Ok(None), - (true, false, false) => Ok(Some(Self::Menu)), - (false, true, false) => Ok(Some(Self::MenuClosed)), - (false, false, true) => Ok(Some(Self::Notification)), - _ => Err(crate::commands::wait_mode::ambiguous_wait_mode()), + let open = open.map(open_kind).transpose()?.map(Self::Open); + let mut chosen = [ + menu.then_some(Self::Menu), + menu_closed.then_some(Self::MenuClosed), + notification.then_some(Self::Notification), + open, + ] + .into_iter() + .flatten(); + match (chosen.next(), chosen.next()) { + (wait, None) => Ok(wait), + (Some(_), Some(_)) | (None, Some(_)) => { + Err(crate::commands::wait_mode::ambiguous_wait_mode()) + } } } } +fn open_kind(kind: &str) -> Result, AppError> { + match kind { + "any" => Ok(None), + "popover" => Ok(Some(SnapshotSurface::Popover)), + "sheet" => Ok(Some(SnapshotSurface::Sheet)), + "alert" => Ok(Some(SnapshotSurface::Alert)), + "menu" => Ok(Some(SnapshotSurface::Menu)), + _ => Err(AppError::invalid_input_with_suggestion( + format!("Unknown surface kind '{kind}' for wait --surface"), + "Use popover, sheet, alert, menu or any.", + )), + } +} + +/// The kinds `wait --surface` names; `any` is any one of them, never a plain +/// window, which Linux and Windows list for every window. +const OPEN_KINDS: [SnapshotSurface; 4] = [ + SnapshotSurface::Popover, + SnapshotSurface::Sheet, + SnapshotSurface::Alert, + SnapshotSurface::Menu, +]; + +/// Whether a listed surface is of the kind a wait asks for. A context menu is +/// a menu. +pub(crate) fn is_kind(surface: &SurfaceInfo, kind: Option) -> bool { + kind_matches(&surface.kind, kind) +} + +/// Whether an inventory entry that names `listed` satisfies the wait. Shared by +/// the listed surfaces and the kinds an entry reports as unclassified, so a +/// surface that was not read is judged by the same rule as one that was. +fn kind_matches(listed: &str, kind: Option) -> bool { + match kind { + None => OPEN_KINDS + .into_iter() + .any(|kind| kind_matches(listed, Some(kind))), + Some(SnapshotSurface::Menu) => matches!(listed, "menu" | "context_menu"), + Some(kind) => listed == kind.as_str(), + } +} + +/// Whether the last observation reports the kind a wait asks for as +/// unclassified: the inventory did not read it, so no matching surface has not +/// shown that the application presented none. +pub(crate) fn unread(surfaces: &[SurfaceInfo], kind: Option) -> bool { + surfaces.iter().any(|surface| { + surface + .unclassified + .iter() + .any(|listed| kind_matches(listed, kind)) + }) +} + #[cfg(test)] #[path = "wait_surface_tests.rs"] mod tests; diff --git a/crates/core/src/commands/wait_surface_scenario_tests.rs b/crates/core/src/commands/wait_surface_scenario_tests.rs new file mode 100644 index 0000000000..391bb91192 --- /dev/null +++ b/crates/core/src/commands/wait_surface_scenario_tests.rs @@ -0,0 +1,174 @@ +use super::*; +use crate::AdapterError; +use crate::adapter::{ActionOps, InputOps, ObservationOps, SystemOps}; + +struct SurfaceInventoryAdapter { + surfaces: Vec, +} + +impl ObservationOps for SurfaceInventoryAdapter { + fn query_app_inventory( + &self, + query: crate::AppInventoryQuery<'_>, + _deadline: crate::Deadline, + ) -> Result { + Ok(query.answer(vec![crate::AppInfo { + aliases: Vec::new(), + name: "SurfaceApp".into(), + pid: crate::ProcessId::new(42), + bundle_id: None, + process_instance: Some("test-instance".into()), + presentation: None, + }])) + } + + fn list_surfaces( + &self, + _process: crate::ProcessIdentity, + _deadline: crate::Deadline, + ) -> Result, AdapterError> { + Ok(self.surfaces.clone()) + } +} + +impl ActionOps for SurfaceInventoryAdapter {} + +impl InputOps for SurfaceInventoryAdapter {} + +impl SystemOps for SurfaceInventoryAdapter { + fn supported_surfaces(&self) -> Vec { + vec![ + crate::SnapshotSurface::Popover, + crate::SnapshotSurface::Sheet, + crate::SnapshotSurface::Alert, + crate::SnapshotSurface::Menu, + ] + } +} + +fn unread_window(kind: &str) -> crate::SurfaceInfo { + crate::SurfaceInfo { + id: "w-7".into(), + kind: "window".into(), + title: Some("Document".into()), + item_count: None, + unclassified: vec![kind.into()], + } +} + +fn read_window() -> crate::SurfaceInfo { + crate::SurfaceInfo { + id: "w-7".into(), + kind: "window".into(), + title: Some("Document".into()), + item_count: None, + unclassified: Vec::new(), + } +} + +fn wait_for(kind: &str, surfaces: Vec) -> AppError { + use super::test_support::wait_args; + let adapter = SurfaceInventoryAdapter { surfaces }; + execute( + WaitArgs { + mode: WaitModeArgs { + surface: Some( + SurfaceWait::from_flags(false, false, false, Some(kind)) + .unwrap() + .expect("one surface wait"), + ), + ..wait_args().mode + }, + app: Some("SurfaceApp".into()), + timeout_ms: 30, + ..wait_args() + }, + &adapter, + &CommandContext::default(), + ) + .unwrap_err() +} + +fn details(error: &AppError) -> Value { + let AppError::Adapter(error) = error else { + panic!("a surface timeout is an adapter timeout, got {error:?}"); + }; + assert_eq!(error.code, ErrorCode::Timeout); + error.details.clone().expect("timeout details") +} + +#[test] +fn a_surface_kind_the_inventory_could_not_read_is_not_reported_as_absent() { + for kind in ["popover", "sheet", "menu"] { + let error = wait_for(kind, vec![unread_window(kind)]); + let message = error.to_string(); + assert!(message.contains("could not be read"), "{kind}: {message}"); + assert!( + !message.contains("No "), + "{kind} claims absence for a surface that was never read: {message}" + ); + let suggestion = error.suggestion().unwrap_or_default(); + assert!( + suggestion.contains("may still present it"), + "{kind}: {suggestion}" + ); + assert!( + !suggestion.contains("showed no such surface"), + "{kind}: {suggestion}" + ); + let details = details(&error); + assert_eq!(details["unread"], true, "{kind}: {details}"); + assert_eq!(details["predicate"], "surface"); + assert_eq!(details["surface"], kind); + assert_eq!(details["last_observed"][0]["id"], "w-7"); + } +} + +#[test] +fn any_surface_is_unread_when_a_listed_surface_reports_any_open_kind() { + let error = wait_for("any", vec![unread_window("menu")]); + assert_eq!(details(&error)["unread"], true); +} + +#[test] +fn a_read_inventory_without_the_surface_still_reports_a_plain_timeout() { + let error = wait_for("popover", vec![read_window()]); + assert!( + error.to_string().contains("No popover surface was open"), + "{error}" + ); + let details = details(&error); + assert!(details.get("unread").is_none(), "{details}"); + assert_eq!(details["last_observed"][0]["id"], "w-7"); +} + +#[test] +fn a_matching_surface_returns_before_any_timeout() { + use super::test_support::wait_args; + let adapter = SurfaceInventoryAdapter { + surfaces: vec![crate::SurfaceInfo { + id: "w-7".into(), + kind: "popover".into(), + title: Some("Filters".into()), + item_count: None, + unclassified: Vec::new(), + }], + }; + let value = execute( + WaitArgs { + mode: WaitModeArgs { + surface: Some(SurfaceWait::Open(Some(crate::SnapshotSurface::Popover))), + ..wait_args().mode + }, + app: Some("SurfaceApp".into()), + timeout_ms: 30, + ..wait_args() + }, + &adapter, + &CommandContext::default(), + ) + .unwrap(); + + assert_eq!(value["found"], true); + assert_eq!(value["surface"]["id"], "w-7"); +} diff --git a/crates/core/src/commands/wait_surface_tests.rs b/crates/core/src/commands/wait_surface_tests.rs index 1b639d55fe..44849bec2e 100644 --- a/crates/core/src/commands/wait_surface_tests.rs +++ b/crates/core/src/commands/wait_surface_tests.rs @@ -1,22 +1,26 @@ -use super::SurfaceWait; +use super::{SurfaceWait, is_kind}; +use crate::{SnapshotSurface, SurfaceInfo}; #[test] fn no_flags_selects_no_surface_wait() { - assert_eq!(SurfaceWait::from_flags(false, false, false).unwrap(), None); + assert_eq!( + SurfaceWait::from_flags(false, false, false, None).unwrap(), + None + ); } #[test] fn each_flag_maps_to_its_variant() { assert_eq!( - SurfaceWait::from_flags(true, false, false).unwrap(), + SurfaceWait::from_flags(true, false, false, None).unwrap(), Some(SurfaceWait::Menu) ); assert_eq!( - SurfaceWait::from_flags(false, true, false).unwrap(), + SurfaceWait::from_flags(false, true, false, None).unwrap(), Some(SurfaceWait::MenuClosed) ); assert_eq!( - SurfaceWait::from_flags(false, false, true).unwrap(), + SurfaceWait::from_flags(false, false, true, None).unwrap(), Some(SurfaceWait::Notification) ); } @@ -29,10 +33,49 @@ fn conflicting_flags_report_exactly_one_mode_error() { (false, true, true), (true, true, true), ] { - let err = SurfaceWait::from_flags(menu, menu_closed, notification).unwrap_err(); + let err = SurfaceWait::from_flags(menu, menu_closed, notification, None).unwrap_err(); assert_eq!(err.code(), "INVALID_ARGS"); assert_eq!(err.to_string(), "wait accepts exactly one mode"); assert!(err.suggestion().is_some()); } } + +#[test] +fn a_surface_kind_selects_an_open_surface_wait_and_conflicts_with_a_flag() { + assert_eq!( + SurfaceWait::from_flags(false, false, false, Some("popover")).unwrap(), + Some(SurfaceWait::Open(Some(SnapshotSurface::Popover))) + ); + assert_eq!( + SurfaceWait::from_flags(false, false, false, Some("any")).unwrap(), + Some(SurfaceWait::Open(None)) + ); + let conflict = SurfaceWait::from_flags(true, false, false, Some("sheet")).unwrap_err(); + assert_eq!(conflict.code(), "INVALID_ARGS"); + let unknown = SurfaceWait::from_flags(false, false, false, Some("window")).unwrap_err(); + assert_eq!(unknown.code(), "INVALID_ARGS"); +} + +#[test] +fn a_listed_surface_matches_its_kind_and_a_context_menu_is_a_menu() { + let listed = |kind: &str| SurfaceInfo { + id: "windows/0".into(), + kind: kind.into(), + title: None, + item_count: None, + unclassified: Vec::new(), + }; + assert!(is_kind(&listed("popover"), Some(SnapshotSurface::Popover))); + assert!(!is_kind(&listed("sheet"), Some(SnapshotSurface::Popover))); + assert!(is_kind( + &listed("context_menu"), + Some(SnapshotSurface::Menu) + )); + assert!(is_kind(&listed("alert"), None)); + assert!(is_kind(&listed("context_menu"), None)); + assert!( + !is_kind(&listed("window"), None), + "any must not match a plain window, which Linux and Windows list for every window" + ); +} diff --git a/crates/core/src/commands/wait_timeout.rs b/crates/core/src/commands/wait_timeout.rs index 50be288f88..8980b0dcd3 100644 --- a/crates/core/src/commands/wait_timeout.rs +++ b/crates/core/src/commands/wait_timeout.rs @@ -28,6 +28,46 @@ pub(crate) fn menu(mut error: AdapterError, timeout_ms: u64) -> AppError { AppError::Adapter(error) } +pub(crate) fn surface( + kind: Option, + timeout_ms: u64, + observed: Option<&[crate::SurfaceInfo]>, + last_error: Option, +) -> Result { + let name = kind.map_or("any", |kind| kind.as_str()); + let what = if name == "any" { + "surface".to_owned() + } else { + format!("{name} surface") + }; + let mut details = json!({ "predicate": "surface", "surface": name, "timeout_ms": timeout_ms }); + let Some(observed) = observed else { + let message = format!("The surfaces could not be read within {timeout_ms}ms"); + return timeout_err(message, with_last_error(details, last_error)); + }; + details["last_observed"] = json!(observed); + if crate::commands::wait_surface::unread(observed, kind) { + details["unread"] = json!(true); + return timeout_err( + format!("The {what} could not be read within {timeout_ms}ms"), + with_last_error(details, last_error), + ) + .map_err(|error| match error { + AppError::Adapter(error) => AppError::Adapter(error.with_suggestion( + "The inventory reports this kind as unread, so the application may still present it: details.last_observed names the window whose read was cut. list-surfaces shows what was read; raise --timeout only if the surface opens later.", + )), + other => other, + }); + } + let message = format!("No {what} was open within {timeout_ms}ms"); + timeout_err(message, with_last_error(details, last_error)).map_err(|error| match error { + AppError::Adapter(error) => AppError::Adapter(error.with_suggestion( + "The application answered and showed no such surface: details.last_observed lists what was open. Raise --timeout only if the surface opens later.", + )), + other => other, + }) +} + /// Builds the wait-loop TIMEOUT error. Every payload carries /// `kind: "wait_timeout"` so agents can discriminate it from the chain /// deadline TIMEOUT schema (`kind: "chain_deadline"`) without sniffing diff --git a/crates/core/src/locator/live_locator/observed_tree.rs b/crates/core/src/locator/live_locator/observed_tree.rs index 738a1d2e81..78301a86ed 100644 --- a/crates/core/src/locator/live_locator/observed_tree.rs +++ b/crates/core/src/locator/live_locator/observed_tree.rs @@ -43,6 +43,16 @@ impl ObservedTree { Ok(tree) } + /// The surface this observation read, which a ref anchored from it records + /// so a later resolution reads the same surface. + pub fn surface(&self) -> crate::SnapshotSurface { + match &self.source { + ObservationSource::Application { surface, .. } + | ObservationSource::Window { surface, .. } => *surface, + ObservationSource::Element { entry, .. } => entry.source.source_surface, + } + } + pub fn is_complete(&self) -> bool { self.structurally_complete } diff --git a/crates/core/src/ref_action/post_release.rs b/crates/core/src/ref_action/post_release.rs index f69aabbf1b..b99fa05236 100644 --- a/crates/core/src/ref_action/post_release.rs +++ b/crates/core/src/ref_action/post_release.rs @@ -28,16 +28,15 @@ impl PostRelease { let surfaces_of = self.surfaces_of; let witness = self.witness; let work = move || { - let mut result = match witness { + let result = match witness { Some(witness) => witness.settle(adapter, landed_on, deadline, result), None => result, }; - if let Some(process) = surfaces_of { - result.surfaces = adapter - .surfaces_raised_by(process, landed_on, deadline) - .unwrap_or_default(); + match surfaces_of { + Some(process) => result + .with_surfaces_read(adapter.surfaces_raised_by(process, landed_on, deadline)), + None => result, } - result }; let Some(front) = self.front else { return work(); diff --git a/crates/core/src/refs/resolve_saved_ref.rs b/crates/core/src/refs/resolve_saved_ref.rs index 6e2dc08b2d..414d86db87 100644 --- a/crates/core/src/refs/resolve_saved_ref.rs +++ b/crates/core/src/refs/resolve_saved_ref.rs @@ -1,6 +1,6 @@ use crate::{ AdapterError, AppError, AppInfo, Deadline, IdentityMatch, IdentityProof, PlatformAdapter, - RefEntry, WindowInfo, + RefEntry, SnapshotSurface, WindowInfo, adapter::{NativeHandle, TreeOptions}, locator::live_locator::{ObservationRequest, ObservationRoot, ObservedTree}, refs::ref_full_predicate::FullPredicate, @@ -86,7 +86,13 @@ pub(crate) fn observe_saved_ref( }; let mut request = whole_window_request(&base, deadline)?; request.observation_mode.identity_only = identity_only; - let observed = observe_window(adapter, &request, &window, lease)?; + let observed = observe_window( + adapter, + &request, + &window, + lease, + entry.source.source_window_id.is_some(), + )?; let index = saved_ref_node(entry, token, &observed)?; let node = observed .nodes @@ -159,6 +165,17 @@ pub(crate) fn recorded_window( return crate::system::app_lookup::live_process_owner(adapter, entry, deadline) .map_err(AppError::into_adapter_error); } + if let Some(window_id) = entry.source.source_window_id.as_deref() + && let Some(process) = entry.process.identity() + && let Some(window) = adapter.recorded_surface_window( + process, + window_id, + entry.source.source_surface, + deadline, + )? + { + return Ok(window); + } let resolved = crate::snapshot::resolve_window_for_surface( adapter, entry.source.source_app.as_deref(), @@ -215,7 +232,8 @@ fn belongs_to_entry(window: &WindowInfo, entry: &RefEntry) -> bool { /// uses: the whole window at the deepest limit a walk supports, so a capture /// proof and a later resolution count the same evidence. `base` supplies the /// surface and the renderer-accessibility hint; its depth and presentation -/// settings are ignored. +/// settings are ignored. `window` is the owner the capture resolved, so a +/// surface presented by that window is read at it. pub(crate) fn observe_whole_window( adapter: &dyn PlatformAdapter, base: &TreeOptions, @@ -227,6 +245,7 @@ pub(crate) fn observe_whole_window( &whole_window_request(base, deadline)?, window, None, + true, ) } @@ -249,6 +268,7 @@ fn observe_window( request: &ObservationRequest, window: &WindowInfo, lease: Option<&crate::InteractionLease>, + surface_window: bool, ) -> Result { let process_instance = window.process_instance.clone(); let app = AppInfo { @@ -259,14 +279,7 @@ fn observe_window( bundle_id: None, presentation: None, }; - let root = if adapter.is_application_surface(request.surface) { - ObservationRoot::Application { - app: &app, - surface: request.surface, - } - } else { - ObservationRoot::Window(window) - }; + let root = observation_root(adapter, request.surface, &app, window, surface_window); let mut observed = crate::tree::renderer_accessibility::observe_tree(adapter, root, request, lease) .map_err(AppError::into_adapter_error)?; @@ -280,6 +293,27 @@ fn observe_window( Ok(observed) } +/// The root one observation of `surface` starts at. `surface_window` says the +/// window is the one the surface is presented by - the id a ref recorded, or the +/// owner a capture resolved - so the read lands on that window instead of +/// re-resolving the surface from the process, which cannot name it while several +/// of that kind are open. Every other application-owned surface has no window of +/// its own and starts at the application root. +fn observation_root<'a>( + adapter: &dyn PlatformAdapter, + surface: SnapshotSurface, + app: &'a AppInfo, + window: &'a WindowInfo, + surface_window: bool, +) -> ObservationRoot<'a> { + let presented_by_window = surface_window && !window.is_process_owner(); + if adapter.is_application_surface(surface) && !presented_by_window { + ObservationRoot::Application { app, surface } + } else { + ObservationRoot::Window(window) + } +} + fn saved_ref_node( entry: &RefEntry, token: Option<&str>, diff --git a/crates/core/src/snapshot/snapshot_ref.rs b/crates/core/src/snapshot/snapshot_ref.rs index dd45e8b602..f5bce4e64b 100644 --- a/crates/core/src/snapshot/snapshot_ref.rs +++ b/crates/core/src/snapshot/snapshot_ref.rs @@ -150,7 +150,9 @@ fn resolve_result_owner( window: &WindowInfo, adapter: &dyn PlatformAdapter, ) -> Result { - if adapter.is_application_surface(entry.source.source_surface) { + if adapter.is_application_surface(entry.source.source_surface) + && entry.source.source_window_id.is_none() + { let app = super::surface_target::application_from_ref(entry)?; crate::system::app_lookup::process_identity(&app)?; Ok(SnapshotOwner::Application(app)) diff --git a/crates/core/src/snapshot/surface_target.rs b/crates/core/src/snapshot/surface_target.rs index 8851196244..73953ff72d 100644 --- a/crates/core/src/snapshot/surface_target.rs +++ b/crates/core/src/snapshot/surface_target.rs @@ -205,9 +205,20 @@ pub(crate) fn resolve_owners( return super::surface_windows(adapter, app_name, window_id, surface, deadline) .map(|windows| windows.into_iter().map(SnapshotOwner::Window).collect()); } - let app = if window_id.is_some() { - let window = super::resolve_window(adapter, app_name, window_id, deadline)?; - crate::system::app_lookup::resolve_app_owning(&window, adapter, deadline)? + let app = if let Some(window_id) = window_id { + match super::resolve_window(adapter, app_name, Some(window_id), deadline) { + Ok(window) => { + crate::system::app_lookup::resolve_app_owning(&window, adapter, deadline)? + } + Err(error) if error.code() == crate::ErrorCode::WindowNotFound.as_str() => { + return match surface_window_named(adapter, app_name, window_id, surface, deadline)? + { + Some(window) => Ok(vec![SnapshotOwner::Window(window)]), + None => Err(error), + }; + } + Err(error) => return Err(error), + } } else if app_name.is_some() { crate::system::app_lookup::resolve_app(app_name, adapter, deadline)? } else { @@ -220,9 +231,40 @@ pub(crate) fn resolve_owners( })? }; crate::system::app_lookup::process_identity(&app)?; + if let Some(window) = adapter.surface_window(&app, surface, deadline)? { + return Ok(vec![SnapshotOwner::Window(window)]); + } Ok(vec![SnapshotOwner::Application(app)]) } +/// The surface window a capture names through `--window-id`, when that id is a +/// surface window the window inventory leaves out. The application must also +/// be named, because a surface window carries a process rather than a census +/// record; an application label that cannot be resolved leaves this to the +/// inventory's own missing-window answer. +fn surface_window_named( + adapter: &dyn PlatformAdapter, + app_name: Option<&str>, + window_id: &str, + surface: crate::SnapshotSurface, + deadline: Deadline, +) -> Result, AppError> { + let Some(app_name) = app_name else { + return Ok(None); + }; + let Ok(app) = crate::system::app_lookup::resolve_app(Some(app_name), adapter, deadline) else { + return Ok(None); + }; + let process = crate::system::app_lookup::process_identity(&app)?; + let Some(mut window) = + adapter.recorded_surface_window(process, window_id, surface, deadline)? + else { + return Ok(None); + }; + window.app = app.name; + Ok(Some(window)) +} + pub(crate) fn resolve_ref_owner( adapter: &dyn PlatformAdapter, entry: &crate::RefEntry, @@ -238,11 +280,12 @@ pub(crate) fn resolve_ref_owner( if application_surface || entry.source.is_process_owned() { return Ok(match adapter.process_state(process, deadline)? { ProcessState::Running => { - let app = application_from_ref(entry)?; - let owner = if application_surface { - SnapshotOwner::Application(app) - } else { - SnapshotOwner::Window(crate::WindowInfo::for_process(&app)) + let owner = match (application_surface, entry.source.source_window_id.is_some()) { + (true, true) => SnapshotOwner::Window(source_window_info(entry)?), + (true, false) => SnapshotOwner::Application(application_from_ref(entry)?), + (false, _) => SnapshotOwner::Window(crate::WindowInfo::for_process( + &application_from_ref(entry)?, + )), }; RefOwnerObservation::Present(owner) } @@ -254,20 +297,7 @@ pub(crate) fn resolve_ref_owner( } }); } - let expected = crate::WindowInfo { - id: entry.source.source_window_id.clone().ok_or_else(|| { - AdapterError::new( - crate::ErrorCode::ActionNotSupported, - "Ref has no source window for post-action observation", - ) - })?, - title: entry.source.source_window_title.clone().unwrap_or_default(), - app: entry.source.source_app.clone().unwrap_or_default(), - pid: entry.process.pid, - process_instance: Some(process.instance.clone()), - bounds: None, - state: Default::default(), - }; + let expected = source_window_info(entry)?; match adapter.resolve_window_strict(&expected, deadline) { Ok(window) => { if window.id != expected.id @@ -311,6 +341,26 @@ pub(crate) fn application_from_ref(entry: &crate::RefEntry) -> Result Result { + Ok(WindowInfo { + id: entry.source.source_window_id.clone().ok_or_else(|| { + AdapterError::new( + crate::ErrorCode::ActionNotSupported, + "Ref has no source window for post-action observation", + ) + })?, + title: entry.source.source_window_title.clone().unwrap_or_default(), + app: entry.source.source_app.clone().unwrap_or_default(), + pid: entry.process.pid, + process_instance: entry.process.process_instance.clone(), + bounds: None, + state: Default::default(), + }) +} + pub(crate) fn ref_observation_surface( adapter: &dyn PlatformAdapter, entry: &crate::RefEntry, diff --git a/crates/core/src/trace/trace_file.rs b/crates/core/src/trace/trace_file.rs index 253f3fc2d0..c70f98619a 100644 --- a/crates/core/src/trace/trace_file.rs +++ b/crates/core/src/trace/trace_file.rs @@ -61,8 +61,8 @@ pub(crate) fn open_trace_file(path: &Path) -> Result { crate::storage::private_file::open_private_append(path).map_err(|error| { if error.kind() == std::io::ErrorKind::PermissionDenied { return AppError::invalid_input_with_suggestion( - "Trace path must be a private user-owned regular file with one link", - "Use a new --trace path or replace the existing unsafe file.", + "Trace path must be a private user-owned regular file with one link, and on Windows its folder must be private too", + "Use a new --trace path in a folder only you can write, or replace the existing unsafe file.", ); } AppError::from(error) diff --git a/crates/ffi/src/commands/wait.rs b/crates/ffi/src/commands/wait.rs index 69a3374730..58afd6b824 100644 --- a/crates/ffi/src/commands/wait.rs +++ b/crates/ffi/src/commands/wait.rs @@ -77,6 +77,7 @@ pub unsafe extern "C" fn ad_wait( ffi_args.mode.surfaces.menu, ffi_args.mode.surfaces.menu_closed, ffi_args.mode.surfaces.notification, + None, ) .and_then(|surface| { wait_args.mode.surface = surface; diff --git a/crates/linux/src/notifications/world.rs b/crates/linux/src/notifications/world.rs index aebcbaa089..073c969ebf 100644 --- a/crates/linux/src/notifications/world.rs +++ b/crates/linux/src/notifications/world.rs @@ -8,7 +8,7 @@ use crate::system::shell::anchor::Anchor; use crate::system::shell::container::{Landmark, locate_anchor}; use crate::system::shell::identity::find_root; use crate::system::shell::kinds::ShellKind; -use crate::system::shell::light::LiveNodes; +use crate::system::shell::light::{Detail, LiveNodes}; use crate::system::shell::open::{Opened, close, is_showing, open}; use crate::system::shell::search::{Walk, walk}; use crate::tree::AtspiElement; @@ -57,7 +57,7 @@ impl ShellWorld for LiveWorld<'_> { fn read(&self, root: &AtspiElement, deadline: Deadline) -> Result { let nodes = LiveNodes::new(self.bus.get(deadline)?.inner().clone(), deadline); - walk(&nodes, root, deadline, &|_| false) + walk(&nodes, root, deadline, Detail::Full, &|_| false) } fn open( diff --git a/crates/linux/src/system/adapter.rs b/crates/linux/src/system/adapter.rs index 53b7680a30..d96d196e52 100644 --- a/crates/linux/src/system/adapter.rs +++ b/crates/linux/src/system/adapter.rs @@ -237,33 +237,24 @@ impl SystemOps for LinuxAdapter { } fn supported_surfaces(&self) -> Vec { - let Ok(deadline) = Deadline::after(SURFACE_PROBE_MS) else { - return Vec::new(); - }; - if !permissions::accessibility_answers(self.bus(), deadline) { - return Vec::new(); + let mut surfaces = answering_app_surfaces(self.bus()); + if !surfaces.is_empty() { + surfaces.extend(shell::supported(self.bus())); } - let mut surfaces = vec![ - SnapshotSurface::Window, - SnapshotSurface::Sheet, - SnapshotSurface::Alert, - ]; - surfaces.extend(menu_surface::supported()); - surfaces.extend(shell::supported(self.bus())); surfaces } + /// An application surface needs no probe. A kind that no shell surface + /// can be is refused without the shell probe, which takes up to its + /// budget on a session whose shell tree answers slowly. fn check_surface_support(&self, requested: SnapshotSurface) -> Result<(), AdapterError> { - if matches!( - requested, - SnapshotSurface::Window - | SnapshotSurface::Sheet - | SnapshotSurface::Alert - | SnapshotSurface::Menu - ) { + if app_surfaces().contains(&requested) { return Ok(()); } - let supported = self.supported_surfaces(); + let supported = match shell::kinds::kind_of(requested) { + Some(_) => self.supported_surfaces(), + None => answering_app_surfaces(self.bus()), + }; if supported.contains(&requested) { return Ok(()); } @@ -325,3 +316,23 @@ impl SystemOps for LinuxAdapter { shell::open_surface(self.bus(), surface, policy, lease) } } + +/// The application surfaces, or none when the session's accessibility bus +/// does not answer. +fn answering_app_surfaces(bus: &crate::system::SharedBus) -> Vec { + match Deadline::after(SURFACE_PROBE_MS) { + Ok(deadline) if permissions::accessibility_answers(bus, deadline) => app_surfaces(), + _ => Vec::new(), + } +} + +/// The surfaces of an application window that every session reads. +fn app_surfaces() -> Vec { + let mut surfaces = vec![ + SnapshotSurface::Window, + SnapshotSurface::Sheet, + SnapshotSurface::Alert, + ]; + surfaces.extend(menu_surface::supported()); + surfaces +} diff --git a/crates/linux/src/system/capture/window_xid_tests.rs b/crates/linux/src/system/capture/window_xid_tests.rs index ece6dfd287..073adbbaf1 100644 --- a/crates/linux/src/system/capture/window_xid_tests.rs +++ b/crates/linux/src/system/capture/window_xid_tests.rs @@ -72,6 +72,7 @@ fn the_server_states_without_a_client_list_keep_their_cause() { fn listed(id: &str, title: &str, active: bool) -> ListedWindow { ListedWindow { + alert: false, app: 0, info: WindowInfo { id: id.to_owned(), diff --git a/crates/linux/src/system/launch/launch_baseline_tests.rs b/crates/linux/src/system/launch/launch_baseline_tests.rs index a1b3725140..34b5f027c6 100644 --- a/crates/linux/src/system/launch/launch_baseline_tests.rs +++ b/crates/linux/src/system/launch/launch_baseline_tests.rs @@ -114,6 +114,7 @@ fn an_old_frame_omitted_by_an_incomplete_baseline_cannot_be_a_launch_window() { pass.recovered.push(0); pass.windows .push(crate::system::registry::listed_window::ListedWindow { + alert: false, app: 0, info: agent_desktop_core::WindowInfo { id: "w-1.5-stopped-x42".to_owned(), diff --git a/crates/linux/src/system/menu/inventory_tests.rs b/crates/linux/src/system/menu/inventory_tests.rs index a06528f5ca..abb0d7c2ee 100644 --- a/crates/linux/src/system/menu/inventory_tests.rs +++ b/crates/linux/src/system/menu/inventory_tests.rs @@ -11,6 +11,7 @@ use crate::tree::{AtspiElement, Field, WalkedNode}; fn window(id: &str, sheet: bool) -> ListedWindow { ListedWindow { + alert: false, app: 0, info: WindowInfo { id: id.to_owned(), diff --git a/crates/linux/src/system/menu/surfaces.rs b/crates/linux/src/system/menu/surfaces.rs index a75282055a..d77d11964e 100644 --- a/crates/linux/src/system/menu/surfaces.rs +++ b/crates/linux/src/system/menu/surfaces.rs @@ -40,15 +40,23 @@ fn surface(id: &str, kind: &str, title: &Option) -> SurfaceInfo { } } -/// The surfaces of one listed window: a `window` entry always, a `sheet` -/// entry alongside it when the window is a modal dialog. +/// The kinds a listed window adds beside its `window` entry: `alert` when the +/// frame is a showing alert, the predicate `snapshot --surface alert` roots +/// at, and `sheet` when it is a modal dialog. A modal alert is both. +fn extra_kinds(window: &ListedWindow) -> impl Iterator { + let alert = window.alert.then_some("alert"); + alert.into_iter().chain(window.sheet.then_some("sheet")) +} + +/// The surfaces of one listed window: a `window` entry always, and an `alert` +/// and a `sheet` entry alongside it when the window is one. pub(crate) fn surfaces_of(windows: &[ListedWindow]) -> Vec { windows .iter() .flat_map(|window| { let title = (!window.info.title.is_empty()).then(|| window.info.title.clone()); std::iter::once("window") - .chain(window.sheet.then_some("sheet")) + .chain(extra_kinds(window)) .map(move |kind| surface(&window.info.id, kind, &title)) }) .collect() diff --git a/crates/linux/src/system/menu/surfaces_tests.rs b/crates/linux/src/system/menu/surfaces_tests.rs index 6fcab2186b..3c36b6cfc4 100644 --- a/crates/linux/src/system/menu/surfaces_tests.rs +++ b/crates/linux/src/system/menu/surfaces_tests.rs @@ -7,6 +7,7 @@ use agent_desktop_core::{AdapterError, ErrorCode}; fn window(id: &str, title: &str, sheet: bool) -> ListedWindow { ListedWindow { + alert: false, app: 0, info: WindowInfo { id: id.to_owned(), @@ -152,3 +153,17 @@ fn an_incomplete_scan_still_reports_the_dialog_it_saw() { assert_eq!(dialogs.titles, ["Save Changes?".to_owned()]); assert!(!dialogs.complete); } + +#[test] +fn a_showing_modal_alert_lists_both_an_alert_and_a_sheet_entry() { + let mut alert = window("w-1", "Save changes?", true); + alert.alert = true; + let kinds: Vec<_> = surfaces_of(&[alert]) + .iter() + .map(|surface| surface.kind.clone()) + .collect(); + assert_eq!(kinds, ["window", "alert", "sheet"]); + let mut plain = window("w-2", "Doc", false); + plain.alert = false; + assert_eq!(surfaces_of(&[plain]).len(), 1); +} diff --git a/crates/linux/src/system/process/protected_tests.rs b/crates/linux/src/system/process/protected_tests.rs index d0019c9a85..840797b042 100644 --- a/crates/linux/src/system/process/protected_tests.rs +++ b/crates/linux/src/system/process/protected_tests.rs @@ -92,6 +92,7 @@ fn a_launch_marker_that_cannot_be_read_refuses_instead_of_protecting_by_name() { fn window(unshown: bool) -> ListedWindow { ListedWindow { + alert: false, app: 0, info: WindowInfo { id: "w-1".to_owned(), diff --git a/crates/linux/src/system/registry/listed_window.rs b/crates/linux/src/system/registry/listed_window.rs index d69df4d360..3fd2f10aff 100644 --- a/crates/linux/src/system/registry/listed_window.rs +++ b/crates/linux/src/system/registry/listed_window.rs @@ -13,6 +13,9 @@ pub(crate) struct ListedWindow { pub(crate) dialog: bool, pub(crate) frame: FrameFacts, pub(crate) sheet: bool, + /// The frame is a showing alert, by the predicate `snapshot --surface alert` + /// roots at. + pub(crate) alert: bool, /// The window neither shows nor is iconified. A toolkit that keeps a /// top-level window for reuse leaves such a husk on the registry after /// it hides or closes. diff --git a/crates/linux/src/system/shell/container.rs b/crates/linux/src/system/shell/container.rs index 06c4914da4..fb40bd6a5c 100644 --- a/crates/linux/src/system/shell/container.rs +++ b/crates/linux/src/system/shell/container.rs @@ -5,7 +5,7 @@ use serde_json::json; use super::anchor::Anchor; use super::identity::ShellRoot; -use super::light::{Light, LiveNodes, Nodes}; +use super::light::{Detail, Light, LiveNodes, Nodes}; use super::located::Located; use super::search::{Visit, walk}; use crate::system::SharedBus; @@ -59,15 +59,17 @@ fn locate_in( }); } Anchor::Landmark(Landmark::MessageList) => { - let walked = walk(nodes, &start, deadline, &|_| false)?; + let walked = walk(nodes, &start, deadline, Detail::Structure, &|_| false)?; ( - lists(&walked.visits), + read_in_full(nodes, lists(&walked.visits))?, walked.complete, "Several shell containers have the requested role chain", ) } Anchor::Landmark(Landmark::DateMenu) => { - let walked = walk(nodes, &start, deadline, &|light| !light.showing)?; + let walked = walk(nodes, &start, deadline, Detail::Full, &|light| { + !light.showing + })?; ( date_menus(&walked.visits), walked.complete, @@ -118,6 +120,21 @@ fn lists(visits: &[Visit]) -> Vec { .collect() } +/// A structure read leaves a node's name, extents and state empty, so the +/// containers a rule named are read again in full before they are reported. +/// A container that left the tree between the two reads is a lost node. +fn read_in_full(nodes: &N, found: Vec) -> Result, AdapterError> { + found + .iter() + .map(|light| match nodes.read(&light.element) { + Err(error) if error.code == ErrorCode::ElementNotFound => { + Err(lost_a_node(Anchor::Landmark(Landmark::MessageList))) + } + other => other, + }) + .collect() +} + /// The date menu is the one showing menu in the shell with no accessible /// name; every other top bar menu names its indicator. fn date_menus(visits: &[Visit]) -> Vec { diff --git a/crates/linux/src/system/shell/container_tests.rs b/crates/linux/src/system/shell/container_tests.rs index 8599c49ceb..7d9bbe3008 100644 --- a/crates/linux/src/system/shell/container_tests.rs +++ b/crates/linux/src/system/shell/container_tests.rs @@ -186,3 +186,41 @@ fn an_unproven_native_tray_uses_only_the_logical_shell_root() { assert_eq!(located.container.element.path(), "/w"); assert_eq!(located.container.role, WINDOW); } + +struct Counting<'a> { + tree: &'a FakeTree, + structure_reads: Cell, + full_reads: std::cell::RefCell>, +} + +impl Nodes for Counting<'_> { + fn read(&self, node: &AtspiElement) -> Result { + self.full_reads.borrow_mut().push(node.path().to_owned()); + self.tree.read(node) + } + + fn read_structure(&self, node: &AtspiElement) -> Result { + self.structure_reads.set(self.structure_reads.get() + 1); + self.tree.read(node) + } +} + +#[test] +fn locating_the_message_list_reads_structure_and_reads_only_the_list_in_full() { + let tree = gnome_shell(true, false); + let nodes = Counting { + tree: &tree, + structure_reads: Cell::new(0), + full_reads: Default::default(), + }; + let located = locate_in( + &nodes, + &FakeTree::root(), + Anchor::Landmark(Landmark::MessageList), + Deadline::after(5_000).unwrap(), + ) + .expect("the footer row proves the list"); + assert_eq!(located.container.element.path(), "/list"); + assert!(nodes.structure_reads.get() > 1); + assert_eq!(*nodes.full_reads.borrow(), vec!["/list".to_owned()]); +} diff --git a/crates/linux/src/system/shell/hit.rs b/crates/linux/src/system/shell/hit.rs index c79c7b7a3b..cd468deca8 100644 --- a/crates/linux/src/system/shell/hit.rs +++ b/crates/linux/src/system/shell/hit.rs @@ -3,7 +3,7 @@ use std::time::Duration; use agent_desktop_core::{AdapterError, Deadline, ErrorCode, HitTestResult, Point}; use super::identity::find_root; -use super::light::{LiveNodes, Nodes}; +use super::light::{Detail, LiveNodes, Nodes}; use super::search::walk; use crate::system::{SharedBus, list_displays}; use crate::tree::{AtspiElement, Extents}; @@ -46,7 +46,7 @@ pub(super) fn verdict( Err(error) => return Err(error), }; pause(MOTION_GAP); - let tree = walk(nodes, root, deadline, &|light| !light.showing)?; + let tree = walk(nodes, root, deadline, Detail::Full, &|light| !light.showing)?; if !tree.complete { return Ok(HitTestResult::Unknown); } diff --git a/crates/linux/src/system/shell/light.rs b/crates/linux/src/system/shell/light.rs index 8436d3719c..f18accda15 100644 --- a/crates/linux/src/system/shell/light.rs +++ b/crates/linux/src/system/shell/light.rs @@ -1,6 +1,6 @@ use crate::tree::placement::visibility::is_placed; use agent_desktop_core::{AdapterError, Deadline, ErrorCode}; -use futures_util::future::{join_all, join5}; +use futures_util::future::{join, join_all, join5}; use zbus::Connection; use zbus::zvariant::OwnedValue; @@ -36,12 +36,35 @@ pub(crate) fn same_object(left: &AtspiElement, right: &AtspiElement) -> bool { left.bus_name() == right.bus_name() && left.path() == right.path() } +/// How much of each node a walk reads. A structure read asks only for the +/// role and the children, two bus calls per node; every other field of the +/// `Light` it returns is left empty and must not be consulted. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Detail { + Structure, + Full, +} + /// Reads shell nodes. The bus implements it; a test substitutes a tree. pub(crate) trait Nodes { fn read(&self, element: &AtspiElement) -> Result; - fn read_level(&self, elements: &[AtspiElement]) -> Vec> { - elements.iter().map(|element| self.read(element)).collect() + fn read_structure(&self, element: &AtspiElement) -> Result { + self.read(element) + } + + fn read_level( + &self, + elements: &[AtspiElement], + detail: Detail, + ) -> Vec> { + elements + .iter() + .map(|element| match detail { + Detail::Structure => self.read_structure(element), + Detail::Full => self.read(element), + }) + .collect() } } @@ -185,6 +208,33 @@ async fn read_one(connection: &Connection, element: &AtspiElement) -> Result Result { + let (children, role) = join( + list_children(connection, element), + role_of(connection, element), + ) + .await; + let children = children.map_err(missing_when_dead)?; + let role = role?.ok_or_else(|| { + AdapterError::new(ErrorCode::ElementNotFound, "The shell node did not answer") + })?; + Ok(Light { + element: element.address(), + role, + name: String::new(), + extents: None, + showing: false, + visible: false, + children: children + .into_iter() + .map(|(bus, path)| AtspiElement::new(bus, path, element.pid())) + .collect(), + }) +} + pub(crate) struct LiveNodes { connection: Connection, deadline: Deadline, @@ -204,15 +254,24 @@ impl Nodes for LiveNodes { within(self.deadline, read_one(&self.connection, element)) } - fn read_level(&self, elements: &[AtspiElement]) -> Vec> { + fn read_structure(&self, element: &AtspiElement) -> Result { + within(self.deadline, read_structure_one(&self.connection, element)) + } + + fn read_level( + &self, + elements: &[AtspiElement], + detail: Detail, + ) -> Vec> { let mut reads = Vec::with_capacity(elements.len()); for chunk in elements.chunks(LEVEL_IN_FLIGHT) { let chunk_reads = within(self.deadline, async { - Ok(join_all( - chunk - .iter() - .map(|element| read_one(&self.connection, element)), - ) + Ok(join_all(chunk.iter().map(|element| async move { + match detail { + Detail::Structure => read_structure_one(&self.connection, element).await, + Detail::Full => read_one(&self.connection, element).await, + } + })) .await) }); match chunk_reads { diff --git a/crates/linux/src/system/shell/search.rs b/crates/linux/src/system/shell/search.rs index 42b1f8788e..b55f4eb25e 100644 --- a/crates/linux/src/system/shell/search.rs +++ b/crates/linux/src/system/shell/search.rs @@ -1,6 +1,8 @@ use agent_desktop_core::{AdapterError, Deadline, ErrorCode}; -use super::light::{Light, Nodes, same_object}; +use serde_json::json; + +use super::light::{Detail, Light, Nodes, same_object}; use crate::tree::AtspiElement; const MAX_NODES: usize = 8_000; @@ -52,6 +54,7 @@ pub(crate) fn walk( nodes: &N, root: &AtspiElement, deadline: Deadline, + detail: Detail, prune: &dyn Fn(&Light) -> bool, ) -> Result { let mut arena: Vec = Vec::new(); @@ -59,13 +62,13 @@ pub(crate) fn walk( let mut frontier: Vec<(AtspiElement, Option)> = vec![(root.clone(), None)]; while !frontier.is_empty() { if deadline.is_expired() { - return Err(deadline.timeout_error()); + return Err(unread(arena.len())); } let elements: Vec = frontier .iter() .map(|(element, _)| element.clone()) .collect(); - let reads = nodes.read_level(&elements); + let reads = nodes.read_level(&elements, detail); let mut next = Vec::new(); for ((_, parent), read) in frontier.drain(..).zip(reads) { let light = match read { @@ -74,6 +77,9 @@ pub(crate) fn walk( complete = false; continue; } + Err(error) if error.code == ErrorCode::Timeout => { + return Err(unread(arena.len())); + } Err(error) => return Err(error), }; if prune(&light) { @@ -108,6 +114,18 @@ pub(crate) fn walk( }) } +/// The budget ended before the shell tree was read. The shell answers its +/// accessibility calls one at a time, so a large tree can outlast the budget +/// while the shell itself is healthy; the error says which tree and how far +/// the read got instead of blaming a busy application. +fn unread(nodes_read: usize) -> AdapterError { + AdapterError::timeout(format!( + "The desktop shell tree was not read within the time limit ({nodes_read} nodes read)" + )) + .with_suggestion("Retry the command; the shell answers its accessibility calls one at a time") + .with_details(json!({ "kind": "shell_tree_unread", "nodes_read": nodes_read })) +} + fn in_paint_order(arena: Vec) -> Vec { let mut order = Vec::with_capacity(arena.len()); let mut stack = if arena.is_empty() { vec![] } else { vec![0] }; diff --git a/crates/linux/src/system/shell/search_tests.rs b/crates/linux/src/system/shell/search_tests.rs index 68293a0742..5a7eb491c8 100644 --- a/crates/linux/src/system/shell/search_tests.rs +++ b/crates/linux/src/system/shell/search_tests.rs @@ -1,6 +1,7 @@ use agent_desktop_core::{Deadline, ErrorCode}; use crate::system::shell::fake_tree::{FakeTree, PANEL, WINDOW, at, element, gnome_shell}; +use crate::system::shell::light::Detail; use crate::system::shell::search::walk; fn deadline() -> Deadline { @@ -20,7 +21,10 @@ fn small() -> FakeTree { #[test] fn nodes_come_in_paint_order_and_know_their_parents() { - let walked = walk(&small(), &element("/w"), deadline(), &|_| false).expect("a walk"); + let walked = walk(&small(), &element("/w"), deadline(), Detail::Full, &|_| { + false + }) + .expect("a walk"); let paths: Vec<&str> = walked .visits .iter() @@ -35,7 +39,10 @@ fn nodes_come_in_paint_order_and_know_their_parents() { #[test] fn within_follows_the_parents_and_position_finds_an_element() { - let walked = walk(&small(), &element("/w"), deadline(), &|_| false).expect("a walk"); + let walked = walk(&small(), &element("/w"), deadline(), Detail::Full, &|_| { + false + }) + .expect("a walk"); assert!(walked.within(3, 1)); assert!(walked.within(3, 3)); assert!(!walked.within(3, 4)); @@ -45,9 +52,13 @@ fn within_follows_the_parents_and_position_finds_an_element() { #[test] fn a_pruned_node_is_neither_listed_nor_entered() { - let walked = walk(&small(), &element("/w"), deadline(), &|light| { - light.element.path() == "/a" - }) + let walked = walk( + &small(), + &element("/w"), + deadline(), + Detail::Full, + &|light| light.element.path() == "/a", + ) .expect("a walk"); let paths: Vec<&str> = walked .visits @@ -61,7 +72,7 @@ fn a_pruned_node_is_neither_listed_nor_entered() { fn a_node_that_vanishes_during_the_walk_is_skipped_and_the_walk_says_so() { let mut tree = gnome_shell(true, false); tree.vanish("/left"); - let walked = walk(&tree, &element("/w"), deadline(), &|_| false).expect("a walk"); + let walked = walk(&tree, &element("/w"), deadline(), Detail::Full, &|_| false).expect("a walk"); assert!(!walked.complete); assert!(walked.position(&element("/system")).is_some()); assert!(walked.position(&element("/left")).is_none()); @@ -71,8 +82,11 @@ fn a_node_that_vanishes_during_the_walk_is_skipped_and_the_walk_says_so() { fn an_expired_deadline_is_a_timeout_not_an_empty_walk() { let expired = Deadline::after(1).expect("a deadline builds"); std::thread::sleep(std::time::Duration::from_millis(5)); - let error = walk(&small(), &element("/w"), expired, &|_| false).expect_err("no time"); + let error = + walk(&small(), &element("/w"), expired, Detail::Full, &|_| false).expect_err("no time"); assert_eq!(error.code, ErrorCode::Timeout); + assert_eq!(error.details.unwrap()["kind"], "shell_tree_unread"); + assert!(!error.suggestion.unwrap().contains("busy")); } #[test] @@ -88,6 +102,7 @@ fn a_walk_over_the_budget_is_an_error_and_never_a_shorter_tree() { at(0, 0, 0, 0), ); } - let error = walk(&tree, &element("/w"), deadline(), &|_| false).expect_err("over budget"); + let error = + walk(&tree, &element("/w"), deadline(), Detail::Full, &|_| false).expect_err("over budget"); assert_eq!(error.code, ErrorCode::Timeout); } diff --git a/crates/linux/src/system/signal/signal_capture_tests.rs b/crates/linux/src/system/signal/signal_capture_tests.rs index 79c9f6a7ad..027b44c599 100644 --- a/crates/linux/src/system/signal/signal_capture_tests.rs +++ b/crates/linux/src/system/signal/signal_capture_tests.rs @@ -45,6 +45,7 @@ impl World { fn listed(app: &RegistryApp, scripted: &Scripted) -> ListedWindow { ListedWindow { + alert: false, app: scripted.owner, info: WindowInfo { id: scripted.id.to_owned(), diff --git a/crates/linux/src/system/signal/signal_population_tests.rs b/crates/linux/src/system/signal/signal_population_tests.rs index eb647dbf8c..26257db614 100644 --- a/crates/linux/src/system/signal/signal_population_tests.rs +++ b/crates/linux/src/system/signal/signal_population_tests.rs @@ -24,6 +24,7 @@ fn app(bus: &str, pid: u32, instance: &str, name: &str) -> RegistryApp { fn window(owner: usize, id: &str, visible: bool) -> ListedWindow { ListedWindow { + alert: false, app: owner, info: WindowInfo { id: id.to_owned(), diff --git a/crates/linux/src/system/signal/signal_surfaces_tests.rs b/crates/linux/src/system/signal/signal_surfaces_tests.rs index b9830a670a..67f8209bf2 100644 --- a/crates/linux/src/system/signal/signal_surfaces_tests.rs +++ b/crates/linux/src/system/signal/signal_surfaces_tests.rs @@ -24,6 +24,7 @@ fn app() -> RegistryApp { fn window(id: &str, title: &str, sheet: bool) -> ListedWindow { ListedWindow { + alert: false, app: 0, info: WindowInfo { id: id.to_owned(), diff --git a/crates/linux/src/system/window/ghost_window_tests.rs b/crates/linux/src/system/window/ghost_window_tests.rs index f9523917af..fce68f1658 100644 --- a/crates/linux/src/system/window/ghost_window_tests.rs +++ b/crates/linux/src/system/window/ghost_window_tests.rs @@ -6,6 +6,7 @@ use crate::system::x11::{FrameFacts, X11Client, X11State}; fn window(id: &str, title: &str, unshown: bool) -> ListedWindow { ListedWindow { + alert: false, app: 0, info: WindowInfo { id: id.to_owned(), diff --git a/crates/linux/src/system/window/listed_twins_tests.rs b/crates/linux/src/system/window/listed_twins_tests.rs index f48df43d98..06b2318c7b 100644 --- a/crates/linux/src/system/window/listed_twins_tests.rs +++ b/crates/linux/src/system/window/listed_twins_tests.rs @@ -5,6 +5,7 @@ use crate::system::x11::{FrameFacts, X11Client}; fn listed(pid: u32, title: &str, active: bool) -> ListedWindow { ListedWindow { + alert: false, app: 0, info: WindowInfo { id: format!("w-{pid}-{title}-{active}"), diff --git a/crates/linux/src/system/window/stopped_windows.rs b/crates/linux/src/system/window/stopped_windows.rs index 752e6acfad..eaae46b333 100644 --- a/crates/linux/src/system/window/stopped_windows.rs +++ b/crates/linux/src/system/window/stopped_windows.rs @@ -42,6 +42,7 @@ pub(crate) fn of_stopped_apps( continue; } found.push(ListedWindow { + alert: false, app: index, info: WindowInfo { id, diff --git a/crates/linux/src/system/window/window_filter_deadline_tests.rs b/crates/linux/src/system/window/window_filter_deadline_tests.rs index b88336cfb0..50866273c8 100644 --- a/crates/linux/src/system/window/window_filter_deadline_tests.rs +++ b/crates/linux/src/system/window/window_filter_deadline_tests.rs @@ -7,6 +7,7 @@ use crate::system::x11::FrameFacts; #[test] fn an_expired_window_read_is_timeout_instead_of_an_unsupported_surface() { let window = ListedWindow { + alert: false, app: 0, info: WindowInfo { id: "window".to_owned(), diff --git a/crates/linux/src/system/window/window_filter_helper_tests.rs b/crates/linux/src/system/window/window_filter_helper_tests.rs index 5009cc0cd0..c657bfd45a 100644 --- a/crates/linux/src/system/window/window_filter_helper_tests.rs +++ b/crates/linux/src/system/window/window_filter_helper_tests.rs @@ -20,6 +20,7 @@ fn bounds(x: i32) -> Extents { fn window(pid: u32, x: i32) -> ListedWindow { ListedWindow { + alert: false, app: 0, info: WindowInfo { id: format!("window-{pid}"), diff --git a/crates/linux/src/system/window/window_filter_tests.rs b/crates/linux/src/system/window/window_filter_tests.rs index b4f5b3877c..c5eb727b8e 100644 --- a/crates/linux/src/system/window/window_filter_tests.rs +++ b/crates/linux/src/system/window/window_filter_tests.rs @@ -190,6 +190,7 @@ fn listed( ) -> crate::system::registry::listed_window::ListedWindow { use agent_desktop_core::{WindowInfo, WindowState}; crate::system::registry::listed_window::ListedWindow { + alert: false, app: 0, info: WindowInfo { id: format!("{:?}", frame.extents), diff --git a/crates/linux/src/system/window/window_listing.rs b/crates/linux/src/system/window/window_listing.rs index 29b6317f49..f30e5f86fb 100644 --- a/crates/linux/src/system/window/window_listing.rs +++ b/crates/linux/src/system/window/window_listing.rs @@ -64,6 +64,7 @@ fn listed( global_position, }, sheet: crate::tree::surfaces::is_sheet(node), + alert: crate::tree::surfaces::is_surface(node, agent_desktop_core::SnapshotSurface::Alert), unshown: state.visible == Some(false) && state.minimized == Some(false), }) } diff --git a/crates/linux/src/system/window/window_ops_tests.rs b/crates/linux/src/system/window/window_ops_tests.rs index 7a68cc29cb..a0f5f6c0bb 100644 --- a/crates/linux/src/system/window/window_ops_tests.rs +++ b/crates/linux/src/system/window/window_ops_tests.rs @@ -9,6 +9,7 @@ use crate::system::x11::{FrameExtents, FrameFacts, X11Client, X11State}; fn window(title: &str, active: bool, modal: bool) -> ListedWindow { ListedWindow { + alert: false, app: 0, info: WindowInfo { id: format!("w-1.1-{title}"), diff --git a/crates/linux/src/system/window/window_order_tests.rs b/crates/linux/src/system/window/window_order_tests.rs index d2e23bb061..8dec17f206 100644 --- a/crates/linux/src/system/window/window_order_tests.rs +++ b/crates/linux/src/system/window/window_order_tests.rs @@ -6,6 +6,7 @@ use crate::system::x11::{FrameFacts, X11Client, X11State}; fn window(title: &str, focused: bool) -> ListedWindow { ListedWindow { + alert: false, app: 0, info: WindowInfo { id: format!("w-{title}"), diff --git a/crates/macos/src/actions/background_effect.rs b/crates/macos/src/actions/background_effect.rs index 612049ca86..a9501c6a4a 100644 --- a/crates/macos/src/actions/background_effect.rs +++ b/crates/macos/src/actions/background_effect.rs @@ -5,7 +5,7 @@ //! Writing `AXFocused` moves focus only inside the target application //! (M-W0-14), so it has no effect here and headless `focus` is delivered. //! -//! The reasons are `shows_menu` and `opens_dialog`. A menu overlay is drawn +//! The reasons are `shows_menu`, `opens_dialog` and `popover_command`. A menu overlay is drawn //! over the user's window, takes their focused element, and AppKit orders the //! owning window front; no AX path selects a popup item or opens a context //! menu without it. A dialog is predicted by an owner-judgment rule: a label @@ -13,7 +13,9 @@ //! is trimmed, is the convention shared by GTK, Qt and macOS applications for //! a control that opens a dialog. It is a predictor, not a proof: no //! accessibility property says that a control opens a window. A label that -//! cannot be read counts as one. +//! cannot be read counts as one. A button inside a popover runs a command +//! that can start a service whose window the platform brings to the front (a +//! share item opens the AirDrop panel), and nothing in the tree tells which. use agent_desktop_core::{Action, AdapterError, Deadline, Effect, InteractionPolicy}; @@ -23,6 +25,7 @@ const MENU_OWNER_ROLES: &[&str] = &["AXPopUpButton", "AXMenuButton", "AXComboBox const ELLIPSES: &[&str] = &["\u{2026}", "..."]; const SHOWS_MENU: &str = "shows_menu"; const OPENS_DIALOG: &str = "opens_dialog"; +const POPOVER_COMMAND: &str = "popover_command"; /// Refuses `operation` with `POLICY_DENIED` when `policy` does not permit /// `effect`, and reports `kind` as the reason the action takes the foreground. @@ -81,6 +84,7 @@ pub(crate) fn press_disturbs(element: &AXElement, deadline: Deadline) -> bool { struct PressTarget { role: Option, labels: Vec, + in_popover: bool, } fn press_effect(action: &Action, target: &Option) -> Option<&'static str> { @@ -94,6 +98,9 @@ fn press_effect(action: &Action, target: &Option) -> Option<&'stati if menu_owner && matches!(action, Action::Click | Action::Expand) { return Some(SHOWS_MENU); } + if target.in_popover && matches!(action, Action::Click) { + return Some(POPOVER_COMMAND); + } let opens_dialog = target.labels.iter().any(|label| { let label = label.trim_end(); ELLIPSES.iter().any(|ellipsis| label.ends_with(ellipsis)) @@ -125,7 +132,12 @@ fn read_target(element: &AXElement, deadline: Deadline) -> Option { return None; } let names = read.attrs.name_evidence; + let in_popover = match read.attrs.role.as_deref() { + Some("AXButton") => inside_popover(element, deadline)?, + _ => false, + }; Some(PressTarget { + in_popover, role: read.attrs.role, labels: [ names.native_title, @@ -139,6 +151,36 @@ fn read_target(element: &AXElement, deadline: Deadline) -> Option { }) } +/// Whether a popover holds `element`, from a walk up its ancestors to its +/// window or application. None when an ancestor cannot be read, which is also +/// how the walk ends once the deadline runs out, so an unknown answer is never +/// read as "no". +fn inside_popover(element: &AXElement, deadline: Deadline) -> Option { + let mut current = element.clone(); + loop { + let Some(parent) = + crate::tree::surface_read::element(¤t, "AXParent", deadline).ok()? + else { + return Some(false); + }; + let role = crate::tree::surface_read::string(&parent, "AXRole", deadline).ok()?; + if role.as_deref() == Some("AXPopover") { + return Some(true); + } + if role.as_deref() == Some("AXApplication") { + return Some(false); + } + let subrole = crate::tree::surface_read::string(&parent, "AXSubrole", deadline).ok()?; + if subrole.as_deref() == Some("AXPopover") { + return Some(true); + } + if role.as_deref() == Some("AXWindow") { + return Some(false); + } + current = parent; + } +} + #[cfg(test)] #[path = "background_effect_tests.rs"] mod tests; diff --git a/crates/macos/src/actions/background_effect_tests.rs b/crates/macos/src/actions/background_effect_tests.rs index 486a4deaaa..1eb1d4f2d7 100644 --- a/crates/macos/src/actions/background_effect_tests.rs +++ b/crates/macos/src/actions/background_effect_tests.rs @@ -6,9 +6,29 @@ fn target(role: &str, label: &str) -> Option { Some(PressTarget { role: Some(role.into()), labels: vec![label.into()], + in_popover: false, }) } +#[test] +fn headless_refuses_a_click_on_a_button_a_popover_holds() { + let in_popover = || { + Some(PressTarget { + in_popover: true, + ..target("AXButton", "AirDrop")? + }) + }; + assert_eq!( + action_effect(&Action::Click, in_popover), + Some("popover_command") + ); + assert_eq!(action_effect(&Action::Toggle, in_popover), None); + assert_eq!( + action_effect(&Action::Click, || target("AXButton", "Share")), + None + ); +} + #[test] fn headless_refuses_what_the_user_would_see_and_delivers_the_rest() { let effect = |action: Action, read: Option| action_effect(&action, || read); diff --git a/crates/macos/src/system/window/cg_window.rs b/crates/macos/src/system/window/cg_window.rs index d72e3fbf88..06e1688b33 100644 --- a/crates/macos/src/system/window/cg_window.rs +++ b/crates/macos/src/system/window/cg_window.rs @@ -178,7 +178,7 @@ pub(crate) fn records_from_dictionaries( Ok(records) } -fn window_dictionaries() -> Result, AdapterError> { +pub(super) fn window_dictionaries() -> Result, AdapterError> { use crate::tree::properties::cf_type::borrowed_cf_dictionary; use core_graphics::display::CGDisplay; let options = window_list_options(); @@ -335,7 +335,7 @@ fn required_string_field(dict: &WindowDictionary, key: &str) -> Result Option { +pub(super) fn int_field(dict: &WindowDictionary, key: &str) -> Option { use crate::tree::properties::cf_type::borrowed_cf_number; use core_foundation::base::TCFType; @@ -383,7 +383,7 @@ fn rect_field(dict: &WindowDictionary, key: &str) -> Option { }) } -fn int_or_float_field(dict: &WindowDictionary, key: &str) -> Option { +pub(super) fn int_or_float_field(dict: &WindowDictionary, key: &str) -> Option { use crate::tree::properties::cf_type::borrowed_cf_number; use core_foundation::base::TCFType; diff --git a/crates/macos/src/system/window/mod.rs b/crates/macos/src/system/window/mod.rs index 2de9e9b969..27b887c957 100644 --- a/crates/macos/src/system/window/mod.rs +++ b/crates/macos/src/system/window/mod.rs @@ -1,5 +1,6 @@ pub(crate) mod cg_window; pub(crate) mod cg_window_exact; +pub(crate) mod popup_window; pub(crate) mod window_ax_state; pub(crate) mod window_bridge; pub(crate) mod window_frame; diff --git a/crates/macos/src/system/window/popup_window.rs b/crates/macos/src/system/window/popup_window.rs new file mode 100644 index 0000000000..15e27084c7 --- /dev/null +++ b/crates/macos/src/system/window/popup_window.rs @@ -0,0 +1,52 @@ +//! Whether an application shows a window that its accessibility window list +//! leaves out. AppKit draws a popover, an open menu and a sharing picker each +//! in a window of its own that `AXWindows` does not name: a popover at the +//! normal level, a menu or a picker at the pop-up menu level. + +use rustc_hash::FxHashSet; + +use super::cg_window::{bool_field, int_field, int_or_float_field, window_dictionaries}; + +/// `kCGMainMenuWindowLevel` to `kCGStatusWindowLevel`: the menu bar and its +/// status items, which are not surfaces of a window. +const MENU_BAR_LEVELS: std::ops::RangeInclusive = 24..=25; +/// `kCGPopUpMenuWindowLevel`. +const POPUP_MENU_WINDOW_LEVEL: i64 = 101; + +/// Whether an on-screen window can hold a surface the accessibility window +/// list does not name. A closed popover leaves its window on screen at alpha 0. +fn holds_unlisted_surface(layer: i64, alpha: f64, number: i64, listed: &FxHashSet) -> bool { + (0..=POPUP_MENU_WINDOW_LEVEL).contains(&layer) + && !MENU_BAR_LEVELS.contains(&layer) + && alpha > 0.0 + && !listed.contains(&number) +} + +/// Whether `pid` has an on-screen window that none of `listed`, the window ids +/// of its accessibility windows, names. A window list that cannot be read says +/// yes, so a caller searches instead of missing a surface. +pub(crate) fn shows_unlisted_window(pid: i32, listed: &FxHashSet) -> bool { + let Ok(windows) = window_dictionaries() else { + return true; + }; + windows.iter().any(|window| { + int_field(window, "kCGWindowOwnerPID") == Some(i64::from(pid)) + && bool_field(window, "kCGWindowIsOnscreen").unwrap_or(true) + && match ( + int_field(window, "kCGWindowLayer"), + int_field(window, "kCGWindowNumber"), + ) { + (Some(layer), Some(number)) => holds_unlisted_surface( + layer, + int_or_float_field(window, "kCGWindowAlpha").unwrap_or(1.0), + number, + listed, + ), + _ => true, + } + }) +} + +#[cfg(test)] +#[path = "popup_window_tests.rs"] +mod tests; diff --git a/crates/macos/src/system/window/popup_window_tests.rs b/crates/macos/src/system/window/popup_window_tests.rs new file mode 100644 index 0000000000..5f33ef64a2 --- /dev/null +++ b/crates/macos/src/system/window/popup_window_tests.rs @@ -0,0 +1,31 @@ +use super::holds_unlisted_surface; +use rustc_hash::FxHashSet; + +#[test] +fn only_a_shown_window_the_accessibility_list_leaves_out_can_hold_a_surface() { + let listed: FxHashSet = [7].into_iter().collect(); + assert!( + holds_unlisted_surface(0, 1.0, 9, &listed), + "a popover window" + ); + assert!( + holds_unlisted_surface(101, 1.0, 9, &listed), + "a menu or picker" + ); + assert!( + !holds_unlisted_surface(0, 1.0, 7, &listed), + "a listed window" + ); + assert!( + !holds_unlisted_surface(0, 0.0, 9, &listed), + "a closed popover" + ); + assert!( + !holds_unlisted_surface(25, 1.0, 9, &listed), + "a status item" + ); + assert!( + !holds_unlisted_surface(-2147483603, 1.0, 9, &listed), + "the desktop" + ); +} diff --git a/crates/macos/src/tree/adapter.rs b/crates/macos/src/tree/adapter.rs index d07fbbc679..b0dc320ef1 100644 --- a/crates/macos/src/tree/adapter.rs +++ b/crates/macos/src/tree/adapter.rs @@ -116,6 +116,7 @@ impl ObservationOps for MacOSAdapter { deadline: Deadline, ) -> Result, AdapterError> { let mut anchored = Vec::new(); + let mut window = None; #[cfg(target_os = "macos")] if let Ok(anchor) = ax_element(raised_by) { crate::tree::surface_inventory::collect_anchored_surfaces( @@ -123,11 +124,20 @@ impl ObservationOps for MacOSAdapter { deadline, &mut anchored, ); + window = crate::tree::surface_read::element(anchor, "AXWindow", deadline) + .ok() + .flatten(); } - crate::tree::surface_inventory::with_anchored( - self.list_surfaces(process, deadline), - anchored, - ) + let inventory = match window { + Some(window) => crate::system::process::process_identity::require_core(&process) + .and_then(|identity| { + crate::tree::surface_inventory::list_surfaces_in_window( + identity, &window, deadline, + ) + }), + None => self.list_surfaces(process, deadline), + }; + crate::tree::surface_inventory::with_anchored(inventory, anchored) } fn hit_test( diff --git a/crates/macos/src/tree/build_context.rs b/crates/macos/src/tree/build_context.rs index 9dc5c2b51f..8dd1f01725 100644 --- a/crates/macos/src/tree/build_context.rs +++ b/crates/macos/src/tree/build_context.rs @@ -10,6 +10,10 @@ pub(crate) struct TreeBuildContext { } impl TreeBuildContext { + /// The focused element only marks one node as focused. An application + /// whose focus sits in a view another process draws (a share or an AirDrop + /// panel) answers its read with an error, and its tree is still readable, + /// so the tree is built without the mark. pub(crate) fn for_pid_with_deadline( pid: i32, include_bounds: bool, @@ -17,7 +21,9 @@ impl TreeBuildContext { ) -> Result { let app = super::element_for_pid(pid); let focused = - super::resolve::resolve_ax_read::read_element(&app, "AXFocusedUIElement", deadline)?; + super::resolve::resolve_ax_read::read_element(&app, "AXFocusedUIElement", deadline) + .ok() + .flatten(); Ok(Self { focused, window_bounds: None, diff --git a/crates/macos/src/tree/element_bounds.rs b/crates/macos/src/tree/element_bounds.rs index b6e67af589..7f48eb8fae 100644 --- a/crates/macos/src/tree/element_bounds.rs +++ b/crates/macos/src/tree/element_bounds.rs @@ -111,14 +111,22 @@ fn within(surface: Option, clips: &[Option]) -> Option { .fold(surface, |viewport, bounds| narrowed(viewport, *bounds)) } +/// The viewport inside an `AXWindow` ancestor. The element's own `AXWindow` +/// attribute names that window when it answers; an element drawn in a sheet has +/// no such value, so the ancestor the parent walk reached is the owning window. +fn window_viewport( + attribute_window: Option, + ancestor_window: Option, + clips: &[Option], +) -> Option { + within(attribute_window.or(ancestor_window), clips) +} + pub(crate) fn ancestor_viewport( element: &AXElement, deadline: Deadline, ) -> Result, AdapterError> { let window = owning_window_bounds(element, deadline)?; - if window.is_none() { - return Ok(None); - } let instant = deadline; let mut clips = Vec::new(); let mut current = super::surface_read::element(element, "AXParent", instant)?; @@ -141,11 +149,15 @@ pub(crate) fn ancestor_viewport( let surface = read_bounds_with_deadline(&parent, instant)?; return Ok(within(surface, &clips)); } - if clips_descendants(&role) { - clips.push(read_bounds_with_deadline(&parent, instant)?); - } + let own_bounds = if clips_descendants(&role) { + let bounds = read_bounds_with_deadline(&parent, instant)?; + clips.push(bounds); + bounds + } else { + None + }; if role == "AXWindow" { - return Ok(within(window, &clips)); + return Ok(window_viewport(window, own_bounds, &clips)); } current = super::surface_read::element(&parent, "AXParent", instant)?; } @@ -287,6 +299,21 @@ mod tests { assert_eq!(within(popover, &[None]), None); } + #[test] + fn an_element_with_no_window_attribute_is_clipped_by_its_window_ancestor() { + let window = Some(rect(100.0, 600.0)); + let sheet = Some(rect(50.0, 800.0)); + assert_eq!(window_viewport(None, window, &[sheet, window]), window); + assert_eq!(window_viewport(None, None, &[sheet]), None); + } + + #[test] + fn the_window_attribute_wins_over_the_ancestor_window() { + let attributed = Some(rect(100.0, 600.0)); + let ancestor = Some(rect(0.0, 50.0)); + assert_eq!(window_viewport(attributed, ancestor, &[]), attributed); + } + #[test] fn missing_clipping_geometry_is_unknown_not_empty() { assert_eq!( diff --git a/crates/macos/src/tree/mod.rs b/crates/macos/src/tree/mod.rs index 4809c51e71..a514e905d7 100644 --- a/crates/macos/src/tree/mod.rs +++ b/crates/macos/src/tree/mod.rs @@ -19,6 +19,7 @@ pub(crate) mod resolve; pub(crate) mod roles; pub(crate) mod shell_surface; pub(crate) mod state_reader; +pub(crate) mod surface_ids; pub(crate) mod surface_inventory; pub(crate) mod surface_read; pub(crate) mod surfaces; diff --git a/crates/macos/src/tree/surface_ids.rs b/crates/macos/src/tree/surface_ids.rs new file mode 100644 index 0000000000..60087928c9 --- /dev/null +++ b/crates/macos/src/tree/surface_ids.rs @@ -0,0 +1,154 @@ +use agent_desktop_core::SurfaceInfo; + +/// One window as the inventory read it, before the surfaces it presents are +/// turned into [`SurfaceInfo`] ids. Keeping the two steps apart lets the id +/// rules be exercised without a desktop. +pub(crate) struct WindowObservation { + pub(crate) number: Option, + pub(crate) kind: Option<&'static str>, + pub(crate) title: Option, + pub(crate) children: Vec, + pub(crate) popover: ObservedPopover, +} + +/// A direct child of a window that is itself a surface. +pub(crate) struct ChildSurface { + pub(crate) number: Option, + pub(crate) kind: &'static str, + pub(crate) title: Option, + pub(crate) index: usize, +} + +/// What the bounded popover search of one window settled on. +pub(crate) enum ObservedPopover { + /// The search read every element and found no popover. + Absent, + /// The search was cut at its element limit or left a container closed, so + /// a popover may be there and was not read. + Unread { title: Option }, + Found { + number: Option, + title: Option, + }, +} + +/// The surfaces one window presents, identified by stable AX window numbers. +/// +/// A window's id is its own number, the one `list-windows` reports as +/// `w-`. An unlisted popover uses its own number too, and a surface +/// presented inside a window that has no number of its own uses its parent's +/// stable id plus its kind and position among that parent's children. Closing +/// an earlier window then never re-ids a surface that survives it, which a +/// signal diff would otherwise read as one dismissal and one appearance. +/// +/// Only what cannot be identified is reported unread: a window whose own +/// number is missing still lists a surface that carries a number of its own, +/// and a plain window it presents nothing on adds no entry at all. +pub(crate) fn window_surfaces(window: WindowObservation) -> Vec { + let window_id = window.number.filter(|number| *number > 0).map(surface_id); + let mut surfaces = Vec::new(); + let mut unread = Vec::new(); + if let Some(kind) = window.kind { + match window_id.as_deref() { + Some(id) => surfaces.push(surface(id.to_owned(), kind, window.title.clone())), + None => push_unread_kind(&mut unread, kind), + } + } + for child in window.children { + match ( + child.number.filter(|number| *number > 0), + window_id.as_deref(), + ) { + (Some(number), _) => { + surfaces.push(surface(surface_id(number), child.kind, child.title)) + } + (None, Some(id)) => surfaces.push(surface( + format!("{id}/{}/{}", child.kind, child.index), + child.kind, + child.title, + )), + (None, None) => push_unread_kind(&mut unread, child.kind), + } + } + match (window.popover, window_id.as_deref()) { + (ObservedPopover::Absent, _) => {} + (ObservedPopover::Unread { title }, Some(id)) => { + mark_popover_unread(&mut surfaces, id, title) + } + (ObservedPopover::Unread { .. }, None) => push_unread_kind(&mut unread, "popover"), + (ObservedPopover::Found { number, title }, parent) => { + match (number.filter(|number| *number > 0), parent) { + (Some(number), _) => surfaces.push(surface(surface_id(number), "popover", title)), + (None, Some(id)) => { + surfaces.push(surface(format!("{id}/popover"), "popover", title)) + } + (None, None) => push_unread_kind(&mut unread, "popover"), + } + } + } + if !unread.is_empty() { + surfaces.push(unread_window(unread)); + } + surfaces +} + +fn push_unread_kind(unread: &mut Vec<&'static str>, kind: &'static str) { + if !unread.contains(&kind) { + unread.push(kind); + } +} + +/// A window whose own AX window number cannot be read, listing the kinds it +/// could present that were not identified. Marking them unread keeps a missing +/// entry from reading as an observed absence. +fn unread_window(kinds: Vec<&'static str>) -> SurfaceInfo { + SurfaceInfo { + id: "window/unread".into(), + kind: "window".into(), + title: None, + item_count: None, + unclassified: kinds.into_iter().map(str::to_string).collect(), + } +} + +pub(crate) fn surface(id: String, kind: &str, title: Option) -> SurfaceInfo { + SurfaceInfo { + id, + kind: kind.into(), + title, + item_count: None, + unclassified: Vec::new(), + } +} + +/// Adds `surface` unless the inventory already lists that id as that kind: one +/// window can be reached both as a window and as a surface of its own, and a +/// surface read twice is still one surface. +pub(crate) fn push_unique(surfaces: &mut Vec, surface: SurfaceInfo) { + let listed = surfaces + .iter() + .any(|listed| listed.id == surface.id && listed.kind == surface.kind); + if !listed { + surfaces.push(surface); + } +} + +/// The id `list-windows` and `snapshot --window-id` use for the same window. +pub(crate) fn surface_id(number: i64) -> String { + format!("w-{number}") +} + +fn mark_popover_unread(surfaces: &mut Vec, window_id: &str, title: Option) { + match surfaces.iter_mut().find(|entry| entry.id == window_id) { + Some(entry) => entry.unclassified.push("popover".into()), + None => { + let mut entry = surface(window_id.to_owned(), "window", title); + entry.unclassified.push("popover".into()); + surfaces.push(entry); + } + } +} + +#[cfg(test)] +#[path = "surface_ids_tests.rs"] +mod tests; diff --git a/crates/macos/src/tree/surface_ids_tests.rs b/crates/macos/src/tree/surface_ids_tests.rs new file mode 100644 index 0000000000..42fd4b8efd --- /dev/null +++ b/crates/macos/src/tree/surface_ids_tests.rs @@ -0,0 +1,246 @@ +use super::*; +use agent_desktop_core::{ + EventKind, ProcessId, SignalBaseline, SignalCompleteness, SnapshotSurface, SurfaceSignal, + diff_signals, +}; + +fn window( + number: Option, + children: Vec, + popover: ObservedPopover, +) -> WindowObservation { + WindowObservation { + number, + kind: None, + title: Some("Document".into()), + children, + popover, + } +} + +fn sheet() -> ChildSurface { + ChildSurface { + number: None, + kind: "sheet", + title: Some("Sheet".into()), + index: 0, + } +} + +fn ids(surfaces: &[SurfaceInfo]) -> Vec<&str> { + surfaces.iter().map(|surface| surface.id.as_str()).collect() +} + +#[test] +fn a_window_is_identified_by_its_ax_window_number() { + let surfaces = window_surfaces(window(Some(42), vec![sheet()], ObservedPopover::Absent)); + assert_eq!(ids(&surfaces), ["w-42/sheet/0"]); +} + +#[test] +fn a_surface_with_its_own_window_number_keeps_that_number() { + let surfaces = window_surfaces(window( + Some(42), + vec![ChildSurface { + number: Some(51), + kind: "sheet", + title: Some("Save".into()), + index: 0, + }], + ObservedPopover::Found { + number: Some(52), + title: Some("Filters".into()), + }, + )); + assert_eq!(ids(&surfaces), ["w-51", "w-52"]); +} + +#[test] +fn closing_an_earlier_window_never_re_ids_a_surviving_surface() { + let before = [ + window( + Some(11), + vec![sheet()], + ObservedPopover::Found { + number: None, + title: Some("Filters".into()), + }, + ), + window( + Some(42), + vec![sheet()], + ObservedPopover::Found { + number: None, + title: Some("Options".into()), + }, + ), + ] + .into_iter() + .flat_map(window_surfaces) + .collect::>(); + let after = [window( + Some(42), + vec![sheet()], + ObservedPopover::Found { + number: None, + title: Some("Options".into()), + }, + )] + .into_iter() + .flat_map(window_surfaces) + .collect::>(); + + assert_eq!( + ids(&before), + [ + "w-11/sheet/0", + "w-11/popover", + "w-42/sheet/0", + "w-42/popover" + ] + ); + assert_eq!(ids(&after), ["w-42/sheet/0", "w-42/popover"]); + + let events = diff_signals(&baseline(before), &baseline(after)); + assert!( + events + .iter() + .all(|event| !matches!(event.kind, EventKind::SurfaceAppeared { .. })), + "closing the first window re-identified the second window's surfaces: {events:?}" + ); + assert!( + events + .iter() + .filter(|event| matches!(event.kind, EventKind::SurfaceDismissed { .. })) + .count() + == 2, + "only the closed window's surfaces were dismissed: {events:?}" + ); +} + +fn baseline(surfaces: Vec) -> SignalBaseline { + SignalBaseline { + windows: Vec::new(), + apps: Vec::new(), + surfaces: surfaces + .into_iter() + .filter_map(|surface| { + Some(SurfaceSignal { + kind: kind_of_listed(&surface.kind)?, + app: "SurfaceApp".into(), + pid: ProcessId::new(42), + process_instance: "instance-42".into(), + id: surface.id, + title: surface.title, + }) + }) + .collect(), + completeness: SignalCompleteness::complete(), + } +} + +fn kind_of_listed(kind: &str) -> Option { + match kind { + "sheet" => Some(SnapshotSurface::Sheet), + "popover" => Some(SnapshotSurface::Popover), + "alert" => Some(SnapshotSurface::Alert), + "menu" | "context_menu" => Some(SnapshotSurface::Menu), + _ => None, + } +} + +#[test] +fn an_unnumbered_window_lists_a_surface_that_carries_its_own_number() { + let surfaces = window_surfaces(window( + None, + vec![ChildSurface { + number: Some(51), + kind: "sheet", + title: Some("Save".into()), + index: 0, + }], + ObservedPopover::Absent, + )); + assert_eq!(ids(&surfaces), ["w-51"]); +} + +#[test] +fn an_unnumbered_window_reports_only_the_kinds_it_could_not_identify() { + let surfaces = window_surfaces(window( + None, + vec![sheet()], + ObservedPopover::Unread { + title: Some("Document".into()), + }, + )); + assert_eq!(ids(&surfaces), ["window/unread"]); + assert_eq!(surfaces[0].kind, "window"); + assert_eq!(surfaces[0].unclassified, ["sheet", "popover"]); + assert_eq!(surfaces[0].title, None); +} + +#[test] +fn a_plain_unnumbered_window_lists_nothing() { + let surfaces = window_surfaces(window(None, Vec::new(), ObservedPopover::Absent)); + assert!(surfaces.is_empty()); +} + +#[test] +fn a_cut_popover_search_names_popover_unread_on_the_window() { + let surfaces = window_surfaces(window( + Some(7), + Vec::new(), + ObservedPopover::Unread { + title: Some("Document".into()), + }, + )); + assert_eq!(ids(&surfaces), ["w-7"]); + assert_eq!(surfaces[0].kind, "window"); + assert_eq!(surfaces[0].unclassified, ["popover"]); + + let marked = window_surfaces(window( + Some(7), + Vec::new(), + ObservedPopover::Unread { title: None }, + )); + assert_eq!(marked[0].unclassified, ["popover"]); +} + +#[test] +fn a_complete_popover_search_without_a_popover_lists_nothing() { + let surfaces = window_surfaces(window(Some(7), Vec::new(), ObservedPopover::Absent)); + assert!(surfaces.is_empty()); +} + +#[test] +fn duplicate_reads_of_one_surface_are_listed_once() { + let mut surfaces = vec![SurfaceInfo { + id: "w-51".into(), + kind: "sheet".into(), + title: None, + item_count: None, + unclassified: Vec::new(), + }]; + push_unique( + &mut surfaces, + SurfaceInfo { + id: "w-51".into(), + kind: "sheet".into(), + title: None, + item_count: None, + unclassified: Vec::new(), + }, + ); + push_unique( + &mut surfaces, + SurfaceInfo { + id: "w-51".into(), + kind: "popover".into(), + title: None, + item_count: None, + unclassified: Vec::new(), + }, + ); + assert_eq!(ids(&surfaces), ["w-51", "w-51"]); + assert_eq!(surfaces[1].kind, "popover"); +} diff --git a/crates/macos/src/tree/surface_inventory.rs b/crates/macos/src/tree/surface_inventory.rs index fb11943827..8ce9886d9c 100644 --- a/crates/macos/src/tree/surface_inventory.rs +++ b/crates/macos/src/tree/surface_inventory.rs @@ -1,27 +1,61 @@ use crate::tree::{AXElement, properties::element::element_for_pid}; use agent_desktop_core::{AdapterError, Deadline, SurfaceInfo}; +use super::surface_ids::{ + ChildSurface, ObservedPopover, WindowObservation, push_unique, surface, surface_id, + window_surfaces, +}; + /// The most children an element that anchors a surface has. An element with /// more is a content container: a list, a table or a column of a browser. pub(crate) const ANCHOR_CHILD_LIMIT: usize = 16; +/// The surfaces of every window of the process, and its open menus. pub(crate) fn list_surfaces_for_process( identity: crate::system::process::process_identity::ProcessIdentity, deadline: Deadline, ) -> Result, AdapterError> { + let app = element_for_pid(identity.pid()); super::app_menu::observe(identity, deadline, || { - list_surfaces_once(identity.pid(), deadline) + let windows = read_array(&app, "AXWindows", deadline)?.unwrap_or_default(); + let listed = windows + .iter() + .filter_map(|window| window_number(window, deadline).ok().flatten()) + .collect(); + let popovers = + crate::system::window::popup_window::shows_unlisted_window(identity.pid(), &listed); + list_surfaces_once(identity.pid(), deadline, popovers, || Ok(windows)) }) } -fn list_surfaces_once(pid: i32, deadline: Deadline) -> Result, AdapterError> { - let app = element_for_pid(pid); +/// The surfaces of one window, and the open menus of its process: what an +/// action on an element of that window can have raised. A popover that opens +/// later is found by `wait --surface`, so the action pays no popover search. +pub(crate) fn list_surfaces_in_window( + identity: crate::system::process::process_identity::ProcessIdentity, + window: &AXElement, + deadline: Deadline, +) -> Result, AdapterError> { + super::app_menu::observe(identity, deadline, || { + list_surfaces_once(identity.pid(), deadline, false, || Ok(vec![window.clone()])) + }) +} + +fn list_surfaces_once( + pid: i32, + deadline: Deadline, + popovers: bool, + windows: impl FnOnce() -> Result, AdapterError>, +) -> Result, AdapterError> { list_surfaces_with( deadline, || { let mut surfaces = Vec::new(); - if let Some(window) = read_element(&app, "AXFocusedWindow", deadline)? { - collect_window_surfaces(&window, "focused-window", deadline, &mut surfaces)?; + for window in windows()? { + let observed = observe_window(&window, deadline, popovers)?; + for surface in window_surfaces(observed) { + push_unique(&mut surfaces, surface); + } } Ok(surfaces) }, @@ -35,6 +69,76 @@ fn list_surfaces_once(pid: i32, deadline: Deadline) -> Result, ) } +/// Reads one window, and searches it for a popover when the application shows +/// a window its accessibility window list leaves out. +fn observe_window( + window: &AXElement, + deadline: Deadline, + popovers: bool, +) -> Result { + let number = window_number(window, deadline)?; + let mut children = Vec::new(); + let listed = read_array(window, "AXChildren", deadline)?.unwrap_or_default(); + for (index, child) in listed.iter().enumerate() { + let Some(kind) = surface_kind(child, deadline)? else { + continue; + }; + children.push(ChildSurface { + number: window_number(child, deadline)?, + kind, + title: read_title(child, deadline)?, + index, + }); + } + let popover = if popovers && !children.iter().any(|child| child.kind == "popover") { + observe_popover(window, deadline)? + } else { + ObservedPopover::Absent + }; + Ok(WindowObservation { + number, + kind: surface_kind(window, deadline)?, + title: read_title(window, deadline)?, + children, + popover, + }) +} + +/// The bounded popover search of one window. A search that read every element +/// and found no popover settles an absence; a search cut at its element limit +/// names `popover` unclassified instead, so a popover it could not read is +/// never reported as one the application does not show. Any other failure is +/// the read's own and propagates. +fn observe_popover( + window: &AXElement, + deadline: Deadline, +) -> Result { + match super::surfaces::popover_in_window(window, deadline) { + Ok(Some(popover)) => Ok(ObservedPopover::Found { + number: window_number(&popover, deadline)?, + title: read_title(&popover, deadline)?, + }), + Ok(None) => Ok(ObservedPopover::Absent), + Err(error) if is_incomplete(&error) => Ok(ObservedPopover::Unread { + title: read_title(window, deadline)?, + }), + Err(error) => Err(error), + } +} + +fn window_number(element: &AXElement, deadline: Deadline) -> Result, AdapterError> { + let number = + crate::system::window::window_resolve::ax_window_id_with_deadline(element, deadline)?; + Ok(number.filter(|number| *number > 0)) +} + +fn is_incomplete(error: &AdapterError) -> bool { + error + .details + .as_ref() + .is_some_and(|details| details["complete"] == false) +} + fn list_surfaces_with( deadline: Deadline, window_surfaces: impl FnOnce() -> Result, AdapterError>, @@ -86,8 +190,24 @@ pub(crate) fn collect_anchored_surfaces( children.as_concrete_TypeRef(), deadline, ); - if anchors_few_children(count.ok()) { - let _ = collect_window_surfaces(anchor, "target", deadline, surfaces); + if !anchors_few_children(count.ok()) { + return; + } + let Ok(listed) = read_array(anchor, "AXChildren", deadline) else { + return; + }; + for (index, child) in listed.unwrap_or_default().iter().enumerate() { + let Ok(Some(kind)) = surface_kind(child, deadline) else { + continue; + }; + let Ok(title) = read_title(child, deadline) else { + continue; + }; + let id = window_number(child, deadline) + .ok() + .flatten() + .map_or_else(|| format!("target/{kind}/{index}"), surface_id); + surfaces.push(surface(id, kind, title)); } } @@ -113,44 +233,15 @@ fn anchors_few_children(count: Option) -> bool { count.is_some_and(|count| (1..=ANCHOR_CHILD_LIMIT).contains(&count)) } -fn collect_window_surfaces( - window: &AXElement, - window_id: &str, - deadline: Deadline, - surfaces: &mut Vec, -) -> Result<(), AdapterError> { - if let Some(kind) = surface_kind(window, deadline)? { - surfaces.push(SurfaceInfo { - id: window_id.to_string(), - kind: kind.into(), - title: read_title(window, deadline)?, - item_count: None, - unclassified: Vec::new(), - }); - } - let Some(children) = read_array(window, "AXChildren", deadline)? else { - return Ok(()); - }; - for (index, child) in children.iter().enumerate() { - if let Some(kind) = surface_kind(child, deadline)? { - surfaces.push(SurfaceInfo { - id: format!("{window_id}/children/{index}"), - kind: kind.into(), - title: read_title(child, deadline)?, - item_count: None, - unclassified: Vec::new(), - }); - } - } - Ok(()) -} - fn surface_kind( element: &AXElement, deadline: Deadline, ) -> Result, AdapterError> { let role = read_string(element, "AXRole", deadline)?; - let subrole = read_string(element, "AXSubrole", deadline)?; + let subrole = match role.as_deref() { + Some("AXWindow") => read_string(element, "AXSubrole", deadline)?, + _ => None, + }; let dialog = subrole.as_deref() == Some("AXDialog"); let (modal, minimized) = if dialog { ( @@ -171,7 +262,10 @@ fn surface_kind( /// The kind of surface an element is. `AXDialog` is a window style, not a /// prompt: a fixed-size ordinary window carries it too. A dialog is an alert /// only when it is modal, and a minimized window is on the Dock, never in -/// front of the application, so it holds nothing up whatever it carries. +/// front of the application, so it holds nothing up whatever it carries. A +/// system dialog is the window a system service opens for an application, +/// such as the AirDrop panel of a share, and is always an alert. A dialog +/// subrole belongs to a window, so only a window's subrole is read. fn classify_surface( role: Option<&str>, subrole: Option<&str>, @@ -181,7 +275,7 @@ fn classify_surface( match subrole { Some("AXSheet") => Some("sheet"), Some("AXPopover") => Some("popover"), - Some("AXAlert") => Some("alert"), + Some("AXAlert" | "AXSystemDialog") => Some("alert"), Some("AXDialog") if modal == Some(true) && minimized != Some(true) => Some("alert"), Some("AXDialog") => None, _ => match role { @@ -215,14 +309,6 @@ fn read_array( crate::tree::surface_read::elements(element, attribute, deadline).map(Some) } -fn read_element( - element: &AXElement, - attribute: &str, - deadline: Deadline, -) -> Result, AdapterError> { - crate::tree::surface_read::element(element, attribute, deadline) -} - fn ensure_before_deadline(deadline: Deadline) -> Result<(), AdapterError> { crate::tree::surface_read::ensure_before_deadline(deadline) } diff --git a/crates/macos/src/tree/surface_inventory_tests.rs b/crates/macos/src/tree/surface_inventory_tests.rs index 6ceda9965d..e83ee76f0a 100644 --- a/crates/macos/src/tree/surface_inventory_tests.rs +++ b/crates/macos/src/tree/surface_inventory_tests.rs @@ -14,9 +14,9 @@ fn surface(id: &str, kind: &str) -> SurfaceInfo { #[test] fn shared_menu_discovery_preserves_other_surfaces_and_existing_menu_ids() { let window_surfaces = vec![ - surface("focused-window", "sheet"), - surface("focused-window/children/2", "popover"), - surface("focused-window/children/4", "alert"), + surface("w-7", "sheet"), + surface("w-9", "popover"), + surface("w-11", "alert"), ]; for menus in [ vec![], @@ -149,8 +149,23 @@ fn sheets_popovers_and_alert_subroles_keep_their_kinds() { classify_surface(Some("AXWindow"), Some("AXAlert"), None, Some(false)), Some("alert") ); + assert_eq!( + classify_surface(Some("AXWindow"), Some("AXSystemDialog"), None, None), + Some("alert") + ); assert_eq!( classify_surface(Some("AXWindow"), Some("AXStandardWindow"), None, None), None ); } + +#[test] +fn an_unclassified_read_is_incomplete_and_a_settled_absence_is_not() { + let cut = AdapterError::new(agent_desktop_core::ErrorCode::ElementNotFound, "cut") + .with_details(serde_json::json!({ "complete": false })); + assert!(is_incomplete(&cut)); + assert!(!is_incomplete(&AdapterError::new( + agent_desktop_core::ErrorCode::ElementNotFound, + "gone" + ))); +} diff --git a/crates/macos/src/tree/surfaces.rs b/crates/macos/src/tree/surfaces.rs index 0a92bb9a75..70415b157d 100644 --- a/crates/macos/src/tree/surfaces.rs +++ b/crates/macos/src/tree/surfaces.rs @@ -96,7 +96,7 @@ pub(crate) fn surface_in_window( /// element: one cut at its element limit fails as not found and says it is /// incomplete. #[cfg(target_os = "macos")] -fn popover_in_window( +pub(super) fn popover_in_window( window: &AXElement, deadline: Deadline, ) -> Result, AdapterError> { @@ -217,7 +217,7 @@ pub(super) fn is_alert(element: &AXElement, deadline: Deadline) -> Result Value { match walk_uia_subtree( root, &ObservationRoot::Window(&window), + SnapshotSurface::Window, WalkBudget::new(u8::MAX, deadline), false, ) { diff --git a/crates/windows/src/adapter.rs b/crates/windows/src/adapter.rs index a067e600ea..820fc1d6bb 100644 --- a/crates/windows/src/adapter.rs +++ b/crates/windows/src/adapter.rs @@ -56,6 +56,46 @@ impl Default for WindowsAdapter { } impl ObservationOps for WindowsAdapter { + /// A popover belongs to the application, not to a census window: its refs + /// stay observable while the process lives, and `surface_window` records + /// the popover a capture read so resolution lands on that one. + fn is_application_surface(&self, surface: SnapshotSurface) -> bool { + surface == SnapshotSurface::Popover + } + + /// A popover is presented by a popup window of its own, so a capture names + /// that window. With several popovers open, the refs it allocates then + /// resolve against the popover that was read instead of whichever the + /// process happens to show first. + fn surface_window( + &self, + app: &agent_desktop_core::AppInfo, + surface: SnapshotSurface, + deadline: Deadline, + ) -> Result, AdapterError> { + if surface != SnapshotSurface::Popover { + return Ok(None); + } + crate::tree::popover_choice::popover_window(app, deadline).map(Some) + } + + /// A stored popover ref, or a capture that named one with `--window-id`, + /// names the popover it means, so it resolves against that window and + /// never against whichever popover the process shows first. + fn recorded_surface_window( + &self, + process: agent_desktop_core::ProcessIdentity, + window_id: &str, + surface: SnapshotSurface, + deadline: Deadline, + ) -> Result, AdapterError> { + if surface != SnapshotSurface::Popover { + return Ok(None); + } + crate::tree::popover_choice::recorded_popover_window(&process, window_id, deadline) + .map(Some) + } + fn observe_tree( &self, root: ObservationRoot<'_>, diff --git a/crates/windows/src/system/adapter.rs b/crates/windows/src/system/adapter.rs index 0dc909bafa..be6d1b65a8 100644 --- a/crates/windows/src/system/adapter.rs +++ b/crates/windows/src/system/adapter.rs @@ -1,7 +1,7 @@ use agent_desktop_core::{ ActionResult, AdapterError, AdapterSession, AppInfo, Deadline, DeliverySemantics, - DismissAllNotificationsRequest, DismissNotificationRequest, DisplayInfo, FrontView, - FrontWindow, ImageBuffer, InteractionLease, InteractionPolicy, KeyCombo, + DismissAllNotificationsRequest, DismissNotificationRequest, DisplayInfo, FrontProcess, + FrontView, FrontWindow, ImageBuffer, InteractionLease, InteractionPolicy, KeyCombo, NotificationActionRequest, NotificationFilter, NotificationInfo, ObservationOps, OperationReport, PermissionReport, ProcessIdentity, ScreenshotTarget, SessionAffinity, SignalBaseline, SignalFilter, SnapshotSurface, SurfaceOpening, SystemOps, WindowFilter, @@ -9,8 +9,7 @@ use agent_desktop_core::{ system::process_state::ProcessState, }; -use crate::{adapter::WindowsAdapter, system::escape_popup}; - +use crate::{adapter::WindowsAdapter, system::escape_popup, system::window::window_front}; #[cfg(target_os = "windows")] #[path = "tcp_listener.rs"] pub(crate) mod tcp_listener; @@ -113,6 +112,7 @@ impl SystemOps for WindowsAdapter { SnapshotSurface::Focused, SnapshotSurface::Sheet, SnapshotSurface::Menu, + SnapshotSurface::Popover, SnapshotSurface::StartMenu, SnapshotSurface::Taskbar, SnapshotSurface::SystemTray, @@ -196,15 +196,15 @@ impl SystemOps for WindowsAdapter { } fn read_front(&self, deadline: Deadline) -> Result { - crate::system::window::window_front::read_front(deadline) + window_front::read_front(deadline) } - fn front_process(&self, pid: u32) -> Option { - crate::system::window::window_front::front_process(pid) + fn front_process(&self, pid: u32) -> Option { + window_front::front_process(pid) } fn spawned_descendants(&self, root: u32, since_ms: u64) -> Option> { - crate::system::window::window_front::spawned_descendants(root, since_ms) + window_front::spawned_descendants(root, since_ms) } fn keep_below( @@ -213,11 +213,11 @@ impl SystemOps for WindowsAdapter { above: &FrontWindow, _lease: &InteractionLease, ) -> Result<(), AdapterError> { - crate::system::window::window_front::keep_below(window, above) + window_front::keep_below(window, above) } fn give_back(&self, win: &FrontWindow, lease: &InteractionLease) -> Result<(), AdapterError> { - crate::system::window::window_front::give_back(win, lease) + window_front::give_back(win, lease) } fn window_op( diff --git a/crates/windows/src/system/adapter_tests.rs b/crates/windows/src/system/adapter_tests.rs index 87976a6fa4..796fc65ad5 100644 --- a/crates/windows/src/system/adapter_tests.rs +++ b/crates/windows/src/system/adapter_tests.rs @@ -149,7 +149,7 @@ fn screenshot_window_frame_is_wired_through_system_ops_to_the_exact_window_captu /// the "advertised" side of the advertise/resolve/emit equality the live /// tests pin. #[test] -fn supported_surfaces_advertises_window_focused_sheet_menu_and_shell_kinds() { +fn supported_surfaces_advertises_window_focused_sheet_menu_popover_and_shell_kinds() { let adapter = WindowsAdapter::new(); assert_eq!( adapter.supported_surfaces(), @@ -158,6 +158,7 @@ fn supported_surfaces_advertises_window_focused_sheet_menu_and_shell_kinds() { SnapshotSurface::Focused, SnapshotSurface::Sheet, SnapshotSurface::Menu, + SnapshotSurface::Popover, SnapshotSurface::StartMenu, SnapshotSurface::Taskbar, SnapshotSurface::SystemTray, diff --git a/crates/windows/src/tree/mod.rs b/crates/windows/src/tree/mod.rs index 29ef54d120..571fb1044e 100644 --- a/crates/windows/src/tree/mod.rs +++ b/crates/windows/src/tree/mod.rs @@ -8,6 +8,8 @@ pub(crate) mod live_read; pub(crate) mod minimized; pub mod name_evidence; pub(crate) mod observe; +pub(crate) mod popover_choice; +pub(crate) mod popover_inventory; pub(crate) mod resolve; pub mod roles; pub mod states; diff --git a/crates/windows/src/tree/observe.rs b/crates/windows/src/tree/observe.rs index 69443d3934..8707812552 100644 --- a/crates/windows/src/tree/observe.rs +++ b/crates/windows/src/tree/observe.rs @@ -58,6 +58,7 @@ pub(crate) fn observe_tree( let outcome = walk_uia_subtree( &element, &root, + request.surface, budget, request.observation_mode.identity_only, )?; @@ -174,8 +175,8 @@ fn still_thin_after_settle() -> AdapterError { /// Rechecks stored ownership and generation evidence after the UIA read. fn re_verify_root(root: ObservationRoot<'_>) -> Result<(), AdapterError> { match root { - ObservationRoot::Application { .. } => { - Err(AdapterError::not_supported("application observation root")) + ObservationRoot::Application { app, .. } => { + verify_process_identity(app.pid, app.process_instance.as_deref()) } ObservationRoot::Window(window) => { let handle = hwnd_of(&window.id)?; diff --git a/crates/windows/src/tree/popover_choice.rs b/crates/windows/src/tree/popover_choice.rs new file mode 100644 index 0000000000..0b77b21541 --- /dev/null +++ b/crates/windows/src/tree/popover_choice.rs @@ -0,0 +1,158 @@ +use agent_desktop_core::{ + AdapterError, AppInfo, Deadline, ErrorCode, ProcessId, ProcessIdentity, WindowInfo, +}; + +use super::surface_inventory::windows_of; +use crate::system::window::window_enum::{EnumeratedWindow, WindowHandle}; +use crate::system::window::window_identity::live_window_title; + +/// The popover a snapshot, a surface read or a stored ref means. +/// +/// A named id must still be one of the process's open popovers: a handle the +/// process no longer presents that way is refused, never followed. With no id +/// there must be exactly one open popover. Several open popovers are refused +/// with their ids rather than resolved to the first, because the caller named +/// none and picking one would land on a popover it never read. +pub(crate) fn resolve_popover( + pid: ProcessId, + named: Option<&str>, + deadline: Deadline, +) -> Result { + let open = windows_of(pid, deadline)?.1; + let handles = open + .iter() + .map(|popover| popover.handle) + .collect::>(); + let handle = choose_popover(&handles, named)?; + open.into_iter() + .find(|popover| popover.handle == handle) + .ok_or_else(no_popover) +} + +/// The window a fresh popover capture is rooted at, identified by the same +/// `w-` id `list-surfaces` reports, so the refs it allocates resolve +/// against the popover that was read. The bounds stay unset: the popover is +/// not a census window, and a window-relative bounds space would change what +/// every ref in it means. +pub(crate) fn popover_window( + app: &AppInfo, + deadline: Deadline, +) -> Result { + let popover = resolve_popover(app.pid, None, deadline)?; + Ok(popover_info( + app.name.clone(), + app.pid, + app.process_instance.clone(), + popover, + )) +} + +/// The popover window a caller named: a stored ref's recorded id, or the +/// `--window-id` of a capture. The id must still name an open popover of that +/// exact process instance: a closed popover, or one owned by a newer process +/// that reused the pid, is refused instead of resolved. +pub(crate) fn recorded_popover_window( + process: &ProcessIdentity, + window_id: &str, + deadline: Deadline, +) -> Result { + if !crate::system::process_identity::matches_instance(process.pid, &process.instance)? { + return Err(popover_closed(window_id, &[])); + } + let popover = resolve_popover(process.pid, Some(window_id), deadline)?; + Ok(popover_info( + crate::system::process_identity::process_image_name(process.pid).unwrap_or_default(), + process.pid, + Some(process.instance.clone()), + popover, + )) +} + +fn popover_info( + app: String, + pid: ProcessId, + process_instance: Option, + popover: EnumeratedWindow, +) -> WindowInfo { + WindowInfo { + id: handle_id(popover.handle), + title: live_window_title(popover.handle).unwrap_or_default(), + app, + pid, + process_instance, + bounds: None, + state: Default::default(), + } +} + +/// The popover handle a caller means, from the process's open popover handles. +fn choose_popover( + open: &[WindowHandle], + named: Option<&str>, +) -> Result { + match named { + Some(id) => open + .iter() + .copied() + .find(|handle| handle_id(*handle) == id) + .ok_or_else(|| popover_closed(id, open)), + None => match open { + [] => Err(no_popover()), + [only] => Ok(*only), + [_, _, ..] => Err(ambiguous_popover(open)), + }, + } +} + +/// The id every window-backed surface on this platform carries, and the id +/// `list-surfaces` reports for the same window. +pub(super) fn handle_id(handle: WindowHandle) -> String { + format!("w-{}", handle as usize) +} + +fn no_popover() -> AdapterError { + AdapterError::new( + ErrorCode::WindowNotFound, + "No popover is open in this application", + ) +} + +fn popover_closed(named: &str, open: &[WindowHandle]) -> AdapterError { + AdapterError::new( + ErrorCode::WindowNotFound, + "The window is not an open popover of this application", + ) + .with_details(serde_json::json!({ + "kind": "popover_closed", + "window_id": named, + "candidates": open.iter().map(|handle| handle_id(*handle)).collect::>(), + })) + .with_suggestion( + "Run 'list-surfaces' to see the open popover ids, then target the one you mean.", + ) +} + +fn ambiguous_popover(open: &[WindowHandle]) -> AdapterError { + let candidates = open + .iter() + .map(|handle| handle_id(*handle)) + .collect::>(); + AdapterError::new( + ErrorCode::AmbiguousTarget, + format!( + "More than one popover is open in this application: {}", + candidates.join(", ") + ), + ) + .with_details(serde_json::json!({ + "kind": "popover_ambiguous", + "candidates": candidates, + })) + .with_suggestion( + "Run 'list-surfaces' to see the open popover ids, then read one with 'snapshot --surface popover --app --window-id ', or close the popovers you do not need.", + ) +} + +#[cfg(test)] +#[path = "popover_choice_tests.rs"] +mod tests; diff --git a/crates/windows/src/tree/popover_choice_tests.rs b/crates/windows/src/tree/popover_choice_tests.rs new file mode 100644 index 0000000000..cd8c2772f9 --- /dev/null +++ b/crates/windows/src/tree/popover_choice_tests.rs @@ -0,0 +1,59 @@ +//! Popover selection: which open popover a capture, a surface read or a stored +//! ref lands on when the process has none, one or several. + +use super::{choose_popover, handle_id}; +use crate::system::window::window_enum::WindowHandle; +use agent_desktop_core::ErrorCode; +use serde_json::json; + +fn handle(number: usize) -> WindowHandle { + number as WindowHandle +} + +#[test] +fn two_open_popovers_without_an_id_are_refused_with_their_ids() { + let error = choose_popover(&[handle(17), handle(34)], None).unwrap_err(); + + assert_eq!(error.code, ErrorCode::AmbiguousTarget); + assert!( + error.message.contains("w-17") && error.message.contains("w-34"), + "the refusal names the open popovers: {}", + error.message + ); + let details = error.details.expect("ambiguous popover carries candidates"); + assert_eq!(details["kind"], "popover_ambiguous"); + assert_eq!(details["candidates"], json!(["w-17", "w-34"])); +} + +#[test] +fn a_named_popover_is_the_one_returned_even_with_two_open() { + let chosen = choose_popover(&[handle(17), handle(34)], Some("w-34")).expect("named popover"); + + assert_eq!(handle_id(chosen), "w-34"); +} + +#[test] +fn a_name_that_is_not_an_open_popover_is_refused() { + let error = choose_popover(&[handle(17)], Some("w-34")).unwrap_err(); + + assert_eq!(error.code, ErrorCode::WindowNotFound); + let details = error.details.expect("a closed popover lists what is open"); + assert_eq!(details["kind"], "popover_closed"); + assert_eq!(details["window_id"], "w-34"); + assert_eq!(details["candidates"], json!(["w-17"])); +} + +#[test] +fn no_open_popover_is_a_missing_window() { + let error = choose_popover(&[], None).unwrap_err(); + + assert_eq!(error.code, ErrorCode::WindowNotFound); +} + +#[test] +fn one_open_popover_is_unambiguous() { + assert_eq!( + handle_id(choose_popover(&[handle(17)], None).expect("one popover")), + "w-17" + ); +} diff --git a/crates/windows/src/tree/popover_inventory.rs b/crates/windows/src/tree/popover_inventory.rs new file mode 100644 index 0000000000..d4cb8d9dd8 --- /dev/null +++ b/crates/windows/src/tree/popover_inventory.rs @@ -0,0 +1,68 @@ +//! Popovers: the transient popup windows an application owns, such as a +//! ribbon drop-down or a split-button list. +//! +//! A popover is a visible popup window that another window of the same +//! process owns and that sits in the tool-window layer, so the window census +//! drops it. A menu has its own detector, and a tooltip never takes the +//! keyboard, so neither is a popover. Control type and ownership decide it, +//! never the application or the window title. + +use agent_desktop_core::ProcessId; + +use crate::system::window::window_enum::{EnumeratedWindow, WindowHandle}; + +/// What the window styles and the owner chain say about one tool window. +#[derive(Debug, Clone, Copy)] +pub(crate) struct PopupFacts { + pub(crate) owned_by_same_process: bool, + pub(crate) popup_style: bool, + pub(crate) no_activate: bool, + pub(crate) menu_class: bool, +} + +/// Whether a visible tool window is a popover. +pub(crate) fn is_popover(facts: &PopupFacts) -> bool { + facts.owned_by_same_process && facts.popup_style && !facts.no_activate && !facts.menu_class +} + +/// The popover candidates among a process's windows: visible, sized, not +/// cloaked tool windows whose facts say popover. +pub(crate) fn is_popover_window(window: &EnumeratedWindow, pid: ProcessId) -> bool { + window.visible + && window.tool + && !window.is_zero_sized() + && !window.cloaked + && is_popover(&popup_facts(window.handle, pid)) +} + +#[cfg(target_os = "windows")] +fn popup_facts(handle: WindowHandle, pid: ProcessId) -> PopupFacts { + use crate::system::window::window_identity::live_window_owner; + use crate::system::window::window_ops::window_class_name; + use windows_sys::Win32::UI::WindowsAndMessaging::{ + GW_OWNER, GWL_EXSTYLE, GWL_STYLE, GetWindow, GetWindowLongW, WS_EX_NOACTIVATE, WS_POPUP, + }; + let owner = unsafe { GetWindow(handle, GW_OWNER) }; + let style = unsafe { GetWindowLongW(handle, GWL_STYLE) } as u32; + let ex_style = unsafe { GetWindowLongW(handle, GWL_EXSTYLE) } as u32; + PopupFacts { + owned_by_same_process: !owner.is_null() && live_window_owner(owner) == Some(pid), + popup_style: style & WS_POPUP != 0, + no_activate: ex_style & WS_EX_NOACTIVATE != 0, + menu_class: window_class_name(handle).as_deref() == Some("#32768"), + } +} + +#[cfg(not(target_os = "windows"))] +fn popup_facts(_handle: WindowHandle, _pid: ProcessId) -> PopupFacts { + PopupFacts { + owned_by_same_process: false, + popup_style: false, + no_activate: false, + menu_class: false, + } +} + +#[cfg(test)] +#[path = "popover_inventory_tests.rs"] +mod tests; diff --git a/crates/windows/src/tree/popover_inventory_tests.rs b/crates/windows/src/tree/popover_inventory_tests.rs new file mode 100644 index 0000000000..c196bde338 --- /dev/null +++ b/crates/windows/src/tree/popover_inventory_tests.rs @@ -0,0 +1,31 @@ +use super::{PopupFacts, is_popover}; + +fn facts() -> PopupFacts { + PopupFacts { + owned_by_same_process: true, + popup_style: true, + no_activate: false, + menu_class: false, + } +} + +#[test] +fn only_an_owned_activating_popup_that_is_not_a_menu_is_a_popover() { + assert!(is_popover(&facts())); + assert!(!is_popover(&PopupFacts { + owned_by_same_process: false, + ..facts() + })); + assert!(!is_popover(&PopupFacts { + popup_style: false, + ..facts() + })); + assert!(!is_popover(&PopupFacts { + no_activate: true, + ..facts() + })); + assert!(!is_popover(&PopupFacts { + menu_class: true, + ..facts() + })); +} diff --git a/crates/windows/src/tree/resolve/resolve_anchor.rs b/crates/windows/src/tree/resolve/resolve_anchor.rs index 214edcda69..5e655bf049 100644 --- a/crates/windows/src/tree/resolve/resolve_anchor.rs +++ b/crates/windows/src/tree/resolve/resolve_anchor.rs @@ -59,6 +59,49 @@ pub(crate) fn resolve_locator_anchor( Err(stale_ref_error(entry)) } +/// A popover ref's path starts at the popover it was captured from, and a +/// popover is no listed window: the process generation is checked, then the +/// popover the ref recorded is found by the same predicate the inventory uses. +/// A ref that recorded no popover id is resolved only when one popover is +/// open; several are refused with their ids rather than guessed at. +#[cfg(target_os = "windows")] +fn popover_root(entry: &RefEntry, deadline: Deadline) -> Result, AdapterError> { + if entry.source.source_surface != agent_desktop_core::SnapshotSurface::Popover { + return Ok(None); + } + let alive = entry + .process + .process_instance + .as_deref() + .map(|instance| { + crate::system::process_identity::matches_instance(entry.process.pid, instance) + }) + .transpose()? + == Some(true); + if !alive { + return Err(stale_ref_error(entry)); + } + let popover = crate::tree::popover_choice::resolve_popover( + entry.process.pid, + entry.source.source_window_id.as_deref(), + deadline, + ) + .map_err(|error| popover_miss(entry, error))?; + crate::tree::automation::root_from_hwnd(popover.handle as isize, deadline).map(Some) +} + +/// A popover that is no longer open is a settled answer about the stored ref. +/// Several open popovers with none recorded on the ref is not: it names them +/// instead of resolving against a popover the ref never read. +#[cfg(target_os = "windows")] +fn popover_miss(entry: &RefEntry, error: AdapterError) -> AdapterError { + if error.code == agent_desktop_core::ErrorCode::WindowNotFound { + stale_ref_error(entry) + } else { + error + } +} + /// The one pure gate runs first, before any of `resolve_window_root`, /// `UiaTreeSource::for_root` or `prepare_root` - three cross-process calls a /// verdict the stored ref alone can settle should never pay for. @@ -79,7 +122,10 @@ fn resolve_locator_anchor_once( return Err(stale_ref_error(entry)); } - let window = crate::tree::resolve::resolve_window_root(entry, deadline)?; + let window = match popover_root(entry, deadline)? { + Some(popover) => popover, + None => crate::tree::resolve::resolve_window_root(entry, deadline)?, + }; let root = match base { Some(handle) => handle .downcast_ref::() diff --git a/crates/windows/src/tree/surface_inventory.rs b/crates/windows/src/tree/surface_inventory.rs index 9f529a8346..4dcf4d5510 100644 --- a/crates/windows/src/tree/surface_inventory.rs +++ b/crates/windows/src/tree/surface_inventory.rs @@ -3,6 +3,7 @@ use agent_desktop_core::{ }; use super::automation::root_from_hwnd; +use super::popover_inventory::is_popover_window; use super::properties::property_ids::TreeProperty; use super::properties::property_outcome::PropertyOutcome; use super::properties::read_one; @@ -37,7 +38,7 @@ pub(crate) fn list_surfaces_for_process( ) -> Result, AdapterError> { deadline.ensure_remaining()?; require_live_process(&process)?; - let windows = windows_of(process.pid, deadline)?; + let (windows, popovers) = windows_of(process.pid, deadline)?; let observed: Vec = windows .iter() .map(|window| ObservedWindow { @@ -53,6 +54,13 @@ pub(crate) fn list_surfaces_for_process( if let Some(menu) = menu { surfaces.push(menu_surface(&menu)?); } + for popover in popovers { + surfaces.push(surface( + SnapshotSurface::Popover, + popover.handle, + live_window_title(popover.handle), + )); + } Ok(surfaces) } @@ -69,12 +77,13 @@ fn require_live_process(process: &ProcessIdentity) -> Result<(), AdapterError> { )) } -/// The pid's agent-facing top-level windows, from the one enumeration pass -/// every window inventory on this platform shares - the same walk -/// `list_windows` and the menu detector draw from, filtered by the same -/// census predicate. -fn windows_of(pid: ProcessId, deadline: Deadline) -> Result, AdapterError> { +/// The process's census windows and its popovers (tool windows the census drops). +pub(super) fn windows_of( + pid: ProcessId, + deadline: Deadline, +) -> Result<(Vec, Vec), AdapterError> { let mut windows = Vec::new(); + let mut popovers = Vec::new(); let failure = std::cell::RefCell::new(None); let mut seen = 0usize; enumerate_top_level(|window| { @@ -85,20 +94,24 @@ fn windows_of(pid: ProcessId, deadline: Deadline) -> Result) -> SurfaceInfo { SurfaceInfo { - id: format!("w-{}", handle as usize), + id: super::popover_choice::handle_id(handle), kind: kind.as_str().to_string(), title, item_count: None, diff --git a/crates/windows/src/tree/surfaces.rs b/crates/windows/src/tree/surfaces.rs index 2791f1c3a7..df26fff55f 100644 --- a/crates/windows/src/tree/surfaces.rs +++ b/crates/windows/src/tree/surfaces.rs @@ -23,6 +23,10 @@ pub(crate) fn surface_root( deadline: Deadline, ) -> Result { match (root, surface) { + (ObservationRoot::Application { app, .. }, SnapshotSurface::Popover) => { + let popover = crate::tree::popover_choice::resolve_popover(app.pid, None, deadline)?; + root_from_hwnd(popover.handle as isize, deadline) + } (ObservationRoot::Application { .. }, _) => { Err(AdapterError::not_supported("application observation root")) } @@ -38,14 +42,13 @@ pub(crate) fn surface_root( root_from_hwnd(handle, deadline) } (ObservationRoot::Window(window), SnapshotSurface::Sheet) => { - let handle = focused_hwnd_of(&window.id)?; - let element = root_from_hwnd(handle, deadline)?; + let element = root_from_hwnd(parse_window_id(&window.id)?, deadline)?; if window_is_modal_sheet(&element) { Ok(element) } else { Err(AdapterError::new( ErrorCode::WindowNotFound, - "The focused window is not a modal sheet", + "The window is not a modal sheet", )) } } @@ -64,6 +67,10 @@ pub(crate) fn surface_root( })?; root_from_hwnd(location.root_handle(), deadline) } + (ObservationRoot::Window(window), SnapshotSurface::Popover) => { + let popover = popover_handle(window.pid, &window.id, deadline)?; + root_from_hwnd(popover.handle as isize, deadline) + } (ObservationRoot::Window(window), SnapshotSurface::StartMenu) | (ObservationRoot::Window(window), SnapshotSurface::Taskbar) | (ObservationRoot::Window(window), SnapshotSurface::SystemTray) @@ -85,6 +92,24 @@ pub(crate) fn surface_root( } } +/// The popover a window-rooted surface read lands on. A window id that names +/// one of the process's open popovers reads that popover. Any other window id +/// keeps this platform's meaning - the popover of that window's application - +/// and is refused when several are open, since none of them was named. +fn popover_handle( + pid: agent_desktop_core::ProcessId, + named: &str, + deadline: Deadline, +) -> Result { + match crate::tree::popover_choice::resolve_popover(pid, Some(named), deadline) { + Ok(popover) => Ok(popover), + Err(error) if error.code == ErrorCode::WindowNotFound => { + crate::tree::popover_choice::resolve_popover(pid, None, deadline) + } + Err(error) => Err(error), + } +} + /// The focused window's HWND, found through the focused-only window inventory /// the same way `focused_window` composes it. fn focused_hwnd_of(expected: &str) -> Result { diff --git a/crates/windows/src/tree/walk/walker.rs b/crates/windows/src/tree/walk/walker.rs index 4b5735ae95..e274709b31 100644 --- a/crates/windows/src/tree/walk/walker.rs +++ b/crates/windows/src/tree/walk/walker.rs @@ -1,6 +1,6 @@ use agent_desktop_core::{ AdapterError, Deadline, ErrorCode, LocatorEvidence, LocatorField, LocatorStats, - ObservationRoot, ObservationSource, ObservedTree, + ObservationRoot, ObservationSource, ObservedTree, SnapshotSurface, }; use serde_json::json; @@ -137,6 +137,7 @@ pub fn walk_from_root( source: &S, root: &S::Node, root_source: &ObservationRoot<'_>, + surface: SnapshotSurface, budget: WalkBudget, ) -> Result { let mut walk = TreeWalk::new(source, budget); @@ -145,7 +146,7 @@ pub fn walk_from_root( let root_subtree = root_subtree.ok_or_else(|| root_missing_error(&stats))?; let tree = ObservedTree::from_roots( vec![root_subtree], - ObservationSource::from_root(root_source, root_source.surface()), + ObservationSource::from_root(root_source, surface), stats.clone(), structurally_complete, )?; diff --git a/crates/windows/src/tree/walk/walker_fake.rs b/crates/windows/src/tree/walk/walker_fake.rs index 8c896f79f6..31b68bc37f 100644 --- a/crates/windows/src/tree/walk/walker_fake.rs +++ b/crates/windows/src/tree/walk/walker_fake.rs @@ -1,6 +1,6 @@ use agent_desktop_core::{ - AdapterError, Deadline, LocatorEvidence, ObservationRoot, ProcessId, RefEntry, WindowInfo, - WindowState, + AdapterError, Deadline, LocatorEvidence, ObservationRoot, ProcessId, RefEntry, SnapshotSurface, + WindowInfo, WindowState, }; use std::collections::{HashMap, HashSet}; @@ -233,8 +233,16 @@ pub(crate) fn window() -> WindowInfo { } pub(crate) fn walk(fake: &FakeTree, budget: WalkBudget) -> WalkOutcome { + walk_on_surface(fake, SnapshotSurface::Window, budget) +} + +pub(crate) fn walk_on_surface( + fake: &FakeTree, + surface: SnapshotSurface, + budget: WalkBudget, +) -> WalkOutcome { let window = window(); - walk_from_root(fake, &1, &ObservationRoot::Window(&window), budget) + walk_from_root(fake, &1, &ObservationRoot::Window(&window), surface, budget) .expect("the walk assembles an observation") } @@ -242,7 +250,13 @@ pub(crate) fn walk(fake: &FakeTree, budget: WalkBudget) -> WalkOutcome { /// error the caller receives can be asserted. pub(crate) fn walk_expecting_failure(fake: &FakeTree, budget: WalkBudget) -> AdapterError { let window = window(); - walk_from_root(fake, &1, &ObservationRoot::Window(&window), budget) - .err() - .expect("the walk was expected to fail") + walk_from_root( + fake, + &1, + &ObservationRoot::Window(&window), + SnapshotSurface::Window, + budget, + ) + .err() + .expect("the walk was expected to fail") } diff --git a/crates/windows/src/tree/walk/walker_source.rs b/crates/windows/src/tree/walk/walker_source.rs index b870bd34af..79a1db1fa3 100644 --- a/crates/windows/src/tree/walk/walker_source.rs +++ b/crates/windows/src/tree/walk/walker_source.rs @@ -1,4 +1,4 @@ -use agent_desktop_core::{AdapterError, ObservationRoot}; +use agent_desktop_core::{AdapterError, ObservationRoot, SnapshotSurface}; use super::walker::{WalkBudget, WalkOutcome, walk_from_root}; use crate::tree::element::UIAElement; @@ -375,12 +375,13 @@ pub(crate) use imp::{ pub fn walk_uia_subtree( root: &UIAElement, root_source: &ObservationRoot<'_>, + surface: SnapshotSurface, budget: WalkBudget, identity_only: bool, ) -> Result { let source = UiaTreeSource::for_root_reading(root, identity_only)?; let prepared = source.prepare_root(root)?; - walk_from_root(&source, &prepared, root_source, budget) + walk_from_root(&source, &prepared, root_source, surface, budget) } #[cfg(test)] diff --git a/crates/windows/src/tree/walk/walker_source_tests.rs b/crates/windows/src/tree/walk/walker_source_tests.rs index 7a9bcf9902..41242773df 100644 --- a/crates/windows/src/tree/walk/walker_source_tests.rs +++ b/crates/windows/src/tree/walk/walker_source_tests.rs @@ -82,7 +82,7 @@ mod non_windows_only { use super::super::*; use crate::tree::element::{CannedElement, UIAElement}; use crate::tree::walk::walker_fake::{budget, window}; - use agent_desktop_core::ObservationRoot; + use agent_desktop_core::{ObservationRoot, SnapshotSurface}; /// The canned arm exists so every module that calls the walk compiles and /// runs off Windows. It enumerates nothing, which is the exhaustion answer, @@ -92,8 +92,14 @@ mod non_windows_only { let window = window(); let root = UIAElement::from(CannedElement); - let outcome = walk_uia_subtree(&root, &ObservationRoot::Window(&window), budget(10), false) - .expect("the canned walk assembles an observation"); + let outcome = walk_uia_subtree( + &root, + &ObservationRoot::Window(&window), + SnapshotSurface::Window, + budget(10), + false, + ) + .expect("the canned walk assembles an observation"); assert!(outcome.tree.is_complete()); assert!(outcome.failures.is_empty()); diff --git a/crates/windows/src/tree/walk/walker_tests.rs b/crates/windows/src/tree/walk/walker_tests.rs index 753a3dc80c..eeef9ecffb 100644 --- a/crates/windows/src/tree/walk/walker_tests.rs +++ b/crates/windows/src/tree/walk/walker_tests.rs @@ -3,8 +3,9 @@ use crate::tree::automation::UiaFailure; use crate::tree::walk::walker_enumerate::TreeWalk; use crate::tree::walk::walker_fake::{ E_FAIL, EXHAUSTION, FakeTree, REAL_FAILURE, budget, walk, walk_expecting_failure, + walk_on_surface, }; -use agent_desktop_core::{Deadline, ErrorCode}; +use agent_desktop_core::{Deadline, ErrorCode, SnapshotSurface}; /// The fakes encode the measured pair, not a reading of the crate. If this /// fails, every other fake-driven assertion below is testing the wrong model. @@ -369,3 +370,15 @@ fn an_identity_walk_leaves_actions_and_states_unknown() { assert_eq!(identity.available_actions, LocatorField::Unknown); assert_eq!(identity.states, LocatorField::Unknown); } + +/// A window-rooted read of a surface the window presents names that surface, +/// so a ref anchored from this observation resolves in the surface it was +/// read from instead of at the window root. +#[test] +fn a_window_rooted_walk_of_a_surface_records_that_surface() { + let fake = FakeTree::default().with_chain(&[1, 2]); + + let outcome = walk_on_surface(&fake, SnapshotSurface::Menu, budget(10)); + + assert_eq!(outcome.tree.surface(), SnapshotSurface::Menu); +} diff --git a/docs/json-output.md b/docs/json-output.md index fc728e400b..623e9bf1fd 100644 --- a/docs/json-output.md +++ b/docs/json-output.md @@ -243,7 +243,7 @@ After the core resolver chooses the element, the platform adapter lands it, and | `AMBIGUOUS_TARGET` | Ref recovery matched multiple plausible targets | | `SNAPSHOT_NOT_FOUND` | Snapshot ID is missing or expired | | `SANDBOX_NOT_FOUND` | No sandbox has that name; run `agent-desktop sandbox list` to see the sandboxes that exist | -| `POLICY_DENIED` | The interaction policy does not permit an effect of the operation; nothing was sent. `details.effect` names it when one effect decided: `focus_steal`, `cursor_move` or `clipboard_write`. A refusal of an effect on the user's foreground also carries `details.check: "foreground"` and `details.foreground_effect: true`. Before dispatch, `details.mechanisms` is the action name and `details.kind` is the reason: `shows_menu`, `opens_dialog`, `opens_popup` or `focus`. When a delivery route is held back, `details.mechanisms` names the withheld route labels. A ref action whose remaining routes all deliver nothing, while one was held back, is `POLICY_DENIED`, not `ACTION_FAILED`, on every platform. Rerun with `--headed` to permit them. A key combo the platform blocks for safety is also `POLICY_DENIED`: headed mode does not lift the block, and `--force` overrides it only when the user authorized the combo's effect | +| `POLICY_DENIED` | The interaction policy does not permit an effect of the operation; nothing was sent. `details.effect` names it when one effect decided: `focus_steal`, `cursor_move` or `clipboard_write`. A refusal of an effect on the user's foreground also carries `details.check: "foreground"` and `details.foreground_effect: true`. Before dispatch, `details.mechanisms` is the action name and `details.kind` is the reason: `shows_menu`, `opens_dialog`, `opens_popup`, `popover_command` (macOS: a button inside a popover, whose command can start a service that takes the front) or `focus`. When a delivery route is held back, `details.mechanisms` names the withheld route labels. A ref action whose remaining routes all deliver nothing, while one was held back, is `POLICY_DENIED`, not `ACTION_FAILED`, on every platform. Rerun with `--headed` to permit them. A key combo the platform blocks for safety is also `POLICY_DENIED`: headed mode does not lift the block, and `--force` overrides it only when the user authorized the combo's effect | | `ACTION_FAILED` | Action rejected, or its observed result contradicted the request | | `ACTION_NOT_SUPPORTED` | The target does not expose the requested action | | `APP_UNRESPONSIVE` | The matching application stopped responding | @@ -281,6 +281,7 @@ The 2.7 envelope keeps every current name. 2.0 is a future breaking release that | Process identity | Flat `pid`, `process_instance` in list-apps, list-windows, and launch; `pid` alone in wait events and list-surfaces; `target.process.{pid,instance}` in close-app and window operations; `process_identity.{pid,process_instance}` in post-action observation; neither in snapshot data | Flat `pid`, `process_instance`; omit an unknown instance | | Window identity | `id`, `title` in window records, operation targets, and snapshot; `window_id`, `title` in wait events; `source_window_id` in post-action observation; snapshot includes only `id`, `title` | Record `id`, `title`; reference `window_id`; full window record in snapshot | | Window container | `window` in launch, snapshot, wait --window, and open-system-surface; `focused` object in focus-window | `window` | +| Open surface | `surface` in wait --surface: the `id`, `type` and `title` of the first open surface of the asked kind; its timeout carries `last_observed` | `surface` | | Focus state | `is_focused` in window records; `focused` element token; `result` in is focused; `focused` boolean in hover and drag | Window `focused`; element token `focused`; hover and drag `window_focused` | | Element state | `states` tokens in snapshot and find; get --property states returns tokens in `value`; ref-action `post_state` has `states` plus `enabled`, `hidden`, `offscreen` booleans | `states` tokens, including `enabled` when evidenced | | Predicate answer | `property`, `result`, `applicable` in is; wait --element `observed` uses `exists`, `enabled`, `visible`, `actionable`, or `matched` with value evidence | No common name specified | diff --git a/skills/agent-desktop-ffi/SKILL.md b/skills/agent-desktop-ffi/SKILL.md index ecc681ed98..c51747fe68 100644 --- a/skills/agent-desktop-ffi/SKILL.md +++ b/skills/agent-desktop-ffi/SKILL.md @@ -102,8 +102,8 @@ ABI. A bare `@eN` ref returns only as fields embedded in the exact structs. `ad_list_surfaces_exact` keeps the surface `id`. From `AD_EXACT_SURFACE_INFO_VERSION` 2, `AdExactSurfaceInfo.unclassified` names the surface kinds its probe could not read (for example `sheet,menu`), or - is null. A missing `sheet` or `menu` next to a listed kind is unknown, not - absent. Only the Windows adapter fills it; macOS and Linux return null. + is null. A missing `sheet`, `menu` or `popover` next to a listed kind is + unknown, not absent. - **Entries with no policy input.** `ad_mouse_event`, `ad_mouse_event_with_modifiers`, `ad_mouse_wheel`, `ad_drag`, `ad_set_clipboard`, `ad_clear_clipboard`, diff --git a/skills/agent-desktop-linux/SKILL.md b/skills/agent-desktop-linux/SKILL.md index e82d2d066d..76f5429e1d 100644 --- a/skills/agent-desktop-linux/SKILL.md +++ b/skills/agent-desktop-linux/SKILL.md @@ -52,26 +52,24 @@ use a private session and runtime directory for isolated work. Menu-role popups use the menu surface instead. - Popup and dialog openers can take the foreground and refuse headless. Qt combo selection may need pointer input to commit rather than highlight a row. - Stop on a headed-only refusal instead of changing mode. Headless `restore` of a minimized window and headless `minimize` of the focused window refuse with `POLICY_DENIED`; the system raises or moves focus. Stop on that refusal. -- A headless graceful `close-app` reads which window has the focus first. When it cannot (a Wayland session, or an owner it cannot identify), it fails with `POLICY_DENIED` (`details.kind: focus_unreadable`) before any close request is sent. Report it to the user, or use `--force`, which discards unsaved work. -- A window can precede its content. Wait for the application's observable - result; an accepted AT-SPI call or a changed selected value is not proof that - dependent handlers ran. Wait for each effect before another click. + Stop on a headed-only refusal instead of changing mode. Headless `restore` of a minimized window and headless `minimize` of the focused window refuse with `POLICY_DENIED`; the system raises or moves focus. +- A headless graceful `close-app` of a native Wayland client returns `ACTION_NOT_SUPPORTED` (`details.cause: wayland_session`). `--force` discards unsaved work. + When it cannot read the focused window it fails with `POLICY_DENIED` (`details.kind: focus_unreadable`) before any close request is sent. +- `press --app` works headless only when the target's window is active. Otherwise it sends nothing and returns `ACTION_FAILED` + (`details.check: window_active`), or `STALE_REF` when the window has no process identity. +- A GTK4 list or grid view has no row nodes, so `select` and `click` cannot pick a row. +- A window can precede its content. Wait for the application's observable result; an accepted AT-SPI call or a changed + selected value does not prove that handlers ran. Wait for each effect before another click. - Wayland refuses headed pointer input; window operations can use a mapped Xwayland client, but native Wayland windows lack that route. -- Authorized physical `type` sends a newline as `Return` on X11 too. It refuses a tab and other control characters. -- Authorized physical `type` on Wayland sends a newline as `Return` and a tab as - `Tab`, which can submit a form or move focus instead of inserting literal text. -- Wayland per-window screenshots are unsupported; display capture uses a portal - that can ask for consent. Ask the user before initiating a visible consent flow, - and do not retry a pending portal request in a loop. -- X11 capture depends on compositing: a covered noncomposited window may have - no readable pixels, and a composited desktop may not support whole-screen capture. - Neither failure authorizes focusing the target. -- Shell notifications require the supported GNOME service; tray reads require a - StatusNotifierWatcher. A missing service is an error, not an empty list. -- Password-role values are withheld, but a field that merely masks its text can - still be readable. Treat observation output as sensitive. +- Authorized physical `type` sends a newline as `Return` on X11 too and refuses a tab and other control characters. + On Wayland it sends a newline as `Return` and a tab as `Tab`, which can submit a form or move focus instead of inserting literal text. +- Wayland per-window screenshots are unsupported; display capture uses a portal that can ask for consent. + Ask the user before a visible consent flow, and do not retry a pending request in a loop. +- X11 capture depends on compositing: a covered noncomposited window may have no readable pixels, and a + composited desktop may not support whole-screen capture. Neither failure authorizes focusing the target. +- Shell notifications need the supported GNOME service; tray reads need a StatusNotifierWatcher. A missing service is an error. +- Password-role values are withheld, but a field that only masks its text can be readable. Treat observation output as sensitive. - `launch` accepts a program on PATH, an absolute path, an installed desktop id, or an unambiguous desktop entry name. A script launch attaches only to the interpreter process that runs that script, never to another script of the same interpreter. `--no-attach` refuses any running process of the same program (the same executable, or the interpreter running the same script) whatever its arguments. Use process and window identity from observations rather than guessing from a window title. Without `--activate`, a launch on X11 gives the focus and window order back and reports `focus_returned: true`, or `false` with a suggestion; a headless click that opens a dialog is guarded the same way. - `press escape --app --window-id ` on a background window with a showing native popup closes it only via a dismissal action (or GTK3 combo box `Press`) and reports `delivered_verified` once gone. Web content and buttons without a dismissal action keep the focus refusal; it never collapses a tree row. - Sandboxes are not available on Linux yet. To run agent-desktop in a container you manage yourself, see `agent-browser.dev/desktop/guides/docker-container`. diff --git a/skills/agent-desktop-macos/SKILL.md b/skills/agent-desktop-macos/SKILL.md index 028d0c6f90..3743a1e842 100644 --- a/skills/agent-desktop-macos/SKILL.md +++ b/skills/agent-desktop-macos/SKILL.md @@ -42,15 +42,20 @@ may report `unknown` when consent would require a prompt. - `menu` and `menubar` observations are application-owned and can omit `data.window`. An app without an ordinary window may still expose process-owned surfaces. Inspect `supported_surfaces` rather than assuming every surface exists. +- `press --app` headless: `return` and `escape` run as accessibility actions on the focused element. Any other key needs a focused element in the + app (`ACTION_FAILED`, `details.check: process_focus`, `not_delivered` otherwise). A modifier shortcut never runs a menu item: `click` the item. - `agent-desktop press escape --app ` closes an open menu or popover with its cancel action when no focused element takes Escape, and reads that it closed; with `--window-id ` it closes the surface that window or the app shows. A popover can appear a moment after the click that opens it: read it with `snapshot --app --surface popover`. +- `list-surfaces` lists the sheets, dialogs and popovers of every window, not only + the focused one. A system service panel, such as AirDrop from a share, is a dialog. - Headless menu-opening and dialog-opening actions can refuse before delivery. A label ending in an ellipsis predicts a dialog; it does not prove one exists. - Stop on a headed-only refusal rather than changing mode. -- Headless `restore` of a minimized window and headless `minimize` of the focused window refuse with `POLICY_DENIED`; the system raises or moves focus. Stop on that refusal. + A click on a button inside a popover refuses with `kind: popover_command`: a + share item starts a service whose window takes the front. Stop on a headed-only + refusal rather than changing mode. Headless `restore` of a minimized window and headless `minimize` of the focused window refuse with `POLICY_DENIED`; the system raises or moves focus. - A file-name text field is not a file-system rename interface. Value-write actions refuse it because a changed field could falsely imply a renamed file. - A tab button (`AXRadioButton`, subrole `AXTabButton`) is selected by press @@ -75,8 +80,7 @@ may report `unknown` when consent would require a prompt. cell editor no keyboard input from a press always takes that failure; type there with `--headed` only if the user explicitly asked for that. The write also commits an edit that is open in another cell. -- AX success alone does not prove an application effect. Verify the task's - result independently, especially after a menu action or a value write. +- AX success alone does not prove an application effect. Verify the result independently, especially after a menu action or value write. ## Troubleshooting @@ -93,3 +97,4 @@ Read the disposition before applying a fix. Match both the code and message. | `PERM_DENIED`: `private file parent is accessible by group or other users` | The state root is not private. Run `chmod 700 "${AGENT_DESKTOP_HOME:-$HOME/.agent-desktop}"`, or use a new state root and let the tool create it. | | `PERM_DENIED`: `private file parent is not owned by the effective user` | The directory belongs to another user. Point `AGENT_DESKTOP_HOME` at a new directory under your home and let the tool create it; do not take over someone else's state. | | `needs_setup` from `sandbox status` for a sandbox that worked before | The guest agent, `agent-desktop-guest`, is not running in the guest, or Accessibility is off for it. Run `sandbox stop `, then `sandbox start --window`. In the guest, turn on automatic login, run `sh "/Volumes/My Shared Files/guest-setup.sh"` in Terminal, and switch on **agent-desktop-guest** in System Settings > Privacy & Security > Accessibility. Then check `status` on the host. A sandbox set up by agent-desktop 1.3.0 needs this once. | +| `ACTION_NOT_SUPPORTED`: `The packaged macOS clipboard helper is missing or invalid` | Every clipboard command runs the packaged `agent-desktop-macos-helper` beside the binary, and it is checked before launch: a regular file (not a symlink) owned by you, executable, one link, no group or world write, no ACL that lets someone else change it, under directories owned by you or root that are not group or world writable unless sticky. `details.kind` is `clipboard_helper_invalid` or `clipboard_helper_not_found`, and `platform_detail` names the failed rule. Repair the install; the clipboard is not empty. | diff --git a/skills/agent-desktop-windows/SKILL.md b/skills/agent-desktop-windows/SKILL.md index ebba180209..d62ba84882 100644 --- a/skills/agent-desktop-windows/SKILL.md +++ b/skills/agent-desktop-windows/SKILL.md @@ -26,6 +26,8 @@ Use `agent-desktop permissions` to recheck after the user fixes access. Quote refs in PowerShell: `'@s8f3k2p9:e1'`. A bare `@token` invokes splatting. Use `$env:NAME = 'value'` for environment variables. +Windows PowerShell 5.1 drops the double quotes in a JSON argument: pass `($json -replace '"','\"')` to `batch`, which has no stdin or file route. +PowerShell appends a line ending to piped text, so `--stdin` keeps it; use `cmd /c "agent-desktop set-value '' --stdin < file.txt"` for exact text. ## Platform behavior @@ -47,20 +49,22 @@ Use `$env:NAME = 'value'` for environment variables. button: then the innermost one is collapsed (`ExpandCollapsePattern.Collapse`), `delivered_verified` once read back closed. A tree item is never collapsed. `collapse` of an open combo box or menu item works headless, and reports `not_delivered` when it is already closed. -- A grid reports `row_count` and `column_count`. A row is a record: find it by its own - name, and its cells through it. `agent-desktop click` on a grid cell that lists `Click` - selects the row that holds it. A cell carries no grid position. +- `press --app` or `--window-id` works headless only when that process owns the foreground window. Otherwise it sends nothing and returns + `ACTION_FAILED` (`details.check: process_focus`, `not_delivered`). There is no background key route. +- `--trace PATH`: the file's folder must exist and have a private DACL (you, SYSTEM, Administrators). A folder that grants `Users` write gives `INVALID_ARGS`. +- A grid reports `row_count` and `column_count`. A row is a record: find it by its own name, and its cells through it. `agent-desktop click` on a grid cell that lists `Click` selects the row that holds it. A cell carries no grid position. - A field whose text is longer than 2048 characters cannot be read: `get` returns `ACTION_FAILED` with `details.kind: "value_exceeds_read_limit"` and the length. Do not retry it. `clear`, `set-value`, `focus` and `click` on its ref still work. - `agent-desktop launch` takes an absolute executable path or a bare program name in the Windows or System32 directory, not an arbitrary display name or a PATH search. Without `--activate` the process starts with a show-window hint that asks for no - activation. A window that opens and takes the foreground or the top of the - window order is sent back below the window that had it, the foreground is - returned, and the result reports `focus_returned: true`, or `false` with a - suggestion when it could not be. A window you switched to is never touched. -- Chromium/Electron trees can be thin while accessibility settles. Finish a - bounded observation before concluding that content is absent. -- An open application menu is the `menu` surface; there is no `menubar` surface. + activation. A window that takes the foreground or the top of the window order is + sent back below the window that had it, and the result reports `focus_returned: true`, + or `false` with a suggestion. A window you switched to is never touched. +- Chromium/Electron trees can be thin while accessibility settles. Finish a bounded observation before concluding content is absent. +- An open application menu is the `menu` surface; there is no `menubar` surface. An owned popup window + of the app (a ribbon drop-down) is a `popover`: `list-surfaces` lists it, `snapshot --surface popover` reads it. + When several popovers are open, name one with `--app --window-id `; + without a name the read is refused with `AMBIGUOUS_TARGET` rather than reading a different popover. Shell surfaces are separate from ordinary window inventory. `quick-settings` refuses with `INVALID_ARGS` naming `action-center`. - Notification reads adopt an already-open Action Center headless; opening it @@ -71,7 +75,7 @@ Use `$env:NAME = 'value'` for environment variables. 1254.2 ms per poll median plus the polling interval; transient toasts can be missed. - `agent-desktop cursor-overlay enable` reports `rendered: true` only after renderer acknowledgement. It does not move the physical pointer, and headed actions skip its travel animation. -- Sandboxes are not available on Windows yet. To run agent-desktop in a container you manage yourself, see `agent-browser.dev/desktop/guides/docker-container`. +- Sandboxes are not available on Windows yet; for your own container see `agent-browser.dev/desktop/guides/docker-container`. Value verification is not application commit: `delivered_verified` with `element_value` confirms only the field. `unavailable` means readback evidence diff --git a/skills/agent-desktop/SKILL.md b/skills/agent-desktop/SKILL.md index f2d9b6bc62..3b4fbed539 100644 --- a/skills/agent-desktop/SKILL.md +++ b/skills/agent-desktop/SKILL.md @@ -70,8 +70,8 @@ agent-desktop get '@s8f3k2p9:e4' --property value agent-desktop close-app "" # a save prompt keeps the app open; see --force below ``` -If an action reports `data.surfaces`, inspect the overlay before acting on the -window behind it. A menu, sheet, or alert needs its own surface observation. +If an action reports `data.surfaces`, inspect the overlay before acting on the window behind it. A menu, sheet, or alert needs its own surface observation. +`data.details.surfaces: "not_read"` means that read failed, so run `list-surfaces` before assuming no overlay opened. Attached selector waits usually observe the parent window, not a separate popup. A gone match cannot prove that popup closed, and matching text elsewhere can satisfy an appearance wait. Use `launch` with a program name or path accepted by the platform. A running @@ -88,8 +88,8 @@ Request `--cdp` only for the step that needs it. `close-app` ends the exposure. and exit 0 can include failures. Read each entry's `ok`, even with `--stop-on-error`, which stops later steps after a failure. - Lifecycle verification: put an action immediately before its event `wait` in the same - batch so the baseline is captured before the action. A standalone event wait starts - its baseline when it observes and can miss an already-completed transition. + batch so the baseline is captured before the action; a later event wait can miss an + already-completed transition. A surface a click opens late is a state: `wait --surface --app `. - Targeting: use `find` when the role or name is known; explore a large window with a skeleton snapshot and a `--root` drill. - Tables: a table node reports `row_count` and `column_count`; a skeleton keeps it as one @@ -106,6 +106,13 @@ Request `--cdp` only for the step that needs it. `close-app` ends the exposure. `--agent-id` per agent on its commands; this does not change session or ref ownership. - Review afterwards: sessions trace by default; inspect the session with `trace show` or make a self-contained viewer with `trace export`. +- Launch takes `--arg ` (repeatable; `--arg=-x` for a leading `-`), `--env KEY=VALUE` (no repeated key) and `--cwd `. + `wait --window ` needs part of the title; with none, put `wait --event window-opened --app "<app>"` after the opener in one batch. +- `--stdin` keeps a trailing newline in the value. Send exact text with `printf '%s' "<text>"`; PowerShell appends a line ending to piped strings. +- Saving into a folder: a Save panel's name field takes a file name, not a path (macOS shows `/` as `:`). Pick the folder with the + Where pop-up, which needs headed mode, so ask first. Check the file on disk. `--trace PATH` needs a private file you own, + and on Windows a private folder too (one that grants `Users` write is refused). +- `press --app` reaches a background app only where the platform can: macOS for `return`, `escape` or an app with a focused element; Windows and Linux need the target in front (`ACTION_FAILED`, `not_delivered`). - Secrets: run secret steps as separate `--stdin` commands, not batch JSON `text` or `value` fields, which expose secrets in process arguments. `--stdin` omits observed `value` fields from results; it does not redact later observations or screenshots. @@ -163,14 +170,7 @@ Names are 1–32 lowercase letters, digits or hyphens, starting with a letter or Read `state`, `message` and optional `next`; `ok: true` alone does not mean the sandbox is ready. -- `unavailable`: satisfy the host requirements in `message` and `next`. -- `missing`: install the provider. -- `ready`: create a sandbox. -- `working`: repeat the command in `next` until the work finishes. -- `needs_setup`: have a person complete guest setup, then check status. -- `running`: run guest commands, or stop before removal. -- `stopped`: start the sandbox to use it, or remove it. -- `broken`: follow `next`; a broken sandbox may need removal. +- `unavailable`: meet `message`. `missing`: install. `ready`: create. `working`: repeat `next`. `needs_setup`: a person completes guest setup. `running`: exec, or stop before `rm`. `stopped`: start or remove. `broken`: follow `next`. A sandbox separates the desktop, not the network or the host. Sandboxes on one host share a virtual network, and a guest can reach the host's network services; keep one trust level per host. The host reaches the guest over the virtual machine's own socket device: only the process that runs the VM can open that connection, and `agent-desktop-guest` refuses any caller that is not the host. The host sends commands only to the agent whose key it recorded at setup, so another guest account cannot answer in its place. The agent runs the guest's `agent-desktop` with the arguments after `--` and never a shell. In the guest, Accessibility belongs to `agent-desktop-guest`. diff --git a/src/cli/doc_literal_drift_tests.rs b/src/cli/doc_literal_drift_tests.rs index 3038a3af5b..0ba42f27e8 100644 --- a/src/cli/doc_literal_drift_tests.rs +++ b/src/cli/doc_literal_drift_tests.rs @@ -24,6 +24,7 @@ const FFI_HEADER: &str = include_str!("../../crates/ffi/include/agent_desktop.h" const FFI_API_DOCS: &str = include_str!("../../apps/docs/content/docs/ffi/api.mdx"); const README: &str = include_str!("../../README.md"); const AGENTS_MD: &str = include_str!("../../AGENTS.md"); +const WAIT_REFERENCE: &str = include_str!("../../apps/docs/content/docs/commands/wait.mdx"); const HELD_INPUT_COMMANDS: &[&str] = &["key-down", "key-up", "mouse-down", "mouse-up"]; fn quoted_values_after<'a>(text: &'a str, marker: &str) -> Vec<&'a str> { @@ -145,3 +146,44 @@ fn documented_command_counts_match_the_cli() { "AGENTS.md must state {operational} of the {total} command names are operational" ); } + +/// The wait reference documents every flag the `wait` subcommand accepts, so a +/// new wait mode cannot ship without its line in the reference. The flags come +/// from the clap tree the binary runs, never from a list kept beside the docs. +#[test] +fn wait_reference_documents_every_wait_flag() { + let wait = Cli::command() + .get_subcommands() + .find(|command| command.get_name() == "wait") + .expect("the wait subcommand exists") + .clone(); + let mut flags = wait + .get_arguments() + .filter(|argument| !matches!(argument.get_id().as_str(), "help" | "version")) + .filter_map(|argument| argument.get_long()) + .collect::<Vec<_>>(); + flags.sort_unstable(); + assert!( + flags.contains(&"surface"), + "wait accepts --surface: {flags:?}" + ); + for flag in flags { + assert!( + documents_flag(WAIT_REFERENCE, flag), + "apps/docs/content/docs/commands/wait.mdx does not document --{flag}" + ); + } +} + +/// Whether `reference` names `flag` as a whole flag: a `--window` line does not +/// document `--window-id`, and a longer flag containing the name documents +/// nothing. +fn documents_flag(reference: &str, flag: &str) -> bool { + let named = format!("--{flag}"); + reference.match_indices(&named).any(|(at, matched)| { + reference[at + matched.len()..] + .chars() + .next() + .is_none_or(|next| !(next.is_ascii_alphanumeric() || next == '-')) + }) +} diff --git a/src/cli_args/system.rs b/src/cli_args/system.rs index d5b87c8b9d..91de369709 100644 --- a/src/cli_args/system.rs +++ b/src/cli_args/system.rs @@ -232,9 +232,9 @@ pub(crate) struct WaitArgs { pub app: Option<String>, } -/// The `--event`/`--window-id` pair, grouped out of [`WaitModeArgs`] to keep -/// it under the repo's field-count limit. `window_id` only ever narrows an -/// `--event` wait, so the two travel together. +/// The desktop-wide waits, grouped out of [`WaitModeArgs`] to keep it under +/// the repo's field-count limit: `--event` with its `--window-id` narrowing, +/// and `--surface`. #[derive(Args, Debug, Deserialize)] #[serde(deny_unknown_fields)] pub(crate) struct WaitEventArgs { @@ -249,6 +249,12 @@ pub(crate) struct WaitEventArgs { help = "Optional: narrow --event window-opened/window-closed/focus-changed to one window ID" )] pub window_id: Option<String>, + #[arg( + long, + value_name = "KIND", + help = "Block until a surface of this kind is open in the app: popover, sheet, alert, menu, or any of them. A surface already open counts, so it also finds one that opened just after a click" + )] + pub surface: Option<String>, } #[derive(Args, Debug, Deserialize)] diff --git a/src/dispatch/system.rs b/src/dispatch/system.rs index 26d24e0906..419e1a9469 100644 --- a/src/dispatch/system.rs +++ b/src/dispatch/system.rs @@ -29,6 +29,7 @@ pub(super) fn wait( args.mode.menu, args.mode.menu_closed, args.mode.notification, + args.event.surface.as_deref(), )?, event: args.event.event, window_id: args.event.window_id, diff --git a/tests/fixtures/contract/actions-click.json b/tests/fixtures/contract/actions-click.json index a5160ed24c..168d067b33 100644 --- a/tests/fixtures/contract/actions-click.json +++ b/tests/fixtures/contract/actions-click.json @@ -1 +1 @@ -{"changed":{"action":"click","details":{"auto_wait":{"lease_contention_count":0,"lease_hold_ms":0,"read_only_preflight_attempts":0,"read_only_resolve_attempts":0}},"disposition":{"delivery":"delivered_verified","retry":"unsafe"},"post_state":{"enabled":true,"hidden":false,"offscreen":false,"role":"checkbox","states":["checked"]},"steps":[{"label":"press","mechanism":"semantic_api","outcome":"succeeded","verified":true}]},"uncertain":{"code":"APP_UNRESPONSIVE","details":{"ax_error":-25204,"post_action_observation":{"elapsed_ms":0,"expected":"present","kind":"post_action_observation","outcome":"expected_state_observed","process_identity":{"pid":1,"process_instance":"test-instance"},"selector":":Agree","selector_matches":true,"surface":"menubar"}},"disposition":{"delivery":"delivery_uncertain","retry":"unsafe"},"message":"Application 'TargetApp' is not responding","suggestion":"Wait for the app to recover or force-quit it before retrying automation"}} +{"changed":{"action":"click","details":{"auto_wait":{"lease_contention_count":0,"lease_hold_ms":0,"read_only_preflight_attempts":0,"read_only_resolve_attempts":0},"surfaces":"not_read"},"disposition":{"delivery":"delivered_verified","retry":"unsafe"},"post_state":{"enabled":true,"hidden":false,"offscreen":false,"role":"checkbox","states":["checked"]},"steps":[{"label":"press","mechanism":"semantic_api","outcome":"succeeded","verified":true}]},"uncertain":{"code":"APP_UNRESPONSIVE","details":{"ax_error":-25204,"post_action_observation":{"elapsed_ms":0,"expected":"present","kind":"post_action_observation","outcome":"expected_state_observed","process_identity":{"pid":1,"process_instance":"test-instance"},"selector":":Agree","selector_matches":true,"surface":"menubar"}},"disposition":{"delivery":"delivery_uncertain","retry":"unsafe"},"message":"Application 'TargetApp' is not responding","suggestion":"Wait for the app to recover or force-quit it before retrying automation"}} diff --git a/tests/fixtures/contract/lifecycle-delivery.json b/tests/fixtures/contract/lifecycle-delivery.json index c316065fba..7d858f4050 100644 --- a/tests/fixtures/contract/lifecycle-delivery.json +++ b/tests/fixtures/contract/lifecycle-delivery.json @@ -1 +1 @@ -{"focus":{"action":"focus","details":{"auto_wait":{"lease_contention_count":0,"lease_hold_ms":0,"read_only_preflight_attempts":0,"read_only_resolve_attempts":0}},"disposition":{"delivery":"delivered_verified","retry":"unsafe"},"steps":[{"label":"press","mechanism":"semantic_api","outcome":"succeeded","verified":true}]},"scroll":{"action":"scroll","details":{"auto_wait":{"lease_contention_count":0,"lease_hold_ms":0,"read_only_preflight_attempts":0,"read_only_resolve_attempts":0}},"disposition":{"delivery":"delivered_verified","retry":"unsafe"},"steps":[{"label":"press","mechanism":"semantic_api","outcome":"succeeded","verified":true}]},"scroll_to":{"action":"scroll-to","details":{"auto_wait":{"lease_contention_count":0,"lease_hold_ms":0,"read_only_preflight_attempts":0,"read_only_resolve_attempts":0}},"disposition":{"delivery":"delivered_verified","retry":"unsafe"},"steps":[{"label":"press","mechanism":"semantic_api","outcome":"succeeded","verified":true}]},"select":{"action":"select","details":{"auto_wait":{"lease_contention_count":0,"lease_hold_ms":0,"read_only_preflight_attempts":0,"read_only_resolve_attempts":0}},"disposition":{"delivery":"delivered_verified","retry":"unsafe"},"steps":[{"label":"press","mechanism":"semantic_api","outcome":"succeeded","verified":true}]}} +{"focus":{"action":"focus","details":{"auto_wait":{"lease_contention_count":0,"lease_hold_ms":0,"read_only_preflight_attempts":0,"read_only_resolve_attempts":0}},"disposition":{"delivery":"delivered_verified","retry":"unsafe"},"steps":[{"label":"press","mechanism":"semantic_api","outcome":"succeeded","verified":true}]},"scroll":{"action":"scroll","details":{"auto_wait":{"lease_contention_count":0,"lease_hold_ms":0,"read_only_preflight_attempts":0,"read_only_resolve_attempts":0}},"disposition":{"delivery":"delivered_verified","retry":"unsafe"},"steps":[{"label":"press","mechanism":"semantic_api","outcome":"succeeded","verified":true}]},"scroll_to":{"action":"scroll-to","details":{"auto_wait":{"lease_contention_count":0,"lease_hold_ms":0,"read_only_preflight_attempts":0,"read_only_resolve_attempts":0}},"disposition":{"delivery":"delivered_verified","retry":"unsafe"},"steps":[{"label":"press","mechanism":"semantic_api","outcome":"succeeded","verified":true}]},"select":{"action":"select","details":{"auto_wait":{"lease_contention_count":0,"lease_hold_ms":0,"read_only_preflight_attempts":0,"read_only_resolve_attempts":0},"surfaces":"not_read"},"disposition":{"delivery":"delivered_verified","retry":"unsafe"},"steps":[{"label":"press","mechanism":"semantic_api","outcome":"succeeded","verified":true}]}}