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
feat(cua-driver-rs): add kill_app tool for force-terminate by pid (closes CUA-541) (#1596)
Francesco Bonacci5c8947f766be
diff --git a/docs/content/docs/cua-driver/guide/getting-started/linux.mdx b/docs/content/docs/cua-driver/guide/getting-started/linux.mdxnew file mode 100644index 0000000000..9a23b31929--- /dev/null+++ b/docs/content/docs/cua-driver/guide/getting-started/linux.mdx@@ -0,0 +1,158 @@+---+title: Running cua-driver on Linux+description: Display server (X11 / Wayland), AT-SPI prerequisites, autostart, and headless workflows for cua-driver on Linux.+---++import { Callout } from 'fumadocs-ui/components/callout';++cua-driver-rs supports Linux as a first-class target — every action tool (`click`, `type_text`, `hotkey`, `drag`, `scroll`, `screenshot`, `launch_app`, `list_windows`, etc.) has a Linux implementation under [`crates/platform-linux/`](https://github.com/trycua/cua/tree/main/libs/cua-driver-rs/crates/platform-linux/src). This page covers the bits that diverge from the macOS / Windows quickstart: which display server you're running, what accessibility plumbing needs to be alive, how to keep the daemon up at logon, and how headless / CI workflows look.++For the install one-liner itself, see [Installation](/cua-driver/guide/getting-started/installation) — the canonical script auto-detects Linux and routes to the Rust port.++## Display server: X11 vs Wayland vs XWayland++cua-driver's window enumeration, input synthesis, and screen capture talk to your display server directly. The Linux backend supports **X11** (including the XWayland compatibility server on Wayland sessions), and probes which one you're on at startup:++```bash+cua-driver doctor+```++The `display server` probe surfaces:+- **`DISPLAY` set, `WAYLAND_DISPLAY` unset** — pure X11 session. Everything works.+- **`WAYLAND_DISPLAY` set, `DISPLAY` set** — Wayland session with XWayland. cua-driver talks to XWayland (treats the session as X11). Native-Wayland-only apps that bypass XWayland aren't visible to the tools — call this out as a known limitation.+- **`WAYLAND_DISPLAY` set, `DISPLAY` unset** — pure Wayland session, no XWayland. **Not supported today**. Run an X11 session, or install / enable XWayland.+- **Neither set** — headless. Window-driving tools will return errors. See [Headless workflow](#headless-workflow) for `Xvfb`.++<Callout type="warn">+**Wayland caveat.** Wayland's security model deliberately isolates apps from each other's window state and input — exactly what cua-driver needs to do its job. The Rust port works around this by talking to XWayland, which acts as an X11 proxy for Wayland clients. **Apps that render natively against Wayland** (no XWayland) — most modern Firefox builds, GTK4 apps, etc. — won't show up in `list_windows` and aren't clickable. If your target app is one of those, run an X11 session (most distros let you pick X11 vs Wayland at the login screen).+</Callout>++## AT-SPI prerequisite++The accessibility-tree tools (`get_window_state`, `click` with `element_index`, anything that walks UIA-equivalent structure) talk to the **AT-SPI 2** D-Bus bus. AT-SPI is the Linux accessibility framework — same role as macOS's AX or Windows' UI Automation. cua-driver expects the AT-SPI bus to be reachable on your session bus.++cua-driver probes this at startup via `gdbus`:++```bash+cua-driver doctor+# [ok ] AT-SPI bus: org.a11y.Bus reachable on session bus+# ...or, if not:+# [warn] AT-SPI bus: org.a11y.Bus not reachable+# install at-spi2-core (or equivalent) and ensure your desktop is+# running with accessibility enabled+```++If the probe fails, install the AT-SPI service and enable accessibility:++| Distro | Package | Enable |+|---|---|---|+| Ubuntu / Debian | `at-spi2-core` (usually pre-installed under GNOME) | `gsettings set org.gnome.desktop.interface toolkit-accessibility true` |+| Fedora | `at-spi2-core` | same `gsettings` command |+| Arch | `at-spi2-core` (extra) | `gsettings set …` if running GNOME; KDE has its own toggle |+| Alpine / minimal | `at-spi2-core dbus dbus-x11` | run `dbus-launch --exit-with-session` from your X startup script |++You don't need accessibility enabled *system-wide* — it needs to be on for the user session that's running cua-driver. Most desktop environments toggle this automatically when an accessibility client connects.++<Callout type="info">+**Why AT-SPI and not raw X11 properties?** Many Linux apps don't expose their UI structure through X11 window manager hints — only through AT-SPI. Without AT-SPI, `click` would have to fall back to raw pixel coordinates from screenshots (the same vision-only mode that works as a fallback). With AT-SPI, cua-driver can address elements by their accessible name / role / index, matching the agent ergonomics on macOS (AX) and Windows (UIA).+</Callout>++## Autostart on Linux++The `cua-driver autostart` verb family is **Windows-only today**. On Linux it currently returns:++```text+cua-driver autostart is currently Windows-only. macOS users: see+libs/cua-driver-rs/scripts/install-local.sh --autostart for the+LaunchAgent recipe. Linux users: same script registers a systemd+--user unit. A cross-platform impl is tracked as a follow-up.+```++The two working alternatives:++### Option A — Use `install-local.sh --autostart`++The dev-loop install script registers a systemd user unit when invoked with `--autostart`. See [`libs/cua-driver-rs/scripts/install-local.sh`](https://github.com/trycua/cua/blob/main/libs/cua-driver-rs/scripts/install-local.sh) — built for local development off a git checkout, but the systemd unit it writes is the same shape you'd use in production.++### Option B — Write your own systemd user unit++Save the following to `~/.config/systemd/user/cua-driver.service`:++```ini+[Unit]+Description=cua-driver background daemon+# Wait for the graphical session (DISPLAY / WAYLAND_DISPLAY will be set).+After=graphical-session.target+PartOf=graphical-session.target++[Service]+Type=simple+ExecStart=%h/.local/bin/cua-driver serve+Restart=on-failure+RestartSec=2++[Install]+WantedBy=graphical-session.target+```++Then enable + start:++```bash+systemctl --user daemon-reload+systemctl --user enable --now cua-driver.service+systemctl --user status cua-driver.service # confirm+cua-driver status # confirm via daemon socket+```++On most distros you'll also want `loginctl enable-linger $USER` if you intend the daemon to keep running after the user logs out (e.g. CI runners that ssh in to drive cua-driver but never have an interactive session).++See the [Autostart](/cua-driver/guide/getting-started/autostart) concept page for the cross-platform breakdown.++## Headless workflow++Linux doesn't have Windows' Session 0 isolation — `sshd` spawns processes that inherit the user's environment cleanly, including `DISPLAY` / `WAYLAND_DISPLAY` when they're set. So the "SSH + daemon proxy" dance that's necessary on Windows ([Running cua-driver under SSH on Windows](/cua-driver/guide/getting-started/windows-ssh)) is *not* needed on Linux: as long as a display server is running on your session, `cua-driver serve` over SSH connects to it.++For **pure headless** (no display server at all — typical CI runner), use `Xvfb` to provide a virtual X server:++```bash+# Install Xvfb (Ubuntu/Debian: xvfb; Fedora: xorg-x11-server-Xvfb; Arch: xorg-server-xvfb)+sudo apt-get install -y xvfb at-spi2-core dbus-x11++# Run cua-driver under a virtual X server:+xvfb-run -a cua-driver serve++# Or, more explicitly, launch Xvfb yourself + point cua-driver at it:+Xvfb :99 -screen 0 1920x1080x24 &+export DISPLAY=:99+dbus-launch --exit-with-session cua-driver serve+```++This is the same recipe used by CI integrations that test cua-driver on Linux runners.++<Callout type="info">+**Tools that don't need a display.** Even without `DISPLAY` set, the non-graphical tools (`list_apps`, `launch_app` via PATH lookup, `read_clipboard` if a clipboard daemon is up) still work. Only the desktop-touching tools (`click`, `screenshot`, `list_windows`, `get_window_state`) require a display server. `cua-driver doctor` makes this explicit per-tool.+</Callout>++## Distro-specific notes++The canonical install script (`/bin/bash -c "$(curl -fsSL …/install.sh)"`) is distro-neutral — it downloads a static-linked binary tarball from GitHub Releases, drops it into `~/.cua-driver-rs/packages/releases/<v>-x86_64-unknown-linux-gnu/`, and symlinks `~/.local/bin/cua-driver`. The same one-liner works on every modern distro.++The bit that varies is **what accessibility / display tooling is pre-installed**:++- **Ubuntu / Debian** — GNOME ships AT-SPI by default; `at-spi2-core` is usually present. KDE Plasma needs `at-spi2-core` installed manually.+- **Fedora** — GNOME ships AT-SPI; same as Ubuntu under GNOME. Wayland is the default session on Fedora 25+; if AT-SPI feels flaky, switch to "GNOME on Xorg" at the login screen.+- **Arch / Manjaro** — minimal install; you'll likely need to explicitly install `at-spi2-core` and ensure `dbus-launch` runs as part of your session startup.+- **Alpine / busybox-style** — slimmest of all; needs `dbus`, `dbus-x11`, `at-spi2-core` plus likely an explicit `dbus-launch --exit-with-session` wrapper.++If `cua-driver doctor` is happy after install, you're set.++## Per-tool Linux verification matrix++See [`libs/cua-driver-rs/PARITY.md`](https://github.com/trycua/cua/blob/main/libs/cua-driver-rs/PARITY.md) for the per-tool Linux-VERIFIED matrix — every action tool is annotated with its Linux source file (`crates/platform-linux/src/tools/impl_.rs`) and which platform features it depends on (X11 root window for `get_cursor_position`, AT-SPI for accessibility tree, `xtest` for synthetic input, etc.).++## See also++- [Installation](/cua-driver/guide/getting-started/installation) — canonical one-liner that handles Linux automatically+- [Autostart](/cua-driver/guide/getting-started/autostart) — concept page (Windows-only verb family; Linux uses systemd)+- [Process attribution](/cua-driver/explanation/process-attribution) — Linux has none of the macOS-TCC or Windows-Session-0 weirdness; this page explains what those problems are and why Linux sidesteps them+- [`PARITY.md`](https://github.com/trycua/cua/blob/main/libs/cua-driver-rs/PARITY.md) — per-tool platform verification matrixdiff --git a/docs/content/docs/cua-driver/guide/getting-started/meta.json b/docs/content/docs/cua-driver/guide/getting-started/meta.jsonindex 8395fadcd3..413e0e7783 100644--- a/docs/content/docs/cua-driver/guide/getting-started/meta.json+++ b/docs/content/docs/cua-driver/guide/getting-started/meta.json@@ -3,5 +3,5 @@"description": "Get up and running with Cua Driver","icon": "Rocket","defaultOpen": true,- "pages": ["introduction", "installation", "quickstart", "windows-ssh", "autostart", "integrations", "swift-integration", "process-model", "comparison", "faq"]+ "pages": ["introduction", "installation", "quickstart", "windows-ssh", "linux", "autostart", "integrations", "swift-integration", "process-model", "comparison", "faq"]}diff --git a/libs/cua-driver-rs/Cargo.lock b/libs/cua-driver-rs/Cargo.lockindex 30de63309a..0b282645c1 100644--- a/libs/cua-driver-rs/Cargo.lock+++ b/libs/cua-driver-rs/Cargo.lock@@ -242,7 +242,7 @@ dependencies = [[[package]]name = "cua-driver"-version = "0.2.5"+version = "0.2.7"dependencies = ["anyhow","async-trait",@@ -270,7 +270,7 @@ dependencies = [[[package]]name = "cursor-overlay"-version = "0.2.5"+version = "0.2.7"dependencies = ["anyhow","image",@@ -407,7 +407,7 @@ checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"[[package]]name = "focus-monitor-win"-version = "0.2.5"+version = "0.2.7"dependencies = ["windows",]@@ -844,7 +844,7 @@ dependencies = [[[package]]name = "mcp-server"-version = "0.2.5"+version = "0.2.7"dependencies = ["anyhow","async-trait",@@ -1130,13 +1130,14 @@ checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"[[package]]name = "platform-linux"-version = "0.2.5"+version = "0.2.7"dependencies = ["anyhow","async-trait","base64","cursor-overlay","image",+ "libc","mcp-server","serde","serde_json",@@ -1149,7 +1150,7 @@ dependencies = [[[package]]name = "platform-macos"-version = "0.2.5"+version = "0.2.7"dependencies = ["anyhow","async-trait",@@ -1179,7 +1180,7 @@ dependencies = [[[package]]name = "platform-windows"-version = "0.2.5"+version = "0.2.7"dependencies = ["anyhow","async-trait",diff --git a/libs/cua-driver-rs/crates/platform-linux/Cargo.toml b/libs/cua-driver-rs/crates/platform-linux/Cargo.tomlindex 5b00aa1227..f904821e20 100644--- a/libs/cua-driver-rs/crates/platform-linux/Cargo.toml+++ b/libs/cua-driver-rs/crates/platform-linux/Cargo.toml@@ -21,3 +21,5 @@ tiny-skia = { version = "0.11", default-features = false, features = ["std"] }x11rb = { version = "0.13", features = ["xinput", "randr", "xfixes", "composite", "shape"] }base64 = { workspace = true }image = { workspace = true }+# kill(2) for the kill_app tool — SIGKILL via libc::kill.+libc = "0.2"diff --git a/libs/cua-driver-rs/crates/platform-linux/src/tools/impl_.rs b/libs/cua-driver-rs/crates/platform-linux/src/tools/impl_.rsindex 838a02dcf8..135e81c019 100644--- a/libs/cua-driver-rs/crates/platform-linux/src/tools/impl_.rs+++ b/libs/cua-driver-rs/crates/platform-linux/src/tools/impl_.rs@@ -1933,6 +1933,49 @@ impl Tool for TypeTextCharsTool {}}+// ── kill_app ──────────────────────────────────────────────────────────────────++pub struct KillAppTool;+static KILL_DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();++#[async_trait]+impl Tool for KillAppTool {+ fn def(&self) -> &ToolDef {+ KILL_DEF.get_or_init(|| ToolDef {+ name: "kill_app".into(),+ description: "Force-terminate a process by pid (kill -9 equivalent on Linux). \+ Use as escalation when the cooperative close path failed to make the process \+ exit. Unsaved state is lost — prefer the cooperative path first.".into(),+ input_schema: json!({"type":"object","required":["pid"],"properties":{+ "pid":{"type":"integer","description":"PID of the process to terminate."}+ },"additionalProperties":false}),+ read_only: false,+ destructive: true,+ idempotent: true,+ open_world: false,+ })+ }++ async fn invoke(&self, args: Value) -> ToolResult {+ let pid_i = match args.get("pid").and_then(|v| v.as_i64()) {+ Some(p) if p > 0 && p <= i32::MAX as i64 => p as i32,+ Some(_) => return ToolResult::error("kill_app: `pid` must be a positive integer".to_string()),+ None => return ToolResult::error("kill_app: missing required integer field `pid`".to_string()),+ };+ // 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 {+ 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."+ ))+ }+ }+}+// ── registry ─────────────────────────────────────────────────────────────────pub fn build_registry() -> ToolRegistry {@@ -1942,6 +1985,7 @@ pub fn build_registry() -> ToolRegistry {r.register(Box::new(ListWindowsTool));r.register(Box::new(GetWindowStateTool { state: state.clone() }));r.register(Box::new(LaunchAppTool));+ r.register(Box::new(KillAppTool));r.register(Box::new(ClickTool { state: state.clone() }));r.register(Box::new(DoubleClickTool { state: state.clone() }));r.register(Box::new(RightClickTool { state: state.clone() }));diff --git a/libs/cua-driver-rs/crates/platform-linux/src/tools/stubs.rs b/libs/cua-driver-rs/crates/platform-linux/src/tools/stubs.rsindex e23761f219..30e844e763 100644--- a/libs/cua-driver-rs/crates/platform-linux/src/tools/stubs.rs+++ b/libs/cua-driver-rs/crates/platform-linux/src/tools/stubs.rs@@ -56,6 +56,10 @@ stub_tool!(launch_app_m, LaunchAppTool, "launch_app","Launch an app in the background. Provide name or bundle_id.",serde_json::json!({"type":"object","properties":{"bundle_id":{"type":"string"},"name":{"type":"string"},"urls":{"type":"array","items":{"type":"string"}}},"additionalProperties":false}));+stub_tool!(kill_app_m, KillAppTool, "kill_app",+ "Force-terminate a process by pid (taskkill /F on Windows, kill -9 on macOS / Linux). Use as escalation when the cooperative close path didn't make the process exit.",+ serde_json::json!({"type":"object","required":["pid"],"properties":{"pid":{"type":"integer","description":"PID of the process to terminate."}},"additionalProperties":false}));+stub_tool!(click_m, ClickTool, "click","Click at (x, y) or on an AT-SPI element by element_index + window_id.",serde_json::json!({"type":"object","required":["pid"],"properties":{"pid":{"type":"integer"},"window_id":{"type":"integer"},"element_index":{"type":"integer"},"x":{"type":"number"},"y":{"type":"number"},"modifier":{"type":"array","items":{"type":"string"}},"from_zoom":{"type":"boolean"}},"additionalProperties":false}));@@ -200,6 +204,7 @@ pub fn build_registry() -> mcp_server::tool::ToolRegistry {r.register(Box::new(ListWindowsTool));r.register(Box::new(GetWindowStateTool));r.register(Box::new(LaunchAppTool));+ r.register(Box::new(KillAppTool));r.register(Box::new(ClickTool));r.register(Box::new(DoubleClickTool));r.register(Box::new(RightClickTool));diff --git a/libs/cua-driver-rs/crates/platform-macos/src/tools/kill_app.rs b/libs/cua-driver-rs/crates/platform-macos/src/tools/kill_app.rsnew file mode 100644index 0000000000..89f3443c99--- /dev/null+++ b/libs/cua-driver-rs/crates/platform-macos/src/tools/kill_app.rs@@ -0,0 +1,73 @@+//! macOS `kill_app` tool — force-terminate a process by pid via SIGKILL.+//!+//! Cross-platform mirror of the Windows `kill_app` tool (which calls+//! `TerminateProcess`). On macOS the canonical force-terminate is+//! `kill(pid, SIGKILL)` — same semantics as `kill -9 <pid>`.+//!+//! Used as the escalation path when the cooperative quit-app flow+//! (`hotkey cmd+q` / sending an `NSWorkspaceTerminate` Apple Event)+//! doesn't actually exit the target — e.g. an app that has caught the+//! quit handler and is showing a "save before quitting?" dialog the+//! agent can't interact with.++use async_trait::async_trait;+use mcp_server::{protocol::ToolResult, tool::{Tool, ToolDef}};+use serde_json::Value;++pub struct KillAppTool;++static DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();++fn def() -> &'static ToolDef {+ DEF.get_or_init(|| ToolDef {+ name: "kill_app".into(),+ description:+ "Force-terminate a process by pid (kill -9 equivalent on macOS / Linux; \+ taskkill /F equivalent on Windows). Use as escalation when the cooperative \+ close path (hotkey cmd+q on macOS, click-the-X on Windows) failed to make \+ the process exit. Unsaved state is lost — prefer the cooperative path first."+ .into(),+ input_schema: serde_json::json!({+ "type": "object",+ "required": ["pid"],+ "properties": {+ "pid": { "type": "integer", "description": "PID of the process to terminate." }+ },+ "additionalProperties": false,+ }),+ read_only: false,+ destructive: true,+ idempotent: true,+ open_world: false,+ })+}++#[async_trait]+impl Tool for KillAppTool {+ fn def(&self) -> &ToolDef { def() }++ async fn invoke(&self, args: Value) -> ToolResult {+ let pid_i = match args.get("pid").and_then(|v| v.as_i64()) {+ Some(p) if p > 0 && p <= i32::MAX as i64 => p as i32,+ Some(_) => return ToolResult::error("kill_app: `pid` must be a positive integer".to_string()),+ None => return ToolResult::error("kill_app: missing required integer field `pid`".to_string()),+ };++ // libc::kill is fast and synchronous; no need to spawn_blocking.+ // Returns 0 on success, -1 on error (errno).+ // SAFETY: SIGKILL (9) is the standard force-kill signal; libc::kill+ // is a thin syscall wrapper with 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 {+ // Capture errno before any allocation that might overwrite it.+ 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 \+ (cross-user or root-owned processes will return EPERM)."+ ))+ }+ }+}diff --git a/libs/cua-driver-rs/crates/platform-macos/src/tools/mod.rs b/libs/cua-driver-rs/crates/platform-macos/src/tools/mod.rsindex 501dbc8ce5..92dd00edea 100644--- a/libs/cua-driver-rs/crates/platform-macos/src/tools/mod.rs+++ b/libs/cua-driver-rs/crates/platform-macos/src/tools/mod.rs@@ -4,6 +4,7 @@ mod list_apps;mod list_windows;mod get_window_state;mod launch_app;+mod kill_app;mod click;mod double_click;mod right_click;@@ -203,6 +204,7 @@ pub fn register_all(registry: &mut ToolRegistry) {registry.register(Box::new(list_windows::ListWindowsTool));registry.register(Box::new(get_window_state::GetWindowStateTool::new(state.clone())));registry.register(Box::new(launch_app::LaunchAppTool));+ registry.register(Box::new(kill_app::KillAppTool));registry.register(Box::new(click::ClickTool::new(state.clone())));registry.register(Box::new(double_click::DoubleClickTool::new(state.clone())));registry.register(Box::new(right_click::RightClickTool::new(state.clone())));diff --git a/libs/cua-driver-rs/crates/platform-windows/src/tools/impl_.rs b/libs/cua-driver-rs/crates/platform-windows/src/tools/impl_.rsindex 20c320cb85..fb3a12ef17 100644--- a/libs/cua-driver-rs/crates/platform-windows/src/tools/impl_.rs+++ b/libs/cua-driver-rs/crates/platform-windows/src/tools/impl_.rs@@ -3082,6 +3082,108 @@ impl Tool for TypeTextCharsTool {}}+// ── kill_app ──────────────────────────────────────────────────────────────────+//+// Force-terminate a process by pid. Background:+// * Win32 / GDI apps respond cleanly to `WM_CLOSE` (Alt+F4 via PostMessage),+// so `click` on the X button or a hand-rolled hotkey gesture suffices.+// * UWP / WinUI3 apps (Calculator, Photos, modern Settings, Win11 Notepad)+// have backgrounding semantics — they accept `WM_CLOSE` but route it+// into a "minimize to suspended" path instead of exiting. Cooperative+// close-button automation produces orphan processes that survive every+// polite eviction attempt. See CUA-541 for the live repro from+// WINDOWS_CLAUDE_CODE_TEST_PLAN.md Test G (3 leftover CalculatorApp.exe).+//+// `kill_app` is the force-terminate escalation — `taskkill /F` equivalent —+// keyed on pid. Marked `destructive: true` so MCP clients with permission+// gating prompt before invoking.++pub struct KillAppTool;+static KILL_DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();++#[async_trait]+impl Tool for KillAppTool {+ fn def(&self) -> &ToolDef {+ KILL_DEF.get_or_init(|| ToolDef {+ name: "kill_app".into(),+ description: "Force-terminate a process by pid. Use when the standard close path \+ (Alt+F4 / WM_CLOSE via `click` on the X button) fails to make the process \+ exit — typical for UWP / WinUI3 apps (Calculator, Photos, modern Notepad) \+ that route WM_CLOSE into a suspended-but-resident state. Equivalent to \+ `taskkill /F /PID <pid>`. Unsaved state is lost. Prefer the click-the-X path \+ first; only escalate to `kill_app` when polite close didn't terminate."+ .into(),+ input_schema: json!({"type":"object","required":["pid"],"properties":{+ "pid":{"type":"integer","description":"PID of the process to terminate."}+ },"additionalProperties":false}),+ read_only: false,+ destructive: true,+ idempotent: true,+ open_world: false,+ })+ }++ async fn invoke(&self, args: Value) -> ToolResult {+ let pid_v: u32 = match args.get("pid").and_then(|v| v.as_u64()) {+ Some(p) if p > 0 && p <= u32::MAX as u64 => p as u32,+ Some(_) => return ToolResult::error("kill_app: `pid` must be a positive integer".to_string()),+ None => return ToolResult::error("kill_app: missing required integer field `pid`".to_string()),+ };++ // Run the syscalls on a blocking thread — TerminateProcess + the+ // WaitForSingleObject confirmation are both blocking, and we don't+ // want to stall the tokio reactor.+ let outcome = tokio::task::spawn_blocking(move || -> Result<(), String> {+ use windows::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0};+ use windows::Win32::System::Threading::{+ OpenProcess, TerminateProcess, WaitForSingleObject,+ PROCESS_TERMINATE, PROCESS_SYNCHRONIZE,+ };++ // SAFETY: OpenProcess returns a Result<HANDLE> in windows-rs;+ // PROCESS_TERMINATE | PROCESS_SYNCHRONIZE lets us both kill the+ // target AND wait for the OS to fully reap it (so the caller's+ // follow-up list_apps reflects the change immediately).+ let h = unsafe { OpenProcess(PROCESS_TERMINATE | PROCESS_SYNCHRONIZE, false, pid_v) }+ .map_err(|e| format!(+ "OpenProcess(pid={pid_v}, PROCESS_TERMINATE|PROCESS_SYNCHRONIZE) failed: {e}. \+ The process may not exist, or the daemon lacks the right to terminate it. \+ Try listing processes first to confirm the pid is correct."+ ))?;++ let term_result = unsafe { TerminateProcess(h, 1) };++ // WaitForSingleObject so the caller can assume the process is+ // really gone on return. 2-second cap — TerminateProcess is+ // synchronous in practice but the OS still needs a moment to+ // reap kernel structures. WAIT_TIMEOUT is treated as a soft+ // success (the kill request landed; the process may take a+ // little longer to disappear from list_apps).+ let wait_status = unsafe { WaitForSingleObject(h, 2000) };+ let _ = unsafe { CloseHandle(h) };++ match (term_result, wait_status) {+ (Ok(()), s) if s == WAIT_OBJECT_0 => Ok(()),+ (Ok(()), _) => Ok(()), // killed, wait timed out — caller can re-check+ (Err(e), _) => Err(format!(+ "TerminateProcess(pid={pid_v}) failed: {e}. The handle was opened \+ successfully but the kill itself was rejected; this is unusual for \+ PROCESS_TERMINATE rights and may indicate a protected-process target \+ (PPL, e.g. csrss / system services)."+ )),+ }+ }).await;++ match outcome {+ Ok(Ok(())) => ToolResult::text(format!("✅ Terminated pid {pid_v}.")),+ Ok(Err(e)) => ToolResult::error(format!("kill_app: {e}")),+ Err(join_err) => ToolResult::error(format!(+ "kill_app: blocking-task join error: {join_err}"+ )),+ }+ }+}+// ── registry builder ──────────────────────────────────────────────────────────pub fn build_registry() -> ToolRegistry {@@ -3091,6 +3193,7 @@ pub fn build_registry() -> ToolRegistry {r.register(Box::new(ListWindowsTool));r.register(Box::new(GetWindowStateTool { state: state.clone() }));r.register(Box::new(LaunchAppTool));+ r.register(Box::new(KillAppTool));r.register(Box::new(ClickTool { state: state.clone() }));r.register(Box::new(DoubleClickTool { state: state.clone() }));r.register(Box::new(RightClickTool { state: state.clone() }));diff --git a/libs/cua-driver-rs/crates/platform-windows/src/tools/stubs.rs b/libs/cua-driver-rs/crates/platform-windows/src/tools/stubs.rsindex ce274f2bd9..8de7ac772b 100644--- a/libs/cua-driver-rs/crates/platform-windows/src/tools/stubs.rs+++ b/libs/cua-driver-rs/crates/platform-windows/src/tools/stubs.rs@@ -56,6 +56,10 @@ stub_tool!(launch_app_m, LaunchAppTool, "launch_app","Launch an app in the background. Provide bundle_id (macOS) or name.",serde_json::json!({"type":"object","properties":{"bundle_id":{"type":"string"},"name":{"type":"string"},"urls":{"type":"array","items":{"type":"string"}}},"additionalProperties":false}));+stub_tool!(kill_app_m, KillAppTool, "kill_app",+ "Force-terminate a process by pid (taskkill /F equivalent on Windows). Use as escalation when the cooperative close path didn't make the process exit — typical for UWP / WinUI3 apps that route WM_CLOSE into a suspended-but-resident state.",+ serde_json::json!({"type":"object","required":["pid"],"properties":{"pid":{"type":"integer","description":"PID of the process to terminate."}},"additionalProperties":false}));+stub_tool!(click_m, ClickTool, "click","Click at (x, y) or on an AX/UIA element by element_index + window_id.",serde_json::json!({"type":"object","required":["pid"],"properties":{"pid":{"type":"integer"},"window_id":{"type":"integer"},"element_index":{"type":"integer"},"x":{"type":"number"},"y":{"type":"number"},"modifier":{"type":"array","items":{"type":"string"}},"from_zoom":{"type":"boolean"}},"additionalProperties":false}));@@ -200,6 +204,7 @@ pub fn build_registry() -> mcp_server::tool::ToolRegistry {r.register(Box::new(ListWindowsTool));r.register(Box::new(GetWindowStateTool));r.register(Box::new(LaunchAppTool));+ r.register(Box::new(KillAppTool));r.register(Box::new(ClickTool));r.register(Box::new(DoubleClickTool));r.register(Box::new(RightClickTool));