Skip to content

armgit / cua

Public Imported from GitHub
0

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

fix(cua-driver): stop the serve daemon in the Unix release uninstaller (#3340)

umutcagand45c256bc826c
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
index 3ebccb4efb..e8b58ca93a 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
@@ -78,6 +78,12 @@ pub enum Command {
},
Stop {
socket: Option<String>,
+ /// `--expected-pid <pid>`: shut down only the daemon whose metadata
+ /// reports this PID. The release uninstaller validates a daemon's
+ /// executable identity and then asks this exact process to stop, so
+ /// an unrelated daemon that replaced the socket is never killed.
+ /// Absent for an ordinary `cua-driver stop`.
+ expected_pid: Option<u32>,
},
Revoke {
socket: Option<String>,
@@ -222,6 +228,8 @@ const VALUE_FLAGS: &[&str] = &[
"--session-policy",
"--capability-manifest",
"--pid-file",
+ // `stop --expected-pid <pid>` binds the shutdown to one daemon identity.
+ "--expected-pid",
"--type",
"--host-bundle-id",
"--pid",
@@ -708,6 +716,8 @@ pub fn parse_command() -> Command {
}
}
+ let expected_stop_pid = parse_expected_stop_pid(&args, positionals.first().copied());
+
if matches!(positionals.first().copied(), None | Some("mcp")) {
if let Some(flag) = serve_only_authorization_flag(&args) {
eprintln!("cua-driver mcp does not accept {flag}; authorization flags belong to `cua-driver serve`.");
@@ -780,7 +790,10 @@ pub fn parse_command() -> Command {
grants,
experimental_history: args.iter().any(|a| a == "--experimental-history"),
},
- Some("stop") => Command::Stop { socket },
+ Some("stop") => Command::Stop {
+ socket,
+ expected_pid: expected_stop_pid,
+ },
Some("revoke") => {
let all = args.iter().any(|a| a == "--all");
if all == approval_session.is_some() {
@@ -1027,6 +1040,28 @@ pub fn parse_command() -> Command {
}
/// Return the value of `--flag value` from argv, or `None`.
+/// Parse the stop-only `--expected-pid <pid>` selector.
+///
+/// The flag is rejected for every other subcommand on purpose. The release
+/// uninstaller always invokes `cua-driver --expected-pid <pid> stop`, so a
+/// helper from an older install — which knows nothing about the flag — exits
+/// non-zero on the unfamiliar argv instead of falling back to an unbound stop
+/// against whatever daemon owns the default socket.
+fn parse_expected_stop_pid(args: &[String], command: Option<&str>) -> Option<u32> {
+ let raw = flag_value(args, "--expected-pid")?;
+ if command != Some("stop") {
+ eprintln!("--expected-pid is valid only with `cua-driver stop`");
+ process::exit(64);
+ }
+ match raw.parse::<u32>() {
+ Ok(pid) if pid != 0 => Some(pid),
+ _ => {
+ eprintln!("--expected-pid requires a positive integer PID");
+ process::exit(64);
+ }
+ }
+}
+
fn flag_value(args: &[String], flag: &str) -> Option<String> {
let mut it = args.iter();
while let Some(a) = it.next() {
@@ -4743,6 +4778,34 @@ mod tests {
);
}
+ #[test]
+ fn expected_pid_keeps_stop_as_the_subcommand() {
+ let argv = args(&["--expected-pid", "42", "stop"]);
+ assert_eq!(positional_args(&argv), vec!["stop"]);
+ assert_eq!(parse_expected_stop_pid(&argv, Some("stop")), Some(42));
+
+ let with_socket = args(&["--socket", "/tmp/cua.sock", "--expected-pid", "42", "stop"]);
+ assert_eq!(positional_args(&with_socket), vec!["stop"]);
+ assert_eq!(
+ parse_expected_stop_pid(&with_socket, Some("stop")),
+ Some(42)
+ );
+ }
+
+ #[test]
+ fn expected_pid_is_absent_for_an_ordinary_stop() {
+ let argv = args(&["stop"]);
+ assert_eq!(parse_expected_stop_pid(&argv, Some("stop")), None);
+ }
+
+ #[test]
+ fn expected_pid_does_not_shadow_other_subcommands() {
+ // `status` still parses as the subcommand; the stop-only rejection
+ // itself exits the process and is covered by the uninstaller tests.
+ let argv = args(&["--expected-pid", "42", "status"]);
+ assert_eq!(positional_args(&argv), vec!["status"]);
+ }
+
#[test]
fn finite_call_tool_extraction_supports_subcommand_and_legacy_forms() {
assert_eq!(
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/main.rs b/libs/cua-driver/rust/crates/cua-driver/src/main.rs
index 04ba424156..26bbde1aca 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/main.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/main.rs
@@ -31,6 +31,7 @@ mod responsibility;
mod sdk_adapter;
mod serve;
mod skills;
+mod stop;
mod telemetry;
mod updater;
mod version_check;
@@ -822,9 +823,15 @@ fn main() {
}
}
}
- cli::Command::Stop { socket } => {
+ cli::Command::Stop {
+ socket,
+ expected_pid,
+ } => {
let sp = socket.unwrap_or_else(serve::default_socket_path);
- serve::run_stop_cmd(&sp);
+ match expected_pid {
+ Some(pid) => stop::run_pid_bound_stop_cmd(&sp, pid),
+ None => serve::run_stop_cmd(&sp),
+ }
}
cli::Command::Revoke {
socket,
@@ -1091,9 +1098,15 @@ fn main() -> anyhow::Result<()> {
.ok();
return Ok(());
}
- cli::Command::Stop { socket } => {
+ cli::Command::Stop {
+ socket,
+ expected_pid,
+ } => {
let sp = socket.unwrap_or_else(serve::default_socket_path);
- serve::run_stop_cmd(&sp);
+ match expected_pid {
+ Some(pid) => stop::run_pid_bound_stop_cmd(&sp, pid),
+ None => serve::run_stop_cmd(&sp),
+ }
return Ok(());
}
cli::Command::Revoke {
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/stop.rs b/libs/cua-driver/rust/crates/cua-driver/src/stop.rs
new file mode 100644
index 0000000000..e5b080cbe5
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver/src/stop.rs
@@ -0,0 +1,189 @@
+//! PID-bound daemon shutdown for `cua-driver stop --expected-pid <pid>`.
+//!
+//! The uninstaller validates a release daemon's executable identity before it
+//! asks the installed helper to stop that exact PID. `Command::Stop` routes
+//! here whenever the parser saw `--expected-pid`; the daemon metadata
+//! handshake and the shutdown request then share one connected transport so
+//! another daemon cannot replace the socket between those two operations. The
+//! daemon wire protocol is unchanged: both requests are the existing
+//! `metadata` and `shutdown` methods.
+
+use cua_driver_core::daemon::{DaemonMetadata, DaemonRequest, DaemonResponse};
+
+fn request(method: &str) -> DaemonRequest {
+ DaemonRequest {
+ method: method.to_owned(),
+ name: None,
+ args: None,
+ session_id: None,
+ observation_origin: None,
+ client_kind: None,
+ }
+}
+
+fn require_ok(response: DaemonResponse, operation: &str) -> anyhow::Result<serde_json::Value> {
+ if !response.ok {
+ anyhow::bail!(
+ "daemon {operation} request failed: {}",
+ response.error.unwrap_or_else(|| "unknown error".to_owned())
+ );
+ }
+ Ok(response.result.unwrap_or(serde_json::Value::Null))
+}
+
+#[cfg(unix)]
+fn pid_bound_shutdown(socket_path: &str, expected_pid: u32) -> anyhow::Result<()> {
+ use std::io::Read as _;
+ use std::os::unix::net::UnixStream;
+ use std::time::{Duration, Instant};
+
+ let mut stream = UnixStream::connect(socket_path)
+ .map_err(|error| anyhow::anyhow!("connect to {socket_path}: {error}"))?;
+ stream.set_write_timeout(Some(Duration::from_secs(5)))?;
+ stream.set_read_timeout(Some(Duration::from_secs(10)))?;
+ let mut writer = stream.try_clone()?;
+ let mut pending = Vec::<u8>::with_capacity(64 * 1024);
+
+ let mut exchange = |request: &DaemonRequest| -> anyhow::Result<DaemonResponse> {
+ let line = serde_json::to_string(request)? + "\n";
+ let write_deadline = Instant::now() + Duration::from_secs(120);
+ cua_driver_core::socket_io::write_all_with_retry(
+ &mut writer,
+ line.as_bytes(),
+ write_deadline,
+ )?;
+
+ let overall_deadline = Instant::now() + Duration::from_secs(120);
+ let mut chunk = [0_u8; 64 * 1024];
+ let response_line = loop {
+ if let Some(newline) = pending.iter().position(|&byte| byte == b'\n') {
+ let line = String::from_utf8_lossy(&pending[..newline]).into_owned();
+ pending.drain(..=newline);
+ break line;
+ }
+ match stream.read(&mut chunk) {
+ Ok(0) if pending.is_empty() => {
+ anyhow::bail!("daemon closed connection without response");
+ }
+ Ok(0) => {
+ let line = String::from_utf8_lossy(&pending).into_owned();
+ pending.clear();
+ break line;
+ }
+ Ok(read) => pending.extend_from_slice(&chunk[..read]),
+ Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
+ Err(error)
+ if matches!(
+ error.kind(),
+ std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
+ ) =>
+ {
+ if Instant::now() >= overall_deadline {
+ anyhow::bail!(
+ "timed out after 120s waiting for daemon response (received {} bytes so far)",
+ pending.len()
+ );
+ }
+ }
+ Err(error) => return Err(error.into()),
+ }
+ };
+ Ok(serde_json::from_str(&response_line)?)
+ };
+
+ let metadata_value = require_ok(exchange(&request("metadata"))?, "metadata")?;
+ let metadata: DaemonMetadata = serde_json::from_value(metadata_value)
+ .map_err(|error| anyhow::anyhow!("invalid daemon metadata: {error}"))?;
+ if metadata.pid != expected_pid {
+ anyhow::bail!(
+ "daemon pid mismatch (expected {expected_pid}, found {})",
+ metadata.pid
+ );
+ }
+
+ require_ok(exchange(&request("shutdown"))?, "shutdown")?;
+ Ok(())
+}
+
+#[cfg(target_os = "windows")]
+fn pid_bound_shutdown(socket_path: &str, expected_pid: u32) -> anyhow::Result<()> {
+ use std::io::{BufRead as _, BufReader, Write as _};
+ use std::time::{Duration, Instant};
+
+ let deadline = Instant::now() + Duration::from_secs(10);
+ let mut pipe = loop {
+ match std::fs::OpenOptions::new()
+ .read(true)
+ .write(true)
+ .open(socket_path)
+ {
+ Ok(pipe) => break pipe,
+ Err(error) if Instant::now() < deadline => {
+ let _ = error;
+ std::thread::sleep(Duration::from_millis(50));
+ }
+ Err(error) => {
+ return Err(anyhow::anyhow!("connect to {socket_path}: {error}"));
+ }
+ }
+ };
+ let mut reader = BufReader::new(pipe.try_clone()?);
+
+ let mut exchange = |request: &DaemonRequest| -> anyhow::Result<DaemonResponse> {
+ pipe.write_all((serde_json::to_string(request)? + "\n").as_bytes())?;
+ pipe.flush()?;
+ let mut response_line = String::new();
+ if reader.read_line(&mut response_line)? == 0 {
+ anyhow::bail!("daemon closed connection without response");
+ }
+ Ok(serde_json::from_str(response_line.trim_end())?)
+ };
+
+ let metadata_value = require_ok(exchange(&request("metadata"))?, "metadata")?;
+ let metadata: DaemonMetadata = serde_json::from_value(metadata_value)
+ .map_err(|error| anyhow::anyhow!("invalid daemon metadata: {error}"))?;
+ if metadata.pid != expected_pid {
+ anyhow::bail!(
+ "daemon pid mismatch (expected {expected_pid}, found {})",
+ metadata.pid
+ );
+ }
+
+ require_ok(exchange(&request("shutdown"))?, "shutdown")?;
+ Ok(())
+}
+
+#[cfg(not(any(unix, target_os = "windows")))]
+fn pid_bound_shutdown(_socket_path: &str, _expected_pid: u32) -> anyhow::Result<()> {
+ anyhow::bail!("--expected-pid is not supported on this platform")
+}
+
+pub fn run_pid_bound_stop_cmd(socket_path: &str, expected_pid: u32) {
+ // A PID-bound stop intentionally does not make an initial liveness probe:
+ // the very first connection is the one whose metadata is checked and whose
+ // shutdown is requested, closing the check/use race.
+ if let Err(error) = pid_bound_shutdown(socket_path, expected_pid) {
+ eprintln!("stop: {error}");
+ std::process::exit(1);
+ }
+
+ // Poll only after the authority-bound shutdown request has completed.
+ // These probes can use fresh connections safely because they confer no
+ // authority; they only verify that the selected endpoint disappeared.
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
+ loop {
+ let gone = if std::path::Path::new(socket_path).exists() {
+ false
+ } else {
+ !crate::serve::is_daemon_listening(socket_path)
+ };
+ if gone {
+ return;
+ }
+ if std::time::Instant::now() >= deadline {
+ eprintln!("Cua Driver daemon did not release socket within 2s");
+ std::process::exit(1);
+ }
+ std::thread::sleep(std::time::Duration::from_millis(50));
+ }
+}
diff --git a/libs/cua-driver/scripts/README.md b/libs/cua-driver/scripts/README.md
index a682099747..e1e3e5f8a6 100644
--- a/libs/cua-driver/scripts/README.md
+++ b/libs/cua-driver/scripts/README.md
@@ -94,3 +94,19 @@ 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.
+
+The release Unix uninstaller shuts down the release service before removing
+anything. It first requires the systemd/launchd supervisor to stop, then uses
+the daemon PID file to validate the installed release process and invokes the
+trusted installed helper as `cua-driver --expected-pid <pid> stop`. A helper
+that supports this option reads daemon metadata and requires the daemon PID to
+match before sending shutdown; older helpers reject this argv shape instead of
+silently stopping an unrelated default-socket daemon. The uninstaller escalates
+only the already-validated release PID if graceful shutdown is unavailable, and
+verifies the daemon stays stopped before cleanup begins.
+
+With a missing or stale PID file, the script performs only a narrow
+release-executable process check. It never signals an ambiguous process. If
+supervisor shutdown, ownership validation, process inspection, or final
+shutdown verification cannot be proven safe, uninstall aborts non-zero while
+the runtime is still in place.
diff --git a/libs/cua-driver/scripts/tests/test_uninstall_daemon_stop.py b/libs/cua-driver/scripts/tests/test_uninstall_daemon_stop.py
new file mode 100644
index 0000000000..b46e181ec7
--- /dev/null
+++ b/libs/cua-driver/scripts/tests/test_uninstall_daemon_stop.py
@@ -0,0 +1,300 @@
+"""Focused coverage for fail-closed Unix release daemon shutdown."""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import tempfile
+import threading
+import unittest
+
+
+REPO_ROOT = Path(__file__).resolve().parents[4]
+UNINSTALL = REPO_ROOT / "libs/cua-driver/scripts/uninstall.sh"
+
+
+def executable(path: Path, body: str) -> None:
+ path.write_text(f"#!/bin/sh\n{body}\n", encoding="utf-8")
+ path.chmod(0o755)
+
+
+def source(env: dict[str, str], body: str) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(
+ ["/bin/bash", "-c", f'source "{UNINSTALL}"\n{body}'],
+ cwd=REPO_ROOT,
+ env={**env, "CUA_DRIVER_UNINSTALL_TEST_SOURCE_ONLY": "1"},
+ text=True,
+ capture_output=True,
+ check=False,
+ )
+
+
+class DaemonStopTests(unittest.TestCase):
+ def setUp(self) -> None:
+ self.temp = tempfile.TemporaryDirectory()
+ self.root = Path(self.temp.name)
+ self.home = self.root / "home"
+ self.bin = self.root / "bin"
+ self.home.mkdir()
+ self.bin.mkdir()
+ self.map = self.root / "process-map"
+ self.map.touch()
+
+ executable(
+ self.bin / "pgrep",
+ f"awk -F'|' '$3 == \"alive\" {{ print $1 }}' '{self.map}' | "
+ "while IFS= read -r pid; do kill -0 \"$pid\" 2>/dev/null && printf '%s\\n' \"$pid\"; done",
+ )
+ executable(
+ self.bin / "ps",
+ f"""
+pid=""; prev=""
+for arg in "$@"; do [ "$prev" = -p ] && pid="$arg"; prev="$arg"; done
+awk -F'|' -v p="$pid" '$1 == p {{ print $2 }}' '{self.map}'
+""",
+ )
+ self.env = {
+ **os.environ,
+ "HOME": str(self.home),
+ "PATH": f"{self.bin}:/usr/bin:/bin",
+ }
+ self.processes: list[subprocess.Popen[bytes]] = []
+
+ def tearDown(self) -> None:
+ for process in self.processes:
+ if process.poll() is None:
+ process.kill()
+ process.wait(timeout=5)
+ self.temp.cleanup()
+
+ def spawn(self, command: str) -> tuple[subprocess.Popen[bytes], str]:
+ path = shutil.which(command)
+ if not path:
+ self.skipTest(f"{command} unavailable")
+ real = str(Path(path).resolve())
+ args = [path, "30"] if command == "sleep" else [path, "-f", "/dev/null"]
+ process = subprocess.Popen(args)
+ self.processes.append(process)
+ threading.Thread(target=process.wait, daemon=True).start()
+ with self.map.open("a", encoding="utf-8") as handle:
+ handle.write(f"{process.pid}|{real}|alive\n")
+ return process, real
+
+ def setup(self, pid_file: Path, helper: Path | None, identity: str) -> str:
+ return f"""
+OS=Linux
+HOME_DIR="$HOME/.cua-driver"
+LEGACY_HOME_DIR="$HOME/.cua-driver-rs"
+DAEMON_PID_FILE="{pid_file}"
+DAEMON_STOP_HELPER="{helper or ''}"
+DAEMON_EXECUTABLES=("{identity}")
+"""
+
+ def helper(self, target: subprocess.Popen[bytes], marker: Path | None = None) -> Path:
+ path = self.home / "cua-driver"
+ marker_line = (
+ f"printf '%s|%s|%s' \"$1\" \"$2\" \"$3\" > '{marker}'"
+ if marker
+ else ":"
+ )
+ executable(
+ path,
+ f"""
+if [ "$1" = "--expected-pid" ] && [ "$2" = "{target.pid}" ] && [ "$3" = stop ]; then
+ {marker_line}
+ awk -F'|' -v p='{target.pid}' 'BEGIN {{ OFS="|" }} $1 == p {{ $3="dead" }} {{ print }}' '{self.map}' > '{self.map}.tmp'
+ mv '{self.map}.tmp' '{self.map}'
+ kill {target.pid} 2>/dev/null || true
+ exit 0
+fi
+exit 1
+""",
+ )
+ return path
+
+ def old_helper(self, foreign: subprocess.Popen[bytes], marker: Path) -> Path:
+ path = self.home / "old-cua-driver"
+ executable(
+ path,
+ f"""
+if [ "$1" = stop ]; then
+ : > '{marker}'
+ kill {foreign.pid} 2>/dev/null || true
+ exit 0
+fi
+exit 2
+""",
+ )
+ return path
+
+ def run_stop(self, setup: str) -> subprocess.CompletedProcess[str]:
+ return source(
+ self.env,
+ setup
+ + """
+status=0
+stop_release_daemon || status=$?
+printf 'status=%s result=%s\n' "$status" "$DAEMON_STOP_RESULT"
+""",
+ )
+
+ def test_pid_file_and_trusted_stop_are_authoritative(self) -> None:
+ daemon, identity = self.spawn("sleep")
+ foreign, _ = self.spawn("tail")
+ pid_file = self.home / "cua-driver.pid"
+ pid_file.write_text(str(daemon.pid), encoding="utf-8")
+ marker = self.root / "expected-pid"
+
+ result = self.run_stop(self.setup(pid_file, self.helper(daemon, marker), identity))
+
+ self.assertIn("status=0 result=stopped", result.stdout)
+ self.assertEqual(
+ marker.read_text(encoding="utf-8"),
+ f"--expected-pid|{daemon.pid}|stop",
+ )
+ daemon.wait(timeout=5)
+ self.assertIsNone(foreign.poll())
+
+ def test_old_helper_cannot_receive_an_unbound_stop(self) -> None:
+ daemon, identity = self.spawn("sleep")
+ foreign, _ = self.spawn("tail")
+ pid_file = self.home / "cua-driver.pid"
+ pid_file.write_text(str(daemon.pid), encoding="utf-8")
+ marker = self.root / "old-helper-issued-stop"
+
+ result = self.run_stop(
+ self.setup(pid_file, self.old_helper(foreign, marker), identity)
+ )
+
+ self.assertIn("status=0 result=stopped", result.stdout)
+ self.assertFalse(marker.exists())
+ daemon.wait(timeout=5)
+ self.assertIsNone(foreign.poll())
+
+ def test_refused_handshake_is_reported_before_the_signal_fallback(self) -> None:
+ daemon, identity = self.spawn("sleep")
+ foreign, _ = self.spawn("tail")
+ pid_file = self.home / "cua-driver.pid"
+ pid_file.write_text(str(daemon.pid), encoding="utf-8")
+ refusing = self.home / "refusing-cua-driver"
+ executable(
+ refusing,
+ "printf 'stop: daemon pid mismatch (expected 1, found 2)\\n' >&2\nexit 1",
+ )
+
+ result = self.run_stop(self.setup(pid_file, refusing, identity))
+
+ # The helper's own diagnosis is the only signal that the socket was
+ # taken over by another daemon, so it must not be swallowed.
+ self.assertIn("trusted stop helper exited 1", result.stderr)
+ self.assertIn("daemon pid mismatch (expected 1, found 2)", result.stderr)
+ # The validated pid is still stopped, and only that pid.
+ self.assertIn("status=0 result=stopped", result.stdout)
+ daemon.wait(timeout=5)
+ self.assertIsNone(foreign.poll())
+
+ def test_history_purge_does_not_issue_a_second_stop(self) -> None:
+ marker = self.root / "purge-helper-argv"
+ helper = self.home / "purge-helper"
+ codesign = self.bin / "codesign"
+ executable(helper, f"printf '%s\\n' \"$*\" >> '{marker}'")
+ executable(codesign, "exit 0")
+
+ result = source(
+ self.env,
+ f"""
+status=0
+purge_linux_history "{helper}" 1 || status=$?
+purge_macos_history "/Applications/CuaDriver.app" "{helper}" 1 "{codesign}" || status=$?
+printf 'status=%s\n' "$status"
+""",
+ )
+
+ self.assertIn("status=0", result.stdout)
+ self.assertEqual(
+ marker.read_text(encoding="utf-8").splitlines(),
+ ["history purge-offline --yes", "history purge-offline --yes"],
+ )
+
+ def test_stale_pid_only_inspects_and_never_calls_helper_or_signals(self) -> None:
+ owned, identity = self.spawn("sleep")
+ pid_file = self.home / "cua-driver.pid"
+ pid_file.write_text("2147483646\n", encoding="utf-8")
+ marker = self.root / "helper-called"
+
+ result = self.run_stop(self.setup(pid_file, self.helper(owned, marker), identity))
+
+ self.assertIn("status=1 result=failed", result.stdout)
+ self.assertFalse(marker.exists())
+ self.assertIsNone(owned.poll())
+
+ def test_live_owned_pid_without_trusted_helper_fails_without_signal(self) -> None:
+ daemon, identity = self.spawn("sleep")
+ pid_file = self.home / "cua-driver.pid"
+ pid_file.write_text(str(daemon.pid), encoding="utf-8")
+
+ result = self.run_stop(self.setup(pid_file, None, identity))
+
+ self.assertIn("status=1 result=failed", result.stdout)
+ self.assertIn("trusted installed cua-driver stop helper is unavailable", result.stderr)
+ self.assertIsNone(daemon.poll())
+
+ def test_pgrep_error_fails_closed(self) -> None:
+ executable(self.bin / "pgrep", "exit 2")
+ pid_file = self.home / "missing.pid"
+
+ result = self.run_stop(self.setup(pid_file, None, "/missing/cua-driver"))
+
+ self.assertIn("status=1 result=failed", result.stdout)
+ self.assertIn("process inspection failed", result.stderr)
+
+ def test_pgrep_no_match_exit_one_is_clean(self) -> None:
+ executable(self.bin / "pgrep", "exit 1")
+ pid_file = self.home / "missing.pid"
+
+ result = self.run_stop(self.setup(pid_file, None, "/missing/cua-driver"))
+
+ self.assertIn("status=0 result=none", result.stdout)
+
+ def test_ps_failure_for_candidate_fails_closed(self) -> None:
+ executable(self.bin / "pgrep", "printf '2147483646\\n'; exit 0")
+ executable(self.bin / "ps", "exit 2")
+ pid_file = self.home / "missing.pid"
+
+ result = self.run_stop(self.setup(pid_file, None, "/missing/cua-driver"))
+
+ self.assertIn("status=1 result=failed", result.stdout)
+ self.assertIn("process inspection failed", result.stderr)
+
+ def test_supervisor_failure_aborts_before_runtime_removal(self) -> None:
+ tools = self.root / "main-bin"
+ tools.mkdir()
+ executable(tools / "id", "printf '501\\n'")
+ executable(tools / "uname", "printf 'Linux\\n'")
+ executable(tools / "systemctl", "exit 1")
+ os.symlink("/bin/rm", tools / "rm")
+ runtime = self.home / ".cua-driver/packages"
+ runtime.mkdir(parents=True)
+ unit = self.home / ".config/systemd/user/cua-driver.service"
+ unit.parent.mkdir(parents=True)
+ unit.write_text("[Service]\n", encoding="utf-8")
+
+ result = subprocess.run(
+ ["/bin/bash", str(UNINSTALL)],
+ cwd=REPO_ROOT,
+ env={**self.env, "PATH": f"{tools}:/usr/bin:/bin"},
+ text=True,
+ capture_output=True,
+ check=False,
+ )
+
+ self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
+ self.assertIn("failed to stop systemd user unit", result.stderr)
+ self.assertTrue(runtime.exists())
+ self.assertTrue(unit.exists())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/libs/cua-driver/scripts/uninstall.sh b/libs/cua-driver/scripts/uninstall.sh
index 9bcbbfe556..d98b9308d4 100755
--- a/libs/cua-driver/scripts/uninstall.sh
+++ b/libs/cua-driver/scripts/uninstall.sh
@@ -20,6 +20,10 @@
# - Claude MCP registrations in ~/.claude.json (cua-driver / cua-computer-use)
#
# Rust uninstall removes:
+# All hosts:
+# - the release supervisor and daemon are proven stopped before any files
+# are removed. A live PID must be owned by the installed release before
+# the trusted installed `cua-driver stop` path may escalate that PID.
# Linux:
# - ~/.local/bin/cua-driver symlink (only when it resolves to a
# cua-driver path — a Swift-driver symlink is left in place)
@@ -119,7 +123,6 @@ purge_macos_history() {
printf 'history_purge_incomplete: installed signed Cua Driver helper unavailable; preserved history state for retry\n' >&2
return 1
fi
- "$helper" stop >/dev/null 2>&1 || true
if ! "$helper" history purge-offline --yes; then
printf 'history_purge_incomplete: exact-namespace key destruction was not verified; preserved history state and app for retry\n' >&2
return 1
@@ -133,13 +136,181 @@ purge_linux_history() {
printf 'history_purge_incomplete: installed Cua Driver helper unavailable; preserved history state for retry\n' >&2
return 1
fi
- "$helper" stop >/dev/null 2>&1 || true
if ! "$helper" history purge-offline --yes; then
printf 'history_purge_incomplete: exact-namespace Secret Service key destruction was not verified; preserved history state and runtime for retry\n' >&2
return 1
fi
}
+daemon_pid_file_path() {
+ case "$OS" in
+ Darwin) printf '%s/Library/Caches/cua-driver/cua-driver.pid' "$HOME" ;;
+ Linux) printf '%s/.cache/cua-driver/cua-driver.pid' "$HOME" ;;
+ *) printf '/tmp/cua-driver.pid' ;;
+ esac
+}
+
+read_daemon_pid() {
+ local pid
+ [[ -r "$1" ]] || return 1
+ IFS= read -r pid < "$1" || true
+ [[ "$pid" =~ ^[1-9][0-9]*$ ]] || return 1
+ printf '%s' "$pid"
+}
+
+daemon_pid_alive() { kill -0 "$1" 2>/dev/null; }
+
+daemon_wait_for_exit() {
+ local pid="$1" attempts=0
+ while daemon_pid_alive "$pid"; do
+ [[ "$attempts" -lt 20 ]] || return 1
+ sleep 0.1 2>/dev/null || sleep 1 || true
+ attempts=$((attempts + 1))
+ done
+}
+
+daemon_process_identity() {
+ local pid="$1" identity=""
+ if [[ -L "/proc/$pid/exe" ]]; then
+ identity="$(readlink "/proc/$pid/exe" 2>/dev/null || true)"
+ identity="${identity% (deleted)}"
+ fi
+ if [[ -z "$identity" ]]; then
+ command -v ps >/dev/null 2>&1 || return 2
+ identity="$(ps -ww -o command= -p "$pid" 2>/dev/null)" || return 2
+ fi
+ identity="${identity#"${identity%%[![:space:]]*}"}"
+ identity="${identity%"${identity##*[![:space:]]}"}"
+ [[ -n "$identity" ]] || return 1
+ printf '%s' "$identity"
+}
+
+daemon_identity_matches_install() {
+ local identity="$1" executable
+ for executable in "${DAEMON_EXECUTABLES[@]:-}"; do
+ [[ -n "$executable" ]] || continue
+ case "$identity" in
+ "$executable"|"$executable"[[:space:]]*) return 0 ;;
+ esac
+ done
+ case "$identity" in
+ "$HOME_DIR"/packages/releases/*/cua-driver|"$HOME_DIR"/packages/releases/*/cua-driver[[:space:]]*) return 0 ;;
+ "$LEGACY_HOME_DIR"/packages/releases/*/cua-driver|"$LEGACY_HOME_DIR"/packages/releases/*/cua-driver[[:space:]]*) return 0 ;;
+ esac
+ return 1
+}
+
+daemon_pid_is_release() {
+ local identity
+ identity="$(daemon_process_identity "$1" 2>/dev/null)" || return 2
+ daemon_identity_matches_install "$identity"
+}
+
+# Missing/stale PID files never trigger a signal. This check only decides
+# whether uninstall can safely continue or must preserve the runtime and abort.
+release_daemon_fallback_pids() {
+ command -v pgrep >/dev/null 2>&1 || return 2
+ command -v ps >/dev/null 2>&1 || return 2
+ local uid pid identity candidates="" pgrep_status=0
+ uid="$(id -u 2>/dev/null || true)"
+ [[ "$uid" =~ ^[0-9]+$ ]] || return 2
+
+ candidates="$(pgrep -U "$uid" -f '(^|[[:space:]/])cua-driver([[:space:]]|$)' 2>/dev/null)" || pgrep_status=$?
+ case "$pgrep_status" in
+ 0) ;;
+ 1) return 0 ;;
+ *) return 2 ;;
+ esac
+
+ while IFS= read -r pid; do
+ [[ -n "$pid" ]] || continue
+ [[ "$pid" =~ ^[1-9][0-9]*$ ]] || return 2
+ identity="$(daemon_process_identity "$pid" 2>/dev/null)" || return 2
+ if daemon_identity_matches_install "$identity"; then
+ printf '%s\n' "$pid"
+ fi
+ done <<< "$candidates"
+}
+
+verify_release_daemon_absent() {
+ local pids="" status=0
+ pids="$(release_daemon_fallback_pids 2>/dev/null)" || status=$?
+ if [[ "$status" != "0" ]]; then
+ printf 'daemon_stop_incomplete: process inspection failed while verifying release daemon shutdown.\n' >&2
+ return 1
+ fi
+ if [[ -n "$pids" ]]; then
+ printf 'daemon_stop_incomplete: release cua-driver process remains but cannot be safely classified or signalled.\n' >&2
+ return 1
+ fi
+}
+
+stop_release_daemon() {
+ DAEMON_STOP_RESULT=none
+ local pid="" helper="${DAEMON_STOP_HELPER:-}" pid_file="${DAEMON_PID_FILE:-}" pid_identity_status=0
+ local helper_status=0 helper_stderr=""
+
+ if [[ -n "$pid_file" ]] && pid="$(read_daemon_pid "$pid_file" 2>/dev/null)" \
+ && daemon_pid_alive "$pid"; then
+ if daemon_pid_is_release "$pid"; then
+ if [[ -z "$helper" || ! -x "$helper" ]]; then
+ printf 'daemon_stop_incomplete: trusted installed cua-driver stop helper is unavailable for pid %s.\n' "$pid" >&2
+ DAEMON_STOP_RESULT=failed
+ return 1
+ fi
+ # Bind the graceful shutdown request to the exact PID whose
+ # executable identity was just validated. Keep the value-taking
+ # option before `stop` deliberately: an older helper does not know
+ # the option, so it treats the PID as the command/tool and fails
+ # instead of issuing an unbound shutdown to the default socket.
+ helper_stderr="$("$helper" --expected-pid "$pid" stop 2>&1 >/dev/null)" || helper_status=$?
+ if [[ "$helper_status" != "0" ]]; then
+ # Either an installed helper that predates --expected-pid, or a
+ # helper that refused because the socket no longer belongs to
+ # this PID. Both are expected outcomes, not script errors, so
+ # the fallback below still runs — but report why the graceful
+ # path was skipped instead of discarding the helper's own
+ # diagnosis. A pid mismatch here is the socket-replacement race
+ # this option exists to catch, and it must stay visible.
+ printf 'note: trusted stop helper exited %s for pid %s; falling back to signals.\n' \
+ "$helper_status" "$pid" >&2
+ [[ -z "$helper_stderr" ]] || printf '%s\n' "$helper_stderr" >&2
+ fi
+ # Signals below target the PID whose executable identity was
+ # validated above, never whatever process currently owns the
+ # socket, so a failed handshake cannot redirect them.
+ if ! daemon_wait_for_exit "$pid"; then
+ kill -TERM "$pid" 2>/dev/null || true
+ if ! daemon_wait_for_exit "$pid"; then
+ kill -KILL "$pid" 2>/dev/null || true
+ if ! daemon_wait_for_exit "$pid"; then
+ printf 'daemon_stop_incomplete: validated release daemon pid %s is still running.\n' "$pid" >&2
+ DAEMON_STOP_RESULT=failed
+ return 1
+ fi
+ fi
+ fi
+ DAEMON_STOP_RESULT=stopped
+ else
+ pid_identity_status=$?
+ if [[ "$pid_identity_status" == "2" ]]; then
+ printf 'daemon_stop_incomplete: failed to identify live daemon pid %s safely.\n' "$pid" >&2
+ DAEMON_STOP_RESULT=failed
+ return 1
+ fi
+ fi
+ fi
+
+ # A stale/missing/foreign PID file reaches only this inspection path. The
+ # same check after a valid stop catches supervisor respawn before deletion.
+ sleep 0.2 2>/dev/null || true
+ if ! verify_release_daemon_absent; then
+ DAEMON_STOP_RESULT=failed
+ return 1
+ fi
+ return 0
+}
+
reject_root_invocation() {
local effective_uid="$1"
if [[ "$effective_uid" == "0" ]]; then
@@ -148,16 +319,6 @@ reject_root_invocation() {
fi
}
-# Narrow source-only seam for the synthetic uninstall fixture. Production
-# execution never sets this variable and continues through the full script.
-if [[ "${CUA_DRIVER_UNINSTALL_TEST_SOURCE_ONLY:-0}" == "1" ]]; then
- return 0
-fi
-
-if ! reject_root_invocation "$(id -u)"; then
- exit 77
-fi
-
# TCC revocation is on by default so uninstall leaves the next macOS install
# in a clean promptable state. The bundle id com.trycua.driver is shared with
# the retired Swift driver, so `--keep-tcc` remains available for users who
@@ -222,6 +383,73 @@ resolve_link() {
esac
}
+select_daemon_stop_helper() {
+ local candidate resolved
+ for candidate in \
+ "$APP_BUNDLE/Contents/MacOS/cua-driver" \
+ "$LEGACY_APP_BUNDLE/Contents/MacOS/cua-driver" \
+ "$PACKAGES_DIR/current/cua-driver" \
+ "$LEGACY_HOME_DIR/packages/current/cua-driver"; do
+ [[ -x "$candidate" ]] || continue
+ resolved="$(realpath "$candidate" 2>/dev/null || true)"
+ [[ -n "$resolved" ]] || resolved="$candidate"
+ case "$resolved" in
+ "$APP_BUNDLE/Contents/MacOS/cua-driver"|"$LEGACY_APP_BUNDLE/Contents/MacOS/cua-driver"|\
+ "$HOME_DIR"/packages/releases/*/cua-driver|"$LEGACY_HOME_DIR"/packages/releases/*/cua-driver)
+ printf '%s' "$resolved"
+ return 0
+ ;;
+ esac
+ done
+ return 1
+}
+
+# Stop the native supervisor without deleting its registration. A failure here
+# is fatal because deleting the runtime under a supervisor that may respawn the
+# daemon is unsafe.
+stop_release_supervisor() {
+ local path name
+ case "$OS" in
+ Linux)
+ for path in "$SYSTEMD_USER_UNIT" "$LEGACY_SYSTEMD_USER_UNIT"; do
+ [[ -f "$path" ]] || continue
+ command -v systemctl >/dev/null 2>&1 || {
+ printf 'daemon_stop_incomplete: systemd user unit exists but systemctl is unavailable.\n' >&2
+ return 1
+ }
+ name="${path##*/}"
+ if ! systemctl --user stop "$name" >/dev/null 2>&1; then
+ printf 'daemon_stop_incomplete: failed to stop systemd user unit %s.\n' "$name" >&2
+ return 1
+ fi
+ done
+ ;;
+ Darwin)
+ for path in "$LAUNCHAGENT_PLIST" "$LEGACY_LAUNCHAGENT_PLIST"; do
+ [[ -f "$path" ]] || continue
+ command -v launchctl >/dev/null 2>&1 || {
+ printf 'daemon_stop_incomplete: LaunchAgent exists but launchctl is unavailable.\n' >&2
+ return 1
+ }
+ if ! launchctl unload "$path" >/dev/null 2>&1; then
+ printf 'daemon_stop_incomplete: failed to unload LaunchAgent %s.\n' "$path" >&2
+ return 1
+ fi
+ done
+ ;;
+ esac
+}
+
+# Narrow source-only seam for the synthetic uninstall fixture. Production
+# execution never sets this variable and continues through the full script.
+if [[ "${CUA_DRIVER_UNINSTALL_TEST_SOURCE_ONLY:-0}" == "1" ]]; then
+ return 0
+fi
+
+if ! reject_root_invocation "$(id -u)"; then
+ exit 77
+fi
+
# ----------------------------------------------------------------------
# Rust uninstall branch (default on Linux + macOS).
# ----------------------------------------------------------------------
@@ -276,6 +504,46 @@ if [[ "$USE_RUST_BACKEND" == "1" ]]; then
RUST_INSTALL_PRESENT=1
fi
+ DAEMON_PID_FILE="$(daemon_pid_file_path)"
+ DAEMON_STOP_HELPER="$(select_daemon_stop_helper || true)"
+ DAEMON_EXECUTABLES=(
+ "$APP_BUNDLE/Contents/MacOS/cua-driver"
+ "$LEGACY_APP_BUNDLE/Contents/MacOS/cua-driver"
+ "$PACKAGES_DIR/current/cua-driver"
+ "$LEGACY_HOME_DIR/packages/current/cua-driver"
+ )
+ if [[ -L "$USER_BIN_LINK" ]]; then
+ DAEMON_RESOLVED="$(resolve_link "$USER_BIN_LINK")"
+ case "$DAEMON_RESOLVED" in
+ "$APP_BUNDLE/Contents/MacOS/cua-driver"|"$LEGACY_APP_BUNDLE/Contents/MacOS/cua-driver"|\
+ "$HOME_DIR"/packages/releases/*/cua-driver|"$LEGACY_HOME_DIR"/packages/releases/*/cua-driver)
+ DAEMON_EXECUTABLES+=("$USER_BIN_LINK" "$DAEMON_RESOLVED")
+ ;;
+ esac
+ unset DAEMON_RESOLVED
+ fi
+
+ # Shutdown is the transaction boundary: supervisor + daemon must both be
+ # proven stopped before any symlink, service file, bundle, or runtime file
+ # is removed.
+ if [[ "$RUST_INSTALL_PRESENT" == "1" ]]; then
+ if ! stop_release_supervisor; then
+ log "could not stop the release supervisor; runtime preserved"
+ exit 1
+ fi
+ if ! stop_release_daemon; then
+ log "could not safely stop and verify the release daemon; runtime preserved"
+ exit 1
+ fi
+ if [[ "$DAEMON_STOP_RESULT" == "stopped" ]]; then
+ log "stopped and verified the running cua-driver daemon"
+ else
+ log "no running release cua-driver daemon"
+ fi
+ else
+ log "no Rust install marker; leaving any running cua-driver process untouched"
+ fi
+
# --- CLI symlink ---
# Only remove ~/.local/bin/cua-driver when it resolves into a
# cua-driver-rs install. Pre-rename installs at
@@ -311,11 +579,8 @@ if [[ "$USE_RUST_BACKEND" == "1" ]]; then
fi
# --- Autostart (Linux systemd --user) ---
- # install-local.sh --autostart registers
- # ~/.config/systemd/user/cua-driver.service. Stop + disable + remove it,
- # plus the pre-rename cua-driver-rs.service when present, so neither daemon
- # comes back at next logon.
- # systemctl --user no-ops gracefully on a non-systemd host.
+ # The stop phase already succeeded above. Disable and remove registrations
+ # only after daemon shutdown has been verified.
if [[ "$OS" == "Linux" ]]; then
FOUND_SYSTEMD_USER_UNIT=0
for SYSTEMD_USER_UNIT_PATH in "$SYSTEMD_USER_UNIT" "$LEGACY_SYSTEMD_USER_UNIT"; do
@@ -323,12 +588,10 @@ if [[ "$USE_RUST_BACKEND" == "1" ]]; then
FOUND_SYSTEMD_USER_UNIT=1
SYSTEMD_USER_UNIT_NAME="${SYSTEMD_USER_UNIT_PATH##*/}"
if command -v systemctl >/dev/null 2>&1; then
- systemctl --user stop "$SYSTEMD_USER_UNIT_NAME" 2>/dev/null || true
systemctl --user disable "$SYSTEMD_USER_UNIT_NAME" 2>/dev/null || true
- log "stopped + disabled systemd --user unit $SYSTEMD_USER_UNIT_NAME"
fi
rm -f "$SYSTEMD_USER_UNIT_PATH"
- log "removed $SYSTEMD_USER_UNIT_PATH"
+ log "disabled + removed systemd --user unit $SYSTEMD_USER_UNIT_NAME"
fi
done
if [[ "$FOUND_SYSTEMD_USER_UNIT" == "0" ]]; then
@@ -339,16 +602,11 @@ if [[ "$USE_RUST_BACKEND" == "1" ]]; then
fi
# --- Autostart (macOS LaunchAgent) ---
- # install-local.sh --autostart on macOS registers
- # ~/Library/LaunchAgents/com.trycua.cua-driver.plist. Unload (so the
- # running daemon stops) + remove it, plus the pre-rename
- # com.trycua.cua-driver-rs.plist when present.
if [[ "$OS" == "Darwin" ]]; then
FOUND_LAUNCHAGENT_PLIST=0
for LAUNCHAGENT_PLIST_PATH in "$LAUNCHAGENT_PLIST" "$LEGACY_LAUNCHAGENT_PLIST"; do
if [[ -f "$LAUNCHAGENT_PLIST_PATH" ]]; then
FOUND_LAUNCHAGENT_PLIST=1
- launchctl unload "$LAUNCHAGENT_PLIST_PATH" 2>/dev/null || true
rm -f "$LAUNCHAGENT_PLIST_PATH"
log "removed LaunchAgent $LAUNCHAGENT_PLIST_PATH"
fi