Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(shell): Baumabbau findet auch den waehrend des Abbruchs gestarteten Arbeiter

purple8346583df851
diff --git a/src-tauri/src/commands/bg_tasks.rs b/src-tauri/src/commands/bg_tasks.rs
index 9aec08f9..3588402f 100644
--- a/src-tauri/src/commands/bg_tasks.rs
+++ b/src-tauri/src/commands/bg_tasks.rs
@@ -776,8 +776,10 @@ mod tests {
async fn cancelling_during_shell_startup_drains_the_pipes() {
let _isolation = super::sweep_isolation().await;
// Exercise the startup window repeatedly, not just a settled tree.
- // A missed ping child holds stdout open for30seconds with the old
- // per-process snapshot kill, even after the shell itself is gone.
+ // A missed ping child holds stdout open for 30 seconds even after the
+ // shell itself is gone, which is what `kill_tree`'s settle window is
+ // there to prevent; measured on the box as a 30.4 s stall in two of
+ // five rounds before that window existed.
for _ in 0..3 {
let started = shell_task_start_impl(&json!({ "command": sleep_cmd_30s() })).await.unwrap();
let id = started["id"].as_str().unwrap();
diff --git a/src-tauri/src/commands/shell.rs b/src-tauri/src/commands/shell.rs
index a517b45a..9d6cdbfb 100644
--- a/src-tauri/src/commands/shell.rs
+++ b/src-tauri/src/commands/shell.rs
@@ -174,6 +174,27 @@ pub(crate) fn descendants(root: u32, sys: &sysinfo::System) -> Vec<u32> {
out
}
+/// Everything below `root` in `sys` that is actually doing work, still alive,
+/// deepest last.
+///
+/// `conhost.exe` is left out because Windows attaches one to every process
+/// that gets a console, CREATE_NO_WINDOW included, and it shows up as a child
+/// of the shell before the shell has started anything of its own. Killing it
+/// says nothing about the `pnpm install` underneath, and counting it as a
+/// survivor would make every cancel wait out its full settle window. The name
+/// matches nothing on Unix, so the filter is inert there.
+pub(crate) fn worker_descendants_in(sys: &sysinfo::System, root: u32) -> Vec<u32> {
+ use sysinfo::Pid;
+ descendants(root, sys)
+ .into_iter()
+ .filter(|pid| {
+ sys.process(Pid::from_u32(*pid))
+ .map(|p| !p.name().to_string_lossy().eq_ignore_ascii_case("conhost.exe"))
+ .unwrap_or(false)
+ })
+ .collect()
+}
+
/// Kill the shell AND everything it started. `Child::kill()` signals only the
/// shell itself, so a timed-out `npm run dev`, build script or spawned server
/// kept running after the tool call gave up — still holding its port and CPU,
@@ -184,7 +205,7 @@ pub(crate) fn kill_tree(root: u32) {
let mut sys = System::new();
sys.refresh_processes(ProcessesToUpdate::All, true);
// Leaves first: a parent that is still alive can't respawn what we killed.
- let mut order = descendants(root, &sys);
+ let mut order = worker_descendants_in(&sys, root);
order.reverse();
order.push(root);
for pid in order {
@@ -194,6 +215,15 @@ pub(crate) fn kill_tree(root: u32) {
}
}
+/// How long the Windows sweep keeps looking for a worker that appeared while
+/// it was running, and how often it looks. A shell that is cancelled during
+/// its own startup is the case this exists for, so the window only has to
+/// cover a `CreateProcess` that was already under way.
+#[cfg(windows)]
+const TREE_KILL_SETTLE: Duration = Duration::from_millis(1500);
+#[cfg(windows)]
+const TREE_KILL_POLL: Duration = Duration::from_millis(50);
+
#[cfg(windows)]
pub(crate) fn kill_tree(root: u32) {
if root == 0 { return; }
@@ -201,6 +231,42 @@ pub(crate) fn kill_tree(root: u32) {
// During shell startup a new child can appear between those calls and
// retain the output pipe after its parent dies. Ask Windows to end the
// owned tree in one operation, not a stale list of individual processes.
+ taskkill_tree(root);
+ // One operation is still ONE enumeration. A shell cancelled while it was
+ // starting up calls CreateProcess for its worker after taskkill has
+ // already walked the tree: the shell dies, the worker lives, it holds the
+ // inherited output pipes, and the task stays "running" until the worker
+ // finishes by itself. Proven on the Windows box (2026-09-19): cancelling
+ // `ping -n 31` 100 ms after the start left the task running for 30.4 s in
+ // two of five rounds, exactly the ping's own lifetime, and for a
+ // `cargo build` that is minutes of work that Stop claimed to have ended.
+ //
+ // So look again. The leftovers are still addressable by their parent:
+ // Windows keeps the parent pid in the process entry after the parent is
+ // gone, and every caller here holds the root's process handle until after
+ // this returns, so the number cannot have been handed to a stranger in
+ // between. taskkill cannot walk a tree from a root that is already dead,
+ // which is why each leftover is felled as a root of its own.
+ let deadline = Instant::now() + TREE_KILL_SETTLE;
+ loop {
+ let leftovers = live_descendants(root);
+ if leftovers.is_empty() {
+ return;
+ }
+ for pid in leftovers {
+ taskkill_tree(pid);
+ }
+ if Instant::now() >= deadline {
+ return;
+ }
+ std::thread::sleep(TREE_KILL_POLL);
+ }
+}
+
+/// End `root` and the tree Windows currently records below it, and wait for
+/// that to have happened.
+#[cfg(windows)]
+fn taskkill_tree(root: u32) {
let mut command = Command::new("taskkill.exe");
command.args(["/PID", &root.to_string(), "/T", "/F"])
.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
@@ -210,6 +276,15 @@ pub(crate) fn kill_tree(root: u32) {
}
}
+/// A fresh snapshot of everything still running below `root`.
+#[cfg(windows)]
+fn live_descendants(root: u32) -> Vec<u32> {
+ use sysinfo::{ProcessesToUpdate, System};
+ let mut sys = System::new();
+ sys.refresh_processes(ProcessesToUpdate::All, true);
+ worker_descendants_in(&sys, root)
+}
+
#[cfg(windows)]
fn finish_tree_kill(killer: &mut std::process::Child) {
// Der Aufrufer toetet danach die Shell als Rueckfall. Kehrt diese Stelle
@@ -270,6 +345,68 @@ mod windows_stop_tests {
assert!(survivors.is_empty(), "shell fallback orphaned children: {survivors:?}");
assert!(drained, "cancelled tree retained an output pipe");
}
+
+ /// The startup race, held still. A shell cancelled while it is still
+ /// starting up calls CreateProcess for its worker after taskkill has
+ /// already walked the tree, and one instant later that worker is a live
+ /// process under a dead parent, holding the output pipes it inherited.
+ /// taskkill cannot walk a tree from a root that no longer exists, so the
+ /// single enumeration the sweep used to rely on left the worker running
+ /// and the cancelled task went on reporting "running" until the worker
+ /// finished by itself: measured on the box as 30.4 s stalls in two of
+ /// five cancels of a `ping -n 31` that Stop had supposedly killed, and
+ /// for the `cargo build` this module exists for, minutes.
+ ///
+ /// Reproduced here without waiting for the race to happen: fell the shell
+ /// alone, with `/F` and no `/T`, which leaves exactly that state behind.
+ #[test]
+ fn a_worker_left_under_a_dead_shell_is_still_felled() {
+ let mut shell = Command::new("powershell.exe");
+ shell.args(["-NoProfile", "-NonInteractive", "-Command", "ping -n 31 127.0.0.1"])
+ .stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
+ crate::process_util::suppress_window(&mut shell);
+ let mut shell = shell.spawn().expect("start test shell");
+ let (_, out_done) = drain(shell.stdout.take().unwrap());
+ let (_, err_done) = drain(shell.stderr.take().unwrap());
+ let ready = Instant::now();
+ let workers = loop {
+ let workers = worker_descendants_of(shell.id());
+ if !workers.is_empty() { break workers; }
+ if ready.elapsed() >= Duration::from_secs(30) {
+ kill_tree(shell.id());
+ let _ = shell.wait();
+ panic!("test shell did not start its child");
+ }
+ std::thread::sleep(Duration::from_millis(20));
+ };
+
+ // The shell only. Nothing walks the tree, so the worker stays.
+ let mut lonely = Command::new("taskkill.exe");
+ lonely.args(["/PID", &shell.id().to_string(), "/F"])
+ .stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
+ crate::process_util::suppress_window(&mut lonely);
+ if let Ok(mut lonely) = lonely.spawn() {
+ let _ = lonely.wait();
+ }
+ // `shell` is deliberately not waited on yet: the open handle keeps the
+ // number reserved, so the parent link the sweep follows still means
+ // this shell and cannot have been handed to a stranger.
+ assert!(
+ workers.iter().all(|pid| is_alive(*pid)),
+ "the worker was gone before the sweep was even asked: {workers:?}"
+ );
+
+ kill_tree(shell.id());
+
+ let _ = shell.wait();
+ settle(&out_done, &err_done, Duration::from_millis(1500));
+ let survivors: Vec<_> = workers.into_iter().filter(|pid| is_alive(*pid)).collect();
+ let drained = out_done.load(Ordering::Acquire) && err_done.load(Ordering::Acquire);
+
+ for pid in &survivors { kill_tree(*pid); }
+ assert!(survivors.is_empty(), "a worker under a dead shell survived the sweep: {survivors:?}");
+ assert!(drained, "the cancelled tree kept an output pipe");
+ }
}
// ── Stop erreicht einen schon gestarteten Befehl ──────────────────────────
diff --git a/src-tauri/src/test_support.rs b/src-tauri/src/test_support.rs
index c6ef80cb..08e4a161 100644
--- a/src-tauri/src/test_support.rs
+++ b/src-tauri/src/test_support.rs
@@ -288,18 +288,14 @@ fn in_process_table(pid: u32) -> bool {
/// its own. A test that grabbed it would end up asserting that Windows' own
/// console host dies, which says nothing about the `pnpm install` underneath.
/// The name matches nothing on Unix, so the filter is inert there.
+///
+/// This IS the production view, not a copy of it: `kill_tree` walks the same
+/// list, so there is one implementation and the tests borrow it.
pub(crate) fn worker_descendants_of(root: u32) -> Vec<u32> {
- use sysinfo::{Pid, ProcessesToUpdate, System};
+ use sysinfo::{ProcessesToUpdate, System};
let mut sys = System::new();
sys.refresh_processes(ProcessesToUpdate::All, true);
- crate::commands::shell::descendants(root, &sys)
- .into_iter()
- .filter(|pid| {
- sys.process(Pid::from_u32(*pid))
- .map(|p| !p.name().to_string_lossy().eq_ignore_ascii_case("conhost.exe"))
- .unwrap_or(false)
- })
- .collect()
+ crate::commands::shell::worker_descendants_in(&sys, root)
}
// ── Tests for the helpers themselves ──────────────────────────────────────