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.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
test(win): 8 weggeschaltete Rust-Tests laufen dort jetzt wirklich
David0c465521b3ad
diff --git a/src-tauri/src/commands/bg_tasks.rs b/src-tauri/src/commands/bg_tasks.rsindex 493fa7cc..933971cf 100644--- a/src-tauri/src/commands/bg_tasks.rs+++ b/src-tauri/src/commands/bg_tasks.rs@@ -131,6 +131,83 @@ fn sweep_isolation() -> std::sync::MutexGuard<'static, ()> {SWEEP_ISOLATION.lock().unwrap_or_else(|e| e.into_inner())}+/// 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`).+///+/// Unix: `sh` running `sleep 30 & echo $! ; wait`, unchanged.+///+/// Windows: no `shell` at all, i.e. the PowerShell this module spawns by+/// default and therefore the shell a real background task actually runs+/// there, with `ping` as the child that outlives the test. Git Bash is+/// deliberately not asked for: `shell_task_start_impl` builds PowerShell's+/// argument form for whatever program it is given on Windows, so a POSIX+/// shell would be handed `-NoProfile -NonInteractive -Command` and would never+/// run the command at all.+#[cfg(test)]+fn a_task_that_starts_a_child() -> Value {+ if cfg!(target_os = "windows") {+ // -n 60 pings once a second, so the child stays for about a minute.+ json!({ "command": "ping -n 60 127.0.0.1" })+ } else {+ json!({ "command": "sleep 30 & echo $! ; wait", "shell": "sh" })+ }+}++/// A one-liner that exits at once, in the dialect of the platform's shell.+#[cfg(test)]+fn a_task_that_finishes_at_once() -> Value {+ if cfg!(target_os = "windows") {+ json!({ "command": "exit 0" })+ } else {+ json!({ "command": "true", "shell": "sh" })+ }+}++/// A one-liner that prints the directory the task is running in.+#[cfg(test)]+fn a_task_that_prints_its_directory(extra: Value) -> Value {+ let mut args = if cfg!(target_os = "windows") {+ json!({ "command": "(Get-Location).Path" })+ } else {+ json!({ "command": "pwd", "shell": "sh" })+ };+ let map = args.as_object_mut().expect("an object");+ for (k, v) in extra.as_object().expect("an object") {+ map.insert(k.clone(), v.clone());+ }+ args+}++/// The pid the registry holds for a task — the only handle the shutdown sweep+/// has on it, and the root of the tree the cancel path kills.+#[cfg(test)]+fn shell_pid_of(id: &str) -> u32 {+ REGISTRY+ .get(id)+ .and_then(|t| t.inner.lock().unwrap().pid)+ .expect("a running task must carry its pid")+}++/// Every process the task's shell has started, once there is at least one.+///+/// Read out of the process table rather than out of the task's own output:+/// PowerShell has no `$!`, and Git Bash's `$!` is an MSYS pid that no Windows+/// API can address. The process table is also the view `kill_tree` walks when+/// it takes the tree down, so the test and the code under test are looking at+/// the same processes.+#[cfg(test)]+async fn wait_for_children_of(shell_pid: u32) -> Vec<u32> {+ for _ in 0..50 {+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ let kids = crate::test_support::worker_descendants_of(shell_pid);+ if !kids.is_empty() {+ return kids;+ }+ }+ panic!("the task's shell ({shell_pid}) never started a child process");+}+fn now_secs() -> u64 {std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)@@ -651,58 +728,40 @@ mod tests {#[cfg(test)]mod cancel_tests {use super::*;-- fn alive(pid: u32) -> bool {- let out = std::process::Command::new("ps")- .args(["-o", "state=", "-p", &pid.to_string()])- .output();- match out {- Ok(o) => {- let st = String::from_utf8_lossy(&o.stdout).trim().to_string();- !st.is_empty() && !st.starts_with('Z')- }- Err(_) => false,- }- }+ use crate::test_support::is_alive as alive;/// A background task is started for the long builds — `pnpm install`,/// `cargo build` — so its process tree is deep by definition. Cancelling/// used to SIGKILL the shell alone and leave the real worker running/// detached, the same defect 743c310 fixed for the foreground shell tool.+ ///+ /// Runs on Windows too: the cancel path is `kill_tree` on every platform+ /// (the Job Object does NOT help here, it fires when LU dies, not on a+ /// cancel), so this is live production behaviour there and not a Unix+ /// mechanism in disguise.#[tokio::test]- #[cfg_attr(target_os = "windows", ignore = "uses sh/ps")]async fn cancelling_takes_the_grandchild_with_it() {let _isolation = super::sweep_isolation();- // The shell prints its grandchild's pid, then waits on it.- let start = shell_task_start_impl(&json!({- "command": "sleep 30 & echo $! ; wait",- "shell": "sh",- }))- .await- .expect("start");+ let start = shell_task_start_impl(&super::a_task_that_starts_a_child())+ .await+ .expect("start");let id = start["id"].as_str().expect("id").to_string();- // Wait for the pid line to land in the tail buffer.- let mut grandchild = None;- for _ in 0..50 {- tokio::time::sleep(std::time::Duration::from_millis(100)).await;- let st = shell_task_status_impl(&json!({ "id": id })).await.expect("status");- let tail = st["output_tail"].as_str().unwrap_or("");- if let Some(line) = tail.lines().find(|l| l.trim().parse::<u32>().is_ok()) {- grandchild = line.trim().parse::<u32>().ok();- break;- }+ let shell_pid = super::shell_pid_of(&id);+ let grandchildren = super::wait_for_children_of(shell_pid).await;+ for pid in &grandchildren {+ assert!(alive(*pid), "grandchild {pid} was not running to begin with");}- let grandchild = grandchild.expect("grandchild never reported its pid");- assert!(alive(grandchild), "grandchild was not running to begin with");shell_task_kill_impl(&json!({ "id": id })).await.expect("kill");tokio::time::sleep(std::time::Duration::from_millis(700)).await;- assert!(- !alive(grandchild),- "cancel killed the shell but left the grandchild ({grandchild}) running",- );+ for pid in &grandchildren {+ assert!(+ !alive(*pid),+ "cancel killed the shell but left the grandchild ({pid}) running",+ );+ }}}@@ -713,74 +772,146 @@ mod cancel_tests {#[cfg(test)]mod shutdown_sweep_tests {use super::*;+ use crate::test_support::is_alive as alive;- fn alive(pid: u32) -> bool {- let out = std::process::Command::new("ps")- .args(["-o", "state=", "-p", &pid.to_string()])- .output();- match out {- Ok(o) => {- let st = String::from_utf8_lossy(&o.stdout).trim().to_string();- !st.is_empty() && !st.starts_with('Z')- }- Err(_) => false,- }- }-+ /// Unix only, and not because of the commands it runs: `kill_all_background_tasks`+ /// IS the quit mechanism here — `arm_exit_sweep` hangs it on `atexit` — while on+ /// Windows nothing in production ever calls it. There the same assurance is+ /// delivered by the Job Object, and it has its own test right below.#[tokio::test]- #[cfg_attr(target_os = "windows", ignore = "uses sh/ps; Windows has the Job Object")]+ #[cfg(unix)]async fn quitting_takes_a_running_task_and_its_children_with_it() {let _isolation = super::sweep_isolation();- let start = shell_task_start_impl(&json!({- "command": "sleep 30 & echo $! ; wait",- "shell": "sh",- }))- .await- .expect("start");+ let start = shell_task_start_impl(&super::a_task_that_starts_a_child())+ .await+ .expect("start");let id = start["id"].as_str().expect("id").to_string();- let mut grandchild = None;- for _ in 0..50 {- tokio::time::sleep(std::time::Duration::from_millis(100)).await;- let st = shell_task_status_impl(&json!({ "id": id })).await.expect("status");- let tail = st["output_tail"].as_str().unwrap_or("");- if let Some(line) = tail.lines().find(|l| l.trim().parse::<u32>().is_ok()) {- grandchild = line.trim().parse::<u32>().ok();- break;- }+ let shell_pid = super::shell_pid_of(&id);+ let grandchildren = super::wait_for_children_of(shell_pid).await;+ let whole_tree: Vec<u32> = std::iter::once(shell_pid)+ .chain(grandchildren.iter().copied())+ .collect();+ for pid in &whole_tree {+ assert!(alive(*pid), "test setup is wrong: {pid} is not running");}- let grandchild = grandchild.expect("grandchild never reported its pid");- let shell_pid = REGISTRY- .get(&id)- .and_then(|t| t.inner.lock().unwrap().pid)- .expect("a running task must carry its pid");- assert!(alive(shell_pid) && alive(grandchild), "test setup is wrong");kill_all_background_tasks();let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);- while alive(shell_pid) || alive(grandchild) {+ loop {+ let survivors: Vec<u32> = whole_tree.iter().copied().filter(|p| alive(*p)).collect();+ if survivors.is_empty() {+ break;+ }assert!(std::time::Instant::now() < deadline,- "the quit sweep left {shell_pid}/{grandchild} running",+ "the quit sweep left {survivors:?} running",);tokio::time::sleep(std::time::Duration::from_millis(100)).await;}}- /// Is this number still a process — zombie included?+ /// The Windows counterpart: same assurance — nothing a background task+ /// started survives LU's death — through the mechanism that delivers it+ /// there.///- /// `alive()` above reports a zombie as dead, which is the wrong question- /// here: a zombie has NOT been reaped, so its pid is still reserved. What- /// matters for the sweep is the moment the kernel is free to hand the- /// number out again, and that is the moment `ps` stops listing it at all.- #[cfg(unix)]- fn in_process_table(pid: u32) -> bool {- std::process::Command::new("ps")- .args(["-o", "pid=", "-p", &pid.to_string()])- .output()- .map(|o| !String::from_utf8_lossy(&o.stdout).trim().is_empty())- .unwrap_or(false)+ /// Unix arms an `atexit` sweep. On Windows `arm_exit_sweep` is a no-op and+ /// `kill_all_background_tasks` is never called in production: the shell is+ /// handed to the app-wide Job Object with KILL_ON_JOB_CLOSE at spawn, so+ /// the kernel tears the tree down even for the deaths no handler ever sees+ /// (Task Manager, a hard kill from a build script). Running the Unix test+ /// here would prove something about a code path that does not run on this+ /// platform.+ ///+ /// What cannot be done in-process is watch it happen: that job's handle is+ /// deliberately never closed, and closing it here would disarm the+ /// mechanism for the rest of the test binary — and take every other test's+ /// children with it. What CAN be established is everything the kernel+ /// needs at that moment, and it is exactly what was missing when a+ /// background build outlived the app: the task's shell AND the process it+ /// started are both inside that one job, and that job carries+ /// KILL_ON_JOB_CLOSE. A process created by a process in a job belongs to+ /// the same job, which is why the second half is a real question and not a+ /// tautology — a breakaway flag on the job would end that inheritance.+ #[tokio::test]+ #[cfg(windows)]+ async fn quitting_takes_a_running_task_and_its_children_with_it_via_the_job_object() {+ use windows_sys::Win32::Foundation::CloseHandle;+ use windows_sys::Win32::System::JobObjects::{+ IsProcessInJob, JobObjectExtendedLimitInformation, QueryInformationJobObject,+ JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,+ };+ use windows_sys::Win32::System::Threading::{OpenProcess, PROCESS_QUERY_INFORMATION};++ /// Is this pid inside that job? False when the process cannot even be+ /// opened, which for a pid the test itself just spawned means the+ /// process is gone and the question is moot.+ fn in_job(pid: u32, job: isize) -> bool {+ unsafe {+ let handle = OpenProcess(PROCESS_QUERY_INFORMATION, 0, pid);+ if handle.is_null() {+ return false;+ }+ let mut member: i32 = 0;+ let queried = IsProcessInJob(handle, job as _, &mut member);+ CloseHandle(handle);+ queried != 0 && member != 0+ }+ }++ let _isolation = super::sweep_isolation();+ let start = shell_task_start_impl(&super::a_task_that_starts_a_child())+ .await+ .expect("start");+ let id = start["id"].as_str().expect("id").to_string();++ let shell_pid = super::shell_pid_of(&id);+ let grandchildren = super::wait_for_children_of(shell_pid).await;+ // Membership of a job the kernel will never have to act on proves+ // nothing, so the tree has to be running when it is asked.+ for pid in std::iter::once(shell_pid).chain(grandchildren.iter().copied()) {+ assert!(alive(pid), "test setup is wrong: {pid} is not running");+ }++ let job = crate::commands::process::kill_on_close_job_for_tests();+ assert!(job != 0, "the app-wide kill-on-close job was never created");++ // The limit flag is the entire mechanism. Without it the job is a+ // bookkeeping device and every child outlives the app.+ let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { std::mem::zeroed() };+ let mut returned: u32 = 0;+ let queried = unsafe {+ QueryInformationJobObject(+ job as _,+ JobObjectExtendedLimitInformation,+ &mut info as *mut _ as *mut _,+ std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,+ &mut returned,+ )+ };+ assert!(queried != 0, "the app-wide job object could not be queried");+ assert!(+ info.BasicLimitInformation.LimitFlags & JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE != 0,+ "the job does not kill its processes when the app's handle closes, \+ so quitting would leave every background task running",+ );++ assert!(+ in_job(shell_pid, job),+ "the task's shell ({shell_pid}) is not in the kill-on-close job, \+ so LU dying would leave the whole background task behind",+ );+ for pid in &grandchildren {+ assert!(+ in_job(*pid, job),+ "the task's shell is in the job but the process it started \+ ({pid}) is not, so the actual worker would survive LU",+ );+ }++ // Do not leave a minute of ping behind for the rest of the run.+ let _ = shell_task_kill_impl(&json!({ "id": id })).await;}/// The window the reaping fix closes.@@ -791,8 +922,15 @@ mod shutdown_sweep_tests {/// as it lives. So: shell exits immediately, grandchild holds the pipe, and/// for the next three seconds the registry kept handing the sweep a number/// that belonged to whatever the kernel gave it to next.+ ///+ /// Unix only, and there is nothing to port: the race it guards is the+ /// reap. Windows recycles a pid only once the LAST handle to the process+ /// object is closed, and `tokio::process::Child` holds one until it is+ /// dropped — which happens after this loop, not inside it — so the number+ /// cannot be handed to a stranger while the registry still names it. The+ /// registry hygiene itself (a finished task carries no pid) is asserted on+ /// both platforms by `a_finished_task_is_not_swept` below.#[tokio::test]- #[cfg_attr(target_os = "windows", ignore = "uses sh/ps")]#[cfg(unix)]async fn a_reaped_pid_is_gone_from_the_registry_the_instant_it_is_freed() {let _isolation = super::sweep_isolation();@@ -814,9 +952,11 @@ mod shutdown_sweep_tests {.pid.expect("a running task must carry its pid");- // Wait for the kernel to release the number — i.e. for the reap.+ // Wait for the kernel to release the number — i.e. for the reap. A+ // zombie still holds it, so this asks whether `ps` lists the pid at+ // all, not whether it is alive.let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);- while in_process_table(shell_pid) {+ while crate::test_support::pid_is_taken(shell_pid) {assert!(std::time::Instant::now() < deadline,"the shell ({shell_pid}) never exited, so there is nothing to prove",@@ -843,10 +983,9 @@ mod shutdown_sweep_tests {/// A finished task's pid may already belong to somebody else — the sweep/// must never fire at it. Sweeping an idle registry must also not panic.#[tokio::test]- #[cfg_attr(target_os = "windows", ignore = "uses sh")]async fn a_finished_task_is_not_swept() {let _isolation = super::sweep_isolation();- let start = shell_task_start_impl(&json!({ "command": "true", "shell": "sh" }))+ let start = shell_task_start_impl(&super::a_task_that_finishes_at_once()).await.expect("start");let id = start["id"].as_str().unwrap().to_string();@@ -869,75 +1008,88 @@ mod shutdown_sweep_tests {mod cwd_default_tests {use super::*;+ /// What the task printed as its own directory, once it has printed+ /// anything. Five seconds, because a cold PowerShell start on Windows is+ /// not instant.+ async fn reported_directory(id: &str) -> String {+ let mut seen = String::new();+ for _ in 0..100 {+ 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() {+ break;+ }+ }+ seen.trim().to_string()+ }++ /// Did the task run in `expected`?+ ///+ /// Both sides go through `canonicalize`, because the two spellings of one+ /// directory differ per platform and neither side is wrong: macOS hands+ /// out `/var/...` which is a symlink to `/private/var` and `pwd` reports+ /// the resolved path, while on Windows the shell prints a plain `C:\...`+ /// and `canonicalize` yields the `\\?\C:\...` verbatim form. Resolving+ /// both is still an exact directory identity — the assertion is not+ /// loosened, it is asked in a form both kernels can answer.+ fn same_directory(reported: &str, expected: &std::path::Path) -> bool {+ match (+ std::fs::canonicalize(reported),+ std::fs::canonicalize(expected),+ ) {+ (Ok(a), Ok(b)) => a == b,+ _ => false,+ }+ }+/// The tool exists for `pnpm install` / `cargo build`, so the folder it/// runs in IS the point. Without an explicit cwd the child used to inherit/// LU's own process directory — the install folder on Windows — so a task/// the model started "in the project" ran somewhere else.#[tokio::test]- #[cfg_attr(target_os = "windows", ignore = "uses sh/pwd")]async fn a_task_without_an_explicit_cwd_lands_in_the_workspace() {let ws = std::env::temp_dir().join(format!("lu-bg-ws-{}", std::process::id()));std::fs::create_dir_all(&ws).unwrap();- // macOS hands out /var/... which is a symlink to /private/var; pwd- // reports the resolved path, so compare against that.- let expected = std::fs::canonicalize(&ws).unwrap();- let start = shell_task_start_impl(&json!({- "command": "pwd",- "shell": "sh",+ let start = shell_task_start_impl(&super::a_task_that_prints_its_directory(json!({"working_directory": ws.to_string_lossy(),- }))+ }))).await.expect("start");let id = start["id"].as_str().unwrap().to_string();- let mut seen = String::new();- for _ in 0..40 {- 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() {- break;- }- }- assert_eq!(- seen.trim(),- expected.to_string_lossy(),- "background task did not start in the workspace",+ let seen = reported_directory(&id).await;+ assert!(+ same_directory(&seen, &ws),+ "background task did not start in the workspace: reported {seen:?}, wanted {ws:?}",);let _ = std::fs::remove_dir_all(&ws);}/// An explicit cwd from the caller still wins over the derived default.#[tokio::test]- #[cfg_attr(target_os = "windows", ignore = "uses sh/pwd")]async fn an_explicit_cwd_still_wins() {let a = std::env::temp_dir().join(format!("lu-bg-a-{}", std::process::id()));let b = std::env::temp_dir().join(format!("lu-bg-b-{}", std::process::id()));std::fs::create_dir_all(&a).unwrap();std::fs::create_dir_all(&b).unwrap();- let expected = std::fs::canonicalize(&b).unwrap();- let start = shell_task_start_impl(&json!({- "command": "pwd",- "shell": "sh",+ let start = shell_task_start_impl(&super::a_task_that_prints_its_directory(json!({"cwd": b.to_string_lossy(),"working_directory": a.to_string_lossy(),- }))+ }))).await.expect("start");let id = start["id"].as_str().unwrap().to_string();- let mut seen = String::new();- for _ in 0..40 {- 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() {- break;- }- }- assert_eq!(seen.trim(), expected.to_string_lossy());+ let seen = reported_directory(&id).await;+ assert!(+ same_directory(&seen, &b),+ "the explicit cwd lost: reported {seen:?}, wanted {b:?}",+ );+ // Negative control: the folder that must NOT have won.+ assert!(!same_directory(&seen, &a), "the task ran in the fallback {a:?}");let _ = std::fs::remove_dir_all(&a);let _ = std::fs::remove_dir_all(&b);}diff --git a/src-tauri/src/commands/engine.rs b/src-tauri/src/commands/engine.rsindex 39b7c9c0..4246069d 100644--- a/src-tauri/src/commands/engine.rs+++ b/src-tauri/src/commands/engine.rs@@ -2042,15 +2042,18 @@ mod tests {}#[test]- #[cfg_attr(target_os = "windows", ignore = "uses sh")]fn a_child_that_dies_on_start_is_reported_at_once_and_not_after_the_budget() {// GH #118: the health wait watched only the port, so an engine that// exited in the first second (a missing runtime library, a GPU backend// that will not initialise) still burned the whole budget before the// user was told anything. The budget here is 30s; the answer has to// arrive in a fraction of that.+ //+ // The shell is resolved, not spelled `sh`: on Windows that name is not+ // on PATH at all and a bare `bash` is the WSL alias stub. See+ // `test_support::posix_shell`.let state = AppState::new();- let child = std::process::Command::new("sh")+ let child = std::process::Command::new(crate::test_support::posix_shell()).args(["-c", "exit 3"]).stdin(Stdio::null()).stdout(Stdio::null())@@ -2079,14 +2082,12 @@ mod tests {}#[test]- #[cfg_attr(target_os = "windows", ignore = "uses sleep")]fn a_child_that_is_still_loading_is_left_alone_until_the_budget_ends() {// Negative control for the check above: a LIVE child must still get// its full budget, or a big GGUF on a cold disk would be declared dead// while it is only slow (ENG-4).let state = AppState::new();- let child = std::process::Command::new("sleep")- .arg("30")+ let child = crate::test_support::sleeper(30).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null())diff --git a/src-tauri/src/commands/process.rs b/src-tauri/src/commands/process.rsindex bcf91c09..02b2a91f 100644--- a/src-tauri/src/commands/process.rs+++ b/src-tauri/src/commands/process.rs@@ -76,6 +76,16 @@ fn kill_on_close_job() -> isize {})}+/// The app-wide job handle, for the Windows tests that have to prove a child+/// really joined it — `bg_tasks.rs` asserts that a background task's shell AND+/// the process it starts are both inside this job, which is what makes LU's+/// death take them along. Test-only: production never needs the raw handle, it+/// only ever adds pids to it.+#[cfg(all(target_os = "windows", test))]+pub(crate) fn kill_on_close_job_for_tests() -> isize {+ kill_on_close_job()+}+/// PID-based variant of [`assign_to_kill_on_close_job`]. Usable from spawn paths/// that don't own a `std::process::Child`, notably `tokio::process::Child`/// (whose `id()` is `Option<u32>`) in the background-task runner (bg_tasks.rs).diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 227381e5..67c3af78 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -11,6 +11,11 @@ mod private_tmp;mod process_util;mod python;mod state;+// Test-only OS helpers (a shell, a sleeper, "is this pid alive"), shared by+// the process tests in state.rs, commands/engine.rs and commands/bg_tasks.rs+// so the Windows answers exist once instead of eight times.+#[cfg(test)]+mod test_support;use state::AppState;use tauri::{diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rsindex 49709b7a..5173f428 100644--- a/src-tauri/src/state.rs+++ b/src-tauri/src/state.rs@@ -595,10 +595,15 @@ impl Drop for AppState {mod shutdown_tests {use super::*;+ // `sleep 30` on Unix, `ping` on Windows, and "is this pid a live process"+ // in the terms of whichever kernel is answering — see `test_support`. The+ // Unix behaviour is unchanged; before, both were spelled out here in Unix+ // terms only, which is what switched this test off on Windows.+ use crate::test_support::{is_alive as alive, sleeper as sleeper_cmd};+/// A live child that outlives the test unless something kills it.fn sleeper() -> std::process::Child {- std::process::Command::new("sleep")- .arg("30")+ sleeper_cmd(30).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null())@@ -606,28 +611,11 @@ mod shutdown_tests {.expect("spawn sleeper")}- /// A killed-but-unreaped child is a ZOMBIE — `ps -p` still lists it, so the- /// process STATE has to be read. Z means the kill landed and only the exit- /// status is still pending; at quit the parent dies and init reaps it.- fn alive(pid: u32) -> bool {- let out = std::process::Command::new("ps")- .args(["-o", "state=", "-p", &pid.to_string()])- .output();- match out {- Ok(o) => {- let st = String::from_utf8_lossy(&o.stdout).trim().to_string();- !st.is_empty() && !st.starts_with('Z')- }- Err(_) => false,- }- }-/// The quit path is normally only reachable through the Tauri exit (tray/// Quit / exit_app), which cannot be triggered from a test or from a shell./// It is a plain method though, so it CAN be exercised with real children —/// which is the only runtime proof available for it on this machine.#[test]- #[cfg_attr(target_os = "windows", ignore = "uses sleep/ps")]fn shutdown_kills_the_tracked_children_and_empties_the_slots() {let state = AppState::new();@@ -645,6 +633,19 @@ mod shutdown_tests {std::mem::forget(trainer); // only the pid is tracked, as in the real flow*state.trainer_process.lock().unwrap() = Some(trainer_pid);+ // The three assertions below only mean something if all three children+ // were actually running when the shutdown fired. A sleeper that had+ // died on its own — or a pid that never belonged to the process the+ // test thinks it does — would make every one of them pass while+ // nothing was killed at all.+ for (what, pid) in [+ ("ollama", ollama_pid),+ ("comfyui", comfy_pid),+ ("trainer", trainer_pid),+ ] {+ assert!(alive(pid), "the {what} child was not running to begin with");+ }+state.shutdown_subprocesses();std::thread::sleep(std::time::Duration::from_millis(400));diff --git a/src-tauri/src/test_support.rs b/src-tauri/src/test_support.rsnew file mode 100644index 00000000..accddff4--- /dev/null+++ b/src-tauri/src/test_support.rs@@ -0,0 +1,464 @@+//! Test-only OS helpers — one place where "and how does that work on Windows"+//! is answered for the whole crate.+//!+//! Nothing here ships: the module is `#[cfg(test)]` in `main.rs`.+//!+//! It exists because the process-level tests — `state.rs` (the quit path),+//! `commands/engine.rs` (the health wait) and `commands/bg_tasks.rs`+//! (cancel, quit sweep, working directory) — all need the same four things+//! from the OS: a shell that runs a POSIX one-liner, a child that stays alive+//! while the test works, an answer to "is this pid still a process", and the+//! children a process started. Each of them used to spell those out in Unix+//! terms only (`sh`, `sleep`, `ps -o state=`), which is why eight of them were+//! switched off on Windows — that is, on the platform whose process handling+//! differs the most from the one they were written on, and where being+//! untested is worth the least.+//!+//! Everything below is compiled on every platform (`if cfg!(windows)`, not+//! `#[cfg(windows)]`), so the Windows half at least type-checks in a macOS+//! `cargo test` run and the pure parts of the resolver are unit-tested at the+//! bottom of this file.++use std::path::{Path, PathBuf};+use std::process::Command;+use std::sync::OnceLock;++const BASH_EXE: &str = "bash.exe";++// ── The shell ─────────────────────────────────────────────────────────────++/// A shell that can run the POSIX one-liners these tests are written in.+///+/// Unix: `sh`, exactly as before.+///+/// Windows: the bash that Git for Windows installs. A bare `bash` is NOT+/// usable there, and that is the whole reason this function exists: on a+/// stock Windows 10/11 the PATH resolves `bash` to+/// `%LOCALAPPDATA%\Microsoft\WindowsApps\bash.exe` — the WSL+/// app-execution-alias stub, a zero-length reparse point. `where bash` prints+/// it and every existence check says yes to it, but with no WSL distro+/// registered CreateProcess refuses it outright, so the spawn dies before a+/// shell is ever reached. Git for Windows always installs a real bash next to+/// git, so that one is resolved deterministically and every WindowsApps+/// candidate is dropped on the floor *before* it is even checked for+/// existence.+///+/// This is the Rust twin of `src/api/__tests__/bash-interpreter.ts`, which+/// solved the same problem for the vitest side; same sources, same order.+pub(crate) fn posix_shell() -> String {+ static RESOLVED: OnceLock<String> = OnceLock::new();+ RESOLVED+ .get_or_init(|| {+ if !cfg!(windows) {+ return "sh".to_string();+ }+ let candidates = windows_bash_candidates();+ match candidates.iter().find(|c| is_usable_bash(c)) {+ Some(found) => found.clone(),+ None => panic!("{}", no_bash_message(&candidates)),+ }+ })+ .clone()+}++/// `...\WindowsApps\bash.exe` is the WSL alias stub — never an actual shell.+fn is_wsl_alias_stub(candidate: &str) -> bool {+ let lower = candidate.to_ascii_lowercase().replace('/', "\\");+ lower.contains("\\windowsapps\\")+}++/// The stub filter runs BEFORE the existence check, on purpose: the stub is a+/// file as far as the file system is concerned, so checking first would let it+/// win.+fn is_usable_bash(candidate: &str) -> bool {+ !is_wsl_alias_stub(candidate) && Path::new(candidate).is_file()+}++/// `where <program>` on Windows: one absolute path per line, and no lines at+/// all when the program is not on PATH. Off Windows there is no `where`+/// executable, the spawn fails, and the caller gets an empty list — which is+/// correct, because nothing off Windows asks.+fn where_on_path(program: &str) -> Vec<String> {+ let out = match Command::new("where").arg(program).output() {+ Ok(o) if o.status.success() => o.stdout,+ _ => return Vec::new(),+ };+ String::from_utf8_lossy(&out)+ .lines()+ .map(|l| l.trim().to_string())+ .filter(|l| !l.is_empty())+ .collect()+}++/// The documented install roots, for a git that is not on PATH at all.+fn program_roots() -> Vec<PathBuf> {+ let mut roots = Vec::new();+ for var in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {+ if let Some(v) = std::env::var_os(var) {+ roots.push(PathBuf::from(v));+ }+ }+ if let Some(local) = std::env::var_os("LOCALAPPDATA") {+ roots.push(PathBuf::from(local).join("Programs"));+ }+ roots+}++fn windows_bash_candidates() -> Vec<String> {+ build_candidates(+ &where_on_path("git"),+ &program_roots(),+ &where_on_path("bash"),+ )+}++/// Every place a real bash could be, most trustworthy first. Nothing in here+/// is machine specific: git's own location is the primary source, the install+/// roots are the fallback, and PATH comes last — after the stub filter, so a+/// WSL alias can never win just because it happens to be first on PATH.+///+/// Split out from its inputs so the ordering can be tested without a Windows+/// machine (see the tests at the bottom of this file).+fn build_candidates(git_exes: &[String], roots: &[PathBuf], bash_on_path: &[String]) -> Vec<String> {+ let mut out: Vec<String> = Vec::new();+ let add = |p: PathBuf, out: &mut Vec<String>| {+ let s = p.to_string_lossy().to_string();+ if !out.iter().any(|e| e.eq_ignore_ascii_case(&s)) {+ out.push(s);+ }+ };++ // 1. Derive it from git. Git for Windows ships bash in the same install,+ // so `where git` -> ...\Git\cmd\git.exe pins down ...\Git\bin\bash.exe.+ // Walk up a few levels instead of assuming `cmd\`, because git.exe also+ // lives under mingw64\bin in some layouts.+ for git_exe in git_exes {+ let mut dir = PathBuf::from(git_exe);+ dir.pop(); // the directory holding git.exe+ for _ in 0..3 {+ if !dir.pop() {+ break;+ }+ add(dir.join("bin").join(BASH_EXE), &mut out);+ add(dir.join("usr").join("bin").join(BASH_EXE), &mut out);+ }+ }++ // 2. The install roots, for a git that is not on PATH at all.+ for root in roots {+ add(root.join("Git").join("bin").join(BASH_EXE), &mut out);+ add(+ root.join("Git").join("usr").join("bin").join(BASH_EXE),+ &mut out,+ );+ }++ // 3. Whatever PATH itself offers, last.+ for on_path in bash_on_path {+ add(PathBuf::from(on_path), &mut out);+ }++ out+}++/// The death message. It names every candidate that was looked at, marks the+/// ones that were skipped as stubs, and says how to get a real bash — a bare+/// "no bash found" on somebody else's machine is unactionable.+fn no_bash_message(candidates: &[String]) -> String {+ let mut msg = String::from(+ "no usable bash found on Windows. The `bash` on PATH is the WSL \+ app-execution-alias stub under WindowsApps, which cannot run without a \+ registered WSL distro, so it is deliberately ignored. Install Git for \+ Windows (https://git-scm.com/download/win, or `winget install --id \+ Git.Git`), which ships Git Bash. Checked:",+ );+ if candidates.is_empty() {+ msg.push_str("\n (nothing — neither git nor bash is on PATH)");+ }+ for c in candidates {+ msg.push_str("\n ");+ msg.push_str(c);+ if is_wsl_alias_stub(c) {+ msg.push_str(" (WSL stub, skipped)");+ }+ }+ msg+}++// ── A child that stays alive ──────────────────────────────────────────────++/// A child that runs for `secs` seconds and whose pid stays THIS process for+/// all of them.+///+/// Unix: `sleep`, as before. Windows: `ping`, the Windows sleep — a native+/// single process, always present in System32.+///+/// Deliberately NOT `bash -c "sleep 30"` on Windows: bash exec-optimises a+/// `-c` that holds a single command, and the MSYS runtime emulates `exec` by+/// starting a NEW Windows process while the original `bash.exe` exits. The pid+/// the test had just tracked would be gone within milliseconds and every+/// "the shutdown killed it" assertion would pass without proving anything.+pub(crate) fn sleeper(secs: u32) -> Command {+ if cfg!(windows) {+ // -n counts the pings; the first goes out at once and the rest are a+ // second apart, so n = secs + 1 lasts about `secs`.+ let mut cmd = Command::new("ping");+ cmd.args(["-n", &(secs + 1).to_string(), "127.0.0.1"]);+ cmd+ } else {+ let mut cmd = Command::new("sleep");+ cmd.arg(secs.to_string());+ cmd+ }+}++// ── Is this pid still a process ───────────────────────────────────────────++/// Is this pid a live process?+///+/// A killed-but-unreaped child is NOT alive: on Unix `ps -p` still lists a+/// zombie, so the process STATE has to be read — `Z` means the kill landed and+/// only the exit status is still pending; at quit the parent dies and init+/// reaps it. Windows has no zombies at all (a terminated process leaves the+/// table at once, even while a handle keeps its number reserved), so there the+/// question is simply whether the process table still lists it — read through+/// `sysinfo`, the same view the production `kill_tree` walks.+pub(crate) fn is_alive(pid: u32) -> bool {+ if cfg!(windows) {+ in_process_table(pid)+ } else {+ let state = unix_ps_field(pid, "state=");+ !state.is_empty() && !state.starts_with('Z')+ }+}++/// Is this number still taken — zombie included?+///+/// [`is_alive`] reports a zombie as dead, which is the wrong question when+/// what matters is the moment the kernel may hand the number out again: a+/// zombie has not been reaped, so its pid is still reserved, and `ps` keeps+/// listing it until it is. On Windows the number is held by the open process+/// handle rather than by an unreaped entry, and the process table is the only+/// thing that can be observed from outside.+pub(crate) fn pid_is_taken(pid: u32) -> bool {+ if cfg!(windows) {+ in_process_table(pid)+ } else {+ !unix_ps_field(pid, "pid=").is_empty()+ }+}++fn unix_ps_field(pid: u32, field: &str) -> String {+ Command::new("ps")+ .args(["-o", field, "-p", &pid.to_string()])+ .output()+ .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())+ .unwrap_or_default()+}++fn in_process_table(pid: u32) -> bool {+ use sysinfo::{Pid, ProcessesToUpdate, System};+ let mut sys = System::new();+ // A full refresh, not `Some(&[pid])`: on Windows a terminated process can+ // still be opened by pid while somebody holds a handle to it, and the+ // per-pid refresh goes through exactly that door. The full snapshot lists+ // what is actually running.+ sys.refresh_processes(ProcessesToUpdate::All, true);+ sys.process(Pid::from_u32(pid)).is_some()+}++/// Everything below `root` in the real parent/child links that is actually+/// doing work.+///+/// The same view the production `kill_tree` walks, which is what makes it the+/// right way to find the child a shell started when the shell cannot report it+/// itself: PowerShell has no `$!`, and Git Bash's `$!` is an MSYS pid that no+/// Windows API can address.+///+/// `conhost.exe` is filtered out because Windows attaches one to every process+/// that gets a console — CREATE_NO_WINDOW still creates one — and it appears+/// as a child of the shell, usually before the shell has started anything of+/// 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.+pub(crate) fn worker_descendants_of(root: u32) -> Vec<u32> {+ use sysinfo::{Pid, 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()+}++// ── Tests for the helpers themselves ──────────────────────────────────────++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_wsl_alias_stub_is_recognised_in_both_slash_flavours() {+ for stub in [+ r"C:\Users\x\AppData\Local\Microsoft\WindowsApps\bash.exe",+ r"c:\users\x\appdata\local\microsoft\windowsapps\bash.exe",+ "C:/Users/x/AppData/Local/Microsoft/WindowsApps/bash.exe",+ ] {+ assert!(is_wsl_alias_stub(stub), "{stub} is the WSL stub");+ }+ for real in [+ r"C:\Program Files\Git\bin\bash.exe",+ r"C:\Program Files\Git\usr\bin\bash.exe",+ "/bin/sh",+ ] {+ assert!(!is_wsl_alias_stub(real), "{real} is a real shell");+ }+ // The word has to be a path SEGMENT. A folder that merely starts with+ // it is somebody's own install, not the alias directory.+ assert!(!is_wsl_alias_stub(r"C:\WindowsAppsBackup\bin\bash.exe"));+ }++ /// Unix-shaped paths on purpose: the ORDER and the derivation are what is+ /// being tested, and `Path::join` is the only separator-aware part.+ #[test]+ fn git_comes_first_the_install_roots_next_and_path_last() {+ let candidates = build_candidates(+ &["/opt/Git/cmd/git.exe".to_string()],+ &[PathBuf::from("/Program Files")],+ &["/WindowsApps/bash.exe".to_string()],+ );++ // Derived from git: one level up from cmd\ is the install root.+ assert_eq!(candidates[0], "/opt/Git/bin/bash.exe");+ assert_eq!(candidates[1], "/opt/Git/usr/bin/bash.exe");+ // ...and it keeps walking up, because git.exe is not always in cmd\.+ assert!(candidates.contains(&"/opt/bin/bash.exe".to_string()));+ // The install roots come after everything git could tell us.+ let root_pos = candidates+ .iter()+ .position(|c| c == "/Program Files/Git/bin/bash.exe")+ .expect("the install root is a candidate");+ assert!(root_pos > 1, "the roots must not outrank git's own location");+ // PATH is last, so a WSL stub can never win a race it only leads+ // because it happens to come first on PATH.+ assert_eq!(candidates.last().unwrap(), "/WindowsApps/bash.exe");+ assert!(is_wsl_alias_stub(candidates.last().unwrap()));+ }++ #[test]+ fn a_candidate_is_never_listed_twice() {+ let candidates = build_candidates(+ &["/opt/Git/cmd/git.exe".to_string(), "/opt/Git/cmd/git.exe".to_string()],+ &[PathBuf::from("/opt")],+ &["/opt/Git/bin/bash.exe".to_string()],+ );+ let mut seen = candidates.clone();+ seen.sort();+ seen.dedup();+ assert_eq!(seen.len(), candidates.len(), "duplicate candidates: {candidates:?}");+ }++ #[test]+ fn the_failure_message_names_every_candidate_and_marks_the_stubs() {+ let msg = no_bash_message(&[+ r"C:\Program Files\Git\bin\bash.exe".to_string(),+ r"C:\Users\x\AppData\Local\Microsoft\WindowsApps\bash.exe".to_string(),+ ]);+ assert!(msg.contains(r"C:\Program Files\Git\bin\bash.exe"), "{msg}");+ assert!(msg.contains("WSL stub, skipped"), "{msg}");+ assert!(msg.contains("git-scm.com/download/win"), "{msg}");+ // The empty case must still say something an operator can act on.+ assert!(no_bash_message(&[]).contains("neither git nor bash is on PATH"));+ }++ /// The stub filter must run before the existence check, or a stub that+ /// really is on disk would be handed to CreateProcess.+ #[test]+ fn a_windowsapps_path_is_refused_even_when_the_file_exists() {+ let dir = std::env::temp_dir().join(format!("lu-wsl-stub-{}", std::process::id()));+ let apps = dir.join("WindowsApps");+ std::fs::create_dir_all(&apps).unwrap();+ let stub = apps.join(BASH_EXE);+ std::fs::write(&stub, b"").unwrap();+ let stub = stub.to_string_lossy().to_string();++ assert!(Path::new(&stub).is_file(), "the stub is a file on disk");+ assert!(!is_usable_bash(&stub), "and it must still be refused");++ std::fs::remove_dir_all(&dir).ok();+ }++ /// `sleeper` has one job: a child that is still there a moment later, with+ /// the pid the caller was handed.+ #[test]+ fn the_sleeper_is_alive_under_its_own_pid_and_dies_when_killed() {+ let mut child = sleeper(30)+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .spawn()+ .expect("spawn a sleeper");+ let pid = child.id();+ std::thread::sleep(std::time::Duration::from_millis(300));+ assert!(is_alive(pid), "the sleeper must outlive the test's first look");+ assert!(pid_is_taken(pid));++ let _ = child.kill();+ let _ = child.wait(); // reaped, so not even a zombie is left+ assert!(!is_alive(pid), "a killed and reaped sleeper is not alive");+ }++ /// The descendant lookup is how the bg-task tests find the process a task+ /// started, so it has to actually find one — under the pid of whoever+ /// started it.+ #[test]+ fn descendants_finds_a_child_of_this_process() {+ let mut child = sleeper(20)+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .spawn()+ .expect("spawn a sleeper");+ let pid = child.id();++ let mut found = false;+ for _ in 0..20 {+ if worker_descendants_of(std::process::id()).contains(&pid) {+ found = true;+ break;+ }+ std::thread::sleep(std::time::Duration::from_millis(100));+ }+ assert!(found, "the child ({pid}) this test started was not found below it");++ let _ = child.kill();+ let _ = child.wait();+ }++ /// The resolved shell has to be a shell that RUNS.+ ///+ /// On Windows this is the end-to-end check on the whole resolver: the WSL+ /// alias stub the PATH offers passes every existence test and then fails+ /// in CreateProcess, so the only way to tell a real bash from it is to+ /// spawn it. `exit` is a shell builtin on purpose — this must not depend+ /// on which of Git Bash's directories are on PATH.+ #[test]+ fn the_resolved_shell_actually_runs_a_one_liner() {+ let status = Command::new(posix_shell())+ .args(["-c", "exit 7"])+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .status()+ .unwrap_or_else(|e| panic!("could not spawn the resolved shell: {e}"));+ assert_eq!(+ status.code(),+ Some(7),+ "the resolved shell did not run the one-liner it was given",+ );+ }+}