Skip to content

Add cleanup_before_exit plugin hook, CLI kills entire app tree - #14443

Merged
lucasfernog merged 17 commits into
tauri-apps:devfrom
sakina1303:fix
Sep 18, 2026
Merged

lucasfernog merged 17 commits into
tauri-apps:devfrom
sakina1303:fix

Conversation

@sakina1303

Copy link
Copy Markdown
Contributor

Adds a best-effort process-tree killer and a lightweight runtime sidecar PID registry, ensuring that descendant processes spawned by sidecars are properly terminated when their parent sidecar is killed.

This resolves the core issue described in #14360 by introducing both API and runtime cleanup mechanisms for sidecar process management.

Details:

  • tauri::process::kill_process_tree(pid: u32) — POSIX shell & PowerShell based, best-effort.
  • Sidecar PID registry via AppHandle::register_sidecar(pid) / unregister_sidecar(pid) for cleanup on exit.
  • App::cleanup_before_exit() drains registry and calls the kill helper.
  • CLI dev-run now attempts process-tree cleanup when stopping dev children.

Files Changed:

  • process.rs: Added kill_process_tree() (POSIX + PowerShell).
  • mod.rs: Added sidecar PID tracking + helper methods.
  • app.rs: Added register/unregister APIs; updated cleanup.
  • desktop.rs: Added kill-tree logic in dev-run path.
  • CHANGELOG.md / PR_DRAFT.md: Updated with notes.

Testing:

  • [ ✅ ] cargo test -p tauri, all tests passed.
  • [ ✅ ] Manual: verified registry and cleanup invoke kill helper.
  • Runtime cleanup is opt-in:
    Call app_handle.register_sidecar(child.id() as u32) after spawning.

Fixes #14360

@sakina1303
sakina1303 requested a review from a team as a code owner November 10, 2025 12:29
@github-actions

github-actions Bot commented Nov 10, 2025 •

Copy link
Copy Markdown
Contributor

Package Changes Through a2a62d8

There are 14 changes which include tauri-cli with minor, @tauri-apps/cli with minor, tauri with minor, tauri-build with minor, tauri-runtime with minor, tauri-runtime-wry with minor, tauri-utils with minor, tauri-bundler with minor, tauri-macos-sign with minor, tauri-codegen with minor, tauri-macros with minor, tauri-plugin with minor, tauri-driver with minor, @tauri-apps/api with minor

Planned Package Versions

The following package releases are the planned based on the context of changes in this pull request.

package current next
@tauri-apps/api 2.11.1 2.12.0
tauri-utils 2.9.3 2.10.0
tauri-macos-sign 2.3.4 2.4.0
tauri-bundler 2.9.4 2.10.0
tauri-runtime 2.11.3 2.12.0
tauri-runtime-wry 2.11.4 2.12.0
tauri-codegen 2.6.3 2.7.0
tauri-macros 2.6.3 2.7.0
tauri-plugin 2.6.3 2.7.0
tauri-build 2.6.3 2.7.0
tauri 2.11.5 2.12.0
@tauri-apps/cli 2.11.4 2.12.0
tauri-cli 2.11.4 2.12.0
tauri-driver 2.0.6 2.1.0

Add another change file through the GitHub UI by following this link.


Read about change files or the docs at github.com/jbolda/covector

Comment thread crates/tauri/src/app.rs Resolved

@Legend-Master Legend-Master left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for working on this!

Comment thread crates/tauri/CHANGELOG.md Resolved
Comment thread crates/tauri/PR_DRAFT.md Resolved
/// 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<R>) {}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We would also want to implement this for the TauriPlugin so that tauri::plugin::Builder could have access to this API

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for sure! I’ll add this to the TauriPlugin trait as well so it’s accessible via tauri::plugin::Builder.

Comment thread crates/tauri/src/app.rs Resolved
@Legend-Master Legend-Master added this to the 2.10 milestone Nov 12, 2025
Comment thread crates/tauri/src/plugin.rs Resolved
Comment thread crates/tauri/src/process.rs Outdated
/// 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<()> {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

since this is a generic function and not bound to this app instance imo this should be moved into https://github.com/tauri-apps/plugins-workspace/tree/v2/plugins/process (and in theory that plugin's exit and restart should probably be part of the app core plugin instead but that's a discussion for another day).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be okay if I leave a TODO for now and move it in a follow-up PR?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, we at least have to decide how to proceed here because once this is added in tauri we cannot remove it without a major release since removing apis is a breaking change.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should I move kill_process_tree to the process plugin now as you suggested? I’ll update this PR to avoid a future breaking change.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think that would make sense, yes. we can always move it back if needed (that way around works)

@Legend-Master

Legend-Master commented Nov 13, 2025 •

Copy link
Copy Markdown
Contributor

I think we have now gathered a few different problems around this now:

  • Only the side car process is killed on app exit, not the entire process tree
    • Just from testing, it seems like some of the processes are killed while some others are not???
  • tauri dev doesn't kill side cars (it kills the app forcefully by sending SIGKILL on mac and linux, TerminateProcess on Windows to cargo)
    • It seems to me that it does kill the side car but not always the entire process tree???
  • NSIS installers don't kill side cars, they kill the app forcefully through TerminateProcess (the Wix .msi installers do, they send WM_QUERYENDSESSION to the app which is now handled after fix(windows): emit LoopDestroyed on WM_ENDSESSION tao#1126 no, I thought they do but what actually happened is just it killed the tray icon by sending WM_CLOSE)
  • Updater plugin exits the app through std::process::exit which doesn't trigger the Exit event so side cars are not killed

My brain is basically fried right now, no more processes 😭

@FabianLars

Copy link
Copy Markdown
Member
  1. and perhaps 2) should imo be fixed via [shell] Add option to spawn command in process group plugins-workspace#1332 and not by trying to kill a process tree. prob doesn't help with the rest though.

@Tunglies

Tunglies commented Dec 2, 2025 •

Copy link
Copy Markdown
Contributor

I think we have now gathered a few different problems around this now:

  • Only the side car process is killed on app exit, not the entire process tree

    • Just from testing, it seems like some of the processes are killed while some others are not???
  • tauri dev doesn't kill side cars (it kills the app forcefully by sending SIGKILL on mac and linux, TerminateProcess on Windows to cargo)

    • It seems to me that it does kill the side car but not always the entire process tree???
  • NSIS installers don't kill side cars, they kill the app forcefully through TerminateProcess (the Wix .msi installers do, they send WM_QUERYENDSESSION to the app which is now handled after fix(windows): emit LoopDestroyed on WM_ENDSESSION tao#1126 no, I thought they do but what actually happened is just it killed the tray icon by sending WM_CLOSE)

  • Updater plugin exits the app through std::process::exit which doesn't trigger the Exit event so side cars are not killed

My brain is basically fried right now, no more processes 😭

I fixed point 1, 2 in my(our) project. 3 and 4 not test on my machine but has no community report related. With sidecar, I hold a custom strcture to wrap ProcessChild and give impl Drop for it to handle kill when droping. The entire app(which is main process) listen on system signal and excute tauri exiting and custom behavior, it will kill itself and its sidecar. They works well both in tauri dev and release build.

@Tunglies

Tunglies commented Dec 2, 2025

Copy link
Copy Markdown
Contributor

I think we have now gathered a few different problems around this now:

  • Only the side car process is killed on app exit, not the entire process tree

    • Just from testing, it seems like some of the processes are killed while some others are not???
  • tauri dev doesn't kill side cars (it kills the app forcefully by sending SIGKILL on mac and linux, TerminateProcess on Windows to cargo)

    • It seems to me that it does kill the side car but not always the entire process tree???
  • NSIS installers don't kill side cars, they kill the app forcefully through TerminateProcess (the Wix .msi installers do, they send WM_QUERYENDSESSION to the app which is now handled after fix(windows): emit LoopDestroyed on WM_ENDSESSION tao#1126 no, I thought they do but what actually happened is just it killed the tray icon by sending WM_CLOSE)

  • Updater plugin exits the app through std::process::exit which doesn't trigger the Exit event so side cars are not killed

My brain is basically fried right now, no more processes 😭

I fixed point 1, 2 in my(our) project. 3 and 4 not test on my machine but has no community report related. With sidecar, I hold a custom strcture to wrap ProcessChild and give impl Drop for it to handle kill when droping. The entire app(which is main process) listen on system signal and excute Apphandle::Exit, it will kill itself and its sidecar. They works well.

We found it's hard to fully trust tauri exit behavior, and external listen system signal mannuly in clash-verge-rev/crates/signal. But behavior of macOS system shutdown signal seems hooked by tauri, can only processing with tauri::RunEvent::Exit otherwise will skip signal hanlde, but ubuntu and other linux works fine.

@Tunglies

Tunglies commented Dec 2, 2025

Copy link
Copy Markdown
Contributor

This PR using system shell. For Windows example in some case, user can not invoke system powershell due to their machine permission setting or even disable powershell usage. We might not want to handle PID with shell diretcly, and there are potential security problems whether if cross-platform.

@Legend-Master

Copy link
Copy Markdown
Contributor

With sidecar, I hold a custom strcture to wrap ProcessChild and give impl Drop for it to handle kill when droping.

I think this is more or less something we should provide in shell plugin?

We found it's hard to fully trust tauri exit behavior

Could you explain about this a bit more?

This PR using system shell.

Not the biggest fan of this either

@Tunglies

Tunglies commented Dec 4, 2025

Copy link
Copy Markdown
Contributor

I think this is more or less something we should provide in shell plugin?

Yes, and the auto-cleanup or likely behavior can be toggled via a field setting whether if spawn or runtime. We did not provide this behavior before, might destroy downstream program behavior if enable by default.

Could you explain about this a bit more?

Months ago, did not remember too much details.

  • The sidecar plugin's process will not be killed when exiting cli tauri dev from terminal.
  • We tried handle with RunEvent::ExitRequested and RunEvent::Exit to reset system network settings when system shudown. None of linux, macOS and windows tasks works as expected. Might just we did not learned the proper way.

More, hanlding with resue tauri::asyncruntime to excute exiting or system shutdown operations in Windows will produce more likehood to failed or skipped. With a new tokio spawn would be totally fixed on that and works fine across Windows, macOS and Linux. clash-verge-rev/clash-verge-rev#5533 (comment) (Chinese)

@Legend-Master

Copy link
Copy Markdown
Contributor

We tried handle with RunEvent::ExitRequested and RunEvent::Exit to reset system network settings when system shudown. None of linux, macOS and windows tasks works as expected. Might just we did not learned the proper way.

RunEvent::Exit event should now fire on system shutdown on Windows (tauri-apps/tao#1126), not on macOS and Linux yet though

More, hanlding with resue tauri::asyncruntime to excute exiting or system shutdown operations in Windows will produce more likehood to failed or skipped.

Hmm, that sounds weird, the tauri async runtime by default should be very much the same as using a tokio one directly

@Tunglies

Tunglies commented Dec 4, 2025

Copy link
Copy Markdown
Contributor

should be very much the same as using a tokio one directly

Our program continuosly handle differents tauri commands, data-related processing, system setting processing. Might be a little more complex than genral program. The async_runtime::spawn The singleton async runtime used by Tauri and exposed to users. that we already used for spawn some inner tasks. A new tokio runtime would not be stuggle with tauri.

/// async_runtime::spawn
pub fn spawn<F>(task: F) -> JoinHandle<F::Output>
where
  F: Future + Send + 'static,
  F::Output: Send + 'static,
{
  let runtime = RUNTIME.get_or_init(default_runtime);
  runtime.spawn(task)
}

@Tunglies

Tunglies commented Dec 4, 2025 •

Copy link
Copy Markdown
Contributor

not on macOS and Linux yet though

Wierd on my test on macOS, signal_hook can not handle shutdown signal, but SIGTERM, SIGTERM interminal or standalone were fine. Macos shutdown handle only works with

#[cfg(target_os = "macos")]
        tauri::RunEvent::Exit => async_runtime::block_on(async {
            some_clean_up()
        }),

Linux works with competely works with signal_hook. Seemed tauri hooked macOS shutdown signal and use tauri::RunEvent::Exit for case.

@FabianLars

Copy link
Copy Markdown
Member

Macos shutdown handle only works with

Not gonna lie, this sounds like something macOS would. Not sending posix signals in favor of the NSApplication delegate bullshit would be such an Apple move 🙃
I'm somewhat sure it's not us doing that.

@aka-danielZhang

Copy link
Copy Markdown

Field data + implementation notes from shipping a very similar system, in case it helps this PR move.

Field data for the tauri dev path specifically. We maintain a Tauri 2 desktop app (dsh-desktop) whose Rust shell spawns a long-lived Node sidecar (a local web server the webview loads). One icon-retune session left 9 orphaned sidecars — each holding a random loopback port and a shared state directory, with live sessions inside them. Root cause chain, confirmed against tauri-cli 2.11.4 sources:

  • interface/rust.rs restarts the app on watch with child.kill() — SIGKILL on Unix, so no RunEvent::Exit, signal handler, Drop, or in-app registry can observe it. In-app cleanup is unreachable by construction on this path.
  • kill_before_dev_process's tree-kill only ever covers the beforeDevCommand child, not the app's own descendants.
  • The watcher's built-in ignore list (node_modules/ target/ gen/ Cargo.lock .DS_Store) doesn't include icons/, so even icon-only changes trigger the kill-restart loop with zero Rust changes.

That's why the CLI-side part of this PR (the desktop.rs dev-run cleanup) is the piece that actually fixes our orphan class — the runtime registry alone can't cover it. If splitting the PR into "CLI dev-run cleanup" and "runtime registry" helps either half land, we'd strongly encourage it.

Registry semantics we learned the hard way (we ship a ~/.dsh-desktop/sidecars.json with sweep-on-next-boot):

  • pid recycling: never reap on pid alone. We record ps lstart at spawn time and require equality before killing; a recycled pid simply reads as dead. This matters more than you'd expect on long-running desktop sessions.
  • fail open: a corrupt or missing registry must read as empty, never brick the boot. (Related to @Qodo-Free-For-OSS's note: best-effort cleanup should also survive a poisoned mutex — lock().unwrap_or_else(|e| e.into_inner()) is the usual pattern for exactly this.)
  • act only on registered pids: never scan the process table by name or cmdline — a terminal user running the same server binary must be unreachable by mistake.

On the primitive itself: we ended up not walking the process tree. On Unix, spawning the sidecar into its own process group (CommandExt::process_group(0), std since 1.64) turns kill(-pgid, SIGTERM) into an atomic, TOCTOU-free tree signal with zero shell involvement — which also sidesteps the PowerShell-availability and shell-quoting concerns raised above. We follow up with SIGKILL on the same group after a grace period so servers get a chance to flush (SIGTERM-first also matters for sidecars that own state, like ours). The same spawn site can adopt process-wrap for Windows Job Objects later, which is the direction of plugins-workspace#1332 — so the runtime half may naturally converge there.

Happy to contribute whichever half the team prefers to move first.

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.
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.
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.
…onstraints

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.
…ndows

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.
…d 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-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.
@lucasfernog lucasfernog changed the title Add kill-tree helper and runtime sidecar PID registry Add cleanup_before_exit plugin hook, CLI kills entire app tree Sep 18, 2026
@lucasfernog
lucasfernog merged commit f6634b2 into tauri-apps:dev Sep 18, 2026
27 checks passed
justanotheranonymoususer added a commit to justanotheranonymoususer/tauri that referenced this pull request Sep 22, 2026
The plugin store is locked for the whole of every plugin callback: setup
(`Builder::build` -> `initialize_plugins`, and `AppHandle::plugin`), the
window and webview hooks, `on_event`, and a plugin command. Since the
`Plugin::cleanup_before_exit` hook was added (tauri-apps#14443),
`App::cleanup_before_exit` locks that same store to run the hooks, so a
plugin that exits the app from one of its own callbacks blocks on a guard
its own thread is holding, and never returns.

The single-instance plugin does exactly that on Windows and Linux: its
setup hook forwards the new argv to the first instance, calls
`app.cleanup_before_exit()` and exits the process. Against tauri
3.0.0-alpha.2 every second launch of such an app instead hangs inside
plugin initialization, leaving a process that never exits and holds
whatever the app takes for its lifetime.

Take the store with `try_lock` and skip the plugin hooks when it cannot be
had. Cleanup is best-effort either way - a store poisoned by an earlier
panic was already skipped rather than allowed to abort the rest - and a
store held by this same thread can never be granted, so waiting for it can
only hang. The normal exit path is unchanged: nothing else holds the store
then, and the hooks run as before.
@justanotheranonymoususer

Copy link
Copy Markdown

This change introduced a deadlock, please take a look, a fix: #16090

lucasfernog added a commit that referenced this pull request Sep 25, 2026
lucasfernog added a commit that referenced this pull request Sep 25, 2026
* Add kill-tree helper and runtime sidecar PID registry

* fixes

* move sidecar cleanup to generic cleanup_before_exit hook

* use taskkill /T /PID for sidecar termination

* feat(core): add cleanup_before_exit hook to TauriPlugin trait and docs

* chore: rustfmt

* fix(cli): `SharedChild::id` returns `u32`, not `Option<u32>`

* 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.

* chore(core): fix clippy `empty_line_after_doc_comments`

* 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.

* 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.

* fix(core): don't panic on a poisoned plugin store in `cleanup_before_exit`

* 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.

* 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.

* 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.

* 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.

---------

Co-authored-by: Sakina Farukh Ahemad <sakina@Sakinas-MacBook-Pro.local>
Co-authored-by: Lucas Nogueira <lucas@tauri.app>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[feat] Add kill tree for sidecar

9 participants