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): Windows-Baumabbau vor dem Shell-Rueckfall beenden

purple10df943ef57a
diff --git a/src-tauri/src/commands/bg_tasks.rs b/src-tauri/src/commands/bg_tasks.rs
index 6a475460..05b5b609 100644
--- a/src-tauri/src/commands/bg_tasks.rs
+++ b/src-tauri/src/commands/bg_tasks.rs
@@ -149,6 +149,20 @@ async fn sweep_isolation() -> tokio::sync::MutexGuard<'static, ()> {
SWEEP_ISOLATION.lock().await
}
+#[cfg(test)]
+async fn finish_test_task(id: &str) {
+ // Eine Abbruchanforderung ist noch kein ausgefuehrter Abbruch.
+ // Endet die Testlaufzeit vorher, verwirft Tokio den Empfaenger und wartet
+ // unter Windows auf dessen blockierende Pipe-Leser bis zum Prozessende.
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
+ loop {
+ let status = shell_task_status_impl(&json!({ "id": id })).await.unwrap();
+ if status["running"] == false { return; }
+ assert!(std::time::Instant::now() < deadline, "test left a background task running");
+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;
+ }
+}
+
/// Start arguments for a task that keeps a CHILD process of its own alive —
/// the shape every teardown test needs, because a task with a deep tree is the
/// reason this module exists (`pnpm install`, `cargo build`).
@@ -435,7 +449,12 @@ pub(crate) async fn shell_task_start_impl(args: &Value) -> CmdResult {
// for the foreground shell tool. The Windows job object does not
// help here either: it fires when LU dies, not on a cancel.
if let Some(pid) = pid {
- crate::commands::shell::kill_tree(pid);
+ // Der Baumabbau wartet auf das Betriebssystem. Dabei muss
+ // der asynchrone Lauf weiter seine Ausgabepipes lesen und
+ // andere Aufgaben bedienen koennen, auf jeder Plattform.
+ let _ = tokio::task::spawn_blocking(move || {
+ crate::commands::shell::kill_tree(pid);
+ }).await;
}
let _ = child.kill().await;
break (None, true);
@@ -744,6 +763,8 @@ mod tests {
let pos1 = ids.iter().position(|s| *s == id1).unwrap();
let pos2 = ids.iter().position(|s| *s == id2).unwrap();
assert!(pos2 < pos1, "newer task should appear first");
+ super::finish_test_task(&id1).await;
+ super::finish_test_task(&id2).await;
}
#[cfg(windows)]
@@ -959,6 +980,7 @@ mod shutdown_sweep_tests {
// Do not leave a minute of ping behind for the rest of the run.
let _ = shell_task_kill_impl(&json!({ "id": id })).await;
+ super::finish_test_task(&id).await;
}
/// The window the reaping fix closes.
@@ -1066,7 +1088,7 @@ mod cwd_default_tests {
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
let st = shell_task_status_impl(&json!({ "id": id })).await.unwrap();
seen = st["output_tail"].as_str().unwrap_or("").to_string();
- if !seen.trim().is_empty() {
+ if !seen.trim().is_empty() && st["running"] == false {
break;
}
}
@@ -1098,6 +1120,7 @@ mod cwd_default_tests {
/// the model started "in the project" ran somewhere else.
#[tokio::test]
async fn a_task_without_an_explicit_cwd_lands_in_the_workspace() {
+ let _isolation = super::sweep_isolation().await;
// `os_paths::test_dir` statt eines handgebauten `temp_dir().join(…)`:
// das Aufräumen hängt am `Drop` und läuft auch dann, wenn das
// `assert!` unten panickt — die letzte Zeile des Tests tat das nicht.
@@ -1120,6 +1143,7 @@ mod cwd_default_tests {
/// An explicit cwd from the caller still wins over the derived default.
#[tokio::test]
async fn an_explicit_cwd_still_wins() {
+ let _isolation = super::sweep_isolation().await;
// Siehe oben: beide Verzeichnisse räumen sich beim Verlassen selbst
// ab, auch über die drei `assert!` hinweg.
let a = crate::os_paths::test_dir("bg-a");
diff --git a/src-tauri/src/commands/shell.rs b/src-tauri/src/commands/shell.rs
index 4fa101fd..daf3b2aa 100644
--- a/src-tauri/src/commands/shell.rs
+++ b/src-tauri/src/commands/shell.rs
@@ -205,28 +205,69 @@ pub(crate) fn kill_tree(root: u32) {
.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
crate::process_util::suppress_window(&mut command);
if let Ok(mut killer) = command.spawn() {
- let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
- loop {
- match killer.try_wait() {
- Ok(Some(_)) => break,
- Ok(None) if std::time::Instant::now() < deadline => {
- std::thread::sleep(std::time::Duration::from_millis(10));
- }
- _ => {
- // Stop WAITING, never stop the teardown. `taskkill /T /F`
- // does not need a minder: it finishes the tree on its own
- // once it is started. Killing the helper here ended the
- // process that was doing the work, so on a slow box the
- // tree survived and its children kept the output pipes
- // open, which is the one thing this function exists to
- // prevent. The deadline stays a bound on how long the
- // CALLER waits for confirmation, nothing more.
- // Never broaden the target
- // to an image name or another process if termination fails.
- break;
- }
+ finish_tree_kill(&mut killer);
+ }
+}
+
+#[cfg(windows)]
+fn finish_tree_kill(killer: &mut std::process::Child) {
+ // Der Aufrufer toetet danach die Shell als Rueckfall. Kehrt diese Stelle
+ // vor taskkill zurueck, verschwindet dessen Wurzel vor der Baumsuche und
+ // das Kind ueberlebt. Den Helfer weiterlaufen zu lassen reicht nicht:
+ // sein Ende muss vor dem Rueckfall liegen. Auf der Box mit einem um
+ // 2,5 Sekunden verzoegerten Helfer samt Gegenprobe nachgewiesen.
+ let _ = killer.wait();
+}
+
+#[cfg(all(test, windows))]
+mod windows_stop_tests {
+ use super::*;
+ use crate::test_support::{is_alive, worker_descendants_of};
+ use std::time::{Duration, Instant};
+
+ #[test]
+ fn a_slow_tree_killer_finishes_before_the_shell_fallback() {
+ 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 children = loop {
+ let children = worker_descendants_of(shell.id());
+ if !children.is_empty() { break children; }
+ 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));
+ };
+ assert!(children.iter().all(|pid| is_alive(*pid)));
+
+ // Ein echter PID-begrenzter taskkill, nur sein Start liegt sicher
+ // hinter der alten Zwei-Sekunden-Frist. Keine globale PATH-Aenderung.
+ let mut killer = Command::new("powershell.exe");
+ killer.args(["-NoProfile", "-NonInteractive", "-Command", &format!(
+ "Start-Sleep -Milliseconds 2500; & $env:SystemRoot\\System32\\taskkill.exe /PID {} /T /F",
+ shell.id(),
+ )]).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
+ crate::process_util::suppress_window(&mut killer);
+ let mut killer = killer.spawn().expect("start delayed tree killer");
+ finish_tree_kill(&mut killer);
+ let _ = shell.kill();
+ let _ = shell.wait();
+ let _ = killer.wait();
+ settle(&out_done, &err_done, Duration::from_millis(500));
+ let survivors: Vec<_> = children.into_iter().filter(|pid| is_alive(*pid)).collect();
+ let drained = out_done.load(Ordering::Acquire) && err_done.load(Ordering::Acquire);
+
+ // Auch die rote Gegenprobe raeumt ausschliesslich ihre Kinder ab.
+ for pid in &survivors { kill_tree(*pid); }
+ assert!(survivors.is_empty(), "shell fallback orphaned children: {survivors:?}");
+ assert!(drained, "cancelled tree retained an output pipe");
}
}