Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(cua-driver): separate local and release identities (#2404)
Francesco Bonaccia8d8142bc1df
diff --git a/.github/scripts/tests/test_cua_driver_release_wiring.py b/.github/scripts/tests/test_cua_driver_release_wiring.pyindex a6f6a6e5a4..0a45efb436 100644--- a/.github/scripts/tests/test_cua_driver_release_wiring.py+++ b/.github/scripts/tests/test_cua_driver_release_wiring.py@@ -166,23 +166,17 @@ class TestCuaDriverReleaseWiring(unittest.TestCase):self.assertIn('"path": "scripts/install.ps1"', config)self.assertIn('"path": "rust/Skills/cua-driver/SKILL.md"', config)- def test_installers_preserve_legacy_telemetry_state_before_cleanup(self) -> None:- for relative_path in (- "libs/cua-driver/scripts/_install-rust.sh",- "libs/cua-driver/scripts/_install-local-rust.sh",- ):- installer = self.read(relative_path)- cleanup = installer.index('rm -rf "$LEGACY_HOME_DIR"')- self.assertLess(- installer.index("for telemetry_file in .telemetry_id .installation_recorded"),- cleanup,- relative_path,- )- self.assertLess(- installer.index('cp -p "$LEGACY_HOME_DIR/$telemetry_file"'),- cleanup,- relative_path,- )+ def test_release_installers_preserve_legacy_telemetry_state_before_cleanup(self) -> None:+ installer = self.read("libs/cua-driver/scripts/_install-rust.sh")+ cleanup = installer.index('rm -rf "$LEGACY_HOME_DIR"')+ self.assertLess(+ installer.index("for telemetry_file in .telemetry_id .installation_recorded"),+ cleanup,+ )+ self.assertLess(+ installer.index('cp -p "$LEGACY_HOME_DIR/$telemetry_file"'),+ cleanup,+ )powershell = self.read("libs/cua-driver/scripts/install.ps1")cleanup = powershell.index("Remove-Item -LiteralPath $LegacyHomeDir -Recurse -Force")@@ -197,6 +191,17 @@ class TestCuaDriverReleaseWiring(unittest.TestCase):cleanup,)+ def test_local_installer_does_not_clean_release_or_legacy_homes(self) -> None:+ installer = self.read("libs/cua-driver/scripts/_install-local-rust.sh")++ self.assertIn(+ 'HOME_DIR="${CUA_DRIVER_LOCAL_HOME:-$HOME/.cua-driver-local}"',+ installer,+ )+ self.assertNotIn("LEGACY_HOME_DIR", installer)+ self.assertNotIn(".cua-driver-rs", installer)+ self.assertNotIn('rm -rf "$HOME/.cua-driver"', installer)+def test_local_macos_signing_uses_an_unambiguous_identity_hash(self) -> None:installer = self.read("libs/cua-driver/scripts/_install-local-rust.sh")diff --git a/libs/cua-driver/python/tests/test_install_local_signing.py b/libs/cua-driver/python/tests/test_install_local_signing.pyindex f9f101c607..d12df6e348 100644--- a/libs/cua-driver/python/tests/test_install_local_signing.py+++ b/libs/cua-driver/python/tests/test_install_local_signing.py@@ -13,30 +13,29 @@ def test_local_installer_accepts_untrusted_self_signed_identity() -> None:assert script.count("security find-identity -p codesigning") >= 2-def test_tcc_reset_compares_live_designated_requirement() -> None:- """The TCC-reset decision inspects the live app's requirement, not just the marker (#2230)."""+def test_local_installer_uses_a_separate_macos_identity() -> None:+ """Local rebuilds never replace or reset the release app identity (#2230)."""script = (Path(__file__).resolve().parents[2] / "scripts" / "_install-local-rust.sh").read_text()- # A classifier collapses a designated requirement to a stable identity class.- assert "classify_designated_requirement()" in script- # The old live requirement is captured before the app is replaced and drives- # the comparison (so a Developer ID -> local transition is detected).- assert "OLD_LIVE_IDENTITY=" in script- assert 'OLD_IDENTITY="$OLD_LIVE_IDENTITY"' in script+ assert 'APP_DEST="/Applications/CuaDriverLocal.app"' in script+ assert 'CFBundleIdentifier -string "com.trycua.driver.local"' in script+ assert 'CFBundleExecutable -string "cua-driver-local"' in script+ assert "tccutil reset" not in script-def test_tcc_reset_gates_marker_write_on_success() -> None:- """A failed `tccutil reset` must not advance the identity marker, so it retries (#2230)."""+def test_unix_local_installer_uses_separate_paths_and_autostart() -> None:+ """Local install state, command, and service names coexist with release."""script = (Path(__file__).resolve().parents[2] / "scripts" / "_install-local-rust.sh").read_text()- # The reset exit status is tracked instead of being discarded with `|| true`.- assert "reset_succeeded=0" in script- # The marker is only written when no reset was needed or the reset succeeded.- assert '[ "$needs_reset" = 0 ] || [ "$reset_succeeded" = 1 ]' in script+ assert 'HOME_DIR="${CUA_DRIVER_LOCAL_HOME:-$HOME/.cua-driver-local}"' in script+ assert 'BIN_DIR/cua-driver-local' in script+ assert "com.trycua.cua-driver-local.plist" in script+ assert "cua-driver-local.service" in script+ assert "stop_cua_driver_daemons" not in scriptdef test_unix_local_installer_always_embeds_source_provenance() -> None:@@ -62,3 +61,24 @@ def test_windows_local_installer_always_embeds_source_provenance() -> None:assert "rev-parse --verify 'HEAD^{commit}'" in scriptassert "status --porcelain --untracked-files=normal" in scriptassert '"$detectedSourceSha-dirty"' in script+++def test_windows_local_installer_uses_separate_paths_and_autostart() -> None:+ script = (+ Path(__file__).resolve().parents[2] / "scripts" / "install-local.ps1"+ ).read_text()++ assert '$BinaryName = "cua-driver-local.exe"' in script+ assert '"Programs\\Cua\\cua-driver-local\\bin"' in script+ assert '".cua-driver-local"' in script+ assert '"cua-driver-local-serve"' in script+ assert "Repair-CuaDriverStaleDaemon" not in script+++def test_release_installers_do_not_target_local_product_artifacts() -> None:+ scripts_dir = Path(__file__).resolve().parents[2] / "scripts"+ for name in ("_install-rust.sh", "install.ps1"):+ script = (scripts_dir / name).read_text()+ assert "CuaDriverLocal" not in script+ assert ".cua-driver-local" not in script+ assert "cua-driver-local-serve" not in scriptdiff --git a/libs/cua-driver/rust/Skills/cua-driver/README.md b/libs/cua-driver/rust/Skills/cua-driver/README.mdindex 8e46eec24c..ca550f708d 100644--- a/libs/cua-driver/rust/Skills/cua-driver/README.md+++ b/libs/cua-driver/rust/Skills/cua-driver/README.md@@ -102,7 +102,8 @@ cua-driver skills install --from main```From a local checkout, `libs/cua-driver/scripts/install-local.sh` installs the-source-built macOS driver. Keep standalone and embedded identity rules from+source-built macOS driver as `cua-driver-local` and `CuaDriverLocal.app`, without+replacing the release installation. Keep standalone and embedded identity rules from`MACOS.md` and `EMBEDDING.md`; launching a raw binary is not a substitute forthe stable app identity that owns macOS TCC grants.diff --git a/libs/cua-driver/rust/crates/cua-driver-uia/src/main.rs b/libs/cua-driver/rust/crates/cua-driver-uia/src/main.rsindex 95e758ba19..8ab4228bad 100644--- a/libs/cua-driver/rust/crates/cua-driver-uia/src/main.rs+++ b/libs/cua-driver/rust/crates/cua-driver-uia/src/main.rs@@ -67,7 +67,18 @@ impl PipeResponse {}#[cfg(target_os = "windows")]-const PIPE_PATH: &str = r"\\.\pipe\cua-driver-uia";+fn pipe_path() -> &'static str {+ let is_local = std::env::current_exe()+ .ok()+ .and_then(|path| path.file_name().map(|name| name.to_owned()))+ .and_then(|name| name.to_str().map(str::to_owned))+ .is_some_and(|name| name.eq_ignore_ascii_case("cua-driver-uia-local.exe"));+ if is_local {+ r"\\.\pipe\cua-driver-local-uia"+ } else {+ r"\\.\pipe\cua-driver-uia"+ }+}#[cfg(target_os = "windows")]fn main() -> anyhow::Result<()> {@@ -92,13 +103,14 @@ async fn async_main() -> anyhow::Result<()> {let registry = std::sync::Arc::new(platform_windows::register_tools());let tool_count = registry.iter_defs().count();- eprintln!("cua-driver-uia: {tool_count} tools registered; listening on {PIPE_PATH}");+ let pipe_path = pipe_path();+ eprintln!("cua-driver-uia: {tool_count} tools registered; listening on {pipe_path}");loop {let server = ServerOptions::new().first_pipe_instance(false)- .create(PIPE_PATH)- .map_err(|e| anyhow::anyhow!("create named pipe {PIPE_PATH}: {e}"))?;+ .create(pipe_path)+ .map_err(|e| anyhow::anyhow!("create named pipe {pipe_path}: {e}"))?;server.connect()diff --git a/libs/cua-driver/rust/crates/cua-driver/src/autostart.rs b/libs/cua-driver/rust/crates/cua-driver/src/autostart.rsindex 1f5f9a23ba..8e16d50fc4 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/autostart.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/autostart.rs@@ -30,8 +30,17 @@use anyhow::{anyhow, Result};-/// Canonical task / unit name. Used by every platform.-pub const TASK_NAME: &str = "cua-driver-serve";+/// Canonical task name for this installed product.+pub fn task_name() -> &'static str {+ #[cfg(target_os = "windows")]+ {+ crate::bundle::autostart_task_name()+ }+ #[cfg(not(target_os = "windows"))]+ {+ "cua-driver-serve"+ }+}/// Reported by `status`.///@@ -213,8 +222,8 @@ $action = New-ScheduledTaskAction `$trigger = New-ScheduledTaskTrigger -AtLogOn -User $user$principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Highest$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1) -ExecutionTimeLimit (New-TimeSpan -Hours 0)-Unregister-ScheduledTask -TaskName 'cua-driver-serve' -Confirm:$false -ErrorAction SilentlyContinue-Register-ScheduledTask -TaskName 'cua-driver-serve' -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Description 'cua-driver-rs: serve daemon, auto-start at interactive logon, RunLevel=Highest for UWP/AppContainer support' | Out-Null+Unregister-ScheduledTask -TaskName $env:CUA_DRIVER_AS_TASK -Confirm:$false -ErrorAction SilentlyContinue+Register-ScheduledTask -TaskName $env:CUA_DRIVER_AS_TASK -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Description "${env:CUA_DRIVER_AS_CLI}: serve daemon, auto-start at interactive logon, RunLevel=Highest for UWP/AppContainer support" | Out-Null# Note: the uiAccess'd worker (`cua-driver-uia.exe`) does NOT get its own# scheduled task. uiAccess PEs can only be launched via ShellExecute, and@@ -234,6 +243,8 @@ Register-ScheduledTask -TaskName 'cua-driver-serve' -Action $action -Trigger $trlet out = Command::new("powershell").args(["-NoProfile", "-NonInteractive", "-Command", REGISTER_PS]).env("CUA_DRIVER_AS_EXE", exe)+ .env("CUA_DRIVER_AS_TASK", task_name())+ .env("CUA_DRIVER_AS_CLI", crate::bundle::cli_name()).output().map_err(|e| anyhow!("failed to invoke powershell: {e}"))?;if out.status.success() {@@ -304,14 +315,15 @@ Register-ScheduledTask -TaskName 'cua-driver-serve' -Action $action -Trigger $tr}pub fn disable() -> Result<()> {- // Tear down any legacy `cua-driver-uia` task from earlier autostart- // versions that registered a separate scheduled task for the uia- // worker. Current versions don't register one (serve.rs spawns the- // worker as a child), but `disable` should still clean up old- // installs. Best-effort — "task not found" is ignored.- let _ = Command::new("schtasks")- .args(["/Delete", "/TN", "cua-driver-uia", "/F"])- .output();+ // Tear down the legacy release `cua-driver-uia` task only when+ // managing the release product. Older versions registered a separate+ // task for the worker; current versions spawn it from serve.rs. Local+ // management must never alter that release task.+ if !crate::bundle::is_local_installation() {+ let _ = Command::new("schtasks")+ .args(["/Delete", "/TN", "cua-driver-uia", "/F"])+ .output();+ }// schtasks /Delete returns 0 on success, 1 on "task not found"// (which we treat as success: the goal is "no task registered"@@ -319,7 +331,7 @@ Register-ScheduledTask -TaskName 'cua-driver-serve' -Action $action -Trigger $tr// code because schtasks doesn't distinguish "doesn't exist" from// "permission denied" via exit code.let out = Command::new("schtasks")- .args(["/Delete", "/TN", TASK_NAME, "/F"])+ .args(["/Delete", "/TN", task_name(), "/F"]).output().map_err(|e| anyhow!("failed to invoke schtasks: {e}"))?;if out.status.success() {@@ -349,7 +361,7 @@ Register-ScheduledTask -TaskName 'cua-driver-serve' -Action $action -Trigger $tr// scheduler namespace could not be inspected and therefore stays// unknown.let out = Command::new("schtasks")- .args(["/Query", "/TN", TASK_NAME, "/HRESULT"])+ .args(["/Query", "/TN", task_name(), "/HRESULT"]).output().map_err(|e| anyhow!("unknown: failed to invoke schtasks: {e}"))?;@@ -394,7 +406,7 @@ Register-ScheduledTask -TaskName 'cua-driver-serve' -Action $action -Trigger $trpub fn kick() -> Result<()> {let out = Command::new("schtasks")- .args(["/Run", "/TN", TASK_NAME])+ .args(["/Run", "/TN", task_name()]).output().map_err(|e| anyhow!("failed to invoke schtasks: {e}"))?;if !out.status.success() {@@ -444,13 +456,18 @@ pub fn run_autostart_cmd(subcommand: &str) {"enable" => (enable(),format!(- "Registered autostart entry '{TASK_NAME}'.\n \- cua-driver serve will start at every interactive logon."+ "Registered autostart entry '{}'.\n \+ {} serve will start at every interactive logon.",+ task_name(),+ crate::bundle::cli_name()),),"disable" => (disable(),- format!("Removed autostart entry '{TASK_NAME}' (no-op if it was already absent)."),+ format!(+ "Removed autostart entry '{}' (no-op if it was already absent).",+ task_name()+ ),),"status" => match status() {Ok(s) => {@@ -464,7 +481,10 @@ pub fn run_autostart_cmd(subcommand: &str) {},"kick" => (kick(),- format!("Started autostart entry '{TASK_NAME}' for the current session."),+ format!(+ "Started autostart entry '{}' for the current session.",+ task_name()+ ),),other => {eprintln!("Unknown autostart subcommand: {other:?}");diff --git a/libs/cua-driver/rust/crates/cua-driver/src/bundle.rs b/libs/cua-driver/rust/crates/cua-driver/src/bundle.rsindex b3fdc0e4c9..75331d14c5 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/bundle.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/bundle.rs@@ -1,15 +1,115 @@-//! Small platform helpers shared by daemon startup paths.+//! Installed-product identity.+//!+//! Release and source builds deliberately use different executable/app names.+//! Deriving the channel from the canonical executable path keeps every runtime+//! entry point (MCP proxy, daemon, status, autostart) in the same namespace+//! without a mutable "active version" switch.-/// Return whether the current executable lives in the installed macOS app-/// bundle. A bundled daemon already has its stable TCC responsibility identity-/// and must not disclaim it during startup.+use std::path::Path;++pub const RELEASE_CLI_NAME: &str = "cua-driver";+pub const LOCAL_CLI_NAME: &str = "cua-driver-local";++pub const RELEASE_APP_NAME: &str = "CuaDriver";+pub const LOCAL_APP_NAME: &str = "CuaDriverLocal";+pub const RELEASE_BUNDLE_ID: &str = "com.trycua.driver";+pub const LOCAL_BUNDLE_ID: &str = "com.trycua.driver.local";++pub(crate) fn path_is_local(path: &Path) -> bool {+ let file_name = path+ .file_name()+ .and_then(|name| name.to_str())+ .unwrap_or_default();+ file_name == LOCAL_CLI_NAME+ || file_name == format!("{LOCAL_CLI_NAME}.exe")+ || path+ .components()+ .any(|component| component.as_os_str().to_str() == Some("CuaDriverLocal.app"))+}++/// Whether this process is the explicitly-installed source-build product.+pub fn is_local_installation() -> bool {+ std::env::current_exe()+ .ok()+ .and_then(|path| std::fs::canonicalize(path).ok())+ .is_some_and(|path| path_is_local(&path))+}++pub fn cli_name() -> &'static str {+ if is_local_installation() {+ LOCAL_CLI_NAME+ } else {+ RELEASE_CLI_NAME+ }+}++pub fn state_namespace() -> &'static str {+ if is_local_installation() {+ "cua-driver-local"+ } else {+ "cua-driver"+ }+}++pub fn user_home_subdirectory() -> &'static str {+ if is_local_installation() {+ ".cua-driver-local"+ } else {+ ".cua-driver"+ }+}++#[cfg(target_os = "windows")]+pub fn uia_executable_name() -> &'static str {+ if is_local_installation() {+ "cua-driver-uia-local.exe"+ } else {+ "cua-driver-uia.exe"+ }+}++#[cfg(target_os = "windows")]+pub fn autostart_task_name() -> &'static str {+ if is_local_installation() {+ "cua-driver-local-serve"+ } else {+ "cua-driver-serve"+ }+}++pub fn app_name() -> &'static str {+ if is_local_installation() {+ LOCAL_APP_NAME+ } else {+ RELEASE_APP_NAME+ }+}++pub fn app_bundle_path() -> String {+ format!("/Applications/{}.app", app_name())+}++pub fn bundle_id() -> &'static str {+ if is_local_installation() {+ LOCAL_BUNDLE_ID+ } else {+ RELEASE_BUNDLE_ID+ }+}++/// A bundled daemon already has its stable TCC responsibility identity and+/// must not disclaim it during startup.#[cfg(target_os = "macos")]pub fn is_executable_inside_cuadriver_app() -> bool {std::env::current_exe().ok().and_then(|path| std::fs::canonicalize(path).ok())- .and_then(|path| path.to_str().map(str::to_owned))- .is_some_and(|path| path.contains("/CuaDriver.app/Contents/MacOS/"))+ .is_some_and(|path| {+ path.to_str().is_some_and(|path| {+ path.contains("/CuaDriver.app/Contents/MacOS/")+ || path.contains("/CuaDriverLocal.app/Contents/MacOS/")+ })+ })}/// Returns `true` when the env var is one of `1|true|yes|on`@@ -25,10 +125,25 @@ pub fn is_env_truthy(name: &str) -> bool {}}-#[cfg(all(test, target_os = "windows"))]+#[cfg(test)]mod tests {use super::*;+ #[test]+ fn local_identity_requires_the_explicit_local_product_name() {+ assert!(path_is_local(Path::new(+ "/Applications/CuaDriverLocal.app/Contents/MacOS/cua-driver-local"+ )));+ assert!(path_is_local(Path::new(+ "/dev/.cua-driver-local/cua-driver-local.exe"+ )));+ assert!(!path_is_local(Path::new(+ "/Applications/CuaDriver.app/Contents/MacOS/cua-driver"+ )));+ assert!(!path_is_local(Path::new("/tmp/cua-driver-local-test")));+ }++ #[cfg(target_os = "windows")]#[test]fn env_truthiness_is_strict() {let name = "CUA_DRIVER_RS_TEST_TRUTHY";diff --git a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs b/libs/cua-driver/rust/crates/cua-driver/src/cli.rsindex 6b34647c1d..8b9605de55 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs@@ -1052,7 +1052,8 @@ pub fn run_describe(registry: &ToolRegistry, name: &str) {}}-/// Spawn `/usr/bin/open -n -g -a CuaDriver --args serve` to launch+/// Launch the release or local app through LaunchServices so the daemon uses+/// the matching TCC identity and namespace./// the daemon under `LaunchServices` (so it inherits the bundle's/// TCC attribution), then poll the socket for up to `timeout_secs`/// seconds. Returns Err with a diagnostic message if `open` failed@@ -1102,7 +1103,9 @@ pub fn launch_daemon_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 pass_socket = socket_path != crate::serve::default_socket_path();- let mut open_args: Vec<&str> = vec!["-n", "-g", "-a", "CuaDriver", "--args", "serve"];+ let app_name = crate::bundle::app_name();+ let app_path = crate::bundle::app_bundle_path();+ let mut open_args: Vec<&str> = vec!["-n", "-g", "-a", app_name, "--args", "serve"];if pass_socket {open_args.push("--socket");open_args.push(socket_path);@@ -1143,8 +1146,8 @@ pub fn launch_daemon_and_wait(return Err(LaunchDaemonError {kind: LaunchDaemonErrorKind::Failed,message: format!(- "`open -n -g -a CuaDriver --args serve{}` exited {:?}. \- Check that `/Applications/CuaDriver.app` is installed.",+ "`open -n -g -a {app_name} --args serve{}` exited {:?}. \+ Check that `{app_path}` is installed.",if pass_socket {format!(" --socket {socket_path}")} else {@@ -1170,7 +1173,7 @@ pub fn launch_daemon_and_wait(message: format!("daemon did not appear on {socket_path} within {timeout_secs}s. If this \is the first launch, grant Accessibility + Screen Recording to \- CuaDriver.app in System Settings and retry."+ {app_name}.app in System Settings and retry."),})}@@ -1251,15 +1254,17 @@ 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!(- "cua-driver-rs: mcp launched without CuaDriver.app's TCC grants; \- auto-launching the daemon via `open -n -g -a CuaDriver --args serve{socket_suffix}` \- and proxying MCP requests through it."+ "{}: mcp launched without {app_name}.app's TCC grants; \+ auto-launching the daemon via `open -n -g -a {app_name} --args serve{socket_suffix}` \+ and proxying MCP requests through it.",+ crate::bundle::cli_name());if let Err(error) = launch_daemon_and_wait(&socket_path, 10, claude_code_compat) {if let Some(on_startup) = on_startup.take() {@@ -2113,6 +2118,13 @@ fn run_recording_render(args: &[String]) {/// installer script — see [`crate::updater`] for why we go through the script/// instead of re-implementing the asset resolution + atomic swap + GC in Rust.pub fn run_update_cmd(apply: bool, json: bool) {+ if apply && crate::bundle::is_local_installation() {+ eprintln!(+ "cua-driver-local is managed by scripts/install-local.sh (or install-local.ps1); \+ refusing to run the release installer from the local product."+ );+ process::exit(2);+ }let apply_started_at = std::time::Instant::now();let daemon_was_running = apply && crate::updater::daemon_is_running();// `--json` short-circuits the text path entirely so scripted callers@@ -2298,6 +2310,9 @@ pub fn run_permissions_cmd(subcommand: &str, json: bool) {/// Never raises a prompt.fn run_permissions_status(json: bool) {let socket = crate::serve::default_socket_path();+ let cli_name = crate::bundle::cli_name();+ let app_name = crate::bundle::app_name();+ let bundle_id = crate::bundle::bundle_id();// Only a listening daemon can answer for com.trycua.driver. A failed/!ok// response (e.g. daemon mid-re-exec during the gate's recheck window) is@@ -2338,9 +2353,9 @@ fn run_permissions_status(json: bool) {let payload = serde_json::json!({"daemon_running": false,"status": "unknown",- "reason": "no CuaDriver daemon is running under the driver's own identity \- (com.trycua.driver), so its real TCC status can't be read from this \- process. Run `cua-driver permissions grant` to grant + verify.",+ "reason": 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."),});println!("{}",@@ -2351,15 +2366,15 @@ fn run_permissions_status(json: bool) {println!("Accessibility: ❓ unknown");println!("Screen Recording: ❓ unknown");println!(- "No CuaDriver daemon is running under the driver's own identity (com.trycua.driver), \+ "No {app_name} daemon is running under the driver's own identity ({bundle_id}), \so its real TCC status can't be read.");println!("(A status check from this terminal would report the terminal's grants, not the \driver's.)");- println!(" → Run `cua-driver permissions grant` to grant + verify, or start the daemon");- println!(" (`open -n -g -a CuaDriver --args serve`) and re-run this command.");+ println!(" → Run `{cli_name} permissions grant` to grant + verify, or start the daemon");+ println!(" (`open -n -g -a {app_name} --args serve`) and re-run this command.");return;};@@ -2397,7 +2412,7 @@ fn run_permissions_status(json: bool) {}println!("Source: {attribution}");if !(ax && sr) {- println!(" → To grant for the driver, run: cua-driver permissions grant");+ println!(" → To grant for the driver, run: {cli_name} permissions grant");}}@@ -2408,21 +2423,23 @@ fn run_permissions_status(json: bool) {fn run_permissions_grant() {#[cfg(target_os = "macos")]{+ let cli_name = crate::bundle::cli_name();+ let app_name = crate::bundle::app_name();let socket = crate::serve::default_socket_path();if crate::serve::is_daemon_listening(&socket) {- println!("CuaDriver daemon already running — checking its permissions…");+ println!("{app_name} daemon already running — checking its permissions…");} else {- println!("Launching CuaDriver to request permissions.");+ println!("Launching {app_name} to request permissions.");println!(- "A dialog titled \u{201c}Cua Driver\u{201d} will appear — approve Accessibility \+ "A dialog for {app_name} will appear — approve Accessibility \and Screen Recording in System Settings, then this command continues.");// Permissions-grant launch never needs the compat screenshot surface.if let Err(e) = launch_daemon_and_wait(&socket, 180, false) {- eprintln!("\nDidn't detect the CuaDriver daemon: {e}");+ eprintln!("\nDidn't detect the {app_name} daemon: {e}");eprintln!(- "If you haven't yet, grant Accessibility + Screen Recording to CuaDriver \- in System Settings, then re-run `cua-driver permissions grant`."+ "If you haven't yet, grant Accessibility + Screen Recording to {app_name} \+ in System Settings, then re-run `{cli_name} permissions grant`.");process::exit(1);}@@ -3091,9 +3108,21 @@ fn diagnose_tcc_db_section() -> String {fn diagnose_config_paths_section() -> String {let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".into());let paths: &[(&str, String)] = &[- ("user data dir", format!("{home}/.cua-driver")),- ("config cache", format!("{home}/Library/Caches/cua-driver")),- ("telemetry id", format!("{home}/.cua-driver/.telemetry_id")),+ (+ "user data dir",+ format!("{home}/{}", crate::bundle::user_home_subdirectory()),+ ),+ (+ "config cache",+ format!("{home}/Library/Caches/{}", crate::bundle::state_namespace()),+ ),+ (+ "telemetry id",+ format!(+ "{home}/{}/.telemetry_id",+ crate::bundle::user_home_subdirectory()+ ),+ ),("updater plist",format!("{home}/Library/LaunchAgents/com.trycua.cua_driver_updater.plist"),diff --git a/libs/cua-driver/rust/crates/cua-driver/src/doctor.rs b/libs/cua-driver/rust/crates/cua-driver/src/doctor.rsindex 5c714d3752..a7a6316480 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/doctor.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/doctor.rs@@ -203,7 +203,7 @@ fn probe_home_dir() -> Probe {Some(h) => h,None => return Probe::warn("home dir", "neither HOME nor USERPROFILE set"),};- let cua_home = home.join(".cua-driver");+ let cua_home = home.join(crate::bundle::user_home_subdirectory());if !cua_home.exists() {return Probe::warn("home dir",diff --git a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs b/libs/cua-driver/rust/crates/cua-driver/src/serve.rsindex 75bef0765a..e8f90bd3fe 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs@@ -245,19 +245,20 @@ fn register_recording_session_end_hook(/// Returns the platform default socket/pipe path.pub fn default_socket_path() -> String {+ let namespace = crate::bundle::state_namespace();#[cfg(target_os = "macos")]{let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".into());- format!("{home}/Library/Caches/cua-driver/cua-driver.sock")+ format!("{home}/Library/Caches/{namespace}/{namespace}.sock")}#[cfg(target_os = "linux")]{let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".into());- format!("{home}/.cache/cua-driver/cua-driver.sock")+ format!("{home}/.cache/{namespace}/{namespace}.sock")}#[cfg(target_os = "windows")]{- r"\\.\pipe\cua-driver".to_owned()+ format!(r"\\.\pipe\{namespace}")}#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]{@@ -275,25 +276,30 @@ pub fn default_socket_path() -> String {/// Medium-IL daemon. See #1602 / the `cua-driver-uia` crate for the worker side.#[cfg(target_os = "windows")]pub fn default_uia_pipe_path() -> String {- r"\\.\pipe\cua-driver-uia".to_owned()+ if crate::bundle::is_local_installation() {+ r"\\.\pipe\cua-driver-local-uia".to_owned()+ } else {+ r"\\.\pipe\cua-driver-uia".to_owned()+ }}/// Returns the platform default PID file path.pub fn default_pid_file_path() -> String {+ let namespace = crate::bundle::state_namespace();#[cfg(target_os = "macos")]{let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".into());- format!("{home}/Library/Caches/cua-driver/cua-driver.pid")+ format!("{home}/Library/Caches/{namespace}/{namespace}.pid")}#[cfg(target_os = "linux")]{let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".into());- format!("{home}/.cache/cua-driver/cua-driver.pid")+ format!("{home}/.cache/{namespace}/{namespace}.pid")}#[cfg(target_os = "windows")]{let local = std::env::var("LOCALAPPDATA").unwrap_or_else(|_| "C:/Temp".into());- format!("{local}/cua-driver/cua-driver.pid")+ format!("{local}/{namespace}/{namespace}.pid")}#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]{@@ -1114,7 +1120,7 @@ fn maybe_spawn_uia_worker() {}};let uia = match current.parent() {- Some(dir) => dir.join("cua-driver-uia.exe"),+ Some(dir) => dir.join(crate::bundle::uia_executable_name()),None => return,};if !uia.exists() {diff --git a/libs/cua-driver/rust/crates/cua-driver/src/skills.rs b/libs/cua-driver/rust/crates/cua-driver/src/skills.rsindex 68b8f900a2..3f58ff9936 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/skills.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/skills.rs@@ -123,12 +123,6 @@ fn is_excluded_platform_doc(basename: &str, all_platforms: bool) -> bool {excluded.iter().any(|f| basename.eq_ignore_ascii_case(f))}-/// Package-home subdir name (matches `telemetry::HOME_SUBDIRECTORY`).-/// Pre-v0.2.16 this was `.cua-driver-rs`; the rename to `.cua-driver/` is-/// the same rename the binary install path went through, kept in lock--/// step so all on-disk state lives under one dot-folder.-const HOME_SUBDIRECTORY: &str = ".cua-driver";-/// Legacy subdir name. `sweep_legacy_skill_pack` removes any skill-pack/// artifacts that landed here before the rename.const LEGACY_HOME_SUBDIRECTORY: &str = ".cua-driver-rs";@@ -149,12 +143,12 @@ fn home_dir() -> Result<PathBuf> {{let userprofile =std::env::var("USERPROFILE").map_err(|_| anyhow!("USERPROFILE not set"))?;- return Ok(PathBuf::from(userprofile).join(HOME_SUBDIRECTORY));+ return Ok(PathBuf::from(userprofile).join(crate::bundle::user_home_subdirectory()));}#[cfg(not(windows))]{let home = std::env::var("HOME").map_err(|_| anyhow!("HOME not set"))?;- return Ok(PathBuf::from(home).join(HOME_SUBDIRECTORY));+ return Ok(PathBuf::from(home).join(crate::bundle::user_home_subdirectory()));}}@@ -162,7 +156,7 @@ fn home_dir() -> Result<PathBuf> {/// `None` when CUA_DRIVER_RS_HOME is set (the env var overrides both/// the new and legacy defaults — caller is on their own).fn legacy_home_dir() -> Option<PathBuf> {- if std::env::var("CUA_DRIVER_RS_HOME").is_ok() {+ if std::env::var("CUA_DRIVER_RS_HOME").is_ok() || crate::bundle::is_local_installation() {return None;}#[cfg(windows)]diff --git a/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs b/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rsindex 3acf2645ac..02b2767ef2 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs@@ -255,7 +255,9 @@ pub fn reset_id() -> Result<(), String> {let Some(home) = telemetry_home_dir() else {return Ok(());};- let legacy = if std::env::var_os(ENV_TELEMETRY_HOME).is_none() {+ let legacy = if std::env::var_os(ENV_TELEMETRY_HOME).is_none()+ && !crate::bundle::is_local_installation()+ {home_root().map(|root| root.join(LEGACY_HOME_SUBDIRECTORY))} else {None@@ -2070,7 +2072,7 @@ fn telemetry_home_dir() -> Option<PathBuf> {if let Some(path) = std::env::var_os(ENV_TELEMETRY_HOME) {return Some(PathBuf::from(path));}- home_root().map(|home| home.join(HOME_SUBDIRECTORY))+ home_root().map(|home| home.join(crate::bundle::user_home_subdirectory()))}fn home_root() -> Option<PathBuf> {@@ -2181,7 +2183,7 @@ fn try_lifecycle_lock(home: &Path) -> Option<File> {}fn migrate_legacy_telemetry_home() {- if std::env::var_os(ENV_TELEMETRY_HOME).is_some() {+ if std::env::var_os(ENV_TELEMETRY_HOME).is_some() || crate::bundle::is_local_installation() {return;}let Some(root) = home_root() else {diff --git a/libs/cua-driver/rust/crates/cua-driver/src/version_check.rs b/libs/cua-driver/rust/crates/cua-driver/src/version_check.rsindex e45cb83469..59c306315f 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/version_check.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/version_check.rs@@ -416,7 +416,9 @@ fn is_enabled() -> bool {/// the file is missing, unreadable, or doesn't have the key.fn read_config_flag() -> Option<bool> {let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;- let path = PathBuf::from(home).join(".cua-driver").join("config.json");+ let path = PathBuf::from(home)+ .join(crate::bundle::user_home_subdirectory())+ .join("config.json");let raw = std::fs::read_to_string(&path).ok()?;let json: serde_json::Value = serde_json::from_str(&raw).ok()?;json.get("update_check_enabled").and_then(|v| v.as_bool())@@ -510,7 +512,11 @@ fn cache_path() -> Option<PathBuf> {let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;Some(PathBuf::from(home)- .join(HOME_SUBDIRECTORY)+ .join(if crate::bundle::is_local_installation() {+ ".cua-driver-local"+ } else {+ HOME_SUBDIRECTORY+ }).join(CACHE_FILE_NAME),)}diff --git a/libs/cua-driver/scripts/README.md b/libs/cua-driver/scripts/README.mdindex 41a07800eb..83b7379bf6 100644--- a/libs/cua-driver/scripts/README.md+++ b/libs/cua-driver/scripts/README.md@@ -5,7 +5,8 @@ Install, uninstall, local-build, and VM sync helpers for cua-driver.| Script | Purpose || --- | --- || `install.sh` / `install.ps1` | Install released cua-driver binaries |-| `install-local.sh` / `install-local.ps1` | Build and install from this checkout |+| `install-local.sh` / `install-local.ps1` | Build this checkout as the separate `cua-driver-local` product |+| `uninstall-local.sh` / `uninstall-local.ps1` | Remove only the source-built `cua-driver-local` product || `uninstall.sh` / `uninstall.ps1` | Remove installed driver artifacts || `_install-common.sh` / `_install-common.psm1` | Shared install helper logic || `_install-rust.sh` / `_install-local-rust.sh` | Rust build/install internals |@@ -21,3 +22,17 @@ or set `CUA_DRIVER_RS_UNINSTALL_PURGE=1` on Windows, to delete them.Keep source commits host-owned. Verification machines should sync from thischeckout and return artifacts, not push code.++Local and released installations are removed independently:++```bash+# macOS / Linux, from the checkout+libs/cua-driver/scripts/uninstall-local.sh++# Windows, from the checkout+libs/cua-driver/scripts/uninstall-local.ps1+```++The local uninstaller leaves `cua-driver`, `CuaDriver.app`, release services,+release state, and release TCC grants untouched. On macOS it revokes only+`com.trycua.driver.local`; pass `--keep-tcc` to retain that local grant.diff --git a/libs/cua-driver/scripts/_install-local-rust.sh b/libs/cua-driver/scripts/_install-local-rust.shindex a11b2d500d..ea86198141 100755--- a/libs/cua-driver/scripts/_install-local-rust.sh+++ b/libs/cua-driver/scripts/_install-local-rust.sh@@ -1,10 +1,7 @@#!/usr/bin/env bash## cua-driver-rs local/debug installer (macOS + Linux). Builds from the-# current source tree and drops the resulting cua-driver binary into the-# same install layout that scripts/install.sh produces — so a local build-# and a release install can coexist + the `current` symlink can flip-# between them.+# current source tree into a durable, separate local-product namespace.## Private helper — invoked by install-local.sh (the multi-backend# dispatcher) when the user picks --backend=rust / --experimental-rust@@ -23,20 +20,14 @@## Linux layout produced (matches install.sh):#-# ${CUA_DRIVER_HOME:-$HOME/.cua-driver}/packages/-# releases/<version>-local-<config>-<target>/cua-driver-# current/cua-driver -> ../releases/<active>/cua-driver-# ${CUA_DRIVER_INSTALL_DIR:-$HOME/.local/bin}/cua-driver-# -> ../current/cua-driver-#-# Legacy env vars `CUA_DRIVER_RS_HOME` / `CUA_DRIVER_RS_INSTALL_DIR` /-# `CUA_DRIVER_RS_BIN_DIR` are still accepted for backwards compat-# (rename from v0.2.16 per PR #1644; this helper was missed in the-# initial rename and ported in PR #1717).+# ${CUA_DRIVER_LOCAL_HOME:-$HOME/.cua-driver-local}/packages/+# releases/<version>-local-<config>-<target>/cua-driver-local+# current/cua-driver-local+# ${CUA_DRIVER_LOCAL_INSTALL_DIR:-$HOME/.local/bin}/cua-driver-local## macOS layout produced:-# /Applications/CuaDriver.app/Contents/MacOS/cua-driver (bundle replaced wholesale)-# $HOME/.local/bin/cua-driver -> .../CuaDriver.app/Contents/MacOS/cua-driver+# /Applications/CuaDriverLocal.app/Contents/MacOS/cua-driver-local+# $HOME/.local/bin/cua-driver-local -> .../CuaDriverLocal.app/Contents/MacOS/cua-driver-local## The version string carries `-local-debug` / `-local-release` so it# never collides with a real release dir and is trivial to GC.@@ -69,24 +60,6 @@ if [ -z "${CUA_DRIVER_SOURCE_SHA:-}" ]; thenfiexport CUA_DRIVER_SOURCE_SHA-# --- Load shared daemon-cleanup helpers ----------------------------------#-# Sibling _install-common.sh defines stop_cua_driver_daemons +-# show_cua_driver_daemon_survivors, mirroring CuaDriverInstall.psm1.-# This is a dev-only path always invoked from a checked-out tree (the-# `install-local.sh` dispatcher only runs from a clone), so the on-disk-# load is the only branch we need — no curl fallback like _install-rust.sh.-# Define no-op stubs if the file is missing so call sites stay-# unconditional and a stale clone doesn't fail the install.-if [ -f "$SCRIPT_DIR/_install-common.sh" ]; then- # shellcheck source=_install-common.sh- . "$SCRIPT_DIR/_install-common.sh"-else- echo "warning: $SCRIPT_DIR/_install-common.sh missing; daemon kill skipped" >&2- stop_cua_driver_daemons() { :; }- show_cua_driver_daemon_survivors() { :; }-fi-BOLD=$(tput bold 2>/dev/null || true)NORMAL=$(tput sgr0 2>/dev/null || true)RED=$(tput setaf 1 2>/dev/null || true)@@ -123,9 +96,9 @@ while [ "$#" -gt 0 ]; doecho " macOS: LaunchAgent under ~/Library/LaunchAgents"echo " Linux: systemd --user unit"echo " On macOS this also fixes TCC: a launchd-started daemon"- echo " is attributed to com.trycua.driver (not your terminal),"+ echo " is attributed to com.trycua.driver.local (not your terminal),"echo " so you grant Accessibility + Screen Recording once and"- echo " every cua-driver call/mcp routes through it correctly."+ echo " every cua-driver-local call/mcp routes through it correctly."echo " --help Show this help."echo ""echo "Examples:"@@ -151,32 +124,11 @@ case "$OS" in*) echo "${RED}Unsupported OS: $OS${NORMAL}"; exit 1 ;;esac-# Canonical home is `~/.cua-driver/` (renamed from `~/.cua-driver-rs/`-# in v0.2.16 — PR #1644). Accept the legacy `CUA_DRIVER_RS_HOME` env var-# too so any dev scripts that still set it keep working.-HOME_DIR="${CUA_DRIVER_HOME:-${CUA_DRIVER_RS_HOME:-$HOME/.cua-driver}}"-BIN_DIR="${CUA_DRIVER_INSTALL_DIR:-${CUA_DRIVER_BIN_DIR:-${CUA_DRIVER_RS_INSTALL_DIR:-${CUA_DRIVER_RS_BIN_DIR:-$HOME/.local/bin}}}}"+HOME_DIR="${CUA_DRIVER_LOCAL_HOME:-$HOME/.cua-driver-local}"+BIN_DIR="${CUA_DRIVER_LOCAL_INSTALL_DIR:-$HOME/.local/bin}"RELEASES_DIR="$HOME_DIR/packages/releases"CURRENT_LINK="$HOME_DIR/packages/current"-# Best-effort sweep: if a previous install left a stale `~/.cua-driver-rs/`-# (the pre-v0.2.16 home), remove it. The runtime sweeps it on first call-# too (see telemetry.rs::migrate_legacy_telemetry_home) so this is belt--# and-braces — keeps the home dir layout single-rooted for the user.-LEGACY_HOME_DIR="$HOME/.cua-driver-rs"-if [ -d "$LEGACY_HOME_DIR" ] && [ "$HOME_DIR" != "$LEGACY_HOME_DIR" ]; then- mkdir -p "$HOME_DIR"- for telemetry_file in .telemetry_id .installation_recorded; do- if [ -f "$LEGACY_HOME_DIR/$telemetry_file" ] && [ ! -e "$HOME_DIR/$telemetry_file" ]; then- cp -p "$LEGACY_HOME_DIR/$telemetry_file" "$HOME_DIR/$telemetry_file" 2>/dev/null \- && echo " Preserved legacy telemetry state $telemetry_file" \- || echo " Could not preserve legacy telemetry state $telemetry_file"- fi- done- echo " Sweeping legacy install dir $LEGACY_HOME_DIR"- rm -rf "$LEGACY_HOME_DIR"-fi-VERSION_TAG="0.0.0-local-$BUILD_CONFIG"VERSIONED_DIR="$RELEASES_DIR/$VERSION_TAG-$TARGET_TRIPLE"@@ -185,7 +137,7 @@ echo " source: ${BOLD}$REPO_ROOT${NORMAL}"echo " sha: ${BOLD}$CUA_DRIVER_SOURCE_SHA${NORMAL}"echo " config: ${BOLD}$BUILD_CONFIG${NORMAL}"echo " target: ${BOLD}$TARGET_TRIPLE${NORMAL}"-echo " bin: ${BOLD}$BIN_DIR/cua-driver${NORMAL}"+echo " bin: ${BOLD}$BIN_DIR/cua-driver-local${NORMAL}"echo " current: ${BOLD}$CURRENT_LINK${NORMAL}"echo ""@@ -237,8 +189,8 @@ echo ""echo "${BOLD}Staging into $VERSIONED_DIR${NORMAL}"mkdir -p "$VERSIONED_DIR"-cp "$BUILT_BINARY" "$VERSIONED_DIR/cua-driver"-chmod +x "$VERSIONED_DIR/cua-driver"+cp "$BUILT_BINARY" "$VERSIONED_DIR/cua-driver-local"+chmod +x "$VERSIONED_DIR/cua-driver-local"# Re-sign with a fresh ad-hoc signature.#@@ -253,7 +205,7 @@ chmod +x "$VERSIONED_DIR/cua-driver"# accepts. Cheap (~50ms on a 40MB binary). macOS-only — no-op on Linux.if [ "$OS" = "Darwin" ]; thenif command -v codesign >/dev/null 2>&1; then- codesign --force --sign - "$VERSIONED_DIR/cua-driver" 2>/dev/null \+ codesign --force --sign - "$VERSIONED_DIR/cua-driver-local" 2>/dev/null \|| echo "${YELLOW}warning: codesign --force --sign - failed; first run may fail with SIGKILL on macOS 26+${NORMAL}" >&2fifi@@ -395,33 +347,10 @@ clean_partial_bundle_signature() {find "$app" -type f -name '*.cstemp' -delete}-# Classify a bundle's macOS designated requirement into a stable identity-# class, used below to decide whether a TCC grant must be reset:-# * "cert:<fp>" — any certificate/anchor-based requirement (a Developer ID-# release build OR the self-signed local cert). <fp> is a-# hash of the normalized requirement text: STABLE across-# rebuilds with the same cert, but DIFFERENT between the-# Developer ID release build and the local build — exactly-# the release<->local transition that invalidates a grant.-# * "adhoc" — a bare `cdhash H"..."` requirement (churns every rebuild).-# * "" — no bundle / unsigned / codesign unavailable.-classify_designated_requirement() {- local app="$1" req- { [ "$OS" = "Darwin" ] && [ -d "$app" ] && command -v codesign >/dev/null 2>&1; } \- || { printf ''; return; }- req="$(codesign -d -r- "$app" 2>&1 | sed -n 's/^designated => //p')"- [ -n "$req" ] || { printf ''; return; }- if printf '%s' "$req" | grep -Eq 'certificate|anchor'; then- printf 'cert:%s' "$(printf '%s' "$req" | shasum | awk '{print $1}')"- else- printf 'adhoc'- fi-}--# --- macOS: wrap the binary in CuaDriver.app for a stable TCC identity ---+# --- macOS: wrap the binary in CuaDriverLocal.app for a stable TCC identity ---## TCC keys Accessibility / Screen-Recording grants on the bundle-# identifier (com.trycua.driver), not the bare executable path. A loose+# identifier (com.trycua.driver.local), not the bare executable path. A loose# binary gets grants attributed to its ad-hoc cdhash, which changes on# every rebuild — so permissions silently reset and never appear cleanly# under System Settings. Mirror the production path (install.sh) + the CD@@ -429,19 +358,19 @@ classify_designated_requirement() {# CuaDriverBundle skeleton, install the bundle to /Applications, and point# the visible bin at the binary INSIDE the bundle. Linux/Windows have no# .app concept and keep the bare-binary symlink below.-APP_DEST="/Applications/CuaDriver.app"+APP_DEST="/Applications/CuaDriverLocal.app"if [ "$OS" = "Darwin" ]; thenSKELETON="$REPO_ROOT/scripts/CuaDriverBundle"if [ ! -d "$SKELETON/Contents" ]; thenecho "${RED}Error: bundle skeleton missing at $SKELETON${NORMAL}" >&2exit 1fi- APP_STAGE="$VERSIONED_DIR/CuaDriver.app"+ APP_STAGE="$VERSIONED_DIR/CuaDriverLocal.app"rm -rf "$APP_STAGE"mkdir -p "$APP_STAGE/Contents/MacOS"cp -R "$SKELETON/Contents/." "$APP_STAGE/Contents/"- cp "$VERSIONED_DIR/cua-driver" "$APP_STAGE/Contents/MacOS/cua-driver"- chmod +x "$APP_STAGE/Contents/MacOS/cua-driver"+ cp "$VERSIONED_DIR/cua-driver-local" "$APP_STAGE/Contents/MacOS/cua-driver-local"+ chmod +x "$APP_STAGE/Contents/MacOS/cua-driver-local"rm -f "$APP_STAGE/Contents/MacOS/.gitkeep"# Stamp the local build version so the bundle reports something sane.if command -v plutil >/dev/null 2>&1; then@@ -449,6 +378,14 @@ if [ "$OS" = "Darwin" ]; then"$APP_STAGE/Contents/Info.plist" 2>/dev/null || trueplutil -replace CFBundleVersion -string "$VERSION_TAG" \"$APP_STAGE/Contents/Info.plist" 2>/dev/null || true+ plutil -replace CFBundleExecutable -string "cua-driver-local" \+ "$APP_STAGE/Contents/Info.plist"+ plutil -replace CFBundleIdentifier -string "com.trycua.driver.local" \+ "$APP_STAGE/Contents/Info.plist"+ plutil -replace CFBundleName -string "Cua Driver Local" \+ "$APP_STAGE/Contents/Info.plist"+ plutil -replace CFBundleDisplayName -string "Cua Driver Local" \+ "$APP_STAGE/Contents/Info.plist"fi# Sign the staged bundle before touching the live installation. Required on# macOS 26+ where Taskgated rejects a copied binary's stale signature.@@ -473,24 +410,16 @@ if [ "$OS" = "Darwin" ]; thenfielseclean_partial_bundle_signature "$APP_STAGE"- echo "${RED}Error: codesign of staged CuaDriver.app failed; live installation was not changed.${NORMAL}" >&2+ echo "${RED}Error: codesign of staged CuaDriverLocal.app failed; live installation was not changed.${NORMAL}" >&2exit 1fifiif ! codesign --verify --deep --strict "$APP_STAGE" 2>/dev/null; then- echo "${RED}Error: staged CuaDriver.app failed signature verification; live installation was not changed.${NORMAL}" >&2+ echo "${RED}Error: staged CuaDriverLocal.app failed signature verification; live installation was not changed.${NORMAL}" >&2exit 1fifi- # Capture the live app's ACTUAL designated requirement before we replace- # it, so the TCC-reset decision below compares real signing identities- # rather than trusting the .tcc-signing-identity marker. The marker records- # only the last *local* signing decision and can disagree with what is- # actually installed — e.g. a Developer ID release bundle whose grant the- # marker knows nothing about. See #2230.- OLD_LIVE_IDENTITY="$(classify_designated_requirement "$APP_DEST")"-# Install to /Applications (user-writable for admins; no sudo — same as# install.sh). Keep the prior bundle available until the copy completes so# an interrupted install cannot leave a corrupt live app.@@ -506,7 +435,7 @@ if [ "$OS" = "Darwin" ]; thenif [ -d "$APP_BACKUP" ]; thenmv "$APP_BACKUP" "$APP_DEST"fi- echo "${RED}Error: failed to install CuaDriver.app; restored the previous bundle.${NORMAL}" >&2+ echo "${RED}Error: failed to install CuaDriverLocal.app; restored the previous bundle.${NORMAL}" >&2exit 1fiecho "${GREEN}installed $APP_DEST${NORMAL}"@@ -514,10 +443,8 @@ if [ "$OS" = "Darwin" ]; then# --- Force LaunchServices registration of the freshly-copied bundle ----## `ditto` drops the bundle on disk, but LaunchServices registers the new- # com.trycua.driver identity ASYNCHRONOUSLY (seconds later). Until it does,- # `tccutil reset com.trycua.driver` fails with -10814 ("No such bundle- # identifier") and the stale-grant reset below silently no-ops, and- # `open -n -g -a CuaDriver` (what `permissions grant` / the MCP proxy use to+ # 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# 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"@@ -525,92 +452,24 @@ if [ "$OS" = "Darwin" ]; then"$LSREGISTER" -f "$APP_DEST" >/dev/null 2>&1 || truefi- # --- Clear a TCC grant pinned to a PREVIOUS signing identity ------------ #- # TCC pins each Accessibility / Screen-Recording grant to the app's- # designated requirement AT GRANT TIME. A user who granted while the app- # was ad-hoc signed has a grant whose csreq is a bare `cdhash H"..."`- # (changes every rebuild); a user who granted under a Developer ID release- # build or a different local cert has one pinned to that leaf. When the- # newly installed build's requirement differs, the old row survives with- # auth_value=allowed but a csreq that no longer matches THIS build — so the- # daemon reads "not granted" while System Settings still shows the toggle- # ON. That's a dead end: re-toggling doesn't help because the row already- # records a decision, so the grant prompt never re-fires.- #- # We compare the LIVE requirement captured before replacement- # (OLD_LIVE_IDENTITY) against the newly installed one — not the- # .tcc-signing-identity marker, which only records the last *local* signing- # decision and misses a release->local transition entirely (#2230). On any- # transition a clean re-grant fixes (release<->local, local-cert-a<->b, or- # cert->adhoc), `tccutil reset` once so the next `permissions grant` prompts- # cleanly and re-pins to the current identity. We deliberately do NOT reset- # adhoc->adhoc: the cdhash churns every rebuild, so a reset there would just- # force a re-grant on every install for no durable benefit.- #- # `tccutil reset` needs no sudo / Full Disk Access and is a no-op when- # nothing was granted. Its exit status is honored: the identity marker is- # only advanced once a needed reset actually succeeds, so a failed reset is- # retried on the next install instead of being recorded as complete (#2230).- if command -v tccutil >/dev/null 2>&1; then- IDENTITY_MARKER="$HOME_DIR/.tcc-signing-identity"- NEW_IDENTITY="$(classify_designated_requirement "$APP_DEST")"- [ -n "$NEW_IDENTITY" ] || NEW_IDENTITY="adhoc"- # Prefer the live pre-replacement requirement; fall back to the marker- # only when the old app was absent/unsigned (first install).- OLD_IDENTITY="$OLD_LIVE_IDENTITY"- [ -n "$OLD_IDENTITY" ] || OLD_IDENTITY="$(cat "$IDENTITY_MARKER" 2>/dev/null || true)"-- old_is_cert=0; new_is_cert=0- case "$OLD_IDENTITY" in cert:*) old_is_cert=1 ;; esac- case "$NEW_IDENTITY" in cert:*) new_is_cert=1 ;; esac- needs_reset=0- if [ "$NEW_IDENTITY" != "$OLD_IDENTITY" ] \- && { [ "$old_is_cert" = 1 ] || [ "$new_is_cert" = 1 ]; }; then- needs_reset=1- fi-- reset_succeeded=1- if [ "$needs_reset" = 1 ]; then- tccutil reset Accessibility com.trycua.driver >/dev/null 2>&1 || reset_succeeded=0- tccutil reset ScreenCapture com.trycua.driver >/dev/null 2>&1 || reset_succeeded=0- if [ "$reset_succeeded" = 1 ]; then- echo "${BOLD}cleared any stale Accessibility / Screen-Recording grant pinned to a previous signing identity.${NORMAL}"- if [ "$new_is_cert" = 1 ]; then- echo " Grant once more (System Settings → Privacy & Security) and it will${BOLD} stick across every future rebuild${NORMAL} — the grant now pins to a stable signing certificate, not the per-build cdhash."- else- echo " Grant once more (System Settings → Privacy & Security). Reinstall once a stable local signing certificate is available to keep the grant across rebuilds."- fi- else- echo "${YELLOW}warning: could not reset the stale TCC grant; leaving the identity marker unchanged so the next install retries.${NORMAL}" >&2- fi- fi-- # Advance the marker only when no reset was needed, or the reset that- # was needed succeeded — otherwise leave it stale so the next install- # retries the transition.- if [ "$needs_reset" = 0 ] || [ "$reset_succeeded" = 1 ]; then- printf '%s\n' "$NEW_IDENTITY" > "$IDENTITY_MARKER" 2>/dev/null || true- fi- fifi# --- Visible-bin symlink ------------------------------------------------## On macOS point at the binary INSIDE the installed bundle so the process-# that actually runs carries the com.trycua.driver identity (TCC keys+# that actually runs carries the com.trycua.driver.local identity (TCC keys# grants on it). On Linux/Windows point at the versioned-store binary.mkdir -p "$BIN_DIR"if [ "$OS" = "Darwin" ]; then- BIN_TARGET="$APP_DEST/Contents/MacOS/cua-driver"+ BIN_TARGET="$APP_DEST/Contents/MacOS/cua-driver-local"else- BIN_TARGET="$CURRENT_LINK/cua-driver"+ BIN_TARGET="$CURRENT_LINK/cua-driver-local"fi-ln -sf "$BIN_TARGET" "$BIN_DIR/cua-driver"-echo "${GREEN}$BIN_DIR/cua-driver -> $BIN_TARGET${NORMAL}"+ln -sf "$BIN_TARGET" "$BIN_DIR/cua-driver-local"+echo "${GREEN}$BIN_DIR/cua-driver-local -> $BIN_TARGET${NORMAL}"echo ""-INSTALLED_BIN="$BIN_DIR/cua-driver"+INSTALLED_BIN="$BIN_DIR/cua-driver-local"# --- Stop any pre-swap cua-driver daemons ------------------------------#@@ -620,8 +479,12 @@ INSTALLED_BIN="$BIN_DIR/cua-driver"# so the next invocation picks up this build. Best-effort, never# fails the install. Survivors (rare on Unix — `pkill` reaches all# user-owned procs without elevation) get a yellow hint.-stop_cua_driver_daemons-show_cua_driver_daemon_survivors+if [ "$OS" = "Darwin" ]; then+ launchctl unload "$HOME/Library/LaunchAgents/com.trycua.cua-driver-local.plist" 2>/dev/null || true+elif [ "$OS" = "Linux" ] && command -v systemctl >/dev/null 2>&1; then+ systemctl --user stop cua-driver-local.service >/dev/null 2>&1 || true+fi+pkill -x cua-driver-local >/dev/null 2>&1 || true# Agent skill pack symlinks: NOT auto-created. Run# `cua-driver skills install --local` to symlink agent dirs to the@@ -632,14 +495,7 @@ echo ""if [ "$INSTALL_AUTOSTART" = true ]; thenif [ "$OS" = "Darwin" ]; then- # Unload + remove any stale LaunchAgent from the pre-rename install- # so the new label doesn't race the old one.- LEGACY_PLIST_PATH="$HOME/Library/LaunchAgents/com.trycua.cua-driver-rs.plist"- if [ -f "$LEGACY_PLIST_PATH" ]; then- launchctl unload "$LEGACY_PLIST_PATH" 2>/dev/null || true- rm -f "$LEGACY_PLIST_PATH"- fi- PLIST_PATH="$HOME/Library/LaunchAgents/com.trycua.cua-driver.plist"+ PLIST_PATH="$HOME/Library/LaunchAgents/com.trycua.cua-driver-local.plist"echo "${BOLD}Writing LaunchAgent → $PLIST_PATH${NORMAL}"mkdir -p "$(dirname "$PLIST_PATH")"cat >"$PLIST_PATH" <<EOF@@ -647,7 +503,7 @@ if [ "$INSTALL_AUTOSTART" = true ]; then<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict>- <key>Label</key><string>com.trycua.cua-driver</string>+ <key>Label</key><string>com.trycua.cua-driver-local</string><key>ProgramArguments</key><array><string>$INSTALLED_BIN</string>@@ -664,19 +520,12 @@ EOFlaunchctl load "$PLIST_PATH"echo "${GREEN}Loaded.${NORMAL} Manage with launchctl load / unload \"$PLIST_PATH\"."elif [ "$OS" = "Linux" ]; then- # Stop + remove any pre-rename systemd unit so the new one doesn't- # race the old one.- LEGACY_UNIT_PATH="$HOME/.config/systemd/user/cua-driver-rs.service"- if [ -f "$LEGACY_UNIT_PATH" ]; then- systemctl --user disable --now cua-driver-rs.service 2>/dev/null || true- rm -f "$LEGACY_UNIT_PATH"- fi- UNIT_PATH="$HOME/.config/systemd/user/cua-driver.service"+ UNIT_PATH="$HOME/.config/systemd/user/cua-driver-local.service"echo "${BOLD}Writing systemd user unit → $UNIT_PATH${NORMAL}"mkdir -p "$(dirname "$UNIT_PATH")"cat >"$UNIT_PATH" <<EOF[Unit]-Description=cua-driver serve daemon+Description=cua-driver-local serve daemonAfter=graphical-session.target[Service]@@ -688,8 +537,8 @@ RestartSec=2WantedBy=default.targetEOFsystemctl --user daemon-reload- systemctl --user enable --now cua-driver.service- echo "${GREEN}Enabled.${NORMAL} Manage with systemctl --user {start|stop|status} cua-driver."+ systemctl --user enable --now cua-driver-local.service+ echo "${GREEN}Enabled.${NORMAL} Manage with systemctl --user {start|stop|status} cua-driver-local."fiecho ""fi@@ -720,9 +569,9 @@ if [ "$INSTALL_AUTOSTART" != true ]; thenecho ""if [ "$OS" = "Darwin" ]; thenecho "Auto-start (recommended on macOS): re-run with --autostart to register a LaunchAgent."- echo " A launchd-started daemon is attributed to com.trycua.driver (not your terminal),"+ echo " A launchd-started daemon is attributed to com.trycua.driver.local (not your terminal),"echo " so permission prompts say \"Cua Driver\" and grants stick — grant Accessibility +"- echo " Screen Recording once and every cua-driver call/mcp routes through it correctly."+ echo " Screen Recording once and every cua-driver-local call/mcp routes through it correctly."echo " (Without it, a prompt raised from a terminal attributes to the terminal instead.)"elseecho "Auto-start (optional): re-run with --autostart to register a systemd user unit."diff --git a/libs/cua-driver/scripts/install-local.ps1 b/libs/cua-driver/scripts/install-local.ps1index 886e355611..2e4f327295 100644--- a/libs/cua-driver/scripts/install-local.ps1+++ b/libs/cua-driver/scripts/install-local.ps1@@ -1,12 +1,9 @@# cua-driver-rs local installer (Windows). Builds release-mode from the-# current source tree and drops the resulting cua-driver.exe into the same-# install layout that scripts/install.ps1 produces — so a local build and-# a release install can coexist + the `current` junction can flip between-# them.+# current source tree into a durable, separate local-product namespace.## Params mirror scripts/install.ps1 so the developer loop matches what# end users experience:-# -AutoStart register the cua-driver-serve Scheduled Task at logon+# -AutoStart register the cua-driver-local-serve Scheduled Task at logon# (Windows-native equivalent of macOS LaunchAgent).# Default off; the post-install message prints the# registration recipe so you can opt in later.@@ -22,12 +19,12 @@# signed/built release from GitHub. This script is for the developer# loop (rapid edit/build/test on a Windows host).#-# Layout produced (matches install.ps1 — see its header for details):+# Separate local layout produced:## <visibleBinDir> [junction → currentDir]# <currentDir> [junction → release dir, retargeted here]# <release dir> [real dir, this script's output]-# 0.0.0-local-release-<target>\cua-driver.exe+# 0.0.0-local-release-<target>\cua-driver-local.exe## The version-string carries `-local-release` so it never collides with# a real release dir and is trivial to garbage-collect.@@ -64,7 +61,9 @@ $ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path# libs/cua-driver/scripts/; the Cargo workspace lives one level deeper# under libs/cua-driver/rust/.$RepoRoot = (Resolve-Path "$ScriptDir\..\rust").Path-$BinaryName = "cua-driver.exe"+$BinaryName = "cua-driver-local.exe"+$BuiltBinaryName = "cua-driver.exe"+$UiaBinaryName = "cua-driver-uia-local.exe"# Always release-config — matches the binary install.ps1 hands end users.$Config = "release"@@ -97,17 +96,15 @@ $Target = switch -Regex ($archEnv) {# ---------- Paths (must match install.ps1's defaults) -----------------------if ($env:CUA_DRIVER_RS_INSTALL_DIR) {- $VisibleBinDir = $env:CUA_DRIVER_RS_INSTALL_DIR+if ($env:CUA_DRIVER_LOCAL_INSTALL_DIR) {+ $VisibleBinDir = $env:CUA_DRIVER_LOCAL_INSTALL_DIR} else {- # Path layout matches install.ps1's v0.2.14+ rename- # (trycua\cua-driver-rs → Cua\cua-driver). See PR #1644.- $VisibleBinDir = Join-Path $env:LOCALAPPDATA "Programs\Cua\cua-driver\bin"+ $VisibleBinDir = Join-Path $env:LOCALAPPDATA "Programs\Cua\cua-driver-local\bin"}-if ($env:CUA_DRIVER_RS_HOME) {- $PackageHome = $env:CUA_DRIVER_RS_HOME+if ($env:CUA_DRIVER_LOCAL_HOME) {+ $PackageHome = $env:CUA_DRIVER_LOCAL_HOME} else {- $PackageHome = Join-Path $env:USERPROFILE ".cua-driver"+ $PackageHome = Join-Path $env:USERPROFILE ".cua-driver-local"}$CurrentDir = Join-Path $PackageHome "packages\current"$ReleasesDir = Join-Path $PackageHome "packages\releases"@@ -145,15 +142,15 @@ function Register-CuaDriverAutostart {}& $InstalledBinary autostart enableif ($LASTEXITCODE -ne 0) {- throw "cua-driver autostart enable failed (exit $LASTEXITCODE)"+ throw "cua-driver-local autostart enable failed (exit $LASTEXITCODE)"}}-# Stop-CuaDriverDaemons + Show-CuaDriverDaemonSurvivors are defined in-# the sibling _install-common.psm1 module - shared with install.ps1-# so the daemon-cleanup logic stays in one place. Local dev runs from-# a checked-out tree, so we always have the file on disk.-Import-Module -Name (Join-Path $ScriptDir "_install-common.psm1") -Force+function Stop-CuaDriverLocalDaemons {+ & schtasks.exe /End /TN "cua-driver-local-serve" 2>$null | Out-Null+ Get-Process -Name "cua-driver-local","cua-driver-uia-local" -ErrorAction SilentlyContinue |+ Stop-Process -Force -ErrorAction SilentlyContinue+}function Write-Step($msg) { Write-Host "==> $msg" -ForegroundColor Cyan }@@ -175,10 +172,10 @@ if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) {# ---------- Build -----------------------------------------------------------Write-Step "cargo build --release -p cua-driver"+Write-Step "cargo build --release -p cua-driver -p cua-driver-uia"Push-Location $RepoRoottry {- & cargo build --release -p cua-driver+ & cargo build --release -p cua-driver -p cua-driver-uiaif ($LASTEXITCODE -ne 0) {Write-Host "Error: cargo build failed." -ForegroundColor Redexit $LASTEXITCODE@@ -187,7 +184,8 @@ try {finally {Pop-Location}-$BuiltBinary = Join-Path $RepoRoot "target\$Config\$BinaryName"+$BuiltBinary = Join-Path $RepoRoot "target\$Config\$BuiltBinaryName"+$BuiltUiaBinary = Join-Path $RepoRoot "target\$Config\cua-driver-uia.exe"if (-not (Test-Path -LiteralPath $BuiltBinary)) {Write-Host "Error: build produced no binary at $BuiltBinary" -ForegroundColor Redexit 1@@ -200,7 +198,7 @@ $VersionedDir = Join-Path $ReleasesDir "$VersionTag-$Target"$DestBinary = Join-Path $VersionedDir $BinaryName# If a previous install-local left a binary here and it's currently-# being executed (typical: `cua-driver autostart kick` spawned a+# being executed (typical: `cua-driver-local autostart kick` spawned a# High-IL daemon at logon, which we can't terminate from this# Medium-IL shell without UAC), the Copy-Item below fails with# "The process cannot access the file ... because it is being used by@@ -218,8 +216,8 @@ if (Test-Path -LiteralPath $DestBinary) {} catch {Write-Host "Note: could not rename previous binary at $DestBinary." -ForegroundColor YellowWrite-Host " ($($_.Exception.Message))" -ForegroundColor Yellow- Write-Host " Most likely a running cua-driver daemon is holding it." -ForegroundColor Yellow- Write-Host " Stop it first (e.g. ``schtasks /End /TN cua-driver-serve`` then re-run)." -ForegroundColor Yellow+ Write-Host " Most likely a running cua-driver-local daemon is holding it." -ForegroundColor Yellow+ Write-Host " Stop it first (e.g. ``schtasks /End /TN cua-driver-local-serve`` then re-run)." -ForegroundColor Yellow}# Best-effort GC of stale-* siblings older than this run. Cheap;# keeps the dir from growing unbounded over many re-builds.@@ -227,22 +225,17 @@ if (Test-Path -LiteralPath $DestBinary) {Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-1) } |ForEach-Object { try { Remove-Item -LiteralPath $_.FullName -Force -ErrorAction SilentlyContinue } catch {} }- Write-Step "killing previous cua-driver processes (best-effort; High-IL needs admin)"- # Repair- variant does Stop-CuaDriverDaemonsWithHealth + stale- # detection + UAC self-elevation when wedged: if survivors are- # present AND the pipe is dead, prompts the user (y/n), and on- # yes triggers a UAC prompt to spawn a brief elevated- # PowerShell that kills the High-IL pids and re-runs the- # scheduled task. On UAC accept + healthy pipe afterward, the- # install proceeds at Medium IL like nothing happened. On UAC- # cancel / failure, falls back to the same printed manual- # recovery instructions the previous flow used.- $null = Repair-CuaDriverStaleDaemon+ Write-Step "killing previous cua-driver-local processes (best-effort; High-IL needs admin)"+ Stop-CuaDriverLocalDaemons}Write-Step "staging into $VersionedDir"New-Item -ItemType Directory -Path $VersionedDir -Force | Out-NullCopy-Item -LiteralPath $BuiltBinary -Destination $DestBinary -Force+$DestUiaBinary = Join-Path $VersionedDir $UiaBinaryName+if (Test-Path -LiteralPath $BuiltUiaBinary) {+ Copy-Item -LiteralPath $BuiltUiaBinary -Destination $DestUiaBinary -Force+}$installedBinary = $DestBinary# Stage the skill pack alongside the binary. install-local mirrors what@@ -310,41 +303,40 @@ Write-Host " source: $installedBinary"Write-Host ""if ($AutoStart) {- Write-Step "registering Scheduled Task 'cua-driver-serve'"+ Write-Step "registering Scheduled Task 'cua-driver-local-serve'"try {Register-CuaDriverAutostart -InstalledBinary (Join-Path $VisibleBinDir $BinaryName)- Write-Host " Registered. cua-driver serve auto-starts at every interactive logon." -ForegroundColor Green+ Write-Host " Registered. cua-driver-local serve auto-starts at every interactive logon." -ForegroundColor Green}catch {Write-Host " Failed to register: $($_.Exception.Message)" -ForegroundColor Red}} else {- # User didn't pass -AutoStart, but if a `cua-driver-serve` task is- # ALREADY registered (from a previous `install.ps1 -AutoStart` or- # `cua-driver autostart enable`), re-register it pointing at this+ # User didn't pass -AutoStart, but if a local task is already registered,+ # re-register it pointing at this# fresh binary. Otherwise the user ends up with a task whose# <Command> path is the OLD release-install dir, running the OLD- # binary - even though `cua-driver` on PATH now resolves to the+ # binary - even though `cua-driver-local` on PATH now resolves to the# fresh one. See trycua/cua#1654 (hidden-console wrapper landed# later - old tasks that survived an upgrade still produce the# visible console window at logon).$prevEAP = $ErrorActionPreference$ErrorActionPreference = 'Continue'try {- & schtasks.exe /Query /TN "cua-driver-serve" 2>$null | Out-Null+ & schtasks.exe /Query /TN "cua-driver-local-serve" 2>$null | Out-Null$hasTask = ($LASTEXITCODE -eq 0)} finally {$ErrorActionPreference = $prevEAP}if ($hasTask) {- Write-Step "found existing 'cua-driver-serve' task - re-registering against fresh binary"+ Write-Step "found existing 'cua-driver-local-serve' task - re-registering against fresh binary"try {Register-CuaDriverAutostart -InstalledBinary (Join-Path $VisibleBinDir $BinaryName)Write-Host " Re-registered. Task action now uses this build's hidden-console wrapper." -ForegroundColor Green}catch {Write-Host " Failed to re-register: $($_.Exception.Message)" -ForegroundColor Red- Write-Host " The existing task still points at the previous binary. Run 'cua-driver autostart enable' from an elevated shell to update."+ Write-Host " The existing task still points at the previous binary. Run 'cua-driver-local autostart enable' from an elevated shell to update."}}}@@ -378,18 +370,18 @@ if ($AutoStart) {# Surface the management subcommands so the user knows how to inspect /# disable later without digging through Task Scheduler.Write-Host ""- Write-Host "Auto-start: 'cua-driver-serve' is registered at RunLevel=Highest." -ForegroundColor Cyan- Write-Host " cua-driver autostart status (inspect)" -ForegroundColor Cyan- Write-Host " cua-driver autostart disable (remove)" -ForegroundColor Cyan- Write-Host " cua-driver autostart kick (start now without re-logging)" -ForegroundColor Cyan+ Write-Host "Auto-start: 'cua-driver-local-serve' is registered at RunLevel=Highest." -ForegroundColor Cyan+ Write-Host " cua-driver-local autostart status (inspect)" -ForegroundColor Cyan+ Write-Host " cua-driver-local autostart disable (remove)" -ForegroundColor Cyan+ Write-Host " cua-driver-local autostart kick (start now without re-logging)" -ForegroundColor CyanWrite-Host ""} else {# Opt-out branch (-NoAutoStart or -AutoStart:`$false`).Write-Host ""Write-Host "Auto-start at logon (NOT enabled - re-run without -NoAutoStart to register, or:):" -ForegroundColor Cyan- Write-Host " cua-driver autostart enable (register Scheduled Task at RunLevel=Highest)" -ForegroundColor Cyan- Write-Host " cua-driver autostart kick (start now without re-logging)" -ForegroundColor Cyan- Write-Host " cua-driver autostart status (inspect)" -ForegroundColor Cyan- Write-Host " cua-driver autostart disable (remove)" -ForegroundColor Cyan+ Write-Host " cua-driver-local autostart enable (register Scheduled Task at RunLevel=Highest)" -ForegroundColor Cyan+ Write-Host " cua-driver-local autostart kick (start now without re-logging)" -ForegroundColor Cyan+ Write-Host " cua-driver-local autostart status (inspect)" -ForegroundColor Cyan+ Write-Host " cua-driver-local autostart disable (remove)" -ForegroundColor CyanWrite-Host ""}diff --git a/libs/cua-driver/scripts/install-local.sh b/libs/cua-driver/scripts/install-local.shindex ea2f630882..de2863616c 100755--- a/libs/cua-driver/scripts/install-local.sh+++ b/libs/cua-driver/scripts/install-local.sh@@ -2,7 +2,8 @@# cua-driver local/debug installer — Rust backend only.## This script is for developers working on the checked-out tree. It builds-# cua-driver from libs/cua-driver/rust and installs the cross-platform binary.+# cua-driver from libs/cua-driver/rust and installs it as `cua-driver-local`,+# separate from any released `cua-driver` installation.## Flags (forwarded verbatim to the Rust helper):# --release build the release configuration (default: debug)diff --git a/libs/cua-driver/scripts/tests/test_uninstall_local.py b/libs/cua-driver/scripts/tests/test_uninstall_local.pynew file mode 100644index 0000000000..d42282f4cf--- /dev/null+++ b/libs/cua-driver/scripts/tests/test_uninstall_local.py@@ -0,0 +1,182 @@+from __future__ import annotations++import json+import os+from pathlib import Path+import subprocess+++REPO_ROOT = Path(__file__).resolve().parents[4]+UNINSTALL_LOCAL = REPO_ROOT / "libs/cua-driver/scripts/uninstall-local.sh"+SCRIPTS = REPO_ROOT / "libs/cua-driver/scripts"+++def _executable(path: Path, body: str) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(f"#!/bin/sh\n{body}", encoding="utf-8")+ path.chmod(0o755)+++def test_unix_local_uninstall_removes_owned_links_and_preserves_release(tmp_path: Path) -> None:+ home = tmp_path / "home"+ fake_bin = tmp_path / "fake-bin"+ local_home = home / ".cua-driver-local"+ release_home = home / ".cua-driver"+ local_bin = home / ".local/bin"+ local_cache = home / ".cache/cua-driver-local"+ release_cache = home / ".cache/cua-driver"+ for path in (fake_bin, local_home, release_home, local_bin, local_cache, release_cache):+ path.mkdir(parents=True, exist_ok=True)++ local_marker = local_home / "packages/current/cua-driver-local"+ local_marker.parent.mkdir(parents=True)+ local_marker.write_text("local\n", encoding="utf-8")++ _executable(fake_bin / "uname", "printf 'Linux\\n'")+ _executable(fake_bin / "pkill", "exit 0")+ _executable(fake_bin / "systemctl", "exit 0")++ local_cli = local_bin / "cua-driver-local"+ local_cli.symlink_to(local_home / "packages/current/cua-driver-local")+ release_cli = local_bin / "cua-driver"+ release_cli.symlink_to(release_home / "packages/current/cua-driver")++ local_skill = home / ".agents/skills/cua-driver"+ local_skill.parent.mkdir(parents=True)+ local_skill.symlink_to(local_home / "skills/cua-driver")++ local_unit = home / ".config/systemd/user/cua-driver-local.service"+ release_unit = home / ".config/systemd/user/cua-driver.service"+ local_unit.parent.mkdir(parents=True)+ local_unit.write_text("local\n", encoding="utf-8")+ release_unit.write_text("release\n", encoding="utf-8")++ claude_json = home / ".claude.json"+ claude_json.write_text(+ json.dumps(+ {+ "mcpServers": {+ "local": {"command": str(local_cli), "args": ["mcp"]},+ "release": {"command": str(release_cli), "args": ["mcp"]},+ }+ }+ ),+ encoding="utf-8",+ )++ env = os.environ.copy()+ env.update(+ {+ "HOME": str(home),+ "PATH": f"{fake_bin}:/usr/bin:/bin",+ "CUA_DRIVER_LOCAL_HOME": str(local_home),+ "CUA_DRIVER_LOCAL_INSTALL_DIR": str(local_bin),+ }+ )+ result = subprocess.run(+ ["/bin/bash", str(UNINSTALL_LOCAL), "--force", "--keep-tcc"],+ cwd=REPO_ROOT,+ env=env,+ text=True,+ capture_output=True,+ check=False,+ )+ assert result.returncode == 0, result.stdout + result.stderr++ assert not local_cli.exists() and not local_cli.is_symlink()+ assert not local_skill.exists() and not local_skill.is_symlink()+ assert not local_home.exists()+ assert not local_cache.exists()+ assert not local_unit.exists()++ assert release_cli.is_symlink()+ assert release_home.exists()+ assert release_cache.exists()+ assert release_unit.exists()+ remaining = json.loads(claude_json.read_text(encoding="utf-8"))["mcpServers"]+ assert set(remaining) == {"release"}+++def test_unix_local_uninstall_keeps_shared_skill_link_owned_by_release(tmp_path: Path) -> None:+ home = tmp_path / "home"+ fake_bin = tmp_path / "fake-bin"+ release_skill_target = home / ".cua-driver/skills/cua-driver"+ release_skill_target.mkdir(parents=True)+ skill_link = home / ".agents/skills/cua-driver"+ skill_link.parent.mkdir(parents=True)+ skill_link.symlink_to(release_skill_target)+ _executable(fake_bin / "uname", "printf 'Linux\\n'")+ _executable(fake_bin / "pkill", "exit 0")++ env = os.environ.copy()+ env.update({"HOME": str(home), "PATH": f"{fake_bin}:/usr/bin:/bin"})+ result = subprocess.run(+ ["/bin/bash", str(UNINSTALL_LOCAL), "--force", "--keep-tcc"],+ cwd=REPO_ROOT,+ env=env,+ text=True,+ capture_output=True,+ check=False,+ )+ assert result.returncode == 0, result.stdout + result.stderr+ assert skill_link.is_symlink()+ assert skill_link.resolve() == release_skill_target+++def test_local_uninstall_contract_is_explicit_on_both_platforms() -> None:+ unix = (SCRIPTS / "uninstall-local.sh").read_text()+ windows = (SCRIPTS / "uninstall-local.ps1").read_text(encoding="utf-8-sig")++ for token in (+ "/Applications/CuaDriverLocal.app",+ "com.trycua.driver.local",+ ".cua-driver-local",+ "cua-driver-local.service",+ "com.trycua.cua-driver-local.plist",+ ):+ assert token in unix+ for token in (+ "cua-driver-local-serve",+ "cua-driver-uia-local",+ ".cua-driver-local",+ "Programs\\Cua\\cua-driver-local\\bin",+ ):+ assert token in windows+ assert "Test-LocalLinkTarget" in windows+ assert "is_local_target" in unix+ assert "LOCAL_HOME_MARKER" in unix+ assert "$LocalHomeMarker" in windows+ assert "Remove-Item -LiteralPath $HomeDir -Force -Recurse" not in windows+ assert 'rm -rf "$HOME_DIR"' not in unix+ assert "--validate-only" in unix+ assert "$ValidateOnly" in windows+++def test_unix_local_uninstall_rejects_release_home_override(tmp_path: Path) -> None:+ home = tmp_path / "home"+ home.mkdir()+ env = os.environ.copy()+ env.update(+ {+ "HOME": str(home),+ "CUA_DRIVER_LOCAL_HOME": str(home / ".cua-driver"),+ }+ )+ result = subprocess.run(+ ["/bin/bash", str(UNINSTALL_LOCAL), "--validate-only"],+ cwd=REPO_ROOT,+ env=env,+ text=True,+ capture_output=True,+ check=False,+ )+ assert result.returncode == 2+ assert "release-owned local home" in result.stderr+++def test_release_uninstallers_do_not_target_local_identity() -> None:+ for name in ("uninstall.sh", "uninstall.ps1"):+ script = (SCRIPTS / name).read_text(encoding="utf-8-sig")+ assert "CuaDriverLocal" not in script+ assert ".cua-driver-local" not in script+ assert "cua-driver-local-serve" not in scriptdiff --git a/libs/cua-driver/scripts/uninstall-local.ps1 b/libs/cua-driver/scripts/uninstall-local.ps1new file mode 100644index 0000000000..bb4b3ed042--- /dev/null+++ b/libs/cua-driver/scripts/uninstall-local.ps1@@ -0,0 +1,186 @@+# Remove only the source-built cua-driver-local product on Windows.+[CmdletBinding()]+param([switch]$Force, [switch]$ValidateOnly)++Set-StrictMode -Version Latest+$ErrorActionPreference = "Stop"++$TaskName = "cua-driver-local-serve"+$HomeDir = if ($env:CUA_DRIVER_LOCAL_HOME) { $env:CUA_DRIVER_LOCAL_HOME } else { Join-Path $env:USERPROFILE ".cua-driver-local" }+$VisibleBinDir = if ($env:CUA_DRIVER_LOCAL_INSTALL_DIR) { $env:CUA_DRIVER_LOCAL_INSTALL_DIR } else { Join-Path $env:LOCALAPPDATA "Programs\Cua\cua-driver-local\bin" }+$RuntimeDir = Join-Path $env:LOCALAPPDATA "cua-driver-local"+$ReleaseHome = Join-Path $env:USERPROFILE ".cua-driver"+$ReleaseBinDir = Join-Path $env:LOCALAPPDATA "Programs\Cua\cua-driver\bin"+if (-not [IO.Path]::IsPathRooted($HomeDir) -or $HomeDir -eq $env:USERPROFILE -or $HomeDir -eq $ReleaseHome) {+ throw "refusing unsafe or release-owned local home: $HomeDir"+}+if (-not [IO.Path]::IsPathRooted($VisibleBinDir) -or $VisibleBinDir -eq $ReleaseBinDir) {+ throw "refusing unsafe or release-owned local bin path: $VisibleBinDir"+}++function Write-Step([string]$Message) { Write-Host "==> $Message" }+function Test-IsReparsePoint([string]$Path) {+ if (-not (Test-Path -LiteralPath $Path)) { return $false }+ $item = Get-Item -LiteralPath $Path -Force+ return [bool]($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint)+}+function Test-LocalLinkTarget([string]$Path) {+ if (-not (Test-IsReparsePoint $Path)) { return $false }+ $item = Get-Item -LiteralPath $Path -Force+ $targetProperty = $item.PSObject.Properties['Target']+ if (-not $targetProperty) { return $false }+ $targets = @($targetProperty.Value)+ foreach ($target in $targets) {+ $prefix = $HomeDir.TrimEnd('\') + '\'+ if ($target -and ($target -eq $HomeDir -or $target.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase))) { return $true }+ }+ return $false+}++if ($ValidateOnly) {+ Write-Output "cli=$(Join-Path $VisibleBinDir 'cua-driver-local.exe')"+ Write-Output "home=$HomeDir"+ Write-Output "runtime=$RuntimeDir"+ Write-Output "task=$TaskName"+ Write-Output "processes=cua-driver-local,cua-driver-uia-local"+ exit 0+}++if (-not $Force) {+ $reply = Read-Host "Remove the local cua-driver identity and its state? [y/N]"+ if ($reply -notmatch '^(y|yes)$') { Write-Step "cancelled"; exit 0 }+}++# The local task may be Highest IL. Fail safely with an actionable message+# instead of falling through into a partial removal.+$previousErrorAction = $ErrorActionPreference+$ErrorActionPreference = 'Continue'+try {+ & schtasks.exe /Query /TN $TaskName 2>$null | Out-Null+ $taskExists = ($LASTEXITCODE -eq 0)+} finally {+ $ErrorActionPreference = $previousErrorAction+}+if ($taskExists) {+ $ErrorActionPreference = 'Continue'+ try {+ & schtasks.exe /End /TN $TaskName 2>$null | Out-Null+ & schtasks.exe /Delete /TN $TaskName /F 2>$null | Out-Null+ $deleteExitCode = $LASTEXITCODE+ } finally {+ $ErrorActionPreference = $previousErrorAction+ }+ if ($deleteExitCode -ne 0) { throw "could not remove $TaskName; rerun from an elevated PowerShell" }+ Write-Step "removed scheduled task $TaskName"+}++Get-Process -Name "cua-driver-local","cua-driver-uia-local" -ErrorAction SilentlyContinue |+ Stop-Process -Force -ErrorAction SilentlyContinue++# The visible bin path is local-only, but still require the junction shape the+# installer creates before removing it.+$LocalBinOwned = $false+if (Test-Path -LiteralPath $VisibleBinDir) {+ if (-not (Test-LocalLinkTarget $VisibleBinDir)) {+ throw "$VisibleBinDir does not point into the local package home; refusing to remove it"+ }+ $LocalBinOwned = $true+ Remove-Item -LiteralPath $VisibleBinDir -Force -Recurse+ Write-Step "removed local bin junction $VisibleBinDir"+}++# Shared skill names are removed only when the reparse target belongs to the+# local package home. Release and hand-managed links are preserved.+$SkillLinks = @(+ (Join-Path $env:USERPROFILE ".claude\skills\cua-driver"),+ (Join-Path $env:USERPROFILE ".agents\skills\cua-driver"),+ (Join-Path $env:USERPROFILE ".openclaw\skills\cua-driver"),+ (Join-Path $env:APPDATA "opencode\skills\cua-driver"),+ (Join-Path $env:USERPROFILE ".gemini\skills\cua-driver"),+ (Join-Path $env:USERPROFILE ".hermes\skills\cua-driver")+)+foreach ($link in $SkillLinks) {+ if (Test-LocalLinkTarget $link) {+ Remove-Item -LiteralPath $link -Force -Recurse+ Write-Step "removed local skill link $link"+ }+}++# Remove Claude MCP entries only when command/args point at the local command+# or package home. A same-named release registration is retained.+$ClaudeJson = Join-Path $env:USERPROFILE ".claude.json"+if (Test-Path -LiteralPath $ClaudeJson) {+ $data = Get-Content -LiteralPath $ClaudeJson -Raw | ConvertFrom-Json+ $changed = $false+ function Remove-LocalServers($servers) {+ if (-not $servers) { return }+ foreach ($property in @($servers.PSObject.Properties)) {+ $server = $property.Value+ $commandProperty = $server.PSObject.Properties['command']+ $argsProperty = $server.PSObject.Properties['args']+ $parts = @()+ if ($commandProperty) { $parts += @($commandProperty.Value) }+ if ($argsProperty) { $parts += @($argsProperty.Value) }+ $joined = ($parts | Where-Object { $_ -is [string] }) -join ' '+ if ($joined.Contains("cua-driver-local") -or $joined.Contains($HomeDir)) {+ $servers.PSObject.Properties.Remove($property.Name)+ $script:changed = $true+ }+ }+ }+ $mcpServersProperty = $data.PSObject.Properties['mcpServers']+ if ($mcpServersProperty) { Remove-LocalServers $mcpServersProperty.Value }+ $projectsProperty = $data.PSObject.Properties['projects']+ if ($projectsProperty) {+ foreach ($project in $projectsProperty.Value.PSObject.Properties) {+ $projectServers = $project.Value.PSObject.Properties['mcpServers']+ if ($projectServers) { Remove-LocalServers $projectServers.Value }+ }+ }+ if ($changed) {+ $backup = "$ClaudeJson.bak-cua-driver-local-uninstall-$(Get-Date -Format yyyyMMddHHmmss)"+ Copy-Item -LiteralPath $ClaudeJson -Destination $backup+ $data | ConvertTo-Json -Depth 100 | Set-Content -LiteralPath $ClaudeJson -Encoding UTF8+ Write-Step "removed local Claude MCP registrations (backup: $backup)"+ }+}++# CUA_DRIVER_LOCAL_HOME is caller-controlled. Require the installer-created+# executable marker and remove only known runtime-owned children; never+# recursively delete the arbitrary override root or unrelated files within it.+$LocalHomeMarker = Join-Path $HomeDir "packages\current\cua-driver-local.exe"+if (Test-Path -LiteralPath $LocalHomeMarker) {+ foreach ($child in @("packages", "skills")) {+ $path = Join-Path $HomeDir $child+ if (Test-Path -LiteralPath $path) { Remove-Item -LiteralPath $path -Force -Recurse }+ }+ foreach ($file in @(+ ".installation_recorded", ".telemetry_enabled", ".telemetry_id",+ ".telemetry_install_channel", ".tcc-signing-identity", "config.json",+ "serve.err.log", "serve.out.log", "version_check.json"+ )) {+ $path = Join-Path $HomeDir $file+ if (Test-Path -LiteralPath $path) { Remove-Item -LiteralPath $path -Force }+ }+ if (@(Get-ChildItem -LiteralPath $HomeDir -Force).Count -eq 0) {+ Remove-Item -LiteralPath $HomeDir -Force+ Write-Step "removed empty local home $HomeDir"+ } else {+ Write-Step "removed local runtime payloads from $HomeDir; preserved unrelated files"+ }+} elseif (Test-Path -LiteralPath $HomeDir) {+ Write-Step "$HomeDir has no cua-driver-local install marker; leaving it untouched"+}+if (Test-Path -LiteralPath $RuntimeDir) {+ Remove-Item -LiteralPath $RuntimeDir -Force -Recurse+ Write-Step "removed $RuntimeDir"+}++# Remove only the exact local PATH entry.+$userPath = [Environment]::GetEnvironmentVariable('Path', 'User')+if ($userPath -and $LocalBinOwned) {+ $filtered = @(($userPath -split ';') | Where-Object { $_ -and ($_.TrimEnd('\') -ne $VisibleBinDir.TrimEnd('\')) })+ [Environment]::SetEnvironmentVariable('Path', ($filtered -join ';'), 'User')+}++Write-Step "cua-driver-local uninstalled; release cua-driver was left untouched"diff --git a/libs/cua-driver/scripts/uninstall-local.sh b/libs/cua-driver/scripts/uninstall-local.shnew file mode 100755index 0000000000..410b49b363--- /dev/null+++ b/libs/cua-driver/scripts/uninstall-local.sh@@ -0,0 +1,228 @@+#!/usr/bin/env bash+# Remove only the source-built cua-driver-local product. The released+# cua-driver installation has different names and paths and is never touched.+set -euo pipefail++RESET_TCC=1+FORCE=0+VALIDATE_ONLY=0+while [[ $# -gt 0 ]]; do+ case "$1" in+ --keep-tcc) RESET_TCC=0 ;;+ --reset-tcc) RESET_TCC=1 ;;+ --force) FORCE=1 ;;+ --validate-only) VALIDATE_ONLY=1 ;;+ --help|-h)+ echo "Usage: $0 [--force] [--keep-tcc] [--validate-only]"+ exit 0+ ;;+ *) echo "error: unknown option: $1" >&2; exit 2 ;;+ esac+ shift+done++OS="$(uname -s 2>/dev/null || echo unknown)"+HOME_DIR="${CUA_DRIVER_LOCAL_HOME:-$HOME/.cua-driver-local}"+BIN_DIR="${CUA_DRIVER_LOCAL_INSTALL_DIR:-$HOME/.local/bin}"+CLI_LINK="$BIN_DIR/cua-driver-local"+APP_BUNDLE="/Applications/CuaDriverLocal.app"+if [[ "$OS" == "Darwin" ]]; then+ CACHE_DIR="$HOME/Library/Caches/cua-driver-local"+else+ CACHE_DIR="$HOME/.cache/cua-driver-local"+fi+LAUNCHAGENT="$HOME/Library/LaunchAgents/com.trycua.cua-driver-local.plist"+SYSTEMD_UNIT="$HOME/.config/systemd/user/cua-driver-local.service"++log() { printf '==> %s\n' "$*"; }++case "$HOME_DIR" in+ /*) ;;+ *) echo "error: CUA_DRIVER_LOCAL_HOME must be an absolute path" >&2; exit 2 ;;+esac+if [[ "$HOME_DIR" == "$HOME" || "$HOME_DIR" == "$HOME/.cua-driver" || "$HOME_DIR" == "/" ]]; then+ echo "error: refusing unsafe or release-owned local home: $HOME_DIR" >&2+ exit 2+fi+case "$BIN_DIR" in+ /*) ;;+ *) echo "error: CUA_DRIVER_LOCAL_INSTALL_DIR must be an absolute path" >&2; exit 2 ;;+esac++if [[ "$VALIDATE_ONLY" == "1" ]]; then+ printf 'cli=%s\nhome=%s\ncache=%s\napp=%s\nbundle=com.trycua.driver.local\nlaunchagent=%s\nsystemd=%s\n' \+ "$CLI_LINK" "$HOME_DIR" "$CACHE_DIR" "$APP_BUNDLE" "$LAUNCHAGENT" "$SYSTEMD_UNIT"+ exit 0+fi++if [[ "$FORCE" != "1" ]]; then+ printf 'Remove the local cua-driver identity and its state? [y/N] '+ read -r reply+ case "$reply" in y|Y|yes|YES) ;; *) log "cancelled"; exit 0 ;; esac+fi++resolve_link() {+ local link="$1" target+ [[ -L "$link" ]] || { printf ''; return; }+ if target="$(realpath "$link" 2>/dev/null)"; then+ printf '%s' "$target"+ return+ fi+ target="$(readlink "$link" 2>/dev/null || true)"+ case "$target" in+ /*) printf '%s' "$target" ;;+ *) printf '%s/%s' "$(cd -- "$(dirname -- "$link")" && pwd)" "$target" ;;+ esac+}++is_local_target() {+ case "$1" in+ "$HOME_DIR"/*|"$APP_BUNDLE"/*) return 0 ;;+ *) return 1 ;;+ esac+}++# Stop only local autostart/process identities.+if [[ "$OS" == "Darwin" && -f "$LAUNCHAGENT" ]]; then+ launchctl unload "$LAUNCHAGENT" 2>/dev/null || true+ rm -f "$LAUNCHAGENT"+ log "removed LaunchAgent $LAUNCHAGENT"+elif [[ "$OS" == "Linux" && -f "$SYSTEMD_UNIT" ]]; then+ if command -v systemctl >/dev/null 2>&1; then+ systemctl --user disable --now cua-driver-local.service 2>/dev/null || true+ fi+ rm -f "$SYSTEMD_UNIT"+ log "removed systemd user unit $SYSTEMD_UNIT"+fi+pkill -x cua-driver-local >/dev/null 2>&1 || true++# Revoke only the local bundle's TCC rows, while LaunchServices can resolve it.+if [[ "$OS" == "Darwin" && "$RESET_TCC" == "1" ]] && command -v tccutil >/dev/null 2>&1; then+ if [[ -d "$APP_BUNDLE" ]]; then+ LSREGISTER="/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister"+ [[ ! -x "$LSREGISTER" ]] || "$LSREGISTER" -f "$APP_BUNDLE" >/dev/null 2>&1 || true+ fi+ for service in Accessibility ScreenCapture AppleEvents; do+ tccutil reset "$service" com.trycua.driver.local >/dev/null 2>&1 || true+ done+ log "revoked TCC grants for com.trycua.driver.local"+fi++# Remove the CLI only if it is an installer-created link into the local product.+if [[ -L "$CLI_LINK" ]]; then+ target="$(resolve_link "$CLI_LINK")"+ if is_local_target "$target"; then+ rm -f "$CLI_LINK"+ log "removed $CLI_LINK"+ else+ log "$CLI_LINK points outside the local install; leaving it"+ fi+elif [[ -e "$CLI_LINK" ]]; then+ log "$CLI_LINK is not a symlink; leaving it"+fi++# Skill links use the shared pack name, so target ownership is mandatory.+for skill_link in \+ "$HOME/.claude/skills/cua-driver" \+ "$HOME/.agents/skills/cua-driver" \+ "$HOME/.openclaw/skills/cua-driver" \+ "$HOME/.config/opencode/skills/cua-driver" \+ "$HOME/.gemini/skills/cua-driver" \+ "$HOME/.hermes/skills/cua-driver"; do+ if [[ -L "$skill_link" ]]; then+ target="$(resolve_link "$skill_link")"+ if is_local_target "$target"; then+ rm -f "$skill_link"+ log "removed local skill link $skill_link"+ fi+ fi+done++# Scrub Claude registrations only when their command/args point at local paths.+CLAUDE_JSON="$HOME/.claude.json"+if [[ -f "$CLAUDE_JSON" ]] && command -v python3 >/dev/null 2>&1; then+ CLAUDE_JSON="$CLAUDE_JSON" LOCAL_HOME="$HOME_DIR" LOCAL_APP="$APP_BUNDLE" python3 <<'PY'+import json, os, shutil, tempfile, time++path = os.environ["CLAUDE_JSON"]+try:+ with open(path, encoding="utf-8") as handle:+ data = json.load(handle)+except (OSError, ValueError):+ raise SystemExit(0)++anchors = ("cua-driver-local", os.environ["LOCAL_HOME"], os.environ["LOCAL_APP"])+removed = []++def is_local(server):+ if not isinstance(server, dict):+ return False+ values = [server.get("command", "")]+ args = server.get("args", [])+ values.extend(args if isinstance(args, list) else [args])+ joined = " ".join(value for value in values if isinstance(value, str))+ return any(anchor and anchor in joined for anchor in anchors)++def scrub(servers, scope):+ if not isinstance(servers, dict):+ return+ for name in list(servers):+ if is_local(servers[name]):+ del servers[name]+ removed.append(f"{scope}:{name}")++scrub(data.get("mcpServers"), "user")+for project_name, project in (data.get("projects") or {}).items():+ if isinstance(project, dict):+ scrub(project.get("mcpServers"), f"project:{project_name}")++if removed:+ backup = f"{path}.bak-cua-driver-local-uninstall-{int(time.time())}"+ shutil.copy2(path, backup)+ fd, temporary = tempfile.mkstemp(prefix=".claude.json.", dir=os.path.dirname(path) or ".", text=True)+ 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)+ print(f"==> removed local Claude MCP registration(s): {', '.join(removed)}")+PY+fi++# Exact local-only directories. The release app, state, cache and services use+# names without the -local suffix and cannot be reached by these paths.+[[ ! -d "$CACHE_DIR" ]] || { rm -rf "$CACHE_DIR"; log "removed $CACHE_DIR"; }++# A caller may override CUA_DRIVER_LOCAL_HOME, so never recursively delete that+# root. Require the installer's local executable marker, remove only known+# runtime-owned children, and leave any unrelated files in place.+LOCAL_HOME_MARKER="$HOME_DIR/packages/current/cua-driver-local"+if [[ -e "$LOCAL_HOME_MARKER" || -L "$LOCAL_HOME_MARKER" ]]; then+ rm -rf "$HOME_DIR/packages" "$HOME_DIR/skills"+ rm -f \+ "$HOME_DIR/.installation_recorded" \+ "$HOME_DIR/.telemetry_enabled" \+ "$HOME_DIR/.telemetry_id" \+ "$HOME_DIR/.telemetry_install_channel" \+ "$HOME_DIR/.tcc-signing-identity" \+ "$HOME_DIR/config.json" \+ "$HOME_DIR/serve.err.log" \+ "$HOME_DIR/serve.out.log" \+ "$HOME_DIR/version_check.json"+ if rmdir "$HOME_DIR" 2>/dev/null; then+ log "removed empty local home $HOME_DIR"+ else+ log "removed local runtime payloads from $HOME_DIR; preserved unrelated files"+ fi+elif [[ -d "$HOME_DIR" ]]; then+ log "$HOME_DIR has no cua-driver-local install marker; leaving it untouched"+fi+if [[ "$OS" == "Darwin" && -d "$APP_BUNDLE" ]]; then+ if [[ -w "$(dirname "$APP_BUNDLE")" ]]; then+ rm -rf "$APP_BUNDLE"+ else+ sudo rm -rf "$APP_BUNDLE"+ fi+ log "removed $APP_BUNDLE"+fi++log "cua-driver-local uninstalled; release cua-driver was left untouched"diff --git a/libs/cua-driver/tests/runners/macos-lume/README.md b/libs/cua-driver/tests/runners/macos-lume/README.mdindex ca7122a83a..37ce3304b3 100644--- a/libs/cua-driver/tests/runners/macos-lume/README.md+++ b/libs/cua-driver/tests/runners/macos-lume/README.md@@ -30,14 +30,14 @@ that exact commit.- Keep the named golden VM stopped and never run tests in it directly.- Put no repository credentials, signing secrets, or maintainer private SSHkeys in the guest. A host public key is sufficient for source sync.-- Grant TCC permissions through `CuaDriver.app`. Do not edit `TCC.db`.+- Grant TCC permissions through `CuaDriverLocal.app`. Do not edit `TCC.db`.- Require a certificate-backed local signature. An ad-hoc signature invalidatesthe inherited grants on the next build.- Clone one worker per run, retrieve its evidence, then delete the worker.SIP-off does not grant or bypass TCC. It makes the disposable behavior lanerepeatable while the private seed carries grants obtained through the normal-`CuaDriver.app` prompt flow. The SIP-on check below owns the separate claim that+`CuaDriverLocal.app` prompt flow. The SIP-on check below owns the separate claim thatthe supported permission flow still works with normal platform protection.## Create the private seed@@ -159,7 +159,7 @@ identity` message before granting permissions through the app-owned flow:```bashbash libs/cua-driver/scripts/install-local.sh --release --autostart-~/.local/bin/cua-driver permissions grant+~/.local/bin/cua-driver-local permissions grant```Complete the Accessibility and Screen Recording prompts. Tahoe 26 also asks@@ -172,15 +172,15 @@ osascript -e \'tell application "System Events" to get name of first application process whose frontmost is true'# The installed app owns driver-side app enumeration.-~/.local/bin/cua-driver list_apps '{}'+~/.local/bin/cua-driver-local list_apps '{}'# A desktop screenshot triggers Tahoe's direct-capture/private-window prompt.-~/.local/bin/cua-driver call start_session \+~/.local/bin/cua-driver-local call start_session \'{"session":"seed-desktop-consent","capture_scope":"desktop"}'-~/.local/bin/cua-driver call get_desktop_state \+~/.local/bin/cua-driver-local call get_desktop_state \'{"session":"seed-desktop-consent"}' \> /tmp/cua-driver-seed-desktop-state.json-~/.local/bin/cua-driver call end_session '{"session":"seed-desktop-consent"}'+~/.local/bin/cua-driver-local call end_session '{"session":"seed-desktop-consent"}'jq -e '.screenshot_mime_type == "image/png"and .screenshot_width > 0@@ -189,20 +189,20 @@ jq -e '' /tmp/cua-driver-seed-desktop-state.json >/dev/null```-Choose Allow for both `Terminal` -> `System Events` and `CuaDriver` ->-`System Events`, and choose Allow on the CuaDriver direct-capture prompt. These+Choose Allow for both `Terminal` -> `System Events` and `CuaDriverLocal` ->+`System Events`, and choose Allow on the CuaDriverLocal direct-capture prompt. Theseare normal macOS consent flows; do not edit `TCC.db`. Rerun the commands andrequire them to finish without another prompt. Then verify the daemon's ownidentity, live capture permission, stable signature, and SIP state:```bash-~/.local/bin/cua-driver permissions status --json | jq -e '+~/.local/bin/cua-driver-local permissions status --json | jq -e '.accessibility == trueand .screen_recording == trueand .screen_recording_capturable == trueand .source.attribution == "driver-daemon"'-codesign -d -r- /Applications/CuaDriver.app 2>&1 | grep 'certificate leaf'+codesign -d -r- /Applications/CuaDriverLocal.app 2>&1 | grep 'certificate leaf'csrutil status```@@ -227,10 +227,10 @@ Lume version, CLT version, Rust version, Node version, and signing-certificatehash in the maintainer log. Also record that the following consent paths weregranted and then rerun without prompts:-- `CuaDriver.app`: Accessibility and Screen Recording+- `CuaDriverLocal.app`: Accessibility and Screen Recording- Terminal controlling System Events-- CuaDriver controlling System Events-- CuaDriver direct screen and audio capture without the system picker+- CuaDriverLocal controlling System Events+- CuaDriverLocal direct screen and audio capture without the system pickerBuild a new seed instead of updating one in place.@@ -317,9 +317,9 @@ golden image's inherited grants.4. In the VM display, reset only the disposable worker's grants:```bash- tccutil reset Accessibility com.trycua.driver- tccutil reset ScreenCapture com.trycua.driver- ~/.local/bin/cua-driver permissions grant+ tccutil reset Accessibility com.trycua.driver.local+ tccutil reset ScreenCapture com.trycua.driver.local+ ~/.local/bin/cua-driver-local permissions grant```5. Complete the prompts and require the same four-fielddiff --git a/libs/cua-driver/tests/runners/macos-lume/run-all.sh b/libs/cua-driver/tests/runners/macos-lume/run-all.shindex 46866e3df4..2aad4cfb8c 100755--- a/libs/cua-driver/tests/runners/macos-lume/run-all.sh+++ b/libs/cua-driver/tests/runners/macos-lume/run-all.sh@@ -139,14 +139,14 @@ echo "[INSTALL] Building and installing ${SOURCE_SHA} with the golden signing idbash "${DRIVER_ROOT}/scripts/install-local.sh" --release --autostart \2>&1 | tee "${ARTIFACT_DIR}/install-local.log"-codesign -d -r- /Applications/CuaDriver.app \+codesign -d -r- /Applications/CuaDriverLocal.app \> "${ARTIFACT_DIR}/codesign-requirement.txt" 2>&1if ! grep -Fq "certificate leaf" "${ARTIFACT_DIR}/codesign-requirement.txt"; then- echo "CuaDriver.app is not signed with the golden image's stable certificate identity" >&2+ echo "CuaDriverLocal.app is not signed with the golden image's stable certificate identity" >&2exit 1fi-INSTALLED_BIN="${HOME}/.local/bin/cua-driver"+INSTALLED_BIN="${HOME}/.local/bin/cua-driver-local"PERMISSIONS_FILE="${ARTIFACT_DIR}/permissions.json"PERMISSIONS_READY=0for _ in 1 2 3 4 5 6 7 8 9 10; do