Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(cua-driver-rs): agent-guidance refactor + uninstall converge + warnings cleanup (#1665)

Francesco Bonaccic52d850a62f1
diff --git a/.github/workflows/cd-rust-cua-driver.yml b/.github/workflows/cd-rust-cua-driver.yml
index fd86dde53b..47d159dd04 100644
--- a/.github/workflows/cd-rust-cua-driver.yml
+++ b/.github/workflows/cd-rust-cua-driver.yml
@@ -446,14 +446,15 @@ jobs:
cp libs/cua-driver/scripts/install.ps1 release-upload/install.ps1
cp libs/cua-driver/scripts/_install-rust.sh release-upload/_install-rust.sh
- # Uninstaller scripts — mirror the install side. The canonical
- # uninstall.sh dispatches to the Swift uninstall path by default
- # and to _uninstall-rust.sh on --experimental-rust / non-macOS
- # auto-detect. uninstall.ps1 is the canonical Windows
- # uninstaller (cua-driver-rs only — no Swift Windows build).
+ # Uninstaller scripts — single canonical file per shell (no
+ # `_uninstall-rust.sh` helper). uninstall.sh handles both Swift
+ # (macOS default) and Rust (Linux auto-select, macOS opt-in via
+ # --experimental-rust / --backend=rust) inline. uninstall.ps1
+ # is the Windows uninstaller (cua-driver-rs only — no Swift
+ # Windows build) and self-elevates via UAC when an -AutoStart
+ # install (RunLevel=Highest task) needs to be torn down.
cp libs/cua-driver/scripts/uninstall.sh release-upload/uninstall.sh
cp libs/cua-driver/scripts/uninstall.ps1 release-upload/uninstall.ps1
- cp libs/cua-driver/scripts/_uninstall-rust.sh release-upload/_uninstall-rust.sh
# Skill pack — single platform-agnostic tarball fetched by
# `cua-driver skills install`. The .md files are identical across
diff --git a/docs/content/docs/cua-driver/guide/getting-started/installation.mdx b/docs/content/docs/cua-driver/guide/getting-started/installation.mdx
index 5e87086e59..33cabec9e3 100644
--- a/docs/content/docs/cua-driver/guide/getting-started/installation.mdx
+++ b/docs/content/docs/cua-driver/guide/getting-started/installation.mdx
@@ -607,7 +607,9 @@ One canonical uninstall URL per platform mirrors the install side. Flag handling
| Linux | Rust port (auto-detected — Swift binary is macOS-only) | `bash -c "$(curl -fsSL https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver/scripts/uninstall.sh)"` |
| Windows | Rust port | `irm https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver/scripts/uninstall.ps1 \| iex` |
-`uninstall.sh` parses the same `--experimental-rust` / `--backend=rust` / `--backend=swift` flag set as `install.sh` and delegates to a colocated private helper, `_uninstall-rust.sh` (under `libs/cua-driver/scripts/`), when the Rust backend is selected. On Linux (and any non-macOS `bash` host) it auto-detects and runs the Rust uninstall without any flag.
+`uninstall.sh` parses the same `--experimental-rust` / `--backend=rust` / `--backend=swift` flag set as `install.sh` and handles both backends inline — single file, no `_uninstall-rust.sh` helper (mirrors the one-file-per-shell shape of `uninstall.ps1`). On Linux (and any non-macOS `bash` host) it auto-detects and runs the Rust uninstall without any flag.
+
+`uninstall.ps1` self-elevates via UAC when it detects an `-AutoStart` install — the `cua-driver-serve` Scheduled Task is registered at `RunLevel=Highest` (see [Autostart](../autostart)), so the daemon spawned by it runs at High IL and a non-elevated process (even the same user that installed it) can't terminate it or delete the task. The script detects either condition upfront and re-spawns itself elevated; the in-place path runs without UAC when no autostart artifacts are present.
**What each uninstall removes**
@@ -616,10 +618,10 @@ One canonical uninstall URL per platform mirrors the install side. Flag handling
| Swift (macOS) | `~/.local/bin/cua-driver`, `/usr/local/bin/cua-driver` (legacy) | `/Applications/CuaDriver.app`, `~/.cua-driver`, `~/Library/Application Support/Cua Driver`, `~/Library/Caches/cua-driver` | `~/Library/LaunchAgents/com.trycua.cua_driver_updater.plist` (legacy ≤ 0.0.5) | `cua-driver` symlinks under `~/.claude/skills`, `~/.agents/skills`, `~/.openclaw/skills`, `~/.config/opencode/skills` | Scrubbed from `~/.claude.json` |
| Rust — macOS | `~/.local/bin/cua-driver` *(only when it resolves into `CuaDriver.app` and `~/.cua-driver-rs/` exists)* | `/Applications/CuaDriver.app` (current), `/Applications/CuaDriverRs.app` (legacy, pre-rename), `~/.cua-driver-rs/` (entire tree) | `~/Library/LaunchAgents/com.trycua.cua-driver-rs.plist` | `cua-driver-rs` symlinks under the same agent dirs | Scrubbed from `~/.claude.json` |
| Rust — Linux | `~/.local/bin/cua-driver` *(when it resolves into `~/.cua-driver-rs/`)* | `~/.cua-driver-rs/` (entire tree) | `~/.config/systemd/user/cua-driver-rs.service` (stop + disable + remove) | Same as above | Scrubbed from `~/.claude.json` |
-| Rust — Windows | `%LOCALAPPDATA%\Programs\trycua\cua-driver-rs\bin` *(directory junction)* | `%USERPROFILE%\.cua-driver-rs\` (entire tree, including `packages\current` junction) | Scheduled Task `cua-driver-serve` (`schtasks /Delete`) | Junctions under `%USERPROFILE%\.claude\skills`, `.agents\skills`, `.openclaw\skills`, `%APPDATA%\opencode\skills` | Not auto-edited — closing message prints `claude mcp remove cua-driver-rs` |
+| Rust — Windows | `%LOCALAPPDATA%\Programs\Cua\cua-driver\bin` *(directory junction; legacy `Programs\trycua\cua-driver-rs\bin` also swept)* | `%USERPROFILE%\.cua-driver\` (entire tree, including `packages\current` junction; legacy `~\.cua-driver-rs\` also swept) | Scheduled Task `cua-driver-serve` (`schtasks /Delete`; needs UAC — script self-elevates) | Junctions under `%USERPROFILE%\.claude\skills`, `.agents\skills`, `.openclaw\skills`, `%APPDATA%\opencode\skills` | Not auto-edited — closing message prints `claude mcp remove cua-driver-rs` |
<Callout type="info">
-**Safety invariants** — every uninstall script (`uninstall.sh`, `_uninstall-rust.sh`, `uninstall.ps1`) refuses to clobber a real directory at a path where the matching installer could have only created a symlink / junction (Linux/macOS use `[[ -L ]]`; Windows checks `IO_REPARSE_TAG_MOUNT_POINT`). A user who hand-managed any of these dirs keeps theirs untouched. Re-running an uninstall on an already-clean system prints `nothing to remove` per item — never errors.
+**Safety invariants** — every uninstall script (`uninstall.sh`, `uninstall.ps1`) refuses to clobber a real directory at a path where the matching installer could have only created a symlink / junction (Linux/macOS use `[[ -L ]]`; Windows checks `IO_REPARSE_TAG_MOUNT_POINT`). A user who hand-managed any of these dirs keeps theirs untouched. Re-running an uninstall on an already-clean system prints `nothing to remove` per item — never errors.
</Callout>
<Callout type="info">
diff --git a/libs/cua-driver-rs/Cargo.lock b/libs/cua-driver-rs/Cargo.lock
index d50f03a564..bd21ee23c8 100644
--- a/libs/cua-driver-rs/Cargo.lock
+++ b/libs/cua-driver-rs/Cargo.lock
@@ -242,7 +242,7 @@ dependencies = [
[[package]]
name = "cua-driver"
-version = "0.2.7"
+version = "0.2.18"
dependencies = [
"anyhow",
"async-trait",
@@ -270,7 +270,7 @@ dependencies = [
[[package]]
name = "cua-driver-uia"
-version = "0.2.7"
+version = "0.2.18"
dependencies = [
"anyhow",
"embed-manifest",
@@ -285,7 +285,7 @@ dependencies = [
[[package]]
name = "cursor-overlay"
-version = "0.2.7"
+version = "0.2.18"
dependencies = [
"anyhow",
"image",
@@ -428,7 +428,7 @@ checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
[[package]]
name = "focus-monitor-win"
-version = "0.2.7"
+version = "0.2.18"
dependencies = [
"windows",
]
@@ -865,7 +865,7 @@ dependencies = [
[[package]]
name = "mcp-server"
-version = "0.2.7"
+version = "0.2.18"
dependencies = [
"anyhow",
"async-trait",
@@ -1151,7 +1151,7 @@ checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
[[package]]
name = "platform-linux"
-version = "0.2.7"
+version = "0.2.18"
dependencies = [
"anyhow",
"async-trait",
@@ -1171,7 +1171,7 @@ dependencies = [
[[package]]
name = "platform-macos"
-version = "0.2.7"
+version = "0.2.18"
dependencies = [
"anyhow",
"async-trait",
@@ -1201,7 +1201,7 @@ dependencies = [
[[package]]
name = "platform-windows"
-version = "0.2.7"
+version = "0.2.18"
dependencies = [
"anyhow",
"async-trait",
diff --git a/libs/cua-driver-rs/Skills/cua-driver-rs/MACOS.md b/libs/cua-driver-rs/Skills/cua-driver-rs/MACOS.md
new file mode 100644
index 0000000000..cf2734ce64
--- /dev/null
+++ b/libs/cua-driver-rs/Skills/cua-driver-rs/MACOS.md
@@ -0,0 +1,475 @@
+# cua-driver-rs — macOS specifics
+
+This file holds macOS-only material that used to live in `SKILL.md`.
+The cross-platform core (snapshot invariant, CLI/MCP defaults,
+behavior matrix, canonical loop, pixel-click contract, common error
+patterns) is in `SKILL.md`. Read this in addition to `SKILL.md` when
+you're driving an app on macOS.
+
+## The no-foreground contract
+
+**The user's frontmost app MUST NOT change.** This is the whole
+reason cua-driver exists. Users pay for the right to keep typing in
+their editor while an agent drives another app in the background.
+Violate this rule and every other nice property the driver gives
+you (no cursor warp, no Space switch, no window raise) stops
+mattering — you just shipped the Accessibility Inspector with extra
+steps.
+
+Before running any shell command, ask: **"does this raise,
+activate, foreground, or make-key any app?"** If yes, don't run it.
+Every one of the commands below activates the target on macOS and
+is therefore forbidden unless the user **explicitly** asked for
+frontmost state:
+
+- **Every form of the `open` CLI — `open -a <App>`, `open -b
+ <bundle-id>`, `open <file>`, `open <path-to-App.app>`, `open
+ <url>` — always activates.** macOS routes all forms through
+ LaunchServices, which unhides and foregrounds the target
+ regardless of whether you passed an app name, a bundle id, a
+ document, a URL, or the bundle path itself. The activation
+ happens even when the only intent was "start the process."
+ **Never use `open` for any app launch.** This includes launching
+ a just-built .app from a local build dir (e.g. `open
+ build/Build/Products/Debug/MyApp.app`) — resolve the
+ `CFBundleIdentifier` from `Info.plist` and use `launch_app`
+ with that id. See "The narrow carve-out" below for why
+ `launch_app` is safe even when the app internally calls
+ `NSApp.activate`.
+- `osascript -e 'tell application "X" to activate'` —
+ activates by design. Same for `... to open <file>`,
+ `... to launch`, and anything with `activate` in the tell block.
+- `osascript -e 'tell application "System Events" to ... frontmost'`
+ in a mutating form (setting `frontmost` rather than reading it).
+- AppleScript files that invoke `activate`, `launch`, or `open`
+ against the target app.
+- `cliclick` (moves the user's real cursor to the target coords
+ before clicking — a focus-steal-equivalent even if the app's
+ window state is unchanged).
+- `CGEventPost` with `cghidEventTap` targeting a coordinate over
+ a different app's window (warps the cursor, possibly activates
+ on hit).
+- `AppleScriptTask`, `NSAppleScript`, `Process` wrapping `osascript`
+ that contains any of the above.
+- `NSRunningApplication.activate(options:)` called from your own
+ helper binary — same class.
+- Dock clicks and any `open` invocation (see the first bullet —
+ every form of `open` goes through LaunchServices which
+ activates, full stop).
+- **Keyboard shortcuts that semantically mean "focus here" —
+ most notably Chrome / Safari / Arc's `⌘L` (focus omnibox) and
+ Finder's `⌘⇧G` (Go to Folder).** These aren't pure key events —
+ the receiving app interprets "user wants to type here" as
+ activation intent and raises its window to be key. Even when
+ delivered to a backgrounded pid via `hotkey`, the downstream app
+ pulls focus. **For omnibox navigation specifically**, the correct
+ path is `launch_app({bundle_id: "com.google.Chrome", urls:
+ ["https://…"]})` — no omnibox dance, no `⌘L`, no focus-steal. Do
+ NOT try `set_value` on the omnibox: Chrome's commit logic requires
+ a "user-typed" signal that neither an AX value write nor
+ `CGEvent.postToPid` keystrokes supply from a backgrounded pid —
+ the URL lands in the field but Return fires as a no-op. See
+ `WEB_APPS.md` → "Navigate to a URL" for the full pattern. The
+ general principle: a shortcut that says "put my cursor inside this
+ app" is a focus-steal; a shortcut that says "do this thing" (copy,
+ save, quit) is fine.
+- **Tab-switching shortcuts in browsers (`⌘1..⌘9`, `⌘]`, `⌘[`,
+ `⌘⇧[`, `⌘⇧]`) are visibly disruptive even when delivered to a
+ backgrounded pid.** The app's key handler processes the shortcut,
+ the window re-renders the new tab's content, the user sees their
+ tabs flipping. There is no AX-only workaround: page content (HTML,
+ form state, `AXWebArea`) populates only for the focused tab;
+ inspecting a background tab requires activating it, which is the
+ visible flip. Observed with Dia; the same mechanic applies to every
+ Chromium-family browser (Chrome, Arc, Brave, Edge).
+
+ **Prefer the windows-over-tabs pattern**: for each URL you need to
+ drive backgrounded, use `launch_app({bundle_id, urls: [url]})` —
+ browsers open each URL in a new **window**. Each window has its own
+ `window_id`, its own AX tree, and can be inspected / interacted with
+ via `element_index` without activating or switching anything. Tabs
+ are a UX grouping for humans; cua-driver workflows should default to
+ windows. See `WEB_APPS.md` → "Tabs vs windows" for the full pattern.
+
+ Tab-title enumeration (read-only) IS safe — walk a window's toolbar
+ AX tree for `AXTab` / `AXRadioButton` children and read their
+ `AXTitle`s. Tab switching (activating one) is not.
+
+Reading frontmost state is fine (`osascript -e 'tell application
+"System Events" to get name of first application process whose
+frontmost is true'`). Mutating it is not.
+
+**Corollary — the AXMenuBar rule.** `AXMenuBarItem` + AXPick
+dispatches at the AX layer regardless of which app is frontmost,
+but macOS's on-screen menu bar always belongs to the frontmost
+app. If you drive a *backgrounded* app's menu bar, the AX call
+succeeds but the viewer sees the dispatch rendered over the
+*frontmost* app's menu bar — confusing in any observed session and
+routinely a silent no-op too, because action menu items go
+`DISABLED` when their owning app isn't the key window. **So: only
+use menu-bar navigation when the target is already frontmost.** For
+backgrounded targets, read state via in-window AX (window title,
+toolbar `AXStaticText`) and dispatch via in-window `element_index`
+or pixel clicks — both paths are frontmost-insensitive. Full
+rationale in "Navigating native menu bars" below.
+
+**"Open \<app\>" in user speech means launch, not activate.**
+`cua-driver launch_app` is the one correct path for process
+startup — it's idempotent (no-op on a running app), returns the
+pid, and has an internal `FocusRestoreGuard` that catches
+`NSApp.activate(ignoringOtherApps:)` calls the target makes during
+`application(_:open:)` and clobbers the frontmost back to what it
+was before the launch. That guard is why `launch_app` with `urls`
+(e.g. `{"bundle_id": "com.colliderli.iina", "urls": ["~/video.mp4"]}`)
+is safe even for apps that normally foreground on media-load
+(Chrome, Electron, media players).
+
+## Intent → tool mapping (macOS-specific)
+
+| Intent | Use | Don't use |
+|---|---|---|
+| Open / launch an app | `launch_app({bundle_id})` or `launch_app({bundle_id, urls:[...]})` | `open -a`, `osascript 'tell app … to launch/activate/open'` |
+| Find a pid | `list_apps` or `launch_app`'s return | `pgrep`, `ps`, `osascript frontmost` |
+| Enumerate an app's windows | `list_windows({pid})` — or read the `windows` array `launch_app` already returns | `osascript 'every window of app …'` |
+| Click / type / scroll / keys | `click`, `type_text`, `scroll`, `press_key`, `hotkey` | `osascript`, `cliclick`, raw `CGEvent`, `open <url>` |
+| Drag / drag-and-drop / marquee select | `drag({pid, from_x, from_y, to_x, to_y})` (pixel-only — macOS AX has no semantic drag) | `cliclick dd:`, `osascript drag` |
+| Screenshot | `screenshot` or the PNG in `get_window_state` | `screencapture` |
+| Quit an app | ask the user first, then `hotkey({pid, keys:["cmd","q"]})` | `kill`, `killall`, `pkill` |
+| Hand a file/URL to an app | `launch_app({bundle_id, urls:[<path>]})` | `open -a <App> <path>`, `open <url>` |
+
+### The narrow carve-out
+
+The **only** legitimate use of `osascript -e 'tell app X to
+activate'` is when the user **explicitly** asked for frontmost
+state ("bring Chrome to the front", "make it frontmost", "I want
+to see X"). Reaching for it because a tool call returned something
+confusing is wrong — that's the skill's classic foot-in-the-door
+failure mode and it steals focus every time.
+
+When a cua-driver call surprises you, diagnose cua-driver first:
+
+- **Tiny screenshot / empty `tree_markdown`?** Check
+ `cua-driver get_config` → `capture_mode`. Default `"som"` returns
+ both the AX tree and screenshot. `"vision"` omits the AX tree
+ (PNG only), `"ax"` omits the PNG. If a snapshot lacks a tree,
+ `capture_mode` is almost certainly `"vision"` — either reason
+ purely from the PNG or flip to `"som"` / `"ax"` via `set_config`.
+- **`has_screenshot: false`?** The window capture failed (transient
+ race against a close, or the window has no backing store yet).
+ Re-snapshot; if persistent, pick a different `window_id` via
+ `list_windows`.
+- **`Invalid element_index` / `No cached AX 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 the same app. Re-snapshot with the same window_id
+ you're about to click in.
+- **Sparse Chromium AX tree?** Retry `get_window_state` once — the
+ tree populates on second call.
+
+Only after those are ruled out, and only if the user's action
+genuinely needs frontmost state, fall through to the activate
+fallback. Always name the focus steal in your response ("I'll
+briefly bring Chrome to the front because …").
+
+### Self-check pattern
+
+Before every `Bash` call whose command line touches any macOS app
+(launching, opening, clicking, typing, scripting, screenshotting),
+run the self-check:
+
+1. **Does this command foreground the target?** If yes — stop and
+ translate to the cua-driver equivalent from the mapping table.
+2. **Does this command move the user's real cursor?** (`cliclick`,
+ any `CGEventPost` at `cghidEventTap` over another app's window).
+ If yes — stop; use `click({pid, x, y})` which routes per-pid
+ via SkyLight and never warps the cursor.
+3. **Does this command bypass cua-driver entirely?** (`osascript`
+ mutating GUI state, AppleScript files, external helpers.) If
+ yes — stop; find the cua-driver tool that does the intent.
+
+If all three are "no," the command is safe. If you can't answer,
+default to stop and ask rather than proceed. A single `open -a`
+run by accident kills the demo, the trust, and the user's in-flight
+editor state.
+
+## Prerequisites — macOS
+
+1. `cua-driver` is on `$PATH` (`which cua-driver`). If not, point the
+ user at `scripts/install-local.sh` and stop.
+2. Run `cua-driver check_permissions` (with the daemon up — see step 3).
+ The default behavior also raises the system permission dialogs for
+ any missing grants, so the user can grant on the spot. If either
+ grant still reads `false` after that (user dismissed the dialog),
+ tell them to open System Settings → Privacy & Security and grant
+ Accessibility and Screen Recording to `CuaDriver.app`, then stop.
+ Pass `'{"prompt":false}'` for a purely read-only status check that
+ won't steal focus.
+3. Start the daemon with `open -n -g -a CuaDriver --args serve` (the
+ recommended form — goes through LaunchServices so TCC attributes
+ the process to CuaDriver.app). `cua-driver serve &` also works;
+ the CLI auto-relaunches through `open -n -g -a CuaDriver` when it
+ detects a wrong-TCC context (any IDE-spawned shell: Claude Code,
+ Cursor, VS Code, Conductor). Verify with `cua-driver status`.
+
+## Resolve target pid — always via `launch_app`
+
+**Always start with `launch_app`**, whether or not the target is already
+running. It's idempotent (relaunching returns the existing pid with no
+side effects) and gives you the pid in one call — no `list_apps` hop.
+
+- `launch_app({bundle_id: "com.apple.finder"})` — preferred, unambiguous.
+- `launch_app({name: "Calculator"})` — when bundle_id isn't known.
+
+`launch_app` is a **hidden-launch primitive by design** — that's the
+entire point of cua-driver: agents drive apps in the background while
+the user keeps typing in their real foreground app. The target's
+window is initialized (AX tree fully populated, clickable via
+`element_index`, the pid appears in `list_apps`) but not drawn on
+screen. The driver never activates or unhides apps on its own; that
+would violate the no-foreground contract the whole driver exists to
+protect.
+
+If the user explicitly wants the window visible (usually for a demo
+or recording), they unhide it themselves — Dock click, Cmd-Tab, or
+Spotlight. Do not reach for `open` / `osascript activate` as a
+shortcut to make the window visible; those paths break the backgrounded
+invariant on every call, not just the call that "needed" the
+foreground. Say out loud what the user needs to do ("click the
+Todo app in your Dock to bring it forward") and let them do it.
+
+Never shell out to **any** form of `open` (including `open
+<path-to-App.app>` for a just-built binary — resolve the bundle id
+from `Info.plist` and use `launch_app` with that), `osascript 'tell
+app … to launch/open'`, or similar. Those paths activate the target,
+bypass the driver's focus-restore guard, and require a Bash
+permission prompt the agent loop shouldn't be burning on app launch.
+
+## Pixel-click dispatch (macOS)
+
+The pixel click is routed through SkyLight's per-pid event path
+(`SLEventPostToPid`), not the system HID stream. The dispatch recipe
+is the backgrounded "noraise" sequence: yabai's focus-without-raise
+SLPS event records followed by an off-screen user-activation primer
+and the real click. The target app becomes AppKit-active for event
+routing but its window does **not** rise to the front of the
+z-stack, and macOS's "switch to Space with windows for app" follow
+is suppressed. Full mechanics in
+`Sources/CuaDriverCore/Input/MouseInput.swift` (`clickViaAuthSignedPost`)
+and the companion `FocusWithoutRaise.swift`.
+
+### Canvases, viewports, games (Blender, Unity, GHOST, Qt, wxWidgets)
+
+Apps whose main surface is an OpenGL / Metal / Qt / wxWidgets
+viewport expose **no useful AX tree** — the whole surface is one
+opaque `AXGroup` or `AXWindow` from AX's perspective. Per-pid event
+paths (`SLEventPostToPid`, `CGEvent.postToPid`) are filtered by the
+viewport's own event-source check and silently dropped — the event
+loop wants "real HID origin".
+
+The working pattern:
+
+1. Bring the target frontmost (a brief `osascript activate` is
+ acceptable here — this is the carve-out the skill's osascript
+ gate allows).
+2. `CGEvent.post(tap: .cghidEventTap)` with a leading `mouseMoved`
+ event (~30 ms before the click). `cua-driver click` when the
+ target is frontmost automatically takes this path.
+3. Accept that the real cursor visibly moves — `cghidEventTap` is
+ the system HID stream, the cursor warps to the click point.
+
+There is no backgrounded path that reaches these apps today.
+
+### Known pixel-click limits
+
+- **Chromium `<video>` play/pause**: pixel click is often rejected
+ by HTML5's click-to-play handler on some builds. Use keyboard
+ instead: `press_key({pid, key: "k"})` (YouTube) or
+ `press_key({pid, key: "space"})` (generic). Keyboard events
+ travel through a different auth envelope.
+- **Pixel right-click on Chromium web content** coerces to a
+ left-click — a known Chromium renderer-IPC limitation that affects
+ every non-HID-tap synthesis path. For context menus on
+ AX-addressable elements (links, buttons, toolbar items), use
+ `right_click({pid, element_index})` instead.
+
+## Navigating native menu bars (AXMenuBar)
+
+**Only drive the menu bar when the target app is frontmost.** This
+is the single most-misused cua-driver capability. If the target is
+backgrounded, don't reach for `AXMenuBarItem` + AXPick — use
+in-window `element_index` or pixel clicks instead. Two reasons, one
+functional and one perceptual:
+
+- **Functional:** menu items that touch document/playback/editor
+ state go `DISABLED` when their owning app isn't the key window
+ (Preview rotate, IINA speed change, most editor commands). AXPick
+ + AXPress will dispatch successfully from the driver's side but
+ no-op at the target — you get a silent false-pass.
+- **Perceptual (matters for demos, screen recordings, and anything
+ the user watches live):** macOS's screen-rendered menu bar
+ always belongs to the *frontmost* app. AXPick on a backgrounded
+ app's `AXMenuBarItem` dispatches to that app's per-process menu at
+ the AX layer, but any visible menu render happens over the
+ frontmost app's menu bar — the viewer sees an IINA submenu
+ flashing on top of Chrome's menus, which reads as "the agent
+ clicked the wrong app." The AX call was correct; the frame the
+ user sees is not. For recorded or observed sessions, this is an
+ integrity bug even though it's not a correctness bug.
+
+**Good decision rule:** if the target is not already frontmost, do
+not use `AXMenuBarItem` at all. For *reading* in-window state,
+snapshot the window AX tree — most apps expose the same state via
+an in-window `AXStaticText`, title bar, or toolbar. For *dispatching*
+actions, use in-window `element_index` (buttons, toolbar items) or
+pixel clicks on in-window controls — both dispatch via AppKit's
+window-under-pointer hit-test and are **not** frontmost-gated.
+
+When the target IS frontmost, the menu-bar flow below is fine and
+the canonical path for menus.
+
+### The two-snapshot pattern (target frontmost only)
+
+Menu contents are a two-snapshot flow. Closed AXMenu subtrees are
+deliberately skipped during snapshot — otherwise every app's File /
+Edit / View hierarchy plus every Recent Items macOS has ever seen
+would inflate the tree 10-100x. But once a menu is *open*, its
+AXMenuItem children do receive `element_index` values so you can
+click them normally.
+
+1. Find the `[N] AXMenuBarItem "<Menu Name>"` in the tree.
+2. `click({pid, element_index: N, action: "pick"})` — menu bar items
+ implement `AXPick` ("open my submenu"), not `AXPress`. Using the
+ default action on an AXMenuBarItem is a no-op.
+3. Re-snapshot. The expanded menu's items now appear under the bar
+ item as `[M] AXMenuItem "<Item Name>"`.
+4. Click the target item — most items respond to `AXPress` (default
+ action). Submenus nest under the item and are walked the same way.
+5. Re-snapshot and verify.
+
+If you ever need to back out without selecting, `press_key({pid, key:
+"escape"})` closes the open menu. Leaving a menu expanded between
+turns poisons subsequent snapshots for that pid.
+
+### Commands gated on the target being frontmost
+
+Some menu items and global shortcuts (Preview's Tools → Rotate
+Right, ⌘R; anything in the View menu that manipulates the current
+document; most editor commands) are **disabled unless the target
+app is the key / frontmost window**. You'll see it in the AX tree
+as `DISABLED` on the menu item even though the user's intent is
+obviously valid.
+
+Before activating, confirm you're in this narrow case — the menu
+item still reads `DISABLED` after a fresh snapshot AND the action
+the user requested genuinely requires frontmost (Preview rotate,
+View menu document manipulation, editor commands). If either
+check fails, don't activate.
+
+When both checks pass, the driver has no `activate` tool
+(deliberately — the whole point is backgroundable control), so
+this is the one legitimate `osascript` fallback:
+
+```bash
+osascript -e 'tell application "<App Name>" to activate'
+```
+
+Then re-snapshot — the menu item loses its `DISABLED` tag — and
+`click({action: "pick"})` the item. Alternatively, a `hotkey`
+call delivered to the now-frontmost app works for the shortcut
+form (`⌘R`, `⌘+`, etc.).
+
+**Always name the focus steal in your response** so the user isn't
+surprised — "Briefly activating Preview to enable Tools → Rotate
+Right" or similar. Don't silently steal focus. You don't need to
+restore the previous frontmost afterwards unless the user asks —
+they can cmd-tab back.
+
+## Browser JS primitives — Apple Events backend
+
+When the AX tree doesn't expose the data you need (common in
+Chromium/Electron — the tree is sparse for web content), use the
+`page` tool or the `javascript` param on `get_window_state` to query
+the DOM directly via Apple Events. Requires "Allow JavaScript from
+Apple Events" to be enabled — see `WEB_APPS.md` for the setup path.
+
+**Three actions on the `page` tool:**
+
+- `page({pid, window_id, action: "get_text"})` — returns
+ `document.body.innerText`. Fastest way to read page content, prices,
+ article text, or any raw text the AX tree truncates or omits.
+
+- `page({pid, window_id, action: "query_dom", css_selector: "a[href]",
+ attributes: ["href"]})` — runs `querySelectorAll` and returns each
+ match's tag, text, and requested attributes as a JSON array. Use for
+ table rows, link hrefs, data attributes, structured page data.
+
+- `page({pid, window_id, action: "execute_javascript", javascript:
+ "..."})` — raw JS. Wrap in an IIFE with try-catch. Don't use this for
+ elements already indexed by `get_window_state` — `click` and
+ `set_value` are more reliable there.
+
+**Co-located read — `get_window_state` with `javascript`:**
+
+```bash
+get_window_state({pid, window_id, javascript: "document.title"})
+```
+
+Runs the JS and appends the result as a `## JavaScript result` section
+alongside the AX snapshot — one round-trip instead of two. Use this
+when you need both the element tree (for subsequent clicks) and some
+page data in the same turn.
+
+**Decision rule — AX vs JS:**
+
+| Need | Use |
+|---|---|
+| Click / type into an element | `get_window_state` → `click` / `set_value` (AX, works backgrounded) |
+| Read text the AX tree drops | `page(get_text)` or `get_window_state(javascript=)` |
+| Scrape structured data (tables, hrefs) | `page(query_dom)` |
+| Trigger JS events / mutations | `page(execute_javascript)` |
+
+Supported backends:
+
+| App type | How | Context |
+|---|---|---|
+| Chrome / Brave / Edge | Apple Events `execute javascript` | Full DOM ✅ |
+| Safari | Apple Events `do JavaScript` | Full DOM ✅ |
+| Electron (VS Code, Cursor…) | SIGUSR1 → V8 inspector → CDP | Main process only: `process`, `Buffer` — no `document`, no `require` in sandboxed apps |
+| Electron (with `--remote-debugging-port`) | CDP page target | Full DOM ✅ |
+
+**Electron sandbox note:** SIGUSR1 connects to the Node.js *main* process.
+Sandboxed Electron apps (VS Code, Cursor) strip `require` and Electron
+APIs there. Useful for: `process.env`, `process.versions`, `process.cwd()`,
+`process.pid`. For full DOM/renderer access, launch the app with
+`--remote-debugging-port=9222` — cua-driver will detect and prefer the
+page target automatically.
+
+Arc returns no values; Firefox has no JS-via-AppleEvents support — see
+`WEB_APPS.md` for the full matrix.
+
+## macOS common error patterns
+
+| Error text | Meaning | Fix |
+|---|---|---|
+| 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 | Affects `screenshot` and `get_window_state` (which always captures). Grant in System Settings — the driver can't operate without it |
+
+## Example end-to-end task (macOS)
+
+**User:** "Open the Downloads folder in Finder."
+
+1. `launch_app({bundle_id: "com.apple.finder", urls: ["~/Downloads"]})`
+ → `{pid: 844, windows: [{window_id: 6123, title: "Downloads", ...}]}`.
+ Idempotent launch; plus Finder opens a hidden window rooted at
+ `~/Downloads` via `application(_:open:)` — zero activation, no
+ focus steal. The `windows` array lets you skip a `list_windows` hop.
+2. `get_window_state({pid: 844, window_id: 6123})` → verify an
+ `AXWindow` whose title contains "Downloads" is present with a
+ populated AX subtree (sidebar, list view, files).
+3. Done.
+
+If the user instead asks to navigate *within* an already-open Finder
+window, use the menu-bar flow from "Navigating native menu bars"
+above (click Go → pick a menu item → re-snapshot → click it).
diff --git a/libs/cua-driver-rs/Skills/cua-driver-rs/SKILL.md b/libs/cua-driver-rs/Skills/cua-driver-rs/SKILL.md
index bc3e051889..96ea1d6ff6 100644
--- a/libs/cua-driver-rs/Skills/cua-driver-rs/SKILL.md
+++ b/libs/cua-driver-rs/Skills/cua-driver-rs/SKILL.md
@@ -12,145 +12,49 @@ invariant is not optional and silently breaks if you skip it.
## Platform-specific reading — read this first
-This file is **macOS-skewed**: the forbidden-list, AX tree
-references, launch semantics, and click mechanisms below describe
-macOS behavior. The shared core (snapshot invariant, MCP vs CLI
-choice, tool surface naming, agent cursor overlay, recording flow,
-common failure modes) applies on every platform.
-
-- **macOS** — read this file in full.
-- **Windows** — read `WINDOWS.md` (covers UIA tree vs AX, UWP /
+This file is the **cross-platform core**: snapshot invariant, CLI vs
+MCP choice, tool surface naming, behavior matrix, canonical loop,
+pixel-click contract, common failure modes. The platform-specific
+material (forbidden-list, accessibility tree implementation, launch
+semantics, click dispatch) lives in companion files in this same
+directory:
+
+- **macOS** — read `MACOS.md` (no-foreground contract, forbidden
+ `open`/`osascript`/`cliclick` invocations, AXMenuBar navigation,
+ SkyLight pixel-click dispatch, Apple-Events JS bridge).
+- **Windows** — read `WINDOWS.md` (UIA tree vs AX, UWP /
ApplicationFrameHost hosting, layered UIA+PostMessage click chain,
- Session 0 isolation, Windows-specific focus-steal vectors). The
- shared core in this file still applies; only the platform-specific
- sections (no-foreground contract, intent→tool table, click
- semantics, web apps) are replaced.
+ Session 0 isolation, Windows-specific focus-steal vectors).
- **Linux** — read `LINUX.md` (X11/Wayland status, AT-SPI,
BETA-level support).
-Use whichever combination matches the host you're driving. When in
-doubt, run `cua-driver doctor` — it reports the platform and the
-right entry point.
-
-The rest of this file targets macOS.
-
-## The no-foreground contract — read this first
-
-**The user's frontmost app MUST NOT change.** This is the whole
-reason cua-driver exists. Users pay for the right to keep typing in
-their editor while an agent drives another app in the background.
-Violate this rule and every other nice property the driver gives
-you (no cursor warp, no Space switch, no window raise) stops
-mattering — you just shipped the Accessibility Inspector with extra
-steps.
-
-Before running any shell command, ask: **"does this raise,
-activate, foreground, or make-key any app?"** If yes, don't run it.
-Every one of the commands below activates the target on macOS and
-is therefore forbidden unless the user **explicitly** asked for
-frontmost state:
-
-- **Every form of the `open` CLI — `open -a <App>`, `open -b
- <bundle-id>`, `open <file>`, `open <path-to-App.app>`, `open
- <url>` — always activates.** macOS routes all forms through
- LaunchServices, which unhides and foregrounds the target
- regardless of whether you passed an app name, a bundle id, a
- document, a URL, or the bundle path itself. The activation
- happens even when the only intent was "start the process."
- **Never use `open` for any app launch.** This includes launching
- a just-built .app from a local build dir (e.g. `open
- build/Build/Products/Debug/MyApp.app`) — resolve the
- `CFBundleIdentifier` from `Info.plist` and use `launch_app`
- with that id. See "The narrow carve-out" below for why
- `launch_app` is safe even when the app internally calls
- `NSApp.activate`.
-- `osascript -e 'tell application "X" to activate'` —
- activates by design. Same for `... to open <file>`,
- `... to launch`, and anything with `activate` in the tell block.
-- `osascript -e 'tell application "System Events" to ... frontmost'`
- in a mutating form (setting `frontmost` rather than reading it).
-- AppleScript files that invoke `activate`, `launch`, or `open`
- against the target app.
-- `cliclick` (moves the user's real cursor to the target coords
- before clicking — a focus-steal-equivalent even if the app's
- window state is unchanged).
-- `CGEventPost` with `cghidEventTap` targeting a coordinate over
- a different app's window (warps the cursor, possibly activates
- on hit).
-- `AppleScriptTask`, `NSAppleScript`, `Process` wrapping `osascript`
- that contains any of the above.
-- `NSRunningApplication.activate(options:)` called from your own
- helper binary — same class.
-- Dock clicks and any `open` invocation (see the first bullet —
- every form of `open` goes through LaunchServices which
- activates, full stop).
-- **Keyboard shortcuts that semantically mean "focus here" —
- most notably Chrome / Safari / Arc's `⌘L` (focus omnibox) and
- Finder's `⌘⇧G` (Go to Folder).** These aren't pure key events —
- the receiving app interprets "user wants to type here" as
- activation intent and raises its window to be key. Even when
- delivered to a backgrounded pid via `hotkey`, the downstream app
- pulls focus. **For omnibox navigation specifically**, the correct
- path is `launch_app({bundle_id: "com.google.Chrome", urls:
- ["https://…"]})` — no omnibox dance, no `⌘L`, no focus-steal. Do
- NOT try `set_value` on the omnibox: Chrome's commit logic requires
- a "user-typed" signal that neither an AX value write nor
- `CGEvent.postToPid` keystrokes supply from a backgrounded pid —
- the URL lands in the field but Return fires as a no-op. See
- `WEB_APPS.md` → "Navigate to a URL" for the full pattern. The
- general principle: a shortcut that says "put my cursor inside this
- app" is a focus-steal; a shortcut that says "do this thing" (copy,
- save, quit) is fine.
-- **Tab-switching shortcuts in browsers (`⌘1..⌘9`, `⌘]`, `⌘[`,
- `⌘⇧[`, `⌘⇧]`) are visibly disruptive even when delivered to a
- backgrounded pid.** The app's key handler processes the shortcut,
- the window re-renders the new tab's content, the user sees their
- tabs flipping. There is no AX-only workaround: page content (HTML,
- form state, `AXWebArea`) populates only for the focused tab;
- inspecting a background tab requires activating it, which is the
- visible flip. Observed with Dia; the same mechanic applies to every
- Chromium-family browser (Chrome, Arc, Brave, Edge).
-
- **Prefer the windows-over-tabs pattern**: for each URL you need to
- drive backgrounded, use `launch_app({bundle_id, urls: [url]})` —
- browsers open each URL in a new **window**. Each window has its own
- `window_id`, its own AX tree, and can be inspected / interacted with
- via `element_index` without activating or switching anything. Tabs
- are a UX grouping for humans; cua-driver workflows should default to
- windows. See `WEB_APPS.md` → "Tabs vs windows" for the full pattern.
-
- Tab-title enumeration (read-only) IS safe — walk a window's toolbar
- AX tree for `AXTab` / `AXRadioButton` children and read their
- `AXTitle`s. Tab switching (activating one) is not.
-
-Reading frontmost state is fine (`osascript -e 'tell application
-"System Events" to get name of first application process whose
-frontmost is true'`). Mutating it is not.
-
-**Corollary — the AXMenuBar rule.** `AXMenuBarItem` + AXPick
-dispatches at the AX layer regardless of which app is frontmost,
-but macOS's on-screen menu bar always belongs to the frontmost
-app. If you drive a *backgrounded* app's menu bar, the AX call
-succeeds but the viewer sees the dispatch rendered over the
-*frontmost* app's menu bar — confusing in any observed session and
-routinely a silent no-op too, because action menu items go
-`DISABLED` when their owning app isn't the key window. **So: only
-use menu-bar navigation when the target is already frontmost.** For
-backgrounded targets, read state via in-window AX (window title,
-toolbar `AXStaticText`) and dispatch via in-window `element_index`
-or pixel clicks — both paths are frontmost-insensitive. Full
-rationale in "Navigating native menu bars" below.
-
-**"Open \<app\>" in user speech means launch, not activate.**
-`cua-driver launch_app` is the one correct path for process
-startup — it's idempotent (no-op on a running app), returns the
-pid, and has an internal `FocusRestoreGuard` that catches
-`NSApp.activate(ignoringOtherApps:)` calls the target makes during
-`application(_:open:)` and clobbers the frontmost back to what it
-was before the launch. That guard is why `launch_app` with `urls`
-(e.g. `{"bundle_id": "com.colliderli.iina", "urls": ["~/video.mp4"]}`)
-is safe even for apps that normally foreground on media-load
-(Chrome, Electron, media players).
+Cross-cutting topics also have their own files:
+
+- `WEB_APPS.md` — browser / Electron / Tauri specifics (sparse AX
+ trees, omnibox navigation, the `set_value` workaround for
+ minimized windows, tabs-vs-windows guidance).
+- `RECORDING.md` — session recording + `replay_trajectory`.
+- `TESTS.md` — internal test surface.
+
+Use whichever combination matches the host. When in doubt, run
+`cua-driver doctor` — it reports the platform and the right entry
+point.
+
+## The no-foreground principle (cross-platform)
+
+**The user's frontmost app MUST NOT change.** Every platform has its
+own list of forbidden commands; the principle is universal:
+
+- macOS: any `open` invocation, any `osascript` that mutates GUI
+ state, `cliclick`, `cghidEventTap` writes targeting another app's
+ window. Full list in `MACOS.md`.
+- Windows: any `Start-Process` that triggers a `ShowWindow`/`SetForegroundWindow`
+ on the target, `WScript.Shell.AppActivate`, attaching to the
+ foreground thread for input forwarding. Full list in `WINDOWS.md`.
+
+If you reach for a command that says "activate", "foreground",
+"raise", or "make key", stop and translate to the cua-driver tool
+that does the same intent without focus-stealing.
## Defaults — always prefer cua-driver over shell shims
@@ -166,105 +70,28 @@ when MCP is requested.
### Claude Code computer-use compatibility mode
-For normal Claude Code use, keep the default CLI or `cua-driver` MCP server path above. If the user explicitly wants Claude Code's vision/computer-use-style flow, they can register:
+For normal Claude Code use, keep the default CLI or `cua-driver` MCP
+server path above. If the user explicitly wants Claude Code's
+vision/computer-use-style flow, they can register:
```bash
claude mcp add --transport stdio cua-computer-use -- cua-driver mcp --claude-code-computer-use-compat
```
-Observation: Claude Code vision flows appear to treat a screenshot MCP tool as the image-grounding anchor. This compatibility mode keeps the normal CuaDriver tools and changes only `screenshot`. The compatibility `screenshot` requires `pid` and `window_id`, captures only that target window, and returns the window-local pixel coordinate frame. Start with `launch_app` or `list_windows`, then call `screenshot({pid, window_id})`; do not assume desktop coordinates or a full-screen capture.
-
-Use MCP for this Claude Code vision/computer-use-style path. Do not shell out to `cua-driver screenshot` as a substitute: CLI screenshots still work as CuaDriver calls, but they do not expose the `mcp__cua-computer-use__screenshot` tool name that Claude Code appears to use as the image-grounding cue.
-
-Intent → tool mapping. If you find yourself reaching for the right
-column, something has gone wrong — re-read "The no-foreground
-contract" above:
-
-| Intent | Use | Don't use |
-|---|---|---|
-| Open / launch an app | `launch_app({bundle_id})` or `launch_app({bundle_id, urls:[...]})` | `open -a`, `osascript 'tell app … to launch/activate/open'` |
-| Find a pid | `list_apps` or `launch_app`'s return | `pgrep`, `ps`, `osascript frontmost` |
-| Enumerate an app's windows | `list_windows({pid})` — or read the `windows` array `launch_app` already returns | `osascript 'every window of app …'` |
-| Click / type / scroll / keys | `click`, `type_text`, `scroll`, `press_key`, `hotkey` | `osascript`, `cliclick`, raw `CGEvent`, `open <url>` |
-| Drag / drag-and-drop / marquee select | `drag({pid, from_x, from_y, to_x, to_y})` (pixel-only — macOS AX has no semantic drag) | `cliclick dd:`, `osascript drag` |
-| Screenshot | `screenshot` or the PNG in `get_window_state` | `screencapture` |
-| Quit an app | ask the user first, then `hotkey({pid, keys:["cmd","q"]})` | `kill`, `killall`, `pkill` |
-| Hand a file/URL to an app | `launch_app({bundle_id, urls:[<path>]})` | `open -a <App> <path>`, `open <url>` |
-
-### The narrow carve-out
-
-The **only** legitimate use of `osascript -e 'tell app X to
-activate'` is when the user **explicitly** asked for frontmost
-state ("bring Chrome to the front", "make it frontmost", "I want
-to see X"). Reaching for it because a tool call returned something
-confusing is wrong — that's the skill's classic foot-in-the-door
-failure mode and it steals focus every time.
-
-When a cua-driver call surprises you, diagnose cua-driver first:
-
-- **Tiny screenshot / empty `tree_markdown`?** Check
- `cua-driver get_config` → `capture_mode`. Default `"som"` returns
- both the AX tree and screenshot. `"vision"` omits the AX tree
- (PNG only), `"ax"` omits the PNG. If a snapshot lacks a tree,
- `capture_mode` is almost certainly `"vision"` — either reason
- purely from the PNG or flip to `"som"` / `"ax"` via `set_config`.
-- **`has_screenshot: false`?** The window capture failed (transient
- race against a close, or the window has no backing store yet).
- Re-snapshot; if persistent, pick a different `window_id` via
- `list_windows`.
-- **`Invalid element_index` / `No cached AX 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 the same app. Re-snapshot with the same window_id
- you're about to click in.
-- **Sparse Chromium AX tree?** Retry `get_window_state` once — the
- tree populates on second call.
-
-Only after those are ruled out, and only if the user's action
-genuinely needs frontmost state, fall through to the activate
-fallback. Always name the focus steal in your response ("I'll
-briefly bring Chrome to the front because …").
-
-### Self-check pattern
-
-Before every `Bash` call whose command line touches any macOS app
-(launching, opening, clicking, typing, scripting, screenshotting),
-run the self-check:
-
-1. **Does this command foreground the target?** If yes — stop and
- translate to the cua-driver equivalent from the mapping table.
-2. **Does this command move the user's real cursor?** (`cliclick`,
- any `CGEventPost` at `cghidEventTap` over another app's window).
- If yes — stop; use `click({pid, x, y})` which routes per-pid
- via SkyLight and never warps the cursor.
-3. **Does this command bypass cua-driver entirely?** (`osascript`
- mutating GUI state, AppleScript files, external helpers.) If
- yes — stop; find the cua-driver tool that does the intent.
-
-If all three are "no," the command is safe. If you can't answer,
-default to stop and ask rather than proceed. A single `open -a`
-run by accident kills the demo, the trust, and the user's in-flight
-editor state.
-
-## Prerequisites — check before starting
-
-1. `cua-driver` is on `$PATH` (`which cua-driver`). If not, point the
- user at `scripts/install-local.sh` and stop.
-2. Run `cua-driver check_permissions` (with the daemon up — see step 3).
- The default behavior also raises the system permission dialogs for
- any missing grants, so the user can grant on the spot. If either
- grant still reads `false` after that (user dismissed the dialog),
- tell them to open System Settings → Privacy & Security and grant
- Accessibility and Screen Recording to `CuaDriver.app`, then stop.
- Pass `'{"prompt":false}'` for a purely read-only status check that
- won't steal focus.
-3. Start the daemon with `open -n -g -a CuaDriver --args serve` (the
- recommended form — goes through LaunchServices so TCC attributes
- the process to CuaDriver.app). `cua-driver serve &` also works;
- the CLI auto-relaunches through `open -n -g -a CuaDriver` when it
- detects a wrong-TCC context (any IDE-spawned shell: Claude Code,
- Cursor, VS Code, Conductor). Verify with `cua-driver status`.
+Observation: Claude Code vision flows appear to treat a screenshot
+MCP tool as the image-grounding anchor. This compatibility mode keeps
+the normal CuaDriver tools and changes only `screenshot`. The
+compatibility `screenshot` requires `pid` and `window_id`, captures
+only that target window, and returns the window-local pixel
+coordinate frame. Start with `launch_app` or `list_windows`, then
+call `screenshot({pid, window_id})`; do not assume desktop
+coordinates or a full-screen capture.
+
+Use MCP for this Claude Code vision/computer-use-style path. Do not
+shell out to `cua-driver screenshot` as a substitute: CLI screenshots
+still work as CuaDriver calls, but they do not expose the
+`mcp__cua-computer-use__screenshot` tool name that Claude Code
+appears to use as the image-grounding cue.
## Using cua-driver from the shell
@@ -272,21 +99,21 @@ Tool names are `snake_case`, management subcommands are
`kebab-case` — no ambiguity. Tools invoked as `cua-driver
<tool-name> '<JSON-args>'`. Management subcommands:
-- `open -n -g -a CuaDriver --args serve` — start persistent daemon
- (**required** for `element_index` workflows; without it each CLI
- invocation spawns a fresh process and the per-pid element cache
- dies between calls). `cua-driver serve &` also works — the CLI
- auto-relaunches via `open` when the shell's TCC context is wrong.
- Pass `--no-relaunch` / `CUA_DRIVER_NO_RELAUNCH=1` to opt out.
+- `cua-driver serve` — start persistent daemon (**required** for
+ `element_index` workflows; without it each CLI invocation spawns a
+ fresh process and the per-pid element cache dies between calls).
+ macOS users: see `MACOS.md` for the LaunchServices-routed launch
+ form.
- `cua-driver stop` / `status`
- `cua-driver list-tools`, `describe <tool>`
- `cua-driver recording start|stop|status` — see `RECORDING.md`
-Canonical multi-step workflow:
+Canonical multi-step workflow (example shape — platform-specific
+launch idioms in the per-OS companion file):
-```
-open -n -g -a CuaDriver --args serve
-cua-driver launch_app '{"bundle_id":"com.apple.calculator"}'
+```bash
+cua-driver serve
+cua-driver launch_app '{"bundle_id":"..."}'
# → {pid: 844, windows: [{window_id: 10725, ...}]}
cua-driver get_window_state '{"pid":844,"window_id":10725}'
cua-driver click '{"pid":844,"window_id":10725,"element_index":14}'
@@ -303,8 +130,8 @@ Motion knobs: `set_agent_cursor_motion` takes any subset of
`start_handle`, `end_handle`, `arc_size`, `arc_flow`, `spring` —
tuneable at runtime, persisted to config.
-Requires an AppKit runloop, which `cua-driver serve` / `mcp`
-bootstraps. One-shot CLI invocations skip the overlay entirely.
+Requires the daemon process's UI runloop, which `cua-driver serve` /
+`mcp` bootstraps. One-shot CLI invocations skip the overlay entirely.
## The core invariant — snapshot before AND after every action
@@ -319,10 +146,10 @@ bootstraps. One-shot CLI invocations skip the overlay entirely.
`No cached AX state`.
- **After** — the post-action snapshot verifies the action actually
landed. Without it you can't tell a silent no-op from a real
- effect. The AX tree change (new value, new window, disappeared
- menu, disabled button, etc.) is your evidence that the action
- fired. If nothing changed, the action probably failed silently —
- say so, don't assume success.
+ effect. The accessibility-tree change (new value, new window,
+ disappeared menu, disabled button, etc.) is your evidence that
+ the action fired. If nothing changed, the action probably failed
+ silently — say so, don't assume success.
This applies to pixel clicks too — re-snapshot after to confirm the
click landed on the intended target.
@@ -336,9 +163,10 @@ off-screen) out-area'd the visible 320×240 player window, so
`get_app_state(pid)` screenshot'd the invisible panel and clicks landed
there silently. The new `get_window_state(pid, window_id)` makes the
caller name the window explicitly — the driver validates that the
-window belongs to the pid and is on the current Space, then snapshots
-exactly what was asked for. Enumerate candidates via `list_windows` or
-read the `windows` array `launch_app` already returns.
+window belongs to the pid and is on the current Space/desktop, then
+snapshots exactly what was asked for. Enumerate candidates via
+`list_windows` or read the `windows` array `launch_app` already
+returns.
## Behavior matrix
@@ -350,7 +178,7 @@ Two orthogonal axes shape what the agent can do.
|---|---|---|
| **`som`** (default) | tree + screenshot | `element_index` preferred; pixel fallback |
| **`ax`** | tree only (no PNG) | `element_index` only |
-| **`vision`** | PNG only (no tree) | pixel only — see [SCREENSHOT.md](./SCREENSHOT.md) |
+| **`vision`** | PNG only (no tree) | pixel only — see `SCREENSHOT.md` |
`vision` was renamed from `screenshot` — the old name still decodes
as a deprecated alias, so an on-disk `"capture_mode": "screenshot"`
@@ -363,29 +191,27 @@ walk) and unrelated to the capture mode.
When a snapshot looks wrong (tiny screenshot / empty tree), check
`cua-driver get_config` for `capture_mode` before anything else.
-Pure-vision mode has its own caveats — Claude Code's vision
-pipeline downsamples dense text aggressively, so pixel grounding
-takes multiple correction cycles on text-heavy UIs. Read
-[SCREENSHOT.md](./SCREENSHOT.md) before driving anything in that
-mode; it documents the iterate/annotate/verify recipe plus the
-JPEG-over-PNG finding.
+Pure-vision mode has its own caveats — Claude Code's vision pipeline
+downsamples dense text aggressively, so pixel grounding takes
+multiple correction cycles on text-heavy UIs.
**Window state → what works**
-| state | `get_window_state` | `click`/`set_value` (AX) | `press_key` commit (Return/Space/Tab) | pixel click |
+| state | `get_window_state` | element-index click (AX/UIA) | `press_key` commit | pixel click |
|---|---|---|---|---|
| frontmost | ✅ | ✅ | ✅ | ✅ |
| backgrounded / visible | ✅ | ✅ | ✅ | ✅ |
-| **minimized** (Dock genie) | ✅ | ✅ (no deminiaturize — AX actions fire on the minimized window in place) | ❌ silent no-op / system beep — use `set_value` or click equivalent | ❌ no on-screen bounds |
-| hidden (`hides=true` / `NSApp.hide`) | ✅ | ✅ | depends | ❌ |
-| on another Space | ⚠️ AX tree often stripped to menu-bar-only on SwiftUI apps (System Settings) — AppKit apps usually fine. Response carries `off_space: true` + `window_space_ids` so you can detect it | ✅ | ✅ | ❌ window not in current-Space list |
+| **minimized** | ✅ | ✅ (actions fire in place) | ❌ silent no-op — use `set_value` or click equivalent | ❌ no on-screen bounds |
+| hidden | ✅ | ✅ | depends | ❌ |
+| on another desktop / Space | ⚠️ tree may be stripped on some apps — response carries `off_space: true` so you can detect it | ✅ | ✅ | ❌ not in current-desktop list |
**Critical cell — minimized + keyboard commit.** The keystroke
-reaches the app but AX focus doesn't propagate to renderer focus on
-a minimized window. Workarounds in order of preference:
-`set_value` to write the field's entire value directly, or AX-click
-a commit-equivalent button (Go, Submit, checkbox). Tell the user
-the window needs to un-minimize only as a last resort.
+reaches the app but accessibility focus doesn't propagate to renderer
+focus on a minimized window. Workarounds in order of preference:
+`set_value` to write the field's entire value directly, or
+element-index-click a commit-equivalent button (Go, Submit,
+checkbox). Tell the user the window needs to un-minimize only as a
+last resort.
## The canonical loop
@@ -402,60 +228,22 @@ launch_app(target)
common case collapses to two calls (`launch_app` → `get_window_state`)
without a separate `list_windows` hop.
-### 1. Resolve target pid — always via `launch_app`
-
-**Always start with `launch_app`**, whether or not the target is already
-running. It's idempotent (relaunching returns the existing pid with no
-side effects) and gives you the pid in one call — no `list_apps` hop.
-
-- `launch_app({bundle_id: "com.apple.finder"})` — preferred, unambiguous.
-- `launch_app({name: "Calculator"})` — when bundle_id isn't known.
-
-`launch_app` is a **hidden-launch primitive by design** — that's the
-entire point of cua-driver: agents drive apps in the background while
-the user keeps typing in their real foreground app. The target's
-window is initialized (AX tree fully populated, clickable via
-`element_index`, the pid appears in `list_apps`) but not drawn on
-screen. The driver never activates or unhides apps on its own; that
-would violate the no-foreground contract the whole driver exists to
-protect.
-
-If the user explicitly wants the window visible (usually for a demo
-or recording), they unhide it themselves — Dock click, Cmd-Tab, or
-Spotlight. Do not reach for `open` / `osascript activate` as a
-shortcut to make the window visible; those paths break the backgrounded
-invariant on every call, not just the call that "needed" the
-foreground. Say out loud what the user needs to do ("click the
-Todo app in your Dock to bring it forward") and let them do it.
-
-Never shell out to **any** form of `open` (including `open
-<path-to-App.app>` for a just-built binary — resolve the bundle id
-from `Info.plist` and use `launch_app` with that), `osascript 'tell
-app … to launch/open'`, or similar. Those paths activate the target,
-bypass the driver's focus-restore guard, and require a Bash
-permission prompt the agent loop shouldn't be burning on app launch.
-See "Prefer cua-driver tools over shell shims" above for the full
-intent → tool mapping.
-
`list_apps` is for app-level discovery (answering "what's installed /
-running / frontmost?") — not part of the core action loop. Skip it in
-the loop. For **window-level** questions — "does this app have a
-visible window?", "which Space is this window on?", "which of this
+running / frontmost?") — not part of the core action loop. Skip it
+in the loop. For **window-level** questions — "does this app have a
+visible window?", "which desktop is this window on?", "which of this
pid's windows is the main one?" — call `list_windows` instead; the
app record doesn't carry window state on purpose. In the common
single-window case you can skip `list_windows` entirely and read the
`windows` array that `launch_app` already returned.
-### 2. Snapshot and act by element_index
+### Snapshot and act by element_index
Call `get_window_state({pid, window_id})` with the `window_id` from
`launch_app`'s `windows` array (or a fresh `list_windows({pid})` if
you're interacting with a long-lived process). The default `som`
-capture_mode returns **both the AX tree and screenshot**, so the
-canonical loop works immediately without any config change. The rest
-of this section walks through `som` mode. If you're in `vision` mode
-(PNG only, no AX tree), flip back: `cua-driver set_config '{"key":
-"capture_mode", "value": "som"}'`.
+capture_mode returns **both the tree and screenshot**, so the
+canonical loop works immediately without any config change.
In `som` mode (the default) the response carries:
@@ -466,108 +254,107 @@ In `som` mode (the default) the response carries:
`jq -r '.tree_markdown'` + `grep` to pull the section you need.
- `screenshot_file_path` — absolute path to the saved screenshot when
`screenshot_out_file` was passed. Absent otherwise.
-- `screenshot_width` / `_height` / `_scale_factor` — dimensions of the
- captured image. Present whenever a screenshot was taken.
+- `screenshot_width` / `_height` / `_scale_factor` — dimensions of
+ the captured image. Present whenever a screenshot was taken.
+
**Getting the screenshot as a file (CLI and context-constrained agents):**
```bash
-# write to file — stdout stays readable (AX tree / summary only, no base64)
+# write to file — stdout stays readable (AX/UIA tree / summary only, no base64)
cua-driver get_window_state '{"pid":N,"window_id":W,"screenshot_out_file":"/tmp/shot.jpg"}'
# CLI --screenshot-out-file flag is equivalent and works for all capture modes
cua-driver get_window_state '{"pid":N,"window_id":W}' --screenshot-out-file /tmp/shot.jpg
```
-Pass `screenshot_out_file` when using `get_window_state` via CLI or from an
-agent whose context window can't absorb ~31 KB of inline base64 (e.g.
-OpenCode with a local Ollama model). The MCP image content block is omitted
-from the response when this param is set — the model receives only the AX
-tree and `screenshot_file_path`, then reads the image from disk.
+Pass `screenshot_out_file` when using `get_window_state` via CLI or
+from an agent whose context window can't absorb ~31 KB of inline
+base64 (e.g. OpenCode with a local Ollama model). The MCP image
+content block is omitted from the response when this param is set —
+the model receives only the tree and `screenshot_file_path`, then
+reads the image from disk.
**Reason over both the tree AND the screenshot — they're
-complementary, not redundant.** In `som` mode every
-turn's `get_window_state` gives you both halves and you should pull
-signal from each:
+complementary, not redundant.** In `som` mode every turn's
+`get_window_state` gives you both halves and you should pull signal
+from each:
-- The **AX tree** tells you *what's clickable* — roles, labels,
+- The **tree** tells you *what's clickable* — roles, labels,
`element_index` handles, advertised actions, parent-child
structure. This is the ground truth for dispatching.
- The **screenshot** tells you *which one* — the tree often has
many buttons with similar or empty labels ("Delete", "OK",
- anonymous UUID-labeled buttons, five `AXStaticText = " "`), and
- visual context disambiguates. Captions, colors, layout relationships
- visible in pixels often don't show up in the AX tree at all
+ anonymous UUID-labeled buttons, repeated static-text), and visual
+ context disambiguates. Captions, colors, layout relationships
+ visible in pixels often don't show up in the tree at all
(especially in Chromium / Electron / web content).
Canonical pattern: look at the screenshot to decide "the blue
Subscribe button on the top-right of the video card", then walk the
-tree to find the matching `AXButton` and dispatch by its
+tree to find the matching element and dispatch by its
`element_index`. Don't try to do it from just the tree — you'll
pick the wrong element when labels repeat. Don't try to do it from
-just the screenshot — you lose the reliable AX-action path and the
-safe backgrounded-dispatch.
+just the screenshot — you lose the reliable accessibility-action
+path and the safe backgrounded-dispatch.
Reach for pixel coordinates only when the target is a canvas /
-video / WebGL / custom-drawn surface that isn't in the AX tree
-(see Pixel-coordinate clicks below).
+video / WebGL / custom-drawn surface that isn't in the tree
+(see "Pixel-coordinate clicks" below).
The `actions=[...]` list on each element is **advisory**, not
authoritative. cua-driver does not pre-flight check against it —
-`click({pid, element_index})` always attempts `AXPress` (or the
-action you pass) and surfaces whatever the target returns. Many
-apps accept `AXPress` on elements that don't advertise it — Chrome's
-omnibox suggestion `AXMenuItem` is a live example. **Try the click
-first** — pivot only on the returned AX error code.
+`click({pid, element_index})` always attempts the default action (or
+the action you pass) and surfaces whatever the target returns. **Try
+the click first** — pivot only on the returned error code.
+
+### Tool dispatch table
-Dispatch table (every row assumes a `(pid, window_id)` pair from the
-last `get_window_state`; `window_id` is required alongside
-`element_index`, ignored on pixel-only forms unless you want to
-anchor the conversion against a specific window):
+Every row assumes a `(pid, window_id)` pair from the last
+`get_window_state`; `window_id` is required alongside `element_index`,
+ignored on pixel-only forms unless you want to anchor the conversion
+against a specific window.
| Intent | Tool | Notes |
|---|---|---|
| List an app's windows | `list_windows({pid})` | returns `window_id`, `title`, `bounds`, `z_index`, `is_on_screen`, `on_current_space`. Already included in `launch_app`'s response — only call this for long-lived pids |
| Snapshot a window | `get_window_state({pid, window_id})` | returns `tree_markdown` + `screenshot_*`; populates the `(pid, window_id)` element_index cache |
-| Left click | `click({pid, window_id, element_index})` | default `action: "press"`. Pixel form: `click({pid, x, y})` (window_id optional — when supplied, pinpoints the anchor window) — `modifier: ["cmd"]` |
-| Double-click / open | `double_click({pid, window_id, element_index})` | AXOpen when advertised (Finder items, openable rows); else stamped pixel double-click at the element's center. Pixel form: `double_click({pid, x, y})` — primer-gated recipe lands on backgrounded Chromium web content (YouTube fullscreen, Finder open-on-dbl). `click({..., count: 2})` still works and routes through the same recipe; `double_click` is the intent-first spelling |
-| Right click / context menu | `right_click({pid, window_id, element_index})` or `click({pid, window_id, element_index, action: "show_menu"})` | Chromium web-content coerces pixel right-click to left — see `WEB_APPS.md` |
-| Type at cursor | `type_text({pid, text, window_id, element_index})` | `AXSelectedText` write; focuses first |
+| Left click | `click({pid, window_id, element_index})` | default `action: "press"`. Pixel form: `click({pid, x, y})` (window_id optional) — `modifier: ["cmd"\|"ctrl"]` |
+| Double-click / open | `double_click({pid, window_id, element_index})` | Default action when the element advertises one (Open on Finder items / openable rows), else stamped pixel double-click at the element's center |
+| Right click / context menu | `right_click({pid, window_id, element_index})` or `click({pid, window_id, element_index, action: "show_menu"})` | Chromium web-content coerces pixel right-click to left on macOS — see `WEB_APPS.md` |
+| Type at cursor | `type_text({pid, text, window_id, element_index})` | focuses element first, then writes via the platform's text-set primitive |
| Set whole field value | `set_value({pid, window_id, element_index, value})` | sliders, steppers, text fields; **use for keyboard-commit workarounds on minimized windows** |
-| Scroll | `scroll({pid, direction, amount, by, window_id, element_index})` | synthesizes PageUp/PageDown/arrows via SLEventPostToPid |
-| Focus + send key | `press_key({pid, key, window_id, element_index, modifiers})` | element_index sets AXFocused, then posts key |
+| Scroll | `scroll({pid, direction, amount, by, window_id, element_index})` | synthesizes per-pid PageUp/PageDown/arrows |
+| Focus + send key | `press_key({pid, key, window_id, element_index, modifiers})` | element_index sets focus, then posts key |
| Send key to pid | `press_key({pid, key, modifiers})` | no focus change; key goes to pid's current focus |
-| Modifier combo | `hotkey({pid, keys})` | e.g. `["cmd","c"]`; posted per-pid, not HID tap |
-| Unicode keystrokes | `type_text({pid, text, delay_ms})` | AX write with automatic CGEvent fallback; reaches Chromium/Electron inputs |
+| Modifier combo | `hotkey({pid, keys})` | e.g. `["cmd","c"]` / `["ctrl","c"]`; posted per-pid, not HID tap |
**All keyboard/text primitives require `pid`.** There is no
frontmost-routed variant — every key goes to the named target via
-`CGEvent.postToPid`, so the driver cannot leak keystrokes into the
-user's foreground app.
+the platform's per-pid event-post path, so the driver cannot leak
+keystrokes into the user's foreground app.
**Why `element_index` is the primary path:** works on hidden /
-occluded / off-Space windows, no focus steal, stable across
+occluded / off-desktop windows, no focus steal, stable across
rebuilds, labels tell you what you're clicking. Reach for pixel
-coordinates only when AX can't.
-
-### Pixel-coordinate clicks
-
-The pixel path (`click({pid, x, y})`) is for surfaces the AX tree
-doesn't reach — canvases, video players, WebGL, custom-drawn controls.
-Coords are **window-local screenshot pixels** (same space as the PNG
-`get_window_state` returns). Top-left origin, y-down. The driver
-handles screen-point conversion internally. Passing `window_id`
-alongside `x, y` is optional but recommended — it pins the
-coordinate conversion to the window whose screenshot produced the
-pixel, rather than the driver's heuristic choice.
-
-#### Reading coordinates from the PNG
-
-PNGs returned by `get_window_state` are capped at **1568 px
-long-side by default** (`max_image_dimension` config), matching
-Anthropic's multimodal-vision downsampling limit. That means the
-image the model reasons over and the image the click tool's
-coordinate system lives in are the **same resolution** — just look
-at the PNG, pick a pixel, click at that pixel. No scaling math.
+coordinates only when the accessibility tree can't.
+
+## Pixel-coordinate clicks
+
+The pixel path (`click({pid, x, y})`) is for surfaces the
+accessibility tree doesn't reach — canvases, video players, WebGL,
+custom-drawn controls. Coords are **window-local screenshot pixels**
+(same space as the PNG `get_window_state` returns). Top-left origin,
+y-down. The driver handles screen-point conversion internally.
+Passing `window_id` alongside `x, y` is optional but recommended —
+it pins the coordinate conversion to the window whose screenshot
+produced the pixel.
+
+PNGs returned by `get_window_state` are capped at **1568 px long-side
+by default** (`max_image_dimension` config), matching Anthropic's
+multimodal-vision downsampling limit. The image the model reasons
+over and the image the click tool's coordinate system lives in are
+the **same resolution** — just look at the PNG, pick a pixel, click
+at that pixel. No scaling math.
This is the default because the mismatch between "rendered
thumbnail" and "native PNG" was a recurring coord-estimation
@@ -575,23 +362,18 @@ footgun. If you opt out (explicit `max_image_dimension=0` for
pixel-perfect verification flows), the old rule applies: don't
eyeball coords from whatever your client renders — it may be
2-4× smaller than the PNG on disk, and a 2% error in thumbnail
-space becomes ~80 px in the real image. Use the crosshair recipe
-below against the full-resolution file in that case.
-
-1. `get_window_state({pid, window_id})` returns an image capped
- at 1568 long-side (default) plus its dimensions
- (`screenshot_width` / `screenshot_height`). Write the bytes to
- disk with `--screenshot-out-file <path>` in any capture mode — works
- identically in `vision` (where it's the only way) and `som`
- (where it sidesteps the jq + base64 dance on the spliced
- `screenshot_png_b64` field).
-2. You are a multimodal model — look at the PNG. Since the PNG
- matches what you see, pick the target pixel directly. No
- fractional math needed.
-3. When precision matters (small targets, dense UIs), draw a
- crosshair on the image (do **not** crop — cropping loses the
- coordinate system and requires error-prone offset math) and
- show it before clicking:
+space becomes ~80 px in the real image.
+
+For precise targeting on small / dense UIs:
+
+1. `get_window_state({pid, window_id})` → image capped at 1568
+ long-side plus `screenshot_width` / `screenshot_height`. Write to
+ disk via `--screenshot-out-file <path>`.
+2. Look at the PNG. Since it matches what you see, pick the target
+ pixel directly.
+3. When precision matters, draw a crosshair on the image (do
+ **not** crop — cropping loses the coordinate system) and verify
+ before clicking:
```python
from PIL import Image, ImageDraw
@@ -608,273 +390,74 @@ img.save('/tmp/shot_annotated.png')
4. Only dispatch the click after the user (or your own re-read of
the annotated image) confirms the crosshair is on target.
-#### Addressing variants
+Addressing variants:
- `click({pid, x, y})` — single left-click.
- `click({pid, x, y, count: 2})` — double-click.
-- `click({pid, x, y, modifier: ["cmd"]})` — cmd-click. Accepts any
- subset of `cmd/shift/option/ctrl`.
+- `click({pid, x, y, modifier: ["cmd"\|"ctrl"]})` — modifier click.
+ Accepts any subset of `cmd/shift/option/alt/ctrl`.
- `right_click({pid, x, y})` — also takes `modifier`.
The pixel path animates the agent cursor overlay but never warps
-the real cursor. If the pid has no on-screen window the call errors
-with `pid X has no on-screen window` — you need a visible window to
-anchor the conversion.
-
-#### How the pixel click is dispatched
-
-The recipe is the backgrounded "noraise" sequence: yabai's
-focus-without-raise SLPS event records followed by an off-screen
-user-activation primer and the real click, all stamped via
-`SLEventPostToPid`. The target app becomes AppKit-active for event
-routing but its window does **not** rise to the front of the
-z-stack, and macOS's "switch to Space with windows for app" follow
-is suppressed. Full mechanics in
-`Sources/CuaDriverCore/Input/MouseInput.swift` (`clickViaAuthSignedPost`)
-and the companion `FocusWithoutRaise.swift`.
-
-#### Known limits
-
-- **Chromium `<video>` play/pause**: pixel click is often rejected
- by HTML5's click-to-play handler on some builds. Use keyboard
- instead: `press_key({pid, key: "k"})` (YouTube) or
- `press_key({pid, key: "space"})` (generic). Keyboard events
- travel through a different auth envelope.
-- **Pixel right-click on Chromium web content** coerces to a
- left-click — a known Chromium renderer-IPC limitation that affects
- every non-HID-tap synthesis path. For context menus on
- AX-addressable elements (links, buttons, toolbar items), use
- `right_click({pid, element_index})` instead.
-
-### Canvases, viewports, games (Blender, Unity, GHOST, Qt, wxWidgets)
-
-Apps whose main surface is an OpenGL / Metal / Qt / wxWidgets
-viewport expose **no useful AX tree** — the whole surface is one
-opaque `AXGroup` or `AXWindow` from AX's perspective. Per-pid event
-paths (`SLEventPostToPid`, `CGEvent.postToPid`) are filtered by the
-viewport's own event-source check and silently dropped — the event
-loop wants "real HID origin".
-
-The working pattern:
-
-1. Bring the target frontmost (a brief `osascript activate` is
- acceptable here — this is the carve-out the skill's osascript
- gate allows).
-2. `CGEvent.post(tap: .cghidEventTap)` with a leading `mouseMoved`
- event (~30 ms before the click). `cua-driver click` when the
- target is frontmost automatically takes this path.
-3. Accept that the real cursor visibly moves — `cghidEventTap` is
- the system HID stream, the cursor warps to the click point.
-
-There is no backgrounded path that reaches these apps today.
-
-## Navigating native menu bars (AXMenuBar)
-
-**Only drive the menu bar when the target app is frontmost.** This
-is the single most-misused cua-driver capability. If the target is
-backgrounded, don't reach for `AXMenuBarItem` + AXPick — use
-in-window `element_index` or pixel clicks instead. Two reasons, one
-functional and one perceptual:
-
-- **Functional:** menu items that touch document/playback/editor
- state go `DISABLED` when their owning app isn't the key window
- (Preview rotate, IINA speed change, most editor commands). AXPick
- + AXPress will dispatch successfully from the driver's side but
- no-op at the target — you get a silent false-pass.
-- **Perceptual (matters for demos, screen recordings, and anything
- the user watches live):** macOS's screen-rendered menu bar
- always belongs to the *frontmost* app. AXPick on a backgrounded
- app's `AXMenuBarItem` dispatches to that app's per-process menu at
- the AX layer, but any visible menu render happens over the
- frontmost app's menu bar — the viewer sees an IINA submenu
- flashing on top of Chrome's menus, which reads as "the agent
- clicked the wrong app." The AX call was correct; the frame the
- user sees is not. For recorded or observed sessions, this is an
- integrity bug even though it's not a correctness bug.
-
-**Good decision rule:** if the target is not already frontmost, do
-not use `AXMenuBarItem` at all. For *reading* in-window state,
-snapshot the window AX tree — most apps expose the same state via
-an in-window `AXStaticText`, title bar, or toolbar. For *dispatching*
-actions, use in-window `element_index` (buttons, toolbar items) or
-pixel clicks on in-window controls — both dispatch via AppKit's
-window-under-pointer hit-test and are **not** frontmost-gated.
-
-When the target IS frontmost, the menu-bar flow below is fine and
-the canonical path for menus.
-
-### The two-snapshot pattern (target frontmost only)
-
-Menu contents are a two-snapshot flow. Closed AXMenu subtrees are
-deliberately skipped during snapshot — otherwise every app's File /
-Edit / View hierarchy plus every Recent Items macOS has ever seen
-would inflate the tree 10-100x. But once a menu is *open*, its
-AXMenuItem children do receive `element_index` values so you can
-click them normally.
-
-1. Find the `[N] AXMenuBarItem "<Menu Name>"` in the tree.
-2. `click({pid, element_index: N, action: "pick"})` — menu bar items
- implement `AXPick` ("open my submenu"), not `AXPress`. Using the
- default action on an AXMenuBarItem is a no-op.
-3. Re-snapshot. The expanded menu's items now appear under the bar
- item as `[M] AXMenuItem "<Item Name>"`.
-4. Click the target item — most items respond to `AXPress` (default
- action). Submenus nest under the item and are walked the same way.
-5. Re-snapshot and verify.
-
-If you ever need to back out without selecting, `press_key({pid, key:
-"escape"})` closes the open menu. Leaving a menu expanded between
-turns poisons subsequent snapshots for that pid.
-
-### Commands gated on the target being frontmost
-
-Some menu items and global shortcuts (Preview's Tools → Rotate
-Right, ⌘R; anything in the View menu that manipulates the current
-document; most editor commands) are **disabled unless the target
-app is the key / frontmost window**. You'll see it in the AX tree
-as `DISABLED` on the menu item even though the user's intent is
-obviously valid.
-
-Before activating, confirm you're in this narrow case — the menu
-item still reads `DISABLED` after a fresh snapshot AND the action
-the user requested genuinely requires frontmost (Preview rotate,
-View menu document manipulation, editor commands). If either
-check fails, don't activate.
-
-When both checks pass, the driver has no `activate` tool
-(deliberately — the whole point is backgroundable control), so
-this is the one legitimate `osascript` fallback:
-
-```
-osascript -e 'tell application "<App Name>" to activate'
-```
-
-Then re-snapshot — the menu item loses its `DISABLED` tag — and
-`click({action: "pick"})` the item. Alternatively, a `hotkey`
-call delivered to the now-frontmost app works for the shortcut
-form (`⌘R`, `⌘+`, etc.).
-
-**Always name the focus steal in your response** so the user isn't
-surprised — "Briefly activating Preview to enable Tools → Rotate
-Right" or similar. Don't silently steal focus. You don't need to
-restore the previous frontmost afterwards unless the user asks —
-they can cmd-tab back.
+the real cursor (the per-pid event paths the driver uses on macOS
+and Windows route around HID synthesis). If the pid has no on-screen
+window the call errors with `pid X has no on-screen window` — you
+need a visible window to anchor the conversion. Dispatch details
+(SkyLight on macOS, layered UIA+PostMessage on Windows) are in the
+per-OS companion files.
## Web-rendered apps (browsers, Electron, Tauri)
For Chrome / Edge / Brave / Arc / Safari, Electron apps (Slack,
VSCode, Notion, Discord), and Tauri apps — see **`WEB_APPS.md`**.
-Covers: sparse AX tree population (retry-once pattern for Chromium),
-URL navigation via omnibox suggestions, the `set_value` workaround
-for keyboard commits on **minimized** windows (Return silently
-no-ops — symptom is a macOS system beep; use `set_value` or click a
-clickable equivalent), scrolling via synthetic PageUp/Down keystrokes,
-in-page clicks, and typing into web inputs.
-
-Chromium web content specifically also coerces `right_click` back to
-left — use `element_index` for AX-addressable targets and accept the
-limit otherwise.
-
-### Browser JS primitives — `page` tool and `get_window_state(javascript=)`
-
-When the AX tree doesn't expose the data you need (common in
-Chromium/Electron — the tree is sparse for web content), use the
-`page` tool or the `javascript` param on `get_window_state` to query
-the DOM directly via Apple Events. Requires "Allow JavaScript from
-Apple Events" to be enabled — see `WEB_APPS.md` for the setup path.
-
-**Three actions on the `page` tool:**
+Covers: sparse accessibility tree population (retry-once pattern for
+Chromium), URL navigation via omnibox suggestions, the `set_value`
+workaround for keyboard commits on **minimized** windows (Return
+silently no-ops — symptom is a system bell; use `set_value` or click
+a clickable equivalent), scrolling via synthetic PageUp/Down
+keystrokes, in-page clicks, and typing into web inputs.
-- `page({pid, window_id, action: "get_text"})` — returns
- `document.body.innerText`. Fastest way to read page content, prices,
- article text, or any raw text the AX tree truncates or omits.
+Browser JS primitives (the `page` tool, `get_window_state(javascript=)`)
+are macOS-only today — see `MACOS.md` for the Apple-Events backend.
-- `page({pid, window_id, action: "query_dom", css_selector: "a[href]",
- attributes: ["href"]})` — runs `querySelectorAll` and returns each
- match's tag, text, and requested attributes as a JSON array. Use for
- table rows, link hrefs, data attributes, structured page data.
+## Re-snapshot and verify — mandatory
-- `page({pid, window_id, action: "execute_javascript", javascript:
- "..."})` — raw JS. Wrap in an IIFE with try-catch. Don't use this for
- elements already indexed by `get_window_state` — `click` and
- `set_value` are more reliable there.
+**Always** call `get_window_state({pid, window_id})` after the
+action. This isn't optional verification — it's the second half of
+the snapshot invariant.
-**Co-located read — `get_window_state` with `javascript`:**
-
-```
-get_window_state({pid, window_id, javascript: "document.title"})
-```
-
-Runs the JS and appends the result as a `## JavaScript result` section
-alongside the AX snapshot — one round-trip instead of two. Use this
-when you need both the element tree (for subsequent clicks) and some
-page data in the same turn.
-
-**Decision rule — AX vs JS:**
-
-| Need | Use |
-|---|---|
-| Click / type into an element | `get_window_state` → `click` / `set_value` (AX, works backgrounded) |
-| Read text the AX tree drops | `page(get_text)` or `get_window_state(javascript=)` |
-| Scrape structured data (tables, hrefs) | `page(query_dom)` |
-| Trigger JS events / mutations | `page(execute_javascript)` |
-
-Supported backends:
-
-| App type | How | Context |
-|---|---|---|
-| Chrome / Brave / Edge | Apple Events `execute javascript` | Full DOM ✅ |
-| Safari | Apple Events `do JavaScript` | Full DOM ✅ |
-| Electron (VS Code, Cursor…) | SIGUSR1 → V8 inspector → CDP | Main process only: `process`, `Buffer` — no `document`, no `require` in sandboxed apps |
-| Electron (with `--remote-debugging-port`) | CDP page target | Full DOM ✅ |
-
-**Electron sandbox note:** SIGUSR1 connects to the Node.js *main* process.
-Sandboxed Electron apps (VS Code, Cursor) strip `require` and Electron
-APIs there. Useful for: `process.env`, `process.versions`, `process.cwd()`,
-`process.pid`. For full DOM/renderer access, launch the app with
-`--remote-debugging-port=9222` — cua-driver will detect and prefer the
-page target automatically.
-
-Arc returns no values; Firefox has no JS-via-AppleEvents support — see
-`WEB_APPS.md` for the full matrix.
-
-### 3. Re-snapshot and verify — mandatory
-
-**Always** call `get_window_state({pid, window_id})` after the action.
-This isn't optional verification — it's the second half of the
-snapshot invariant.
-
-Check the AX tree diff: a changed value, a new element, a new
-window, or the disappearance of the thing you just clicked (menus
-collapse after selection, buttons may become disabled, etc.). If
-nothing changed, the action likely failed silently — **tell the
-user what you attempted and what you observed**, don't paper over
-with "done" language. Agents that skip this step report success on
+Check the tree diff: a changed value, a new element, a new window,
+or the disappearance of the thing you just clicked (menus collapse
+after selection, buttons may become disabled, etc.). If nothing
+changed, the action likely failed silently — **tell the user what
+you attempted and what you observed**, don't paper over with "done"
+language. Agents that skip this step report success on
silently-dropped actions — the single most common failure mode.
## Recording trajectories
-Session-scoped action recording + replay, for demos, regressions, and
-training data. Only invoke when the user explicitly asks to record a
-session — the skill does not auto-enable this. CLI surface:
+Session-scoped action recording + replay, for demos, regressions,
+and training data. Only invoke when the user explicitly asks to
+record a session — the skill does not auto-enable this. CLI surface:
`cua-driver recording start|stop|status`; raw tool: `set_recording`.
See **`RECORDING.md`** for the full flow: enable/disable, turn folder
contents, replay via `replay_trajectory`, and the element_index
doesn't-survive-across-sessions caveat.
-## Common error patterns
+## Common error patterns (cross-platform)
| Error text | Meaning | Fix |
|---|---|---|
| `No cached AX state for pid X window_id W` | You either skipped `get_window_state` this turn, or passed a different `window_id` to the click than the one the snapshot cached against | Call `get_window_state({pid: X, window_id: W})` first — the same window_id you intend to click in |
| `Invalid element_index N for pid X window_id W` | Index is stale or out of range | Re-run `get_window_state` with the same window_id, pick a fresh index from the new tree |
| `window_id W belongs to pid P, not …` | Passed a window_id that's owned by a different process | Use `list_windows({pid: X})` to enumerate this pid's own windows |
-| `AX action AXPress failed with code …` | Element doesn't support AXPress | Try `show_menu`, `confirm`, `cancel`, or `pick` |
-| 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 | Affects `screenshot` and `get_window_state` (which always captures). Grant in System Settings — the driver can't operate without it |
+| `AX action … failed with code …` / `UIA invoke failed` | Element doesn't support the default action | Try `show_menu`, `confirm`, `cancel`, `pick`, or fall through to a pixel click on the element's center |
+
+Platform-specific errors (TCC dialogs on macOS, Session 0 / UAC
+prompts on Windows, AT-SPI bus issues on Linux) live in their
+respective companion files.
## Things to avoid
@@ -882,10 +465,11 @@ doesn't-survive-across-sessions caveat.
- **Never** translate screenshot pixels into a click — the screenshot
is for visual disambiguation, not coordinates. Use the
`element_index`.
-- **Prefer AX over pixels.** `click({pid, x, y})` works for
- canvas / WebView regions, but it lands blindly and skips the
- agent-cursor overlay. Exhaust AX paths (menu bars, cmd-k palettes,
- toolbar items, keyboard shortcuts) before dropping to coordinates.
+- **Prefer accessibility actions over pixels.** `click({pid, x, y})`
+ works for canvas / WebView regions, but it lands blindly and skips
+ the agent-cursor overlay. Exhaust accessibility paths (menu bars,
+ cmd-k palettes, toolbar items, keyboard shortcuts) before dropping
+ to coordinates.
- **Never** drive destructive actions (delete files, close unsaved
documents, send messages, submit forms) without explicit user
intent for that specific destructive step.
@@ -894,18 +478,16 @@ doesn't-survive-across-sessions caveat.
## Example end-to-end task
-**User:** "Open the Downloads folder in Finder."
+**User:** "Open the Downloads folder in the system file manager."
1. `launch_app({bundle_id: "com.apple.finder", urls: ["~/Downloads"]})`
- → `{pid: 844, windows: [{window_id: 6123, title: "Downloads", ...}]}`.
- Idempotent launch; plus Finder opens a hidden window rooted at
- `~/Downloads` via `application(_:open:)` — zero activation, no
- focus steal. The `windows` array lets you skip a `list_windows` hop.
-2. `get_window_state({pid: 844, window_id: 6123})` → verify an
- `AXWindow` whose title contains "Downloads" is present with a
- populated AX subtree (sidebar, list view, files).
+ on macOS, or `launch_app({name: "explorer", args: ["%USERPROFILE%\\Downloads"]})`
+ on Windows. Returns `{pid, windows: [{window_id, title, ...}]}`.
+ Idempotent launch; the driver opens a hidden window via the
+ platform's launch primitive — zero activation, no focus steal.
+2. `get_window_state({pid, window_id})` → verify the expected window
+ title is present with a populated tree (sidebar, list view, files).
3. Done.
-If the user instead asks to navigate *within* an already-open Finder
-window, use the menu-bar flow from the "Navigating native menu bars"
-section above (click Go → pick a menu item → re-snapshot → click it).
+Platform-specific examples and edge cases (Finder menu navigation,
+Explorer ribbon, GNOME Files) live in the per-OS companion files.
diff --git a/libs/cua-driver-rs/crates/cua-driver/src/bundle.rs b/libs/cua-driver-rs/crates/cua-driver/src/bundle.rs
index bea611bd63..cf642fe786 100644
--- a/libs/cua-driver-rs/crates/cua-driver/src/bundle.rs
+++ b/libs/cua-driver-rs/crates/cua-driver/src/bundle.rs
@@ -47,6 +47,7 @@ pub fn is_executable_inside_cuadriver_app() -> bool {
}
#[cfg(not(target_os = "macos"))]
+#[allow(dead_code)] // Non-macOS stub kept for API symmetry — see module header.
pub fn is_executable_inside_cuadriver_app() -> bool {
false
}
@@ -74,6 +75,7 @@ pub fn parent_is_not_launchd() -> bool {
}
#[cfg(not(unix))]
+#[allow(dead_code)] // Non-unix stub kept for API symmetry — see module header.
pub fn parent_is_not_launchd() -> bool {
// No launchd on non-Unix; the heuristic is macOS-only anyway.
// Returning false keeps the caller in-process on unsupported
diff --git a/libs/cua-driver-rs/crates/cua-driver/src/cli.rs b/libs/cua-driver-rs/crates/cua-driver/src/cli.rs
index faca5a7183..265a88c818 100644
--- a/libs/cua-driver-rs/crates/cua-driver/src/cli.rs
+++ b/libs/cua-driver-rs/crates/cua-driver/src/cli.rs
@@ -1111,11 +1111,6 @@ pub fn run_update_cmd(apply: bool) {
}
}
-/// `cua-driver dump-docs [--pretty]` — output all MCP tool schemas as JSON.
-pub fn run_dump_docs(registry: &ToolRegistry, pretty: bool) {
- run_dump_docs_with_type(registry, pretty, "all")
-}
-
/// Output documentation as JSON. `doc_type` is one of:
/// - `"mcp"` — only MCP tool docs (`{version, tools: [...]}`)
/// - `"cli"` — CLI docs (stub on Rust — Swift extracts via swift-argument-parser
diff --git a/libs/cua-driver-rs/crates/mcp-server/src/protocol.rs b/libs/cua-driver-rs/crates/mcp-server/src/protocol.rs
index 4dfe46adcc..be4ba7512c 100644
--- a/libs/cua-driver-rs/crates/mcp-server/src/protocol.rs
+++ b/libs/cua-driver-rs/crates/mcp-server/src/protocol.rs
@@ -152,22 +152,53 @@ pub fn initialize_result() -> Value {
"protocolVersion": "2025-06-18",
"capabilities": { "tools": {} },
"serverInfo": { "name": "cua-driver-rs", "version": env!("CARGO_PKG_VERSION") },
- "instructions": AGENT_INSTRUCTIONS
+ "instructions": agent_instructions()
})
}
-const AGENT_INSTRUCTIONS: &str = "\
-cua-driver-rs: cross-platform background computer-use automation.
-
-Tools let you interact with any app without stealing keyboard focus or \
-moving the visible cursor. Prefer element_index (AX/UIA) paths over pixel \
-coordinates — they work on backgrounded/hidden windows.
+/// MCP `instructions` (`InitializeResult.instructions`) sent to every
+/// connecting client. The spec frames this as a "hint... MAY be added
+/// to the system prompt" — eager, every-turn cost. We keep it under
+/// the community-recommended ~200-word ceiling and host the long-form
+/// workflow in `Skills/cua-driver-rs/SKILL.md`.
+///
+/// Templated per-host: the accessibility-tree provider name (AX on
+/// macOS, UIA on Windows, AT-SPI on Linux) is injected so a connecting
+/// agent only sees the path that applies, not all three. Same pattern
+/// Goose uses in its `ComputerController` extension and Open
+/// Interpreter uses for its system message.
+fn agent_instructions() -> String {
+ let (tree_kind, platform_skill_pointer) = if cfg!(target_os = "macos") {
+ (
+ "AX (Accessibility)",
+ "MACOS.md (no-foreground contract, AXMenuBar navigation, SkyLight click dispatch)",
+ )
+ } else if cfg!(target_os = "windows") {
+ (
+ "UIA (UI Automation)",
+ "WINDOWS.md (UIA tree, UWP / ApplicationFrameHost hosting, Session 0 isolation)",
+ )
+ } else {
+ (
+ "AT-SPI",
+ "LINUX.md (X11/Wayland status, AT-SPI bus, BETA-level support)",
+ )
+ };
+
+ format!(
+ r#"cua-driver-rs: cross-platform background computer-use automation.
+
+Tools let you interact with any app without stealing keyboard focus or moving the visible cursor. Prefer element_index ({tree_kind}) paths over pixel coordinates — they work on backgrounded/hidden windows.
Workflow per turn:
-1. list_apps → confirm the target is running, get pid
-2. list_windows → pick a window_id on the current Space
-3. get_window_state(pid, window_id) → refresh AX/UIA snapshot, get element indices
+1. launch_app → idempotent, returns pid + windows array in one call
+2. (skip list_windows when launch_app already returned a single window)
+3. get_window_state(pid, window_id) → refresh the {tree_kind} snapshot, get element indices
4. click/type_text/press_key using element_index from step 3
+5. get_window_state(pid, window_id) again → verify the action landed
+
+Agent cursor: set_agent_cursor_* tools visualise where the agent is acting without affecting the real mouse pointer.
-Agent cursor: set_agent_cursor_* tools visualise where the agent is acting \
-without affecting the real mouse pointer.";
+If a `cua-driver-rs` skill is loaded in your harness (Claude Code / Codex / OpenClaw / OpenCode dirs), prefer its detailed workflow — SKILL.md plus {platform_skill_pointer}. Install with `cua-driver skills install` if not yet present."#
+ )
+}
diff --git a/libs/cua-driver-rs/crates/platform-linux/src/tools/impl_.rs b/libs/cua-driver-rs/crates/platform-linux/src/tools/impl_.rs
index 9a1f7864e6..59fd70de3b 100644
--- a/libs/cua-driver-rs/crates/platform-linux/src/tools/impl_.rs
+++ b/libs/cua-driver-rs/crates/platform-linux/src/tools/impl_.rs
@@ -533,10 +533,17 @@ impl Tool for ClickTool {
fn def(&self) -> &ToolDef {
CLICK_DEF.get_or_init(|| ToolDef {
name: "click".into(),
- description: "Click at (x,y) coordinates or an element_index (AT-SPI) in a window via \
- XSendEvent. 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 back to \
- full-window space.".into(),
+ description: "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.\n\n\
+ Provide either (window_id + x/y) or (pid + element_index). Routes via \
+ XSendEvent (no focus steal). 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.\n\n\
+ After a zoom call, pass from_zoom=true to auto-translate zoom-image coords \
+ back to full-window space.".into(),
input_schema: json!({
"type":"object","required":["pid"],"properties":{
"pid":{"type":"integer"},
@@ -953,8 +960,17 @@ impl Tool for ScreenshotTool {
SS_DEF.get_or_init(|| ToolDef {
name: "screenshot".into(),
description: "Capture a screenshot via XGetImage or `import` (ImageMagick). \
- Without window_id captures the full primary display. Supports png and jpeg formats \
- (default jpeg, quality 85).".into(),
+ Returns base64-encoded image data in the requested format (default `jpeg`, \
+ quality `85`). The long edge is downscaled to fit the `max_image_dimension` \
+ config (default `1568` px — matches Anthropic's multimodal-vision input size, \
+ so a click-coord picked off this PNG addresses the same pixels the model \
+ reasoned over).\n\n\
+ **Prefer `get_window_state` for UI work** — it returns the AT-SPI tree \
+ alongside the same screenshot in one call, populates the element_index cache \
+ the click / type_text / scroll tools resolve against, and is the only path to \
+ backgrounded accessibility actions. `screenshot` is for when you just need \
+ pixels (vision grounding, debugging, attaching to a report).\n\n\
+ Without window_id captures the full primary display.".into(),
input_schema: json!({
"type":"object","properties":{
"window_id":{"type":"integer"},
diff --git a/libs/cua-driver-rs/crates/platform-macos/src/tools/click.rs b/libs/cua-driver-rs/crates/platform-macos/src/tools/click.rs
index aa71f007e4..dca1d580b0 100644
--- a/libs/cua-driver-rs/crates/platform-macos/src/tools/click.rs
+++ b/libs/cua-driver-rs/crates/platform-macos/src/tools/click.rs
@@ -43,12 +43,21 @@ fn def() -> &'static ToolDef {
DEF.get_or_init(|| ToolDef {
name: "click".into(),
description:
- "Left-click against a target pid. Two addressing modes:\n\n\
+ "Left-click against a target pid. **Prefer `element_index` over pixel \
+ coordinates** — element_index works on backgrounded / minimized / hidden / \
+ off-Space 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 AX tree.\n\n\
+ Two addressing modes:\n\n\
- element_index + window_id (from last get_window_state): AX action path. \
Works on backgrounded/hidden windows. No cursor move, no focus steal. \
- Preferred path.\n\n\
- - x, y (window-local screenshot pixels): CGEvent path. Synthesizes mouse \
- events and posts to pid. Use modifier for cmd/shift/option/ctrl.\n\n\
+ element_index 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\
+ - 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.\n\n\
action: press (default), show_menu, pick, confirm, cancel, open.\n\
from_zoom: set true after a zoom call to auto-translate zoom-image pixel \
coordinates to full-window space."
diff --git a/libs/cua-driver-rs/crates/platform-macos/src/tools/screenshot.rs b/libs/cua-driver-rs/crates/platform-macos/src/tools/screenshot.rs
index e8d1ba8106..1ec1dbed92 100644
--- a/libs/cua-driver-rs/crates/platform-macos/src/tools/screenshot.rs
+++ b/libs/cua-driver-rs/crates/platform-macos/src/tools/screenshot.rs
@@ -16,7 +16,15 @@ fn def() -> &'static ToolDef {
name: "screenshot".into(),
description:
"Capture a screenshot. Returns base64-encoded image data in the requested format \
- (default jpeg, quality 85).\n\n\
+ (default `jpeg`, quality `85`). The long edge is downscaled to fit the \
+ `max_image_dimension` config (default `1568` px — matches Anthropic's \
+ multimodal-vision input size, so a click-coord picked off this PNG addresses the \
+ same pixels the model reasoned over).\n\n\
+ **Prefer `get_window_state` for UI work** — it returns the AX tree alongside the \
+ same screenshot in one call, populates the element_index cache the click / \
+ type_text / scroll tools resolve against, and is the only path to backgrounded \
+ accessibility actions. `screenshot` is for when you just need pixels (vision \
+ grounding, debugging, attaching to a report).\n\n\
Without `window_id`, captures the full main display. With `window_id`, captures \
just that window (pair with `list_windows` or `get_accessibility_tree` which return \
window IDs).\n\n\
diff --git a/libs/cua-driver-rs/crates/platform-windows/src/capture.rs b/libs/cua-driver-rs/crates/platform-windows/src/capture.rs
index 2615ad863f..dcd8de39f3 100644
--- a/libs/cua-driver-rs/crates/platform-windows/src/capture.rs
+++ b/libs/cua-driver-rs/crates/platform-windows/src/capture.rs
@@ -211,8 +211,8 @@ unsafe fn screenshot_window_bytes_unsafe(hwnd: u64) -> Result<Vec<u8>> {
let ok = GetDIBits(mem_dc, bitmap, 0, h as u32, Some(pixels.as_mut_ptr() as *mut _), &mut bmi, DIB_RGB_COLORS);
SelectObject(mem_dc, old_bitmap);
- DeleteObject(bitmap);
- DeleteDC(mem_dc);
+ let _ = DeleteObject(bitmap);
+ let _ = DeleteDC(mem_dc);
ReleaseDC(hwnd, screen_dc);
if ok == 0 { bail!("GetDIBits returned 0"); }
@@ -372,8 +372,8 @@ pub fn screenshot_display_bytes() -> Result<Vec<u8>> {
let mut pixels = vec![0u8; (w * h * 4) as usize];
let ok = GetDIBits(mem_dc, bitmap, 0, h as u32, Some(pixels.as_mut_ptr() as *mut _), &mut bmi, DIB_RGB_COLORS);
SelectObject(mem_dc, old_bitmap);
- DeleteObject(bitmap);
- DeleteDC(mem_dc);
+ let _ = DeleteObject(bitmap);
+ let _ = DeleteDC(mem_dc);
ReleaseDC(HWND::default(), screen_dc);
if ok == 0 { bail!("GetDIBits returned 0"); }
encode_bgra_to_png(&pixels, w as u32, h as u32)
diff --git a/libs/cua-driver-rs/crates/platform-windows/src/overlay.rs b/libs/cua-driver-rs/crates/platform-windows/src/overlay.rs
index 648b81b3a0..4b9b515dcf 100644
--- a/libs/cua-driver-rs/crates/platform-windows/src/overlay.rs
+++ b/libs/cua-driver-rs/crates/platform-windows/src/overlay.rs
@@ -12,7 +12,7 @@
#![allow(non_snake_case, non_upper_case_globals)]
use std::sync::{Mutex, OnceLock};
-use std::time::{Duration, Instant};
+use std::time::Instant;
use cursor_overlay::{
CursorConfig, CursorShape, MotionConfig, OverlayCommand, Palette, PathPlanner, PathState,
@@ -468,9 +468,7 @@ fn draw_default_arrow(
#[cfg(target_os = "windows")]
fn run_overlay_thread(cfg: CursorConfig, rx: std::sync::mpsc::Receiver<OverlayCommand>) {
- use windows::Win32::Foundation::*;
use windows::Win32::UI::WindowsAndMessaging::*;
- use windows::Win32::Graphics::Gdi::*;
use windows::Win32::Media::timeBeginPeriod;
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::core::PCWSTR;
@@ -544,7 +542,7 @@ fn run_overlay_thread(cfg: CursorConfig, rx: std::sync::mpsc::Receiver<OverlayCo
let hwnd = hwnd.unwrap();
// Show without activation (mirrors ShowWithoutActivation in C# ref).
- unsafe { ShowWindow(hwnd, SW_SHOWNOACTIVATE); }
+ unsafe { let _ = ShowWindow(hwnd, SW_SHOWNOACTIVATE); }
// Set up timer at 8ms (~125 Hz) matching the C# reference.
unsafe { SetTimer(hwnd, 1, 8, None); }
@@ -558,7 +556,7 @@ fn run_overlay_thread(cfg: CursorConfig, rx: std::sync::mpsc::Receiver<OverlayCo
let mut msg = MSG::default();
unsafe {
while GetMessageW(&mut msg, None, 0, 0).as_bool() {
- TranslateMessage(&msg);
+ let _ = TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
@@ -588,7 +586,6 @@ unsafe extern "system" fn wnd_proc(
) -> windows::Win32::Foundation::LRESULT {
use windows::Win32::Foundation::*;
use windows::Win32::UI::WindowsAndMessaging::*;
- use windows::Win32::Graphics::Gdi::*;
match msg {
WM_TIMER => {
@@ -604,7 +601,7 @@ unsafe extern "system" fn wnd_proc(
let mut guard = RENDER.lock().unwrap();
if let Some(rs) = guard.as_mut() {
// Drain the channel.
- if let Ok(mut rx_guard) = CMD_RX_WIN.try_lock() {
+ if let Ok(rx_guard) = CMD_RX_WIN.try_lock() {
if let Some(ref rx) = *rx_guard {
while let Ok(cmd) = rx.try_recv() {
rs.apply_command(cmd);
@@ -661,7 +658,7 @@ unsafe fn update_layered_window(
let hdc_mem = CreateCompatibleDC(hdc_screen);
// Create a 32-bit top-down DIB section (BGRA).
- let mut bmi = BITMAPINFO {
+ let bmi = BITMAPINFO {
bmiHeader: BITMAPINFOHEADER {
biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,
biWidth: w,
@@ -684,7 +681,7 @@ unsafe fn update_layered_window(
0,
);
if hbmp.is_err() || bits_ptr.is_null() {
- DeleteDC(hdc_mem);
+ let _ = DeleteDC(hdc_mem);
ReleaseDC(None, hdc_screen);
return;
}
@@ -729,11 +726,11 @@ unsafe fn update_layered_window(
SourceConstantAlpha: 255,
AlphaFormat: 1, // AC_SRC_ALPHA
};
- UpdateLayeredWindow(hwnd, hdc_screen, Some(&pt_dst), Some(&sz),
+ let _ = UpdateLayeredWindow(hwnd, hdc_screen, Some(&pt_dst), Some(&sz),
hdc_mem, Some(&pt_src), COLORREF(0), Some(&blend), ULW_ALPHA);
- DeleteObject(hbmp);
- DeleteDC(hdc_mem);
+ let _ = DeleteObject(hbmp);
+ let _ = DeleteDC(hdc_mem);
ReleaseDC(None, hdc_screen);
}
diff --git a/libs/cua-driver-rs/crates/platform-windows/src/tools/impl_.rs b/libs/cua-driver-rs/crates/platform-windows/src/tools/impl_.rs
index dd52507fa0..36c2e69de3 100644
--- a/libs/cua-driver-rs/crates/platform-windows/src/tools/impl_.rs
+++ b/libs/cua-driver-rs/crates/platform-windows/src/tools/impl_.rs
@@ -1209,17 +1209,25 @@ impl Tool for ClickTool {
// window-local pixel coords via PostMessage). Windows-only schema
// extras (`button`, no `modifier`/`action`/`debug_image_out`) are
// documented in PARITY.md.
- description: "Left-click against a target pid. Two addressing modes:\n\n\
+ description: "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.\n\n\
+ Two addressing modes:\n\n\
- `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).\n\n\
+ is scoped per (pid, window_id) and is replaced by the next snapshot of the \
+ same window.\n\n\
- `x`, `y` (window-local screenshot pixels, top-left origin of the PNG \
returned by `get_window_state`) — synthesizes mouse events via \
PostMessage(WM_LBUTTONDOWN/UP) and delivers them to the deepest child \
window under that point. `count: 2` posts two down/up pairs for a \
- double-click.\n\n\
+ 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 in both modes. `window_id` is required when \
`element_index` is used (scopes the cache lookup). After a `zoom` call, \
@@ -2141,7 +2149,15 @@ impl Tool for ScreenshotTool {
// ScreenCaptureKit).
description: "Capture a screenshot of a single window via BitBlt + PrintWindow \
(no focus change). Returns base64-encoded image data in the requested format \
- (default jpeg, quality 85).\n\n\
+ (default `jpeg`, quality `85`). The long edge is downscaled to fit the \
+ `max_image_dimension` config (default `1568` px — matches Anthropic's \
+ multimodal-vision input size, so a click-coord picked off this PNG addresses \
+ the same pixels the model reasoned over).\n\n\
+ **Prefer `get_window_state` for UI work** — it returns the UIA tree alongside \
+ the same screenshot in one call, populates the element_index cache the click / \
+ type_text / scroll tools resolve against, and is the only path to backgrounded \
+ accessibility actions. `screenshot` is for when you just need pixels (vision \
+ grounding, debugging, attaching to a report).\n\n\
`window_id` is recommended (use `list_windows` to find it). When omitted, \
captures the full primary display — a Windows-only convenience for whole-\
screen snapshots without a per-window target.\n\n\
@@ -3545,7 +3561,7 @@ impl Tool for ZoomTool {
// ── type_text_chars ───────────────────────────────────────────────────────────
-pub struct TypeTextCharsTool { state: Arc<ToolState> }
+pub struct TypeTextCharsTool { _state: Arc<ToolState> }
static TYPE_CHARS_DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();
#[async_trait]
@@ -3993,7 +4009,7 @@ pub fn build_registry() -> ToolRegistry {
// mcp-server's `ToolRegistry::invoke`. Keeping it out of the registry
// means it doesn't show up in `tools/list` either, matching Swift's
// ToolRegistry.swift (`type_text_chars` not in `handlers`).
- let _: &TypeTextCharsTool = &TypeTextCharsTool { state: state.clone() }; // touch struct so it stays in this crate for now
+ let _: &TypeTextCharsTool = &TypeTextCharsTool { _state: state.clone() }; // touch struct so it stays in this crate for now
r.register_recording_tools();
r
}
diff --git a/libs/cua-driver-rs/crates/platform-windows/src/uia/mod.rs b/libs/cua-driver-rs/crates/platform-windows/src/uia/mod.rs
index 9aab153e28..d82bc4fb2d 100644
--- a/libs/cua-driver-rs/crates/platform-windows/src/uia/mod.rs
+++ b/libs/cua-driver-rs/crates/platform-windows/src/uia/mod.rs
@@ -170,8 +170,9 @@ unsafe fn walk_tree_unsafe(hwnd: u64, query: Option<&str>) -> UiaTreeResult {
if fallback_nodes.iter().any(|n| n.element_index.is_some()) {
nodes = fallback_nodes;
lines = fallback_lines;
- counter = fallback_counter;
- total = fallback_total;
+ // counter/total aren't read after this point — they're
+ // only used by walk_cached's &mut params for element
+ // indexing inside that call.
}
}
}
diff --git a/libs/cua-driver-rs/crates/platform-windows/src/uia/windows_enum.rs b/libs/cua-driver-rs/crates/platform-windows/src/uia/windows_enum.rs
index fb316a279c..12cb2603dd 100644
--- a/libs/cua-driver-rs/crates/platform-windows/src/uia/windows_enum.rs
+++ b/libs/cua-driver-rs/crates/platform-windows/src/uia/windows_enum.rs
@@ -12,6 +12,12 @@
//! UIA element's `NativeWindowHandle` — i.e. an honest Win32 HWND that downstream
//! code can pass to `GetWindowRect`, `PostMessage`, etc.
+// We pattern-match against `UIA_*ControlTypeId` constants from the `windows`
+// crate, which use mixed case we can't rename. The lint's suggested rewrite
+// (UIA_BUTTON_CONTROL_TYPE_ID) would silently shadow the external constant
+// with a fresh local binding and break the match. Mirrors overlay.rs:12.
+#![allow(non_upper_case_globals)]
+
use std::cell::RefCell;
use anyhow::{bail, Context};
diff --git a/libs/cua-driver-rs/scripts/install-local.ps1 b/libs/cua-driver-rs/scripts/install-local.ps1
index a7c7640b31..4c66486b4a 100644
--- a/libs/cua-driver-rs/scripts/install-local.ps1
+++ b/libs/cua-driver-rs/scripts/install-local.ps1
@@ -246,7 +246,13 @@ if ($AutoStart) {
$installedBinary = Join-Path $VisibleBinDir $BinaryName
$HintsTxt = Join-Path $RepoRoot "..\cua-driver\scripts\post-install-hints.txt"
if (Test-Path -LiteralPath $HintsTxt) {
- $hintsRaw = Get-Content -Raw -LiteralPath $HintsTxt
+ # Read explicitly as UTF-8. PowerShell 5.1's Get-Content -Raw falls
+ # back to Windows-1252 when the source file has no BOM, which turns
+ # the .txt's `•` / `—` into mojibake (`•` / `â€"`) in the rendered
+ # block. The other 3 installers don't hit this: install.ps1 reads
+ # the URL response via Invoke-WebRequest (HTTP charset decoding);
+ # _install-rust.sh / install-local.sh stream raw bytes through sed.
+ $hintsRaw = [System.IO.File]::ReadAllText($HintsTxt, [System.Text.Encoding]::UTF8)
Write-Host ($hintsRaw -replace '\{\{BINARY\}\}', $installedBinary)
} else {
# Repo layout changed or .txt missing — fall back to one-line
diff --git a/libs/cua-driver/scripts/_uninstall-rust.sh b/libs/cua-driver/scripts/_uninstall-rust.sh
deleted file mode 100755
index 037c6dc0fd..0000000000
--- a/libs/cua-driver/scripts/_uninstall-rust.sh
+++ /dev/null
@@ -1,353 +0,0 @@
-#!/usr/bin/env bash
-# _uninstall-rust.sh — private helper invoked by libs/cua-driver/scripts/uninstall.sh
-# (the canonical user-facing uninstaller) when --backend=rust is selected or
-# the script auto-detects a non-macOS host. Not intended for direct
-# invocation; user-facing one-liners always go through the parent
-# uninstall.sh, which forwards args + handles backend selection.
-#
-# Mirrors _install-rust.sh's on-disk knowledge — removes everything the
-# install script laid down:
-#
-# Linux:
-# - ~/.local/bin/cua-driver symlink (only when it resolves to a
-# cua-driver-rs path — a Swift-driver symlink is left in place)
-# - ~/.cua-driver-rs/ (entire package home: telemetry id, install
-# marker, versioned releases, current symlink, lockfile)
-# - ~/.config/systemd/user/cua-driver-rs.service (if --autostart was
-# used via install-local.sh — stop + disable + remove)
-# - Skill symlinks under ~/.claude/skills/cua-driver-rs, ~/.agents/
-# skills/cua-driver-rs, ~/.openclaw/skills/cua-driver-rs,
-# ~/.config/opencode/skills/cua-driver-rs
-#
-# macOS:
-# - /Applications/CuaDriver.app bundle (and legacy CuaDriverRs.app if present)
-# - ~/.local/bin/cua-driver symlink (only when it resolves into
-# /Applications/CuaDriver.app — see note on the bundle-id share below)
-# - ~/.cua-driver-rs/ (entire package home)
-# - ~/Library/LaunchAgents/com.trycua.cua-driver-rs.plist (if
-# --autostart was used via install-local.sh — unload + remove)
-# - Skill symlinks under ~/.claude/skills/cua-driver-rs, etc.
-#
-# Also scrubs Claude MCP registrations in ~/.claude.json that point at
-# the cua-driver-rs binary.
-#
-# Does NOT revoke TCC grants on macOS — same conservative stance as the
-# Swift uninstall.sh. The closing message points at the tccutil commands
-# for a clean re-install flow.
-set -euo pipefail
-
-USER_BIN_LINK="$HOME/.local/bin/cua-driver"
-# Canonical bundle path (post-rename — shares bundle id `com.trycua.driver`
-# with the Swift driver). The Rust install replaces Swift here; both
-# the Rust and Swift uninstallers target this path.
-APP_BUNDLE="/Applications/CuaDriver.app"
-# Legacy bundle path from earlier Rust releases that coexisted with
-# Swift under a separate name. Cleaned up if found.
-LEGACY_APP_BUNDLE="/Applications/CuaDriverRs.app"
-HOME_DIR="${CUA_DRIVER_RS_HOME:-$HOME/.cua-driver-rs}"
-LAUNCHAGENT_PLIST="$HOME/Library/LaunchAgents/com.trycua.cua-driver-rs.plist"
-SYSTEMD_USER_UNIT="$HOME/.config/systemd/user/cua-driver-rs.service"
-SKILL_PACK_NAME="cua-driver-rs"
-
-OS="$(uname -s 2>/dev/null || echo unknown)"
-
-log() { printf '==> %s\n' "$*"; }
-
-# Resolve a symlink target to an absolute path. realpath -e fails when the
-# target is missing — we want to inspect dangling symlinks too (a leftover
-# from a half-removed install should still be cleaned up here), so fall
-# back to readlink + manual normalize when realpath errors out.
-resolve_link() {
- local link="$1"
- if [[ ! -L "$link" ]]; then
- printf ''; return 0
- fi
- local target
- if target="$(realpath "$link" 2>/dev/null)"; then
- printf '%s' "$target"
- return 0
- fi
- # Dangling symlink — readlink still returns the stored target. Make
- # it absolute by joining with the link's dirname for non-absolute
- # stored values.
- target="$(readlink "$link" 2>/dev/null || true)"
- case "$target" in
- /*) printf '%s' "$target" ;;
- *) printf '%s/%s' "$(cd -- "$(dirname -- "$link")" && pwd)" "$target" ;;
- esac
-}
-
-# --- CLI symlink ---------------------------------------------------------
-#
-# Only remove ~/.local/bin/cua-driver when it resolves into a cua-driver-rs
-# install. Post-rename, the Rust install lives at /Applications/CuaDriver.app
-# — the SAME path the Swift driver uses, with the same bundle id
-# `com.trycua.driver`. Path-based detection alone can't distinguish
-# them. We rely on the presence of `$HOME_DIR` (~/.cua-driver-rs/) — the
-# Rust-specific state dir — as the marker that this is a Rust install.
-# Pre-rename installs at /Applications/CuaDriverRs.app are still cleaned
-# up unambiguously by path.
-if [[ -L "$USER_BIN_LINK" ]]; then
- RESOLVED="$(resolve_link "$USER_BIN_LINK")"
- case "$RESOLVED" in
- *"CuaDriverRs.app"*|*"/Applications/CuaDriver.app"*|*"$HOME_DIR"*|*".cua-driver-rs"*)
- rm -f "$USER_BIN_LINK"
- log "removed $USER_BIN_LINK -> $RESOLVED"
- ;;
- *)
- log "$USER_BIN_LINK resolves to $RESOLVED (not a cua-driver-rs path; skipping)"
- ;;
- esac
-elif [[ -e "$USER_BIN_LINK" ]]; then
- log "$USER_BIN_LINK exists but is not a symlink (skipping; refusing to clobber a real file)"
-else
- log "no CLI symlink at $USER_BIN_LINK (skipping)"
-fi
-
-# --- Autostart (Linux systemd --user) -----------------------------------
-#
-# install-local.sh --autostart registers ~/.config/systemd/user/
-# cua-driver-rs.service. Stop + disable + remove if present so the
-# daemon doesn't come back at the next logon. systemctl --user no-ops
-# gracefully on a non-systemd host (returns non-zero, which we swallow).
-if [[ "$OS" == "Linux" && -f "$SYSTEMD_USER_UNIT" ]]; then
- if command -v systemctl >/dev/null 2>&1; then
- systemctl --user stop cua-driver-rs.service 2>/dev/null || true
- systemctl --user disable cua-driver-rs.service 2>/dev/null || true
- log "stopped + disabled systemd --user unit cua-driver-rs.service"
- fi
- rm -f "$SYSTEMD_USER_UNIT"
- log "removed $SYSTEMD_USER_UNIT"
- if command -v systemctl >/dev/null 2>&1; then
- systemctl --user daemon-reload 2>/dev/null || true
- fi
-elif [[ "$OS" == "Linux" ]]; then
- log "no systemd --user unit at $SYSTEMD_USER_UNIT (skipping)"
-fi
-
-# --- Autostart (macOS LaunchAgent) --------------------------------------
-#
-# install-local.sh --autostart on macOS registers
-# ~/Library/LaunchAgents/com.trycua.cua-driver-rs.plist. Unload (so the
-# running daemon stops) + remove the plist.
-if [[ "$OS" == "Darwin" && -f "$LAUNCHAGENT_PLIST" ]]; then
- launchctl unload "$LAUNCHAGENT_PLIST" 2>/dev/null || true
- rm -f "$LAUNCHAGENT_PLIST"
- log "removed LaunchAgent $LAUNCHAGENT_PLIST"
-elif [[ "$OS" == "Darwin" ]]; then
- log "no LaunchAgent at $LAUNCHAGENT_PLIST (skipping)"
-fi
-
-# --- .app bundle (macOS only) -------------------------------------------
-#
-# Removes /Applications/CuaDriver.app (current canonical Rust path,
-# shared with the Swift driver via bundle id `com.trycua.driver`) AND
-# /Applications/CuaDriverRs.app (legacy, pre-rename releases).
-# Removing the shared `.app` path is correct here: a user who runs
-# `uninstall.sh --experimental-rust` wants the binary on disk gone;
-# if they previously had the Swift binary at the same path, they've
-# already overwritten it with Rust on install. Re-installing the
-# Swift driver afterward is a re-run of the canonical `install.sh`.
-if [[ "$OS" == "Darwin" ]]; then
- for bundle_path in "$APP_BUNDLE" "$LEGACY_APP_BUNDLE"; do
- if [[ -d "$bundle_path" ]]; then
- SUDO=""
- if [[ ! -w "$(dirname "$bundle_path")" ]]; then
- SUDO="sudo"
- fi
- $SUDO rm -rf "$bundle_path"
- log "removed $bundle_path"
- else
- log "no app bundle at $bundle_path (skipping)"
- fi
- done
-fi
-
-# --- Package home -------------------------------------------------------
-#
-# Everything under $CUA_DRIVER_RS_HOME (default ~/.cua-driver-rs):
-# telemetry id, install marker, versioned releases, current symlink,
-# lockfile, local skill copy, version_check.json cache.
-if [[ -d "$HOME_DIR" ]]; then
- rm -rf "$HOME_DIR"
- log "removed $HOME_DIR"
-else
- log "no package home at $HOME_DIR (skipping)"
-fi
-
-# --- Agent skill symlinks -----------------------------------------------
-#
-# Only remove when the link is a symlink — never clobber a real
-# directory (a dev user with a hand-managed skills dir is safe). Note
-# we don't check the target here because `cua-driver skills install`
-# writes platform-dependent targets (the local copy under $HOME_DIR/
-# skills/cua-driver-rs/), and on Windows the `<HomeDir>/skills` shape
-# is different. The [[ -L ]] check is the load-bearing safety bar.
-for SKILL_LINK in \
- "$HOME/.claude/skills/$SKILL_PACK_NAME" \
- "$HOME/.agents/skills/$SKILL_PACK_NAME" \
- "$HOME/.openclaw/skills/$SKILL_PACK_NAME" \
- "$HOME/.config/opencode/skills/$SKILL_PACK_NAME"; do
- if [[ -L "$SKILL_LINK" ]]; then
- rm -f "$SKILL_LINK"
- log "removed skill symlink $SKILL_LINK"
- elif [[ -d "$SKILL_LINK" ]]; then
- log "$SKILL_LINK is a real directory, not a symlink (skipping)"
- else
- log "no skill symlink at $SKILL_LINK (skipping)"
- fi
-done
-
-# --- Claude Code MCP registrations --------------------------------------
-#
-# Same scrub shape as the Swift uninstall.sh, keyed on the cua-driver-rs
-# binary name + the per-platform install paths. Unrelated MCP servers
-# are left alone.
-CLAUDE_JSON="$HOME/.claude.json"
-if [[ -f "$CLAUDE_JSON" ]] && command -v python3 >/dev/null 2>&1; then
- PY_OUTPUT="$(
- CLAUDE_JSON="$CLAUDE_JSON" HOME_DIR="$HOME_DIR" python3 <<'PY'
-import json
-import os
-import shutil
-import sys
-import tempfile
-import time
-
-path = os.environ["CLAUDE_JSON"]
-home_dir = os.environ.get("HOME_DIR", "")
-
-try:
- with open(path, "r", encoding="utf-8") as f:
- data = json.load(f)
-except Exception as exc:
- print(f"could not read Claude config {path}: {exc}", file=sys.stderr)
- raise SystemExit(0)
-
-removed = []
-
-def text_parts(value):
- if isinstance(value, str):
- return [value]
- if isinstance(value, list):
- return [item for item in value if isinstance(item, str)]
- return []
-
-def invokes_cua_driver_rs(server):
- if not isinstance(server, dict):
- return False
- parts = []
- parts.extend(text_parts(server.get("command")))
- parts.extend(text_parts(server.get("args")))
- joined = " ".join(parts)
- # Match the Rust-port-specific anchors: bundle name, package home,
- # explicit ".cua-driver-rs" segment. Plain "cua-driver" alone is
- # ambiguous (the Swift binary uses the same filename), so we key on
- # the Rust-specific paths here. The user can run the Swift
- # uninstall.sh separately if they have both.
- if home_dir and home_dir in joined:
- return True
- return ("CuaDriverRs.app" in joined
- or "/Applications/CuaDriver.app" in joined
- or ".cua-driver-rs" in joined
- or "cua-driver-rs" in joined)
-
-def should_remove(name, server):
- return name in {"cua-driver-rs"} or invokes_cua_driver_rs(server)
-
-def scrub_servers(servers, scope):
- if not isinstance(servers, dict):
- return
- for name in list(servers.keys()):
- if should_remove(name, servers[name]):
- del servers[name]
- removed.append(f"{scope}:{name}")
-
-scrub_servers(data.get("mcpServers"), "user")
-
-projects = data.get("projects")
-if isinstance(projects, dict):
- for project in projects.values():
- if isinstance(project, dict):
- scrub_servers(project.get("mcpServers"), "project")
-
-if not removed:
- raise SystemExit(0)
-
-backup = f"{path}.bak-cua-driver-rs-uninstall-{int(time.time())}"
-shutil.copy2(path, backup)
-
-directory = os.path.dirname(path) or "."
-fd, tmp_path = tempfile.mkstemp(
- prefix=".claude.json.",
- suffix=".tmp",
- dir=directory,
- text=True,
-)
-try:
- with os.fdopen(fd, "w", encoding="utf-8") as f:
- json.dump(data, f, indent=2, ensure_ascii=False)
- f.write("\n")
- os.replace(tmp_path, path)
-except Exception:
- try:
- os.unlink(tmp_path)
- except OSError:
- pass
- raise
-
-print(f"removed Claude MCP registration(s): {', '.join(removed)}")
-print(f"backed up Claude config to {backup}")
-PY
- )"
- if [[ -n "$PY_OUTPUT" ]]; then
- while IFS= read -r line; do
- log "$line"
- done <<< "$PY_OUTPUT"
- else
- log "no Claude MCP registrations for cua-driver-rs found in $CLAUDE_JSON"
- fi
-else
- log "no Claude config cleanup via python3 (missing $CLAUDE_JSON or python3)"
-fi
-
-# Best-effort CLI cleanup. `claude mcp remove` only touches the active
-# project / user scopes — fine to run; it's a no-op when the entries
-# were already scrubbed above.
-if command -v claude >/dev/null 2>&1; then
- for SERVER in cua-driver-rs; do
- for SCOPE in local project user; do
- if claude mcp remove "$SERVER" -s "$SCOPE" >/dev/null 2>&1; then
- log "removed Claude MCP server $SERVER from $SCOPE scope"
- fi
- done
- done
-else
- log "claude CLI not found (skipping Claude MCP CLI cleanup)"
-fi
-
-# --- Closing message ----------------------------------------------------
-
-if [[ "$OS" == "Darwin" ]]; then
- cat << 'FINALUNMSG'
-
-cua-driver-rs uninstalled.
-
-TCC grants (Accessibility + Screen Recording) remain in System
-Settings > Privacy & Security. Reset them explicitly if you want a
-clean re-install flow:
-
- tccutil reset Accessibility com.trycua.driver
- tccutil reset ScreenCapture com.trycua.driver
-
- (Note: `com.trycua.driver` is shared with the Swift cua-driver.
- Resetting it clears grants for both backends. If you still use the
- Swift driver, skip this step and let macOS keep the grants — the
- next Swift launch will re-use them.)
-FINALUNMSG
-else
- cat << 'FINALUNMSG'
-
-cua-driver-rs uninstalled.
-FINALUNMSG
-fi
diff --git a/libs/cua-driver/scripts/uninstall.ps1 b/libs/cua-driver/scripts/uninstall.ps1
index 9d22ca2dcf..caa45f41b4 100644
--- a/libs/cua-driver/scripts/uninstall.ps1
+++ b/libs/cua-driver/scripts/uninstall.ps1
@@ -1,4 +1,4 @@
-# cua-driver-rs uninstaller (Windows) — removes everything install.ps1
+# cua-driver-rs uninstaller (Windows) — removes everything install.ps1
# laid down: the Scheduled Task autostart entry, running daemon
# processes, the directory junctions wiring the visible bin dir back to
# a per-version release dir, the entire package home tree, and any skill
@@ -51,6 +51,18 @@
# each major delete. The one-liner is interactive by
# default so a stray paste doesn't accidentally wipe a
# working install.
+#
+# Elevation:
+# `install.ps1 -AutoStart` (and `cua-driver autostart enable`) register
+# the `cua-driver-serve` Scheduled Task at RunLevel=Highest — the
+# daemon spawned by it then runs at High IL so it can drive UWP /
+# AppContainer apps (Calculator, Settings, Photos — see
+# autostart.rs:127). Side-effect: a non-elevated process (even the same
+# user that installed it) can NOT terminate the daemon or delete the
+# task — both fail with Access Denied, and the binary stays locked
+# under ~\.cua-driver\... . If we detect either condition at startup
+# we self-elevate via UAC; otherwise we run in-place. Mirrors the
+# install side's elevation pattern in autostart.rs:215-223.
[CmdletBinding()]
param(
@@ -61,6 +73,65 @@ Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$ProgressPreference = "SilentlyContinue"
+# ---------- Elevation pre-check -------------------------------------------
+
+$AutoStartTask = "cua-driver-serve"
+
+function Test-IsElevated {
+ ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
+}
+
+function Test-NeedsElevation {
+ # Either the autostart task exists (RunLevel=Highest, so deleting it
+ # needs admin) or a cua-driver.exe is running (its parent was the
+ # elevated task, so terminating it needs admin too). Detecting either
+ # upfront lets us self-elevate before we start tearing things down
+ # — otherwise the non-elevated path silently swallows access-denied
+ # from schtasks /Delete + Stop-Process and leaves a dangling install.
+ $prevEAP = $ErrorActionPreference
+ $ErrorActionPreference = 'Continue'
+ try {
+ & schtasks.exe /Query /TN $AutoStartTask 2>$null | Out-Null
+ $hasTask = ($LASTEXITCODE -eq 0)
+ } finally {
+ $ErrorActionPreference = $prevEAP
+ }
+ $hasDaemon = @(Get-Process -Name "cua-driver" -ErrorAction SilentlyContinue).Count -gt 0
+ return ($hasTask -or $hasDaemon)
+}
+
+if (-not (Test-IsElevated) -and (Test-NeedsElevation)) {
+ Write-Host "==> cua-driver-rs uninstaller: detected -AutoStart install state" -ForegroundColor Cyan
+ Write-Host " (the 'cua-driver-serve' task is RunLevel=Highest and/or a daemon is"
+ Write-Host " running at High IL). Removing them needs admin — triggering UAC prompt."
+
+ # Re-exec self elevated. $MyInvocation.MyCommand.Path is set when invoked
+ # from a file on disk; empty when piped through `irm ... | iex` (the
+ # canonical one-liner). For the iex case we materialize the script body
+ # to a tempfile and re-exec from there — RunAs needs a file path.
+ $forwarded = @()
+ if ($Force) { $forwarded += '-Force' }
+
+ $scriptPath = $MyInvocation.MyCommand.Path
+ if (-not $scriptPath) {
+ $tmp = Join-Path $env:TEMP ("cua-driver-uninstall-" + [Guid]::NewGuid().ToString('N') + ".ps1")
+ $body = $MyInvocation.MyCommand.Definition
+ Set-Content -LiteralPath $tmp -Value $body -Encoding UTF8
+ $scriptPath = $tmp
+ }
+
+ $argList = @('-ExecutionPolicy', 'Bypass', '-NoProfile', '-File', $scriptPath) + $forwarded
+ try {
+ $proc = Start-Process -FilePath powershell.exe -ArgumentList $argList -Verb RunAs -PassThru -Wait -ErrorAction Stop
+ exit $proc.ExitCode
+ } catch {
+ Write-Host "error: failed to elevate ($($_.Exception.Message))" -ForegroundColor Red
+ Write-Host " Re-run this script from an elevated PowerShell instead:" -ForegroundColor Yellow
+ Write-Host " Right-click PowerShell → Run as Administrator, then re-run the uninstall." -ForegroundColor Yellow
+ exit 1
+ }
+}
+
# ---------- Path resolution (mirrors install.ps1) -------------------------
if ($env:CUA_DRIVER_RS_INSTALL_DIR) {
@@ -87,7 +158,7 @@ $LegacyHomeDir = Join-Path $env:USERPROFILE ".cua-driver-rs"
$PackagesDir = Join-Path $HomeDir "packages"
$CurrentDir = Join-Path $PackagesDir "current"
-$AutoStartTask = "cua-driver-serve"
+# $AutoStartTask hoisted to the elevation pre-check block above.
# Skill junctions — mirrors the AGENTS list in
# libs/cua-driver-rs/crates/cua-driver/src/skills.rs (the verb that
diff --git a/libs/cua-driver/scripts/uninstall.sh b/libs/cua-driver/scripts/uninstall.sh
index e66aa5c46d..e31393a80a 100755
--- a/libs/cua-driver/scripts/uninstall.sh
+++ b/libs/cua-driver/scripts/uninstall.sh
@@ -1,29 +1,54 @@
#!/usr/bin/env bash
-# cua-driver uninstaller. Removes everything install.sh laid down — Swift
-# driver by default, cua-driver-rs (Rust port) when --experimental-rust /
-# --backend=rust is passed (mirrors install.sh's flag set), or auto-detects
-# the Rust port on non-macOS hosts (same as install.sh).
+# cua-driver uninstaller (Swift driver + Rust port, all platforms in a
+# single file). Mirrors uninstall.ps1 on Windows: one canonical script
+# per shell, no private `_uninstall-rust.sh` helper.
+#
+# Behaviour by host + flag:
+# macOS + no flag → Swift uninstall (today's default)
+# macOS + --backend=swift → Swift uninstall (explicit no-op default)
+# macOS + --experimental-rust → Rust port uninstall (Swift binary untouched)
+# macOS + --backend=rust → same as --experimental-rust
+# Linux/ + no flag → auto-selects Rust uninstall
+# other (Swift binary is macOS-only; nothing to remove on Linux)
+# Linux/ + --backend=swift → no-op (still allowed for compatibility)
#
# Swift uninstall removes:
-# - ~/.local/bin/cua-driver symlink
+# - ~/.local/bin/cua-driver symlink (+ legacy /usr/local/bin/cua-driver)
# - /Applications/CuaDriver.app bundle
# - ~/.cua-driver/ (telemetry id + install marker)
# - ~/Library/Application Support/Cua Driver/ (config.json)
# - ~/Library/Caches/cua-driver/ (daemon/cache state)
+# - Skill symlinks under ~/.claude/skills/cua-driver, ~/.agents/skills/
+# cua-driver, ~/.openclaw/skills/cua-driver, ~/.config/opencode/
+# skills/cua-driver (only when they point at our app bundle)
+# - Claude MCP registrations in ~/.claude.json (cua-driver / cua-computer-use)
#
-# Rust uninstall (--experimental-rust / --backend=rust / non-macOS) delegates
-# to a colocated private helper, _uninstall-rust.sh — see that script for
-# the full list of paths it removes.
+# Rust uninstall removes:
+# Linux:
+# - ~/.local/bin/cua-driver symlink (only when it resolves to a
+# cua-driver-rs path — a Swift-driver symlink is left in place)
+# - ~/.cua-driver-rs/ (entire package home: telemetry id, install
+# marker, versioned releases, current symlink, lockfile)
+# - ~/.config/systemd/user/cua-driver-rs.service (if --autostart
+# was used via install-local.sh — stop + disable + remove)
+# - Skill symlinks under ~/.claude/skills/cua-driver-rs, ~/.agents/
+# skills/cua-driver-rs, ~/.openclaw/skills/cua-driver-rs,
+# ~/.config/opencode/skills/cua-driver-rs
+# macOS:
+# - /Applications/CuaDriver.app bundle (+ legacy CuaDriverRs.app)
+# - ~/.local/bin/cua-driver symlink (only when it resolves into
+# /Applications/CuaDriver.app)
+# - ~/.cua-driver-rs/ (entire package home)
+# - ~/Library/LaunchAgents/com.trycua.cua-driver-rs.plist (if
+# --autostart was used via install-local.sh — unload + remove)
+# - Skill symlinks under ~/.claude/skills/cua-driver-rs, etc.
#
-# Does NOT revoke TCC grants (Accessibility + Screen Recording) on macOS.
+# Also scrubs Claude MCP registrations in ~/.claude.json that match
+# the active backend.
#
-# Flags:
-# --experimental-rust uninstall the cua-driver-rs (Rust port) backend
-# instead of the Swift binary. Delegates to
-# libs/cua-driver/scripts/_uninstall-rust.sh. The
-# Swift binary (if present) is left untouched.
-# Also accepted as --backend=rust.
-# --backend=swift explicit no-op default (Swift uninstall).
+# Does NOT revoke TCC grants on macOS (Accessibility + Screen Recording).
+# The closing message points at the tccutil commands for a clean
+# re-install flow.
#
# Usage:
# /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver/scripts/uninstall.sh)"
@@ -32,21 +57,22 @@
# /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver/scripts/uninstall.sh)" -- --experimental-rust
#
# # Linux auto-detects and removes the Rust port without any flag.
+#
+# Env overrides (mirror install side):
+# CUA_DRIVER_RS_HOME Rust package home to remove (default ~/.cua-driver-rs)
set -euo pipefail
-# Rust-backend delegation target. The Rust uninstall logic is a private
-# helper script colocated with this one — _uninstall-rust.sh — so that
-# this directory holds the single user-facing uninstall.sh per platform.
-# `--experimental-rust` below either execs the on-disk helper (dev /
-# checked-out-tree case) or curls this URL and pipes it to bash
-# (`curl ... | bash` uninstall case). Mirrors install.sh's pattern.
-RUST_UNINSTALLER_URL="https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver/scripts/_uninstall-rust.sh"
-
-# Lightweight flag parsing — same two-pass shape as install.sh so the
-# argv shapes stay bit-compatible across install/uninstall and a future
-# Rust-only flag added to _uninstall-rust.sh flows through here without
-# edits to this file.
+# ----------------------------------------------------------------------
+# Flag parsing — same two-pass shape as install.sh so the argv shapes
+# stay bit-compatible across install/uninstall and a future Rust-only
+# flag flows through without edits.
+# ----------------------------------------------------------------------
USE_RUST_BACKEND=0
+# Tracks whether the user explicitly named a backend. Needed so that
+# `--backend=swift` on Linux suppresses the auto-Rust dispatch below
+# (the doc says `--backend=swift` is an "explicit no-op default" —
+# without this flag the auto-Rust branch silently overrode it).
+BACKEND_EXPLICIT=0
FORWARDED_ARGS=()
PASSTHROUGH=0
while [[ $# -gt 0 ]]; do
@@ -54,9 +80,9 @@ while [[ $# -gt 0 ]]; do
FORWARDED_ARGS+=("$1"); shift; continue
fi
case "$1" in
- --experimental-rust) USE_RUST_BACKEND=1; shift ;;
- --backend=rust) USE_RUST_BACKEND=1; shift ;;
- --backend=swift) shift ;; # explicit default — no-op
+ --experimental-rust) USE_RUST_BACKEND=1; BACKEND_EXPLICIT=1; shift ;;
+ --backend=rust) USE_RUST_BACKEND=1; BACKEND_EXPLICIT=1; shift ;;
+ --backend=swift) BACKEND_EXPLICIT=1; shift ;; # explicit default — no-op
--backend=*)
printf 'error: unknown backend %q; supported: swift, rust\n' "${1#*=}" >&2
exit 2
@@ -66,71 +92,382 @@ while [[ $# -gt 0 ]]; do
esac
done
-# --- Auto-delegate to Rust on non-macOS ---------------------------------
-#
-# The Swift binary is macOS-only — there's nothing for the Swift uninstall
-# path to remove on Linux. Auto-set USE_RUST_BACKEND=1 so a single
-# canonical URL works on every platform: `curl … cua-driver/scripts/
-# uninstall.sh | bash` removes the Swift driver on macOS (today's default)
-# and the Rust port on Linux. macOS users who want to remove the Rust
-# port still pass `--experimental-rust` / `--backend=rust` explicitly.
+# Auto-select Rust on non-macOS — but only when the user didn't pin a
+# backend. The Swift binary is macOS-only, so `--backend=swift` on
+# Linux is a deliberate no-op (the script reaches the Swift branch
+# below, finds nothing, exits clean). Same logic as install.sh so a
+# single canonical URL works on every platform.
+OS="$(uname -s 2>/dev/null || echo unknown)"
AUTO_RUST=0
-if [[ "$USE_RUST_BACKEND" == "0" && "$(uname -s 2>/dev/null)" != "Darwin" ]]; then
+if [[ "$BACKEND_EXPLICIT" == "0" && "$USE_RUST_BACKEND" == "0" && "$OS" != "Darwin" ]]; then
USE_RUST_BACKEND=1
AUTO_RUST=1
- printf 'note: detected non-macOS host (%s); auto-selecting the cua-driver-rs Rust uninstall.\n' \
- "$(uname -s 2>/dev/null || echo unknown)" >&2
+ printf 'note: detected non-macOS host (%s); auto-selecting the cua-driver-rs Rust uninstall.\n' "$OS" >&2
printf ' Pass --backend=swift to force the Swift uninstall path (will be a no-op on non-Darwin).\n' >&2
fi
-# --- Optional delegation to the experimental Rust backend ---------------
-#
-# If the user opted in with --experimental-rust / --backend=rust, hand the
-# rest of argv to _uninstall-rust.sh and exit. The Swift uninstall path
-# below is never touched in this case, so the Swift binary (if present)
-# is left exactly as-is.
+if [[ "$USE_RUST_BACKEND" == "1" && "$AUTO_RUST" == "0" ]]; then
+ printf 'note: uninstalling cua-driver-rs (Rust port). The Swift binary won'"'"'t be touched.\n' >&2
+elif [[ "$USE_RUST_BACKEND" == "1" && "$AUTO_RUST" == "1" ]]; then
+ printf 'note: uninstalling cua-driver-rs (the Rust port — canonical on non-macOS).\n' >&2
+fi
+
+# ----------------------------------------------------------------------
+# Shared helpers
+# ----------------------------------------------------------------------
+log() { printf '==> %s\n' "$*"; }
+
+# Resolve a symlink target to an absolute path. realpath -e fails when
+# the target is missing — we want to inspect dangling symlinks too (a
+# leftover from a half-removed install should still be cleaned up), so
+# fall back to readlink + manual normalize when realpath errors out.
+resolve_link() {
+ local link="$1"
+ if [[ ! -L "$link" ]]; then
+ printf ''; return 0
+ fi
+ local target
+ if target="$(realpath "$link" 2>/dev/null)"; then
+ printf '%s' "$target"
+ return 0
+ fi
+ target="$(readlink "$link" 2>/dev/null || true)"
+ case "$target" in
+ /*) printf '%s' "$target" ;;
+ *) printf '%s/%s' "$(cd -- "$(dirname -- "$link")" && pwd)" "$target" ;;
+ esac
+}
+
+# ----------------------------------------------------------------------
+# Rust uninstall branch (Linux + opt-in on macOS).
+# ----------------------------------------------------------------------
if [[ "$USE_RUST_BACKEND" == "1" ]]; then
- if [[ "$AUTO_RUST" == "0" ]]; then
- # Explicit opt-in on macOS.
- printf 'note: uninstalling cua-driver-rs (Rust port). The Swift binary won'"'"'t be touched.\n' >&2
+ USER_BIN_LINK="$HOME/.local/bin/cua-driver"
+ # Canonical bundle path (post-rename — shares bundle id
+ # `com.trycua.driver` with the Swift driver). The Rust install
+ # replaces Swift here; both uninstallers target this path.
+ APP_BUNDLE="/Applications/CuaDriver.app"
+ # Legacy bundle path from earlier Rust releases that coexisted with
+ # Swift under a separate name. Cleaned up if found.
+ LEGACY_APP_BUNDLE="/Applications/CuaDriverRs.app"
+ HOME_DIR="${CUA_DRIVER_RS_HOME:-$HOME/.cua-driver-rs}"
+ LAUNCHAGENT_PLIST="$HOME/Library/LaunchAgents/com.trycua.cua-driver-rs.plist"
+ SYSTEMD_USER_UNIT="$HOME/.config/systemd/user/cua-driver-rs.service"
+ SKILL_PACK_NAME="cua-driver-rs"
+
+ # Rust-install marker. The post-rename Rust bundle path
+ # `/Applications/CuaDriver.app` is shared with the Swift driver
+ # (same bundle id `com.trycua.driver`), so we can't use that path
+ # alone as a Rust-install discriminator — a Swift-only Mac that
+ # runs `uninstall.sh --experimental-rust` by mistake would lose
+ # its Swift bundle, symlink, and Claude MCP registrations. This
+ # marker says "there's at least one unambiguously-Rust artifact
+ # on disk." We gate every shared-path removal below on it.
+ #
+ # Markers (any one suffices):
+ # - $HOME_DIR exists (~/.cua-driver-rs/ — Rust-only state dir)
+ # - /Applications/CuaDriverRs.app exists (legacy, pre-rename)
+ # - LaunchAgent plist exists (autostart was used)
+ RUST_INSTALL_PRESENT=0
+ if [[ -d "$HOME_DIR" || -d "$LEGACY_APP_BUNDLE" || -f "$LAUNCHAGENT_PLIST" || -f "$SYSTEMD_USER_UNIT" ]]; then
+ RUST_INSTALL_PRESENT=1
+ fi
+
+ # --- CLI symlink ---
+ # Only remove ~/.local/bin/cua-driver when it resolves into a
+ # cua-driver-rs install. Pre-rename installs at
+ # /Applications/CuaDriverRs.app are unambiguously Rust and always
+ # removed. Post-rename, the Rust install lives at
+ # /Applications/CuaDriver.app — the SAME path the Swift driver
+ # uses — so we only remove that link when $RUST_INSTALL_PRESENT.
+ if [[ -L "$USER_BIN_LINK" ]]; then
+ RESOLVED="$(resolve_link "$USER_BIN_LINK")"
+ case "$RESOLVED" in
+ *"CuaDriverRs.app"*|*"$HOME_DIR"*|*".cua-driver-rs"*)
+ # Unambiguous Rust paths.
+ rm -f "$USER_BIN_LINK"
+ log "removed $USER_BIN_LINK -> $RESOLVED"
+ ;;
+ *"/Applications/CuaDriver.app"*)
+ # Shared with the Swift driver — require a Rust marker.
+ if [[ "$RUST_INSTALL_PRESENT" == "1" ]]; then
+ rm -f "$USER_BIN_LINK"
+ log "removed $USER_BIN_LINK -> $RESOLVED"
+ else
+ log "$USER_BIN_LINK -> $RESOLVED (shared with Swift driver and no Rust marker on disk; skipping)"
+ fi
+ ;;
+ *)
+ log "$USER_BIN_LINK resolves to $RESOLVED (not a cua-driver-rs path; skipping)"
+ ;;
+ esac
+ elif [[ -e "$USER_BIN_LINK" ]]; then
+ log "$USER_BIN_LINK exists but is not a symlink (skipping; refusing to clobber a real file)"
else
- # Auto-selected on Linux/other — drop the "experimental" qualifier
- # (Rust is the canonical install path on every non-macOS platform).
- printf 'note: uninstalling cua-driver-rs (the Rust port — canonical on non-macOS).\n' >&2
+ log "no CLI symlink at $USER_BIN_LINK (skipping)"
+ fi
+
+ # --- Autostart (Linux systemd --user) ---
+ # install-local.sh --autostart registers
+ # ~/.config/systemd/user/cua-driver-rs.service. Stop + disable +
+ # remove if present so the daemon doesn't come back at next logon.
+ # systemctl --user no-ops gracefully on a non-systemd host.
+ if [[ "$OS" == "Linux" && -f "$SYSTEMD_USER_UNIT" ]]; then
+ if command -v systemctl >/dev/null 2>&1; then
+ systemctl --user stop cua-driver-rs.service 2>/dev/null || true
+ systemctl --user disable cua-driver-rs.service 2>/dev/null || true
+ log "stopped + disabled systemd --user unit cua-driver-rs.service"
+ fi
+ rm -f "$SYSTEMD_USER_UNIT"
+ log "removed $SYSTEMD_USER_UNIT"
+ if command -v systemctl >/dev/null 2>&1; then
+ systemctl --user daemon-reload 2>/dev/null || true
+ fi
+ elif [[ "$OS" == "Linux" ]]; then
+ log "no systemd --user unit at $SYSTEMD_USER_UNIT (skipping)"
+ fi
+
+ # --- Autostart (macOS LaunchAgent) ---
+ # install-local.sh --autostart on macOS registers
+ # ~/Library/LaunchAgents/com.trycua.cua-driver-rs.plist. Unload (so
+ # the running daemon stops) + remove the plist.
+ if [[ "$OS" == "Darwin" && -f "$LAUNCHAGENT_PLIST" ]]; then
+ launchctl unload "$LAUNCHAGENT_PLIST" 2>/dev/null || true
+ rm -f "$LAUNCHAGENT_PLIST"
+ log "removed LaunchAgent $LAUNCHAGENT_PLIST"
+ elif [[ "$OS" == "Darwin" ]]; then
+ log "no LaunchAgent at $LAUNCHAGENT_PLIST (skipping)"
fi
- # Prefer the on-disk copy when this script is running from a checked-out
- # tree (dev / CI). Falls back to curling the canonical URL for the
- # `curl ... | bash` uninstall path, where $BASH_SOURCE is unset / -.
- LOCAL_RUST_UNINSTALLER=""
- if [[ -n "${BASH_SOURCE[0]:-}" && "${BASH_SOURCE[0]}" != "-" && -f "${BASH_SOURCE[0]}" ]]; then
- SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
- CANDIDATE="$SCRIPT_DIR/_uninstall-rust.sh"
- if [[ -f "$CANDIDATE" ]]; then
- LOCAL_RUST_UNINSTALLER="$CANDIDATE"
+ # --- .app bundle (macOS only) ---
+ # Legacy /Applications/CuaDriverRs.app is unambiguously Rust and
+ # always removed when present. /Applications/CuaDriver.app is the
+ # current canonical Rust path BUT also where the Swift driver
+ # lives (same bundle id `com.trycua.driver`), so we only remove
+ # it when $RUST_INSTALL_PRESENT — protects a Swift-only Mac from
+ # losing its bundle if `uninstall.sh --experimental-rust` is run
+ # by mistake.
+ if [[ "$OS" == "Darwin" ]]; then
+ if [[ -d "$LEGACY_APP_BUNDLE" ]]; then
+ SUDO=""
+ if [[ ! -w "$(dirname "$LEGACY_APP_BUNDLE")" ]]; then
+ SUDO="sudo"
+ fi
+ $SUDO rm -rf "$LEGACY_APP_BUNDLE"
+ log "removed $LEGACY_APP_BUNDLE"
+ else
+ log "no app bundle at $LEGACY_APP_BUNDLE (skipping)"
+ fi
+ if [[ -d "$APP_BUNDLE" ]]; then
+ if [[ "$RUST_INSTALL_PRESENT" == "1" ]]; then
+ SUDO=""
+ if [[ ! -w "$(dirname "$APP_BUNDLE")" ]]; then
+ SUDO="sudo"
+ fi
+ $SUDO rm -rf "$APP_BUNDLE"
+ log "removed $APP_BUNDLE"
+ else
+ log "$APP_BUNDLE exists but no Rust marker on disk (~/.cua-driver-rs/, CuaDriverRs.app, LaunchAgent, systemd unit); leaving it (looks like a Swift-only install)"
+ fi
+ else
+ log "no app bundle at $APP_BUNDLE (skipping)"
fi
fi
- # macOS ships bash 3.2, which trips `set -u` when expanding an empty
- # array via "${arr[@]}" — guard with the +alt-value pattern so the
- # zero-arg case becomes a literal no-expansion.
- if [[ -n "$LOCAL_RUST_UNINSTALLER" ]]; then
- exec /bin/bash "$LOCAL_RUST_UNINSTALLER" ${FORWARDED_ARGS[@]+"${FORWARDED_ARGS[@]}"}
+ # --- Package home ---
+ # Everything under $CUA_DRIVER_RS_HOME (default ~/.cua-driver-rs):
+ # telemetry id, install marker, versioned releases, current
+ # symlink, lockfile, local skill copy, version_check.json cache.
+ if [[ -d "$HOME_DIR" ]]; then
+ rm -rf "$HOME_DIR"
+ log "removed $HOME_DIR"
else
- if ! command -v curl >/dev/null 2>&1; then
- printf 'error: curl not found on PATH; cannot fetch %s\n' "$RUST_UNINSTALLER_URL" >&2
- exit 1
+ log "no package home at $HOME_DIR (skipping)"
+ fi
+
+ # --- Agent skill symlinks ---
+ # Only remove when the link is a symlink — never clobber a real
+ # directory (a dev user with a hand-managed skills dir is safe).
+ # We don't check the target here because `cua-driver skills install`
+ # writes platform-dependent targets (the local copy under $HOME_DIR/
+ # skills/cua-driver-rs/). The [[ -L ]] check is the load-bearing
+ # safety bar.
+ for SKILL_LINK in \
+ "$HOME/.claude/skills/$SKILL_PACK_NAME" \
+ "$HOME/.agents/skills/$SKILL_PACK_NAME" \
+ "$HOME/.openclaw/skills/$SKILL_PACK_NAME" \
+ "$HOME/.config/opencode/skills/$SKILL_PACK_NAME"; do
+ if [[ -L "$SKILL_LINK" ]]; then
+ rm -f "$SKILL_LINK"
+ log "removed skill symlink $SKILL_LINK"
+ elif [[ -d "$SKILL_LINK" ]]; then
+ log "$SKILL_LINK is a real directory, not a symlink (skipping)"
+ else
+ log "no skill symlink at $SKILL_LINK (skipping)"
fi
- # `exec` so the Rust uninstaller replaces this process — we don't
- # want to fall through to the Swift uninstall path on any error here.
- RUST_UNINSTALLER_SCRIPT="$(curl -fsSL "$RUST_UNINSTALLER_URL")" || {
- printf 'error: failed to download Rust uninstaller from %s\n' "$RUST_UNINSTALLER_URL" >&2
- exit 1
- }
- exec /bin/bash -c "$RUST_UNINSTALLER_SCRIPT" cua-driver-rs-uninstall ${FORWARDED_ARGS[@]+"${FORWARDED_ARGS[@]}"}
+ done
+
+ # --- Claude Code MCP registrations ---
+ # Same scrub shape as the Swift branch, keyed on the cua-driver-rs
+ # binary name + the per-platform install paths. Unrelated MCP
+ # servers are left alone.
+ CLAUDE_JSON="$HOME/.claude.json"
+ if [[ -f "$CLAUDE_JSON" ]] && command -v python3 >/dev/null 2>&1; then
+ PY_OUTPUT="$(
+ CLAUDE_JSON="$CLAUDE_JSON" HOME_DIR="$HOME_DIR" RUST_INSTALL_PRESENT="$RUST_INSTALL_PRESENT" python3 <<'PY'
+import json
+import os
+import shutil
+import sys
+import tempfile
+import time
+
+path = os.environ["CLAUDE_JSON"]
+home_dir = os.environ.get("HOME_DIR", "")
+rust_install_present = os.environ.get("RUST_INSTALL_PRESENT", "0") == "1"
+
+try:
+ with open(path, "r", encoding="utf-8") as f:
+ data = json.load(f)
+except Exception as exc:
+ print(f"could not read Claude config {path}: {exc}", file=sys.stderr)
+ raise SystemExit(0)
+
+removed = []
+
+def text_parts(value):
+ if isinstance(value, str):
+ return [value]
+ if isinstance(value, list):
+ return [item for item in value if isinstance(item, str)]
+ return []
+
+def invokes_cua_driver_rs(server):
+ if not isinstance(server, dict):
+ return False
+ parts = []
+ parts.extend(text_parts(server.get("command")))
+ parts.extend(text_parts(server.get("args")))
+ joined = " ".join(parts)
+ # Match the Rust-port-specific anchors: bundle name, package home,
+ # explicit ".cua-driver-rs" segment. Plain "cua-driver" alone is
+ # ambiguous (the Swift binary uses the same filename). The shared
+ # /Applications/CuaDriver.app path is ALSO ambiguous (Rust took
+ # over Swift's bundle id) — only count it as Rust when a Rust
+ # install marker is on disk; otherwise it's almost certainly a
+ # Swift registration we shouldn't scrub.
+ if home_dir and home_dir in joined:
+ return True
+ if "CuaDriverRs.app" in joined or ".cua-driver-rs" in joined or "cua-driver-rs" in joined:
+ return True
+ if rust_install_present and "/Applications/CuaDriver.app" in joined:
+ return True
+ return False
+
+def should_remove(name, server):
+ return name in {"cua-driver-rs"} or invokes_cua_driver_rs(server)
+
+def scrub_servers(servers, scope):
+ if not isinstance(servers, dict):
+ return
+ for name in list(servers.keys()):
+ if should_remove(name, servers[name]):
+ del servers[name]
+ removed.append(f"{scope}:{name}")
+
+scrub_servers(data.get("mcpServers"), "user")
+
+projects = data.get("projects")
+if isinstance(projects, dict):
+ for project in projects.values():
+ if isinstance(project, dict):
+ scrub_servers(project.get("mcpServers"), "project")
+
+if not removed:
+ raise SystemExit(0)
+
+backup = f"{path}.bak-cua-driver-rs-uninstall-{int(time.time())}"
+shutil.copy2(path, backup)
+
+directory = os.path.dirname(path) or "."
+fd, tmp_path = tempfile.mkstemp(
+ prefix=".claude.json.",
+ suffix=".tmp",
+ dir=directory,
+ text=True,
+)
+try:
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
+ json.dump(data, f, indent=2, ensure_ascii=False)
+ f.write("\n")
+ os.replace(tmp_path, path)
+except Exception:
+ try:
+ os.unlink(tmp_path)
+ except OSError:
+ pass
+ raise
+
+print(f"removed Claude MCP registration(s): {', '.join(removed)}")
+print(f"backed up Claude config to {backup}")
+PY
+ )"
+ if [[ -n "$PY_OUTPUT" ]]; then
+ while IFS= read -r line; do
+ log "$line"
+ done <<< "$PY_OUTPUT"
+ else
+ log "no Claude MCP registrations for cua-driver-rs found in $CLAUDE_JSON"
+ fi
+ else
+ log "no Claude config cleanup via python3 (missing $CLAUDE_JSON or python3)"
+ fi
+
+ # Best-effort CLI cleanup. `claude mcp remove` only touches the
+ # active project / user scopes — fine to run; it's a no-op when the
+ # entries were already scrubbed above.
+ if command -v claude >/dev/null 2>&1; then
+ for SERVER in cua-driver-rs; do
+ for SCOPE in local project user; do
+ if claude mcp remove "$SERVER" -s "$SCOPE" >/dev/null 2>&1; then
+ log "removed Claude MCP server $SERVER from $SCOPE scope"
+ fi
+ done
+ done
+ else
+ log "claude CLI not found (skipping Claude MCP CLI cleanup)"
fi
+
+ # --- Closing message ---
+ if [[ "$OS" == "Darwin" ]]; then
+ cat << 'FINALUNMSG'
+
+cua-driver-rs uninstalled.
+
+TCC grants (Accessibility + Screen Recording) remain in System
+Settings > Privacy & Security. Reset them explicitly if you want a
+clean re-install flow:
+
+ tccutil reset Accessibility com.trycua.driver
+ tccutil reset ScreenCapture com.trycua.driver
+
+ (Note: `com.trycua.driver` is shared with the Swift cua-driver.
+ Resetting it clears grants for both backends. If you still use the
+ Swift driver, skip this step and let macOS keep the grants — the
+ next Swift launch will re-use them.)
+FINALUNMSG
+ else
+ cat << 'FINALUNMSG'
+
+cua-driver-rs uninstalled.
+FINALUNMSG
+ fi
+ exit 0
fi
+# ----------------------------------------------------------------------
+# Swift uninstall branch (macOS, default).
+# ----------------------------------------------------------------------
USER_BIN_LINK="$HOME/.local/bin/cua-driver"
SYSTEM_BIN_LINK="/usr/local/bin/cua-driver"
APP_BUNDLE="/Applications/CuaDriver.app"
@@ -141,8 +478,6 @@ CACHE_DIR="$HOME/Library/Caches/cua-driver"
LEGACY_UPDATE_SCRIPT="/usr/local/bin/cua-driver-update"
LEGACY_UPDATER_PLIST="$HOME/Library/LaunchAgents/com.trycua.cua_driver_updater.plist"
-log() { printf '==> %s\n' "$*"; }
-
# CLI symlinks. Try the user-bin first (no sudo), then the legacy
# /usr/local/bin path (needs sudo on default macOS).
for BIN_LINK in "$USER_BIN_LINK" "$SYSTEM_BIN_LINK"; do
@@ -203,8 +538,8 @@ else
fi
# Agent skill symlinks (Claude Code + Codex). Only remove when the link
-# is ours — a dev user pointing the symlink at a working copy of the repo
-# keeps theirs untouched.
+# is ours — a dev user pointing the symlink at a working copy of the
+# repo keeps theirs untouched.
SKILL_TARGET_EXPECTED="$APP_BUNDLE/Contents/Resources/Skills/cua-driver"
for SKILL_LINK in \
"$HOME/.claude/skills/cua-driver" \
@@ -220,11 +555,11 @@ for SKILL_LINK in \
done
# Claude Code MCP registrations. `claude mcp remove` only removes from
-# the current project / user scopes, while ~/.claude.json can also contain
-# stale project entries for other directories. Scrub only registrations
-# that are explicitly named cua-driver or whose command points at a
-# cua-driver binary, so unrelated servers named "computer-use" are left
-# alone.
+# the current project / user scopes, while ~/.claude.json can also
+# contain stale project entries for other directories. Scrub only
+# registrations explicitly named cua-driver or whose command points at
+# a cua-driver binary, so unrelated servers named "computer-use" are
+# left alone.
CLAUDE_JSON="$HOME/.claude.json"
if [[ -f "$CLAUDE_JSON" ]] && command -v python3 >/dev/null 2>&1; then
PY_OUTPUT="$(
@@ -323,8 +658,8 @@ else
fi
# Best-effort CLI cleanup for the active Claude project. This covers
-# .mcp.json / current-working-directory scopes when present and is harmless
-# when the entries were already removed above.
+# .mcp.json / current-working-directory scopes when present and is
+# harmless when the entries were already removed above.
if command -v claude >/dev/null 2>&1; then
for SERVER in cua-driver cua-computer-use; do
for SCOPE in local project user; do