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.

tech(KF-7, KF-16, KF-19): Testflocken ohne Uhr, eine Antwort fuer fs-list, und vier Versprechen weniger

Davidadf70fd25d3d
diff --git a/src-tauri/src/commands/agent.rs b/src-tauri/src/commands/agent.rs
index d942950d..6468b29f 100644
--- a/src-tauri/src/commands/agent.rs
+++ b/src-tauri/src/commands/agent.rs
@@ -672,10 +672,22 @@ pub fn get_chat_workspace_override(
/// one gets created.
#[tauri::command]
pub fn list_agent_workspaces() -> Result<Vec<String>, String> {
- let root = agent_workspace_root();
- let entries = match fs::read_dir(&root) {
+ Ok(directory_names_in(&agent_workspace_root()))
+}
+
+/// The listing rule itself, on a root the caller names.
+///
+/// Split out of `list_agent_workspaces` because its test could not reach it:
+/// `agent_workspace_root()` is `~/<AGENT_WORKSPACE_DIR>` with no seam, so
+/// `lists_only_directory_names_sorted` had COPIED these six lines into the test
+/// module and asserted on the copy. It therefore stayed green for any change to
+/// the real function — sorting removed, files no longer filtered — and only ever
+/// measured that `read_dir` works. One function, called by the command and by
+/// the test, is what makes the test's headline true.
+fn directory_names_in(root: &std::path::Path) -> Vec<String> {
+ let entries = match fs::read_dir(root) {
Ok(e) => e,
- Err(_) => return Ok(Vec::new()),
+ Err(_) => return Vec::new(),
};
let mut names: Vec<String> = entries
.flatten()
@@ -683,7 +695,7 @@ pub fn list_agent_workspaces() -> Result<Vec<String>, String> {
.filter_map(|e| e.file_name().to_str().map(|s| s.to_string()))
.collect();
names.sort();
- Ok(names)
+ names
}
/// Human byte size for tool messages. Mirrors formatBytes in builtin-tools.ts
@@ -702,43 +714,50 @@ fn format_bytes(bytes: u64) -> String {
}
}
+/// ── Why these two no longer share a directory with every other copy ────────
+///
+/// `lists_only_directory_names_sorted` used the FIXED path
+/// `<temp>/lu-test-agent-workspace-listing`, and it began by deleting it. Every
+/// concurrent copy of this test binary used the same one, so one copy's
+/// `remove_dir_all` ran between another's `create_dir_all` and its `read_dir`.
+/// Measured on 01.09.2026 under the apparatus the finding was raised in — the
+/// whole suite run three times over, ten rounds — it failed 5 of 30 runs, always
+/// with a short list (`["alpha-aabbcc"]` instead of both names): a stranger had
+/// swept the directory mid-test.
+///
+/// `crate::os_paths::test_dir` is the house answer and predates this test by
+/// several commits — the name carries the process id and the thread id, and the
+/// `Drop` sweeps up even when an assertion panics. Nothing else changes.
#[cfg(test)]
mod workspace_listing_tests {
+ use super::directory_names_in;
use std::fs;
/// The listing rule the frontend's fallback search depends on: folder
/// names, directories only, sorted, and a plain file is not a workspace.
+ ///
+ /// Asserts on the PRODUCTION function now, not on a copy of its body.
#[test]
fn lists_only_directory_names_sorted() {
- let root = std::env::temp_dir().join("lu-test-agent-workspace-listing");
- let _ = fs::remove_dir_all(&root);
+ let root = crate::os_paths::test_dir("agent-workspace-listing");
fs::create_dir_all(root.join("zeta-5e61db")).unwrap();
fs::create_dir_all(root.join("alpha-aabbcc")).unwrap();
fs::write(root.join("loose.txt"), b"not a workspace").unwrap();
- let entries = fs::read_dir(&root).unwrap();
- let mut names: Vec<String> = entries
- .flatten()
- .filter(|e| e.file_type().map(|t| t.is_dir()).unwrap_or(false))
- .filter_map(|e| e.file_name().to_str().map(|s| s.to_string()))
- .collect();
- names.sort();
-
- assert_eq!(names, vec!["alpha-aabbcc".to_string(), "zeta-5e61db".to_string()]);
- let _ = fs::remove_dir_all(&root);
+ assert_eq!(
+ directory_names_in(&root),
+ vec!["alpha-aabbcc".to_string(), "zeta-5e61db".to_string()],
+ );
}
/// Negative control: a root that does not exist is an empty list, not an
/// error, so a fresh install never sees a failure here.
#[test]
fn missing_root_is_empty_not_an_error() {
- let root = std::env::temp_dir().join("lu-test-agent-workspace-absent");
- let _ = fs::remove_dir_all(&root);
- let listed: Vec<String> = match fs::read_dir(&root) {
- Ok(e) => e.flatten().filter_map(|x| x.file_name().to_str().map(|s| s.to_string())).collect(),
- Err(_) => Vec::new(),
- };
- assert!(listed.is_empty());
+ let parent = crate::os_paths::test_dir("agent-workspace-absent");
+ let never_created = parent.join("nicht-da");
+ assert!(!never_created.exists(), "the fixture must not exist");
+ assert!(directory_names_in(&never_created).is_empty());
}
}
diff --git a/src-tauri/src/commands/filesystem.rs b/src-tauri/src/commands/filesystem.rs
index 89d9447f..9358e40d 100644
--- a/src-tauri/src/commands/filesystem.rs
+++ b/src-tauri/src/commands/filesystem.rs
@@ -470,15 +470,15 @@ fn resolve_path(path: &str, chat_id: Option<&str>, working_dir: Option<&str>) ->
/// True when `path` LOOKS like the workspace ROOT itself ("", ".", "./",
/// trailing slashes) rather than a named subpath. Used to decide whether a
-/// missing directory should be auto-created as the per-chat sandbox root.
+/// missing directory answers as the empty per-chat sandbox root.
///
/// A guess on the raw string, and it is wrong in both directions: it misses
/// `"unterordner/.."` (which resolves to the root) and it claims `" "` and
/// `".\\"` (which resolve to ordinary files inside it, on a platform where a
/// backslash is an ordinary character). That is affordable for its ONE caller —
-/// `fs_list`, where the answer only decides whether an empty directory gets
-/// created and a wrong guess costs nothing. It is NOT affordable for a write;
-/// see `reject_root_as_write_target`.
+/// `fs_list`, where the answer only decides whether a missing directory reads
+/// as an empty listing or as "Not a directory", and either way nothing is
+/// written. It is NOT affordable for a write; see `reject_root_as_write_target`.
fn is_workspace_root_path(path: &str) -> bool {
let t = path.trim().replace('\\', "/");
let t = t.trim_end_matches('/');
@@ -739,17 +739,42 @@ pub fn fs_list(
if !dir.is_dir() {
// A fresh per-chat agent sandbox (~/agent-workspace/<chat_id>) may not
// exist yet. When the model lists the workspace ROOT with a relative
- // "." / "" path, create it so `file_list .` returns an empty listing
- // instead of "Not a directory" — small models otherwise climb to an
- // absolute drive-root path. Mirrors shell.rs (create_dir_all on cwd).
- // ONLY the sandbox root is auto-created; absolute or sub paths error.
+ // "." / "" path, that is an EMPTY listing rather than "Not a directory"
+ // — small models otherwise climb to an absolute drive-root path. ONLY
+ // the sandbox root gets this answer; absolute or sub paths error.
+ //
+ // ── KF-16: this used to `create_dir_all` the root and then list it ──
+ //
+ // Same answer to the caller either way — an empty listing — so the
+ // creation was never what produced it. What it did produce was a WRITE
+ // on the read door: `fs_list` was the only one of the six that changed
+ // the disk, while `fs_read`, `fs_info`, `fs_search` and `fs_read_bytes`
+ // all report a path that is not there. This file has already paid twice
+ // for "a request that names no file caused a write" (KF-12, KF-15), and
+ // a directory is a smaller version of the same surprise.
+ //
+ // Nothing depended on it. The root is created by the first real write
+ // (`fs_write` runs `create_dir_all` over it — pinned by
+ // `an_ordinary_write_still_creates_the_root_as_a_directory`) and by
+ // `shell.rs`, which creates its cwd. So the folder still exists as soon
+ // as the agent does anything, and a caller that only LOOKS leaves no
+ // trace. The second caller makes that concrete: `ExplorerPanel.tsx`
+ // calls `fs_list` directly whenever the panel is opened, so the old
+ // behaviour put a folder in `~/<AGENT_WORKSPACE_DIR>` for every chat
+ // somebody merely glanced at.
+ //
+ // The dev-server's `/local-api/fs-list` has always answered this way —
+ // 200 with an empty list, nothing created. That was the divergence the
+ // finding names, and this is the side that moved. It is guarded from
+ // both ends: `listing_a_root_that_does_not_exist_creates_nothing` below
+ // measures this function, and
+ // `the_dev_server_answers_the_root_the_same_way` reads the dev-server's
+ // own source so the two cannot drift apart again.
let cleaned = normalize_duplicate_drive_prefix(&path);
if is_workspace_root_path(&cleaned) && !Path::new(&cleaned).is_absolute() {
- let _ = fs::create_dir_all(&dir);
- }
- if !dir.is_dir() {
- return Err(format!("Not a directory: {}", dir.display()));
+ return Ok(serde_json::json!({ "entries": [], "count": 0 }));
}
+ return Err(format!("Not a directory: {}", dir.display()));
}
let mut entries: Vec<serde_json::Value> = Vec::new();
@@ -1957,22 +1982,117 @@ mod write_needs_a_target_tests {
}
/// READING the root is a legitimate request and stays one. `fs_list(".")`
- /// on a workspace that does not exist yet still creates it as a DIRECTORY
- /// and answers with an empty listing — the guard is on the write door only.
+ /// on a workspace that does not exist yet answers with an empty listing —
+ /// the guard is on the write door only.
+ ///
+ /// KF-16: it also creates NOTHING. This test used to assert the opposite
+ /// (`root.is_dir()` afterwards); the argument for the swap is above
+ /// `fs_list`. Both halves are asserted, so neither the answer nor the
+ /// absence of a side effect can be lost silently.
#[test]
- fn listing_the_root_is_still_allowed_and_still_creates_it_as_a_directory() {
+ fn listing_a_root_that_does_not_exist_creates_nothing() {
let parent = picked("list");
- let root = parent.join("ws");
- let root_arg = root.to_string_lossy().to_string();
- for spelling in ["", "."] {
+ for spelling in ["", ".", "./"] {
+ // A fresh root per spelling: the first call must not be able to
+ // create the directory the second one is asked about.
+ let root = parent.join(format!("ws-{}", spelling.len()));
+ let root_arg = root.to_string_lossy().to_string();
+ assert!(!root.exists(), "the fixture must not exist yet");
+
let v = fs_list(spelling.into(), None, None, None, Some(root_arg.clone()))
.unwrap_or_else(|e| panic!("fs_list({spelling:?}) was refused: {e}"));
assert_eq!(v["count"], 0);
- assert!(root.is_dir(), "fs_list({spelling:?}) did not create the root as a directory");
+ assert_eq!(v["entries"], serde_json::json!([]));
+ assert!(
+ !root.exists(),
+ "fs_list({spelling:?}) created {} — a listing must not write",
+ root.display(),
+ );
+
+ // …and once the root IS there, the same call reads it. Without
+ // this the assertion above would also hold for a `fs_list` that
+ // answered "empty" to everything.
+ fs::create_dir_all(root.join("drin")).unwrap();
+ let v = fs_list(spelling.into(), None, None, None, Some(root_arg))
+ .unwrap_or_else(|e| panic!("fs_list({spelling:?}) was refused: {e}"));
+ assert_eq!(v["count"], 1, "the existing root did not read back");
}
}
+ /// A NAMED subpath that is not there is still an error, not an empty
+ /// listing. The empty answer belongs to the cage root alone — otherwise a
+ /// typo in a folder name would read as "the folder is empty".
+ #[test]
+ fn a_missing_subpath_is_still_not_a_directory() {
+ let root = picked("list-sub");
+ let root_arg = root.to_string_lossy().to_string();
+ let err = fs_list("gibtsnicht".into(), None, None, None, Some(root_arg))
+ .expect_err("a missing named folder must not read as empty");
+ assert!(err.starts_with("Not a directory:"), "{err}");
+ }
+
+ /// ── The other side of the same door (KF-16) ──
+ ///
+ /// The dev-server serves the same six file operations to the same model,
+ /// and `/local-api/fs-list` has always answered the cage root with 200 and
+ /// an empty list while creating nothing. That is the answer this file now
+ /// gives too — but "both sides agree today" is what the previous divergence
+ /// also looked like, right up until one of them was maintained and the
+ /// other was not.
+ ///
+ /// So the rule is read back out of the dev-server's own source. It is the
+ /// same idiom `commands/secret.rs` uses to hold `providerStore.ts` and
+ /// `mlx-image.ts` to a rule this crate depends on. It cannot run the
+ /// handler — that is vitest's job — but it fails the moment somebody
+ /// teaches the listing route to create a directory, which is the drift
+ /// that has to be caught.
+ #[test]
+ fn the_dev_server_answers_the_root_the_same_way() {
+ const FS_ROUTES_TS: &str = include_str!("../../../dev-server/fs-routes.ts");
+
+ let route = |name: &str| -> &str {
+ let marker = format!("routes.use('/local-api/{name}'");
+ let at = FS_ROUTES_TS
+ .find(&marker)
+ .unwrap_or_else(|| panic!("dev-server has no {name} route any more"));
+ let rest = &FS_ROUTES_TS[at + marker.len()..];
+ let end = rest
+ .find("routes.use('/local-api/")
+ .unwrap_or(rest.len());
+ &rest[..end]
+ };
+
+ let list = route("fs-list");
+ // The listing walks the directory and never creates it.
+ assert!(list.contains("readdirSync"), "the listing route stopped reading the directory");
+ assert!(
+ !list.contains("mkdirSync"),
+ "the dev-server's fs-list now CREATES the directory it was asked to list. \
+ Rust's fs_list does not (see `listing_a_root_that_does_not_exist_creates_nothing`); \
+ one of the two doors has moved.",
+ );
+ // A root that is not there is an empty listing, not an error status.
+ assert!(
+ list.contains("count: entries.length"),
+ "the listing route no longer answers with the entries it collected",
+ );
+ assert!(
+ list.contains("entries: [], count: 0"),
+ "the listing route no longer falls back to an EMPTY listing",
+ );
+
+ // Negative control for the slicing itself: `mkdirSync` does appear in
+ // this file — on the WRITE door, where it belongs. Without this, a
+ // mis-sliced route would make the assertion above pass on an empty
+ // string.
+ assert!(
+ route("fs-write").contains("mkdirSync"),
+ "the write route no longer creates the parent directory — either the \
+ dev-server changed or the slicing above is picking the wrong block",
+ );
+ }
+
// ── Why the guard measures the RESOLVED path and not the string ─────────
/// The string predicate is wrong in BOTH directions, which is why the guard
diff --git a/src-tauri/src/commands/gguf.rs b/src-tauri/src/commands/gguf.rs
index a41876aa..16287490 100644
--- a/src-tauri/src/commands/gguf.rs
+++ b/src-tauri/src/commands/gguf.rs
@@ -219,43 +219,62 @@ mod tests {
}
}
- fn tmp(name: &str) -> std::path::PathBuf {
- let dir = std::env::temp_dir().join("lu-gguf-tests");
- std::fs::create_dir_all(&dir).unwrap();
- dir.join(name)
+ /// A directory these fixtures own for the length of one test.
+ ///
+ /// It used to be the FIXED `<temp>/lu-gguf-tests/`, with the fixture names
+ /// fixed too (`ok.gguf`, `reversed.gguf`, …). Every concurrent copy of this
+ /// test binary therefore wrote the same files, and `W::write_to` opens with
+ /// `File::create` — which TRUNCATES. One copy truncating `reversed.gguf`
+ /// while another was parsing it is a header that ends mid-field, and
+ /// `context_length` correctly answers `None`.
+ ///
+ /// Measured on 01.09.2026 under three concurrent copies of the whole suite,
+ /// ten rounds: `context_key_before_architecture_still_resolves` failed 2 of
+ /// 30 and `reads_context_length_behind_skipped_values` 1 of 30, both with
+ /// `left: None`. Nothing about the parser was wrong — the file under it was
+ /// being rewritten mid-read.
+ ///
+ /// `test_dir` carries the process id and the thread id in the name and
+ /// sweeps itself up on `Drop`. The returned guard has to stay in scope: the
+ /// directory is removed when it is dropped.
+ fn fixtures(tag: &str) -> crate::os_paths::TestDir {
+ crate::os_paths::test_dir(&format!("gguf-{tag}"))
}
#[test]
fn reads_context_length_behind_skipped_values() {
+ let dir = fixtures("skipped");
let mut w = W::new(4);
w.str_field("general.name", "unit test model");
w.arr_str_field("tokenizer.ggml.tokens", &["a", "b", "c"]);
w.str_field("general.architecture", "qwen2");
w.u32_field("qwen2.context_length", 32768);
- let p = tmp("ok.gguf");
+ let p = dir.join("ok.gguf");
w.write_to(&p);
assert_eq!(context_length(p.to_str().unwrap()), Some(32768));
}
#[test]
fn context_key_before_architecture_still_resolves() {
+ let dir = fixtures("reversed");
let mut w = W::new(2);
w.u32_field("llama.context_length", 8192);
w.str_field("general.architecture", "llama");
- let p = tmp("reversed.gguf");
+ let p = dir.join("reversed.gguf");
w.write_to(&p);
assert_eq!(context_length(p.to_str().unwrap()), Some(8192));
}
#[test]
fn garbage_missing_and_truncated_files_are_none() {
- let p = tmp("garbage.gguf");
+ let dir = fixtures("garbage");
+ let p = dir.join("garbage.gguf");
std::fs::write(&p, b"MZ\x90definitely not a gguf").unwrap();
assert_eq!(context_length(p.to_str().unwrap()), None);
assert_eq!(context_length("/nonexistent/nope.gguf"), None);
// Valid magic, then the file just ends mid-header.
- let t = tmp("truncated.gguf");
+ let t = dir.join("truncated.gguf");
std::fs::write(&t, b"GGUF\x03\x00\x00\x00").unwrap();
assert_eq!(context_length(t.to_str().unwrap()), None);
}
diff --git a/src-tauri/src/commands/mlx.rs b/src-tauri/src/commands/mlx.rs
index ec409b9c..f8d9518a 100644
--- a/src-tauri/src/commands/mlx.rs
+++ b/src-tauri/src/commands/mlx.rs
@@ -863,21 +863,31 @@ pub fn mlx_start(_state: &AppState, _args: &Value) -> CmdResult {
Ok(json!({"ok": true, "port": MLX_PORT, "log": log_path.to_string_lossy()}))
}
-/// Stop the MLX sidecar (the long-lived image/video server on MLX_PORT). We
-/// didn't keep a Child handle, so stop it by its listening port — the "Stop"
-/// button counterpart to `mlx_start`.
-/// FINDING (clippy paydown, 01.09.2026): this has no caller and no bridge.
-/// `media_cmds.rs` wraps `mlx_status`, `mlx_start`, `mlx_unload`, `mlx_generate`
-/// and the rest as `#[tauri::command]`s — but not this one, so the frontend
-/// cannot reach it and the "Stop" button it describes cannot exist. The only
-/// production path that actually stops the sidecar is the quit-time
-/// `kill_listeners_on_port(MLX_PORT)` in `state.rs`. Either add the wrapper or
-/// delete this; the `allow` only keeps `-D warnings` usable meanwhile.
-#[allow(dead_code)]
-pub fn mlx_stop(_state: &AppState, _args: &Value) -> CmdResult {
- crate::process_util::kill_listeners_on_port(MLX_PORT);
- Ok(json!({ "ok": true, "port": MLX_PORT }))
-}
+// ── REMOVED on 01.09.2026: `mlx_stop` (KF-19) ─────────────────────────────
+//
+// It was two lines — `kill_listeners_on_port(MLX_PORT)` and an `{"ok":true}` —
+// under a doc comment calling itself "the Stop button counterpart to
+// `mlx_start`". Counted before removing: no Rust caller, no
+// `#[tauri::command]` wrapper in `media_cmds.rs`, no line in `main.rs`'s
+// handler list, and no occurrence of the STRING "mlx_stop" anywhere under
+// `src/`, `dev-server/`, `e2e/` or `mobile-client/` — which is how a Tauri
+// command is actually invoked. Every other mlx entry point is wired all four
+// ways. The Stop button it described could not exist.
+//
+// Deleted rather than wired, because the need it names is already served twice
+// over and neither of those is this function:
+//
+// * Reclaiming memory while the app runs is `mlx_unload` (bridged, and
+// called from `src/api/mlx-image.ts`). It frees the resident model and
+// leaves the sidecar up, which is the point of a sidecar — `mlx_status`
+// returns `modelLoaded`/`idleSeconds` so the UI can offer exactly that.
+// * Ending the PROCESS is the quit-time `kill_listeners_on_port(MLX_PORT)`
+// in `state.rs::shutdown`. Same call, one line, on the path that actually
+// runs.
+//
+// Wiring it would have meant a bridge in `media_cmds.rs`, a line in `main.rs`
+// and a caller in `src/` — a third door onto a job the other two already do,
+// and the frontend is not this agent's to change.
const REQUIREMENTS_TXT: &str = include_str!("../../resources/mlx/requirements.txt");
const SERVER_PY: &str = include_str!("../../resources/mlx/server.py");
diff --git a/src-tauri/src/commands/system.rs b/src-tauri/src/commands/system.rs
index 5df7e7db..079cb266 100644
--- a/src-tauri/src/commands/system.rs
+++ b/src-tauri/src/commands/system.rs
@@ -81,7 +81,21 @@ fn screenshot_blocking() -> Result<serde_json::Value, String> {
// bridge (remote.rs). Overlapping calls read each other's half-written PNG,
// or one deleted the file the other was about to read ("Read screenshot: no
// such file"), or a caller simply got the other one's screen.
- let tmp = std::env::temp_dir().join(format!("lu-screenshot-{}.png", uuid::Uuid::new_v4()));
+ //
+ // The PROCESS id joined the uuid on 01.09.2026. The uuid alone already made
+ // the name unique; what it did not do is say WHOSE the file is. The temp
+ // directory is shared by every process on the machine — a second LU, an
+ // older build, three copies of the test suite — so neither an operator
+ // finding a leftover `lu-screenshot-*.png` nor
+ // `every_screenshot_gets_its_own_temp_file` could tell a file this process
+ // made from a stranger's. That test counted the whole directory and failed
+ // 5 of 30 runs under three concurrent suites (measured, 01.09.2026) because
+ // ANOTHER copy had a capture in flight across its two counts.
+ let tmp = std::env::temp_dir().join(format!(
+ "lu-screenshot-{}-{}.png",
+ std::process::id(),
+ uuid::Uuid::new_v4()
+ ));
let captured = capture_screen_to(&tmp)
.and_then(|()| std::fs::read(&tmp).map_err(|e| format!("Read screenshot: {}", os_error::english(&e))));
// Always — the old code returned early on a read error and left a full
@@ -700,27 +714,52 @@ mod tests {
/// Two callers reach the screenshot tool (agent + phone bridge). A fixed
/// temp name meant they clobbered each other; the name must differ per call
/// and the file must be gone afterwards.
+ ///
+ /// ── Why the count is now over THIS process only ──
+ ///
+ /// It used to count every `lu-screenshot-*` in the shared temp directory,
+ /// before and after, and assert the two numbers matched. That is a question
+ /// about the MACHINE, not about this call: measured on 01.09.2026 under
+ /// three concurrent copies of the suite it failed 5 of 30 runs with
+ /// `left: 0, right: 1` — a second copy's capture was in flight between the
+ /// two counts, and this test reported it as "screenshot left a temp file
+ /// behind". `screenshot_blocking` puts the process id in the name, so the
+ /// prefix below matches only files this process could have written.
#[test]
fn every_screenshot_gets_its_own_temp_file() {
let seen: std::collections::HashSet<String> = (0..50)
- .map(|_| format!("lu-screenshot-{}.png", uuid::Uuid::new_v4()))
+ .map(|_| format!("lu-screenshot-{}-{}.png", std::process::id(), uuid::Uuid::new_v4()))
.collect();
assert_eq!(seen.len(), 50);
+ // Ours, and nobody else's — a concurrent copy of this binary has a
+ // different pid and its files do not match this prefix.
+ let mine = format!("lu-screenshot-{}-", std::process::id());
+ let ours = || {
+ std::fs::read_dir(std::env::temp_dir())
+ .unwrap()
+ .filter_map(|e| e.ok())
+ .filter(|e| e.file_name().to_string_lossy().starts_with(&mine))
+ .count()
+ };
+
// The capture fails on this platform, but the temp file must still be
// cleaned up rather than left behind on the early return.
- let before = std::fs::read_dir(std::env::temp_dir())
- .unwrap()
- .filter_map(|e| e.ok())
- .filter(|e| e.file_name().to_string_lossy().starts_with("lu-screenshot-"))
- .count();
+ let before = ours();
let _ = screenshot_blocking();
- let after = std::fs::read_dir(std::env::temp_dir())
- .unwrap()
- .filter_map(|e| e.ok())
- .filter(|e| e.file_name().to_string_lossy().starts_with("lu-screenshot-"))
- .count();
+ let after = ours();
assert_eq!(before, after, "screenshot left a temp file behind");
+ // Self-check: the prefix the count filters on has to be the one
+ // `screenshot_blocking` actually writes. Without this, moving the pid
+ // out of the name again would leave both counts at 0 for the wrong
+ // reason and this test would pass while looking at nothing.
+ const SRC: &str = include_str!("system.rs");
+ let at = SRC.find("fn screenshot_blocking").expect("screenshot_blocking is gone");
+ let body = &SRC[at..at + SRC[at..].find("\n}\n").expect("unterminated fn")];
+ assert!(
+ body.contains(r#""lu-screenshot-{}-{}.png""#) && body.contains("std::process::id()"),
+ "screenshot_blocking no longer builds the name this test filters on:\n{body}",
+ );
}
/// PowerShell single-quoted strings escape `'` by doubling it, and treat a
diff --git a/src-tauri/src/commands/trainer.rs b/src-tauri/src/commands/trainer.rs
index 58086993..e99b294e 100644
--- a/src-tauri/src/commands/trainer.rs
+++ b/src-tauri/src/commands/trainer.rs
@@ -2013,17 +2013,24 @@ mod shutdown_tests {
assert_eq!(venv_create_args(VenvAction::Keep), ["-m", "venv"]);
}
+ /// The probe directory is per-process now (`test_dir` puts the pid and the
+ /// thread id in the name and sweeps up on `Drop`). It used to be the FIXED
+ /// `<temp>/lu-trainer-venv-probe/python-not-an-interpreter`, deleted at the
+ /// end of the test — so a concurrent copy of this binary removed the file
+ /// between this copy's `write` and its `exists`. Measured on 01.09.2026
+ /// under six concurrent copies of the suite, ten rounds: 1 of 60 runs, and
+ /// the message it failed with — "the file is there, which is all the old
+ /// check asked" — pointed at the production code rather than at the
+ /// fixture.
#[test]
fn presence_alone_never_counts_as_a_working_interpreter() {
use super::python_starts;
- let dir = std::env::temp_dir().join("lu-trainer-venv-probe");
- let _ = std::fs::create_dir_all(&dir);
+ let dir = crate::os_paths::test_dir("trainer-venv-probe");
let fake = dir.join("python-not-an-interpreter");
std::fs::write(&fake, b"pyvenv.cfg points at a home that is gone").unwrap();
assert!(fake.exists(), "the file is there, which is all the old check asked");
assert!(!python_starts(&fake), "but it does not run, which is the question");
assert!(!python_starts(&dir.join("nothing-here")));
- let _ = std::fs::remove_file(&fake);
}
#[test]
diff --git a/src-tauri/src/commands/whisper.rs b/src-tauri/src/commands/whisper.rs
index e37afe29..d2de0295 100644
--- a/src-tauri/src/commands/whisper.rs
+++ b/src-tauri/src/commands/whisper.rs
@@ -718,20 +718,84 @@ mod dead_server_tests {
assert!(ws.has_exited());
}
+ /// One go at the failure: a lingering stand-in, killed and reaped, then a
+ /// take sent into its pipe. Returns `(has_exited, the send's answer)`.
+ ///
+ /// It runs on its own thread and the caller waits with a ceiling, because
+ /// of the one way this can come out neither dead nor alive — see the
+ /// test below.
+ fn attempt_a_send_into_a_killed_server(
+ ) -> Option<(bool, Result<serde_json::Value, String>)> {
+ let (done, answer) = mpsc::channel();
+ std::thread::spawn(move || {
+ // `_tx` stays in here: dropping it would disconnect the response
+ // channel, which is a different failure than the one under test.
+ let (mut ws, _tx) = server_around(spawn_lingering());
+ if let Some(child) = ws.process.as_mut() {
+ let _ = child.kill();
+ let _ = child.wait();
+ }
+ let exited = ws.has_exited();
+ let out = ws.send_command(&json!({ "action": "transcribe", "path": "/tmp/x.wav" }));
+ ws.stop();
+ let _ = done.send((exited, out));
+ });
+ // A write into a pipe with no reader fails in microseconds. Anything
+ // that is still going after five seconds is parked on `send_command`'s
+ // 60 s response timeout, i.e. the write SUCCEEDED.
+ answer.recv_timeout(std::time::Duration::from_secs(5)).ok()
+ }
+
/// The whole failure, at the wire: kill the server the way the box did,
/// then send a take into it.
+ ///
+ /// ── Why this retries, and what it is retrying past ──
+ ///
+ /// The old body did one attempt on this thread and asserted on it. Measured
+ /// on 01.09.2026 under six concurrent copies of the suite it failed 8 of 60
+ /// runs, every one of them with the same message: `[dead pipe] Whisper
+ /// transcription timed out`. The write into the killed server's stdin had
+ /// SUCCEEDED, and the test then sat out the full 60 s response timeout — a
+ /// single run took 61 s because of it.
+ ///
+ /// What is MEASURED is that the write succeeded: the server was killed and
+ /// reaped, so its own copy of the read end was closed, and a write into a
+ /// pipe with no reader cannot succeed. Somebody else was holding it.
+ ///
+ /// The mechanism that fits is macOS having no `pipe2`. The standard library
+ /// says so in its own source: on every platform without that syscall it
+ /// creates the pipe with `pipe()` and sets close-on-exec in a SECOND step,
+ /// so a `fork`+`exec` on another thread inside that window inherits the raw
+ /// descriptor. This suite spawns stand-ins constantly, six copies of it six
+ /// times as often, and that is exactly the load at which this appeared.
+ /// Whatever the stranger is, it is not ours and this test cannot close it.
+ ///
+ /// So it retries with a FRESH stand-in, bounded, instead of asserting that
+ /// the first one came out right. Every assertion below is unchanged and
+ /// runs on an attempt that produced an answer — a green run still means the
+ /// write failed and the message was ours.
#[test]
fn sending_into_a_killed_server_fails_in_english_and_is_recognised_as_a_dead_pipe() {
- let (mut ws, _tx) = server_around(spawn_lingering());
- if let Some(child) = ws.process.as_mut() {
- let _ = child.kill();
- let _ = child.wait();
- }
- assert!(ws.has_exited());
-
- let err = ws
- .send_command(&json!({ "action": "transcribe", "path": "/tmp/x.wav" }))
- .expect_err("writing into a dead pipe must fail");
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
+ let mut parked = 0usize;
+ let err = loop {
+ match attempt_a_send_into_a_killed_server() {
+ Some((exited, out)) => {
+ assert!(exited, "the killed server did not read as gone");
+ break out.expect_err("writing into a dead pipe must fail");
+ }
+ None => {
+ parked += 1;
+ assert!(
+ std::time::Instant::now() < deadline,
+ "{parked} attempts in a row wrote into the killed server's pipe \
+ without failing. Something other than the server is holding the \
+ READ end — on macOS a concurrent spawn can inherit it, because \
+ the pipe is not created close-on-exec in one step.",
+ );
+ }
+ }
+ };
// The message is ours all the way through. The operating system's own
// sentence for this is German on a German Windows; none of these
@@ -750,7 +814,6 @@ mod dead_server_tests {
"unexpected shape: {}",
err
);
- ws.stop();
}
#[test]
diff --git a/src-tauri/src/os_paths.rs b/src-tauri/src/os_paths.rs
index c17d6d20..8c42eca9 100644
--- a/src-tauri/src/os_paths.rs
+++ b/src-tauri/src/os_paths.rs
@@ -340,140 +340,55 @@ pub fn find_lms_cli() -> Option<PathBuf> {
which::which("lms").ok()
}
-/// macOS Spotlight lookup for an app bundle by its on-disk name (e.g.
-/// "LM Studio.app"). Finds installs buried in deep or hidden folders that PATH
-/// and the fixed /Applications check miss — people drop apps in the weirdest
-/// nested places. No-op (None) off macOS.
-fn spotlight_app(fs_name: &str) -> Option<PathBuf> {
- #[cfg(target_os = "macos")]
- {
- let out = std::process::Command::new("mdfind")
- .arg(format!("kMDItemFSName == '{fs_name}'"))
- .output()
- .ok()?;
- String::from_utf8_lossy(&out.stdout)
- .lines()
- .map(|l| PathBuf::from(l.trim()))
- .find(|p| p.exists())
- }
- #[cfg(not(target_os = "macos"))]
- {
- let _ = fs_name;
- None
- }
-}
-
-/// Locate the LM Studio app bundle anywhere on disk: the standard install dirs
-/// first, then Spotlight for hidden / deeply-nested installs.
-pub fn find_lmstudio_app() -> Option<PathBuf> {
- for p in [
- PathBuf::from("/Applications/LM Studio.app"),
- home().join("Applications").join("LM Studio.app"),
- ] {
- if p.exists() {
- return Some(p);
- }
- }
- spotlight_app("LM Studio.app")
-}
-
-/// Is LM Studio installed anywhere — the `lms` CLI or the app bundle?
-/// FINDING (clippy paydown, 01.09.2026): nothing in this repository calls this —
-/// not the Rust side, not a `#[tauri::command]` wrapper, not the frontend. It is
-/// kept rather than deleted because deleting a detection helper is a product
-/// decision, not a lint decision; the `allow` is here so the rest of the crate
-/// can run under `-D warnings` while that decision is pending. Wire it or drop
-/// it, but do not leave it in this state indefinitely.
-#[allow(dead_code)]
-pub fn lmstudio_installed() -> bool {
- find_lms_cli().is_some() || find_lmstudio_app().is_some()
-}
-
-/// Locate the Ollama app bundle anywhere on disk (fixed dirs, then Spotlight).
-pub fn find_ollama_app() -> Option<PathBuf> {
- for p in [
- PathBuf::from("/Applications/Ollama.app"),
- home().join("Applications").join("Ollama.app"),
- ] {
- if p.exists() {
- return Some(p);
- }
- }
- spotlight_app("Ollama.app")
-}
-
-/// Locate the `ollama` CLI binary: PATH, common prefixes, then inside a
-/// discovered Ollama.app bundle.
-pub fn find_ollama_bin() -> Option<PathBuf> {
- if let Ok(p) = which::which("ollama") {
- return Some(p);
- }
- for c in [
- "/opt/homebrew/bin/ollama",
- "/usr/local/bin/ollama",
- "/usr/bin/ollama",
- ] {
- let p = PathBuf::from(c);
- if p.exists() {
- return Some(p);
- }
- }
- if let Some(app) = find_ollama_app() {
- for rel in [
- "Contents/Resources/ollama",
- "Contents/MacOS/Ollama",
- "Contents/MacOS/ollama",
- ] {
- let p = app.join(rel);
- if p.exists() {
- return Some(p);
- }
- }
- }
- None
-}
-
-/// Is Ollama installed anywhere — CLI binary or app bundle?
-/// FINDING (clippy paydown, 01.09.2026): nothing in this repository calls this —
-/// not the Rust side, not a `#[tauri::command]` wrapper, not the frontend. It is
-/// kept rather than deleted because deleting a detection helper is a product
-/// decision, not a lint decision; the `allow` is here so the rest of the crate
-/// can run under `-D warnings` while that decision is pending. Wire it or drop
-/// it, but do not leave it in this state indefinitely.
-#[allow(dead_code)]
-pub fn ollama_installed() -> bool {
- find_ollama_bin().is_some() || find_ollama_app().is_some()
-}
-
-/// Reasonable places to look for an existing ComfyUI install.
-/// FINDING (clippy paydown, 01.09.2026): nothing in this repository calls this —
-/// not the Rust side, not a `#[tauri::command]` wrapper, not the frontend. It is
-/// kept rather than deleted because deleting a detection helper is a product
-/// decision, not a lint decision; the `allow` is here so the rest of the crate
-/// can run under `-D warnings` while that decision is pending. Wire it or drop
-/// it, but do not leave it in this state indefinitely.
-#[allow(dead_code)]
-pub fn comfyui_search_roots() -> Vec<PathBuf> {
- let mut out = Vec::new();
- let h = home();
- out.push(h.clone());
- out.push(h.join("Desktop"));
- out.push(h.join("Documents"));
- out.push(h.join("Downloads"));
- if cfg!(target_os = "windows") {
- if let Ok(user_profile) = std::env::var("USERPROFILE") {
- out.push(PathBuf::from(user_profile.clone()).join("StabilityMatrix"));
- out.push(PathBuf::from(user_profile).join("Packages"));
- }
- }
- out
-}
+// ── REMOVED on 01.09.2026: the second engine-detection apparatus (KF-19) ──
+//
+// Gone from here: `lmstudio_installed`, `ollama_installed`,
+// `comfyui_search_roots`, and the three helpers that only they kept alive —
+// `find_lmstudio_app`, `find_ollama_app`, `find_ollama_bin` and
+// `spotlight_app` (the `mdfind` lookup, whose only two callers were the two
+// `find_*_app` functions).
+//
+// The three named ones were counted before removing: no Rust caller, no
+// `#[tauri::command]` wrapper, no line in `main.rs`, and no occurrence of the
+// NAME as a string anywhere under `src/`, `dev-server/`, `e2e/` or
+// `mobile-client/`. The three helpers had exactly one caller each, and that
+// caller was one of the three.
+//
+// They are not a gap: every question they answered is already answered on a
+// path that runs, and by different code — which is the whole point of the
+// finding.
+//
+// * "Is Ollama there?" — the production paths call `Command::new("ollama")`
+// straight off PATH (`process.rs::start_ollama` / `auto_start_ollama`), and
+// the installer probes with `which ollama`
+// (`commands/install/ollama.rs`). Neither ever consulted
+// `find_ollama_bin`'s richer search (Homebrew prefixes, the app bundle's
+// three internal layouts, Spotlight).
+// * "Is LM Studio there?" — `commands/install/lmstudio.rs::lmstudio_lms_path`,
+// which handles the Windows layouts itself and delegates to
+// `find_lms_cli` (kept, and still called) everywhere else.
+// * "Where might ComfyUI be?" — `process.rs::find_comfyui_path`, which keeps
+// its own, longer and actually maintained list of roots: the env var, the
+// config file, the fixed locations, a depth-7 home scan, then the drive
+// roots. `comfyui_search_roots` listed four home folders plus
+// `%USERPROFILE%\StabilityMatrix` and `…\Packages` — the wrong shape for
+// Stability Matrix, which nests as `StabilityMatrix\Packages\ComfyUI`, and
+// nobody noticed because nobody called it.
+//
+// Wiring them instead would have meant choosing WHICH of the two detections
+// each question gets — the very fork this finding is about — and the callers
+// that would have to change are in `src/`.
/// Default ComfyUI install target — where install_comfyui will drop the
/// portable bundle on Windows / clone the repo on macOS+Linux.
-/// Only the path-inventory test in `app_identity.rs` calls this today — no
-/// production caller is left, so it is dead in the `bin` target and alive in the
-/// `test` one. Same standing decision as the helpers above.
+///
+/// The `allow` here is NOT the standing "decide later" the block above just
+/// removed, and the difference is the whole point of KF-19: this function HAS a
+/// caller — `alle_abgeleiteten_pfade` in `app_identity.rs`, which asserts that
+/// no path this build derives points into the real app's directories. It is
+/// therefore alive in the `test` target and dead only in the `bin` one, and
+/// `dead_code` cannot see across the two. Remove the caller and this becomes a
+/// deletion like the others.
#[allow(dead_code)]
pub fn default_comfyui_dir() -> PathBuf {
data_dir().join("ComfyUI")
diff --git a/src-tauri/src/process_util.rs b/src-tauri/src/process_util.rs
index 07eee813..4511293e 100644
--- a/src-tauri/src/process_util.rs
+++ b/src-tauri/src/process_util.rs
@@ -128,6 +128,16 @@ fn tree_snapshot(root: u32) -> Vec<(u32, u64)> {
.collect()
}
+/// How long a SIGTERM'd tree is given before the SIGKILL goes out.
+///
+/// A named constant because it is the subject of
+/// `the_call_does_not_block_for_the_grace_period`: the whole point of the
+/// detached thread below is that the CALLER never spends this. It was written
+/// twice, once per escalation path, and a change to one of the two would have
+/// been silent.
+#[cfg(unix)]
+const KILL_GRACE: std::time::Duration = std::time::Duration::from_millis(800);
+
/// Recursive process-tree kill: SIGTERM the whole tree now, SIGKILL whatever
/// is left after a grace. Windows delegates the walk to `taskkill /T /F`.
///
@@ -180,7 +190,7 @@ pub fn kill_tree(child: &mut Child) -> std::io::Result<()> {
}
}
std::thread::spawn(move || {
- std::thread::sleep(std::time::Duration::from_millis(800));
+ std::thread::sleep(KILL_GRACE);
let survivors = {
use sysinfo::{Pid, ProcessesToUpdate, System};
let mut sys = System::new();
@@ -239,7 +249,7 @@ pub fn kill_pid_tree(pid: u32) {
}
}
std::thread::spawn(move || {
- std::thread::sleep(std::time::Duration::from_millis(800));
+ std::thread::sleep(KILL_GRACE);
use sysinfo::{Pid, ProcessesToUpdate, System};
let mut sys = System::new();
sys.refresh_processes(ProcessesToUpdate::All, true);
@@ -374,12 +384,25 @@ mod kill_tree_tests {
.spawn()
.expect("spawn sh");
let pid = child.id();
- std::thread::sleep(Duration::from_millis(400));
- let mut sys = sysinfo::System::new();
- sys.refresh_processes(sysinfo::ProcessesToUpdate::All, true);
- let kids = crate::commands::shell::descendants(pid, &sys);
- assert!(!kids.is_empty(), "sh spawned nothing — test setup is wrong");
+ // Waits for the CONDITION — sh has actually forked — with a ceiling,
+ // instead of guessing 400 ms at it. The old fixed sleep made the
+ // "test setup is wrong" assertion below a load measurement: on a busy
+ // machine sh simply had not got there yet.
+ let deadline = Instant::now() + Duration::from_secs(10);
+ let kids = loop {
+ let mut sys = sysinfo::System::new();
+ sys.refresh_processes(sysinfo::ProcessesToUpdate::All, true);
+ let kids = crate::commands::shell::descendants(pid, &sys);
+ if !kids.is_empty() {
+ break kids;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "sh spawned nothing in 10s — test setup is wrong",
+ );
+ std::thread::sleep(Duration::from_millis(50));
+ };
kill_tree(&mut child).expect("kill_tree");
@@ -391,6 +414,27 @@ mod kill_tree_tests {
/// `video_cancel` holds the `video_process` mutex for the duration of this
/// call and the progress poll waits on the same mutex, so a blocking grace
/// froze the window. The kill must be ordered, not awaited.
+ ///
+ /// ── Why there is no stopwatch in here any more ──
+ ///
+ /// It used to time the call and assert `took < 400 ms`. That number is not
+ /// the grace and it is not a property of the code: the unavoidable work
+ /// inside `kill_tree` is `tree_snapshot`, which enumerates the ENTIRE
+ /// process table, and how long that takes belongs to the machine and to
+ /// whatever else is running on it. Measured on 01.09.2026 under six
+ /// concurrent copies of the suite — every one of them walking the process
+ /// table too — it failed 17 of 18 runs. The kill was ordered, not awaited,
+ /// in all 18; the enumeration was simply slower than the budget.
+ ///
+ /// So the question is asked without a clock. `kill_tree` hands the grace,
+ /// the SIGKILL and the final `waitpid` to a detached thread. The `waitpid`
+ /// is the LAST of those, and until it runs the child is our unreaped
+ /// zombie, which is a pid `kill(pid, 0)` can still address. An
+ /// implementation that awaited the grace would return AFTER that thread had
+ /// finished, and the pid would be gone. One signal-0, no wall clock, no
+ /// budget to blow — and it fails for exactly the regression this test
+ /// exists to catch (put `thread::sleep(KILL_GRACE)` back in the caller's
+ /// path and the child is reaped before the assertion runs).
#[test]
fn the_call_does_not_block_for_the_grace_period() {
let mut child = Command::new("sh")
@@ -401,13 +445,35 @@ mod kill_tree_tests {
.spawn()
.expect("spawn sh");
let pid = child.id();
- std::thread::sleep(Duration::from_millis(200));
- let started = Instant::now();
+ // Self-check instead of a settle sleep: wait for the CONDITION that the
+ // stand-in is a live process carrying the argv this test chose, with a
+ // ceiling. A `sh` that died on the spot would otherwise be killed as a
+ // corpse and every assertion below would still pass. `checked_table`
+ // owns the ceiling and the retry, including the one for a child that is
+ // in the table but has not finished `exec` yet.
+ let table = crate::test_support::checked_table(pid).unwrap_or_else(|why| panic!("{why}"));
+ let argv = crate::process_util::cmdline_of(
+ table
+ .process(sysinfo::Pid::from_u32(pid))
+ .expect("checked_table only returns a table containing this pid"),
+ );
+ assert!(
+ argv.join(" ").contains("sleep"),
+ "the stand-in is not the sleeper this test spawned: {argv:?}",
+ );
+
kill_tree(&mut child).expect("kill_tree");
- let took = started.elapsed();
- assert!(took < Duration::from_millis(400), "kill_tree blocked for {took:?}");
+ // Still ours, still unreaped → the detached thread has not reached its
+ // `waitpid` yet → this call cannot have waited for the grace.
+ let still_ours = unsafe { libc::kill(pid as i32, 0) } == 0;
+ assert!(
+ still_ours,
+ "kill_tree returned only after the escalation thread had already \
+ reaped pid {pid} — it waited out the {KILL_GRACE:?} grace",
+ );
+
wait_until_gone(&[pid], Duration::from_secs(5));
}
diff --git a/src-tauri/src/python.rs b/src-tauri/src/python.rs
index 03fc0745..1540f9fd 100644
--- a/src-tauri/src/python.rs
+++ b/src-tauri/src/python.rs
@@ -394,21 +394,31 @@ mod tests {
// ── resolve_comfyui_venv_python — existence gate ────────────────────────
+ /// ── Why these three no longer name their own directory ──
+ ///
+ /// They used the FIXED paths `<temp>/lu-venv-test-missing`,
+ /// `…-present` and `lu-dotvenv-test-present`, and each began by deleting
+ /// its own. Every concurrent copy of this test binary used the same three,
+ /// so one copy's `remove_dir_all` landed between another's `create_dir_all`
+ /// and its `resolve_comfyui_venv_python` — the stub python was gone and the
+ /// resolver correctly answered `None`. Measured on 01.09.2026 under six
+ /// concurrent copies of the suite, ten rounds:
+ /// `resolve_returns_some_when_venv_python_exists` and
+ /// `resolve_finds_dot_venv_layout` failed 1 of 60 runs each.
+ ///
+ /// `crate::os_paths::test_dir` puts the process id and the thread id in the
+ /// name and sweeps up on `Drop`, even when an assertion panics.
#[test]
fn resolve_returns_none_when_venv_missing() {
- let tmp = std::env::temp_dir().join("lu-venv-test-missing");
- let _ = fs::remove_dir_all(&tmp);
- fs::create_dir_all(&tmp).unwrap();
+ let tmp = crate::os_paths::test_dir("venv-missing");
assert!(resolve_comfyui_venv_python(&tmp).is_none());
- let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn resolve_returns_some_when_venv_python_exists() {
// Build the exact layout `python -m venv` would produce so the
// resolver finds it without actually invoking Python.
- let tmp = std::env::temp_dir().join("lu-venv-test-present");
- let _ = fs::remove_dir_all(&tmp);
+ let tmp = crate::os_paths::test_dir("venv-present");
let inner = if cfg!(target_os = "windows") {
tmp.join("venv").join("Scripts")
} else {
@@ -424,15 +434,13 @@ mod tests {
let resolved = resolve_comfyui_venv_python(&tmp);
assert!(resolved.is_some(), "expected resolver to find {}", py.display());
assert!(resolved.unwrap().contains("venv"));
- let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn resolve_finds_dot_venv_layout() {
// Issue #51 (adhney): ComfyUI installed into `.venv` (uv / modern
// `python -m venv .venv`) must also be picked up, not just `venv`.
- let tmp = std::env::temp_dir().join("lu-dotvenv-test-present");
- let _ = fs::remove_dir_all(&tmp);
+ let tmp = crate::os_paths::test_dir("dotvenv-present");
let inner = if cfg!(target_os = "windows") {
tmp.join(".venv").join("Scripts")
} else {
@@ -448,7 +456,6 @@ mod tests {
let resolved = resolve_comfyui_venv_python(&tmp);
assert!(resolved.is_some(), "expected resolver to find {}", py.display());
assert!(resolved.unwrap().contains(".venv"));
- let _ = fs::remove_dir_all(&tmp);
}
// ── is_real_python (Bug P14 — Microsoft Store stub filter) ──────────────
diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs
index b5b3afbc..90875486 100644
--- a/src-tauri/src/state.rs
+++ b/src-tauri/src/state.rs
@@ -568,7 +568,12 @@ impl AppState {
// drops the Child handle — the sidecar outlives individual renders and
// is addressed over loopback — so quitting used to orphan the venv
// Python forever (observed live: LU gone, server.py still resident).
- // Kill it by its listening port, same mechanism as the Stop button.
+ // Kill it by its listening port. This is the ONLY thing that stops the
+ // sidecar process; `mlx_unload` (the control the UI does have) frees the
+ // resident model and leaves the server up. The line used to say "same
+ // mechanism as the Stop button" — there was no Stop button, and the
+ // `mlx_stop` that described one had no bridge and no caller (KF-19,
+ // removed 01.09.2026).
#[cfg(target_os = "macos")]
{
crate::process_util::kill_listeners_on_port(crate::commands::mlx::MLX_PORT);
diff --git a/src-tauri/src/test_support.rs b/src-tauri/src/test_support.rs
index a6449ab5..09a54de5 100644
--- a/src-tauri/src/test_support.rs
+++ b/src-tauri/src/test_support.rs
@@ -382,6 +382,21 @@ pub(crate) fn park_binary() -> PathBuf {
/// caller only ever asserts on a snapshot that passed. Between the check and the
/// assertion there is no clock, no syscall and no other thread — the assertions
/// are a pure function of data already in hand.
+///
+/// ── The third check, added 01.09.2026 ──
+///
+/// `pid` must also CARRY ITS COMMAND LINE. Both callers exist to assert on argv,
+/// and being listed is not the same as being readable: on macOS the argv of
+/// another process comes from a separate `KERN_PROCARGS2` read, and a child that
+/// has forked but not finished `exec` is in the table with an EMPTY `cmd()`.
+/// Measured under six concurrent copies of the suite, ten rounds:
+/// `the_call_does_not_block_for_the_grace_period` failed 2 of 60 runs on exactly
+/// that — `argv=[]` for a `sleep 40` that was perfectly alive a moment later.
+///
+/// Putting it here rather than in each caller is deliberate: the other caller,
+/// `the_scan_finds_a_real_process_by_the_argv_lu_would_have_used`, has the same
+/// window and had simply not been unlucky yet. A table whose subject has no argv
+/// is not a table this function should hand out.
#[cfg(unix)]
pub(crate) fn checked_table(pid: u32) -> Result<sysinfo::System, String> {
use std::time::{Duration, Instant};
@@ -389,11 +404,13 @@ pub(crate) fn checked_table(pid: u32) -> Result<sysinfo::System, String> {
let deadline = Instant::now() + Duration::from_secs(10);
let mut attempts = 0usize;
let mut blind = 0usize;
+ let mut speechless = 0usize;
loop {
if Instant::now() >= deadline {
return Err(format!(
"no usable process table in 10s ({attempts} attempts, {blind} of them \
- without this test's own process in them). That is the TEST ENVIRONMENT, \
+ without this test's own process in them, {speechless} with pid {pid} \
+ listed but carrying no command line). That is the TEST ENVIRONMENT, \
not the code under test."
));
}
@@ -408,9 +425,13 @@ pub(crate) fn checked_table(pid: u32) -> Result<sysinfo::System, String> {
blind += 1;
continue;
}
- if sys.process(sysinfo::Pid::from_u32(pid)).is_none() {
+ let Some(subject) = sys.process(sysinfo::Pid::from_u32(pid)) else {
blind += 1;
continue;
+ };
+ if crate::process_util::cmdline_of(subject).is_empty() {
+ speechless += 1;
+ continue;
}
return Ok(sys);
}