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.

fix(cua-driver): launch the installed app by path, stop daemons from any copy, drop extra copies (#5471)

Francesco Bonacci41eee2fb91c2
diff --git a/.github/scripts/tests/test_cua_driver_release_wiring.py b/.github/scripts/tests/test_cua_driver_release_wiring.py
index b856bee7d4..2fd771861d 100644
--- a/.github/scripts/tests/test_cua_driver_release_wiring.py
+++ b/.github/scripts/tests/test_cua_driver_release_wiring.py
@@ -688,24 +688,47 @@ fi
self.assertIn("launches the installed", shared_hints)
self.assertNotIn("launches CuaDriver", shared_hints)
- def test_post_install_hints_include_muse_stdio_mcp_config(self) -> None:
+ def test_post_install_hints_stay_short_and_point_at_mcp_config(self) -> None:
shared_hints = self.read("libs/cua-driver/scripts/post-install-hints.txt")
- self.assertIn("Muse Code (macOS / Linux", shared_hints)
- self.assertIn("$XDG_CONFIG_HOME/muse/settings.json", shared_hints)
- self.assertIn('"mcp_servers": {', shared_hints)
- self.assertIn('"transport": "stdio"', shared_hints)
- self.assertIn('"command": "{{BINARY}}"', shared_hints)
- self.assertIn('"args": ["mcp"]', shared_hints)
- self.assertIn("MCP servers load at startup", shared_hints)
-
- def test_post_install_hints_use_canonical_capability_manifest_flags(self) -> None:
- shared_hints = self.read("libs/cua-driver/scripts/post-install-hints.txt")
-
- self.assertIn("--capability-manifest", shared_hints)
- self.assertIn("--approve-capability-manifest", shared_hints)
- self.assertNotIn("--session-policy", shared_hints)
- self.assertNotIn("--approve-session-policy", shared_hints)
+ # Three essential steps; client snippets live behind `mcp-config`.
+ for step in (" 1. ", " 2. ", " 3. "):
+ self.assertIn(step, shared_hints)
+ self.assertNotIn(" 4. ", shared_hints)
+ self.assertLess(len(shared_hints.splitlines()), 30)
+ self.assertIn("{{BINARY}} permissions grant", shared_hints)
+ self.assertIn("{{BINARY}} mcp-config --client <name>", shared_hints)
+ for removed in (
+ '"mcpServers"',
+ "codex mcp add",
+ "droid mcp add",
+ "qwen mcp add",
+ "check_permissions",
+ "open -n -g",
+ "-a CuaDriver",
+ ):
+ self.assertNotIn(removed, shared_hints)
+
+ def test_clients_without_an_mcp_config_preset_are_documented(self) -> None:
+ # Muse Code and GitHub Copilot CLI have no `mcp-config --client` preset;
+ # their snippets moved out of the installer output into the docs.
+ docs = self.read("docs/content/docs/cua-driver/guides/connect-your-agent.mdx")
+
+ self.assertIn("Muse Code (macOS, Linux)", docs)
+ self.assertIn("$XDG_CONFIG_HOME/muse/settings.json", docs)
+ self.assertIn('"mcp_servers"', docs)
+ self.assertIn('"transport": "stdio"', docs)
+ self.assertIn("MCP servers load at startup", docs)
+ self.assertIn("GitHub Copilot CLI", docs)
+ self.assertIn("~/.copilot/mcp-config.json", docs)
+
+ def test_permission_docs_use_canonical_capability_manifest_flags(self) -> None:
+ docs = self.read("docs/content/docs/cua-driver/guides/permissions.mdx")
+
+ self.assertIn("--capability-manifest", docs)
+ self.assertIn("--approve-capability-manifest", docs)
+ self.assertNotIn("--session-policy", docs)
+ self.assertNotIn("--approve-session-policy", docs)
def test_agent_sdk_examples_use_implicit_sessions_and_per_call_targets(self) -> None:
example_dir = REPO_ROOT / "libs/cua-driver/examples/agent-sdks"
diff --git a/.github/scripts/tests/test_verify_cua_driver_release_signatures.py b/.github/scripts/tests/test_verify_cua_driver_release_signatures.py
index d0c87d3127..d14180548d 100644
--- a/.github/scripts/tests/test_verify_cua_driver_release_signatures.py
+++ b/.github/scripts/tests/test_verify_cua_driver_release_signatures.py
@@ -96,6 +96,7 @@ class FakeMacTools:
self.team = team
self.requirement = requirement
self.calls: list[list[str]] = []
+ self.unregistered: list[tuple[str, Path, bool]] = []
def __call__(self, argv) -> CommandResult:
argv = list(argv)
@@ -105,6 +106,10 @@ class FakeMacTools:
with tarfile.open(argv[2]) as tar:
tar.extractall(argv[4])
return CommandResult(0, "")
+ if tool == gate.LSREGISTER:
+ # The bundle must still be on disk when it is unregistered.
+ self.unregistered.append((argv[1], target, target.is_dir()))
+ return CommandResult(0, "")
adhoc = not self.signed or target.name in self.adhoc_names
if tool == "codesign" and "--verify" in argv:
if not self.signed or target.name in self.unsigned_names:
@@ -150,6 +155,42 @@ def test_notarized_release_passes(tmp_path: Path) -> None:
assert verified.count(name) == 4, name
+def test_extracted_apps_are_unregistered_from_launchservices_then_deleted(tmp_path: Path) -> None:
+ """Checking a release must not leave extra CuaDriver.app copies registered."""
+ tools = FakeMacTools()
+ scratch = tmp_path / "scratch"
+ scratch.mkdir()
+
+ report = verify_macos(
+ make_darwin_artifacts(tmp_path / "a"), VERSION, run=tools, workdir=scratch
+ )
+
+ assert report.failures == []
+ # One extracted CuaDriver.app per full darwin archive, each unregistered with
+ # `lsregister -u` while it still exists, and nothing left behind.
+ assert [flag for flag, _, _ in tools.unregistered] == ["-u"] * 3
+ assert {path.name for _, path, _ in tools.unregistered} == {"CuaDriver.app"}
+ assert all(existed for _, _, existed in tools.unregistered)
+ assert list(scratch.iterdir()) == []
+ # The unregistering happens after the last check and before nothing else.
+ last_check = max(i for i, call in enumerate(tools.calls) if call[0] != gate.LSREGISTER)
+ first_unregister = min(i for i, call in enumerate(tools.calls) if call[0] == gate.LSREGISTER)
+ assert first_unregister > last_check
+
+
+def test_a_host_without_lsregister_still_verifies(tmp_path: Path) -> None:
+ tools = FakeMacTools()
+
+ def run(argv):
+ if argv[0] == gate.LSREGISTER:
+ raise FileNotFoundError(argv[0])
+ return tools(argv)
+
+ report = verify_macos(make_darwin_artifacts(tmp_path / "a"), VERSION, run=run)
+
+ assert report.failures == []
+
+
def test_unsigned_node_runtime_fails_unless_checking_a_legacy_release(tmp_path: Path) -> None:
# 0.28.2 through 0.30.2 shipped a notarized app next to an unsigned
# cua_driver_node_runtime.node (#4168).
diff --git a/.github/scripts/verify_cua_driver_release_signatures.py b/.github/scripts/verify_cua_driver_release_signatures.py
index 1549cc450e..89b69df0f4 100644
--- a/.github/scripts/verify_cua_driver_release_signatures.py
+++ b/.github/scripts/verify_cua_driver_release_signatures.py
@@ -207,6 +207,28 @@ def check_notarized(
report.ok(f"{label}: stapled notarization ticket is valid")
+LSREGISTER = (
+ "/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/"
+ "LaunchServices.framework/Versions/A/Support/lsregister"
+)
+
+
+def _forget_extracted_apps(scratch: Path, run: Runner) -> None:
+ """Unregister every app bundle extracted under ``scratch`` from LaunchServices.
+
+ ``codesign`` and ``spctl`` make macOS learn a bundle's path and bundle id.
+ A released CuaDriver.app extracted into a temp dir and then deleted would
+ stay registered, and ``open -a CuaDriver`` (or a permission row in System
+ Settings) can later resolve to that dead copy. Best effort; the files are
+ deleted by the caller.
+ """
+ for app in sorted(scratch.rglob("*.app")):
+ try:
+ run([LSREGISTER, "-u", str(app)])
+ except OSError:
+ return # no lsregister here (not macOS); nothing was registered
+
+
def _extract_tar(archive: Path, destination: Path, run: Runner) -> bool:
# System tar matches what the installer runs and preserves bundle metadata.
result = run(["tar", "-xzf", str(archive), "-C", str(destination)])
@@ -279,6 +301,7 @@ def verify_macos(
target, f"{name}:{file_name}", team_id, run, report, deep=False
)
finally:
+ _forget_extracted_apps(scratch, run)
shutil.rmtree(scratch, ignore_errors=True)
for installer in sorted(artifacts.rglob("*.pkg")):
diff --git a/.github/workflows/ci-jev-use.yml b/.github/workflows/ci-jev-use.yml
index 976e97f713..16117242fb 100644
--- a/.github/workflows/ci-jev-use.yml
+++ b/.github/workflows/ci-jev-use.yml
@@ -401,7 +401,7 @@ jobs:
"$CUA_DRIVER_BIN" stop >/dev/null 2>&1 || true
bash libs/cua-driver/tests/runners/macos-lume/seed-tcc-guest.sh \
--app /Applications/CuaDriver.app --expected-client com.trycua.driver
- open -n -g -a CuaDriver --args serve
+ open -n -g /Applications/CuaDriver.app --args serve
for _ in $(seq 1 60); do
if "$CUA_DRIVER_BIN" permissions status --json > "$RUNNER_TEMP/permissions.json" 2>/dev/null \
&& jq -e '.accessibility == true and .screen_recording == true' "$RUNNER_TEMP/permissions.json" >/dev/null; then
@@ -518,7 +518,7 @@ jobs:
"$CUA_DRIVER_BIN" stop >/dev/null 2>&1 || true
bash libs/cua-driver/tests/runners/macos-lume/seed-tcc-guest.sh \
--app /Applications/CuaDriver.app --expected-client com.trycua.driver
- open -n -g -a CuaDriver --args serve
+ open -n -g /Applications/CuaDriver.app --args serve
for _ in $(seq 1 60); do
if "$CUA_DRIVER_BIN" permissions status --json > "$RUNNER_TEMP/permissions.json" 2>/dev/null \
&& jq -e '.accessibility == true and .screen_recording == true' "$RUNNER_TEMP/permissions.json" >/dev/null; then
diff --git a/blog/evaluating-gemini-3.5-flash-on-computer-use.md b/blog/evaluating-gemini-3.5-flash-on-computer-use.md
index 03a5c35fc7..5609c38752 100644
--- a/blog/evaluating-gemini-3.5-flash-on-computer-use.md
+++ b/blog/evaluating-gemini-3.5-flash-on-computer-use.md
@@ -105,7 +105,7 @@ cua-driver --version
**macOS**
```bash
-open -n -g -a CuaDriver --args serve
+cua-driver permissions grant
```
**Linux (pre-release)**
diff --git a/docs/content/docs/cua-driver/guides/connect-your-agent.mdx b/docs/content/docs/cua-driver/guides/connect-your-agent.mdx
index ce2ad22b0d..157264e991 100644
--- a/docs/content/docs/cua-driver/guides/connect-your-agent.mdx
+++ b/docs/content/docs/cua-driver/guides/connect-your-agent.mdx
@@ -39,6 +39,8 @@ cua-driver mcp-config --client <client>
| Qwen Code | `--client qwen`, which prints `qwen mcp add cua-driver <path> mcp` | |
| Pi | `--client pi` | No MCP: runs one-shot `cua-driver call …` commands. |
| Kimi Code | `kimi mcp add cua-driver -- <path> mcp`, then `kimi mcp test cua-driver` | No preset. |
+| GitHub Copilot CLI | Add `{"mcpServers": {"cua-driver": {"type": "local", "command": "<path>", "args": ["mcp"], "tools": ["*"]}}}` to `~/.copilot/mcp-config.json` | No preset. |
+| Muse Code (macOS, Linux) | Merge `{"mcp_servers": {"cua-driver": {"enabled": true, "transport": "stdio", "command": "<path>", "args": ["mcp"]}}}` into `$XDG_CONFIG_HOME/muse/settings.json`, or `~/.config/muse/settings.json` | No preset. Start a new Muse session; MCP servers load at startup. |
| T3 Code | Register Cua Driver in the harness that T3 Code launches | |
Find `<path>` with `command -v cua-driver`. The full roster is in the
diff --git a/docs/content/docs/cua-driver/guides/operate.mdx b/docs/content/docs/cua-driver/guides/operate.mdx
index 469570b8a9..d6f4f72925 100644
--- a/docs/content/docs/cua-driver/guides/operate.mdx
+++ b/docs/content/docs/cua-driver/guides/operate.mdx
@@ -179,7 +179,7 @@ cua-driver update --apply
`check-update` only checks (`--json` for scripts, `--no-cache` to skip the
1-hour cache); `update --apply` runs the canonical installer. Then restart the
-daemon with your usual start command (`open -n -g -a CuaDriver --args serve`,
+daemon with your usual start command (`cua-driver permissions grant`,
`cua-driver autostart kick`, or `cua-driver serve`), keeping any mode flags. The
same check is the `check_for_update` MCP tool.
diff --git a/docs/content/docs/cua-driver/guides/permissions.mdx b/docs/content/docs/cua-driver/guides/permissions.mdx
index eda0118d87..7b9436f927 100644
--- a/docs/content/docs/cua-driver/guides/permissions.mdx
+++ b/docs/content/docs/cua-driver/guides/permissions.mdx
@@ -41,7 +41,8 @@ cua-driver serve --dangerously-bypass-approvals
`--permission-mode unrestricted` alone fails closed. Add the two manifest flags
to `standard` or `unrestricted` to narrow them too. On macOS, pass the flags
-after `serve` in `open -n -g -a CuaDriver --args serve …` and use an absolute
+after `serve` when you start the installed app by its exact path
+(`open -n -g /Applications/CuaDriver.app --args serve …`), and use an absolute
manifest path.
What `standard` allows:
diff --git a/docs/content/docs/cua-driver/guides/troubleshoot.mdx b/docs/content/docs/cua-driver/guides/troubleshoot.mdx
index 9de1386d2c..6c52d4ee7c 100644
--- a/docs/content/docs/cua-driver/guides/troubleshoot.mdx
+++ b/docs/content/docs/cua-driver/guides/troubleshoot.mdx
@@ -20,8 +20,9 @@ before sharing.
| --- | --- |
| `list_apps` or `list_windows` returns `[]` | The daemon cannot see the desktop. On Windows over SSH, see [Windows over SSH](/cua-driver/guides/vms-and-remote#windows-over-ssh); on Linux, start `serve` inside the desktop session. |
| No screenshot in `get_window_state` on macOS | Screen Recording is missing: without this grant it returns the tree only (no PNG). Accessibility is needed for every tree read and input. |
-| `permissions status` says `unknown` | No app-owned daemon answered. Run `open -n -g -a CuaDriver --args serve`. |
+| `permissions status` says `unknown` | No app-owned daemon answered. Run `cua-driver permissions grant`. |
| Permission granted in System Settings but reported false | Stale grant: [reset it](#reset-stale-macos-permissions). |
+| System Settings names Cua Driver with an old version (for example `CuaDriver-0.34.0`), or `open` starts the wrong copy | Another copy of the app is registered with macOS. See [Extra copies of CuaDriver.app](#extra-copies-of-cuadriverapp). |
| `libXi.so.6: cannot open shared object file` | `sudo apt install libxi6 at-spi2-core`. |
| `doctor` warns AT-SPI is unreachable | `get_window_state` needs the accessibility bus; start the app inside a full desktop session. |
| Action returned success but nothing changed | Check `effect` and follow `escalation`; see [the action ladder](/cua-driver/concepts/how-cua-driver-works#the-action-ladder). |
@@ -30,6 +31,24 @@ before sharing.
| `invalid_arguments` (`unknown argument element_index`) | Action tools take `element_token` only; read it from the latest `get_window_state` row. |
| `desktop_scope_disabled` | A legacy window-less call: pass a window target, or `target: {kind: "desktop", display_id: "primary"}`. |
+## Extra copies of CuaDriver.app
+
+macOS can hold several copies of the app (an old release in Downloads, the Trash
+or a benchmark folder) and picks one of them when something asks for
+`com.trycua.driver`. That copy can start instead of the installed one and label
+the permission rows with its own name. `doctor` lists the extra copies and any
+permission rows tied to a different path or version:
+
+```bash test="cli-shape" id="cua-driver-doctor-copies"
+cua-driver doctor
+cua-driver doctor --fix
+```
+
+`doctor --fix` makes macOS forget the extra copies. It deletes no files, so
+remove the old copies yourself if you no longer need them. The installer does
+the same step after every install. A stale permission row has to be removed in
+System Settings: select the extra Cua Driver entry and click the minus button.
+
## Reset stale macOS permissions
Use this when CuaDriver is enabled in **System Settings → Privacy & Security**
diff --git a/docs/content/docs/cua-driver/guides/vms-and-remote.mdx b/docs/content/docs/cua-driver/guides/vms-and-remote.mdx
index 41c93e1263..93aa4c18cd 100644
--- a/docs/content/docs/cua-driver/guides/vms-and-remote.mdx
+++ b/docs/content/docs/cua-driver/guides/vms-and-remote.mdx
@@ -47,7 +47,7 @@ commands; they must finish without prompts. Then confirm the daemon's grants:
Expect `accessibility: true`, `screen_recording: true`, and
`source.attribution: "driver-daemon"`. `unknown` means no app-owned daemon
-answered: start it with `open -n -g -a CuaDriver --args serve`.
+answered: run `cua-driver permissions grant`, which starts it.
Run an agent inside the VM with the usual
[`mcp-config`](/cua-driver/guides/connect-your-agent), or from the host over
diff --git a/docs/content/docs/cua-driver/quickstart.mdx b/docs/content/docs/cua-driver/quickstart.mdx
index 3c9c3cc699..796a5de625 100644
--- a/docs/content/docs/cua-driver/quickstart.mdx
+++ b/docs/content/docs/cua-driver/quickstart.mdx
@@ -39,12 +39,11 @@ platform.
```bash test="cli-shape" id="cua-driver-permissions-grant"
/bin/bash -c "$(curl -fsSL https://cua.ai/driver/install.sh)"
-open -n -g -a CuaDriver --args serve
cua-driver permissions grant
```
-Starting through the app bundle makes macOS attribute the prompts to
-CuaDriver, so the grant sticks to the driver.
+`permissions grant` starts the installed app by its exact path, so macOS
+attributes the prompts to that copy of CuaDriver and the grant sticks to the driver.
macOS asks once for each permission. Neither prompt grants anything by
itself: both offer **Open System Settings**, not **Allow**.
@@ -64,7 +63,7 @@ off. Switching it on is what grants access.
Switch on both **Accessibility** and **Screen & System Audio Recording**. If you choose
**Deny**, the driver cannot see or drive your desktop. macOS may offer to quit and reopen
CuaDriver when you flip a toggle. Accept: the driver only picks up a changed grant after a full
- relaunch. If the daemon does not come back, run `open -n -g -a CuaDriver --args serve`.
+ relaunch. If the daemon does not come back, run `cua-driver permissions grant` again.
</Callout>
macOS does not always show both prompts in one pass. Check what landed:
diff --git a/docs/content/docs/cua-driver/reference/cli/serve-and-configure.mdx b/docs/content/docs/cua-driver/reference/cli/serve-and-configure.mdx
index 7cbafdc611..bac98cec6b 100644
--- a/docs/content/docs/cua-driver/reference/cli/serve-and-configure.mdx
+++ b/docs/content/docs/cua-driver/reference/cli/serve-and-configure.mdx
@@ -535,7 +535,7 @@ cua-driver permissions grant
Run platform-aware diagnostic probes.
-Exit code is non-zero when any probe is an error.
+Exit code is non-zero when any probe is an error. On macOS it warns about other copies of CuaDriver.app that macOS can launch instead of the installed one, and about permission rows tied to a different path or version.
```text output
cua-driver doctor [OPTIONS]
@@ -544,6 +544,7 @@ cua-driver doctor [OPTIONS]
| Flag | Type | Default | Description |
| --- | --- | --- | --- |
| <span id="cua-driver-doctor--json"></span>`--json` | boolean | `false` | Emit the probe report as JSON. |
+| <span id="cua-driver-doctor--fix"></span>`--fix` | boolean | `false` | macOS: make LaunchServices forget every other copy of CuaDriver.app. No files are deleted. |
**Examples**
@@ -553,6 +554,9 @@ cua-driver doctor
# Emit the probe report as JSON
cua-driver doctor --json
+
+# macOS: make macOS forget extra copies of the app (deletes no files)
+cua-driver doctor --fix
```
## `cua-driver diagnose`
diff --git a/libs/cua-driver/README.md b/libs/cua-driver/README.md
index 0c213beadb..9d267f50d7 100644
--- a/libs/cua-driver/README.md
+++ b/libs/cua-driver/README.md
@@ -217,7 +217,7 @@ Use MCP for this Claude Code vision/computer-use-style path. CLI screenshots sti
macOS attributes Accessibility and Screen Recording grants to a responsible app identity, not simply to an executable path. Use one of these supported launch modes:
-- **Standalone:** install `CuaDriver.app`, grant permissions to it, and start its daemon with `open -n -g -a CuaDriver --args serve`. The installed `cua-driver mcp` CLI may proxy through this daemon automatically.
+- **Standalone:** install `CuaDriver.app`, grant permissions to it, and start its daemon with `cua-driver permissions grant`. The installed `cua-driver mcp` CLI may proxy through this daemon automatically.
- **Explicit direct MCP:** `cua-driver mcp --direct` makes the MCP process own
its runtime. On macOS this deliberately uses the spawning host's TCC
attribution and does not provide the AppKit cursor overlay without a
diff --git a/libs/cua-driver/rust/Skills/cua-driver/EMBEDDING.md b/libs/cua-driver/rust/Skills/cua-driver/EMBEDDING.md
index f2aac08389..8ab682382f 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/EMBEDDING.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/EMBEDDING.md
@@ -313,7 +313,7 @@ and about 980 ms at `2`. All ten read-backs (five per value) matched exactly.
| --------------------------------------------- | ----------------------------- | -------------------------------------- |
| Responsibility disclaim re-exec | ON (owns its TCC identity) | OFF (stays in the host's chain) |
| Tool execution process | `serve` daemon | host-spawned `serve --embedded` daemon |
-| Daemon auto-relaunch via `open -a CuaDriver` | Yes, when installed | Never (would leave the host's chain) |
+| Daemon auto-relaunch of the installed app | Yes, when installed | Never (would leave the host's chain) |
| TCC identity | `com.trycua.driver` | the host app |
| Permission prompts / startup gate | May prompt once | **Never prompts** |
| Settings → Privacy & Security entries | CuaDriver | your app only |
@@ -334,7 +334,7 @@ would treat it as its own responsible process: your user would get a _second_ pr
attributed to the driver binary, a second Settings entry, and capture/AX
would fail until that second grant. That is the exact experience embedding exists
to eliminate. Embedded mode short-circuits the disclaim re-exec
-(`responsibility.rs`) and the `open -a CuaDriver` daemon relaunch. MCP is
+(`responsibility.rs`) and the installed-app daemon relaunch. MCP is
always a proxy, so the embedded daemon remains the single process that checks
TCC and executes tools.
diff --git a/libs/cua-driver/rust/Skills/cua-driver/MACOS.md b/libs/cua-driver/rust/Skills/cua-driver/MACOS.md
index e75ca04485..e9794edf4d 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/MACOS.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/MACOS.md
@@ -238,10 +238,11 @@ editor state.
1. `cua-driver` is on `$PATH` (`which cua-driver`). If not, point the
user at `scripts/install-local.sh` and stop.
-2. 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
+2. Start the daemon with `cua-driver permissions grant` (the
+ recommended form: it launches the installed CuaDriver.app by its
+ exact path through LaunchServices, so TCC attributes the process to
+ that app). `cua-driver serve &` also works;
+ the CLI auto-relaunches the installed app by path when it
detects a wrong-TCC context (any IDE-spawned shell: Claude Code,
Cursor, VS Code, Conductor). Verify with `cua-driver status`.
3. Run `cua-driver permissions status --json`. This
@@ -293,7 +294,7 @@ Verify with the daemon running:
```bash
cua-driver --version
-open -n -g -a CuaDriver --args serve
+cua-driver permissions grant
cua-driver status
cua-driver doctor
cua-driver permissions status --json # read-only, never prompts
@@ -382,7 +383,7 @@ Limits:
consent, can still appear.
After the MDM installs the profile, restart the daemon (`cua-driver stop`, then
-`open -n -g -a CuaDriver --args serve`) and run
+`cua-driver permissions grant`) and run
`cua-driver permissions status --json`. Expect `accessibility: true`.
#### (b) Operator-authorized hosts: approve through the host's screen sharing
@@ -515,7 +516,7 @@ display over SSH for this first run.
logged: `cua_vnc.py click X Y "CuaDriver: Accessibility"`.
4. Take another screenshot and confirm that the dialog is gone or the switch is on.
5. If macOS offers **Quit & Reopen** for CuaDriver, accept it, then restart the
- daemon (`open -n -g -a CuaDriver --args serve`).
+ daemon (`cua-driver permissions grant`).
6. If macOS asks for an administrator password or Touch ID, that credential
belongs to the owner: stop and ask them to enter it. Only when they gave you
a disposable VM's password for this task, put it in an environment variable
@@ -529,7 +530,7 @@ lines of the approval log: which prompts you approved, when, and on which host.
Send these steps in plain words:
-1. Run `open -n -g -a CuaDriver --args serve`, then `cua-driver permissions grant`.
+1. Run `cua-driver permissions grant`.
2. In the **CuaDriver Permissions** window, click **Open System Settings**.
3. Under **Privacy & Security**, switch **CuaDriver** on under **Accessibility**
and under **Screen & System Audio Recording**. Add
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rs
index f01eda3527..64d94f5dd5 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rs
@@ -288,7 +288,7 @@ impl McpDriver {
if !daemon_socket_is_reachable(&socket) {
eprintln!(
"[testkit] CuaDriver daemon not listening at {socket} — \
- run `./scripts/install-local.sh` and `open -n -g -a CuaDriver --args serve`; skipping"
+ run `./scripts/install-local.sh` and `cua-driver permissions grant`; skipping"
);
return None;
}
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
index 7f27daa1d8..4098709288 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
@@ -136,6 +136,8 @@ pub enum Command {
},
Doctor {
json: bool,
+ /// macOS: make LaunchServices forget every other copy of the app.
+ fix: bool,
},
Diagnose,
/// `cua-driver permissions status|grant [--json]` — report TCC status
@@ -964,7 +966,8 @@ pub fn parse_command() -> Command {
// `--json` switches to machine-readable output for scripting.
// Bare flag — no value, position-independent.
let json = args.iter().any(|a| a == "--json");
- Command::Doctor { json }
+ let fix = args.iter().any(|a| a == "--fix");
+ Command::Doctor { json, fix }
}
Some("diagnose") => Command::Diagnose,
Some("permissions") => {
@@ -1447,9 +1450,14 @@ fn launch_daemon_with_state_and_wait(
// actually differs from the default, so the common case keeps the
// shorter `open` argv (and matches Swift's invocation byte-for-byte).
let app_name = crate::bundle::app_name();
+ let cli_name = crate::bundle::cli_name();
let app_path = crate::bundle::app_bundle_path();
let pass_socket = socket_path != crate::serve::default_socket_path();
- let open_args = daemon_launch_arguments(app_name, socket_path, state, experimental_history);
+ // Launch the resolved bundle by path rather than `-a <name>`: when more
+ // than one copy is registered (for example `/Applications` and
+ // `~/Applications`), LaunchServices may otherwise pick a different copy
+ // than the one this CLI belongs to, with different TCC grants.
+ let open_args = daemon_launch_arguments(&app_path, socket_path, state, experimental_history);
// Thread the Claude-Code compat flag through to the daemon. Without this
// the proxy-spawned daemon always called build_macos_registry() (compat
// hardcoded false), so `cua-driver mcp --claude-code-computer-use-compat`
@@ -1482,14 +1490,14 @@ fn launch_daemon_with_state_and_wait(
return Err(LaunchDaemonError {
kind: LaunchDaemonErrorKind::Failed,
message: format!(
- "`open -n -g -a {app_name} --args serve{}` exited {:?}. \
- Check that `{app_path}` is installed.",
+ "launching `{app_path}` exited {:?}{}. Check that {app_name} is installed \
+ at that path, then run `{cli_name} permissions grant`.",
+ status.code(),
if pass_socket {
- format!(" --socket {socket_path}")
+ format!(" (socket {socket_path})")
} else {
String::new()
},
- status.code()
),
});
}
@@ -1745,7 +1753,7 @@ fn restart_managed_daemon_if_present(_executable: &std::path::Path) -> bool {
#[cfg(target_os = "macos")]
fn daemon_launch_arguments(
- app_name: &str,
+ app: &str,
socket_path: &str,
state: &crate::history_runtime::DaemonLaunchState,
experimental_history: bool,
@@ -1753,8 +1761,7 @@ fn daemon_launch_arguments(
let mut args = vec![
"-n".to_owned(),
"-g".to_owned(),
- "-a".to_owned(),
- app_name.to_owned(),
+ app.to_owned(),
"--args".to_owned(),
"serve".to_owned(),
];
@@ -1865,14 +1872,9 @@ where
#[cfg(target_os = "macos")]
{
let app_name = crate::bundle::app_name();
- let socket_suffix = if socket_path != crate::serve::default_socket_path() {
- format!(" --socket {socket_path}")
- } else {
- String::new()
- };
eprintln!(
"{}: mcp launched without {app_name}.app's TCC grants; \
- auto-launching the daemon via `open -n -g -a {app_name} --args serve{socket_suffix}` \
+ auto-launching the installed {app_name}.app daemon \
and proxying MCP requests through it.",
crate::bundle::cli_name()
);
@@ -2137,7 +2139,10 @@ pub fn build_manifest() -> serde_json::Value {
] },
{ "name": "doctor",
"description": "Self-diagnose probes for runtime prerequisites (permissions, accessibility, capture, etc.).",
- "args": [ { "name": "--json", "type": "flag", "description": "Machine-readable doctor report." } ] },
+ "args": [
+ { "name": "--json", "type": "flag", "description": "Machine-readable doctor report." },
+ { "name": "--fix", "type": "flag", "description": "macOS: make LaunchServices forget every other copy of CuaDriver.app (no files are deleted)." }
+ ] },
{ "name": "diagnose",
"description": "Emit a developer-focused diagnostic dump suitable for bug reports.",
"args": [] },
@@ -3548,8 +3553,8 @@ fn run_permissions_status(json: bool) {
format!(
"No {app_name} daemon is running under the driver's own identity ({bundle_id}), \
so its real TCC status can't be read from this process. \
- Run `{cli_name} permissions grant` to grant + verify, or start the daemon \
- (`open -n -g -a {app_name} --args serve`) and re-run this command."
+ Run `{cli_name} permissions grant` to grant + verify and start the daemon, \
+ then re-run this command."
)
};
if json {
@@ -4647,10 +4652,10 @@ fn cli_docs_literal() -> serde_json::Value {
{
"name": "doctor",
"abstract": "Run platform-aware diagnostic probes.",
- "discussion": "Exit code is non-zero when any probe is an error.",
+ "discussion": "Exit code is non-zero when any probe is an error. On macOS it warns about other copies of CuaDriver.app that macOS can launch instead of the installed one, and about permission rows tied to a different path or version.",
"arguments": no_args,
"options": no_options,
- "flags": [{"name":"json","short_name":null,"help":"Emit the probe report as JSON.","default_value":false}],
+ "flags": [{"name":"json","short_name":null,"help":"Emit the probe report as JSON.","default_value":false},{"name":"fix","short_name":null,"help":"macOS: make LaunchServices forget every other copy of CuaDriver.app. No files are deleted.","default_value":false}],
"subcommands": no_subcommands
},
{
@@ -4853,6 +4858,7 @@ const CLI_EXAMPLES: &[(&str, &[(&str, &str)])] = &[
("doctor", &[
("cua-driver doctor", "Run the diagnostic probes"),
("cua-driver doctor --json", "Emit the probe report as JSON"),
+ ("cua-driver doctor --fix", "macOS: make macOS forget extra copies of the app (deletes no files)"),
]),
("diagnose", &[("cua-driver diagnose", "Print an install and permission report to paste into an issue")]),
("autostart", &[("cua-driver autostart status", "Check the autostart entry")]),
@@ -5415,11 +5421,13 @@ pub fn run_config_cmd(
///
/// See [`crate::doctor`] for the probe catalog. Output is plain text by
/// default; `--json` switches to a machine-readable shape for scripting.
+/// `--fix` (macOS) also makes LaunchServices forget every other copy of the
+/// app; it never deletes a file.
/// Exit code is `0` when every probe is `[ok]` or `[warn]`, non-zero when
/// at least one `[err]` probe failed (e.g. the binary cannot resolve its
/// own install dir).
-pub fn run_doctor_cmd(json: bool) {
- let report = crate::doctor::run();
+pub fn run_doctor_cmd(json: bool, fix: bool) {
+ let report = crate::doctor::run(fix);
if json {
let val = report.to_json();
@@ -5773,7 +5781,12 @@ mod tests {
grants,
};
#[cfg(target_os = "macos")]
- let launch = daemon_launch_arguments("CuaDriver", "/tmp/history-test.sock", &state, true);
+ let launch = daemon_launch_arguments(
+ "/Applications/CuaDriver.app",
+ "/tmp/history-test.sock",
+ &state,
+ true,
+ );
#[cfg(not(target_os = "macos"))]
let launch = daemon_process_arguments("history-test.sock", &state, true);
assert!(launch
@@ -5798,6 +5811,27 @@ mod tests {
.any(|pair| pair == ["--socket", "/tmp/history-test.sock"]));
}
+ /// The daemon must be launched from the exact installed bundle path. `open -a
+ /// CuaDriver` lets LaunchServices pick any registered copy named CuaDriver
+ /// (an old version in the Trash or a benchmark folder), which then owns the
+ /// permission prompts and the System Settings entry.
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn daemon_launch_targets_the_exact_bundle_path_not_the_app_name() {
+ let launch = daemon_launch_arguments(
+ "/Applications/CuaDriver.app",
+ &crate::serve::default_socket_path(),
+ &crate::history_runtime::DaemonLaunchState::default(),
+ false,
+ );
+ assert_eq!(
+ launch,
+ ["-n", "-g", "/Applications/CuaDriver.app", "--args", "serve"]
+ );
+ assert!(!launch.contains(&"-a".to_owned()));
+ assert!(!launch.contains(&"CuaDriver".to_owned()));
+ }
+
#[test]
fn history_relaunch_preserves_explicit_unrestricted_approval() {
let state = crate::history_runtime::DaemonLaunchState {
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/doctor.rs b/libs/cua-driver/rust/crates/cua-driver/src/doctor.rs
index df3d6fbb87..092168d75f 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/doctor.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/doctor.rs
@@ -628,13 +628,65 @@ fn append_platform_probes(report: &mut Report) {
// ── Public entry point ────────────────────────────────────────────────────
-/// Run every probe and return the aggregated report.
-pub fn run() -> Report {
- assemble(
+/// Run every probe and return the aggregated report. `fix` also repairs what
+/// can be repaired safely: on macOS it makes LaunchServices forget every other
+/// copy of the app (no files are deleted).
+pub fn run(fix: bool) -> Report {
+ #[cfg_attr(not(target_os = "macos"), allow(unused_mut))]
+ let mut report = assemble(
home_dir().as_deref(),
&crate::telemetry::status(),
append_platform_probes,
- )
+ );
+ #[cfg(target_os = "macos")]
+ append_install_hygiene_probes(&mut report, fix);
+ #[cfg(not(target_os = "macos"))]
+ let _ = fix;
+ report
+}
+
+/// macOS: other copies of the app that macOS can launch instead of the
+/// installed one, and permission rows tied to another path or version.
+#[cfg(target_os = "macos")]
+fn append_install_hygiene_probes(report: &mut Report, fix: bool) {
+ use crate::duplicate_copies as copies;
+
+ let active = PathBuf::from(crate::bundle::app_bundle_path());
+ let bundle_id = crate::bundle::bundle_id();
+ let (registered, indexed_only): (Vec<_>, Vec<_>) =
+ copies::discover(&active, bundle_id, &copies::run_program)
+ .into_iter()
+ .partition(|copy| copy.registered);
+ let fixed = if fix && !registered.is_empty() {
+ let outcomes = copies::unregister(&registered, &copies::run_program);
+ // What LaunchServices still has registered after the fix.
+ let remaining: Vec<_> = copies::discover(&active, bundle_id, &copies::run_program)
+ .into_iter()
+ .filter(|copy| copy.registered)
+ .collect();
+ Some((outcomes, remaining))
+ } else {
+ None
+ };
+ report.push(copies::duplicate_probe(
+ &active,
+ crate::bundle::app_name(),
+ &registered,
+ &indexed_only,
+ fixed
+ .as_ref()
+ .map(|(outcomes, remaining)| (outcomes.as_slice(), remaining.as_slice())),
+ ));
+
+ let executable = active
+ .join("Contents/MacOS")
+ .join(crate::bundle::cli_name());
+ let rows = home_dir()
+ .ok_or_else(|| "HOME is not set".to_owned())
+ .and_then(|home| copies::read_tcc_rows(&home, &copies::run_program));
+ report.push(copies::permission_row_probe(&executable, rows, |bundle| {
+ copies::bundle_version_of(bundle, &copies::run_program)
+ }));
}
/// The cross-platform probes over explicit host inputs, then `platform`'s.
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/duplicate_copies.rs b/libs/cua-driver/rust/crates/cua-driver/src/duplicate_copies.rs
new file mode 100644
index 0000000000..a33f6eb6b0
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver/src/duplicate_copies.rs
@@ -0,0 +1,856 @@
+//! Other copies of Cua Driver.app that macOS knows about.
+//!
+//! A Mac can hold several copies of `CuaDriver.app`: an old release in
+//! `~/Downloads`, one in the Trash, a benchmark folder. macOS resolves a bundle
+//! id, an `open -a CuaDriver` and a System Settings permission row to *one* of
+//! the registered copies, not necessarily the installed one. That is how a
+//! 0.34.0 copy from the Trash got launched and labelled the permission row
+//! "CuaDriver-0.34.0".
+//!
+//! This module finds those copies (LaunchServices' `lsregister -dump` plus
+//! Spotlight's `mdfind`), and `cua-driver doctor --fix` makes LaunchServices
+//! forget them with `lsregister -u`. It never deletes a file. The installer does
+//! the same in shell (`unregister_other_cua_driver_copies` in
+//! `scripts/_install-common.sh`); keep the two algorithms in step.
+//!
+//! The pure parts take injected inputs so unit tests never touch the real
+//! LaunchServices database.
+
+#![cfg_attr(not(target_os = "macos"), allow(dead_code))]
+
+use crate::doctor::Probe;
+use std::path::{Path, PathBuf};
+use std::time::Duration;
+
+pub const LSREGISTER: &str = "/System/Library/Frameworks/CoreServices.framework/Versions/A/\
+Frameworks/LaunchServices.framework/Versions/A/Support/lsregister";
+const MDFIND: &str = "/usr/bin/mdfind";
+const SQLITE3: &str = "/usr/bin/sqlite3";
+const PLUTIL: &str = "/usr/bin/plutil";
+
+/// How long the (slow) LaunchServices dump may take before we give up on it.
+const DUMP_TIMEOUT: Duration = Duration::from_secs(180);
+const QUICK_TIMEOUT: Duration = Duration::from_secs(20);
+
+/// Run `program args…` and return its stdout when it exits 0 within `timeout`.
+pub type Run<'a> = &'a dyn Fn(&str, &[&str], Duration) -> Option<String>;
+
+/// One app bundle that is not the installed one.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct AppCopy {
+ pub path: PathBuf,
+ pub version: Option<String>,
+ /// False when the registration outlived the files (a deleted copy).
+ pub exists: bool,
+ /// LaunchServices has this copy registered, so macOS can launch it. A copy
+ /// that only Spotlight lists is on disk but is not launched by `open -a`.
+ pub registered: bool,
+}
+
+impl AppCopy {
+ pub fn describe(&self) -> String {
+ let mut text = self.path.display().to_string();
+ match (&self.version, self.exists) {
+ (Some(version), true) => text.push_str(&format!(" (version {version})")),
+ (None, true) => {}
+ (Some(version), false) => text.push_str(&format!(" (version {version}, files gone)")),
+ (None, false) => text.push_str(" (files gone)"),
+ }
+ text
+ }
+}
+
+/// The result of asking macOS to forget one copy.
+#[derive(Debug, Clone)]
+pub struct FixOutcome {
+ pub copy: AppCopy,
+ pub result: Result<(), String>,
+}
+
+/// Paths of every bundle in an `lsregister -dump` whose `identifier:` is exactly
+/// `bundle_id`. The dump is a series of blocks split by a line of dashes; each
+/// block has a `path:` line (with a trailing `(0x…)` record id) and an
+/// `identifier:` line.
+pub fn parse_lsregister_dump(dump: &str, bundle_id: &str) -> Vec<PathBuf> {
+ let mut found: Vec<PathBuf> = Vec::new();
+ let mut path: Option<String> = None;
+ let mut matches = false;
+ let mut flush = |path: &mut Option<String>, matches: &mut bool| {
+ if let Some(path) = path.take() {
+ if *matches {
+ found.push(PathBuf::from(path));
+ }
+ }
+ *matches = false;
+ };
+ for line in dump.lines() {
+ if line.starts_with("----------") {
+ flush(&mut path, &mut matches);
+ } else if let Some(rest) = line.strip_prefix("path:") {
+ if rest.starts_with(char::is_whitespace) {
+ path = Some(strip_record_id(rest.trim()));
+ }
+ } else if let Some(rest) = line.strip_prefix("identifier:") {
+ if rest.starts_with(char::is_whitespace) {
+ matches = rest.trim() == bundle_id;
+ }
+ }
+ }
+ flush(&mut path, &mut matches);
+ found
+}
+
+/// `/Applications/CuaDriver.app (0x10268)` -> `/Applications/CuaDriver.app`.
+fn strip_record_id(text: &str) -> String {
+ match text.rfind(" (0x") {
+ Some(index) if text.ends_with(')') => text[..index].to_owned(),
+ _ => text.to_owned(),
+ }
+}
+
+/// The copies that are not `active`, from every `(path, registered)` pair macOS
+/// reported. A path reported both ways counts as registered.
+pub fn other_copies(
+ active: &Path,
+ reported: impl IntoIterator<Item = (PathBuf, bool)>,
+ version_of: impl Fn(&Path) -> Option<String>,
+) -> Vec<AppCopy> {
+ let canonical = |path: &Path| std::fs::canonicalize(path).unwrap_or_else(|_| path.to_owned());
+ let active_real = canonical(active);
+ let mut copies: Vec<AppCopy> = Vec::new();
+ for (path, registered) in reported {
+ if path == active || canonical(&path) == active_real {
+ continue;
+ }
+ if let Some(seen) = copies.iter_mut().find(|copy| copy.path == path) {
+ seen.registered |= registered;
+ continue;
+ }
+ let exists = path.is_dir();
+ let version = if exists { version_of(&path) } else { None };
+ copies.push(AppCopy {
+ path,
+ version,
+ exists,
+ registered,
+ });
+ }
+ copies.sort_by(|a, b| a.path.cmp(&b.path));
+ copies
+}
+
+/// Every other bundle with `bundle_id` that LaunchServices (`lsregister -dump`)
+/// or Spotlight (`mdfind`) knows. If the LaunchServices dump is unavailable the
+/// Spotlight hits are treated as registered, so the doctor errs on the side of
+/// warning.
+pub fn discover(active: &Path, bundle_id: &str, run: Run) -> Vec<AppCopy> {
+ let mut reported: Vec<(PathBuf, bool)> = Vec::new();
+ let dump = run(LSREGISTER, &["-dump"], DUMP_TIMEOUT);
+ let dump_available = dump.is_some();
+ if let Some(dump) = dump {
+ reported.extend(
+ parse_lsregister_dump(&dump, bundle_id)
+ .into_iter()
+ .map(|path| (path, true)),
+ );
+ }
+ let query = format!("kMDItemCFBundleIdentifier == '{bundle_id}'");
+ if let Some(found) = run(MDFIND, &[&query], QUICK_TIMEOUT) {
+ reported.extend(
+ found
+ .lines()
+ .map(str::trim)
+ .filter(|line| !line.is_empty())
+ .map(|line| (PathBuf::from(line), !dump_available)),
+ );
+ }
+ other_copies(active, reported, |bundle| bundle_version_of(bundle, run))
+}
+
+pub fn bundle_version_of(bundle: &Path, run: Run) -> Option<String> {
+ let plist = bundle.join("Contents/Info.plist");
+ let plist = plist.to_str()?;
+ let out = run(
+ PLUTIL,
+ &[
+ "-extract",
+ "CFBundleShortVersionString",
+ "raw",
+ "-o",
+ "-",
+ plist,
+ ],
+ QUICK_TIMEOUT,
+ )?;
+ let version = out.trim();
+ (!version.is_empty()).then(|| version.to_owned())
+}
+
+/// Make LaunchServices forget every copy. Files are never touched.
+pub fn unregister(copies: &[AppCopy], run: Run) -> Vec<FixOutcome> {
+ copies
+ .iter()
+ .map(|copy| {
+ let path = copy.path.to_string_lossy().into_owned();
+ let result = match run(LSREGISTER, &["-u", &path], QUICK_TIMEOUT) {
+ Some(_) => Ok(()),
+ None => Err(format!("`lsregister -u {path}` failed")),
+ };
+ FixOutcome {
+ copy: copy.clone(),
+ result,
+ }
+ })
+ .collect()
+}
+
+fn plural(count: usize) -> &'static str {
+ if count == 1 {
+ "copy"
+ } else {
+ "copies"
+ }
+}
+
+/// The doctor probe for duplicate copies.
+///
+/// `fixed` is `None` for a plain `doctor` run and the outcomes of `--fix`
+/// otherwise; `remaining` is what macOS still reports after the fix.
+pub fn duplicate_probe(
+ active: &Path,
+ app_name: &str,
+ copies: &[AppCopy],
+ indexed_only: &[AppCopy],
+ fixed: Option<(&[FixOutcome], &[AppCopy])>,
+) -> Probe {
+ let label = "duplicate copies";
+ if copies.is_empty() {
+ let probe = Probe::ok(
+ label,
+ format!("only {} is registered with macOS", active.display()),
+ );
+ if indexed_only.is_empty() {
+ return probe;
+ }
+ // On disk and listed by Spotlight, but not registered: `open -a` does not
+ // launch them. Say so without nagging.
+ return probe.with_detail(format!(
+ "Spotlight also lists {} {} on disk that macOS does not launch:\n{}\n\
+ Delete {} when you no longer need {}.",
+ indexed_only.len(),
+ plural(indexed_only.len()),
+ indexed_only
+ .iter()
+ .map(|copy| format!("- {}", copy.describe()))
+ .collect::<Vec<_>>()
+ .join("\n"),
+ if indexed_only.len() == 1 {
+ "it"
+ } else {
+ "them"
+ },
+ if indexed_only.len() == 1 {
+ "it"
+ } else {
+ "them"
+ },
+ ));
+ }
+ let list = |copies: &mut dyn Iterator<Item = &AppCopy>| {
+ copies
+ .map(|copy| format!("- {}", copy.describe()))
+ .collect::<Vec<_>>()
+ .join("\n")
+ };
+ let Some((outcomes, remaining)) = fixed else {
+ return Probe::warn(
+ label,
+ format!(
+ "{} other {} of {app_name} known to macOS; it can open or label permissions \
+ with one of them instead of {}",
+ copies.len(),
+ plural(copies.len()),
+ active.display()
+ ),
+ )
+ .with_detail(format!(
+ "{}\nRun `cua-driver doctor --fix` to make macOS forget them. No files are deleted.",
+ list(&mut copies.iter())
+ ));
+ };
+
+ let failed: Vec<&FixOutcome> = outcomes.iter().filter(|o| o.result.is_err()).collect();
+ let done = outcomes.len() - failed.len();
+ let mut detail = outcomes
+ .iter()
+ .map(|outcome| match &outcome.result {
+ Ok(()) => format!("unregistered {}", outcome.copy.describe()),
+ Err(error) => format!("could not unregister {}: {error}", outcome.copy.describe()),
+ })
+ .collect::<Vec<_>>()
+ .join("\n");
+ detail.push_str(
+ "\nNo files were deleted; remove the old copies yourself if you do not need them.",
+ );
+ if !remaining.is_empty() {
+ detail.push_str(&format!(
+ "\nmacOS still reports {} {} (it re-registers apps it can see in indexed folders). \
+ Move or delete:\n{}",
+ remaining.len(),
+ plural(remaining.len()),
+ list(&mut remaining.iter())
+ ));
+ return Probe::warn(
+ label,
+ format!(
+ "unregistered {done} of {} other {}, but macOS still knows {}",
+ outcomes.len(),
+ plural(outcomes.len()),
+ remaining.len()
+ ),
+ )
+ .with_detail(detail);
+ }
+ if failed.is_empty() {
+ Probe::ok(
+ label,
+ format!(
+ "unregistered {done} other {}; macOS will now only use {}",
+ plural(done),
+ active.display()
+ ),
+ )
+ .with_detail(detail)
+ } else {
+ Probe::warn(
+ label,
+ format!(
+ "could not unregister {} of {} copies",
+ failed.len(),
+ outcomes.len()
+ ),
+ )
+ .with_detail(detail)
+ }
+}
+
+// ── Permission rows ───────────────────────────────────────────────────────
+
+/// One row of the TCC `access` table that mentions Cua Driver.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct TccRow {
+ pub service: String,
+ pub client: String,
+ /// 0 = bundle identifier, 1 = absolute path of an executable.
+ pub client_type: i64,
+}
+
+/// Cua Driver rows in the current user's permission database. `Err` carries the
+/// plain reason, normally that macOS only lets apps with Full Disk Access read it.
+pub fn read_tcc_rows(home: &Path, run: Run) -> Result<Vec<TccRow>, String> {
+ let db = home.join("Library/Application Support/com.apple.TCC/TCC.db");
+ let db_text = db.to_string_lossy().into_owned();
+ let sql = "SELECT service, client, client_type FROM access \
+ WHERE client = 'com.trycua.driver' OR client LIKE '%cua-driver%' \
+ OR client LIKE '%CuaDriver%';";
+ let out =
+ run(SQLITE3, &["-separator", "|", &db_text, sql], QUICK_TIMEOUT).ok_or_else(|| {
+ "macOS only lets apps with Full Disk Access read the permission database".to_owned()
+ })?;
+ Ok(parse_tcc_rows(&out))
+}
+
+pub fn parse_tcc_rows(output: &str) -> Vec<TccRow> {
+ output
+ .lines()
+ .filter_map(|line| {
+ let mut parts = line.splitn(3, '|');
+ let service = parts.next()?.to_owned();
+ let client = parts.next()?.to_owned();
+ let client_type = parts.next()?.trim().parse().ok()?;
+ Some(TccRow {
+ service,
+ client,
+ client_type,
+ })
+ })
+ .collect()
+}
+
+fn service_name(service: &str) -> &str {
+ match service {
+ "kTCCServiceAccessibility" => "Accessibility",
+ "kTCCServiceScreenCapture" => "Screen Recording",
+ other => other,
+ }
+}
+
+const REMOVE_ROWS_HELP: &str = "To remove one stale row: System Settings > Privacy & Security > \
+Accessibility (and Screen & System Audio Recording), select the extra Cua Driver entry and click \
+the minus button.\nTo clear every Cua Driver row and start over: `tccutil reset Accessibility \
+com.trycua.driver`, `tccutil reset ScreenCapture com.trycua.driver`, then \
+`cua-driver permissions grant`.";
+
+/// The doctor probe for permission rows tied to a different path or version.
+///
+/// Rows keyed by bundle id follow whichever copy macOS resolves; rows keyed by
+/// an absolute path belong to that exact executable. A path row that is not the
+/// installed executable is stale.
+pub fn permission_row_probe(
+ active_executable: &Path,
+ rows: Result<Vec<TccRow>, String>,
+ version_of: impl Fn(&Path) -> Option<String>,
+) -> Probe {
+ let label = "permission rows";
+ let rows = match rows {
+ Ok(rows) => rows,
+ Err(reason) => return Probe::ok(label, format!("not checked: {reason}")),
+ };
+ let canonical = |path: &Path| std::fs::canonicalize(path).unwrap_or_else(|_| path.to_owned());
+ let active_real = canonical(active_executable);
+ let stale: Vec<&TccRow> = rows
+ .iter()
+ .filter(|row| row.client_type == 1)
+ .filter(|row| {
+ let path = Path::new(&row.client);
+ path != active_executable && canonical(path) != active_real
+ })
+ .collect();
+ if stale.is_empty() {
+ return Probe::ok(label, "none tied to another path or version");
+ }
+ let lines: Vec<String> = stale
+ .iter()
+ .map(|row| {
+ let path = Path::new(&row.client);
+ let bundle = row
+ .client
+ .split_once("/Contents/MacOS/")
+ .map(|(bundle, _)| PathBuf::from(bundle));
+ let version = bundle.as_deref().and_then(&version_of);
+ let state = match (version, path.exists()) {
+ (Some(version), true) => format!("version {version}"),
+ (None, true) => "other copy".to_owned(),
+ (Some(version), false) => format!("version {version}, files gone"),
+ (None, false) => "files gone".to_owned(),
+ };
+ format!("- {}: {} ({state})", service_name(&row.service), row.client)
+ })
+ .collect();
+ Probe::warn(
+ label,
+ format!(
+ "{} permission row{} belong{} to a different Cua Driver path or version than {}",
+ stale.len(),
+ if stale.len() == 1 { "" } else { "s" },
+ if stale.len() == 1 { "s" } else { "" },
+ active_executable.display()
+ ),
+ )
+ .with_detail(format!("{}\n{REMOVE_ROWS_HELP}", lines.join("\n")))
+}
+
+// ── Process runner ────────────────────────────────────────────────────────
+
+/// Run a program, returning stdout when it exits 0 within `timeout`.
+pub fn run_program(program: &str, args: &[&str], timeout: Duration) -> Option<String> {
+ use std::io::Read;
+ use std::process::{Command, Stdio};
+ use std::time::Instant;
+
+ let mut child = Command::new(program)
+ .args(args)
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .spawn()
+ .ok()?;
+ let mut stdout = child.stdout.take()?;
+ let reader = std::thread::spawn(move || {
+ let mut bytes = Vec::new();
+ let _ = stdout.read_to_end(&mut bytes);
+ bytes
+ });
+ let deadline = Instant::now() + timeout;
+ let status = loop {
+ match child.try_wait() {
+ Ok(Some(status)) => break Some(status),
+ Ok(None) if Instant::now() < deadline => {
+ std::thread::sleep(Duration::from_millis(50));
+ }
+ _ => {
+ let _ = child.kill();
+ let _ = child.wait();
+ break None;
+ }
+ }
+ };
+ let bytes = reader.join().ok()?;
+ status
+ .filter(|status| status.success())
+ .map(|_| String::from_utf8_lossy(&bytes).into_owned())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::doctor::Status;
+
+ const DUMP: &str = "\
+--------------------------------------------------------------------------------
+bundle id: Cua Driver (0xf0ac)
+path: /Applications/CuaDriver.app (0x10268)
+name: Cua Driver
+identifier: com.trycua.driver
+version: 0.36 ({length = 32, bytes = 0x00})
+infoDictionary: 14 values (144140 (0x2330c))
+ {
+ CFBundleIdentifier = \"com.trycua.driver\";
+ }
+--------------------------------------------------------------------------------
+bundle id: CuaDriver-0.34.0 (0x1)
+path: /Users/me/.Trash/Old Apps/CuaDriver.app (0x2)
+identifier: com.trycua.driver
+--------------------------------------------------------------------------------
+bundle id: Cua Driver Local (0x3)
+path: /Applications/CuaDriverLocal.app (0x4)
+identifier: com.trycua.driver.local
+--------------------------------------------------------------------------------
+bundle id: Other (0x5)
+path: /tmp/bench/CuaDriver.app (0x6)
+identifier: com.trycua.driver
+--------------------------------------------------------------------------------
+";
+
+ #[test]
+ fn dump_parser_returns_every_bundle_with_the_exact_identifier() {
+ assert_eq!(
+ parse_lsregister_dump(DUMP, "com.trycua.driver"),
+ [
+ PathBuf::from("/Applications/CuaDriver.app"),
+ PathBuf::from("/Users/me/.Trash/Old Apps/CuaDriver.app"),
+ PathBuf::from("/tmp/bench/CuaDriver.app"),
+ ],
+ "the local product (com.trycua.driver.local) must not match, \
+ and a path with spaces and its (0x..) record id parse cleanly"
+ );
+ assert_eq!(
+ parse_lsregister_dump(DUMP, "com.trycua.driver.local"),
+ [PathBuf::from("/Applications/CuaDriverLocal.app")]
+ );
+ }
+
+ #[test]
+ fn a_second_bundle_at_another_path_is_found_and_the_installed_one_is_not() {
+ let root = tempfile::tempdir().unwrap();
+ let active = root.path().join("Applications/CuaDriver.app");
+ let old = root.path().join("Downloads/CuaDriver.app");
+ let gone = root.path().join(".Trash/CuaDriver.app");
+ std::fs::create_dir_all(&active).unwrap();
+ std::fs::create_dir_all(&old).unwrap();
+ let alias = root.path().join("alias.app");
+ std::os::unix::fs::symlink(&active, &alias).unwrap();
+
+ let copies = other_copies(
+ &active,
+ [
+ (active.clone(), true),
+ (old.clone(), false),
+ (old.clone(), true),
+ (gone.clone(), true),
+ (alias, true),
+ ],
+ |path| (path == old).then(|| "0.34.0".to_owned()),
+ );
+
+ assert_eq!(
+ copies,
+ [
+ AppCopy {
+ path: gone,
+ version: None,
+ exists: false,
+ registered: true
+ },
+ AppCopy {
+ path: old,
+ version: Some("0.34.0".to_owned()),
+ exists: true,
+ registered: true
+ },
+ ]
+ );
+ }
+
+ #[test]
+ fn discover_merges_launchservices_and_spotlight_and_reads_versions() {
+ let root = tempfile::tempdir().unwrap();
+ let active = root.path().join("Applications/CuaDriver.app");
+ let old = root.path().join("tmp/CuaDriver.app");
+ let indexed = root.path().join("images/CuaDriver.app");
+ for dir in [&active, &old, &indexed] {
+ std::fs::create_dir_all(dir).unwrap();
+ }
+ let dump = format!(
+ "{sep}\npath: {} (0x1)\nidentifier: com.trycua.driver\n\
+ {sep}\npath: {} (0x2)\nidentifier: com.trycua.driver\n",
+ active.display(),
+ old.display(),
+ sep = "-".repeat(40)
+ );
+ let spotlight = format!("{}\n{}\n\n", active.display(), indexed.display());
+ let run = move |program: &str, args: &[&str], _: Duration| -> Option<String> {
+ match (program, args.first().copied()) {
+ (LSREGISTER, Some("-dump")) => Some(dump.clone()),
+ (MDFIND, _) => Some(spotlight.clone()),
+ (PLUTIL, _) => Some("0.36.0\n".to_owned()),
+ _ => None,
+ }
+ };
+
+ let copies = discover(&active, "com.trycua.driver", &run);
+
+ let paths: Vec<_> = copies.iter().map(|c| c.path.clone()).collect();
+ assert_eq!(paths, [indexed.clone(), old.clone()]);
+ assert!(copies
+ .iter()
+ .all(|c| c.version.as_deref() == Some("0.36.0")));
+ // Only LaunchServices' own dump makes a copy launchable; Spotlight alone
+ // just means the files exist.
+ let registered: Vec<_> = copies.iter().map(|c| c.registered).collect();
+ assert_eq!(registered, [false, true]);
+ }
+
+ #[test]
+ fn without_a_launchservices_dump_spotlight_hits_count_as_registered() {
+ let root = tempfile::tempdir().unwrap();
+ let active = root.path().join("Applications/CuaDriver.app");
+ let found = root.path().join("tmp/CuaDriver.app");
+ std::fs::create_dir_all(&found).unwrap();
+ let spotlight = format!("{}\n", found.display());
+ let run = move |program: &str, _: &[&str], _: Duration| -> Option<String> {
+ (program == MDFIND).then(|| spotlight.clone())
+ };
+
+ let copies = discover(&active, "com.trycua.driver", &run);
+
+ assert_eq!(copies.len(), 1);
+ assert!(copies[0].registered, "cannot prove it is unregistered");
+ }
+
+ #[test]
+ fn copies_only_spotlight_lists_do_not_raise_a_warning() {
+ let active = Path::new("/Applications/CuaDriver.app");
+ let indexed = [copy("/Users/me/Downloads/CuaDriver.app", Some("0.34.0"))];
+
+ let probe = duplicate_probe(active, "CuaDriver", &[], &indexed, None);
+
+ assert_eq!(probe.status, Status::Ok);
+ assert!(probe.message.contains("only /Applications/CuaDriver.app"));
+ let detail = probe.detail.unwrap();
+ assert!(detail.contains("Spotlight also lists 1 copy on disk that macOS does not launch"));
+ assert!(detail.contains("Downloads/CuaDriver.app (version 0.34.0)"));
+ }
+
+ #[test]
+ fn unregister_uses_lsregister_u_per_copy_and_reports_failures() {
+ let calls = std::cell::RefCell::new(Vec::<Vec<String>>::new());
+ let run = |program: &str, args: &[&str], _: Duration| -> Option<String> {
+ let mut call = vec![program.to_owned()];
+ call.extend(args.iter().map(|a| (*a).to_owned()));
+ calls.borrow_mut().push(call);
+ (args.last() != Some(&"/bad/CuaDriver.app")).then(String::new)
+ };
+ let copies = [
+ AppCopy {
+ path: "/good/CuaDriver.app".into(),
+ version: None,
+ exists: true,
+ registered: true,
+ },
+ AppCopy {
+ path: "/bad/CuaDriver.app".into(),
+ version: None,
+ exists: true,
+ registered: true,
+ },
+ ];
+
+ let outcomes = unregister(&copies, &run);
+
+ assert!(outcomes[0].result.is_ok());
+ assert!(outcomes[1].result.is_err());
+ assert_eq!(
+ calls.borrow()[0],
+ [LSREGISTER, "-u", "/good/CuaDriver.app"],
+ "only registration is removed; nothing deletes a file"
+ );
+ }
+
+ fn copy(path: &str, version: Option<&str>) -> AppCopy {
+ AppCopy {
+ path: path.into(),
+ version: version.map(str::to_owned),
+ exists: true,
+ registered: true,
+ }
+ }
+
+ #[test]
+ fn doctor_warns_about_duplicate_copies_and_points_at_fix() {
+ let active = Path::new("/Applications/CuaDriver.app");
+ let copies = [
+ copy("/Users/me/.Trash/CuaDriver.app", Some("0.34.0")),
+ copy("/tmp/CuaDriver.app", Some("0.36.0")),
+ ];
+
+ let probe = duplicate_probe(active, "CuaDriver", &copies, &[], None);
+
+ assert_eq!(probe.status, Status::Warn);
+ assert!(probe.message.contains("2 other copies of CuaDriver"));
+ let detail = probe.detail.unwrap();
+ assert!(detail.contains("/Users/me/.Trash/CuaDriver.app (version 0.34.0)"));
+ assert!(detail.contains("cua-driver doctor --fix"));
+ assert!(detail.contains("No files are deleted"));
+ }
+
+ #[test]
+ fn doctor_is_quiet_when_only_the_installed_copy_is_registered() {
+ let probe = duplicate_probe(
+ Path::new("/Applications/CuaDriver.app"),
+ "CuaDriver",
+ &[],
+ &[],
+ None,
+ );
+
+ assert_eq!(probe.status, Status::Ok);
+ assert!(probe.message.contains("only /Applications/CuaDriver.app"));
+ }
+
+ #[test]
+ fn fix_reports_what_it_unregistered_and_what_macos_still_knows() {
+ let active = Path::new("/Applications/CuaDriver.app");
+ let a = copy("/tmp/a/CuaDriver.app", Some("0.34.0"));
+ let b = copy("/tmp/b/CuaDriver.app", None);
+ let outcomes = [
+ FixOutcome {
+ copy: a.clone(),
+ result: Ok(()),
+ },
+ FixOutcome {
+ copy: b.clone(),
+ result: Ok(()),
+ },
+ ];
+
+ let clean = duplicate_probe(
+ active,
+ "CuaDriver",
+ &[a.clone(), b.clone()],
+ &[],
+ Some((&outcomes, &[])),
+ );
+ assert_eq!(clean.status, Status::Ok);
+ assert!(clean.message.contains(
+ "unregistered 2 other copies; macOS will now only use /Applications/CuaDriver.app"
+ ));
+ assert!(clean.detail.unwrap().contains("No files were deleted"));
+
+ let reregistered = duplicate_probe(
+ active,
+ "CuaDriver",
+ &[a.clone(), b.clone()],
+ &[],
+ Some((&outcomes, std::slice::from_ref(&b))),
+ );
+ assert_eq!(reregistered.status, Status::Warn);
+ assert!(reregistered.message.contains("macOS still knows 1"));
+ assert!(reregistered.detail.unwrap().contains("Move or delete"));
+
+ let failed = [FixOutcome {
+ copy: a.clone(),
+ result: Err("`lsregister -u` failed".to_owned()),
+ }];
+ let probe = duplicate_probe(active, "CuaDriver", &[a], &[], Some((&failed, &[])));
+ assert_eq!(probe.status, Status::Warn);
+ assert!(probe.message.contains("could not unregister 1 of 1"));
+ }
+
+ #[test]
+ fn permission_rows_tied_to_another_path_are_flagged_with_removal_steps() {
+ let active = Path::new("/Applications/CuaDriver.app/Contents/MacOS/cua-driver");
+ let rows = Ok(parse_tcc_rows(
+ "kTCCServiceAccessibility|com.trycua.driver|0\n\
+ kTCCServiceAccessibility|/Applications/CuaDriver.app/Contents/MacOS/cua-driver|1\n\
+ kTCCServiceScreenCapture|/Users/me/Downloads/CuaDriver.app/Contents/MacOS/cua-driver|1\n",
+ ));
+
+ let probe = permission_row_probe(active, rows, |bundle| {
+ bundle
+ .ends_with("Downloads/CuaDriver.app")
+ .then(|| "0.34.0".to_owned())
+ });
+
+ assert_eq!(probe.status, Status::Warn);
+ assert!(probe
+ .message
+ .starts_with("1 permission row belongs to a different"));
+ let detail = probe.detail.unwrap();
+ assert!(detail.contains(
+ "- Screen Recording: /Users/me/Downloads/CuaDriver.app/Contents/MacOS/cua-driver \
+ (version 0.34.0, files gone)"
+ ));
+ assert!(detail.contains("click the minus button"));
+ assert!(detail.contains("tccutil reset Accessibility com.trycua.driver"));
+ }
+
+ #[test]
+ fn permission_rows_for_the_installed_app_and_its_bundle_id_are_fine() {
+ let active = Path::new("/Applications/CuaDriver.app/Contents/MacOS/cua-driver");
+ let rows = Ok(parse_tcc_rows(
+ "kTCCServiceAccessibility|com.trycua.driver|0\n\
+ kTCCServiceAccessibility|/Applications/CuaDriver.app/Contents/MacOS/cua-driver|1\n",
+ ));
+
+ let probe = permission_row_probe(active, rows, |_| None);
+
+ assert_eq!(probe.status, Status::Ok);
+ }
+
+ #[test]
+ fn an_unreadable_permission_database_is_reported_as_not_checked() {
+ let probe = permission_row_probe(
+ Path::new("/Applications/CuaDriver.app/Contents/MacOS/cua-driver"),
+ Err("macOS only lets apps with Full Disk Access read the permission database".into()),
+ |_| None,
+ );
+
+ assert_eq!(probe.status, Status::Ok);
+ assert!(probe
+ .message
+ .starts_with("not checked: macOS only lets apps"));
+ }
+
+ #[test]
+ fn run_program_returns_stdout_only_for_a_zero_exit_within_the_timeout() {
+ // `/bin/sh` is the only absolute path every host has, including the
+ // Nix build sandbox, which has no `/bin/echo` or `/usr/bin/false`. Only
+ // shell builtins run here, so a missing tool cannot fake a `None`.
+ let sh = "/bin/sh";
+ let ok = run_program(sh, &["-c", "echo hi"], Duration::from_secs(5));
+ assert_eq!(ok.as_deref(), Some("hi\n"));
+ assert_eq!(
+ run_program(sh, &["-c", "echo hi; exit 1"], Duration::from_secs(5)),
+ None
+ );
+ assert_eq!(
+ run_program(
+ sh,
+ &["-c", "while :; do :; done"],
+ Duration::from_millis(100)
+ ),
+ None
+ );
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/main.rs b/libs/cua-driver/rust/crates/cua-driver/src/main.rs
index 2dc89ef221..a7abdcbc45 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/main.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/main.rs
@@ -24,6 +24,8 @@ mod check_update_tool;
mod cli;
mod doctor;
mod driver_service_http;
+#[cfg(any(target_os = "macos", all(test, unix)))]
+mod duplicate_copies;
mod extension_manager;
mod history_runtime;
mod mcp_envelope;
@@ -675,9 +677,9 @@ fn main() {
// is ungranted. Fresh helper processes poll TCC until the user
// grants or the deadline elapses. If serve ran after the gate,
// the daemon's socket wouldn't appear for minutes on first
- // launch, so `permissions grant` / MCP clients launched via
- // `open -n -g -a CuaDriver --args serve` (the correct-TCC-
- // attribution path) couldn't reach the daemon to even report
+ // launch, so `permissions grant` / MCP clients launching the
+ // installed app bundle by path (the correct-TCC-attribution
+ // path) couldn't reach the daemon to even report
// "pending". Binding the socket first makes the daemon
// reachable within ~1s while the gate works toward the grant.
//
@@ -823,7 +825,7 @@ fn main() {
} => {
cli::run_channel_cmd(&subcommand, value.as_deref(), json);
}
- cli::Command::Doctor { json } => {
+ cli::Command::Doctor { json, fix } => {
// Long-running interactive entry point — kick off the
// background "new version available?" check so the banner
// can land on stderr if the user is on an outdated install.
@@ -831,7 +833,7 @@ fn main() {
if !json {
version_check::maybe_announce_update();
}
- cli::run_doctor_cmd(json);
+ cli::run_doctor_cmd(json, fix);
}
cli::Command::Diagnose => {
cli::run_diagnose_cmd();
@@ -1130,14 +1132,14 @@ fn main() -> anyhow::Result<()> {
cli::run_channel_cmd(&subcommand, value.as_deref(), json);
Ok(())
}
- cli::Command::Doctor { json } => {
+ cli::Command::Doctor { json, fix } => {
// Long-running interactive entry point — kick off the
// background update check so the banner can land on stderr.
// Skip the banner in --json mode so output stays parseable.
if !json {
version_check::maybe_announce_update();
}
- cli::run_doctor_cmd(json);
+ cli::run_doctor_cmd(json, fix);
Ok(())
}
cli::Command::Diagnose => {
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs b/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs
index 810bf385e5..02b4498be7 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs
@@ -203,7 +203,7 @@ pub async fn run_proxy(socket_path: String) -> anyhow::Result<()> {
if !is_daemon_listening(&socket_path) {
anyhow::bail!(
"cua-driver-rs daemon not reachable on {socket_path}. Start it \
- with `open -n -g -a CuaDriver --args serve` and retry."
+ with `cua-driver permissions grant` and retry."
);
}
// A selected service may outlive the CLI package that launched this
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/responsibility.rs b/libs/cua-driver/rust/crates/cua-driver/src/responsibility.rs
index ae0649d824..f430982905 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/responsibility.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/responsibility.rs
@@ -181,7 +181,7 @@ fn unbundled_warning(embedded: bool, inside_bundle: bool) -> Option<&'static str
"warning: running unbundled (outside CuaDriver.app). The daemon is its own responsible \
process, so macOS gives it no valid WindowServer connection: background (no-raise) \
focus steps fail with status 1002 and background actions will be refused. Run the \
- app-bundle daemon instead: `open -n -g -a CuaDriver --args serve`.",
+ app-bundle daemon instead: `cua-driver permissions grant`.",
)
}
@@ -207,7 +207,8 @@ mod tests {
#[test]
fn unbundled_daemon_gets_a_startup_warning_and_bundled_or_embedded_does_not() {
let message = unbundled_warning(false, false).expect("warns when unbundled");
- assert!(message.contains("open -n -g -a CuaDriver --args serve"));
+ assert!(message.contains("cua-driver permissions grant"));
+ assert!(!message.contains("-a CuaDriver"));
assert!(unbundled_warning(false, true).is_none());
assert!(unbundled_warning(true, false).is_none());
}
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/health_report.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/health_report.rs
index fbca96e439..7ec69a56af 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/health_report.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/health_report.rs
@@ -177,7 +177,7 @@ fn standalone_bundle_identity(bid: Option<String>, exe: String) -> CheckEntry {
};
let hint = "This bundle check does not identify the app or executable macOS attributes \
this process's permission request to. For standalone CuaDriver, start the \
- daemon inside CuaDriver.app with `open -n -g -a CuaDriver --args serve` and \
+ daemon inside CuaDriver.app with `cua-driver permissions grant` and \
connect via `cua-driver mcp`. For an embedded or linked driver, use the \
host's launch and permission setup instead.";
@@ -429,7 +429,7 @@ mod tests {
let seen = windowserver_connection_entry(false, true);
assert_eq!(seen.status, CheckStatus::Fail);
assert!(seen.message.contains("1002"));
- assert!(seen.hint.unwrap().contains("open -n -g -a CuaDriver"));
+ assert!(seen.hint.unwrap().contains("cua-driver permissions grant"));
assert_eq!(
windowserver_connection_entry(true, false).status,
CheckStatus::Fail
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs
index 771e6717e3..7b0efb0d9e 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs
@@ -305,7 +305,7 @@ pub(crate) fn background_refusal_result(
}
/// Hint shown with every `windowserver_connection_invalid` refusal.
-pub(crate) const WINDOWSERVER_INVALID_HINT: &str = "This daemon runs without its own app-bundle identity (a bare `cua-driver serve`), so macOS gives it no valid WindowServer connection and every no-raise focus step fails. Run the app-bundle daemon: `open -n -g -a CuaDriver --args serve`.";
+pub(crate) const WINDOWSERVER_INVALID_HINT: &str = "This daemon runs without its own app-bundle identity (a bare `cua-driver serve`), so macOS gives it no valid WindowServer connection and every no-raise focus step fails. Run the app-bundle daemon: `cua-driver permissions grant`.";
/// Structured refusal for a background action whose no-raise focus step got
/// `SLPSPostEventRecordTo` status 1002 (invalid connection). Nothing was sent
@@ -1407,6 +1407,6 @@ mod windowserver_refusal_tests {
assert!(structured["hint"]
.as_str()
.unwrap()
- .contains("open -n -g -a CuaDriver --args serve"));
+ .contains("cua-driver permissions grant"));
}
}
diff --git a/libs/cua-driver/rust/scripts/CuaDriverBundle/Contents/Info.plist b/libs/cua-driver/rust/scripts/CuaDriverBundle/Contents/Info.plist
index a6f2cb05ad..5dd83d5062 100644
--- a/libs/cua-driver/rust/scripts/CuaDriverBundle/Contents/Info.plist
+++ b/libs/cua-driver/rust/scripts/CuaDriverBundle/Contents/Info.plist
@@ -10,7 +10,7 @@
port over an existing Swift install is a seamless upgrade: TCC
grants (Accessibility, Screen Recording) keyed on
`com.trycua.driver` transfer to the new binary; LaunchServices
- discovery via `open -n -g -a CuaDriver` keeps working.
+ discovery by bundle id keeps working.
Earlier releases of the Rust port shipped under
`/Applications/CuaDriverRs.app` with bundle id
@@ -19,10 +19,11 @@
replaces the Swift driver, not parallels it.
Exists so the Rust port can use the same TCC-attribution trick as
- the Swift cua-driver: `open -n -g -a CuaDriver --args serve`
- relaunches into a process attributed to `com.trycua.driver` (a
- stable bundle identifier TCC keys grants against), instead of
- inheriting the calling shell/IDE-terminal's TCC responsibility.
+ the Swift cua-driver: launching the installed bundle by its exact
+ path (`cua-driver permissions grant` does this) relaunches into a
+ process attributed to `com.trycua.driver` (a stable bundle
+ identifier TCC keys grants against), instead of inheriting the
+ calling shell/IDE-terminal's TCC responsibility.
Note on macOS code-signing: TCC pairs the bundle id with the
binary's cdhash. The Rust binary has a different cdhash from the
diff --git a/libs/cua-driver/scripts/_install-common.sh b/libs/cua-driver/scripts/_install-common.sh
index 6596ab5845..4a34abe87b 100644
--- a/libs/cua-driver/scripts/_install-common.sh
+++ b/libs/cua-driver/scripts/_install-common.sh
@@ -8,6 +8,15 @@
# stop_cua_driver_daemons ↔ Stop-CuaDriverDaemons
# show_cua_driver_daemon_survivors ↔ Show-CuaDriverDaemonSurvivors
#
+# macOS-only, no PowerShell counterpart:
+#
+# cua_driver_release_processes — every process of the current user that
+# runs a com.trycua.driver bundle, wherever
+# the app lives and whatever its version
+# cua_driver_stop_release_processes — stop those: graceful, then TERM, then KILL
+# unregister_other_cua_driver_copies — make LaunchServices forget every other
+# copy of the app (never deletes files)
+#
# This script is sourced (not exec'd) by the Rust install helpers:
#
# * _install-rust.sh (production Rust delegate)
@@ -109,7 +118,13 @@ stop_cua_driver_daemons() {
# PowerShell module after schtasks /End.
sleep 0.2 2>/dev/null || sleep 1
- if command -v pkill >/dev/null 2>&1; then
+ if [ "$(uname -s 2>/dev/null || echo unknown)" = "Darwin" ]; then
+ # macOS: stop what we can PROVE is Cua Driver (bundle id
+ # com.trycua.driver, any path, any version) instead of every
+ # process that happens to be named `cua-driver`. Another app can
+ # ship its own helper with that name; it is not ours to kill.
+ cua_driver_stop_release_processes
+ elif command -v pkill >/dev/null 2>&1; then
# `-x` = exact match on process name so we don't kill a
# user's `cua-driver-rs-foo` test harness or any script
# named "cua-driver-something". The Rust + Swift binaries
@@ -145,6 +160,24 @@ stop_cua_driver_daemons() {
# Idempotent — safe to call even when stop_cua_driver_daemons did
# clean up everything. Prints nothing in the common case.
show_cua_driver_daemon_survivors() {
+ if [ "$(uname -s 2>/dev/null || echo unknown)" = "Darwin" ]; then
+ # A stop request starts short-lived cua-driver processes of its own (the
+ # CLI re-executes itself); give them a moment before calling them
+ # survivors.
+ local mac_survivors waited=0 limit=$(( ${CUA_DRIVER_STOP_TIMEOUT:-5} * 2 ))
+ while :; do
+ mac_survivors=$(cua_driver_release_processes | awk -F '\t' '{ printf "%s%s", sep, $1; sep = ", " }')
+ [ -n "$mac_survivors" ] || return 0
+ [ "$waited" -lt "$limit" ] || break
+ sleep 0.5 2>/dev/null || sleep 1
+ waited=$((waited + 1))
+ done
+ printf 'Note: Cua Driver process(es) still running after the stop attempt (pid: %s).\n' "$mac_survivors"
+ printf ' They ignored SIGTERM and SIGKILL. Log out and back in, or run\n'
+ printf ' `kill -9 <pid>` yourself, then re-run this installer.\n'
+ return 0
+ fi
+
# `pgrep -x` matches the exact process name the same way `pkill -x`
# did above, so the survivor list is exactly what the kill couldn't
# reach (not random other cua-driver-* binaries).
@@ -188,3 +221,299 @@ show_cua_driver_daemon_survivors() {
"$yellow" "$normal"
return 0
}
+
+# ---------------------------------------------------------------------------
+# macOS: find and stop every Cua Driver process, wherever its app lives
+# ---------------------------------------------------------------------------
+#
+# A Mac can hold several copies of CuaDriver.app (an old release in ~/Downloads,
+# one in the Trash, a benchmark folder) and `open -a CuaDriver` may start any of
+# them. A daemon from such a copy is not the file we are about to replace, so
+# neither the pid file nor the install path finds it. We therefore identify
+# processes by what they are: an executable named cua-driver inside an app
+# bundle whose CFBundleIdentifier is com.trycua.driver, owned by this user.
+# Other users' processes (ps -U <uid>) and other apps (a different bundle id,
+# CuaDriverLocal's com.trycua.driver.local included) are never touched.
+
+CUA_DRIVER_RELEASE_BUNDLE_ID="com.trycua.driver"
+
+# Value of a top-level string key in an Info.plist. PlistBuddy reads binary and
+# XML plists; the awk fallback reads XML plists, so test fixtures and hosts
+# without PlistBuddy work too.
+cua_driver_plist_string() {
+ local plist="$1" key="$2" value=""
+ [ -f "$plist" ] || return 1
+ if [ -x /usr/libexec/PlistBuddy ]; then
+ value="$(/usr/libexec/PlistBuddy -c "Print :$key" "$plist" 2>/dev/null)" || value=""
+ fi
+ if [ -z "$value" ]; then
+ value="$(awk -v key="$key" '
+ function text(line) { sub(".*<string>", "", line); sub("</string>.*", "", line); return line }
+ index($0, "<key>" key "</key>") {
+ if ($0 ~ /<string>/) { print text($0); exit }
+ want = 1; next
+ }
+ want && /<string>/ { print text($0); exit }
+ want && /<key>/ { exit }
+ ' "$plist" 2>/dev/null)" || value=""
+ fi
+ [ -n "$value" ] || return 1
+ printf '%s' "$value"
+}
+
+# The .app directory when "$1" (a process command line) runs a cua-driver
+# executable inside an app bundle. Paths with spaces are fine: we cut at the
+# fixed /Contents/MacOS/cua-driver suffix, not at the first space.
+cua_driver_bundle_of_command() {
+ local command_line="$1" bundle
+ case "$command_line" in
+ */Contents/MacOS/cua-driver|*/Contents/MacOS/cua-driver\ *) ;;
+ *) return 1 ;;
+ esac
+ bundle="${command_line%%/Contents/MacOS/cua-driver*}"
+ case "$bundle" in
+ /*.app) printf '%s' "$bundle" ;;
+ *) return 1 ;;
+ esac
+}
+
+# True when the bundle is a Cua Driver release app. The bundle's own Info.plist
+# decides. If it cannot be read (the app was deleted while its daemon kept
+# running) only the stock names CuaDriver.app / CuaDriver-<version>.app count.
+cua_driver_bundle_is_release() {
+ local bundle="$1" id=""
+ id="$(cua_driver_plist_string "$bundle/Contents/Info.plist" CFBundleIdentifier)" || id=""
+ if [ -n "$id" ]; then
+ [ "$id" = "$CUA_DRIVER_RELEASE_BUNDLE_ID" ]
+ return
+ fi
+ case "${bundle##*/}" in
+ CuaDriver.app|CuaDriver-*.app|"CuaDriver "*.app) return 0 ;;
+ *) return 1 ;;
+ esac
+}
+
+# This shell and every parent: an installer started by `cua-driver update` or by
+# an agent that runs under a cua-driver process must not stop its own caller.
+cua_driver_ancestor_pids() {
+ local pid="$$" depth=0 parent
+ while [ -n "$pid" ] && [ "$pid" -gt 1 ] 2>/dev/null && [ "$depth" -lt 32 ]; do
+ printf '%s\n' "$pid"
+ parent="$(ps -o ppid= -p "$pid" 2>/dev/null | tr -d '[:space:]')" || break
+ [ -n "$parent" ] || break
+ pid="$parent"
+ depth=$((depth + 1))
+ done
+}
+
+# One "<pid><TAB><bundle dir>" line per running Cua Driver process of this user.
+cua_driver_release_processes() {
+ local uid ancestors line pid command_line bundle
+ uid="$(id -u 2>/dev/null)" || return 0
+ command -v ps >/dev/null 2>&1 || return 0
+ ancestors="$(cua_driver_ancestor_pids)"
+ ps -U "$uid" -ww -o pid= -o command= 2>/dev/null | while IFS= read -r line; do
+ line="${line#"${line%%[![:space:]]*}"}"
+ pid="${line%%[[:space:]]*}"
+ case "$pid" in ''|*[!0-9]*) continue ;; esac
+ command_line="${line#"$pid"}"
+ command_line="${command_line#"${command_line%%[![:space:]]*}"}"
+ printf '%s\n' "$ancestors" | grep -qx "$pid" && continue
+ bundle="$(cua_driver_bundle_of_command "$command_line")" || continue
+ cua_driver_bundle_is_release "$bundle" || continue
+ printf '%s\t%s\n' "$pid" "$bundle"
+ done
+}
+
+# The bundle dir if "$1" is STILL a Cua Driver process (guards against pid reuse
+# between listing and signalling).
+cua_driver_pid_release_bundle() {
+ local command_line bundle
+ command_line="$(ps -ww -o command= -p "$1" 2>/dev/null)" || return 1
+ command_line="${command_line#"${command_line%%[![:space:]]*}"}"
+ bundle="$(cua_driver_bundle_of_command "$command_line")" || return 1
+ cua_driver_bundle_is_release "$bundle" || return 1
+ printf '%s' "$bundle"
+}
+
+# Wait up to $2 seconds for pid $1 to exit.
+cua_driver_wait_gone() {
+ local pid="$1" tenths=$(( ${2:-5} * 10 ))
+ while kill -0 "$pid" 2>/dev/null; do
+ [ "$tenths" -gt 0 ] || return 1
+ sleep 0.1 2>/dev/null || sleep 1
+ tenths=$((tenths - 1))
+ done
+ return 0
+}
+
+# Run a command, giving up (and killing it) after $1 seconds. Output is dropped.
+cua_driver_run_bounded() {
+ local limit="$1" child tenths
+ shift
+ "$@" >/dev/null 2>&1 &
+ child=$!
+ tenths=$((limit * 10))
+ while kill -0 "$child" 2>/dev/null && [ "$tenths" -gt 0 ]; do
+ sleep 0.1 2>/dev/null || sleep 1
+ tenths=$((tenths - 1))
+ done
+ kill "$child" 2>/dev/null || true
+ wait "$child" 2>/dev/null || true
+}
+
+# Stop every Cua Driver process of this user, wherever its app lives. Order:
+# the daemon's own `stop` request (clean shutdown), then SIGTERM, then SIGKILL,
+# each given CUA_DRIVER_STOP_TIMEOUT seconds (default 5). Prints one line per
+# process saying how it ended. Returns 1 if any process survived.
+cua_driver_stop_release_processes() {
+ local timeout="${CUA_DRIVER_STOP_TIMEOUT:-5}" list pid bundle version label how helper tab failed=0
+ tab="$(printf '\t')"
+ list="$(cua_driver_release_processes)"
+ [ -n "$list" ] || return 0
+ while IFS="$tab" read -r pid bundle; do
+ [ -n "$pid" ] || continue
+ version="$(cua_driver_plist_string "$bundle/Contents/Info.plist" CFBundleShortVersionString)" || version=""
+ label="pid $pid, ${version:+version $version, }$bundle"
+ how=""
+
+ # 1. Ask the daemon to shut down through its own bundle's CLI. Old
+ # releases do not know --expected-pid and simply fail; that is fine.
+ helper="$bundle/Contents/MacOS/cua-driver"
+ if [ -x "$helper" ] && cua_driver_pid_release_bundle "$pid" >/dev/null; then
+ cua_driver_run_bounded "$timeout" "$helper" --expected-pid "$pid" stop
+ if cua_driver_wait_gone "$pid" 1; then
+ how="a graceful stop request"
+ fi
+ fi
+ # 2. SIGTERM, re-checking the pid still belongs to Cua Driver.
+ if [ -z "$how" ] && cua_driver_pid_release_bundle "$pid" >/dev/null; then
+ kill -TERM "$pid" 2>/dev/null || true
+ if cua_driver_wait_gone "$pid" "$timeout"; then
+ how="SIGTERM"
+ fi
+ fi
+ # 3. SIGKILL.
+ if [ -z "$how" ] && cua_driver_pid_release_bundle "$pid" >/dev/null; then
+ kill -KILL "$pid" 2>/dev/null || true
+ if cua_driver_wait_gone "$pid" 2; then
+ how="SIGKILL after it ignored SIGTERM for ${timeout}s"
+ fi
+ fi
+ if [ -z "$how" ] && ! kill -0 "$pid" 2>/dev/null; then
+ how="its own exit"
+ fi
+ if [ -n "$how" ]; then
+ printf '==> stopped Cua Driver (%s) with %s\n' "$label" "$how"
+ else
+ printf '==> could not stop Cua Driver (%s); it is still running\n' "$label" >&2
+ failed=1
+ fi
+ done <<EOF
+$list
+EOF
+ return "$failed"
+}
+
+# ---------------------------------------------------------------------------
+# macOS: make LaunchServices forget every other copy of the app
+# ---------------------------------------------------------------------------
+#
+# `open -a CuaDriver`, a bundle-id lookup and System Settings' permission rows
+# all resolve to whichever registered copy macOS likes best, which is how an old
+# copy in the Trash became the "CuaDriver-0.34.0" row. After an install only the
+# installed bundle should stay registered. `lsregister -u` removes the
+# registration only; no file is deleted.
+
+# Where lsregister lives. CUA_DRIVER_LSREGISTER overrides it (tests).
+cua_driver_lsregister_path() {
+ printf '%s' "${CUA_DRIVER_LSREGISTER:-/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister}"
+}
+
+# Paths of every bundle with the given id that LaunchServices (lsregister -dump)
+# or Spotlight (mdfind) knows about, one per line, sorted and unique. The dump
+# is slow on a busy Mac (tens of seconds), so it is capped by
+# CUA_DRIVER_LSREGISTER_TIMEOUT seconds (default 120).
+cua_driver_known_bundle_paths() {
+ local bundle_id="${1:-$CUA_DRIVER_RELEASE_BUNDLE_ID}" lsregister dump pid waited=0 limit
+ lsregister="$(cua_driver_lsregister_path)"
+ limit="${CUA_DRIVER_LSREGISTER_TIMEOUT:-120}"
+ {
+ if [ -x "$lsregister" ]; then
+ dump="$(mktemp -t cua-lsdump.XXXXXX 2>/dev/null)" || dump=""
+ if [ -n "$dump" ]; then
+ "$lsregister" -dump >"$dump" 2>/dev/null &
+ pid=$!
+ while kill -0 "$pid" 2>/dev/null; do
+ if [ "$waited" -ge "$limit" ]; then
+ kill "$pid" 2>/dev/null || true
+ break
+ fi
+ sleep 1
+ waited=$((waited + 1))
+ done
+ wait "$pid" 2>/dev/null || true
+ # A dump is a series of blocks split by a line of dashes; each
+ # block has "path:" and "identifier:" lines.
+ awk -v id="$bundle_id" '
+ function flush() { if (path != "" && matches) print path; path = ""; matches = 0 }
+ /^----------/ { flush(); next }
+ /^path:[ \t]/ {
+ p = $0; sub(/^path:[ \t]+/, "", p); sub(/[ \t]+\(0x[0-9a-fA-F]+\)$/, "", p)
+ path = p; next
+ }
+ /^identifier:[ \t]/ {
+ i = $0; sub(/^identifier:[ \t]+/, "", i); sub(/[ \t]+$/, "", i)
+ matches = (i == id); next
+ }
+ END { flush() }
+ ' "$dump"
+ rm -f "$dump"
+ fi
+ fi
+ if command -v mdfind >/dev/null 2>&1; then
+ mdfind "kMDItemCFBundleIdentifier == '$bundle_id'" 2>/dev/null || true
+ fi
+ } | sed '/^$/d' | sort -u
+}
+
+# unregister_other_cua_driver_copies <installed bundle dir>
+# Unregisters every other com.trycua.driver bundle and prints one summary line.
+# Best effort: never fails the install, never deletes anything.
+unregister_other_cua_driver_copies() {
+ local active="$1" lsregister active_real path real found=0 paths word on_disk="" on_disk_count=0
+ lsregister="$(cua_driver_lsregister_path)"
+ [ -x "$lsregister" ] || return 0
+ active_real="$(cd "$active" 2>/dev/null && pwd -P)" || active_real="$active"
+ paths="$(cua_driver_known_bundle_paths "$CUA_DRIVER_RELEASE_BUNDLE_ID")"
+ [ -n "$paths" ] || return 0
+ while IFS= read -r path; do
+ [ -n "$path" ] || continue
+ real="$path"
+ if [ -d "$path" ]; then
+ real="$(cd "$path" 2>/dev/null && pwd -P)" || real="$path"
+ fi
+ if [ "$path" = "$active" ] || [ "$real" = "$active_real" ]; then
+ continue
+ fi
+ found=$((found + 1))
+ if ! "$lsregister" -u "$path" >/dev/null 2>&1; then
+ printf 'warning: could not unregister the old Cua Driver copy at %s\n' "$path" >&2
+ fi
+ if [ -d "$path" ]; then
+ on_disk_count=$((on_disk_count + 1))
+ [ "$on_disk_count" -gt 3 ] || on_disk="${on_disk:+$on_disk, }$path"
+ fi
+ done <<EOF
+$paths
+EOF
+ [ "$found" -gt 0 ] || return 0
+ word="copies"
+ [ "$found" -ne 1 ] || word="copy"
+ printf 'Found %s old Cua Driver %s; macOS will now only use %s\n' "$found" "$word" "$active"
+ if [ "$on_disk_count" -gt 0 ]; then
+ [ "$on_disk_count" -le 3 ] || on_disk="$on_disk and $((on_disk_count - 3)) more"
+ printf 'Their files were left in place (delete them when you no longer need them): %s\n' "$on_disk"
+ fi
+ return 0
+}
diff --git a/libs/cua-driver/scripts/_install-local-rust.sh b/libs/cua-driver/scripts/_install-local-rust.sh
index e4b3384048..2ce39b18cc 100755
--- a/libs/cua-driver/scripts/_install-local-rust.sh
+++ b/libs/cua-driver/scripts/_install-local-rust.sh
@@ -483,8 +483,8 @@ if [ "$OS" = "Darwin" ]; then
#
# `ditto` drops the bundle on disk, but LaunchServices registers the new
# com.trycua.driver.local identity ASYNCHRONOUSLY (seconds later). Until it
- # does, `open -n -g -a CuaDriverLocal` (what `permissions grant` / MCP use to
- # launch the daemon) fails with -1728. A synchronous `lsregister -f` closes
+ # does, launching the bundle (what `permissions grant` / MCP do to start
+ # the daemon) can fail with -1728. A synchronous `lsregister -f` closes
# that race so both the reset and the first launch resolve the bundle id.
LSREGISTER="/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister"
if [ -x "$LSREGISTER" ]; then
diff --git a/libs/cua-driver/scripts/_install-rust.sh b/libs/cua-driver/scripts/_install-rust.sh
index 2e8506d094..d9dbc5de92 100644
--- a/libs/cua-driver/scripts/_install-rust.sh
+++ b/libs/cua-driver/scripts/_install-rust.sh
@@ -119,6 +119,8 @@ if [[ "$_cua_install_common_loaded" == "0" ]]; then
printf 'warning: could not load _install-common.sh (on-disk + network); daemon kill skipped\n' >&2
stop_cua_driver_daemons() { :; }
show_cua_driver_daemon_survivors() { :; }
+ unregister_other_cua_driver_copies() { :; }
+ cua_driver_lsregister_path() { return 1; }
fi
REPO="trycua/cua"
@@ -350,8 +352,22 @@ release_install_lock() {
# Combine TMP_DIR cleanup with lock release in a single trap so neither
# clobbers the other. INT/TERM also re-raise via $? so the user-visible
# exit code reflects the signal.
+# The release archive is unpacked into $TMP_DIR, which includes a CuaDriver.app
+# that is deleted on exit. Make sure LaunchServices never keeps that dead copy:
+# a registered temp copy can later be what `open -a CuaDriver` or a permission
+# row resolves to.
+forget_staged_macos_app() {
+ [[ "$(uname -s 2>/dev/null)" == "Darwin" && -n "${SRC_APP:-}" && -d "$SRC_APP" ]] || return 0
+ local lsregister
+ lsregister="$(cua_driver_lsregister_path 2>/dev/null || true)"
+ if [[ -x "$lsregister" ]]; then
+ "$lsregister" -u "$SRC_APP" >/dev/null 2>&1 || true
+ fi
+}
+
cleanup_on_exit() {
restore_macos_app_backup_on_exit
+ forget_staged_macos_app
rm -rf "$TMP_DIR" 2>/dev/null || true
release_install_lock
}
@@ -891,8 +907,8 @@ version_is_at_least() {
# macOS — fetch the directory tarball (cua-driver-rs-vN-darwin-universal.tar.gz).
# The directory layout includes `CuaDriver.app/` alongside the bare
# binary, which we need to install into /Applications so the TCC
-# auto-relaunch path in `cua-driver-rs mcp` can resolve
-# `com.trycua.driver` via `open -n -g -a CuaDriver`. The
+# auto-relaunch path in `cua-driver-rs mcp` can launch the installed
+# `com.trycua.driver` app by its exact path. The
# directory variant carries the same universal binary as the
# bare-binary tarball, so users on both Apple Silicon and Intel
# get a working install from one download.
@@ -1242,7 +1258,7 @@ fi
# $HOME_DIR/packages/releases/<v>/ + current symlink layout used on
# Linux. Reason: /Applications/CuaDriver.app placement is the
# anchor for both TCC attribution (cdhash + bundle id) and
-# LaunchServices' `open -a CuaDriver` discovery — symlinking the
+# LaunchServices' bundle-id discovery — symlinking the
# .app from /Applications to a versioned dir under $HOME_DIR breaks
# both. The asymmetry is deliberate; rollback on macOS = reinstall
# an older release tag.
@@ -1377,8 +1393,9 @@ if [[ "$OS" == "Darwin" && -n "$SRC_APP" && -d "$SRC_APP" ]]; then
exit 1
fi
- # Register synchronously so both `open -a CuaDriver` and `tccutil reset`
- # resolve the replacement bundle rather than a stale LaunchServices entry.
+ # Register synchronously so both `permissions grant` (which launches the
+ # bundle by its exact path) and `tccutil reset` resolve the replacement
+ # bundle rather than a stale LaunchServices entry.
LSREGISTER="/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister"
if [[ -x "$LSREGISTER" ]] \
&& "$LSREGISTER" -f "$APP_DEST" >/dev/null 2>&1; then
@@ -1417,6 +1434,10 @@ if [[ "$OS" == "Darwin" && -n "$SRC_APP" && -d "$SRC_APP" ]]; then
rm -rf "$MACOS_APP_BACKUP" || true
ln -sf "$APP_BINARY" "$BIN_LINK"
log "symlinked $BIN_LINK -> $APP_BINARY"
+ # Other copies of the app (an old release in ~/Downloads, the Trash, a
+ # benchmark folder) make macOS open the wrong app and label the permission
+ # rows with the wrong name. Forget them; their files stay where they are.
+ unregister_other_cua_driver_copies "$APP_DEST" || true
if ! macos_reset_tcc_after_requirement_change "$REQUIREMENT_COMPATIBILITY"; then
exit 1
fi
@@ -1619,17 +1640,11 @@ else
# Network fetch failed — print a one-line essentials fallback so the
# user always gets enough to recover, even if hint-text fetching is
# blocked. Skip everything else.
- echo "Next steps: $BIN_LINK --version | $BIN_LINK mcp-config | $BIN_LINK skills install"
+ echo "Next steps: $BIN_LINK permissions grant | $BIN_LINK mcp-config --client <name> | $BIN_LINK list-tools"
echo "Docs: https://github.com/trycua/cua/tree/main/libs/cua-driver/rust"
fi
case "$(uname -s)" in
- Darwin)
- echo ""
- echo "macOS TCC: grant Accessibility + Screen Recording on first run:"
- echo " open -n -g -a CuaDriver --args serve"
- echo " $BIN_LINK check_permissions"
- ;;
Linux)
echo ""
echo "Auto-start at logon (optional):"
diff --git a/libs/cua-driver/scripts/post-install-hints.txt b/libs/cua-driver/scripts/post-install-hints.txt
index d75006d167..08c13efe77 100644
--- a/libs/cua-driver/scripts/post-install-hints.txt
+++ b/libs/cua-driver/scripts/post-install-hints.txt
@@ -1,103 +1,20 @@
Next steps:
- 1. Try it:
- {{BINARY}} --version
+ 1. Grant permissions (macOS: Accessibility + Screen Recording):
+ {{BINARY}} permissions grant
+ This launches the installed app by its exact path, so every dialog and
+ Settings entry names Cua Driver, not your terminal.
+
+ 2. Connect your agent:
+ {{BINARY}} mcp-config --client <name>
+ Names: claude, codex, cursor, hermes, antigravity, openclaw, opencode,
+ pi, prime-agent, qwen, droid, zcode. Leave out --client for a generic
+ snippet. Muse Code and GitHub Copilot CLI: see the docs link below.
+
+ 3. Check it works:
{{BINARY}} list-tools
- 2. Grant permissions (macOS — Accessibility + Screen Recording):
- {{BINARY}} permissions status # report status (read-only; tells you which
- # identity the grants belong to)
- {{BINARY}} permissions grant # the correct way to grant — launches the installed
- # app so every dialog and Settings entry matches
- # this driver identity, not your terminal.
- # Tip: `--autostart` (above) keeps a launchd daemon
- # running so you grant once and it persists.
-
- 3. Agent skill pack (optional):
- {{BINARY}} skills install # fetch + link the cua-driver skill pack
- # into Claude Code / Codex / Prime Agent /
- # OpenClaw / OpenCode and other supported agents.
- # The binary installer never touches your agent dirs.
-
- Prime Agent needs no MCP registration. It loads the installed skill and
- calls cua-driver from its persistent IPython environment. Print its setup:
- {{BINARY}} mcp-config --client prime-agent
- Then run /reload in Prime Agent (or start a new session).
-
- 4. As an MCP server — run the one matching your client. Each is also
- available via '{{BINARY}} mcp-config --client <name>':
-
- • Claude Code (computer-use compatibility mode):
- {{BINARY}} mcp-config --client claude
- Copy-paste the printed command into your shell — it uses
- `claude mcp add-json` (not bare `--`) so the long flag travels
- through PowerShell's arg parser intact. This mode grounds Claude
- Code's vision/computer-use-style flow on CuaDriver window
- screenshots — it keeps the normal CuaDriver tools and changes
- only the screenshot tool.
-
- • Codex (OpenAI):
- codex mcp add cua-driver -- {{BINARY}} mcp
-
- • Qwen Code:
- qwen mcp add cua-driver {{BINARY}} mcp
-
- • Factory Droid:
- droid mcp add cua-driver "{{BINARY}} mcp"
-
- • OpenClaw:
- {{BINARY}} mcp-config --client openclaw
-
- • GitHub Copilot CLI (paste into ~/.copilot/mcp-config.json):
- {
- "mcpServers": {
- "cua-driver": {
- "type": "local",
- "command": "{{BINARY}}",
- "args": ["mcp"],
- "tools": ["*"]
- }
- }
- }
-
- • Cursor / OpenCode / Hermes (no add CLI — paste config):
- {{BINARY}} mcp-config --client cursor # JSON for ~/.cursor/mcp.json
- {{BINARY}} mcp-config --client opencode # JSON for opencode.json
- {{BINARY}} mcp-config --client hermes # YAML for ~/.hermes/config.yaml
-
- • Muse Code (macOS / Linux — merge into
- $XDG_CONFIG_HOME/muse/settings.json, or ~/.config/muse/settings.json):
- {
- "mcp_servers": {
- "cua-driver": {
- "enabled": true,
- "transport": "stdio",
- "command": "{{BINARY}}",
- "args": ["mcp"]
- }
- }
- }
- Start a new Muse session after saving; MCP servers load at startup.
-
- • ZCode (Z.ai — GUI app; paste in Settings → MCP Servers):
- {{BINARY}} mcp-config --client zcode
-
- For other clients accepting the generic mcpServers shape:
- {{BINARY}} mcp-config
-
- Permission modes:
- • standard is the promptless default for normal automation.
- • To use an existing logged-in Chrome or Edge profile in standard:
- {{BINARY}} mcp --grant existing-profile
- Add the same flag to `serve` when using a long-running daemon.
- • Use a reviewed capability manifest to limit tools, apps, browser
- profiles, origins, and file roots. Bounded requires one:
- {{BINARY}} serve --permission-mode bounded \
- --capability-manifest ./cua-capabilities.yaml \
- --approve-capability-manifest
- • unrestricted requires explicit risk acceptance:
- {{BINARY}} serve --permission-mode unrestricted \
- --dangerously-bypass-approvals
-
+More: {{BINARY}} skills install (agent skill pack), {{BINARY}} doctor
+(diagnose this install). Permission modes: see the docs.
Docs: https://cua.ai/docs/cua-driver/guides/connect-your-agent
diff --git a/libs/cua-driver/scripts/tests/test_uninstall_daemon_stop.py b/libs/cua-driver/scripts/tests/test_uninstall_daemon_stop.py
index 8306705324..3cdc939ef0 100644
--- a/libs/cua-driver/scripts/tests/test_uninstall_daemon_stop.py
+++ b/libs/cua-driver/scripts/tests/test_uninstall_daemon_stop.py
@@ -59,6 +59,7 @@ DAEMON_STOP_HELPER="{helper or ''}"
daemon_pid_alive() {{ return 0; }}
daemon_pid_is_release() {{ return 0; }}
daemon_process_generation() {{ printf generation-1; }}
+release_daemon_fallback_pids() {{ return 0; }}
verify_release_daemon_absent() {{ return 0; }}
"""
@@ -119,10 +120,19 @@ stop_release_daemon
self.assertTrue(generations.exists(), "the stop path never captured a generation")
self.assertFalse(signals.exists(), signals.read_text() if signals.exists() else "")
- def test_missing_helper_fails_before_signal(self) -> None:
- result = self.shell(self.setup(None) + "stop_release_daemon")
- self.assertNotEqual(result.returncode, 0)
- self.assertIn("stop helper is unavailable", result.stderr)
+ def test_missing_helper_falls_back_to_the_signal_sweep(self) -> None:
+ """The installed copy may be gone, or not the one running: do not abort."""
+ signals = self.root / "signals"
+ result = self.shell(
+ self.setup(None)
+ + f"""
+stop_stray_release_daemons() {{ : > "{signals}"; }}
+stop_release_daemon
+"""
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertIn("no trusted stop helper for pid 4242", result.stderr)
+ self.assertTrue(signals.exists(), "the signal sweep never ran")
def test_process_generation_guards_signal(self) -> None:
marker = self.root / "signal"
diff --git a/libs/cua-driver/scripts/tests/test_uninstall_stops_daemons_from_other_copies.py b/libs/cua-driver/scripts/tests/test_uninstall_stops_daemons_from_other_copies.py
new file mode 100644
index 0000000000..f149921b4f
--- /dev/null
+++ b/libs/cua-driver/scripts/tests/test_uninstall_stops_daemons_from_other_copies.py
@@ -0,0 +1,400 @@
+"""A Cua Driver daemon from ANY copy of the app gets stopped, and nothing else does.
+
+A Mac can hold a second CuaDriver.app (an old release in ~/Downloads, the Trash, a
+benchmark folder). `open -a CuaDriver` may start that copy, so the daemon is not
+the installed file and not in the pid file. The uninstaller and the installer's
+swap step must still identify it by bundle id (com.trycua.driver), stop it
+gracefully, then SIGTERM, then SIGKILL, say what they stopped, and never touch
+other users' processes or other apps.
+
+Safety: every "daemon" here is a throwaway `sleep` that this test spawns. `ps`,
+`pgrep` and process identity are faked, so the tests can never see, let alone
+signal, a real Cua Driver daemon running on the machine.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import signal
+import subprocess
+import time
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[4]
+SCRIPTS = ROOT / "libs/cua-driver/scripts"
+UNINSTALL = SCRIPTS / "uninstall.sh"
+COMMON = SCRIPTS / "_install-common.sh"
+
+PLIST = """<?xml version="1.0" encoding="UTF-8"?>
+<plist version="1.0">
+<dict>
+ <key>CFBundleExecutable</key>
+ <string>cua-driver</string>
+ <key>CFBundleIdentifier</key>
+ <string>{bundle_id}</string>
+ <key>CFBundleShortVersionString</key>
+ <string>{version}</string>
+</dict>
+</plist>
+"""
+
+
+def alive(pid: int) -> bool:
+ try:
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ return False
+ return True
+
+
+class Machine:
+ """Fake processes in fake app bundles, with `ps`/`pgrep` shims over them."""
+
+ def __init__(self, root: Path) -> None:
+ self.root = root
+ self.bin = root / "bin"
+ self.fake = root / "fake"
+ self.home = root / "home"
+ for directory in (self.bin, self.fake, self.home):
+ directory.mkdir()
+ self.pids: list[int] = []
+ self.pgrep_log = root / "pgrep.log"
+ self._write(
+ self.bin / "pgrep",
+ f'echo "$@" >> "{self.pgrep_log}"\n'
+ f'for f in "{self.fake}"/*.cmd; do [ -e "$f" ] || continue; '
+ 'pid="$(basename "$f" .cmd)"; kill -0 "$pid" 2>/dev/null && echo "$pid"; done; exit 0',
+ )
+ # ps: only used for ancestors (-o ppid=) and the installer's listing.
+ self._write(
+ self.bin / "ps",
+ f'case "$*" in\n'
+ f' *ppid=*) exit 0 ;;\n'
+ f' *"-o pid="*)\n'
+ f' for f in "{self.fake}"/*.cmd; do [ -e "$f" ] || continue; '
+ 'pid="$(basename "$f" .cmd)"; kill -0 "$pid" 2>/dev/null && '
+ 'printf "%s %s\\n" "$pid" "$(cat "$f")"; done; exit 0 ;;\n'
+ f' *"-o command="*)\n'
+ f' for a in "$@"; do pid="$a"; done\n'
+ f' cat "{self.fake}/$pid.cmd" 2>/dev/null; exit 0 ;;\n'
+ f'esac\nexit 2',
+ )
+ for name, body in {
+ "id": 'if [ "$1" = -u ]; then echo 501; else /usr/bin/id "$@"; fi',
+ "pkill": f'echo pkill "$@" >> "{root}/pkill.log"',
+ }.items():
+ self._write(self.bin / name, body)
+
+ @staticmethod
+ def _write(path: Path, body: str) -> None:
+ path.write_text(f"#!/bin/sh\n{body}\n", encoding="utf-8")
+ path.chmod(0o755)
+
+ def bundle(
+ self,
+ where: str,
+ bundle_id: str | None = "com.trycua.driver",
+ version: str = "0.34.0",
+ helper: str = "exit 1",
+ ) -> Path:
+ """An app bundle whose cua-driver helper runs `helper` (a shell body)."""
+ app = self.root / where
+ (app / "Contents/MacOS").mkdir(parents=True)
+ if bundle_id is not None:
+ (app / "Contents/Info.plist").write_text(
+ PLIST.format(bundle_id=bundle_id, version=version), encoding="utf-8"
+ )
+ self._write(app / "Contents/MacOS/cua-driver", helper)
+ return app
+
+ def spawn(self, app: Path, ignore_term: bool = False) -> int:
+ """Start a throwaway process that the fakes report as running from `app`."""
+ guard = 'trap "" TERM; ' if ignore_term else ""
+ # The inner sh exits at once, so the worker is re-parented and never
+ # lingers as a zombie that `kill -0` would still see.
+ out = subprocess.run(
+ ["/bin/sh", "-c", f"({guard}exec sleep 300) >/dev/null 2>&1 & echo $!"],
+ capture_output=True,
+ text=True,
+ check=True,
+ )
+ pid = int(out.stdout.strip())
+ self.pids.append(pid)
+ (self.fake / f"{pid}.cmd").write_text(
+ f"{app}/Contents/MacOS/cua-driver serve", encoding="utf-8"
+ )
+ return pid
+
+ def spawn_exit_after(self, pid: int, seconds: int) -> None:
+ """Make the fake process `pid` exit by itself after `seconds`."""
+ subprocess.Popen(
+ ["/bin/sh", "-c", f"sleep {seconds}; kill {pid}"],
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ start_new_session=True,
+ )
+
+ def wait_dead(self, pid: int, seconds: float = 3.0) -> bool:
+ deadline = time.time() + seconds
+ while time.time() < deadline:
+ if not alive(pid):
+ return True
+ time.sleep(0.05)
+ return not alive(pid)
+
+ def cleanup(self) -> None:
+ for pid in self.pids:
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+
+ def env(self, **extra: str) -> dict[str, str]:
+ env = {k: v for k, v in os.environ.items() if not k.startswith("CUA_DRIVER_")}
+ env.update(
+ HOME=str(self.home),
+ PATH=f"{self.bin}:/usr/bin:/bin",
+ CUA_DRIVER_UNINSTALL_TEST_SOURCE_ONLY="1",
+ CUA_DRIVER_STOP_TIMEOUT="1",
+ )
+ env.update(extra)
+ return env
+
+ def uninstall_shell(self, body: str) -> subprocess.CompletedProcess[str]:
+ """Source uninstall.sh and run `body` with process identity read from the fakes."""
+ prelude = f"""
+APP_BUNDLE=/Applications/CuaDriver.app
+LEGACY_APP_BUNDLE=/Applications/CuaDriverRs.app
+HOME_DIR="$HOME/.cua-driver"
+LEGACY_HOME_DIR="$HOME/.cua-driver-rs"
+USER_BIN_LINK="$HOME/.local/bin/cua-driver"
+DAEMON_PID_FILE=""
+DAEMON_STOP_HELPER=""
+daemon_process_identity() {{ cat "{self.fake}/$1.cmd" 2>/dev/null || return 2; }}
+daemon_process_generation() {{ printf 'generation-%s' "$1"; }}
+"""
+ return subprocess.run(
+ ["/bin/bash", "-c", f'source "{UNINSTALL}"\n{prelude}\n{body}'],
+ cwd=ROOT,
+ env=self.env(),
+ text=True,
+ capture_output=True,
+ check=False,
+ timeout=60,
+ )
+
+ def common_shell(self, body: str, **env: str) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(
+ ["/bin/bash", "-c", f'source "{COMMON}"\n{body}'],
+ cwd=ROOT,
+ env=self.env(**env),
+ text=True,
+ capture_output=True,
+ check=False,
+ timeout=60,
+ )
+
+
+def machine(tmp_path: Path):
+ m = Machine(tmp_path)
+ yield m
+ m.cleanup()
+
+
+def test_uninstaller_stops_a_daemon_from_another_copy_of_the_app(machine: Machine) -> None:
+ old = machine.bundle("Old Apps/CuaDriver-0.34.0.app", version="0.34.0")
+ stray = machine.spawn(old)
+
+ result = machine.uninstall_shell("stop_release_daemon")
+
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert machine.wait_dead(stray), "the stray daemon is still running"
+ assert f"stopped Cua Driver (pid {stray}, version 0.34.0, {old}) with SIGTERM" in result.stdout
+ assert "daemon_stop_incomplete" not in result.stderr
+ assert old.exists(), "stopping a daemon must not delete the app"
+
+
+def test_pid_file_daemon_from_another_copy_is_described_when_stopped(machine: Machine) -> None:
+ old = machine.bundle("Downloads/CuaDriver.app", version="0.34.0")
+ stray = machine.spawn(old)
+ pid_file = machine.root / "daemon.pid"
+ pid_file.write_text(f"{stray}\n", encoding="utf-8")
+ helper = machine.root / "trusted-helper"
+ machine._write(helper, '[ "$2" = "$STRAY" ] && kill "$2"')
+
+ result = machine.uninstall_shell(
+ f'DAEMON_PID_FILE="{pid_file}"\nDAEMON_STOP_HELPER="{helper}"\nexport STRAY={stray}\n'
+ "stop_release_daemon"
+ )
+
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert machine.wait_dead(stray)
+ assert f"stopped Cua Driver daemon (pid {stray}, version 0.34.0, {old})" in result.stdout
+
+
+def test_uninstaller_tries_a_graceful_stop_through_the_copys_own_cli_first(machine: Machine) -> None:
+ old = machine.bundle(
+ "Downloads/CuaDriver.app",
+ helper='[ "$1" = --expected-pid ] && [ "$3" = stop ] && kill "$2"',
+ )
+ stray = machine.spawn(old)
+
+ result = machine.uninstall_shell("stop_release_daemon")
+
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert machine.wait_dead(stray)
+ assert "with a graceful stop request" in result.stdout
+
+
+def test_uninstaller_escalates_to_sigkill_when_sigterm_is_ignored(machine: Machine) -> None:
+ old = machine.bundle(".Trash/CuaDriver.app")
+ stubborn = machine.spawn(old, ignore_term=True)
+
+ result = machine.uninstall_shell("stop_release_daemon")
+
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert machine.wait_dead(stubborn), "SIGKILL fallback never fired"
+ assert "with SIGKILL after it ignored SIGTERM for 1s" in result.stdout
+
+
+def test_uninstaller_stops_every_copy_but_never_other_apps(machine: Machine) -> None:
+ old_a = machine.bundle("Downloads/CuaDriver.app", version="0.34.0")
+ old_b = machine.bundle("bench/CuaDriver.app", version="0.36.0")
+ deleted = machine.bundle("gone/CuaDriver-0.35.0.app", bundle_id=None)
+ local = machine.bundle("Applications/CuaDriverLocal.app", bundle_id="com.trycua.driver.local")
+ other_app = machine.bundle("Applications/Other.app", bundle_id="com.example.other")
+ unreadable_other = machine.bundle("Mystery.app", bundle_id=None)
+
+ mine = [machine.spawn(old_a), machine.spawn(old_b), machine.spawn(deleted)]
+ not_mine = [machine.spawn(local), machine.spawn(other_app), machine.spawn(unreadable_other)]
+
+ result = machine.uninstall_shell("stop_release_daemon")
+
+ assert result.returncode == 0, result.stdout + result.stderr
+ for pid in mine:
+ assert machine.wait_dead(pid), f"Cua Driver pid {pid} survived"
+ for pid in not_mine:
+ assert alive(pid), f"pid {pid} belongs to another app and must not be stopped"
+ assert result.stdout.count("stopped Cua Driver (") == 3
+
+
+def test_uninstaller_only_looks_at_the_current_users_processes(machine: Machine) -> None:
+ machine.uninstall_shell("release_daemon_fallback_pids")
+
+ # pgrep is asked for this user's processes only (-U <uid>); another user's
+ # cua-driver is never even a candidate.
+ assert re.search(r"-U \d+", machine.pgrep_log.read_text())
+
+
+def test_uninstaller_never_selects_its_own_ancestors(machine: Machine) -> None:
+ old = machine.bundle("Downloads/CuaDriver.app")
+ caller = machine.spawn(old) # e.g. `cua-driver update` that started the uninstaller
+ other = machine.spawn(old)
+
+ result = machine.uninstall_shell(
+ f'cua_driver_ancestor_pids() {{ echo {caller}; }}\nrelease_daemon_fallback_pids'
+ )
+
+ assert result.stdout.split() == [str(other)]
+ assert alive(caller)
+
+
+def test_uninstaller_fails_closed_and_names_a_process_it_cannot_stop(machine: Machine) -> None:
+ old = machine.bundle("Downloads/CuaDriver.app")
+ machine.spawn(old)
+
+ # Signals that cannot be delivered: the process survives every step.
+ result = machine.uninstall_shell(
+ "daemon_signal_if_current() { return 1; }\nstop_release_daemon"
+ )
+
+ assert result.returncode == 1
+ assert "daemon_stop_incomplete: Cua Driver process(es) still running" in result.stderr
+
+
+def test_installer_swap_step_stops_a_daemon_from_another_copy(machine: Machine) -> None:
+ old = machine.bundle("tmp/CuaDriver.app", version="0.36.0")
+ stray = machine.spawn(old)
+
+ result = machine.common_shell("cua_driver_stop_release_processes")
+
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert machine.wait_dead(stray)
+ assert f"stopped Cua Driver (pid {stray}, version 0.36.0, {old}) with SIGTERM" in result.stdout
+
+
+def test_installer_swap_step_never_touches_other_apps_and_skips_pkill_on_macos(machine: Machine) -> None:
+ other_app = machine.bundle("Applications/Spaces.app", bundle_id="com.example.spaces")
+ local = machine.bundle("Applications/CuaDriverLocal.app", bundle_id="com.trycua.driver.local")
+ bystanders = [machine.spawn(other_app), machine.spawn(local)]
+ machine._write(machine.bin / "uname", "echo Darwin")
+ machine._write(machine.bin / "launchctl", "exit 0")
+
+ result = machine.common_shell("stop_cua_driver_daemons")
+
+ assert result.returncode == 0, result.stdout + result.stderr
+ for pid in bystanders:
+ assert alive(pid)
+ assert not (machine.root / "pkill.log").exists(), (
+ "macOS must not pkill by name: another app's helper may share the name cua-driver"
+ )
+
+
+def test_installer_survivor_note_names_the_pid(machine: Machine) -> None:
+ old = machine.bundle("tmp/CuaDriver.app")
+ stray = machine.spawn(old)
+ machine._write(machine.bin / "uname", "echo Darwin")
+
+ result = machine.common_shell("show_cua_driver_daemon_survivors")
+
+ assert f"(pid: {stray})" in result.stdout
+
+
+def test_a_short_lived_stop_helper_process_is_not_reported_as_a_survivor(machine: Machine) -> None:
+ """`cua-driver --expected-pid N stop` re-executes itself; it is not a daemon left behind."""
+ old = machine.bundle("tmp/CuaDriver.app")
+ helper = machine.spawn(old) # exits by itself in ~1s, like the stop helper chain
+ machine.spawn_exit_after(helper, 1)
+ machine._write(machine.bin / "uname", "echo Darwin")
+
+ result = machine.common_shell("show_cua_driver_daemon_survivors", CUA_DRIVER_STOP_TIMEOUT="4")
+
+ assert result.stdout == ""
+ assert machine.wait_dead(helper)
+
+
+def test_uninstaller_waits_for_a_short_lived_helper_before_failing(machine: Machine) -> None:
+ old = machine.bundle("Downloads/CuaDriver.app")
+ helper = machine.spawn(old)
+ machine.spawn_exit_after(helper, 1)
+
+ result = machine.uninstall_shell(
+ "CUA_DRIVER_STOP_TIMEOUT=4\nverify_release_daemon_absent"
+ )
+
+ assert result.returncode == 0, result.stdout + result.stderr
+
+
+def _function_body(script: Path, name: str) -> str:
+ match = re.search(rf"^{name}\(\) \{{\n.*?^\}}\n", script.read_text(), re.S | re.M)
+ assert match, f"{name} missing from {script.name}"
+ return match.group(0)
+
+
+ "name",
+ [
+ "cua_driver_plist_string",
+ "cua_driver_bundle_of_command",
+ "cua_driver_bundle_is_release",
+ "cua_driver_ancestor_pids",
+ "cua_driver_run_bounded",
+ ],
+)
+def test_uninstall_copy_of_each_shared_helper_has_not_drifted(name: str) -> None:
+ """uninstall.sh runs standalone (curl | bash), so it carries verbatim copies."""
+ assert _function_body(UNINSTALL, name) == _function_body(COMMON, name)
diff --git a/libs/cua-driver/scripts/tests/test_unregister_other_copies.py b/libs/cua-driver/scripts/tests/test_unregister_other_copies.py
new file mode 100644
index 0000000000..b6e9f487ee
--- /dev/null
+++ b/libs/cua-driver/scripts/tests/test_unregister_other_copies.py
@@ -0,0 +1,282 @@
+"""After an install, macOS must know exactly one Cua Driver: the installed one.
+
+`open -a CuaDriver`, a bundle-id lookup and System Settings resolve to whichever
+registered copy macOS prefers, so an old release in the Trash or a benchmark
+folder gets launched and labels the permission rows ("CuaDriver-0.34.0"). The
+installer parses `lsregister -dump` and `mdfind`, unregisters every other
+com.trycua.driver bundle with `lsregister -u`, prints one line, and never
+deletes a file. The real lsregister is never called: a fake records its argv.
+"""
+
+from __future__ import annotations
+
+import os
+import subprocess
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[4]
+COMMON = ROOT / "libs/cua-driver/scripts/_install-common.sh"
+
+SEPARATOR = "-" * 80
+
+BLOCK = """{sep}
+bundle id: {name} (0xf0ac)
+container: / (0x4)
+path: {path} (0x10268)
+name: {name}
+identifier: {identifier}
+version: 0.36 ({{length = 32, bytes = 0x0000}})
+codeInfoID: {identifier}
+executable: Contents/MacOS/cua-driver
+infoDictionary: 14 values (144140 (0x2330c))
+ {{
+ CFBundleIdentifier = "{identifier}";
+ }}
+"""
+
+
+def dump(*entries: tuple[str, str, str]) -> str:
+ return "".join(
+ BLOCK.format(sep=SEPARATOR, name=name, path=path, identifier=identifier)
+ for name, path, identifier in entries
+ ) + SEPARATOR + "\n"
+
+
+class Fixture:
+ def __init__(self, root: Path) -> None:
+ self.root = root
+ self.bin = root / "bin"
+ self.bin.mkdir()
+ self.unregistered = root / "unregistered.log"
+ self.active = root / "Applications/CuaDriver.app"
+ self.active.mkdir(parents=True)
+
+ def app(self, relative: str) -> Path:
+ path = self.root / relative
+ (path / "Contents").mkdir(parents=True)
+ (path / "Contents/Info.plist").write_text("<plist/>", encoding="utf-8")
+ return path
+
+ def fake_lsregister(self, dump_text: str) -> Path:
+ dump_file = self.root / "dump.txt"
+ dump_file.write_text(dump_text, encoding="utf-8")
+ script = self.bin / "lsregister"
+ script.write_text(
+ "#!/bin/sh\n"
+ f'case "$1" in\n'
+ f' -dump) cat "{dump_file}" ;;\n'
+ f' -u) printf "%s\\n" "$2" >> "{self.unregistered}" ;;\n'
+ f' *) exit 2 ;;\nesac\n',
+ encoding="utf-8",
+ )
+ script.chmod(0o755)
+ return script
+
+ def fake_mdfind(self, *paths: Path) -> None:
+ script = self.bin / "mdfind"
+ lines = "".join(f'echo "{p}"\n' for p in paths)
+ script.write_text(f"#!/bin/sh\n{lines}", encoding="utf-8")
+ script.chmod(0o755)
+
+ def run(self, body: str, lsregister: Path | None) -> subprocess.CompletedProcess[str]:
+ env = {k: v for k, v in os.environ.items() if not k.startswith("CUA_DRIVER_")}
+ env["PATH"] = f"{self.bin}:/usr/bin:/bin"
+ if lsregister is not None:
+ env["CUA_DRIVER_LSREGISTER"] = str(lsregister)
+ return subprocess.run(
+ ["/bin/bash", "-c", f'source "{COMMON}"\n{body}'],
+ cwd=ROOT,
+ env=env,
+ text=True,
+ capture_output=True,
+ check=False,
+ timeout=60,
+ )
+
+ def unregistered_paths(self) -> list[str]:
+ if not self.unregistered.exists():
+ return []
+ return self.unregistered.read_text().splitlines()
+
+
+def fx(tmp_path: Path) -> Fixture:
+ return Fixture(tmp_path)
+
+
+def test_unregisters_every_other_copy_and_prints_one_line(fx: Fixture) -> None:
+ downloads = fx.app("Downloads/CuaDriver.app")
+ trash = fx.app(".Trash/CuaDriver.app")
+ bench = fx.app("bench folder/CuaDriver-0.34.0.app") # a path with spaces
+ ls = fx.fake_lsregister(
+ dump(
+ ("Cua Driver", str(fx.active), "com.trycua.driver"),
+ ("Cua Driver", str(downloads), "com.trycua.driver"),
+ ("CuaDriver", str(trash), "com.trycua.driver"),
+ ("CuaDriver-0.34.0", str(bench), "com.trycua.driver"),
+ )
+ )
+ fx.fake_mdfind()
+
+ result = fx.run(f'unregister_other_cua_driver_copies "{fx.active}"', ls)
+
+ assert result.returncode == 0, result.stderr
+ assert sorted(fx.unregistered_paths()) == sorted([str(downloads), str(trash), str(bench)])
+ lines = result.stdout.splitlines()
+ assert lines[0] == f"Found 3 old Cua Driver copies; macOS will now only use {fx.active}"
+ # Honest about the files: they are still where the user put them.
+ assert lines[1].startswith("Their files were left in place")
+ for path in (downloads, trash, bench):
+ assert str(path) in lines[1]
+ assert len(lines) == 2
+ # `lsregister -u` forgets a copy; the files stay where the user put them.
+ for path in (downloads, trash, bench, fx.active):
+ assert path.exists()
+
+
+def test_one_copy_reads_naturally(fx: Fixture) -> None:
+ old = fx.app("tmp/CuaDriver.app")
+ ls = fx.fake_lsregister(
+ dump(
+ ("Cua Driver", str(fx.active), "com.trycua.driver"),
+ ("Cua Driver", str(old), "com.trycua.driver"),
+ )
+ )
+ fx.fake_mdfind()
+
+ result = fx.run(f'unregister_other_cua_driver_copies "{fx.active}"', ls)
+
+ assert result.stdout.splitlines()[0] == (
+ f"Found 1 old Cua Driver copy; macOS will now only use {fx.active}"
+ )
+
+
+def test_copies_found_only_by_spotlight_are_unregistered_too(fx: Fixture) -> None:
+ indexed = fx.app("Library/Application Support/images/CuaDriver.app")
+ ls = fx.fake_lsregister(dump(("Cua Driver", str(fx.active), "com.trycua.driver")))
+ fx.fake_mdfind(fx.active, indexed)
+
+ result = fx.run(f'unregister_other_cua_driver_copies "{fx.active}"', ls)
+
+ assert fx.unregistered_paths() == [str(indexed)]
+ assert "Found 1 old Cua Driver copy" in result.stdout
+
+
+def test_other_bundle_ids_and_the_installed_copy_are_left_alone(fx: Fixture) -> None:
+ local = fx.app("Applications/CuaDriverLocal.app")
+ spaces = fx.app("Applications/Cua Spaces.app")
+ alias = fx.root / "alias"
+ alias.symlink_to(fx.active) # the installed copy under another name
+ ls = fx.fake_lsregister(
+ dump(
+ ("Cua Driver", str(fx.active), "com.trycua.driver"),
+ ("Cua Driver", str(alias), "com.trycua.driver"),
+ ("Cua Driver Local", str(local), "com.trycua.driver.local"),
+ ("Cua Spaces", str(spaces), "com.cua.spaces"),
+ )
+ )
+ fx.fake_mdfind()
+
+ result = fx.run(f'unregister_other_cua_driver_copies "{fx.active}"', ls)
+
+ assert fx.unregistered_paths() == []
+ assert result.stdout == ""
+
+
+def test_no_other_copies_prints_nothing(fx: Fixture) -> None:
+ ls = fx.fake_lsregister(dump(("Cua Driver", str(fx.active), "com.trycua.driver")))
+ fx.fake_mdfind(fx.active)
+
+ result = fx.run(f'unregister_other_cua_driver_copies "{fx.active}"', ls)
+
+ assert result.returncode == 0
+ assert result.stdout == ""
+
+
+def test_a_failed_unregister_warns_but_never_fails_the_install(fx: Fixture) -> None:
+ old = fx.app("Downloads/CuaDriver.app")
+ ls = fx.fake_lsregister(
+ dump(
+ ("Cua Driver", str(fx.active), "com.trycua.driver"),
+ ("Cua Driver", str(old), "com.trycua.driver"),
+ )
+ )
+ fx.fake_mdfind()
+ ls.write_text("#!/bin/sh\n[ \"$1\" = -dump ] && cat " + str(fx.root / "dump.txt") + "\nexit 1\n")
+
+ result = fx.run(f'unregister_other_cua_driver_copies "{fx.active}"', ls)
+
+ assert result.returncode == 0
+ assert f"could not unregister the old Cua Driver copy at {old}" in result.stderr
+
+
+def test_missing_lsregister_is_a_quiet_no_op(fx: Fixture) -> None:
+ result = fx.run(
+ f'unregister_other_cua_driver_copies "{fx.active}"', fx.root / "does-not-exist"
+ )
+
+ assert result.returncode == 0
+ assert result.stdout == "" and result.stderr == ""
+
+
+def test_installer_runs_the_cleanup_after_the_swap_commits() -> None:
+ installer = (ROOT / "libs/cua-driver/scripts/_install-rust.sh").read_text()
+
+ commit = installer.index("MACOS_APP_INSTALL_COMMITTED=1")
+ cleanup = installer.index('unregister_other_cua_driver_copies "$APP_DEST"')
+ reset = installer.index("macos_reset_tcc_after_requirement_change", commit)
+ # After the new bundle is registered and committed, before any permission
+ # reset resolves the bundle id through LaunchServices.
+ assert commit < cleanup < reset
+ # A tarball loader failure must not abort the install either.
+ assert "unregister_other_cua_driver_copies() { :; }" in installer
+
+
+def test_installer_forgets_the_unpacked_app_before_deleting_its_temp_dir() -> None:
+ installer = (ROOT / "libs/cua-driver/scripts/_install-rust.sh").read_text()
+
+ cleanup = installer[installer.index("cleanup_on_exit() {"):]
+ cleanup = cleanup[: cleanup.index("\n}\n")]
+ forget = cleanup.index("forget_staged_macos_app")
+ delete = cleanup.index('rm -rf "$TMP_DIR"')
+ assert forget < delete
+ helper = installer[installer.index("forget_staged_macos_app() {"):]
+ helper = helper[: helper.index("\n}\n")]
+ assert '"$lsregister" -u "$SRC_APP"' in helper
+
+
+def test_registrations_whose_files_are_gone_get_no_left_in_place_note(fx: Fixture) -> None:
+ gone = fx.root / "extracted-and-deleted/CuaDriver.app" # never created on disk
+ ls = fx.fake_lsregister(
+ dump(
+ ("Cua Driver", str(fx.active), "com.trycua.driver"),
+ ("Cua Driver", str(gone), "com.trycua.driver"),
+ )
+ )
+ fx.fake_mdfind()
+
+ result = fx.run(f'unregister_other_cua_driver_copies "{fx.active}"', ls)
+
+ assert fx.unregistered_paths() == [str(gone)]
+ assert result.stdout.splitlines() == [
+ f"Found 1 old Cua Driver copy; macOS will now only use {fx.active}"
+ ]
+
+
+def test_many_leftover_copies_are_summarised(fx: Fixture) -> None:
+ olds = [fx.app(f"old{i}/CuaDriver.app") for i in range(5)]
+ ls = fx.fake_lsregister(
+ dump(
+ ("Cua Driver", str(fx.active), "com.trycua.driver"),
+ *[("Cua Driver", str(path), "com.trycua.driver") for path in olds],
+ )
+ )
+ fx.fake_mdfind()
+
+ result = fx.run(f'unregister_other_cua_driver_copies "{fx.active}"', ls)
+
+ lines = result.stdout.splitlines()
+ assert lines[0].startswith("Found 5 old Cua Driver copies")
+ assert lines[1].endswith("and 2 more")
diff --git a/libs/cua-driver/scripts/uninstall.sh b/libs/cua-driver/scripts/uninstall.sh
index cde1b3160d..976d6aab07 100755
--- a/libs/cua-driver/scripts/uninstall.sh
+++ b/libs/cua-driver/scripts/uninstall.sh
@@ -222,9 +222,9 @@ daemon_signal_if_current() {
}
daemon_wait_for_exit() {
- local pid="$1" attempts=0
+ local pid="$1" attempts=0 limit=$(( ${CUA_DRIVER_STOP_TIMEOUT:-5} * 10 ))
while daemon_pid_alive "$pid"; do
- [[ "$attempts" -lt 20 ]] || return 1
+ [[ "$attempts" -lt "$limit" ]] || return 1
sleep 0.1 2>/dev/null || sleep 1 || true
attempts=$((attempts + 1))
done
@@ -246,6 +246,85 @@ daemon_process_identity() {
printf '%s' "$identity"
}
+# A daemon can run from ANY copy of CuaDriver.app (an old release in ~/Downloads, the
+# Trash, a benchmark folder), not only the one this script removes. These three
+# helpers identify a Cua Driver process by its bundle id instead of its path. They
+# are copied verbatim from _install-common.sh (a test keeps the copies identical)
+# because this script must work standalone via curl | bash.
+CUA_DRIVER_RELEASE_BUNDLE_ID="com.trycua.driver"
+
+cua_driver_plist_string() {
+ local plist="$1" key="$2" value=""
+ [ -f "$plist" ] || return 1
+ if [ -x /usr/libexec/PlistBuddy ]; then
+ value="$(/usr/libexec/PlistBuddy -c "Print :$key" "$plist" 2>/dev/null)" || value=""
+ fi
+ if [ -z "$value" ]; then
+ value="$(awk -v key="$key" '
+ function text(line) { sub(".*<string>", "", line); sub("</string>.*", "", line); return line }
+ index($0, "<key>" key "</key>") {
+ if ($0 ~ /<string>/) { print text($0); exit }
+ want = 1; next
+ }
+ want && /<string>/ { print text($0); exit }
+ want && /<key>/ { exit }
+ ' "$plist" 2>/dev/null)" || value=""
+ fi
+ [ -n "$value" ] || return 1
+ printf '%s' "$value"
+}
+
+cua_driver_bundle_of_command() {
+ local command_line="$1" bundle
+ case "$command_line" in
+ */Contents/MacOS/cua-driver|*/Contents/MacOS/cua-driver\ *) ;;
+ *) return 1 ;;
+ esac
+ bundle="${command_line%%/Contents/MacOS/cua-driver*}"
+ case "$bundle" in
+ /*.app) printf '%s' "$bundle" ;;
+ *) return 1 ;;
+ esac
+}
+
+cua_driver_bundle_is_release() {
+ local bundle="$1" id=""
+ id="$(cua_driver_plist_string "$bundle/Contents/Info.plist" CFBundleIdentifier)" || id=""
+ if [ -n "$id" ]; then
+ [ "$id" = "$CUA_DRIVER_RELEASE_BUNDLE_ID" ]
+ return
+ fi
+ case "${bundle##*/}" in
+ CuaDriver.app|CuaDriver-*.app|"CuaDriver "*.app) return 0 ;;
+ *) return 1 ;;
+ esac
+}
+
+cua_driver_ancestor_pids() {
+ local pid="$$" depth=0 parent
+ while [ -n "$pid" ] && [ "$pid" -gt 1 ] 2>/dev/null && [ "$depth" -lt 32 ]; do
+ printf '%s\n' "$pid"
+ parent="$(ps -o ppid= -p "$pid" 2>/dev/null | tr -d '[:space:]')" || break
+ [ -n "$parent" ] || break
+ pid="$parent"
+ depth=$((depth + 1))
+ done
+}
+
+cua_driver_run_bounded() {
+ local limit="$1" child tenths
+ shift
+ "$@" >/dev/null 2>&1 &
+ child=$!
+ tenths=$((limit * 10))
+ while kill -0 "$child" 2>/dev/null && [ "$tenths" -gt 0 ]; do
+ sleep 0.1 2>/dev/null || sleep 1
+ tenths=$((tenths - 1))
+ done
+ kill "$child" 2>/dev/null || true
+ wait "$child" 2>/dev/null || true
+}
+
daemon_identity_matches_install() {
case "$1" in
"$APP_BUNDLE"/Contents/MacOS/cua-driver|"$APP_BUNDLE"/Contents/MacOS/cua-driver[[:space:]]*|\
@@ -255,8 +334,12 @@ daemon_identity_matches_install() {
"$HOME_DIR"/packages/releases/*/cua-driver|"$HOME_DIR"/packages/releases/*/cua-driver[[:space:]]*|\
"$LEGACY_HOME_DIR"/packages/current/cua-driver|"$LEGACY_HOME_DIR"/packages/current/cua-driver[[:space:]]*|\
"$LEGACY_HOME_DIR"/packages/releases/*/cua-driver|"$LEGACY_HOME_DIR"/packages/releases/*/cua-driver[[:space:]]*) return 0 ;;
- *) return 1 ;;
esac
+ # Not one of our install paths: still ours when it runs a com.trycua.driver
+ # app bundle from anywhere else.
+ local bundle
+ bundle="$(cua_driver_bundle_of_command "$1")" || return 1
+ cua_driver_bundle_is_release "$bundle"
}
daemon_pid_is_release() {
@@ -268,9 +351,11 @@ daemon_pid_is_release() {
release_daemon_fallback_pids() {
command -v pgrep >/dev/null 2>&1 || return 2
command -v ps >/dev/null 2>&1 || return 2
- local uid pid identity candidates="" pgrep_status=0
+ local uid pid identity candidates="" pgrep_status=0 ancestors
uid="$(id -u 2>/dev/null || true)"
[[ "$uid" =~ ^[0-9]+$ ]] || return 2
+ # Never select this script or the process that started it.
+ ancestors="$(cua_driver_ancestor_pids)"
candidates="$(pgrep -U "$uid" -f '(^|[[:space:]/])cua-driver([[:space:]]|$)' 2>/dev/null)" || pgrep_status=$?
case "$pgrep_status" in
@@ -282,6 +367,7 @@ release_daemon_fallback_pids() {
while IFS= read -r pid; do
[[ -n "$pid" ]] || continue
[[ "$pid" =~ ^[1-9][0-9]*$ ]] || return 2
+ printf '%s\n' "$ancestors" | grep -qx "$pid" && continue
identity="$(daemon_process_identity "$pid" 2>/dev/null)" || return 2
if daemon_identity_matches_install "$identity"; then
printf '%s\n' "$pid"
@@ -290,33 +376,96 @@ release_daemon_fallback_pids() {
}
verify_release_daemon_absent() {
- local pids="" status=0
+ local pids="" status=0 waited=0 limit=$(( ${CUA_DRIVER_STOP_TIMEOUT:-5} * 2 ))
+ while :; do
+ status=0
+ pids="$(release_daemon_fallback_pids 2>/dev/null)" || status=$?
+ if [[ "$status" != "0" ]]; then
+ printf 'daemon_stop_incomplete: process inspection failed while verifying release daemon shutdown.\n' >&2
+ return 1
+ fi
+ [[ -n "$pids" ]] || return 0
+ # A stop request starts short-lived cua-driver processes of its own (the
+ # CLI re-executes itself); give them a moment before failing.
+ [[ "$waited" -lt "$limit" ]] || break
+ sleep 0.5 2>/dev/null || sleep 1
+ waited=$((waited + 1))
+ done
+ printf 'daemon_stop_incomplete: Cua Driver process(es) still running after SIGTERM and SIGKILL (pid: %s).\n' \
+ "$(printf '%s' "$pids" | tr '\n' ' ' | sed 's/ *$//')" >&2
+ return 1
+}
+
+# Stop every Cua Driver process of this user that is not the pid-file daemon:
+# daemons started from another copy of the app, and extra instances. Each gets,
+# in order, a graceful stop request through its own bundle's CLI (or the trusted
+# installed helper), SIGTERM, then SIGKILL, with CUA_DRIVER_STOP_TIMEOUT seconds
+# (default 5) between steps. A pid is re-identified and its start time compared
+# before every signal, so a recycled pid is never signalled. Other users'
+# processes and other apps (any other bundle id) are never selected.
+stop_stray_release_daemons() {
+ local pids="" status=0 pid identity bundle version label generation helper how
pids="$(release_daemon_fallback_pids 2>/dev/null)" || status=$?
- if [[ "$status" != "0" ]]; then
- printf 'daemon_stop_incomplete: process inspection failed while verifying release daemon shutdown.\n' >&2
- return 1
- fi
- if [[ -n "$pids" ]]; then
- printf 'daemon_stop_incomplete: release cua-driver process remains but cannot be safely classified or signalled.\n' >&2
- return 1
- fi
+ # Inspection failures are reported (and fail closed) by verify_release_daemon_absent.
+ [[ "$status" == "0" && -n "$pids" ]] || return 0
+ while IFS= read -r pid; do
+ [[ -n "$pid" ]] || continue
+ daemon_pid_alive "$pid" || continue
+ identity="$(daemon_process_identity "$pid" 2>/dev/null)" || continue
+ generation="$(daemon_process_generation "$pid" 2>/dev/null)" || continue
+ bundle="$(cua_driver_bundle_of_command "$identity" || true)"
+ version=""
+ [[ -z "$bundle" ]] || version="$(cua_driver_plist_string "$bundle/Contents/Info.plist" CFBundleShortVersionString || true)"
+ label="pid $pid, ${version:+version $version, }${bundle:-$identity}"
+ how=""
+
+ helper="${bundle:+$bundle/Contents/MacOS/cua-driver}"
+ [[ -n "$helper" && -x "$helper" ]] || helper="${DAEMON_STOP_HELPER:-}"
+ if [[ -n "$helper" && -x "$helper" ]] && daemon_pid_matches_generation "$pid" "$generation"; then
+ cua_driver_run_bounded "${CUA_DRIVER_STOP_TIMEOUT:-5}" "$helper" --expected-pid "$pid" stop
+ if daemon_wait_for_exit "$pid"; then how="a graceful stop request"; fi
+ fi
+ if [[ -z "$how" ]] && daemon_signal_if_current "$pid" "$generation" TERM; then
+ if daemon_wait_for_exit "$pid"; then how="SIGTERM"; fi
+ fi
+ if [[ -z "$how" ]] && daemon_signal_if_current "$pid" "$generation" KILL; then
+ if daemon_wait_for_exit "$pid"; then
+ how="SIGKILL after it ignored SIGTERM for ${CUA_DRIVER_STOP_TIMEOUT:-5}s"
+ fi
+ fi
+ if [[ -z "$how" ]] && ! daemon_pid_alive "$pid"; then how="its own exit"; fi
+ if [[ -n "$how" ]]; then
+ log "stopped Cua Driver ($label) with $how"
+ else
+ printf 'daemon_stop_incomplete: could not stop Cua Driver (%s); it is still running.\n' "$label" >&2
+ fi
+ done <<< "$pids"
+ return 0
}
stop_release_daemon() {
- local pid="" helper="${DAEMON_STOP_HELPER:-}" generation="" status=0 helper_stderr=""
+ local pid="" helper="${DAEMON_STOP_HELPER:-}" generation="" status=0 helper_stderr="" label="" bundle="" version=""
if [[ -n "${DAEMON_PID_FILE:-}" ]] \
&& pid="$(read_daemon_pid "$DAEMON_PID_FILE" 2>/dev/null)" \
&& daemon_pid_alive "$pid"; then
+ # Describe the daemon now: once it has exited there is nothing left to read.
+ label="$(daemon_process_identity "$pid" 2>/dev/null || true)"
+ bundle="$(cua_driver_bundle_of_command "$label" || true)"
+ if [[ -n "$bundle" ]]; then
+ version="$(cua_driver_plist_string "$bundle/Contents/Info.plist" CFBundleShortVersionString || true)"
+ label="$bundle"
+ fi
+ label="pid $pid, ${version:+version $version, }${label:-unknown path}"
daemon_pid_is_release "$pid" || status=$?
if [[ "$status" == "2" ]]; then
printf 'daemon_stop_incomplete: failed to identify live daemon pid %s safely.\n' "$pid" >&2
return 1
fi
- if [[ "$status" == "0" ]]; then
- [[ -n "$helper" && -x "$helper" ]] || {
- printf 'daemon_stop_incomplete: trusted installed cua-driver stop helper is unavailable for pid %s.\n' "$pid" >&2
- return 1
- }
+ if [[ "$status" == "0" ]] && [[ ! -n "$helper" || ! -x "$helper" ]]; then
+ # The installed copy is gone or was never the one running (the daemon
+ # belongs to another copy of the app): the signal sweep below handles it.
+ printf 'note: no trusted stop helper for pid %s; stopping it with signals.\n' "$pid" >&2
+ elif [[ "$status" == "0" ]]; then
generation="$(daemon_process_generation "$pid")" || {
printf 'daemon_stop_incomplete: failed to capture process generation for daemon pid %s.\n' "$pid" >&2
return 1
@@ -347,8 +496,10 @@ stop_release_daemon() {
fi
fi
fi
+ log "stopped Cua Driver daemon ($label)"
fi
fi
+ stop_stray_release_daemons
sleep 0.2 2>/dev/null || true
verify_release_daemon_absent
}
diff --git a/libs/cua-driver/tests/runners/macos-lume/README.md b/libs/cua-driver/tests/runners/macos-lume/README.md
index a3c8608fb9..ecc64a3657 100644
--- a/libs/cua-driver/tests/runners/macos-lume/README.md
+++ b/libs/cua-driver/tests/runners/macos-lume/README.md
@@ -261,7 +261,7 @@ observes the new grant:
```bash
~/.local/bin/cua-driver-local stop
-open -a CuaDriverLocal
+open /Applications/CuaDriverLocal.app
```
Then verify the daemon's own identity and the read-only status contract before
@@ -335,7 +335,7 @@ After seeding, restart `CuaDriverLocal.app` before checking permission status if
```bash
~/.local/bin/cua-driver-local stop
-open -a CuaDriverLocal
+open /Applications/CuaDriverLocal.app
```
If the VM sudo password is not the default `lume`, pass it without putting it
diff --git a/libs/cua/skills/cua-driver/EMBEDDING.md b/libs/cua/skills/cua-driver/EMBEDDING.md
index a00eba98be..f59c55b431 100644
--- a/libs/cua/skills/cua-driver/EMBEDDING.md
+++ b/libs/cua/skills/cua-driver/EMBEDDING.md
@@ -289,7 +289,7 @@ and about 980 ms at `2`. All ten read-backs (five per value) matched exactly.
| --------------------------------------------- | ----------------------------- | -------------------------------------- |
| Responsibility disclaim re-exec | ON (owns its TCC identity) | OFF (stays in the host's chain) |
| Tool execution process | `serve` daemon | host-spawned `serve --embedded` daemon |
-| Daemon auto-relaunch via `open -a CuaDriver` | Yes, when installed | Never (would leave the host's chain) |
+| Daemon auto-relaunch of the installed app | Yes, when installed | Never (would leave the host's chain) |
| TCC identity | `com.trycua.driver` | the host app |
| Permission prompts / startup gate | May prompt once | **Never prompts** |
| Settings → Privacy & Security entries | CuaDriver | your app only |
@@ -310,7 +310,7 @@ would treat it as its own responsible process: your user would get a _second_ pr
attributed to the driver binary, a second Settings entry, and capture/AX
would fail until that second grant. That is the exact experience embedding exists
to eliminate. Embedded mode short-circuits the disclaim re-exec
-(`responsibility.rs`) and the `open -a CuaDriver` daemon relaunch. MCP is
+(`responsibility.rs`) and the installed-app daemon relaunch. MCP is
always a proxy, so the embedded daemon remains the single process that checks
TCC and executes tools.
diff --git a/libs/cua/skills/cua-driver/MACOS.md b/libs/cua/skills/cua-driver/MACOS.md
index 10b24ed403..fdb117c17f 100644
--- a/libs/cua/skills/cua-driver/MACOS.md
+++ b/libs/cua/skills/cua-driver/MACOS.md
@@ -216,10 +216,11 @@ editor state.
1. `cua-driver` is on `$PATH` (`which cua-driver`). If not, point the
user at `scripts/install-local.sh` and stop.
-2. 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
+2. Start the daemon with `cua-driver permissions grant` (the
+ recommended form: it launches the installed CuaDriver.app by its
+ exact path through LaunchServices, so TCC attributes the process to
+ that app). `cua-driver serve &` also works;
+ the CLI auto-relaunches the installed app by path when it
detects a wrong-TCC context (any IDE-spawned shell: Claude Code,
Cursor, VS Code, Conductor). Verify with `cua-driver status`.
3. Run `cua-driver permissions status --json`. This
diff --git a/scripts/docs-generators/cli-specs/cua-driver.json b/scripts/docs-generators/cli-specs/cua-driver.json
index f7aaeb71ca..654ff9afff 100644
--- a/scripts/docs-generators/cli-specs/cua-driver.json
+++ b/scripts/docs-generators/cli-specs/cua-driver.json
@@ -1312,7 +1312,7 @@
{
"abstract": "Run platform-aware diagnostic probes.",
"arguments": [],
- "discussion": "Exit code is non-zero when any probe is an error.",
+ "discussion": "Exit code is non-zero when any probe is an error. On macOS it warns about other copies of CuaDriver.app that macOS can launch instead of the installed one, and about permission rows tied to a different path or version.",
"examples": [
{
"command": "cua-driver doctor",
@@ -1321,6 +1321,10 @@
{
"command": "cua-driver doctor --json",
"description": "Emit the probe report as JSON"
+ },
+ {
+ "command": "cua-driver doctor --fix",
+ "description": "macOS: make macOS forget extra copies of the app (deletes no files)"
}
],
"flags": [
@@ -1329,6 +1333,12 @@
"help": "Emit the probe report as JSON.",
"name": "json",
"short_name": null
+ },
+ {
+ "default_value": false,
+ "help": "macOS: make LaunchServices forget every other copy of CuaDriver.app. No files are deleted.",
+ "name": "fix",
+ "short_name": null
}
],
"name": "doctor",