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
tech(T-39/T-61/T-65/T-68/T-72): eine Prozesstabelle, ein Kill-Weg, keine stillen Ausreden
Davidc57733223798
diff --git a/src-tauri/src/commands/engine.rs b/src-tauri/src/commands/engine.rsindex 4246069d..0db95afa 100644--- a/src-tauri/src/commands/engine.rs+++ b/src-tauri/src/commands/engine.rs@@ -827,8 +827,16 @@ fn start_bundled_engine_blocking(// cache for memory — llama-server with `-ngl 999` loses as a CUDA OOM// (RTX 5080 field report: ACE-Step → chat = crash until app restart). Ask// ComfyUI to drop its cache first; best-effort no-op when it isn't running.- if crate::commands::process::free_comfyui_memory() {- println!("[Engine] asked ComfyUI to free VRAM before engine start");+ // T-65: the address comes from AppState (user-configured port/host), and a+ // ComfyUI that is not this machine's is reported as such instead of+ // reading like an idle one.+ match crate::commands::process::free_comfyui_memory(state) {+ r if r.released() => println!("[Engine] asked ComfyUI to free VRAM before engine start"),+ r => {+ if let Some((target, why)) = r.not_responsible() {+ println!("[Engine] did not free ComfyUI VRAM ({target}) — {why}");+ }+ }}// Ollama fights for the same VRAM and, unlike ComfyUI, its freshly-used@@ -836,8 +844,15 @@ fn start_bundled_engine_blocking(// just-active 14B loaded, this engine's own load crawled through paging and// blew the health budget (live repro 2026-07-31; an IDLE model gets evicted// fine). Evict via keep_alive:0 — Ollama reloads lazily on its next use.- if crate::commands::process::offload_ollama_loaded_models() {- println!("[Engine] asked Ollama to evict loaded models before engine start");+ match crate::commands::process::offload_ollama_loaded_models(state) {+ r if r.released() => {+ println!("[Engine] asked Ollama to evict loaded models before engine start")+ }+ r => {+ if let Some((target, why)) = r.not_responsible() {+ println!("[Engine] did not evict Ollama models ({target}) — {why}");+ }+ }}let binary = resolve_engine_binary(app).ok_or_else(|| {diff --git a/src-tauri/src/commands/gguf.rs b/src-tauri/src/commands/gguf.rsindex c50ad14a..ca082d4e 100644--- a/src-tauri/src/commands/gguf.rs+++ b/src-tauri/src/commands/gguf.rs@@ -260,13 +260,145 @@ mod tests {assert_eq!(context_length(t.to_str().unwrap()), None);}+ // ── The one check in this file against a GGUF this module did not write ──+ //+ // Everything above parses bytes produced by `W`, the writer twenty lines+ // up. That cannot catch the failure both halves share a wrong assumption+ // about; only a file llama.cpp produced can. So this probe is worth+ // keeping — but the way it was written, it was worth nothing:+ //+ // let home = std::env::var("HOME").unwrap_or_default();+ // let p = format!("{home}/Library/Application Support/Locally \+ // Uncensored/models/Qwen2.5-0.5B-Instruct-Q8_0.gguf");+ // if Path::new(&p).exists() { assert_eq!(...) }+ //+ // Two things were wrong with that.+ //+ // 1. It built the path by hand, so it was macOS-only and it named the+ // directory of the PRODUCTION app directly instead of going through+ // `os_paths`, which is the single place that knows the app directory+ // and, on this branch, its isolation suffix. Reading is not a violation+ // — but a hand-built copy of a path is how a WRITE ends up in the+ // user's real data later.+ // 2. It turned itself off in silence. On every machine without that exact+ // file — CI, Windows, Linux, a fresh checkout — it passed while+ // asserting nothing, and said so nowhere. A test that quietly checks+ // nothing is worse than a red one: the red one gets fixed.+ //+ // What replaces it: the path build is pinned by a test that always runs+ // and always asserts, and the file-dependent half announces its skip on a+ // stream the test harness does not capture.++ /// The model the built-in engine ships with. Its trained context length is+ /// a property of the file, not of this repo.+ const REAL_MODEL_FILE: &str = "Qwen2.5-0.5B-Instruct-Q8_0.gguf";+ const REAL_MODEL_CONTEXT: u32 = 32768;++ /// The production app's directory name.+ ///+ /// A literal on purpose, and the only one in this file: derived from+ /// `APP_DISPLAY_DIR` it would follow whatever that constant becomes, and+ /// the assertion below — that this build's directory is NOT the+ /// production one — would then be checking itself. Same reasoning as+ /// `NAMEN_DER_ECHTEN_APP` in `app_identity`.+ const PRODUCTION_DISPLAY_DIR: &str = "Locally Uncensored";++ /// Where a real GGUF may be found, most-owned first.+ ///+ /// 1. This build's own model directory, straight from `os_paths`.+ /// 2. The production install's model directory — same parent, same+ /// `models` leaf, directory name without this branch's suffix. READ+ /// ONLY: on a dev machine that is the only place a real model is, and+ /// the isolated build never downloads one.+ fn real_gguf_candidates() -> Vec<std::path::PathBuf> {+ let own = crate::os_paths::builtin_models_dir();+ let mut out = vec![own.join(REAL_MODEL_FILE)];+ // <data_dir>/<APP_DISPLAY_DIR>/models -> <data_dir>/<production>/models+ if let Some(data_dir) = own.parent().and_then(|p| p.parent()) {+ out.push(+ data_dir+ .join(PRODUCTION_DISPLAY_DIR)+ .join("models")+ .join(REAL_MODEL_FILE),+ );+ }+ out+ }++ /// Always runs, always asserts: the probe looks where `os_paths` says, and+ /// this build's own directory is not the production one.#[test]- fn real_bundled_gguf_if_present() {- // Best-effort against the dev machine's local test model; absent in CI.- let home = std::env::var("HOME").unwrap_or_default();- let p = format!("{home}/Library/Application Support/Locally Uncensored/models/Qwen2.5-0.5B-Instruct-Q8_0.gguf");- if std::path::Path::new(&p).exists() {- assert_eq!(super::context_length(&p), Some(32768));+ fn the_real_gguf_probe_goes_through_the_central_path_builder() {+ use crate::app_identity::APP_DISPLAY_DIR;++ let candidates = real_gguf_candidates();+ assert_eq!(candidates.len(), 2, "{candidates:?}");++ // #1 is os_paths' own answer, not a string built here.+ assert_eq!(+ candidates[0],+ crate::os_paths::builtin_models_dir().join(REAL_MODEL_FILE)+ );++ // The isolation suffix is real and this build carries it.+ assert_ne!(+ APP_DISPLAY_DIR, PRODUCTION_DISPLAY_DIR,+ "this build reads and would write the production app's model directory"+ );+ let own_dir = candidates[0]+ .parent()+ .and_then(|p| p.parent())+ .and_then(|p| p.file_name())+ .expect("no app directory in the built path");+ assert_eq!(own_dir, APP_DISPLAY_DIR);++ // #2 differs from #1 in exactly that one component.+ let prod_dir = candidates[1]+ .parent()+ .and_then(|p| p.parent())+ .and_then(|p| p.file_name())+ .expect("no app directory in the production path");+ assert_eq!(prod_dir, PRODUCTION_DISPLAY_DIR);+ assert_eq!(+ candidates[0].parent().and_then(|p| p.parent()).and_then(|p| p.parent()),+ candidates[1].parent().and_then(|p| p.parent()).and_then(|p| p.parent()),+ "the two candidates are not siblings under the same data dir"+ );+ assert!(candidates.iter().all(|c| c.ends_with(REAL_MODEL_FILE)));+ }++ /// Parses a real GGUF when one is on this machine — and says out loud when+ /// there is none, instead of passing in silence.+ ///+ /// The skip notice is written straight to `stderr` rather than through+ /// `eprintln!`: libtest's capture swaps the sink the print macros use, so+ /// a macro line from a PASSING test is swallowed, while a direct write to+ /// the handle reaches the terminal. Verified on this machine, 2026-09-01.+ #[test]+ fn a_real_gguf_parses_or_the_run_says_why_it_could_not() {+ let candidates = real_gguf_candidates();+ match candidates.iter().find(|p| p.exists()) {+ Some(path) => {+ assert_eq!(+ context_length(path.to_str().expect("non-UTF-8 model path")),+ Some(REAL_MODEL_CONTEXT),+ "parsing the real model at {} gave the wrong context length",+ path.display()+ );+ }+ None => {+ use std::io::Write;+ let looked: Vec<String> =+ candidates.iter().map(|p| p.display().to_string()).collect();+ let _ = writeln!(+ std::io::stderr(),+ "\n SKIPPED gguf::a_real_gguf_parses_or_the_run_says_why_it_could_not\n \+ reason: no real {REAL_MODEL_FILE} on this machine, so the parser was \+ not checked against a file llama.cpp produced.\n looked at:\n {}\n \+ to run it for real, download the built-in engine's model once.\n",+ looked.join("\n ")+ );+ }}}}diff --git a/src-tauri/src/commands/install.rs b/src-tauri/src/commands/install.rsindex 506fd4ae..1899b8b9 100644--- a/src-tauri/src/commands/install.rs+++ b/src-tauri/src/commands/install.rs@@ -2261,8 +2261,8 @@ const MIN_INSTALLER_BYTES: u64 = 1_000_000;/// SHA-256 of the LM Studio installer at [`LMSTUDIO_INSTALLER_URL`].////// That URL is version-pinned and immutable (`0.3.16-6`), so its bytes never-/// change and a digest here would be a free integrity guarantee for a ~570 MB-/// executable LU runs with `/S`.+/// change and a digest here would be an integrity guarantee for an executable+/// LU runs with `/S`.////// It is `None`, and it has to stay `None` until somebody fills it with a/// digest they measured from that exact file. A guessed or mistyped value does@@ -2275,8 +2275,15 @@ const MIN_INSTALLER_BYTES: u64 = 1_000_000;/// certutil -hashfile LM-Studio-0.3.16-6-x64.exe SHA256/// ```///-/// Until then the size and Authenticode checks below are what stands between-/// the user and an unverified executable.+/// The vendor publishes no checksum to copy instead: `<url>.sha256`,+/// `.sha256sum`, `.SHA256`, `.checksum` and the directory index all answer 404+/// (checked 2026-09-01). So the digest can only come from the file itself, and+/// a digest measured over the same unauthenticated channel the app downloads+/// through is trust-on-first-use: it pins against a LATER substitution at that+/// URL, not against a download that was already tampered with.+///+/// Until then the size checks and the Authenticode check below are what stands+/// between the user and an unverified executable.////// Ollama's installer gets no pin at all and cannot: its URL/// (`ollama.com/download/OllamaSetup.exe`) always serves the current release,@@ -2284,6 +2291,31 @@ const MIN_INSTALLER_BYTES: u64 = 1_000_000;/// answer available there.const LMSTUDIO_INSTALLER_SHA256: Option<&str> = None;+/// Exact byte count of the file at [`LMSTUDIO_INSTALLER_URL`].+///+/// The half of the pin that CAN be established without the file: the vendor's+/// own server reports it in one header request, so anyone can re-check it in a+/// second instead of moving 211 MiB.+///+/// ```text+/// curl -sI https://installers.lmstudio.ai/win32/x64/0.3.16-6/LM-Studio-0.3.16-6-x64.exe+/// ```+///+/// Measured 2026-09-01: `content-length: 221768208`, `last-modified: Fri, 23+/// May 2025 22:14:17 GMT`, `etag: "4c5f34448d76416730ec408b05a54270"` (32 hex+/// chars, no `-N` part suffix — a single-part object). A `last-modified` 15+/// months in the past under a version-pinned path is the evidence that this URL+/// is immutable; this constant is what turns that evidence from an ASSUMPTION+/// into something the code enforces.+///+/// It is deliberately much weaker than a digest — it catches a truncated or+/// substituted transfer of a different length, not a same-length forgery — and+/// it carries the same maintenance duty: if LM Studio ever re-uploads different+/// bytes here, the install fails loudly instead of silently running new,+/// unchecked bytes. That is the intended direction. `LMSTUDIO_INSTALLER_URL`+/// and this constant have to move together.+const LMSTUDIO_INSTALLER_BYTES: Option<u64> = Some(221_768_208);+/// Hex SHA-256 of a file, streamed in chunks — a 570 MB installer must not/// need 570 MB of memory to be checked.pub(crate) fn sha256_file(path: &Path) -> Result<String, String> {@@ -2404,15 +2436,35 @@ fn authenticode_verdict(path: &Path) -> SignatureVerdict {}}+/// Is this file exactly the size the immutable URL is known to serve?+///+/// Only ever called for a URL whose bytes are supposed to never change. A+/// mismatch means one of two things and both are refusals: the transfer was+/// cut short / rewritten, or the vendor replaced a file LU treats as fixed.+pub(crate) fn installer_exact_size_verdict(expected: u64, actual: u64, label: &str) -> Result<(), String> {+ if expected == actual {+ return Ok(());+ }+ Err(format!(+ "The downloaded {label} installer is {actual} bytes; the version-pinned \+ download URL is known to serve exactly {expected}. Either the transfer \+ was altered or cut short, or the vendor replaced a file at a URL that \+ is supposed to be immutable. LU will not run it — install {label} from \+ the vendor's own site instead."+ ))+}+/// Everything that has to be true before LU executes a file it downloaded:-/// it is big enough to be an installer, it matches its pinned digest if one-/// exists, and on Windows it carries a valid Authenticode signature.+/// it is big enough to be an installer, it is exactly the size an immutable+/// URL is known to serve (when there is one), it matches its pinned digest if+/// one exists, and on Windows it carries a valid Authenticode signature.////// `label` names the product in the error text — the user has to know which/// download to fetch by hand when LU refuses.fn verify_downloaded_installer(path: &Path,expected_sha256: Option<&str>,+ expected_bytes: Option<u64>,label: &str,) -> Result<(), String> {let size = fs::metadata(path)@@ -2420,6 +2472,11 @@ fn verify_downloaded_installer(.len();installer_size_verdict(size)?;+ if let Some(expected) = expected_bytes {+ installer_exact_size_verdict(expected, size, label)?;+ info!(label, bytes = size, "installer matched its pinned size");+ }+if let Some(pin) = expected_sha256 {let actual = sha256_file(path)?;if !digest_matches(pin, &actual) {@@ -2525,7 +2582,7 @@ fn install_ollama_windows_impl<F: Fn(&str, &str)>(// OI-8: verified before it is executed. Ollama's URL always serves the// current release, so there is no immutable digest to pin here — the size// and Authenticode checks are the whole answer available.- if let Err(e) = verify_downloaded_installer(&installer_path, None, "Ollama") {+ if let Err(e) = verify_downloaded_installer(&installer_path, None, None, "Ollama") {let _ = fs::remove_file(&installer_path);error!(error = %e, "refused to execute an unverified Ollama installer");update("error", &e);@@ -3075,6 +3132,7 @@ pub fn install_lmstudio(state: State<'_, AppState>) -> Result<serde_json::Value,if let Err(e) = verify_downloaded_installer(&installer_path,LMSTUDIO_INSTALLER_SHA256,+ LMSTUDIO_INSTALLER_BYTES,"LM Studio",) {let _ = fs::remove_file(&installer_path);@@ -4749,7 +4807,7 @@ mod tests {let tmp = tempfile::tempdir().unwrap();let f = tmp.path().join("Setup.exe");std::fs::write(&f, b"<html>captive portal</html>").unwrap();- let err = verify_downloaded_installer(&f, None, "LM Studio").unwrap_err();+ let err = verify_downloaded_installer(&f, None, None, "LM Studio").unwrap_err();assert!(err.to_lowercase().contains("too small"), "{err}");}@@ -4758,12 +4816,71 @@ mod tests {let tmp = tempfile::tempdir().unwrap();let f = tmp.path().join("Setup.exe");std::fs::write(&f, vec![0u8; MIN_INSTALLER_BYTES as usize + 1]).unwrap();- let err = verify_downloaded_installer(&f, Some("deadbeef"), "LM Studio").unwrap_err();+ let err = verify_downloaded_installer(&f, Some("deadbeef"), None, "LM Studio").unwrap_err();assert!(err.contains("deadbeef"), "{err}");assert!(err.contains("expected") && err.contains("got"), "{err}");assert!(err.contains("LM Studio"), "{err}");}+ /// T-72 — the size pin for the immutable installer URL.+ ///+ /// WHAT THIS DOES NOT PROVE: that 221_768_208 is still what the vendor+ /// serves. That is one header request away (`curl -sI <url>`), and the+ /// constant's doc comment carries both the command and the date it was+ /// last measured. No test can hold that for you without going to the+ /// network on every run.+ #[test]+ fn a_file_of_the_wrong_length_from_the_immutable_url_is_refused() {+ let expected = LMSTUDIO_INSTALLER_BYTES.expect("the size pin was removed");+ let tmp = tempfile::tempdir().unwrap();+ let f = tmp.path().join("LMStudioSetup.exe");++ // Big enough to clear the generic floor, wrong for THIS url.+ std::fs::write(&f, vec![0u8; MIN_INSTALLER_BYTES as usize + 7]).unwrap();+ let err = verify_downloaded_installer(&f, None, Some(expected), "LM Studio").unwrap_err();+ assert!(err.contains(&expected.to_string()), "{err}");+ assert!(err.contains("immutable"), "{err}");+ assert!(err.contains("LM Studio"), "{err}");++ // The generic floor alone would have let it through — that is the gap+ // this pin closes.+ assert!(installer_size_verdict(MIN_INSTALLER_BYTES + 7).is_ok());+ }++ #[test]+ fn the_exact_size_rule_passes_only_on_an_exact_match() {+ assert!(installer_exact_size_verdict(221_768_208, 221_768_208, "LM Studio").is_ok());+ assert!(installer_exact_size_verdict(221_768_208, 221_768_207, "LM Studio").is_err());+ assert!(installer_exact_size_verdict(221_768_208, 221_768_209, "LM Studio").is_err());+ assert!(installer_exact_size_verdict(221_768_208, 0, "LM Studio").is_err());+ }++ /// Ollama's URL always serves the current release, so pinning either its+ /// size or its digest would break the install on every Ollama release.+ /// Neither may be passed for it.+ #[test]+ fn the_moving_ollama_url_is_never_pinned() {+ const SRC: &str = include_str!("install.rs");+ assert!(+ SRC.contains(concat!("verify_downloaded_installer", "(&installer_path, None, None, \"Ollama\")")),+ "the Ollama installer path acquired a pin it cannot keep"+ );+ }++ /// The URL and the size are one fact in two places. Moving one without the+ /// other is the failure mode this pin introduces, so it gets its own guard.+ #[test]+ fn the_pinned_url_and_the_pinned_size_belong_to_the_same_version() {+ assert!(+ LMSTUDIO_INSTALLER_URL.contains("0.3.16-6"),+ "the installer URL moved: re-measure LMSTUDIO_INSTALLER_BYTES with \+ `curl -sI {LMSTUDIO_INSTALLER_URL}` and update it in the same commit"+ );+ // A plausible installer size, not a placeholder someone left behind.+ let bytes = LMSTUDIO_INSTALLER_BYTES.expect("the size pin was removed");+ assert!(bytes > MIN_INSTALLER_BYTES, "the size pin is below the generic floor");+ }+#[test]fn the_lmstudio_pin_is_either_absent_or_a_real_sha256() {// Guard rail for whoever fills LMSTUDIO_INSTALLER_SHA256 in: adiff --git a/src-tauri/src/commands/process.rs b/src-tauri/src/commands/process.rsindex 02b2a91f..a15fdb91 100644--- a/src-tauri/src/commands/process.rs+++ b/src-tauri/src/commands/process.rs@@ -1432,7 +1432,18 @@ fn start_comfyui_blocking(state: &AppState) -> Result<serde_json::Value, String>let port = *state.comfy_port.lock().unwrap();if is_comfyui_running_on_port(port) {- return Ok(serde_json::json!({"status": "already_running"}));+ // T-68: say WHOSE ComfyUI that is. "already_running" alone is what let+ // an orphan of a hard-killed session look identical to a ComfyUI the+ // user started — and Stop behaved as if both were untouchable.+ let orphan = find_orphaned_comfyui(port);+ if let Some(pid) = orphan {+ println!("[ComfyUI] Already running on port {port} — orphan of an earlier session (pid {pid}); Stop can adopt it");+ info!(pid = pid, port = port, "comfyui orphan found on start");+ }+ return Ok(serde_json::json!({+ "status": "already_running",+ "adoptable": orphan.is_some(),+ }));}// The port probe alone misses a ComfyUI that is STARTING: it imports for@@ -1720,6 +1731,154 @@ pub async fn stop_comfyui(app: tauri::AppHandle) -> Result<serde_json::Value, St.map_err(|e| format!("stop_comfyui task: {e}"))?}+// ── T-68: the orphan a hard kill leaves behind ──────────────────────────────+//+// `tie_child_to_app_lifetime` prevents orphans on Windows (kill-on-close job+// object) and the graceful shutdown path covers the normal quit. Neither+// covers the case in the finding: LU is SIGKILLed (or the box loses power on+// the app, or a dev session is hard-stopped), the ComfyUI child is reparented+// to init and keeps the GPU. On the next launch `state.comfy_process` is+// `None`, so the port probe reports "Already running", the status panel says+// running — and Stop returned `{"status":"not_running"}` and did nothing, for+// as long as that install lived. That is the read-only adoption the audit+// names: LU could see the orphan and not touch it.+//+// The missing half is a way back to control. `find_orphaned_comfyui` looks for+// a ComfyUI process that LU itself started, on LU's own configured port, and+// `stop_comfyui` kills that tree instead of lying.++/// Is this command line a ComfyUI that LU started on `port`?+///+/// Three conditions, all of them required:+///+/// * it is a ComfyUI (`main.py`, the only entry point LU ever launches),+/// * it carries `--enable-cors-header`, which LU passes on EVERY start and a+/// user-managed ComfyUI does not — the "Fix CORS" button in Settings exists+/// precisely because a hand-started ComfyUI lacks it,+/// * it serves exactly `port`, not a port whose number merely starts the same+/// way (`--port 8188` must not match a ComfyUI on 81880).+///+/// Narrow on purpose: this decides whether LU may kill a process it did not+/// spawn in this run. A ComfyUI the user started themselves fails the CORS+/// test and is left alone, and Stop says so instead of killing it.+///+/// Pure, so the rule is testable without a process table.+pub(crate) fn is_lu_started_comfyui(cmd: &[String], port: u16) -> bool {+ let joined = cmd.join(" ");+ let lower = joined.to_ascii_lowercase();+ if !lower.contains("main.py") || !lower.contains("--enable-cors-header") {+ return false;+ }+ cmdline_names_port(&lower, port)+}++/// Does this command line pass exactly `port` as `--port`?+///+/// `contains("--port 8188")` is also true of `--port 81880`, and this decides+/// a kill — so the whole digit run has to equal the port. Both spellings+/// (`--port 8188` and `--port=8188`) are accepted because argv joining is not+/// the only way this string can be produced.+fn cmdline_names_port(lower: &str, port: u16) -> bool {+ let wanted = port.to_string();+ for sep in ["--port ", "--port="] {+ let mut rest = lower;+ while let Some(at) = rest.find(sep) {+ let tail = &rest[at + sep.len()..];+ let digits: String = tail.chars().take_while(char::is_ascii_digit).collect();+ if digits == wanted {+ return true;+ }+ rest = &rest[at + sep.len()..];+ }+ }+ false+}++/// The pid of an LU-started ComfyUI on `port` that this process has no handle+/// for. `None` when nothing matches — including when the ComfyUI on that port+/// belongs to the user.+pub(crate) fn find_orphaned_comfyui(port: u16) -> Option<u32> {+ // The table MUST come from this helper: a bare `refresh_processes` does not+ // fetch command lines, and every match here would silently be against "".+ // See the note above `process_table_with_cmdlines`.+ let sys = crate::process_util::process_table_with_cmdlines();+ let own = std::process::id();+ for (pid, process) in sys.processes() {+ let pid = pid.as_u32();+ if pid == own {+ continue;+ }+ if is_lu_started_comfyui(&crate::process_util::cmdline_of(process), port) {+ return Some(pid);+ }+ }+ None+}++// ── The same shape, one step out: a child that outlives its launcher ────────+//+// `tauri-plugin-shell`'s `CommandChild::kill` is `SharedChild::kill`, i.e. one+// signal to the DIRECT child (verified in tauri-plugin-shell-2.3.5,+// `src/process/mod.rs:78`). For an MCP server the frontend starts as+// `npx -y <package>` (Windows: `npx.cmd`, which runs through cmd.exe), the+// direct child is the launcher and the `node` process behind it is a+// grandchild — so `child.kill()` reaps the shim and leaves the server running.+//+// That is T-68's sachverhalt one level out, so it gets T-68's machinery rather+// than a second kill path: `process_util::kill_pid_tree` walks the tree, and+// the command below is the door the frontend uses to reach it.++/// May this app kill `pid`?+///+/// Only a process inside THIS app's own subtree. The pid is an argument from+/// the frontend, and a command that kills any pid it is handed is a much+/// bigger hole than the orphan it was meant to close — the caller could stop+/// the user's editor, or LU itself.+///+/// Pure so the rule is testable without a process table.+pub(crate) fn may_kill_pid(pid: u32, own: u32, own_descendants: &[u32]) -> Result<(), String> {+ if pid == 0 || pid == own {+ return Err(format!("refused: pid {pid} is this app itself"));+ }+ if !own_descendants.contains(&pid) {+ return Err(format!(+ "refused: pid {pid} is not a process this app started (it may have already \+ exited, in which case its own children are init's now — kill the tree \+ INSTEAD of the child, not after it)"+ ));+ }+ Ok(())+}++/// Kill a process tree this app spawned, addressed by the pid of its root.+///+/// ORDERING, and it matters: call this INSTEAD of the shell plugin's+/// `child.kill()`, never after it. Once the direct child is dead its own+/// children are reparented to init and are no longer this app's descendants —+/// the guard above will then (correctly) refuse, and the grandchild survives+/// exactly as before.+#[tauri::command]+pub async fn kill_process_tree(pid: u32) -> Result<serde_json::Value, String> {+ tokio::task::spawn_blocking(move || kill_process_tree_blocking(pid))+ .await+ .map_err(|e| format!("kill_process_tree task: {e}"))?+}++pub(crate) fn kill_process_tree_blocking(pid: u32) -> Result<serde_json::Value, String> {+ use sysinfo::{ProcessesToUpdate, System};+ let own = std::process::id();+ let mut sys = System::new();+ sys.refresh_processes(ProcessesToUpdate::All, true);+ let mine = crate::commands::shell::descendants(own, &sys);+ may_kill_pid(pid, own, &mine)?;++ let tree = crate::commands::shell::descendants(pid, &sys).len() + 1;+ println!("[Process] killing tree of pid {pid} ({tree} process(es))");+ info!(pid = pid, processes = tree, "killing a spawned process tree");+ crate::process_util::kill_pid_tree(pid);+ Ok(serde_json::json!({ "killed": true, "pid": pid, "processes": tree }))+}+fn stop_comfyui_blocking(state: &AppState) -> Result<serde_json::Value, String> {let mut proc = state.comfy_process.lock().unwrap();if let Some(ref mut child) = *proc {@@ -1741,9 +1900,53 @@ fn stop_comfyui_blocking(state: &AppState) -> Result<serde_json::Value, String>*state.comfy_start_at.lock().unwrap() = None;println!("[ComfyUI] Stopped");info!(pid = pid, "comfyui stopped");- Ok(serde_json::json!({"status": "stopped"}))- } else {- Ok(serde_json::json!({"status": "not_running"}))+ return Ok(serde_json::json!({"status": "stopped"}));+ }+ drop(proc);++ // No handle. Before 2.6.7 this was the end of the function and Stop was a+ // no-op — see the T-68 note above.+ let host = state+ .comfy_host+ .lock()+ .map(|g| g.clone())+ .unwrap_or_else(|_| "localhost".to_string());+ if !is_local_host(&host) {+ // A remote ComfyUI has never been ours to stop, and saying+ // "not_running" about a server that IS running was the same lie in a+ // smaller size.+ return Ok(serde_json::json!({+ "status": "remote",+ "host": host,+ "message": "ComfyUI runs on another host — stop it on that machine."+ }));+ }+ let port = *state.comfy_port.lock().unwrap();+ if !is_comfyui_running_on_port(port) {+ return Ok(serde_json::json!({"status": "not_running"}));+ }++ // Something IS serving ComfyUI on our port and it is not a child of this+ // run. Adopt it only if LU started it (see `is_lu_started_comfyui`).+ match find_orphaned_comfyui(port) {+ Some(pid) => {+ println!("[ComfyUI] Adopting orphan pid {pid} on port {port} and stopping it");+ info!(pid = pid, port = port, "comfyui orphan adopted and stopped");+ crate::process_util::kill_pid_tree(pid);+ *state.comfy_start_at.lock().unwrap() = None;+ Ok(serde_json::json!({"status": "stopped", "adopted": true, "pid": pid}))+ }+ None => {+ // A ComfyUI the user runs themselves. Killing it would be LU+ // reaching outside its own process tree; saying "not_running"+ // would be false. Say what is actually true.+ println!("[ComfyUI] Port {port} is served by a ComfyUI this app did not start");+ Ok(serde_json::json!({+ "status": "not_ours",+ "port": port,+ "message": "A ComfyUI this app did not start is serving that port. Stop it where you started it."+ }))+ }}}@@ -2230,7 +2433,15 @@ pub fn auto_start_comfyui(state: &AppState) {let port = *state.comfy_port.lock().unwrap();if is_comfyui_running_on_port(port) {- println!("[ComfyUI] Already running on port {}", port);+ // T-68: a ComfyUI on our port at launch is either the user's own or an+ // orphan this app left behind when it was killed. Naming which one in+ // the log is what makes a later "Stop did nothing" diagnosable.+ match find_orphaned_comfyui(port) {+ Some(pid) => println!(+ "[ComfyUI] Already running on port {port} — orphan of an earlier session (pid {pid}); Stop can adopt it"+ ),+ None => println!("[ComfyUI] Already running on port {} (not started by this app)", port),+ }return;}@@ -2837,44 +3048,199 @@ pub(crate) fn offload_local_models_blocking(state: &AppState, include_comfyui: Ofreed.push("bundled-embed");}+ // T-65: `not_ours` carries the backends LU did NOT free and why. Before,+ // both of these returned a bare `false` for "nothing was loaded" and for+ // "that address is not mine", and the caller was told the same thing in+ // both cases. The result now says which it was.+ let mut not_ours: Vec<serde_json::Value> = Vec::new();+ let mut note = |backend: &str, outcome: &VramRelease| {+ if let Some((target, why)) = outcome.not_responsible() {+ println!("[Offload] {backend}: not this app's to free ({target}) — {why}");+ not_ours.push(serde_json::json!({+ "backend": backend,+ "target": target,+ "why": why,+ }));+ }+ };+// 3) Ollama — keep `serve` up (cheap, idle) but evict every loaded model.- if offload_ollama_loaded_models() {+ let ollama = offload_ollama_loaded_models(state);+ if ollama.released() {freed.push("ollama");}+ note("ollama", &ollama);// 4) ComfyUI — free VRAM/RAM without killing the server, so the next local// render just reloads the checkpoint (no slow process restart). Skipped// when a local render is the caller (it keeps its own checkpoint cached).- if free_comfy && free_comfyui_memory() {- freed.push("comfyui");+ if free_comfy {+ let comfy = free_comfyui_memory(state);+ if comfy.released() {+ freed.push("comfyui");+ }+ note("comfyui", &comfy);+ }++ println!(+ "[Offload] released local model backends (comfyui={}): {:?}; not ours: {}",+ free_comfy,+ freed,+ not_ours.len()+ );+ Ok(serde_json::json!({ "offloaded": freed, "notOurs": not_ours }))+}++// ── T-65: the make-room-for-VRAM step, at the address the app actually uses ──+//+// Both helpers below used to hardcode `http://localhost:8188` and+// `http://localhost:11434`, so on a user-configured ComfyUI port or a+// non-default Ollama base they asked a machine nobody was listening on. The+// address is not a second source of truth to invent: `AppState::comfy_host` /+// `comfy_port` (config.json, `set_comfyui_port`) and `AppState::ollama_base`+// (config.json `ollama_base`, then `OLLAMA_HOST`, then the default — see+// `state::load_ollama_base`) already are that source, and every other caller in+// the app reads them. These now do too.+//+// The second half of the finding is the return type. `bool` made "the backend+// let nothing go" and "LU asked an address it does not own" the same answer,+// `false` — so a user on a custom port got the exact silence a user with an+// idle backend got. Fixing the address without fixing that would only move the+// silence one case further out: a ComfyUI on another machine still holds VRAM+// that freeing cannot help with, and that has to READ as "not LU's to free",+// not as "nothing found".++/// The outcome of asking one backend to let go of its memory.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) enum VramRelease {+ /// The backend answered and released something.+ Released,+ /// The backend answered; it was holding nothing to release.+ NothingLoaded,+ /// LU did not release anything and this memory is not LU's to free —+ /// the backend is configured on another machine, or nothing answered at+ /// the address LU owns.+ NotResponsible {+ /// The address that was asked (or would have been), for the log.+ target: String,+ why: String,+ },+}++impl VramRelease {+ /// Did this actually free memory? The one question the old `bool` could+ /// answer — kept, so callers that only branch on it stay readable.+ pub(crate) fn released(&self) -> bool {+ matches!(self, VramRelease::Released)+ }++ /// Short reason for the log / the command result. `None` when LU was+ /// responsible and did its part.+ pub(crate) fn not_responsible(&self) -> Option<(&str, &str)> {+ match self {+ VramRelease::NotResponsible { target, why } => Some((target, why)),+ _ => None,+ }+ }+}++/// Is this base URL pointed at this machine?+///+/// A backend on another host holds another machine's memory: asking it to+/// unload cannot make room here, so the honest answer is "not responsible"+/// rather than a silent no-op. Falls back to "not local" for a URL that will+/// not parse — refusing to guess is the safe direction here.+pub(crate) fn base_url_is_local(base: &str) -> bool {+ match url::Url::parse(base) {+ Ok(u) => match u.host_str() {+ // `host_str` keeps the brackets on an IPv6 literal (`[::1]`),+ // which `is_local_host` does not know about.+ Some(h) => is_local_host(h.trim_start_matches('[').trim_end_matches(']')),+ // No host at all (e.g. a bare path) — nothing to reach.+ None => false,+ },+ Err(_) => false,+ }+}++/// Where THIS machine's ComfyUI is, or why there is nothing here to free.+///+/// Split from the state read so the rule itself is testable without an+/// `AppState`: everything that decides an address lives in `_for`.+pub(crate) fn comfy_vram_target_for(host: &str, port: u16) -> Result<String, (String, String)> {+ let base = format!("http://{}:{}", host, port);+ if !is_local_host(host) {+ return Err((+ base,+ "ComfyUI is configured on another host, so its VRAM is not this machine's to free"+ .to_string(),+ ));}+ Ok(base)+}- println!("[Offload] released local model backends (comfyui={}): {:?}", free_comfy, freed);- Ok(serde_json::json!({ "offloaded": freed }))+pub(crate) fn comfy_vram_target(state: &AppState) -> Result<String, (String, String)> {+ let host = state+ .comfy_host+ .lock()+ .map(|g| g.clone())+ .unwrap_or_else(|_| "localhost".to_string());+ let port = state.comfy_port.lock().map(|g| *g).unwrap_or(8188);+ comfy_vram_target_for(&host, port)+}++/// Where THIS machine's Ollama is, or why there is nothing here to free.+pub(crate) fn ollama_vram_target_for(base: &str) -> Result<String, (String, String)> {+ if !base_url_is_local(base) {+ return Err((+ base.to_string(),+ "Ollama is configured on another host, so its RAM/VRAM is not this machine's to free"+ .to_string(),+ ));+ }+ Ok(base.trim_end_matches('/').to_string())+}++pub(crate) fn ollama_vram_target(state: &AppState) -> Result<String, (String, String)> {+ let base = state+ .ollama_base+ .lock()+ .map(|g| g.clone())+ .unwrap_or_else(|_| "http://localhost:11434".to_string());+ ollama_vram_target_for(&base)}/// Evict every model Ollama currently holds in memory via `keep_alive: 0`,/// leaving `ollama serve` running (idle serve is cheap). Best-effort.-pub(crate) fn offload_ollama_loaded_models() -> bool {+///+/// `base` comes from `AppState::ollama_base` via [`ollama_vram_target`] — see+/// the T-65 note above for why it is not a constant here.+pub(crate) fn offload_ollama_loaded_models_at(base: &str) -> VramRelease {+ let unreachable = |why: &str| VramRelease::NotResponsible {+ target: base.to_string(),+ why: why.to_string(),+ };let client = match reqwest::blocking::Client::builder().timeout(std::time::Duration::from_secs(2)).build(){Ok(c) => c,- Err(_) => return false,+ Err(e) => return unreachable(&format!("no HTTP client: {e}")),};let ps = match client- .get("http://localhost:11434/api/ps")+ .get(format!("{base}/api/ps")).send().ok().and_then(|r| r.json::<serde_json::Value>().ok()){Some(v) => v,- None => return false,+ None => return unreachable("nothing answered /api/ps there"),};+ // Ollama answered — from here on LU IS responsible, so "no models" is+ // NothingLoaded and not a shrug.let models = match ps.get("models").and_then(|m| m.as_array()) {Some(a) => a,- None => return false,+ None => return VramRelease::NothingLoaded,};let mut any = false;for m in models {@@ -2884,33 +3250,74 @@ pub(crate) fn offload_ollama_loaded_models() -> bool {.and_then(|n| n.as_str()){let _ = client- .post("http://localhost:11434/api/generate")+ .post(format!("{base}/api/generate")).json(&serde_json::json!({ "model": name, "keep_alive": 0 })).send();any = true;}}- any+ if any {+ VramRelease::Released+ } else {+ VramRelease::NothingLoaded+ }}/// Ask ComfyUI to unload checkpoints and free memory, keeping the server up so-/// the next local render reloads on demand. Best-effort (default port 8188).+/// the next local render reloads on demand. Best-effort./// Also used by the character trainer — on a 12 GB card a cached video/// checkpoint next door is the difference between training and CUDA OOM.-pub(crate) fn free_comfyui_memory() -> bool {+///+/// `base` comes from `AppState::comfy_host`/`comfy_port` via+/// [`comfy_vram_target`]; the port is user-configurable and the default 8188 is+/// only a default.+pub(crate) fn free_comfyui_memory_at(base: &str) -> VramRelease {let client = match reqwest::blocking::Client::builder().timeout(std::time::Duration::from_secs(2)).build(){Ok(c) => c,- Err(_) => return false,+ Err(e) => {+ return VramRelease::NotResponsible {+ target: base.to_string(),+ why: format!("no HTTP client: {e}"),+ }+ }};- client- .post("http://localhost:8188/free")+ match client+ .post(format!("{base}/free")).json(&serde_json::json!({ "unload_models": true, "free_memory": true })).send()- .map(|r| r.status().is_success())- .unwrap_or(false)+ {+ // ComfyUI answers 200 to /free whether or not anything was cached, so+ // there is no NothingLoaded to distinguish here — a 200 means it did+ // what it could.+ Ok(r) if r.status().is_success() => VramRelease::Released,+ Ok(r) => VramRelease::NotResponsible {+ target: base.to_string(),+ why: format!("/free answered HTTP {}", r.status().as_u16()),+ },+ Err(e) => VramRelease::NotResponsible {+ target: base.to_string(),+ why: format!("nothing answered /free there ({e})"),+ },+ }+}++/// State-aware wrappers: resolve the address first, then ask. A backend the+/// user put on another machine never gets asked and never reads as a failure.+pub(crate) fn free_comfyui_memory(state: &AppState) -> VramRelease {+ match comfy_vram_target(state) {+ Ok(base) => free_comfyui_memory_at(&base),+ Err((target, why)) => VramRelease::NotResponsible { target, why },+ }+}++pub(crate) fn offload_ollama_loaded_models(state: &AppState) -> VramRelease {+ match ollama_vram_target(state) {+ Ok(base) => offload_ollama_loaded_models_at(&base),+ Err((target, why)) => VramRelease::NotResponsible { target, why },+ }}#[cfg(test)]@@ -3114,3 +3521,442 @@ mod orphan_safety_tests {);}}++/// T-65 — the make-room-for-VRAM step must ask the address the user configured,+/// and must say which of "nothing to free" / "not mine to free" happened.+///+/// The two `_at` helpers are exercised against a REAL HTTP server on a real+/// loopback port (`127.0.0.1:0`, so never 8188 or 11434) — that is the whole+/// point: a test that only ever succeeds on the default port could not tell+/// the fix from the bug.+#[cfg(test)]+mod vram_release_tests {+ use super::*;+ use std::io::{BufRead, BufReader, Write};+ use std::net::TcpListener;+ use std::sync::mpsc;++ /// A one-shot HTTP server on an ephemeral port. Returns the base URL and a+ /// receiver that yields the request line + body of the first request.+ fn one_shot(status: &'static str, body: &'static str) -> (String, mpsc::Receiver<String>) {+ let listener = TcpListener::bind("127.0.0.1:0").expect("bind");+ let port = listener.local_addr().unwrap().port();+ let (tx, rx) = mpsc::channel();+ std::thread::spawn(move || {+ // Serve until the client is done with us; /api/ps is followed by+ // one /api/generate per loaded model.+ for stream in listener.incoming().take(4) {+ let Ok(mut stream) = stream else { break };+ let mut reader = BufReader::new(stream.try_clone().unwrap());+ let mut request_line = String::new();+ let _ = reader.read_line(&mut request_line);+ let mut len = 0usize;+ loop {+ let mut line = String::new();+ if reader.read_line(&mut line).unwrap_or(0) == 0 {+ break;+ }+ if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") {+ len = v.trim().parse().unwrap_or(0);+ }+ if line.trim().is_empty() {+ break;+ }+ }+ let mut payload = vec![0u8; len];+ if len > 0 {+ use std::io::Read;+ let _ = reader.read_exact(&mut payload);+ }+ let _ = tx.send(format!(+ "{} | {}",+ request_line.trim(),+ String::from_utf8_lossy(&payload)+ ));+ let _ = write!(+ stream,+ "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",+ body.len()+ );+ let _ = stream.flush();+ }+ });+ (format!("http://127.0.0.1:{port}"), rx)+ }++ /// A port with nothing behind it. Bind it, read the port, drop the+ /// listener — the OS will not hand it out again immediately.+ fn dead_port() -> u16 {+ let l = TcpListener::bind("127.0.0.1:0").expect("bind");+ l.local_addr().unwrap().port()+ }++ #[test]+ fn comfyui_is_asked_on_the_configured_port_not_8188() {+ let (base, rx) = one_shot("200 OK", "{}");+ assert!(!base.ends_with(":8188"), "the ephemeral port must not be the default");+ assert_eq!(free_comfyui_memory_at(&base), VramRelease::Released);+ let seen = rx.recv_timeout(std::time::Duration::from_secs(5)).expect("no request arrived");+ assert!(seen.starts_with("POST /free "), "{seen}");+ assert!(seen.contains("\"unload_models\":true"), "{seen}");+ }++ #[test]+ fn ollama_is_asked_on_the_configured_base_not_11434() {+ let (base, rx) = one_shot("200 OK", r#"{"models":[{"name":"qwen3:8b"}]}"#);+ assert!(!base.ends_with(":11434"), "the ephemeral port must not be the default");+ assert_eq!(offload_ollama_loaded_models_at(&base), VramRelease::Released);+ let ps = rx.recv_timeout(std::time::Duration::from_secs(5)).expect("no /api/ps");+ assert!(ps.starts_with("GET /api/ps "), "{ps}");+ let evict = rx.recv_timeout(std::time::Duration::from_secs(5)).expect("no eviction");+ assert!(evict.starts_with("POST /api/generate "), "{evict}");+ assert!(evict.contains("\"keep_alive\":0"), "{evict}");+ assert!(evict.contains("qwen3:8b"), "{evict}");+ }++ /// The half of the finding the address fix alone does not close: a backend+ /// that answered and held nothing must NOT read the same as a backend LU+ /// could not ask.+ #[test]+ fn nothing_loaded_and_not_ours_are_different_answers() {+ let (base, _rx) = one_shot("200 OK", r#"{"models":[]}"#);+ assert_eq!(offload_ollama_loaded_models_at(&base), VramRelease::NothingLoaded);++ let dead = format!("http://127.0.0.1:{}", dead_port());+ let verdict = offload_ollama_loaded_models_at(&dead);+ let (target, why) = verdict+ .not_responsible()+ .unwrap_or_else(|| panic!("a dead port read as {verdict:?}"));+ assert_eq!(target, dead);+ assert!(!why.is_empty());+ assert!(!verdict.released());++ // Both are "did not free anything", and that is exactly why `bool`+ // was not enough.+ assert!(!VramRelease::NothingLoaded.released());+ assert_ne!(VramRelease::NothingLoaded, verdict);+ }++ #[test]+ fn a_comfyui_that_answers_with_an_error_is_not_a_success() {+ let (base, _rx) = one_shot("500 Internal Server Error", "boom");+ let verdict = free_comfyui_memory_at(&base);+ assert!(!verdict.released());+ assert!(verdict.not_responsible().unwrap().1.contains("500"), "{verdict:?}");+ }++ #[test]+ fn a_remote_backend_is_never_asked_and_says_so() {+ // ComfyUI on the LAN: its VRAM is another machine's.+ let (target, why) = comfy_vram_target_for("192.168.1.50", 8188).unwrap_err();+ assert_eq!(target, "http://192.168.1.50:8188");+ assert!(why.contains("another host"), "{why}");++ let (target, why) = ollama_vram_target_for("http://192.168.0.54:11434").unwrap_err();+ assert_eq!(target, "http://192.168.0.54:11434");+ assert!(why.contains("another host"), "{why}");+ }++ #[test]+ fn a_local_backend_on_a_custom_port_resolves_to_that_port() {+ assert_eq!(comfy_vram_target_for("localhost", 9999).unwrap(), "http://localhost:9999");+ assert_eq!(comfy_vram_target_for("127.0.0.1", 8189).unwrap(), "http://127.0.0.1:8189");+ assert_eq!(+ ollama_vram_target_for("http://127.0.0.1:12345").unwrap(),+ "http://127.0.0.1:12345"+ );+ // state::load_ollama_base normalises away the trailing slash, but a+ // hand-edited config.json can still carry one and `{base}/api/ps`+ // would then be a double slash.+ assert_eq!(+ ollama_vram_target_for("http://localhost:11434/").unwrap(),+ "http://localhost:11434"+ );+ }++ #[test]+ fn locality_is_decided_on_the_resolved_host_not_the_string() {+ assert!(base_url_is_local("http://localhost:11434"));+ assert!(base_url_is_local("http://127.0.0.1:11434"));+ assert!(base_url_is_local("http://[::1]:11434"));+ assert!(!base_url_is_local("http://192.168.0.54:11434"));+ assert!(!base_url_is_local("http://ollama.example.com"));+ // A host that merely CONTAINS a local name is not local.+ assert!(!base_url_is_local("http://localhost.evil.example"));+ assert!(!base_url_is_local("not a url"));+ }++ /// No hardcoded default address survives in the make-room path.+ #[test]+ fn the_vram_path_carries_no_hardcoded_backend_address() {+ const SRC: &str = include_str!("process.rs");+ let start = SRC+ .find("pub(crate) fn offload_ollama_loaded_models_at")+ .expect("offload helper is gone");+ let end = SRC+ .find(concat!("#[cfg(test)]\nmod vram_release", "_tests"))+ .expect("test module marker is gone");+ let body = &SRC[start..end];+ for needle in ["localhost:8188", "localhost:11434", "127.0.0.1:8188", "127.0.0.1:11434"] {+ assert!(+ !body.contains(needle),+ "'{needle}' is hardcoded again in the make-room-for-VRAM path"+ );+ }+ }+}++/// T-68 — the orphan of a hard-killed session, and the line between it and a+/// ComfyUI the user runs themselves.+///+/// VERIFICATION LIMIT, stated here and not only in a report: the failure this+/// closes needs a SIGKILLed LU on Linux with a live ComfyUI child. That cannot+/// be produced on the Mac this branch is developed on — macOS never+/// auto-starts ComfyUI (local media is MLX-only) and there is no ComfyUI+/// install here at all. What IS tested is every part that does not need one:+/// the classifier that decides whether LU may kill a process it did not spawn,+/// and the process-table scan against a REAL process this test starts and then+/// finds by its command line. The kill escalation itself and the end-to-end+/// hard-kill sequence are unproven here.+#[cfg(test)]+mod comfy_adoption_tests {+ use super::*;++ fn argv(line: &str) -> Vec<String> {+ line.split(' ').map(str::to_string).collect()+ }++ /// Exactly what `start_comfyui_blocking` spawns, in argv order.+ fn lu_argv(port: u16) -> Vec<String> {+ argv(&format!(+ "/usr/bin/python3 main.py --listen 127.0.0.1 --port {port} --enable-cors-header *"+ ))+ }++ #[test]+ fn the_argv_this_app_actually_spawns_is_recognised() {+ assert!(is_lu_started_comfyui(&lu_argv(8188), 8188));+ assert!(is_lu_started_comfyui(&lu_argv(9001), 9001));+ // …and the CPU-fallback / flash-attention variants of the same start.+ assert!(is_lu_started_comfyui(+ &argv("python main.py --listen 127.0.0.1 --port 8188 --enable-cors-header * --cpu"),+ 8188+ ));+ assert!(is_lu_started_comfyui(+ &argv("python main.py --listen 127.0.0.1 --port 8188 --enable-cors-header * --use-flash-attention"),+ 8188+ ));+ }++ /// The whole reason the classifier is narrow: this decides whether LU+ /// kills a process it did not spawn.+ #[test]+ fn a_comfyui_the_user_started_is_never_adopted() {+ // No --enable-cors-header: this is the shape the "Fix CORS" button in+ // Settings exists for, i.e. a hand-started ComfyUI.+ assert!(!is_lu_started_comfyui(+ &argv("python main.py --listen 0.0.0.0 --port 8188"),+ 8188+ ));+ // ComfyUI Desktop / a launcher script — not main.py.+ assert!(!is_lu_started_comfyui(+ &argv("/Applications/ComfyUI.app/Contents/MacOS/ComfyUI --port 8188"),+ 8188+ ));+ // Not a ComfyUI at all.+ assert!(!is_lu_started_comfyui(&argv("node server.js --port 8188"), 8188));+ assert!(!is_lu_started_comfyui(&[], 8188));+ }++ /// A second ComfyUI, on a port that merely starts with our digits, is a+ /// stranger. `contains("--port 8188")` would have killed it.+ #[test]+ fn a_neighbouring_port_is_not_our_port() {+ // 61880 starts with the digits of 6188 — a substring test would+ // have called this ours and killed it.+ let neighbour = argv("python main.py --port 61880 --enable-cors-header *");+ assert!(!is_lu_started_comfyui(&neighbour, 6188));+ assert!(is_lu_started_comfyui(&neighbour, 61880));++ let shorter = argv("python main.py --port 618 --enable-cors-header *");+ assert!(!is_lu_started_comfyui(&shorter, 6188));++ // Both spellings of the flag resolve to the same port.+ assert!(is_lu_started_comfyui(+ &argv("python main.py --port=8188 --enable-cors-header *"),+ 8188+ ));+ assert!(!is_lu_started_comfyui(+ &argv("python main.py --port=61880 --enable-cors-header *"),+ 6188+ ));+ }++ /// The scan runs against the real process table. A process whose argv+ /// matches must be found by pid; the same process on another port must+ /// not.+ ///+ /// Unix only: the stand-in needs a program that keeps LU's argv shape+ /// while doing nothing, and `sh -c` is the portable way to get one. The+ /// finding itself is a Linux/macOS one — Windows children join the+ /// kill-on-close job object and do not orphan in the first place.+ #[cfg(unix)]+ #[test]+ fn the_scan_finds_a_real_process_by_the_argv_lu_would_have_used() {+ // The trailing `; :` matters: a single simple command makes sh exec+ // it and hand over its argv, which would erase the very thing being+ // matched.+ let port: u16 = 61888;+ let mut child = Command::new("/bin/sh")+ .args([+ "-c",+ "sleep 30; :",+ "main.py",+ "--listen",+ "127.0.0.1",+ "--port",+ &port.to_string(),+ "--enable-cors-header",+ "*",+ ])+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .expect("spawn the stand-in");++ // sysinfo needs the process to be in the table.+ std::thread::sleep(std::time::Duration::from_millis(300));+ let found = find_orphaned_comfyui(port);+ let other = find_orphaned_comfyui(port + 1);++ let _ = child.kill();+ let _ = child.wait();++ assert_eq!(found, Some(child.id()), "the scan did not find the stand-in");+ assert_eq!(other, None, "the scan matched a process on another port");+ }++ /// Stop must not still be the no-op the finding describes.+ #[test]+ fn stop_no_longer_answers_not_running_without_looking() {+ const SRC: &str = include_str!("process.rs");+ let start = SRC+ .find("fn stop_comfyui_blocking")+ .expect("stop_comfyui_blocking is gone");+ let body = &SRC[start..];+ let end = start + body.find("\n}\n").expect("unterminated fn");+ let body = &SRC[start..end];+ assert!(+ body.contains("find_orphaned_comfyui("),+ "stop_comfyui_blocking no longer looks for the orphan"+ );+ assert!(+ body.contains("kill_pid_tree("),+ "stop_comfyui_blocking finds the orphan and does not stop it"+ );+ }+}++/// A child that outlives its launcher — the `npx -y <package>` MCP server, and+/// anything else the shell plugin starts through a shim.+///+/// VERIFICATION LIMIT: the Unix half is proved here against real processes.+/// The Windows half (`taskkill /T /F`) and the `npx.cmd` → cmd.exe → node+/// chain it has to walk are NOT exercised on this machine.+#[cfg(test)]+mod process_tree_kill_tests {+ use super::*;++ #[test]+ fn only_this_apps_own_processes_may_be_killed() {+ let own = std::process::id();+ let mine = vec![4242u32, 4243];+ assert!(may_kill_pid(4242, own, &mine).is_ok());++ // init / the session leader / the user's editor: not ours.+ for stranger in [1u32, 999_999, own] {+ let err = may_kill_pid(stranger, own, &mine)+ .expect_err("a pid outside our subtree was accepted");+ assert!(err.starts_with("refused:"), "{err}");+ }+ assert!(may_kill_pid(0, own, &mine).is_err());++ // The ordering trap gets named in the message, because the misuse+ // (kill the child first, then ask for its tree) looks like a bug in+ // this command rather than in the call order.+ let err = may_kill_pid(4244, own, &mine).unwrap_err();+ assert!(err.contains("INSTEAD of the child"), "{err}");+ }++ /// The whole point: the grandchild dies too. `child.kill()` from the shell+ /// plugin would have left it running.+ #[cfg(unix)]+ #[test]+ fn killing_the_launcher_takes_the_grandchild_with_it() {+ use sysinfo::{Pid, ProcessesToUpdate, System};++ // A launcher that spawns a long-lived grandchild and then waits —+ // the shape `npx -y <pkg>` has (shim in front, real server behind).+ let mut launcher = Command::new("/bin/sh")+ .args(["-c", "sleep 60 & wait"])+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .expect("spawn the launcher");+ let launcher_pid = launcher.id();++ let grandchild = {+ let mut found = None;+ for _ in 0..40 {+ std::thread::sleep(std::time::Duration::from_millis(50));+ let mut sys = System::new();+ sys.refresh_processes(ProcessesToUpdate::All, true);+ let kids = crate::commands::shell::descendants(launcher_pid, &sys);+ if let Some(pid) = kids.first() {+ found = Some(*pid);+ break;+ }+ }+ found.expect("the launcher never spawned its grandchild")+ };+ assert_ne!(grandchild, launcher_pid);++ let out = kill_process_tree_blocking(launcher_pid).expect("the tree kill was refused");+ assert_eq!(out["killed"], serde_json::json!(true));+ assert!(out["processes"].as_u64().unwrap() >= 2, "{out}");++ // SIGTERM goes out immediately; give the escalation room anyway.+ let mut still_there = true;+ for _ in 0..40 {+ std::thread::sleep(std::time::Duration::from_millis(50));+ let mut sys = System::new();+ sys.refresh_processes(ProcessesToUpdate::All, true);+ if sys.process(Pid::from_u32(grandchild)).is_none() {+ still_there = false;+ break;+ }+ }+ let _ = launcher.kill();+ let _ = launcher.wait();+ assert!(+ !still_there,+ "the grandchild (pid {grandchild}) outlived the kill — this is exactly the \+ npx orphan the plugin's own kill leaves behind"+ );+ }++ /// One kill path, not two: the command must go through the same helper the+ /// ComfyUI adoption uses.+ #[test]+ fn there_is_one_tree_kill_path() {+ const SRC: &str = include_str!("process.rs");+ let start = SRC.find("pub(crate) fn kill_process_tree_blocking").expect("gone");+ let body = &SRC[start..start + 1400];+ assert!(+ body.contains("process_util::kill_pid_tree("),+ "kill_process_tree grew its own kill instead of using the shared one"+ );+ }+}diff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rsindex 1c0ee09c..a060b00d 100644--- a/src-tauri/src/commands/remote.rs+++ b/src-tauri/src/commands/remote.rs@@ -5370,24 +5370,41 @@ fn targets_loopback_port(text: &str, port: u16) -> bool {/// user believes is LAN-only, reachable from the internet, with the app's own/// tunnel indicator reading OFF because this process never started it.fn kill_orphaned_tunnels(port: u16) -> usize {- use sysinfo::{ProcessesToUpdate, System};- let mut sys = System::new();- sys.refresh_processes(ProcessesToUpdate::All, true);+ // The table MUST come from this helper. Until 2026-09-01 this function+ // built its own with `System::refresh_processes`, which does not fetch+ // command lines — so `process.cmd()` was EMPTY, `targets_loopback_port`+ // was handed "", and the sweep could never match a single process. It ran+ // on every start, reported 0, and looked like it worked. The identical+ // mistake sat in `process::find_orphaned_comfyui`; only one of the two was+ // ever noticed, which is why the refresh now lives in one place.+ let sys = crate::process_util::process_table_with_cmdlines();let mut killed = 0usize;- for process in sys.processes().values() {- let name = process.name().to_string_lossy().to_string();- let cmd: Vec<String> = process- .cmd()- .iter()- .map(|c| c.to_string_lossy().to_string())- .collect();- if is_stale_tunnel_process(&name, &cmd, port) && process.kill() {- killed += 1;+ for pid in find_stale_tunnels(&sys, port) {+ if let Some(process) = sys.process(sysinfo::Pid::from_u32(pid)) {+ if process.kill() {+ killed += 1;+ }}}killed}+/// The pids of every cloudflared publishing `port`, read off an already+/// refreshed table.+///+/// Split from the kill so the scan can be tested against real processes+/// without the test having to kill anything.+fn find_stale_tunnels(sys: &sysinfo::System, port: u16) -> Vec<u32> {+ sys.processes()+ .iter()+ .filter(|(_, process)| {+ let name = process.name().to_string_lossy().to_string();+ is_stale_tunnel_process(&name, &crate::process_util::cmdline_of(process), port)+ })+ .map(|(pid, _)| pid.as_u32())+ .collect()+}+#[tauri::command]pub async fn start_remote_server(app: AppHandle,@@ -6934,6 +6951,67 @@ mod remote_hardening_tests {assert!(!is_stale_tunnel_process("cloudflared", &cmd("cloudflared --version"), 11435));}+ /// The sweep against the REAL process table.+ ///+ /// The two tests around this one feed `is_stale_tunnel_process` strings and+ /// have always passed — including for the fifteen months the sweep could+ /// not match anything at all, because `refresh_processes` never fetched the+ /// argv they were pretending to be. Only a real process proves the scan is+ /// wired to real data.+ ///+ /// The stand-in is a COPY of `/bin/sh` named `cloudflared`: sysinfo reports+ /// `name()` from the executed file, so a copy gets the name the matcher+ /// requires (a symlink does not — it reports the resolved target, measured+ /// 2026-09-01). Nothing is killed here; the test reaps its own child.+ #[cfg(unix)]+ #[test]+ fn the_sweep_finds_a_real_cloudflared_by_its_argv() {+ use std::os::unix::fs::PermissionsExt;+ use std::process::{Command, Stdio};++ let port: u16 = 61435;+ let dir = tempfile::tempdir().expect("tempdir");+ let bin = dir.path().join("cloudflared");+ std::fs::copy("/bin/sh", &bin).expect("copy the stand-in");+ std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).expect("chmod");++ let mut child = Command::new(&bin)+ .args([+ "-c",+ "sleep 30; :",+ "tunnel",+ "--url",+ &format!("http://127.0.0.1:{port}"),+ ])+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .expect("spawn the stand-in");++ let mut found = false;+ let mut other_port = true;+ for _ in 0..40 {+ std::thread::sleep(std::time::Duration::from_millis(50));+ let sys = crate::process_util::process_table_with_cmdlines();+ if find_stale_tunnels(&sys, port).contains(&child.id()) {+ found = true;+ other_port = find_stale_tunnels(&sys, port + 1).contains(&child.id());+ break;+ }+ }+ let _ = child.kill();+ let _ = child.wait();++ assert!(+ found,+ "the sweep did not find a live cloudflared publishing {port} — this is \+ exactly the state the sweep was in while it reported 0 killed on \+ every start"+ );+ assert!(!other_port, "a sweep for another port matched this tunnel");+ }+#[test]fn a_sweep_for_one_port_does_not_kill_the_tunnel_of_another() {// The port was matched as a substring, so `127.0.0.1:1143` was "found"diff --git a/src-tauri/src/commands/secret.rs b/src-tauri/src/commands/secret.rsindex 6522e522..41f2775c 100644--- a/src-tauri/src/commands/secret.rs+++ b/src-tauri/src/commands/secret.rs@@ -33,6 +33,65 @@#[cfg(any(target_os = "windows", target_os = "macos"))]const SERVICE: &str = crate::app_identity::KEYCHAIN_SERVICE;+// ── T-61: the account name is an argument, so it needs an allowlist ─────────+//+// `secret_set` / `secret_get` / `secret_delete` take the account straight from+// the frontend, and the invoke bridge is reachable from any script that gets to+// run in the webview (`__TAURI_INTERNALS__.invoke`; `withGlobalTauri: false`+// removed the convenience wrapper, not the bridge). Without a check on the+// name, one script-execution bug reads the whole vault — the Supabase session+// and every provider key — and can write anything into it under a name the app+// will never look at again.+//+// The list below is ERHOBEN, nicht geraten: every entry has exactly one call+// site in the frontend, and `the_allowlist_covers_every_account_the_frontend_uses`+// re-derives it from those files on every test run.+//+// ollama / openai / anthropic `PROVIDER_IDS` in stores/providerStore.ts,+// the ids `setProviderApiKey` stores keys for+// huggingface-token `HF_TOKEN_ACCOUNT` in api/mlx-image.ts+// lu-cloud-session `SESSION_ACCOUNT` in api/cloud/supabase.ts+// lu-cloud-session-code-verifier the PKCE verifier: supabase-js writes it+// through the same storage adapter under+// `${storageKey}-code-verifier`+//+// HAZARD, named on purpose: this is an exact-match list, so a supabase-js+// upgrade that routes a THIRD key through `keychainStorage` would be refused+// here and would break sign-in. That is why a refusal is logged at warn level+// with the offending name — the failure has to be diagnosable from the rolling+// log, not just visible as a dead login. The alternative (a `lu-cloud-session*`+// prefix family) was rejected: it would leave a writable corner of the vault+// open, which is the half of the finding about writes.+const ALLOWED_ACCOUNTS: [&str; 6] = [+ "ollama",+ "openai",+ "anthropic",+ "huggingface-token",+ "lu-cloud-session",+ "lu-cloud-session-code-verifier",+];++/// Reject an account name the app never stores under.+///+/// Deliberately NOT phrased like the two strings the frontend treats as "there+/// is no keychain here" (`keychainMissing` in api/cloud/supabase.ts matches+/// "keychain unavailable" / "keychain unsupported"). A refused NAME must not+/// latch the adapter onto its plaintext-localStorage fallback — that would turn+/// a rejected write into a downgrade, which is worse than the write.+fn check_account(account: &str) -> Result<(), String> {+ if ALLOWED_ACCOUNTS.contains(&account) {+ return Ok(());+ }+ tracing::warn!(+ account = %account,+ "refused a secret operation for an account this app does not store"+ );+ Err(format!(+ "refused: '{account}' is not one of the accounts this app stores ({})",+ ALLOWED_ACCOUNTS.join(", ")+ ))+}+#[cfg(any(target_os = "windows", target_os = "macos"))]mod chunked {use super::SERVICE;@@ -225,6 +284,7 @@ async fn run_keychain<T: Send + 'static>(#[cfg(any(target_os = "windows", target_os = "macos"))]#[tauri::command]pub async fn secret_set(account: String, value: String) -> Result<(), String> {+ check_account(&account)?;if keychain_disabled() {return Err("keychain unavailable (LU_NO_KEYCHAIN test mode)".into());}@@ -242,6 +302,7 @@ pub async fn secret_set(account: String, value: String) -> Result<(), String> {#[cfg(any(target_os = "windows", target_os = "macos"))]#[tauri::command]pub async fn secret_get(account: String) -> Result<Option<String>, String> {+ check_account(&account)?;if keychain_disabled() {return Err("keychain unavailable (LU_NO_KEYCHAIN test mode)".into());}@@ -251,6 +312,7 @@ pub async fn secret_get(account: String) -> Result<Option<String>, String> {#[cfg(any(target_os = "windows", target_os = "macos"))]#[tauri::command]pub async fn secret_delete(account: String) -> Result<(), String> {+ check_account(&account)?;if keychain_disabled() {return Err("keychain unavailable (LU_NO_KEYCHAIN test mode)".into());}@@ -264,19 +326,22 @@ pub async fn secret_delete(account: String) -> Result<(), String> {#[cfg(not(any(target_os = "windows", target_os = "macos")))]#[tauri::command]-pub fn secret_set(_account: String, _value: String) -> Result<(), String> {+pub fn secret_set(account: String, _value: String) -> Result<(), String> {+ check_account(&account)?;Err("keychain unsupported on this platform".into())}#[cfg(not(any(target_os = "windows", target_os = "macos")))]#[tauri::command]-pub fn secret_get(_account: String) -> Result<Option<String>, String> {+pub fn secret_get(account: String) -> Result<Option<String>, String> {+ check_account(&account)?;Err("keychain unsupported on this platform".into())}#[cfg(not(any(target_os = "windows", target_os = "macos")))]#[tauri::command]-pub fn secret_delete(_account: String) -> Result<(), String> {+pub fn secret_delete(account: String) -> Result<(), String> {+ check_account(&account)?;Err("keychain unsupported on this platform".into())}@@ -307,3 +372,145 @@ mod tests {assert_eq!(parse_marker("eyJhbGciOiJIUzI1NiJ9.payload.sig"), None);}}++/// T-61 — the account allowlist. Compiled on every platform on purpose: the+/// commands take the same argument everywhere, so the rule that decides which+/// names reach the vault has to be under test everywhere too.+#[cfg(test)]+mod account_allowlist_tests {+ use super::*;++ /// Pull the value out of `… <needle>'value'`, the shape every one of these+ /// account constants has in the frontend.+ fn quoted_after(src: &str, needle: &str) -> String {+ let rest = src+ .split_once(needle)+ .unwrap_or_else(|| panic!("'{needle}' is gone from the frontend source"))+ .1;+ let rest = rest+ .split_once('\'')+ .unwrap_or_else(|| panic!("no opening quote after '{needle}'"))+ .1;+ rest.split_once('\'')+ .unwrap_or_else(|| panic!("no closing quote after '{needle}'"))+ .0+ .to_string()+ }++ #[test]+ fn every_account_the_app_uses_is_accepted() {+ for account in ALLOWED_ACCOUNTS {+ assert!(+ check_account(account).is_ok(),+ "'{account}' is in the allowlist but was refused"+ );+ }+ }++ #[test]+ fn a_foreign_account_is_refused_and_never_reaches_the_vault() {+ // The three names the finding is actually about: anything the caller+ // invents, plus a near-miss of a real one, plus the internal chunk+ // shape (built inside this module from an already-checked base — a+ // caller must not be able to address it directly).+ for account in [+ "evil",+ "",+ "lu-cloud-session-code-verifier-x",+ "LU-CLOUD-SESSION",+ "lu-cloud-session#0",+ "openai ",+ ] {+ let err = match check_account(account) {+ Ok(()) => panic!("'{account}' was accepted"),+ Err(e) => e,+ };+ assert!(err.starts_with("refused:"), "{err}");+ }+ }++ /// A refused NAME must not read as "there is no keychain here".+ ///+ /// `keychainMissing` in `src/api/cloud/supabase.ts` matches exactly these+ /// two substrings and latches the session onto obfuscated localStorage+ /// when it sees one. If the refusal said either of them, blocking a write+ /// would have DOWNGRADED the refresh token to disk — the opposite of what+ /// this check is for.+ #[test]+ fn the_refusal_is_not_a_keychain_availability_answer() {+ let err = check_account("evil").unwrap_err();+ assert!(!err.contains("keychain unavailable"), "{err}");+ assert!(!err.contains("keychain unsupported"), "{err}");+ }++ /// The allowlist is only worth having if it tracks the frontend. This+ /// re-derives every account from the files that call the commands, so+ /// adding a keychain account in TypeScript without adding it here is a red+ /// test rather than a broken feature on the next release.+ #[test]+ fn the_allowlist_covers_every_account_the_frontend_uses() {+ const PROVIDER_STORE: &str = include_str!("../../../src/stores/providerStore.ts");+ const MLX_IMAGE: &str = include_str!("../../../src/api/mlx-image.ts");+ const SUPABASE: &str = include_str!("../../../src/api/cloud/supabase.ts");++ let mut wanted: Vec<String> = Vec::new();++ // stores/providerStore.ts — the ids hydrateProviderKeys probes and+ // setProviderApiKey writes.+ let list = PROVIDER_STORE+ .split_once("const PROVIDER_IDS: ProviderId[] = [")+ .expect("PROVIDER_IDS is gone from providerStore.ts")+ .1+ .split_once(']')+ .expect("PROVIDER_IDS list is not closed")+ .0;+ for part in list.split(',') {+ if let Some(id) = part.trim().strip_prefix('\'').and_then(|s| s.strip_suffix('\'')) {+ wanted.push(id.to_string());+ }+ }+ assert_eq!(wanted.len(), 3, "PROVIDER_IDS changed shape: {list}");++ // api/mlx-image.ts — the HuggingFace token.+ wanted.push(quoted_after(MLX_IMAGE, "HF_TOKEN_ACCOUNT ="));++ // api/cloud/supabase.ts — the session, plus the PKCE verifier that+ // supabase-js writes through the same adapter under+ // `${storageKey}-code-verifier` (keychainAccount preserves the suffix).+ let session = quoted_after(SUPABASE, "const SESSION_ACCOUNT =");+ assert!(+ SUPABASE.contains("-code-verifier"),+ "supabase.ts no longer mentions the PKCE verifier key — re-derive the suffix"+ );+ wanted.push(format!("{session}-code-verifier"));+ wanted.push(session);++ for account in &wanted {+ assert!(+ ALLOWED_ACCOUNTS.contains(&account.as_str()),+ "the frontend stores a secret under '{account}', which the allowlist refuses"+ );+ }+ // …and nothing sits in the allowlist that no caller uses. An account+ // nobody writes is an account nobody notices being read.+ for allowed in ALLOWED_ACCOUNTS {+ assert!(+ wanted.iter().any(|w| w == allowed),+ "'{allowed}' is allowlisted but no frontend call site stores under it"+ );+ }+ }++ /// Every command body checks the name before it does anything else. Six+ /// commands: three on the keychain platforms, three on the stub platforms.+ #[test]+ fn no_command_reaches_the_vault_without_the_check() {+ const SECRET_RS: &str = include_str!("secret.rs");+ // Both needles are split so these two lines do not match themselves:+ // the file being counted is this one.+ let commands = SECRET_RS.matches(concat!("#[tauri", "::command]")).count();+ let checks = SECRET_RS.matches(concat!("check_account", "(&account)?;")).count();+ assert_eq!(commands, 6, "command count changed — recount the checks");+ assert_eq!(checks, commands, "a secret command runs without the name check");+ }+}diff --git a/src-tauri/src/commands/trainer.rs b/src-tauri/src/commands/trainer.rsindex 5ad8c608..aeff246b 100644--- a/src-tauri/src/commands/trainer.rs+++ b/src-tauri/src/commands/trainer.rs@@ -1168,6 +1168,10 @@ pub fn start_character_training(let cancel = state.trainer_cancel.clone();let pid_slot = state.trainer_process.clone();let env_broken = state.trainer_env_broken.clone();+ // T-65: the training thread outlives this `State` borrow, so resolve+ // ComfyUI's ACTUAL address here (user-configured host/port from AppState,+ // not a hardcoded localhost:8188) and move the verdict in.+ let comfy_vram_target = crate::commands::process::comfy_vram_target(state.inner());cancel.store(false, Ordering::SeqCst);std::thread::spawn(move || {@@ -1302,8 +1306,24 @@ pub fn start_character_training(// 3) the train itself — documented 12 GB combo: fp8 base + block swap// + gradient checkpointing + 8-bit optimizer. ComfyUI's model cache// would eat the same VRAM the trainer needs — ask it to let go first.- if crate::commands::process::free_comfyui_memory() {- push_log(&run, "Freed ComfyUI's cached models to make room for training.");+ match &comfy_vram_target {+ Ok(base) => {+ let outcome = crate::commands::process::free_comfyui_memory_at(base);+ if outcome.released() {+ push_log(&run, "Freed ComfyUI's cached models to make room for training.");+ } else if let Some((target, why)) = outcome.not_responsible() {+ // Used to be a silent `false`. On a 12 GB card the user is+ // about to hit CUDA OOM, and "LU could not ask" is the one+ // sentence that explains it.+ push_log(+ &run,+ &format!("Did not free ComfyUI's VRAM ({target}): {why}"),+ );+ }+ }+ Err((target, why)) => {+ push_log(&run, &format!("Did not free ComfyUI's VRAM ({target}): {why}"));+ }}set_status(&run, "running", &format!("Step 3/4: Training ({steps} steps). This runs for a while, live log below..."));let accelerate = {diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 67c3af78..4550e487 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -258,6 +258,7 @@ fn main() {commands::process::start_ollama,commands::process::start_comfyui,commands::process::stop_comfyui,+ commands::process::kill_process_tree,commands::process::fix_comfyui_cors,commands::process::comfyui_status,commands::process::comfyui_last_output,diff --git a/src-tauri/src/process_util.rs b/src-tauri/src/process_util.rsindex f88c3627..07eee813 100644--- a/src-tauri/src/process_util.rs+++ b/src-tauri/src/process_util.rs@@ -29,6 +29,55 @@ pub fn suppress_window(cmd: &mut Command) {}}+// ── Reading the process table by COMMAND LINE ───────────────────────────────+//+// `System::refresh_processes` does NOT fetch command lines. Its refresh kind is+// memory + cpu + disk_usage + exe (sysinfo-0.33 `common/system.rs:296`), so+// `Process::cmd()` comes back as an EMPTY slice for every process, and any+// matcher that joins it silently compares against "".+//+// That is not a hypothetical. It cost this repo two independent bugs, and the+// second one is the reason this helper exists rather than a third copy of the+// same three lines:+//+// * `process::find_orphaned_comfyui` (T-68) — the scan for a ComfyUI orphaned+// by a hard kill found nothing at all, so Stop stayed the no-op the audit+// described even after the adoption path was written.+// * `remote::kill_orphaned_tunnels` (T-39) — the startup sweep that kills a+// cloudflared tunnel surviving from the last run could never match, so a+// tunnel kept publishing the LAN server to the internet while the app's own+// indicator read OFF. AUDIT-COVERAGE.md recorded that finding as fixed,+// because the fix LOOKED like it applied.+//+// One of the two got repaired and the other did not, purely because nobody knew+// they were the same line twice. So: one helper, one place to get this wrong.++/// A refreshed process table whose entries actually carry their command lines.+///+/// Use this — never a bare `System::new()` + `refresh_processes()` — whenever+/// the answer depends on `Process::cmd()`.+pub fn process_table_with_cmdlines() -> sysinfo::System {+ use sysinfo::{ProcessRefreshKind, ProcessesToUpdate, System, UpdateKind};+ let mut sys = System::new();+ sys.refresh_processes_specifics(+ ProcessesToUpdate::All,+ true,+ // `name()` stays populated by the base discovery, so a matcher that+ // reads both the name and the argv is served by this one refresh.+ ProcessRefreshKind::nothing().with_cmd(UpdateKind::Always),+ );+ sys+}++/// One process's command line as owned strings, in argv order.+pub fn cmdline_of(process: &sysinfo::Process) -> Vec<String> {+ process+ .cmd()+ .iter()+ .map(|c| c.to_string_lossy().to_string())+ .collect()+}+/// Spawn a command with stdout+stderr piped, console suppressed on Windows.pub fn spawn_piped(mut cmd: Command) -> std::io::Result<Child> {cmd.stdout(Stdio::piped()).stderr(Stdio::piped());@@ -163,6 +212,54 @@ pub fn kill_tree(child: &mut Child) -> std::io::Result<()> {Ok(())}+/// Same escalation as [`kill_tree`], but for a pid this process does NOT own.+///+/// The case it exists for (T-68): LU is hard-killed, its ComfyUI child is+/// reparented to init and survives. The next launch can identify that process+/// but has no `Child` for it — so there is nothing to `wait()` on, and calling+/// `waitpid` on a stranger would fail with ECHILD anyway. Everything else is+/// the same walk: snapshot the tree while the parent links still exist,+/// SIGTERM it, then SIGKILL whatever is still there (and still the same+/// process, by start time) after the grace, off the caller's thread.+pub fn kill_pid_tree(pid: u32) {+ #[cfg(windows)]+ {+ let _ = Command::new("taskkill")+ .args(["/T", "/F", "/PID", &pid.to_string()])+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .status();+ }+ #[cfg(unix)]+ {+ let tree = tree_snapshot(pid);+ for (p, _) in &tree {+ unsafe {+ libc::kill(*p as i32, libc::SIGTERM);+ }+ }+ std::thread::spawn(move || {+ std::thread::sleep(std::time::Duration::from_millis(800));+ use sysinfo::{Pid, ProcessesToUpdate, System};+ let mut sys = System::new();+ sys.refresh_processes(ProcessesToUpdate::All, true);+ for (p, start) in tree {+ let same = sys+ .process(Pid::from_u32(p))+ .map(|proc_| start == 0 || proc_.start_time() == start)+ .unwrap_or(false);+ if same {+ unsafe {+ libc::kill(p as i32, libc::SIGKILL);+ }+ }+ }+ // No waitpid: an adopted orphan is init's child, not ours. init+ // reaps it.+ });+ }+}+/// Best-effort stop of whatever process is LISTENING on a local TCP port./// Used by the "Stop" buttons for port-bound backends the bridge didn't spawn/// itself (so there's no `Child` handle to kill) — the MLX sidecar and the@@ -345,3 +442,72 @@ mod kill_tree_tests {}}}++/// The one regression this helper exists to stop: a process table without+/// command lines.+///+/// Both callers (`process::find_orphaned_comfyui`, `remote::kill_orphaned_tunnels`)+/// match on argv, and both were silently matching against "" before this was+/// centralised. This test is the shared guard — it fails for either of them.+#[cfg(test)]+mod process_table_tests {+ use super::*;++ #[cfg(unix)]+ #[test]+ fn the_table_carries_command_lines() {+ use std::process::{Command, Stdio};+ // The trailing `; :` stops sh from exec'ing the single command and+ // handing over its own argv — which would erase what is being read.+ let marker = "lu-process-table-probe-8f3a";+ let mut child = Command::new("/bin/sh")+ .args(["-c", "sleep 30; :", marker, "--flag", "value"])+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .expect("spawn the stand-in");++ let mut seen: Option<Vec<String>> = None;+ for _ in 0..40 {+ std::thread::sleep(std::time::Duration::from_millis(50));+ let sys = process_table_with_cmdlines();+ if let Some(p) = sys.process(sysinfo::Pid::from_u32(child.id())) {+ let cmd = cmdline_of(p);+ if !cmd.is_empty() {+ seen = Some(cmd);+ break;+ }+ }+ }+ let _ = child.kill();+ let _ = child.wait();++ let cmd = seen.expect(+ "the process table came back with an EMPTY command line — \+ refresh_processes does not fetch cmd, and every argv matcher in \+ this repo would silently be comparing against \"\"",+ );+ assert!(cmd.iter().any(|a| a == marker), "{cmd:?}");+ assert!(cmd.iter().any(|a| a == "--flag"), "{cmd:?}");+ }++ /// Nobody may quietly reintroduce a second, cmd-less refresh for an argv+ /// match. The two known matchers must go through the helper.+ #[test]+ fn the_argv_matchers_share_one_refresh() {+ const PROCESS_RS: &str = include_str!("commands/process.rs");+ const REMOTE_RS: &str = include_str!("commands/remote.rs");+ for (name, src, func) in [+ ("process.rs", PROCESS_RS, "pub(crate) fn find_orphaned_comfyui"),+ ("remote.rs", REMOTE_RS, "fn kill_orphaned_tunnels"),+ ] {+ let start = src.find(func).unwrap_or_else(|| panic!("{func} is gone from {name}"));+ let body = &src[start..start + 1200];+ assert!(+ body.contains("process_table_with_cmdlines()"),+ "{name}: {func} builds its own process table again"+ );+ }+ }+}