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): report Linux kill_app success only after the process exits (#4281)
Francesco Bonacci3470e230a1f1
diff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_gtk3_test.rs b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_gtk3_test.rsindex 67ffdb8e45..c899ceca03 100644--- a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_gtk3_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_gtk3_test.rs@@ -260,6 +260,15 @@ fn harness_gtk3_rejects_exited_target_and_recovers_with_fresh_app() {let killed = driver.call("kill_app", serde_json::json!({ "pid": stale_pid as i64 }));assert!(!killed.is_error(), "kill_app failed: {}", killed.text());+ // kill_app reports success only after the same process exited, not+ // when the signal was merely accepted (#2661).+ assert_eq!(+ killed.structured()["terminated"],+ true,+ "kill_app did not confirm termination: {}",+ killed.text()+ );+ assert_eq!(killed.structured()["effect"], "confirmed");let exit_deadline = Instant::now() + Duration::from_secs(5);while Instant::now() < exit_deadline {diff --git a/libs/cua-driver/rust/crates/platform-linux/src/proc_fs.rs b/libs/cua-driver/rust/crates/platform-linux/src/proc_fs.rsindex 91d1cfd84c..7cf1622cdf 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/proc_fs.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/proc_fs.rs@@ -58,6 +58,55 @@ pub fn process_instance_id(pid: u32) -> Option<u64> {process_start_time_from_stat(&stat)}+/// One process instance as `/proc/<pid>/stat` describes it: its scheduler+/// state and its kernel start time.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) struct ProcessStat {+ pub state: char,+ pub start_time: u64,+}++/// Parse state (field 3) and start time (field 22) from `/proc/<pid>/stat`.+pub(crate) fn process_stat_from_stat(stat: &str) -> Option<ProcessStat> {+ let state = stat+ .rsplit_once(')')?+ .1+ .split_whitespace()+ .next()?+ .chars()+ .next()?;+ Some(ProcessStat {+ state,+ start_time: process_start_time_from_stat(stat)?,+ })+}++/// Read one pid's [`ProcessStat`]; `Ok(None)` when no such process exists.+pub(crate) fn read_process_stat(pid: u32) -> std::io::Result<Option<ProcessStat>> {+ match fs::read_to_string(format!("/proc/{pid}/stat")) {+ Ok(stat) => process_stat_from_stat(&stat).map(Some).ok_or_else(|| {+ std::io::Error::new(std::io::ErrorKind::InvalidData, "malformed /proc stat")+ }),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),+ Err(error) => Err(error),+ }+}++/// How the process first read as `before` ended, judged from a later read of+/// the same pid, or `None` while that same instance is still alive. A zombie+/// has exited and only waits for its parent to reap it.+pub(crate) fn process_exit_observation(+ before: ProcessStat,+ now: Option<ProcessStat>,+) -> Option<&'static str> {+ match now {+ None => Some("process_absent"),+ Some(now) if now.start_time != before.start_time => Some("pid_reused"),+ Some(now) if matches!(now.state, 'Z' | 'X') => Some("zombie"),+ Some(_) => None,+ }+}+/// Return all running processes by reading /proc/<pid>/status.pub fn list_processes() -> Vec<ProcessInfo> {let mut result = Vec::new();@@ -139,6 +188,42 @@ mod tests {);}+ #[test]+ fn exit_observation_tells_the_same_live_instance_from_its_end() {+ let stat = |state| super::ProcessStat {+ state,+ start_time: 7,+ };+ let parsed = super::process_stat_from_stat(&format!(+ "42 (a) b) S {} 7 23",+ (4..=21)+ .map(|f| f.to_string())+ .collect::<Vec<_>>()+ .join(" ")+ ));+ assert_eq!(parsed, Some(stat('S')));+ assert_eq!(+ super::process_exit_observation(stat('S'), Some(stat('R'))),+ None+ );+ assert_eq!(+ super::process_exit_observation(stat('S'), Some(stat('Z'))),+ Some("zombie")+ );+ assert_eq!(+ super::process_exit_observation(stat('S'), None),+ Some("process_absent")+ );+ let reused = super::ProcessStat {+ state: 'S',+ start_time: 8,+ };+ assert_eq!(+ super::process_exit_observation(stat('S'), Some(reused)),+ Some("pid_reused")+ );+ }+#[test]fn process_states_fail_closed() {assert!(super::is_process_live_state(diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rsindex 77ba76f86e..dad3ba8c8d 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs@@ -13302,20 +13302,101 @@ impl Tool for KillAppTool {)}};+ // Read the instance before signaling so the confirmation below can+ // tell its exit from a later process that reused the pid.+ let before = match crate::proc_fs::read_process_stat(pid_i as u32) {+ Ok(Some(before)) => before,+ Ok(None) => {+ return kill_app_failure(+ pid_i,+ "process_not_found",+ format!("kill_app: pid {pid_i} does not exist; no signal was sent."),+ )+ }+ Err(error) => {+ return kill_app_failure(+ pid_i,+ "process_identity_unavailable",+ format!(+ "kill_app: cannot read /proc/{pid_i}/stat to verify termination: \+ {error}; no signal was sent."+ ),+ )+ }+ };// SAFETY: libc::kill is a thin syscall wrapper, no thread-safety concerns.let rc = unsafe { libc::kill(pid_i, libc::SIGKILL) };- if rc == 0 {- ToolResult::text(format!("✅ Sent SIGKILL to pid {pid_i}."))- } else {+ if rc != 0 {let err = std::io::Error::last_os_error();- ToolResult::error(format!(- "kill_app: kill(pid={pid_i}, SIGKILL) failed: {err}. \- The process may not exist, or the daemon lacks permission to signal it."- ))+ return kill_app_failure(+ pid_i,+ "signal_failed",+ format!(+ "kill_app: kill(pid={pid_i}, SIGKILL) failed: {err}. \+ The process may not exist, or the daemon lacks permission to signal it."+ ),+ );+ }+ // An accepted signal is not an exit: a sandbox (gVisor) can accept+ // SIGKILL for a process that keeps running. Report success only once+ // the same instance is gone.+ let deadline = tokio::time::Instant::now() + KILL_CONFIRM_TIMEOUT;+ loop {+ let now = crate::proc_fs::read_process_stat(pid_i as u32);+ if let Some(observation) = now+ .as_ref()+ .ok()+ .and_then(|now| crate::proc_fs::process_exit_observation(before, *now))+ {+ return ToolResult::text(format!(+ "✅ Terminated pid {pid_i} with SIGKILL (confirmed: {observation})."+ ))+ .with_structured(json!({+ "status": "terminated",+ "effect": "confirmed",+ "pid": pid_i,+ "terminated": true,+ "observation": observation,+ }));+ }+ if tokio::time::Instant::now() >= deadline {+ let detail = match now {+ Err(error) => format!("/proc/{pid_i}/stat became unreadable: {error}"),+ Ok(_) => format!(+ "the same process was still alive {} ms later",+ KILL_CONFIRM_TIMEOUT.as_millis()+ ),+ };+ let mut result = kill_app_failure(+ pid_i,+ "termination_unconfirmed",+ format!("kill_app: SIGKILL was accepted for pid {pid_i}, but {detail}."),+ );+ if let Some(structured) = result.structured_content.as_mut() {+ structured["effect"] = json!("suspected_noop");+ }+ return result;+ }+ tokio::time::sleep(KILL_CONFIRM_INTERVAL).await;}}}+/// How long `kill_app` waits for the signaled process to exit, and how often+/// it re-reads `/proc/<pid>/stat` meanwhile.+const KILL_CONFIRM_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);+const KILL_CONFIRM_INTERVAL: std::time::Duration = std::time::Duration::from_millis(10);++fn kill_app_failure(pid: i32, code: &str, message: String) -> ToolResult {+ ToolResult::error(message.clone()).with_structured(json!({+ "status": "failed",+ "pid": pid,+ "terminated": false,+ "code": code,+ "message": message,+ }))+}+fn kill_app_stale_process_refusal(message: String) -> ToolResult {ToolResult::error(message.clone()).with_structured(json!({"status": "refused",