From 047a684e320d50240259809e7bf53c079671277b Mon Sep 17 00:00:00 2001 From: Sakina Farukh Ahemad Date: Mon, 10 Nov 2025 17:50:08 +0530 Subject: [PATCH 01/16] Add kill-tree helper and runtime sidecar PID registry --- .../tauri-cli/src/interface/rust/desktop.rs | 37 +++++++++ crates/tauri/CHANGELOG.md | 10 +++ crates/tauri/PR_DRAFT.md | 35 +++++++++ crates/tauri/src/app.rs | 21 +++++ crates/tauri/src/manager/mod.rs | 23 +++++- crates/tauri/src/process.rs | 76 +++++++++++++++++++ 6 files changed, 201 insertions(+), 1 deletion(-) create mode 100644 crates/tauri/PR_DRAFT.md diff --git a/crates/tauri-cli/src/interface/rust/desktop.rs b/crates/tauri-cli/src/interface/rust/desktop.rs index f5edb4d6e693..b0f8a11163f1 100644 --- a/crates/tauri-cli/src/interface/rust/desktop.rs +++ b/crates/tauri-cli/src/interface/rust/desktop.rs @@ -28,6 +28,43 @@ pub struct DevChild { impl DevProcess for DevChild { fn kill(&self) -> std::io::Result<()> { + // Best-effort: attempt to kill the child process tree before killing the process + // This mirrors the approach used in the main `tauri` crate's helper. + if let Some(pid) = self.dev_child.id() { + #[cfg(windows)] + { + use std::process::Command; + let ps = format!( + "function Kill-Tree {{ Param([int]$ppid); Get-CimInstance Win32_Process | Where-Object {{ $_.ParentProcessId -eq $ppid }} | ForEach-Object {{ Kill-Tree $_.ProcessId }}; Stop-Process -Id $ppid -ErrorAction SilentlyContinue }}; Kill-Tree {}", + pid + ); + let _ = Command::new("powershell") + .arg("-NoProfile") + .arg("-Command") + .arg(ps) + .status(); + } + + #[cfg(not(windows))] + { + use std::process::Command; + let sh = format!(r#" +getcpid() {{ + for cpid in $(pgrep -P "$1" 2>/dev/null || true); do + getcpid "$cpid" + echo "$cpid" + done +}} +for p in $(getcpid {pid}); do + kill -9 "$p" 2>/dev/null || true +done +kill -9 {pid} 2>/dev/null || true +"#, pid = pid); + + let _ = Command::new("sh").arg("-c").arg(sh).status(); + } + } + self.dev_child.kill()?; self.manually_killed_app.store(true, Ordering::Relaxed); Ok(()) diff --git a/crates/tauri/CHANGELOG.md b/crates/tauri/CHANGELOG.md index 5dfa010859da..154702c0639a 100644 --- a/crates/tauri/CHANGELOG.md +++ b/crates/tauri/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## \[Unreleased] + +### Enhancements + +- Added a best-effort process tree killer and sidecar PID registry: + - `kill_process_tree(pid: u32)` helper (cross-platform, shell/PowerShell based). + - Runtime-side sidecar PID registry and `AppHandle::register_sidecar` / `unregister_sidecar`. + - CLI dev-run integration attempts to kill sidecar descendant processes during terminate. + This helps ensure descendant processes spawned by sidecars are terminated when a sidecar is killed. (Fixes #14360) + ## \[2.9.2] ### Bug Fixes diff --git a/crates/tauri/PR_DRAFT.md b/crates/tauri/PR_DRAFT.md new file mode 100644 index 000000000000..8309b75b5837 --- /dev/null +++ b/crates/tauri/PR_DRAFT.md @@ -0,0 +1,35 @@ +Title: Add kill-tree helper and runtime sidecar PID registry (Fixes #14360) + +Summary + +This PR adds a best-effort process-tree killer and a lightweight runtime registry to help ensure that descendant processes spawned by sidecars are terminated when a sidecar is killed. + +What I changed + +- crates/tauri/src/process.rs + - Added `pub fn kill_process_tree(pid: u32) -> std::io::Result<()>` which invokes platform-specific shell/PowerShell snippets to terminate a process tree (best-effort, no new deps). + +- crates/tauri/src/manager/mod.rs + - Added `sidecar_pids: Arc>>` and methods: `register_sidecar`, `unregister_sidecar`, `drain_sidecar_pids`. + +- crates/tauri/src/app.rs + - Added `AppHandle::register_sidecar` and `AppHandle::unregister_sidecar` convenience methods. + - Wired `cleanup_before_exit()` to drain the sidecar registry and call `kill_process_tree` for each registered PID. + +- crates/tauri-cli/src/interface/rust/desktop.rs + - Dev-run kill path now attempts a best-effort kill-tree invocation for dev child processes. + +Testing done + +- Ran `cargo test -p tauri` locally: unit tests and doc-tests passed. +- The changes are designed to be best-effort (no panics on failures). The runtime requires spawners to call `register_sidecar(pid)` after spawning a sidecar so it can be cleaned up at exit. + +Notes & follow-ups + +- This is a pragmatic, short-term fix using shell/PowerShell helpers. We can consider a Rust-native implementation later for better portability and finer control. +- We should update any sidecar spawners (plugins or examples that call `Command::spawn()`) to call `app.handle().register_sidecar(child.id() as u32)` after spawning and `unregister_sidecar` when stopping the sidecar. +- Add an integration test that spawns a parent process which itself spawns a child, registers the parent PID, and asserts both are gone after cleanup. + +References + +- Fixes #14360 diff --git a/crates/tauri/src/app.rs b/crates/tauri/src/app.rs index b950895bc002..3758f4c364a5 100644 --- a/crates/tauri/src/app.rs +++ b/crates/tauri/src/app.rs @@ -501,6 +501,19 @@ impl AppHandle { Ok(()) } + /// Register a sidecar PID to be killed on application cleanup. + /// + /// This is a best-effort API: failures to kill child processes are logged but do not + /// cause the application to panic. + pub fn register_sidecar(&self, pid: u32) { + self.manager.register_sidecar(pid); + } + + /// Unregister a previously-registered sidecar PID. + pub fn unregister_sidecar(&self, pid: u32) { + self.manager.unregister_sidecar(pid); + } + /// Removes the plugin with the given name. /// /// # Examples @@ -1037,6 +1050,14 @@ macro_rules! shared_app_impl { for (_, webview) in self.manager.webviews() { webview.resources_table().clear(); } + // Best-effort: kill registered sidecar process trees. + // We drain the registry so we don't attempt to kill them again. + let sidecar_pids = self.manager.drain_sidecar_pids(); + for pid in sidecar_pids { + if let Err(e) = crate::process::kill_process_tree(pid) { + log::warn!("failed to kill sidecar pid {}: {}", pid, e); + } + } } /// Gets the invoke key that must be referenced when using [`crate::webview::InvokeRequest`]. diff --git a/crates/tauri/src/manager/mod.rs b/crates/tauri/src/manager/mod.rs index 2126dd8957ce..6c8de78bd2ed 100644 --- a/crates/tauri/src/manager/mod.rs +++ b/crates/tauri/src/manager/mod.rs @@ -4,7 +4,7 @@ use std::{ borrow::Cow, - collections::HashMap, + collections::{HashMap, HashSet}, fmt, sync::{atomic::AtomicBool, Arc, Mutex, MutexGuard}, }; @@ -214,6 +214,8 @@ pub struct AppManager { /// Application Resources Table pub(crate) resources_table: Arc>, + /// Registered sidecar PIDs that should be cleaned up on app exit. + pub(crate) sidecar_pids: Arc>>, /// Runtime-generated invoke key. pub(crate) invoke_key: String, @@ -322,6 +324,7 @@ impl AppManager { pattern: Arc::new(context.pattern), plugin_global_api_scripts: Arc::new(context.plugin_global_api_scripts), resources_table: Arc::default(), + sidecar_pids: Arc::default(), invoke_key, channel_interceptor, restart_on_exit: AtomicBool::new(false), @@ -696,6 +699,24 @@ impl AppManager { pub(crate) fn invoke_key(&self) -> &str { &self.invoke_key } + + /// Register a sidecar PID to be cleaned up on application exit. + pub fn register_sidecar(&self, pid: u32) { + let mut pids = self.sidecar_pids.lock().expect("poisoned sidecar_pids"); + pids.insert(pid); + } + + /// Unregister a previously-registered sidecar PID. + pub fn unregister_sidecar(&self, pid: u32) { + let mut pids = self.sidecar_pids.lock().expect("poisoned sidecar_pids"); + pids.remove(&pid); + } + + /// Drain and return the currently registered sidecar PIDs. + pub fn drain_sidecar_pids(&self) -> Vec { + let mut pids = self.sidecar_pids.lock().expect("poisoned sidecar_pids"); + pids.drain().collect() + } } #[cfg(desktop)] diff --git a/crates/tauri/src/process.rs b/crates/tauri/src/process.rs index 76937b1fe4b6..758687b014da 100644 --- a/crates/tauri/src/process.rs +++ b/crates/tauri/src/process.rs @@ -128,3 +128,79 @@ fn restart_macos_app(current_binary: &std::path::Path, env: &Env) { } } } + +/// Kill a process and all of its descendant processes (process tree). +/// +/// This helper will attempt a platform-appropriate recursive kill. It does not add any +/// extra crate dependencies and instead delegates to the system shell utilities. +/// +/// - On Windows it calls PowerShell and uses `Get-CimInstance Win32_Process` to traverse +/// the process tree and `Stop-Process` to terminate processes. +/// - On Unix (Linux / macOS / *nix) it uses `pgrep -P` recursively to find children and +/// sends SIGKILL to them. It tolerates missing `pgrep` by returning an error from the +/// spawned shell command. +/// +/// Note: This function attempts a best-effort termination and will return the +/// underlying I/O error if the platform command failed to spawn or returned a non-zero +/// exit status. +pub fn kill_process_tree(pid: u32) -> std::io::Result<()> { + #[cfg(windows)] + { + use std::process::Command; + + // Use PowerShell to recursively find and stop child processes, then stop the root. + // This mirrors the approach used elsewhere in the project (tauri-cli). + let ps = format!( + "function Kill-Tree {{ Param([int]$ppid); Get-CimInstance Win32_Process | Where-Object {{ $_.ParentProcessId -eq $ppid }} | ForEach-Object {{ Kill-Tree $_.ProcessId }}; Stop-Process -Id $ppid -ErrorAction SilentlyContinue }}; Kill-Tree {}", + pid + ); + + let status = Command::new("powershell") + .arg("-NoProfile") + .arg("-Command") + .arg(ps) + .status()?; + + if status.success() { + Ok(()) + } else { + Err(std::io::Error::new( + std::io::ErrorKind::Other, + format!("powershell kill-tree failed with status: {}", status), + )) + } + } + + #[cfg(not(windows))] + { + use std::process::Command; + + // On Unix, recursively collect children via pgrep -P and kill them. We use a small + // shell function to traverse descendants and then kill them. Use SIGKILL to ensure + // termination (best effort). + let sh = format!(r#" +getcpid() {{ + for cpid in $(pgrep -P "$1" 2>/dev/null || true); do + getcpid "$cpid" + echo "$cpid" + done +}} +for p in $(getcpid {pid}); do + kill -9 "$p" 2>/dev/null || true +done +kill -9 {pid} 2>/dev/null || true +"#, pid = pid); + + let status = Command::new("sh").arg("-c").arg(sh).status()?; + + if status.success() { + Ok(()) + } else { + Err(std::io::Error::new( + std::io::ErrorKind::Other, + format!("sh kill-tree failed with status: {}", status), + )) + } + } +} + From 6cef7c47877e91815cce53683c273de42d9f4e7d Mon Sep 17 00:00:00 2001 From: Sakina Farukh Ahemad Date: Mon, 10 Nov 2025 18:18:31 +0530 Subject: [PATCH 02/16] fixes --- .../tauri-cli/src/interface/rust/desktop.rs | 2 -- crates/tauri/src/app.rs | 9 +-------- crates/tauri/src/manager/mod.rs | 6 ------ crates/tauri/src/process.rs | 19 ------------------- 4 files changed, 1 insertion(+), 35 deletions(-) diff --git a/crates/tauri-cli/src/interface/rust/desktop.rs b/crates/tauri-cli/src/interface/rust/desktop.rs index b0f8a11163f1..92b87de34146 100644 --- a/crates/tauri-cli/src/interface/rust/desktop.rs +++ b/crates/tauri-cli/src/interface/rust/desktop.rs @@ -28,8 +28,6 @@ pub struct DevChild { impl DevProcess for DevChild { fn kill(&self) -> std::io::Result<()> { - // Best-effort: attempt to kill the child process tree before killing the process - // This mirrors the approach used in the main `tauri` crate's helper. if let Some(pid) = self.dev_child.id() { #[cfg(windows)] { diff --git a/crates/tauri/src/app.rs b/crates/tauri/src/app.rs index 3758f4c364a5..a8d699babcbd 100644 --- a/crates/tauri/src/app.rs +++ b/crates/tauri/src/app.rs @@ -501,15 +501,10 @@ impl AppHandle { Ok(()) } - /// Register a sidecar PID to be killed on application cleanup. - /// - /// This is a best-effort API: failures to kill child processes are logged but do not - /// cause the application to panic. pub fn register_sidecar(&self, pid: u32) { self.manager.register_sidecar(pid); } - /// Unregister a previously-registered sidecar PID. pub fn unregister_sidecar(&self, pid: u32) { self.manager.unregister_sidecar(pid); } @@ -1050,9 +1045,7 @@ macro_rules! shared_app_impl { for (_, webview) in self.manager.webviews() { webview.resources_table().clear(); } - // Best-effort: kill registered sidecar process trees. - // We drain the registry so we don't attempt to kill them again. - let sidecar_pids = self.manager.drain_sidecar_pids(); + let sidecar_pids = self.manager.drain_sidecar_pids(); for pid in sidecar_pids { if let Err(e) = crate::process::kill_process_tree(pid) { log::warn!("failed to kill sidecar pid {}: {}", pid, e); diff --git a/crates/tauri/src/manager/mod.rs b/crates/tauri/src/manager/mod.rs index 6c8de78bd2ed..05f9b0b9846e 100644 --- a/crates/tauri/src/manager/mod.rs +++ b/crates/tauri/src/manager/mod.rs @@ -214,7 +214,6 @@ pub struct AppManager { /// Application Resources Table pub(crate) resources_table: Arc>, - /// Registered sidecar PIDs that should be cleaned up on app exit. pub(crate) sidecar_pids: Arc>>, /// Runtime-generated invoke key. @@ -700,19 +699,14 @@ impl AppManager { &self.invoke_key } - /// Register a sidecar PID to be cleaned up on application exit. pub fn register_sidecar(&self, pid: u32) { let mut pids = self.sidecar_pids.lock().expect("poisoned sidecar_pids"); pids.insert(pid); } - - /// Unregister a previously-registered sidecar PID. pub fn unregister_sidecar(&self, pid: u32) { let mut pids = self.sidecar_pids.lock().expect("poisoned sidecar_pids"); pids.remove(&pid); } - - /// Drain and return the currently registered sidecar PIDs. pub fn drain_sidecar_pids(&self) -> Vec { let mut pids = self.sidecar_pids.lock().expect("poisoned sidecar_pids"); pids.drain().collect() diff --git a/crates/tauri/src/process.rs b/crates/tauri/src/process.rs index 758687b014da..227fe7ab8ec0 100644 --- a/crates/tauri/src/process.rs +++ b/crates/tauri/src/process.rs @@ -129,27 +129,11 @@ fn restart_macos_app(current_binary: &std::path::Path, env: &Env) { } } -/// Kill a process and all of its descendant processes (process tree). -/// -/// This helper will attempt a platform-appropriate recursive kill. It does not add any -/// extra crate dependencies and instead delegates to the system shell utilities. -/// -/// - On Windows it calls PowerShell and uses `Get-CimInstance Win32_Process` to traverse -/// the process tree and `Stop-Process` to terminate processes. -/// - On Unix (Linux / macOS / *nix) it uses `pgrep -P` recursively to find children and -/// sends SIGKILL to them. It tolerates missing `pgrep` by returning an error from the -/// spawned shell command. -/// -/// Note: This function attempts a best-effort termination and will return the -/// underlying I/O error if the platform command failed to spawn or returned a non-zero -/// exit status. pub fn kill_process_tree(pid: u32) -> std::io::Result<()> { #[cfg(windows)] { use std::process::Command; - // Use PowerShell to recursively find and stop child processes, then stop the root. - // This mirrors the approach used elsewhere in the project (tauri-cli). let ps = format!( "function Kill-Tree {{ Param([int]$ppid); Get-CimInstance Win32_Process | Where-Object {{ $_.ParentProcessId -eq $ppid }} | ForEach-Object {{ Kill-Tree $_.ProcessId }}; Stop-Process -Id $ppid -ErrorAction SilentlyContinue }}; Kill-Tree {}", pid @@ -175,9 +159,6 @@ pub fn kill_process_tree(pid: u32) -> std::io::Result<()> { { use std::process::Command; - // On Unix, recursively collect children via pgrep -P and kill them. We use a small - // shell function to traverse descendants and then kill them. Use SIGKILL to ensure - // termination (best effort). let sh = format!(r#" getcpid() {{ for cpid in $(pgrep -P "$1" 2>/dev/null || true); do From 130dad20b972bca9c02d7d8842b485e8493a56bd Mon Sep 17 00:00:00 2001 From: Sakina Farukh Ahemad Date: Wed, 12 Nov 2025 13:10:07 +0530 Subject: [PATCH 03/16] move sidecar cleanup to generic cleanup_before_exit hook --- crates/tauri/CHANGELOG.md | 7 ++++--- crates/tauri/PR_DRAFT.md | 37 +++++++++++++++++++++------------ crates/tauri/src/app.rs | 19 +++++++---------- crates/tauri/src/manager/mod.rs | 17 +-------------- crates/tauri/src/plugin.rs | 18 ++++++++++++++++ crates/tauri/src/process.rs | 5 +++++ 6 files changed, 59 insertions(+), 44 deletions(-) diff --git a/crates/tauri/CHANGELOG.md b/crates/tauri/CHANGELOG.md index 154702c0639a..481c1d5c1e97 100644 --- a/crates/tauri/CHANGELOG.md +++ b/crates/tauri/CHANGELOG.md @@ -4,11 +4,12 @@ ### Enhancements -- Added a best-effort process tree killer and sidecar PID registry: +- Added a best-effort process tree killer and plugin-level cleanup hook: - `kill_process_tree(pid: u32)` helper (cross-platform, shell/PowerShell based). - - Runtime-side sidecar PID registry and `AppHandle::register_sidecar` / `unregister_sidecar`. + - Plugin lifecycle hook `Plugin::cleanup_before_exit` and `PluginStore::cleanup_before_exit` — the runtime now delegates shutdown cleanup to plugins (for example the shell plugin) so they can manage sidecar lifecycle and process termination. + - Removed public convenience `AppHandle::register_sidecar` / `unregister_sidecar`: sidecar lifecycle and registration should be owned by the plugin responsible for spawning them. - CLI dev-run integration attempts to kill sidecar descendant processes during terminate. - This helps ensure descendant processes spawned by sidecars are terminated when a sidecar is killed. (Fixes #14360) + This ensures descendant processes spawned by sidecars are terminated while keeping process-control logic inside the plugin that owns the sidecar (Fixes #14360) ## \[2.9.2] diff --git a/crates/tauri/PR_DRAFT.md b/crates/tauri/PR_DRAFT.md index 8309b75b5837..0c59d8466566 100644 --- a/crates/tauri/PR_DRAFT.md +++ b/crates/tauri/PR_DRAFT.md @@ -1,34 +1,45 @@ -Title: Add kill-tree helper and runtime sidecar PID registry (Fixes #14360) +Title: Use plugin cleanup hooks for sidecar shutdown; add kill-tree helper (Fixes #14360) Summary -This PR adds a best-effort process-tree killer and a lightweight runtime registry to help ensure that descendant processes spawned by sidecars are terminated when a sidecar is killed. +This PR centralizes process-kill helpers in the runtime and moves responsibility for sidecar shutdown to plugins by adding a plugin-level cleanup hook. The core runtime no longer contains hardcoded sidecar draining logic; instead it calls `Plugin::cleanup_before_exit` so plugins (for example, the shell plugin) can take care of stopping sidecars and terminating process trees. What I changed - crates/tauri/src/process.rs - Added `pub fn kill_process_tree(pid: u32) -> std::io::Result<()>` which invokes platform-specific shell/PowerShell snippets to terminate a process tree (best-effort, no new deps). -- crates/tauri/src/manager/mod.rs - - Added `sidecar_pids: Arc>>` and methods: `register_sidecar`, `unregister_sidecar`, `drain_sidecar_pids`. +- crates/tauri/src/plugin.rs + - Added a plugin lifecycle hook `fn cleanup_before_exit(&mut self, app: &AppHandle) {}` with a default no-op. + - Added `PluginStore::cleanup_before_exit(&mut self, app: &AppHandle)` which invokes the hook for every registered plugin. - crates/tauri/src/app.rs - - Added `AppHandle::register_sidecar` and `AppHandle::unregister_sidecar` convenience methods. - - Wired `cleanup_before_exit()` to drain the sidecar registry and call `kill_process_tree` for each registered PID. + - Replaced the hardcoded sidecar PID draining and kill logic in the app shutdown path with a call to `plugins.lock().unwrap().cleanup_before_exit(self.app_handle())` so plugins perform shutdown work. + - Removed the previous `AppHandle::register_sidecar` / `unregister_sidecar` convenience methods from the public API (spawners should migrate to plugin-managed registries). -- crates/tauri-cli/src/interface/rust/desktop.rs - - Dev-run kill path now attempts a best-effort kill-tree invocation for dev child processes. +- Note on migration / shell plugin responsibilities + - The shell plugin (which lives in the plugins workspace) should implement `cleanup_before_exit` and perform any sidecar shutdown it needs. A minimal implementation is to drain the manager's sidecar registry and call `kill_process_tree` for each PID, e.g.: + + ```text + fn cleanup_before_exit(&mut self, app: &AppHandle) { + let pids = app.manager.drain_sidecar_pids(); + for pid in pids { + let _ = tauri::process::kill_process_tree(pid); + } + } + ``` + + This keeps process-management details inside the shell plugin (owner of sidecar lifecycle) and makes the runtime more extensible. Testing done -- Ran `cargo test -p tauri` locally: unit tests and doc-tests passed. -- The changes are designed to be best-effort (no panics on failures). The runtime requires spawners to call `register_sidecar(pid)` after spawning a sidecar so it can be cleaned up at exit. +- Ran `cargo check -p tauri` locally to verify compilation after wiring the plugin hook (no compile errors; one doc warning for `kill_process_tree`). Notes & follow-ups -- This is a pragmatic, short-term fix using shell/PowerShell helpers. We can consider a Rust-native implementation later for better portability and finer control. -- We should update any sidecar spawners (plugins or examples that call `Command::spawn()`) to call `app.handle().register_sidecar(child.id() as u32)` after spawning and `unregister_sidecar` when stopping the sidecar. -- Add an integration test that spawns a parent process which itself spawns a child, registers the parent PID, and asserts both are gone after cleanup. +- Implement `cleanup_before_exit` in the shell plugin (plugins-workspace repo). The shell plugin should be updated to drain any sidecar PID registries it manages and use `kill_process_tree` to ensure descendant processes are terminated. +- Update examples and any existing sidecar spawners to use the shell plugin or to call plugin-provided APIs instead of the removed `AppHandle::register_sidecar`/`unregister_sidecar`. +- Consider adding an integration test that validates sidecar shutdown via the shell plugin's cleanup hook. References diff --git a/crates/tauri/src/app.rs b/crates/tauri/src/app.rs index a8d699babcbd..97f8a323363e 100644 --- a/crates/tauri/src/app.rs +++ b/crates/tauri/src/app.rs @@ -501,13 +501,7 @@ impl AppHandle { Ok(()) } - pub fn register_sidecar(&self, pid: u32) { - self.manager.register_sidecar(pid); - } - pub fn unregister_sidecar(&self, pid: u32) { - self.manager.unregister_sidecar(pid); - } /// Removes the plugin with the given name. /// @@ -1045,12 +1039,13 @@ macro_rules! shared_app_impl { for (_, webview) in self.manager.webviews() { webview.resources_table().clear(); } - let sidecar_pids = self.manager.drain_sidecar_pids(); - for pid in sidecar_pids { - if let Err(e) = crate::process::kill_process_tree(pid) { - log::warn!("failed to kill sidecar pid {}: {}", pid, e); - } - } + // run plugin cleanup hooks so plugins can perform shutdown tasks (e.g. stop sidecars) + self + .manager + .plugins + .lock() + .unwrap() + .cleanup_before_exit(self.app_handle()); } /// Gets the invoke key that must be referenced when using [`crate::webview::InvokeRequest`]. diff --git a/crates/tauri/src/manager/mod.rs b/crates/tauri/src/manager/mod.rs index 05f9b0b9846e..2126dd8957ce 100644 --- a/crates/tauri/src/manager/mod.rs +++ b/crates/tauri/src/manager/mod.rs @@ -4,7 +4,7 @@ use std::{ borrow::Cow, - collections::{HashMap, HashSet}, + collections::HashMap, fmt, sync::{atomic::AtomicBool, Arc, Mutex, MutexGuard}, }; @@ -214,7 +214,6 @@ pub struct AppManager { /// Application Resources Table pub(crate) resources_table: Arc>, - pub(crate) sidecar_pids: Arc>>, /// Runtime-generated invoke key. pub(crate) invoke_key: String, @@ -323,7 +322,6 @@ impl AppManager { pattern: Arc::new(context.pattern), plugin_global_api_scripts: Arc::new(context.plugin_global_api_scripts), resources_table: Arc::default(), - sidecar_pids: Arc::default(), invoke_key, channel_interceptor, restart_on_exit: AtomicBool::new(false), @@ -698,19 +696,6 @@ impl AppManager { pub(crate) fn invoke_key(&self) -> &str { &self.invoke_key } - - pub fn register_sidecar(&self, pid: u32) { - let mut pids = self.sidecar_pids.lock().expect("poisoned sidecar_pids"); - pids.insert(pid); - } - pub fn unregister_sidecar(&self, pid: u32) { - let mut pids = self.sidecar_pids.lock().expect("poisoned sidecar_pids"); - pids.remove(&pid); - } - pub fn drain_sidecar_pids(&self) -> Vec { - let mut pids = self.sidecar_pids.lock().expect("poisoned sidecar_pids"); - pids.drain().collect() - } } #[cfg(desktop)] diff --git a/crates/tauri/src/plugin.rs b/crates/tauri/src/plugin.rs index 9c7f9a1abaaf..f6f407d3221b 100644 --- a/crates/tauri/src/plugin.rs +++ b/crates/tauri/src/plugin.rs @@ -104,6 +104,15 @@ pub trait Plugin: Send { #[allow(unused_variables)] fn on_event(&mut self, app: &AppHandle, event: &RunEvent) {} + /// Callback invoked when the application is performing cleanup before exit. + /// + /// Plugins can use this hook to perform any process shutdown/cleanup they need + /// to do before the runtime exits (for example, killing sidecars or stopping + /// background tasks). This is guaranteed to run from the thread performing + /// the app cleanup/exit sequence. + #[allow(unused_variables)] + fn cleanup_before_exit(&mut self, app: &AppHandle) {} + /// Extend commands to [`crate::Builder::invoke_handler`]. #[allow(unused_variables)] fn extend_api(&mut self, invoke: Invoke) -> bool { @@ -979,6 +988,15 @@ impl PluginStore { .for_each(|plugin| plugin.on_event(app, event)) } + /// Runs the cleanup_before_exit hook for all plugins in the store. + pub(crate) fn cleanup_before_exit(&mut self, app: &AppHandle) { + self.store.iter_mut().for_each(|plugin| { + #[cfg(feature = "tracing")] + let _span = tracing::trace_span!("plugin::hooks::cleanup_before_exit", name = plugin.name()).entered(); + plugin.cleanup_before_exit(app) + }) + } + /// Runs the plugin `extend_api` hook if it exists. Returns whether the invoke message was handled or not. /// /// The message is not handled when the plugin exists **and** the command does not. diff --git a/crates/tauri/src/process.rs b/crates/tauri/src/process.rs index 227fe7ab8ec0..dbd99fdb9718 100644 --- a/crates/tauri/src/process.rs +++ b/crates/tauri/src/process.rs @@ -134,6 +134,8 @@ pub fn kill_process_tree(pid: u32) -> std::io::Result<()> { { use std::process::Command; + // Use PowerShell to recursively find and stop child processes, then stop the root. + // This mirrors the approach used elsewhere in the project (tauri-cli). let ps = format!( "function Kill-Tree {{ Param([int]$ppid); Get-CimInstance Win32_Process | Where-Object {{ $_.ParentProcessId -eq $ppid }} | ForEach-Object {{ Kill-Tree $_.ProcessId }}; Stop-Process -Id $ppid -ErrorAction SilentlyContinue }}; Kill-Tree {}", pid @@ -159,6 +161,9 @@ pub fn kill_process_tree(pid: u32) -> std::io::Result<()> { { use std::process::Command; + // On Unix, recursively collect children via pgrep -P and kill them. We use a small + // shell function to traverse descendants and then kill them. Use SIGKILL to ensure + // termination (best effort). let sh = format!(r#" getcpid() {{ for cpid in $(pgrep -P "$1" 2>/dev/null || true); do From 5b6c5497020e3842d5725db66b02eff1da460661 Mon Sep 17 00:00:00 2001 From: Sakina Farukh Ahemad Date: Wed, 12 Nov 2025 13:17:23 +0530 Subject: [PATCH 04/16] use taskkill /T /PID for sidecar termination --- crates/tauri/PR_DRAFT.md | 8 ++++++++ crates/tauri/src/process.rs | 37 ++++++++++++++++++++++++++++++++++--- 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/crates/tauri/PR_DRAFT.md b/crates/tauri/PR_DRAFT.md index 0c59d8466566..b2bcadc699bb 100644 --- a/crates/tauri/PR_DRAFT.md +++ b/crates/tauri/PR_DRAFT.md @@ -41,6 +41,14 @@ Notes & follow-ups - Update examples and any existing sidecar spawners to use the shell plugin or to call plugin-provided APIs instead of the removed `AppHandle::register_sidecar`/`unregister_sidecar`. - Consider adding an integration test that validates sidecar shutdown via the shell plugin's cleanup hook. +- Windows implementation note + + - On Windows `kill_process_tree` now prefers the built-in `taskkill /T /PID /F` utility + which will terminate a process tree. If `taskkill` isn't available or returns a non-zero + exit status (for example due to permissions), the runtime falls back to a PowerShell-based + recursive traversal that mirrors the prior behavior. This makes termination more robust on + typical Windows environments while still preserving the previous fallback. + References - Fixes #14360 diff --git a/crates/tauri/src/process.rs b/crates/tauri/src/process.rs index dbd99fdb9718..8006552d24ee 100644 --- a/crates/tauri/src/process.rs +++ b/crates/tauri/src/process.rs @@ -129,13 +129,44 @@ fn restart_macos_app(current_binary: &std::path::Path, env: &Env) { } } +/// Kill a process and its descendant process tree (best-effort). +/// +/// On Windows this function prefers the built-in `taskkill /T /PID /F` +/// utility which can terminate a process tree. If `taskkill` is unavailable +/// or returns a non-zero exit status (for example due to permissions), the +/// function falls back to a PowerShell-based recursive traversal which mirrors +/// the previous implementation. +/// +/// On Unix-like systems a small shell function using `pgrep -P` is used to +/// collect child PIDs and send `SIGKILL` to descendants and the root PID. +/// +/// Note: terminating processes is inherently best-effort and may fail for +/// protected or system processes, or when the caller lacks sufficient +/// privileges. Callers should handle and log any errors returned by this +/// function. pub fn kill_process_tree(pid: u32) -> std::io::Result<()> { #[cfg(windows)] { use std::process::Command; - // Use PowerShell to recursively find and stop child processes, then stop the root. - // This mirrors the approach used elsewhere in the project (tauri-cli). + // Prefer the built-in `taskkill` utility on Windows which can terminate a process + // tree with `/T`. If that fails (permissions, not found, or non-zero exit), fall + // back to a PowerShell-based recursive stop that mirrors the previous behavior. + let pid_s = pid.to_string(); + + if let Ok(status) = Command::new("taskkill") + .args(&["/T", "/PID", &pid_s, "/F"]) // /F to force termination + .status() + { + if status.success() { + return Ok(()); + } + // If taskkill returned non-zero, fall through to try PowerShell. + } + + // Fallback: Use PowerShell to recursively find and stop child processes, then stop the root. + // This mirrors the approach used elsewhere in the project (tauri-cli) and preserves + // behavior on systems where taskkill isn't available or failed due to permissions. let ps = format!( "function Kill-Tree {{ Param([int]$ppid); Get-CimInstance Win32_Process | Where-Object {{ $_.ParentProcessId -eq $ppid }} | ForEach-Object {{ Kill-Tree $_.ProcessId }}; Stop-Process -Id $ppid -ErrorAction SilentlyContinue }}; Kill-Tree {}", pid @@ -152,7 +183,7 @@ pub fn kill_process_tree(pid: u32) -> std::io::Result<()> { } else { Err(std::io::Error::new( std::io::ErrorKind::Other, - format!("powershell kill-tree failed with status: {}", status), + format!("kill-tree failed: powershell exited with status: {}", status), )) } } From 74c437b0fedb6dc26319517be480d95b0a6181fc Mon Sep 17 00:00:00 2001 From: Sakina Farukh Ahemad Date: Sat, 15 Nov 2025 16:30:16 +0530 Subject: [PATCH 05/16] feat(core): add cleanup_before_exit hook to TauriPlugin trait and docs --- .changes/use-plugin-cleanups-and-kill-tree.md | 14 +++++ crates/tauri/CHANGELOG.md | 11 ---- crates/tauri/PR_DRAFT.md | 54 ------------------- crates/tauri/src/plugin.rs | 4 +- crates/tauri/src/process.rs | 2 + 5 files changed, 18 insertions(+), 67 deletions(-) create mode 100644 .changes/use-plugin-cleanups-and-kill-tree.md delete mode 100644 crates/tauri/PR_DRAFT.md diff --git a/.changes/use-plugin-cleanups-and-kill-tree.md b/.changes/use-plugin-cleanups-and-kill-tree.md new file mode 100644 index 000000000000..61b9713b3d39 --- /dev/null +++ b/.changes/use-plugin-cleanups-and-kill-tree.md @@ -0,0 +1,14 @@ +--- +'@tauri-apps/tauri': 'minor:enhance' +--- + +Introduce plugin-level cleanup hooks and centralize process-tree termination logic. + +This change: +- Adds `kill_process_tree` helper to the runtime for cross-platform process-tree shutdown. +- Adds a new `cleanup_before_exit` lifecycle hook to plugins and wires it so plugin authors + can handle sidecar shutdown without core runtime logic. +- Removes hardcoded sidecar-draining from the runtime and delegates shutdown behavior to plugins. + +This allows plugins (such as the shell plugin) to manage their own sidecar processes cleanly +and improves extensibility of the Tauri runtime. Fixes #14360. diff --git a/crates/tauri/CHANGELOG.md b/crates/tauri/CHANGELOG.md index 481c1d5c1e97..5dfa010859da 100644 --- a/crates/tauri/CHANGELOG.md +++ b/crates/tauri/CHANGELOG.md @@ -1,16 +1,5 @@ # Changelog -## \[Unreleased] - -### Enhancements - -- Added a best-effort process tree killer and plugin-level cleanup hook: - - `kill_process_tree(pid: u32)` helper (cross-platform, shell/PowerShell based). - - Plugin lifecycle hook `Plugin::cleanup_before_exit` and `PluginStore::cleanup_before_exit` — the runtime now delegates shutdown cleanup to plugins (for example the shell plugin) so they can manage sidecar lifecycle and process termination. - - Removed public convenience `AppHandle::register_sidecar` / `unregister_sidecar`: sidecar lifecycle and registration should be owned by the plugin responsible for spawning them. - - CLI dev-run integration attempts to kill sidecar descendant processes during terminate. - This ensures descendant processes spawned by sidecars are terminated while keeping process-control logic inside the plugin that owns the sidecar (Fixes #14360) - ## \[2.9.2] ### Bug Fixes diff --git a/crates/tauri/PR_DRAFT.md b/crates/tauri/PR_DRAFT.md deleted file mode 100644 index b2bcadc699bb..000000000000 --- a/crates/tauri/PR_DRAFT.md +++ /dev/null @@ -1,54 +0,0 @@ -Title: Use plugin cleanup hooks for sidecar shutdown; add kill-tree helper (Fixes #14360) - -Summary - -This PR centralizes process-kill helpers in the runtime and moves responsibility for sidecar shutdown to plugins by adding a plugin-level cleanup hook. The core runtime no longer contains hardcoded sidecar draining logic; instead it calls `Plugin::cleanup_before_exit` so plugins (for example, the shell plugin) can take care of stopping sidecars and terminating process trees. - -What I changed - -- crates/tauri/src/process.rs - - Added `pub fn kill_process_tree(pid: u32) -> std::io::Result<()>` which invokes platform-specific shell/PowerShell snippets to terminate a process tree (best-effort, no new deps). - -- crates/tauri/src/plugin.rs - - Added a plugin lifecycle hook `fn cleanup_before_exit(&mut self, app: &AppHandle) {}` with a default no-op. - - Added `PluginStore::cleanup_before_exit(&mut self, app: &AppHandle)` which invokes the hook for every registered plugin. - -- crates/tauri/src/app.rs - - Replaced the hardcoded sidecar PID draining and kill logic in the app shutdown path with a call to `plugins.lock().unwrap().cleanup_before_exit(self.app_handle())` so plugins perform shutdown work. - - Removed the previous `AppHandle::register_sidecar` / `unregister_sidecar` convenience methods from the public API (spawners should migrate to plugin-managed registries). - -- Note on migration / shell plugin responsibilities - - The shell plugin (which lives in the plugins workspace) should implement `cleanup_before_exit` and perform any sidecar shutdown it needs. A minimal implementation is to drain the manager's sidecar registry and call `kill_process_tree` for each PID, e.g.: - - ```text - fn cleanup_before_exit(&mut self, app: &AppHandle) { - let pids = app.manager.drain_sidecar_pids(); - for pid in pids { - let _ = tauri::process::kill_process_tree(pid); - } - } - ``` - - This keeps process-management details inside the shell plugin (owner of sidecar lifecycle) and makes the runtime more extensible. - -Testing done - -- Ran `cargo check -p tauri` locally to verify compilation after wiring the plugin hook (no compile errors; one doc warning for `kill_process_tree`). - -Notes & follow-ups - -- Implement `cleanup_before_exit` in the shell plugin (plugins-workspace repo). The shell plugin should be updated to drain any sidecar PID registries it manages and use `kill_process_tree` to ensure descendant processes are terminated. -- Update examples and any existing sidecar spawners to use the shell plugin or to call plugin-provided APIs instead of the removed `AppHandle::register_sidecar`/`unregister_sidecar`. -- Consider adding an integration test that validates sidecar shutdown via the shell plugin's cleanup hook. - -- Windows implementation note - - - On Windows `kill_process_tree` now prefers the built-in `taskkill /T /PID /F` utility - which will terminate a process tree. If `taskkill` isn't available or returns a non-zero - exit status (for example due to permissions), the runtime falls back to a PowerShell-based - recursive traversal that mirrors the prior behavior. This makes termination more robust on - typical Windows environments while still preserving the previous fallback. - -References - -- Fixes #14360 diff --git a/crates/tauri/src/plugin.rs b/crates/tauri/src/plugin.rs index f6f407d3221b..114f700f78a3 100644 --- a/crates/tauri/src/plugin.rs +++ b/crates/tauri/src/plugin.rs @@ -108,8 +108,8 @@ pub trait Plugin: Send { /// /// Plugins can use this hook to perform any process shutdown/cleanup they need /// to do before the runtime exits (for example, killing sidecars or stopping - /// background tasks). This is guaranteed to run from the thread performing - /// the app cleanup/exit sequence. + /// background tasks). This hook is executed inside `App::cleanup_before_exit` during application shutdown. + #[allow(unused_variables)] fn cleanup_before_exit(&mut self, app: &AppHandle) {} diff --git a/crates/tauri/src/process.rs b/crates/tauri/src/process.rs index 8006552d24ee..ed357caa9f26 100644 --- a/crates/tauri/src/process.rs +++ b/crates/tauri/src/process.rs @@ -144,6 +144,8 @@ fn restart_macos_app(current_binary: &std::path::Path, env: &Env) { /// protected or system processes, or when the caller lacks sufficient /// privileges. Callers should handle and log any errors returned by this /// function. + +// TODO: Move this helper into the `process` plugin in the plugins-workspace repo. pub fn kill_process_tree(pid: u32) -> std::io::Result<()> { #[cfg(windows)] { From 171c0e58fc5cb7a23d975a43506a4f657958fb57 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Date: Thu, 17 Sep 2026 15:13:58 -0300 Subject: [PATCH 06/16] chore: rustfmt --- crates/tauri-cli/src/interface/rust/desktop.rs | 7 +++++-- crates/tauri/src/app.rs | 2 -- crates/tauri/src/plugin.rs | 3 ++- crates/tauri/src/process.rs | 13 +++++++++---- 4 files changed, 16 insertions(+), 9 deletions(-) diff --git a/crates/tauri-cli/src/interface/rust/desktop.rs b/crates/tauri-cli/src/interface/rust/desktop.rs index 744d09e6668c..7b74dcb4f65d 100644 --- a/crates/tauri-cli/src/interface/rust/desktop.rs +++ b/crates/tauri-cli/src/interface/rust/desktop.rs @@ -46,7 +46,8 @@ impl DevProcess for DevChild { #[cfg(not(windows))] { use std::process::Command; - let sh = format!(r#" + let sh = format!( + r#" getcpid() {{ for cpid in $(pgrep -P "$1" 2>/dev/null || true); do getcpid "$cpid" @@ -57,7 +58,9 @@ for p in $(getcpid {pid}); do kill -9 "$p" 2>/dev/null || true done kill -9 {pid} 2>/dev/null || true -"#, pid = pid); +"#, + pid = pid + ); let _ = Command::new("sh").arg("-c").arg(sh).status(); } diff --git a/crates/tauri/src/app.rs b/crates/tauri/src/app.rs index 9d7196f2e37b..6a34bc9da1c1 100644 --- a/crates/tauri/src/app.rs +++ b/crates/tauri/src/app.rs @@ -541,8 +541,6 @@ impl AppHandle { Ok(()) } - - /// Removes the plugin with the given name. /// /// # Examples diff --git a/crates/tauri/src/plugin.rs b/crates/tauri/src/plugin.rs index 7949eab801d2..4285bf00e423 100644 --- a/crates/tauri/src/plugin.rs +++ b/crates/tauri/src/plugin.rs @@ -993,7 +993,8 @@ impl PluginStore { pub(crate) fn cleanup_before_exit(&mut self, app: &AppHandle) { self.store.iter_mut().for_each(|plugin| { #[cfg(feature = "tracing")] - let _span = tracing::trace_span!("plugin::hooks::cleanup_before_exit", name = plugin.name()).entered(); + let _span = + tracing::trace_span!("plugin::hooks::cleanup_before_exit", name = plugin.name()).entered(); plugin.cleanup_before_exit(app) }) } diff --git a/crates/tauri/src/process.rs b/crates/tauri/src/process.rs index a2f3a48e02fd..fea51adf4215 100644 --- a/crates/tauri/src/process.rs +++ b/crates/tauri/src/process.rs @@ -185,7 +185,10 @@ pub fn kill_process_tree(pid: u32) -> std::io::Result<()> { } else { Err(std::io::Error::new( std::io::ErrorKind::Other, - format!("kill-tree failed: powershell exited with status: {}", status), + format!( + "kill-tree failed: powershell exited with status: {}", + status + ), )) } } @@ -197,7 +200,8 @@ pub fn kill_process_tree(pid: u32) -> std::io::Result<()> { // On Unix, recursively collect children via pgrep -P and kill them. We use a small // shell function to traverse descendants and then kill them. Use SIGKILL to ensure // termination (best effort). - let sh = format!(r#" + let sh = format!( + r#" getcpid() {{ for cpid in $(pgrep -P "$1" 2>/dev/null || true); do getcpid "$cpid" @@ -208,7 +212,9 @@ for p in $(getcpid {pid}); do kill -9 "$p" 2>/dev/null || true done kill -9 {pid} 2>/dev/null || true -"#, pid = pid); +"#, + pid = pid + ); let status = Command::new("sh").arg("-c").arg(sh).status()?; @@ -222,4 +228,3 @@ kill -9 {pid} 2>/dev/null || true } } } - From 32384e0383645afc3d2ad640e12afd7abfc58f7f Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Date: Thu, 17 Sep 2026 15:15:42 -0300 Subject: [PATCH 07/16] fix(cli): `SharedChild::id` returns `u32`, not `Option` --- .../tauri-cli/src/interface/rust/desktop.rs | 46 +++++++++---------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/crates/tauri-cli/src/interface/rust/desktop.rs b/crates/tauri-cli/src/interface/rust/desktop.rs index 7b74dcb4f65d..3dbf201b727e 100644 --- a/crates/tauri-cli/src/interface/rust/desktop.rs +++ b/crates/tauri-cli/src/interface/rust/desktop.rs @@ -28,26 +28,27 @@ pub struct DevChild { impl DevProcess for DevChild { fn kill(&self) -> std::io::Result<()> { - if let Some(pid) = self.dev_child.id() { - #[cfg(windows)] - { - use std::process::Command; - let ps = format!( - "function Kill-Tree {{ Param([int]$ppid); Get-CimInstance Win32_Process | Where-Object {{ $_.ParentProcessId -eq $ppid }} | ForEach-Object {{ Kill-Tree $_.ProcessId }}; Stop-Process -Id $ppid -ErrorAction SilentlyContinue }}; Kill-Tree {}", - pid - ); - let _ = Command::new("powershell") - .arg("-NoProfile") - .arg("-Command") - .arg(ps) - .status(); - } + let pid = self.dev_child.id(); + + #[cfg(windows)] + { + use std::process::Command; + let ps = format!( + "function Kill-Tree {{ Param([int]$ppid); Get-CimInstance Win32_Process | Where-Object {{ $_.ParentProcessId -eq $ppid }} | ForEach-Object {{ Kill-Tree $_.ProcessId }}; Stop-Process -Id $ppid -ErrorAction SilentlyContinue }}; Kill-Tree {}", + pid + ); + let _ = Command::new("powershell") + .arg("-NoProfile") + .arg("-Command") + .arg(ps) + .status(); + } - #[cfg(not(windows))] - { - use std::process::Command; - let sh = format!( - r#" + #[cfg(not(windows))] + { + use std::process::Command; + let sh = format!( + r#" getcpid() {{ for cpid in $(pgrep -P "$1" 2>/dev/null || true); do getcpid "$cpid" @@ -59,11 +60,10 @@ for p in $(getcpid {pid}); do done kill -9 {pid} 2>/dev/null || true "#, - pid = pid - ); + pid = pid + ); - let _ = Command::new("sh").arg("-c").arg(sh).status(); - } + let _ = Command::new("sh").arg("-c").arg(sh).status(); } self.dev_child.kill()?; From 336f2739d7dbd49768420801c279ef706c226050 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Date: Thu, 17 Sep 2026 15:19:03 -0300 Subject: [PATCH 08/16] refactor(core): drop `kill_process_tree` from `tauri::process` Per review, a public helper in core cannot be removed later without a major release, and a PID-only tree kill cannot be made robust (it needs control at spawn time: process groups on Unix, Job Objects on Windows). It belongs in the `process`/`shell` plugin in plugins-workspace instead (see plugins-workspace#1332). The shell-based implementation also spawned `taskkill`/`powershell` without `CREATE_NO_WINDOW` (console flash in GUI apps) and was compiled for iOS/Android where `sh`/`pgrep` are unavailable. --- crates/tauri/src/process.rs | 100 ------------------------------------ 1 file changed, 100 deletions(-) diff --git a/crates/tauri/src/process.rs b/crates/tauri/src/process.rs index fea51adf4215..c4218a95ca94 100644 --- a/crates/tauri/src/process.rs +++ b/crates/tauri/src/process.rs @@ -128,103 +128,3 @@ fn restart_macos_app(current_binary: &std::path::Path, env: &Env) { } } } - -/// Kill a process and its descendant process tree (best-effort). -/// -/// On Windows this function prefers the built-in `taskkill /T /PID /F` -/// utility which can terminate a process tree. If `taskkill` is unavailable -/// or returns a non-zero exit status (for example due to permissions), the -/// function falls back to a PowerShell-based recursive traversal which mirrors -/// the previous implementation. -/// -/// On Unix-like systems a small shell function using `pgrep -P` is used to -/// collect child PIDs and send `SIGKILL` to descendants and the root PID. -/// -/// Note: terminating processes is inherently best-effort and may fail for -/// protected or system processes, or when the caller lacks sufficient -/// privileges. Callers should handle and log any errors returned by this -/// function. - -// TODO: Move this helper into the `process` plugin in the plugins-workspace repo. -pub fn kill_process_tree(pid: u32) -> std::io::Result<()> { - #[cfg(windows)] - { - use std::process::Command; - - // Prefer the built-in `taskkill` utility on Windows which can terminate a process - // tree with `/T`. If that fails (permissions, not found, or non-zero exit), fall - // back to a PowerShell-based recursive stop that mirrors the previous behavior. - let pid_s = pid.to_string(); - - if let Ok(status) = Command::new("taskkill") - .args(&["/T", "/PID", &pid_s, "/F"]) // /F to force termination - .status() - { - if status.success() { - return Ok(()); - } - // If taskkill returned non-zero, fall through to try PowerShell. - } - - // Fallback: Use PowerShell to recursively find and stop child processes, then stop the root. - // This mirrors the approach used elsewhere in the project (tauri-cli) and preserves - // behavior on systems where taskkill isn't available or failed due to permissions. - let ps = format!( - "function Kill-Tree {{ Param([int]$ppid); Get-CimInstance Win32_Process | Where-Object {{ $_.ParentProcessId -eq $ppid }} | ForEach-Object {{ Kill-Tree $_.ProcessId }}; Stop-Process -Id $ppid -ErrorAction SilentlyContinue }}; Kill-Tree {}", - pid - ); - - let status = Command::new("powershell") - .arg("-NoProfile") - .arg("-Command") - .arg(ps) - .status()?; - - if status.success() { - Ok(()) - } else { - Err(std::io::Error::new( - std::io::ErrorKind::Other, - format!( - "kill-tree failed: powershell exited with status: {}", - status - ), - )) - } - } - - #[cfg(not(windows))] - { - use std::process::Command; - - // On Unix, recursively collect children via pgrep -P and kill them. We use a small - // shell function to traverse descendants and then kill them. Use SIGKILL to ensure - // termination (best effort). - let sh = format!( - r#" -getcpid() {{ - for cpid in $(pgrep -P "$1" 2>/dev/null || true); do - getcpid "$cpid" - echo "$cpid" - done -}} -for p in $(getcpid {pid}); do - kill -9 "$p" 2>/dev/null || true -done -kill -9 {pid} 2>/dev/null || true -"#, - pid = pid - ); - - let status = Command::new("sh").arg("-c").arg(sh).status()?; - - if status.success() { - Ok(()) - } else { - Err(std::io::Error::new( - std::io::ErrorKind::Other, - format!("sh kill-tree failed with status: {}", status), - )) - } - } -} From 3279eb5eb4dafa56a0c976d4d1a4060082ad5418 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Date: Thu, 17 Sep 2026 15:20:30 -0300 Subject: [PATCH 09/16] chore(core): fix clippy `empty_line_after_doc_comments` --- crates/tauri/src/plugin.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/tauri/src/plugin.rs b/crates/tauri/src/plugin.rs index 4285bf00e423..c3fc670a5441 100644 --- a/crates/tauri/src/plugin.rs +++ b/crates/tauri/src/plugin.rs @@ -109,7 +109,6 @@ pub trait Plugin: Send { /// Plugins can use this hook to perform any process shutdown/cleanup they need /// to do before the runtime exits (for example, killing sidecars or stopping /// background tasks). This hook is executed inside `App::cleanup_before_exit` during application shutdown. - #[allow(unused_variables)] fn cleanup_before_exit(&mut self, app: &AppHandle) {} From 59342dc3b459c3110734f71f2a0ceda789d75e17 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Date: Thu, 17 Sep 2026 15:23:36 -0300 Subject: [PATCH 10/16] feat(core): expose `cleanup_before_exit` hook on `plugin::Builder` Plugins built with `tauri::plugin::Builder` (which includes every plugins-workspace plugin, e.g. `shell`) could not use the new `Plugin::cleanup_before_exit` hook because `TauriPlugin` did not implement it. Add `Builder::on_cleanup_before_exit` and forward it. --- crates/tauri/src/plugin.rs | 63 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/crates/tauri/src/plugin.rs b/crates/tauri/src/plugin.rs index c3fc670a5441..d0e9dd41bef3 100644 --- a/crates/tauri/src/plugin.rs +++ b/crates/tauri/src/plugin.rs @@ -125,6 +125,7 @@ type SetupHook = type OnWindowReady = dyn FnMut(Window) + Send; type OnWebviewReady = dyn FnMut(Webview) + Send; type OnEvent = dyn FnMut(&AppHandle, &RunEvent) + Send; +type OnCleanupBeforeExit = dyn FnMut(&AppHandle) + Send; type OnNavigation = dyn Fn(&Webview, &Url) -> bool + Send; type OnPageLoad = dyn FnMut(&Webview, &PageLoadPayload<'_>) + Send; type OnDrop = dyn FnOnce(AppHandle) + Send; @@ -280,6 +281,7 @@ pub struct Builder { on_window_ready: Box>, on_webview_ready: Box>, on_event: Box>, + on_cleanup_before_exit: Box>, on_drop: Option>>, uri_scheme_protocols: HashMap>>, } @@ -297,6 +299,7 @@ impl Builder { on_window_ready: Box::new(|_| ()), on_webview_ready: Box::new(|_| ()), on_event: Box::new(|_, _| ()), + on_cleanup_before_exit: Box::new(|_| ()), on_drop: None, uri_scheme_protocols: Default::default(), } @@ -576,6 +579,32 @@ impl Builder { self } + /// Callback invoked when the application is performing cleanup before exit. + /// + /// See [`Plugin::cleanup_before_exit`] for details. + /// + /// # Examples + /// + /// ```rust + /// use tauri::{plugin::{Builder, TauriPlugin}, Runtime}; + /// + /// fn init() -> TauriPlugin { + /// Builder::new("example") + /// .on_cleanup_before_exit(|app| { + /// // release OS resources such as child processes here + /// }) + /// .build() + /// } + /// ``` + #[must_use] + pub fn on_cleanup_before_exit(mut self, on_cleanup_before_exit: F) -> Self + where + F: FnMut(&AppHandle) + Send + 'static, + { + self.on_cleanup_before_exit = Box::new(on_cleanup_before_exit); + self + } + /// Callback invoked when the plugin is dropped. /// /// # Examples @@ -749,6 +778,7 @@ impl Builder { on_window_ready: self.on_window_ready, on_webview_ready: self.on_webview_ready, on_event: self.on_event, + on_cleanup_before_exit: self.on_cleanup_before_exit, on_drop: self.on_drop, uri_scheme_protocols: self.uri_scheme_protocols, }) @@ -776,6 +806,7 @@ pub struct TauriPlugin { on_window_ready: Box>, on_webview_ready: Box>, on_event: Box>, + on_cleanup_before_exit: Box>, on_drop: Option>>, uri_scheme_protocols: HashMap>>, } @@ -856,6 +887,10 @@ impl Plugin for TauriPlugin { (self.on_event)(app, event) } + fn cleanup_before_exit(&mut self, app: &AppHandle) { + (self.on_cleanup_before_exit)(app) + } + fn extend_api(&mut self, invoke: Invoke) -> bool { (self.invoke_handler)(invoke) } @@ -1078,3 +1113,31 @@ impl<'de> Deserialize<'de> for PermissionState { } } } + +#[cfg(test)] +mod tests { + use super::{Builder, TauriPlugin}; + use crate::test::{MockRuntime, mock_builder, mock_context, noop_assets}; + use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }; + + #[test] + fn builder_cleanup_before_exit_hook_runs_on_app_cleanup() { + let called = Arc::new(AtomicBool::new(false)); + let called_ = called.clone(); + let plugin: TauriPlugin = Builder::new("cleanup-test") + .on_cleanup_before_exit(move |_app| called_.store(true, Ordering::SeqCst)) + .build(); + + let app = mock_builder() + .plugin(plugin) + .build(mock_context(noop_assets())) + .unwrap(); + + app.cleanup_before_exit(); + + assert!(called.load(Ordering::SeqCst)); + } +} From 7e38113120744d7ceae4a8c62fc7e26da3f090c0 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Date: Thu, 17 Sep 2026 15:25:18 -0300 Subject: [PATCH 11/16] fix(core): run plugin cleanup hooks before tearing down app resources Plugin `cleanup_before_exit` hooks were invoked after tray icons and resource tables were cleared and windows hidden, so plugins could not rely on those APIs during their own cleanup. Run them first. --- crates/tauri/src/app.rs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/crates/tauri/src/app.rs b/crates/tauri/src/app.rs index 6a34bc9da1c1..13d17946477f 100644 --- a/crates/tauri/src/app.rs +++ b/crates/tauri/src/app.rs @@ -1108,6 +1108,14 @@ macro_rules! shared_app_impl { /// Runs necessary cleanup tasks before exiting the process. /// **You should always exit the tauri app immediately after this function returns and not use any tauri-related APIs.** pub fn cleanup_before_exit(&self) { + // run plugin cleanup hooks first so plugins can still use the app resources (e.g. stop sidecars) + self + .manager + .plugins + .lock() + .unwrap() + .cleanup_before_exit(self.app_handle()); + #[cfg(all(desktop, feature = "tray-icon"))] self.manager.tray.icons.lock().unwrap().clear(); self.manager.resources_table().clear(); @@ -1119,13 +1127,6 @@ macro_rules! shared_app_impl { for (_, webview) in self.manager.webviews() { webview.resources_table().clear(); } - // run plugin cleanup hooks so plugins can perform shutdown tasks (e.g. stop sidecars) - self - .manager - .plugins - .lock() - .unwrap() - .cleanup_before_exit(self.app_handle()); } /// Gets the invoke key that must be referenced when using [`crate::webview::InvokeRequest`]. From b5af4e720468b428cd865177a87fc5cd7f77000a Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Date: Thu, 17 Sep 2026 15:27:37 -0300 Subject: [PATCH 12/16] fix(core): don't panic on a poisoned plugin store in `cleanup_before_exit` --- crates/tauri/src/app.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/tauri/src/app.rs b/crates/tauri/src/app.rs index 13d17946477f..c3d246c6e8c1 100644 --- a/crates/tauri/src/app.rs +++ b/crates/tauri/src/app.rs @@ -1109,11 +1109,12 @@ macro_rules! shared_app_impl { /// **You should always exit the tauri app immediately after this function returns and not use any tauri-related APIs.** pub fn cleanup_before_exit(&self) { // run plugin cleanup hooks first so plugins can still use the app resources (e.g. stop sidecars) + // cleanup is best-effort, so a plugin store poisoned by an earlier panic must not abort it self .manager .plugins .lock() - .unwrap() + .unwrap_or_else(std::sync::PoisonError::into_inner) .cleanup_before_exit(self.app_handle()); #[cfg(all(desktop, feature = "tray-icon"))] From 871a0acb9fa1dff1fd93d9508752737afb84d1a8 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Date: Thu, 17 Sep 2026 15:30:48 -0300 Subject: [PATCH 13/16] docs(core): clarify when `Plugin::cleanup_before_exit` runs and its constraints Explain how it differs from `RunEvent::Exit` (it also covers restart from the main thread), which paths it does not cover (process kill, `std::process::exit`), and that the plugin store is locked while it runs so plugin-store APIs must not be called from it. --- crates/tauri/src/plugin.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/crates/tauri/src/plugin.rs b/crates/tauri/src/plugin.rs index d0e9dd41bef3..634aa63a0d98 100644 --- a/crates/tauri/src/plugin.rs +++ b/crates/tauri/src/plugin.rs @@ -104,11 +104,19 @@ pub trait Plugin: Send { #[allow(unused_variables)] fn on_event(&mut self, app: &AppHandle, event: &RunEvent) {} - /// Callback invoked when the application is performing cleanup before exit. + /// Callback invoked by [`App::cleanup_before_exit`](crate::App::cleanup_before_exit) right before the process exits. + /// + /// Use it to release resources the OS does not reclaim on its own, such as child processes (sidecars). + /// + /// Unlike [`RunEvent::Exit`], this hook also runs on exit paths that bypass the event loop, + /// e.g. [`AppHandle::restart`] when called on the main thread. On a regular exit, + /// [`Plugin::on_event`] receives [`RunEvent::Exit`] first and then this hook is called. + /// It does **not** run when the process is killed (e.g. by `tauri dev` on rebuild) + /// or when `std::process::exit` is called directly. /// - /// Plugins can use this hook to perform any process shutdown/cleanup they need - /// to do before the runtime exits (for example, killing sidecars or stopping - /// background tasks). This hook is executed inside `App::cleanup_before_exit` during application shutdown. + /// The plugin store is locked while this hook runs, so it must not call APIs that access + /// other plugins such as [`AppHandle::remove_plugin`] or [`AppHandle::plugin`]. + /// No Tauri API should be used after it returns. #[allow(unused_variables)] fn cleanup_before_exit(&mut self, app: &AppHandle) {} From 10e1330a28d079e21093f3e9185e3badbda0e6fe Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Date: Thu, 17 Sep 2026 15:36:44 -0300 Subject: [PATCH 14/16] enhance(cli): use `taskkill /T /F` to kill the dev process tree on Windows Spawning PowerShell and enumerating `Win32_Process` per recursion level on every watcher-triggered restart is slow, and PowerShell can be disabled by policy. `taskkill` is built in and does the tree kill natively. --- crates/tauri-cli/src/interface/rust/desktop.rs | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/crates/tauri-cli/src/interface/rust/desktop.rs b/crates/tauri-cli/src/interface/rust/desktop.rs index 3dbf201b727e..5edf55647749 100644 --- a/crates/tauri-cli/src/interface/rust/desktop.rs +++ b/crates/tauri-cli/src/interface/rust/desktop.rs @@ -32,15 +32,10 @@ impl DevProcess for DevChild { #[cfg(windows)] { - use std::process::Command; - let ps = format!( - "function Kill-Tree {{ Param([int]$ppid); Get-CimInstance Win32_Process | Where-Object {{ $_.ParentProcessId -eq $ppid }} | ForEach-Object {{ Kill-Tree $_.ProcessId }}; Stop-Process -Id $ppid -ErrorAction SilentlyContinue }}; Kill-Tree {}", - pid - ); - let _ = Command::new("powershell") - .arg("-NoProfile") - .arg("-Command") - .arg(ps) + // `/T` terminates the whole process tree, `/F` forces it + let pid = pid.to_string(); + let _ = Command::new("taskkill") + .args(["/T", "/F", "/PID", pid.as_str()]) .status(); } From 44c4a71da1162b4fbda9a87ca40c996b63b2da24 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Date: Thu, 17 Sep 2026 15:40:52 -0300 Subject: [PATCH 15/16] refactor(cli): pass the pid to the kill-tree script as an argument and kill the root first Passing the pid as `$1` avoids escaping the script through `format!`. Killing the root before its (already collected) descendants prevents it from respawning children between the pgrep walk and the kill. Also drops the `use std::process::Command` that shadowed the module-level import. --- .../tauri-cli/src/interface/rust/desktop.rs | 33 ++++++++++--------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/crates/tauri-cli/src/interface/rust/desktop.rs b/crates/tauri-cli/src/interface/rust/desktop.rs index 5edf55647749..01f1e4186c23 100644 --- a/crates/tauri-cli/src/interface/rust/desktop.rs +++ b/crates/tauri-cli/src/interface/rust/desktop.rs @@ -41,24 +41,27 @@ impl DevProcess for DevChild { #[cfg(not(windows))] { - use std::process::Command; - let sh = format!( - r#" -getcpid() {{ - for cpid in $(pgrep -P "$1" 2>/dev/null || true); do - getcpid "$cpid" - echo "$cpid" + // collect the whole tree first, then kill the root before its descendants + // so it cannot respawn them in the meantime + const KILL_TREE: &str = r#" +descendants() { + for child in $(pgrep -P "$1" 2>/dev/null); do + echo "$child" + descendants "$child" done -}} -for p in $(getcpid {pid}); do - kill -9 "$p" 2>/dev/null || true +} +tree=$(descendants "$1") +kill -9 "$1" 2>/dev/null +for p in $tree; do + kill -9 "$p" 2>/dev/null done -kill -9 {pid} 2>/dev/null || true -"#, - pid = pid - ); +true +"#; - let _ = Command::new("sh").arg("-c").arg(sh).status(); + let pid = pid.to_string(); + let _ = Command::new("sh") + .args(["-c", KILL_TREE, "sh", pid.as_str()]) + .status(); } self.dev_child.kill()?; From a2a62d8a111bb00272c74b380741763d2b692bb8 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Date: Thu, 17 Sep 2026 15:42:57 -0300 Subject: [PATCH 16/16] chore: fix change files `@tauri-apps/tauri` is not a covector package (the crate is `tauri`), the CLI change had no entry, and the body described intermediate PR history instead of the user-facing change. --- .changes/cli-dev-kill-process-tree.md | 6 ++++++ .changes/plugin-cleanup-before-exit.md | 5 +++++ .changes/use-plugin-cleanups-and-kill-tree.md | 14 -------------- 3 files changed, 11 insertions(+), 14 deletions(-) create mode 100644 .changes/cli-dev-kill-process-tree.md create mode 100644 .changes/plugin-cleanup-before-exit.md delete mode 100644 .changes/use-plugin-cleanups-and-kill-tree.md diff --git a/.changes/cli-dev-kill-process-tree.md b/.changes/cli-dev-kill-process-tree.md new file mode 100644 index 000000000000..7f47727b842d --- /dev/null +++ b/.changes/cli-dev-kill-process-tree.md @@ -0,0 +1,6 @@ +--- +"tauri-cli": patch:bug +"@tauri-apps/cli": patch:bug +--- + +`tauri dev` now kills the whole process tree of the running app when it restarts or exits, so processes spawned by the app (e.g. sidecars) are no longer left orphaned. diff --git a/.changes/plugin-cleanup-before-exit.md b/.changes/plugin-cleanup-before-exit.md new file mode 100644 index 000000000000..6418b3e8b73f --- /dev/null +++ b/.changes/plugin-cleanup-before-exit.md @@ -0,0 +1,5 @@ +--- +"tauri": minor:feat +--- + +Added the `Plugin::cleanup_before_exit` hook and `plugin::Builder::on_cleanup_before_exit`, invoked by `App::cleanup_before_exit` right before the process exits so plugins can release resources such as sidecar processes. Unlike `RunEvent::Exit`, it also runs on exit paths that bypass the event loop such as `AppHandle::restart` on the main thread. diff --git a/.changes/use-plugin-cleanups-and-kill-tree.md b/.changes/use-plugin-cleanups-and-kill-tree.md deleted file mode 100644 index 61b9713b3d39..000000000000 --- a/.changes/use-plugin-cleanups-and-kill-tree.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -'@tauri-apps/tauri': 'minor:enhance' ---- - -Introduce plugin-level cleanup hooks and centralize process-tree termination logic. - -This change: -- Adds `kill_process_tree` helper to the runtime for cross-platform process-tree shutdown. -- Adds a new `cleanup_before_exit` lifecycle hook to plugins and wires it so plugin authors - can handle sidecar shutdown without core runtime logic. -- Removes hardcoded sidecar-draining from the runtime and delegates shutdown behavior to plugins. - -This allows plugins (such as the shell plugin) to manage their own sidecar processes cleanly -and improves extensibility of the Tauri runtime. Fixes #14360.