Repository navigation
Add cleanup_before_exit plugin hook, CLI kills entire app tree - #14443
Conversation
Package Changes Through a2a62d8There 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 VersionsThe following package releases are the planned based on the context of changes in this pull request.
Add another change file through the GitHub UI by following this link. Read about change files or the docs at github.com/jbolda/covector |
Legend-Master
left a comment
There was a problem hiding this comment.
Thanks for working on this!
| /// 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>) {} |
There was a problem hiding this comment.
We would also want to implement this for the TauriPlugin so that tauri::plugin::Builder could have access to this API
There was a problem hiding this comment.
for sure! I’ll add this to the TauriPlugin trait as well so it’s accessible via tauri::plugin::Builder.
| /// 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<()> { |
There was a problem hiding this comment.
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)
There was a problem hiding this comment.
Would it be okay if I leave a TODO for now and move it in a follow-up PR?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
i think that would make sense, yes. we can always move it back if needed (that way around works)
|
I think we have now gathered a few different problems around this now:
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. |
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 |
|
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. |
I think this is more or less something we should provide in shell plugin?
Could you explain about this a bit more?
Not the biggest fan of this either |
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.
Months ago, did not remember too much details.
More, hanlding with resue |
Hmm, that sounds weird, the tauri async runtime by default 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 /// 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)
} |
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 |
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 🙃 |
|
Field data + implementation notes from shipping a very similar system, in case it helps this PR move. Field data for the
That's why the CLI-side part of this PR (the Registry semantics we learned the hard way (we ship a
On the primitive itself: we ended up not walking the process tree. On Unix, spawning the sidecar into its own process group ( 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.
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.
|
This change introduced a deadlock, please take a look, a fix: #16090 |
* 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>
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:
Files Changed:
Testing:
Call app_handle.register_sidecar(child.id() as u32) after spawning.
Fixes #14360