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): tie Claude MCP cleanup to actual release removal

injaneityff770f5d5211
diff --git a/.github/workflows/ci-test-scripts.yml b/.github/workflows/ci-test-scripts.yml
index b91ac65309..2f2be28d3a 100644
--- a/.github/workflows/ci-test-scripts.yml
+++ b/.github/workflows/ci-test-scripts.yml
@@ -97,6 +97,31 @@ permissions:
contents: read
jobs:
+ macos-uninstall:
+ name: macOS uninstall regressions
+ runs-on: macos-26
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ persist-credentials: false
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.11"
+ - name: Install test dependency
+ run: python -m pip install pytest
+ # Discover every uninstall module, including ownership, failure ordering,
+ # daemon/autostart, local-install, and Windows guidance contracts. Other
+ # script tooling (such as Lume runner tests) remains in the Ubuntu suite.
+ - name: Test uninstall contracts, system Bash syntax, and script encoding
+ run: |
+ python -m pytest -v -p no:cacheprovider \
+ libs/cua-driver/scripts/tests/test_uninstall_*.py \
+ libs/cua-driver/scripts/tests/test_installer_bash32_syntax.py \
+ .github/scripts/tests/test_driver_script_encoding.py
+ - name: Test Computer History purge during uninstall
+ run: /bin/bash libs/cua-driver/scripts/tests/uninstall-history-purge-test.sh
+
windows-uninstall:
runs-on: windows-latest
timeout-minutes: 5
diff --git a/libs/cua-driver/scripts/tests/test_uninstall_claude_mcp.py b/libs/cua-driver/scripts/tests/test_uninstall_claude_mcp.py
index ac7828ca70..953f13ec5e 100644
--- a/libs/cua-driver/scripts/tests/test_uninstall_claude_mcp.py
+++ b/libs/cua-driver/scripts/tests/test_uninstall_claude_mcp.py
@@ -78,6 +78,9 @@ def _run(
claude_json.write_text(json.dumps(expanded), encoding="utf-8")
env = os.environ.copy()
+ for key in list(env):
+ if key.startswith("CUA_DRIVER_"):
+ env.pop(key)
env.update({"HOME": str(home), "PATH": f"{fake_bin}:/usr/bin:/bin"})
result = subprocess.run(
["/bin/bash", str(UNINSTALL)],
@@ -100,7 +103,8 @@ def _project_servers(config: dict, project: str = "/work/repo") -> set[str]:
def _claude_removals(tmp_path: Path) -> set[str]:
- calls = (tmp_path / "claude-calls").read_text(encoding="utf-8").splitlines()
+ path = tmp_path / "claude-calls"
+ calls = path.read_text(encoding="utf-8").splitlines() if path.exists() else []
return {
parts[2]
for parts in (call.split() for call in calls)
@@ -177,7 +181,7 @@ def test_shared_name_without_command_is_preserved(tmp_path: Path) -> None:
assert _user_servers(config) == {"cua-computer-use"}
-def test_legacy_name_is_removed_without_a_marker(tmp_path: Path) -> None:
+def test_legacy_name_without_live_target_is_preserved(tmp_path: Path) -> None:
config, _ = _run(
tmp_path,
{
@@ -191,7 +195,8 @@ def test_legacy_name_is_removed_without_a_marker(tmp_path: Path) -> None:
rust_marker=False,
)
- assert _user_servers(config) == set()
+ # A historical name is not current filesystem ownership evidence.
+ assert _user_servers(config) == {"cua-driver-rs"}
def test_shared_release_name_is_kept_without_rust_marker(tmp_path: Path) -> None:
@@ -271,7 +276,7 @@ def test_custom_bin_launcher_is_removed_when_it_resolves_into_release(tmp_path:
assert _user_servers(config) == set()
-def test_missing_canonical_launcher_is_safe_fallback(tmp_path: Path) -> None:
+def test_missing_canonical_launcher_is_preserved_as_unproven(tmp_path: Path) -> None:
config, _ = _run(
tmp_path,
{
@@ -286,7 +291,8 @@ def test_missing_canonical_launcher_is_safe_fallback(tmp_path: Path) -> None:
create_canonical_launcher=False,
)
- assert _user_servers(config) == set()
+ # Deliberately narrower than the contributor fallback: no live target.
+ assert _user_servers(config) == {"cua-computer-use"}
def test_foreign_dangling_canonical_launcher_is_preserved(tmp_path: Path) -> None:
@@ -371,10 +377,10 @@ def test_scope_ownership_does_not_leak_to_same_name_in_project(tmp_path: Path) -
assert _user_servers(config) == set()
assert _project_servers(config) == {"cua-computer-use"}
- assert _claude_removals(tmp_path) == {"cua-driver-rs"}
+ assert _claude_removals(tmp_path) == set()
-def test_cli_fallback_only_uses_unambiguous_legacy_name(tmp_path: Path) -> None:
+def test_no_name_only_cli_fallback(tmp_path: Path) -> None:
_run(
tmp_path,
{"mcpServers": {}},
@@ -382,7 +388,7 @@ def test_cli_fallback_only_uses_unambiguous_legacy_name(tmp_path: Path) -> None:
with_claude_cli=True,
)
- assert _claude_removals(tmp_path) == {"cua-driver-rs"}
+ assert _claude_removals(tmp_path) == set()
def test_shared_name_never_enters_cli_fallback_after_json_scrub(tmp_path: Path) -> None:
@@ -400,7 +406,7 @@ def test_shared_name_never_enters_cli_fallback_after_json_scrub(tmp_path: Path)
with_claude_cli=True,
)
- assert _claude_removals(tmp_path) == {"cua-driver-rs"}
+ assert _claude_removals(tmp_path) == set()
def test_windows_guidance_uses_registered_user_scope() -> None:
diff --git a/libs/cua-driver/scripts/tests/test_uninstall_claude_mcp_safety.py b/libs/cua-driver/scripts/tests/test_uninstall_claude_mcp_safety.py
index 9fc29f356f..d4b48f4cd8 100644
--- a/libs/cua-driver/scripts/tests/test_uninstall_claude_mcp_safety.py
+++ b/libs/cua-driver/scripts/tests/test_uninstall_claude_mcp_safety.py
@@ -6,6 +6,10 @@ import json
import os
from pathlib import Path
import subprocess
+import shlex
+import sys
+
+import pytest
REPO_ROOT = Path(__file__).resolve().parents[4]
@@ -37,14 +41,28 @@ def _release_fixture(tmp_path: Path, *, pgrep_body: str = "exit 1") -> tuple[Pat
_executable(fake_bin / "pkill")
_executable(fake_bin / "systemctl")
+ # Preserve real rm semantics, but never allow a fixture to remove host state.
+ _executable(fake_bin / "rm", f"exec {shlex.quote(sys.executable)} {shlex.quote(str(fake_bin / 'safe_rm.py'))} \"$@\"")
+ (fake_bin / "safe_rm.py").write_text(
+ "import os, pathlib, sys\n"
+ f"root = pathlib.Path({str(tmp_path.resolve())!r})\n"
+ "for arg in sys.argv[1:]:\n"
+ " if arg.startswith('-'): continue\n"
+ " path = pathlib.Path(arg)\n"
+ " assert root == path.parent.resolve() or root in path.parent.resolve().parents, arg\n"
+ "os.execv('/bin/rm', ['/bin/rm', *sys.argv[1:]])\n"
+ )
env = os.environ.copy()
+ for key in list(env):
+ if key.startswith("CUA_DRIVER_"):
+ env.pop(key)
env.update({"HOME": str(home), "PATH": f"{fake_bin}:/usr/bin:/bin"})
return home, release_binary, launcher, env
-def _run(env: dict[str, str]) -> subprocess.CompletedProcess[str]:
+def _run(env: dict[str, str], *args: str) -> subprocess.CompletedProcess[str]:
return subprocess.run(
- ["/bin/bash", str(UNINSTALL)],
+ ["/bin/bash", str(UNINSTALL), *args],
cwd=REPO_ROOT,
env=env,
text=True,
@@ -91,3 +109,221 @@ def test_malformed_claude_config_fails_before_release_or_daemon_mutation(tmp_pat
assert launcher.is_symlink()
assert not pgrep_marker.exists(), "daemon inspection ran before Claude config validation"
assert "cua-driver uninstalled." not in result.stdout
+
+
+def _config(home: Path, servers: dict) -> Path:
+ path = home / ".claude.json"
+ path.write_text(json.dumps({"mcpServers": servers}))
+ return path
+
+
[email protected]("owned", [False, True])
+def test_original_symlink_dotdot_command_controls_ownership(tmp_path: Path, owned: bool) -> None:
+ home, release, _, env = _release_fixture(tmp_path)
+ normal, other = tmp_path / "normal", tmp_path / "other"
+ normal.mkdir()
+ (other / "child").mkdir(parents=True)
+ (normal / "jump").symlink_to(other / "child", target_is_directory=True)
+ foreign = (normal if owned else other) / "cua-driver"
+ _executable(foreign)
+ ((other if owned else normal) / "cua-driver").symlink_to(release)
+ command = str(normal / "jump") + "/../cua-driver"
+ assert Path(command).samefile(release if owned else foreign)
+ config = _config(home, {"entry": {"command": command}})
+ result = _run(env)
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert ("entry" in json.loads(config.read_text())["mcpServers"]) is not owned
+ assert foreign.exists()
+ assert not release.exists()
+ assert Path(command).exists() is not owned
+
+
[email protected]("purge", [False, True])
+def test_selected_home_symlink_matches_actual_removal(tmp_path: Path, purge: bool) -> None:
+ home, _, launcher, env = _release_fixture(tmp_path)
+ actual = tmp_path / "actual-home"
+ release = actual / "packages/current/cua-driver"
+ _executable(release)
+ selected = tmp_path / "selected-home"
+ selected.symlink_to(actual, target_is_directory=True)
+ env["CUA_DRIVER_HOME"] = str(selected)
+ config = _config(home, {"entry": {"command": str(release)}})
+ result = _run(env, *(('--purge',) if purge else ()))
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert ("entry" in json.loads(config.read_text())["mcpServers"]) is purge
+ assert release.exists() is purge
+ assert selected.is_symlink() is not purge
+ assert launcher.exists() # the other installation remains
+
+
+def test_linux_does_not_claim_app_or_foreign_legacy_name(tmp_path: Path) -> None:
+ home, _, _, env = _release_fixture(tmp_path)
+ foreign = tmp_path / "foreign"
+ _executable(foreign)
+ original = {
+ "cua-driver-rs": {"command": str(foreign)},
+ "mac-release": {"command": "/Applications/CuaDriver.app/Contents/MacOS/cua-driver"},
+ "legacy-app": {"command": "/Applications/CuaDriverRs.app/Contents/MacOS/cua-driver"},
+ }
+ config = _config(home, original)
+ result = _run(env)
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert json.loads(config.read_text())["mcpServers"] == original
+ assert foreign.exists()
+
+
[email protected]("operation", ["backup", "replace"])
+def test_config_write_failure_preserves_release(tmp_path: Path, operation: str) -> None:
+ home, release, launcher, env = _release_fixture(tmp_path)
+ config = _config(home, {"entry": {"command": str(release)}})
+ before = config.read_bytes()
+ fake_bin = tmp_path / "fake-bin"
+ # Fault injection stays at the existing python process seam, not in production.
+ wrapper = fake_bin / "python3"
+ wrapper.write_text(
+ f"#!{sys.executable}\n"
+ "import os, shutil, sys\n"
+ "if sys.argv[1:2] == ['-']: sys.argv = sys.argv[1:]\n"
+ "def fail(*args, **kwargs): raise OSError('fixture write failure')\n"
+ + ("shutil.copyfileobj = fail\nshutil.copy2 = fail\n" if operation == "backup" else "os.replace = fail\n")
+ + "exec(compile(sys.stdin.read(), '<uninstaller>', 'exec'))\n"
+ )
+ wrapper.chmod(0o755)
+ result = _run(env)
+ assert result.returncode != 0
+ assert "fixture write failure" in result.stderr
+ assert config.read_bytes() == before
+ assert release.exists() and launcher.exists()
+ assert not list(home.glob(".claude.json.*.tmp"))
+ backups = list(home.glob(".claude.json.bak-*"))
+ if operation == "replace":
+ assert len(backups) == 1 and backups[0].read_bytes() == before
+
+
+def test_failed_history_purge_preserves_registration_and_launcher(tmp_path: Path) -> None:
+ home, release, launcher, env = _release_fixture(tmp_path)
+ _executable(release, "exit 1")
+ config = _config(home, {"entry": {"command": str(release)}})
+ before = config.read_bytes()
+ result = _run(env, "--purge")
+ assert result.returncode != 0
+ assert "history_purge_incomplete" in result.stderr
+ assert config.read_bytes() == before
+ assert release.exists() and launcher.exists()
+
+
+def test_lexical_root_is_not_alternative_ownership_evidence(tmp_path: Path) -> None:
+ home, release, _, env = _release_fixture(tmp_path)
+ foreign = tmp_path / "foreign/packages/cua-driver"
+ _executable(foreign)
+ (tmp_path / "foreign/child").mkdir()
+ jump = home / ".cua-driver/jump"
+ jump.symlink_to(tmp_path / "foreign/child", target_is_directory=True)
+ command = str(jump) + "/../packages/cua-driver"
+ assert Path(command).samefile(foreign)
+ config = _config(home, {"entry": {"command": command}})
+ before = config.read_bytes()
+ result = _run(env)
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert config.read_bytes() == before
+ assert Path(command).samefile(foreign)
+ assert not release.exists()
+
+
+def test_final_packages_symlink_is_unlinked_not_traversed(tmp_path: Path) -> None:
+ home, release, _, env = _release_fixture(tmp_path)
+ packages = home / ".cua-driver/packages"
+ external = tmp_path / "external-packages"
+ packages.rename(external)
+ packages.symlink_to(external, target_is_directory=True)
+ foreign = external / "current/cua-driver"
+ config = _config(home, {"entry": {"command": str(foreign)}})
+ before = config.read_bytes()
+ result = _run(env)
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert config.read_bytes() == before
+ assert foreign.exists()
+ assert not packages.is_symlink()
+ assert not release.exists()
+
+
[email protected]("suffix", ["/", "/.", "/..", "/../.cua-driver"])
+def test_ambiguous_purge_operand_fails_before_mutation(tmp_path: Path, suffix: str) -> None:
+ marker = tmp_path / "process-inspection"
+ home, release, launcher, env = _release_fixture(tmp_path, pgrep_body=f"touch {marker}; exit 1")
+ config = _config(home, {"entry": {"command": str(release)}})
+ before = config.read_bytes()
+ env["CUA_DRIVER_HOME"] = str(home / ".cua-driver") + suffix
+ result = _run(env, "--purge")
+ assert result.returncode != 0
+ assert "unsafe release removal operand" in result.stderr
+ assert config.read_bytes() == before
+ assert release.exists() and launcher.exists()
+ assert not marker.exists()
+
+
+def test_original_missing_component_and_dangling_target_are_preserved(tmp_path: Path) -> None:
+ home, release, launcher, env = _release_fixture(tmp_path)
+ dangling = tmp_path / "dangling"
+ dangling.symlink_to(release.parent / "missing")
+ original = {
+ "missing-step": {"command": str(release.parent / "missing") + "/../cua-driver"},
+ "owned-looking-dangling": {"command": str(dangling)},
+ "tilde": {"command": "~/.local/bin/cua-driver"},
+ }
+ config = _config(home, original)
+ before = config.read_bytes()
+ result = _run(env)
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert config.read_bytes() == before
+ assert not release.exists() and not launcher.exists()
+ assert dangling.is_symlink()
+
+
+def test_earlier_payload_cannot_break_later_removal_operand(tmp_path: Path) -> None:
+ home, release, _, env = _release_fixture(tmp_path)
+ external = tmp_path / "external-home"
+ executable = external / "packages/current/cua-driver"
+ _executable(executable)
+ bridge = release.parents[1] / "bridge"
+ bridge.symlink_to(external, target_is_directory=True)
+ (home / ".cua-driver-rs").symlink_to(bridge, target_is_directory=True)
+ config = _config(home, {"entry": {"command": str(executable)}})
+ result = _run(env)
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert json.loads(config.read_text())["mcpServers"] == {}
+ assert not executable.exists()
+ assert not release.exists()
+
+
+def test_trailing_newline_operand_never_selects_neighbor(tmp_path: Path) -> None:
+ home, _, _, env = _release_fixture(tmp_path)
+ selected = tmp_path / "selected\n"
+ neighbor = tmp_path / "selected"
+ intended = selected / "packages/current/cua-driver"
+ foreign = neighbor / "packages/current/cua-driver"
+ _executable(intended)
+ _executable(foreign)
+ env["CUA_DRIVER_HOME"] = str(selected)
+ config = _config(home, {"owned": {"command": str(intended)}, "foreign": {"command": str(foreign)}})
+ result = _run(env, "--purge")
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert json.loads(config.read_text())["mcpServers"] == {"foreign": {"command": str(foreign)}}
+ assert not intended.exists()
+ assert foreign.exists()
+
+
+def test_relative_home_ignores_inherited_cdpath(tmp_path: Path) -> None:
+ home, _, _, env = _release_fixture(tmp_path)
+ intended = tmp_path / "selected/packages/current/cua-driver"
+ foreign = tmp_path / "search/selected/packages/current/cua-driver"
+ _executable(intended)
+ _executable(foreign)
+ env.update({"CUA_DRIVER_HOME": "selected", "CDPATH": str(tmp_path / "search")})
+ config = _config(home, {"owned": {"command": str(intended)}, "foreign": {"command": str(foreign)}})
+ result = subprocess.run(["/bin/bash", str(UNINSTALL)], cwd=tmp_path, env=env,
+ text=True, capture_output=True, check=False)
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert json.loads(config.read_text())["mcpServers"] == {"foreign": {"command": str(foreign)}}
+ assert not intended.exists()
+ assert foreign.exists()
diff --git a/libs/cua-driver/scripts/tests/test_uninstall_windows_mcp_guidance.py b/libs/cua-driver/scripts/tests/test_uninstall_windows_mcp_guidance.py
index 9b35ccf217..7e169c84a9 100644
--- a/libs/cua-driver/scripts/tests/test_uninstall_windows_mcp_guidance.py
+++ b/libs/cua-driver/scripts/tests/test_uninstall_windows_mcp_guidance.py
@@ -16,3 +16,5 @@ def test_windows_guidance_requires_command_ownership_verification() -> None:
assert "cua-driver-local" in script
assert "claude mcp remove cua-computer-use -s user" in script
assert "claude mcp remove cua-driver-rs -s user" in script
+
+ assert "For the older cua-driver-rs name, verify the exact command ownership too" in script
diff --git a/libs/cua-driver/scripts/tests/uninstall-history-purge-test.sh b/libs/cua-driver/scripts/tests/uninstall-history-purge-test.sh
index c26646aba7..2c55f3dfbf 100644
--- a/libs/cua-driver/scripts/tests/uninstall-history-purge-test.sh
+++ b/libs/cua-driver/scripts/tests/uninstall-history-purge-test.sh
@@ -58,10 +58,10 @@ fi
grep -Fq history_purge_incomplete "$FIXTURE/linux-error.log"
purge_line="$(grep -n 'purge_macos_history \\' "$UNINSTALL" | tail -1 | cut -d: -f1)"
-remove_line="$(grep -n 'rm -rf "\$APP_BUNDLE"' "$UNINSTALL" | head -1 | cut -d: -f1)"
+remove_line="$(grep -n 'rm -rf -- "\$PAYLOAD"' "$UNINSTALL" | head -1 | cut -d: -f1)"
[[ "$purge_line" -lt "$remove_line" ]]
linux_purge_line="$(grep -n 'purge_linux_history "\$HISTORY_PURGE_HELPER"' "$UNINSTALL" | tail -1 | cut -d: -f1)"
-package_remove_line="$(grep -n 'rm -rf "\$HOME_DIR"' "$UNINSTALL" | head -1 | cut -d: -f1)"
+package_remove_line="$(grep -n 'rm -rf -- "\$HOME_PAYLOAD"' "$UNINSTALL" | head -1 | cut -d: -f1)"
[[ "$linux_purge_line" -lt "$package_remove_line" ]]
grep -Fq 'preserved encrypted Computer History' "$UNINSTALL"
diff --git a/libs/cua-driver/scripts/uninstall.ps1 b/libs/cua-driver/scripts/uninstall.ps1
index 12c17422b6..a11a04f4c5 100644
--- a/libs/cua-driver/scripts/uninstall.ps1
+++ b/libs/cua-driver/scripts/uninstall.ps1
@@ -514,7 +514,7 @@ Write-Host ""
Write-Host " If it points somewhere else (for example cua-driver-local or another"
Write-Host " side-by-side install), preserve it and use that installation's uninstaller."
Write-Host ""
-Write-Host " Installs from v0.2.13 and earlier used the release-specific name cua-driver-rs:"
+Write-Host " For the older cua-driver-rs name, verify the exact command ownership too:"
Write-Host ""
Write-Host " claude mcp remove cua-driver-rs -s user"
Write-Host ""
diff --git a/libs/cua-driver/scripts/uninstall.sh b/libs/cua-driver/scripts/uninstall.sh
index 74585aea7e..e22424f845 100755
--- a/libs/cua-driver/scripts/uninstall.sh
+++ b/libs/cua-driver/scripts/uninstall.sh
@@ -49,8 +49,9 @@
# the LaunchAgent/systemd unit, or current Rust telemetry state).
#
# Also scrubs release-owned Claude MCP registrations in ~/.claude.json.
-# Shared names are removed only when their command resolves into this release
-# package home/app bundle. Local, Swift, and side-by-side entries are kept.
+# Entries are removed only when their original absolute command resolves to a
+# live file in a directory selected for recursive deletion. Unproven entries
+# (including missing, relative and legacy-name-only commands) are kept.
#
# Revokes TCC grants on macOS by default (Accessibility + Screen Recording)
# so the next install prompts cleanly under the new signing identity. Pass
@@ -491,6 +492,141 @@ release_supervisor() {
esac
}
+# One standalone helper for preflight and fresh cleanup. Keep its heredoc out of
+# command substitution: macOS Bash 3.2 parses quotes differently inside $().
+claude_release_config() {
+ local mode="$1"
+ shift
+ if [[ ! -e "$CLAUDE_JSON" && ! -L "$CLAUDE_JSON" ]]; then
+ return 0
+ fi
+ if ! command -v python3 >/dev/null 2>&1; then
+ printf 'error: python3 is required to safely inspect Claude MCP ownership before uninstalling a release with %s; install python3 and retry. No release files were removed.\n' "$CLAUDE_JSON" >&2
+ return 1
+ fi
+ python3 - "$mode" "$CLAUDE_JSON" "$@" <<'PYCLAUDE'
+import io
+import json
+import os
+import shutil
+import stat
+import sys
+import tempfile
+
+
+def clean():
+ mode, path, *payloads = sys.argv[1:]
+ try:
+ with open(path, "rb") as handle:
+ original = handle.read()
+ data = json.loads(original.decode("utf-8"))
+ if not isinstance(data, dict):
+ raise ValueError("top-level value must be a JSON object")
+ except Exception as exc:
+ raise ValueError(f"could not read Claude config {path}: {exc}") from exc
+
+ # These exact operands also drive rm below. A final symlink is only
+ # unlinked; symlinks in its parent directories are traversed by rm.
+ roots = set()
+ for payload in payloads:
+ if not payload:
+ continue
+ try:
+ before = os.lstat(payload)
+ except FileNotFoundError:
+ continue
+ if not stat.S_ISDIR(before.st_mode):
+ continue
+ resolved = os.path.realpath(payload)
+ after = os.stat(resolved)
+ if resolved == os.path.sep or not os.path.samestat(before, after):
+ raise ValueError(f"unsafe release removal operand: {payload}")
+ roots.add(resolved)
+ if mode == "check":
+ return
+
+ def owned(server):
+ if not isinstance(server, dict):
+ return False
+ command = server.get("command")
+ if not isinstance(command, str) or not os.path.isabs(command):
+ return False
+ try:
+ # stat ORIGINAL spelling first: missing/../file cannot be repaired
+ # into an executable, nor can symlink/.. be collapsed lexically.
+ before = os.stat(command)
+ if not stat.S_ISREG(before.st_mode):
+ return False
+ resolved = os.path.realpath(command)
+ if not os.path.samestat(before, os.stat(resolved)):
+ return False
+ return any(os.path.commonpath((resolved, root)) == root for root in roots)
+ except (OSError, ValueError):
+ return False
+
+ removed, kept, local = [], [], []
+
+ def scrub(servers, scope):
+ if not isinstance(servers, dict):
+ return
+ for name in list(servers):
+ server = servers[name]
+ if owned(server):
+ del servers[name]
+ removed.append(f"{scope}:{name}")
+ else:
+ command = server.get("command") if isinstance(server, dict) else None
+ basename = os.path.basename(command) if isinstance(command, str) else ""
+ if basename == "cua-driver-local":
+ local.append(f"{scope}:{name}")
+ elif name in ("cua-driver", "cua-driver-rs", "cua-computer-use") or basename == "cua-driver":
+ kept.append(f"{scope}:{name}")
+
+ scrub(data.get("mcpServers"), "user")
+ projects = data.get("projects")
+ if isinstance(projects, dict):
+ for project_name, project in projects.items():
+ if isinstance(project, dict):
+ scrub(project.get("mcpServers"), f"project:{project_name}")
+
+ if removed:
+ directory = os.path.dirname(path) or "."
+ fd, backup = tempfile.mkstemp(
+ prefix=os.path.basename(path) + ".bak-cua-driver-rs-uninstall-", dir=directory
+ )
+ try:
+ with os.fdopen(fd, "wb") as handle:
+ shutil.copyfileobj(io.BytesIO(original), handle)
+ except Exception:
+ os.unlink(backup)
+ raise
+ fd, temporary = tempfile.mkstemp(prefix=".claude.json.", suffix=".tmp", dir=directory)
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ json.dump(data, handle, indent=2, ensure_ascii=False)
+ handle.write("\n")
+ os.replace(temporary, path)
+ finally:
+ if os.path.exists(temporary):
+ os.unlink(temporary)
+ print("==> removed Claude MCP registration(s): " + ", ".join(removed))
+ print(f"==> backed up Claude config to {backup}")
+ if local:
+ print("==> preserved local Claude MCP registration(s): " + ", ".join(local)
+ + "; remove cua-driver-local with libs/cua-driver/scripts/uninstall-local.sh from the source checkout")
+ if kept:
+ print("==> preserved unproven Claude MCP registration(s): " + ", ".join(kept)
+ + "; inspect the exact entry before removing it manually")
+
+
+try:
+ clean()
+except Exception as exc:
+ print(f"error: Claude MCP cleanup failed: {exc}", file=sys.stderr)
+ raise SystemExit(1)
+PYCLAUDE
+}
+
if [[ "${CUA_DRIVER_UNINSTALL_TEST_SOURCE_ONLY:-0}" == "1" ]]; then
return 0
fi
@@ -553,36 +689,60 @@ if [[ "$USE_RUST_BACKEND" == "1" ]]; then
RUST_INSTALL_PRESENT=1
fi
- # Ownership-aware Claude cleanup uses Python's JSON + realpath support.
- # Validate the config before daemon shutdown or any release mutation so a
- # malformed/unreadable config cannot turn into a successful partial
- # uninstall that leaves ownership-sensitive registrations behind.
- CLAUDE_JSON="$HOME/.claude.json"
- if [[ -f "$CLAUDE_JSON" ]]; then
- if ! command -v python3 >/dev/null 2>&1; then
- printf 'error: python3 is required to safely inspect Claude MCP ownership before uninstalling a release with %s; install python3 and retry. No release files were removed.\n' "$CLAUDE_JSON" >&2
- exit 1
- fi
- if ! CLAUDE_JSON="$CLAUDE_JSON" python3 <<'PYCLAUDE_VALIDATE'
-import json
-import os
-import sys
-
-path = os.environ["CLAUDE_JSON"]
-try:
- with open(path, "r", encoding="utf-8") as handle:
- data = json.load(handle)
- if not isinstance(data, dict):
- raise ValueError("top-level value must be a JSON object")
-except Exception as exc:
- print(f"could not read Claude config {path}: {exc}", file=sys.stderr)
- raise SystemExit(1)
-PYCLAUDE_VALIDATE
- then
- printf 'error: refusing to uninstall because Claude config could not be safely inspected. No release files were removed.\n' >&2
- exit 1
- fi
+ # Select executable-bearing removals once; proof and deletion consume the
+ # same operands. Empty slots mean this invocation will not remove that tree.
+ APP_PAYLOAD="" LEGACY_APP_PAYLOAD="" HOME_PAYLOAD="" LEGACY_HOME_PAYLOAD=""
+ if [[ "$OS" == "Darwin" ]]; then
+ if [[ -d "$LEGACY_APP_BUNDLE" ]]; then LEGACY_APP_PAYLOAD="$LEGACY_APP_BUNDLE"; fi
+ if [[ -d "$APP_BUNDLE" && "$RUST_INSTALL_PRESENT" == "1" ]]; then APP_PAYLOAD="$APP_BUNDLE"; fi
+ fi
+ if [[ -d "$HOME_DIR" && ( "$RUST_INSTALL_PRESENT" == "1" || "$PURGE_DATA" == "1" ) ]]; then
+ if [[ "$PURGE_DATA" == "1" ]]; then HOME_PAYLOAD="$HOME_DIR"; else HOME_PAYLOAD="$PACKAGES_DIR"; fi
+ fi
+ if [[ -d "$LEGACY_HOME_DIR" ]]; then
+ if [[ "$PURGE_DATA" == "1" ]]; then LEGACY_HOME_PAYLOAD="$LEGACY_HOME_DIR"; else LEGACY_HOME_PAYLOAD="$LEGACY_HOME_DIR/packages"; fi
fi
+ # Freeze physical parent traversal before any earlier removal can unlink an
+ # alias used by a later slot. Preserve a final symlink as an unlink operand;
+ # it must never grant ownership of its target. No Python is needed here.
+ prepare_payload_operand() {
+ local payload="$1" parent
+ if [[ -z "$payload" ]]; then printf -v "$2" '%s' ""; return 0; fi
+ case "$payload" in
+ */|.|..|./*|../*|*/./*|*/../*|*/.|*/..)
+ printf 'error: unsafe release removal operand: %s\n' "$payload" >&2
+ return 1 ;;
+ esac
+ if [[ -d "$payload" && ! -L "$payload" ]]; then
+ if [[ ! -r "$payload" || ! -x "$payload" ]]; then
+ printf 'error: inaccessible release removal operand: %s\n' "$payload" >&2
+ return 1
+ fi
+ # A sentinel protects trailing newlines from command substitution.
+ payload="$(CDPATH= cd -- "$payload" && pwd -P && printf '.')" || return 1
+ payload="${payload%$'\n.'}"
+ if [[ "$payload" == "/" ]]; then
+ printf 'error: unsafe release removal operand: /\n' >&2
+ return 1
+ fi
+ elif [[ -L "$payload" ]]; then
+ case "$payload" in
+ */*) parent="${payload%/*}"; [[ -n "$parent" ]] || parent="/" ;;
+ *) parent="." ;;
+ esac
+ parent="$(CDPATH= cd -- "$parent" && pwd -P && printf '.')" || return 1
+ parent="${parent%$'\n.'}"
+ payload="$parent/${payload##*/}"
+ fi
+ # printf -v avoids another lossy command substitution at the call site.
+ printf -v "$2" '%s' "$payload"
+ }
+ prepare_payload_operand "$APP_PAYLOAD" APP_PAYLOAD || exit 1
+ prepare_payload_operand "$LEGACY_APP_PAYLOAD" LEGACY_APP_PAYLOAD || exit 1
+ prepare_payload_operand "$HOME_PAYLOAD" HOME_PAYLOAD || exit 1
+ prepare_payload_operand "$LEGACY_HOME_PAYLOAD" LEGACY_HOME_PAYLOAD || exit 1
+ CLAUDE_JSON="$HOME/.claude.json"
+ claude_release_config check "$APP_PAYLOAD" "$LEGACY_APP_PAYLOAD" "$HOME_PAYLOAD" "$LEGACY_HOME_PAYLOAD" || exit 1
DAEMON_PID_FILE="$(daemon_pid_file_path)"
DAEMON_STOP_HELPER="$(select_daemon_stop_helper || true)"
@@ -601,209 +761,32 @@ PYCLAUDE_VALIDATE
log "no Rust install marker; leaving any running cua-driver process untouched"
fi
- # --- Claude Code MCP registrations ---
- # Inspect registrations before deleting the launcher/package tree. Claude
- # allows the same server name in multiple scopes, so a name is not proof
- # of ownership. Resolve each command while its target still exists and
- # remove only entries whose command belongs to this selected release.
- CLAUDE_JSON="$HOME/.claude.json"
- if [[ -f "$CLAUDE_JSON" ]] && command -v python3 >/dev/null 2>&1; then
- PY_OUTPUT="$(
- CLAUDE_JSON="$CLAUDE_JSON" \
- HOME_DIR="$HOME_DIR" \
- LEGACY_HOME_DIR="$LEGACY_HOME_DIR" \
- APP_BUNDLE="$APP_BUNDLE" \
- LEGACY_APP_BUNDLE="$LEGACY_APP_BUNDLE" \
- USER_BIN_LINK="$USER_BIN_LINK" \
- RUST_INSTALL_PRESENT="$RUST_INSTALL_PRESENT" \
- python3 <<'PYCLAUDE'
-import json
-import os
-import shutil
-import sys
-import tempfile
-import time
-
-path = os.environ["CLAUDE_JSON"]
-home_dir = os.path.abspath(os.environ["HOME_DIR"])
-legacy_home_dir = os.path.abspath(os.environ["LEGACY_HOME_DIR"])
-app_bundle = os.path.abspath(os.environ["APP_BUNDLE"])
-legacy_app_bundle = os.path.abspath(os.environ["LEGACY_APP_BUNDLE"])
-canonical_launcher = os.path.abspath(os.environ["USER_BIN_LINK"])
-rust_install_present = os.environ.get("RUST_INSTALL_PRESENT", "0") == "1"
-
-try:
- with open(path, "r", encoding="utf-8") as handle:
- data = json.load(handle)
-except Exception as exc:
- print(f"could not read Claude config {path}: {exc}", file=sys.stderr)
- raise SystemExit(1)
-
-removed = []
-preserved_local = []
-
-
-def normalize(value):
- """Absolute path for a registered command, or None when it is relative.
-
- Claude runs a registration from its own working directory, which is not
- the one this uninstaller runs in. Resolving a relative command here would
- attribute a ./cua-driver in an unrelated project to this release whenever
- the uninstaller happens to run from the release package tree, so a command
- that is still relative after home expansion is never ownership evidence.
-
- Apostrophes are avoided in this heredoc on purpose: bash 3.2, the system
- bash on macOS, tracks quotes while scanning for the closing paren of the
- surrounding command substitution and fails to parse the script otherwise.
- """
- expanded = os.path.expanduser(value)
- if not os.path.isabs(expanded):
- return None
- return os.path.abspath(expanded)
-
-
-def is_under(candidate, root):
- try:
- return os.path.commonpath((candidate, root)) == root
- except (ValueError, OSError):
- return False
-
-
-def release_owned_command(server):
- if not isinstance(server, dict):
- return False
- command = server.get("command")
- if not isinstance(command, str) or not command:
- return False
-
- command_path = normalize(command)
- if command_path is None:
- return False
- resolved = os.path.realpath(command_path)
- candidates = (command_path, resolved)
-
- legacy_roots = (
- os.path.join(legacy_home_dir, "packages"),
- legacy_app_bundle,
- )
- if any(
- is_under(candidate, root)
- for candidate in candidates
- for root in legacy_roots
- ):
- return True
-
- if not rust_install_present:
- return False
-
- release_roots = (
- os.path.join(home_dir, "packages"),
- app_bundle,
- )
- if any(
- is_under(candidate, root)
- for candidate in candidates
- for root in release_roots
- ):
- return True
-
- # The canonical launcher is the only safe path-only fallback, and only
- # when no filesystem entry exists at that path. A symlink, including a
- # dangling one, still identifies the chosen target of another installation.
- return command_path == canonical_launcher and not os.path.lexists(command_path)
-
-
-def is_local_launcher(server):
- if not isinstance(server, dict):
- return False
- command = server.get("command")
- if not isinstance(command, str) or not command:
- return False
- # Advisory only: a relative command still names the local launcher, so
- # match on the basename without resolving it against any directory.
- return os.path.basename(os.path.expanduser(command)) == "cua-driver-local"
-
-
-def should_remove(name, server):
- if name == "cua-driver-rs":
- return True
- return release_owned_command(server)
-
-
-def scrub_servers(servers, scope):
- if not isinstance(servers, dict):
- return
- for name in list(servers):
- server = servers[name]
- if should_remove(name, server):
- del servers[name]
- removed.append(f"{scope}:{name}")
- elif is_local_launcher(server):
- preserved_local.append(f"{scope}:{name}")
-
-
-scrub_servers(data.get("mcpServers"), "user")
-projects = data.get("projects")
-if isinstance(projects, dict):
- for project_name, project in projects.items():
- if isinstance(project, dict):
- scrub_servers(project.get("mcpServers"), f"project:{project_name}")
-
-if removed:
- backup = f"{path}.bak-cua-driver-rs-uninstall-{int(time.time())}"
- shutil.copy2(path, backup)
- directory = os.path.dirname(path) or "."
- fd, tmp_path = tempfile.mkstemp(
- prefix=".claude.json.",
- suffix=".tmp",
- dir=directory,
- text=True,
- )
- try:
- with os.fdopen(fd, "w", encoding="utf-8") as handle:
- json.dump(data, handle, indent=2, ensure_ascii=False)
- handle.write("\n")
- os.replace(tmp_path, path)
- except Exception:
- try:
- os.unlink(tmp_path)
- except OSError:
- pass
- raise
- print(f"removed Claude MCP registration(s): {', '.join(removed)}")
- print(f"backed up Claude config to {backup}")
-
-if preserved_local:
- print(
- "preserved local Claude MCP registration(s): "
- + ", ".join(preserved_local)
- + "; remove cua-driver-local with libs/cua-driver/scripts/uninstall-local.sh from the source checkout"
- )
-PYCLAUDE
- )"
- if [[ -n "$PY_OUTPUT" ]]; then
- while IFS= read -r line; do
- log "$line"
- done <<< "$PY_OUTPUT"
- else
- log "no release-owned Claude MCP registrations found in $CLAUDE_JSON"
+ # Cryptographic history purge must run while the exact installed helper
+ # executable still exists. The helper uses the production KeyProvider and
+ # its own bundle-derived namespace, then takes the exclusive writer lease;
+ # failure leaves the runtime and all retryable history state in place.
+ if [[ "$OS" == "Darwin" && "$PURGE_DATA" == "1" ]]; then
+ HISTORY_PURGE_HELPER="$APP_BUNDLE/Contents/MacOS/cua-driver"
+ if ! purge_macos_history \
+ "$APP_BUNDLE" "$HISTORY_PURGE_HELPER" "$RUST_INSTALL_PRESENT" /usr/bin/codesign; then
+ exit 1
fi
- else
- log "no Claude config cleanup via python3 (missing $CLAUDE_JSON or python3)"
+ log "cryptographically purged release Computer History key and local history state"
+ elif [[ "$OS" == "Darwin" ]]; then
+ log "preserved encrypted Computer History if present; reinstall to reopen it or run uninstall.sh --purge to destroy it"
+ elif [[ "$OS" == "Linux" && "$PURGE_DATA" == "1" ]]; then
+ HISTORY_PURGE_HELPER="$PACKAGES_DIR/current/cua-driver"
+ if ! purge_linux_history "$HISTORY_PURGE_HELPER" "$RUST_INSTALL_PRESENT"; then
+ exit 1
+ fi
+ log "cryptographically purged release Computer History Secret Service key and local history state"
+ elif [[ "$OS" == "Linux" ]]; then
+ log "preserved encrypted Computer History if present; reinstall to reopen it or run uninstall.sh --purge to destroy it"
fi
- # `cua-driver-rs` was release-only, so its legacy name-based fallback is
- # safe. Do not feed cua-driver/cua-computer-use through every scope: owning
- # one scope says nothing about a same-named entry in another scope.
- if command -v claude >/dev/null 2>&1; then
- for SCOPE in local project user; do
- if claude mcp remove cua-driver-rs -s "$SCOPE" >/dev/null 2>&1; then
- log "removed Claude MCP server cua-driver-rs from $SCOPE scope"
- fi
- done
- else
- log "claude CLI not found (skipping legacy Claude MCP CLI cleanup)"
- fi
+ # Fresh proof while payloads still exist. No name-only CLI fallback may
+ # bypass this per-entry decision, including for the legacy server name.
+ claude_release_config apply "$APP_PAYLOAD" "$LEGACY_APP_PAYLOAD" "$HOME_PAYLOAD" "$LEGACY_HOME_PAYLOAD" || exit 1
# --- CLI symlink ---
# Only remove ~/.local/bin/cua-driver when it resolves into a
@@ -841,29 +824,6 @@ PYCLAUDE
release_supervisor remove
- # Cryptographic history purge must run while the exact installed helper
- # executable still exists. The helper uses the production KeyProvider and
- # its own bundle-derived namespace, then takes the exclusive writer lease;
- # failure leaves the runtime and all retryable history state in place.
- if [[ "$OS" == "Darwin" && "$PURGE_DATA" == "1" ]]; then
- HISTORY_PURGE_HELPER="$APP_BUNDLE/Contents/MacOS/cua-driver"
- if ! purge_macos_history \
- "$APP_BUNDLE" "$HISTORY_PURGE_HELPER" "$RUST_INSTALL_PRESENT" /usr/bin/codesign; then
- exit 1
- fi
- log "cryptographically purged release Computer History key and local history state"
- elif [[ "$OS" == "Darwin" ]]; then
- log "preserved encrypted Computer History if present; reinstall to reopen it or run uninstall.sh --purge to destroy it"
- elif [[ "$OS" == "Linux" && "$PURGE_DATA" == "1" ]]; then
- HISTORY_PURGE_HELPER="$PACKAGES_DIR/current/cua-driver"
- if ! purge_linux_history "$HISTORY_PURGE_HELPER" "$RUST_INSTALL_PRESENT"; then
- exit 1
- fi
- log "cryptographically purged release Computer History Secret Service key and local history state"
- elif [[ "$OS" == "Linux" ]]; then
- log "preserved encrypted Computer History if present; reinstall to reopen it or run uninstall.sh --purge to destroy it"
- fi
-
# --- Revoke TCC grants BEFORE removing the app ---
# tccutil resolves com.trycua.driver through LaunchServices, so the reset
# only works while /Applications/CuaDriver.app is still installed. Running
@@ -871,40 +831,14 @@ PYCLAUDE
# take — otherwise it fails with -10814 and the grant silently survives.
maybe_reset_tcc
- # --- .app bundle (macOS only) ---
- # Legacy /Applications/CuaDriverRs.app is unambiguously Rust and
- # always removed when present. /Applications/CuaDriver.app is the
- # current canonical Rust path BUT also where the Swift driver
- # lives (same bundle id `com.trycua.driver`), so we only remove
- # it when $RUST_INSTALL_PRESENT — protects a Swift-only Mac from
- # losing its bundle if `uninstall.sh --experimental-rust` is run
- # by mistake.
- if [[ "$OS" == "Darwin" ]]; then
- if [[ -d "$LEGACY_APP_BUNDLE" ]]; then
- SUDO=""
- if [[ ! -w "$(dirname "$LEGACY_APP_BUNDLE")" ]]; then
- SUDO="sudo"
- fi
- $SUDO rm -rf "$LEGACY_APP_BUNDLE"
- log "removed $LEGACY_APP_BUNDLE"
- else
- log "no app bundle at $LEGACY_APP_BUNDLE (skipping)"
- fi
- if [[ -d "$APP_BUNDLE" ]]; then
- if [[ "$RUST_INSTALL_PRESENT" == "1" ]]; then
- SUDO=""
- if [[ ! -w "$(dirname "$APP_BUNDLE")" ]]; then
- SUDO="sudo"
- fi
- $SUDO rm -rf "$APP_BUNDLE"
- log "removed $APP_BUNDLE"
- else
- log "$APP_BUNDLE exists but no Rust marker on disk (~/.cua-driver/packages/, ~/.cua-driver-rs/, CuaDriverRs.app, current/legacy LaunchAgent or systemd unit); leaving it (looks like a Swift-only install)"
- fi
- else
- log "no app bundle at $APP_BUNDLE (skipping)"
- fi
- fi
+ # --- Selected app bundles (macOS only) ---
+ for PAYLOAD in "$LEGACY_APP_PAYLOAD" "$APP_PAYLOAD"; do
+ [[ -n "$PAYLOAD" ]] || continue
+ SUDO=""
+ if [[ ! -w "$(dirname "$PAYLOAD")" ]]; then SUDO="sudo"; fi
+ $SUDO rm -rf -- "$PAYLOAD"
+ log "removed $PAYLOAD"
+ done
# --- Package home ---
# A normal uninstall deliberately keeps the pseudonymous installation ID,
@@ -913,41 +847,26 @@ PYCLAUDE
# any events while disabled. `--purge` is the explicit identity reset.
# All removal remains gated on the Rust marker so a mistaken invocation
# cannot damage a Swift-only Mac's shared ~/.cua-driver state.
- if [[ -d "$HOME_DIR" ]]; then
- if [[ "$RUST_INSTALL_PRESENT" == "1" || "$PURGE_DATA" == "1" ]]; then
- if [[ "$PURGE_DATA" == "1" ]]; then
- rm -rf "$HOME_DIR"
- log "purged $HOME_DIR (including telemetry identity and preference)"
- else
- # Remove only installer/runtime-owned payloads. Unknown files
- # and all telemetry state remain untouched.
- rm -rf "$HOME_DIR/packages" "$HOME_DIR/skills"
- rm -f \
- "$HOME_DIR/.tcc-signing-identity" \
- "$HOME_DIR/serve.out.log" \
- "$HOME_DIR/serve.err.log"
- log "removed runtime payloads from $HOME_DIR"
- log "preserved telemetry identity, preference, and registration markers"
- fi
+ if [[ -n "$HOME_PAYLOAD" ]]; then
+ rm -rf -- "$HOME_PAYLOAD"
+ if [[ "$PURGE_DATA" == "1" ]]; then
+ log "purged $HOME_DIR (including telemetry identity and preference)"
else
- log "$HOME_DIR exists but no Rust marker on disk; leaving it (looks like a Swift-only / shared config dir)"
+ rm -rf -- "$HOME_DIR/skills"
+ rm -f -- "$HOME_DIR/.tcc-signing-identity" "$HOME_DIR/serve.out.log" "$HOME_DIR/serve.err.log"
+ log "removed runtime payloads from $HOME_DIR"
+ log "preserved telemetry identity, preference, and registration markers"
fi
else
- log "no package home at $HOME_DIR (skipping)"
+ log "no selected release package home at $HOME_DIR (skipping)"
fi
- # Preserve legacy telemetry state during a normal uninstall so the
- # runtime's existing one-shot migration can carry the same identity into
- # ~/.cua-driver on reinstall.
- if [[ -d "$LEGACY_HOME_DIR" ]]; then
+ if [[ -n "$LEGACY_HOME_PAYLOAD" ]]; then
+ rm -rf -- "$LEGACY_HOME_PAYLOAD"
if [[ "$PURGE_DATA" == "1" ]]; then
- rm -rf "$LEGACY_HOME_DIR"
log "purged legacy package home $LEGACY_HOME_DIR"
else
- rm -rf "$LEGACY_HOME_DIR/packages" "$LEGACY_HOME_DIR/skills"
- rm -f \
- "$LEGACY_HOME_DIR/.tcc-signing-identity" \
- "$LEGACY_HOME_DIR/serve.out.log" \
- "$LEGACY_HOME_DIR/serve.err.log"
+ rm -rf -- "$LEGACY_HOME_DIR/skills"
+ rm -f -- "$LEGACY_HOME_DIR/.tcc-signing-identity" "$LEGACY_HOME_DIR/serve.out.log" "$LEGACY_HOME_DIR/serve.err.log"
log "removed legacy runtime payloads and preserved legacy telemetry state"
fi
fi