Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(cua-driver)!: resolve element tokens against a snapshot store invalidated on read (#3873)
r33drichards61f1c0ab255a
diff --git a/docs/content/docs/concepts/capture-and-delivery-modalities.mdx b/docs/content/docs/concepts/capture-and-delivery-modalities.mdxindex ce6d66d3f8..ec725b6ed8 100644--- a/docs/content/docs/concepts/capture-and-delivery-modalities.mdx+++ b/docs/content/docs/concepts/capture-and-delivery-modalities.mdx@@ -11,7 +11,7 @@ Every Cua Driver action is shaped by four things: **what the agent observes**, *`get_window_state(pid, window_id)` returns **both the accessibility tree and a screenshot by default**, in one call. There is no capture mode to pick: you ground on the tree and the screenshot together and cross-check one against the other. This matters because the tree *lies* on some surfaces: it can expose useful structure while still echoing a write the app did not apply, omitting the rendered value, or reporting geometry that disagrees with the pixels. A grounding screenshot is always present, so when the tree looks wrong you check the pixels in the *same* response.-The accessibility tree is the ground truth for *what is clickable*: roles, labels, advertised actions, and an `element_index` handle on every actionable element. The screenshot tells you *which one*. It disambiguates repeated or empty labels and shows captions, colors, and layout the tree omits, which is common in Chromium and Electron. They come back together because each catches what the other misses.+The accessibility tree is the ground truth for *what is clickable*: roles, labels, advertised actions, and an `element_token` handle on every actionable element. The screenshot tells you *which one*. It disambiguates repeated or empty labels and shows captions, colors, and layout the tree omits, which is common in Chromium and Electron. They come back together because each catches what the other misses.When neither the tree nor typed browser state exposes the target, the optional perception extension can parse that same screenshot into labelled regions; see [How the perception extension works](/concepts/how-the-perception-extension-works).@@ -25,12 +25,12 @@ You don't pick a capture mode; you pick **how you address the target** on the ac| Rung | Address with | Delivered through | Properties ||---|---|---|---|-| **element ax action** | `element_index` / `element_token` | the accessibility rung: UIA Invoke (Windows), `AXPerformAction` (macOS), AT-SPI `doAction` (Linux) | Backgroundable, z-order-independent, and the only **driver-verifiable** rung. |+| **element ax action** | `element_token` | the accessibility rung: UIA Invoke (Windows), `AXPerformAction` (macOS), AT-SPI `doAction` (Linux) | Backgroundable, z-order-independent, and the only **driver-verifiable** rung. || **element px action** | `x, y` | the pixel rung, reading the coordinate straight off the screenshot already in the `get_window_state` response | Best-effort; the caller confirms the effect off the screenshot. |Default to the element ax action because the driver can verify it and often keep it in the background. Drop to an element px action when the tree cannot disambiguate repeated or empty labels, when it is empty (`degraded`, a non-AX surface), when an action came back `suspected_noop`, or when the tree disagrees with the pixels. You never re-capture to switch rungs. The screenshot is already in the snapshot, so you only change *how you address* the target.-Both rungs apply to the **keyboard family** (`type_text`, `press_key`, `hotkey`) as well as the pointer tools. Address by `element_index` (ax) to target a field with no pre-click. Address by `x, y` (px) to pixel-click at `(x, y)`, establish real renderer focus, and deliver the keystroke(s) to the now-focused element. The px form is the one-call path for Chromium/Electron inputs the AX layer cannot focus: `type_text({ pid, window_id, x, y, text })` focuses and types in a single call. The two forms are mutually exclusive. `set_value` is the exception: it stays ax-only because it sets the value of a non-text control like a dropdown, checkbox, or slider.+Both rungs apply to the **keyboard family** (`type_text`, `press_key`, `hotkey`) as well as the pointer tools. Address by `element_token` (ax) to target a field with no pre-click. Address by `x, y` (px) to pixel-click at `(x, y)`, establish real renderer focus, and deliver the keystroke(s) to the now-focused element. The px form is the one-call path for Chromium/Electron inputs the AX layer cannot focus: `type_text({ pid, window_id, x, y, text })` focuses and types in a single call. The two forms are mutually exclusive. `set_value` is the exception: it stays ax-only because it sets the value of a non-text control like a dropdown, checkbox, or slider.### 3. Delivery: how input is delivered@@ -41,7 +41,7 @@ Set `delivery_mode` per call on the input family (`click`, `double_click`, `righ| `background` (default) | Input is routed to the target process/window/element directly. The user's frontmost app, real cursor, and window z-order are untouched when the target surface supports background delivery. See [Best-effort background](/concepts/the-no-foreground-contract). || `foreground` | The target is briefly fronted for that action, input lands on the now-active window, then the prior frontmost is restored. Use this when a background attempt did not land, or when the app only accepts events while foregrounded (DirectInput games, raw-input canvases). |-Only `background` and `foreground` are valid; the historical `auto` heuristic is removed. At runtime, omitted or unknown values fall back to `background` for safety. Element ax actions (`element_index`) address an element instead of the focused window, so they hold the background path without any `delivery_mode` flag. The delivery axis matters most for the pixel rung (`x, y`), where `background` routes the event to the target and `foreground` raises the window first.+Only `background` and `foreground` are valid; the historical `auto` heuristic is removed. At runtime, omitted or unknown values fall back to `background` for safety. Element ax actions (`element_token`) address an element instead of the focused window, so they hold the background path without any `delivery_mode` flag. The delivery axis matters most for the pixel rung (`x, y`), where `background` routes the event to the target and `foreground` raises the window first.`bring_to_front` is not a normal escalation step. Reserve it for focus-proxy surfaces that must stay foreground across multiple calls, such as a remote desktop session. For an ordinary `background_unavailable` response, retry only the refused action with `delivery_mode:"foreground"`.diff --git a/docs/content/docs/concepts/the-no-foreground-contract.mdx b/docs/content/docs/concepts/the-no-foreground-contract.mdxindex e3bfcb1561..a5fb884b49 100644--- a/docs/content/docs/concepts/the-no-foreground-contract.mdx+++ b/docs/content/docs/concepts/the-no-foreground-contract.mdx@@ -78,7 +78,7 @@ The agent tests and fixes an app while the terminal remains in front.The safest ladder is:-1. Act by `element_index` in the background.+1. Act by `element_token` in the background.2. If the element path is unavailable or unverifiable, act by `x, y` from the same window screenshot.3. If the app still rejects the action, retry that one action with `delivery_mode: "foreground"`.diff --git a/docs/content/docs/how-to-guides/driver/connect-your-agent.mdx b/docs/content/docs/how-to-guides/driver/connect-your-agent.mdxindex ca0d9b3f8a..9b8c842d2f 100644--- a/docs/content/docs/how-to-guides/driver/connect-your-agent.mdx+++ b/docs/content/docs/how-to-guides/driver/connect-your-agent.mdx@@ -261,5 +261,5 @@ Driver in the underlying harness, then launch that harness from [T3 Code](/use-c## Next steps- [Keep Cua Driver running](/how-to-guides/driver/keep-running): keep the daemon alive across reboots and sessions.-- [Agent action policy](/reference/cua-driver/action-selection-policy): behavior agent wrappers should follow for `element_index`, `x,y`, and foreground escalation.+- [Agent action policy](/reference/cua-driver/action-selection-policy): behavior agent wrappers should follow for `element_token`, `x,y`, and foreground escalation.- [MCP tools](/reference/cua-driver/mcp-tools): inspect every exposed tool and parameter.diff --git a/docs/content/docs/how-to-guides/driver/update.mdx b/docs/content/docs/how-to-guides/driver/update.mdxindex 5f6933a1e9..2b7c7eb074 100644--- a/docs/content/docs/how-to-guides/driver/update.mdx+++ b/docs/content/docs/how-to-guides/driver/update.mdx@@ -46,6 +46,42 @@ in `error`. A saved stable/nightly preference is ignored and left unchanged.The vendor update and channel instructions that follow apply to installationsnot managed by pacman.+## Before updating to token-only element targeting++Releases that include [#3873](https://github.com/trycua/cua/pull/3873) address+accessibility elements only by `element_token`. Update scripts, agents, and+wrappers that act on elements before you update:++1. Pass `element_token` instead of `element_index` or `snapshot_id`. Read it+ from `structuredContent.elements[].element_token` in the latest+ `get_window_state` result and send it with the window's `pid`. The token+ names its window, so `window_id` is optional; a different `window_id` is+ refused with `conflicting_element_target`. `get_window_state` still returns+ `element_index` and `snapshot_id` for display and correlation.+2. Remove arguments that a tool does not advertise. Tools with closed input+ schemas now refuse unknown argument names with `invalid_arguments`+ (`<tool>: unknown argument <name>`) instead of ignoring them. This includes+ `element_index` and `snapshot_id` on action tools, and `from_zoom` on the+ Windows `type_text`, `press_key`, and `hotkey` tools, which Windows read+ without advertising. Pass window coordinates or an `element_token` there.+3. Read a window before you use window-relative pixels. Pixel actions and+ `zoom` against a window target return `screenshot_context_missing` until+ the same session has read that window with a screenshot; Driver no longer+ assumes native pixels. `from_zoom` coordinates return `zoom_context_missing`+ once a newer read replaces the zoomed snapshot. Coordinates for a desktop+ target are unaffected.+4. Re-read after a stale token. Each `get_window_state` call replaces the+ previous snapshot of that window and lists the ids it replaced in+ `invalidated_snapshot_ids`. An older token, or a token from another Driver+ runtime, is refused with `stale_element_token`, which lists the process's+ current snapshots. Earlier releases reported a token from another runtime+ as `generation_mismatch`.++Each one-shot `cua-driver call` without a `session` label runs in its own+disposable session, and that session's snapshots are retired when the call+returns. Pass the same `session` label to the read and to the actions that use+its tokens or pixels.+## Before updating from 0.12.x to 0.13.0The installer command, CLI/MCP connection flow, tool names, and Python anddiff --git a/docs/content/docs/reference/cua-driver/action-selection-policy.mdx b/docs/content/docs/reference/cua-driver/action-selection-policy.mdxindex 4754675fc5..c19bdf9286 100644--- a/docs/content/docs/reference/cua-driver/action-selection-policy.mdx+++ b/docs/content/docs/reference/cua-driver/action-selection-policy.mdx@@ -6,7 +6,7 @@ description: "Behavior an agent should follow when choosing element, pixel, pageThis policy describes how an agent should choose Cua Driver action parameters. It is meant for agent prompts, wrappers, and evaluators. It is not a user walkthrough.Use it when the agent must decide what to pass to `click`, `type_text`,-`get_window_state`, and related tools: `element_index` versus `x, y`,+`get_window_state`, and related tools: `element_token` versus `x, y`,`delivery_mode: background` versus `foreground`, and a window versus desktoptarget.@@ -16,17 +16,17 @@ The agent should already be connected to the driver and able to launch an app an## Start on the accessibility path (the default)-The agent should default to the **element ax action with background delivery**. Act by `element_index`. It is the only rung the driver can verify, it avoids foregrounding when the target surface supports it, and it works on Windows, macOS, and Linux (X11 and Wayland).+The agent should default to the **element ax action with background delivery**. Act by `element_token`. It is the only rung the driver can verify, it avoids foregrounding when the target surface supports it, and it works on Windows, macOS, and Linux (X11 and Wayland).Read the window once, then act on an element from that snapshot. The snapshot already carries the screenshot too, so the agent does not re-capture to switch how it addresses the target:```jsonc// 1. snapshot: returns the accessibility tree AND a screenshot by defaultget_window_state({ pid, window_id })-// → elements[], each with an element_index and a frame, plus a grounding screenshot+// → elements[], each with an element_token and a frame, plus a grounding screenshot-// 2. act by element_index: the element ax action, background by default-click({ pid, window_id, element_index: 12 })+// 2. act by element_token: the element ax action, background by default+click({ pid, element_token: "s0000002a:12" })type_text({ pid, text: "hello" })```@@ -36,7 +36,7 @@ When the agent is only re-indexing before an element ax action and does not needEvery action response carries the signals that tell the agent the next rung. Walk the ladder in order, and only step down when the response says to:-1. **Element ax action, background (the default).** Act by `element_index`. If the response shows `effect: "confirmed"`, the driver read the result back. If `get_window_state` came back `degraded` (empty AX tree), an action returns `effect: "suspected_noop"` (the AX action ran but likely no-op'd), an action returns `effect: "unverifiable"` on an echo-prone surface, or the tree disagrees with the screenshot (an `h:1` or off-viewport row), follow `escalation.recommended`.+1. **Element ax action, background (the default).** Act by `element_token`. If the response shows `effect: "confirmed"`, the driver read the result back. If `get_window_state` came back `degraded` (empty AX tree), an action returns `effect: "suspected_noop"` (the AX action ran but likely no-op'd), an action returns `effect: "unverifiable"` on an echo-prone surface, or the tree disagrees with the screenshot (an `h:1` or off-viewport row), follow `escalation.recommended`.2. **Element px action, background.** When `escalation.recommended` is `"px"`, pick the target pixel from the screenshot already in the `get_window_state` response and click it. Coordinates are window-relative for a windowed target.@@ -48,7 +48,7 @@ Every action response carries the signals that tell the agent the next rung. WalUse the same px form for keyboard fallback. If AX `type_text`, `press_key`, or `hotkey` returns `effect: "unverifiable"` on Electron/Chromium, retry with `x, y`: the tool pixel-clicks to focus, then sends the keys.```jsonc- type_text({ pid, window_id, element_index: 18, text: "hello" })+ type_text({ pid, element_token: "s0000002a:18", text: "hello" })// → { effect: "unverifiable", escalation: { recommended: "px", reason: "..." } }type_text({ pid, window_id, x: 320, y: 210, text: "hello" })@@ -61,7 +61,7 @@ Every action response carries the signals that tell the agent the next rung. Wal3. **Browser-tab DOM.** When `escalation.recommended` is `"page"`, switch to the `page` tool for browser-tab DOM work instead of retrying the AX write.```jsonc- type_text({ pid, window_id, element_index: 18, text: "hello" })+ type_text({ pid, element_token: "s0000002a:18", text: "hello" })// → { effect: "unverifiable", escalation: { recommended: "page", reason: "..." } }page({@@ -89,7 +89,7 @@ Two additive fields make the ladder explicit, so the agent escalates from data r- **`escalation`**: present when there is a next rung: `{ recommended: "px" | "foreground" | "page", reason }`. A `degraded` `get_window_state` carries the same hint (recommending `px`).```jsonc-click({ pid, window_id, element_index: 12 })+click({ pid, element_token: "s0000002a:12" })// → { effect: "suspected_noop", escalation: { recommended: "px", reason: "..." } }```@@ -133,7 +133,7 @@ exact window target, or use`target: {kind: "desktop", display_id: "primary"}` for screen-absolute work.**Problem: keystrokes don't land on a Linux app.**-On native Wayland, raw keys have no background path. Type into accessible fields with `type_text`, drive controls by `element_index`, or run the app under XWayland. See [Known limits](/reference/cua-driver/limits#native-wayland-background-keyboard-input-is-focus-bound).+On native Wayland, raw keys have no background path. Type into accessible fields with `type_text`, drive controls by `element_token`, or run the app under XWayland. See [Known limits](/reference/cua-driver/limits#native-wayland-background-keyboard-input-is-focus-bound).## Relateddiff --git a/docs/content/docs/reference/cua-driver/cli-reference.mdx b/docs/content/docs/reference/cua-driver/cli-reference.mdxindex 4b68614615..9935e75588 100644--- a/docs/content/docs/reference/cua-driver/cli-reference.mdx+++ b/docs/content/docs/reference/cua-driver/cli-reference.mdx@@ -88,7 +88,7 @@ On Windows and Linux, bare cua-driver mcp owns its runtime directly and shuts itRun Cua Driver as a long-running daemon.-The daemon owns per-process state such as element-index caches, recording state, and cursor overlay state.+The daemon owns per-process state such as accessibility snapshots, recording state, and cursor overlay state.**Options:**diff --git a/docs/content/docs/reference/cua-driver/contracts.mdx b/docs/content/docs/reference/cua-driver/contracts.mdxindex 06dd324e8d..a46cb7bc2e 100644--- a/docs/content/docs/reference/cua-driver/contracts.mdx+++ b/docs/content/docs/reference/cua-driver/contracts.mdx@@ -17,7 +17,7 @@ MCP may own that runtime directly or select `cua-driver serve` explicitly.| Dimension | CLI (`call`) | MCP (`mcp`) ||---|---|---|| Lifetime | each one-shot call gets a disposable implicit session; the selected service may own other durable state | one implicit session per authenticated transport connection |-| `element_index` cache | owned by the selected service; survives until invalidation or service restart | owned by the MCP runtime; lives across calls |+| snapshot store | owned by the selected service; survives until invalidation or service restart | owned by the MCP runtime; lives across calls || Public label | optional `session`; it does not carry authority | optional `session`; it does not carry authority || Where `set_config` lands | the persisted global default when no public session is supplied | an in-memory override when a public session is supplied || Agent cursor | initialized for the call and cleaned up with its disposable session | initialized on the first cursor-bearing action and reused on later unnamed calls |@@ -132,12 +132,12 @@ Every input tool chooses its route from the target and action arguments:| Arguments | Path | Behavior ||---|---|---|-| window target plus `element_index` | accessibility action | UIA Invoke, `AXPerformAction`, or AT-SPI. Background, no cursor move, no focus steal. |+| `element_token` | accessibility action | UIA Invoke, `AXPerformAction`, or AT-SPI. Background, no cursor move, no focus steal. || window target plus `x`, `y` | window-local pixel | coordinates are relative to that window's screenshot. For keyboard tools, this form can click the coordinate to establish renderer focus before sending keys. || desktop target plus `x`, `y` | screen-absolute | true screen pixels on the primary display, with foreground delivery |The keyboard family's coordinate form is mutually exclusive with-`element_index`. A malformed, mixed, or ambiguous target fails before+`element_token`. A malformed, mixed, or ambiguous target fails beforeauthorization and platform dispatch.---@@ -150,12 +150,12 @@ delivery mode:| Target | Action rung | `delivery_mode` | Valid? | Why ||---|---|---|---|---|-| window | `ax` (`element_index`) | `background` | ✅ | Semantic action on a background-capable window. |-| window | `ax` (`element_index`) | `foreground` | ✅ | Activate, then act by element. |+| window | `ax` (`element_token`) | `background` | ✅ | Semantic action on a background-capable window. |+| window | `ax` (`element_token`) | `foreground` | ✅ | Activate, then act by element. || window | `px` (`x`, `y`) | `background` | ✅ | Act at a coordinate from the window screenshot without raising the target when supported. || window | `px` (`x`, `y`) | `foreground` | ✅ | Activate, then act by coordinate. || desktop | `px` (`x`, `y`) | `foreground` | ✅ | Act at screen coordinates on the primary display. |-| desktop | `ax` (`element_index`) | any | ❌ | A desktop target has no window element tree. |+| desktop | `ax` (`element_token`) | any | ❌ | A desktop target has no window element tree. || desktop | any | `background` | ❌ | Screen input lands on the active desktop and has no per-process background route. |The driver enforces these rejections before it sends input.diff --git a/docs/content/docs/reference/cua-driver/limits.mdx b/docs/content/docs/reference/cua-driver/limits.mdxindex 2effdaaf99..e59463758a 100644--- a/docs/content/docs/reference/cua-driver/limits.mdx+++ b/docs/content/docs/reference/cua-driver/limits.mdx@@ -92,11 +92,11 @@ does not imply arbitrary raw background PX delivery on Wayland.**Workarounds, in order of preference:**-1. Use `right_click({pid, element_index})` on AX-addressable targets (links, buttons, toolbar items). AX delivery sidesteps the renderer filter entirely.+1. Use `right_click({pid, element_token})` on AX-addressable targets (links, buttons, toolbar items). AX delivery sidesteps the renderer filter entirely.2. For context menus on pure web content (nothing in the AX tree), activate Chrome briefly and fall back to a HID-tap right-click. This interrupts best-effort background behavior for that one click.<Callout type="info">- Element-indexed right-click (`right_click` with `element_index`) works fine. The limit is+ Element right-click (`right_click` with `element_token`) works fine. The limit isspecifically pixel right-click on non-AX Chromium web content.</Callout>@@ -165,13 +165,13 @@ does not imply arbitrary raw background PX delivery on Wayland.## Minimized windows silently drop keyboard commits-**Symptom:** `press_key({pid, element_index, key: "return"})` on a text field in a minimized window returns success, but the field doesn't commit. The macOS system-alert beep fires, or nothing happens.+**Symptom:** `press_key({pid, element_token, key: "return"})` on a text field in a minimized window returns success, but the field doesn't commit. The macOS system-alert beep fires, or nothing happens.**Cause:** AX reads and AX clicks propagate through to minimized windows normally, but keyboard-commit events (Return, Space, Tab) require renderer focus, which AX focus does not confer on a minimized window. This is a macOS-wide behavior.**Workarounds:**-1. Use `set_value({pid, element_index, value: "..."})` to write the field's value directly. No keyboard event involved; no focus handoff required.+1. Use `set_value({pid, element_token, value: "..."})` to write the field's value directly. No keyboard event involved; no focus handoff required.2. AX-click a commit-equivalent button (Go, Submit, Send, OK) rather than relying on Return.3. Restore the window through the Dock or an application-specific Window menu command. This interrupts best-effort background behavior for that window. (`Cmd+M` minimizes a window; it does not restore one.)@@ -201,7 +201,7 @@ not require the same portal route.**Workarounds:**1. Type into accessible text fields with `type_text`. AT-SPI `insertText` writes the field directly, with no synthetic key event involved.-2. Drive controls by `element_index` (`click`, `set_value`) instead of keyboard shortcuts where an equivalent control exists.+2. Drive controls by `element_token` (`click`, `set_value`) instead of keyboard shortcuts where an equivalent control exists.3. Retry with `delivery_mode:"foreground"` when the desktop exposes a verifiedactivation and input adapter.4. Run the app under XWayland (`GDK_BACKEND=x11` / `QT_QPA_PLATFORM=xcb`). It@@ -253,8 +253,7 @@ the window-local screenshot space. `double_click` currently labels these asscreen coordinates in its generated argument reference, but its implementationuses the same window-local conversion as the other pixel actions.-**What to do:** prefer `element_token`, or `element_index` with the matching-`snapshot_id`. The accessibility path carries no coordinates, so it is+**What to do:** prefer `element_token`. The accessibility path carries no coordinates, so it isunaffected by this mismatch, and it also works on backgrounded windows. Reachfor a pixel action only on canvas, WebGL, or custom-drawn surfaces that exposeno element.@@ -322,7 +321,7 @@ Cua Driver is constrained by the macOS permission model. Two relevant grants:| Grant | Required for || ----- | ------------ |-| **Accessibility** (System Settings → Privacy & Security → Accessibility) | Every AX read, every element-indexed click, every keyboard/text primitive. Without it, `check_permissions` returns `accessibility: false` and every tool returns a structured error. |+| **Accessibility** (System Settings → Privacy & Security → Accessibility) | Every AX read, every `element_token` click, every keyboard/text primitive. Without it, `check_permissions` returns `accessibility: false` and every tool returns a structured error. || **Screen Recording** | Screenshots. `get_window_state` returns both the accessibility tree and a screenshot by default; without this grant it returns the tree only (no PNG). The tree path still works. |Grants are tied to the `CuaDriver.app` bundle identity (`com.trycua.driver`). The Rust build and installer preserve this identity, so TCC grants persist across rebuilds and updates.diff --git a/docs/content/docs/reference/cua-driver/mcp-tool-notes.mdx b/docs/content/docs/reference/cua-driver/mcp-tool-notes.mdxindex bca35f8e61..4e6ab23c89 100644--- a/docs/content/docs/reference/cua-driver/mcp-tool-notes.mdx+++ b/docs/content/docs/reference/cua-driver/mcp-tool-notes.mdx@@ -16,7 +16,7 @@ Several parameters are a **shared cross-platform contract**: the same JSON shape| `delivery_mode` | the input family (`click`, `double_click`, `right_click`, `drag`, `scroll`, `type_text`, `press_key`, `hotkey`) | `"background"` (default) tries to inject without fronting or raising the target. See [Best-effort background](/concepts/the-no-foreground-contract). `"foreground"` briefly fronts the target, acts, then restores the prior frontmost. Use it when a background attempt did not land. Legacy `"auto"` is removed; omitted or unknown values fall back to `"background"` for safety. || `capture_mode` | `get_window_state` | **Deprecated and ignored.** Still accepted for back-compat so old callers do not error, but it has no effect. `get_window_state` always returns both the accessibility tree and a screenshot by default. There is no `ax`/`vision`/`som` capture choice; the modality (`ax` vs `px`) is chosen at action time by how you address the target. || `include_screenshot` | `get_window_state` | Boolean, default `true` (returns the tree **and** a screenshot). Set `false` to skip the screenshot grab and return the tree only when re-indexing before an element-`ax` action. |-| `modifier`, `button`, `element_index`, `element_token` | pointer and element tools | Held modifier keys, mouse button, and the two element-addressing handles. |+| `modifier`, `button`, `element_token` | pointer and element tools | Held modifier keys, mouse button, and the element-addressing handle. |### Required parametersdiff --git a/docs/content/docs/reference/cua-driver/mcp-tools-linux.mdx b/docs/content/docs/reference/cua-driver/mcp-tools-linux.mdxindex 86bd61736d..4933d41c24 100644--- a/docs/content/docs/reference/cua-driver/mcp-tools-linux.mdx+++ b/docs/content/docs/reference/cua-driver/mcp-tools-linux.mdx@@ -48,7 +48,9 @@ Running apps come from `/proc`. Installed apps come from XDG Desktop Entry filesUse this for "is X installed?" as well as "is X running?". For per-window state — visibility, geometry, titles — call list_windows instead.-**Arguments:** none.+**Arguments:**++- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.### `list_windows`@@ -58,14 +60,15 @@ List top-level windows. Each record includes z_index (integer or null; higher va- `on_screen_only` (boolean, optional): When true, filter to visible windows only. Default false.- `pid` (integer, optional)+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.### `get_window_state`-Walk a running app's AT-SPI tree and return BOTH a structured `elements` array (preferred) AND a Markdown rendering of the same tree (back-compat). Every actionable element is tagged with [element_index N] in the markdown and as `element_index` in the structured array.+Walk a running app's AT-SPI tree and return BOTH a structured `elements` array (preferred) AND a Markdown rendering of the same tree (back-compat). Every actionable element is tagged with [element_index N] in the markdown and as `element_index` in the structured array; pass each element's `element_token` to `click`, `type_text`, `set_value`, etc.PREFERRED CONSUMERS read `structuredContent.elements` (one entry per indexed row with `element_index`, `role`, `label`, `value`, `enabled`, `selected`, `actions` (names of AT-SPI actions exposed by the element, omitted when empty), `frame: {x,y,w,h}` when AT-SPI reports usable bounds, `parent_index`, `depth`). The markdown `tree_markdown` stays available and unchanged in shape for existing text-parsing callers — but new fields will only be added to the structured side. Set `query` to project BOTH representations to matching rows plus their ancestor chain while preserving original indices. `total_element_count` reports the complete snapshot and `returned_element_count` reports the projection.-Always returns BOTH the element tree AND a screenshot — ground on both and cross-check (the tree lies on some surfaces). Choose the modality at ACTION time: an element ax action (element_index/element_token → accessibility rung) or an element px action (x,y → pixel rung off this screenshot). capture_mode is deprecated and ignored. On Wayland, where output capture cannot prove the requested surface's identity, the truthful tree is returned without a screenshot and `screenshot_error.code` is `surface_identity_unproven`.+Always returns BOTH the element tree AND a screenshot — ground on both and cross-check (the tree lies on some surfaces). Choose the modality at ACTION time: an element ax action (element_token → accessibility rung) or an element px action (x,y → pixel rung off this screenshot). capture_mode is deprecated and ignored. On Wayland, where output capture cannot prove the requested surface's identity, the truthful tree is returned without a screenshot and `screenshot_error.code` is `surface_identity_unproven`.The mirror image: pass `include_accessibility_tree:false` to SKIP the AT-SPI walk entirely and return just the screenshot plus window metadata (window_bounds, app_name, window_title) — the capture-only path for a live window preview / picture-in-picture. Setting BOTH `include_accessibility_tree:false` and `include_screenshot:false` is an error. Optional `max_dimension` caps the returned screenshot's long edge in pixels for a cheap thumbnail.@@ -75,11 +78,11 @@ TIME BUDGET: `timeout_ms` (default 1000) bounds the whole AT-SPI walk. Large appSCREENSHOT SCALE: the screenshot is delivered at or below 1.15 megapixels (long edge <= max_image_dimension, 1568 by default), because larger images are downsized before a model reads them and its pixel coordinates would then be uniformly short. Element `screenshot_frame`s and x/y for the pointer tools are pixels of the delivered screenshot (`frame` stays in screen coordinates, as on every platform); `frame_scale` < 1 reports the downsizing. An explicit per-call `max_image_dimension` (0 = native) replaces this cap.-POPUP MENUS: a context menu / popover / combo list is an override-redirect window that list_windows never shows. A click or right_click that opened one names it in its result (`popup: {window_id, bounds, title}`); pass that window_id here to walk the popup's own AT-SPI toplevel so its menu items get element indices (then click them by element_index). Omitting window_id while a popup of this pid is open walks that popup.+POPUP MENUS: a context menu / popover / combo list is an override-redirect window that list_windows never shows. A click or right_click that opened one names it in its result (`popup: {window_id, bounds, title}`); pass that window_id here to walk the popup's own AT-SPI toplevel so its menu items get element indices (then click them by element_token). Omitting window_id while a popup of this pid is open walks that popup.**Arguments:**-- `capture_mode` (string, optional): DEPRECATED and ignored. get_window_state always returns BOTH the element tree and a screenshot — ground on both. The modality is chosen at action time by how you address the target: an element ax action (element_index/element_token) or an element px action (x,y). Any value (including the old "som"/"screenshot" aliases) is accepted but has no effect.+- `capture_mode` (string, optional): DEPRECATED and ignored. get_window_state always returns BOTH the element tree and a screenshot — ground on both. The modality is chosen at action time by how you address the target: an element ax action (element_token) or an element px action (x,y). Any value (including the old "som"/"screenshot" aliases) is accepted but has no effect.- `include_accessibility_tree` (boolean, optional): Default true — walk the AT-SPI tree and return `elements` + `tree_markdown` alongside the screenshot. Set false to SKIP the AT-SPI walk entirely and return just the screenshot plus window metadata (window_bounds, app_name, window_title) — the capture-only path for a live window preview / picture-in-picture. Mirrors include_screenshot. Setting BOTH include_accessibility_tree:false AND include_screenshot:false is an error (nothing to return).- `include_screenshot` (boolean, optional): Default true — returns a grounding screenshot alongside the tree. Set false to skip the grab and return tree only (the cheap path for re-indexing before an element ax action).- `max_depth` (integer, optional): Cap on the AT-SPI tree walk depth. Omit for the default (uncapped). Lower for deeply nested apps. range: 1–unbounded@@ -103,7 +106,9 @@ Return a lightweight snapshot of the desktop: running processes and on-screen viFor the full AT-SPI subtree of a single window (with interactive element indices you can click by), use get_window_state instead — this is a fast discovery read.-**Arguments:** none.+**Arguments:**++- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.### `get_desktop_state`@@ -135,7 +140,9 @@ Return the current mouse cursor position in screen points (origin top-left).Return current cua-driver-rs configuration.-**Arguments:** none.+**Arguments:**++- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.### `get_recording_state`@@ -143,7 +150,9 @@ Report the current trajectory recorder state: whether recording is enabled, thePure read-only.-**Arguments:** none.+**Arguments:**++- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.### `get_agent_cursor_state`@@ -169,6 +178,7 @@ Launch a Linux app in the background. Provide launch_path (preferred — round-t- `bundle_id` (string, optional): Ignored on Linux (macOS/Windows concept).- `launch_path` (string, optional): Round-trip the `launch_path` returned by `list_apps` — the Exec= command from the .desktop file with XDG field codes already stripped. Highest precedence on Linux; spawned directly via the system shell.- `name` (string, optional): App name or command to launch. Tried as a direct command first, then matched against installed .desktop applications (exact display name, desktop-file id, or Exec basename; else an unambiguous display-name substring).+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.- `urls` (array of string, optional): URLs to open via xdg-open.### `kill_app`@@ -178,6 +188,7 @@ Force-terminate a process by pid (kill -9 equivalent on Linux). Use as escalatio**Arguments:**- `pid` (integer, required): PID of the process to terminate.+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.```json{"pid":844}@@ -190,6 +201,7 @@ Persistently activate a window so subsequent input lands on it. This deliberatel**Arguments:**- `pid` (integer, required)+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.- `window_id` (integer, optional): X11 window id (xid) to activate. If omitted, the first window of `pid` is used.```json@@ -217,9 +229,9 @@ accepts it. Omit it to use the authenticated transport's implicit lifecycle sess### `click`-Click against a target pid. **Prefer `element_index` over pixel coordinates** — element_index works on backgrounded / hidden windows, surfaces a stable handle, and tells you what you're clicking via the cached AT-SPI element's role + label. Reach for `x, y` only when the target is a canvas / custom-drawn surface that doesn't appear in the AT-SPI tree.+Click against a target pid. **Prefer `element_token` over pixel coordinates** — element_token works on backgrounded / hidden windows, surfaces a stable handle, and tells you what you're clicking via the cached AT-SPI element's role + label. Reach for `x, y` only when the target is a canvas / custom-drawn surface that doesn't appear in the AT-SPI tree.-Provide either (window_id + x/y) or (pid + element_index). x/y are WINDOW-LOCAL pixels of window_id (the get_window_state screenshot frame); a point outside the window is refused (point_outside_window) and every pixel result reports the resolved window_point / screen_point. Background delivery first resolves the accessible under the point and fires its action (the result says `hit: <role> "<name>" action=...`; a file / list item is selected through its container: `selected: ...`), else presses the real virtual pointer there. A click that opens a popup menu names it (`popup: {window_id, bounds}`): pass that window_id to get_window_state to index its items. element_index cache is scoped per (pid, window_id) and is replaced by the next get_window_state of the same window — re-snapshot every turn before clicking.+Provide either (window_id + x/y) or (pid + element_token). x/y are WINDOW-LOCAL pixels of window_id (the get_window_state screenshot frame); a point outside the window is refused (point_outside_window) and every pixel result reports the resolved window_point / screen_point. Background delivery first resolves the accessible under the point and fires its action (the result says `hit: <role> "<name>" action=...`; a file / list item is selected through its container: `selected: ...`), else presses the real virtual pointer there. A click that opens a popup menu names it (`popup: {window_id, bounds}`): pass that window_id to get_window_state to index its items. The token is stale once the next get_window_state of the same window replaces its snapshot — re-snapshot every turn before clicking.After a zoom call, pass from_zoom=true to auto-translate zoom-image coords back to full-window space.@@ -235,14 +247,12 @@ button: "left" (default), "right", or "middle". Defaults to left so the field is- `count` (integer, optional): Number of clicks in one press train: 1 (default), 2 = double-click, 3 = triple-click (line/paragraph selection). There is no separate triple_click tool — pass count: 3 here. range: 1–unbounded- `cursor_id` (string, optional): Optional multi-cursor instance id. Default: 'default'.- `delivery_mode` (string, optional): Input delivery mode. 'background' (default) never activates or raises the target window. On X11 it injects via XTEST / the XInput2 master pointer (no focus steal). On Wayland it goes through libei + xdg-desktop-portal, which injects to the compositor's input focus — Wayland's security model has no per-window background targeting, so a specific non-focused window cannot be aimed at; when no libei backend is available the tool returns a structured background_unavailable error. 'foreground' is the explicit escalation: activate the target (X11 _NET_ACTIVE_WINDOW; Wayland compositor activate), inject, then restore the prior active window — a brief focus swap unless the target was already active. Matches the macOS / Windows delivery_mode surface. default: `"background"`-- `element_index` (integer, optional): Element index from get_window_state. Requires the matching `snapshot_id` alongside it. Prefer `element_token`, which carries both values.-- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.+- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.- `from_zoom` (boolean, optional): Set true after a zoom call to auto-translate zoom-image pixel coordinates back to full-window space.- `modifier` (array of string, optional): Modifier keys held during the action: cmd, shift, option/alt, ctrl.- `pid` (integer, optional)- `scope` (string, optional): default: `"window"`- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.-- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.- `target` (window target or desktop target, optional): Exact capture/input target selected independently for each action.`display_id="primary"` is the portable desktop target in this release.@@ -254,19 +264,17 @@ than silently changing coordinate spaces.### `double_click`-Double-click at (x,y) or an element_index (AT-SPI bounds). Background delivery on X11 sends real button events from the session's virtual master pointer (path mpx_pointer); a point covered by another application's window is refused (target_occluded), one covered by this app's own dialog is retargeted to it (retargeted_to). No focus steal. Provide either (window_id + x/y) or (pid + element_index). After a zoom call, pass from_zoom=true to auto-translate zoom-image coords.+Double-click at (x,y) or an element_token (AT-SPI bounds). Background delivery on X11 sends real button events from the session's virtual master pointer (path mpx_pointer); a point covered by another application's window is refused (target_occluded), one covered by this app's own dialog is retargeted to it (retargeted_to). No focus steal. Provide either (window_id + x/y) or (pid + element_token). After a zoom call, pass from_zoom=true to auto-translate zoom-image coords.**Arguments:**- `coordinate_frame` (string, optional): Frame of x/y (and from_x/from_y/to_x/to_y). Default "window": window-local screenshot pixels as returned by get_window_state. "desktop": full-screen pixels as returned by get_desktop_state, translated to the target window. Passing scope:"desktop" together with pid/window_id means the same thing.- `cursor_id` (string, optional): Optional multi-cursor instance id. Default: 'default'.- `delivery_mode` (string, optional): Input delivery mode. 'background' (default) never activates or raises the target window. On X11 it injects via XTEST / the XInput2 master pointer (no focus steal). On Wayland it goes through libei + xdg-desktop-portal, which injects to the compositor's input focus — Wayland's security model has no per-window background targeting, so a specific non-focused window cannot be aimed at; when no libei backend is available the tool returns a structured background_unavailable error. 'foreground' is the explicit escalation: activate the target (X11 _NET_ACTIVE_WINDOW; Wayland compositor activate), inject, then restore the prior active window — a brief focus swap unless the target was already active. Matches the macOS / Windows delivery_mode surface. default: `"background"`-- `element_index` (integer, optional): Element index from get_window_state. Requires the matching `snapshot_id` alongside it. Prefer `element_token`, which carries both values.-- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.+- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.- `from_zoom` (boolean, optional): Set true after a zoom call to auto-translate zoom-image pixel coordinates back to full-window space.- `pid` (integer, required)- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.-- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.- `window_id` (integer, optional)- `x` (number, optional): Window-local pixel X of the target window's own get_window_state screenshot (0..screenshot_width). For get_desktop_state pixels pass scope:"desktop" (or coordinate_frame:"desktop").- `y` (number, optional): Window-local pixel Y of the target window's own get_window_state screenshot (0..screenshot_height); see x.@@ -277,20 +285,18 @@ Double-click at (x,y) or an element_index (AT-SPI bounds). Background delivery o### `right_click`-Right-click at (x,y) or an element_index (AT-SPI bounds). Background delivery on X11 sends real button events from the session's virtual master pointer (path mpx_pointer); a point covered by another application's window is refused (target_occluded), one covered by this app's own dialog is retargeted to it (retargeted_to), one outside the window is refused (point_outside_window; x/y are window-local pixels, the result reports window_point / screen_point). No focus steal. When a context menu opens, the result names it (`popup: {window_id, bounds, title}`): call get_window_state(pid, window_id=<that id>) to index its menu items and click them by element_index. Provide either (window_id + x/y) or (pid + element_index). After a zoom call, pass from_zoom=true to auto-translate zoom-image coords.+Right-click at (x,y) or an element_token (AT-SPI bounds). Background delivery on X11 sends real button events from the session's virtual master pointer (path mpx_pointer); a point covered by another application's window is refused (target_occluded), one covered by this app's own dialog is retargeted to it (retargeted_to), one outside the window is refused (point_outside_window; x/y are window-local pixels, the result reports window_point / screen_point). No focus steal. When a context menu opens, the result names it (`popup: {window_id, bounds, title}`): call get_window_state(pid, window_id=<that id>) to index its menu items and click them by element_token. Provide either (window_id + x/y) or (pid + element_token). After a zoom call, pass from_zoom=true to auto-translate zoom-image coords.**Arguments:**- `coordinate_frame` (string, optional): Frame of x/y (and from_x/from_y/to_x/to_y). Default "window": window-local screenshot pixels as returned by get_window_state. "desktop": full-screen pixels as returned by get_desktop_state, translated to the target window. Passing scope:"desktop" together with pid/window_id means the same thing.- `cursor_id` (string, optional): Optional multi-cursor instance id. Default: 'default'.- `delivery_mode` (string, optional): Input delivery mode. 'background' (default) never activates or raises the target window. On X11 it injects via XTEST / the XInput2 master pointer (no focus steal). On Wayland it goes through libei + xdg-desktop-portal, which injects to the compositor's input focus — Wayland's security model has no per-window background targeting, so a specific non-focused window cannot be aimed at; when no libei backend is available the tool returns a structured background_unavailable error. 'foreground' is the explicit escalation: activate the target (X11 _NET_ACTIVE_WINDOW; Wayland compositor activate), inject, then restore the prior active window — a brief focus swap unless the target was already active. Matches the macOS / Windows delivery_mode surface. default: `"background"`-- `element_index` (integer, optional): Element index from get_window_state. Requires the matching `snapshot_id` alongside it. Prefer `element_token`, which carries both values.-- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.+- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.- `from_zoom` (boolean, optional): Set true after a zoom call to auto-translate zoom-image pixel coordinates back to full-window space.- `modifier` (array of string, optional): Modifier keys held during the action: cmd, shift, option/alt, ctrl.- `pid` (integer, required)- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.-- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.- `window_id` (integer, optional)- `x` (number, optional): Window-local pixel X of the target window's own get_window_state screenshot (0..screenshot_width). For get_desktop_state pixels pass scope:"desktop" (or coordinate_frame:"desktop").- `y` (number, optional): Window-local pixel Y of the target window's own get_window_state screenshot (0..screenshot_height); see x.@@ -339,12 +345,10 @@ Type text to a window via XSendEvent (KeyPress/KeyRelease). No focus steal.- `coordinate_frame` (string, optional): Frame of x/y (and from_x/from_y/to_x/to_y). Default "window": window-local screenshot pixels as returned by get_window_state. "desktop": full-screen pixels as returned by get_desktop_state, translated to the target window. Passing scope:"desktop" together with pid/window_id means the same thing.- `delivery_mode` (string, optional): Input delivery mode. 'background' (default) never activates or raises the target window. On X11 it injects via XTEST / the XInput2 master pointer (no focus steal). On Wayland it goes through libei + xdg-desktop-portal, which injects to the compositor's input focus — Wayland's security model has no per-window background targeting, so a specific non-focused window cannot be aimed at; when no libei backend is available the tool returns a structured background_unavailable error. 'foreground' is the explicit escalation: activate the target (X11 _NET_ACTIVE_WINDOW; Wayland compositor activate), inject, then restore the prior active window — a brief focus swap unless the target was already active. Matches the macOS / Windows delivery_mode surface. default: `"background"`-- `element_index` (integer, optional): Element index from get_window_state. Requires the matching `snapshot_id` alongside it. Prefer `element_token`, which carries both values.-- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.+- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.- `pid` (integer, optional)- `scope` (string, optional): default: `"window"`- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.-- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.- `target` (window target or desktop target, optional): Exact capture/input target selected independently for each action.`display_id="primary"` is the portable desktop target in this release.@@ -352,7 +356,7 @@ Platforms that cannot address another display reject it explicitly ratherthan silently changing coordinate spaces.- `text` (string, required)- `window_id` (integer, optional)-- `x` (number, optional): Pixel X of the field to type into — the element px action form. Pass x,y (no element_index) and the tool pixel-clicks there to establish real renderer focus, then types. Use for Chromium/Electron inputs the AX path can't reach. Window-local pixels of the target window's own get_window_state screenshot by default (same convention as click); for get_desktop_state pixels pass scope:"desktop" (or coordinate_frame:"desktop") — a bare pid+x/y is otherwise misinterpreted as window-local and can focus the wrong widget.+- `x` (number, optional): Pixel X of the field to type into — the element px action form. Pass x,y (no element_token) and the tool pixel-clicks there to establish real renderer focus, then types. Use for Chromium/Electron inputs the AX path can't reach. Window-local pixels of the target window's own get_window_state screenshot by default (same convention as click); for get_desktop_state pixels pass scope:"desktop" (or coordinate_frame:"desktop") — a bare pid+x/y is otherwise misinterpreted as window-local and can focus the wrong widget.- `y` (number, optional): Pixel Y of the field (see x).```json@@ -367,21 +371,19 @@ Press a key via XSendEvent to a window. No focus steal.- `coordinate_frame` (string, optional): Frame of x/y (and from_x/from_y/to_x/to_y). Default "window": window-local screenshot pixels as returned by get_window_state. "desktop": full-screen pixels as returned by get_desktop_state, translated to the target window. Passing scope:"desktop" together with pid/window_id means the same thing.- `delivery_mode` (string, optional): Input delivery mode. 'background' (default) never activates or raises the target window. On X11 it injects via XTEST / the XInput2 master pointer (no focus steal). On Wayland it goes through libei + xdg-desktop-portal, which injects to the compositor's input focus — Wayland's security model has no per-window background targeting, so a specific non-focused window cannot be aimed at; when no libei backend is available the tool returns a structured background_unavailable error. 'foreground' is the explicit escalation: activate the target (X11 _NET_ACTIVE_WINDOW; Wayland compositor activate), inject, then restore the prior active window — a brief focus swap unless the target was already active. Matches the macOS / Windows delivery_mode surface. default: `"background"`-- `element_index` (integer, optional): Element index from get_window_state. Requires the matching `snapshot_id` alongside it. Prefer `element_token`, which carries both values.-- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.+- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.- `key` (string, required): Key name: enter/return, tab, escape, space, backspace, delete, insert, home, end, pageup, pagedown, up, down, left, right, f1-f12, or any single ASCII character.- `modifiers` (array of string, optional)- `pid` (integer, optional)- `scope` (string, optional): default: `"window"`- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.-- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.- `target` (window target or desktop target, optional): Exact capture/input target selected independently for each action.`display_id="primary"` is the portable desktop target in this release.Platforms that cannot address another display reject it explicitly ratherthan silently changing coordinate spaces.- `window_id` (integer, optional)-- `x` (number, optional): Pixel X — the element px action form: pixel-click there to focus, then send the key. Use when the key must go to a Chromium/Electron surface the AX path can't focus. Pass with y, no element_index. Window-local pixels by default (same convention as click); for get_desktop_state pixels pass scope:"desktop" (or coordinate_frame:"desktop").+- `x` (number, optional): Pixel X — the element px action form: pixel-click there to focus, then send the key. Use when the key must go to a Chromium/Electron surface the AX path can't focus. Pass with y, no element_token. Window-local pixels by default (same convention as click); for get_desktop_state pixels pass scope:"desktop" (or coordinate_frame:"desktop").- `y` (number, optional): Pixel Y (see x).```json@@ -395,13 +397,11 @@ Press a combination of keys simultaneously, e.g. ["ctrl","c"] for Copy. Delivere**Arguments:**- `delivery_mode` (string, optional): Input delivery mode. 'background' (default) never activates or raises the target window. On X11 it injects via XTEST / the XInput2 master pointer (no focus steal). On Wayland it goes through libei + xdg-desktop-portal, which injects to the compositor's input focus — Wayland's security model has no per-window background targeting, so a specific non-focused window cannot be aimed at; when no libei backend is available the tool returns a structured background_unavailable error. 'foreground' is the explicit escalation: activate the target (X11 _NET_ACTIVE_WINDOW; Wayland compositor activate), inject, then restore the prior active window — a brief focus swap unless the target was already active. Matches the macOS / Windows delivery_mode surface. default: `"background"`-- `element_index` (integer, optional): Element index from get_window_state. Requires the matching `snapshot_id` alongside it. Prefer `element_token`, which carries both values.-- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.+- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.- `keys` (array of string, required): Modifier(s) + one non-modifier key, e.g. ["ctrl","c"]. items: 2–unbounded- `pid` (integer, optional)- `scope` (string, optional): default: `"window"`- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.-- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.- `target` (window target or desktop target, optional): Exact capture/input target selected independently for each action.`display_id="primary"` is the portable desktop target in this release.@@ -421,13 +421,12 @@ Set value of an AT-SPI element via SetValue action.**Arguments:**-- `element_index` (integer, optional): Element index from get_window_state. Requires the matching `snapshot_id` alongside it. Prefer `element_token`, which carries both values.-- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.+- `delivery_mode` (string, optional): Input delivery mode. 'background' (default) never activates or raises the target window. On X11 it injects via XTEST / the XInput2 master pointer (no focus steal). On Wayland it goes through libei + xdg-desktop-portal, which injects to the compositor's input focus — Wayland's security model has no per-window background targeting, so a specific non-focused window cannot be aimed at; when no libei backend is available the tool returns a structured background_unavailable error. 'foreground' is the explicit escalation: activate the target (X11 _NET_ACTIVE_WINDOW; Wayland compositor activate), inject, then restore the prior active window — a brief focus swap unless the target was already active. Matches the macOS / Windows delivery_mode surface. default: `"background"`+- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.- `pid` (integer, required)- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.-- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.- `value` (string or number, required): New value. Written through AT-SPI EditableText/Value when the element exposes them; otherwise (GTK2 spin scales, VCL spin buttons) the field is clicked with the session's real pointer, its text selected and replaced through the virtual keyboard and committed with Tab, then read back.-- `window_id` (integer, optional): Required when element_index is used; optional when element_token is supplied (the token carries it).+- `window_id` (integer, optional): Omit when element_token is supplied (the token carries it).```json{"pid":844,"value":"value"}@@ -445,20 +444,18 @@ Scroll the target pid's focused region via XSendEvent Button4/5. direction requi- `cursor_id` (string, optional): Optional multi-cursor instance id. Default: 'default'.- `delivery_mode` (string, optional): Input delivery mode. 'background' (default) never activates or raises the target window. On X11 it injects via XTEST / the XInput2 master pointer (no focus steal). On Wayland it goes through libei + xdg-desktop-portal, which injects to the compositor's input focus — Wayland's security model has no per-window background targeting, so a specific non-focused window cannot be aimed at; when no libei backend is available the tool returns a structured background_unavailable error. 'foreground' is the explicit escalation: activate the target (X11 _NET_ACTIVE_WINDOW; Wayland compositor activate), inject, then restore the prior active window — a brief focus swap unless the target was already active. Matches the macOS / Windows delivery_mode surface. default: `"background"`- `direction` (string, required)-- `element_index` (integer, optional): Element index from get_window_state. Requires the matching `snapshot_id` alongside it. Prefer `element_token`, which carries both values.-- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.+- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.- `pid` (integer, optional)- `scope` (string, optional): default: `"window"`- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.-- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.- `target` (window target or desktop target, optional): Exact capture/input target selected independently for each action.`display_id="primary"` is the portable desktop target in this release.Platforms that cannot address another display reject it explicitly ratherthan silently changing coordinate spaces.- `window_id` (integer, optional)-- `x` (number, optional): Window-local screenshot-pixel X of the scroll target. Pass with y and without element_index.-- `y` (number, optional): Window-local screenshot-pixel Y of the scroll target. Pass with x and without element_index.+- `x` (number, optional): Window-local screenshot-pixel X of the scroll target. Pass with y and without element_token.+- `y` (number, optional): Window-local screenshot-pixel Y of the scroll target. Pass with x and without element_token.```json{"direction":"up"}@@ -485,11 +482,12 @@ Move the synthetic agent cursor without changing the user's pointer. Only an expCapture a cropped JPEG of a window region (x1,y1)–(x2,y2) in screenshot pixels, with 20% padding. Output is at most 500 px wide.-After a zoom, pass from_zoom=true to click/type_text to auto-translate coordinates back to full-window space. Coordinate actions return `screenshot_context_missing` when the latest snapshot does not contain a screenshot owned by this session. `from_zoom` actions return `zoom_context_missing` when the zoom was never created or was replaced; call `get_window_state`, then `zoom`, again on the same connection.+After a zoom, pass from_zoom=true to click/type_text to auto-translate coordinates back to full-window space. Coordinate actions return `screenshot_context_missing` when no current snapshot contains a screenshot owned by this session. `from_zoom` actions return `zoom_context_missing` when the zoom was never created or was replaced; call `get_window_state`, then `zoom`, again on the same connection.**Arguments:**- `pid` (integer, optional): Optional target pid. When omitted, the driver resolves the unique current snapshot for this session and window.+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.- `window_id` (integer, required)- `x1` (number, required)- `x2` (number, required)@@ -525,6 +523,7 @@ Actions:- `javascript` (string, optional): JavaScript to execute. Required for execute_javascript.- `pid` (integer, optional): Target process ID.- `selector` (string, optional): CSS selector for click_element (e.g. 'button.submit', '#login a').+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.- `target_url_contains` (string, optional): Optional, for execute_javascript/insert_text/type_keystrokes: require exactly one browser tab whose URL contains this substring. Use this on a multi-tab browser — there's no built-in link between window_id and which tab a CDP call reaches.- `text` (string, optional): Text to insert or type. Required for insert_text and type_keystrokes. The target field must already have DOM focus (click/focus it first).- `user_has_confirmed_enabling` (boolean, optional): Must be true to proceed with enable_javascript_apple_events. This will quit and relaunch the browser.@@ -605,14 +604,16 @@ Stop trajectory recording. Disables further per-turn capture and, when video wasA manual `stop_recording` is **unconditional** — it stops whatever recording is active regardless of which session started it. Ownership-scoped teardown (so one client disconnecting can't stop a recording a later client started) is handled by the registry's `session_end` lifecycle hook, not by this tool.-**Arguments:** none.+**Arguments:**++- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.### `replay_trajectory`Replay a recorded trajectory by re-invoking every turn's tool call in lexical order. `dir` must point at a directory previously written by `start_recording`. Each `turn-NNNNN/` is parsed for `action.json`, and the recorded tool is called with its recorded `arguments` via the same dispatch path an MCP / CLI call uses.Caveats:-- Element-indexed actions (`click({pid, element_index})` etc.) will fail because element indices are per-snapshot and don't survive across sessions. Pixel clicks (`click({pid, x, y})`) and all keyboard tools replay cleanly. Failures are reported but don't stop replay unless `stop_on_error` is true.+- Element-token actions (`click({pid, element_token})` etc.) will fail because element tokens are per-snapshot and don't survive across sessions. Pixel clicks (`click({pid, x, y})`) and all keyboard tools replay cleanly. Failures are reported but don't stop replay unless `stop_on_error` is true.- `get_window_state` and other read-only tools are NOT currently recorded, so replays do not re-populate the per-(pid, window_id) element cache.- If recording is ENABLED while replay runs, the replay itself is recorded into the currently configured output directory. That's deliberate: recording a replay against a new build and diffing the two trajectories is the regression-test workflow.@@ -620,6 +621,7 @@ Caveats:- `delay_ms` (integer, optional): Milliseconds to sleep between turns, for human-observable pacing. Default 500. range: 0–10000- `dir` (string, required): Trajectory directory previously written by `start_recording`. Absolute or ~-rooted.+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.- `stop_on_error` (boolean, optional): Stop replay on the first tool-call error. Default true — set false to best-effort through the full trajectory.```json@@ -645,6 +647,7 @@ The experimental_pip keys persist to ~/.cua-driver/config.json and apply on next- `experimental_pip_geometry` (string, optional): PiP window size + optional position in `WxH` or `WxH+X+Y` form.- `key` (string, optional): Name of a single config field to write ({key, value} shape). Pair with `value`.- `max_image_dimension` (integer, optional): Legacy per-field shape. Max dimension for screenshot resizing (0 = no limit).+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.- `value` (unknown, optional): New value for `key`. JSON type depends on the key.### `start_session`@@ -710,7 +713,9 @@ Configure only movement physics and visibility timing for a session cursor.Check required permissions for cua-driver-rs on Linux.-**Arguments:** none.+**Arguments:**++- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.### `health_report`@@ -760,13 +765,16 @@ Stability: schema_version="1" is the contract. Future breaking changes will be `**Arguments:**- `include` (array of string, optional): Only run these checks (canonical names). Wins over `skip`.+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.- `skip` (array of string, optional): Skip these checks (canonical names). Ignored when `include` is set.### `check_for_update`Check the saved stable/nightly Cua Driver channel for a release on GitHub. Returns current and selected channels, current and latest versions, an `update_available` boolean, the install one-liner, and the release notes URL. Read-only — never installs. Pacman-owned Linux executables return package-manager guidance without checking GitHub. Mirror of `cua-driver check-update --json`.-**Arguments:** none.+**Arguments:**++- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.### `install_ffmpeg`@@ -775,6 +783,7 @@ Install the ffmpeg binary used by start_recording's video capture (Linux/Windows**Arguments:**- `confirm` (boolean, optional): Run the install command. Without it, only the planned command is reported.+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.## Other tools@@ -877,6 +886,7 @@ Run multiple mouse drag gestures concurrently via Linux MPX/XI2 virtual master p**Arguments:**- `drags` (array of object, required): items: 2–unbounded+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.```json{"drags":["example"]}@@ -1101,6 +1111,7 @@ Preview or install one Driver-managed optional extension. The first call without- `confirm` (boolean, optional): Install the previewed extension. Omit or false for a read-only plan.- `name` (string, required)+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.```json{"name":"perception"}@@ -1114,6 +1125,7 @@ Parse one immutable registered capture into model-neutral text and icon regions.- `capture_id` (string, required)- `options` (object, optional): Optional, model-neutral controls for one bounded parse. default: `{}`+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.```json{"capture_id":"example"}diff --git a/docs/content/docs/reference/cua-driver/mcp-tools-windows.mdx b/docs/content/docs/reference/cua-driver/mcp-tools-windows.mdxindex 45b00f871a..a4d873b765 100644--- a/docs/content/docs/reference/cua-driver/mcp-tools-windows.mdx+++ b/docs/content/docs/reference/cua-driver/mcp-tools-windows.mdx@@ -48,7 +48,9 @@ Running apps are derived from visible top-level windows + the foreground pid (miUse this for "is X installed?" as well as "is X running?". For per-window state — on-screen, minimized, window titles — call list_windows instead. For just opening an app — running or not — call launch_app({path: ...}) directly; list_apps is not a prerequisite.-**Arguments:** none.+**Arguments:**++- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.### `list_windows`@@ -64,12 +66,13 @@ Inputs: pid (optional pid filter), on_screen_only (bool, default false).- `on_screen_only` (boolean, optional): When true, drop windows that aren't currently on-screen. Default false.- `pid` (integer, optional): Optional pid filter. When set, only this pid's windows are returned.+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.### `get_window_state`-Walk a running app's UIA tree and return BOTH a structured `elements` array (preferred) AND a Markdown rendering of the same tree (back-compat). Every actionable element is tagged with [element_index N] in the markdown and as `element_index` in the structured array — pass those indices to `click`, `type_text`, `scroll`, etc.+Walk a running app's UIA tree and return BOTH a structured `elements` array (preferred) AND a Markdown rendering of the same tree (back-compat). Every actionable element is tagged with [element_index N] in the markdown and as `element_index` in the structured array; pass each element's `element_token` to `click`, `type_text`, `scroll`, etc.-INVARIANT: call `get_window_state` once per turn per (pid, window_id) before any element-indexed action against that window. The index map is replaced by the next snapshot of the same (pid, window_id).+INVARIANT: call `get_window_state` once per turn per (pid, window_id) before any element action against that window. The next snapshot of the same (pid, window_id) replaces this one, stales its element tokens, and lists the replaced ids in `invalidated_snapshot_ids`.PREFERRED CONSUMERS read `structuredContent.elements` (one entry per indexed row with `element_index`, `role`, `label`, `value`, `enabled`, `selected`, `actions` (names of UIA patterns exposed as actions, omitted when empty), `frame: {x,y,w,h}`, `parent_index`, `depth`). The markdown `tree_markdown` stays available and unchanged in shape for existing text-parsing callers — but new fields will only be added to the structured side.@@ -79,7 +82,7 @@ The UIA tree walked is the window's tree (HWND-scoped); the screenshot and windoSet `query` to a case-insensitive substring to project BOTH `tree_markdown` and `structuredContent.elements` to matching rows plus their ancestor chain. Original element indices are preserved. `total_element_count` reports the complete snapshot; `returned_element_count` reports the projection.-Always returns BOTH the element tree AND a screenshot — ground on both and cross-check (the tree lies on some surfaces). Choose the modality at ACTION time: an element ax action (element_index/element_token → accessibility rung) or an element px action (x,y → pixel rung off this screenshot). capture_mode is deprecated and ignored.+Always returns BOTH the element tree AND a screenshot — ground on both and cross-check (the tree lies on some surfaces). Choose the modality at ACTION time: an element ax action (element_token → accessibility rung) or an element px action (x,y → pixel rung off this screenshot). capture_mode is deprecated and ignored.The mirror image: pass `include_accessibility_tree:false` to SKIP the UIA walk entirely and return just the screenshot plus window metadata (window_bounds, app_name, window_title) — the capture-only path for a live window preview / picture-in-picture. Setting BOTH `include_accessibility_tree:false` and `include_screenshot:false` is an error. Optional `max_image_dimension` overrides the configured screenshot long-edge limit for this call; pass 0 for native resolution. Legacy `max_dimension` remains a cap on the configured limit.@@ -93,7 +96,7 @@ Windows requires no special permissions.**Arguments:**-- `capture_mode` (string, optional): DEPRECATED and ignored. get_window_state always returns BOTH the element tree and a screenshot — ground on both. The modality is chosen at action time by how you address the target: an element ax action (element_index/element_token) or an element px action (x,y). Any value (including the old "som"/"screenshot" aliases) is accepted but has no effect.+- `capture_mode` (string, optional): DEPRECATED and ignored. get_window_state always returns BOTH the element tree and a screenshot — ground on both. The modality is chosen at action time by how you address the target: an element ax action (element_token) or an element px action (x,y). Any value (including the old "som"/"screenshot" aliases) is accepted but has no effect.- `include_accessibility_tree` (boolean, optional): Default true — walk the UIA tree and return `elements` + `tree_markdown` alongside the screenshot. Set false to SKIP the UIA walk entirely and return just the screenshot plus window metadata (window_bounds, app_name, window_title) — the capture-only path for a live window preview / picture-in-picture. Mirrors include_screenshot. Setting BOTH include_accessibility_tree:false AND include_screenshot:false is an error (nothing to return).- `include_screenshot` (boolean, optional): Default true — returns a grounding screenshot alongside the tree. Set false to skip the grab and return tree only (the cheap path for re-indexing before an element ax action).- `max_depth` (integer, optional): Cap on the UIA-tree walk depth. Nodes whose rendered indent would exceed this are omitted. Omit for the default (25). Lower for deep menu / Electron trees. range: 1–unbounded@@ -117,7 +120,9 @@ Return a lightweight snapshot of the desktop: running processes and on-screen viFor the full UIA subtree of a single window (with interactive element indices you can click by), use get_window_state instead — this is a fast discovery read.-**Arguments:** none.+**Arguments:**++- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.### `get_desktop_state`@@ -164,7 +169,9 @@ Current schema (Windows):`capture_mode` is deprecated and no longer affects behavior — `get_window_state` always returns both the UIA tree and a screenshot.-**Arguments:** none.+**Arguments:**++- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.### `get_recording_state`@@ -172,7 +179,9 @@ Report the current trajectory recorder state: whether recording is enabled, thePure read-only.-**Arguments:** none.+**Arguments:**++- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.### `get_agent_cursor_state`@@ -209,6 +218,7 @@ Windows-only field: `path` (Swift uses `bundle_id` since macOS apps resolve via- `launch_path` (string, optional): Round-trip the `launch_path` returned by `list_apps`. Highest precedence — when set, this exact string is handed to ShellExecuteEx unchanged. For Windows desktop apps it's the full `.exe` commandline (path + arguments preserved from the source shortcut); for UWP apps it's `shell:appsFolder\{PackageFamilyName}!{AppId}`. For precise UWP pid capture, prefer `aumid` over `launch_path`.- `name` (string, optional): App display name. Tried against the `shell:AppsFolder` index first for packaged-app lookup; on a miss, passed to ShellExecuteEx's PATH search.- `path` (string, optional): Full path to executable. Windows-only; takes precedence over name/bundle_id/aumid (but not over `launch_path`).+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.- `start_minimized` (boolean, optional): When true, launch the app's window minimized to the taskbar instead of restored-but-not-activated. Use this when the agent wants to drive the app entirely in the background — the user's previously-frontmost window (e.g. terminal) stays visually on top. Desktop launches hold the foreground lock through startup and use SW_SHOWMINNOACTIVE; packaged-app activation remains broker-controlled and receives a best-effort SW_SHOWMINNOACTIVE post-pass. UIA / background dispatch still work on a minimized window; only `screenshot` and `delivery_mode:"foreground"` need it restored.- `urls` (array of string, optional): URLs to open in the default browser via ShellExecuteEx (no activation).- `webkit_inspector_port` (integer, optional): Accepted for cross-platform parity; no-op on Windows.@@ -220,6 +230,7 @@ Force-terminate a process by pid. Use when the standard close path (Alt+F4 / WM_**Arguments:**- `pid` (integer, required): PID of the process to terminate.+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.```json{"pid":844}@@ -236,6 +247,7 @@ Implementation uses the `AttachThreadInput` trick to bypass Windows' foreground-**Arguments:**- `pid` (integer, required): Target process ID.+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.- `window_id` (integer, optional): Optional HWND. Defaults to pid's first visible top-level window.```json@@ -263,38 +275,37 @@ accepts it. Omit it to use the authenticated transport's implicit lifecycle sess### `click`-Left-click against a target pid. **Prefer `element_index` over pixel coordinates** — element_index works on backgrounded / minimized / hidden / off-desktop windows, surfaces a stable handle that survives rebuilds, and tells you what you're clicking via the cached element's role + label. Reach for `x, y` only when the target is a canvas / video / WebGL / custom-drawn surface that doesn't appear in the UIA tree.+Left-click against a target pid. **Prefer `element_token` over pixel coordinates** — element_token works on backgrounded / minimized / hidden / off-desktop windows, surfaces a stable handle that survives rebuilds, and tells you what you're clicking via the cached element's role + label. Reach for `x, y` only when the target is a canvas / video / WebGL / custom-drawn surface that doesn't appear in the UIA tree.Two addressing modes:-- `element_index` + `window_id` (from the last `get_window_state` snapshot of that window) — performs the UIA Invoke pattern on the cached element via PostMessage. No cursor move, no focus steal. Requires a prior `get_window_state(pid, window_id)` in this turn; the element_index cache is scoped per (pid, window_id) and is replaced by the next snapshot of the same window.+- `element_token` (from the last `get_window_state` snapshot of that window) — performs the UIA Invoke pattern on the cached element via PostMessage. No cursor move, no focus steal. Requires a prior `get_window_state(pid, window_id)` in this turn; the token is stale once the next snapshot of the same window replaces it.-- `x`, `y` (window-local screenshot pixels, top-left origin of the PNG returned by `get_window_state`). On `delivery_mode:"background"` (the default), cua-driver FIRST does a UIA hit-test at the resolved screen position: if the deepest invokable element under that point exposes `InvokePattern`, it's invoked through the accessibility channel — same background-safe path as the `element_index` mode, no foreground swap, no visible flash. **This makes pixel clicks on UWP / WinUI3 / Win11 packaged apps work flash-free out of the box** — agents should default to `delivery_mode:"background"` even on XAML hosts whose CoreInput dispatcher drops raw PostMessage. The PostMessage(WM_LBUTTONDOWN/UP) fallback only runs when the UIA hit-test misses (canvas / video / WebGL / custom-drawn surfaces with no UIA peer), and on those targets `delivery_mode:"background"` returns a structured `background_unavailable` error if PostMessage is known to drop too — at which point you switch to `delivery_mode:"foreground"`. **Always try the default `background` click first and let that error be your signal — do NOT pass `foreground` preemptively because the target 'looks like' GTK/Chromium/etc. The driver decides when background is impossible; a guessed foreground click needlessly steals the user's focus.** `count: 2` posts two down/up pairs for a double-click. Pixel clicks need a visible on-screen window to anchor the coordinate conversion (errors with `pid X has no on-screen window` otherwise).+- `x`, `y` (window-local screenshot pixels, top-left origin of the PNG returned by `get_window_state`). On `delivery_mode:"background"` (the default), cua-driver FIRST does a UIA hit-test at the resolved screen position: if the deepest invokable element under that point exposes `InvokePattern`, it's invoked through the accessibility channel — same background-safe path as the `element_token` mode, no foreground swap, no visible flash. **This makes pixel clicks on UWP / WinUI3 / Win11 packaged apps work flash-free out of the box** — agents should default to `delivery_mode:"background"` even on XAML hosts whose CoreInput dispatcher drops raw PostMessage. The PostMessage(WM_LBUTTONDOWN/UP) fallback only runs when the UIA hit-test misses (canvas / video / WebGL / custom-drawn surfaces with no UIA peer), and on those targets `delivery_mode:"background"` returns a structured `background_unavailable` error if PostMessage is known to drop too — at which point you switch to `delivery_mode:"foreground"`. **Always try the default `background` click first and let that error be your signal — do NOT pass `foreground` preemptively because the target 'looks like' GTK/Chromium/etc. The driver decides when background is impossible; a guessed foreground click needlessly steals the user's focus.** `count: 2` posts two down/up pairs for a double-click. Pixel clicks need a visible on-screen window to anchor the coordinate conversion (errors with `pid X has no on-screen window` otherwise).-Exactly one of `element_index` or (`x` AND `y`) must be provided. `pid` is required for window scope and omitted for desktop scope. `window_id` is required when `element_index` is used (scopes the cache lookup). After a `zoom` call, pass `from_zoom=true` to auto-translate zoom-image coords back to full-window space.+Exactly one of `element_token` or (`x` AND `y`) must be provided. `pid` is required for window scope and omitted for desktop scope. After a `zoom` call, pass `from_zoom=true` to auto-translate zoom-image coords back to full-window space.-Windows-only convenience: `button: "left"|"right"|"middle"` switches the mouse button (Swift exposes right-click as a separate `right_click` tool). The Swift-only `action` / `modifier` / `debug_image_out` schema fields aren't supported yet.+Windows-only convenience: `button: "left"|"right"|"middle"` switches the mouse button (Swift exposes right-click as a separate `right_click` tool). `action: "expand"` on an `element_token` opens the element through UIA ExpandCollapsePattern (the dropdown half of an MSAA split button); other actions use the default invoke. `debug_image_out` isn't supported yet.**Arguments:**+- `action` (string, optional): Accessibility action for an element_token target. "expand" opens the element through UIA ExpandCollapsePattern, or clicks the dropdown half of an MSAA split button. Omit for the default invoke.- `button` (string, optional): Mouse button. Default "left".- `capture_id` (string, optional): Optional ID from get_window_state or get_desktop_state. When present, x and y are admitted against that exact capture and the ID is consumed before native dispatch.- `count` (integer, optional): Click count — 1 (single), 2 (double), 3 (triple). Default 1. range: 1–3- `delivery_mode` (string, optional): Input delivery mode. 'background' (default) never swaps foreground: it routes through UIA Invoke / PostMessage and the window is never raised. For targets whose input stack silently drops posted events (Chromium/Electron content, GTK buttons, VCL/LibreOffice accelerators) the tool returns a structured background_unavailable error rather than fronting. 'foreground' is the explicit escalation: a brief SetForegroundWindow swap + SendInput, restoring the prior foreground afterward. IMPORTANT: 'background' is not a hint to weigh — it is the mandatory first attempt. Do NOT pass 'foreground' preemptively because a target 'looks like' GTK/Chromium/Electron; the DRIVER decides when background is impossible and tells you so via a background_unavailable error (or a verified no-op). Only THEN re-issue the same action with 'foreground'. The lists above are the driver's detectors, not a checklist for you to front on a guess — fronting up-front needlessly steals the user's focus and is a bug, not a shortcut. Matches the macOS delivery_mode surface.-- `element_index` (integer, optional): Element index from get_window_state. Requires the matching `snapshot_id` alongside it. Prefer `element_token`, which carries both values.-- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.+- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.- `from_zoom` (boolean, optional): When true, x and y are pixel coordinates in the last `zoom` image for this pid. The driver maps them back to window coords.- `modifier` (array of string, optional): Modifier keys held during the action: cmd, shift, option/alt, ctrl.- `pid` (integer, optional): Target process ID for window scope. Omit with scope=desktop for screen-absolute coordinates from get_desktop_state.- `scope` (string, optional): default: `"window"`- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.-- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.- `target` (window target or desktop target, optional): Exact capture/input target selected independently for each action.`display_id="primary"` is the portable desktop target in this release.Platforms that cannot address another display reject it explicitly ratherthan silently changing coordinate spaces.-- `window_id` (integer, optional): HWND for the window whose get_window_state produced the element_index. Required when element_index is used. Optional when element_token is supplied (the token carries it).+- `window_id` (integer, optional): HWND of the target window. Omit when element_token is supplied (the token carries it).- `x` (number, optional): X in window-local screenshot pixels — same space as the PNG get_window_state returns. Must be provided together with y.- `y` (number, optional): Y in window-local screenshot pixels. Must be provided together with x.@@ -302,23 +313,21 @@ than silently changing coordinate spaces.Double-click against a target pid. Two addressing modes:-- `element_index` + `window_id` (from the last `get_window_state` snapshot of that window) — synthesizes a stamped pixel double-click at the element's cached on-screen center via PostMessage. (Windows has no AXOpen analogue; Swift's AXOpen-first path falls through to the same pixel recipe when the element doesn't advertise AXOpen, so the user-visible behavior matches.)+- `element_token` (from the last `get_window_state` snapshot of that window) — synthesizes a stamped pixel double-click at the element's cached on-screen center via PostMessage. (Windows has no AXOpen analogue; Swift's AXOpen-first path falls through to the same pixel recipe when the element doesn't advertise AXOpen, so the user-visible behavior matches.)- `x`, `y` (window-local screenshot pixels, top-left origin of the PNG returned by `get_window_state`) — posts two WM_LBUTTONDOWN/UP pairs in quick succession to the deepest child window at that point.-Exactly one of `element_index` or (`x` AND `y`) must be provided. `pid` is required in both modes. `window_id` is required when `element_index` is used. The macOS-only `modifier` field is accepted for parity (no-op on Windows — PostMessage doesn't propagate modifier-key state).+Exactly one of `element_token` or (`x` AND `y`) must be provided. `pid` is required in both modes. The macOS-only `modifier` field is accepted for parity (no-op on Windows — PostMessage doesn't propagate modifier-key state).**Arguments:**- `delivery_mode` (string, optional): Input delivery mode. 'background' (default) never swaps foreground: it routes through UIA Invoke / PostMessage and the window is never raised. For targets whose input stack silently drops posted events (Chromium/Electron content, GTK buttons, VCL/LibreOffice accelerators) the tool returns a structured background_unavailable error rather than fronting. 'foreground' is the explicit escalation: a brief SetForegroundWindow swap + SendInput, restoring the prior foreground afterward. IMPORTANT: 'background' is not a hint to weigh — it is the mandatory first attempt. Do NOT pass 'foreground' preemptively because a target 'looks like' GTK/Chromium/Electron; the DRIVER decides when background is impossible and tells you so via a background_unavailable error (or a verified no-op). Only THEN re-issue the same action with 'foreground'. The lists above are the driver's detectors, not a checklist for you to front on a guess — fronting up-front needlessly steals the user's focus and is a bug, not a shortcut. Matches the macOS delivery_mode surface.-- `element_index` (integer, optional): Element index from get_window_state. Requires the matching `snapshot_id` alongside it. Prefer `element_token`, which carries both values.-- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.+- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.- `from_zoom` (boolean, optional): After a zoom call, pass true to translate zoom-image coords back to window space.- `modifier` (array of string, optional): Modifier keys held during the action: cmd, shift, option/alt, ctrl.- `pid` (integer, required): Target process ID.- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.-- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.-- `window_id` (integer, optional): HWND for the target window. Required when element_index is used. Optional when element_token is supplied (the token carries it).+- `window_id` (integer, optional): HWND for the target window. Omit when element_token is supplied (the token carries it).- `x` (number, optional): X in window-local screenshot pixels. Must be provided together with y.- `y` (number, optional): Y in window-local screenshot pixels. Must be provided together with x.@@ -330,23 +339,21 @@ Exactly one of `element_index` or (`x` AND `y`) must be provided. `pid` is requiRight-click against a target pid. Two addressing modes:-- `element_index` + `window_id` (from the last `get_window_state` snapshot of that window) — posts WM_RBUTTONDOWN/UP at the element's cached on-screen center via PostMessage. (Windows has no AXShowMenu analogue wired up yet; Swift's AX-action path falls through to the same pixel recipe on non-advertising elements, so user-visible behavior matches.)+- `element_token` (from the last `get_window_state` snapshot of that window) — posts WM_RBUTTONDOWN/UP at the element's cached on-screen center via PostMessage. (Windows has no AXShowMenu analogue wired up yet; Swift's AX-action path falls through to the same pixel recipe on non-advertising elements, so user-visible behavior matches.)- `x`, `y` (window-local screenshot pixels, top-left origin of the PNG returned by `get_window_state`) — posts WM_RBUTTONDOWN/UP to the deepest child window at that point.-Exactly one of `element_index` or (`x` AND `y`) must be provided. `pid` is required in both modes. `window_id` is required when `element_index` is used. `modifier` is accepted for parity (no-op on Windows — PostMessage doesn't propagate modifier-key state).+Exactly one of `element_token` or (`x` AND `y`) must be provided. `pid` is required in both modes. `modifier` is accepted for parity (no-op on Windows — PostMessage doesn't propagate modifier-key state).**Arguments:**- `delivery_mode` (string, optional): Input delivery mode. 'background' (default) never swaps foreground: it routes through UIA Invoke / PostMessage and the window is never raised. For targets whose input stack silently drops posted events (Chromium/Electron content, GTK buttons, VCL/LibreOffice accelerators) the tool returns a structured background_unavailable error rather than fronting. 'foreground' is the explicit escalation: a brief SetForegroundWindow swap + SendInput, restoring the prior foreground afterward. IMPORTANT: 'background' is not a hint to weigh — it is the mandatory first attempt. Do NOT pass 'foreground' preemptively because a target 'looks like' GTK/Chromium/Electron; the DRIVER decides when background is impossible and tells you so via a background_unavailable error (or a verified no-op). Only THEN re-issue the same action with 'foreground'. The lists above are the driver's detectors, not a checklist for you to front on a guess — fronting up-front needlessly steals the user's focus and is a bug, not a shortcut. Matches the macOS delivery_mode surface.-- `element_index` (integer, optional): Element index from get_window_state. Requires the matching `snapshot_id` alongside it. Prefer `element_token`, which carries both values.-- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.+- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.- `from_zoom` (boolean, optional): After a zoom call, pass true to translate zoom-image coords back to window space.- `modifier` (array of string, optional): Modifier keys held during the action: cmd, shift, option/alt, ctrl.- `pid` (integer, required): Target process ID.- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.-- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.-- `window_id` (integer, optional): HWND for the target window. Required when element_index is used. Optional when element_token is supplied (the token carries it).+- `window_id` (integer, optional): HWND for the target window. Omit when element_token is supplied (the token carries it).- `x` (number, optional): X in window-local screenshot pixels. Must be provided together with y.- `y` (number, optional): Y in window-local screenshot pixels. Must be provided together with x.@@ -390,7 +397,7 @@ Insert text into the target pid via character-by-character PostMessage(WM_CHAR)Special keys (Return, Escape, arrows, Tab) go through `press_key` / `hotkey` — they are not text.-**Routing on Windows.** When the target's owning EXE or top-level window class identifies it as a XAML / WinUI3 / UWP host (modern Notepad, Calculator, Photos, Settings, etc.), the tool requires `element_index` + `window_id` and routes through UI Automation's `ValuePattern.SetValue` — same backend as the `set_value` tool. PostMessage WM_CHAR doesn't reach those hosts (their CoreInput dispatcher only consumes events from the system input queue), so the fallback path silently dropped chars. If you call `type_text(pid, text)` on a XAML host without `element_index`, the tool returns an actionable error pointing you at `get_window_state` first. Native ConsoleHost on Windows ARM64 is hard-refused because it can accept synthesized Unicode events without delivering them; use a process or PTY setup channel instead. Legacy Win32 apps still use the PostMessage path, preserving the no-focus-steal property.+**Routing on Windows.** When the target's owning EXE or top-level window class identifies it as a XAML / WinUI3 / UWP host (modern Notepad, Calculator, Photos, Settings, etc.), the tool requires `element_token` and routes through UI Automation's `ValuePattern.SetValue` — same backend as the `set_value` tool. PostMessage WM_CHAR doesn't reach those hosts (their CoreInput dispatcher only consumes events from the system input queue), so the fallback path silently dropped chars. If you call `type_text(pid, text)` on a XAML host without `element_token`, the tool returns an actionable error pointing you at `get_window_state` first. Native ConsoleHost on Windows ARM64 is hard-refused because it can accept synthesized Unicode events without delivering them; use a process or PTY setup channel instead. Legacy Win32 apps still use the PostMessage path, preserving the no-focus-steal property.`delay_ms` (0–200, default 30) spaces successive characters on the PostMessage path so autocomplete and IME can keep up. Ignored on the UIA path (SetValue is atomic).@@ -398,20 +405,18 @@ Special keys (Return, Escape, arrows, Tab) go through `press_key` / `hotkey` —- `delay_ms` (integer, optional): Milliseconds between characters. Default 30. range: 0–200- `delivery_mode` (string, optional): Input delivery mode. 'background' (default) never swaps foreground: it routes through UIA Invoke / PostMessage and the window is never raised. For targets whose input stack silently drops posted events (Chromium/Electron content, GTK buttons, VCL/LibreOffice accelerators) the tool returns a structured background_unavailable error rather than fronting. 'foreground' is the explicit escalation: a brief SetForegroundWindow swap + SendInput, restoring the prior foreground afterward. IMPORTANT: 'background' is not a hint to weigh — it is the mandatory first attempt. Do NOT pass 'foreground' preemptively because a target 'looks like' GTK/Chromium/Electron; the DRIVER decides when background is impossible and tells you so via a background_unavailable error (or a verified no-op). Only THEN re-issue the same action with 'foreground'. The lists above are the driver's detectors, not a checklist for you to front on a guess — fronting up-front needlessly steals the user's focus and is a bug, not a shortcut. Matches the macOS delivery_mode surface.-- `element_index` (integer, optional): Element index from the last get_window_state for the same (pid, window_id). When supplied, type_text writes through UIA ValuePattern and reads that exact element back by handle. The shared ActionResult is confirmed only when the complete expected value is synchronously visible. If SetValue succeeds but read-back is stale or unavailable, the result is unverifiable with no escalation; take a fresh snapshot before retrying because deferred providers may publish only after this call returns. Requires window_id.-- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.+- `element_token` (string, optional): Opaque element handle from get_window_state. When supplied, type_text writes through UIA ValuePattern and reads that exact element back by handle. The shared ActionResult is confirmed only when the complete expected value is synchronously visible. If SetValue succeeds but read-back is stale or unavailable, the result is unverifiable with no escalation; take a fresh snapshot before retrying because deferred providers may publish only after this call returns.- `pid` (integer, optional): Target process ID.- `scope` (string, optional): Use desktop with no pid/window_id to type into the current foreground application.- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.-- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.- `target` (window target or desktop target, optional): Exact capture/input target selected independently for each action.`display_id="primary"` is the portable desktop target in this release.Platforms that cannot address another display reject it explicitly ratherthan silently changing coordinate spaces.- `text` (string, required): Text to insert at the focused element's cursor.-- `window_id` (integer, optional): HWND of the target window. Required when element_index is used. Optional when element_token is supplied (the token carries it).-- `x` (number, optional): Window-local screenshot-pixel X of the field to type into — the element px action form. Pass x,y (no element_index) and the tool pixel-clicks there to establish real renderer focus, then types. Use for Chromium/Electron inputs the UIA/WM_CHAR path can't reach. Read straight off the get_window_state PNG, same convention as click.+- `window_id` (integer, optional): HWND of the target window. Omit when element_token is supplied (the token carries it).+- `x` (number, optional): Window-local screenshot-pixel X of the field to type into — the element px action form. Pass x,y (no element_token) and the tool pixel-clicks there to establish real renderer focus, then types. Use for Chromium/Electron inputs the UIA/WM_CHAR path can't reach. Read straight off the get_window_state PNG, same convention as click.- `y` (number, optional): Window-local screenshot-pixel Y of the field (see x).```json@@ -426,26 +431,24 @@ Optional `window_id` selects a specific HWND when the pid owns more than one; wiKey vocabulary: return, tab, escape, up/down/left/right, space, delete, home, end, pageup, pagedown, f1-f12, plus any letter or digit. Optional `modifiers` array takes ctrl/shift/alt/win. For true combinations (ctrl+c), `hotkey` is a cleaner surface.-`element_index` focuses the cached UIA element before sending the key; the top-level window remains backgrounded when delivery_mode is background.+`element_token` focuses the cached UIA element before sending the key; the top-level window remains backgrounded when delivery_mode is background.**Arguments:**- `delivery_mode` (string, optional): Input delivery mode. 'background' (default) never swaps foreground: it routes through UIA Invoke / PostMessage and the window is never raised. For targets whose input stack silently drops posted events (Chromium/Electron content, GTK buttons, VCL/LibreOffice accelerators) the tool returns a structured background_unavailable error rather than fronting. 'foreground' is the explicit escalation: a brief SetForegroundWindow swap + SendInput, restoring the prior foreground afterward. IMPORTANT: 'background' is not a hint to weigh — it is the mandatory first attempt. Do NOT pass 'foreground' preemptively because a target 'looks like' GTK/Chromium/Electron; the DRIVER decides when background is impossible and tells you so via a background_unavailable error (or a verified no-op). Only THEN re-issue the same action with 'foreground'. The lists above are the driver's detectors, not a checklist for you to front on a guess — fronting up-front needlessly steals the user's focus and is a bug, not a shortcut. Matches the macOS delivery_mode surface.-- `element_index` (integer, optional): Optional element_index from the last get_window_state; focuses that UIA element before the key is delivered.-- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.+- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.- `key` (string, required): Key name (return, tab, escape, up, down, left, right, space, delete, home, end, pageup, pagedown, f1-f12, letter, digit).- `modifiers` (array of string, optional): Optional modifier names held while the key is pressed (ctrl/shift/alt/win).- `pid` (integer, optional): Target process ID.- `scope` (string, optional): Use desktop with no pid/window_id to send the key to the current foreground application.- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.-- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.- `target` (window target or desktop target, optional): Exact capture/input target selected independently for each action.`display_id="primary"` is the portable desktop target in this release.Platforms that cannot address another display reject it explicitly ratherthan silently changing coordinate spaces.-- `window_id` (integer, optional): HWND for the target window. Required when element_index is used; otherwise auto-resolves the pid's first visible window.-- `x` (number, optional): Window-local screenshot-pixel X — the element px action form: pixel-click there to focus, then send the key. Use when the key must go to a Chromium/Electron surface the UIA path can't focus. Pass with y, no element_index.+- `window_id` (integer, optional): HWND for the target window. Omit when element_token is supplied; otherwise auto-resolves the pid's first visible window.+- `x` (number, optional): Window-local screenshot-pixel X — the element px action form: pixel-click there to focus, then send the key. Use when the key must go to a Chromium/Electron surface the UIA path can't focus. Pass with y, no element_token.- `y` (number, optional): Window-local screenshot-pixel Y (see x).```json@@ -471,13 +474,11 @@ Recognized modifiers: ctrl/control, shift, alt, win/windows. Non-modifier keys u**Arguments:**- `delivery_mode` (string, optional): Input delivery mode. 'background' (default) never swaps foreground: it routes through UIA Invoke / PostMessage and the window is never raised. For targets whose input stack silently drops posted events (Chromium/Electron content, GTK buttons, VCL/LibreOffice accelerators) the tool returns a structured background_unavailable error rather than fronting. 'foreground' is the explicit escalation: a brief SetForegroundWindow swap + SendInput, restoring the prior foreground afterward. IMPORTANT: 'background' is not a hint to weigh — it is the mandatory first attempt. Do NOT pass 'foreground' preemptively because a target 'looks like' GTK/Chromium/Electron; the DRIVER decides when background is impossible and tells you so via a background_unavailable error (or a verified no-op). Only THEN re-issue the same action with 'foreground'. The lists above are the driver's detectors, not a checklist for you to front on a guess — fronting up-front needlessly steals the user's focus and is a bug, not a shortcut. Matches the macOS delivery_mode surface.-- `element_index` (integer, optional): Element index from get_window_state. Requires the matching `snapshot_id` alongside it. Prefer `element_token`, which carries both values.-- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.+- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.- `keys` (array of string, required): Modifier(s) and one non-modifier key, e.g. ["ctrl", "c"]. items: 2–unbounded- `pid` (integer, optional): Target process ID.- `scope` (string, optional): Use desktop with no pid/window_id to send the hotkey to the current foreground application.- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.-- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.- `target` (window target or desktop target, optional): Exact capture/input target selected independently for each action.`display_id="primary"` is the portable desktop target in this release.@@ -503,13 +504,12 @@ For free-form text entry that the target accepts via keystrokes only, prefer `ty**Arguments:**-- `element_index` (integer, optional): Element index from get_window_state. Requires the matching `snapshot_id` alongside it. Prefer `element_token`, which carries both values.-- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.+- `delivery_mode` (string, optional): Input delivery mode. 'background' (default) never swaps foreground: it routes through UIA Invoke / PostMessage and the window is never raised. For targets whose input stack silently drops posted events (Chromium/Electron content, GTK buttons, VCL/LibreOffice accelerators) the tool returns a structured background_unavailable error rather than fronting. 'foreground' is the explicit escalation: a brief SetForegroundWindow swap + SendInput, restoring the prior foreground afterward. IMPORTANT: 'background' is not a hint to weigh — it is the mandatory first attempt. Do NOT pass 'foreground' preemptively because a target 'looks like' GTK/Chromium/Electron; the DRIVER decides when background is impossible and tells you so via a background_unavailable error (or a verified no-op). Only THEN re-issue the same action with 'foreground'. The lists above are the driver's detectors, not a checklist for you to front on a guess — fronting up-front needlessly steals the user's focus and is a bug, not a shortcut. Matches the macOS delivery_mode surface.+- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.- `pid` (integer, required): Target process ID.- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.-- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.- `value` (string, required): New value. UIA will coerce to the element's native type.-- `window_id` (integer, optional): HWND of the window. Required when element_index is used; optional when element_token is supplied (the token carries it).+- `window_id` (integer, optional): HWND of the window. Omit when element_token is supplied (the token carries it).```json{"pid":844,"value":"42"}@@ -523,7 +523,7 @@ Windows transport: WM_VSCROLL / WM_HSCROLL posted to the window — the same eveMapping: `by: "page"` → SB_PAGEDOWN/UP/LEFT/RIGHT × amount; `by: "line"` → SB_LINEDOWN/UP/LEFT/RIGHT × amount.-Note: `element_index` is accepted for cross-platform parity but currently no-op on Windows (UIA SetFocus not wired up yet — same caveat as `press_key`).+Note: `element_token` is accepted for cross-platform parity but currently no-op on Windows (UIA SetFocus not wired up yet — same caveat as `press_key`).**Arguments:**@@ -531,18 +531,16 @@ Note: `element_index` is accepted for cross-platform parity but currently no-op- `by` (string, optional): Scroll granularity. Default: line.- `delivery_mode` (string, optional): Input delivery mode. 'background' (default) never swaps foreground: it routes through UIA Invoke / PostMessage and the window is never raised. For targets whose input stack silently drops posted events (Chromium/Electron content, GTK buttons, VCL/LibreOffice accelerators) the tool returns a structured background_unavailable error rather than fronting. 'foreground' is the explicit escalation: a brief SetForegroundWindow swap + SendInput, restoring the prior foreground afterward. IMPORTANT: 'background' is not a hint to weigh — it is the mandatory first attempt. Do NOT pass 'foreground' preemptively because a target 'looks like' GTK/Chromium/Electron; the DRIVER decides when background is impossible and tells you so via a background_unavailable error (or a verified no-op). Only THEN re-issue the same action with 'foreground'. The lists above are the driver's detectors, not a checklist for you to front on a guess — fronting up-front needlessly steals the user's focus and is a bug, not a shortcut. Matches the macOS delivery_mode surface.- `direction` (string, required)-- `element_index` (integer, optional): Optional element_index. Accepted for parity; currently no-op on Windows.-- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.+- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.- `pid` (integer, optional): Target process ID for window scope. Omit with scope=desktop for screen-absolute coordinates from get_desktop_state.- `scope` (string, optional): default: `"window"`- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.-- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.- `target` (window target or desktop target, optional): Exact capture/input target selected independently for each action.`display_id="primary"` is the portable desktop target in this release.Platforms that cannot address another display reject it explicitly ratherthan silently changing coordinate spaces.-- `window_id` (integer, optional): HWND of the target window. Required when element_index is used; otherwise auto-resolves the pid's first visible window.+- `window_id` (integer, optional): HWND of the target window. Omit when element_token is supplied; otherwise auto-resolves the pid's first visible window.- `x` (number, optional): With pid/window_id: window-local screenshot X used to target a nested scroll surface in foreground mode. Without pid/window_id: screen-absolute X for desktop scope. Must be paired with y.- `y` (number, optional): With pid/window_id: window-local screenshot Y used to target a nested scroll surface in foreground mode. Without pid/window_id: screen-absolute Y for desktop scope. Must be paired with x.@@ -575,13 +573,14 @@ Coordinates `x1, y1, x2, y2` are in the same pixel space as the screenshot returA 20% padding is automatically added on every side of the requested region so the target remains visible even if the caller's coordinates are slightly off.-After a zoom, pass `from_zoom=true` to click/type_text to auto-translate coordinates back to full-window space. Coordinate actions return `screenshot_context_missing` when the latest snapshot does not contain a screenshot owned by this session. `from_zoom` actions return `zoom_context_missing` when the zoom was never created or was replaced; call `get_window_state`, then `zoom`, again on the same connection.+After a zoom, pass `from_zoom=true` to click/type_text to auto-translate coordinates back to full-window space. Coordinate actions return `screenshot_context_missing` when no current snapshot contains a screenshot owned by this session. `from_zoom` actions return `zoom_context_missing` when the zoom was never created or was replaced; call `get_window_state`, then `zoom`, again on the same connection.Windows-specific: `window_id` is the canonical addressing field (HWND). `pid` is preferred when available; otherwise the driver resolves the unique current snapshot owned by this session and window.**Arguments:**- `pid` (integer, optional): Optional target process ID. When omitted, the unique current snapshot for this session and HWND is used.+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.- `window_id` (integer, required): HWND of the target window.- `x1` (number, required): Left edge of the region (resized-image pixels).- `x2` (number, required): Right edge of the region (resized-image pixels).@@ -617,6 +616,7 @@ Actions:- `javascript` (string, optional): JavaScript to execute. Required for execute_javascript.- `pid` (integer, optional): Target process ID.- `selector` (string, optional): CSS selector for click_element (e.g. 'button.submit', '#login a').+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.- `target_url_contains` (string, optional): Optional, for execute_javascript/insert_text/type_keystrokes: require exactly one browser tab whose URL contains this substring. Use this on a multi-tab browser — there's no built-in link between window_id and which tab a CDP call reaches.- `text` (string, optional): Text to insert or type. Required for insert_text and type_keystrokes. The target field must already have DOM focus (click/focus it first).- `user_has_confirmed_enabling` (boolean, optional): Must be true to proceed with enable_javascript_apple_events. This will quit and relaunch the browser.@@ -697,14 +697,16 @@ Stop trajectory recording. Disables further per-turn capture and, when video wasA manual `stop_recording` is **unconditional** — it stops whatever recording is active regardless of which session started it. Ownership-scoped teardown (so one client disconnecting can't stop a recording a later client started) is handled by the registry's `session_end` lifecycle hook, not by this tool.-**Arguments:** none.+**Arguments:**++- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.### `replay_trajectory`Replay a recorded trajectory by re-invoking every turn's tool call in lexical order. `dir` must point at a directory previously written by `start_recording`. Each `turn-NNNNN/` is parsed for `action.json`, and the recorded tool is called with its recorded `arguments` via the same dispatch path an MCP / CLI call uses.Caveats:-- Element-indexed actions (`click({pid, element_index})` etc.) will fail because element indices are per-snapshot and don't survive across sessions. Pixel clicks (`click({pid, x, y})`) and all keyboard tools replay cleanly. Failures are reported but don't stop replay unless `stop_on_error` is true.+- Element-token actions (`click({pid, element_token})` etc.) will fail because element tokens are per-snapshot and don't survive across sessions. Pixel clicks (`click({pid, x, y})`) and all keyboard tools replay cleanly. Failures are reported but don't stop replay unless `stop_on_error` is true.- `get_window_state` and other read-only tools are NOT currently recorded, so replays do not re-populate the per-(pid, window_id) element cache.- If recording is ENABLED while replay runs, the replay itself is recorded into the currently configured output directory. That's deliberate: recording a replay against a new build and diffing the two trajectories is the regression-test workflow.@@ -712,6 +714,7 @@ Caveats:- `delay_ms` (integer, optional): Milliseconds to sleep between turns, for human-observable pacing. Default 500. range: 0–10000- `dir` (string, required): Trajectory directory previously written by `start_recording`. Absolute or ~-rooted.+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.- `stop_on_error` (boolean, optional): Stop replay on the first tool-call error. Default true — set false to best-effort through the full trajectory.```json@@ -743,6 +746,7 @@ Returns the full updated config in the same shape as `get_config`.- `experimental_pip_geometry` (string, optional): Legacy per-field shape. PiP window size + optional position.- `key` (string, optional): Dotted snake_case path to a leaf config field (Swift-compatible shape). Pair with `value`.- `max_image_dimension` (integer, optional): Legacy per-field shape.+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.- `value` (unknown, optional): New value for `key`. JSON type depends on the key.### `start_session`@@ -808,7 +812,9 @@ Configure only movement physics and visibility timing for a session cursor.Check required permissions for cua-driver-rs on Windows.-**Arguments:** none.+**Arguments:**++- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.### `health_report`@@ -858,13 +864,16 @@ Stability: schema_version="1" is the contract. Future breaking changes will be `**Arguments:**- `include` (array of string, optional): Only run these checks (canonical names). Wins over `skip`.+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.- `skip` (array of string, optional): Skip these checks (canonical names). Ignored when `include` is set.### `check_for_update`Check the saved stable/nightly Cua Driver channel for a release on GitHub. Returns current and selected channels, current and latest versions, an `update_available` boolean, the install one-liner, and the release notes URL. Read-only — never installs. Pacman-owned Linux executables return package-manager guidance without checking GitHub. Mirror of `cua-driver check-update --json`.-**Arguments:** none.+**Arguments:**++- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.### `install_ffmpeg`@@ -873,6 +882,7 @@ Install the ffmpeg binary used by start_recording's video capture (Linux/Windows**Arguments:**- `confirm` (boolean, optional): Run the install command. Without it, only the planned command is reported.+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.## Other tools@@ -920,6 +930,7 @@ Diagnostic: dump everything cua-driver sees about a pid's top-level windows from**Arguments:**- `pid` (integer, required): PID of the process to inspect.+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.```json{"pid":844}@@ -1144,6 +1155,7 @@ Preview or install one Driver-managed optional extension. The first call without- `confirm` (boolean, optional): Install the previewed extension. Omit or false for a read-only plan.- `name` (string, required)+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.```json{"name":"perception"}@@ -1157,6 +1169,7 @@ Parse one immutable registered capture into model-neutral text and icon regions.- `capture_id` (string, required)- `options` (object, optional): Optional, model-neutral controls for one bounded parse. default: `{}`+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.```json{"capture_id":"example"}diff --git a/docs/content/docs/reference/cua-driver/mcp-tools.mdx b/docs/content/docs/reference/cua-driver/mcp-tools.mdxindex ce362d4f03..e53d604b08 100644--- a/docs/content/docs/reference/cua-driver/mcp-tools.mdx+++ b/docs/content/docs/reference/cua-driver/mcp-tools.mdx@@ -46,7 +46,9 @@ Standalone running entries include only apps with NSApplicationActivationPolicyRUse this for "is X installed?" as well as "is X running?". For per-window state — on-screen, on-current-Space, minimized, window titles — call list_windows instead. For just opening an app — running or not — call launch_app({bundle_id: ...}) directly; list_apps is not a prerequisite.-**Arguments:** none.+**Arguments:**++- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.### `list_windows`@@ -58,16 +60,17 @@ Per-record fields: window_id, pid, app_name, title, bounds (x/y/width/height, to- `on_screen_only` (boolean, optional): When true, drop windows not on the current Space. Default false.- `pid` (integer, optional): Optional pid filter. When set, only this pid's windows are returned.+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.### `get_window_state`-Walk a running app's AX tree and return BOTH a structured `elements` array (preferred) AND a Markdown rendering of the same tree (back-compat). Every actionable element is tagged with [element_index N] in the markdown and as `element_index` in the structured array — pass those indices to click, type_text, press_key, etc.+Walk a running app's AX tree and return BOTH a structured `elements` array (preferred) AND a Markdown rendering of the same tree (back-compat). Every actionable element is tagged with [element_index N] in the markdown and as `element_index` in the structured array; pass each element's `element_token` to click, type_text, press_key, etc.-INVARIANT: call get_window_state once per turn per (pid, window_id) before any element-indexed action. The index map is replaced by the next snapshot.+INVARIANT: call get_window_state once per turn per (pid, window_id) before any element action. The next snapshot of the window replaces this one, stales its element tokens, and lists the replaced ids in `invalidated_snapshot_ids`.PREFERRED CONSUMERS read `structuredContent.elements` (one entry per indexed row with `element_index`, `role`, `label`, `value` (the element's text/AXValue when present — use it to verify what a field holds), `actions` (names of AX actions exposed by the element, omitted when empty), `frame: {x,y,w,h}`, `parent_index`, `depth`). The markdown `tree_markdown` stays available and unchanged in shape for existing text-parsing callers — but new fields will only be added to the structured side.-Always returns BOTH the element tree AND a screenshot — ground on both and cross-check (the tree lies on some surfaces: Electron echo-confirms, Catalyst null values, virtualized off-viewport rows with `h:1` frames). You choose the modality at ACTION time, not here: an element ax action (pass `element_index`/`element_token` → the accessibility rung) or an element px action (pass `x`,`y` → the pixel rung, read straight off this screenshot). `capture_mode` is deprecated and ignored. Pass `include_screenshot:false` to skip the grab and get the tree only — the cheap path when you're just re-indexing before an element ax action.+Always returns BOTH the element tree AND a screenshot — ground on both and cross-check (the tree lies on some surfaces: Electron echo-confirms, Catalyst null values, virtualized off-viewport rows with `h:1` frames). You choose the modality at ACTION time, not here: an element ax action (pass `element_token` → the accessibility rung) or an element px action (pass `x`,`y` → the pixel rung, read straight off this screenshot). `capture_mode` is deprecated and ignored. Pass `include_screenshot:false` to skip the grab and get the tree only — the cheap path when you're just re-indexing before an element ax action.The mirror image: pass `include_accessibility_tree:false` to SKIP the AX walk entirely (the expensive part, bounded by timeout_ms) and return just the screenshot plus window metadata — `window_bounds`, `screenshot_scale`, `screenshot_width`/`screenshot_height`, `app_name`, and `window_title` — the capture-only path for rendering a live window preview / picture-in-picture without paying for perception. Setting BOTH `include_accessibility_tree:false` and `include_screenshot:false` is an error (nothing to return). Optional `max_image_dimension` overrides the configured screenshot long-edge limit for this call; use 0 for native resolution. The legacy `max_dimension` remains a tighter cap for compatibility.@@ -79,7 +82,7 @@ Optional `max_elements` / `max_depth` bound the AX walk to mitigate context-wind**Arguments:**-- `capture_mode` (string, optional): DEPRECATED and ignored. get_window_state always returns BOTH the element tree and a screenshot — ground on both. The modality is chosen at action time by how you address the target: an element ax action (element_index/element_token) or an element px action (x,y). Any value (including the old "som"/"screenshot" aliases) is accepted but has no effect.+- `capture_mode` (string, optional): DEPRECATED and ignored. get_window_state always returns BOTH the element tree and a screenshot — ground on both. The modality is chosen at action time by how you address the target: an element ax action (element_token) or an element px action (x,y). Any value (including the old "som"/"screenshot" aliases) is accepted but has no effect.- `include_accessibility_tree` (boolean, optional): Default true — walk the AX tree and return `elements` + `tree_markdown` alongside the screenshot. Set false to SKIP the AX walk entirely (the expensive part, bounded by timeout_ms) and return just the screenshot plus window metadata (bounds, scale, app_name, window_title) — the capture-only path for rendering a live window preview / picture-in-picture. Mirrors include_screenshot. Setting BOTH include_accessibility_tree:false AND include_screenshot:false is an error (nothing to return).- `include_screenshot` (boolean, optional): Default true — returns a grounding screenshot alongside the tree. Set false to skip the grab and return the tree only (the cheap path when you're just re-indexing before an element ax action; saves the image tokens + screen-grab latency). screenshot_out_file still forces a capture to disk.- `max_depth` (integer, optional): Cap on the AX-tree walk depth. Nodes whose rendered indent would exceed this are omitted. Omit for the default (25). Lower this for deep menu/Electron trees. range: 1–unbounded@@ -103,7 +106,9 @@ Return a lightweight snapshot of the desktop: running regular apps and on-screenFor the full AX subtree of a single window (with interactive element indices you can click by), use `get_window_state` instead — that's the heavy per-window tool. This one is a fast discovery read that needs no TCC grants.-**Arguments:** none.+**Arguments:**++- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.### `get_desktop_state`@@ -135,7 +140,9 @@ Return the current mouse cursor position in screen points (origin top-left).Return the current cua-driver-rs configuration.-**Arguments:** none.+**Arguments:**++- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.### `get_recording_state`@@ -143,7 +150,9 @@ Report the current trajectory recorder state: whether recording is enabled, thePure read-only.-**Arguments:** none.+**Arguments:**++- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.### `get_agent_cursor_state`@@ -183,6 +192,7 @@ Returns the launched app's pid, bundle_id, name, and a `windows` array (same sha- `bundle_id` (string, optional): App bundle identifier, e.g. com.apple.calculator. Preferred over name.- `creates_new_application_instance` (boolean, optional): When true, force a new app instance even if already running (open -n). Use for concurrent multi-agent/multi-session work so each session gets an isolated instance + window instead of sharing one — on single-instance apps (e.g. Calculator) every caller otherwise gets the same window and the sessions clobber each other.- `name` (string, optional): App display name. Used only when bundle_id is absent.+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.- `urls` (array of string, optional): Optional file paths or URLs to open with the app (e.g. a folder path for Finder).- `webkit_inspector_port` (integer, optional): Open a WebKit inspector server on this port (sets WEBKIT_INSPECTOR_SERVER env var).@@ -193,6 +203,7 @@ Force-terminate a process by pid (kill -9 equivalent on macOS / Linux; taskkill**Arguments:**- `pid` (integer, required): PID of the process to terminate.+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.```json{"pid":844}@@ -205,6 +216,7 @@ Persistently activate an app and leave it in the foreground. Most input does not**Arguments:**- `pid` (integer, required)+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.- `window_id` (integer, optional)```json@@ -236,7 +248,7 @@ Click against a target pid. **Prefer `element_token` over pixel coordinates**Two addressing modes:-- element_token, or element_index + snapshot_id (from get_window_state): AX action path. Works on backgrounded/hidden windows. No cursor move, no focus steal. The snapshot cache is scoped per (pid, window_id) and is replaced by the next snapshot of the same window — re-snapshot every turn before clicking.+- element_token (from get_window_state): AX action path. Works on backgrounded/hidden windows. No cursor move, no focus steal. The snapshot cache is scoped per (pid, window_id) and is replaced by the next snapshot of the same window — re-snapshot every turn before clicking.- x, y (window-local screenshot pixels, top-left origin of the PNG returned by get_window_state): CGEvent path. Synthesizes mouse events and posts to pid. Use modifier for cmd/shift/option/ctrl. Needs a visible on-screen window to anchor the conversion.@@ -251,41 +263,37 @@ from_zoom: set true after a zoom call to auto-translate zoom-image pixel coordin- `capture_id` (string, optional): Optional immutable source capture ID returned by get_window_state or get_desktop_state. With x,y, Driver atomically admits and consumes that exact capture before dispatch; stale, mismatched, or out-of-bounds captures are refused without fallback.- `count` (integer, optional): Click count (pixel path only). Default 1.- `debug_image_out` (string, optional): Optional file path. When set on a pixel-addressed click, captures a fresh screenshot, draws a red crosshair at (x, y), and writes the PNG. Use to verify coordinate spaces. Requires window_id; incompatible with from_zoom.-- `delivery_mode` (string, optional): Best-effort-background ladder rung (default "background"). "background": perform the AX action or post the CGEvent without fronting. "foreground": briefly front the window, act, let transient UI settle, then restore the prior frontmost app. Requires window_id. Modified clicks require "foreground" so macOS observes physical modifier-key state. A generic click has no independent postcondition read-back, except selection of list-like AX rows whose AXSelected state can be confirmed; otherwise confirm the effect from a fresh state snapshot. Use the agent loop: background AX (element_index) → snapshot → background pixel (x/y) → snapshot → delivery_mode:"foreground".-- `element_index` (integer, optional): Element index from get_window_state. Requires the matching `snapshot_id` alongside it. Prefer `element_token`, which carries both values.-- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.+- `delivery_mode` (string, optional): Best-effort-background ladder rung (default "background"). "background": perform the AX action or post the CGEvent without fronting. "foreground": briefly front the window, act, let transient UI settle, then restore the prior frontmost app. Requires window_id. Modified clicks require "foreground" so macOS observes physical modifier-key state. A generic click has no independent postcondition read-back, except selection of list-like AX rows whose AXSelected state can be confirmed; otherwise confirm the effect from a fresh state snapshot. Use the agent loop: background AX (element_token) → snapshot → background pixel (x/y) → snapshot → delivery_mode:"foreground".+- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.- `from_zoom` (boolean, optional): When true, x and y are in the last zoom image for this pid; driver translates back to full-window coordinates.- `modifier` (array of string, optional): Modifier keys: cmd, shift, option/alt, ctrl.- `pid` (integer, optional): Target process ID.- `scope` (string, optional): Coordinate frame for a windowless screen-absolute click (default "window"). Pass "desktop" when sending x,y with NO pid/window_id — the coordinates are then true screen pixels (read from get_desktop_state with scope="desktop"). Per-call; not a setting.- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.-- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.- `target` (window target or desktop target, optional): Exact capture/input target selected independently for each action.`display_id="primary"` is the portable desktop target in this release.Platforms that cannot address another display reject it explicitly ratherthan silently changing coordinate spaces.-- `window_id` (integer, optional): Target window ID. Required for element_index. Optional when element_token is supplied (the token carries it).+- `window_id` (integer, optional): Target window ID. Omit when element_token is supplied (the token carries it).- `x` (number, optional): X in screenshot pixels. A window target uses the get_window_state PNG; a desktop target uses the native get_desktop_state PNG. The driver reverses Retina backing scale and any window-image downscale.- `y` (number, optional): Y in screenshot pixels from the image selected by target.### `double_click`-Double-click at (x, y) or on an AX element identified by element_index + window_id.+Double-click at (x, y) or on an AX element identified by element_token.-AX path (element_index provided): performs `AXOpen` when the element advertises it (Finder items, openable list rows/cells); otherwise resolves the element's on-screen center and falls back to a pixel double-click there.+AX path (element_token provided): performs `AXOpen` when the element advertises it (Finder items, openable list rows/cells); otherwise resolves the element's on-screen center and falls back to a pixel double-click there.Pixel path (x, y provided): two down/up pairs ~80 ms apart at the given coordinates.**Arguments:**- `delivery_mode` (string, optional): Best-effort-background ladder rung (default "background"). "background": inject without fronting or raising the target — no focus steal. "foreground": briefly front the target, act, then restore the prior frontmost — the explicit last resort when a background attempt didn't land. Re-call with "foreground" only for the action that needs it.-- `element_index` (integer, optional): Element index from get_window_state. Requires the matching `snapshot_id` alongside it. Prefer `element_token`, which carries both values.-- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.+- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.- `pid` (integer, required)- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.-- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.-- `window_id` (integer, optional): CGWindowID. Required when element_index is used. Optional when element_token is supplied (the token carries it).+- `window_id` (integer, optional): CGWindowID. Omit when element_token is supplied (the token carries it).- `x` (number, optional): Screen X coordinate (pixel path).- `y` (number, optional): Screen Y coordinate (pixel path).@@ -297,22 +305,20 @@ Pixel path (x, y provided): two down/up pairs ~80 ms apart at the given coordinaRight-click against a target pid. Two addressing modes:-- `element_index` + `window_id` (from the last `get_window_state` snapshot) — performs `AXShowMenu` on the cached element. Pure AX RPC, works on backgrounded / hidden windows, no cursor move or focus steal. Requires a prior `get_window_state(pid, window_id)` in this turn.+- `element_token` (from the last `get_window_state` snapshot) — performs `AXShowMenu` on the cached element. Pure AX RPC, works on backgrounded / hidden windows, no cursor move or focus steal. Requires a prior `get_window_state(pid, window_id)` in this turn.- `x`, `y` — synthesizes `rightMouseDown` / `rightMouseUp` CGEvent pair posted to the pid. Driver converts image-pixel → screen-point internally. `modifier` forces the CGEvent path (AX actions don't propagate modifier keys).-Exactly one of `element_index` or (`x` AND `y`) must be provided. `pid` always required. `window_id` required when `element_index` is used.+Exactly one of `element_token` or (`x` AND `y`) must be provided. `pid` always required.**Arguments:**- `delivery_mode` (string, optional): Best-effort-background ladder rung (default "background"). "background": inject without fronting or raising the target — no focus steal. "foreground": briefly front the target, act, then restore the prior frontmost — the explicit last resort when a background attempt didn't land. Re-call with "foreground" only for the action that needs it.-- `element_index` (integer, optional): Element index from get_window_state. Requires the matching `snapshot_id` alongside it. Prefer `element_token`, which carries both values.-- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.+- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.- `modifier` (array of string, optional): Modifier keys held during the right-click: cmd/shift/option/ctrl. Pixel path only.- `pid` (integer, required): Target process ID.- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.-- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.-- `window_id` (integer, optional): CGWindowID. Required when element_index is used. Optional when element_token is supplied (the token carries it).+- `window_id` (integer, optional): CGWindowID. Omit when element_token is supplied (the token carries it).- `x` (number, optional): X in window-local screenshot pixels. Must be provided together with y.- `y` (number, optional): Y in window-local screenshot pixels. Must be provided together with x.@@ -362,28 +368,26 @@ than silently changing coordinate spaces.Insert text into the target pid via `AXSetAttribute(kAXSelectedText)`. Works for standard Cocoa text fields and text views. No keystrokes are synthesized — special keys (Return / Escape / arrows) go through `press_key` / `hotkey`. For Chromium / Electron inputs that don't implement `kAXSelectedText`, the tool falls back to CGEvent character synthesis automatically when the estimated route stays within the daemon transport budget. Longer synthesized routes are refused before character events and return a safe chunk size; one-call AX insertion remains uncapped.-Optional `element_index` + `window_id` (from the last `get_window_state` snapshot) directs the write to a specific field. Without `element_index`, the write goes to the pid's currently focused element.+Optional `element_token` (from the last `get_window_state` snapshot) directs the write to a specific field. Without `element_token`, the write goes to the pid's currently focused element.-WEB CONTENT (Chromium/WebKit/Electron — browser tabs, Slack, VS Code, X's compose box): AXValue is not independent proof that the renderer/DOM observed an AX write or synthesized keystrokes. The driver detects this at the element level (an AXWebArea ancestor) and refuses to trust AXValue-only read-back there. Electron AX targets that are web content or cannot be proven native refuse background delivery before mutation because the AX route cannot establish exact renderer focus; use the px form or explicit foreground delivery. Other web-content paths return effect:"unverifiable" + escalation, never a false "confirmed" (a browser's own native address bar/toolbar stays trusted). For a browser TAB the reliable path is the `page` tool (drives the DOM via CDP); for an embedded web view use this tool's px form: pass x,y (no element_index) to pixel-click the field then type, in one call. NOTE: a px focus-click won't reliably open+focus a CLOSED control; AX-press to open/activate it first (works in the background), then px-type. Always confirm via the screenshot; if px-background still drops, escalate to delivery_mode:"foreground".+WEB CONTENT (Chromium/WebKit/Electron — browser tabs, Slack, VS Code, X's compose box): AXValue is not independent proof that the renderer/DOM observed an AX write or synthesized keystrokes. The driver detects this at the element level (an AXWebArea ancestor) and refuses to trust AXValue-only read-back there. Electron AX targets that are web content or cannot be proven native refuse background delivery before mutation because the AX route cannot establish exact renderer focus; use the px form or explicit foreground delivery. Other web-content paths return effect:"unverifiable" + escalation, never a false "confirmed" (a browser's own native address bar/toolbar stays trusted). For a browser TAB the reliable path is the `page` tool (drives the DOM via CDP); for an embedded web view use this tool's px form: pass x,y (no element_token) to pixel-click the field then type, in one call. NOTE: a px focus-click won't reliably open+focus a CLOSED control; AX-press to open/activate it first (works in the background), then px-type. Always confirm via the screenshot; if px-background still drops, escalate to delivery_mode:"foreground".**Arguments:**- `delay_ms` (integer, optional): Milliseconds between characters in the CGEvent fallback path. Default 30. Ignored when the AX path succeeds. range: 0–200- `delivery_mode` (string, optional): Best-effort-background ladder rung (default "background"). "background": AX insert, then CGEvent keystrokes if needed — no focus steal; native controls can be confirmed via AXValue read-back, while web-content writes remain effect:"unverifiable". "foreground": briefly front the window, type, restore the prior frontmost — the explicit last resort for focus-sensitive surfaces (e.g. WhatsApp/Catalyst) where background keystrokes don't land. Re-call with "foreground" when a background attempt remains unverifiable and a fresh snapshot shows the text did not appear.-- `element_index` (integer, optional): Element index from get_window_state. Requires the matching `snapshot_id` alongside it. Prefer `element_token`, which carries both values.-- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.+- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.- `pid` (integer, optional): Target process ID.- `scope` (string, optional): Use desktop with no pid/window_id to type into the frontmost application. default: `"window"`- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.-- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.- `target` (window target or desktop target, optional): Exact capture/input target selected independently for each action.`display_id="primary"` is the portable desktop target in this release.Platforms that cannot address another display reject it explicitly ratherthan silently changing coordinate spaces.- `text` (string, required): Text to insert at the target's cursor.-- `window_id` (integer, optional): CGWindowID. Required when element_index is used. Optional when element_token is supplied (the token carries it).-- `x` (number, optional): Screenshot-pixel X of the field to type into — the element px action form. Pass x,y (no element_index) and the tool pixel-clicks there to establish real renderer focus, then types. Use for Chromium/Electron inputs the AX path can't reach. Read straight off the get_window_state PNG, same convention as click.+- `window_id` (integer, optional): CGWindowID. Omit when element_token is supplied (the token carries it).+- `x` (number, optional): Screenshot-pixel X of the field to type into — the element px action form. Pass x,y (no element_token) and the tool pixel-clicks there to establish real renderer focus, then types. Use for Chromium/Electron inputs the AX path can't reach. Read straight off the get_window_state PNG, same convention as click.- `y` (number, optional): Screenshot-pixel Y of the field (see x).```json@@ -393,7 +397,7 @@ than silently changing coordinate spaces.### `press_key`Press and release a single key. Follows the same `delivery_mode` ladder as click/type_text — it does NOT raise the window by default:-• `background` (default): post to the pid WITHOUT fronting/raising — the auth-message path (Chromium-safe). With element_index it focuses that AX element first. `window_id` only targets; it does not raise.+• `background` (default): post to the pid WITHOUT fronting/raising — the auth-message path (Chromium-safe). With element_token it focuses that AX element first. `window_id` only targets; it does not raise.• `foreground`: guard and briefly front the exact window, focus an addressed AX element when supplied, send a genuine HID key transition so Chromium content, inline editors, and native menu equivalents receive it, then restore prior frontmost. Requires window_id.A key press is confirmed only when a bounded native AX value/selection read-back changes on the same control. Otherwise a successfully attempted post remains effect:"unverifiable" without implying delivery failure or recommending foreground. Key names: return, tab, escape, up/down/left/right, space, delete, home, end, pageup, pagedown, f1-f12, plus any letter or digit. Modifiers array: cmd, shift, option/alt, ctrl, fn.@@ -401,21 +405,19 @@ A key press is confirmed only when a bounded native AX value/selection read-back**Arguments:**- `delivery_mode` (string, optional): Best-effort-background ladder rung (default "background"). "background": inject without fronting or raising the target — no focus steal. "foreground": briefly front the target, act, then restore the prior frontmost — the explicit last resort when a background attempt didn't land. Re-call with "foreground" only for the action that needs it.-- `element_index` (integer, optional): Element index from get_window_state. Requires the matching `snapshot_id` alongside it. Prefer `element_token`, which carries both values.-- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.+- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.- `key` (string, required): Key name: return, tab, escape, up, down, etc.- `modifiers` (array of string, optional): Modifier keys: cmd, shift, option/alt, ctrl, fn.- `pid` (integer, optional)- `scope` (string, optional): Use desktop with no pid/window_id to send the key to the frontmost application. default: `"window"`- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.-- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.- `target` (window target or desktop target, optional): Exact capture/input target selected independently for each action.`display_id="primary"` is the portable desktop target in this release.Platforms that cannot address another display reject it explicitly ratherthan silently changing coordinate spaces.- `window_id` (integer, optional): Target window. Required for delivery_mode:"foreground". Does NOT itself raise the window — raising is gated on delivery_mode.-- `x` (number, optional): Screenshot-pixel X — the element px action form: pixel-click there to focus, then send the key. Use when the key must go to a Chromium/Electron surface the AX path can't focus. Pass with y, no element_index.+- `x` (number, optional): Screenshot-pixel X — the element px action form: pixel-click there to focus, then send the key. Use when the key must go to a Chromium/Electron surface the AX path can't focus. Pass with y, no element_token.- `y` (number, optional): Screenshot-pixel Y (see x).```json@@ -435,13 +437,11 @@ Recognized modifiers: cmd/command, shift, option/alt, ctrl/control, fn. Non-modi**Arguments:**- `delivery_mode` (string, optional): Best-effort-background ladder rung (default "background"). "background": inject without fronting or raising the target — no focus steal. "foreground": briefly front the target, act, then restore the prior frontmost — the explicit last resort when a background attempt didn't land. Re-call with "foreground" only for the action that needs it.-- `element_index` (integer, optional): Element index from get_window_state. Requires the matching `snapshot_id` alongside it. Prefer `element_token`, which carries both values.-- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.+- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.- `keys` (array of string, required): Modifier(s) and one non-modifier key, e.g. ["cmd", "c"]. items: 2–unbounded- `pid` (integer, optional): Target process ID.- `scope` (string, optional): Use desktop with no pid/window_id to send the chord to the frontmost application. default: `"window"`- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.-- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.- `target` (window target or desktop target, optional): Exact capture/input target selected independently for each action.`display_id="primary"` is the portable desktop target in this release.@@ -467,13 +467,11 @@ For free-form text entry into web inputs, prefer `type_text_chars` which synthes**Arguments:**-- `element_index` (integer, optional): Element index from get_window_state. Requires the matching `snapshot_id` alongside it. Prefer `element_token`, which carries both values.-- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.+- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.- `pid` (integer, required)- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.-- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.- `value` (string, required): New value. AX will coerce to the element's native type.-- `window_id` (integer, optional): CGWindowID for the window whose get_window_state produced the element_index. Required when element_index is used; optional when element_token is supplied (the token carries it).+- `window_id` (integer, optional): CGWindowID. Omit when element_token is supplied (the token carries it).```json{"pid":844,"value":"42"}@@ -483,7 +481,7 @@ For free-form text entry into web inputs, prefer `type_text_chars` which synthesScroll the target pid. Two paths, picked by how you address the scroll:-• **Targeted wheel path** — when you pass a target, either `element_index`/`element_token` (preferred) or window-local `x, y` pixels: the driver synthesizes a real mouse-wheel event (CGEventCreateScrollWheelEvent, at that screen point. The renderer hit-tests the wheel at the cursor, so the scroll lands on whatever element is under the point — exactly like physically rolling the wheel over it. This is the ONLY way to scroll a nested `overflow:auto` region (e.g. a scrollable <div> with no tabindex): such regions never take keyboard focus, so the keystroke path below no-ops on them. Use this for inner/nested scrollers in web views.+• **Targeted wheel path** — when you pass a target, either `element_token` (preferred) or window-local `x, y` pixels: the driver synthesizes a real mouse-wheel event (CGEventCreateScrollWheelEvent, at that screen point. The renderer hit-tests the wheel at the cursor, so the scroll lands on whatever element is under the point — exactly like physically rolling the wheel over it. This is the ONLY way to scroll a nested `overflow:auto` region (e.g. a scrollable <div> with no tabindex): such regions never take keyboard focus, so the keystroke path below no-ops on them. Use this for inner/nested scrollers in web views.• **Keystroke path (focused region)** — when you pass NO target (just pid + direction): synthesizes PageDown/PageUp (by='page') or Down/Up arrows (by='line'); horizontal uses Left/Right arrows. Drives the focused / page scroller only.@@ -495,12 +493,10 @@ Mapping: by='page' → larger step; by='line' → smaller step; amount = number- `by` (string, optional): Scroll granularity. Default: line.- `delivery_mode` (string, optional): Best-effort-background ladder rung (default "background"). "background": inject without fronting or raising the target — no focus steal. "foreground": briefly front the target, act, then restore the prior frontmost — the explicit last resort when a background attempt didn't land. Re-call with "foreground" only for the action that needs it.- `direction` (string, required): Scroll direction.-- `element_index` (integer, optional): Element index from get_window_state. Requires the matching `snapshot_id` alongside it. Prefer `element_token`, which carries both values.-- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.+- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.- `pid` (integer, optional)- `scope` (string, optional): Use desktop with x,y and no pid/window_id for native get_desktop_state screenshot coordinates. default: `"window"`- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.-- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.- `target` (window target or desktop target, optional): Exact capture/input target selected independently for each action.`display_id="primary"` is the portable desktop target in this release.@@ -535,11 +531,12 @@ Move a cursor to (x, y). In window scope (default), moves only the agent cursorCapture a cropped JPEG of a window region (x1,y1)–(x2,y2) in screenshot pixel coordinates, with 20% padding added on each side. The output image is at most 500 px wide.-After a zoom, pass `from_zoom=true` to click/type_text to auto-translate coordinates back to full-window space. Coordinate actions return `screenshot_context_missing` when the latest snapshot does not contain a screenshot owned by this session. `from_zoom` actions return `zoom_context_missing` when the zoom was never created or was replaced; call `get_window_state`, then `zoom`, again on the same connection.+After a zoom, pass `from_zoom=true` to click/type_text to auto-translate coordinates back to full-window space. Coordinate actions return `screenshot_context_missing` when no current snapshot contains a screenshot owned by this session. `from_zoom` actions return `zoom_context_missing` when the zoom was never created or was replaced; call `get_window_state`, then `zoom`, again on the same connection.**Arguments:**- `pid` (integer, optional): Optional target pid. When omitted, the driver resolves the unique current snapshot for this session and window.+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.- `window_id` (integer, required): CGWindowID from list_windows.- `x1` (number, required): Left edge of region in screenshot pixels.- `x2` (number, required): Right edge of region in screenshot pixels.@@ -575,6 +572,7 @@ Actions:- `javascript` (string, optional): JavaScript to execute. Required for execute_javascript.- `pid` (integer, optional): Target process ID.- `selector` (string, optional): CSS selector for click_element (e.g. 'button.submit', '#login a').+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.- `target_url_contains` (string, optional): Optional, for execute_javascript/insert_text/type_keystrokes: require exactly one browser tab whose URL contains this substring. Use this on a multi-tab browser — there's no built-in link between window_id and which tab a CDP call reaches.- `text` (string, optional): Text to insert or type. Required for insert_text and type_keystrokes. The target field must already have DOM focus (click/focus it first).- `user_has_confirmed_enabling` (boolean, optional): Must be true to proceed with enable_javascript_apple_events. This will quit and relaunch the browser.@@ -655,14 +653,16 @@ Stop trajectory recording. Disables further per-turn capture and, when video wasA manual `stop_recording` is **unconditional** — it stops whatever recording is active regardless of which session started it. Ownership-scoped teardown (so one client disconnecting can't stop a recording a later client started) is handled by the registry's `session_end` lifecycle hook, not by this tool.-**Arguments:** none.+**Arguments:**++- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.### `replay_trajectory`Replay a recorded trajectory by re-invoking every turn's tool call in lexical order. `dir` must point at a directory previously written by `start_recording`. Each `turn-NNNNN/` is parsed for `action.json`, and the recorded tool is called with its recorded `arguments` via the same dispatch path an MCP / CLI call uses.Caveats:-- Element-indexed actions (`click({pid, element_index})` etc.) will fail because element indices are per-snapshot and don't survive across sessions. Pixel clicks (`click({pid, x, y})`) and all keyboard tools replay cleanly. Failures are reported but don't stop replay unless `stop_on_error` is true.+- Element-token actions (`click({pid, element_token})` etc.) will fail because element tokens are per-snapshot and don't survive across sessions. Pixel clicks (`click({pid, x, y})`) and all keyboard tools replay cleanly. Failures are reported but don't stop replay unless `stop_on_error` is true.- `get_window_state` and other read-only tools are NOT currently recorded, so replays do not re-populate the per-(pid, window_id) element cache.- If recording is ENABLED while replay runs, the replay itself is recorded into the currently configured output directory. That's deliberate: recording a replay against a new build and diffing the two trajectories is the regression-test workflow.@@ -670,6 +670,7 @@ Caveats:- `delay_ms` (integer, optional): Milliseconds to sleep between turns, for human-observable pacing. Default 500. range: 0–10000- `dir` (string, required): Trajectory directory previously written by `start_recording`. Absolute or ~-rooted.+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.- `stop_on_error` (boolean, optional): Stop replay on the first tool-call error. Default true — set false to best-effort through the full trajectory.```json@@ -690,6 +691,7 @@ Note: capture_mode is a per-call param (on get_window_state / click), not a stor- `experimental_pip_geometry` (string, optional): PiP window size + optional position in `WxH` or `WxH+X+Y` form (e.g. `320x200+24+24`). Applies on next daemon restart.- `key` (string, optional): Name of a single config field to write ({key, value} shape, matching the CLI `config set` and the Windows/Linux tools). Pair with `value`. Equivalent to passing the field directly.- `max_image_dimension` (integer, optional): Max dimension for screenshot resizing (0 = no limit).+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.- `value` (unknown, optional): New value for `key`. JSON type depends on the key.### `start_session`@@ -761,6 +763,7 @@ Returns: `accessibility` + `screen_recording` (booleans from the TCC preflight A- `probe_direct_capture` (boolean, optional): When prompting and Screen Recording is granted, also run the live ScreenCaptureKit probe that may raise Tahoe's direct-capture consent. Default true. Set false for a staged Accessibility/Screen Recording request.- `prompt` (boolean, optional): Raise the system permission prompts for missing grants. Default false; only a trusted host setup route may set true. default: `false`+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.### `health_report`@@ -810,13 +813,16 @@ Stability: schema_version="1" is the contract. Future breaking changes will be `**Arguments:**- `include` (array of string, optional): Only run these checks (canonical names). Wins over `skip`.+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.- `skip` (array of string, optional): Skip these checks (canonical names). Ignored when `include` is set.### `check_for_update`Check the saved stable/nightly Cua Driver channel for a release on GitHub. Returns current and selected channels, current and latest versions, an `update_available` boolean, the install one-liner, and the release notes URL. Read-only — never installs. Pacman-owned Linux executables return package-manager guidance without checking GitHub. Mirror of `cua-driver check-update --json`.-**Arguments:** none.+**Arguments:**++- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.### `install_ffmpeg`@@ -825,6 +831,7 @@ Install the ffmpeg binary used by start_recording's video capture (Linux/Windows**Arguments:**- `confirm` (boolean, optional): Run the install command. Without it, only the planned command is reported.+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.## Other tools@@ -1084,6 +1091,7 @@ Preview or install one Driver-managed optional extension. The first call without- `confirm` (boolean, optional): Install the previewed extension. Omit or false for a read-only plan.- `name` (string, required)+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.```json{"name":"perception"}@@ -1097,6 +1105,7 @@ Parse one immutable registered capture into model-neutral text and icon regions.- `capture_id` (string, required)- `options` (object, optional): Optional, model-neutral controls for one bounded parse. default: `{}`+- `session` (string, optional): For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.```json{"capture_id":"example"}diff --git a/docs/content/docs/reference/cua-driver/process-model.mdx b/docs/content/docs/reference/cua-driver/process-model.mdxindex 5c7116b111..1b6603f399 100644--- a/docs/content/docs/reference/cua-driver/process-model.mdx+++ b/docs/content/docs/reference/cua-driver/process-model.mdx@@ -137,7 +137,7 @@ five-minute idle TTL provides the same cleanup for abandoned live transports.## Lifetimes and memory-The proxy and one-shot CLI processes may come and go, but the daemon owns element-index caches, active recordings, configuration, policy, and cursor state. This makes the execution identity and permission-policy boundary stable across client reconnects.+The proxy and one-shot CLI processes may come and go, but the daemon owns accessibility snapshots, active recordings, configuration, policy, and cursor state. This makes the execution identity and permission-policy boundary stable across client reconnects.If the daemon disappears, daemon-backed clients fail closed. They do notconstruct a fresh tool registry or continue with partial state.diff --git a/libs/cua-driver/docs/action-icon-catalog.md b/libs/cua-driver/docs/action-icon-catalog.mdindex 7d381e66e0..7d280670ce 100644--- a/libs/cua-driver/docs/action-icon-catalog.md+++ b/libs/cua-driver/docs/action-icon-catalog.md@@ -51,7 +51,7 @@ need unrelated illustrations. A maintainable asset system uses:| Token | Meaning | How it is selected || ----------------- | ----------------------------------------------------- | ----------------------------------------- |-| `ax` | Accessibility-addressed element action | `element_token` or `element_index` |+| `ax` | Accessibility-addressed element action | `element_token` || `px` | Window-local pixel action | Window target plus `x`/`y` coordinates || `focused` | Acts on the target's currently focused control | No element or point supplied || `desktop` | Screen-absolute action | `scope:"desktop"` without a window target |diff --git a/libs/cua-driver/rust/Skills/cua-driver/LINUX.md b/libs/cua-driver/rust/Skills/cua-driver/LINUX.mdindex 585a2ab743..61ff015974 100644--- a/libs/cua-driver/rust/Skills/cua-driver/LINUX.md+++ b/libs/cua-driver/rust/Skills/cua-driver/LINUX.md@@ -115,7 +115,7 @@ through the core keyboard (`path: "xtest_core_grab"`, the result names thepopup and states that the core focus and active window were verifiedunchanged), or — when another application holds the core focus — are refusedwith `code: "popup_keyboard_grab"` and a hint: dismiss the popup (click-outside it, or click one of its rows by element_index after+outside it, or click one of its rows by element_token after`get_window_state(pid, window_id=<popup>)`) and retry. Typing an absolute pathinto a Qt file dialog opens its completer after the first `/`; prefer`set_value` on the "File name" field, which writes the path in one go.@@ -161,7 +161,7 @@ native `do_action` acknowledgement alone is not task completion.## AT-SPI needs the session bus (headless / containers / `runuser`)-AT-SPI — the accessibility tree behind `get_window_state`, element-indexed+AT-SPI — the accessibility tree behind `get_window_state`, `element_token`clicks, and focus-free `type_text` — lives **entirely on the desktopsession's D-Bus**. cua-driver reaches it via `DBUS_SESSION_BUS_ADDRESS`. Whenthe daemon is started _inside_ a normal desktop login that variable is already@@ -199,7 +199,7 @@ Each input rung and its stable public route:| Modality | `delivery_mode` | `route` | Postcondition proof || ------------------------------- | ------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------- |-| Element click (`element_index`) | `background` | `accessibility` | Use `verify_state`; invocation alone is not confirmation |+| Element click (`element_token`) | `background` | `accessibility` | Use `verify_state`; invocation alone is not confirmation || **element px action (x,y)** | `background` | `accessibility` when AT-SPI-at-point lands, otherwise `global_input` | Use `verify_state` or multimodal reading || Pixel (px) click, escalated | `foreground` | `global_input` | Use `verify_state` or multimodal reading || `type_text` into editable | `background` | `accessibility` | `confirmed` only with `value_readback` evidence |diff --git a/libs/cua-driver/rust/Skills/cua-driver/MACOS.md b/libs/cua-driver/rust/Skills/cua-driver/MACOS.mdindex 5a2356dbf7..96de271171 100644--- a/libs/cua-driver/rust/Skills/cua-driver/MACOS.md+++ b/libs/cua-driver/rust/Skills/cua-driver/MACOS.md@@ -135,10 +135,10 @@ When a cua-driver call surprises you, diagnose cua-driver first:race against a close, or the window has no backing store yet).Re-snapshot; if persistent, pick a different `window_id` via`list_windows`.-- **`snapshot_id_required` / `stale_element_token` / no cached AX state?**- Re-snapshot the exact window and use the new `element_token`, or pair its- `snapshot_id` with the matching `element_index`. A new snapshot of that- window invalidates older targets immediately.+- **`stale_element_token` / no cached AX state?**+ Re-snapshot the exact window and use the new `element_token`. A new+ snapshot of that window invalidates older targets immediately; the refusal+ names the current snapshots so you can tell whether you already hold one.- **Sparse Chromium AX tree?** Retry `get_window_state` once — thetree populates on second call.@@ -184,7 +184,7 @@ the surfaces that warrant it.Rule of thumb:- **element ax action** (default) — the element lookup before a click- AND the first verify after it; you address by `[N]` `element_index`+ AND the first verify after it; you address by the `[N]` row's `element_token`and read the tree diff.- **element px action** — when the tree is unreadable / `suspected_noop`/ `degraded` / disagrees with the pixels, or for pure visual@@ -231,7 +231,7 @@ editor state.tell the user to run `cua-driver permissions grant` and approve it.- If Screen Recording is `false`, continue only when the task can becompleted and verified from the AX tree. Call `get_window_state` with- `include_screenshot:false` and use element-indexed AX actions. Do not use+ `include_screenshot:false` and use `element_token` AX actions. Do not usescreenshots, pixel coordinates, or pixel-based verification.- If the task materially needs pixels, stop and ask the user to run`cua-driver permissions grant`. That command explains and deliberately@@ -255,7 +255,7 @@ window has not appeared yet, bound retries of `list_windows`.entire point of cua-driver: agents drive apps in the background whilethe user keeps typing in their real foreground app. The target'swindow is initialized (AX tree fully populated, clickable via-`element_index`, the pid appears in `list_apps`) but not drawn on+`element_token`, the pid appears in `list_apps`) but not drawn onscreen. The driver never activates or unhides apps on its own; thatwould violate the no-foreground contract the whole driver exists toprotect.@@ -297,7 +297,7 @@ breadth Windows and Linux already exposed (`type_text` / `press_key` /no raise, no focus steal. `"foreground"` briefly fronts the owning app,acts, then restores the prior frontmost — the explicit last resort for asurface that only accepts events while frontmost (the canvas/viewport/game-case below). Unmodified element-indexed (AX) actions remain background-capable+case below). Unmodified `element_token` (AX) actions remain background-capableand hold the no-foreground contract without the flag.A foreground window-scoped **pixel** `click`, `double_click`, or@@ -403,7 +403,7 @@ unverified too.) Bottom line: on these surfaces **do not trust the AXconfirm — the screenshot in the same response is the only truth.**Fix — **one call**: `type_text({pid, window_id, x, y, text})`. Passing-`x,y` (no `element_index`) is the **element px action** form of+`x,y` (no `element_token`) is the **element px action** form of`type_text` — the tool pixel-clicks at `(x,y)` to give the Chromium /UIKit renderer the real keyboard focus the AX layer can't, then typesinto the now-focused field. Read `x,y` straight off the screenshot in@@ -426,7 +426,7 @@ content. Send Cmd+V only after that read-back succeeds.2. Only if the keystrokes _still_ drop (a focus-polling app), escalatethat one `type_text` with `delivery_mode:"foreground"`.-The `x,y` (px) form is **mutually exclusive** with `element_index`+The `x,y` (px) form is **mutually exclusive** with `element_token`(ax) — pass one or the other, not both. Why not `Cmd+V` / `hotkey`: akeyboard combo does **not** focus a text field, and `hotkey` /`press_key` no longer raise the window on their own (raising is gated@@ -505,7 +505,7 @@ starting point for new browser workflows.| ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || macOS system-alert beep on `press_key` with no visible change | Target window is minimized; Return / Space / Tab commits don't establish real renderer focus on minimized windows | AX-click a clickable equivalent (Go button, Submit button, checkbox) instead of pressing the key; see "Keyboard commits on minimized windows" under the Browser section || `Accessibility permission not granted` | TCC not granted | Stop; tell user to grant in System Settings |-| `Screen Recording permission not granted` | TCC not granted for capture | Screenshots and pixel actions are unavailable. If the task is AX-completable, use `get_window_state({include_screenshot:false})` and element-indexed actions; otherwise stop and ask the user to run `cua-driver permissions grant` |+| `Screen Recording permission not granted` | TCC not granted for capture | Screenshots and pixel actions are unavailable. If the task is AX-completable, use `get_window_state({include_screenshot:false})` and `element_token` actions; otherwise stop and ask the user to run `cua-driver permissions grant` |## Example end-to-end task (macOS)diff --git a/libs/cua-driver/rust/Skills/cua-driver/RECORDING.md b/libs/cua-driver/rust/Skills/cua-driver/RECORDING.mdindex dbc36e3bcb..3bb72d2677 100644--- a/libs/cua-driver/rust/Skills/cua-driver/RECORDING.md+++ b/libs/cua-driver/rust/Skills/cua-driver/RECORDING.md@@ -93,7 +93,7 @@ Each action writes to `turn-NNNNN/` (five-digit zero-padded counter):status. The original before/after images and state remain intact.**Both addressing modes are covered:** explicit`x, y` clicks use the platform's recording-coordinate mapping, and- `element_index`-addressed clicks resolve to the element's center+ `element_token`-addressed clicks resolve to the element's centervia the live AX/UIA cache, then convert to the retained image's coordinatespace. Native Hyprland recording retains the output image, so both kinds ofmarker use output coordinates. Pixel markers also account for the targetdiff --git a/libs/cua-driver/rust/Skills/cua-driver/SKILL.md b/libs/cua-driver/rust/Skills/cua-driver/SKILL.mdindex af85057cea..47c08a3572 100644--- a/libs/cua-driver/rust/Skills/cua-driver/SKILL.md+++ b/libs/cua-driver/rust/Skills/cua-driver/SKILL.md@@ -58,7 +58,7 @@ Check the installed version and advertised schema before using unfamiliar parame1. Select the exact target on each action. A session is lifecycle metadata, not capture scope or permission authority.2. Observe before input and verify after it. `effect:"unverifiable"` and a successful exit are not task success; never replay a partial, canceled, or unknown action blindly.-3. Use returned tokens, never invented indices. A fresh snapshot replaces prior element handles; prefer `element_token` over `element_index` plus `snapshot_id`.+3. Use returned tokens, never invented indices. A fresh snapshot replaces prior element handles and lists them in `invalidated_snapshot_ids`; act with `element_token`.4. Keep background window actions non-interfering. Foreground delivery and desktop input require authorization for visible control; an unavailable route is not permission to escalate.5. Never infer pixels from a missing image, a different window, or an unaccounted-for resized preview. Capture failure and an empty accessibility tree are different failures.6. Keep one controller for a shared desktop. Distinct sessions/cursors do not isolate focus, keyboard input, application state, or snapshot caches.diff --git a/libs/cua-driver/rust/Skills/cua-driver/WINDOWS.md b/libs/cua-driver/rust/Skills/cua-driver/WINDOWS.mdindex 675ada97f8..57133eb854 100644--- a/libs/cua-driver/rust/Skills/cua-driver/WINDOWS.md+++ b/libs/cua-driver/rust/Skills/cua-driver/WINDOWS.md@@ -32,7 +32,7 @@ strict no-foreground:| `delivery_mode` | Behavior on Windows || ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `"background"` (DEFAULT) | Never fronts and **never raises/restacks** the target — macOS-aligned (mirrors CGEvent-to-pid). **Pixel clicks**: a UIA hit-test at the point first (accessibility-channel Invoke — works on UWP / WinUI3 / Win11 packaged apps, no flash); if that misses, coordinate-injected pen/touch, **but only when the target is the _visible_ window at that point**; PostMessage for plain Win32. It returns a structured `background_unavailable` error — rather than raising or fronting — when the target is **occluded** at the point, or the event kind is known-dropped (Chromium DOM mouse + key-combos, GTK buttons, VCL/LibreOffice accelerators, terminal / WPF text with no `element_index`). **No foreground swap and no z-order raise, ever.** |+| `"background"` (DEFAULT) | Never fronts and **never raises/restacks** the target — macOS-aligned (mirrors CGEvent-to-pid). **Pixel clicks**: a UIA hit-test at the point first (accessibility-channel Invoke — works on UWP / WinUI3 / Win11 packaged apps, no flash); if that misses, coordinate-injected pen/touch, **but only when the target is the _visible_ window at that point**; PostMessage for plain Win32. It returns a structured `background_unavailable` error — rather than raising or fronting — when the target is **occluded** at the point, or the event kind is known-dropped (Chromium DOM mouse + key-combos, GTK buttons, VCL/LibreOffice accelerators, terminal / WPF text with no `element_token`). **No foreground swap and no z-order raise, ever.** || `"foreground"` | SendInput with brief `SetForegroundWindow(target)` → restore. The explicit, agent-chosen rung where fronting IS allowed — required to reach occluded targets, Chromium DOM content, GTK buttons, VCL accelerators, WPF drag, terminals, and canvas / custom-drawn surfaces with no UIA peer. Implemented for **every** input tool — `type_text` (SendInput Unicode via `send_text_synthesized`) and `scroll` (SendInput wheel via `send_wheel_synthesized`) included. The activation and restoration are scoped to that action. |> **macOS is the source of truth — `background` never alters the screen.**@@ -209,7 +209,7 @@ frontmost state:drive backgrounded, use `launch_app({urls: [url]})` — Chromium-family browsers open each URL in a new **window**. Each window hasits own `window_id`, its own UIA tree, and can be inspected /- interacted with via `element_index` without activating or switching+ interacted with via `element_token` without activating or switchinganything. Tabs are a UX grouping for humans; cua-driver-rsworkflows should default to windows.@@ -366,13 +366,12 @@ When a cua-driver surprises you, diagnose cua-driver first:element at that pixel inside the target HWND, so it fell throughto `PostMessage(WM_LBUTTONDOWN)`. For UWP / WebView2 surfaces,PostMessage silently no-ops — re-snapshot via- `get_window_state(pid, window_id)` and use `element_index` so the+ `get_window_state(pid, window_id)` and use `element_token` so thedaemon can invoke the cached UIA element by identity instead of bypoint.-- **`Invalid element_index` / `No cached UIA state`?** You either- skipped `get_window_state` this turn or passed a different- `window_id` than the one the snapshot cached against. The cache is- keyed on `(pid, window_id)` — indices don't carry across windows of+- **`stale_element_token` / `No cached UIA state`?** You either+ skipped `get_window_state` this turn or used a token from an older+ snapshot. Snapshots are keyed on `(pid, window_id)` — tokens don't carry across windows ofthe same app. Re-snapshot with the same window_id you're about toclick in.- **`Invalid window handle (0x80070578)`?** The HWND you passed is@@ -406,7 +405,7 @@ When a cua-driver surprises you, diagnose cua-driver first:means UWP and you're on the PostMessage path. UWP processespointer input via `Windows.UI.Input`, NOT through HWND messagequeues — PostMessage(WM_LBUTTONDOWN) gets ignored. Use- `element_index` instead of (x,y) for UWP targets.+ `element_token` instead of (x,y) for UWP targets.Only after those are ruled out should you fall through to theactivate fallback. Always name the focus steal in your response@@ -515,13 +514,13 @@ Do not assume the window array is populated immediately on a cold launch.**Every action MUST be bracketed by `get_window_state(pid, window_id)`**:- **Before** — the pre-action snapshot resolves the `element_token`- you're about to use. A bare integer is rejected in 0.17; clients that keep- integers must send the same response's `snapshot_id`. Targets from previous turns are stale; the- server replaces the element index map on every snapshot, keyed- on `(pid, window_id)`. Indices from turn N don't resolve in turn+ you're about to use. Targets from previous turns are stale; the+ server replaces the snapshot on every read, keyed on+ `(pid, window_id)`, and lists the replaced ids in+ `invalidated_snapshot_ids`. Tokens from turn N don't resolve in turnN+1, and targets from window A don't resolve against window B of- the same app. Skip this and element-indexed actions fail with- `stale_element_token` or `snapshot_id_required`.+ the same app. Skip this and element actions fail with+ `stale_element_token`, which names the current snapshots.- **After** — the post-action snapshot verifies the action actuallylanded. Without it you can't tell a silent no-op from a realeffect. The UIA tree change (new value, new window, disappeared@@ -733,7 +732,7 @@ typed browser tools yet.a different desktop session. Re-resolve via `list_windows`.- **Calc display stuck at "0" after pixel clicks** — the (x,y) UIAhit-test missed and PostMessage fell through (PostMessage is a- silent no-op on UWP). Switch to `element_index` mode. Symptom:+ silent no-op on UWP). Switch to `element_token` mode. Symptom:the action result reports `route:"synthetic_events"` instead of`route:"accessibility"`.- **LibreOffice (VCL) `type_text` / `hotkey` reported success but@@ -746,7 +745,7 @@ typed browser tools yet.- **`hotkey` / `press_key`** (keystroke + key-combo): `delivery_mode:"background"`surfaces a `background_unavailable` error for VCL.- **`type_text`** does a **UIA read-back** and returns the shared- `ActionResult`. With an `element_index`, the ValuePattern path returns+ `ActionResult`. With an `element_token`, the ValuePattern path returns`effect:"confirmed"` with `evidence:[{"kind":"value_readback"}]` onlywhen the complete expected value is synchronously visible and differs fromthe prior value. If SetValue succeeded but the provider still exposes the@@ -760,7 +759,7 @@ typed browser tools yet.contains the requested text, the result stays `effect:"unverifiable"` becauseWM_CHAR does not expose the insertion point. Take a fresh snapshot beforeretrying. It may recommend foreground when a background insert appears- dropped. Passing an `element_index` makes the+ dropped. Passing an `element_token` makes theread-back target that exact element by handle (ValuePattern → TextPattern),independent of foreground focus. Without one, PostMessage verificationfalls back to system-wide `GetFocusedElement`, which normally resolves onlydiff --git a/libs/cua-driver/rust/Skills/cua-driver/WORKFLOW.md b/libs/cua-driver/rust/Skills/cua-driver/WORKFLOW.mdindex a1ab002277..fab56fd008 100644--- a/libs/cua-driver/rust/Skills/cua-driver/WORKFLOW.md+++ b/libs/cua-driver/rust/Skills/cua-driver/WORKFLOW.md@@ -50,7 +50,7 @@ The accessibility model may lag or disagree with rendered state: Electron text s## Act once-Use an opaque `element_token` from the latest snapshot of the intended window. If using an integer, pair `element_index` with that response's `snapshot_id`. Do not derive or edit tokens. A later snapshot can invalidate a pending action, including when another agent observes the same window.+Use an opaque `element_token` from the latest snapshot of the intended window. Do not derive or edit tokens. A later snapshot can invalidate a pending action, including when another agent observes the same window.Example CLI window action, with IDs and token replaced from the preceding response:diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/src/cursor.rs b/libs/cua-driver/rust/crates/cua-driver-contract/src/cursor.rsindex 482cfdfbc7..d50148f5e3 100644--- a/libs/cua-driver/rust/crates/cua-driver-contract/src/cursor.rs+++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/cursor.rs@@ -262,8 +262,7 @@ pub fn classify_cursor_semantics(name: &str, args: &Value) -> Option<CursorSeman} else if matches!(name, "set_window_frame" | "invoke_menu") {Some(CursorTarget::Desktop)} else if args- .get("element_index")- .or_else(|| args.get("element_token"))+ .get("element_token").is_some_and(|value| !value.is_null()){Some(CursorTarget::Ax)@@ -320,7 +319,7 @@ mod tests {assert_eq!(classify_cursor_semantics("click",- &json!({"element_index":"ax:1","delivery_mode":"background"})+ &json!({"element_token":"s00000001:1","delivery_mode":"background"})),Some(CursorSemantics {action: CursorAction::Click,diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/capture_mode.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/capture_mode.rsindex b33b7b4cb2..7f5c55b7e3 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/capture_mode.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/capture_mode.rs@@ -27,7 +27,7 @@ pub fn capture_mode_schema() -> serde_json::Value {"description": "DEPRECATED and ignored. get_window_state always returns \BOTH the element tree and a screenshot — ground on both. The modality \is chosen at action time by how you address the target: an element ax \- action (element_index/element_token) or an element px action (x,y). \+ action (element_token) or an element px action (x,y). \Any value (including the old \"som\"/\"screenshot\" aliases) is \accepted but has no effect."})diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/capture_scope.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/capture_scope.rsindex 3711b192f8..bf86eea05b 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/capture_scope.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/capture_scope.rs@@ -210,7 +210,6 @@ fn tool_scope(tool_name: &str, args: &Value) -> ToolScope {let explicit_desktop = args.get("scope").and_then(Value::as_str) == Some("desktop");let has_window_target = args.get("pid").is_some()|| args.get("window_id").is_some()- || args.get("element_index").is_some()|| args.get("element_token").is_some();if explicit_desktop && !has_window_target {ToolScope::Desktopdiff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/element_cache.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/element_cache.rsdeleted file mode 100644index 6d71353910..0000000000--- a/libs/cua-driver/rust/crates/cua-driver-core/src/element_cache.rs+++ /dev/null@@ -1,1665 +0,0 @@-use crate::element_token::{- parse_element_args, refusal, ResolvedElement, LRU_CAP_PER_PID, STALE_TOKEN_ERROR,-};-use crate::protocol::ToolResult;-use std::any::Any;-use std::collections::{HashMap, HashSet, VecDeque};-use std::sync::{Arc, Mutex, OnceLock, Weak};--pub trait SnapshotPayload: Send + Sync + 'static {- type Element;- fn len(&self) -> usize;- fn retain(&self, index: usize) -> Option<Self::Element>;-}--struct Snapshot<S> {- id: u32,- window_id: u64,- screenshot_owner: Option<String>,- screenshot_scale: Option<f64>,- payload: S,-}--struct ElementCacheState<S> {- snapshots: HashMap<i32, Vec<Snapshot<S>>>,- retired_screenshots: HashSet<(i32, u64)>,- retired_screenshot_order: VecDeque<(i32, u64)>,- retired_screenshot_overflowed: bool,-}--const RETIRED_SCREENSHOT_CAPACITY: usize = 256;--impl<S> Default for ElementCacheState<S> {- fn default() -> Self {- Self {- snapshots: HashMap::new(),- retired_screenshots: HashSet::new(),- retired_screenshot_order: VecDeque::new(),- retired_screenshot_overflowed: false,- }- }-}--impl<S> ElementCacheState<S> {- fn retire_screenshot(&mut self, key: (i32, u64)) {- if self.retired_screenshot_overflowed || self.retired_screenshots.contains(&key) {- return;- }- if self.retired_screenshots.len() == RETIRED_SCREENSHOT_CAPACITY {- self.retired_screenshot_overflowed = true;- return;- }- self.retired_screenshots.insert(key);- self.retired_screenshot_order.push_back(key);- }-- fn restore_screenshot(&mut self, key: (i32, u64)) {- if self.retired_screenshots.remove(&key) {- self.retired_screenshot_order.retain(|entry| *entry != key);- }- }-- fn missing_screenshot_is_retired(&self, pid: i32, window_id: Option<u64>) -> bool {- self.retired_screenshot_overflowed- || match window_id {- Some(window_id) => self.retired_screenshots.contains(&(pid, window_id)),- None => self- .retired_screenshots- .iter()- .any(|(retired_pid, _)| *retired_pid == pid),- }- }-- fn reset_retired_screenshots(&mut self) {- self.retired_screenshots.clear();- self.retired_screenshot_order.clear();- self.retired_screenshot_overflowed = false;- }-}--#[derive(Clone, Copy, Debug, Eq, PartialEq)]-pub enum ScreenshotContextError {- ReplacedOrUnavailable,-}--#[derive(Clone, Copy, Debug, PartialEq)]-pub struct ScreenshotContext {- pub snapshot_id: u32,- pub window_id: u64,- pub scale: f64,-}--#[derive(Clone, Copy, Debug, PartialEq)]-pub struct SnapshotBoundZoomContext {- pub screenshot: ScreenshotContext,- pub origin_x: f64,- pub origin_y: f64,- pub scale_inv: f64,-}--impl SnapshotBoundZoomContext {- pub fn zoom_to_window(&self, x: f64, y: f64) -> (f64, f64) {- (- self.origin_x + x * self.scale_inv,- self.origin_y + y * self.scale_inv,- )- }-}--pub struct SnapshotBoundZoomRegistry {- inner: Mutex<HashMap<(i32, u64, Option<String>), SnapshotBoundZoomContext>>,-}--impl SnapshotBoundZoomRegistry {- pub fn new() -> Self {- Self {- inner: Mutex::new(HashMap::new()),- }- }-- pub fn set_if_current<S: SnapshotPayload>(- &self,- cache: &ElementCacheCore<S>,- pid: i32,- session: Option<&str>,- context: SnapshotBoundZoomContext,- ) -> Result<(), ToolResult> {- cache- .with_valid_screenshot_context(pid, session, context.screenshot, || {- self.inner.lock().unwrap().insert(- (- pid,- context.screenshot.window_id,- session.map(str::to_owned),- ),- context,- );- })- .map_err(|_| zoom_context_refusal(pid, Some(context.screenshot.window_id)))- }-- pub fn resolve<S: SnapshotPayload>(- &self,- cache: &ElementCacheCore<S>,- pid: i32,- window_id: Option<u64>,- session: Option<&str>,- ) -> Result<SnapshotBoundZoomContext, ToolResult> {- let owner = session.map(str::to_owned);- let (key, context) = {- let inner = self.inner.lock().unwrap();- let mut matches = inner- .iter()- .filter(|((entry_pid, entry_window, entry_owner), _)| {- *entry_pid == pid- && window_id.is_none_or(|window_id| *entry_window == window_id)- && entry_owner == &owner- });- let Some((key, context)) = matches.next() else {- return Err(zoom_context_refusal(pid, window_id));- };- if matches.next().is_some() {- return Err(zoom_context_refusal(pid, window_id));- }- (key.clone(), *context)- };- if cache- .validate_screenshot_context(pid, session, context.screenshot)- .is_err()- {- self.inner.lock().unwrap().remove(&key);- return Err(zoom_context_refusal(pid, window_id));- }- Ok(context)- }-- pub fn retire_replaced(&self, pid: i32, window_id: u64, current_snapshot_id: u32) -> bool {- let mut inner = self.inner.lock().unwrap();- let before = inner.len();- inner.retain(|(entry_pid, entry_window, _), context| {- *entry_pid != pid- || *entry_window != window_id- || context.screenshot.snapshot_id == current_snapshot_id- });- inner.len() != before- }-- pub fn retire_session(&self, session: &str) -> usize {- let mut inner = self.inner.lock().unwrap();- let before = inner.len();- inner.retain(|(_, _, owner), _| owner.as_deref() != Some(session));- before - inner.len()- }-}--impl Default for SnapshotBoundZoomRegistry {- fn default() -> Self {- Self::new()- }-}--fn screenshot_context_refusal(pid: Option<i32>, window_id: Option<u64>) -> ToolResult {- ToolResult::error(- "The latest snapshot for this window does not contain a screenshot owned by this session. Call get_window_state with a screenshot on the same connection before using pixels.",- )- .with_structured(serde_json::json!({- "code": "screenshot_context_missing",- "pid": pid,- "window_id": window_id,- }))-}--fn zoom_context_refusal(pid: i32, window_id: Option<u64>) -> ToolResult {- ToolResult::error(- "The zoom coordinate context is missing or was replaced by a newer snapshot. Call get_window_state and zoom again on the same connection before using from_zoom coordinates.",- )- .with_structured(serde_json::json!({- "code": "zoom_context_missing",- "pid": pid,- "window_id": window_id,- }))-}--pub struct ElementCacheCore<S: SnapshotPayload> {- runtime_scope: String,- inner: Mutex<ElementCacheState<S>>,-}--impl<S: SnapshotPayload> ElementCacheCore<S> {- pub fn new() -> Self {- Self {- runtime_scope: current_runtime_scope(),- inner: Mutex::new(ElementCacheState::default()),- }- }-- pub fn publish(&self, pid: i32, window_id: u64, payload: S) -> u32 {- self.publish_for_session(pid, window_id, payload, None, None)- .expect("anonymous snapshot publication cannot be retired")- }-- /// Publish the latest runtime-owned snapshot and its screenshot coordinate frame.- ///- /// `screenshot_scale` is the native-image-width / delivered-image-width ratio.- /// A `None` scale deliberately records that the latest observation did not- /// deliver an actionable screenshot. Publications completing after their- /// owning session ended are discarded instead of resurrecting retired state.- pub fn publish_for_session(- &self,- pid: i32,- window_id: u64,- payload: S,- session: Option<&str>,- screenshot_scale: Option<f64>,- ) -> Option<u32> {- let (id, replaced, evicted) = {- let mut inner = self.inner.lock().unwrap();- if session.is_some_and(crate::session::is_session_ended) {- return None;- }- inner.restore_screenshot((pid, window_id));- let (id, replaced, evicted) = {- let lane = inner.snapshots.entry(pid).or_default();- let replaced = lane- .iter()- .position(|entry| entry.window_id == window_id)- .map(|position| lane.remove(position));- let evicted = (lane.len() == LRU_CAP_PER_PID).then(|| lane.remove(0));- let id = crate::element_token::mint_snapshot_id();- lane.push(Snapshot {- id,- window_id,- screenshot_owner: session.map(str::to_owned),- screenshot_scale,- payload,- });- (id, replaced, evicted)- };- if let Some(evicted) = &evicted {- inner.retire_screenshot((pid, evicted.window_id));- }- (id, replaced, evicted)- };- drop((replaced, evicted));- Some(id)- }-- /// Resolve the screenshot transform from the same authoritative latest- /// snapshot used for element tokens.- ///- /// No snapshot preserves the legacy native-pixel fallback. Once a snapshot- /// exists, a different owner or a newer observation without a screenshot- /// makes older image coordinates stale and must be refused.- pub fn screenshot_scale(- &self,- pid: i32,- window_id: Option<u64>,- session: Option<&str>,- ) -> Result<Option<f64>, ScreenshotContextError> {- Ok(self- .screenshot_context(pid, window_id, session)?- .map(|context| context.scale))- }-- pub fn screenshot_context(- &self,- pid: i32,- window_id: Option<u64>,- session: Option<&str>,- ) -> Result<Option<ScreenshotContext>, ScreenshotContextError> {- let inner = self.inner.lock().unwrap();- let Some(lane) = inner.snapshots.get(&pid) else {- return if inner.missing_screenshot_is_retired(pid, window_id) {- Err(ScreenshotContextError::ReplacedOrUnavailable)- } else {- Ok(None)- };- };- if let Some(window_id) = window_id {- let Some(snapshot) = lane.iter().find(|entry| entry.window_id == window_id) else {- return if inner.missing_screenshot_is_retired(pid, Some(window_id)) {- Err(ScreenshotContextError::ReplacedOrUnavailable)- } else {- Ok(None)- };- };- if snapshot.screenshot_owner.as_deref() != session {- return Err(ScreenshotContextError::ReplacedOrUnavailable);- }- let scale = snapshot- .screenshot_scale- .ok_or(ScreenshotContextError::ReplacedOrUnavailable)?;- return Ok(Some(ScreenshotContext {- snapshot_id: snapshot.id,- window_id,- scale,- }));- }- if inner.missing_screenshot_is_retired(pid, None) {- return Err(ScreenshotContextError::ReplacedOrUnavailable);- }- let mut agreed: Option<ScreenshotContext> = None;- for snapshot in lane {- if snapshot.screenshot_owner.as_deref() != session {- return Err(ScreenshotContextError::ReplacedOrUnavailable);- }- let scale = snapshot- .screenshot_scale- .ok_or(ScreenshotContextError::ReplacedOrUnavailable)?;- let context = ScreenshotContext {- snapshot_id: snapshot.id,- window_id: snapshot.window_id,- scale,- };- match agreed {- None => agreed = Some(context),- Some(previous) if (previous.scale - scale).abs() < 1e-9 => {}- Some(_) => return Err(ScreenshotContextError::ReplacedOrUnavailable),- }- }- Ok(agreed)- }-- pub fn validate_screenshot_context(- &self,- pid: i32,- session: Option<&str>,- expected: ScreenshotContext,- ) -> Result<(), ScreenshotContextError> {- match self.screenshot_context(pid, Some(expected.window_id), session)? {- Some(current)- if current.snapshot_id == expected.snapshot_id- && (current.scale - expected.scale).abs() < 1e-9 =>- {- Ok(())- }- _ => Err(ScreenshotContextError::ReplacedOrUnavailable),- }- }-- fn with_valid_screenshot_context<R>(- &self,- pid: i32,- session: Option<&str>,- expected: ScreenshotContext,- publish: impl FnOnce() -> R,- ) -> Result<R, ScreenshotContextError> {- let inner = self.inner.lock().unwrap();- let valid = inner.snapshots.get(&pid).is_some_and(|lane| {- lane.iter().any(|snapshot| {- snapshot.window_id == expected.window_id- && snapshot.id == expected.snapshot_id- && snapshot.screenshot_owner.as_deref() == session- && snapshot- .screenshot_scale- .is_some_and(|scale| (scale - expected.scale).abs() < 1e-9)- })- });- if !valid {- return Err(ScreenshotContextError::ReplacedOrUnavailable);- }- let result = publish();- drop(inner);- Ok(result)- }-- pub fn unique_screenshot_context_for_window(- &self,- window_id: u64,- session: Option<&str>,- ) -> Result<(i32, ScreenshotContext), ScreenshotContextError> {- let inner = self.inner.lock().unwrap();- let mut matches = inner.snapshots.iter().filter_map(|(pid, lane)| {- let snapshot = lane- .iter()- .find(|snapshot| snapshot.window_id == window_id)?;- (snapshot.screenshot_owner.as_deref() == session).then_some((pid, snapshot))- });- let Some((pid, snapshot)) = matches.next() else {- return Err(ScreenshotContextError::ReplacedOrUnavailable);- };- if matches.next().is_some() {- return Err(ScreenshotContextError::ReplacedOrUnavailable);- }- let scale = snapshot- .screenshot_scale- .ok_or(ScreenshotContextError::ReplacedOrUnavailable)?;- Ok((- *pid,- ScreenshotContext {- snapshot_id: snapshot.id,- window_id,- scale,- },- ))- }-- pub fn screenshot_context_or_refusal(- &self,- pid: i32,- window_id: u64,- session: Option<&str>,- ) -> Result<ScreenshotContext, ToolResult> {- match self.screenshot_context(pid, Some(window_id), session) {- Ok(Some(context)) => Ok(context),- Ok(None) | Err(ScreenshotContextError::ReplacedOrUnavailable) => {- Err(screenshot_context_refusal(Some(pid), Some(window_id)))- }- }- }-- pub fn screenshot_context_for_zoom(- &self,- pid: Option<i32>,- window_id: u64,- session: Option<&str>,- ) -> Result<(i32, ScreenshotContext), ToolResult> {- match pid {- Some(pid) => self- .screenshot_context_or_refusal(pid, window_id, session)- .map(|context| (pid, context)),- None => self- .unique_screenshot_context_for_window(window_id, session)- .map_err(|_| screenshot_context_refusal(None, Some(window_id))),- }- }-- pub fn screenshot_scale_or_refusal(- &self,- pid: i32,- window_id: Option<u64>,- session: Option<&str>,- ) -> Result<f64, ToolResult> {- match self.screenshot_scale(pid, window_id, session) {- Ok(scale) => Ok(scale.unwrap_or(1.0)),- Err(ScreenshotContextError::ReplacedOrUnavailable) => {- Err(screenshot_context_refusal(Some(pid), window_id))- }- }- }-- pub fn retire_session_screenshots(&self, session: &str) -> usize {- let retired = {- let mut inner = self.inner.lock().unwrap();- let mut retired = Vec::new();- let mut tombstones = Vec::new();- for (pid, lane) in inner.snapshots.iter_mut() {- let mut index = 0;- while index < lane.len() {- if lane[index].screenshot_owner.as_deref() == Some(session) {- tombstones.push((*pid, lane[index].window_id));- retired.push(lane.remove(index));- } else {- index += 1;- }- }- }- inner.snapshots.retain(|_, lane| !lane.is_empty());- tombstones.sort_unstable();- for tombstone in tombstones {- inner.retire_screenshot(tombstone);- }- retired- };- let count = retired.len();- drop(retired);- count- }-- /// The window a published snapshot describes, so a pid-only action that- /// names a `snapshot_id` (a popup's or a dialog's) is routed to that- /// window instead of the pid's default window.- pub fn window_for_snapshot(&self, pid: i32, snapshot_id: u32) -> Option<u64> {- let inner = self.inner.lock().unwrap();- inner- .snapshots- .get(&pid)?- .iter()- .find(|entry| entry.id == snapshot_id)- .map(|entry| entry.window_id)- }-- pub fn resolve_element_args(- &self,- pid: i32,- element_index: Option<usize>,- element_token: Option<&str>,- snapshot_id: Option<&str>,- window_id: Option<u64>,- tool_name: &str,- ) -> Result<ResolvedElement<S::Element>, ToolResult> {- let Some(reference) = parse_element_args(- element_index,- element_token,- snapshot_id,- window_id,- tool_name,- )?- else {- return Ok(ResolvedElement::None);- };- if current_runtime_scope() != self.runtime_scope {- return Err(refusal(- "generation_mismatch",- "element_token belongs to another runtime generation".into(),- ));- }- let inner = self.inner.lock().unwrap();- let entry = inner- .snapshots- .get(&pid)- .and_then(|lane| lane.iter().find(|entry| entry.id == reference.snapshot_id));- let Some(entry) = entry else {- drop(inner);- let caches = runtime_caches()- .lock()- .unwrap()- .iter()- .filter(|(scope, _)| *scope != &self.runtime_scope)- .filter_map(|(_, cache)| cache.upgrade())- .collect::<Vec<_>>();- let foreign = caches- .iter()- .any(|cache| cache.contains(pid, reference.snapshot_id));- return Err(if foreign {- refusal(- "generation_mismatch",- "element_token belongs to another runtime generation".into(),- )- } else {- refusal("stale_element_token", STALE_TOKEN_ERROR.into())- });- };- let element = entry- .payload- .retain(reference.element_index)- .ok_or_else(|| {- refusal(- "invalid_element_token",- format!(- "element_token element_index {} out of range (snapshot had {} elements)",- reference.element_index,- entry.payload.len()- ),- )- })?;- let window_id = entry.window_id;- drop(inner);- reference.validate_window(window_id, tool_name)?;- Ok(ResolvedElement::Element {- window_id: Some(window_id),- element_index: reference.element_index,- via_token: reference.via_token,- element,- })- }-- pub fn remove(&self, pid: i32, window_id: u64) {- let retired = {- let mut inner = self.inner.lock().unwrap();- let retired = inner.snapshots.get_mut(&pid).and_then(|lane| {- let position = lane.iter().position(|entry| entry.window_id == window_id)?;- Some(lane.remove(position))- });- if retired.is_some() {- inner.retire_screenshot((pid, window_id));- }- retired- };- drop(retired);- }-- pub fn clear(&self) -> usize {- let mut inner = self.inner.lock().unwrap();- let retired = std::mem::take(&mut inner.snapshots);- inner.reset_retired_screenshots();- let count = retired.len();- drop(inner);- drop(retired);- count- }-}--impl<S: SnapshotPayload> Drop for ElementCacheCore<S> {- fn drop(&mut self) {- let mut caches = runtime_caches().lock().unwrap();- if caches- .get(&self.runtime_scope)- .is_some_and(|cache| std::ptr::addr_eq(cache.as_ptr(), self as *const Self))- {- caches.remove(&self.runtime_scope);- }- if caches.is_empty() {- caches.shrink_to_fit();- }- }-}--impl<S: SnapshotPayload> Default for ElementCacheCore<S> {- fn default() -> Self {- Self::new()- }-}--trait RuntimeCache: Any + Send + Sync {- fn contains(&self, pid: i32, snapshot_id: u32) -> bool;- fn clear(&self) -> usize;-}--impl<S: SnapshotPayload> RuntimeCache for ElementCacheCore<S> {- fn contains(&self, pid: i32, snapshot_id: u32) -> bool {- self.inner- .lock()- .unwrap()- .snapshots- .get(&pid)- .is_some_and(|lane| lane.iter().any(|entry| entry.id == snapshot_id))- }-- fn clear(&self) -> usize {- self.clear()- }-}--fn runtime_caches() -> &'static Mutex<HashMap<String, Weak<dyn RuntimeCache>>> {- static CACHES: OnceLock<Mutex<HashMap<String, Weak<dyn RuntimeCache>>>> = OnceLock::new();- CACHES.get_or_init(|| Mutex::new(HashMap::new()))-}--fn current_runtime_scope() -> String {- crate::tool::current_dispatch_runtime_scope().unwrap_or_else(|| "legacy".into())-}--pub fn register_runtime_cache<S: SnapshotPayload>(cache: &Arc<ElementCacheCore<S>>) {- let erased: Arc<dyn RuntimeCache> = cache.clone();- let mut caches = runtime_caches().lock().unwrap();- caches.retain(|_, cache| cache.strong_count() > 0);- caches.insert(cache.runtime_scope.clone(), Arc::downgrade(&erased));-}--pub fn current_runtime_cache<S: SnapshotPayload>() -> Option<Arc<ElementCacheCore<S>>> {- let cache = runtime_caches()- .lock()- .unwrap()- .get(¤t_runtime_scope())?- .upgrade()?;- let erased: Arc<dyn Any + Send + Sync> = cache;- erased.downcast().ok()-}--pub fn retire_runtime_scope(runtime_scope: &str) -> usize {- let cache = runtime_caches()- .lock()- .unwrap()- .remove(runtime_scope)- .and_then(|cache| cache.upgrade());- cache.map_or(0, |cache| cache.clear())-}--#[cfg(test)]-mod tests {- use super::*;- use crate::element_token::token_for;- use crate::snapshot_test_support::Payload;- use std::sync::atomic::{AtomicUsize, Ordering};-- fn publish(cache: &ElementCacheCore<Payload>, pid: i32, window: u64, count: usize) -> u32 {- cache.publish(pid, window, Payload((0..count).collect()))- }-- fn resolve(- cache: &ElementCacheCore<Payload>,- pid: i32,- token: &str,- ) -> Result<(u64, usize), String> {- cache- .resolve_element_args(pid, None, Some(token), None, None, "click")- .map(|result| match result {- ResolvedElement::Element {- window_id: Some(window),- element_index,- element,- ..- } => {- assert_eq!(element, element_index);- (window, element_index)- }- _ => panic!("expected element"),- })- .map_err(|error| {- error.structured_content.unwrap()["refusal"]["message"]- .as_str()- .unwrap()- .to_owned()- })- }-- #[test]- fn publish_then_resolve_returns_projection() {- let cache = ElementCacheCore::new();- let id = cache.publish(42, 7, Payload(vec![10, 20, 30]));- let result = cache- .resolve_element_args(42, None, Some(&token_for(id, 2)), None, None, "click")- .unwrap();- assert!(matches!(- result,- ResolvedElement::Element {- window_id: Some(7),- element_index: 2,- element: 30,- ..- }- ));- }-- #[test]- fn resolve_with_unknown_pid_returns_stale_error() {- assert_eq!(- resolve(&ElementCacheCore::new(), 999, &token_for(0x1234, 0)),- Err(STALE_TOKEN_ERROR.into())- );- }-- #[test]- fn resolve_with_bad_format_returns_invalid_error() {- let cache = ElementCacheCore::new();- publish(&cache, 10, 1, 1);- assert!(resolve(&cache, 10, "garbage")- .unwrap_err()- .contains("invalid format"));- }-- #[test]- fn out_of_range_index_returns_actionable_error() {- let cache = ElementCacheCore::new();- let id = publish(&cache, 11, 1, 3);- assert!(resolve(&cache, 11, &token_for(id, 7))- .unwrap_err()- .contains("out of range"));- }-- #[test]- fn snapshots_for_different_windows_share_the_bounded_lru() {- let cache = ElementCacheCore::new();- let first = publish(&cache, 12, 1, 5);- let second = publish(&cache, 12, 2, 5);- assert_eq!(resolve(&cache, 12, &token_for(first, 0)), Ok((1, 0)));- assert_eq!(resolve(&cache, 12, &token_for(second, 0)), Ok((2, 0)));- }-- #[test]- fn tokens_in_different_pids_dont_collide() {- let cache = ElementCacheCore::new();- let first = publish(&cache, 100, 11, 3);- let second = publish(&cache, 200, 22, 3);- assert_eq!(resolve(&cache, 100, &token_for(first, 0)), Ok((11, 0)));- assert_eq!(resolve(&cache, 200, &token_for(second, 0)), Ok((22, 0)));- assert_eq!(- resolve(&cache, 200, &token_for(first, 0)),- Err(STALE_TOKEN_ERROR.into())- );- }-- #[test]- fn clear_then_register_starts_clean() {- let cache = ElementCacheCore::new();- let first = publish(&cache, 1, 1, 1);- assert_eq!(cache.clear(), 1);- assert_eq!(cache.clear(), 0);- assert_eq!(- resolve(&cache, 1, &token_for(first, 0)),- Err(STALE_TOKEN_ERROR.into())- );- let second = publish(&cache, 1, 1, 1);- assert_eq!(resolve(&cache, 1, &token_for(second, 0)), Ok((1, 0)));- }-- #[test]- fn bare_element_index_is_refused() {- assert!(ElementCacheCore::<Payload>::new()- .resolve_element_args(1, Some(7), None, None, Some(99), "click")- .is_err());- }-- #[test]- fn element_token_alone_resolves_to_same_action() {- let cache = ElementCacheCore::new();- let id = publish(&cache, 1, 555, 4);- let resolved = cache- .resolve_element_args(1, None, Some(&token_for(id, 2)), None, None, "click")- .unwrap();- assert!(matches!(- resolved,- ResolvedElement::Element {- window_id: Some(555),- element_index: 2,- via_token: true,- element: 2- }- ));- }-- #[test]- fn conflicting_token_and_index_are_refused() {- let cache = ElementCacheCore::new();- let id = publish(&cache, 1, 777, 5);- assert!(cache- .resolve_element_args(1, Some(99), Some(&token_for(id, 3)), None, None, "click")- .is_err());- }-- #[test]- fn snapshot_id_and_index_resolve_safely() {- let cache = ElementCacheCore::new();- let id = publish(&cache, 1, 888, 5);- let result = cache- .resolve_element_args(- 1,- Some(2),- None,- Some(&format!("s{id:08x}")),- Some(888),- "click",- )- .unwrap();- assert!(matches!(- result,- ResolvedElement::Element {- window_id: Some(888),- element_index: 2,- via_token: false,- element: 2- }- ));- }-- #[test]- fn token_only_stale_returns_error_not_silent_fallback_to_integer() {- let result = ElementCacheCore::<Payload>::new()- .resolve_element_args(- 1,- Some(0),- Some(&token_for(0xdead, 0)),- None,- Some(1),- "click",- )- .unwrap_err();- assert!(result.is_error.unwrap_or(false));- }-- #[test]- fn neither_returns_none() {- assert!(matches!(- ElementCacheCore::<Payload>::new()- .resolve_element_args(1, None, None, None, None, "click")- .unwrap(),- ResolvedElement::None- ));- }-- #[test]- fn membership_matches_payload_length() {- let cache = ElementCacheCore::new();- let id = cache.publish(9, 99, Payload(vec![1, 2, 3, 4, 5]));- for index in 0..5 {- assert!(cache- .resolve_element_args(9, None, Some(&token_for(id, index)), None, None, "click")- .is_ok());- }- assert!(cache- .resolve_element_args(9, None, Some(&token_for(id, 5)), None, None, "click")- .is_err());- }-- #[test]- fn screenshot_coordinates_never_borrow_another_sessions_latest_transform() {- let cache = ElementCacheCore::new();- cache.publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(7.35));- assert_eq!(- cache.screenshot_scale(10, Some(20), Some("client-a")),- Ok(Some(7.35))- );-- cache.publish_for_session(10, 20, Payload(vec![]), Some("client-b"), Some(1.0));- assert_eq!(- cache.screenshot_scale(10, Some(20), Some("client-b")),- Ok(Some(1.0))- );- assert_eq!(- cache.screenshot_scale(10, Some(20), Some("client-a")),- Err(ScreenshotContextError::ReplacedOrUnavailable)- );- let refusal = cache- .screenshot_scale_or_refusal(10, Some(20), Some("client-a"))- .expect_err("stale image coordinates must be refused");- assert_eq!(- refusal.structured_content.as_ref().unwrap()["code"],- "screenshot_context_missing"- );- }-- #[test]- fn screenshot_transforms_are_independent_across_windows() {- let cache = ElementCacheCore::new();- cache.publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(7.35));- cache.publish_for_session(10, 21, Payload(vec![]), Some("client-b"), Some(2.0));- assert_eq!(- cache.screenshot_scale(10, Some(20), Some("client-a")),- Ok(Some(7.35))- );- assert_eq!(- cache.screenshot_scale(10, Some(21), Some("client-b")),- Ok(Some(2.0))- );- }-- #[test]- fn same_session_latest_snapshot_replaces_or_refuses_older_image_context() {- let cache = ElementCacheCore::new();- cache.publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(7.35));- cache.publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(1.0));- assert_eq!(- cache.screenshot_scale(10, Some(20), Some("client-a")),- Ok(Some(1.0)),- "a newer native capture replaces the older resized frame"- );-- cache.publish_for_session(10, 20, Payload(vec![]), Some("client-a"), None);- assert_eq!(- cache.screenshot_scale(10, Some(20), Some("client-a")),- Err(ScreenshotContextError::ReplacedOrUnavailable),- "a newer tree-only observation retires the older image frame"- );- }-- #[test]- fn recreating_an_idle_reclaimed_implicit_session_keeps_its_old_tokens_stale() {- use crate::session::{- begin_session_dispatch, evict_idle_with_prefix, register_scoped_session_end_hook,- SessionClientKind, SessionTransport,- };- let session = format!("element-cache-idle-implicit-{}", std::process::id());- let cache = Arc::new(ElementCacheCore::<Payload>::new());- let retiring = cache.clone();- let _hook = register_scoped_session_end_hook(move |ended| {- retiring.retire_session_screenshots(ended);- });- let begin = || {- begin_session_dispatch(- &session,- None,- &session,- true,- SessionTransport::McpStdio,- SessionClientKind::Mcp,- )- };-- let guard = begin().expect("first unnamed call starts the session");- let snapshot = cache- .publish_for_session(10, 20, Payload(vec![0, 1]), Some(&session), Some(1.0))- .expect("live session publishes");- let token = token_for(snapshot, 1);- drop(guard);- assert_eq!(- evict_idle_with_prefix(std::time::Duration::ZERO, &session),- [session.clone()]- );-- let guard = begin().expect("next unnamed call recreates the session");- assert_eq!(resolve(&cache, 10, &token), Err(STALE_TOKEN_ERROR.into()));- let fresh = cache- .publish_for_session(10, 20, Payload(vec![0, 1]), Some(&session), Some(1.0))- .expect("recreated session publishes again");- assert_eq!(resolve(&cache, 10, &token_for(fresh, 1)), Ok((20, 1)));- drop(guard);- crate::session::end_session(&session);- crate::session::revive_session(&session);- }-- #[test]- fn session_retirement_removes_only_snapshots_owned_by_that_session() {- let cache = ElementCacheCore::new();- cache.publish_for_session(10, 20, Payload(vec![]), Some("ending"), Some(7.35));- cache.publish_for_session(10, 21, Payload(vec![]), Some("survivor"), Some(2.0));- assert_eq!(cache.retire_session_screenshots("ending"), 1);- assert_eq!(- cache.screenshot_scale(10, Some(20), Some("ending")),- Err(ScreenshotContextError::ReplacedOrUnavailable)- );- assert_eq!(- cache.screenshot_scale(10, Some(21), Some("survivor")),- Ok(Some(2.0))- );- }-- #[test]- fn retired_screenshot_refuses_cross_session_and_anonymous_replay_until_republished() {- let cache = ElementCacheCore::new();- cache.publish_for_session(10, 20, Payload(vec![]), Some("ending"), Some(7.35));- assert_eq!(cache.retire_session_screenshots("ending"), 1);-- for session in [Some("ending"), Some("other"), None] {- assert_eq!(- cache.screenshot_scale(10, Some(20), session),- Err(ScreenshotContextError::ReplacedOrUnavailable),- "a retired screenshot must not become native-pixel fallback"- );- }- assert_eq!(- cache.screenshot_scale(10, None, Some("other")),- Err(ScreenshotContextError::ReplacedOrUnavailable)- );-- cache.publish_for_session(10, 20, Payload(vec![]), Some("other"), Some(2.0));- assert_eq!(- cache.screenshot_scale(10, Some(20), Some("other")),- Ok(Some(2.0)),- "a fresh snapshot clears the lightweight retirement tombstone"- );- assert_eq!(- cache.screenshot_scale(10, Some(20), None),- Err(ScreenshotContextError::ReplacedOrUnavailable)- );-- cache.publish_for_session(10, 20, Payload(vec![]), None, Some(1.5));- assert_eq!(- cache.screenshot_scale(10, Some(20), None),- Ok(Some(1.5)),- "a fresh anonymous snapshot also recovers the coordinate context"- );- }-- #[test]- fn lru_eviction_retires_only_the_evicted_screenshot_key() {- let cache = ElementCacheCore::new();- for window_id in 0..LRU_CAP_PER_PID as u64 {- cache.publish_for_session(10, window_id, Payload(vec![]), Some("client-a"), Some(2.0));- }- cache.publish_for_session(- 10,- LRU_CAP_PER_PID as u64,- Payload(vec![]),- Some("client-a"),- Some(2.0),- );-- assert_eq!(- cache.screenshot_scale(10, Some(0), Some("client-a")),- Err(ScreenshotContextError::ReplacedOrUnavailable),- "evicting an observed window must not restore native-pixel fallback"- );- assert_eq!(- cache.screenshot_scale(10, Some(1), Some("client-a")),- Ok(Some(2.0))- );- assert_eq!(- cache.screenshot_scale(10, Some(9999), Some("client-a")),- Ok(None),- "a never-observed key keeps the legacy fallback"- );- }-- #[test]- fn explicit_remove_retires_only_a_snapshot_that_existed() {- let cache = ElementCacheCore::new();- cache.publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(2.0));- cache.remove(10, 20);-- assert_eq!(- cache.screenshot_scale(10, Some(20), Some("client-a")),- Err(ScreenshotContextError::ReplacedOrUnavailable),- "removing an observed window must not restore native-pixel fallback"- );- cache.remove(10, 21);- assert_eq!(- cache.screenshot_scale(10, Some(21), Some("client-a")),- Ok(None),- "removing an absent key must not retire a never-observed window"- );- }-- #[test]- fn capture_completing_after_session_end_is_not_published() {- let cache = ElementCacheCore::new();- let session = format!("snapshot-late-capture-{}", uuid::Uuid::new_v4());- assert!(crate::session::fire_session_end(&session));- assert_eq!(- cache.publish_for_session(10, 20, Payload(vec![]), Some(&session), Some(7.35)),- None- );- assert_eq!(- cache.screenshot_scale(10, Some(20), Some(&session)),- Ok(None)- );- }-- #[test]- fn no_snapshot_keeps_legacy_native_pixel_fallback() {- let cache = ElementCacheCore::<Payload>::new();- assert_eq!(- cache.screenshot_scale(10, Some(20), Some("client-a")),- Ok(None)- );- }-- #[test]- fn retired_screenshot_index_has_deterministic_fixed_capacity() {- let mut state = ElementCacheState::<Payload>::default();- let expected = (0..RETIRED_SCREENSHOT_CAPACITY)- .map(|index| (1000 + index as i32, 2000 + index as u64))- .collect::<Vec<_>>();- for key in &expected {- state.retire_screenshot(*key);- }-- assert_eq!(state.retired_screenshots.len(), RETIRED_SCREENSHOT_CAPACITY);- assert_eq!(- state- .retired_screenshot_order- .iter()- .copied()- .collect::<Vec<_>>(),- expected- );- assert!(!state.retired_screenshot_overflowed);-- let order_before_duplicate = state.retired_screenshot_order.clone();- state.retire_screenshot(expected[0]);- assert_eq!(state.retired_screenshot_order, order_before_duplicate);-- state.retire_screenshot((9999, 9999));- assert!(state.retired_screenshot_overflowed);- assert_eq!(state.retired_screenshots.len(), RETIRED_SCREENSHOT_CAPACITY);- assert_eq!(state.retired_screenshot_order, order_before_duplicate);- assert!(!state.retired_screenshots.contains(&(9999, 9999)));- }-- fn overflow_retired_screenshots(cache: &ElementCacheCore<Payload>) -> (i32, u64) {- for index in 0..=RETIRED_SCREENSHOT_CAPACITY {- cache.publish_for_session(- 1000 + index as i32,- 2000 + index as u64,- Payload(vec![]),- Some("ending"),- Some(2.0),- );- }- assert_eq!(- cache.retire_session_screenshots("ending"),- RETIRED_SCREENSHOT_CAPACITY + 1- );- (- 1000 + RETIRED_SCREENSHOT_CAPACITY as i32,- 2000 + RETIRED_SCREENSHOT_CAPACITY as u64,- )- }-- #[test]- fn retired_screenshot_overflow_refuses_unrecorded_and_unseen_replay() {- let cache = ElementCacheCore::new();- let overflow_key = overflow_retired_screenshots(&cache);-- let inner = cache.inner.lock().unwrap();- assert!(inner.retired_screenshot_overflowed);- assert_eq!(inner.retired_screenshots.len(), RETIRED_SCREENSHOT_CAPACITY);- assert_eq!(- inner.retired_screenshot_order.len(),- RETIRED_SCREENSHOT_CAPACITY- );- assert!(!inner.retired_screenshots.contains(&overflow_key));- drop(inner);-- assert_eq!(- cache.screenshot_scale(overflow_key.0, Some(overflow_key.1), None),- Err(ScreenshotContextError::ReplacedOrUnavailable)- );- assert_eq!(- cache.screenshot_scale(9999, Some(9999), None),- Err(ScreenshotContextError::ReplacedOrUnavailable)- );- }-- #[test]- fn fresh_snapshot_resolves_while_retirement_index_is_overflowed() {- let cache = ElementCacheCore::new();- let overflow_key = overflow_retired_screenshots(&cache);-- cache.publish_for_session(- overflow_key.0,- overflow_key.1,- Payload(vec![]),- Some("fresh"),- Some(3.0),- );- assert_eq!(- cache.screenshot_scale(overflow_key.0, Some(overflow_key.1), Some("fresh")),- Ok(Some(3.0))- );- assert_eq!(- cache.screenshot_scale(overflow_key.0, Some(overflow_key.1), Some("other")),- Err(ScreenshotContextError::ReplacedOrUnavailable)- );- assert_eq!(- cache.screenshot_scale(9999, Some(9999), Some("fresh")),- Err(ScreenshotContextError::ReplacedOrUnavailable)- );- }-- #[test]- fn clear_resets_retired_screenshot_overflow() {- let cache = ElementCacheCore::new();- overflow_retired_screenshots(&cache);- cache.clear();-- let inner = cache.inner.lock().unwrap();- assert!(inner.retired_screenshots.is_empty());- assert!(inner.retired_screenshot_order.is_empty());- assert!(!inner.retired_screenshot_overflowed);- drop(inner);- assert_eq!(cache.screenshot_scale(9999, Some(9999), None), Ok(None));- }-- #[test]- fn zoom_context_is_bound_to_snapshot_session_and_window() {- let cache = ElementCacheCore::new();- let zooms = SnapshotBoundZoomRegistry::new();- let snapshot = cache- .publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(7.35))- .unwrap();- let context = SnapshotBoundZoomContext {- screenshot: ScreenshotContext {- snapshot_id: snapshot,- window_id: 20,- scale: 7.35,- },- origin_x: 100.0,- origin_y: 50.0,- scale_inv: 2.0,- };- zooms- .set_if_current(&cache, 10, Some("client-a"), context)- .unwrap();-- assert_eq!(- zooms- .resolve(&cache, 10, Some(20), Some("client-a"))- .unwrap(),- context- );- assert_eq!(context.zoom_to_window(3.0, 4.0), (106.0, 58.0));- assert_eq!(- zooms- .resolve(&cache, 10, Some(20), Some("client-b"))- .unwrap_err()- .structured_content- .as_ref()- .unwrap()["code"],- "zoom_context_missing"- );- assert_eq!(- zooms- .resolve(&cache, 10, Some(21), Some("client-a"))- .unwrap_err()- .structured_content- .as_ref()- .unwrap()["code"],- "zoom_context_missing"- );- }-- #[test]- fn window_only_screenshot_lookup_requires_one_current_owned_snapshot() {- let cache = ElementCacheCore::new();- let first = cache- .publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(2.0))- .unwrap();- assert_eq!(- cache- .screenshot_context_for_zoom(None, 20, Some("client-a"))- .unwrap(),- (- 10,- ScreenshotContext {- snapshot_id: first,- window_id: 20,- scale: 2.0,- }- )- );- assert_eq!(- cache- .screenshot_context_for_zoom(Some(10), 20, Some("client-a"))- .unwrap()- .0,- 10- );- assert!(cache- .unique_screenshot_context_for_window(20, Some("client-b"))- .is_err());-- cache.publish_for_session(11, 20, Payload(vec![]), Some("client-a"), Some(1.0));- assert!(cache- .unique_screenshot_context_for_window(20, Some("client-a"))- .is_err());- }-- #[test]- fn late_zoom_completion_cannot_replace_newer_valid_context() {- let cache = ElementCacheCore::new();- let zooms = SnapshotBoundZoomRegistry::new();- let snapshot_a = cache- .publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(2.0))- .unwrap();- let slow_a = SnapshotBoundZoomContext {- screenshot: ScreenshotContext {- snapshot_id: snapshot_a,- window_id: 20,- scale: 2.0,- },- origin_x: 10.0,- origin_y: 20.0,- scale_inv: 2.0,- };-- let snapshot_b = cache- .publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(1.0))- .unwrap();- let valid_b = SnapshotBoundZoomContext {- screenshot: ScreenshotContext {- snapshot_id: snapshot_b,- window_id: 20,- scale: 1.0,- },- origin_x: 30.0,- origin_y: 40.0,- scale_inv: 1.0,- };- zooms- .set_if_current(&cache, 10, Some("client-a"), valid_b)- .unwrap();- assert!(zooms- .set_if_current(&cache, 10, Some("client-a"), slow_a)- .is_err());- assert_eq!(- zooms- .resolve(&cache, 10, Some(20), Some("client-a"))- .unwrap(),- valid_b- );- }-- #[test]- fn newer_snapshot_retires_zoom_for_click_drag_and_held_pointer_coordinates() {- let cache = ElementCacheCore::new();- let zooms = SnapshotBoundZoomRegistry::new();- let snapshot = cache- .publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(7.35))- .unwrap();- let context = SnapshotBoundZoomContext {- screenshot: ScreenshotContext {- snapshot_id: snapshot,- window_id: 20,- scale: 7.35,- },- origin_x: 100.0,- origin_y: 50.0,- scale_inv: 2.0,- };- zooms- .set_if_current(&cache, 10, Some("client-a"), context)- .unwrap();-- let click = context.zoom_to_window(1.0, 2.0);- let drag_from = context.zoom_to_window(3.0, 4.0);- let held_pointer_to = context.zoom_to_window(5.0, 6.0);- assert_eq!(- (click, drag_from, held_pointer_to),- ((102.0, 54.0), (106.0, 58.0), (110.0, 62.0))- );-- let replacement = cache- .publish_for_session(10, 20, Payload(vec![]), Some("client-b"), Some(1.0))- .unwrap();- assert!(zooms.retire_replaced(10, 20, replacement));- let refusal = zooms- .resolve(&cache, 10, Some(20), Some("client-a"))- .expect_err("all uses of the old zoom image must become stale together");- assert_eq!(- refusal.structured_content.as_ref().unwrap()["code"],- "zoom_context_missing"- );- }-- #[test]- fn zoom_context_retires_on_same_session_replacement_and_session_end() {- let cache = ElementCacheCore::new();- let zooms = SnapshotBoundZoomRegistry::new();- let snapshot = cache- .publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(7.35))- .unwrap();- zooms- .set_if_current(- &cache,- 10,- Some("client-a"),- SnapshotBoundZoomContext {- screenshot: ScreenshotContext {- snapshot_id: snapshot,- window_id: 20,- scale: 7.35,- },- origin_x: 0.0,- origin_y: 0.0,- scale_inv: 1.0,- },- )- .unwrap();-- let replacement = cache- .publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(1.0))- .unwrap();- assert!(zooms.retire_replaced(10, 20, replacement));- assert!(zooms- .resolve(&cache, 10, Some(20), Some("client-a"))- .is_err());-- let latest = cache- .screenshot_context(10, Some(20), Some("client-a"))- .unwrap()- .unwrap();- zooms- .set_if_current(- &cache,- 10,- Some("client-a"),- SnapshotBoundZoomContext {- screenshot: latest,- origin_x: 0.0,- origin_y: 0.0,- scale_inv: 1.0,- },- )- .unwrap();- assert_eq!(zooms.retire_session("client-a"), 1);- assert!(zooms- .resolve(&cache, 10, Some(20), Some("client-a"))- .is_err());- }-- struct DropCounter {- owner: Weak<ElementCacheCore<DropCounter>>,- drops: Arc<AtomicUsize>,- }- impl SnapshotPayload for DropCounter {- type Element = ();- fn len(&self) -> usize {- 1- }- fn retain(&self, index: usize) -> Option<()> {- (index == 0).then_some(())- }- }- impl Drop for DropCounter {- fn drop(&mut self) {- if let Some(owner) = self.owner.upgrade() {- assert!(- owner.inner.try_lock().is_ok(),- "native cleanup ran under the storage lock"- );- }- self.drops.fetch_add(1, Ordering::SeqCst);- }- }-- #[test]- fn screenshot_retirement_keeps_only_tombstone_not_payload() {- let cache = Arc::new(ElementCacheCore::new());- let drops = Arc::new(AtomicUsize::new(0));- cache.publish_for_session(- 10,- 20,- DropCounter {- owner: Arc::downgrade(&cache),- drops: drops.clone(),- },- Some("ending"),- Some(2.0),- );- assert_eq!(cache.retire_session_screenshots("ending"), 1);- assert_eq!(drops.load(Ordering::SeqCst), 1);- let inner = cache.inner.lock().unwrap();- assert!(inner.snapshots.is_empty());- assert_eq!(inner.retired_screenshots.len(), 1);- assert_eq!(inner.retired_screenshot_order.len(), 1);- drop(inner);- assert_eq!(- cache.screenshot_scale(10, Some(20), None),- Err(ScreenshotContextError::ReplacedOrUnavailable)- );- }-- #[test]- fn replacement_remove_and_clear_run_drop_outside_lock() {- let cache = Arc::new(ElementCacheCore::new());- let drops = Arc::new(AtomicUsize::new(0));- let payload = || DropCounter {- owner: Arc::downgrade(&cache),- drops: drops.clone(),- };- cache.publish(1, 1, payload());- assert_eq!(drops.load(Ordering::SeqCst), 0);- cache.publish(1, 1, payload());- assert_eq!(drops.load(Ordering::SeqCst), 1);- cache.remove(1, 1);- assert_eq!(drops.load(Ordering::SeqCst), 2);- cache.publish(1, 1, payload());- cache.clear();- assert_eq!(drops.load(Ordering::SeqCst), 3);- }-- #[test]- fn window_identity_preserves_high_bits_through_resolution_and_retirement() {- let cache = ElementCacheCore::new();- let low = 7;- let high = (1_u64 << 32) | low;- let first = cache.publish(42, low, Payload(vec![10]));- let second = cache.publish(42, high, Payload(vec![20]));- let token = token_for(second, 0);- let resolved = cache- .resolve_element_args(42, None, Some(&token), None, Some(high), "click")- .unwrap();- assert!(- matches!(resolved, ResolvedElement::Element { window_id: Some(window), element: 20, .. } if window == high)- );- assert!(cache- .resolve_element_args(42, None, Some(&token), None, Some(low), "click")- .is_err());- let handle = format!("s{second:08x}");- assert!(cache- .resolve_element_args(42, Some(0), None, Some(&handle), Some(high), "click")- .is_ok());- assert!(cache- .resolve_element_args(42, Some(0), None, Some(&handle), Some(low), "click")- .is_err());- cache.remove(42, high);- assert!(cache- .resolve_element_args(42, None, Some(&token), None, None, "click")- .is_err());- assert!(cache- .resolve_element_args(- 42,- None,- Some(&token_for(first, 0)),- None,- Some(low),- "click"- )- .is_ok());- }-- #[test]- fn bindings_sharing_a_scope_keep_independent_payload_ownership() {- crate::tool::with_runtime_scope("snapshot-binding-ownership".into(), || {- let first = Arc::new(ElementCacheCore::new());- let second = Arc::new(ElementCacheCore::new());- register_runtime_cache(&first);- register_runtime_cache(&second);- let first_id = first.publish(42, 7, Payload(vec![10]));- let second_id = second.publish(42, 7, Payload(vec![20]));- assert!(second- .resolve_element_args(42, None, Some(&token_for(first_id, 0)), None, None, "click")- .is_err());- drop(first);- let resolved = second- .resolve_element_args(- 42,- None,- Some(&token_for(second_id, 0)),- None,- None,- "click",- )- .unwrap();- assert!(matches!(- resolved,- ResolvedElement::Element { element: 20, .. }- ));- assert!(Arc::ptr_eq(- ¤t_runtime_cache::<Payload>().unwrap(),- &second- ));- retire_runtime_scope("snapshot-binding-ownership");- });- }-- #[test]- fn recording_discovery_does_not_extend_payload_lifetime() {- crate::tool::with_runtime_scope("snapshot-weak-discovery".into(), || {- let cache = Arc::new(ElementCacheCore::new());- let drops = Arc::new(AtomicUsize::new(0));- cache.publish(- 42,- 7,- DropCounter {- owner: Arc::downgrade(&cache),- drops: drops.clone(),- },- );- register_runtime_cache(&cache);- assert_eq!(Arc::strong_count(&cache), 1);- drop(cache);- assert_eq!(drops.load(Ordering::SeqCst), 1);- assert!(current_runtime_cache::<DropCounter>().is_none());- {- let caches = runtime_caches().lock().unwrap();- assert!(!caches.contains_key("snapshot-weak-discovery"));- if caches.is_empty() {- assert_eq!(caches.capacity(), 0);- }- }- assert_eq!(retire_runtime_scope("snapshot-weak-discovery"), 0);- });- }-}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/element_token.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/element_token.rsindex 581b7a1850..8834e0f6d5 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/element_token.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/element_token.rs@@ -11,8 +11,12 @@ pub(crate) fn mint_snapshot_id() -> u32 {SNAPSHOT_COUNTER.fetch_add(1, Ordering::Relaxed)}+pub fn format_snapshot_id(snapshot_id: u32) -> String {+ format!("s{snapshot_id:08x}")+}+pub fn token_for(snapshot_id: u32, element_index: usize) -> String {- format!("s{snapshot_id:08x}:{element_index}")+ format!("{}:{element_index}", format_snapshot_id(snapshot_id))}pub fn parse_token(token: &str) -> Option<(u32, usize)> {@@ -32,9 +36,8 @@ pub fn parse_snapshot_handle(handle: &str) -> Option<u32> {pub enum ResolvedElement<T> {None,Element {- window_id: Option<u64>,+ window_id: u64,element_index: usize,- via_token: bool,element: T,},}@@ -50,34 +53,8 @@ impl<T> ResolvedElement<T> {window_id,element_index,element,- ..- } => (Some(element_index), window_id, Some(element)),- }- }-}--pub(crate) struct ElementReference {- pub snapshot_id: u32,- pub element_index: usize,- pub via_token: bool,- window_id: Option<u64>,- conflicting: bool,-}--impl ElementReference {- pub fn validate_window(&self, window_id: u64, tool: &str) -> Result<(), ToolResult> {- if !self.conflicting && self.window_id.is_none_or(|supplied| supplied == window_id) {- return Ok(());+ } => (Some(element_index), Some(window_id), Some(element)),}- let message = if self.via_token {- format!("{tool}: element_token conflicts with element_index, snapshot_id, or window_id")- } else {- format!(- "{tool}: snapshot belongs to window_id {window_id}, not {}",- self.window_id.unwrap()- )- };- Err(refusal("conflicting_element_target", message))}}@@ -87,51 +64,6 @@ pub(crate) fn refusal(code: &str, message: String) -> ToolResult {}))}-pub(crate) fn parse_element_args(- element_index: Option<usize>,- element_token: Option<&str>,- snapshot_handle: Option<&str>,- window_id: Option<u64>,- tool: &str,-) -> Result<Option<ElementReference>, ToolResult> {- match (element_index, element_token, snapshot_handle) {- (None, None, None) => return Ok(None),- (None, None, Some(_)) => return Err(refusal(- "element_index_required", format!("{tool}: snapshot_id requires element_index"),- )),- (Some(_), None, None) => return Err(refusal(- "snapshot_id_required",- format!("{tool}: bare element_index is not accepted; pass element_token, or snapshot_id together with element_index"),- )),- _ => {}- }- let (snapshot_id, index) = if let Some(token) = element_token {- parse_token(token).ok_or_else(|| {- refusal(- "invalid_element_token",- "element_token has invalid format".into(),- )- })?- } else {- let id = parse_snapshot_handle(snapshot_handle.unwrap()).ok_or_else(|| {- refusal(- "invalid_snapshot_id",- format!("{tool}: snapshot_id has invalid format"),- )- })?;- (id, element_index.unwrap())- };- Ok(Some(ElementReference {- snapshot_id,- element_index: index,- via_token: element_token.is_some(),- window_id,- conflicting: element_index.is_some_and(|supplied| supplied != index)- || snapshot_handle- .is_some_and(|handle| parse_snapshot_handle(handle) != Some(snapshot_id)),- }))-}-#[cfg(test)]mod tests {use super::*;diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rsindex b7549c13a6..547fbc170b 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs@@ -60,7 +60,6 @@ pub mod cursor_shape;pub mod daemon;pub mod delivery;pub mod desktop_capture_scale;-pub mod element_cache;pub mod element_frame;pub mod element_query;pub mod element_token;@@ -88,6 +87,7 @@ pub mod session_authorization;pub mod session_manifest;pub mod session_tools;pub mod single_flight;+pub mod snapshot_store;#[cfg(test)]pub(crate) mod snapshot_test_support;pub mod socket_io;diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/protocol.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/protocol.rsindex ec46f81507..d7e7da82a0 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/protocol.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/protocol.rs@@ -385,7 +385,7 @@ For non-GUI outcomes, prefer a client-provided app API/SDK, headless/backgroundOn continuation/recent-work, when available, call `history_status`; if ready, make one bounded initial `history_query` before broad discovery; otherwise continue.-For app/window outcomes, use the narrowest semantic Cua route first: `set_window_frame` plus `list_windows` readback for geometry, typed browser tools for supported page content, and clipboard tools for clipboard state. Then climb through background `element_index` ({tree_kind}), background pixels, foreground delivery, and desktop fallback. Never advance on transport success alone.+For app/window outcomes, use the narrowest semantic Cua route first: `set_window_frame` plus `list_windows` readback for geometry, typed browser tools for supported page content, and clipboard tools for clipboard state. Then climb through background `element_token` ({tree_kind}), background pixels, foreground delivery, and desktop fallback. Never advance on transport success alone.Workflow per turn:0. `start_session` is optional. For multi-call work, prefer a short `session` label and repeat it on every call that accepts it. Unnamed calls use the transport's implicit session. Only `start_session` revives an ended name; `end_session` explicitly cleans up.@@ -496,7 +496,7 @@ mod agent_instruction_tests {assert!(instructions.contains("has no shell"));assert!(instructions.find("client-provided app API/SDK")- < instructions.find("background `element_index`"),+ < instructions.find("background `element_token`"),"semantic/headless operations must precede native UI dispatch");assert!(diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/recording.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/recording.rsindex 3cbb9bc697..3046006ada 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/recording.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/recording.rs@@ -1285,10 +1285,9 @@ fn semantic_action_without_point(action: &Value) -> bool {&& action["result_error"] == false&& action.get("click_point").is_none()&& action.get("click_point_image").is_none()- && (args["element_index"].as_u64().is_some()- || args["element_token"]- .as_str()- .is_some_and(|token| !token.is_empty()))+ && args["element_token"]+ .as_str()+ .is_some_and(|token| !token.is_empty())&& args.get("x").is_none()&& args.get("y").is_none()&& args.get("raw").is_none_or(|value| value == false)@@ -1650,7 +1649,7 @@ mod tests {fn semantic_click_fixture() -> Value {serde_json::json!({"tool": "click", "result_error": false,- "arguments": {"pid": 1, "window_id": 2, "element_index": 3},+ "arguments": {"pid": 1, "window_id": 2, "element_token": "s00000001:3"},"action_truth": {"effect": "unverifiable", "transport": "linux_at_spi_action","route": "accessibility", "requested_delivery": "background",@@ -1665,7 +1664,7 @@ mod tests {generation: 0,turn_dir: root.to_path_buf(),tool_name: "click".into(),- args: serde_json::json!({"pid": 901, "window_id": 902, "element_index": 3}),+ args: serde_json::json!({"pid": 901, "window_id": 902, "element_token": "s00000001:3"}),start_ms: 0,session_start_ms: 0,window_id: Some(902),@@ -1799,7 +1798,7 @@ mod tests {.begin_turn("click",&serde_json::json!({- "pid":901, "window_id":902, "element_index":3,+ "pid":901, "window_id":902, "element_token": "s00000001:3",}),0,RecordingCaller::default(),@@ -1921,11 +1920,6 @@ mod tests {original["action_truth"]["transport"] = serde_json::json!(transport);assert!(semantic_action_without_point(&original));let mut token = original.clone();- token["arguments"]- .as_object_mut()- .unwrap()- .remove("element_index");- token["arguments"]["element_token"] = serde_json::json!("e:fixture");token["action_truth"]["requested_delivery"] = serde_json::json!("foreground");token["action_truth"]["actual_delivery"] = serde_json::json!("foreground");token["action_truth"]["effect"] = serde_json::json!("confirmed");@@ -1964,7 +1958,7 @@ mod tests {"/action_truth/attempts",serde_json::json!([[{}], [{}, {}]]),),- ("/arguments/element_index", serde_json::json!([null, -1])),+ ("/arguments/element_token", serde_json::json!([null, ""])),] {for replacement in replacements.as_array().unwrap() {let mut action = original.clone();@@ -2056,7 +2050,7 @@ mod tests {generation: 0,turn_dir: root.path().to_path_buf(),tool_name: "click".into(),- args: serde_json::json!({"pid":1,"element_index":3}),+ args: serde_json::json!({"pid":1,"element_token": "s00000001:3"}),start_ms: 0,session_start_ms: 0,window_id: None,@@ -2116,7 +2110,7 @@ mod tests {let args = if pixel {serde_json::json!({"pid":1,"x":point.0,"y":point.1})} else {- serde_json::json!({"pid":1,"element_index":3})+ serde_json::json!({"pid":1,"element_token": "s00000001:3"})};write_turn(PendingTurn {@@ -2206,20 +2200,10 @@ mod tests {});setup_test_marker();set_element_bounds_fn(|pid, args, capture_point| {- use crate::tool_args::ArgsExt;- let cache = crate::element_cache::current_runtime_cache::<+ let cache = crate::snapshot_store::current_runtime_store::<crate::snapshot_test_support::Payload,>()?;- let target = cache- .resolve_element_args(- pid as i32,- args.opt_u64("element_index").map(|index| index as usize),- args.get("element_token").and_then(Value::as_str),- args.get("snapshot_id").and_then(Value::as_str),- args.opt_u64("window_id"),- "recording",- )- .ok()?;+ let target = cache.resolve(pid as i32, args).ok()?;let (index, window, _) = target.into_parts(None);let window = window?;Some((diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rsindex 5b891c7ecb..1c3d8a4a7b 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rs@@ -356,8 +356,8 @@ impl Tool for ReplayTrajectoryTool {recorded tool is called with its recorded `arguments` via the same dispatch \path an MCP / CLI call uses.\n\n\Caveats:\n\- - Element-indexed actions (`click({pid, element_index})` etc.) will fail \- because element indices are per-snapshot and don't survive across \+ - Element-token actions (`click({pid, element_token})` etc.) will fail \+ because element tokens are per-snapshot and don't survive across \sessions. Pixel clicks (`click({pid, x, y})`) and all keyboard tools \replay cleanly. Failures are reported but don't stop replay unless \`stop_on_error` is true.\n\diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/snapshot_store.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/snapshot_store.rsnew file mode 100644index 0000000000..b5ba763791--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/snapshot_store.rs@@ -0,0 +1,1036 @@+use crate::element_token::{+ format_snapshot_id, parse_token, refusal, ResolvedElement, LRU_CAP_PER_PID, STALE_TOKEN_ERROR,+};+use crate::protocol::ToolResult;+use std::any::Any;+use std::collections::HashMap;+use std::sync::{Arc, Mutex, OnceLock, Weak};++pub trait SnapshotPayload: Send + Sync + 'static {+ type Element;+ fn len(&self) -> usize;+ fn retain(&self, index: usize) -> Option<Self::Element>;+}++struct Snapshot<S> {+ id: u32,+ window_id: u64,+ screenshot_owner: Option<String>,+ screenshot_scale: Option<f64>,+ zoom: Option<ZoomContext>,+ payload: S,+}++impl<S> Snapshot<S> {+ fn screenshot(&self, session: Option<&str>) -> Option<ScreenshotContext> {+ let scale = self+ .screenshot_scale+ .filter(|_| self.screenshot_owner.as_deref() == session)?;+ Some(ScreenshotContext {+ snapshot_id: self.id,+ window_id: self.window_id,+ scale,+ })+ }+}++#[derive(Clone, Copy, Debug, PartialEq)]+pub struct ScreenshotContext {+ pub snapshot_id: u32,+ pub window_id: u64,+ pub scale: f64,+}++#[derive(Clone, Copy, Debug, PartialEq)]+pub struct ZoomContext {+ pub screenshot: ScreenshotContext,+ pub origin_x: f64,+ pub origin_y: f64,+ pub scale_inv: f64,+}++impl ZoomContext {+ pub fn zoom_to_window(&self, x: f64, y: f64) -> (f64, f64) {+ (+ self.origin_x + x * self.scale_inv,+ self.origin_y + y * self.scale_inv,+ )+ }+}++fn screenshot_context_refusal(pid: Option<i32>, window_id: Option<u64>) -> ToolResult {+ ToolResult::error(+ "No current snapshot for this window contains a screenshot owned by this session. Call get_window_state with a screenshot on the same connection before using pixels.",+ )+ .with_structured(serde_json::json!({+ "code": "screenshot_context_missing",+ "pid": pid,+ "window_id": window_id,+ }))+}++fn stale_token_refusal<S>(pid: i32, lane: &[Snapshot<S>]) -> ToolResult {+ let current: Vec<_> = lane+ .iter()+ .map(|snapshot| (format_snapshot_id(snapshot.id), snapshot.window_id))+ .collect();+ let message = match current.as_slice() {+ [] => format!("{STALE_TOKEN_ERROR}; pid {pid} has no current snapshot"),+ current => format!(+ "{STALE_TOKEN_ERROR}; current snapshots for pid {pid}: {}",+ current+ .iter()+ .map(|(snapshot_id, window_id)| format!("{snapshot_id} (window {window_id})"))+ .collect::<Vec<_>>()+ .join(", ")+ ),+ };+ ToolResult::error(message.clone()).with_structured(serde_json::json!({+ "status": "refused",+ "refusal": { "code": "stale_element_token", "message": message },+ "current_snapshots": current+ .iter()+ .map(|(snapshot_id, window_id)| {+ serde_json::json!({ "snapshot_id": snapshot_id, "window_id": window_id })+ })+ .collect::<Vec<_>>(),+ }))+}++fn zoom_context_refusal(pid: i32, window_id: Option<u64>) -> ToolResult {+ ToolResult::error(+ "The zoom coordinate context is missing or was replaced by a newer snapshot. Call get_window_state and zoom again on the same connection before using from_zoom coordinates.",+ )+ .with_structured(serde_json::json!({+ "code": "zoom_context_missing",+ "pid": pid,+ "window_id": window_id,+ }))+}++pub struct SnapshotStore<S: SnapshotPayload> {+ runtime_scope: String,+ inner: Mutex<HashMap<i32, Vec<Snapshot<S>>>>,+}++impl<S: SnapshotPayload> SnapshotStore<S> {+ pub fn new() -> Self {+ Self {+ runtime_scope: current_runtime_scope(),+ inner: Mutex::new(HashMap::new()),+ }+ }++ pub fn publish(&self, pid: i32, window_id: u64, payload: S) -> u32 {+ self.publish_for_session(pid, window_id, payload, None, None)+ .expect("anonymous snapshot publication cannot be retired")+ .0+ }++ /// Publish the latest runtime-owned snapshot and its screenshot coordinate frame,+ /// returning its id and the ids of the snapshots it replaced or evicted.+ ///+ /// `screenshot_scale` is the native-image-width / delivered-image-width ratio.+ /// A `None` scale deliberately records that the latest observation did not+ /// deliver an actionable screenshot. Publications completing after their+ /// owning session ended are discarded instead of resurrecting retired state.+ pub fn publish_for_session(+ &self,+ pid: i32,+ window_id: u64,+ payload: S,+ session: Option<&str>,+ screenshot_scale: Option<f64>,+ ) -> Option<(u32, Vec<u32>)> {+ let (id, retired) = {+ let mut inner = self.inner.lock().unwrap();+ if session.is_some_and(crate::session::is_session_ended) {+ return None;+ }+ let lane = inner.entry(pid).or_default();+ let mut retired = Vec::new();+ if let Some(position) = lane.iter().position(|entry| entry.window_id == window_id) {+ retired.push(lane.remove(position));+ }+ if lane.len() == LRU_CAP_PER_PID {+ retired.push(lane.remove(0));+ }+ let id = crate::element_token::mint_snapshot_id();+ lane.push(Snapshot {+ id,+ window_id,+ screenshot_owner: session.map(str::to_owned),+ screenshot_scale,+ zoom: None,+ payload,+ });+ (id, retired)+ };+ let invalidated = retired.iter().map(|snapshot| snapshot.id).collect();+ drop(retired);+ Some((id, invalidated))+ }++ /// Resolve the screenshot transform from the same authoritative latest+ /// snapshot used for element tokens. Without a window, every snapshot of+ /// the process must agree on one transform owned by this session.+ pub fn screenshot_context(+ &self,+ pid: i32,+ window_id: Option<u64>,+ session: Option<&str>,+ ) -> Result<ScreenshotContext, ToolResult> {+ let inner = self.inner.lock().unwrap();+ let lane = inner.get(&pid).map(Vec::as_slice).unwrap_or_default();+ let context = match window_id {+ Some(window_id) => lane+ .iter()+ .find(|snapshot| snapshot.window_id == window_id)+ .and_then(|snapshot| snapshot.screenshot(session)),+ None => {+ let mut contexts = lane.iter().map(|snapshot| snapshot.screenshot(session));+ contexts.next().flatten().filter(|first| {+ contexts.all(|context| {+ context.is_some_and(|context| (context.scale - first.scale).abs() < 1e-9)+ })+ })+ }+ };+ context.ok_or_else(|| screenshot_context_refusal(Some(pid), window_id))+ }++ pub fn screenshot_context_for_zoom(+ &self,+ pid: Option<i32>,+ window_id: u64,+ session: Option<&str>,+ ) -> Result<(i32, ScreenshotContext), ToolResult> {+ if let Some(pid) = pid {+ return self+ .screenshot_context(pid, Some(window_id), session)+ .map(|context| (pid, context));+ }+ let inner = self.inner.lock().unwrap();+ let mut matches = inner.iter().filter_map(|(pid, lane)| {+ let snapshot = lane+ .iter()+ .find(|snapshot| snapshot.window_id == window_id)?;+ Some((*pid, snapshot.screenshot(session)?))+ });+ match (matches.next(), matches.next()) {+ (Some(found), None) => Ok(found),+ _ => Err(screenshot_context_refusal(None, Some(window_id))),+ }+ }++ pub fn set_zoom(+ &self,+ pid: i32,+ session: Option<&str>,+ zoom: ZoomContext,+ ) -> Result<(), ToolResult> {+ let mut inner = self.inner.lock().unwrap();+ let snapshot = inner+ .get_mut(&pid)+ .and_then(|lane| {+ lane.iter_mut()+ .find(|snapshot| snapshot.window_id == zoom.screenshot.window_id)+ })+ .filter(|snapshot| snapshot.screenshot(session) == Some(zoom.screenshot))+ .ok_or_else(|| zoom_context_refusal(pid, Some(zoom.screenshot.window_id)))?;+ snapshot.zoom = Some(zoom);+ Ok(())+ }++ pub fn zoom(+ &self,+ pid: i32,+ window_id: Option<u64>,+ session: Option<&str>,+ ) -> Result<ZoomContext, ToolResult> {+ let inner = self.inner.lock().unwrap();+ let mut zooms = inner+ .get(&pid)+ .into_iter()+ .flatten()+ .filter(|snapshot| {+ window_id.is_none_or(|window_id| snapshot.window_id == window_id)+ && snapshot.screenshot_owner.as_deref() == session+ })+ .filter_map(|snapshot| snapshot.zoom);+ match (zooms.next(), zooms.next()) {+ (Some(zoom), None) => Ok(zoom),+ _ => Err(zoom_context_refusal(pid, window_id)),+ }+ }++ pub fn retire_session_screenshots(&self, session: &str) -> usize {+ let retired = {+ let mut inner = self.inner.lock().unwrap();+ let mut retired = Vec::new();+ for lane in inner.values_mut() {+ let (owned, kept) = std::mem::take(lane)+ .into_iter()+ .partition(|snapshot| snapshot.screenshot_owner.as_deref() == Some(session));+ *lane = kept;+ retired.extend::<Vec<_>>(owned);+ }+ inner.retain(|_, lane| !lane.is_empty());+ retired+ };+ let count = retired.len();+ drop(retired);+ count+ }++ pub fn window_for_snapshot(&self, pid: i32, snapshot_id: u32) -> Option<u64> {+ self.inner+ .lock()+ .unwrap()+ .get(&pid)?+ .iter()+ .find(|entry| entry.id == snapshot_id)+ .map(|entry| entry.window_id)+ }++ pub fn resolve(+ &self,+ pid: i32,+ args: &serde_json::Value,+ ) -> Result<ResolvedElement<S::Element>, ToolResult> {+ let Some(token) = args+ .get("element_token")+ .and_then(serde_json::Value::as_str)+ else {+ return Ok(ResolvedElement::None);+ };+ let (snapshot_id, element_index) = parse_token(token).ok_or_else(|| {+ refusal(+ "invalid_element_token",+ "element_token has invalid format".into(),+ )+ })?;+ let inner = self.inner.lock().unwrap();+ let lane = inner.get(&pid).map(Vec::as_slice).unwrap_or_default();+ let Some(snapshot) = lane.iter().find(|snapshot| snapshot.id == snapshot_id) else {+ return Err(stale_token_refusal(pid, lane));+ };+ if args["window_id"]+ .as_u64()+ .is_some_and(|window_id| window_id != snapshot.window_id)+ {+ return Err(refusal(+ "conflicting_element_target",+ "element_token conflicts with window_id".into(),+ ));+ }+ let element = snapshot.payload.retain(element_index).ok_or_else(|| {+ refusal(+ "invalid_element_token",+ format!(+ "element_token element_index {element_index} out of range (snapshot had {} elements)",+ snapshot.payload.len()+ ),+ )+ })?;+ Ok(ResolvedElement::Element {+ window_id: snapshot.window_id,+ element_index,+ element,+ })+ }++ pub fn remove(&self, pid: i32, window_id: u64) -> Option<u32> {+ let retired = {+ let mut inner = self.inner.lock().unwrap();+ inner.get_mut(&pid).and_then(|lane| {+ let position = lane.iter().position(|entry| entry.window_id == window_id)?;+ Some(lane.remove(position))+ })+ };+ retired.map(|snapshot| snapshot.id)+ }++ pub fn clear(&self) -> usize {+ let retired = std::mem::take(&mut *self.inner.lock().unwrap());+ let count = retired.len();+ drop(retired);+ count+ }+}++impl<S: SnapshotPayload> Drop for SnapshotStore<S> {+ fn drop(&mut self) {+ let mut caches = runtime_stores().lock().unwrap();+ if caches+ .get(&self.runtime_scope)+ .is_some_and(|cache| std::ptr::addr_eq(cache.as_ptr(), self as *const Self))+ {+ caches.remove(&self.runtime_scope);+ }+ if caches.is_empty() {+ caches.shrink_to_fit();+ }+ }+}++impl<S: SnapshotPayload> Default for SnapshotStore<S> {+ fn default() -> Self {+ Self::new()+ }+}++trait RuntimeStore: Any + Send + Sync {+ fn clear(&self) -> usize;+}++impl<S: SnapshotPayload> RuntimeStore for SnapshotStore<S> {+ fn clear(&self) -> usize {+ self.clear()+ }+}++fn runtime_stores() -> &'static Mutex<HashMap<String, Weak<dyn RuntimeStore>>> {+ static STORES: OnceLock<Mutex<HashMap<String, Weak<dyn RuntimeStore>>>> = OnceLock::new();+ STORES.get_or_init(|| Mutex::new(HashMap::new()))+}++fn current_runtime_scope() -> String {+ crate::tool::current_dispatch_runtime_scope().unwrap_or_else(|| "legacy".into())+}++pub fn register_runtime_store<S: SnapshotPayload>(cache: &Arc<SnapshotStore<S>>) {+ let erased: Arc<dyn RuntimeStore> = cache.clone();+ let mut caches = runtime_stores().lock().unwrap();+ caches.retain(|_, cache| cache.strong_count() > 0);+ caches.insert(cache.runtime_scope.clone(), Arc::downgrade(&erased));+}++pub fn current_runtime_store<S: SnapshotPayload>() -> Option<Arc<SnapshotStore<S>>> {+ let cache = runtime_stores()+ .lock()+ .unwrap()+ .get(¤t_runtime_scope())?+ .upgrade()?;+ let erased: Arc<dyn Any + Send + Sync> = cache;+ erased.downcast().ok()+}++pub fn retire_runtime_scope(runtime_scope: &str) -> usize {+ let cache = runtime_stores()+ .lock()+ .unwrap()+ .remove(runtime_scope)+ .and_then(|cache| cache.upgrade());+ cache.map_or(0, |cache| cache.clear())+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::element_token::token_for;+ use crate::snapshot_test_support::Payload;+ use std::sync::atomic::{AtomicUsize, Ordering};++ #[test]+ fn publish_then_resolve_returns_projection() {+ let cache = SnapshotStore::new();+ let id = cache.publish(42, 7, Payload(vec![10, 20, 30]));+ let result = cache+ .resolve(+ 42,+ &serde_json::json!({ "element_token": token_for(id, 2) }),+ )+ .unwrap();+ assert!(matches!(+ result,+ ResolvedElement::Element { element: 30, .. }+ ));+ }++ #[test]+ fn miss_returns_refusal() {+ let cache = SnapshotStore::<Payload>::new();+ assert!(cache+ .resolve(1, &serde_json::json!({ "element_token": token_for(0, 0) }))+ .is_err());+ }++ #[test]+ fn token_resolution_rejects_conflicting_windows() {+ let cache = SnapshotStore::new();+ let token = token_for(cache.publish(7, 42, Payload(vec![1])), 0);+ let mut args = serde_json::json!({ "element_token": token });+ for window_id in [None, Some(42)] {+ if let Some(window_id) = window_id {+ args["window_id"] = serde_json::json!(window_id);+ }+ assert!(matches!(+ cache.resolve(7, &args).unwrap(),+ ResolvedElement::Element { window_id: 42, .. }+ ));+ }+ args["window_id"] = serde_json::json!(99);+ let error = cache.resolve(7, &args).unwrap_err();+ assert_eq!(+ error.structured_content.unwrap()["refusal"]["code"],+ "conflicting_element_target"+ );+ }++ #[test]+ fn membership_matches_payload_length() {+ let cache = SnapshotStore::new();+ let id = cache.publish(9, 99, Payload(vec![1, 2, 3, 4, 5]));+ for index in 0..5 {+ assert!(cache+ .resolve(+ 9,+ &serde_json::json!({ "element_token": token_for(id, index) })+ )+ .is_ok());+ }+ assert!(cache+ .resolve(9, &serde_json::json!({ "element_token": token_for(id, 5) }))+ .is_err());+ }++ fn token_refusal(cache: &SnapshotStore<Payload>, pid: i32, token: &str) -> serde_json::Value {+ cache+ .resolve(pid, &serde_json::json!({ "element_token": token }))+ .unwrap_err()+ .structured_content+ .unwrap()+ }++ #[test]+ fn malformed_token_is_invalid_not_stale() {+ let cache = SnapshotStore::new();+ cache.publish(10, 1, Payload(vec![0]));+ assert_eq!(+ token_refusal(&cache, 10, "garbage")["refusal"]["code"],+ "invalid_element_token"+ );+ }++ #[test]+ fn tokens_in_different_pids_dont_collide() {+ let cache = SnapshotStore::new();+ let first = cache.publish(100, 11, Payload(vec![0]));+ cache.publish(200, 22, Payload(vec![0]));+ assert_eq!(+ token_refusal(&cache, 200, &token_for(first, 0))["refusal"]["code"],+ "stale_element_token"+ );+ }++ #[test]+ fn stale_token_names_the_current_snapshots() {+ let cache = SnapshotStore::new();+ let current = cache.publish(1, 555, Payload(vec![0]));+ let structured = token_refusal(&cache, 1, &token_for(0xdead, 0));+ assert_eq!(structured["refusal"]["code"], "stale_element_token");+ assert_eq!(+ structured["current_snapshots"],+ serde_json::json!([{ "snapshot_id": format_snapshot_id(current), "window_id": 555 }])+ );+ }++ #[test]+ fn clear_then_publish_starts_clean() {+ let cache = SnapshotStore::new();+ let first = cache.publish(1, 1, Payload(vec![0]));+ assert_eq!(cache.clear(), 1);+ assert_eq!(cache.clear(), 0);+ assert_eq!(+ token_refusal(&cache, 1, &token_for(first, 0))["refusal"]["code"],+ "stale_element_token"+ );+ let second = cache.publish(1, 1, Payload(vec![0]));+ assert!(cache+ .resolve(+ 1,+ &serde_json::json!({ "element_token": token_for(second, 0) })+ )+ .is_ok());+ }++ #[test]+ fn missing_token_resolves_to_none() {+ assert!(matches!(+ SnapshotStore::<Payload>::new()+ .resolve(1, &serde_json::json!({}))+ .unwrap(),+ ResolvedElement::None+ ));+ }++ #[test]+ fn runtime_store_discovery_is_weak_and_shared_across_calls() {+ crate::tool::with_runtime_scope("token-discovery-test".into(), || {+ let cache = Arc::new(SnapshotStore::<Payload>::new());+ register_runtime_store(&cache);+ assert!(Arc::ptr_eq(+ &cache,+ ¤t_runtime_store::<Payload>().unwrap()+ ));+ drop(cache);+ assert!(current_runtime_store::<Payload>().is_none());+ });+ }++ fn refusal_code(result: ToolResult) -> String {+ result.structured_content.unwrap()["code"]+ .as_str()+ .unwrap()+ .to_owned()+ }++ fn scale(cache: &SnapshotStore<Payload>, window_id: u64, session: &str) -> Option<f64> {+ cache+ .screenshot_context(10, Some(window_id), Some(session))+ .ok()+ .map(|context| context.scale)+ }++ fn zoom_on(snapshot: u32, scale: f64) -> ZoomContext {+ ZoomContext {+ screenshot: ScreenshotContext {+ snapshot_id: snapshot,+ window_id: 20,+ scale,+ },+ origin_x: 100.0,+ origin_y: 50.0,+ scale_inv: 2.0,+ }+ }++ #[test]+ fn screenshot_coordinates_never_borrow_another_sessions_latest_transform() {+ let cache = SnapshotStore::new();+ cache.publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(7.35));+ assert_eq!(scale(&cache, 20, "client-a"), Some(7.35));++ cache.publish_for_session(10, 20, Payload(vec![]), Some("client-b"), Some(1.0));+ assert_eq!(scale(&cache, 20, "client-b"), Some(1.0));+ let refusal = cache+ .screenshot_context(10, Some(20), Some("client-a"))+ .expect_err("stale image coordinates must be refused");+ assert_eq!(refusal_code(refusal), "screenshot_context_missing");+ }++ #[test]+ fn screenshot_transforms_are_independent_across_windows() {+ let cache = SnapshotStore::new();+ cache.publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(7.35));+ cache.publish_for_session(10, 21, Payload(vec![]), Some("client-b"), Some(2.0));+ assert_eq!(scale(&cache, 20, "client-a"), Some(7.35));+ assert_eq!(scale(&cache, 21, "client-b"), Some(2.0));+ }++ #[test]+ fn same_session_latest_snapshot_replaces_or_refuses_older_image_context() {+ let cache = SnapshotStore::new();+ cache.publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(7.35));+ cache.publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(1.0));+ assert_eq!(+ scale(&cache, 20, "client-a"),+ Some(1.0),+ "a newer native capture replaces the older resized frame"+ );++ cache.publish_for_session(10, 20, Payload(vec![]), Some("client-a"), None);+ assert_eq!(+ scale(&cache, 20, "client-a"),+ None,+ "a newer tree-only observation retires the older image frame"+ );+ }++ #[test]+ fn window_relative_pixels_require_a_current_snapshot() {+ let cache = SnapshotStore::<Payload>::new();+ assert_eq!(scale(&cache, 20, "client-a"), None);+ cache.publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(2.0));+ cache.remove(10, 20);+ assert_eq!(scale(&cache, 20, "client-a"), None);+ }++ #[test]+ fn window_less_screenshot_context_requires_one_agreed_transform() {+ let cache = SnapshotStore::new();+ assert!(cache+ .screenshot_context(10, None, Some("client-a"))+ .is_err());+ cache.publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(2.0));+ cache.publish_for_session(10, 21, Payload(vec![]), Some("client-a"), Some(2.0));+ assert_eq!(+ cache+ .screenshot_context(10, None, Some("client-a"))+ .unwrap()+ .scale,+ 2.0+ );+ cache.publish_for_session(10, 22, Payload(vec![]), Some("client-a"), Some(3.0));+ assert!(cache+ .screenshot_context(10, None, Some("client-a"))+ .is_err());+ }++ #[test]+ fn publication_reports_replaced_and_evicted_snapshots() {+ let cache = SnapshotStore::new();+ let (first, invalidated) = cache+ .publish_for_session(10, 0, Payload(vec![]), None, None)+ .unwrap();+ assert!(invalidated.is_empty());+ let (second, invalidated) = cache+ .publish_for_session(10, 0, Payload(vec![]), None, None)+ .unwrap();+ assert_eq!(invalidated, vec![first]);+ for window_id in 1..LRU_CAP_PER_PID as u64 {+ cache.publish(10, window_id, Payload(vec![]));+ }+ let (_, invalidated) = cache+ .publish_for_session(10, LRU_CAP_PER_PID as u64, Payload(vec![]), None, None)+ .unwrap();+ assert_eq!(invalidated, vec![second]);+ }++ #[test]+ fn session_retirement_removes_only_snapshots_owned_by_that_session() {+ let cache = SnapshotStore::new();+ cache.publish_for_session(10, 20, Payload(vec![]), Some("ending"), Some(7.35));+ cache.publish_for_session(10, 21, Payload(vec![]), Some("survivor"), Some(2.0));+ assert_eq!(cache.retire_session_screenshots("ending"), 1);+ assert_eq!(scale(&cache, 20, "ending"), None);+ assert_eq!(scale(&cache, 21, "survivor"), Some(2.0));+ }++ #[test]+ fn recreating_an_idle_reclaimed_implicit_session_keeps_its_old_tokens_stale() {+ use crate::session::{+ begin_session_dispatch, evict_idle_with_prefix, register_scoped_session_end_hook,+ SessionClientKind, SessionTransport,+ };+ let session = format!("snapshot-idle-implicit-{}", std::process::id());+ let cache = Arc::new(SnapshotStore::<Payload>::new());+ let retiring = cache.clone();+ let _hook = register_scoped_session_end_hook(move |ended| {+ retiring.retire_session_screenshots(ended);+ });+ let begin = || {+ begin_session_dispatch(+ &session,+ None,+ &session,+ true,+ SessionTransport::McpStdio,+ SessionClientKind::Mcp,+ )+ };+ let resolve =+ |token: &str| cache.resolve(10, &serde_json::json!({ "element_token": token }));++ let guard = begin().expect("first unnamed call starts the session");+ let (snapshot, _) = cache+ .publish_for_session(10, 20, Payload(vec![0, 1]), Some(&session), Some(1.0))+ .expect("live session publishes");+ let token = token_for(snapshot, 1);+ drop(guard);+ assert_eq!(+ evict_idle_with_prefix(std::time::Duration::ZERO, &session),+ [session.clone()]+ );++ let guard = begin().expect("next unnamed call recreates the session");+ assert!(resolve(&token).is_err());+ let (fresh, _) = cache+ .publish_for_session(10, 20, Payload(vec![0, 1]), Some(&session), Some(1.0))+ .expect("recreated session publishes again");+ assert!(matches!(+ resolve(&token_for(fresh, 1)).unwrap(),+ ResolvedElement::Element {+ window_id: 20,+ element: 1,+ ..+ }+ ));+ drop(guard);+ crate::session::end_session(&session);+ crate::session::revive_session(&session);+ }++ #[test]+ fn capture_completing_after_session_end_is_not_published() {+ let cache = SnapshotStore::new();+ let session = format!("snapshot-late-capture-{}", uuid::Uuid::new_v4());+ assert!(crate::session::fire_session_end(&session));+ assert_eq!(+ cache.publish_for_session(10, 20, Payload(vec![]), Some(&session), Some(7.35)),+ None+ );+ assert_eq!(scale(&cache, 20, &session), None);+ }++ #[test]+ fn zoom_context_is_bound_to_snapshot_session_and_window() {+ let cache = SnapshotStore::new();+ let snapshot = cache+ .publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(7.35))+ .unwrap()+ .0;+ let context = zoom_on(snapshot, 7.35);+ cache.set_zoom(10, Some("client-a"), context).unwrap();++ assert_eq!(cache.zoom(10, Some(20), Some("client-a")).unwrap(), context);+ assert_eq!(cache.zoom(10, None, Some("client-a")).unwrap(), context);+ assert_eq!(context.zoom_to_window(3.0, 4.0), (106.0, 58.0));+ for (window_id, session) in [(20, "client-b"), (21, "client-a")] {+ assert_eq!(+ refusal_code(cache.zoom(10, Some(window_id), Some(session)).unwrap_err()),+ "zoom_context_missing"+ );+ }+ }++ #[test]+ fn window_only_screenshot_lookup_requires_one_current_owned_snapshot() {+ let cache = SnapshotStore::new();+ let first = cache+ .publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(2.0))+ .unwrap()+ .0;+ assert_eq!(+ cache+ .screenshot_context_for_zoom(None, 20, Some("client-a"))+ .unwrap(),+ (+ 10,+ ScreenshotContext {+ snapshot_id: first,+ window_id: 20,+ scale: 2.0,+ }+ )+ );+ assert_eq!(+ cache+ .screenshot_context_for_zoom(Some(10), 20, Some("client-a"))+ .unwrap()+ .0,+ 10+ );+ assert!(cache+ .screenshot_context_for_zoom(None, 20, Some("client-b"))+ .is_err());++ cache.publish_for_session(11, 20, Payload(vec![]), Some("client-a"), Some(1.0));+ assert!(cache+ .screenshot_context_for_zoom(None, 20, Some("client-a"))+ .is_err());+ }++ #[test]+ fn late_zoom_completion_cannot_replace_newer_valid_context() {+ let cache = SnapshotStore::new();+ let snapshot_a = cache+ .publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(2.0))+ .unwrap()+ .0;+ let snapshot_b = cache+ .publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(1.0))+ .unwrap()+ .0;+ let valid_b = zoom_on(snapshot_b, 1.0);+ cache.set_zoom(10, Some("client-a"), valid_b).unwrap();+ assert!(cache+ .set_zoom(10, Some("client-a"), zoom_on(snapshot_a, 2.0))+ .is_err());+ assert_eq!(cache.zoom(10, Some(20), Some("client-a")).unwrap(), valid_b);+ }++ #[test]+ fn newer_snapshot_or_session_end_retires_zoom() {+ let cache = SnapshotStore::new();+ let snapshot = cache+ .publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(7.35))+ .unwrap()+ .0;+ cache+ .set_zoom(10, Some("client-a"), zoom_on(snapshot, 7.35))+ .unwrap();+ cache.publish_for_session(10, 20, Payload(vec![]), Some("client-b"), Some(1.0));+ assert_eq!(+ refusal_code(cache.zoom(10, Some(20), Some("client-a")).unwrap_err()),+ "zoom_context_missing"+ );++ let latest = cache+ .publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(1.0))+ .unwrap()+ .0;+ cache+ .set_zoom(10, Some("client-a"), zoom_on(latest, 1.0))+ .unwrap();+ assert_eq!(cache.retire_session_screenshots("client-a"), 1);+ assert!(cache.zoom(10, Some(20), Some("client-a")).is_err());+ }++ struct DropCounter {+ owner: Weak<SnapshotStore<DropCounter>>,+ drops: Arc<AtomicUsize>,+ }+ impl SnapshotPayload for DropCounter {+ type Element = ();+ fn len(&self) -> usize {+ 1+ }+ fn retain(&self, index: usize) -> Option<()> {+ (index == 0).then_some(())+ }+ }+ impl Drop for DropCounter {+ fn drop(&mut self) {+ if let Some(owner) = self.owner.upgrade() {+ assert!(+ owner.inner.try_lock().is_ok(),+ "native cleanup ran under the storage lock"+ );+ }+ self.drops.fetch_add(1, Ordering::SeqCst);+ }+ }++ #[test]+ fn session_retirement_drops_payload_outside_lock() {+ let cache = Arc::new(SnapshotStore::new());+ let drops = Arc::new(AtomicUsize::new(0));+ cache.publish_for_session(+ 10,+ 20,+ DropCounter {+ owner: Arc::downgrade(&cache),+ drops: drops.clone(),+ },+ Some("ending"),+ Some(2.0),+ );+ assert_eq!(cache.retire_session_screenshots("ending"), 1);+ assert_eq!(drops.load(Ordering::SeqCst), 1);+ assert!(cache.inner.lock().unwrap().is_empty());+ }++ #[test]+ fn replacement_remove_and_clear_run_drop_outside_lock() {+ let cache = Arc::new(SnapshotStore::new());+ let drops = Arc::new(AtomicUsize::new(0));+ let payload = || DropCounter {+ owner: Arc::downgrade(&cache),+ drops: drops.clone(),+ };+ cache.publish(1, 1, payload());+ assert_eq!(drops.load(Ordering::SeqCst), 0);+ cache.publish(1, 1, payload());+ assert_eq!(drops.load(Ordering::SeqCst), 1);+ cache.remove(1, 1);+ assert_eq!(drops.load(Ordering::SeqCst), 2);+ cache.publish(1, 1, payload());+ cache.clear();+ assert_eq!(drops.load(Ordering::SeqCst), 3);+ }++ #[test]+ fn window_identity_preserves_high_bits_through_resolution_and_retirement() {+ let cache = SnapshotStore::new();+ let low = 7;+ let high = (1_u64 << 32) | low;+ let first = cache.publish(42, low, Payload(vec![10]));+ let second = cache.publish(42, high, Payload(vec![20]));+ let token = serde_json::json!({ "element_token": token_for(second, 0) });+ assert!(matches!(+ cache.resolve(42, &token).unwrap(),+ ResolvedElement::Element { window_id, element: 20, .. } if window_id == high+ ));+ cache.remove(42, high);+ assert!(cache.resolve(42, &token).is_err());+ assert!(matches!(+ cache+ .resolve(+ 42,+ &serde_json::json!({ "element_token": token_for(first, 0) })+ )+ .unwrap(),+ ResolvedElement::Element { window_id: 7, .. }+ ));+ }++ #[test]+ fn bindings_sharing_a_scope_keep_independent_payload_ownership() {+ crate::tool::with_runtime_scope("snapshot-binding-ownership".into(), || {+ let first = Arc::new(SnapshotStore::new());+ let second = Arc::new(SnapshotStore::new());+ register_runtime_store(&first);+ register_runtime_store(&second);+ let first_id = first.publish(42, 7, Payload(vec![10]));+ let second_id = second.publish(42, 7, Payload(vec![20]));+ assert!(second+ .resolve(+ 42,+ &serde_json::json!({ "element_token": token_for(first_id, 0) })+ )+ .is_err());+ drop(first);+ let resolved = second+ .resolve(+ 42,+ &serde_json::json!({ "element_token": token_for(second_id, 0) }),+ )+ .unwrap();+ assert!(matches!(+ resolved,+ ResolvedElement::Element { element: 20, .. }+ ));+ assert!(Arc::ptr_eq(+ ¤t_runtime_store::<Payload>().unwrap(),+ &second+ ));+ retire_runtime_scope("snapshot-binding-ownership");+ });+ }++ #[test]+ fn recording_discovery_does_not_extend_payload_lifetime() {+ crate::tool::with_runtime_scope("snapshot-weak-discovery".into(), || {+ let cache = Arc::new(SnapshotStore::new());+ let drops = Arc::new(AtomicUsize::new(0));+ cache.publish(+ 42,+ 7,+ DropCounter {+ owner: Arc::downgrade(&cache),+ drops: drops.clone(),+ },+ );+ register_runtime_store(&cache);+ assert_eq!(Arc::strong_count(&cache), 1);+ drop(cache);+ assert_eq!(drops.load(Ordering::SeqCst), 1);+ assert!(current_runtime_store::<DropCounter>().is_none());+ {+ let caches = runtime_stores().lock().unwrap();+ assert!(!caches.contains_key("snapshot-weak-discovery"));+ if caches.is_empty() {+ assert_eq!(caches.capacity(), 0);+ }+ }+ assert_eq!(retire_runtime_scope("snapshot-weak-discovery"), 0);+ });+ }++ #[test]+ fn default_impl_matches_new() {+ let _cache: SnapshotStore<Payload> = SnapshotStore::default();+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/snapshot_test_support.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/snapshot_test_support.rsindex b97cdf355b..bbfeb7a063 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/snapshot_test_support.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/snapshot_test_support.rs@@ -1,4 +1,4 @@-use crate::element_cache::{register_runtime_cache, ElementCacheCore, SnapshotPayload};+use crate::snapshot_store::{register_runtime_store, SnapshotPayload, SnapshotStore};use std::sync::Arc;pub(crate) struct Payload(pub Vec<usize>);@@ -13,8 +13,8 @@ impl SnapshotPayload for Payload {}}-pub(crate) fn cache() -> Arc<ElementCacheCore<Payload>> {- let cache = Arc::new(ElementCacheCore::new());- register_runtime_cache(&cache);+pub(crate) fn cache() -> Arc<SnapshotStore<Payload>> {+ let cache = Arc::new(SnapshotStore::new());+ register_runtime_store(&cache);cache}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rsindex 56392b612c..5a6207cbd8 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs@@ -196,14 +196,34 @@ impl ToolDef {}}+/// First argument name absent from the tool's advertised closed schema.+fn unknown_argument(def: &ToolDef, args: &Value) -> Option<String> {+ let schema = advertised_runtime_input_schema(&def.name, &def.input_schema);+ if schema["additionalProperties"] != false {+ return None;+ }+ let properties = schema.get("properties").and_then(Value::as_object);+ args.as_object()?+ .keys()+ .find(|name| !properties.is_some_and(|properties| properties.contains_key(*name)))+ .cloned()+}+fn advertised_runtime_input_schema(tool_name: &str, schema: &Value) -> Value {let mut schema = schema.clone();- if !crate::action_target::supports_typed_target(tool_name) {- return schema;- }+ let closed = schema["additionalProperties"] == false;let Some(properties) = schema.get_mut("properties").and_then(Value::as_object_mut) else {return schema;};+ // Dispatch reads `session` for every tool, so every closed schema must admit it.+ if closed {+ properties+ .entry("session")+ .or_insert_with(crate::tool_schema::session_schema);+ }+ if !crate::action_target::supports_typed_target(tool_name) {+ return schema;+ }// Reuse the portable contract's exact tagged-union schema while retaining// the live runtime's broader legacy `scope=window|desktop` decoder.if let Some(portable) = cua_driver_contract::tool_contract(tool_name) {@@ -244,7 +264,7 @@ fn advertised_runtime_input_schema(tool_name: &str, schema: &Value) -> Value {/// - `accessibility.tree`, `accessibility.tree.structured`,/// `accessibility.tree.bounded`, `accessibility.window_state`,/// `accessibility.element_tokens` (Surface 6 — tool accepts the-/// opaque `element_token` arg alongside the integer `element_index`)+/// opaque `element_token` arg)/// - `app.launch`, `app.list`, `app.kill`, `window.list`,/// `window.activate`, `window.frame.set`, `window.debug_info`/// - `system.permissions.tcc`,@@ -277,8 +297,7 @@ pub fn default_capabilities_for(tool_name: &str) -> Vec<String> {// ── input.pointer ────────────────────────────────────────────//// Surface 6: tools that accept the opaque `element_token` arg- // (in addition to the integer `element_index`) claim the- // `accessibility.element_tokens` token so consumers can branch+ // claim the `accessibility.element_tokens` token so consumers can branch// on its presence — Hermes' wrapper currently does this by name// for each tool; the capability token removes that coupling."double_click" => &[@@ -907,6 +926,34 @@ impl ToolRegistry {*self.replay_registry.lock().unwrap() = Arc::downgrade(self);}+ /// Registered tools whose advertised input schema cannot admit a valid+ /// call through the dispatch argument check. Open schemas bypass that+ /// check, so each must be named in `open`.+ pub fn input_conformance_violations(&self, open: &[&str]) -> Vec<String> {+ let mut violations = Vec::new();+ for name in &self.order {+ let def = self.tools[name].def();+ let schema = advertised_runtime_input_schema(name, &def.input_schema);+ if schema["additionalProperties"] != false {+ if !open.contains(&name.as_str()) {+ violations.push(format!("{name}: input schema is not closed"));+ }+ continue;+ }+ if schema.pointer("/properties/session").is_none() {+ violations.push(format!("{name}: input schema does not accept `session`"));+ }+ let properties = &schema["properties"];+ for field in schema["required"].as_array().into_iter().flatten() {+ let field = field.as_str().unwrap_or_default();+ if properties.get(field).is_none() {+ violations.push(format!("{name}: required `{field}` is not advertised"));+ }+ }+ }+ violations+ }+pub fn tools_list(&self) -> Value {let list: Vec<Value> = self.order@@ -1127,6 +1174,7 @@ impl ToolRegistry {// Normalize deprecated public argument spellings before any policy,// consent, recording, or implementation layer interprets the call.normalize_delivery_mode_args(tool.def(), &mut args);+ let unknown_argument = unknown_argument(tool.def(), &args);if let Err(result) = crate::action_target::normalize_action_target(resolved_name, &mut args){return result;@@ -1289,6 +1337,13 @@ impl ToolRegistry {);}+ if let Some(name) = unknown_argument {+ return protected_refusal(+ "invalid_arguments",+ &format!("{resolved_name}: unknown argument {name}"),+ );+ }+// Resource adapters run at the same canonical boundary as policy and// manifest admission, after session capture-scope validation but// before recording or the platform tool can observe user state. This@@ -3252,6 +3307,11 @@ mod runtime_isolation_tests {},"additionalProperties": false})+ } else if name == "check_permissions" {+ serde_json::json!({+ "type": "object", "properties": {"prompt": {"type": "boolean"}},+ "additionalProperties": false+ })} else {serde_json::json!({"type": "object"})};@@ -4062,7 +4122,7 @@ resources:}#[tokio::test]- async fn canonical_dispatch_normalizes_legacy_delivery_mode_before_execution() {+ async fn dispatch_checks_argument_names_after_alias_normalization() {let hits = Arc::new(AtomicUsize::new(0));let last_args = Arc::new(Mutex::new(None));let mut registry = super::ToolRegistry::new();@@ -4076,7 +4136,8 @@ resources:"type": "object","properties": {"delivery_mode": crate::tool_schema::delivery_mode_schema()- }+ },+ "additionalProperties": false}),read_only: false,destructive: false,@@ -4089,7 +4150,7 @@ resources:let result = registry.invoke_with_context("click",- serde_json::json!({"dispatch": "foreground"}),+ serde_json::json!({"dispatch": "foreground", "session": "schema-test"}),standard_context(),).await;@@ -4099,6 +4160,24 @@ resources:let received = last_args.lock().unwrap().clone().expect("arguments");assert_eq!(received["delivery_mode"], "foreground");assert!(received.get("dispatch").is_none());++ let result = registry+ .invoke_with_context(+ "click",+ serde_json::json!({"unknown": null}),+ standard_context(),+ )+ .await;+ assert_eq!(result.is_error, Some(true));+ assert_eq!(+ result.structured_content.unwrap()["refusal"]["code"],+ "invalid_arguments"+ );+ assert_eq!(+ hits.load(Ordering::SeqCst),+ 1,+ "must refuse before invocation"+ );}#[tokio::test]@@ -4275,7 +4354,7 @@ resources:let denied = registry.invoke_with_context("check_permissions",- serde_json::json!({"prompt": true, "session": "permissions"}),+ serde_json::json!({"prompt": true, "session": "permissions", "unknown": null}),context,).await;@@ -4989,7 +5068,7 @@ resources:}#[tokio::test]- async fn element_tokens_are_bound_to_the_dispatch_runtime_generation() {+ async fn element_tokens_resolve_only_in_the_runtime_that_published_them() {let pid = 8_675_309;let (first_cache, token) = DISPATCH_RUNTIME_SCOPE.scope("token-dispatch-runtime-a".to_owned(), async {@@ -5007,30 +5086,23 @@ resources:let structured = DISPATCH_RUNTIME_SCOPE.scope("token-dispatch-runtime-b".to_owned(), async {second_cache- .resolve_element_args(pid, None, Some(&token), None, None, "click")+ .resolve(pid, &serde_json::json!({ "element_token": token })).unwrap_err()}).await.structured_content.unwrap();- assert_eq!(- structured["refusal"]["message"],- "element_token belongs to another runtime generation"- );- assert_eq!(- structured.pointer("/refusal/code"),- Some(&serde_json::Value::String("generation_mismatch".into()))- );+ assert_eq!(structured["refusal"]["code"], "stale_element_token");let owner = DISPATCH_RUNTIME_SCOPE.scope("token-dispatch-runtime-a".to_owned(), async {- first_cache.resolve_element_args(pid, None, Some(&token), None, None, "click")+ first_cache.resolve(pid, &serde_json::json!({ "element_token": token }))}).await;assert!(matches!(owner.unwrap(),crate::element_token::ResolvedElement::Element {- window_id: Some(44),+ window_id: 44,element_index: 0,element: 0,..@@ -5348,7 +5420,11 @@ fn synthesize_action_label(tool_name: &str, args: &Value) -> String {};let summary = match tool_name {"click" | "double_click" | "right_click" => {- if let Some(idx) = args.opt_u64("element_index") {+ if let Some((_, idx)) = args+ .opt_str("element_token")+ .as_deref()+ .and_then(crate::element_token::parse_token)+ {format!("element_index={idx}")} else if let (Some(x), Some(y)) = (args.opt_f64("x"), args.opt_f64("y")) {format!("({x:.0}, {y:.0})")diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/tool_schema.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/tool_schema.rsindex 70fb1fd91d..ea77fc3b35 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/tool_schema.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/tool_schema.rs@@ -91,34 +91,14 @@ pub fn scope_schema() -> Value {})}-/// `element_index` — the integer handle from the last get_window_state.-pub fn element_index_schema() -> Value {- json!({- "type": "integer",- "description": "Element index from get_window_state. Requires the \- matching `snapshot_id` alongside it. Prefer `element_token`, \- which carries both values."- })-}--/// `snapshot_id` — the snapshot handle paired with a numeric element index.-pub fn snapshot_id_schema() -> Value {- json!({- "type": "string",- "pattern": "^s[0-9a-f]{8}$",- "description": "Snapshot handle from get_window_state. Required when \- targeting by element_index; stale snapshots fail closed."- })-}-/// `element_token` — the opaque, validity-checked handle from get_window_state.pub fn element_token_schema() -> Value {json!({"type": "string","description": "Opaque per-snapshot element handle from \- `structuredContent.elements[].element_token`. If element_index, \- snapshot_id, or window_id are also supplied they must agree. Returns \- an explicit stale error once a newer snapshot supersedes it."+ `structuredContent.elements[].element_token`. Returns an explicit \+ stale error naming the current snapshots once a newer read \+ supersedes it."})}@@ -185,9 +165,7 @@ fn shared_param_canonical(name: &str) -> Option<Value> {"modifier" => modifier_schema(),"button" => button_schema(),"scope" => scope_schema(),- "element_index" => element_index_schema(),"element_token" => element_token_schema(),- "snapshot_id" => snapshot_id_schema(),"capture_mode" => crate::capture_mode::capture_mode_schema(),"timeout_ms" => timeout_ms_schema(),_ => return None,diff --git a/libs/cua-driver/rust/crates/cua-driver-core/tests/contract_parity.rs b/libs/cua-driver/rust/crates/cua-driver-core/tests/contract_parity.rsindex 64697390de..2ce4fcedee 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/tests/contract_parity.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/tests/contract_parity.rs@@ -34,7 +34,16 @@ fn canonical_core_contracts_match_live_registry() {.find(|entry| entry["name"] == contract.name).unwrap_or_else(|| panic!("{} missing from live registry", contract.name));assert_eq!(entry["description"], contract.description, "description");- assert_eq!(entry["inputSchema"], contract.input_schema, "inputSchema");+ // Dispatch admits `session` on every closed runtime schema.+ let mut expected_schema = contract.input_schema.clone();+ if expected_schema["additionalProperties"] == false {+ if let Some(properties) = expected_schema["properties"].as_object_mut() {+ properties+ .entry("session")+ .or_insert_with(cua_driver_core::tool_schema::session_schema);+ }+ }+ assert_eq!(entry["inputSchema"], expected_schema, "inputSchema");assert_eq!(entry["annotations"]["readOnlyHint"], contract.annotations.read_only,"readOnlyHint"diff --git a/libs/cua-driver/rust/crates/cua-driver-core/tests/recording_semantic_evidence.rs b/libs/cua-driver/rust/crates/cua-driver-core/tests/recording_semantic_evidence.rsindex 1a0d0f0ec8..a0482b7614 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/tests/recording_semantic_evidence.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/tests/recording_semantic_evidence.rs@@ -21,8 +21,7 @@ fn macos_semantic_activation_without_a_point_preserves_truth_without_a_marker()let args = json!({"pid": 32166,"window_id": 2467,- "element_index": 12,- "snapshot_id": "s00000232",+ "element_token": "s00000001:12","action": "press","delivery_mode": "foreground"});diff --git a/libs/cua-driver/rust/crates/cua-driver-core/tests/snapshot_dispatch_invariants.rs b/libs/cua-driver/rust/crates/cua-driver-core/tests/snapshot_dispatch_invariants.rsindex 5d5ae1b625..61cc2d5dc7 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/tests/snapshot_dispatch_invariants.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/tests/snapshot_dispatch_invariants.rs@@ -1,12 +1,12 @@use cua_driver_core::authorization::PermissionMode;-use cua_driver_core::element_cache::{- register_runtime_cache, retire_runtime_scope, ElementCacheCore, SnapshotPayload,-};use cua_driver_core::element_token::{token_for, ResolvedElement};use cua_driver_core::protocol::ToolResult;use cua_driver_core::session_authorization::{EffectiveAuthorizationContext, SessionAuthorizationRegistry, SessionModeCeiling,};+use cua_driver_core::snapshot_store::{+ register_runtime_store, retire_runtime_scope, SnapshotPayload, SnapshotStore,+};use cua_driver_core::tool::{with_runtime_scope, Tool, ToolDef, ToolRegistry};use serde_json::{json, Value};use std::sync::{Arc, Mutex};@@ -30,7 +30,7 @@ impl SnapshotPayload for Payload {}struct ProbeState {- cache: Arc<ElementCacheCore<Payload>>,+ cache: Arc<SnapshotStore<Payload>>,capture_started: Notify,finish_capture: Notify,observed: Mutex<Vec<u64>>,@@ -76,21 +76,12 @@ impl Tool for ProbeTool {}]}));}- let resolved = match self.state.cache.resolve_element_args(- PID,- args["element_index"].as_u64().map(|index| index as usize),- args["element_token"].as_str(),- args["snapshot_id"].as_str(),- Some(WINDOW),- "click",- ) {+ let resolved = match self.state.cache.resolve(PID, &args) {Ok(resolved) => resolved,Err(refusal) => return refusal,};let ResolvedElement::Element {- window_id: Some(_),- element: revision,- ..+ element: revision, ..} = resolvedelse {return ToolResult::error("test requires a snapshot-bound target");@@ -123,8 +114,8 @@ impl Fixture {fn new() -> Self {let context = context();let cache = with_runtime_scope(context.runtime_scope_key(), || {- let cache = Arc::new(ElementCacheCore::new());- register_runtime_cache(&cache);+ let cache = Arc::new(SnapshotStore::new());+ register_runtime_store(&cache);cache});let state = Arc::new(ProbeState {@@ -241,7 +232,7 @@ async fn dispatch_stale_refusal_and_fresh_recovery_reach_the_expected_lookup() {}#[tokio::test]-async fn dispatch_generation_refusal_precedes_native_payload_lookup() {+async fn foreign_runtime_token_is_stale_before_native_payload_lookup() {let first = Fixture::new();let second = Fixture::new();let first_token = token(&first.read(1).await);@@ -249,7 +240,7 @@ async fn dispatch_generation_refusal_precedes_native_payload_lookup() {let refused = second.click(&first_token).await;assert_eq!(refused.structured_content.as_ref().unwrap()["refusal"]["code"],- "generation_mismatch"+ "stale_element_token");assert!(second.state.observed.lock().unwrap().is_empty());first.click(&first_token).await;diff --git a/libs/cua-driver/rust/crates/cua-driver-core/tests/snapshot_invariants.rs b/libs/cua-driver/rust/crates/cua-driver-core/tests/snapshot_invariants.rsindex 83f9d01229..d6899d6393 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/tests/snapshot_invariants.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/tests/snapshot_invariants.rs@@ -1,8 +1,6 @@-use cua_driver_core::element_cache::{- register_runtime_cache, retire_runtime_scope, ElementCacheCore, SnapshotPayload,-};-use cua_driver_core::element_token::{- token_for, ResolvedElement, LRU_CAP_PER_PID, STALE_TOKEN_ERROR,+use cua_driver_core::element_token::{token_for, ResolvedElement, LRU_CAP_PER_PID};+use cua_driver_core::snapshot_store::{+ register_runtime_store, retire_runtime_scope, SnapshotPayload, SnapshotStore,};use cua_driver_core::tool::with_runtime_scope;use std::sync::atomic::{AtomicUsize, Ordering};@@ -39,22 +37,18 @@ fn payload<T: Clone + Send + Sync + 'static>(elements: Vec<T>) -> Payload<T> {}fn resolve<T: Clone + Send + Sync + 'static>(- cache: &ElementCacheCore<Payload<T>>,+ cache: &SnapshotStore<Payload<T>>,snapshot: u32,index: usize,) -> Result<(u64, usize, T), String> {cache- .resolve_element_args(+ .resolve(42,- None,- Some(&token_for(snapshot, index)),- None,- None,- "click",+ &serde_json::json!({ "element_token": token_for(snapshot, index) }),).map(|result| match result {ResolvedElement::Element {- window_id: Some(window),+ window_id: window,element_index,element,..@@ -62,7 +56,7 @@ fn resolve<T: Clone + Send + Sync + 'static>(_ => panic!("expected element"),}).map_err(|error| {- error.structured_content.unwrap()["refusal"]["message"]+ error.structured_content.unwrap()["refusal"]["code"].as_str().unwrap().to_owned()@@ -71,7 +65,7 @@ fn resolve<T: Clone + Send + Sync + 'static>(#[test]fn empty_snapshot_has_no_resolvable_members() {- let cache = ElementCacheCore::new();+ let cache = SnapshotStore::new();let snapshot = cache.publish(42, 7, payload(Vec::<usize>::new()));assert!(resolve(&cache, snapshot, 0).is_err(),@@ -81,14 +75,14 @@ fn empty_snapshot_has_no_resolvable_members() {#[test]fn replacement_invalidates_every_old_member_and_admits_new_members() {- let cache = ElementCacheCore::new();+ let cache = SnapshotStore::new();let first = cache.publish(42, 7, payload(vec![0, 1]));let second = cache.publish(42, 7, payload(vec![10, 11]));assert_ne!(first, second);for index in 0..2 {assert_eq!(resolve(&cache, first, index),- Err(STALE_TOKEN_ERROR.to_owned())+ Err("stale_element_token".to_owned()));assert_eq!(resolve(&cache, second, index), Ok((7, index, index + 10)));}@@ -96,7 +90,7 @@ fn replacement_invalidates_every_old_member_and_admits_new_members() {#[test]fn resolving_does_not_change_publication_order_eviction() {- let cache = ElementCacheCore::new();+ let cache = SnapshotStore::new();let mut ids: Vec<_> = (1..=LRU_CAP_PER_PID as u64).map(|window| cache.publish(42, window, payload(vec![1]))).collect();@@ -104,7 +98,10 @@ fn resolving_does_not_change_publication_order_eviction() {assert_eq!(resolve(&cache, first, 0), Ok((1, 0, 1)));let latest = cache.publish(42, LRU_CAP_PER_PID as u64 + 1, payload(vec![1]));ids.push(latest);- assert_eq!(resolve(&cache, first, 0), Err(STALE_TOKEN_ERROR.to_owned()));+ assert_eq!(+ resolve(&cache, first, 0),+ Err("stale_element_token".to_owned())+ );assert!(resolve(&cache, latest, 0).is_ok());assert_eq!(ids.iter()@@ -118,22 +115,18 @@ fn resolving_does_not_change_publication_order_eviction() {fn clearing_one_runtime_preserves_other_runtime_same_window() {let make = |scope: &str| {with_runtime_scope(scope.into(), || {- let cache = Arc::new(ElementCacheCore::new());- register_runtime_cache(&cache);+ let cache = Arc::new(SnapshotStore::new());+ register_runtime_store(&cache);let id = cache.publish(42, 7, payload(vec![1]));(cache, id)})};let (first_cache, first) = make("invariant-a");let (second_cache, second) = make("invariant-b");- with_runtime_scope("invariant-b".into(), || {- assert!(resolve(&second_cache, first, 0)- .unwrap_err()- .contains("another runtime generation"));- assert!(resolve(&first_cache, first, 0)- .unwrap_err()- .contains("another runtime generation"));- });+ assert_eq!(+ resolve(&second_cache, first, 0),+ Err("stale_element_token".to_owned())+ );assert_eq!(retire_runtime_scope("invariant-a"), 1);assert_eq!(retire_runtime_scope("invariant-a"), 0);with_runtime_scope("invariant-a".into(), || {@@ -147,7 +140,7 @@ fn clearing_one_runtime_preserves_other_runtime_same_window() {#[test]fn token_resolution_cannot_be_retargeted_by_cache_replacement() {- let cache = ElementCacheCore::new();+ let cache = SnapshotStore::new();let snapshot = cache.publish(42, 7, payload(vec!["original-target"]));let (resolved_tx, resolved_rx) = mpsc::channel();let (replaced_tx, replaced_rx) = mpsc::channel();@@ -174,8 +167,8 @@ fn token_resolution_cannot_be_retargeted_by_cache_replacement() {fn runtime_retirement_releases_unadmitted_cache_payload() {let drops = Arc::new(AtomicUsize::new(0));let cache = with_runtime_scope("retirement-invariant".into(), || {- let cache = Arc::new(ElementCacheCore::new());- register_runtime_cache(&cache);+ let cache = Arc::new(SnapshotStore::new());+ register_runtime_store(&cache);cache.publish(42,7,@@ -198,7 +191,7 @@ fn runtime_retirement_releases_unadmitted_cache_payload() {#[test]fn eviction_releases_unadmitted_cache_payload() {- let cache = ElementCacheCore::new();+ let cache = SnapshotStore::new();let drops = Arc::new(AtomicUsize::new(0));for window in 0..=LRU_CAP_PER_PID as u64 {cache.publish(diff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/agent_cursor_windows_test.rs b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/agent_cursor_windows_test.rsindex b727b6df52..9264a73429 100644--- a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/agent_cursor_windows_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/agent_cursor_windows_test.rs@@ -49,7 +49,6 @@ fn agent_cursor_overlay_obeys_untargeted_and_targeted_z_order() {bring_to_front(&mut driver, target);driver.start_behavior_recording();let (x, y) = window_center(target.native_id);- let cursor_id = "windows-agent-cursor-e2e";let foreground_before = unsafe { GetForegroundWindow() };assert_eq!(foreground_before.0 as u64, target.native_id);let real_cursor_before = real_cursor_position();@@ -65,12 +64,11 @@ fn agent_cursor_overlay_obeys_untargeted_and_targeted_z_order() {for (tool, arguments) in [("set_agent_cursor_enabled",- serde_json::json!({"enabled": true, "cursor_id": cursor_id}),+ serde_json::json!({"enabled": true}),),("set_agent_cursor_motion",serde_json::json!({- "cursor_id": cursor_id,"glide_duration_ms": 100,"idle_hide_ms": 0}),@@ -79,8 +77,7 @@ fn agent_cursor_overlay_obeys_untargeted_and_targeted_z_order() {"move_cursor",serde_json::json!({"x": x,- "y": y,- "cursor_id": cursor_id+ "y": y}),),] {@@ -223,10 +220,8 @@ fn agent_cursor_overlay_obeys_untargeted_and_targeted_z_order() {serde_json::json!({"pid": target.pid,"window_id": target.native_id,- "element_index": button_index,- "snapshot_id": target_state.snapshot_id(),- "delivery_mode": "background",- "cursor_id": cursor_id+ "element_token": target_state.element_token(button_index),+ "delivery_mode": "background"}),);assert!(@@ -263,7 +258,7 @@ fn agent_cursor_overlay_obeys_untargeted_and_targeted_z_order() {let disabled = driver.call("set_agent_cursor_enabled",- serde_json::json!({"enabled": false, "cursor_id": cursor_id}),+ serde_json::json!({"enabled": false}),);assert!(!disabled.is_error(),@@ -314,18 +309,16 @@ fn agent_cursor_move_does_not_leak_input() {);let x = screen.structured()["width"].as_f64().unwrap_or(0.0) / 2.0;let y = screen.structured()["height"].as_f64().unwrap_or(0.0) / 2.0;- let cursor_id = "windows-agent-cursor-no-input-leak";let (_, passed) = sentinel.observe_desktop(|| {for (tool, arguments) in [("set_agent_cursor_enabled",- serde_json::json!({"enabled": true, "cursor_id": cursor_id}),+ serde_json::json!({"enabled": true}),),("set_agent_cursor_motion",serde_json::json!({- "cursor_id": cursor_id,"glide_duration_ms": 100,"idle_hide_ms": 0}),@@ -334,8 +327,7 @@ fn agent_cursor_move_does_not_leak_input() {"move_cursor",serde_json::json!({"x": x,- "y": y,- "cursor_id": cursor_id+ "y": y}),),] {diff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/computer_history_cross_platform_test.rs b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/computer_history_cross_platform_test.rsindex 3ed8250e12..f383eb5aec 100644--- a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/computer_history_cross_platform_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/computer_history_cross_platform_test.rs@@ -565,8 +565,7 @@ fn encrypted_history_survives_restart_and_cryptographically_purges() {json!({"pid": pid,"window_id": window_id,- "element_index": element_index,- "snapshot_id": snapshot.snapshot_id(),+ "element_token": snapshot.element_token(element_index),"delivery_mode": "foreground","session": RAW_SESSION}),diff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/cross_platform_behavior_test.rs b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/cross_platform_behavior_test.rsindex 14873b3b6c..ccadcd58a0 100644--- a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/cross_platform_behavior_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/cross_platform_behavior_test.rs@@ -764,10 +764,9 @@ fn action_target_args(});let object = args.as_object_mut().expect("action arguments object");if addressing == "ax" {- object.insert("element_index".to_owned(), serde_json::json!(index));object.insert(- "snapshot_id".to_owned(),- serde_json::json!(state.snapshot_id()),+ "element_token".to_owned(),+ serde_json::json!(state.element_token(index)),);} else {let origin = window_origin(fixture, state);diff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_appkit_test.rs b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_appkit_test.rsindex 12e704fe4a..4fa4e14ab6 100644--- a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_appkit_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_appkit_test.rs@@ -835,8 +835,7 @@ fn harness_appkit_stale_element_token_fails_closed() {serde_json::json!({"pid": pid as i64,"window_id": wid,- "snapshot_id": first.snapshot_id(),- "element_index": index+ "element_token": first.element_token(index)}),);assert!(@@ -975,8 +974,7 @@ fn harness_appkit_text_input() {serde_json::json!({"pid": pid as i64,"window_id": wid,- "element_index": idx,- "snapshot_id": snap_pre.snapshot_id(),+ "element_token": snap_pre.element_token(idx),"value": "hello-cua"}),);@@ -1360,8 +1358,7 @@ fn harness_appkit_type_text_background() {let resp = driver.call("type_text",serde_json::json!({- "pid": pid as i64, "window_id": wid, "element_index": idx,- "snapshot_id": snap_pre.snapshot_id(),+ "pid": pid as i64, "window_id": wid, "element_token": snap_pre.element_token(idx),"text": "kbd-cua", "delivery_mode": "background"}),);@@ -1402,8 +1399,7 @@ fn harness_appkit_scroll_foreground() {serde_json::json!({"pid": pid as i64,"window_id": wid,- "element_index": index,- "snapshot_id": pre.snapshot_id(),+ "element_token": pre.element_token(index),"direction": "down","amount": 5,"delivery_mode": "foreground"@@ -1442,8 +1438,7 @@ fn harness_appkit_scroll_background() {serde_json::json!({"pid": pid as i64,"window_id": wid,- "element_index": index,- "snapshot_id": pre.snapshot_id(),+ "element_token": pre.element_token(index),"direction": "down","amount": 5,"delivery_mode": "background"@@ -1493,8 +1488,7 @@ fn harness_appkit_counter() {serde_json::json!({"pid": pid as i64,"window_id": wid,- "element_index": idx,- "snapshot_id": snap_pre.snapshot_id(),+ "element_token": snap_pre.element_token(idx),"action": "press","delivery_mode": "background"}),diff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_gtk3_test.rs b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_gtk3_test.rsindex c899ceca03..528036ae57 100644--- a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_gtk3_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_gtk3_test.rs@@ -807,7 +807,7 @@ fn invoke_operation("click",serde_json::json!({"pid": pid as i64, "window_id": window_id,- "element_index": index, "snapshot_id": pre.snapshot_id(),+ "element_token": pre.element_token(index),"delivery_mode": mode}),),@@ -825,7 +825,7 @@ fn invoke_operation("type_text",serde_json::json!({"pid": pid as i64, "window_id": window_id,- "element_index": index, "snapshot_id": pre.snapshot_id(),+ "element_token": pre.element_token(index),"text": text, "delivery_mode": mode}),),@@ -846,7 +846,7 @@ fn invoke_operation("set_value",serde_json::json!({"pid": pid as i64, "window_id": window_id,- "element_index": index, "snapshot_id": pre.snapshot_id(),+ "element_token": pre.element_token(index),"value": value}),),@@ -946,8 +946,8 @@ fn invoke_operation(args["x"] = serde_json::json!(x + width / 2.0);args["y"] = serde_json::json!(y + height / 2.0);} else {- args["element_index"] = serde_json::json!(element_index(&pre, target));- args["snapshot_id"] = serde_json::json!(pre.snapshot_id());+ args["element_token"] =+ serde_json::json!(pre.element_token(element_index(&pre, target)));}let response = driver.call("scroll", args);if expect_refusal {@@ -1008,7 +1008,7 @@ fn invoke_operation("click",serde_json::json!({"pid": pid as i64, "window_id": window_id,- "element_index": index, "snapshot_id": pre.snapshot_id(),+ "element_token": pre.element_token(index),"delivery_mode": mode}),);diff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_libreoffice_test.rs b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_libreoffice_test.rsindex 85ba315125..a194b9dcd3 100644--- a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_libreoffice_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_libreoffice_test.rs@@ -207,7 +207,7 @@ fn harness_lo_vcl_font_color_expand_opens_picker() {"click",serde_json::json!({"pid": pid as i64, "window_id": wid,- "element_index": idx, "snapshot_id": snap.snapshot_id(),+ "element_token": snap.element_token(idx),"action": "expand"}),);diff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_swiftui_test.rs b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_swiftui_test.rsindex 4f296d3dad..302f7cb022 100644--- a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_swiftui_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_swiftui_test.rs@@ -266,8 +266,7 @@ fn harness_swiftui_counter_background() {serde_json::json!({"pid": pid as i64,"window_id": wid,- "element_index": index,- "snapshot_id": pre.snapshot_id(),+ "element_token": pre.element_token(index),"action": "press","delivery_mode": "background"}),@@ -303,8 +302,7 @@ fn harness_swiftui_set_value_background() {serde_json::json!({"pid": pid as i64,"window_id": wid,- "element_index": index,- "snapshot_id": pre.snapshot_id(),+ "element_token": pre.element_token(index),"value": "swiftui-cua"}),);@@ -354,8 +352,7 @@ fn harness_swiftui_popover_foreground() {serde_json::json!({"pid": pid as i64,"window_id": wid,- "element_index": trigger_idx,- "snapshot_id": snap_pre.snapshot_id(),+ "element_token": snap_pre.element_token(trigger_idx),"action": "press","delivery_mode": "foreground"}),diff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_winui3_test.rs b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_winui3_test.rsindex 708176c124..358cef72ac 100644--- a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_winui3_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_winui3_test.rs@@ -259,8 +259,7 @@ fn harness_winui3_type_text() {let resp = driver.call("type_text",serde_json::json!({- "pid": pid as i64, "window_id": wid, "element_index": idx,- "snapshot_id": snap.snapshot_id(),+ "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(idx),"text": "winui3-typed", "delivery_mode": "background"}),);@@ -293,8 +292,7 @@ fn harness_winui3_xaml_popup_open() {let response = driver.call("click",serde_json::json!({- "pid": pid as i64, "window_id": wid, "element_index": idx,- "snapshot_id": snap.snapshot_id(),+ "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(idx),"delivery_mode": "background"}),);@@ -336,8 +334,7 @@ fn harness_winui3_checkbox_toggle() {let response = driver.call("click",serde_json::json!({- "pid": pid as i64, "window_id": wid, "element_index": idx,- "snapshot_id": snap.snapshot_id(),+ "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(idx),"delivery_mode": "background"}),);@@ -376,8 +373,7 @@ fn harness_winui3_radio_select() {let response = driver.call("click",serde_json::json!({- "pid": pid as i64, "window_id": wid, "element_index": idx,- "snapshot_id": snap.snapshot_id(),+ "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(idx),"delivery_mode": "background"}),);@@ -428,8 +424,7 @@ fn harness_winui3_slider_set_value() {let resp = driver.call("set_value",serde_json::json!({- "pid": pid as i64, "window_id": wid, "element_index": idx,- "snapshot_id": snap.snapshot_id(),+ "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(idx),"value": "42"}),);@@ -475,8 +470,7 @@ fn harness_winui3_combo_select() {let expand = driver.call("click",serde_json::json!({- "pid": pid as i64, "window_id": wid, "element_index": combo_idx,- "snapshot_id": snap.snapshot_id(),+ "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(combo_idx),"delivery_mode": "background"}),);@@ -493,8 +487,7 @@ fn harness_winui3_combo_select() {let select = driver.call("click",serde_json::json!({- "pid": pid as i64, "window_id": wid, "element_index": item_idx,- "snapshot_id": snap2.snapshot_id(),+ "pid": pid as i64, "window_id": wid, "element_token": snap2.element_token(item_idx),"delivery_mode": "background"}),);diff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_wpf_test.rs b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_wpf_test.rsindex f0e791e881..3f3d3fac93 100644--- a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_wpf_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_wpf_test.rs@@ -532,8 +532,7 @@ fn harness_wpf_counter_invoke() {driver.call("click",serde_json::json!({- "pid": pid as i64, "window_id": wid, "element_index": idx,- "snapshot_id": pre.snapshot_id(),+ "pid": pid as i64, "window_id": wid, "element_token": pre.element_token(idx),"delivery_mode": "background"}),)@@ -607,8 +606,7 @@ fn harness_wpf_minimized_element_click_refuses_without_side_effects() {serde_json::json!({"pid": pid as i64,"window_id": wid,- "element_index": idx,- "snapshot_id": ready.snapshot_id(),+ "element_token": ready.element_token(idx),"delivery_mode": "background"}),)@@ -809,8 +807,7 @@ fn harness_wpf_type_text() {serde_json::json!({"pid": pid as i64,"window_id": wid,- "element_index": idx,- "snapshot_id": snap.snapshot_id(),+ "element_token": snap.element_token(idx),"text": "harness-typed","delivery_mode": "foreground"}),@@ -865,8 +862,7 @@ fn harness_wpf_set_value() {driver.call("set_value",serde_json::json!({- "pid": pid as i64, "window_id": wid, "element_index": idx,- "snapshot_id": snap.snapshot_id(),+ "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(idx),"value": "via-uia-setvalue"}),)@@ -909,8 +905,7 @@ fn harness_wpf_deferred_type_text_requires_fresh_snapshot_before_retry() {serde_json::json!({"pid": pid as i64,"window_id": wid,- "element_index": idx,- "snapshot_id": snap.snapshot_id(),+ "element_token": snap.element_token(idx),"text": "deferred-once","delivery_mode": "background"}),@@ -981,8 +976,7 @@ fn harness_wpf_right_click() {let resp = driver.call("right_click",serde_json::json!({- "pid": pid as i64, "window_id": wid, "element_index": idx,- "snapshot_id": snap.snapshot_id(),+ "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(idx),"delivery_mode": "foreground"}),);@@ -1025,8 +1019,7 @@ fn harness_wpf_double_click() {let resp = driver.call("double_click",serde_json::json!({- "pid": pid as i64, "window_id": wid, "element_index": idx,- "snapshot_id": snap.snapshot_id(),+ "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(idx),"delivery_mode": "foreground"}),);@@ -1162,8 +1155,7 @@ fn harness_wpf_scroll() {serde_json::json!({"pid": pid as i64,"window_id": wid,- "element_index": idx,- "snapshot_id": pre.snapshot_id(),+ "element_token": pre.element_token(idx),"delivery_mode": "foreground"}),);@@ -1222,8 +1214,7 @@ fn harness_wpf_modal_messagebox() {let open = driver.call("click",serde_json::json!({- "pid": pid as i64, "window_id": wid, "element_index": idx,- "snapshot_id": snap.snapshot_id(),+ "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(idx),"delivery_mode": "foreground"}),);@@ -1284,8 +1275,7 @@ fn harness_wpf_modal_messagebox() {let dismiss = driver.call("click",serde_json::json!({- "pid": pid as i64, "window_id": modal_wid, "element_index": cancel_idx,- "snapshot_id": modal_snap.snapshot_id(),+ "pid": pid as i64, "window_id": modal_wid, "element_token": modal_snap.element_token(cancel_idx),"delivery_mode": "foreground"}),);@@ -1317,8 +1307,7 @@ fn harness_wpf_owned_popup() {let open = driver.call("click",serde_json::json!({- "pid": pid as i64, "window_id": wid, "element_index": idx,- "snapshot_id": snap.snapshot_id(),+ "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(idx),"delivery_mode": "foreground"}),);@@ -1377,8 +1366,7 @@ fn harness_wpf_layered_popup_capture() {let open = driver.call("click",serde_json::json!({- "pid": pid as i64, "window_id": wid, "element_index": idx,- "snapshot_id": snap.snapshot_id(),+ "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(idx),"delivery_mode": "foreground"}),);@@ -1593,8 +1581,7 @@ fn harness_wpf_slider_increase_large() {let resp = driver.call("click",serde_json::json!({- "pid": pid as i64, "window_id": wid, "element_index": idx,- "snapshot_id": snap.snapshot_id()+ "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(idx)}),);println!("invoke IncreaseLarge #{i}: {}", resp.text());@@ -1645,8 +1632,7 @@ fn harness_wpf_checkbox_toggle() {let resp = driver.call("click",serde_json::json!({- "pid": pid as i64, "window_id": wid, "element_index": idx,- "snapshot_id": snap.snapshot_id(),+ "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(idx),"delivery_mode": "foreground"}),);@@ -1685,8 +1671,7 @@ fn harness_wpf_radio_select() {let response = driver.call("click",serde_json::json!({- "pid": pid as i64, "window_id": wid, "element_index": idx,- "snapshot_id": snap.snapshot_id(),+ "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(idx),"delivery_mode": "foreground"}),);@@ -1724,8 +1709,7 @@ fn harness_wpf_combo_select() {let expand = driver.call("click",serde_json::json!({- "pid": pid as i64, "window_id": wid, "element_index": combo_idx,- "snapshot_id": snap.snapshot_id(),+ "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(combo_idx),"action": "expand", "delivery_mode": "background"}),);@@ -1738,8 +1722,7 @@ fn harness_wpf_combo_select() {let select = driver.call("click",serde_json::json!({- "pid": pid as i64, "window_id": wid, "element_index": item_idx,- "snapshot_id": snap2.snapshot_id(),+ "pid": pid as i64, "window_id": wid, "element_token": snap2.element_token(item_idx),"delivery_mode": "background"}),);@@ -1777,8 +1760,7 @@ fn harness_wpf_listbox_select() {let response = driver.call("click",serde_json::json!({- "pid": pid as i64, "window_id": wid, "element_index": idx,- "snapshot_id": snap.snapshot_id(),+ "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(idx),"delivery_mode": "foreground"}),);@@ -1820,8 +1802,7 @@ fn harness_wpf_modified_click_preserves_selection() {let select_apple = driver.call("click",serde_json::json!({- "pid": pid as i64, "window_id": wid, "element_index": apple,- "snapshot_id": first.snapshot_id(), "delivery_mode": "foreground"+ "pid": pid as i64, "window_id": wid, "element_token": first.element_token(apple), "delivery_mode": "foreground"}),);assert!(@@ -1837,8 +1818,7 @@ fn harness_wpf_modified_click_preserves_selection() {let refused_background = driver.call("click",serde_json::json!({- "pid": pid as i64, "window_id": wid, "element_index": banana,- "snapshot_id": second.snapshot_id(), "modifier": ["ctrl"]+ "pid": pid as i64, "window_id": wid, "element_token": second.element_token(banana), "modifier": ["ctrl"]}),);assert!(@@ -1864,8 +1844,7 @@ fn harness_wpf_modified_click_preserves_selection() {let add_banana = driver.call("click",serde_json::json!({- "pid": pid as i64, "window_id": wid, "element_index": banana,- "snapshot_id": after_refusal.snapshot_id(), "delivery_mode": "foreground",+ "pid": pid as i64, "window_id": wid, "element_token": after_refusal.element_token(banana), "delivery_mode": "foreground","modifier": ["ctrl"]}),);diff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/installed_app_textedit_macos_test.rs b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/installed_app_textedit_macos_test.rsindex 244e90b7f6..94ff8d7445 100644--- a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/installed_app_textedit_macos_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/installed_app_textedit_macos_test.rs@@ -78,7 +78,7 @@ fn background_type_on_native_cocoa_is_ax_verified() {// so prefer visible windows and select the one that actually exposes// the editor instead of assuming `windows[0]` is the document.windows.sort_by_key(|window| !window["is_on_screen"].as_bool().unwrap_or(false));- let (wid, el, snapshot_id) = windows+ let (wid, element_token) = windows.iter().filter_map(|window| window["window_id"].as_u64()).find_map(|window_id| {@@ -96,9 +96,9 @@ fn background_type_on_native_cocoa_is_ax_verified() {elements.iter().find(|element| element["role"] == "AXTextArea")- .and_then(|element| element["element_index"].as_u64())+ .and_then(|element| element["element_token"].as_str())})- .map(|element_index| (window_id, element_index, state.snapshot_id().to_owned()))+ .map(|element_token| (window_id, element_token.to_owned()))}).expect("TextEdit opened no window containing an AXTextArea");@@ -112,8 +112,7 @@ fn background_type_on_native_cocoa_is_ax_verified() {driver.call("type_text",serde_json::json!({- "pid": pid, "window_id": wid, "element_index": el,- "snapshot_id": snapshot_id,+ "pid": pid, "window_id": wid, "element_token": element_token,"text": marker, "delivery_mode": "background"}),)diff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/standalone_browser_behavior_test.rs b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/standalone_browser_behavior_test.rsindex 8b902bb949..b8a320fec5 100644--- a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/standalone_browser_behavior_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/standalone_browser_behavior_test.rs@@ -2097,8 +2097,7 @@ fn run_native_omnibox_select_all(spec: &BrowserSpec) {serde_json::json!({"pid": fixture.pid as i64,"window_id": fixture.window_id,- "element_index": index,- "snapshot_id": snapshot.snapshot_id(),+ "element_token": snapshot.element_token(index),"value": initial,}),);diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rsindex a7903a7125..440edd98b8 100644--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs@@ -234,7 +234,7 @@ impl DriverRuntime {cua_driver_core::session::forget_suspended_runtime_scope(&self.compatibility_context.runtime_scope_key(),);- cua_driver_core::element_cache::retire_runtime_scope(+ cua_driver_core::snapshot_store::retire_runtime_scope(&self.compatibility_context.runtime_scope_key(),);let recording = self.registry.recording.clone();@@ -456,7 +456,7 @@ impl Drop for DriverRuntime {cua_driver_core::session::revoke_sessions_with_prefix(&runtime_prefix);cua_driver_core::session::forget_ended_sessions_with_prefix(&runtime_prefix);cua_driver_core::session::forget_suspended_runtime_scope(&runtime_scope);- cua_driver_core::element_cache::retire_runtime_scope(&runtime_scope);+ cua_driver_core::snapshot_store::retire_runtime_scope(&runtime_scope);// Explicit `shutdown()` drains work and finalizes recordings. Drop is// runtime-scoped and non-blocking so a retained binding cannot affect// another generation.@@ -741,6 +741,31 @@ mod tests {options}+ #[test]+ fn every_registered_tool_schema_matches_the_dispatch_argument_check() {+ let registry = build_registry(&RuntimeOptions::embedded(false));+ // These schemas declare `additionalProperties: true`.+ let open = [+ "get_browser_state",+ "browser_prepare",+ "browser_navigate",+ "browser_click",+ "browser_type",+ "browser_dialog",+ "browser_set_input_files",+ "browser_download",+ "browser_pointer",+ "start_session",+ "escalate_session",+ "get_session",+ "list_sessions",+ "get_session_state",+ "end_session",+ ];+ let violations = registry.input_conformance_violations(&open);+ assert!(violations.is_empty(), "{violations:#?}");+ }+#[test]fn canonical_inventory_advertises_unavailable_perception_tool() {let inventory = tool_inventory(RuntimeOptions::embedded(false));diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/tests/snapshot_lifecycle.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/tests/snapshot_lifecycle.rsindex a35d31f9d8..e47b8768e6 100644--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/tests/snapshot_lifecycle.rs+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/tests/snapshot_lifecycle.rs@@ -1,7 +1,7 @@use super::{CuaDriver, DriverHostOptions};-use cua_driver_core::element_cache::{register_runtime_cache, ElementCacheCore, SnapshotPayload};-use cua_driver_core::element_token::{token_for, ResolvedElement, STALE_TOKEN_ERROR};+use cua_driver_core::element_token::{token_for, ResolvedElement};use cua_driver_core::protocol::ToolResult;+use cua_driver_core::snapshot_store::{register_runtime_store, SnapshotPayload, SnapshotStore};use cua_driver_core::tool::{current_dispatch_runtime_scope, with_runtime_scope, Tool, ToolDef, ToolRegistry,};@@ -25,22 +25,22 @@ impl SnapshotPayload for ProbePayload {}fn resolve<S: SnapshotPayload>(- cache: &ElementCacheCore<S>,+ cache: &SnapshotStore<S>,pid: i32,token: &str,) -> Result<(u64, usize), String> {cache- .resolve_element_args(pid, None, Some(token), None, None, "click")+ .resolve(pid, &serde_json::json!({ "element_token": token })).map(|result| match result {ResolvedElement::Element {- window_id: Some(window),+ window_id: window,element_index,..} => (window, element_index),_ => panic!("expected element"),}).map_err(|error| {- error.structured_content.unwrap()["refusal"]["message"]+ error.structured_content.unwrap()["refusal"]["code"].as_str().unwrap().to_owned()@@ -53,7 +53,7 @@ struct CaptureProbe {native_finished: Notify,release: Mutex<Option<mpsc::Receiver<()>>>,published: Mutex<Option<(String, String)>>,- cache: Mutex<Option<Arc<ElementCacheCore<ProbePayload>>>>,+ cache: Mutex<Option<Arc<SnapshotStore<ProbePayload>>>>,}struct ReleaseNative(Option<mpsc::Sender<()>>);@@ -81,7 +81,7 @@ thread_local! {struct CaptureTool {def: ToolDef,probe: Arc<CaptureProbe>,- cache: Arc<ElementCacheCore<ProbePayload>>,+ cache: Arc<SnapshotStore<ProbePayload>>,}#[async_trait::async_trait]@@ -112,8 +112,8 @@ impl Tool for CaptureTool {fn register_capture_probe(registry: &mut ToolRegistry) {let probe = NEXT_PROBE.with(|probe| probe.borrow_mut().take().unwrap());- let cache = Arc::new(ElementCacheCore::new());- register_runtime_cache(&cache);+ let cache = Arc::new(SnapshotStore::new());+ register_runtime_store(&cache);*probe.cache.lock().unwrap() = Some(cache.clone());registry.register(Box::new(CaptureTool {def: ToolDef {@@ -220,7 +220,7 @@ async fn sdk_shutdown_drains_snapshot_publication_and_retires_the_result() {"closed runtime admitted another publisher");assert!(!result.is_error);- assert_eq!(resolution, Err(STALE_TOKEN_ERROR.to_owned()));+ assert_eq!(resolution, Err("stale_element_token".to_owned()));}#[tokio::test]@@ -274,8 +274,8 @@ mod native {use crate::DriverBackend;use core_foundation::base::{CFGetRetainCount, CFRetain, CFTypeRef, TCFType};use core_foundation::string::CFString;- use cua_driver_core::element_cache::current_runtime_cache;- use platform_macos::ax::cache::{CachedSnapshot, ElementCache};+ use cua_driver_core::snapshot_store::current_runtime_store;+ use platform_macos::ax::snapshot::{AxSnapshot, Snapshots};thread_local! {static NEXT_STATE: RefCell<Option<(usize, u32, Option<String>)>> = const { RefCell::new(None) };@@ -283,7 +283,7 @@ mod native {struct NativeStateTool {def: ToolDef,- cache: Arc<ElementCache>,+ cache: Arc<Snapshots>,token: String,}@@ -304,7 +304,7 @@ mod native {fn register_native_state(registry: &mut ToolRegistry) {let cache =- current_runtime_cache::<CachedSnapshot>().expect("built-in native cache registered");+ current_runtime_store::<AxSnapshot>().expect("built-in native cache registered");let token = NEXT_STATE.with(|next| {let mut next = next.borrow_mut();let (ptr, windows, oldest) = next.as_mut().unwrap();@@ -313,7 +313,7 @@ mod native {let id = cache.publish(731_348,u64::from(window),- CachedSnapshot {+ AxSnapshot {elements: vec![*ptr],},);@@ -350,8 +350,8 @@ mod native {}fn resolve_native(token: &str) -> Result<(u64, usize), String> {- let cache = current_runtime_cache::<CachedSnapshot>()- .ok_or_else(|| STALE_TOKEN_ERROR.to_owned())?;+ let cache = current_runtime_store::<AxSnapshot>()+ .ok_or_else(|| "stale_element_token".to_owned())?;resolve(&cache, 731_348, token)}@@ -369,7 +369,7 @@ mod native {drop(driver);let retained_after_destroy = unsafe { CFGetRetainCount(ptr as CFTypeRef) };drop(serial);- assert_eq!(retired, Err(STALE_TOKEN_ERROR.to_owned()));+ assert_eq!(retired, Err("stale_element_token".to_owned()));assert_eq!(retained_after_destroy, base,"destroy must balance the native retain"@@ -423,7 +423,7 @@ mod native {drop(driver);let retained_after_destroy = unsafe { CFGetRetainCount(ptr as CFTypeRef) };drop(serial);- assert_eq!(retired, Err(STALE_TOKEN_ERROR.to_owned()));+ assert_eq!(retired, Err("stale_element_token".to_owned()));assert_eq!(retained_after_destroy, base);assert_eq!(retained_after_eviction,diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/response.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/response.rsindex 2d1b3d1503..91bcb06888 100644--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/response.rs+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/response.rs@@ -104,14 +104,26 @@ impl ToolResponse {.unwrap_or(false)}- /// Snapshot handle paired with numeric element indices. Element-targeted- /// calls in the 0.17 contract must send this value with `element_index`.pub fn snapshot_id(&self) -> &str {self.structured.get("snapshot_id").and_then(Value::as_str).expect("get_window_state response must carry snapshot_id")}++ pub fn element_token(&self, element_index: u64) -> &str {+ self.structured["elements"]+ .as_array()+ .and_then(|elements| {+ elements+ .iter()+ .find(|element| element["element_index"] == element_index)+ })+ .and_then(|element| element["element_token"].as_str())+ .unwrap_or_else(|| {+ panic!("get_window_state reported no element_token for {element_index}")+ })+ }}#[cfg(test)]diff --git a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs b/libs/cua-driver/rust/crates/cua-driver/src/cli.rsindex e785dbd032..8cac84830a 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs@@ -4039,7 +4039,7 @@ fn cli_docs_json() -> serde_json::Value {{"name": "serve","abstract": "Run Cua Driver as a long-running daemon.",- "discussion": "The daemon owns per-process state such as element-index caches, recording state, and cursor overlay state.",+ "discussion": "The daemon owns per-process state such as accessibility snapshots, recording state, and cursor overlay state.","arguments": no_args,"options": [{"name":"socket","short_name":null,"help":"Override the daemon socket or named-pipe path.","type":"String","default_value":null,"is_optional":true},diff --git a/libs/cua-driver/rust/crates/cua-driver/src/skills.rs b/libs/cua-driver/rust/crates/cua-driver/src/skills.rsindex 755ea067d5..cd8016deef 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/skills.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/skills.rs@@ -1187,7 +1187,7 @@ mod tests {"screen_recording_capturable` is `null","direct_capture_status` is `\"not_checked\"","include_screenshot:false",- "element-indexed AX actions",+ "`element_token` AX actions",] {assert!(macos.contains(required),diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_element_token_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_element_token_test.rsindex fdbf01818b..088c09a7a6 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_element_token_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_element_token_test.rs@@ -69,15 +69,9 @@ fn token_accepting_tools_advertise_element_token_in_schema_and_capabilities() {Some("string"),"{tool_name} element_token must be type:string");- assert_eq!(- props["element_index"]["type"].as_str(),- Some("integer"),- "{tool_name} element_index must remain available only as a snapshot-bound pair"- );- assert_eq!(- props["snapshot_id"]["type"].as_str(),- Some("string"),- "{tool_name} must advertise snapshot_id for safe integer targeting"+ assert!(+ !props.contains_key("element_index") && !props.contains_key("snapshot_id"),+ "{tool_name} must accept only element_token as an element target");// (b) capabilities array includes `accessibility.element_tokens`.diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_media_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_media_test.rsindex d41cde33ad..cce76d0f1c 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_media_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_media_test.rs@@ -86,6 +86,13 @@ fn zoom_tool_returns_jpeg() {continue;}+ // Window-relative pixels need this connection's current screenshot.+ d.send(&serde_json::json!({+ "jsonrpc":"2.0","id": 100 + tried as u64,"method":"tools/call",+ "params":{"name":"get_window_state","arguments":{"pid": win["pid"], "window_id": wid}}+ }));+ d.recv();+d.send(&serde_json::json!({"jsonrpc":"2.0","id": request_id + 1,"method":"tools/call","params":{"name":"zoom","arguments":{@@ -204,11 +211,16 @@ fn zoom_from_zoom_click_round_trip() {"Expected error when from_zoom=true with no context, got: {resp:?}");assert!(- err_text.contains("no zoom context"),- "Expected 'no zoom context' error, got: {err_text}"+ err_text.contains("zoom coordinate context is missing"),+ "Expected missing zoom context error, got: {err_text}");- // Step 2: call zoom on that window to store context.+ // Step 2: read the window, then zoom on it to store context.+ d.send(&serde_json::json!({+ "jsonrpc":"2.0","id":40,"method":"tools/call",+ "params":{"name":"get_window_state","arguments":{"pid": pid, "window_id": window_id}}+ }));+ d.recv();d.send(&serde_json::json!({"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"zoom","arguments":{"window_id": window_id, "pid": pid, "x1":0,"y1":0,"x2":50,"y2":50}}@@ -237,8 +249,8 @@ fn zoom_from_zoom_click_round_trip() {let err_text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");// Translation should succeed — if click fails it's for another reason (target app state), not missing context.assert!(- !err_text.contains("no zoom context"),- "After zoom(), from_zoom click should not say 'no zoom context', got: {err_text}"+ !err_text.contains("zoom coordinate context is missing"),+ "After zoom(), from_zoom click should have zoom context, got: {err_text}");}diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_schema_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_schema_test.rsindex 713a5c09d8..e2583444ed 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_schema_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_schema_test.rs@@ -168,6 +168,9 @@ fn tools_list_schema_shape() {"hotkey","scroll","browser_dialog",+ // macOS set_value has no delivery ladder.+ #[cfg(any(target_os = "linux", target_os = "windows"))]+ "set_value",];for tool in DELIVERY_MODE_TOOLS {let delivery = &properties(tool)["delivery_mode"];diff --git a/libs/cua-driver/rust/crates/platform-linux/src/atspi/mod.rs b/libs/cua-driver/rust/crates/platform-linux/src/atspi/mod.rsindex 4d74d0039c..68b6a008f7 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/atspi/mod.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/atspi/mod.rs@@ -9,12 +9,13 @@//! When the AT-SPI bus is unavailable (or the app exposes no a11y tree) we//! fall back to a minimal X11 property tree (window title + role) via x11rb.+use self::snapshot as cache;use anyhow::Result;-pub mod cache;pub mod native;-pub use cache::ElementCache;+pub mod snapshot;pub use native::ensure_listener_active;+pub use snapshot::Snapshots;/// Stable address on one AT-SPI bus connection, including the owning frame./// Unique bus names prevent a restarted process from reusing an observed path.diff --git a/libs/cua-driver/rust/crates/platform-linux/src/atspi/cache.rs b/libs/cua-driver/rust/crates/platform-linux/src/atspi/snapshot.rssimilarity index 81%rename from libs/cua-driver/rust/crates/platform-linux/src/atspi/cache.rsrename to libs/cua-driver/rust/crates/platform-linux/src/atspi/snapshot.rsindex 5775df1c9d..c3f06cfb2b 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/atspi/cache.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/atspi/snapshot.rs@@ -2,9 +2,9 @@//!//! Two views of the same `get_window_state` snapshot live here://!-//! 1. [`CachedSnapshot`], the [`SnapshotPayload`] published into the runtime-//! element cache (`cua_driver_core::element_cache`). An `element_token` /-//! `element_index` resolves through it to a [`CachedElement`]: the+//! 1. [`AtspiSnapshot`], the [`SnapshotPayload`] published into the runtime+//! snapshot store (`cua_driver_core::snapshot_store`). An `element_token`+//! resolves through it to a [`CachedElement`]: the//! element's proven AT-SPI identity ([`AtspiIdentity`]) plus what a later//! per-index action needs to act WITHOUT re-walking the application (its//! D-Bus address ([`native::ObjectRef`]), role, and the screen frame the@@ -23,7 +23,7 @@use super::native::{self, ObjectRef};use super::{AtspiIdentity, AtspiNode};-use cua_driver_core::element_cache::{ElementCacheCore, SnapshotPayload};+use cua_driver_core::snapshot_store::{SnapshotPayload, SnapshotStore};use std::collections::HashMap;use std::sync::{Arc, Mutex, OnceLock};@@ -51,11 +51,11 @@ pub struct CachedElement {pub bounds: Option<(i32, i32, u32, u32)>,}-pub struct CachedSnapshot {+pub struct AtspiSnapshot {elements: Arc<HashMap<usize, CachedElement>>,}-impl CachedSnapshot {+impl AtspiSnapshot {pub fn from_nodes(nodes: &[AtspiNode]) -> Self {Self::from_nodes_with_bounds(nodes, &[])}@@ -95,7 +95,7 @@ impl CachedSnapshot {}}-impl SnapshotPayload for CachedSnapshot {+impl SnapshotPayload for AtspiSnapshot {type Element = CachedElement;fn len(&self) -> usize {self.elements.len()@@ -105,7 +105,7 @@ impl SnapshotPayload for CachedSnapshot {}}-pub type ElementCache = ElementCacheCore<CachedSnapshot>;+pub type Snapshots = SnapshotStore<AtspiSnapshot>;// -- (pid, xid) side index ----------------------------------------------------@@ -123,8 +123,8 @@ pub(crate) fn update_snapshot(xid: u64,nodes: &[AtspiNode],bounds: &[(usize, i32, i32, u32, u32)],-) -> CachedSnapshot {- let snapshot = CachedSnapshot::from_nodes_with_bounds(nodes, bounds);+) -> AtspiSnapshot {+ let snapshot = AtspiSnapshot::from_nodes_with_bounds(nodes, bounds);store().lock().unwrap()@@ -133,7 +133,7 @@ pub(crate) fn update_snapshot(}/// Forget the side-index entry for (pid, xid) (the runtime cache is retired-/// separately by the owning `ElementCache`).+/// separately by the owning `SnapshotStore`).pub(crate) fn forget_window(pid: u32, xid: u64) {store().lock().unwrap().remove(&CacheKey { pid, xid });}@@ -218,11 +218,14 @@ mod tests {#[test]fn sparse_application_indices_are_members_not_dense_offsets_or_native_keys() {- let cache = ElementCache::new();- let id = cache.publish(42, 7, CachedSnapshot::from_nodes(&[node(11), node(7)]));+ let cache = Snapshots::new();+ let id = cache.publish(42, 7, AtspiSnapshot::from_nodes(&[node(11), node(7)]));for index in [7, 11] {let resolved = cache- .resolve_element_args(42, None, Some(&token_for(id, index)), None, None, "click")+ .resolve(+ 42,+ &serde_json::json!({ "element_token": token_for(id, index) }),+ ).unwrap();assert!(matches!(resolved, ResolvedElement::Element { element, .. } if element.identity.path == format!("/node/{index}"))@@ -230,7 +233,10 @@ mod tests {}for index in [0, 1, 8, 999] {assert!(cache- .resolve_element_args(42, None, Some(&token_for(id, index)), None, None, "click")+ .resolve(+ 42,+ &serde_json::json!({ "element_token": token_for(id, index) })+ ).is_err());}}@@ -239,7 +245,7 @@ mod tests {fn duplicate_and_unindexed_nodes_do_not_create_members() {let mut unindexed = node(8);unindexed.element_index = None;- let payload = CachedSnapshot::from_nodes(&[node(11), unindexed, node(7), node(11)]);+ let payload = AtspiSnapshot::from_nodes(&[node(11), unindexed, node(7), node(11)]);assert_eq!(payload.len(), 2);assert_eq!(payload.retain(7).unwrap().identity.path, "/node/7");assert_eq!(payload.retain(11).unwrap().identity.path, "/node/11");@@ -251,27 +257,33 @@ mod tests {fn unproven_identity_is_discovery_only() {let mut unproven = node(3);unproven.identity = None;- let payload = CachedSnapshot::from_nodes(&[unproven, node(4)]);+ let payload = AtspiSnapshot::from_nodes(&[unproven, node(4)]);assert_eq!(payload.len(), 1);assert!(payload.retain(3).is_none());}#[test]fn reordered_live_index_cannot_retarget_an_observed_control() {- let cache = ElementCache::new();- let observed = cache.publish(42, 7, CachedSnapshot::from_nodes(&[node(5)]));+ let cache = Snapshots::new();+ let observed = cache.publish(42, 7, AtspiSnapshot::from_nodes(&[node(5)]));let mut replacement = node(5);replacement.identity.as_mut().unwrap().path = "/node/replacement".into();- let current = cache.publish(42, 7, CachedSnapshot::from_nodes(&[replacement]));+ let current = cache.publish(42, 7, AtspiSnapshot::from_nodes(&[replacement]));// The former observation is invalidated rather than resolving index 5// to the replacement. The current token retains the replacement's own// object address for the X11 click resolver to match directly.assert!(cache- .resolve_element_args(42, None, Some(&token_for(observed, 5)), None, None, "click")+ .resolve(+ 42,+ &serde_json::json!({ "element_token": token_for(observed, 5) })+ ).is_err());let current = cache- .resolve_element_args(42, None, Some(&token_for(current, 5)), None, None, "click")+ .resolve(+ 42,+ &serde_json::json!({ "element_token": token_for(current, 5) }),+ ).unwrap();assert!(matches!(current, ResolvedElement::Element { element, .. } if element.identity.path == "/node/replacement")@@ -280,35 +292,37 @@ mod tests {#[test]fn replacement_retires_old_linux_membership() {- let cache = ElementCache::new();- let old = cache.publish(42, 7, CachedSnapshot::from_nodes(&[node(7), node(11)]));- let fresh = cache.publish(42, 7, CachedSnapshot::from_nodes(&[node(3)]));+ let cache = Snapshots::new();+ let old = cache.publish(42, 7, AtspiSnapshot::from_nodes(&[node(7), node(11)]));+ let fresh = cache.publish(42, 7, AtspiSnapshot::from_nodes(&[node(3)]));for index in [7, 11] {let refusal = cache- .resolve_element_args(42, None, Some(&token_for(old, index)), None, None, "click")+ .resolve(+ 42,+ &serde_json::json!({ "element_token": token_for(old, index) }),+ ).unwrap_err();assert_eq!(refusal.structured_content.unwrap()["refusal"]["code"],"stale_element_token");assert!(cache- .resolve_element_args(+ .resolve(42,- None,- Some(&token_for(fresh, index)),- None,- None,- "click"+ &serde_json::json!({ "element_token": token_for(fresh, index) })).is_err());}let target = cache- .resolve_element_args(42, None, Some(&token_for(fresh, 3)), None, None, "click")+ .resolve(+ 42,+ &serde_json::json!({ "element_token": token_for(fresh, 3) }),+ ).unwrap();assert!(matches!(target,ResolvedElement::Element {- window_id: Some(7),+ window_id: 7,element,..} if element.identity.path == "/node/3"@@ -317,10 +331,13 @@ mod tests {#[test]fn empty_linux_snapshot_has_no_element_zero() {- let cache = ElementCache::new();- let id = cache.publish(42, 7, CachedSnapshot::from_nodes(&[]));+ let cache = Snapshots::new();+ let id = cache.publish(42, 7, AtspiSnapshot::from_nodes(&[]));assert!(cache- .resolve_element_args(42, None, Some(&token_for(id, 0)), None, None, "click")+ .resolve(+ 42,+ &serde_json::json!({ "element_token": token_for(id, 0) })+ ).is_err());}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/recording_hooks.rs b/libs/cua-driver/rust/crates/platform-linux/src/recording_hooks.rsindex 98ee2c4770..e068429c7a 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/recording_hooks.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/recording_hooks.rs@@ -97,21 +97,10 @@ pub fn element_window_local_xy(args: &serde_json::Value,capture_point: bool,) -> Option<(u64, Option<(f64, f64)>)> {- use cua_driver_core::tool_args::ArgsExt;- let cache = cua_driver_core::element_cache::current_runtime_cache::<- crate::atspi::cache::CachedSnapshot,+ let cache = cua_driver_core::snapshot_store::current_runtime_store::<+ crate::atspi::snapshot::AtspiSnapshot,>()?;- let resolved = cache- .resolve_element_args(- i32::try_from(pid).ok()?,- args.opt_u64("element_index").map(|index| index as usize),- args.get("element_token")- .and_then(serde_json::Value::as_str),- args.get("snapshot_id").and_then(serde_json::Value::as_str),- args.opt_u64("window_id"),- "recording",- )- .ok()?;+ let resolved = cache.resolve(i32::try_from(pid).ok()?, args).ok()?;let (index, window, _) = resolved.into_parts(None);let window_id = window?;let element_index = u32::try_from(index?).ok()?;diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rsindex 5858fb1edb..e7b5653eb4 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs@@ -16,7 +16,7 @@ use std::fs;use std::path::PathBuf;use std::sync::{Arc, RwLock};-use crate::atspi::ElementCache;+use crate::atspi::Snapshots;use cursor_overlay::CursorRegistry;fn window_target_candidates_for_pid(@@ -137,7 +137,7 @@ fn snapshot_window_resolver(Arc::new(move |pid, handle| {let pid = i32::try_from(pid).ok()?;let id = cua_driver_core::element_token::parse_snapshot_handle(handle)?;- state.element_cache.window_for_snapshot(pid, id)+ state.snapshots.window_for_snapshot(pid, id)})}@@ -179,14 +179,11 @@ pub fn load_driver_config() -> DriverConfig {cfg}-use cua_driver_core::element_cache::{- SnapshotBoundZoomContext as ZoomContext, SnapshotBoundZoomRegistry as ZoomRegistry,-};+use cua_driver_core::snapshot_store::ZoomContext;pub struct ToolState {- pub element_cache: Arc<ElementCache>,+ pub snapshots: Arc<Snapshots>,pub cursor_registry: Arc<CursorRegistry>,- pub zoom_registry: Arc<ZoomRegistry>,pub capture_service: Arc<cua_driver_core::capture_runtime::CaptureService>,pub mouse_hold: std::sync::Mutex<std::collections::HashMap<String, MouseHoldState>>,pub config: Arc<RwLock<DriverConfig>>,@@ -213,12 +210,11 @@ impl ToolState {fn new_with_capture_service(capture_service: Arc<cua_driver_core::capture_runtime::CaptureService>,) -> Arc<Self> {- let element_cache = Arc::new(ElementCache::new());- cua_driver_core::element_cache::register_runtime_cache(&element_cache);+ let snapshots = Arc::new(Snapshots::new());+ cua_driver_core::snapshot_store::register_runtime_store(&snapshots);Arc::new(Self {- element_cache,+ snapshots,cursor_registry: Arc::new(CursorRegistry::new()),- zoom_registry: Arc::new(ZoomRegistry::new()),capture_service,mouse_hold: std::sync::Mutex::new(Default::default()),config: Arc::new(RwLock::new(load_driver_config())),@@ -231,8 +227,7 @@ impl ToolState {pid: u32,window_id: Option<u64>,) -> Result<ZoomContext, ToolResult> {- self.zoom_registry.resolve(- &self.element_cache,+ self.snapshots.zoom(pid as i32,window_id,args.get("_session_id").and_then(Value::as_str),@@ -246,11 +241,14 @@ fn screenshot_scale(pid: u32,window_id: Option<u64>,) -> Result<f64, ToolResult> {- state.element_cache.screenshot_scale_or_refusal(- pid as i32,- window_id,- args.get("_session_id").and_then(Value::as_str),- )+ state+ .snapshots+ .screenshot_context(+ pid as i32,+ window_id,+ args.get("_session_id").and_then(Value::as_str),+ )+ .map(|context| context.scale)}// ── list_apps ────────────────────────────────────────────────────────────────@@ -909,7 +907,7 @@ impl WindowOverlays {parts.push(format!("popup (window_id {id}, bounds x={} y={} {}x{}) is open: call \get_window_state(pid={pid}, window_id={id}) to index its items and click them \- by element_index.",+ by element_token.",popup["bounds"]["x"],popup["bounds"]["y"],popup["bounds"]["width"],@@ -1009,7 +1007,8 @@ impl Tool for GetWindowStateTool {structured `elements` array (preferred) AND a Markdown rendering of \the same tree (back-compat). Every actionable element is tagged \with [element_index N] in the markdown and as `element_index` in \- the structured array.\n\n\+ the structured array; pass each element's `element_token` to \+ `click`, `type_text`, `set_value`, etc.\n\n\PREFERRED CONSUMERS read `structuredContent.elements` (one entry \per indexed row with `element_index`, `role`, `label`, `value`, \`enabled`, `selected`, `actions` (names of AT-SPI actions exposed \@@ -1025,7 +1024,7 @@ impl Tool for GetWindowStateTool {Always returns BOTH the element tree AND a screenshot — ground on \both and cross-check (the tree lies on some surfaces). Choose the \modality at ACTION time: an element ax action \- (element_index/element_token → accessibility rung) or an element px \+ (element_token → accessibility rung) or an element px \action (x,y → pixel rung off this screenshot). capture_mode is \deprecated and ignored. On Wayland, where output capture cannot prove \the requested surface's identity, the truthful tree is returned without \@@ -1064,7 +1063,7 @@ impl Tool for GetWindowStateTool {right_click that opened one names it in its result (`popup: \{window_id, bounds, title}`); pass that window_id here to walk the \popup's own AT-SPI toplevel so its menu items get element indices \- (then click them by element_index). Omitting window_id while a popup \+ (then click them by element_token). Omitting window_id while a popup \of this pid is open walks that popup.".into(),input_schema: json!({"type":"object","required":["pid"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),@@ -1162,7 +1161,7 @@ impl Tool for GetWindowStateTool {// returns BOTH the AT-SPI tree and a screenshot now, so the agent grounds// on both and cross-checks (the tree lies often enough that a grounding// screenshot should always be present). The modality is chosen at action- // time: an element ax action (element_index) or element px action (x,y).+ // time: an element ax action (element_token) or element px action (x,y).// We don't even read the arg; it stays in the schema only so old callers// don't trip additionalProperties:false.let query = args.opt_str("query");@@ -1398,6 +1397,7 @@ impl Tool for GetWindowStateTool {original_w.map_or(1.0, |ow| ow as f64 / *w as f64)});let mut published_snapshot = false;+ let mut invalidated = Vec::new();if let Some(tr) = tree_opt {let source_trusted = tr.trusted;@@ -1422,7 +1422,7 @@ impl Tool for GetWindowStateTool {} else if !tr.bounds_complete {header.push_str("⚠️ bounds phase ran out of time: some elements have no frame \- (element_index clicks still work; pixel targeting may not). \+ (element_token clicks still work; pixel targeting may not). \Retry with a larger timeout_ms if you need frames.\n",);}@@ -1451,31 +1451,25 @@ impl Tool for GetWindowStateTool {&& crate::wayland::hyprland::is_session())|| tr.window_scoped;if !observation_only && !target_scoped {- state.element_cache.remove(pid as i32, xid);- crate::atspi::cache::forget_window(pid, xid);+ invalidated.extend(state.snapshots.remove(pid as i32, xid));+ crate::atspi::snapshot::forget_window(pid, xid);}- // The payload carries each element's proven identity plus- // the frames this walk produced, so later per-index- // actions act on the observed object without re-walking.- let snapshot_id = (!observation_only && target_scoped)+ let (snapshot_id, replaced) = (!observation_only && target_scoped).then(|| {- state.element_cache.publish_for_session(+ state.snapshots.publish_for_session(pid as i32,xid,- crate::atspi::cache::update_snapshot(+ crate::atspi::snapshot::update_snapshot(pid, xid, &tr.nodes, &tr.bounds,),session_id.as_deref(),screenshot_scale,)})- .flatten();+ .flatten()+ .unzip();published_snapshot = snapshot_id.is_some();- if let Some(snapshot_id) = snapshot_id {- state- .zoom_registry- .retire_replaced(pid as i32, xid, snapshot_id);- }+ invalidated.extend(replaced.into_iter().flatten());// Structured `elements` array: one entry per actionable node.// Shape: `{element_index, element_token, role, label,@@ -1553,10 +1547,9 @@ impl Tool for GetWindowStateTool {structured["elements"] = json!(elements);// Surface 6: snapshot id mirror for debug correlation.if let Some(snapshot_id) = snapshot_id {- structured["snapshot_id"] =- json!(cua_driver_core::element_token::token_for(snapshot_id, 0)- .trim_end_matches(":0")- .to_string());+ structured["snapshot_id"] = json!(+ cua_driver_core::element_token::format_snapshot_id(snapshot_id)+ );}structured["_note"] = json!("Prefer `elements` — `tree_markdown` will continue to work \@@ -1614,18 +1607,27 @@ impl Tool for GetWindowStateTool {}if !observation_only && !published_snapshot && screenshot_scale.is_some() {- if let Some(snapshot_id) = state.element_cache.publish_for_session(+ if let Some((_, replaced)) = state.snapshots.publish_for_session(pid as i32,xid,- crate::atspi::cache::CachedSnapshot::from_nodes(&[]),+ crate::atspi::snapshot::AtspiSnapshot::from_nodes(&[]),session_id.as_deref(),screenshot_scale,) {- state- .zoom_registry- .retire_replaced(pid as i32, xid, snapshot_id);+ invalidated.extend(replaced);}}+ if !invalidated.is_empty() {+ let ids: Vec<String> = invalidated+ .into_iter()+ .map(cua_driver_core::element_token::format_snapshot_id)+ .collect();+ content.push(cua_driver_core::protocol::Content::text(format!(+ "Invalidated snapshots {}: their element_tokens are stale.",+ ids.join(", ")+ )));+ structured["invalidated_snapshot_ids"] = json!(ids);+ }if let Some((b64_opt, file_path, w, h, orig_w, capture_id)) = shot_opt {// ax mode + screenshot_out_file writes the PNG to disk and@@ -2566,7 +2568,7 @@ fn apply_foreground_report(v: &mut Value, report: &crate::input::ForegroundRepor/// executed at window-local (0, 0) — the top-left corner, i.e. the File menu.fn invalid_pointer_arguments(tool: &str, detail: &str) -> ToolResult {let accepted = [- "pid + element_index (or element_token) from get_window_state",+ "pid + element_token from get_window_state","pid/window_id + x + y (window-local pixels of window_id; coordinate_frame:\"desktop\" for screen pixels)","x + y + scope:\"desktop\" (screen pixels, no pid)",];@@ -2591,7 +2593,7 @@ fn require_point_args(tool: &str, args: &Value) -> Option<ToolResult> {(true, true) => None,(false, false) => Some(invalid_pointer_arguments(tool,- "no element_index/element_token and no x/y were given (a `target_id` is not an \+ "no element_token and no x/y were given (a `target_id` is not an \element handle)",)),(true, false) => Some(invalid_pointer_arguments(tool, "x was given without y")),@@ -3569,7 +3571,7 @@ impl PointerRoute {text.push_str(&format!(" {} opened (popup: window_id={}, bounds x={} y={} {}x{}); call \get_window_state(pid={}, window_id={}) to index its items and click them \- by element_index, or click(window_id={}, x, y) with popup-local pixels.",+ by element_token, or click(window_id={}, x, y) with popup-local pixels.",popup.describe(),popup.window,popup.x,@@ -3813,7 +3815,7 @@ fn linux_input_error(error: anyhow::Error) -> ToolResult {"The point is under window {}{}{}, which belongs to a different application, so \a background pointer press there would hit that window instead of the target; \no input was sent. Either act on that window (pass its window_id{} and click / \- press keys there, or dismiss it), click the target by element_index (an AT-SPI \+ press keys there, or dismiss it), click the target by element_token (an AT-SPI \action that needs no pointer), or pick a point of the target that is not \covered (list_windows gives bounds and z_index).",occluded.covering_window,@@ -3849,7 +3851,7 @@ fn linux_input_error(error: anyhow::Error) -> ToolResult {grab drops keys from the virtual keyboard, and the core keyboard would go to the \focused application instead. Dismiss the popup first (click outside it, or \click an item in it with pid/window_id={}), or click the popup's item by \- element_index after get_window_state(pid={}, window_id={}); then retry.",+ element_token after get_window_state(pid={}, window_id={}); then retry.",grab.pid,grab.popup.describe(),grab.popup.window,@@ -3895,7 +3897,7 @@ fn linux_input_error(error: anyhow::Error) -> ToolResult {}));}if let Some(failed) = error.downcast_ref::<BackgroundPointerFailed>() {- let hint = "Click by element_index (AT-SPI action) or retry with \+ let hint = "Click by element_token (AT-SPI action) or retry with \delivery_mode:\"foreground\".";return ToolResult::error(format!("{failed}. {hint}")).with_structured(json!({"code": "background_pointer_failed",@@ -4765,10 +4767,10 @@ fn coordinate_less_mouse_button_up_survives_snapshot_replacement() {x: 120.0,y: 80.0,};- state.element_cache.publish_for_session(+ state.snapshots.publish_for_session(hold.pid as i32,hold.xid,- crate::atspi::cache::CachedSnapshot::from_nodes(&[]),+ crate::atspi::snapshot::AtspiSnapshot::from_nodes(&[]),Some("press-owner"),Some(2.0),);@@ -4778,10 +4780,10 @@ fn coordinate_less_mouse_button_up_survives_snapshot_replacement() {.unwrap().insert(cursor_id.to_owned(), hold.clone());- state.element_cache.publish_for_session(+ state.snapshots.publish_for_session(hold.pid as i32,hold.xid,- crate::atspi::cache::CachedSnapshot::from_nodes(&[]),+ crate::atspi::snapshot::AtspiSnapshot::from_nodes(&[]),Some("replacement-owner"),Some(1.0),);@@ -5688,7 +5690,7 @@ impl ClickTool {cursor_id: &str,pid: u32,idx: usize,- observed: &crate::atspi::cache::CachedElement,+ observed: &crate::atspi::snapshot::CachedElement,xid_hint: Option<u64>,placement: Option<(u64, f64, f64)>,button: u8,@@ -5950,7 +5952,7 @@ impl ClickTool {/// placement decision. Runs blocking X11 / AT-SPI queries.fn decide_foreground_element_placement(pid: u32,- observed: &crate::atspi::cache::CachedElement,+ observed: &crate::atspi::snapshot::CachedElement,xid_hint: Option<u64>,placement: Option<(u64, f64, f64)>,) -> (Option<u64>, ForegroundElementPlacement) {@@ -6037,12 +6039,12 @@ impl Tool for ClickTool {fn def(&self) -> &ToolDef {CLICK_DEF.get_or_init(|| ToolDef {name: "click".into(),- description: "Click against a target pid. **Prefer `element_index` over pixel \- coordinates** — element_index works on backgrounded / hidden windows, surfaces \+ description: "Click against a target pid. **Prefer `element_token` over pixel \+ coordinates** — element_token works on backgrounded / hidden windows, surfaces \a stable handle, and tells you what you're clicking via the cached AT-SPI \element's role + label. Reach for `x, y` only when the target is a canvas / \custom-drawn surface that doesn't appear in the AT-SPI tree.\n\n\- Provide either (window_id + x/y) or (pid + element_index). x/y are \+ Provide either (window_id + x/y) or (pid + element_token). x/y are \WINDOW-LOCAL pixels of window_id (the get_window_state screenshot frame); \a point outside the window is refused (point_outside_window) and every \pixel result reports the resolved window_point / screen_point. Background \@@ -6051,8 +6053,8 @@ impl Tool for ClickTool {selected through its container: `selected: ...`), else presses the real \virtual pointer there. A click that opens a popup menu names it (`popup: \{window_id, bounds}`): pass that window_id to get_window_state to index its \- items. element_index cache is scoped per (pid, \- window_id) and is replaced by the next get_window_state of the same window — \+ items. The token is stale once the next get_window_state of the same \+ window replaces its snapshot — \re-snapshot every turn before clicking.\n\n\After a zoom call, pass from_zoom=true to auto-translate zoom-image coords \back to full-window space.\n\n\@@ -6078,9 +6080,7 @@ impl Tool for ClickTool {"window_id":{"type":"integer"},"x":{"type":"number","description":"Window-local pixel X of the target window's own get_window_state screenshot (0..screenshot_width). For get_desktop_state pixels pass scope:\"desktop\" (or coordinate_frame:\"desktop\")."},"y":{"type":"number","description":"Window-local pixel Y of the target window's own get_window_state screenshot (0..screenshot_height); see x."},- "element_index": cua_driver_core::tool_schema::element_index_schema(),"element_token": cua_driver_core::tool_schema::element_token_schema(),- "snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),"capture_id":{"type":"string","description":"Optional one-shot binding to the exact PNG returned by get_window_state or get_desktop_state. When present, x/y are interpreted in that capture and admitted before native dispatch."},// Shape matches the shared button_schema() canon (string +// [left,right,middle]); kept inline to carry the Linux/Wayland@@ -6219,18 +6219,9 @@ impl Tool for ClickTool {// Surface 6: element_token / element_index precedence resolution.// We resolve before the legacy `opt_u64("element_index")` branch// so a token-only call (no integer arg) still takes the element path.- let element_token_arg = args.opt_str("element_token");let capture_id_arg = args.opt_str("capture_id");let window_id_arg = args.opt_u64("window_id");- let element_index_arg = args.opt_u64("element_index").map(|v| v as usize);- let resolved = match self.state.element_cache.resolve_element_args(- pid as i32,- element_index_arg,- element_token_arg.as_deref(),- args.opt_str("snapshot_id").as_deref(),- window_id_arg,- "click",- ) {+ let resolved = match self.state.snapshots.resolve(pid as i32, &args) {Ok(r) => r,Err(e) => return e,};@@ -6242,7 +6233,7 @@ impl Tool for ClickTool {};let window_id_resolved: Option<u64> = match &resolved {cua_driver_core::element_token::ResolvedElement::Element { window_id, .. } => {- window_id_arg.or_else(|| window_id.map(|v| v as u64))+ Some(*window_id)}cua_driver_core::element_token::ResolvedElement::None => window_id_arg,};@@ -6617,7 +6608,7 @@ impl Tool for ClickTool {}let xid = match args.opt_u64("window_id") {Some(v) => v,- None => return ToolResult::error("Provide either element_index or window_id + x/y."),+ None => return ToolResult::error("Provide either element_token or window_id + x/y."),};let desktop_frame = desktop_frame_requested(&args);let from_zoom = args.bool_or("from_zoom", false);@@ -6940,7 +6931,7 @@ impl Tool for ClickTool {);let hint = "No accessible control covers this point and the toolkit drops \synthetic pointer events, so a background pixel click here would \- change nothing. Use get_window_state and click by element_index \+ change nothing. Use get_window_state and click by element_token \(AT-SPI action), or retry with delivery_mode='foreground'.";refusal.content@@ -7097,10 +7088,8 @@ impl Tool for TypeTextTool {"pid":{"type":"integer"},"window_id":{"type":"integer"},"text":{"type":"string"},- "element_index": cua_driver_core::tool_schema::element_index_schema(),"element_token": cua_driver_core::tool_schema::element_token_schema(),- "snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),- "x":{"type":"number","description":"Pixel X of the field to type into — the element px action form. Pass x,y (no element_index) and the tool pixel-clicks there to establish real renderer focus, then types. Use for Chromium/Electron inputs the AX path can't reach. Window-local pixels of the target window's own get_window_state screenshot by default (same convention as click); for get_desktop_state pixels pass scope:\"desktop\" (or coordinate_frame:\"desktop\") — a bare pid+x/y is otherwise misinterpreted as window-local and can focus the wrong widget."},+ "x":{"type":"number","description":"Pixel X of the field to type into — the element px action form. Pass x,y (no element_token) and the tool pixel-clicks there to establish real renderer focus, then types. Use for Chromium/Electron inputs the AX path can't reach. Window-local pixels of the target window's own get_window_state screenshot by default (same convention as click); for get_desktop_state pixels pass scope:\"desktop\" (or coordinate_frame:\"desktop\") — a bare pid+x/y is otherwise misinterpreted as window-local and can focus the wrong widget."},"y":{"type":"number","description":"Pixel Y of the field (see x)."},"scope":{"type":"string","enum":["window","desktop"],"default":"window"},"coordinate_frame": coordinate_frame_schema(),@@ -7154,17 +7143,7 @@ impl Tool for TypeTextTool {// cua_driver_core::text_sanitize docs for rationale.let text = cua_driver_core::text_sanitize::strip_trailing_agent_protocol_tags(&text_raw).into_owned();- // Surface 6: resolve element_token / element_index for the- // optional pre-typing focus glide below. The token also carries- // the window_id when supplied so the caller can omit window_id.- let resolved = match self.state.element_cache.resolve_element_args(- pid as i32,- args.opt_u64("element_index").map(|v| v as usize),- args.opt_str("element_token").as_deref(),- args.opt_str("snapshot_id").as_deref(),- args.opt_u64("window_id"),- "type_text",- ) {+ let resolved = match self.state.snapshots.resolve(pid as i32, &args) {Ok(r) => r,Err(e) => return e,};@@ -7173,10 +7152,10 @@ impl Tool for TypeTextTool {element_index,window_id,..- } => (Some(*element_index), window_id.map(|v| v as u64)),+ } => (Some(*element_index), Some(*window_id)),cua_driver_core::element_token::ResolvedElement::None => (None, None),};- let xid_opt = args.opt_u64("window_id").or(resolved_window_id);+ let xid_opt = resolved_window_id.or(args.opt_u64("window_id"));// Resolve XID: use window_id if given, else first window for pid.let xid = match xid_opt {@@ -7281,7 +7260,7 @@ impl Tool for TypeTextTool {}if px.is_some() && resolved_elem_idx.is_some() {return ToolResult::error(- "Pass either element_index (ax) or x,y (px) to type_text, not both.",+ "Pass either element_token (ax) or x,y (px) to type_text, not both.",);}@@ -7422,7 +7401,7 @@ impl Tool for TypeTextTool {}// ── px form: focus by pixel-click, then type into the now-focused element ──- // Pass x,y (no element_index/token) for an *element px action*: pixel-click+ // Pass x,y (no element_token) for an *element px action*: pixel-click// the field to give the renderer the real keyboard focus the AT-SPI path// can't, then fall through to the focused-element type path below (it// escalates AT-SPI → key events and lands once focused). Reuses ClickTool's@@ -7985,10 +7964,8 @@ impl Tool for PressKeyTool {"window_id":{"type":"integer"},"key":{"type":"string","description":"Key name: enter/return, tab, escape, space, backspace, delete, insert, home, end, pageup, pagedown, up, down, left, right, f1-f12, or any single ASCII character."},"modifiers":{"type":"array","items":{"type":"string"}},- "element_index": cua_driver_core::tool_schema::element_index_schema(),"element_token": cua_driver_core::tool_schema::element_token_schema(),- "snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),- "x":{"type":"number","description":"Pixel X — the element px action form: pixel-click there to focus, then send the key. Use when the key must go to a Chromium/Electron surface the AX path can't focus. Pass with y, no element_index. Window-local pixels by default (same convention as click); for get_desktop_state pixels pass scope:\"desktop\" (or coordinate_frame:\"desktop\")."},+ "x":{"type":"number","description":"Pixel X — the element px action form: pixel-click there to focus, then send the key. Use when the key must go to a Chromium/Electron surface the AX path can't focus. Pass with y, no element_token. Window-local pixels by default (same convention as click); for get_desktop_state pixels pass scope:\"desktop\" (or coordinate_frame:\"desktop\")."},"y":{"type":"number","description":"Pixel Y (see x)."},"scope":{"type":"string","enum":["window","desktop"],"default":"window"},"coordinate_frame": coordinate_frame_schema(),@@ -8047,21 +8024,12 @@ impl Tool for PressKeyTool {let (combo_mods, key) = split_key_combo(&key);mods.extend(combo_mods);- // Surface 6: resolve the element token/index into both its owning- // window and exact child. Foreground delivery establishes child focus- // inside the verified top-level activation transaction; background- // XSendEvent retains the historical direct-window path.- let element_token_arg = args.opt_str("element_token");+ // Resolve the element token into both its owning window and exact+ // child. Foreground delivery establishes child focus inside the+ // verified top-level activation transaction; background XSendEvent+ // retains the historical direct-window path.let window_id_arg = args.opt_u64("window_id");- let element_index_arg = args.opt_u64("element_index").map(|v| v as usize);- let resolved = match self.state.element_cache.resolve_element_args(- pid as i32,- element_index_arg,- element_token_arg.as_deref(),- args.opt_str("snapshot_id").as_deref(),- window_id_arg,- "press_key",- ) {+ let resolved = match self.state.snapshots.resolve(pid as i32, &args) {Ok(r) => r,Err(e) => return e,};@@ -8073,7 +8041,7 @@ impl Tool for PressKeyTool {};let xid_opt = match &resolved {cua_driver_core::element_token::ResolvedElement::Element { window_id, .. } => {- window_id_arg.or_else(|| window_id.map(|v| v as u64))+ Some(*window_id)}cua_driver_core::element_token::ResolvedElement::None => window_id_arg,};@@ -8129,7 +8097,7 @@ impl Tool for PressKeyTool {// ── px form: pixel-click to focus, then the key goes to the focused element ──// Reuses click's translation + delivery_mode; after it, deliver via the plain// background path (the focus-click already handled fronting when fg). Pass x,y- // (no element_index) for Chromium/Electron surfaces the AX path can't focus.+ // (no element_token) for Chromium/Electron surfaces the AX path can't focus.let delivery = crate::input::delivery::DeliveryMode::from_args(&args);if isolated_hyprland_background(delivery) {if xid_opt.is_none() {@@ -8183,7 +8151,7 @@ impl Tool for PressKeyTool {}if px.is_some() && resolved_element_index.is_some() {return ToolResult::error(- "Pass either element_index (ax) or x,y (px) to press_key, not both.",+ "Pass either element_token (ax) or x,y (px) to press_key, not both.",);}@@ -8417,9 +8385,7 @@ impl Tool for HotkeyTool {"window_id":{"type":"integer"},"keys":{"type":"array","items":{"type":"string"},"minItems":2,"description":"Modifier(s) + one non-modifier key, e.g. [\"ctrl\",\"c\"]."},- "element_index": cua_driver_core::tool_schema::element_index_schema(),"element_token": cua_driver_core::tool_schema::element_token_schema(),- "snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),"x":{"type":"number","description":"Screenshot-pixel X — the element px action form: pixel-click there to focus, then send the combo (so e.g. Ctrl+V pastes into that field). Pass with y. Use for Chromium/Electron surfaces the background combo can't reach."},"y":{"type":"number","description":"Screenshot-pixel Y (see x)."},"scope":{"type":"string","enum":["window","desktop"],"default":"window"},@@ -8475,15 +8441,7 @@ impl Tool for HotkeyTool {}let mut pid = args.u64_or("pid", 0) as u32;let window_id_arg = args.opt_u64("window_id");- let element_index_arg = args.opt_u64("element_index").map(|value| value as usize);- let resolved = match self.state.element_cache.resolve_element_args(- pid as i32,- element_index_arg,- args.opt_str("element_token").as_deref(),- args.opt_str("snapshot_id").as_deref(),- window_id_arg,- "hotkey",- ) {+ let resolved = match self.state.snapshots.resolve(pid as i32, &args) {Ok(resolved) => resolved,Err(error) => return error,};@@ -8495,7 +8453,7 @@ impl Tool for HotkeyTool {};let xid_opt = match &resolved {cua_driver_core::element_token::ResolvedElement::Element { window_id, .. } => {- window_id_arg.or_else(|| window_id.map(|value| value as u64))+ Some(*window_id)}cua_driver_core::element_token::ResolvedElement::None => window_id_arg,};@@ -8638,7 +8596,7 @@ impl Tool for HotkeyTool {}if px.is_some() && resolved_element_index.is_some() {return ToolResult::error(- "Pass either element_index (ax) or x,y (px) to hotkey, not both.",+ "Pass either element_token (ax) or x,y (px) to hotkey, not both.",);}@@ -8854,11 +8812,10 @@ impl Tool for SetValueTool {"type":"object","required":["pid","value"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},- "window_id":{"type":"integer","description":"Required when element_index is used; optional when element_token is supplied (the token carries it)."},- "element_index": cua_driver_core::tool_schema::element_index_schema(),+ "window_id":{"type":"integer","description":"Omit when element_token is supplied (the token carries it)."},"element_token": cua_driver_core::tool_schema::element_token_schema(),- "snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),- "value":{"type":["string","number"],"description":"New value. Written through AT-SPI EditableText/Value when the element exposes them; otherwise (GTK2 spin scales, VCL spin buttons) the field is clicked with the session's real pointer, its text selected and replaced through the virtual keyboard and committed with Tab, then read back."}+ "value":{"type":["string","number"],"description":"New value. Written through AT-SPI EditableText/Value when the element exposes them; otherwise (GTK2 spin scales, VCL spin buttons) the field is clicked with the session's real pointer, its text selected and replaced through the virtual keyboard and committed with Tab, then read back."},+ "delivery_mode": crate::input::delivery::delivery_mode_schema()},"additionalProperties":false}),read_only: false, destructive: true, idempotent: false, open_world: true,@@ -8879,31 +8836,24 @@ impl Tool for SetValueTool {.with_structured(json!({ "code": "invalid_arguments" }))}};- // Surface 6: element_token / element_index precedence resolution.- let resolved = match self.state.element_cache.resolve_element_args(- pid as i32,- args.opt_u64("element_index").map(|v| v as usize),- args.opt_str("element_token").as_deref(),- args.opt_str("snapshot_id").as_deref(),- args.opt_u64("window_id"),- "set_value",- ) {+ let resolved = match self.state.snapshots.resolve(pid as i32, &args) {Ok(r) => r,Err(e) => return e,};- let (idx, resolved_window_id) = match &resolved {+ let (idx, xid) = match &resolved {cua_driver_core::element_token::ResolvedElement::Element {element_index,window_id,..- } => (*element_index, window_id.map(u64::from)),- cua_driver_core::element_token::ResolvedElement::None => return ToolResult::error(- "set_value requires element_index or element_token to address the target element.",- ),+ } => (*element_index, *window_id),+ cua_driver_core::element_token::ResolvedElement::None => {+ return ToolResult::error(+ "set_value requires element_token to address the target element.",+ )+ }};let value_for_task = value.clone();- let xid_opt = args.opt_u64("window_id").or(resolved_window_id);- let xid = xid_opt.unwrap_or(0);+ let xid_opt = Some(xid);let delivery = crate::input::delivery::DeliveryMode::from_args(&args);let cursor_id = resolve_cursor_key(&args);position_named_session_keyboard_cursor(&self.state, &args, pid, xid, Some(idx), None, true)@@ -8940,22 +8890,24 @@ impl Tool for SetValueTool {"{ax_error}; the keyboard fallback needs {}",if wayland {"an X11 session"- } else if delivery.is_foreground() {- "an X11 session"} else {"the focus-free real-input route (a writable /dev/uinput), or delivery_mode:\"foreground\""});+ let mut structured = json!({+ "code": "set_value_unavailable",+ "detail": detail,+ "effect": "none",+ });+ // Only X11 can run the foreground keyboard fallback.+ if !wayland {+ structured["escalation"] = json!({ "recommended": "foreground", "reason": "click the field and type the value with delivery_mode:\"foreground\"" });+ }return ToolResult::error(format!("set_value: element [{idx}] has no accessibility write route and no keyboard \fallback is available: {detail}."))- .with_structured(json!({- "code": "set_value_unavailable",- "detail": detail,- "effect": "none",- "escalation": { "recommended": "foreground", "reason": "click the field and type the value with delivery_mode:\"foreground\"" },- }));+ .with_structured(structured);}let value_for_keys = value.clone();let typed = spawn_blocking_bounded(@@ -9209,11 +9161,9 @@ impl Tool for ScrollTool {"by":{"type":"string","enum":["line","page"]},"amount":{"type":"integer","minimum":1,"maximum":50},"window_id":{"type":"integer"},- "element_index": cua_driver_core::tool_schema::element_index_schema(),"element_token": cua_driver_core::tool_schema::element_token_schema(),- "snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),- "x":{"type":"number","description":"Window-local screenshot-pixel X of the scroll target. Pass with y and without element_index."},- "y":{"type":"number","description":"Window-local screenshot-pixel Y of the scroll target. Pass with x and without element_index."},+ "x":{"type":"number","description":"Window-local screenshot-pixel X of the scroll target. Pass with y and without element_token."},+ "y":{"type":"number","description":"Window-local screenshot-pixel Y of the scroll target. Pass with x and without element_token."},"scope":{"type":"string","enum":["window","desktop"],"default":"window"},"coordinate_frame": coordinate_frame_schema(),"delivery_mode": crate::input::delivery::delivery_mode_schema()@@ -9283,26 +9233,18 @@ impl Tool for ScrollTool {Ok(by) => by,Err(error) => return ToolResult::error(format!("Invalid scroll by: {error}")),};- // Surface 6: resolve element_token / element_index. The Linux- // scroll implementation today doesn't actually pre-focus the- // element (X11 scroll buttons go to the window root), but the- // token still needs to be accepted + validated so a stale- // token surfaces an error instead of silently no-op'ing.- let resolved = match self.state.element_cache.resolve_element_args(- pid as i32,- args.opt_u64("element_index").map(|v| v as usize),- args.opt_str("element_token").as_deref(),- args.opt_str("snapshot_id").as_deref(),- args.opt_u64("window_id"),- "scroll",- ) {+ // The Linux scroll implementation doesn't pre-focus the element (X11+ // scroll buttons go to the window root), but the token still needs to+ // be validated so a stale token surfaces an error instead of silently+ // no-op'ing.+ let resolved = match self.state.snapshots.resolve(pid as i32, &args) {Ok(r) => r,Err(e) => return e,};let xid_opt: Option<u64> = match &resolved {- cua_driver_core::element_token::ResolvedElement::Element { window_id, .. } => window_id- .map(|v| v as u64)- .or_else(|| args.opt_u64("window_id")),+ cua_driver_core::element_token::ResolvedElement::Element { window_id, .. } => {+ Some(*window_id)+ }cua_driver_core::element_token::ResolvedElement::None => args.opt_u64("window_id"),};@@ -9404,7 +9346,7 @@ impl Tool for ScrollTool {};if pixel_target.is_some() && resolved_element_index.is_some() {return ToolResult::error(- "Pass either element_index (ax) or x,y (px) to scroll, not both.",+ "Pass either element_token (ax) or x,y (px) to scroll, not both.",);}@@ -9764,11 +9706,11 @@ impl Tool for DoubleClickTool {fn def(&self) -> &ToolDef {DCLICK_DEF.get_or_init(|| ToolDef {name: "double_click".into(),- description: "Double-click at (x,y) or an element_index (AT-SPI bounds). Background \+ description: "Double-click at (x,y) or an element_token (AT-SPI bounds). Background \delivery on X11 sends real button events from the session's virtual master pointer \(path mpx_pointer); a point covered by another application's window is refused \(target_occluded), one covered by this app's own dialog is retargeted to it \- (retargeted_to). No focus steal. Provide either (window_id + x/y) or (pid + element_index). \+ (retargeted_to). No focus steal. Provide either (window_id + x/y) or (pid + element_token). \After a zoom call, pass from_zoom=true to auto-translate zoom-image coords.".into(),input_schema: json!({"type":"object","required":["pid"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),@@ -9778,9 +9720,7 @@ impl Tool for DoubleClickTool {"x":{"type":"number","description":"Window-local pixel X of the target window's own get_window_state screenshot (0..screenshot_width). For get_desktop_state pixels pass scope:\"desktop\" (or coordinate_frame:\"desktop\")."},"y":{"type":"number","description":"Window-local pixel Y of the target window's own get_window_state screenshot (0..screenshot_height); see x."},"coordinate_frame": coordinate_frame_schema(),- "element_index": cua_driver_core::tool_schema::element_index_schema(),"element_token": cua_driver_core::tool_schema::element_token_schema(),- "snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),"from_zoom":{"type":"boolean","description":"Set true after a zoom call to auto-translate zoom-image pixel coordinates back to full-window space."},"delivery_mode": crate::input::delivery::delivery_mode_schema()},"additionalProperties":false}),@@ -9817,15 +9757,7 @@ impl Tool for DoubleClickTool {.invoke(args).await;}- // Surface 6: element_token / element_index precedence.- let resolved = match self.state.element_cache.resolve_element_args(- pid as i32,- args.opt_u64("element_index").map(|v| v as usize),- args.opt_str("element_token").as_deref(),- args.opt_str("snapshot_id").as_deref(),- args.opt_u64("window_id"),- "double_click",- ) {+ let resolved = match self.state.snapshots.resolve(pid as i32, &args) {Ok(r) => r,Err(e) => return e,};@@ -9836,9 +9768,9 @@ impl Tool for DoubleClickTool {cua_driver_core::element_token::ResolvedElement::None => None,};let window_id_resolved: Option<u64> = match &resolved {- cua_driver_core::element_token::ResolvedElement::Element { window_id, .. } => args- .opt_u64("window_id")- .or_else(|| window_id.map(|v| v as u64)),+ cua_driver_core::element_token::ResolvedElement::Element { window_id, .. } => {+ Some(*window_id)+ }cua_driver_core::element_token::ResolvedElement::None => args.opt_u64("window_id"),};if let Some(idx) = elem_idx_resolved {@@ -9916,7 +9848,7 @@ impl Tool for DoubleClickTool {}let xid = match window_id_resolved {Some(v) => v,- None => return ToolResult::error("Provide either element_index or window_id + x/y."),+ None => return ToolResult::error("Provide either element_token or window_id + x/y."),};let desktop_frame = desktop_frame_requested(&args);let from_zoom = args.bool_or("from_zoom", false);@@ -10048,7 +9980,7 @@ impl Tool for RightClickTool {fn def(&self) -> &ToolDef {RCLICK_DEF.get_or_init(|| ToolDef {name: "right_click".into(),- description: "Right-click at (x,y) or an element_index (AT-SPI bounds). Background \+ description: "Right-click at (x,y) or an element_token (AT-SPI bounds). Background \delivery on X11 sends real button events from the session's virtual master pointer \(path mpx_pointer); a point covered by another application's window is refused \(target_occluded), one covered by this app's own dialog is retargeted to it \@@ -10056,7 +9988,7 @@ impl Tool for RightClickTool {window-local pixels, the result reports window_point / screen_point). No focus \steal. When a context menu opens, the result names it (`popup: {window_id, bounds, \title}`): call get_window_state(pid, window_id=<that id>) to index its menu items \- and click them by element_index. Provide either (window_id + x/y) or (pid + element_index). \+ and click them by element_token. Provide either (window_id + x/y) or (pid + element_token). \After a zoom call, pass from_zoom=true to auto-translate zoom-image coords.".into(),input_schema: json!({"type":"object","required":["pid"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),@@ -10066,9 +9998,7 @@ impl Tool for RightClickTool {"x":{"type":"number","description":"Window-local pixel X of the target window's own get_window_state screenshot (0..screenshot_width). For get_desktop_state pixels pass scope:\"desktop\" (or coordinate_frame:\"desktop\")."},"y":{"type":"number","description":"Window-local pixel Y of the target window's own get_window_state screenshot (0..screenshot_height); see x."},"coordinate_frame": coordinate_frame_schema(),- "element_index": cua_driver_core::tool_schema::element_index_schema(),"element_token": cua_driver_core::tool_schema::element_token_schema(),- "snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),"modifier": cua_driver_core::tool_schema::modifier_schema(),"from_zoom":{"type":"boolean","description":"Set true after a zoom call to auto-translate zoom-image pixel coordinates back to full-window space."},"delivery_mode": crate::input::delivery::delivery_mode_schema()@@ -10106,15 +10036,7 @@ impl Tool for RightClickTool {.invoke(args).await;}- // Surface 6: element_token / element_index precedence.- let resolved = match self.state.element_cache.resolve_element_args(- pid as i32,- args.opt_u64("element_index").map(|v| v as usize),- args.opt_str("element_token").as_deref(),- args.opt_str("snapshot_id").as_deref(),- args.opt_u64("window_id"),- "right_click",- ) {+ let resolved = match self.state.snapshots.resolve(pid as i32, &args) {Ok(r) => r,Err(e) => return e,};@@ -10125,9 +10047,9 @@ impl Tool for RightClickTool {cua_driver_core::element_token::ResolvedElement::None => None,};let window_id_resolved: Option<u64> = match &resolved {- cua_driver_core::element_token::ResolvedElement::Element { window_id, .. } => args- .opt_u64("window_id")- .or_else(|| window_id.map(|v| v as u64)),+ cua_driver_core::element_token::ResolvedElement::Element { window_id, .. } => {+ Some(*window_id)+ }cua_driver_core::element_token::ResolvedElement::None => args.opt_u64("window_id"),};if let Some(idx) = elem_idx_resolved {@@ -10205,7 +10127,7 @@ impl Tool for RightClickTool {}let xid = match window_id_resolved {Some(v) => v,- None => return ToolResult::error("Provide either element_index or window_id + x/y."),+ None => return ToolResult::error("Provide either element_token or window_id + x/y."),};let desktop_frame = desktop_frame_requested(&args);let from_zoom = args.bool_or("from_zoom", false);@@ -13021,7 +12943,7 @@ impl Tool for ZoomTool {screenshot pixels, with 20% padding. Output is at most 500 px wide.\n\n\After a zoom, pass from_zoom=true to click/type_text to auto-translate \coordinates back to full-window space. Coordinate actions return \- `screenshot_context_missing` when the latest snapshot does not contain a \+ `screenshot_context_missing` when no current snapshot contains a \screenshot owned by this session. `from_zoom` actions return \`zoom_context_missing` when the zoom was never created or was replaced; call \`get_window_state`, then `zoom`, again on the same connection.".into(),@@ -13051,7 +12973,7 @@ impl Tool for ZoomTool {},};let session_id = args.opt_str("_session_id");- let (pid, screenshot) = match self.state.element_cache.screenshot_context_for_zoom(+ let (pid, screenshot) = match self.state.snapshots.screenshot_context_for_zoom(requested_pid,xid,session_id.as_deref(),@@ -13098,8 +13020,7 @@ impl Tool for ZoomTool {match result {Ok(Ok(crop)) => {- if let Err(refusal) = state.zoom_registry.set_if_current(- &state.element_cache,+ if let Err(refusal) = state.snapshots.set_zoom(pid,session_id.as_deref(),ZoomContext {@@ -13157,7 +13078,6 @@ impl Tool for TypeTextCharsTool {"window_id":{"type":"integer"},"text":{"type":"string"},"delay_ms":{"type":"integer","description":"Milliseconds between chars (default 30)."},- "element_index": cua_driver_core::tool_schema::element_index_schema(),"type_chars_only":{"type":"boolean","description":"Skip element focus, type directly. Default false."}},"additionalProperties":false}),@@ -13979,10 +13899,7 @@ pub fn build_registry_with_provider(}state_for_session_end- .zoom_registry- .retire_session(session_id);- state_for_session_end- .element_cache+ .snapshots.retire_session_screenshots(session_id);cursor_registry.remove(session_id);crate::overlay::remove_cursor(session_id.to_owned());diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/stubs.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/stubs.rsindex bc8a05e093..76a2802ba8 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/stubs.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/stubs.rs@@ -98,7 +98,7 @@ stub_tool!("get_window_state","Walk a running app's AT-SPI tree and return BOTH the element tree AND a \screenshot — ground on both and cross-check (the tree lies on some surfaces). \- Choose the modality at ACTION time: an element ax action (element_index) or an \+ Choose the modality at ACTION time: an element ax action (element_token) or an \element px action (x,y) off the screenshot. capture_mode is deprecated and ignored.",serde_json::json!({"type":"object","required":["pid","window_id"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"window_id":{"type":"integer"},"query":{"type":"string"},"include_screenshot":{"type":"boolean","description":"Default true — returns a grounding screenshot alongside the tree. Set false to skip the grab and return tree only (the cheap path for re-indexing before an element ax action)."},"capture_mode": cua_driver_core::capture_mode::capture_mode_schema()},"additionalProperties":false}));@@ -119,16 +119,16 @@ stub_tool!(click_m,ClickTool,"click",- "Click at (x, y) or on an AT-SPI element by element_index + window_id.",- serde_json::json!({"type":"object","required":[],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"x":{"type":"number"},"y":{"type":"number"},"modifier": cua_driver_core::tool_schema::modifier_schema(),"from_zoom":{"type":"boolean"}},"additionalProperties":false})+ "Click at (x, y) or on an AT-SPI element by element_token.",+ serde_json::json!({"type":"object","required":[],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"window_id":{"type":"integer"},"element_token": cua_driver_core::tool_schema::element_token_schema(),"x":{"type":"number"},"y":{"type":"number"},"modifier": cua_driver_core::tool_schema::modifier_schema(),"from_zoom":{"type":"boolean"}},"additionalProperties":false}));stub_tool!(double_click_m,DoubleClickTool,"double_click",- "Double-click at (x, y) or on an AT-SPI element by element_index + window_id.",- serde_json::json!({"type":"object","required":["pid"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"x":{"type":"number"},"y":{"type":"number"},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema()},"additionalProperties":false})+ "Double-click at (x, y) or on an AT-SPI element by element_token.",+ serde_json::json!({"type":"object","required":["pid"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"x":{"type":"number"},"y":{"type":"number"},"window_id":{"type":"integer"},"element_token": cua_driver_core::tool_schema::element_token_schema()},"additionalProperties":false}));stub_tool!(@@ -136,7 +136,7 @@ stub_tool!(RightClickTool,"right_click","Right-click (AT-SPI action on element, or synthesized event at x,y).",- serde_json::json!({"type":"object","required":["pid"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"window_id":{"type":"integer"},"x":{"type":"number"},"y":{"type":"number"},"modifier": cua_driver_core::tool_schema::modifier_schema()},"additionalProperties":false})+ serde_json::json!({"type":"object","required":["pid"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"element_token": cua_driver_core::tool_schema::element_token_schema(),"window_id":{"type":"integer"},"x":{"type":"number"},"y":{"type":"number"},"modifier": cua_driver_core::tool_schema::modifier_schema()},"additionalProperties":false}));stub_tool!(@@ -144,7 +144,7 @@ stub_tool!(TypeTextTool,"type_text","Insert text into the target pid via AT-SPI SetTextContents or XSendEvent keystrokes.",- serde_json::json!({"type":"object","required":["pid","text"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"text":{"type":"string"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"window_id":{"type":"integer"},"x":{"type":"number","description":"Screenshot-pixel X of the field to type into — the element px action form: pixel-click there to focus, then type. Pass with y, no element_index."},"y":{"type":"number","description":"Screenshot-pixel Y of the field (see x)."}},"additionalProperties":false})+ serde_json::json!({"type":"object","required":["pid","text"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"text":{"type":"string"},"element_token": cua_driver_core::tool_schema::element_token_schema(),"window_id":{"type":"integer"},"x":{"type":"number","description":"Screenshot-pixel X of the field to type into — the element px action form: pixel-click there to focus, then type. Pass with y, no element_token."},"y":{"type":"number","description":"Screenshot-pixel Y of the field (see x)."}},"additionalProperties":false}));stub_tool!(@@ -152,7 +152,7 @@ stub_tool!(TypeTextCharsTool,"type_text_chars","Type text character-by-character with configurable per-character delay.",- serde_json::json!({"type":"object","required":["pid","text"],"properties":{"pid":{"type":"integer"},"text":{"type":"string"},"delay_ms":{"type":"integer"},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema()},"additionalProperties":false})+ serde_json::json!({"type":"object","required":["pid","text"],"properties":{"pid":{"type":"integer"},"text":{"type":"string"},"delay_ms":{"type":"integer"},"window_id":{"type":"integer"},"element_token": cua_driver_core::tool_schema::element_token_schema()},"additionalProperties":false}));stub_tool!(@@ -160,7 +160,7 @@ stub_tool!(PressKeyTool,"press_key","Press and release a single key delivered directly to the target pid. No focus steal.",- serde_json::json!({"type":"object","required":["pid","key"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"key":{"type":"string"},"modifiers":{"type":"array","items":{"type":"string"}},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"x":{"type":"number","description":"Screenshot-pixel X — the element px action form: pixel-click there to focus, then send the key. Pass with y, no element_index."},"y":{"type":"number","description":"Screenshot-pixel Y (see x)."}},"additionalProperties":false})+ serde_json::json!({"type":"object","required":["pid","key"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"key":{"type":"string"},"modifiers":{"type":"array","items":{"type":"string"}},"window_id":{"type":"integer"},"element_token": cua_driver_core::tool_schema::element_token_schema(),"x":{"type":"number","description":"Screenshot-pixel X — the element px action form: pixel-click there to focus, then send the key. Pass with y, no element_token."},"y":{"type":"number","description":"Screenshot-pixel Y (see x)."}},"additionalProperties":false}));stub_tool!(@@ -176,12 +176,12 @@ stub_tool!(SetValueTool,"set_value","Set the value of an AT-SPI element (text field, dropdown, checkbox).",- serde_json::json!({"type":"object","required":["pid","value"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"value":{"type":"string"}},"additionalProperties":false})+ serde_json::json!({"type":"object","required":["pid","value"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"window_id":{"type":"integer"},"element_token": cua_driver_core::tool_schema::element_token_schema(),"value":{"type":"string"}},"additionalProperties":false}));stub_tool!(scroll_m, ScrollTool, "scroll","Scroll the target pid's focused region. direction required; by defaults to line, amount defaults to 3.",- serde_json::json!({"type":"object","required":["direction"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"cursor_id":{"type":"string"},"pid":{"type":"integer"},"direction":{"type":"string","enum":["up","down","left","right"]},"by":{"type":"string","enum":["line","page"]},"amount":{"type":"integer","minimum":1,"maximum":50},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema()},"additionalProperties":false}));+ serde_json::json!({"type":"object","required":["direction"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"cursor_id":{"type":"string"},"pid":{"type":"integer"},"direction":{"type":"string","enum":["up","down","left","right"]},"by":{"type":"string","enum":["line","page"]},"amount":{"type":"integer","minimum":1,"maximum":50},"window_id":{"type":"integer"},"element_token": cua_driver_core::tool_schema::element_token_schema()},"additionalProperties":false}));stub_tool!(screenshot_m, ScreenshotTool, "screenshot","Capture a screenshot. Without window_id captures the full display. Supports png and jpeg formats.",diff --git a/libs/cua-driver/rust/crates/platform-macos/src/ax/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/ax/mod.rsindex 7640808f6f..c521a21870 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/ax/mod.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/ax/mod.rs@@ -17,14 +17,14 @@//! - 2-space indent per depth levelpub mod bindings;-pub mod cache;pub mod enablement;pub mod exact_target;pub mod launch;+pub mod snapshot;pub mod tree;pub mod window_scope;-pub use cache::ElementCache;+pub use snapshot::Snapshots;pub use tree::{walk_tree, walk_tree_bounded, AXNode, TreeWalkResult, DEFAULT_MAX_DEPTH, DEFAULT_MAX_ELEMENTS,};diff --git a/libs/cua-driver/rust/crates/platform-macos/src/ax/cache.rs b/libs/cua-driver/rust/crates/platform-macos/src/ax/snapshot.rssimilarity index 84%rename from libs/cua-driver/rust/crates/platform-macos/src/ax/cache.rsrename to libs/cua-driver/rust/crates/platform-macos/src/ax/snapshot.rsindex e660c046fb..a780080c8b 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/ax/cache.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/ax/snapshot.rs@@ -1,7 +1,7 @@use super::bindings::AXUIElementRef;use super::tree::AXNode;use core_foundation::base::{CFRelease, CFRetain, CFTypeRef};-use cua_driver_core::element_cache::{ElementCacheCore, SnapshotPayload};+use cua_driver_core::snapshot_store::{SnapshotPayload, SnapshotStore};pub struct RetainedElement(usize);@@ -32,11 +32,11 @@ impl Drop for RetainedElement {}}-pub struct CachedSnapshot {+pub struct AxSnapshot {pub elements: Vec<usize>,}-impl CachedSnapshot {+impl AxSnapshot {pub fn from_nodes(nodes: &[AXNode]) -> Self {Self {elements: nodes@@ -48,7 +48,7 @@ impl CachedSnapshot {}}-impl SnapshotPayload for CachedSnapshot {+impl SnapshotPayload for AxSnapshot {type Element = RetainedElement;fn len(&self) -> usize {self.elements.len()@@ -60,7 +60,7 @@ impl SnapshotPayload for CachedSnapshot {}}-impl Drop for CachedSnapshot {+impl Drop for AxSnapshot {fn drop(&mut self) {for ptr in &self.elements {if *ptr != 0 {@@ -70,7 +70,7 @@ impl Drop for CachedSnapshot {}}-pub type ElementCache = ElementCacheCore<CachedSnapshot>;+pub type Snapshots = SnapshotStore<AxSnapshot>;#[cfg(test)]mod tests {@@ -79,15 +79,11 @@ mod tests {use core_foundation::string::CFString;use cua_driver_core::element_token::{token_for, ResolvedElement};- fn resolve(cache: &ElementCache, snapshot: u32, index: usize) -> Option<RetainedElement> {+ fn resolve(cache: &Snapshots, snapshot: u32, index: usize) -> Option<RetainedElement> {match cache- .resolve_element_args(+ .resolve(1,- None,- Some(&token_for(snapshot, index)),- None,- Some(2),- "click",+ &serde_json::json!({ "element_token": token_for(snapshot, index) }),).ok()?{@@ -96,9 +92,9 @@ mod tests {}}- fn payload(ptr: usize) -> CachedSnapshot {+ fn payload(ptr: usize) -> AxSnapshot {unsafe { CFRetain(ptr as CFTypeRef) };- CachedSnapshot {+ AxSnapshot {elements: vec![ptr],}}@@ -108,12 +104,12 @@ mod tests {let value = CFString::new("cua-driver-uaf-test-element-placeholder");let ptr = value.as_concrete_TypeRef() as usize;let base = unsafe { CFGetRetainCount(ptr as CFTypeRef) };- let cache = ElementCache::new();+ let cache = Snapshots::new();let snapshot = cache.publish(1, 2, payload(ptr));assert_eq!(unsafe { CFGetRetainCount(ptr as CFTypeRef) }, base + 1);let guard = resolve(&cache, snapshot, 0).unwrap();assert_eq!(unsafe { CFGetRetainCount(ptr as CFTypeRef) }, base + 2);- cache.publish(1, 2, CachedSnapshot::from_nodes(&[]));+ cache.publish(1, 2, AxSnapshot::from_nodes(&[]));assert_eq!(unsafe { CFGetRetainCount(ptr as CFTypeRef) }, base + 1);assert!(resolve(&cache, snapshot, 0).is_none());drop(guard);@@ -125,7 +121,7 @@ mod tests {let value = CFString::new("cua-driver-invariant-admitted-native-work");let ptr = value.as_concrete_TypeRef() as usize;let base = unsafe { CFGetRetainCount(ptr as CFTypeRef) };- let cache = ElementCache::new();+ let cache = Snapshots::new();let snapshot = cache.publish(1, 2, payload(ptr));let guard = resolve(&cache, snapshot, 0).unwrap();let (finish_tx, finish_rx) = std::sync::mpsc::channel();@@ -144,9 +140,9 @@ mod tests {#[test]fn missing_index_returns_none() {- let cache = ElementCache::new();+ let cache = Snapshots::new();assert!(resolve(&cache, 0, 0).is_none());- let snapshot = cache.publish(1, 2, CachedSnapshot::from_nodes(&[]));+ let snapshot = cache.publish(1, 2, AxSnapshot::from_nodes(&[]));assert!(resolve(&cache, snapshot, 0).is_none());assert!(resolve(&cache, snapshot, 5).is_none());}@@ -158,7 +154,7 @@ mod tests {let original_ptr = original.as_concrete_TypeRef() as usize;let replacement_ptr = replacement.as_concrete_TypeRef() as usize;let base = unsafe { CFGetRetainCount(replacement_ptr as CFTypeRef) };- let cache = ElementCache::new();+ let cache = Snapshots::new();let snapshot = cache.publish(1, 2, payload(original_ptr));let prepared = payload(replacement_ptr);assert_eq!(resolve(&cache, snapshot, 0).unwrap().as_ptr(), original_ptr);diff --git a/libs/cua-driver/rust/crates/platform-macos/src/recording_hooks.rs b/libs/cua-driver/rust/crates/platform-macos/src/recording_hooks.rsindex 9158903a82..bb28e4b64f 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/recording_hooks.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/recording_hooks.rs@@ -1,13 +1,12 @@use crate::ax::bindings::{element_screen_center, AXUIElementRef};-use crate::ax::cache::{CachedSnapshot, ElementCache};-use cua_driver_core::element_cache::{current_runtime_cache, register_runtime_cache};+use crate::ax::snapshot::{AxSnapshot, Snapshots};use cua_driver_core::element_token::ResolvedElement;-use cua_driver_core::tool_args::ArgsExt;+use cua_driver_core::snapshot_store::{current_runtime_store, register_runtime_store};use serde_json::Value;use std::sync::Arc;-pub fn set_element_cache(cache: Arc<ElementCache>) {- register_runtime_cache(&cache);+pub fn set_snapshots(cache: Arc<Snapshots>) {+ register_runtime_store(&cache);}/// Per-turn application state for trajectory recording. The walk shares the@@ -34,7 +33,7 @@ pub fn app_state_json_for(crate::ax::tree::DEFAULT_MAX_ELEMENTS,),);- let _payload = CachedSnapshot::from_nodes(&result.nodes);+ let _payload = AxSnapshot::from_nodes(&result.nodes);let element_count = result.nodes.iter()@@ -55,21 +54,10 @@ pub fn element_window_local_xy(args: &Value,capture_point: bool,) -> Option<(u64, Option<(f64, f64)>)> {- let cache = current_runtime_cache::<CachedSnapshot>()?;- let target = cache- .resolve_element_args(- i32::try_from(pid).ok()?,- args.opt_u64("element_index").map(|index| index as usize),- args.get("element_token").and_then(Value::as_str),- args.get("snapshot_id").and_then(Value::as_str),- args.opt_u64("window_id"),- "recording",- )- .ok()?;+ let cache = current_runtime_store::<AxSnapshot>()?;+ let target = cache.resolve(i32::try_from(pid).ok()?, args).ok()?;let ResolvedElement::Element {- window_id: Some(window_id),- element,- ..+ window_id, element, ..} = targetelse {return None;diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rsindex fcf8bd969e..7996734a99 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs@@ -2,7 +2,7 @@//!//! Two addressing modes://!-//! * **AX path** (`element_index` + `window_id`): performs AXAction on the cached+//! * **AX path** (`element_token`): performs AXAction on the cached//! element. Fires via AX RPC — the target app never needs to be frontmost.//! Extra behaviors vs. the naive dispatch://! - AXTextField / AXTextArea: 800 ms post-click delay for WebKit DOM focus settle.@@ -183,7 +183,7 @@ fn def() -> &'static ToolDef {`x, y` only when the target is a canvas / video / WebGL / custom-drawn surface \that doesn't appear in the AX tree.\n\n\Two addressing modes:\n\n\- - element_token, or element_index + snapshot_id (from get_window_state): AX action path. \+ - element_token (from get_window_state): AX action path. \Works on backgrounded/hidden windows. No cursor move, no focus steal. \The snapshot cache is scoped per (pid, window_id) and is replaced by the \next snapshot of the same window — re-snapshot every turn before clicking.\n\n\@@ -212,10 +212,8 @@ fn def() -> &'static ToolDef {"properties": {"session": { "type": "string", "description": "For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session." },"pid": { "type": "integer", "description": "Target process ID." },- "window_id": { "type": "integer", "description": "Target window ID. Required for element_index. Optional when element_token is supplied (the token carries it)." },- "element_index": cua_driver_core::tool_schema::element_index_schema(),+ "window_id": { "type": "integer", "description": "Target window ID. Omit when element_token is supplied (the token carries it)." },"element_token": cua_driver_core::tool_schema::element_token_schema(),- "snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),"capture_id": { "type": "string", "description": "Optional immutable source capture ID returned by get_window_state or get_desktop_state. With x,y, Driver atomically admits and consumes that exact capture before dispatch; stale, mismatched, or out-of-bounds captures are refused without fallback." },"x": { "type": "number", "description": "X in screenshot pixels. A window target uses the get_window_state PNG; a desktop target uses the native get_desktop_state PNG. The driver reverses Retina backing scale and any window-image downscale." },"y": { "type": "number", "description": "Y in screenshot pixels from the image selected by target." },@@ -242,7 +240,7 @@ fn def() -> &'static ToolDef {"delivery_mode": {"type": "string","enum": ["background", "foreground"],- "description": "Best-effort-background ladder rung (default \"background\"). \"background\": perform the AX action or post the CGEvent without fronting. \"foreground\": briefly front the window, act, let transient UI settle, then restore the prior frontmost app. Requires window_id. Modified clicks require \"foreground\" so macOS observes physical modifier-key state. A generic click has no independent postcondition read-back, except selection of list-like AX rows whose AXSelected state can be confirmed; otherwise confirm the effect from a fresh state snapshot. Use the agent loop: background AX (element_index) → snapshot → background pixel (x/y) → snapshot → delivery_mode:\"foreground\"."+ "description": "Best-effort-background ladder rung (default \"background\"). \"background\": perform the AX action or post the CGEvent without fronting. \"foreground\": briefly front the window, act, let transient UI settle, then restore the prior frontmost app. Requires window_id. Modified clicks require \"foreground\" so macOS observes physical modifier-key state. A generic click has no independent postcondition read-back, except selection of list-like AX rows whose AXSelected state can be confirmed; otherwise confirm the effect from a fresh state snapshot. Use the agent loop: background AX (element_token) → snapshot → background pixel (x/y) → snapshot → delivery_mode:\"foreground\"."},"scope": {"type": "string",@@ -413,21 +411,8 @@ impl Tool for ClickTool {// the calling session's cursor, not the shared "default" one.let cursor_key = super::cursor_tools::resolve_cursor_key(&args);- // Surface 6: resolve element_token / element_index precedence- // BEFORE the pixel-path fallback. Token wins on disagreement; a- // stale token returns an explicit error instead of silently- // falling back to the integer (Surface 6 hard constraint).- let element_token_arg = args.opt_str("element_token");let window_id_arg = args.opt_u64("window_id");- let element_index_arg = args.opt_u64("element_index").map(|v| v as usize);- let resolved = match self.state.element_cache.resolve_element_args(- pid,- element_index_arg,- element_token_arg.as_deref(),- args.opt_str("snapshot_id").as_deref(),- window_id_arg,- "click",- ) {+ let resolved = match self.state.snapshots.resolve(pid, &args) {Ok(r) => r,Err(e) => return e,};@@ -550,7 +535,7 @@ impl Tool for ClickTool {Some(c) => c,None => {return ToolResult::error(- "click(button=middle) on element_index: could not resolve element \+ "click(button=middle) on element_token: could not resolve element \center for the pixel-middle-click fallback. Pass x, y directly.",)}@@ -1300,9 +1285,7 @@ impl Tool for ClickTool {Err(e) => ToolResult::error(format!("Task error: {e}")),}} else {- ToolResult::error(- "Provide either (element_index + window_id) or (x + y). pid is always required.",- )+ ToolResult::error("Provide either element_token or (x + y). pid is always required.")}}}@@ -1517,7 +1500,7 @@ fn perform_ax_click(summary.push_str("\n\n⚠️ This is a popup/select button. The native macOS menu closes \immediately when the window is in the background. Do NOT use click \- again — instead, use:\n set_value(pid, window_id, element_index, value)\n\+ again — instead, use:\n set_value(pid, element_token, value)\n\Available options: [",);summary.push_str(&opt_list);diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rsindex 4e8bf84ec1..33805b4b43 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rs@@ -38,8 +38,8 @@ fn def() -> &'static ToolDef {DEF.get_or_init(|| ToolDef {name: "double_click".into(),description:- "Double-click at (x, y) or on an AX element identified by element_index + window_id.\n\n\- AX path (element_index provided): performs `AXOpen` when the element advertises it \+ "Double-click at (x, y) or on an AX element identified by element_token.\n\n\+ AX path (element_token provided): performs `AXOpen` when the element advertises it \(Finder items, openable list rows/cells); otherwise resolves the element's on-screen \center and falls back to a pixel double-click there.\n\n\Pixel path (x, y provided): two down/up pairs ~80 ms apart at the given coordinates."@@ -52,10 +52,8 @@ fn def() -> &'static ToolDef {"pid": { "type": "integer" },"x": { "type": "number", "description": "Screen X coordinate (pixel path)." },"y": { "type": "number", "description": "Screen Y coordinate (pixel path)." },- "window_id": { "type": "integer", "description": "CGWindowID. Required when element_index is used. Optional when element_token is supplied (the token carries it)." },- "element_index": cua_driver_core::tool_schema::element_index_schema(),+ "window_id": { "type": "integer", "description": "CGWindowID. Omit when element_token is supplied (the token carries it)." },"element_token": cua_driver_core::tool_schema::element_token_schema(),- "snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),"delivery_mode": cua_driver_core::tool_schema::delivery_mode_schema()},"additionalProperties": false@@ -84,19 +82,8 @@ impl Tool for DoubleClickTool {// background CGEvents), via the same skylight assist click uses.let delivery_mode = super::DeliveryMode::parse(args.opt_str("delivery_mode").as_deref());let cursor_key = super::cursor_tools::resolve_cursor_key(&args);- // Surface 6: token / index precedence — see click.rs for the- // canonical comment.- let element_token_arg = args.opt_str("element_token");let window_id_arg = args.opt_u64("window_id");- let element_index_arg = args.opt_u64("element_index").map(|v| v as usize);- let resolved = match self.state.element_cache.resolve_element_args(- pid,- element_index_arg,- element_token_arg.as_deref(),- args.opt_str("snapshot_id").as_deref(),- window_id_arg,- "double_click",- ) {+ let resolved = match self.state.snapshots.resolve(pid, &args) {Ok(r) => r,Err(e) => return e,};@@ -162,11 +149,7 @@ impl Tool for DoubleClickTool {// ── Pixel path ───────────────────────────────────────────────────────let mut cx = match args.get("x").and_then(|v| v.as_f64()) {Some(v) => v,- None => {- return ToolResult::error(- "Either element_index + window_id or x + y must be provided.",- )- }+ None => return ToolResult::error("Either element_token or x + y must be provided."),};let mut cy = match args.get("y").and_then(|v| v.as_f64()) {Some(v) => v,diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rsindex 1635189fff..ffee395396 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs@@ -30,10 +30,11 @@ fn def() -> &'static ToolDef {description: "Walk a running app's AX tree and return BOTH a structured \`elements` array (preferred) AND a Markdown rendering of the same tree \(back-compat). Every actionable element is tagged with [element_index N] \- in the markdown and as `element_index` in the structured array — pass \- those indices to click, type_text, press_key, etc.\n\n\+ in the markdown and as `element_index` in the structured array; pass \+ each element's `element_token` to click, type_text, press_key, etc.\n\n\INVARIANT: call get_window_state once per turn per (pid, window_id) before any \- element-indexed action. The index map is replaced by the next snapshot.\n\n\+ element action. The next snapshot of the window replaces this one, stales its \+ element tokens, and lists the replaced ids in `invalidated_snapshot_ids`.\n\n\PREFERRED CONSUMERS read `structuredContent.elements` (one entry per \indexed row with `element_index`, `role`, `label`, `value` (the \element's text/AXValue when present — use it to verify what a field \@@ -46,7 +47,7 @@ fn def() -> &'static ToolDef {both and cross-check (the tree lies on some surfaces: Electron \echo-confirms, Catalyst null values, virtualized off-viewport rows \with `h:1` frames). You choose the modality at ACTION time, not here: \- an element ax action (pass `element_index`/`element_token` → the \+ an element ax action (pass `element_token` → the \accessibility rung) or an element px action (pass `x`,`y` → the pixel \rung, read straight off this screenshot). `capture_mode` is deprecated \and ignored. Pass `include_screenshot:false` to skip the grab and get \@@ -312,7 +313,7 @@ impl Tool for GetWindowStateTool {max_depth,cua_driver_core::walk_budget::WalkBudget::new(timeout_ms, max_elements),);- let payload = crate::ax::cache::CachedSnapshot::from_nodes(&tree.nodes);+ let payload = crate::ax::snapshot::AxSnapshot::from_nodes(&tree.nodes);(tree, payload)});// A launching app is waited on for up to `timeout_ms` before the@@ -349,9 +350,9 @@ impl Tool for GetWindowStateTool {// this tool never does — so treat that as resolved.let scope_matched = window_scope.as_ref().is_none_or(|s| s.is_matched());- if !scope_matched && !observation_only {- self.state.element_cache.remove(pid, u64::from(window_id));- }+ let removed = (!scope_matched && !observation_only)+ .then(|| self.state.snapshots.remove(pid, u64::from(window_id)))+ .flatten();// Capture the screenshot and deliver it alongside the tree — the// grounding frame the agent cross-checks the (sometimes-lying) tree@@ -527,24 +528,20 @@ impl Tool for GetWindowStateTool {let snapshot_payload = prepared_snapshot.or_else(|| {screenshot_resize_scale.is_some()- .then(|| crate::ax::cache::CachedSnapshot::from_nodes(&[]))+ .then(|| crate::ax::snapshot::AxSnapshot::from_nodes(&[]))});- let snapshot_id = snapshot_payload+ let (snapshot_id, replaced) = snapshot_payload.filter(|_| scope_matched && !observation_only).and_then(|payload| {- self.state.element_cache.publish_for_session(+ self.state.snapshots.publish_for_session(pid,u64::from(window_id),payload,session_id.as_deref(),screenshot_resize_scale,)- });- if let Some(snapshot_id) = snapshot_id {- self.state- .zoom_registry- .retire_replaced(pid, u64::from(window_id), snapshot_id);- }+ })+ .unzip();let capture_id = match (snapshot_id, screenshot.as_ref()) {(Some(_), Some((png, _, width, height, native_width, native_height, _, _))) => {match self.state.capture_bindings.publish_window(@@ -624,9 +621,19 @@ impl Tool for GetWindowStateTool {// registered (unresolved window scope).if let Some(sid) = snapshot_id {structured["snapshot_id"] =- serde_json::json!(cua_driver_core::element_token::token_for(sid, 0)- .trim_end_matches(":0")- .to_string());+ serde_json::json!(cua_driver_core::element_token::format_snapshot_id(sid));+ }+ let invalidated: Vec<String> = removed+ .into_iter()+ .chain(replaced.into_iter().flatten())+ .map(cua_driver_core::element_token::format_snapshot_id)+ .collect();+ if !invalidated.is_empty() {+ content.push(Content::text(format!(+ "Invalidated snapshots {}: their element_tokens are stale.",+ invalidated.join(", ")+ )));+ structured["invalidated_snapshot_ids"] = serde_json::json!(invalidated);}if let Some(capture_id) = capture_id {structured["capture_id"] = serde_json::json!(capture_id);@@ -786,7 +793,7 @@ impl Tool for GetWindowStateTool {/// clicked by `element_index`. Both refusals name the exact retry, matching the/// remedy-in-the-refusal shape the rest of the driver uses.///-/// The owner pid is REPORTED, not followed: `element_cache`, the element-token+/// The owner pid is REPORTED, not followed: `snapshots`, the element-token/// registry and snapshot-owned screenshot transform are keyed on the caller-supplied pid, so/// walking under `owner_pid` while echoing the requested pid would hand back/// indices the caller replays against the wrong key. One retry with the named@@ -1490,14 +1497,14 @@ mod tests {#[test]fn build_elements_array_with_token_emits_element_token_per_row() {- let cache = crate::ax::cache::ElementCache::new();+ let cache = crate::ax::snapshot::Snapshots::new();let pid = 0x6abc_0001_i32;let nodes = vec![node(Some(0), "AXButton", Some("A"), 1, None, None, vec![]),node(Some(1), "AXButton", Some("B"), 1, None, None, vec![]),node(Some(2), "AXButton", Some("C"), 1, None, None, vec![]),];- let sid = cache.publish(pid, 9, crate::ax::cache::CachedSnapshot::from_nodes(&nodes));+ let sid = cache.publish(pid, 9, crate::ax::snapshot::AxSnapshot::from_nodes(&nodes));let entries = build_elements_array_with_token(&nodes, Some(sid));assert_eq!(entries.len(), 3);// Every entry must have BOTH fields (additive contract).@@ -1517,7 +1524,7 @@ mod tests {let idx = e["element_index"].as_u64().unwrap() as usize;let tok = e["element_token"].as_str().unwrap();let (resolved_idx, wid, _) = cache- .resolve_element_args(pid, None, Some(tok), None, None, "click")+ .resolve(pid, &serde_json::json!({ "element_token": tok })).expect("token must resolve").into_parts(None);assert_eq!(wid, Some(9));diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/hotkey.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/hotkey.rsindex c684dcdf8c..6a5fa5f958 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/hotkey.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/hotkey.rs@@ -76,9 +76,7 @@ fn def() -> &'static ToolDef {"type": "integer","description": "Target window. Required for delivery_mode:\"foreground\" (the NSMenu activation needs a window). Does NOT itself raise the window — raising is gated on delivery_mode."},- "element_index": cua_driver_core::tool_schema::element_index_schema(),"element_token": cua_driver_core::tool_schema::element_token_schema(),- "snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),"scope": { "type": "string", "enum": ["window", "desktop"], "default": "window", "description": "Use desktop with no pid/window_id to send the chord to the frontmost application." },"delivery_mode": cua_driver_core::tool_schema::delivery_mode_schema()},@@ -228,17 +226,8 @@ impl Tool for HotkeyTool {// Use the last non-modifier key; if there are multiple, treat earlier ones as extra keys.let key = non_modifiers.last().unwrap().clone();let key_display = raw_keys.join("+");- let element_token_arg = args.opt_str("element_token");let window_id_arg = args.opt_u64("window_id");- let element_index_arg = args.opt_u64("element_index").map(|v| v as usize);- let resolved = match self.state.element_cache.resolve_element_args(- pid,- element_index_arg,- element_token_arg.as_deref(),- args.opt_str("snapshot_id").as_deref(),- window_id_arg,- "hotkey",- ) {+ let resolved = match self.state.snapshots.resolve(pid, &args) {Ok(resolved) => resolved,Err(error) => return error,};@@ -257,7 +246,7 @@ impl Tool for HotkeyTool {let py = args.get("y").and_then(|value| value.as_f64());if px.is_some() && py.is_some() && element_index.is_some() {return ToolResult::error(- "Pass either element_index (ax) or x,y (px) to hotkey, not both.",+ "Pass either element_token (ax) or x,y (px) to hotkey, not both.",);}@@ -538,9 +527,7 @@ mod tests {let properties = def().input_schema["properties"].as_object().expect("hotkey properties");- for field in ["element_index", "element_token", "snapshot_id"] {- assert!(properties.contains_key(field), "missing {field} schema");- }+ assert!(properties.contains_key("element_token"));}#[test]diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rsindex b6ec2b0fa4..e5d6b5adde 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs@@ -47,7 +47,7 @@ use cua_driver_core::{use std::collections::HashMap;use std::sync::Arc;-use crate::{ax::cache::ElementCache, cursor::state::CursorRegistry};+use crate::{ax::snapshot::Snapshots, cursor::state::CursorRegistry};fn native_window_id(window_id: Option<u64>,@@ -147,9 +147,7 @@ pub use check_permissions::{PERMISSIONS_HOST_REQUEST_ARG,};-pub use cua_driver_core::element_cache::{- SnapshotBoundZoomContext as ZoomContext, SnapshotBoundZoomRegistry as ZoomRegistry,-};+pub use cua_driver_core::snapshot_store::ZoomContext;/// The shared per-call delivery mode; see [`cua_driver_core::delivery`].///@@ -220,7 +218,7 @@ async fn decide_background_window_action(decide_background_input, BackgroundInputDecision, ExactWindowTarget,};let element_guard =- element_ptr.map(|ptr| unsafe { crate::ax::cache::RetainedElement::retain(ptr) });+ element_ptr.map(|ptr| unsafe { crate::ax::snapshot::RetainedElement::retain(ptr) });let facts = match tokio::task::spawn_blocking(move || {let element_ptr = element_guard.as_ref().map(|guard| guard.as_ptr());crate::ax::exact_target::gather_background_facts(pid, window_id, element_ptr)@@ -617,9 +615,8 @@ impl Default for SessionConfigRegistry {/// Shared state passed to all tools.pub struct ToolState {- pub element_cache: Arc<ElementCache>,+ pub snapshots: Arc<Snapshots>,pub cursor_registry: Arc<CursorRegistry>,- pub zoom_registry: Arc<ZoomRegistry>,pub(crate) capture_bindings: Arc<capture_binding::MacCaptureBindings>,/// Global, disk-persisted config — the base layer and the only one the/// anonymous session / CLI writes.@@ -670,9 +667,8 @@ impl ToolState {host_bundle_id: Option<String>,) -> Self {Self {- element_cache: Arc::new(ElementCache::new()),+ snapshots: Arc::new(Snapshots::new()),cursor_registry: Arc::new(CursorRegistry::new()),- zoom_registry: Arc::new(ZoomRegistry::new()),capture_bindings: Arc::new(capture_binding::MacCaptureBindings::new(capture_service)),// Load persisted config from ~/.cua-driver/config.json so that// `cua-driver config set` changes carry over into MCP sessions.@@ -692,11 +688,14 @@ pub(super) fn screenshot_scale(pid: i32,window_id: Option<u32>,) -> Result<f64, cua_driver_core::protocol::ToolResult> {- state.element_cache.screenshot_scale_or_refusal(- pid,- window_id.map(u64::from),- args.get("_session_id").and_then(serde_json::Value::as_str),- )+ state+ .snapshots+ .screenshot_context(+ pid,+ window_id.map(u64::from),+ args.get("_session_id").and_then(serde_json::Value::as_str),+ )+ .map(|context| context.scale)}pub(super) fn zoom_context(@@ -705,8 +704,7 @@ pub(super) fn zoom_context(pid: i32,window_id: Option<u32>,) -> Result<ZoomContext, cua_driver_core::protocol::ToolResult> {- state.zoom_registry.resolve(- &state.element_cache,+ state.snapshots.zoom(pid,window_id.map(u64::from),args.get("_session_id").and_then(serde_json::Value::as_str),@@ -798,22 +796,20 @@ pub fn register_all(}// Share the element cache with the recording-hook layer so it can// resolve element_index → window-local screenshot coords for click.png.- crate::recording_hooks::set_element_cache(state.element_cache.clone());+ crate::recording_hooks::set_snapshots(state.snapshots.clone());// Drop a disconnecting session's config overrides + owned cursor on// `session_end`. The daemon fans the session id out to this hook;// recording ownership is handled separately on the core RecordingSession.{let session_config = state.session_config.clone();- let element_cache = state.element_cache.clone();- let zoom_registry = state.zoom_registry.clone();+ let snapshots = state.snapshots.clone();let cursor_registry = state.cursor_registry.clone();let capture_bindings = state.capture_bindings.clone();let registration =cua_driver_core::session::register_scoped_session_end_hook(move |session_id| {session_config.clear(session_id);- zoom_registry.retire_session(session_id);- element_cache.retire_session_screenshots(session_id);+ snapshots.retire_session_screenshots(session_id);capture_bindings.retire_session(session_id);// Per-session agent cursor: the session_id is the cursor key when// the caller gave no explicit cursor_id, so dropping it here bothdiff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/press_key.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/press_key.rsindex 5788bad5f3..d7c612e08f 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/press_key.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/press_key.rs@@ -184,7 +184,7 @@ fn def() -> &'static ToolDef {description: "Press and release a single key. Follows the same `delivery_mode` ladder as click/type_text \— it does NOT raise the window by default:\n\• `background` (default): post to the pid WITHOUT fronting/raising — the \- auth-message path (Chromium-safe). With element_index it focuses that AX \+ auth-message path (Chromium-safe). With element_token it focuses that AX \element first. `window_id` only targets; it does not raise.\n\• `foreground`: guard and briefly front the exact window, focus an addressed AX \element when supplied, send a genuine HID key transition so Chromium content, \@@ -209,10 +209,8 @@ fn def() -> &'static ToolDef {"description": "Modifier keys: cmd, shift, option/alt, ctrl, fn."},"window_id": { "type": "integer", "description": "Target window. Required for delivery_mode:\"foreground\". Does NOT itself raise the window — raising is gated on delivery_mode." },- "element_index": cua_driver_core::tool_schema::element_index_schema(),"element_token": cua_driver_core::tool_schema::element_token_schema(),- "snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),- "x": { "type": "number", "description": "Screenshot-pixel X — the element px action form: pixel-click there to focus, then send the key. Use when the key must go to a Chromium/Electron surface the AX path can't focus. Pass with y, no element_index." },+ "x": { "type": "number", "description": "Screenshot-pixel X — the element px action form: pixel-click there to focus, then send the key. Use when the key must go to a Chromium/Electron surface the AX path can't focus. Pass with y, no element_token." },"y": { "type": "number", "description": "Screenshot-pixel Y (see x)." },"scope": { "type": "string", "enum": ["window", "desktop"], "default": "window", "description": "Use desktop with no pid/window_id to send the key to the frontmost application." },"delivery_mode": cua_driver_core::tool_schema::delivery_mode_schema()@@ -270,18 +268,8 @@ impl Tool for PressKeyTool {Err(e) => return e,};let mut modifiers: Vec<String> = args.str_array("modifiers");- // Surface 6: element_token / element_index precedence resolution.- let element_token_arg = args.opt_str("element_token");let window_id_arg = args.opt_u64("window_id");- let element_index_arg = args.opt_u64("element_index").map(|v| v as usize);- let resolved = match self.state.element_cache.resolve_element_args(- pid,- element_index_arg,- element_token_arg.as_deref(),- args.opt_str("snapshot_id").as_deref(),- window_id_arg,- "press_key",- ) {+ let resolved = match self.state.snapshots.resolve(pid, &args) {Ok(r) => r,Err(e) => return e,};@@ -318,7 +306,7 @@ impl Tool for PressKeyTool {let py = args.get("y").and_then(|v| v.as_f64());if px.is_some() && py.is_some() && element_index.is_some() {return ToolResult::error(- "Pass either element_index (ax) or x,y (px) to press_key, not both.",+ "Pass either element_token (ax) or x,y (px) to press_key, not both.",);}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rsindex 70ed22ebb0..9af941d8be 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rs@@ -29,15 +29,15 @@ fn def() -> &'static ToolDef {name: "right_click".into(),description:"Right-click against a target pid. Two addressing modes:\n\n\- - `element_index` + `window_id` (from the last `get_window_state` snapshot) — \+ - `element_token` (from the last `get_window_state` snapshot) — \performs `AXShowMenu` on the cached element. Pure AX RPC, works on backgrounded / \hidden windows, no cursor move or focus steal. Requires a prior \`get_window_state(pid, window_id)` in this turn.\n\n\- `x`, `y` — synthesizes `rightMouseDown` / `rightMouseUp` CGEvent pair posted \to the pid. Driver converts image-pixel → screen-point internally. \`modifier` forces the CGEvent path (AX actions don't propagate modifier keys).\n\n\- Exactly one of `element_index` or (`x` AND `y`) must be provided. `pid` always \- required. `window_id` required when `element_index` is used."+ Exactly one of `element_token` or (`x` AND `y`) must be provided. `pid` always \+ required.".into(),input_schema: serde_json::json!({"type": "object",@@ -45,12 +45,10 @@ fn def() -> &'static ToolDef {"properties": {"session": { "type": "string", "description": "For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session." },"pid": { "type": "integer", "description": "Target process ID." },- "element_index": cua_driver_core::tool_schema::element_index_schema(),"element_token": cua_driver_core::tool_schema::element_token_schema(),- "snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),"window_id": {"type": "integer",- "description": "CGWindowID. Required when element_index is used. Optional when element_token is supplied (the token carries it)."+ "description": "CGWindowID. Omit when element_token is supplied (the token carries it)."},"x": {"type": "number",@@ -95,18 +93,8 @@ impl Tool for RightClickTool {let delivery_mode = super::DeliveryMode::parse(args.opt_str("delivery_mode").as_deref());let cursor_key = super::cursor_tools::resolve_cursor_key(&args);- // Surface 6: element_token / element_index precedence resolution.- let element_token_arg = args.opt_str("element_token");let window_id_arg = args.opt_u64("window_id");- let element_index_arg = args.opt_u64("element_index").map(|v| v as usize);- let resolved = match self.state.element_cache.resolve_element_args(- pid,- element_index_arg,- element_token_arg.as_deref(),- args.opt_str("snapshot_id").as_deref(),- window_id_arg,- "right_click",- ) {+ let resolved = match self.state.snapshots.resolve(pid, &args) {Ok(r) => r,Err(e) => return e,};@@ -125,16 +113,13 @@ impl Tool for RightClickTool {return ToolResult::error("Provide both x and y together, not just one.");}if element_index.is_some() && has_xy {- return ToolResult::error("Provide either element_index or (x, y), not both.");+ return ToolResult::error("Provide either element_token or (x, y), not both.");}if element_index.is_none() && !has_xy {return ToolResult::error(- "Provide element_index or (x, y) to address the right-click target.",+ "Provide element_token or (x, y) to address the right-click target.",);}- if element_index.is_some() && window_id.is_none() {- return ToolResult::error("window_id is required when element_index is used.");- }// ── AX element path ──────────────────────────────────────────────────if let (Some(idx), Some(wid), Some(element_guard)) =diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/scroll.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/scroll.rsindex aeee63cc5e..b04863f238 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/scroll.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/scroll.rs@@ -60,7 +60,7 @@ fn def() -> &'static ToolDef {name: "scroll".into(),description: "Scroll the target pid. Two paths, picked by how you address the scroll:\n\n\• **Targeted wheel path** — when you pass a target, either \- `element_index`/`element_token` (preferred) or window-local `x, y` pixels: \+ `element_token` (preferred) or window-local `x, y` pixels: \the driver synthesizes a real mouse-wheel event (CGEventCreateScrollWheelEvent, \at that screen point. The renderer hit-tests the wheel at the \cursor, so the scroll lands on whatever element is under the point — exactly \@@ -99,9 +99,7 @@ fn def() -> &'static ToolDef {"description": "Pixel-wheel path: number of wheel notches. Keystroke path: number of keystroke repetitions. Larger requests are clamped to the maximum. Default: 3."},"window_id": { "type": "integer" },- "element_index": cua_driver_core::tool_schema::element_index_schema(),"element_token": cua_driver_core::tool_schema::element_token_schema(),- "snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),"x": { "type": "number", "description": "Window-local screenshot X (top-left origin of the PNG from get_window_state). With `y`, routes through the pixel-wheel path at this point — use for a scrollable surface that isn't in the AX tree. Requires window_id to anchor the window→screen conversion." },"y": { "type": "number", "description": "Window-local screenshot Y. See `x`." },"scope": { "type": "string", "enum": ["window", "desktop"], "default": "window", "description": "Use desktop with x,y and no pid/window_id for native get_desktop_state screenshot coordinates." },@@ -187,18 +185,8 @@ impl Tool for ScrollTool {};let by = args.str_or("by", "line");let amount = clamp_amount(args.u64_or("amount", 3));- // Surface 6: element_token / element_index precedence.- let element_token_arg = args.opt_str("element_token");let window_id_arg = args.opt_u64("window_id");- let element_index_arg = args.opt_u64("element_index").map(|v| v as usize);- let resolved = match self.state.element_cache.resolve_element_args(- pid,- element_index_arg,- element_token_arg.as_deref(),- args.opt_str("snapshot_id").as_deref(),- window_id_arg,- "scroll",- ) {+ let resolved = match self.state.snapshots.resolve(pid, &args) {Ok(r) => r,Err(e) => return e,};diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/set_value.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/set_value.rsindex 79bcca10be..f185f1bd65 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/set_value.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/set_value.rs@@ -68,11 +68,9 @@ fn def() -> &'static ToolDef {"pid": { "type": "integer" },"window_id": {"type": "integer",- "description": "CGWindowID for the window whose get_window_state produced the element_index. Required when element_index is used; optional when element_token is supplied (the token carries it)."+ "description": "CGWindowID. Omit when element_token is supplied (the token carries it)."},- "element_index": cua_driver_core::tool_schema::element_index_schema(),"element_token": cua_driver_core::tool_schema::element_token_schema(),- "snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),"value": {"type": "string","description": "New value. AX will coerce to the element's native type."@@ -104,48 +102,23 @@ impl Tool for SetValueTool {Err(e) => return e,};- // Surface 6: element_token / element_index precedence. Neither- // is now schema-required so the resolver can centralize the- // "missing addressing" error message.- let element_token_arg = args.opt_str("element_token");- let window_id_arg = args.opt_u64("window_id");- let element_index_arg = args.opt_u64("element_index").map(|v| v as usize);- let resolved = match self.state.element_cache.resolve_element_args(- pid,- element_index_arg,- element_token_arg.as_deref(),- args.opt_str("snapshot_id").as_deref(),- window_id_arg,- "set_value",- ) {- Ok(r) => r,- Err(e) => return e,- };- let (element_index, window_id, element_guard) = match resolved {- cua_driver_core::element_token::ResolvedElement::None => {- return ToolResult::error(- "set_value requires element_index (+ window_id) or element_token to \- address the target element.",- )- }- cua_driver_core::element_token::ResolvedElement::Element {- window_id: Some(wid),- element_index: idx,- element,- ..- } => match u32::try_from(wid) {- Ok(wid) => (idx, wid, element),- Err(_) => return ToolResult::error("window_id is out of range for macOS."),- },- cua_driver_core::element_token::ResolvedElement::Element {- window_id: None, ..- } => {- return ToolResult::error(- "set_value requires window_id when element_index is used \- (omit only when supplying element_token, which carries it).",- )- }- };+ let (element_index, window_id, element_guard) =+ match self.state.snapshots.resolve(pid, &args) {+ Ok(cua_driver_core::element_token::ResolvedElement::None) => {+ return ToolResult::error(+ "set_value requires element_token to address the target element.",+ )+ }+ Ok(cua_driver_core::element_token::ResolvedElement::Element {+ window_id,+ element_index,+ element,+ }) => match u32::try_from(window_id) {+ Ok(window_id) => (element_index, window_id, element),+ Err(_) => return ToolResult::error("window_id is out of range for macOS."),+ },+ Err(refusal) => return refusal,+ };let element_ptr = element_guard.as_ptr();diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text.rsindex 862588f8d2..e489608bae 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text.rs@@ -67,9 +67,9 @@ fn def() -> &'static ToolDef {within the daemon transport budget. Longer synthesized routes are \refused before character events and return a safe chunk size; \one-call AX insertion remains uncapped.\n\n\- Optional `element_index` + `window_id` (from the last \+ Optional `element_token` (from the last \`get_window_state` snapshot) directs the write to a specific field. \- Without `element_index`, the write goes to the pid's currently \+ Without `element_token`, the write goes to the pid's currently \focused element.\n\n\WEB CONTENT (Chromium/WebKit/Electron — browser tabs, Slack, VS Code, \X's compose box): AXValue is not independent proof that the \@@ -84,7 +84,7 @@ fn def() -> &'static ToolDef {browser's own native address bar/toolbar stays trusted). For a browser \TAB the reliable path is the `page` tool (drives the DOM via CDP); for \an embedded web view use this tool's px form: pass x,y (no \- element_index) to pixel-click the field then type, in one call. NOTE: \+ element_token) to pixel-click the field then type, in one call. NOTE: \a px focus-click won't reliably open+focus a CLOSED control; AX-press \to open/activate it first (works in the background), then px-type. \Always confirm via the screenshot; if px-background still drops, \@@ -99,12 +99,10 @@ fn def() -> &'static ToolDef {"text": { "type": "string", "description": "Text to insert at the target's cursor." },"window_id": {"type": "integer",- "description": "CGWindowID. Required when element_index is used. Optional when element_token is supplied (the token carries it)."+ "description": "CGWindowID. Omit when element_token is supplied (the token carries it)."},- "element_index": cua_driver_core::tool_schema::element_index_schema(),"element_token": cua_driver_core::tool_schema::element_token_schema(),- "snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),- "x": { "type": "number", "description": "Screenshot-pixel X of the field to type into — the element px action form. Pass x,y (no element_index) and the tool pixel-clicks there to establish real renderer focus, then types. Use for Chromium/Electron inputs the AX path can't reach. Read straight off the get_window_state PNG, same convention as click." },+ "x": { "type": "number", "description": "Screenshot-pixel X of the field to type into — the element px action form. Pass x,y (no element_token) and the tool pixel-clicks there to establish real renderer focus, then types. Use for Chromium/Electron inputs the AX path can't reach. Read straight off the get_window_state PNG, same convention as click." },"y": { "type": "number", "description": "Screenshot-pixel Y of the field (see x)." },"delay_ms": {"type": "integer",@@ -210,18 +208,8 @@ impl Tool for TypeTextTool {// cua_driver_core::text_sanitize docs for rationale.let text = cua_driver_core::text_sanitize::strip_trailing_agent_protocol_tags(&text_raw).into_owned();- // Surface 6: element_token / element_index precedence resolution.- let element_token_arg = args.opt_str("element_token");let window_id_arg = args.opt_u64("window_id");- let element_index_arg = args.opt_u64("element_index").map(|v| v as usize);- let resolved = match self.state.element_cache.resolve_element_args(- pid,- element_index_arg,- element_token_arg.as_deref(),- args.opt_str("snapshot_id").as_deref(),- window_id_arg,- "type_text",- ) {+ let resolved = match self.state.snapshots.resolve(pid, &args) {Ok(r) => r,Err(e) => return e,};@@ -240,12 +228,6 @@ impl Tool for TypeTextTool {return error;}- // Validate element_index requires window_id (still applies for- // the legacy integer path; token path already resolved window_id).- if element_index.is_some() && window_id.is_none() {- return ToolResult::error("window_id is required when element_index is used.");- }-// Argument-shape errors are reported before any gating or retained// lookups: a malformed call must fail the same way regardless of// background-target state.@@ -253,7 +235,7 @@ impl Tool for TypeTextTool {let py = args.get("y").and_then(|v| v.as_f64());if px.is_some() && py.is_some() && element_index.is_some() {return ToolResult::error(- "Pass either element_index (ax) or x,y (px) to type_text, not both.",+ "Pass either element_token (ax) or x,y (px) to type_text, not both.",);}@@ -279,7 +261,7 @@ impl Tool for TypeTextTool {};// ── px form: focus by pixel-click, then type into the focused element ──- // Pass x,y (no element_index) for an *element px action*: pixel-click the+ // Pass x,y (no element_token) for an *element px action*: pixel-click the// field to give the Chromium/Electron renderer the real keyboard focus the// AX path can't, then fall through to the focused-element type path (which// escalates AX → CGEvent and lands once focused). Reuses ClickTool's exact@@ -833,7 +815,7 @@ async fn background_keyboard_policy(};let lease = super::acquire_background_mutation(pid).await;let element_guard =- element_ptr.map(|ptr| unsafe { crate::ax::cache::RetainedElement::retain(ptr) });+ element_ptr.map(|ptr| unsafe { crate::ax::snapshot::RetainedElement::retain(ptr) });let facts = match tokio::task::spawn_blocking(move || {let element_ptr = element_guard.as_ref().map(|guard| guard.as_ptr());crate::ax::exact_target::gather_background_facts(pid, window_id, element_ptr)diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text_chars.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text_chars.rsindex 45a2a28269..712a9ebfac 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text_chars.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text_chars.rs@@ -34,9 +34,7 @@ fn def() -> &'static ToolDef {"text": { "type": "string", "description": "Text to type." },"delay_ms": { "type": "integer", "description": "Milliseconds between characters (default 30)." },"window_id": { "type": "integer", "description": "Window ID for element focus. Optional when element_token is supplied." },- "element_index": cua_driver_core::tool_schema::element_index_schema(),"element_token": cua_driver_core::tool_schema::element_token_schema(),- "snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),"type_chars_only": { "type": "boolean", "description": "Skip AX focus, type directly. Default false." }},"additionalProperties": false@@ -69,18 +67,8 @@ impl Tool for TypeTextCharsTool {let text = cua_driver_core::text_sanitize::strip_trailing_agent_protocol_tags(&text_raw).into_owned();let delay_ms = args.u64_or("delay_ms", 30);- // Surface 6: element_token / element_index precedence resolution.- let element_token_arg = args.opt_str("element_token");let window_id_arg = args.opt_u64("window_id");- let element_index_arg = args.opt_u64("element_index").map(|v| v as usize);- let resolved = match self.state.element_cache.resolve_element_args(- pid,- element_index_arg,- element_token_arg.as_deref(),- args.opt_str("snapshot_id").as_deref(),- window_id_arg,- "type_text_chars",- ) {+ let resolved = match self.state.snapshots.resolve(pid, &args) {Ok(r) => r,Err(e) => return e,};diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/zoom.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/zoom.rsindex dd5a1b19e7..6b5677be61 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/zoom.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/zoom.rs@@ -23,7 +23,7 @@ fn def() -> &'static ToolDef {500 px wide.\n\n\After a zoom, pass `from_zoom=true` to click/type_text to auto-translate coordinates \back to full-window space. Coordinate actions return `screenshot_context_missing` \- when the latest snapshot does not contain a screenshot owned by this session. \+ when no current snapshot contains a screenshot owned by this session. \`from_zoom` actions return `zoom_context_missing` when the zoom was never created or \was replaced; call `get_window_state`, then `zoom`, again on the same connection.".into(),input_schema: serde_json::json!({@@ -66,7 +66,7 @@ impl Tool for ZoomTool {},};let session_id = args.opt_str("_session_id");- let (pid, screenshot) = match self.state.element_cache.screenshot_context_for_zoom(+ let (pid, screenshot) = match self.state.snapshots.screenshot_context_for_zoom(requested_pid,u64::from(window_id),session_id.as_deref(),@@ -111,8 +111,7 @@ impl Tool for ZoomTool {match result {Ok(Ok(crop)) => {// Store zoom context so from_zoom clicks can translate back.- if let Err(refusal) = state.zoom_registry.set_if_current(- &state.element_cache,+ if let Err(refusal) = state.snapshots.set_zoom(pid,session_id.as_deref(),ZoomContext {diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/click_domains.rs b/libs/cua-driver/rust/crates/platform-windows/examples/click_domains.rsindex f21c05036f..dda3393057 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/click_domains.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/click_domains.rs@@ -83,11 +83,22 @@ fn main() {println!(" candidate #{i}: [{idx}] {}", line.trim());}let (idx, _) = candidates[0];- println!("Using element_index={idx}");+ let state: serde_json::Value = serde_json::from_str(state_resp.trim()).unwrap();+ let token = state+ .pointer("/result/structuredContent/elements")+ .and_then(|elements| elements.as_array())+ .and_then(|elements| {+ elements+ .iter()+ .find(|element| element["element_index"] == idx)+ })+ .and_then(|element| element["element_token"].as_str())+ .expect("get_window_state reported no element_token");+ println!("Using element_token={token}");let click_req = format!(- r#"{{"method":"call","name":"click","args":{{"pid":{},"window_id":{},"element_index":{}}}}}"#,- chrome_pid, chrome_wid, idx+ r#"{{"method":"call","name":"click","args":{{"pid":{},"window_id":{},"element_token":"{}"}}}}"#,+ chrome_pid, chrome_wid, token);let click_resp = req(&mut pipe, &click_req);println!("Click resp: {}", click_resp.trim());diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/click_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/click_parity.rsindex 04ec1bd823..da838df355 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/click_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/click_parity.rs@@ -116,7 +116,7 @@ fn main() {let v_m: serde_json::Value = serde_json::from_str(r_m.trim()).expect("parse");let err1 = extract_text(&v_m);assert!(- err1.contains("Provide element_index or (x, y) to address the click target"),+ err1.contains("Provide element_token or (x, y) to address the click target"),"Expected Swift-style missing-target wording, got: {err1:?}");println!("Missing-target err OK: {err1:?}");diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/double_click_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/double_click_parity.rsindex a23e3d209a..7d0d2f6bd7 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/double_click_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/double_click_parity.rs@@ -77,7 +77,7 @@ fn main() {let v1: serde_json::Value = serde_json::from_str(r1.trim()).unwrap();let e1 = extract_text(&v1);assert!(- e1.contains("Provide element_index or (x, y) to address the double-click target"),+ e1.contains("Provide element_token or (x, y) to address the double-click target"),"Missing-target wording wrong: {e1:?}");println!("Missing-target err OK");@@ -97,32 +97,32 @@ fn main() {);println!("Partial-xy err OK");- // 3. Both element_index AND xy.+ // 3. A stale element_token AND xy.let r3 = req(&mut pipe,&format!(- r#"{{"method":"call","name":"double_click","args":{{"pid":{pid},"window_id":{wid},"element_index":0,"x":100,"y":100}}}}"#+ r#"{{"method":"call","name":"double_click","args":{{"pid":{pid},"window_id":{wid},"element_token":"s00000000:0","x":100,"y":100}}}}"#),);let v3: serde_json::Value = serde_json::from_str(r3.trim()).unwrap();let e3 = extract_text(&v3);assert!(- e3.contains("Provide either element_index or (x, y), not both"),+ e3.contains("element_token is stale"),"Both-modes wording wrong: {e3:?}");println!("Both-modes err OK");- // 4. element_index without window_id.+ // 4. A stale element_token without window_id.let r4 = req(&mut pipe,&format!(- r#"{{"method":"call","name":"double_click","args":{{"pid":{pid},"element_index":0}}}}"#+ r#"{{"method":"call","name":"double_click","args":{{"pid":{pid},"element_token":"s00000000:0"}}}}"#),);let v4: serde_json::Value = serde_json::from_str(r4.trim()).unwrap();let e4 = extract_text(&v4);assert!(- e4.contains("window_id is required when element_index is used"),+ e4.contains("element_token is stale"),"Element-without-window wording wrong: {e4:?}");println!("Element-without-window err OK");diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/press_key_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/press_key_parity.rsindex f29033f29f..a2c07eb012 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/press_key_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/press_key_parity.rs@@ -53,15 +53,15 @@ fn main() {);println!("Missing-key err OK: {err1:?}");- // 2. element_index without window_id should error per Swift.+ // 2. A stale element_token without window_id is refused.let r2 = req(&mut pipe,- r#"{"method":"call","name":"press_key","args":{"pid":1,"key":"a","element_index":0}}"#,+ r#"{"method":"call","name":"press_key","args":{"pid":1,"key":"a","element_token":"s00000000:0"}}"#,);let v2: serde_json::Value = serde_json::from_str(r2.trim()).unwrap();let err2 = extract_text(&v2);assert!(- err2.contains("window_id is required when element_index is used"),+ err2.contains("element_token is stale"),"Expected Swift-style element-without-window error, got: {err2:?}");println!("Element-without-window err OK");diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/right_click_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/right_click_parity.rsindex ddd8109ba8..38c9a0b8ec 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/right_click_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/right_click_parity.rs@@ -75,7 +75,7 @@ fn main() {);let v1: serde_json::Value = serde_json::from_str(r1.trim()).unwrap();assert!(extract_text(&v1)- .contains("Provide element_index or (x, y) to address the right-click target"));+ .contains("Provide element_token or (x, y) to address the right-click target"));println!("Missing-target err OK");// 2. Partial xy.@@ -93,22 +93,24 @@ fn main() {let r3 = req(&mut pipe,&format!(- r#"{{"method":"call","name":"right_click","args":{{"pid":{pid},"window_id":{wid},"element_index":0,"x":50,"y":50}}}}"#+ r#"{{"method":"call","name":"right_click","args":{{"pid":{pid},"window_id":{wid},"element_token":"s00000000:0","x":50,"y":50}}}}"#),);- assert!(extract_text(&serde_json::from_str(r3.trim()).unwrap())- .contains("Provide either element_index or (x, y), not both"));+ assert!(+ extract_text(&serde_json::from_str(r3.trim()).unwrap()).contains("element_token is stale")+ );println!("Both-modes err OK");- // 4. element_index without window_id.+ // 4. A stale element_token without window_id.let r4 = req(&mut pipe,&format!(- r#"{{"method":"call","name":"right_click","args":{{"pid":{pid},"element_index":0}}}}"#+ r#"{{"method":"call","name":"right_click","args":{{"pid":{pid},"element_token":"s00000000:0"}}}}"#),);- assert!(extract_text(&serde_json::from_str(r4.trim()).unwrap())- .contains("window_id is required when element_index is used"));+ assert!(+ extract_text(&serde_json::from_str(r4.trim()).unwrap()).contains("element_token is stale")+ );println!("Element-without-window err OK");// 5. Real pixel right-click.diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/scroll_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/scroll_parity.rsindex c5b56d279e..dc21ebd899 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/scroll_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/scroll_parity.rs@@ -52,14 +52,14 @@ fn main() {);println!("Missing-direction err OK");- // element_index without window_id.+ // A stale element_token without window_id.let r2 = req(&mut pipe,- r#"{"method":"call","name":"scroll","args":{"pid":1,"direction":"down","element_index":0}}"#,+ r#"{"method":"call","name":"scroll","args":{"pid":1,"direction":"down","element_token":"s00000000:0"}}"#,);let e2 = extract_text(&serde_json::from_str(r2.trim()).unwrap());assert!(- e2.contains("window_id is required when element_index is used"),+ e2.contains("element_token is stale"),"Element-without-window wording wrong: {e2:?}");println!("Element-without-window err OK");diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/set_value_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/set_value_parity.rsindex 8c25982a3b..fa3341752e 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/set_value_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/set_value_parity.rs@@ -45,9 +45,8 @@ fn main() {.unwrap_or_default()}- // Missing value error (with all three integers present). Note: pid /- // window_id / element_index are schema-required; we pick a real pid +- // window_id to ensure the schema doesn't reject before our tool runs.+ // Missing value error. We pick a real pid + window_id to ensure the+ // schema doesn't reject before our tool runs.let lw = req(&mut pipe,r#"{"method":"call","name":"list_windows","args":{}}"#,@@ -80,7 +79,7 @@ fn main() {let r1 = req(&mut pipe,&format!(- r#"{{"method":"call","name":"set_value","args":{{"pid":{pid},"window_id":{wid},"element_index":0}}}}"#+ r#"{{"method":"call","name":"set_value","args":{{"pid":{pid},"window_id":{wid},"element_token":"s00000000:0"}}}}"#),);let e1 = extract_text(&serde_json::from_str(r1.trim()).unwrap());@@ -95,7 +94,7 @@ fn main() {let r2 = req(&mut pipe,&format!(- r#"{{"method":"call","name":"set_value","args":{{"pid":{pid},"window_id":{wid},"element_index":99999,"value":"x"}}}}"#+ r#"{{"method":"call","name":"set_value","args":{{"pid":{pid},"window_id":{wid},"element_token":"s00000000:99999","value":"x"}}}}"#),);let e2 = extract_text(&serde_json::from_str(r2.trim()).unwrap());diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/type_text_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/type_text_parity.rsindex 190f9e07a9..7a91a95c18 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/type_text_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/type_text_parity.rs@@ -52,14 +52,14 @@ fn main() {);println!("Missing-text err OK");- // 2. element_index without window_id.+ // 2. A stale element_token without window_id.let r2 = req(&mut pipe,- r#"{"method":"call","name":"type_text","args":{"pid":1,"text":"x","element_index":0}}"#,+ r#"{"method":"call","name":"type_text","args":{"pid":1,"text":"x","element_token":"s00000000:0"}}"#,);let e2 = extract_text(&serde_json::from_str(r2.trim()).unwrap());assert!(- e2.contains("window_id is required when element_index is used"),+ e2.contains("element_token is stale"),"Element-without-window wording wrong: {e2:?}");println!("Element-without-window err OK");diff --git a/libs/cua-driver/rust/crates/platform-windows/src/recording_hooks.rs b/libs/cua-driver/rust/crates/platform-windows/src/recording_hooks.rsindex 131e9b044f..450bcbe531 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/recording_hooks.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/recording_hooks.rs@@ -10,13 +10,13 @@use std::sync::Arc;#[cfg(target_os = "windows")]-use cua_driver_core::element_cache::{current_runtime_cache, register_runtime_cache};+use cua_driver_core::snapshot_store::{current_runtime_store, register_runtime_store};#[cfg(target_os = "windows")]-use crate::uia::cache::{CachedSnapshot, SnapshotKind};+use crate::uia::snapshot::{SnapshotKind, UiaSnapshot};#[cfg(target_os = "windows")]-use crate::uia::ElementCache;+use crate::uia::Snapshots;use cua_driver_core::recording::ScreenshotCapture;@@ -32,8 +32,8 @@ use windows::Win32::UI::WindowsAndMessaging::{};#[cfg(target_os = "windows")]-pub fn set_element_cache(cache: Arc<ElementCache>) {- register_runtime_cache(&cache);+pub fn set_snapshots(cache: Arc<Snapshots>) {+ register_runtime_store(&cache);}/// Resolve the window whose application evidence should be captured. Keep a@@ -118,7 +118,7 @@ pub fn app_state_json_for(} else {SnapshotKind::Uia};- let _native_payload = CachedSnapshot::from_nodes(&result.nodes, kind);+ let _native_payload = UiaSnapshot::from_nodes(&result.nodes, kind);let element_count = result.nodes.iter()@@ -140,24 +140,11 @@ pub fn element_window_local_xy(args: &serde_json::Value,capture_point: bool,) -> Option<(u64, Option<(f64, f64)>)> {- let cache = current_runtime_cache::<CachedSnapshot>()?;+ let cache = current_runtime_store::<UiaSnapshot>()?;let pid_u32 = u32::try_from(pid).ok()?;- let resolved = cache- .resolve_element_args(- pid_u32 as i32,- args.get("element_index")- .and_then(|value| value.as_u64())- .map(|value| value as usize),- args.get("element_token").and_then(|value| value.as_str()),- args.get("snapshot_id").and_then(|value| value.as_str()),- args.get("window_id").and_then(|value| value.as_u64()),- "recording",- )- .ok()?;+ let resolved = cache.resolve(pid_u32 as i32, args).ok()?;let cua_driver_core::element_token::ResolvedElement::Element {- window_id: Some(window_id),- element,- ..+ window_id, element, ..} = resolvedelse {return None;diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rsindex 4d9c80f7e4..c3101d1005 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs@@ -104,7 +104,7 @@ fn keyboard_window_center(hwnd: u64) -> Option<(f64, f64)> {/// window. MSAA-walked elements are skipped (no ScrollItemPattern) and keep the/// existing failure.fn resolve_onscreen_point_with_scroll(- admitted: &Option<crate::uia::cache::RetainedElement>,+ admitted: &Option<crate::uia::snapshot::RetainedElement>,hwnd: u64,idx: usize,cx: i32,@@ -382,7 +382,7 @@ use cua_driver_core::{use serde_json::{json, Value};use std::sync::{Arc, RwLock};-use crate::uia::ElementCache;+use crate::uia::Snapshots;use cursor_overlay::CursorRegistry;use windows::core::Interface as _;@@ -594,14 +594,11 @@ pub fn load_driver_config() -> DriverConfig {cfg}-use cua_driver_core::element_cache::{- SnapshotBoundZoomContext as ZoomContext, SnapshotBoundZoomRegistry as ZoomRegistry,-};+use cua_driver_core::snapshot_store::ZoomContext;pub struct ToolState {- pub element_cache: Arc<ElementCache>,+ pub snapshots: Arc<Snapshots>,pub cursor_registry: Arc<CursorRegistry>,- pub zoom_registry: Arc<ZoomRegistry>,pub config: Arc<RwLock<DriverConfig>>,capture_bridge: Option<Arc<crate::capture_admission::WindowsCaptureBridge>>,}@@ -611,9 +608,8 @@ impl ToolState {capture_service: Option<Arc<cua_driver_core::capture_runtime::CaptureService>>,) -> Arc<Self> {Arc::new(Self {- element_cache: Arc::new(ElementCache::new()),+ snapshots: Arc::new(Snapshots::new()),cursor_registry: Arc::new(CursorRegistry::new()),- zoom_registry: Arc::new(ZoomRegistry::new()),config: Arc::new(RwLock::new(load_driver_config())),capture_bridge: capture_service.map(crate::capture_admission::WindowsCaptureBridge::new),@@ -626,8 +622,7 @@ impl ToolState {pid: u32,window_id: Option<u64>,) -> Result<ZoomContext, ToolResult> {- self.zoom_registry.resolve(- &self.element_cache,+ self.snapshots.zoom(pid as i32,window_id,args.get("_session_id").and_then(Value::as_str),@@ -641,11 +636,14 @@ fn screenshot_scale(pid: u32,window_id: Option<u64>,) -> Result<f64, ToolResult> {- state.element_cache.screenshot_scale_or_refusal(- pid as i32,- window_id,- args.get("_session_id").and_then(Value::as_str),- )+ state+ .snapshots+ .screenshot_context(+ pid as i32,+ window_id,+ args.get("_session_id").and_then(Value::as_str),+ )+ .map(|context| context.scale)}fn capture_admission_refusal(error: anyhow::Error) -> ToolResult {@@ -1148,11 +1146,12 @@ impl Tool for GetWindowStateTool {description: "Walk a running app's UIA tree and return BOTH a structured \`elements` array (preferred) AND a Markdown rendering of the same tree \(back-compat). Every actionable element is tagged with [element_index N] \- in the markdown and as `element_index` in the structured array — pass \- those indices to `click`, `type_text`, `scroll`, etc.\n\n\+ in the markdown and as `element_index` in the structured array; pass each \+ element's `element_token` to `click`, `type_text`, `scroll`, etc.\n\n\INVARIANT: call `get_window_state` once per turn per (pid, window_id) before \- any element-indexed action against that window. The index map is replaced by \- the next snapshot of the same (pid, window_id).\n\n\+ any element action against that window. The next snapshot of the same \+ (pid, window_id) replaces this one, stales its element tokens, and lists the \+ replaced ids in `invalidated_snapshot_ids`.\n\n\PREFERRED CONSUMERS read `structuredContent.elements` (one entry per \indexed row with `element_index`, `role`, `label`, `value`, `enabled`, \`selected`, `actions` (names of UIA patterns exposed as actions, \@@ -1172,7 +1171,7 @@ impl Tool for GetWindowStateTool {complete snapshot; `returned_element_count` reports the projection.\n\n\Always returns BOTH the element tree AND a screenshot — ground on both \and cross-check (the tree lies on some surfaces). Choose the modality at \- ACTION time: an element ax action (element_index/element_token → \+ ACTION time: an element ax action (element_token → \accessibility rung) or an element px action (x,y → pixel rung off this \screenshot). capture_mode is deprecated and ignored.\n\n\The mirror image: pass `include_accessibility_tree:false` to SKIP the \@@ -1370,11 +1369,11 @@ impl Tool for GetWindowStateTool {let tree =crate::uia::walk_tree_budgeted(hwnd, q.as_deref(), max_depth, &mut budget);let kind = if tree.nodes.iter().any(|node| node.msaa_role.is_some()) {- crate::uia::cache::SnapshotKind::Msaa+ crate::uia::snapshot::SnapshotKind::Msaa} else {- crate::uia::cache::SnapshotKind::Uia+ crate::uia::snapshot::SnapshotKind::Uia};- let payload = crate::uia::cache::CachedSnapshot::from_nodes(&tree.nodes, kind);+ let payload = crate::uia::snapshot::UiaSnapshot::from_nodes(&tree.nodes, kind);(tree, payload, budget.outcome())});let started = std::time::Instant::now();@@ -1396,9 +1395,9 @@ impl Tool for GetWindowStateTool {),nodes: Vec::new(),};- let payload = crate::uia::cache::CachedSnapshot::from_nodes(+ let payload = crate::uia::snapshot::UiaSnapshot::from_nodes(&[],- crate::uia::cache::SnapshotKind::Uia,+ crate::uia::snapshot::SnapshotKind::Uia,);Some((tree, payload, walk))}@@ -1468,6 +1467,7 @@ impl Tool for GetWindowStateTool {.as_ref().map(|(_, _, w, _, native_w, _, _)| *native_w as f64 / *w as f64);let mut published_snapshot = false;+ let mut invalidated = Vec::new();if let Some((tr, payload, walk)) = tree_opt {let is_msaa = tr.nodes.iter().any(|node| node.msaa_role.is_some());@@ -1493,9 +1493,9 @@ impl Tool for GetWindowStateTool {structured["tree_markdown"] = json!(tr.tree_markdown);walk.apply(&mut structured);- let snapshot_id = (!observation_only)+ let (snapshot_id, replaced) = (!observation_only).then(|| {- state.element_cache.publish_for_session(+ state.snapshots.publish_for_session(pid as i32,hwnd,payload,@@ -1503,13 +1503,10 @@ impl Tool for GetWindowStateTool {screenshot_scale,)})- .flatten();+ .flatten()+ .unzip();published_snapshot = snapshot_id.is_some();- if let Some(snapshot_id) = snapshot_id {- state- .zoom_registry- .retire_replaced(pid as i32, hwnd, snapshot_id);- }+ invalidated.extend(replaced.into_iter().flatten());// Structured `elements` array — preferred consumption// path. Shape matches the cross-platform spec:@@ -1545,10 +1542,9 @@ impl Tool for GetWindowStateTool {structured["elements"] = json!(elements);// Surface 6: snapshot id mirror for debug correlation.if let Some(snapshot_id) = snapshot_id {- structured["snapshot_id"] =- json!(cua_driver_core::element_token::token_for(snapshot_id, 0)- .trim_end_matches(":0")- .to_string());+ structured["snapshot_id"] = json!(+ cua_driver_core::element_token::format_snapshot_id(snapshot_id)+ );}structured["_note"] = json!("Prefer `elements` — `tree_markdown` will continue to work \@@ -1594,22 +1590,31 @@ impl Tool for GetWindowStateTool {}if !observation_only && !published_snapshot && screenshot_scale.is_some() {- let payload = crate::uia::cache::CachedSnapshot::from_nodes(+ let payload = crate::uia::snapshot::UiaSnapshot::from_nodes(&[],- crate::uia::cache::SnapshotKind::Uia,+ crate::uia::snapshot::SnapshotKind::Uia,);- if let Some(snapshot_id) = state.element_cache.publish_for_session(+ if let Some((_, replaced)) = state.snapshots.publish_for_session(pid as i32,hwnd,payload,session_id.as_deref(),screenshot_scale,) {- state- .zoom_registry- .retire_replaced(pid as i32, hwnd, snapshot_id);+ invalidated.extend(replaced);}}+ if !invalidated.is_empty() {+ let ids: Vec<String> = invalidated+ .into_iter()+ .map(cua_driver_core::element_token::format_snapshot_id)+ .collect();+ content.push(cua_driver_core::protocol::Content::text(format!(+ "Invalidated snapshots {}: their element_tokens are stale.",+ ids.join(", ")+ )));+ structured["invalidated_snapshot_ids"] = json!(ids);+ }if let Some((b64_opt, file_path, w, h, native_w, native_h, png)) = screenshot_opt {let capture_id = if !observation_only {@@ -3180,28 +3185,28 @@ impl Tool for ClickTool {CLICK_DEF.get_or_init(|| ToolDef {name: "click".into(),// Description matches Swift `ClickTool.swift` semantics (left-click- // primitive with two addressing modes — element_index via UIA, or+ // primitive with two addressing modes — element_token via UIA, or// window-local pixel coords via PostMessage). Windows-only schema- // extras (`button`, no `modifier`/`action`/`debug_image_out`) apply here.- description: "Left-click against a target pid. **Prefer `element_index` over \- pixel coordinates** — element_index works on backgrounded / minimized / \+ // extras (`button`; `action` limited to "expand"; no+ // `debug_image_out`) apply here.+ description: "Left-click against a target pid. **Prefer `element_token` over \+ pixel coordinates** — element_token works on backgrounded / minimized / \hidden / off-desktop windows, surfaces a stable handle that survives \rebuilds, and tells you what you're clicking via the cached element's \role + label. Reach for `x, y` only when the target is a canvas / video / \WebGL / custom-drawn surface that doesn't appear in the UIA tree.\n\n\Two addressing modes:\n\n\- - `element_index` + `window_id` (from the last `get_window_state` snapshot \+ - `element_token` (from the last `get_window_state` snapshot \of that window) — performs the UIA Invoke pattern on the cached element via \PostMessage. No cursor move, no focus steal. Requires a prior \- `get_window_state(pid, window_id)` in this turn; the element_index cache \- is scoped per (pid, window_id) and is replaced by the next snapshot of the \- same window.\n\n\+ `get_window_state(pid, window_id)` in this turn; the token is stale once \+ the next snapshot of the same window replaces it.\n\n\- `x`, `y` (window-local screenshot pixels, top-left origin of the PNG \returned by `get_window_state`). On `delivery_mode:\"background\"` (the \default), cua-driver FIRST does a UIA hit-test at the resolved \screen position: if the deepest invokable element under that point exposes \`InvokePattern`, it's invoked through the accessibility channel — same \- background-safe path as the `element_index` mode, no foreground swap, no \+ background-safe path as the `element_token` mode, no foreground swap, no \visible flash. **This makes pixel clicks on UWP / WinUI3 / Win11 packaged \apps work flash-free out of the box** — agents should default to \`delivery_mode:\"background\"` even on XAML hosts whose CoreInput dispatcher \@@ -3217,23 +3222,23 @@ impl Tool for ClickTool {`count: 2` posts two down/up pairs for a double-click. Pixel clicks need \a visible on-screen window to anchor the coordinate conversion (errors \with `pid X has no on-screen window` otherwise).\n\n\- Exactly one of `element_index` or (`x` AND `y`) must be provided. \- `pid` is required for window scope and omitted for desktop scope. `window_id` is required when \- `element_index` is used (scopes the cache lookup). After a `zoom` call, \+ Exactly one of `element_token` or (`x` AND `y`) must be provided. \+ `pid` is required for window scope and omitted for desktop scope. After a `zoom` call, \pass `from_zoom=true` to auto-translate zoom-image coords back to \full-window space.\n\n\Windows-only convenience: `button: \"left\"|\"right\"|\"middle\"` switches \the mouse button (Swift exposes right-click as a separate `right_click` \- tool). The Swift-only `action` / `modifier` / `debug_image_out` schema \- fields aren't supported yet.".into(),+ tool). `action: \"expand\"` on an `element_token` opens the element \+ through UIA ExpandCollapsePattern (the dropdown half of an MSAA split \+ button); other actions use the default invoke. `debug_image_out` isn't \+ supported yet.".into(),input_schema: json!({"type":"object","properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer","description":"Target process ID for window scope. Omit with scope=desktop for screen-absolute coordinates from get_desktop_state."},- "window_id":{"type":"integer","description":"HWND for the window whose get_window_state produced the element_index. Required when element_index is used. Optional when element_token is supplied (the token carries it)."},- "element_index": cua_driver_core::tool_schema::element_index_schema(),+ "window_id":{"type":"integer","description":"HWND of the target window. Omit when element_token is supplied (the token carries it)."},"element_token": cua_driver_core::tool_schema::element_token_schema(),- "snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),+ "action":{"type":"string","description":"Accessibility action for an element_token target. \"expand\" opens the element through UIA ExpandCollapsePattern, or clicks the dropdown half of an MSAA split button. Omit for the default invoke."},"capture_id":{"type":"string","minLength":1,"description":"Optional ID from get_window_state or get_desktop_state. When present, x and y are admitted against that exact capture and the ID is consumed before native dispatch."},"x":{"type":"number","description":"X in window-local screenshot pixels — same space as the PNG get_window_state returns. Must be provided together with y."},"y":{"type":"number","description":"Y in window-local screenshot pixels. Must be provided together with x."},@@ -3251,7 +3256,7 @@ impl Tool for ClickTool {async fn invoke(&self, args: Value) -> ToolResult {use crate::input::delivery::{DeliveryMode, EventKind};- use crate::uia::cache::SnapshotKind;+ use crate::uia::snapshot::SnapshotKind;use cua_driver_core::tool_args::ArgsExt;let cursor_key = resolve_cursor_key(&args);@@ -3380,17 +3385,7 @@ impl Tool for ClickTool {Ok(v) => v,Err(e) => return e,};- // Surface 6: element_token / element_index precedence resolution.- // Windows uses u64 HWND but the token registry stores u32; truncate- // through the same path get_window_state used when registering.- let resolved = match self.state.element_cache.resolve_element_args(- pid as i32,- args.opt_u64("element_index").map(|v| v as usize),- args.opt_str("element_token").as_deref(),- args.opt_str("snapshot_id").as_deref(),- args.opt_u64("window_id"),- "click",- ) {+ let resolved = match self.state.snapshots.resolve(pid as i32, &args) {Ok(r) => r,Err(e) => return e,};@@ -4136,7 +4131,7 @@ impl Tool for ClickTool {}// delivery_mode:"background" on WinUI3 for double / right / middle (pixel- // path, no element_index → no cached element to UIA-Invoke): these+ // path, no element_token → no cached element to UIA-Invoke): these// can't both land and hold the contract on WinUI3 (posted input is// ignored, the pen injector steals foreground) → structured error.if delivery == DeliveryMode::Background@@ -4286,7 +4281,7 @@ impl Tool for ClickTool {}} else {// Match Swift's error wording for the missing-target case.- ToolResult::error("Provide element_index or (x, y) to address the click target.")+ ToolResult::error("Provide element_token or (x, y) to address the click target.")}}}@@ -4385,7 +4380,7 @@ pub struct TypeTextTool {}fn wait_for_cached_element_keyboard_focus(- admitted: &Option<crate::uia::cache::RetainedElement>,+ admitted: &Option<crate::uia::snapshot::RetainedElement>,timeout: std::time::Duration,) -> bool {let deadline = std::time::Instant::now() + timeout;@@ -4410,7 +4405,7 @@ fn wait_for_cached_element_keyboard_focus(/// bounded fallback. Both routes require `CurrentHasKeyboardFocus` read-back/// before any keyboard input is allowed to leave the driver.fn focus_cached_element_for_foreground(- admitted: &Option<crate::uia::cache::RetainedElement>,+ admitted: &Option<crate::uia::snapshot::RetainedElement>,hwnd: u64,element_index: usize,click_point: Option<(i32, i32)>,@@ -4467,12 +4462,12 @@ impl Tool for TypeTextTool {`hotkey` — they are not text.\n\n\**Routing on Windows.** When the target's owning EXE or top-level window \class identifies it as a XAML / WinUI3 / UWP host (modern Notepad, \- Calculator, Photos, Settings, etc.), the tool requires `element_index` \- + `window_id` and routes through UI Automation's `ValuePattern.SetValue` \+ Calculator, Photos, Settings, etc.), the tool requires `element_token` \+ and routes through UI Automation's `ValuePattern.SetValue` \— same backend as the `set_value` tool. PostMessage WM_CHAR doesn't \reach those hosts (their CoreInput dispatcher only consumes events from \the system input queue), so the fallback path silently dropped chars. \- If you call `type_text(pid, text)` on a XAML host without `element_index`, \+ If you call `type_text(pid, text)` on a XAML host without `element_token`, \the tool returns an actionable error pointing you at `get_window_state` \first. Native ConsoleHost on Windows ARM64 is hard-refused because it can \accept synthesized Unicode events without delivering them; use a process \@@ -4487,11 +4482,9 @@ impl Tool for TypeTextTool {"scope":{"type":"string","enum":["window","desktop"],"description":"Use desktop with no pid/window_id to type into the current foreground application."},"pid":{"type":"integer","description":"Target process ID."},"text":{"type":"string","description":"Text to insert at the focused element's cursor."},- "window_id":{"type":"integer","description":"HWND of the target window. Required when element_index is used. Optional when element_token is supplied (the token carries it)."},- "element_index":{"type":"integer","description":"Element index from the last get_window_state for the same (pid, window_id). When supplied, type_text writes through UIA ValuePattern and reads that exact element back by handle. The shared ActionResult is confirmed only when the complete expected value is synchronously visible. If SetValue succeeds but read-back is stale or unavailable, the result is unverifiable with no escalation; take a fresh snapshot before retrying because deferred providers may publish only after this call returns. Requires window_id."},- "element_token": cua_driver_core::tool_schema::element_token_schema(),- "snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),- "x":{"type":"number","description":"Window-local screenshot-pixel X of the field to type into — the element px action form. Pass x,y (no element_index) and the tool pixel-clicks there to establish real renderer focus, then types. Use for Chromium/Electron inputs the UIA/WM_CHAR path can't reach. Read straight off the get_window_state PNG, same convention as click."},+ "window_id":{"type":"integer","description":"HWND of the target window. Omit when element_token is supplied (the token carries it)."},+ "element_token":{"type":"string","description":"Opaque element handle from get_window_state. When supplied, type_text writes through UIA ValuePattern and reads that exact element back by handle. The shared ActionResult is confirmed only when the complete expected value is synchronously visible. If SetValue succeeds but read-back is stale or unavailable, the result is unverifiable with no escalation; take a fresh snapshot before retrying because deferred providers may publish only after this call returns."},+ "x":{"type":"number","description":"Window-local screenshot-pixel X of the field to type into — the element px action form. Pass x,y (no element_token) and the tool pixel-clicks there to establish real renderer focus, then types. Use for Chromium/Electron inputs the UIA/WM_CHAR path can't reach. Read straight off the get_window_state PNG, same convention as click."},"y":{"type":"number","description":"Window-local screenshot-pixel Y of the field (see x)."},"delay_ms":{"type":"integer","minimum":0,"maximum":200,"description":"Milliseconds between characters. Default 30."},"delivery_mode": crate::input::delivery::delivery_mode_schema()@@ -4553,15 +4546,7 @@ impl Tool for TypeTextTool {Err(e) => return e,};let pid = raw_pid as u32;- // Surface 6: element_token / element_index precedence resolution.- let resolved = match self.state.element_cache.resolve_element_args(- pid as i32,- args.opt_u64("element_index").map(|v| v as usize),- args.opt_str("element_token").as_deref(),- args.opt_str("snapshot_id").as_deref(),- args.opt_u64("window_id"),- "type_text",- ) {+ let resolved = match self.state.snapshots.resolve(pid as i32, &args) {Ok(r) => r,Err(e) => return e,};@@ -4569,7 +4554,7 @@ impl Tool for TypeTextTool {let delivery = DeliveryMode::from_args(&args);// ── px form: focus by pixel-click, then type into the focused element ──- // Pass x,y (no element_index) for an *element px action*: pixel-click the+ // Pass x,y (no element_token) for an *element px action*: pixel-click the// field to give the Chromium/Electron renderer the real keyboard focus the// UIA/WM_CHAR path can't establish on its own, then fall through to the// focused-window WM_CHAR path below (which lands once focused). Reuses@@ -4580,7 +4565,7 @@ impl Tool for TypeTextTool {if let (Some(cx), Some(cy)) = (px, py) {if elem_idx.is_some() {return ToolResult::error(- "Pass either element_index (ax) or x,y (px) to type_text, not both.",+ "Pass either element_token (ax) or x,y (px) to type_text, not both.",);}let from_zoom = args@@ -4608,13 +4593,6 @@ impl Tool for TypeTextTool {}}- if elem_idx.is_some() && hwnd_opt.is_none() {- return ToolResult::error(- "window_id is required when element_index is used — the element_index cache \- is scoped per (pid, window_id). Pass the same window_id you used in \- `get_window_state`.",- );- }// Same no-raise guard as click: a XAML/WPF ValuePattern.SetValue handler// calls UIElement.Focus()→SetForegroundWindow; WS_EX_NOACTIVATE on the// target makes that a no-op while the value still gets set. Safe because@@ -4954,7 +4932,7 @@ impl Tool for TypeTextTool {// Prefer a focus-independent read of the *specific* cached element// when we have its index; only fall back to the (flaky, focus-// dependent) system focused element when typing into "whatever is- // focused" with no element_index.+ // focused" with no element_token.let read = |idx: Option<usize>| match idx {Some(_) => read_cached_element_value(&admitted),None => read_focused_value_uia(verify_pid),@@ -5100,7 +5078,7 @@ fn classify_value_write_readback(/// pattern. Mirrors the cache-retain + `mem::forget` discipline of the/// ValuePattern.SetValue path so the cached COM ref isn't released.fn read_cached_element_value(- admitted: &Option<crate::uia::cache::RetainedElement>,+ admitted: &Option<crate::uia::snapshot::RetainedElement>,) -> Option<String> {use windows::core::Interface;use windows::Win32::UI::Accessibility::{@@ -5195,7 +5173,7 @@ impl Tool for PressKeyTool {end, pageup, pagedown, f1-f12, plus any letter or digit. Optional `modifiers` \array takes ctrl/shift/alt/win. For true combinations (ctrl+c), `hotkey` is a \cleaner surface.\n\n\- `element_index` focuses the cached UIA element before sending the key; the \+ `element_token` focuses the cached UIA element before sending the key; the \top-level window remains backgrounded when delivery_mode is background.".into(),input_schema: json!({"type":"object","required":["key"],"properties":{@@ -5204,12 +5182,10 @@ impl Tool for PressKeyTool {"pid":{"type":"integer","description":"Target process ID."},"key":{"type":"string","description":"Key name (return, tab, escape, up, down, left, right, space, delete, home, end, pageup, pagedown, f1-f12, letter, digit)."},"modifiers":{"type":"array","items":{"type":"string"},"description":"Optional modifier names held while the key is pressed (ctrl/shift/alt/win)."},- "element_index":{"type":"integer","description":"Optional element_index from the last get_window_state; focuses that UIA element before the key is delivered."},"element_token": cua_driver_core::tool_schema::element_token_schema(),- "snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),- "x":{"type":"number","description":"Window-local screenshot-pixel X — the element px action form: pixel-click there to focus, then send the key. Use when the key must go to a Chromium/Electron surface the UIA path can't focus. Pass with y, no element_index."},+ "x":{"type":"number","description":"Window-local screenshot-pixel X — the element px action form: pixel-click there to focus, then send the key. Use when the key must go to a Chromium/Electron surface the UIA path can't focus. Pass with y, no element_token."},"y":{"type":"number","description":"Window-local screenshot-pixel Y (see x)."},- "window_id":{"type":"integer","description":"HWND for the target window. Required when element_index is used; otherwise auto-resolves the pid's first visible window."},+ "window_id":{"type":"integer","description":"HWND for the target window. Omit when element_token is supplied; otherwise auto-resolves the pid's first visible window."},"delivery_mode": crate::input::delivery::delivery_mode_schema()},"additionalProperties":false}),@@ -5262,15 +5238,7 @@ impl Tool for PressKeyTool {Err(e) => return e,};let pid = raw_pid as u32;- // Surface 6: element_token / element_index precedence resolution.- let resolved = match self.state.element_cache.resolve_element_args(- pid as i32,- args.opt_u64("element_index").map(|v| v as usize),- args.opt_str("element_token").as_deref(),- args.opt_str("snapshot_id").as_deref(),- args.opt_u64("window_id"),- "press_key",- ) {+ let resolved = match self.state.snapshots.resolve(pid as i32, &args) {Ok(r) => r,Err(e) => return e,};@@ -5278,13 +5246,6 @@ impl Tool for PressKeyTool {let delivery = DeliveryMode::from_args(&args);// Swift requires window_id when element_index is supplied — ports the// same validation.- if elem_idx.is_some() && hwnd_opt.is_none() {- return ToolResult::error(- "window_id is required when element_index is used — the element_index cache \- is scoped per (pid, window_id). Pass the same window_id you used in \- `get_window_state`.",- );- }// px form: pixel-click to focus, then the key goes to the focused element.// Reuses click's translation + delivery_mode; after it, deliver via the@@ -5297,7 +5258,7 @@ impl Tool for PressKeyTool {if let (Some(cx), Some(cy)) = (px, py) {if elem_idx.is_some() {return ToolResult::error(- "Pass either element_index (ax) or x,y (px) to press_key, not both.",+ "Pass either element_token (ax) or x,y (px) to press_key, not both.",);}let from_zoom = args@@ -5573,9 +5534,7 @@ impl Tool for HotkeyTool {"pid":{"type":"integer","description":"Target process ID."},"keys":{"type":"array","items":{"type":"string"},"minItems":2,"description":"Modifier(s) and one non-modifier key, e.g. [\"ctrl\", \"c\"]."},- "element_index": cua_driver_core::tool_schema::element_index_schema(),"element_token": cua_driver_core::tool_schema::element_token_schema(),- "snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),"x":{"type":"number","description":"Window-local screenshot-pixel X — the element px action form: pixel-click there to focus, then send the combo (so e.g. Ctrl+V pastes into that field). Pass with y. Use for Chromium/Electron surfaces the background combo can't reach."},"y":{"type":"number","description":"Window-local screenshot-pixel Y (see x)."},"window_id":{"type":"integer","description":"Explicit HWND when the pid owns multiple windows."},@@ -5680,25 +5639,11 @@ impl Tool for HotkeyTool {Err(e) => return e,};let pid = raw_pid as u32;- let resolved = match self.state.element_cache.resolve_element_args(- pid as i32,- args.opt_u64("element_index").map(|value| value as usize),- args.opt_str("element_token").as_deref(),- args.opt_str("snapshot_id").as_deref(),- args.opt_u64("window_id"),- "hotkey",- ) {+ let resolved = match self.state.snapshots.resolve(pid as i32, &args) {Ok(resolved) => resolved,Err(error) => return error,};let (elem_idx, hwnd_opt, admitted) = resolved.into_parts(args.opt_u64("window_id"));- if elem_idx.is_some() && hwnd_opt.is_none() {- return ToolResult::error(- "window_id is required when element_index is used — the element_index cache \- is scoped per (pid, window_id). Pass the same window_id you used in \- `get_window_state`.",- );- }let delivery = DeliveryMode::from_args(&args);// Resolve HWND: use window_id if given, else pick first window for pid.@@ -5741,7 +5686,7 @@ impl Tool for HotkeyTool {if let (Some(cx), Some(cy)) = (px, py) {if elem_idx.is_some() {return ToolResult::error(- "Pass either element_index (ax) or x,y (px) to hotkey, not both.",+ "Pass either element_token (ax) or x,y (px) to hotkey, not both.",);}let from_zoom = args@@ -5948,11 +5893,10 @@ impl Tool for SetValueTool {"type":"object","required":["pid","value"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer","description":"Target process ID."},- "window_id":{"type":"integer","description":"HWND of the window. Required when element_index is used; optional when element_token is supplied (the token carries it)."},- "element_index": cua_driver_core::tool_schema::element_index_schema(),+ "window_id":{"type":"integer","description":"HWND of the window. Omit when element_token is supplied (the token carries it)."},"element_token": cua_driver_core::tool_schema::element_token_schema(),- "snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),- "value":{"type":"string","description":"New value. UIA will coerce to the element's native type."}+ "value":{"type":"string","description":"New value. UIA will coerce to the element's native type."},+ "delivery_mode": crate::input::delivery::delivery_mode_schema()},"additionalProperties":false}),// Swift: idempotent: true (setting same value twice is idempotent).@@ -5961,28 +5905,17 @@ impl Tool for SetValueTool {}async fn invoke(&self, args: Value) -> ToolResult {- use cua_driver_core::tool_args::ArgsExt;let cursor_key = resolve_cursor_key(&args);let raw_pid = args.get("pid").and_then(|v| v.as_i64());if raw_pid.is_none() {- return ToolResult::error(- "Missing required integer fields pid, window_id, and element_index.",- );+ return ToolResult::error("Missing required integer field pid.");}let pid = raw_pid.unwrap() as u32;let value = match args.get("value").and_then(|v| v.as_str()) {Some(v) => v.to_owned(),None => return ToolResult::error("Missing required string field value."),};- // Surface 6: element_token / element_index precedence resolution.- let resolved = match self.state.element_cache.resolve_element_args(- pid as i32,- args.opt_u64("element_index").map(|v| v as usize),- args.opt_str("element_token").as_deref(),- args.opt_str("snapshot_id").as_deref(),- args.opt_u64("window_id"),- "set_value",- ) {+ let resolved = match self.state.snapshots.resolve(pid as i32, &args) {Ok(r) => r,Err(e) => return e,};@@ -6121,7 +6054,7 @@ impl Tool for ScrollTool {approaches reach backgrounded windows.\n\n\Mapping: `by: \"page\"` → SB_PAGEDOWN/UP/LEFT/RIGHT × amount; \`by: \"line\"` → SB_LINEDOWN/UP/LEFT/RIGHT × amount.\n\n\- Note: `element_index` is accepted for cross-platform parity but currently \+ Note: `element_token` is accepted for cross-platform parity but currently \no-op on Windows (UIA SetFocus not wired up yet — same caveat as `press_key`).".into(),input_schema: json!({"type":"object","required":["direction"],"properties":{@@ -6133,10 +6066,8 @@ impl Tool for ScrollTool {"description":"Number of scroll ticks. Default 3."},"x":{"type":"number","description":"With pid/window_id: window-local screenshot X used to target a nested scroll surface in foreground mode. Without pid/window_id: screen-absolute X for desktop scope. Must be paired with y."},"y":{"type":"number","description":"With pid/window_id: window-local screenshot Y used to target a nested scroll surface in foreground mode. Without pid/window_id: screen-absolute Y for desktop scope. Must be paired with x."},- "window_id":{"type":"integer","description":"HWND of the target window. Required when element_index is used; otherwise auto-resolves the pid's first visible window."},- "element_index":{"type":"integer","description":"Optional element_index. Accepted for parity; currently no-op on Windows."},+ "window_id":{"type":"integer","description":"HWND of the target window. Omit when element_token is supplied; otherwise auto-resolves the pid's first visible window."},"element_token": cua_driver_core::tool_schema::element_token_schema(),- "snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),"scope":{"type":"string","enum":["window","desktop"],"default":"window"},"delivery_mode": crate::input::delivery::delivery_mode_schema()},"additionalProperties":false@@ -6215,26 +6146,11 @@ impl Tool for ScrollTool {let by = args.str_or("by", "line");let direction_display = direction.clone();let by_display = by.clone();- // Surface 6: element_token / element_index precedence resolution.- let resolved = match self.state.element_cache.resolve_element_args(- pid as i32,- args.opt_u64("element_index").map(|v| v as usize),- args.opt_str("element_token").as_deref(),- args.opt_str("snapshot_id").as_deref(),- args.opt_u64("window_id"),- "scroll",- ) {+ let resolved = match self.state.snapshots.resolve(pid as i32, &args) {Ok(r) => r,Err(e) => return e,};let (elem_idx, hwnd_opt, admitted) = resolved.into_parts(args.opt_u64("window_id"));- if elem_idx.is_some() && hwnd_opt.is_none() {- return ToolResult::error(- "window_id is required when element_index is used — the element_index cache \- is scoped per (pid, window_id). Pass the same window_id you used in \- `get_window_state`.",- );- }// Resolve HWND: use window_id if given, else first window for pid.let hwnd = match hwnd_opt {@@ -6577,7 +6493,7 @@ async fn chromium_click_short_circuit(/// `spawn_blocking`. Returns `Some(Ok)` on success, `Some(Err)` if Invoke/// failed, `None` if the element isn't cached or has no InvokePattern.fn winui3_uia_multi_invoke(- admitted: &Option<crate::uia::cache::RetainedElement>,+ admitted: &Option<crate::uia::snapshot::RetainedElement>,hwnd: u64,count: usize,) -> Option<anyhow::Result<()>> {@@ -6636,7 +6552,7 @@ fn winui3_uia_multi_invoke(/// Returns `None` for non-WinUI3 targets (caller falls through to its normal/// routing).async fn winui3_background_gesture(- admitted: &Option<crate::uia::cache::RetainedElement>,+ admitted: &Option<crate::uia::snapshot::RetainedElement>,pid: u32,hwnd: u64,idx: Option<usize>,@@ -6699,7 +6615,7 @@ impl Tool for DoubleClickTool {// wired up — element path always falls back to a stamped pixel// double-click via PostMessage).description: "Double-click against a target pid. Two addressing modes:\n\n\- - `element_index` + `window_id` (from the last `get_window_state` snapshot \+ - `element_token` (from the last `get_window_state` snapshot \of that window) — synthesizes a stamped pixel double-click at the element's \cached on-screen center via PostMessage. (Windows has no AXOpen analogue; \Swift's AXOpen-first path falls through to the same pixel recipe when the \@@ -6707,17 +6623,14 @@ impl Tool for DoubleClickTool {- `x`, `y` (window-local screenshot pixels, top-left origin of the PNG \returned by `get_window_state`) — posts two WM_LBUTTONDOWN/UP pairs in \quick succession to the deepest child window at that point.\n\n\- Exactly one of `element_index` or (`x` AND `y`) must be provided. \- `pid` is required in both modes. `window_id` is required when \- `element_index` is used. The macOS-only `modifier` field is accepted for \+ Exactly one of `element_token` or (`x` AND `y`) must be provided. \+ `pid` is required in both modes. The macOS-only `modifier` field is accepted for \parity (no-op on Windows — PostMessage doesn't propagate modifier-key state).".into(),input_schema: json!({"type":"object","required":["pid"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer","description":"Target process ID."},- "window_id":{"type":"integer","description":"HWND for the target window. Required when element_index is used. Optional when element_token is supplied (the token carries it)."},- "element_index": cua_driver_core::tool_schema::element_index_schema(),+ "window_id":{"type":"integer","description":"HWND for the target window. Omit when element_token is supplied (the token carries it)."},"element_token": cua_driver_core::tool_schema::element_token_schema(),- "snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),"x":{"type":"number","description":"X in window-local screenshot pixels. Must be provided together with y."},"y":{"type":"number","description":"Y in window-local screenshot pixels. Must be provided together with x."},"modifier": cua_driver_core::tool_schema::modifier_schema(),@@ -6736,15 +6649,7 @@ impl Tool for DoubleClickTool {};let pid = raw_pid as u32;use cua_driver_core::tool_args::ArgsExt;- // Surface 6: element_token / element_index precedence resolution.- let resolved = match self.state.element_cache.resolve_element_args(- pid as i32,- args.opt_u64("element_index").map(|v| v as usize),- args.opt_str("element_token").as_deref(),- args.opt_str("snapshot_id").as_deref(),- args.opt_u64("window_id"),- "double_click",- ) {+ let resolved = match self.state.snapshots.resolve(pid as i32, &args) {Ok(r) => r,Err(e) => return e,};@@ -6753,25 +6658,18 @@ impl Tool for DoubleClickTool {let y = args.opt_f64("y");let delivery = DeliveryMode::from_args(&args);let cursor_key = resolve_cursor_key(&args);- // Swift validates "both x and y or neither" and "no element_index without window_id".+ // Swift validates "both x and y or neither" and "no element_token without window_id".let has_xy = x.is_some() && y.is_some();let partial_xy = x.is_some() != y.is_some();if partial_xy {return ToolResult::error("Provide both x and y together, not just one.");}if elem_idx.is_some() && has_xy {- return ToolResult::error("Provide either element_index or (x, y), not both.");+ return ToolResult::error("Provide either element_token or (x, y), not both.");}if elem_idx.is_none() && !has_xy {return ToolResult::error(- "Provide element_index or (x, y) to address the double-click target.",- );- }- if elem_idx.is_some() && hwnd_opt.is_none() {- return ToolResult::error(- "window_id is required when element_index is used — the element_index cache \- is scoped per (pid, window_id). Pass the same window_id you used in \- `get_window_state`.",+ "Provide element_token or (x, y) to address the double-click target.",);}@@ -6960,7 +6858,7 @@ impl Tool for DoubleClickTool {cursor_key.clone(),cursor_overlay::OverlayCommand::ClickPulse { x: sx, y: sy },);- // delivery_mode:"background" on WinUI3 (pixel path, no element_index): a+ // delivery_mode:"background" on WinUI3 (pixel path, no element_token): a// background double-click on WinUI3 only lands via UIA Invoke on a// cached element, which the pixel path doesn't have → structured// error (caller retries with delivery_mode:foreground or uses element_index).@@ -7074,7 +6972,7 @@ impl Tool for RightClickTool {// analogue (UIA ShowContextMenu) is not yet wired up, so element// path falls through to the pixel recipe at the cached center.description: "Right-click against a target pid. Two addressing modes:\n\n\- - `element_index` + `window_id` (from the last `get_window_state` snapshot \+ - `element_token` (from the last `get_window_state` snapshot \of that window) — posts WM_RBUTTONDOWN/UP at the element's cached on-screen \center via PostMessage. (Windows has no AXShowMenu analogue wired up yet; \Swift's AX-action path falls through to the same pixel recipe on non-\@@ -7082,17 +6980,15 @@ impl Tool for RightClickTool {- `x`, `y` (window-local screenshot pixels, top-left origin of the PNG \returned by `get_window_state`) — posts WM_RBUTTONDOWN/UP to the deepest \child window at that point.\n\n\- Exactly one of `element_index` or (`x` AND `y`) must be provided. `pid` is \- required in both modes. `window_id` is required when `element_index` is used. \+ Exactly one of `element_token` or (`x` AND `y`) must be provided. `pid` is \+ required in both modes. \`modifier` is accepted for parity (no-op on Windows — PostMessage doesn't \propagate modifier-key state).".into(),input_schema: json!({"type":"object","required":["pid"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer","description":"Target process ID."},- "window_id":{"type":"integer","description":"HWND for the target window. Required when element_index is used. Optional when element_token is supplied (the token carries it)."},- "element_index": cua_driver_core::tool_schema::element_index_schema(),+ "window_id":{"type":"integer","description":"HWND for the target window. Omit when element_token is supplied (the token carries it)."},"element_token": cua_driver_core::tool_schema::element_token_schema(),- "snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),"x":{"type":"number","description":"X in window-local screenshot pixels. Must be provided together with y."},"y":{"type":"number","description":"Y in window-local screenshot pixels. Must be provided together with x."},"modifier": cua_driver_core::tool_schema::modifier_schema(),@@ -7111,15 +7007,7 @@ impl Tool for RightClickTool {};let pid = raw_pid as u32;use cua_driver_core::tool_args::ArgsExt;- // Surface 6: element_token / element_index precedence resolution.- let resolved = match self.state.element_cache.resolve_element_args(- pid as i32,- args.opt_u64("element_index").map(|v| v as usize),- args.opt_str("element_token").as_deref(),- args.opt_str("snapshot_id").as_deref(),- args.opt_u64("window_id"),- "right_click",- ) {+ let resolved = match self.state.snapshots.resolve(pid as i32, &args) {Ok(r) => r,Err(e) => return e,};@@ -7135,18 +7023,11 @@ impl Tool for RightClickTool {return ToolResult::error("Provide both x and y together, not just one.");}if elem_idx.is_some() && has_xy {- return ToolResult::error("Provide either element_index or (x, y), not both.");+ return ToolResult::error("Provide either element_token or (x, y), not both.");}if elem_idx.is_none() && !has_xy {return ToolResult::error(- "Provide element_index or (x, y) to address the right-click target.",- );- }- if elem_idx.is_some() && hwnd_opt.is_none() {- return ToolResult::error(- "window_id is required when element_index is used — the element_index cache \- is scoped per (pid, window_id). Pass the same window_id you used in \- `get_window_state`.",+ "Provide element_token or (x, y) to address the right-click target.",);}@@ -8878,7 +8759,7 @@ impl Tool for ZoomTool {the target remains visible even if the caller's coordinates are slightly off.\n\n\After a zoom, pass `from_zoom=true` to click/type_text to auto-translate \coordinates back to full-window space. Coordinate actions return \- `screenshot_context_missing` when the latest snapshot does not contain a \+ `screenshot_context_missing` when no current snapshot contains a \screenshot owned by this session. `from_zoom` actions return \`zoom_context_missing` when the zoom was never created or was replaced; call \`get_window_state`, then `zoom`, again on the same connection.\n\n\@@ -8937,7 +8818,7 @@ impl Tool for ZoomTool {// ratio so the crop lands on the intended region; the zoom context then// holds native-pixel values, which is what `from_zoom` clicks expect.let session_id = args.opt_str("_session_id");- let (pid, screenshot) = match self.state.element_cache.screenshot_context_for_zoom(+ let (pid, screenshot) = match self.state.snapshots.screenshot_context_for_zoom(requested_pid,hwnd,session_id.as_deref(),@@ -8961,8 +8842,7 @@ impl Tool for ZoomTool {match result {Ok(Ok(crop)) => {- if let Err(refusal) = state.zoom_registry.set_if_current(- &state.element_cache,+ if let Err(refusal) = state.snapshots.set_zoom(pid,session_id.as_deref(),ZoomContext {@@ -9024,7 +8904,6 @@ impl Tool for TypeTextCharsTool {"window_id":{"type":"integer"},"text":{"type":"string"},"delay_ms":{"type":"integer","description":"Milliseconds between chars (default 30)."},- "element_index":{"type":"integer"},"type_chars_only":{"type":"boolean","description":"Skip element focus, type directly. Default false."}},"additionalProperties":false}),@@ -10135,7 +10014,7 @@ pub fn build_registry_with_provider(};// Share the element cache with the recording-hook layer so it can// resolve element_index → window-local screenshot coords for click.png.- crate::recording_hooks::set_element_cache(state.element_cache.clone());+ crate::recording_hooks::set_snapshots(state.snapshots.clone());// Drop a session's owned cursor on `session_end` (explicit end_session, the// CLI `session end` verb, or the daemon idle-TTL sweep). The session id IS@@ -10146,12 +10025,10 @@ pub fn build_registry_with_provider(// deregisters when that runtime's registry is dropped. Mirrors the macOS// `register_all` session_end hook (platform-macos/src/tools/mod.rs).let cursor_registry = state.cursor_registry.clone();- let element_cache = state.element_cache.clone();- let zoom_registry = state.zoom_registry.clone();+ let snapshots = state.snapshots.clone();let session_end_hook =cua_driver_core::session::register_scoped_session_end_hook(move |session_id| {- zoom_registry.retire_session(session_id);- element_cache.retire_session_screenshots(session_id);+ snapshots.retire_session_screenshots(session_id);cursor_registry.remove(session_id);crate::overlay::remove_cursor(session_id.to_owned());});diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/stubs.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/stubs.rsindex d87386eca2..5ec3aa9229 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/stubs.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/stubs.rs@@ -93,7 +93,7 @@ stub_tool!();stub_tool!(get_window_state_m, GetWindowStateTool, "get_window_state",- "Always returns BOTH the element tree AND a screenshot — ground on both and cross-check (the tree lies on some surfaces). Choose the modality at ACTION time: an element ax action (element_index/element_token → accessibility rung) or an element px action (x,y → pixel rung off this screenshot). capture_mode is deprecated and ignored.",+ "Always returns BOTH the element tree AND a screenshot — ground on both and cross-check (the tree lies on some surfaces). Choose the modality at ACTION time: an element ax action (element_token → accessibility rung) or an element px action (x,y → pixel rung off this screenshot). capture_mode is deprecated and ignored.",serde_json::json!({"type":"object","required":["pid","window_id"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"window_id":{"type":"integer"},"query":{"type":"string"},"capture_mode": cua_driver_core::capture_mode::capture_mode_schema(),"include_screenshot":{"type":"boolean","description":"Default true — returns a grounding screenshot alongside the tree. Set false to skip the grab and return tree only (the cheap path for re-indexing before an element ax action)."}},"additionalProperties":false}));stub_tool!(@@ -112,16 +112,16 @@ stub_tool!(click_m,ClickTool,"click",- "Click at (x, y) or on an AX/UIA element by element_index + window_id.",- serde_json::json!({"type":"object","required":[],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"element_token": cua_driver_core::tool_schema::element_token_schema(),"snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),"x":{"type":"number"},"y":{"type":"number"},"button": cua_driver_core::tool_schema::button_schema(),"modifier": cua_driver_core::tool_schema::modifier_schema(),"from_zoom":{"type":"boolean"}},"additionalProperties":false})+ "Click at (x, y) or on an AX/UIA element by element_token.",+ serde_json::json!({"type":"object","required":[],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"window_id":{"type":"integer"},"element_token": cua_driver_core::tool_schema::element_token_schema(),"x":{"type":"number"},"y":{"type":"number"},"button": cua_driver_core::tool_schema::button_schema(),"modifier": cua_driver_core::tool_schema::modifier_schema(),"from_zoom":{"type":"boolean"}},"additionalProperties":false}));stub_tool!(double_click_m,DoubleClickTool,"double_click",- "Double-click at (x, y) or on an AX/UIA element by element_index + window_id.",- serde_json::json!({"type":"object","required":["pid"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"x":{"type":"number"},"y":{"type":"number"},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema()},"additionalProperties":false})+ "Double-click at (x, y) or on an AX/UIA element by element_token.",+ serde_json::json!({"type":"object","required":["pid"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"x":{"type":"number"},"y":{"type":"number"},"window_id":{"type":"integer"},"element_token": cua_driver_core::tool_schema::element_token_schema()},"additionalProperties":false}));stub_tool!(@@ -129,19 +129,19 @@ stub_tool!(RightClickTool,"right_click","Right-click (AXShowMenu on element, or synthesized event at x,y).",- serde_json::json!({"type":"object","required":["pid"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"window_id":{"type":"integer"},"x":{"type":"number"},"y":{"type":"number"},"modifier": cua_driver_core::tool_schema::modifier_schema()},"additionalProperties":false})+ serde_json::json!({"type":"object","required":["pid"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"element_token": cua_driver_core::tool_schema::element_token_schema(),"window_id":{"type":"integer"},"x":{"type":"number"},"y":{"type":"number"},"modifier": cua_driver_core::tool_schema::modifier_schema()},"additionalProperties":false}));stub_tool!(type_text_m, TypeTextTool, "type_text","Insert text into the target pid via AXSelectedText or WM_CHAR. Falls back to CGEvent/keystrokes.",- serde_json::json!({"type":"object","required":["pid","text"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"text":{"type":"string"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"window_id":{"type":"integer"},"x":{"type":"number"},"y":{"type":"number"}},"additionalProperties":false}));+ serde_json::json!({"type":"object","required":["pid","text"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"text":{"type":"string"},"element_token": cua_driver_core::tool_schema::element_token_schema(),"window_id":{"type":"integer"},"x":{"type":"number"},"y":{"type":"number"}},"additionalProperties":false}));stub_tool!(type_chars_m,TypeTextCharsTool,"type_text_chars","Type text character-by-character with configurable per-character delay.",- serde_json::json!({"type":"object","required":["pid","text"],"properties":{"pid":{"type":"integer"},"text":{"type":"string"},"delay_ms":{"type":"integer"},"window_id":{"type":"integer"},"element_index":{"type":"integer"}},"additionalProperties":false})+ serde_json::json!({"type":"object","required":["pid","text"],"properties":{"pid":{"type":"integer"},"text":{"type":"string"},"delay_ms":{"type":"integer"},"window_id":{"type":"integer"},"element_token": cua_driver_core::tool_schema::element_token_schema()},"additionalProperties":false}));stub_tool!(@@ -149,7 +149,7 @@ stub_tool!(PressKeyTool,"press_key","Press and release a single key delivered directly to the target pid. No focus steal.",- serde_json::json!({"type":"object","required":["pid","key"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"key":{"type":"string"},"modifiers":{"type":"array","items":{"type":"string"}},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"x":{"type":"number"},"y":{"type":"number"}},"additionalProperties":false})+ serde_json::json!({"type":"object","required":["pid","key"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"key":{"type":"string"},"modifiers":{"type":"array","items":{"type":"string"}},"window_id":{"type":"integer"},"element_token": cua_driver_core::tool_schema::element_token_schema(),"x":{"type":"number"},"y":{"type":"number"}},"additionalProperties":false}));stub_tool!(@@ -165,12 +165,12 @@ stub_tool!(SetValueTool,"set_value","Set the value of an AX/UIA element (text field, dropdown, checkbox).",- serde_json::json!({"type":"object","required":["pid","window_id","element_index","value"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"value":{"type":"string"}},"additionalProperties":false})+ serde_json::json!({"type":"object","required":["pid","value"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"window_id":{"type":"integer"},"element_token": cua_driver_core::tool_schema::element_token_schema(),"value":{"type":"string"}},"additionalProperties":false}));stub_tool!(scroll_m, ScrollTool, "scroll","Scroll the target pid's focused region. direction required; by defaults to line, amount defaults to 3.",- serde_json::json!({"type":"object","required":["direction"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"direction":{"type":"string","enum":["up","down","left","right"]},"by":{"type":"string","enum":["line","page"]},"amount":{"type":"integer","minimum":1,"maximum":50},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema()},"additionalProperties":false}));+ serde_json::json!({"type":"object","required":["direction"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"direction":{"type":"string","enum":["up","down","left","right"]},"by":{"type":"string","enum":["line","page"]},"amount":{"type":"integer","minimum":1,"maximum":50},"window_id":{"type":"integer"},"element_token": cua_driver_core::tool_schema::element_token_schema()},"additionalProperties":false}));stub_tool!(screenshot_m, ScreenshotTool, "screenshot","Capture a screenshot. Without window_id captures the full display. Supports png and jpeg formats.",diff --git a/libs/cua-driver/rust/crates/platform-windows/src/uia/mod.rs b/libs/cua-driver/rust/crates/platform-windows/src/uia/mod.rsindex 6a15ce99b4..7536aed789 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/uia/mod.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/uia/mod.rs@@ -28,11 +28,11 @@ use windows::Win32::UI::Accessibility::{UIA_ValueValuePropertyId,};-pub mod cache;pub mod fg_bypass;pub mod scroll;+pub mod snapshot;pub mod windows_enum;-pub use cache::ElementCache;+pub use snapshot::Snapshots;pub use windows_enum::enumerate_top_level_windows;/// Default cap; callers can override via [`walk_tree_bounded`].@@ -68,7 +68,7 @@ pub struct UiaNode {/// Toggle/selection state when the element exposes one of those patterns.pub selected: Option<bool>,/// Raw COM pointer (IUIAutomationElement for UIA path, IAccessible for- /// MSAA path) as usize. Retained — `ElementCache` Drop releases it via+ /// MSAA path) as usize. Retained — `Snapshots` Drop releases it via/// the `kind`-appropriate vtable.pub element_ptr: usize,/// Screen-coordinate center, captured at walk time to avoid later COM calls.diff --git a/libs/cua-driver/rust/crates/platform-windows/src/uia/cache.rs b/libs/cua-driver/rust/crates/platform-windows/src/uia/snapshot.rssimilarity index 92%rename from libs/cua-driver/rust/crates/platform-windows/src/uia/cache.rsrename to libs/cua-driver/rust/crates/platform-windows/src/uia/snapshot.rsindex 19139b2093..5f2e69a7ba 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/uia/cache.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/uia/snapshot.rs@@ -1,9 +1,9 @@use super::UiaNode;-use cua_driver_core::element_cache::{ElementCacheCore, SnapshotPayload};+use cua_driver_core::snapshot_store::{SnapshotPayload, SnapshotStore};use windows::core::Interface;use windows::Win32::UI::Accessibility::{IAccessible, IUIAutomationElement};-pub type ElementCache = ElementCacheCore<CachedSnapshot>;+pub type Snapshots = SnapshotStore<UiaSnapshot>;#[derive(Debug)]pub struct RetainedElement {@@ -95,11 +95,11 @@ pub enum SnapshotKind {Msaa,}-pub struct CachedSnapshot {+pub struct UiaSnapshot {elements: Vec<RetainedElement>,}-impl CachedSnapshot {+impl UiaSnapshot {pub fn from_nodes(nodes: &[UiaNode], kind: SnapshotKind) -> Self {Self {elements: nodes@@ -117,7 +117,7 @@ impl CachedSnapshot {}}-impl SnapshotPayload for CachedSnapshot {+impl SnapshotPayload for UiaSnapshot {type Element = RetainedElement;fn len(&self) -> usize {@@ -133,5 +133,5 @@ impl SnapshotPayload for CachedSnapshot {}#[cfg(test)]-#[path = "cache_uaf_repro.rs"]-mod cache_uaf_repro;+#[path = "snapshot_uaf_repro.rs"]+mod snapshot_uaf_repro;diff --git a/libs/cua-driver/rust/crates/platform-windows/src/uia/cache_uaf_repro.rs b/libs/cua-driver/rust/crates/platform-windows/src/uia/snapshot_uaf_repro.rssimilarity index 92%rename from libs/cua-driver/rust/crates/platform-windows/src/uia/cache_uaf_repro.rsrename to libs/cua-driver/rust/crates/platform-windows/src/uia/snapshot_uaf_repro.rsindex 9f6e95d0fb..276517bb69 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/uia/cache_uaf_repro.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/uia/snapshot_uaf_repro.rs@@ -3,8 +3,8 @@//!//! THE RACE (what these tests model)://! Two concurrent sessions drive the same (pid, hwnd).-//! - Session A: `get_window_state` → `ElementCache::update` → `core.insert`-//! replaces the snapshot → old `CachedSnapshot::drop` → COM `Release` on+//! - Session A: `get_window_state` → `Snapshots::update` → `core.insert`+//! replaces the snapshot → old `UiaSnapshot::drop` → COM `Release` on//! every cached `IUIAutomationElement`.//! - Session B: `click` / `type_text` / `set_value` looked the element up out//! of the cache and is mid-action, dereferencing the same COM pointer.@@ -18,7 +18,7 @@//! (`AddRef` via `clone()`, `Release` via `drop`). So we feed it a real,//! independently-refcounted COM-ABI object of our own (`FakeObj`) with a//! hand-rolled IUnknown vtable. The cache's real `with_snapshot` mutex, real-//! `CachedSnapshot::drop`, and the real retain-under-lock resolution all run+//! `UiaSnapshot::drop`, and the real retain-under-lock resolution all run//! unchanged against it. An AddRef/Release seen while the refcount is//! already <= 0 bumps a shared `uaf_hits` counter (a use-after-free that a//! sanitizer would flag); memory stays mapped so the assertion is@@ -28,7 +28,7 @@//! replaces + releases → B dereferences) with channels instead of relying on//! luck.-use super::{CachedSnapshot, ElementCache, RetainedElement, SnapshotKind};+use super::{RetainedElement, SnapshotKind, Snapshots, UiaSnapshot};use cua_driver_core::element_token::{token_for, ResolvedElement};use std::ffi::c_void;use std::sync::atomic::{AtomicIsize, AtomicUsize, Ordering};@@ -104,8 +104,8 @@ fn make_fake(uaf_hits: &'static AtomicUsize) -> usize {Box::into_raw(obj) as usize}-fn snapshot_with(ptrs: Vec<usize>) -> CachedSnapshot {- CachedSnapshot {+fn snapshot_with(ptrs: Vec<usize>) -> UiaSnapshot {+ UiaSnapshot {elements: ptrs.into_iter().map(|ptr| RetainedElement {@@ -119,15 +119,11 @@ fn snapshot_with(ptrs: Vec<usize>) -> CachedSnapshot {}}-fn acquire(cache: &ElementCache, snapshot: u32, idx: usize) -> Option<RetainedElement> {+fn acquire(cache: &Snapshots, snapshot: u32, idx: usize) -> Option<RetainedElement> {match cache- .resolve_element_args(+ .resolve(PID as i32,- None,- Some(&token_for(snapshot, idx)),- None,- Some(HWND),- "test",+ &serde_json::json!({ "element_token": token_for(snapshot, idx) }),).ok()?{@@ -154,7 +150,7 @@ const HWND: u64 = (1_u64 << 40) | 0x1234;/// number of use-after-free touches observed.fn run_forced_interleave() -> usize {let uaf_hits: &'static AtomicUsize = Box::leak(Box::new(AtomicUsize::new(0)));- let cache = Arc::new(ElementCache::new());+ let cache = Arc::new(Snapshots::new());let ptr = make_fake(uaf_hits);let snapshot = cache.publish(PID as i32, HWND, snapshot_with(vec![ptr]));@@ -199,7 +195,7 @@ fn fixed_path_survives_concurrent_replace() {#[test]fn fixed_path_stress_no_uaf() {let uaf_hits: &'static AtomicUsize = Box::leak(Box::new(AtomicUsize::new(0)));- let cache = Arc::new(ElementCache::new());+ let cache = Arc::new(Snapshots::new());// Seed a snapshot of several elements.let seed: Vec<usize> = (0..8).map(|_| make_fake(uaf_hits)).collect();@@ -251,7 +247,7 @@ fn fixed_path_stress_no_uaf() {#[test]fn exact_snapshot_retains_matching_identity_and_geometry() {let hits = Box::leak(Box::new(AtomicUsize::new(0)));- let cache = ElementCache::new();+ let cache = Snapshots::new();let ptr = make_fake(hits);let mut payload = snapshot_with(vec![ptr]);payload.elements[0].kind = SnapshotKind::Msaa;@@ -270,16 +266,6 @@ fn exact_snapshot_retains_matching_identity_and_geometry() {assert!(guard.focus_element().is_err());assert_eq!(guard.element_has_keyboard_focus(), None);assert_eq!(acquire(&cache, second, 0).unwrap().center, (0, 0));- assert!(cache- .resolve_element_args(- PID as i32,- None,- Some(&token_for(second, 0)),- None,- Some(HWND + 1),- "test",- )- .is_err());let cloned = guard.clone();drop(guard);unsafe { touch_vtable(cloned.as_ptr()) };@@ -294,7 +280,7 @@ fn exact_snapshot_retains_matching_identity_and_geometry() {#[test]fn eviction_remove_and_clear_release_payload_but_not_acquired_guard() {let hits = Box::leak(Box::new(AtomicUsize::new(0)));- let cache = ElementCache::new();+ let cache = Snapshots::new();let ptr = make_fake(hits);let first = cache.publish(PID as i32, HWND, snapshot_with(vec![ptr]));let guard = acquire(&cache, first, 0).unwrap();@@ -334,7 +320,7 @@ fn eviction_remove_and_clear_release_payload_but_not_acquired_guard() {#[tokio::test]async fn detached_worker_keeps_only_admitted_target_and_geometry() {let hits = Box::leak(Box::new(AtomicUsize::new(0)));- let cache = ElementCache::new();+ let cache = Snapshots::new();let target = make_fake(hits);let sibling = make_fake(hits);let mut payload = snapshot_with(vec![target, sibling]);@@ -394,8 +380,8 @@ async fn detached_worker_keeps_only_admitted_target_and_geometry() {fn recording_metadata_uses_snapshot_without_native_geometry() {cua_driver_core::tool::with_runtime_scope("windows-recording-metadata-test".into(), || {let hits = Box::leak(Box::new(AtomicUsize::new(0)));- let cache = Arc::new(ElementCache::new());- cua_driver_core::element_cache::register_runtime_cache(&cache);+ let cache = Arc::new(Snapshots::new());+ cua_driver_core::snapshot_store::register_runtime_store(&cache);let ptr = make_fake(hits);let id = cache.publish(PID as i32, HWND, snapshot_with(vec![ptr]));let args = serde_json::json!({"element_token": token_for(id, 0)});@@ -414,7 +400,7 @@ fn recording_metadata_uses_snapshot_without_native_geometry() {#[test]fn null_native_pointer_is_not_an_actionable_member() {- let cache = ElementCache::new();+ let cache = Snapshots::new();let snapshot = cache.publish(PID as i32, HWND, snapshot_with(vec![0]));assert!(acquire(&cache, snapshot, 0).is_none());}@@ -423,7 +409,7 @@ fn null_native_pointer_is_not_an_actionable_member() {async fn cancelled_caller_keeps_the_blocking_workers_native_target_alive() {let hits = Box::leak(Box::new(AtomicUsize::new(0)));let ptr = make_fake(hits);- let cache = ElementCache::new();+ let cache = Snapshots::new();let snapshot = cache.publish(PID as i32, HWND, snapshot_with(vec![ptr]));let guard = acquire(&cache, snapshot, 0).unwrap();let (started_tx, started_rx) = tokio::sync::oneshot::channel();diff --git a/libs/cua-driver/rust/fuzz/corpus/mcp_request/typed_target.json b/libs/cua-driver/rust/fuzz/corpus/mcp_request/typed_target.jsonindex 8a0dfbf321..71cc289030 100644--- a/libs/cua-driver/rust/fuzz/corpus/mcp_request/typed_target.json+++ b/libs/cua-driver/rust/fuzz/corpus/mcp_request/typed_target.json@@ -1 +1 @@-{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"click","arguments":{"target":{"kind":"window","pid":42,"window_id":7},"element_index":3,"dispatch":"Foreground"}}}\ No newline at end of file+{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"click","arguments":{"target":{"kind":"window","pid":42,"window_id":7},"element_token":"s00000001:3","dispatch":"Foreground"}}}\ No newline at end of filediff --git a/libs/cua-driver/tests/fixtures/smoke/macos.sh b/libs/cua-driver/tests/fixtures/smoke/macos.shindex 28403af3c4..1c428b023e 100755--- a/libs/cua-driver/tests/fixtures/smoke/macos.sh+++ b/libs/cua-driver/tests/fixtures/smoke/macos.sh@@ -168,7 +168,7 @@ elserun_tool press_key "{\"pid\":$HARNESS_PID,\"window_id\":$WIN_ID,\"key\":\"a\"}"run_tool hotkey "{\"pid\":$HARNESS_PID,\"window_id\":$WIN_ID,\"keys\":[\"cmd\",\"a\"]}"run_tool bring_to_front "{\"pid\":$HARNESS_PID,\"window_id\":$WIN_ID}"- # set_value needs element_index — we don't have one without a snapshot.+ # set_value needs element_token — we don't have one without a snapshot.record set_value SKIP "exercised by harness_appkit_text_input integration test instead"fidiff --git a/samples/driver/multi-cursor/Cargo.lock b/samples/driver/multi-cursor/Cargo.lockindex 8df441af11..d250f01141 100644--- a/samples/driver/multi-cursor/Cargo.lock+++ b/samples/driver/multi-cursor/Cargo.lock@@ -79,6 +79,12 @@ dependencies = ["png",]+[[package]]+name = "itoa"+version = "1.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"+[[package]]name = "legacy-app"version = "0.1.0"@@ -86,6 +92,12 @@ dependencies = ["windows",]+[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"+[[package]]name = "miniz_oxide"version = "0.8.9"@@ -120,6 +132,7 @@ name = "orchestrator"version = "0.1.0"dependencies = ["image",+ "serde_json","windows",]@@ -160,6 +173,48 @@ dependencies = ["proc-macro2",]+[[package]]+name = "serde"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"+dependencies = [+ "serde_core",+]++[[package]]+name = "serde_core"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "serde_json"+version = "1.0.151"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"+dependencies = [+ "itoa",+ "memchr",+ "serde",+ "serde_core",+ "zmij",+]+[[package]]name = "simd-adler32"version = "0.3.9"@@ -177,6 +232,17 @@ dependencies = ["unicode-ident",]+[[package]]+name = "syn"+version = "3.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]+[[package]]name = "unicode-ident"version = "1.0.24"@@ -214,7 +280,7 @@ checksum = "2bbd5b46c938e506ecbce286b6628a02171d56153ba733b6c741fc627ec9579b"dependencies = ["proc-macro2","quote",- "syn",+ "syn 2.0.117",][[package]]@@ -225,7 +291,7 @@ checksum = "053c4c462dc91d3b1504c6fe5a726dd15e216ba718e84a0e46a88fbe5ded3515"dependencies = ["proc-macro2","quote",- "syn",+ "syn 2.0.117",][[package]]@@ -310,3 +376,9 @@ name = "windows_x86_64_msvc"version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"++[[package]]+name = "zmij"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"diff --git a/samples/driver/multi-cursor/orchestrator/Cargo.toml b/samples/driver/multi-cursor/orchestrator/Cargo.tomlindex 889bd24dce..f2da4e40ad 100644--- a/samples/driver/multi-cursor/orchestrator/Cargo.toml+++ b/samples/driver/multi-cursor/orchestrator/Cargo.toml@@ -15,6 +15,8 @@ windows-app = [][dependencies]# PNG decode + resize for the screenshot-based maze line-diff verification.image = { version = "0.25", default-features = false, features = ["png"] }+# Reads element_token from get_window_state's structured output.+serde_json = "1"windows = { version = "0.58", features = ["Win32_Foundation","Win32_UI_WindowsAndMessaging",diff --git a/samples/driver/multi-cursor/orchestrator/src/main.rs b/samples/driver/multi-cursor/orchestrator/src/main.rsindex 8c4cfd1209..3ffe2d638a 100644--- a/samples/driver/multi-cursor/orchestrator/src/main.rs+++ b/samples/driver/multi-cursor/orchestrator/src/main.rs@@ -189,19 +189,22 @@ fn main() {let ax = format!(r#"{{"pid":{pid},"window_id":{hwnd_addr},"capture_mode":"ax","session":"{session}"}}"#);let mut seen_records: i64 = -1;for act in rx {- // Re-discover element indices on a FRESH snapshot each action —- // a11y vs pixel is decided per action (Chromium's tree appears- // late and re-numbers as rows are added; GDI never has a tree).+ // Re-read the window before each action: element tokens are+ // bound to the snapshot that read minted, and a11y vs pixel is+ // decided per action (Chromium's tree appears late and+ // re-numbers as rows are added; GDI never has a tree).let tree = run_call_out(&cua, "get_window_state", &ax);- let field = find_idx(&tree, |l| l.contains("] Edit"));- let submit = find_idx(&tree, |l| l.contains("] Button") && l.to_uppercase().contains("ADD RECORD"));+ let field = find_idx(&tree, |l| l.contains("] Edit"))+ .and_then(|idx| element_token(&tree, idx));+ let submit = find_idx(&tree, |l| l.contains("] Button") && l.to_uppercase().contains("ADD RECORD"))+ .and_then(|idx| element_token(&tree, idx));match act {Action::Type { text } => {let ok = match field {- // a11y: plain type_text with element_index — cua-driver+ // a11y: plain type_text with element_token — cua-driver// auto-routes to UIA ValuePattern.SetValue on its own.- Some(idx) => run_call(&cua, "type_text", &format!(- r#"{{"pid":{pid},"window_id":{hwnd_addr},"element_index":{idx},"text":"{}","session":"{session}"}}"#, json_escape(&text))),+ Some(token) => run_call(&cua, "type_text", &format!(+ r#"{{"pid":{pid},"window_id":{hwnd_addr},"element_token":"{}","text":"{}","session":"{session}"}}"#, json_escape(&token), json_escape(&text))),// no a11y (GDI): focus the field by pixel, then WM_CHAR.None => {if let Some((x, y)) = client_rel_to_local_px(hwnd, FIELD_FRAC.0, FIELD_FRAC.1) {@@ -216,8 +219,8 @@ fn main() {}Action::Click { rx, ry } => {let ok = match submit {- Some(idx) => run_call(&cua, "click", &format!(- r#"{{"pid":{pid},"window_id":{hwnd_addr},"element_index":{idx},"session":"{session}"}}"#)),+ Some(token) => run_call(&cua, "click", &format!(+ r#"{{"pid":{pid},"window_id":{hwnd_addr},"element_token":"{}","session":"{session}"}}"#, json_escape(&token))),None => {if let Some((x, y)) = client_rel_to_local_px(hwnd, rx, ry) {run_call(&cua, "click", &format!(@@ -495,6 +498,18 @@ fn find_idx(tree: &str, pred: impl Fn(&str) -> bool) -> Option<u64> {None}+/// The `element_token` that get_window_state minted for row `[idx]`. Actions+/// address elements only by this token, which is bound to that read.+fn element_token(state: &str, idx: u64) -> Option<String> {+ let state: serde_json::Value = serde_json::from_str(state).ok()?;+ state["elements"]+ .as_array()?+ .iter()+ .find(|element| element["element_index"].as_u64() == Some(idx))?["element_token"]+ .as_str()+ .map(str::to_owned)+}+/// Parse the "Records: N" counter from a window-state tree (status bar).fn records_count(tree: &str) -> Option<u32> {let pos = tree.find("Records:")?;