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): bind uninstall signals to process generation (#3446)
injaneity63c700d78aec
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs b/libs/cua-driver/rust/crates/cua-driver/src/cli.rsindex e8b58ca93a..089f088a87 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs@@ -78,11 +78,6 @@ 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 {@@ -228,7 +223,6 @@ 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",@@ -1039,14 +1033,6 @@ 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") {@@ -1062,6 +1048,7 @@ fn parse_expected_stop_pid(args: &[String], command: Option<&str>) -> Option<u32}}+/// Return the value of `--flag value` from argv, or `None`.fn flag_value(args: &[String], flag: &str) -> Option<String> {let mut it = args.iter();while let Some(a) = it.next() {@@ -4800,8 +4787,6 @@ mod tests {#[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"]);}diff --git a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs b/libs/cua-driver/rust/crates/cua-driver/src/serve.rsindex 029ef80149..1fa0436a44 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs@@ -641,6 +641,45 @@ fn daemon_metadata_response() -> DaemonResponse {)}+fn shutdown_response(request: &DaemonRequest) -> (DaemonResponse, bool) {+ if request.method == "shutdown" {+ return (+ DaemonResponse::ok(serde_json::json!({"shutdown": true})),+ true,+ );+ }+ let expected_pid = request+ .args+ .as_ref()+ .and_then(|args| args.get("expected_pid"))+ .and_then(serde_json::Value::as_u64)+ .and_then(|pid| u32::try_from(pid).ok())+ .filter(|pid| *pid != 0);+ let Some(expected_pid) = expected_pid else {+ return (+ DaemonResponse::err(+ "shutdown_if_pid requires a positive integer expected_pid",+ 64,+ ),+ false,+ );+ };+ let actual_pid = std::process::id();+ if expected_pid != actual_pid {+ return (+ DaemonResponse::err(+ format!("daemon pid mismatch (expected {expected_pid}, found {actual_pid})"),+ 1,+ ),+ false,+ );+ }+ (+ DaemonResponse::ok(serde_json::json!({"shutdown": true})),+ true,+ )+}+async fn wait_for_parent_stdin_eof() {use tokio::io::AsyncReadExt as _;@@ -757,7 +796,7 @@ fn service_authorization_status(trusted_host_connection: bool) -> serde_json::Vamod peer_authentication_tests {use super::{authenticate_unix_peer, authenticate_unix_uid, history_relaunch_state_response,- DaemonRequest, ToolObservationOrigin,+ shutdown_response, DaemonRequest, ToolObservationOrigin,};#[tokio::test]@@ -791,6 +830,40 @@ mod peer_authentication_tests {);assert!(history_relaunch_state_response(&request, true).ok);}++ fn shutdown_request(expected_pid: serde_json::Value) -> DaemonRequest {+ DaemonRequest {+ method: "shutdown_if_pid".to_owned(),+ name: None,+ args: Some(serde_json::json!({"expected_pid": expected_pid})),+ session_id: None,+ observation_origin: None,+ client_kind: None,+ }+ }++ #[test]+ fn pid_bound_shutdown_accepts_only_the_current_process() {+ let (response, should_shutdown) =+ shutdown_response(&shutdown_request(std::process::id().into()));+ assert!(response.ok);+ assert!(should_shutdown);++ let wrong_pid = if std::process::id() == 1 { 2 } else { 1 };+ let (response, should_shutdown) = shutdown_response(&shutdown_request(wrong_pid.into()));+ assert!(!response.ok);+ assert!(!should_shutdown);+ assert!(response.error.unwrap().contains("daemon pid mismatch"));+ }++ #[test]+ fn pid_bound_shutdown_rejects_malformed_pid() {+ let (response, should_shutdown) =+ shutdown_response(&shutdown_request(serde_json::json!("1")));+ assert!(!response.ok);+ assert!(!should_shutdown);+ assert_eq!(response.exit_code, Some(64));+ }}/// Run the daemon server. Binds `socket_path`, writes `pid_file_path`,@@ -912,11 +985,14 @@ pub async fn run_serve((serde_json::to_string(&resp).unwrap() + "\n").as_bytes()).await;}- "shutdown" => {- let resp = DaemonResponse::ok(serde_json::json!({"shutdown": true}));+ "shutdown" | "shutdown_if_pid" => {+ let (resp, should_shutdown) = shutdown_response(&req);let _ = writer.write_all((serde_json::to_string(&resp).unwrap() + "\n").as_bytes()).await;+ if !should_shutdown {+ continue;+ }let mut guard = shutdown_tx2.lock().await;if let Some(tx) = guard.take() {let _ = tx.send(());@@ -1650,11 +1726,14 @@ pub async fn run_serve((serde_json::to_string(&resp).unwrap() + "\n").as_bytes()).await;}- "shutdown" => {- let resp = DaemonResponse::ok(serde_json::json!({"shutdown": true}));+ "shutdown" | "shutdown_if_pid" => {+ let (resp, should_shutdown) = shutdown_response(&req);let _ = writer.write_all((serde_json::to_string(&resp).unwrap() + "\n").as_bytes()).await;+ if !should_shutdown {+ continue;+ }let mut guard = shutdown_tx2.lock().await;if let Some(tx) = guard.take() { let _ = tx.send(()); }return;diff --git a/libs/cua-driver/rust/crates/cua-driver/src/stop.rs b/libs/cua-driver/rust/crates/cua-driver/src/stop.rsindex e5b080cbe5..214be2a05e 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/stop.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/stop.rs@@ -1,175 +1,34 @@-//! 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::{send_request, DaemonRequest};-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 {+ let response = send_request(+ socket_path,+ &DaemonRequest {+ method: "shutdown_if_pid".to_owned(),+ name: None,+ args: Some(serde_json::json!({"expected_pid": expected_pid})),+ session_id: None,+ observation_origin: None,+ client_kind: None,+ },+ )?;+ if !response.ok {anyhow::bail!(- "daemon pid mismatch (expected {expected_pid}, found {})",- metadata.pid+ "{}",+ response+ .error+ .unwrap_or_else(|| "daemon shutdown request failed".to_owned()));}-- 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() {diff --git a/libs/cua-driver/scripts/tests/test_uninstall_daemon_stop.py b/libs/cua-driver/scripts/tests/test_uninstall_daemon_stop.pyindex b46e181ec7..6d59e50937 100644--- a/libs/cua-driver/scripts/tests/test_uninstall_daemon_stop.py+++ b/libs/cua-driver/scripts/tests/test_uninstall_daemon_stop.py@@ -4,15 +4,13 @@ from __future__ import annotationsimport osfrom pathlib import Path-import shutilimport subprocessimport tempfile-import threadingimport unittest-REPO_ROOT = Path(__file__).resolve().parents[4]-UNINSTALL = REPO_ROOT / "libs/cua-driver/scripts/uninstall.sh"+ROOT = Path(__file__).resolve().parents[4]+UNINSTALL = ROOT / "libs/cua-driver/scripts/uninstall.sh"def executable(path: Path, body: str) -> None:@@ -20,17 +18,6 @@ def executable(path: Path, body: str) -> None: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()@@ -39,259 +26,156 @@ class DaemonStopTests(unittest.TestCase):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",+ "CUA_DRIVER_UNINSTALL_TEST_SOURCE_ONLY": "1",}- 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 shell(self, body: str) -> subprocess.CompletedProcess[str]:+ return subprocess.run(+ ["/bin/bash", "-c", f'source "{UNINSTALL}"\n{body}'],+ cwd=ROOT,+ env=self.env,+ text=True,+ capture_output=True,+ check=False,+ )- def setup(self, pid_file: Path, helper: Path | None, identity: str) -> str:+ def setup(self, helper: Path | None) -> str:+ pid_file = self.home / "daemon.pid"+ pid_file.write_text("4242\n", encoding="utf-8")return f"""-OS=Linux+APP_BUNDLE=/Applications/CuaDriver.app+LEGACY_APP_BUNDLE=/Applications/CuaDriverRs.appHOME_DIR="$HOME/.cua-driver"LEGACY_HOME_DIR="$HOME/.cua-driver-rs"DAEMON_PID_FILE="{pid_file}"DAEMON_STOP_HELPER="{helper or ''}"-DAEMON_EXECUTABLES=("{identity}")+daemon_pid_alive() {{ return 0; }}+daemon_pid_is_release() {{ return 0; }}+daemon_process_generation() {{ printf generation-1; }}+verify_release_daemon_absent() {{ return 0; }}"""- 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+ def test_helper_receives_only_guarded_stop(self) -> None:+ marker = self.root / "argv"+ helper = self.home / "cua-driver"+ executable(helper, f"printf '%s|' \"$@\" > '{marker}'")+ result = self.shell(+ self.setup(helper)+ """-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_for_exit() { return 0; }+stop_release_daemon+""")- 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.assertEqual(result.returncode, 0, result.stderr)+ self.assertEqual(marker.read_text(), "--expected-pid|4242|stop|")++ def test_old_helper_falls_back_without_plain_stop(self) -> None:+ unbound = self.root / "unbound"+ signals = self.root / "signals"+ waits = self.root / "waits"+ helper = self.home / "old-cua-driver"+ executable(helper, f'[ "$1" != stop ] || : > "{unbound}"\nexit 2')+ result = self.shell(+ self.setup(helper)+ + f"""+daemon_wait_for_exit() {{+ count=0; [[ ! -f "{waits}" ]] || count=$(cat "{waits}")+ count=$((count + 1)); printf '%s' "$count" > "{waits}"+ [[ "$count" -gt 1 ]]+}}+daemon_signal_if_current() {{ printf '%s' "$3" > "{signals}"; return 0; }}+stop_release_daemon+""")-- 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",+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertFalse(unbound.exists())+ self.assertEqual(signals.read_text(), "TERM")++ def test_reused_pid_is_not_signalled(self) -> None:+ helper = self.home / "cua-driver"+ executable(helper, "exit 1")+ result = self.shell(+ self.setup(helper)+ + """+daemon_wait_for_exit() { return 1; }+daemon_signal_if_current() { return 1; }+kill() { return 99; }+stop_release_daemon+""")-- 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=$?+ self.assertEqual(result.returncode, 0, result.stderr)++ def test_missing_helper_fails_before_signal(self) -> None:+ result = self.shell(self.setup(None) + "stop_release_daemon")+ self.assertNotEqual(result.returncode, 0)+ self.assertIn("stop helper is unavailable", result.stderr)++ def test_process_generation_guards_signal(self) -> None:+ marker = self.root / "signal"+ result = self.shell(+ self.setup(None)+ + f"""+daemon_pid_is_release() {{ return 0; }}+daemon_process_generation() {{ printf "$GENERATION"; }}+kill() {{ printf '%s' "$*" > "{marker}"; }}+GENERATION=old+daemon_signal_if_current 4242 old TERM+GENERATION=new+daemon_signal_if_current 4242 old KILL || 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"],+""")+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertEqual(marker.read_text(), "-TERM 4242")+ self.assertIn("status=1", result.stdout)- 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")+ def test_process_inspection_statuses_are_fail_closed(self) -> None: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)+ for pgrep_body, expected in (("exit 1", 0), ("exit 2", 1), ("echo 4242", 1)):+ with self.subTest(pgrep=pgrep_body):+ executable(self.bin / "pgrep", pgrep_body)+ result = self.shell(+ """+APP_BUNDLE=/Applications/CuaDriver.app+LEGACY_APP_BUNDLE=/Applications/CuaDriverRs.app+HOME_DIR="$HOME/.cua-driver"+LEGACY_HOME_DIR="$HOME/.cua-driver-rs"+status=0; verify_release_daemon_absent || status=$?; exit "$status"+"""+ )+ self.assertEqual(result.returncode, expected, result.stderr)- def test_supervisor_failure_aborts_before_runtime_removal(self) -> None:- tools = self.root / "main-bin"+ def test_supervisor_failure_preserves_runtime(self) -> None:+ tools = self.root / "tools"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")-+ unit.write_text("[Service]\n")result = subprocess.run(["/bin/bash", str(UNINSTALL)],- cwd=REPO_ROOT,- env={**self.env, "PATH": f"{tools}:/usr/bin:/bin"},+ cwd=ROOT,+ env={+ **self.env,+ "PATH": f"{tools}:/usr/bin:/bin",+ "CUA_DRIVER_UNINSTALL_TEST_SOURCE_ONLY": "0",+ },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())diff --git a/libs/cua-driver/scripts/tests/uninstall-history-purge-test.sh b/libs/cua-driver/scripts/tests/uninstall-history-purge-test.shindex 3b85f90a33..c26646aba7 100644--- a/libs/cua-driver/scripts/tests/uninstall-history-purge-test.sh+++ b/libs/cua-driver/scripts/tests/uninstall-history-purge-test.sh@@ -34,13 +34,13 @@ figrep -Fq 'do not run the Cua Driver uninstaller with sudo' "$FIXTURE/root-error.log"reject_root_invocation 501purge_macos_history "$APP" "$HELPER" 1 "$FIXTURE/codesign"-[[ "$(sed -n '1p' "$LOG")" == "stop" ]]-[[ "$(sed -n '2p' "$LOG")" == "history purge-offline --yes" ]]+[[ "$(sed -n '1p' "$LOG")" == "history purge-offline --yes" ]]+[[ "$(wc -l < "$LOG")" == "1" ]]: > "$LOG"purge_linux_history "$HELPER" 1-[[ "$(sed -n '1p' "$LOG")" == "stop" ]]-[[ "$(sed -n '2p' "$LOG")" == "history purge-offline --yes" ]]+[[ "$(sed -n '1p' "$LOG")" == "history purge-offline --yes" ]]+[[ "$(wc -l < "$LOG")" == "1" ]]export UNINSTALL_FIXTURE_FAIL=1if purge_macos_history "$APP" "$HELPER" 1 "$FIXTURE/codesign" 2> "$FIXTURE/error.log"; thendiff --git a/libs/cua-driver/scripts/uninstall.sh b/libs/cua-driver/scripts/uninstall.shindex d98b9308d4..09d827444a 100755--- a/libs/cua-driver/scripts/uninstall.sh+++ b/libs/cua-driver/scripts/uninstall.sh@@ -20,10 +20,6 @@# - 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)@@ -160,6 +156,35 @@ read_daemon_pid() {daemon_pid_alive() { kill -0 "$1" 2>/dev/null; }+daemon_process_generation() {+ local start=""+ command -v ps >/dev/null 2>&1 || return 2+ start="$(LC_ALL=C ps -ww -o lstart= -p "$1" 2>/dev/null)" || return 2+ start="${start#"${start%%[![:space:]]*}"}"+ start="${start%"${start##*[![:space:]]}"}"+ [[ -n "$start" ]] || return 2+ printf '%s' "$start"+}++daemon_pid_matches_generation() {+ local pid="$1" expected="$2" current="" identity_status=0+ daemon_pid_alive "$pid" || return 1+ current="$(daemon_process_generation "$pid")" || return 2+ [[ "$current" == "$expected" ]] || return 1+ daemon_pid_is_release "$pid" || identity_status=$?+ [[ "$identity_status" == "0" ]] && return 0+ [[ "$identity_status" == "2" ]] && return 2+ return 1+}++daemon_signal_if_current() {+ local status=0+ daemon_pid_matches_generation "$1" "$2" || status=$?+ [[ "$status" == "2" ]] && return 2+ [[ "$status" == "0" ]] || return 1+ kill -"$3" "$1" 2>/dev/null || return 1+}+daemon_wait_for_exit() {local pid="$1" attempts=0while daemon_pid_alive "$pid"; do@@ -186,18 +211,16 @@ daemon_process_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 ;;+ case "$1" in+ "$APP_BUNDLE"/Contents/MacOS/cua-driver|"$APP_BUNDLE"/Contents/MacOS/cua-driver[[:space:]]*|\+ "$LEGACY_APP_BUNDLE"/Contents/MacOS/cua-driver|"$LEGACY_APP_BUNDLE"/Contents/MacOS/cua-driver[[:space:]]*|\+ "$USER_BIN_LINK"|"$USER_BIN_LINK"[[:space:]]*|\+ "$HOME_DIR"/packages/current/cua-driver|"$HOME_DIR"/packages/current/cua-driver[[:space:]]*|\+ "$HOME_DIR"/packages/releases/*/cua-driver|"$HOME_DIR"/packages/releases/*/cua-driver[[:space:]]*|\+ "$LEGACY_HOME_DIR"/packages/current/cua-driver|"$LEGACY_HOME_DIR"/packages/current/cua-driver[[:space:]]*|\"$LEGACY_HOME_DIR"/packages/releases/*/cua-driver|"$LEGACY_HOME_DIR"/packages/releases/*/cua-driver[[:space:]]*) return 0 ;;+ *) return 1 ;;esac- return 1}daemon_pid_is_release() {@@ -206,8 +229,6 @@ daemon_pid_is_release() {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 2command -v ps >/dev/null 2>&1 || return 2@@ -246,69 +267,54 @@ verify_release_daemon_absent() {}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)" \+ local pid="" helper="${DAEMON_STOP_HELPER:-}" generation="" status=0 helper_stderr=""+ if [[ -n "${DAEMON_PID_FILE:-}" ]] \+ && pid="$(read_daemon_pid "$DAEMON_PID_FILE" 2>/dev/null)" \&& daemon_pid_alive "$pid"; then- if daemon_pid_is_release "$pid"; then- if [[ -z "$helper" || ! -x "$helper" ]]; then+ daemon_pid_is_release "$pid" || status=$?+ if [[ "$status" == "2" ]]; then+ printf 'daemon_stop_incomplete: failed to identify live daemon pid %s safely.\n' "$pid" >&2+ return 1+ fi+ if [[ "$status" == "0" ]]; then+ [[ -n "$helper" && -x "$helper" ]] || {printf 'daemon_stop_incomplete: trusted installed cua-driver stop helper is unavailable for pid %s.\n' "$pid" >&2- DAEMON_STOP_RESULT=failedreturn 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+ }+ generation="$(daemon_process_generation "$pid")" || {+ printf 'daemon_stop_incomplete: failed to capture process generation for daemon pid %s.\n' "$pid" >&2+ return 1+ }+ status=0+ helper_stderr="$("$helper" --expected-pid "$pid" stop 2>&1 >/dev/null)" || status=$?+ if [[ "$status" != "0" ]]; then+ printf 'note: trusted stop helper exited %s for pid %s; falling back to signals.\n' "$status" "$pid" >&2[[ -z "$helper_stderr" ]] || printf '%s\n' "$helper_stderr" >&2fi- # 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+ status=0+ daemon_signal_if_current "$pid" "$generation" TERM || status=$?+ [[ "$status" != "2" ]] || {+ printf 'daemon_stop_incomplete: failed to revalidate daemon pid %s before TERM.\n' "$pid" >&2+ return 1+ }+ if [[ "$status" == "0" ]] && ! daemon_wait_for_exit "$pid"; then+ status=0+ daemon_signal_if_current "$pid" "$generation" KILL || status=$?+ [[ "$status" != "2" ]] || {+ printf 'daemon_stop_incomplete: failed to revalidate daemon pid %s before KILL.\n' "$pid" >&2+ return 1+ }+ if [[ "$status" == "0" ]] && ! daemon_wait_for_exit "$pid"; thenprintf 'daemon_stop_incomplete: validated release daemon pid %s is still running.\n' "$pid" >&2- DAEMON_STOP_RESULT=failedreturn 1fififi- 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- fififi-- # 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+ verify_release_daemon_absent}reject_root_invocation() {@@ -404,44 +410,55 @@ select_daemon_stop_helper() {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+release_supervisor() {+ local action="$1" path name found=0case "$OS" inLinux)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- }+ found=1name="${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+ if [[ "$action" == "stop" ]]; then+ command -v systemctl >/dev/null 2>&1 \+ && systemctl --user stop "$name" >/dev/null 2>&1 || {+ printf 'daemon_stop_incomplete: failed to stop systemd user unit %s.\n' "$name" >&2+ return 1+ }+ else+ command -v systemctl >/dev/null 2>&1 \+ && systemctl --user disable "$name" >/dev/null 2>&1 || true+ rm -f "$path"+ log "disabled + removed systemd --user unit $name"fidone+ if [[ "$action" == "remove" ]]; then+ [[ "$found" == "1" ]] || log "no current or legacy systemd --user unit found (skipping)"+ command -v systemctl >/dev/null 2>&1 \+ && systemctl --user daemon-reload >/dev/null 2>&1 || true+ fi;;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+ found=1+ if [[ "$action" == "stop" ]]; then+ command -v launchctl >/dev/null 2>&1 \+ && launchctl unload "$path" >/dev/null 2>&1 || {+ printf 'daemon_stop_incomplete: failed to unload LaunchAgent %s.\n' "$path" >&2+ return 1+ }+ else+ rm -f "$path"+ log "removed LaunchAgent $path"fidone+ if [[ "$action" == "remove" && "$found" == "0" ]]; then+ log "no current or legacy LaunchAgent found (skipping)"+ fi;;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" ]]; thenreturn 0fi@@ -506,28 +523,9 @@ if [[ "$USE_RUST_BACKEND" == "1" ]]; thenDAEMON_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+ if ! release_supervisor stop; thenlog "could not stop the release supervisor; runtime preserved"exit 1fi@@ -535,11 +533,7 @@ if [[ "$USE_RUST_BACKEND" == "1" ]]; thenlog "could not safely stop and verify the release daemon; runtime preserved"exit 1fi- if [[ "$DAEMON_STOP_RESULT" == "stopped" ]]; then- log "stopped and verified the running cua-driver daemon"- else- log "no running release cua-driver daemon"- fi+ log "verified no running release cua-driver daemon"elselog "no Rust install marker; leaving any running cua-driver process untouched"fi@@ -578,43 +572,7 @@ if [[ "$USE_RUST_BACKEND" == "1" ]]; thenlog "no CLI symlink at $USER_BIN_LINK (skipping)"fi- # --- Autostart (Linux systemd --user) ---- # 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- if [[ -f "$SYSTEMD_USER_UNIT_PATH" ]]; 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 disable "$SYSTEMD_USER_UNIT_NAME" 2>/dev/null || true- fi- rm -f "$SYSTEMD_USER_UNIT_PATH"- log "disabled + removed systemd --user unit $SYSTEMD_USER_UNIT_NAME"- fi- done- if [[ "$FOUND_SYSTEMD_USER_UNIT" == "0" ]]; then- log "no current or legacy systemd --user unit found (skipping)"- elif command -v systemctl >/dev/null 2>&1; then- systemctl --user daemon-reload 2>/dev/null || true- fi- fi-- # --- Autostart (macOS LaunchAgent) ---- 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- rm -f "$LAUNCHAGENT_PLIST_PATH"- log "removed LaunchAgent $LAUNCHAGENT_PLIST_PATH"- fi- done- if [[ "$FOUND_LAUNCHAGENT_PLIST" == "0" ]]; then- log "no current or legacy LaunchAgent found (skipping)"- fi- fi+ release_supervisor remove# Cryptographic history purge must run while the exact installed helper# executable still exists. The helper uses the production KeyProvider and