Skip to content

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

fix(comfy): die fuenf Befunde des Testers und sieben Nachzuegler

purplec142ba017f3b
diff --git a/src-tauri/src/commands/custom_models.rs b/src-tauri/src/commands/custom_models.rs
index 05dd5d88..14ad623a 100644
--- a/src-tauri/src/commands/custom_models.rs
+++ b/src-tauri/src/commands/custom_models.rs
@@ -10,9 +10,10 @@
//! So the honest way in is ComfyUI's own mechanism: an extra-model-paths config.
//! We write our own file and pass it with `--extra-model-paths-config`, so a
//! hand written `extra_model_paths.yaml` in the ComfyUI folder is never touched
-//! and nothing changes for a user who set none. Two limits are real and the
-//! Settings text says both: it reaches a ComfyUI that LU starts, and it takes
-//! effect the next time ComfyUI starts.
+//! and nothing changes for a user who set none. One limit is real and the
+//! Settings text says it: only a ComfyUI that LU starts is handed the folder.
+//! The subfolders are scanned again on every one of those starts, so a folder
+//! created after the setting was made arrives with the next start.
//!
//! Only subfolders NAMED like ComfyUI's model folders are mapped. A flat dump
//! of mixed files is left alone on purpose: mapping it into every key would
@@ -95,7 +96,8 @@ pub(crate) fn build_extra_model_paths_yaml(root: &Path) -> Option<String> {
}
let mut s = String::from(
"# Written by Locally Uncensored from Settings -> Model Storage.\n\
- # Edit the folder in the app, not this file: it is rewritten on every change.\n\
+ # Edit the folder in the app, not this file: LU rewrites it every time it\n\
+ # starts ComfyUI.\n\
lu_custom_models:\n",
);
for (key, path) in found {
@@ -125,15 +127,113 @@ pub(crate) fn extra_model_paths_file() -> Result<PathBuf, String> {
Ok(dir.join("lu_extra_model_paths.yaml"))
}
-/// The file to pass to ComfyUI, or `None` when there is nothing to pass.
-/// Called from the ComfyUI start path, so it never creates anything.
-pub fn extra_model_paths_arg() -> Option<PathBuf> {
- let base = dirs::data_dir()?;
- let file = base
- .join(crate::app_identity::APP_DISPLAY_DIR)
- .join("lu_extra_model_paths.yaml");
+/// What `config.json` knows about the folder under Model Storage.
+///
+/// Three states, not two, and the difference between the first two is the one
+/// that costs a boot if it is dropped. `Missing` is a build that never wrote
+/// the key: the app data dir may still hold a good file from before, and the
+/// boot auto-start runs on its own thread (`main.rs`) before the frontend has
+/// pushed anything down. Rewriting from nothing there would take the folder
+/// away on exactly the first start after the update. `Cleared` is the user
+/// having emptied the field, and that one has to take the file away.
+#[derive(Debug, PartialEq, Eq)]
+pub(crate) enum RememberedRoot {
+ Missing,
+ Cleared,
+ Folder(String),
+}
+
+/// The `config.json` key. Rust needs its own copy of the folder because the
+/// ComfyUI start path has nobody to ask: the setting lives in the frontend
+/// store (`hfDownloadPathOverride`) and reaches Rust only as a call argument.
+/// A field on `AppState` would not do, because the boot auto-start runs on its
+/// own thread and can be past the arguments before the frontend has pushed
+/// anything down. The persisted value is the last session's, and that is the
+/// right one as long as nobody moved the folder while the app was closed.
+pub(crate) const REMEMBERED_ROOT_KEY: &str = "custom_model_dir";
+
+/// Read-modify-write on the shared file, in the shape `set_comfyui_port` uses
+/// (`process.rs`): `comfyui_port` and `comfyui_host` live in the same JSON and
+/// must survive this write.
+pub(crate) fn remember_root_in(config: &Path, dir: &str) {
+ if let Some(parent) = config.parent() {
+ let _ = std::fs::create_dir_all(parent);
+ }
+ let mut json: serde_json::Value = std::fs::read_to_string(config)
+ .ok()
+ .and_then(|s| serde_json::from_str(&s).ok())
+ .unwrap_or_else(|| serde_json::json!({}));
+ json[REMEMBERED_ROOT_KEY] = serde_json::json!(dir);
+ let _ = std::fs::write(config, serde_json::to_string_pretty(&json).unwrap_or_default());
+}
+
+/// An empty value reads as `Cleared`, never as a folder named "": a folder the
+/// user switched off must stay off over a restart.
+pub(crate) fn remembered_root_in(config: &Path) -> RememberedRoot {
+ let root = std::fs::read_to_string(config)
+ .ok()
+ .and_then(|raw| serde_json::from_str::<serde_json::Value>(&raw).ok())
+ .and_then(|json| {
+ json.get(REMEMBERED_ROOT_KEY)
+ .and_then(|v| v.as_str())
+ .map(|s| s.trim().to_string())
+ });
+ match root {
+ None => RememberedRoot::Missing,
+ Some(dir) if dir.is_empty() => RememberedRoot::Cleared,
+ Some(dir) => RememberedRoot::Folder(dir),
+ }
+}
+
+fn remember_root(dir: &str) {
+ remember_root_in(&crate::os_paths::app_config_json(), dir);
+}
+
+fn remembered_root() -> RememberedRoot {
+ remembered_root_in(&crate::os_paths::app_config_json())
+}
+
+/// The file to pass to ComfyUI, written fresh right before the start.
+///
+/// P3: the function this replaced only asked whether the file was there, and
+/// the file was written at exactly one moment, namely when the setting
+/// changed. A subfolder created afterwards could not reach ComfyUI, no matter
+/// how often ComfyUI was restarted, while the Settings line promised the next
+/// start would pick it up.
+///
+/// What the old function could say and this one cannot: it created nothing.
+/// `extra_model_paths_file` runs `create_dir_all` on the app data dir, so
+/// every ComfyUI start now creates that folder, and a failure there costs the
+/// handover even when the file itself is already lying in place.
+pub fn refresh_extra_model_paths_arg() -> Option<PathBuf> {
+ let file = extra_model_paths_file().ok()?;
+ refresh_extra_model_paths_to(&file, &remembered_root())
+}
+
+/// The same work against a named file and a known folder, so a test can walk
+/// the start path without touching the installed app's config.
+///
+/// A write error is logged and swallowed: ComfyUI running without the extra
+/// folders is better for everyone than ComfyUI not running.
+pub(crate) fn refresh_extra_model_paths_to(
+ file: &Path,
+ root: &RememberedRoot,
+) -> Option<PathBuf> {
+ let rewrite = |dir: Option<&str>| {
+ if let Err(e) = sync_custom_model_paths_to(file, dir) {
+ eprintln!("[ComfyUI] Extra model paths not rewritten: {e}");
+ }
+ };
+ match root {
+ // Nothing is known, so nothing is decided here. A file an older build
+ // left behind is the best answer there is until the frontend pushes
+ // the folder down (`App.tsx` does that on every launch).
+ RememberedRoot::Missing => {}
+ RememberedRoot::Cleared => rewrite(None),
+ RememberedRoot::Folder(dir) => rewrite(Some(dir)),
+ }
if file.is_file() {
- Some(file)
+ Some(file.to_path_buf())
} else {
None
}
@@ -149,21 +249,34 @@ pub(crate) fn is_usable_root(root: &Path) -> bool {
}
/// One syscall that answers "is the folder there and readable" before the
-/// per-key stats run. On a dead network drive every stat blocks for the SMB
-/// timeout, so asking twenty times what one call already answered is twenty
-/// times the wait.
-pub(crate) fn root_reachable(root: &Path) -> bool {
- std::fs::read_dir(root).is_ok()
+/// per-key stats run, and WHY when the answer is no. `None` means reachable.
+///
+/// On a dead network drive every stat blocks for the SMB timeout, so asking
+/// twenty times what one call already answered is twenty times the wait.
+///
+/// The kind rather than the message, for the reason `mobile_page.rs` gives:
+/// `ErrorKind` is language neutral and free, while the text is whatever
+/// FormatMessageW felt like saying. P3 pointed a folder LU may not read at
+/// Model Storage and was told the drive was disconnected or the path was
+/// missing. Both were false, and the true answer was one `ErrorKind` away.
+pub(crate) fn root_probe(root: &Path) -> Option<std::io::ErrorKind> {
+ std::fs::read_dir(root).err().map(|e| e.kind())
}
/// What the folder is currently worth to ComfyUI.
+///
+/// `denied` is its own answer and not a flavour of `unreachable`: the drive is
+/// there, the path is there, and telling someone to check the cable sends them
+/// looking for a fault that does not exist.
pub(crate) fn folder_status(root: &Path) -> &'static str {
if !is_usable_root(root) {
"unusable"
- } else if !root_reachable(root) {
- "unreachable"
} else {
- "ok"
+ match root_probe(root) {
+ None => "ok",
+ Some(std::io::ErrorKind::PermissionDenied) => "denied",
+ Some(_) => "unreachable",
+ }
}
}
@@ -187,6 +300,11 @@ pub async fn sync_custom_model_paths(dir: Option<String>) -> Result<serde_json::
pub(crate) fn sync_custom_model_paths_blocking(
dir: Option<&str>,
) -> Result<serde_json::Value, String> {
+ // Vor dem Mac-Zweig, und bewusst nicht in sync_custom_model_paths_to: das
+ // ist die getestete Schicht mit frei waehlbarer Zieldatei und darf nichts
+ // Globales anfassen. Ohne diese Zeile kennt der ComfyUI-Start den Ordner
+ // nicht, denn er lebt sonst nur im Frontend-Store.
+ remember_root(dir.unwrap_or("").trim());
let file = extra_model_paths_file()?;
// The Mac runs local media on MLX and never starts ComfyUI
// (process::comfy_supported_here), so there is nobody to hand the folder
@@ -422,7 +540,7 @@ mod tests {
fn a_real_absolute_folder_passes_both_guards() {
let root = tmp("guards");
assert!(is_usable_root(&root));
- assert!(root_reachable(&root));
+ assert_eq!(root_probe(&root), None);
assert_eq!(folder_status(&root), "ok");
}
@@ -431,10 +549,44 @@ mod tests {
let root = tmp("vanished");
std::fs::remove_dir_all(&root).unwrap();
assert!(is_usable_root(&root));
- assert!(!root_reachable(&root));
+ assert_eq!(root_probe(&root), Some(std::io::ErrorKind::NotFound));
assert_eq!(folder_status(&root), "unreachable");
}
+ /// P3, 7.4: er zeigte auf einen Ordner, den LU nicht lesen darf, und bekam
+ /// "drive disconnected or path missing". Das Laufwerk war verbunden und der
+ /// Pfad war da. Der ErrorKind wusste es die ganze Zeit.
+ ///
+ /// Unter Unix ueber chmod herstellbar und damit auf der Entwicklermaschine
+ /// echt pruefbar. Unter Windows braucht eine ACL ohne Leserecht fuer den
+ /// eigenen Benutzer eine zweite Identitaet, also wird der Fall dort
+ /// ausgelassen statt vorgetaeuscht; der Beweis dafuer gehoert auf die Box.
+ #[test]
+ #[cfg(unix)]
+ fn ein_ordner_ohne_leserecht_heisst_denied_und_nicht_unreachable() {
+ use std::os::unix::fs::PermissionsExt;
+ let root = tmp("denied");
+ std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o000)).unwrap();
+ // Als root liest read_dir auch das, dann sagt dieser Lauf nichts aus.
+ if std::fs::read_dir(&root).is_ok() {
+ let _ = std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700));
+ return;
+ }
+ assert!(is_usable_root(&root));
+ assert_eq!(root_probe(&root), Some(std::io::ErrorKind::PermissionDenied));
+ assert_eq!(folder_status(&root), "denied");
+
+ // Der Gegenpol, im selben Test: ein geloeschter Ordner bleibt
+ // unreachable. Sonst haette man beide Faelle auf einen neuen Wert
+ // gelegt und nichts unterschieden.
+ let weg = tmp("denied-gegenpol");
+ std::fs::remove_dir_all(&weg).unwrap();
+ assert_eq!(folder_status(&weg), "unreachable");
+
+ let _ = std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700));
+ std::fs::remove_dir_all(&root).ok();
+ }
+
// ── What the Settings panel is told ───────────────────────────────────
#[test]
@@ -493,6 +645,178 @@ mod tests {
assert_eq!(res["written"], false);
}
+ // ── The ComfyUI start path ───────────────────────────────────────
+
+ /// P3, the tester's run rebuilt one to one: folder set, ComfyUI started,
+ /// `vae` created afterwards, ComfyUI restarted from the UI only. Every
+ /// other test in this file goes through `sync_custom_model_paths_to`, so
+ /// every other test asks about the moment the SETTING changes. This one
+ /// asks about the moment ComfyUI STARTS, which is where the fault was.
+ #[test]
+ fn a_subfolder_created_after_the_setting_reaches_the_next_start() {
+ let root = tmp("late-vae");
+ std::fs::create_dir_all(root.join("loras")).unwrap();
+ let file = tmp("late-vae-out").join("lu_extra_model_paths.yaml");
+ sync_custom_model_paths_to(&file, Some(root.to_str().unwrap())).unwrap();
+ let before = std::fs::read_to_string(&file).unwrap();
+ assert!(!before.contains("vae:"), "precondition: no vae folder yet");
+
+ // Der Nutzer legt den Ordner jetzt an und fasst die Einstellung nicht an.
+ std::fs::create_dir_all(root.join("vae")).unwrap();
+
+ // Was der Startpfad bis 2.6.8 tat, woertlich nachgebaut: nur fragen, ob
+ // die Datei da ist. Sie ist da, sie wird uebergeben, und sie kennt vae
+ // nicht. Ohne diese vier Zeilen prueft der Rest nur den Schreiber.
+ let old_arg = if file.is_file() { Some(file.clone()) } else { None };
+ assert_eq!(old_arg, Some(file.clone()), "the file was there all along");
+ assert!(
+ !std::fs::read_to_string(&file).unwrap().contains("vae:"),
+ "and it still had no vae in it: that is the finding",
+ );
+
+ let got = refresh_extra_model_paths_to(
+ &file,
+ &RememberedRoot::Folder(root.to_string_lossy().to_string()),
+ );
+ assert_eq!(got, Some(file.clone()));
+ let after = std::fs::read_to_string(&file).unwrap();
+ assert_ne!(after, before, "the start path did not rewrite the file");
+ let parsed: serde_yaml::Value = serde_yaml::from_str(&after).expect("must parse");
+ let block = &parsed["lu_custom_models"];
+ assert_eq!(
+ block["vae"].as_str().unwrap(),
+ root.join("vae").to_string_lossy(),
+ );
+ // Und der alte Eintrag bleibt, statt vom neuen verdraengt zu werden.
+ assert_eq!(
+ block["loras"].as_str().unwrap(),
+ root.join("loras").to_string_lossy(),
+ );
+ assert!(block.get("checkpoints").is_none(), "invented a folder");
+ }
+
+ /// The other direction, so a fix that only ever adds cannot pass: a folder
+ /// that lost its ComfyUI-shaped subfolders stops feeding ComfyUI at the
+ /// next start, instead of handing over paths that are gone.
+ #[test]
+ fn a_folder_that_lost_its_subfolders_stops_feeding_comfyui_at_the_next_start() {
+ let root = tmp("lost-vae");
+ std::fs::create_dir_all(root.join("vae")).unwrap();
+ let file = tmp("lost-vae-out").join("lu_extra_model_paths.yaml");
+ sync_custom_model_paths_to(&file, Some(root.to_str().unwrap())).unwrap();
+ assert!(file.exists(), "precondition: a file was written");
+
+ std::fs::remove_dir_all(root.join("vae")).unwrap();
+ let got = refresh_extra_model_paths_to(
+ &file,
+ &RememberedRoot::Folder(root.to_string_lossy().to_string()),
+ );
+ assert_eq!(got, None);
+ assert!(!file.exists(), "the old file must not keep feeding ComfyUI");
+ }
+
+ /// The deliberate part of this change, written down so it is a decision and
+ /// not a surprise: a drive that is not connected at the moment ComfyUI
+ /// starts costs the mapping for that run. Before, ComfyUI would have been
+ /// handed the last good file and looked for models on a drive that is not
+ /// there. It heals itself at the next start with the drive back, and that
+ /// second half is the reason this is acceptable.
+ #[test]
+ fn a_drive_that_is_away_at_start_time_costs_the_mapping_and_gets_it_back() {
+ let root = tmp("away-drive");
+ std::fs::create_dir_all(root.join("vae")).unwrap();
+ let file = tmp("away-drive-out").join("lu_extra_model_paths.yaml");
+ let remembered = RememberedRoot::Folder(root.to_string_lossy().to_string());
+ sync_custom_model_paths_to(&file, Some(root.to_str().unwrap())).unwrap();
+ assert!(file.exists(), "precondition: a file was written");
+
+ std::fs::remove_dir_all(&root).unwrap();
+ assert_eq!(refresh_extra_model_paths_to(&file, &remembered), None);
+ assert!(!file.exists());
+
+ std::fs::create_dir_all(root.join("vae")).unwrap();
+ assert_eq!(
+ refresh_extra_model_paths_to(&file, &remembered),
+ Some(file.clone()),
+ "the mapping has to come back on its own",
+ );
+ }
+
+ /// The one case no test would catch that is not written for it, and the
+ /// only boot at which a user meets this change for the first time: the key
+ /// is not in `config.json` yet, because the build that wrote the file
+ /// never knew it. Deleting the file there would cost the folder exactly
+ /// once, on the launch the user is looking at.
+ #[test]
+ fn the_first_start_after_the_update_keeps_the_file_an_empty_setting_clears_it() {
+ let root = tmp("migration");
+ std::fs::create_dir_all(root.join("loras")).unwrap();
+ let file = tmp("migration-out").join("lu_extra_model_paths.yaml");
+ sync_custom_model_paths_to(&file, Some(root.to_str().unwrap())).unwrap();
+ assert!(file.exists(), "precondition: the older build left a file");
+
+ assert_eq!(
+ refresh_extra_model_paths_to(&file, &RememberedRoot::Missing),
+ Some(file.clone()),
+ "an unknown folder must not throw the file away",
+ );
+ assert!(file.exists());
+
+ // Gegenprobe, und der Unterschied, um den es geht: abgewaehlt ist
+ // etwas anderes als unbekannt, und abgewaehlt heisst weg.
+ assert_eq!(refresh_extra_model_paths_to(&file, &RememberedRoot::Cleared), None);
+ assert!(!file.exists(), "a folder the user cleared kept feeding ComfyUI");
+ }
+
+ /// The folder has to survive a restart, because the start path is the only
+ /// reader and it has no window to ask.
+ #[test]
+ fn the_folder_survives_a_restart_and_an_empty_one_switches_it_off() {
+ let dir = tmp("config-json");
+ let config = dir.join("config.json");
+ assert_eq!(
+ remembered_root_in(&config),
+ RememberedRoot::Missing,
+ "no config file at all",
+ );
+ std::fs::write(&config, br#"{"comfyui_port":8189}"#).unwrap();
+ assert_eq!(
+ remembered_root_in(&config),
+ RememberedRoot::Missing,
+ "a config file without the key",
+ );
+
+ remember_root_in(&config, r"G:\AI\Models");
+ assert_eq!(
+ remembered_root_in(&config),
+ RememberedRoot::Folder(r"G:\AI\Models".to_string()),
+ );
+ let json: serde_json::Value =
+ serde_json::from_str(&std::fs::read_to_string(&config).unwrap()).unwrap();
+ assert_eq!(json["comfyui_port"], 8189, "the port setting was overwritten");
+
+ remember_root_in(&config, " ");
+ assert_eq!(
+ remembered_root_in(&config),
+ RememberedRoot::Cleared,
+ "an empty folder must not come back as a folder named \"\"",
+ );
+ let json: serde_json::Value =
+ serde_json::from_str(&std::fs::read_to_string(&config).unwrap()).unwrap();
+ assert_eq!(json["comfyui_port"], 8189);
+
+ // Negativkontrolle: ein naives Schreiben derselben Datei verliert den
+ // Port. Ohne sie bewiese die Zusicherung oben nichts.
+ std::fs::write(
+ &config,
+ serde_json::to_string(&serde_json::json!({ REMEMBERED_ROOT_KEY: "x" })).unwrap(),
+ )
+ .unwrap();
+ let naive: serde_json::Value =
+ serde_json::from_str(&std::fs::read_to_string(&config).unwrap()).unwrap();
+ assert!(naive.get("comfyui_port").is_none());
+ }
+
/// Negative control: a missing folder is not an error and not a config.
#[test]
fn a_folder_that_is_not_there_yields_nothing() {
diff --git a/src-tauri/src/commands/engine.rs b/src-tauri/src/commands/engine.rs
index 487d1ec3..276b4885 100644
--- a/src-tauri/src/commands/engine.rs
+++ b/src-tauri/src/commands/engine.rs
@@ -350,8 +350,12 @@ pub(crate) enum RootStatus {
/// The deadline or the entry budget ran out. What was found is real, the
/// list is not complete.
Truncated,
- /// `read_dir` on the root itself failed: gone, unplugged, unreadable.
+ /// `read_dir` on the root itself failed: gone, or unplugged.
Unreachable,
+ /// The folder is there and this account may not read it. Its own answer,
+ /// because "check that the drive is connected" sends the user looking for
+ /// a fault that is not there (P3, 7.4).
+ Denied,
/// Not a path the OS can resolve on its own: relative, or a shell `~`.
Unusable,
}
@@ -362,6 +366,7 @@ impl RootStatus {
RootStatus::Ok => "ok",
RootStatus::Truncated => "truncated",
RootStatus::Unreachable => "unreachable",
+ RootStatus::Denied => "denied",
RootStatus::Unusable => "unusable",
}
}
@@ -437,10 +442,19 @@ pub(crate) fn scan_gguf_roots(roots: &[ScanRoot]) -> ScanOutcome {
continue;
}
// One call answers "is it there and readable" before the walk, so a
- // dead mount costs one timeout instead of one per directory.
- if std::fs::read_dir(root.dir).is_err() {
- statuses.push(RootStatus::Unreachable);
- continue;
+ // dead mount costs one timeout instead of one per directory. The same
+ // call as the ComfyUI handover makes, so the two verdicts about one
+ // folder cannot drift apart.
+ match crate::commands::custom_models::root_probe(root.dir) {
+ None => {}
+ Some(std::io::ErrorKind::PermissionDenied) => {
+ statuses.push(RootStatus::Denied);
+ continue;
+ }
+ Some(_) => {
+ statuses.push(RootStatus::Unreachable);
+ continue;
+ }
}
let mut out = Vec::new();
let mut sets = GgufSplitSets::new();
@@ -3123,20 +3137,50 @@ mod tests {
std::fs::remove_dir_all(&gone).unwrap();
let relative = PathBuf::from("some/relative/models");
- let outcome = scan_gguf_roots(&[
+ // P3, 7.4: ein vierter Root, der da ist und den dieses Konto nicht
+ // lesen darf. Unter Windows laesst sich das in einem Unit-Test nicht
+ // herstellen (eine ACL ohne Leserecht fuer den eigenen Benutzer
+ // braucht eine zweite Identitaet), dort steht der Beweis auf der Box.
+ // Laeuft der Test als root, liest read_dir trotzdem, und dann wird der
+ // Fall ehrlich uebersprungen statt gruen gefaerbt.
+ #[cfg(unix)]
+ let denied = {
+ use std::os::unix::fs::PermissionsExt;
+ let d = scratch("status-denied");
+ std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o000)).unwrap();
+ d
+ };
+ #[cfg(unix)]
+ let denied_holds = std::fs::read_dir(&denied).is_err();
+
+ let mut roots = vec![
ScanRoot { dir: &app, max_depth: MAX_SCAN_DEPTH },
ScanRoot { dir: &gone, max_depth: MAX_CUSTOM_SCAN_DEPTH },
ScanRoot { dir: &relative, max_depth: MAX_CUSTOM_SCAN_DEPTH },
- ]);
- assert_eq!(
- outcome.statuses,
- vec![RootStatus::Ok, RootStatus::Unreachable, RootStatus::Unusable],
- );
+ ];
+ let mut expected = vec![RootStatus::Ok, RootStatus::Unreachable, RootStatus::Unusable];
+ #[cfg(unix)]
+ if denied_holds {
+ roots.push(ScanRoot { dir: &denied, max_depth: MAX_CUSTOM_SCAN_DEPTH });
+ expected.push(RootStatus::Denied);
+ }
+
+ let outcome = scan_gguf_roots(&roots);
+ // Der Gegenpol steht in derselben Liste: der geloeschte Ordner bleibt
+ // unreachable. Ohne ihn haette man beide Faelle auf einen neuen Wert
+ // gelegt und nichts unterschieden.
+ assert_eq!(outcome.statuses, expected);
// The app folder still answered, which is the point: one bad root is
// not allowed to cost the list.
assert_eq!(outcome.models.len(), 1);
assert_eq!(outcome.models[0].name, "real");
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let _ = std::fs::set_permissions(&denied, std::fs::Permissions::from_mode(0o700));
+ std::fs::remove_dir_all(&denied).ok();
+ }
std::fs::remove_dir_all(&app).ok();
}
diff --git a/src-tauri/src/commands/install/children.rs b/src-tauri/src/commands/install/children.rs
index 3aee64b5..f825a439 100644
--- a/src-tauri/src/commands/install/children.rs
+++ b/src-tauri/src/commands/install/children.rs
@@ -11,7 +11,9 @@
//! Kill auf die Zahl, die das Betriebssystem inzwischen weiterverwendet hat,
//! und diese Gefahr lässt sich nur an einer Stelle im Blick behalten.
-use std::sync::Mutex;
+use std::process::{Child, ExitStatus};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex};
use tracing::info;
@@ -84,6 +86,51 @@ pub fn kill_installer_children() -> usize {
pids.len()
}
+/// Wait for an installer child, and give up the moment the cancel flag flips.
+///
+/// `Ok(status)` means the child ended by itself. `Err("cancelled")` is the
+/// same sentinel `pip` and `env_check` already return, so callers catch a
+/// cancel the way they always did. Any other `Err` is the wait itself failing.
+///
+/// The kill takes the whole TREE, not just the child LU spawned: `python -m
+/// venv` runs `ensurepip` as its own process, and `Child::kill` never reaches
+/// it. That is a kill on ONE pid, not on [`INSTALLER_CHILDREN`], which also
+/// holds the whisper, Piper, custom-node and trainer pip runs.
+///
+/// P3 (04.09.): cancelling a repair took 76 seconds because the venv build had
+/// no loop like this one and simply ran to the end. `pip.rs` keeps its own
+/// copy of the loop deliberately: that one also turns the child's cumulative
+/// read bytes into download progress and speed once a second, which is work
+/// this bare version has no reason to do. Whoever removes the progress
+/// counters from pip folds the two together.
+pub(crate) fn wait_or_cancel(
+ child: &mut Child,
+ cancel: Option<&Arc<AtomicBool>>,
+ label: &str,
+) -> Result<ExitStatus, String> {
+ let pid = child.id();
+ loop {
+ if cancel.map(|c| c.load(Ordering::SeqCst)).unwrap_or(false) {
+ crate::commands::shell::kill_tree(pid);
+ let _ = child.kill();
+ let _ = child.wait();
+ return Err("cancelled".to_string());
+ }
+ match child.try_wait() {
+ Ok(Some(status)) => return Ok(status),
+ // 200 ms is the interval every other cancel poll in the installer
+ // uses, so the budget the UI promises is the same everywhere.
+ Ok(None) => std::thread::sleep(std::time::Duration::from_millis(200)),
+ Err(e) => {
+ return Err(format!(
+ "Waiting for {label} failed: {}",
+ crate::os_error::english(&e)
+ ))
+ }
+ }
+ }
+}
+
/// How many installer children are registered right now. Test-facing: the
/// registry's contract is that it is empty again once a run is over.
#[allow(dead_code)]
@@ -115,4 +162,78 @@ mod tests {
assert_eq!(tracked_installer_children(), before);
}
+ // ── P3 (04.09.): a cancel that is sat out is not a cancel ─────────────
+ //
+ // The repair's venv build had no wait loop, so pressing Cancel during it
+ // did nothing until `python -m venv` was finished by itself. These two
+ // drive the loop directly, with a real child and no Python needed.
+
+ /// A child that will not end on its own inside a test's lifetime.
+ fn a_child_that_never_ends() -> Child {
+ #[cfg(windows)]
+ let mut cmd = {
+ let mut c = std::process::Command::new("cmd");
+ c.args(["/C", "timeout", "/T", "120", "/NOBREAK"]);
+ c
+ };
+ #[cfg(not(windows))]
+ let mut cmd = {
+ let mut c = std::process::Command::new("sleep");
+ c.arg("120");
+ c
+ };
+ cmd.spawn().expect("a sleeping child could not be started")
+ }
+
+ #[test]
+ fn a_cancelled_child_is_given_up_on_in_a_fraction_of_its_runtime() {
+ let mut child = a_child_that_never_ends();
+ let flag = Arc::new(AtomicBool::new(false));
+ let trip = flag.clone();
+ std::thread::spawn(move || {
+ std::thread::sleep(std::time::Duration::from_millis(400));
+ trip.store(true, Ordering::SeqCst);
+ });
+
+ let started = std::time::Instant::now();
+ let out = wait_or_cancel(&mut child, Some(&flag), "the test child");
+ let waited = started.elapsed();
+
+ assert_eq!(out.err().as_deref(), Some("cancelled"));
+ // The child sleeps two minutes. Anything near that means the flag was
+ // read once at the start and never again, which is the bug.
+ assert!(
+ waited < std::time::Duration::from_secs(5),
+ "the cancel was sat out for {waited:?}"
+ );
+ // And the child is really gone, not just abandoned.
+ assert!(
+ child.try_wait().expect("try_wait after cancel").is_some(),
+ "the child outlived the cancel"
+ );
+ }
+
+ #[test]
+ fn a_child_left_alone_still_runs_to_its_own_end() {
+ // Negative control, and the important half: a helper that always
+ // answered "cancelled" would pass the test above and kill every venv
+ // build in the app. With no flag, and with a flag that stays down,
+ // the child must finish and hand back its own exit status.
+ for cancel in [None, Some(Arc::new(AtomicBool::new(false)))] {
+ #[cfg(windows)]
+ let mut child = std::process::Command::new("cmd")
+ .args(["/C", "exit", "0"])
+ .spawn()
+ .expect("a short child could not be started");
+ #[cfg(not(windows))]
+ let mut child = std::process::Command::new("true")
+ .spawn()
+ .expect("a short child could not be started");
+
+ let status = wait_or_cancel(&mut child, cancel.as_ref(), "the test child")
+ .expect("a child nobody cancelled came back as an error");
+ assert!(status.success(), "the child's own exit status was lost");
+ }
+ }
+
}
diff --git a/src-tauri/src/commands/install/comfy_install.rs b/src-tauri/src/commands/install/comfy_install.rs
index 716b186f..ce97b6c6 100644
--- a/src-tauri/src/commands/install/comfy_install.rs
+++ b/src-tauri/src/commands/install/comfy_install.rs
@@ -78,7 +78,7 @@ use super::CREATE_NO_WINDOW;
/// Best-effort in the other direction too: `None` when `sysinfo` lists no
/// mount point that is a prefix of `target_dir`, so a probing flake never
/// blocks a well-meaning install.
-fn check_install_disk_pressure(target_dir: &Path) -> Option<String> {
+pub(crate) fn check_install_disk_pressure(target_dir: &Path) -> Option<String> {
use sysinfo::Disks;
let disks = Disks::new_with_refreshed_list();
// Find the disk that contains the target dir. sysinfo's Disk::mount_point
@@ -284,8 +284,8 @@ pub fn install_comfyui(
};
// Set when `pip install -r requirements.txt` failed and the run carried
- // on with LU's own package list. Folder plus reason, so the live log
- // line and the line the finished run leaves behind agree (A15).
+ // on with the packages LU knows about. Folder plus reason, so the live
+ // log line and the line the finished run leaves behind agree (A15).
let mut requirements_fallback: Option<(String, &'static str)> = None;
let cancelled = || cancel_flag.load(Ordering::SeqCst);
@@ -450,7 +450,22 @@ pub fn install_comfyui(
// packages in one interpreter and start another: press Install after a
// Repair and the requirements land in the system Python while ComfyUI
// keeps running out of the venv that still has the hole.
- let existing_venv = crate::python::resolve_comfyui_venv_python(&target_dir);
+ // P3: a venv without its interpreter is not "no venv". Installing past
+ // it would put every package in the system Python while the launcher
+ // refuses to start out of anything else, so the run stops here with
+ // the sentence that names the missing file and the button that fixes
+ // it.
+ let existing_venv = match crate::python::comfy_venv_state(&target_dir) {
+ crate::python::ComfyVenv::Usable(p) => Some(p),
+ crate::python::ComfyVenv::Broken { venv_dir, interpreter } => {
+ update(
+ "error",
+ &crate::commands::process::comfy_broken_venv_message(&venv_dir, &interpreter),
+ );
+ return;
+ }
+ crate::python::ComfyVenv::Absent => None,
+ };
let effective_python = if let Some(venv_py) = existing_venv {
update(
"installing",
@@ -467,7 +482,7 @@ pub fn install_comfyui(
pip can install PyTorch + ComfyUI deps without touching your \
system Python …",
);
- match create_comfyui_venv(&target_dir, &python_bin) {
+ match create_comfyui_venv(&target_dir, &python_bin, Some(&cancel_flag)) {
Ok(venv_py) => {
let p = venv_py.to_string_lossy().to_string();
update(
@@ -476,6 +491,14 @@ pub fn install_comfyui(
);
p
}
+ // A cancel the user asked for is not a failed install. Without
+ // this arm the new cancel path inside `create_comfyui_venv`
+ // would arrive here as the card "Installing ComfyUI did not
+ // finish", over a run that stopped because they said so.
+ Err(e) if e == "cancelled" => {
+ update("cancelled", "Install cancelled while the venv was being created.");
+ return;
+ }
Err(e) => {
update("error", &format!("venv creation failed.\n\n{}", e));
return;
@@ -771,6 +794,43 @@ mod tests {
assert!(comfy_install_looks_finished(real.path()));
}
+ #[test]
+ fn a_cancelled_venv_build_is_not_reported_as_a_failed_install() {
+ // P3 (04.09.): `create_comfyui_venv` can answer "cancelled" now, and
+ // the install's only error arm turns whatever it gets into "venv
+ // creation failed", which the panel shows as "Installing ComfyUI did
+ // not finish." So a cancel the user asked for would arrive as a
+ // failure, on the PEP 668 path where this call lives.
+ //
+ // Read out of the source, like the order guards in comfy_repair.rs,
+ // and with needles split in half for the same reason: written whole
+ // they would match themselves here and the `.expect` could never fire.
+ let src = include_str!("comfy_install.rs");
+ let needle = |head: &str, tail: &str| format!("{head}{tail}");
+
+ let build = needle("create_comfyui_venv(&target_dir, &python_bin,", " Some(&cancel_flag))");
+ let cancelled_arm = needle("\"Install cancelled while the venv", " was being created.\"");
+ let failed_arm = needle("\"venv creation faile", "d.\\n\\n{}\"");
+
+ let at_build = src.find(&build).expect("the install's venv build no longer gets the cancel flag");
+ let at_cancelled = src.find(&cancelled_arm).expect("a cancelled venv build is reported as a failed install");
+ let at_failed = src.find(&failed_arm).expect("the venv failure arm is gone");
+
+ assert!(at_build < at_cancelled, "the cancel arm does not belong to this call");
+ assert!(
+ at_cancelled < at_failed,
+ "the general failure arm comes first, so it swallows the cancel"
+ );
+
+ for (what, n) in [("the venv build", build), ("the cancel arm", cancelled_arm), ("the failure arm", failed_arm)] {
+ assert_eq!(
+ src.matches(&n).count(),
+ 1,
+ "{what}: the search string finds itself in this test, so its .expect can never fire",
+ );
+ }
+ }
+
}
/// KF-28: der Doc-Kommentar über `check_install_disk_pressure` darf nur
diff --git a/src-tauri/src/commands/install/comfy_job.rs b/src-tauri/src/commands/install/comfy_job.rs
index afe69659..0379bdc8 100644
--- a/src-tauri/src/commands/install/comfy_job.rs
+++ b/src-tauri/src/commands/install/comfy_job.rs
@@ -36,6 +36,15 @@ pub async fn cancel_comfyui_install(app: tauri::AppHandle) -> Result<serde_json:
.map_err(|e| format!("cancel_comfyui_install task: {e}"))?
}
+/// What the log says the moment Cancel is pressed.
+///
+/// One sentence for all three jobs, because cancel cannot tell them apart:
+/// the only thing it can read is the shared status string, and that says
+/// "installing" whether git is cloning, pip is downloading, an import probe is
+/// running or a folder is being moved aside. A sentence naming a subprocess is
+/// therefore a guess, and P3 caught it guessing wrong.
+pub(crate) const CANCEL_WAIT_LINE: &str = "Cancellation requested. Stopping at the next safe point...";
+
fn cancel_comfyui_install_blocking(state: &AppState) -> Result<serde_json::Value, String> {
// OI-7: the flag is still what cancel uses, deliberately. It is scoped to
// the ComfyUI install — the poll loops that watch it now take the child's
@@ -52,7 +61,14 @@ fn cancel_comfyui_install_blocking(state: &AppState) -> Result<serde_json::Value
// "Cancelling…" indicator even before the spawn loop notices.
if s.status == "installing" || s.status == "downloading" {
s.status = "cancelling".to_string();
- s.logs.push("Cancellation requested, waiting for the active subprocess to exit...".to_string());
+ // P3 (04.09.): this line used to promise "waiting for the active
+ // subprocess to exit", and the only thing cancel can see is that
+ // status string, which says nothing about what kind of work is
+ // running. During the venv step of a repair there is no subprocess
+ // at all, so the sentence was simply wrong at the moment the user
+ // read it. What every step DOES share is the shape of the answer:
+ // each one stops at its next check.
+ s.logs.push(CANCEL_WAIT_LINE.to_string());
}
}
Ok(serde_json::json!({"status": "cancelling"}))
@@ -182,9 +198,17 @@ pub fn install_comfyui_status(state: State<'_, AppState>) -> Result<serde_json::
/// The live log line that names the fallback while it happens.
+///
+/// It says what the run really does, and only since P3 (04.09.) is that worth
+/// saying: the environment check holds its own list of packages
+/// (`KNOWN_IMPORT_NAMES`), imports every one of them and installs back what is
+/// missing. Before that the check read its target state from the same
+/// requirements.txt pip had just failed on, so the old wording, "installing
+/// LU's own package list instead", promised a list that did nothing.
pub(crate) fn requirements_fallback_log(folder: &str, reason: &str) -> String {
format!(
- "requirements.txt in {} could not be used ({}), installing LU's own package list instead.",
+ "requirements.txt in {} could not be used ({}), checking the packages LU knows about and \
+ installing the ones that are missing.",
folder, reason
)
}
@@ -215,8 +239,9 @@ pub(crate) fn finished_notice(
/// away with the log.
pub(crate) fn requirements_fallback_notice(folder: &str, reason: &str) -> String {
format!(
- "The requirements.txt in {} could not be used ({}), so LU installed its own package \
- list instead. Anything that file asks for on top of that list is not installed.",
+ "The requirements.txt in {} could not be used ({}), so LU checked the packages it knows \
+ about and installed the ones that were missing. Anything that file asks for on top of \
+ that list is not installed.",
folder, reason
)
}
@@ -292,7 +317,8 @@ mod tests {
requirements_failure_reason(INVENTED_PACKAGE),
);
assert!(notice.contains("C:\\Users\\ddrob\\ComfyUI"), "got: {notice}");
- assert!(notice.contains("LU installed its own package list instead"), "got: {notice}");
+ assert!(notice.contains("LU checked the packages it knows about"), "got: {notice}");
+ assert!(notice.contains("installed the ones that were missing"), "got: {notice}");
// The half the report asked for: the user has to learn that ComfyUI is
// now short of whatever that file wanted.
assert!(notice.contains("is not installed"), "got: {notice}");
@@ -345,4 +371,57 @@ mod tests {
assert_eq!(kind, "warn");
}
+ // ── P3 (04.09.): the line cancel writes must be true in every step ─────
+
+ #[test]
+ fn cancel_does_not_promise_a_subprocess_it_cannot_see() {
+ // The tester cancelled during "Removing the old venv", where no child
+ // process is running at all, and was told LU was waiting for one to
+ // exit. Cancel's only input is the status string, so it cannot know
+ // better; the fix is a sentence that does not claim to.
+ let state = AppState::new();
+ {
+ let mut s = state.install_status.lock().unwrap();
+ s.status = "installing".to_string();
+ s.logs.push("Removing the old venv (models, outputs and custom nodes stay untouched)...".to_string());
+ }
+
+ cancel_comfyui_install_blocking(&state).expect("cancel refused");
+
+ let s = state.install_status.lock().unwrap();
+ assert_eq!(s.status, "cancelling", "the panel was not switched over");
+ let last = s.logs.last().expect("cancel wrote no line at all");
+ assert!(
+ !last.to_lowercase().contains("subprocess"),
+ "cancel still names a subprocess: {last}"
+ );
+ assert!(last.contains("Cancellation requested"), "got: {last}");
+ // And it says what actually happens, so the wait is not a mystery.
+ assert!(last.contains("next safe point"), "got: {last}");
+ }
+
+ #[test]
+ fn cancel_writes_nothing_into_a_run_that_is_not_going() {
+ // The control on the other side. The status guard is what keeps a
+ // stray Cancel from stamping "Cancellation requested" over a finished
+ // run's log, and a test that only reads the sentence would not see it
+ // if that guard were dropped along with the old wording.
+ let state = AppState::new();
+ {
+ let mut s = state.install_status.lock().unwrap();
+ s.status = "complete".to_string();
+ s.logs.push("Repair finished. ComfyUI is ready.".to_string());
+ }
+
+ cancel_comfyui_install_blocking(&state).expect("cancel refused");
+
+ let s = state.install_status.lock().unwrap();
+ assert_eq!(s.status, "complete", "a finished run was marked as cancelling");
+ assert_eq!(
+ s.logs.last().map(String::as_str),
+ Some("Repair finished. ComfyUI is ready."),
+ "cancel wrote into a run that was already over"
+ );
+ }
+
}
diff --git a/src-tauri/src/commands/install/comfy_repair.rs b/src-tauri/src/commands/install/comfy_repair.rs
index e5238bcd..842b6ed2 100644
--- a/src-tauri/src/commands/install/comfy_repair.rs
+++ b/src-tauri/src/commands/install/comfy_repair.rs
@@ -27,7 +27,7 @@ use std::sync::atomic::Ordering;
use std::os::windows::process::CommandExt;
use tauri::State;
-use tracing::{error, info};
+use tracing::{error, info, warn};
use crate::state::AppState;
use crate::os_error;
@@ -41,7 +41,8 @@ use super::comfy_job::{ComfyJob, COMFY_JOB};
use super::comfy_job::comfy_job_busy_message;
use super::pip::pip_install_streaming_with_retry_cancellable;
use super::torch::plan_pytorch_install;
-use super::venv::{create_comfyui_venv, detect_venv_passengers};
+use super::venv::{create_comfyui_venv, detect_venv_passengers, retire_venv, sweep_retired_venvs};
+use crate::python::venv_python_path;
#[cfg(target_os = "windows")]
use super::git::{windows_git_install_hint, windows_git_probe, WindowsGitState};
#[cfg(target_os = "windows")]
@@ -145,8 +146,8 @@ pub fn repair_comfyui_env(state: State<'_, AppState>) -> Result<serde_json::Valu
};
// Set when `pip install -r requirements.txt` failed and the run carried
- // on with LU's own package list. Folder plus reason, so the live log
- // line and the line the finished run leaves behind agree (A15).
+ // on with the packages LU knows about. Folder plus reason, so the live
+ // log line and the line the finished run leaves behind agree (A15).
let mut requirements_fallback: Option<(String, &'static str)> = None;
// A16 (A15-2): before anything is deleted and before anything is
@@ -159,10 +160,33 @@ pub fn repair_comfyui_env(state: State<'_, AppState>) -> Result<serde_json::Valu
return;
}
+ // P3 (04.09.): the repair had exactly one cancel check, and it sat
+ // BEHIND the venv build. Everything before it was a click the app
+ // swallowed. This is the same helper the installer has had all along
+ // (comfy_install.rs), and the checks below are placed the same way:
+ // before each stretch that cannot be interrupted from inside.
+ let cancelled = || cancel_flag.load(Ordering::SeqCst);
+ if cancelled() {
+ update("cancelled", "Repair cancelled before anything was changed.");
+ return;
+ }
+
+ // The rebuild puts about two gigabytes back, and the old venv is now
+ // deleted alongside that instead of before it, so the drive gets less
+ // slack than it used to. Say so before the work starts, exactly as the
+ // installer does; a warning is not a refusal.
+ if let Some(warning) = super::comfy_install::check_install_disk_pressure(&comfy_dir) {
+ update("installing", &warning);
+ }
+
// A broken venv must go entirely: pip inside it would report the
// damaged packages as already satisfied, which is the exact dead end
// this command exists to break.
let venv_dir = comfy_dir.join("venv");
+ // Where the old venv went, once it has been moved aside. Deleted in the
+ // background further down, and waited on before the download, so the
+ // old copy and the new two gigabytes never fill the drive at once.
+ let mut retired_venv: Option<PathBuf> = None;
// OI-3: faster-whisper and Piper live in this venv too. Take stock
// BEFORE the delete, because afterwards there is nothing left to read.
let passengers = detect_venv_passengers(&venv_dir);
@@ -200,26 +224,120 @@ pub fn repair_comfyui_env(state: State<'_, AppState>) -> Result<serde_json::Valu
"installing",
"Removing the old venv (models, outputs and custom nodes stay untouched)...",
);
- if let Err(e) = std::fs::remove_dir_all(&venv_dir) {
- update("error", &venv_removal_error(&venv_dir, &e));
- return;
+ // Moved aside, not walked. Deleting in line was 40000 to 80000
+ // files inside one blocking call that never looks at the cancel
+ // flag, which is where P3's 76 seconds started. The new name is a
+ // sibling, so the same drive, so one metadata operation.
+ match retire_venv(&venv_dir) {
+ Ok(retired) => {
+ update(
+ "installing",
+ "The old venv has been set aside and is being deleted in the background.",
+ );
+ retired_venv = Some(retired);
+ }
+ Err(rename_failed) => {
+ // Windows refuses a rename while a process holds the
+ // directory itself open or has its working directory in
+ // it. Then there is no way around walking the tree, but it
+ // goes on its own thread so the cancel flag still gets
+ // read every 200 ms.
+ info!(error = %rename_failed, "venv rename failed, falling back to deleting it in place");
+ // The interpreter first, and on its own. What the fallback
+ // leaves behind on a cancel is a half-emptied venv still
+ // called `venv`, and this one file is what the launcher
+ // asks about before offering that venv to autostart. Since
+ // P3 a missing interpreter is answered with a message
+ // rather than a silent start on some other Python, so what
+ // this unlink now buys is that the message is the truth.
+ // One unlink, so it cannot be interrupted.
+ let _ = std::fs::remove_file(venv_python_path(&comfy_dir));
+ let doomed = venv_dir.clone();
+ let worker = std::thread::spawn(move || std::fs::remove_dir_all(&doomed));
+ while !worker.is_finished() {
+ if cancelled() {
+ update(
+ "cancelled",
+ "Repair cancelled. The old venv is still being deleted in the background.",
+ );
+ return;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(200));
+ }
+ if let Ok(Err(e)) = worker.join() {
+ update("error", &venv_removal_error(&venv_dir, &e));
+ return;
+ }
+ }
}
}
+ // One worker for everything that still has to be walked, in this order:
+ // the folder this run just set aside, then the leftovers of runs that
+ // died between their rename and the end of their delete. One thread and
+ // not two, because two would race each other over the same tree the
+ // moment the sweep listed the folder after this run's rename.
+ let deleting = {
+ let sweep_dir = comfy_dir.clone();
+ std::thread::spawn(move || {
+ if let Some(retired) = retired_venv {
+ if let Err(e) = std::fs::remove_dir_all(&retired) {
+ warn!(error = %e, folder = %retired.display(), "the retired venv could not be deleted");
+ }
+ }
+ sweep_retired_venvs(&sweep_dir);
+ })
+ };
+
+ // The check that was missing. It used to sit behind the venv build, so
+ // a cancel during the delete still wrote the line below and then built
+ // the whole venv before noticing.
+ if cancelled() {
+ update("cancelled", "Repair cancelled.");
+ return;
+ }
+
update(
"installing",
"Step 1/4: Creating a fresh isolated venv inside the ComfyUI folder...",
);
- let venv_py = match create_comfyui_venv(&comfy_dir, &python_bin) {
+ let venv_py = match create_comfyui_venv(&comfy_dir, &python_bin, Some(&cancel_flag)) {
Ok(p) => p.to_string_lossy().to_string(),
+ Err(e) if e == "cancelled" => {
+ update("cancelled", "Repair cancelled while the new venv was being created.");
+ return;
+ }
Err(e) => {
update("error", &format!("venv creation failed.\n\n{}", e));
return;
}
};
- if cancel_flag.load(Ordering::SeqCst) {
- update("cancelled", "Repair cancelled.");
- return;
+
+ // The old venv is still on the drive until that worker finishes, and
+ // the next step puts two gigabytes of PyTorch down beside it. Waiting
+ // here costs nothing when the delete is already through, and when it is
+ // not, waiting is the honest answer: the loop keeps reading the cancel
+ // flag, so the user is never more than 200 ms from leaving.
+ {
+ let mut said = false;
+ while !deleting.is_finished() {
+ if cancelled() {
+ update(
+ "cancelled",
+ "Repair cancelled. The old venv is still being deleted in the background.",
+ );
+ return;
+ }
+ if !said {
+ said = true;
+ update(
+ "installing",
+ "Waiting for the old venv to finish deleting before the download starts...",
+ );
+ }
+ std::thread::sleep(std::time::Duration::from_millis(200));
+ }
+ let _ = deleting.join();
}
let (torch_args, gpu_info) = plan_pytorch_install();
@@ -428,8 +546,19 @@ pub fn update_comfyui(state: State<'_, AppState>) -> Result<serde_json::Value, S
// Prefer the install's venv Python (same preference the launcher uses);
// refuse without a usable interpreter — a pulled core with stale
// requirements is worse than no update (frontend package pins move often).
- let python_bin = crate::python::resolve_comfyui_venv_python(&comfy_dir)
- .unwrap_or_else(|| state.python_bin.lock().unwrap().clone());
+ // P3: the same third answer the launcher has. Updating into the system
+ // Python while ComfyUI can only ever start out of this venv leaves the
+ // hole exactly where it was, one git pull further along.
+ let python_bin = match crate::python::comfy_venv_state(&comfy_dir) {
+ crate::python::ComfyVenv::Usable(p) => p,
+ crate::python::ComfyVenv::Broken { venv_dir, interpreter } => {
+ return fail(
+ &state,
+ &crate::commands::process::comfy_broken_venv_message(&venv_dir, &interpreter),
+ );
+ }
+ crate::python::ComfyVenv::Absent => state.python_bin.lock().unwrap().clone(),
+ };
if python_bin.is_empty() || !crate::python::is_real_python(&python_bin) {
return fail(
&state,
@@ -454,8 +583,8 @@ pub fn update_comfyui(state: State<'_, AppState>) -> Result<serde_json::Value, S
};
// Set when `pip install -r requirements.txt` failed and the run carried
- // on with LU's own package list. Folder plus reason, so the live log
- // line and the line the finished run leaves behind agree (A15).
+ // on with the packages LU knows about. Folder plus reason, so the live
+ // log line and the line the finished run leaves behind agree (A15).
let mut requirements_fallback: Option<(String, &'static str)> = None;
#[cfg(target_os = "windows")]
@@ -698,4 +827,55 @@ mod tests {
}
}
+ #[test]
+ fn the_repair_asks_about_cancel_between_the_delete_and_the_venv() {
+ // P3 (04.09.): Cancel during "Removing the old venv" took 75,8 seconds
+ // and the run carried on into step 1/4 anyway. Both halves of that were
+ // one missing line: the only cancel check in this stretch sat BEHIND
+ // `create_comfyui_venv`, so the delete, the step-1/4 log line and the
+ // whole venv build all happened after the click.
+ //
+ // Same shape as the precheck order test above, and for the same reason:
+ // the body is a thread inside a Tauri command, so the order is read out
+ // of this file. Needles split in half so they never match themselves
+ // here, and each one checked to occur exactly once.
+ let src = include_str!("comfy_repair.rs");
+ let needle = |head: &str, tail: &str| format!("{head}{tail}");
+
+ let removal = needle("\"Removing the old venv (models, outputs", " and custom nodes stay untouched)...\",");
+ let check = needle("update(\"cancelled\", \"Repair cance", "lled.\");");
+ let step_one = needle("\"Step 1/4: Creating a fresh isolated venv", " inside the ComfyUI folder...\",");
+ let build = needle("create_comfyui_venv(&comfy_dir, &python_bin,", " Some(&cancel_flag))");
+
+ let at_removal = src.find(&removal).expect("the venv removal step is gone");
+ let at_check = src.find(&check).expect("the repair no longer stops between the delete and the venv build");
+ let at_step_one = src.find(&step_one).expect("the step 1/4 line is gone");
+ let at_build = src.find(&build).expect("the venv build no longer gets the cancel flag");
+
+ assert!(at_removal < at_check, "the cancel check runs before the old venv is dealt with");
+ assert!(at_check < at_step_one, "the cancel check sits behind the step 1/4 line, so a cancelled run still announces it");
+ assert!(at_check < at_build, "the cancel check sits behind the venv build");
+
+ // The old way out has to be gone, not merely bypassed. A second path
+ // that deletes the venv in line would bring the 76 seconds back the
+ // next time somebody edits this function.
+ assert!(
+ !src.contains(&needle("std::fs::remove_dir_all(&venv", "_dir)")),
+ "the blocking in-line delete of the venv is still in this file"
+ );
+
+ for (what, n) in [
+ ("the venv removal step", removal),
+ ("the cancel check", check),
+ ("the step 1/4 line", step_one),
+ ("the venv build", build),
+ ] {
+ assert_eq!(
+ src.matches(&n).count(),
+ 1,
+ "{what}: the search string finds itself in this test, so its .expect can never fire",
+ );
+ }
+ }
+
}
diff --git a/src-tauri/src/commands/install/custom_nodes.rs b/src-tauri/src/commands/install/custom_nodes.rs
index 7fce0030..dbe101dc 100644
--- a/src-tauri/src/commands/install/custom_nodes.rs
+++ b/src-tauri/src/commands/install/custom_nodes.rs
@@ -261,8 +261,17 @@ fn install_node_requirements(
if !reqs.exists() {
return Ok(());
}
- let venv_python = crate::python::resolve_comfyui_venv_python(comfy_dir);
- let python_bin = venv_python.unwrap_or_else(|| fallback_python.to_string());
+ // P3, dritte Stelle mit derselben Frage: ein venv ohne Interpreter ist
+ // nicht "kein venv". Die Anforderungen des Knotens landeten sonst im
+ // System-Python, aus dem dieses ComfyUI nie startet, und der Knoten fehlt
+ // beim naechsten Lauf trotzdem.
+ let python_bin = match crate::python::comfy_venv_state(comfy_dir) {
+ crate::python::ComfyVenv::Usable(p) => p,
+ crate::python::ComfyVenv::Broken { venv_dir, interpreter } => {
+ return Err(crate::commands::process::comfy_broken_venv_message(&venv_dir, &interpreter));
+ }
+ crate::python::ComfyVenv::Absent => fallback_python.to_string(),
+ };
if python_bin.is_empty() {
return Err(format!(
"Custom node {} cloned, but cannot install requirements: \
diff --git a/src-tauri/src/commands/install/env_check.rs b/src-tauri/src/commands/install/env_check.rs
index 23687cd1..95ec4fc7 100644
--- a/src-tauri/src/commands/install/env_check.rs
+++ b/src-tauri/src/commands/install/env_check.rs
@@ -46,38 +46,53 @@ use super::pip::{
/// does not know is installed but not probed, which is exactly the behaviour
/// before this change.
///
-/// The list is names only. It pins no version, and a requirements.txt that
-/// stops naming a package stops it being probed.
-pub(crate) const KNOWN_IMPORT_NAMES: &[(&str, &str)] = &[
- ("torch", "torch"),
- ("torchvision", "torchvision"),
- ("torchaudio", "torchaudio"),
- ("torchsde", "torchsde"),
- ("numpy", "numpy"),
- ("einops", "einops"),
- ("transformers", "transformers"),
- ("tokenizers", "tokenizers"),
- ("sentencepiece", "sentencepiece"),
- ("safetensors", "safetensors"),
- ("aiohttp", "aiohttp"),
- ("yarl", "yarl"),
- ("pyyaml", "yaml"),
- ("pillow", "PIL"),
- ("scipy", "scipy"),
- ("tqdm", "tqdm"),
- ("psutil", "psutil"),
- ("alembic", "alembic"),
- ("sqlalchemy", "sqlalchemy"),
- ("av", "av"),
- ("kornia", "kornia"),
- ("spandrel", "spandrel"),
- ("soundfile", "soundfile"),
- ("pydantic", "pydantic"),
- ("pydantic-settings", "pydantic_settings"),
- ("requests", "requests"),
- ("filelock", "filelock"),
- ("blake3", "blake3"),
- ("simpleeval", "simpleeval"),
+/// The list is names only, it pins no version, and the third column says
+/// whether the package is probed even when requirements.txt has stopped naming
+/// it. `true` makes this table the floor of the check, which is the whole point
+/// of it: pip buys from requirements.txt, so a check that also reads its target
+/// state from requirements.txt cannot notice a line that is gone from both
+/// halves at once.
+///
+/// `false` means "probe this one only where the file asks for it", and the two
+/// PyTorch side wheels need exactly that. They come from `plan_pytorch_install`
+/// and not from this file, and a trio member in `report.missing` empties the
+/// heal list for the whole run (`dists_to_heal`) and fails it outright
+/// (`probe_verdict`). A floor that demanded torchvision or torchaudio would
+/// turn one absent side wheel into an aborted repair. `torch` itself stays on
+/// the floor because it is the DLL canary and is added first regardless.
+///
+/// Anything added here that not every ComfyUI version ships has to be `false`
+/// too, or the heal step installs a package that core never asked for.
+pub(crate) const KNOWN_IMPORT_NAMES: &[(&str, &str, bool)] = &[
+ ("torch", "torch", true),
+ ("torchvision", "torchvision", false),
+ ("torchaudio", "torchaudio", false),
+ ("torchsde", "torchsde", true),
+ ("numpy", "numpy", true),
+ ("einops", "einops", true),
+ ("transformers", "transformers", true),
+ ("tokenizers", "tokenizers", true),
+ ("sentencepiece", "sentencepiece", true),
+ ("safetensors", "safetensors", true),
+ ("aiohttp", "aiohttp", true),
+ ("yarl", "yarl", true),
+ ("pyyaml", "yaml", true),
+ ("pillow", "PIL", true),
+ ("scipy", "scipy", true),
+ ("tqdm", "tqdm", true),
+ ("psutil", "psutil", true),
+ ("alembic", "alembic", true),
+ ("sqlalchemy", "sqlalchemy", true),
+ ("av", "av", true),
+ ("kornia", "kornia", true),
+ ("spandrel", "spandrel", true),
+ ("soundfile", "soundfile", true),
+ ("pydantic", "pydantic", true),
+ ("pydantic-settings", "pydantic_settings", true),
+ ("requests", "requests", true),
+ ("filelock", "filelock", true),
+ ("blake3", "blake3", true),
+ ("simpleeval", "simpleeval", true),
];
/// The comment ComfyUI's own requirements.txt uses to separate the packages a
@@ -129,16 +144,23 @@ pub(crate) struct RequirementLine {
pub(crate) dist: String,
/// False below the optional-dependencies comment: reported, never fatal.
pub(crate) essential: bool,
+ /// The line carries an environment marker, so pip decides whether it
+ /// applies to this machine. Kept rather than dropped: `probe_targets` has
+ /// to see that the file has spoken about the package, or its floor would
+ /// put a Windows only package back on a Linux box.
+ pub(crate) platform_gated: bool,
}
/// Distribution names a requirements.txt asks for. Options (`-r`, `-e`,
/// `--index-url`), comments, blank lines and URLs are dropped; version
/// specifiers and extras are cut off.
///
-/// A line carrying an environment marker (`foo ; sys_platform == "win32"`) is
-/// dropped entirely rather than stripped down to its name. pip decides whether
-/// that line applies to this machine, and the probe has no business asking for
-/// a Windows only package on Linux and then calling the environment broken.
+/// A line carrying an environment marker (`foo ; sys_platform == "win32"`)
+/// comes back with `platform_gated` set. pip owns the marker, so the probe
+/// never asks for such a line, and it has no business asking for a Windows only
+/// package on Linux and then calling the environment broken. It is kept rather
+/// than dropped because the floor in `probe_targets` has to be able to tell
+/// "this file never mentions the package" from "this file excludes it here".
pub(crate) fn parse_requirement_lines(text: &str) -> Vec<RequirementLine> {
let mut out: Vec<RequirementLine> = Vec::new();
let mut essential = true;
@@ -153,11 +175,10 @@ pub(crate) fn parse_requirement_lines(text: &str) -> Vec<RequirementLine> {
if code.is_empty() || code.starts_with('-') {
continue;
}
- // pip owns the marker, so a line that has one is installed but not
- // probed.
- if code.contains(';') {
- continue;
- }
+ let (code, platform_gated) = match code.split_once(';') {
+ Some((name, _marker)) => (name.trim(), true),
+ None => (code, false),
+ };
// `name @ url` is still a name; a bare URL is not.
let head = code.split('@').next().unwrap_or("").trim();
if head.is_empty() || head.contains("://") {
@@ -170,33 +191,67 @@ pub(crate) fn parse_requirement_lines(text: &str) -> Vec<RequirementLine> {
if dist.is_empty() || out.iter().any(|l| l.dist == dist) {
continue;
}
- out.push(RequirementLine { dist, essential });
+ out.push(RequirementLine {
+ dist,
+ essential,
+ platform_gated,
+ });
}
out
}
-/// What the probe should import for a given requirements.txt. torch always
-/// comes first and always comes along: it is installed in its own step, it is
-/// the one package whose failure is a native library fault rather than a
-/// missing file, and it is the canary for every DLL report in A3.
+/// What the probe should import for a given requirements.txt.
+///
+/// The table is the floor and the file may only add to it. P3, 04.09.: the
+/// tester deleted the simpleeval line from requirements.txt, pressed Repair,
+/// and the check went from 28 packages to 27. pip buys from that file, so the
+/// package was missing from the venv afterwards and the run still finished on
+/// "ComfyUI is ready". The check has to hold a target state of its own, or it
+/// can only ever confirm the shopping list it was handed.
+///
+/// torch always comes first and always comes along: it is installed in its own
+/// step, it is the one package whose failure is a native library fault rather
+/// than a missing file, and it is the canary for every DLL report in A3.
+///
+/// A package that only the floor asks for is never essential. `probe_verdict`
+/// weighs Heal before it weighs essential, so such a package is reinstalled
+/// first and only ends the run in a warning when pip cannot bring it. An older
+/// or forked core that genuinely never needed it can therefore never fail a
+/// repair over it.
pub(crate) fn probe_targets(requirements: &str) -> Vec<ProbeTarget> {
+ let lines = parse_requirement_lines(requirements);
let mut out = vec![ProbeTarget {
dist: "torch".to_string(),
module: "torch",
essential: true,
}];
- for line in parse_requirement_lines(requirements) {
- if line.dist == "torch" {
+ for line in &lines {
+ if line.dist == "torch" || line.platform_gated {
continue;
}
- if let Some((_, module)) = KNOWN_IMPORT_NAMES.iter().find(|(d, _)| *d == line.dist) {
+ if let Some(&(_, module, _)) = KNOWN_IMPORT_NAMES.iter().find(|(d, _, _)| *d == line.dist) {
out.push(ProbeTarget {
- dist: line.dist,
+ dist: line.dist.clone(),
module,
essential: line.essential,
});
}
}
+ for &(dist, module, always) in KNOWN_IMPORT_NAMES {
+ // A file that names the package has the last word, whether it asks for
+ // it or excludes it with a marker.
+ if !always
+ || out.iter().any(|t| t.dist == dist)
+ || lines.iter().any(|l| l.dist == dist)
+ {
+ continue;
+ }
+ out.push(ProbeTarget {
+ dist: dist.to_string(),
+ module,
+ essential: false,
+ });
+ }
out
}
@@ -603,7 +658,12 @@ fn run_import_probe_bounded(
let status = install_status.cloned();
std::thread::spawn(move || {
for line in BufReader::new(stdout).lines().map_while(Result::ok) {
- let line = line.trim().to_string();
+ // Vor allem anderen, denn PROBE_FAIL kommt hier heraus und
+ // traegt `str(e)` des Interpreters (P3, 7.3): "ImportError: DLL
+ // load failed while importing _core: Das angegebene Modul wurde
+ // nicht gefunden." Diese Zeile landet woertlich in der
+ // Fehlermeldung, die der Kunde liest.
+ let line = os_error::english_child_text(line.trim()).into_owned();
if line.is_empty() {
continue;
}
@@ -624,7 +684,9 @@ fn run_import_probe_bounded(
let done = readers_done.clone();
std::thread::spawn(move || {
for line in BufReader::new(stderr).lines().map_while(Result::ok) {
- let line = line.trim().to_string();
+ // Dieselbe Behandlung wie auf stdout: der Absturztext geht
+ // ueber `promote_crash_from_stderr` in dieselbe Meldung.
+ let line = os_error::english_child_text(line.trim()).into_owned();
if !line.is_empty() {
if let Ok(mut v) = sink.lock() {
v.push(line);
@@ -674,9 +736,6 @@ fn run_import_probe_bounded(
let stdout_text = out_lines.lock().map(|v| v.join("\n")).unwrap_or_default();
let stderr_text = err_lines.lock().map(|v| v.join("\n")).unwrap_or_default();
- // A localised Windows wording in the interpreter's own words would
- // otherwise be quoted straight into an English message.
- let stderr_text = os_error::sanitize_os_wording(&stderr_text).into_owned();
let survived = exit.map(|s| s.success()).unwrap_or(false);
let mut report = parse_import_probe(&stdout_text, survived);
report.timed_out = timed_out;
@@ -700,7 +759,24 @@ pub(super) fn verify_and_heal_environment(
install_status: &Arc<Mutex<InstallState>>,
cancel: Option<&Arc<AtomicBool>>,
) -> Result<(), String> {
- let text = fs::read_to_string(requirements).unwrap_or_default();
+ // A file that cannot be read used to become an empty string without a
+ // word, and the check then asked for a single package and called the
+ // environment ready. The floor in `probe_targets` keeps the check whole,
+ // and this says why it is running on the floor alone.
+ let text = match fs::read_to_string(requirements) {
+ Ok(t) => t,
+ Err(e) => {
+ push_install_log(
+ install_status,
+ &format!(
+ "requirements.txt could not be read ({}), checking the packages LU knows \
+ about instead.",
+ os_error::english(&e)
+ ),
+ );
+ String::new()
+ }
+ };
let targets = probe_targets(&text);
let modules: Vec<&str> = targets.iter().map(|t| t.module).collect();
push_install_log(
@@ -789,7 +865,8 @@ mod tests {
use super::super::pip::VC_REDIST_PAGE;
/// The shape of ComfyUI's own requirements.txt, including the comment that
- /// splits it and the two names the mods were typing into the ticket.
+ /// splits it, the two names the mods were typing into the ticket, and the
+ /// line P3 took out of the file on 04.09.
const COMFY_REQUIREMENTS: &str = "comfyui-frontend-package\n\
torch\n\
torchsde\n\
@@ -800,6 +877,7 @@ mod tests {
SQLAlchemy\n\
alembic\n\
av\n\
+ simpleeval>=1.0.0\n\
#non essential dependencies:\n\
kornia>=0.7.1\n\
spandrel\n\
@@ -850,14 +928,23 @@ mod tests {
#[test]
fn a_line_with_an_environment_marker_is_installed_but_never_probed() {
// pip owns the marker. Probing a Windows only package on Linux and
- // then calling the environment broken is a bug we would have shipped.
+ // then calling the environment broken is a bug we would have shipped,
+ // and the floor must not smuggle such a package back in.
let with_marker = "torch\nsoundfile ; sys_platform == \"win32\"\n";
let modules: Vec<&str> = probe_targets(with_marker).iter().map(|t| t.module).collect();
- assert_eq!(modules, vec!["torch"], "a marked line was probed: {modules:?}");
- // Negative control: the same package without a marker IS probed, so
- // the rule is about the marker and not about soundfile.
- let plain: Vec<&str> = probe_targets("torch\nsoundfile\n").iter().map(|t| t.module).collect();
- assert!(plain.contains(&"soundfile"), "{plain:?}");
+ assert!(!modules.contains(&"soundfile"), "a marked line was probed: {modules:?}");
+ // Negative control, on the one package the table does NOT stand behind
+ // on its own, so the marker rule and the floor cannot cover for each
+ // other: with the marker torchaudio stays out, without it, it is
+ // probed. Run against soundfile this would prove nothing, because the
+ // floor asks for soundfile either way.
+ let gated: Vec<&str> = probe_targets("torch\ntorchaudio ; sys_platform == \"win32\"\n")
+ .iter()
+ .map(|t| t.module)
+ .collect();
+ assert!(!gated.contains(&"torchaudio"), "{gated:?}");
+ let plain: Vec<&str> = probe_targets("torch\ntorchaudio\n").iter().map(|t| t.module).collect();
+ assert!(plain.contains(&"torchaudio"), "{plain:?}");
}
#[test]
@@ -865,15 +952,138 @@ mod tests {
// Negative control: guessing would turn a healthy environment into a
// false alarm and send the customer to Repair environment for nothing.
let targets = probe_targets("comfyui-workflow-templates\nsome-brand-new-thing\n");
- let modules: Vec<&str> = targets.iter().map(|t| t.module).collect();
- assert_eq!(modules, vec!["torch"], "an unknown package was guessed at: {modules:?}");
+ for t in &targets {
+ assert!(
+ KNOWN_IMPORT_NAMES.iter().any(|(d, _, _)| *d == t.dist),
+ "a package the table does not know was probed: {}",
+ t.dist,
+ );
+ }
+ let dists: Vec<&str> = targets.iter().map(|t| t.dist.as_str()).collect();
+ assert!(!dists.contains(&"some-brand-new-thing"), "{dists:?}");
+ assert!(!dists.contains(&"comfyui-workflow-templates"), "{dists:?}");
}
#[test]
fn requirements_parsing_drops_the_lines_that_are_not_packages() {
let reqs = "# a comment\n\n-r other.txt\n--index-url https://example.invalid/simple\nhttps://example.invalid/wheel.whl\ntorch==2.9.1\nPyYAML\nspandrel ; python_version >= \"3.10\"\nkornia[extra]>=0.7\n";
- let dists: Vec<String> = parse_requirement_lines(reqs).into_iter().map(|l| l.dist).collect();
- assert_eq!(dists, vec!["torch", "pyyaml", "kornia"], "got {dists:?}");
+ let lines = parse_requirement_lines(reqs);
+ let dists: Vec<&str> = lines.iter().map(|l| l.dist.as_str()).collect();
+ assert_eq!(dists, vec!["torch", "pyyaml", "spandrel", "kornia"], "got {dists:?}");
+ // The marked line keeps its name and its mark: the probe still never
+ // asks for it, and the floor can tell that this file has spoken about
+ // spandrel.
+ let gated: Vec<&str> = lines
+ .iter()
+ .filter(|l| l.platform_gated)
+ .map(|l| l.dist.as_str())
+ .collect();
+ assert_eq!(gated, vec!["spandrel"], "got {gated:?}");
+ }
+
+ #[test]
+ fn a_line_that_disappears_from_the_file_is_still_probed() {
+ // P3, 04.09.: simpleeval taken out of requirements.txt, Repair
+ // pressed, and the check went from 28 packages to 27. pip installs
+ // from the same file, so the package was gone from the venv and the
+ // run still ended on "ComfyUI is ready".
+ let full = probe_targets(COMFY_REQUIREMENTS);
+ let short = probe_targets(&COMFY_REQUIREMENTS.replace("simpleeval>=1.0.0\n", ""));
+ let modules: Vec<&str> = short.iter().map(|t| t.module).collect();
+ assert!(modules.contains(&"simpleeval"), "the check shrank with the file: {modules:?}");
+ assert_eq!(short.len(), full.len(), "{} against {}", short.len(), full.len());
+ // Negative control one, the tester's second attempt: a name the table
+ // does not know does not grow the list either, so this is not "probe
+ // whatever the file says".
+ let added = probe_targets(&format!("{COMFY_REQUIREMENTS}pywin32\n"));
+ assert!(!added.iter().any(|t| t.dist == "pywin32"), "pywin32 became a target");
+ assert_eq!(added.len(), full.len());
+ // Negative control two: the floor is not "the whole table, whatever
+ // the file says" either. A file that excludes a package for this
+ // platform still wins.
+ let gated = probe_targets(&format!("{COMFY_REQUIREMENTS}soundfile ; sys_platform == \"win32\"\n"));
+ assert!(!gated.iter().any(|t| t.dist == "soundfile"), "the floor overrode a marker");
+ }
+
+ #[test]
+ fn a_package_the_file_no_longer_names_is_reinstalled_and_not_just_reported() {
+ // The other half of the tester's run: being probed is worth nothing
+ // unless the heal step really reaches the package.
+ let short = probe_targets(&COMFY_REQUIREMENTS.replace("simpleeval>=1.0.0\n", ""));
+ let report = parse_import_probe(
+ "PROBE_VENV 1\nPROBE_TRY torch\nPROBE_OK torch\n\
+ PROBE_TRY simpleeval\nPROBE_FAIL simpleeval :: ModuleNotFoundError: No module named 'simpleeval'\n\
+ PROBE_DONE\n",
+ true,
+ );
+ assert_eq!(dists_to_heal(&short, &report), vec!["simpleeval"]);
+ assert_eq!(
+ probe_verdict(&short, &report, false),
+ ProbeVerdict::Heal(vec!["simpleeval".to_string()]),
+ );
+ // Negative control one: once the heal has run, the same result is not
+ // another trip round the pip loop.
+ assert!(!matches!(probe_verdict(&short, &report, true), ProbeVerdict::Heal(_)));
+ // Negative control two, and the reason the two PyTorch side wheels are
+ // not on the floor: a missing trio member empties the heal list for
+ // the WHOLE run and fails it outright, so a floor that asked for
+ // torchaudio would turn one absent side wheel into an aborted repair.
+ assert!(!probe_targets("").iter().any(|t| t.dist == "torchaudio"), "torchaudio is on the floor");
+ let trio = parse_import_probe(
+ "PROBE_VENV 1\nPROBE_TRY torchaudio\nPROBE_FAIL torchaudio :: ModuleNotFoundError: No module named 'torchaudio'\nPROBE_DONE\n",
+ true,
+ );
+ let asked = probe_targets("torch\ntorchaudio\n");
+ assert!(dists_to_heal(&asked, &trio).is_empty());
+ assert!(matches!(probe_verdict(&asked, &trio, false), ProbeVerdict::Fail(_)));
+ }
+
+ #[test]
+ fn a_requirements_txt_that_cannot_be_read_does_not_shrink_the_check_to_torch() {
+ // The sharper edge of the same line: an unreadable file became an
+ // empty string, the check asked for one package and the run said
+ // ready. Now it falls back on the whole floor.
+ let targets = probe_targets("");
+ let modules: Vec<&str> = targets.iter().map(|t| t.module).collect();
+ assert_eq!(modules[0], "torch", "{modules:?}");
+ for m in ["sqlalchemy", "yaml", "PIL", "simpleeval"] {
+ assert!(modules.contains(&m), "{m} fell out of the check: {modules:?}");
+ }
+ // Exactly the floor, so a `false` in the table means what it says.
+ for &(dist, module, always) in KNOWN_IMPORT_NAMES {
+ assert_eq!(modules.contains(&module), always, "{dist}");
+ }
+ // And a floor package can never fail a run on its own: torch stays the
+ // one mandatory name, which is what keeps the DLL branch alive.
+ assert!(targets[0].essential, "torch stopped being mandatory");
+ assert!(
+ targets.iter().skip(1).all(|t| !t.essential),
+ "a package only the floor asks for could fail a repair",
+ );
+ }
+
+ #[test]
+ fn a_requirements_file_that_will_not_open_says_so_and_checks_the_floor() {
+ // The read error used to be swallowed by unwrap_or_default(), and the
+ // panel then showed "importing 1 packages" with nothing to explain it.
+ // No interpreter needed: the probe is handed a binary that cannot
+ // start, and what is asserted is the two log lines written before it.
+ let state = Arc::new(Mutex::new(InstallState::default()));
+ let gone = std::env::temp_dir().join("lu-no-such-requirements-abc123.txt");
+ let _ = std::fs::remove_file(&gone);
+ let _ = verify_and_heal_environment("lu-not-a-python-binary", &gone, &state, None);
+ let logs = state.lock().unwrap().logs.join("\n");
+ assert!(logs.contains("requirements.txt could not be read"), "{logs}");
+ let count = format!("importing {} packages", probe_targets("").len());
+ assert!(logs.contains(&count), "the check did not fall back on the floor: {logs}");
+ // Negative control: a file that IS readable says nothing of the kind.
+ let there = std::env::temp_dir().join("lu-a-real-requirements-abc123.txt");
+ std::fs::write(&there, "torch\n").expect("fixture");
+ let second = Arc::new(Mutex::new(InstallState::default()));
+ let _ = verify_and_heal_environment("lu-not-a-python-binary", &there, &second, None);
+ let quiet = second.lock().unwrap().logs.join("\n");
+ let _ = std::fs::remove_file(&there);
+ assert!(!quiet.contains("could not be read"), "{quiet}");
}
#[test]
@@ -1007,6 +1217,37 @@ mod tests {
assert!(msg.contains(VC_REDIST_PAGE), "no way out of the DLL failure: {msg}");
}
+ #[test]
+ fn ein_probe_fail_mit_deutschem_windows_satz_kommt_englisch_in_der_meldung_an() {
+ // P3, 7.2 und 7.3: der Interpreter schreibt `str(e)` auf stdout, und
+ // auf einem deutschen Windows ist die Haelfte davon deutsch. Diese
+ // Zeile landet woertlich in {reason} der Fail-Meldung.
+ //
+ // Die Zeile mit der Marke steht hier, weil sie ueberall beweisbar ist:
+ // die Umschrift liest die Nummer und schneidet den fremden Satz
+ // strukturell ab. Die Zeile OHNE Nummer (7.3) kann nur das Windows des
+ // Nutzers aufloesen, dafuer steht der Beweis mit Attrappe in
+ // `os_error::tests`.
+ let raw = "PROBE_FAIL torch :: OSError: [WinError 126] Das angegebene Modul wurde nicht \
+ gefunden. Error loading \
+ \"C:\\Users\\ddrob\\ComfyUI\\venv\\Lib\\site-packages\\torch\\lib\\c10_cuda.dll\" \
+ or one of its dependencies.";
+ // Genau der Griff, den der stdout-Leser der Probe tut.
+ let line = os_error::english_child_text(raw).into_owned();
+ let out = format!("PROBE_VENV 1\nPROBE_TRY torch\n{line}\nPROBE_DONE\n");
+ let report = parse_import_probe(&out, true);
+ let msg = match probe_verdict(&probe_targets(COMFY_REQUIREMENTS), &report, false) {
+ ProbeVerdict::Fail(m) => m,
+ other => panic!("{other:?}"),
+ };
+ assert!(!msg.contains("Das angegebene Modul"), "der deutsche Satz steht in der Meldung: {msg}");
+ assert!(msg.contains("the specified module could not be found"), "{msg}");
+ // Und alles, was die Meldung vorher konnte, kann sie weiter.
+ assert!(msg.contains("torch"), "{msg}");
+ assert!(msg.contains("c10_cuda.dll"), "der DLL-Pfad ist verloren gegangen: {msg}");
+ assert!(msg.contains(VC_REDIST_PAGE), "no way out of the DLL failure: {msg}");
+ }
+
#[test]
fn an_interpreter_that_dies_mid_import_names_the_module_that_killed_it() {
// petermanmancusso: "Process exited with code 0xC0000005". No
diff --git a/src-tauri/src/commands/install/mod.rs b/src-tauri/src/commands/install/mod.rs
index 26ee486a..d6ad959f 100644
--- a/src-tauri/src/commands/install/mod.rs
+++ b/src-tauri/src/commands/install/mod.rs
@@ -220,7 +220,7 @@ mod tests {
.nth(1)
.expect("install_comfyui");
let venv_at = install_body
- .find("resolve_comfyui_venv_python")
+ .find("comfy_venv_state")
.expect("install_comfyui ignores an existing venv");
let pep_at = install_body
.find("is_pep668_protected")
@@ -231,6 +231,38 @@ mod tests {
);
}
+ /// Wer Pakete fuer ComfyUI einkauft, stellt die venv-Frage vollstaendig.
+ ///
+ /// P3: `resolve_comfyui_venv_python` kennt zwei Antworten, und ein venv
+ /// ohne Interpreter faellt in dieselbe Schublade wie "hier war nie eines".
+ /// Fuer den Launcher war das der stille Rueckfall auf ein fremdes Python;
+ /// hier ist es dasselbe eine Ebene tiefer, naemlich pip in einen
+ /// Interpreter, aus dem dieses ComfyUI nie startet.
+ #[test]
+ fn every_comfy_install_path_asks_the_full_venv_question() {
+ for name in ["comfy_install.rs", "comfy_repair.rs", "custom_nodes.rs"] {
+ let src = ausgeliefert(datei(name));
+ assert!(
+ !src.contains("resolve_comfyui_venv_python"),
+ "{name}: nimmt die Zwei-Antworten-Frage und faellt an einem kaputten venv vorbei",
+ );
+ assert!(
+ src.contains("comfy_broken_venv_message("),
+ "{name}: erkennt das kaputte venv und sagt es niemandem",
+ );
+ }
+
+ // Die eine bewusste Ausnahme, damit sie nicht beim naechsten Durchgang
+ // als vergessene Stelle wieder auftaucht: `resolve_lu_python` versorgt
+ // Whisper und die Sprachausgabe. Die brauchen irgendein Python mit den
+ // richtigen Paketen, nicht das, aus dem ComfyUI startet, also ist der
+ // Rueckfall dort richtig.
+ assert!(
+ ausgeliefert(datei("venv.rs")).contains("resolve_comfyui_venv_python"),
+ "venv.rs::resolve_lu_python ist umgezogen: pruef, ob die Ausnahme noch gilt",
+ );
+ }
+
// ── Ticket 003: jeder Python-Start setzt die Kodierung ─────────────────
#[test]
diff --git a/src-tauri/src/commands/install/pip.rs b/src-tauri/src/commands/install/pip.rs
index b0c411d7..33664466 100644
--- a/src-tauri/src/commands/install/pip.rs
+++ b/src-tauri/src/commands/install/pip.rs
@@ -579,6 +579,14 @@ pub(crate) fn pip_install_streaming_with_retry_raw(
if let Some(out) = stdout {
let reader = BufReader::new(out);
for line in reader.lines().map_while(Result::ok) {
+ // Die Woerter des Betriebssystems sind unsere, auch wenn
+ // pip sie weitergereicht hat: diese Zeilen stehen in der
+ // Fortschrittskarte und im snippet, das
+ // `diagnose_pip_error_inner` an die Meldung haengt. Die
+ // Marken "winerror 5]", "winerror 126" und "winerror 1114"
+ // bleiben dabei stehen, `pip_failure_kind` verliert also
+ // nichts und gewinnt "access is denied" hinzu.
+ let line = os_error::english_child_text(&line).into_owned();
let trimmed = line.trim();
if !trimmed.is_empty() {
if let Some(bytes) = parse_pip_download_size(trimmed) {
@@ -599,6 +607,10 @@ pub(crate) fn pip_install_streaming_with_retry_raw(
if let Some(err) = stderr {
let reader = BufReader::new(err);
for line in reader.lines().map_while(Result::ok) {
+ // Einmal umgeschrieben, in beide Senken: der Mitschnitt
+ // entscheidet ueber den Wiederholungsversuch UND liefert
+ // den Ausschnitt fuer die Fehlermeldung.
+ let line = os_error::english_child_text(&line).into_owned();
if let Ok(mut buf) = stderr_capture_clone.lock() {
buf.push_str(&line);
buf.push('\n');
@@ -710,10 +722,10 @@ pub(crate) fn pip_install_streaming_with_retry_raw(
///
/// A15, Windows Nachlauf 02.09.: a requirements.txt whose first line named a
/// package that does not exist made `pip install -r` fail, the run went on with
-/// LU's own package list, and it ended on "Environment repaired" with nothing
-/// said. The fallback itself is right, because a core whose file will not
-/// resolve must not block a rebuild. The silence is not: the user is left with
-/// a ComfyUI missing whatever that file asked for on top of our list.
+/// the packages LU knows about, and it ended on "Environment repaired" with
+/// nothing said. The fallback itself is right, because a core whose file will
+/// not resolve must not block a rebuild. The silence is not: the user is left
+/// with a ComfyUI missing whatever that file asked for on top of our list.
pub(crate) fn requirements_failure_reason(pip_output: &str) -> &'static str {
match pip_failure_kind(pip_output) {
PipFailureKind::NoMatchingWheel => "pip found no installable version for a package it names",
@@ -1246,6 +1258,29 @@ mod tests {
assert_eq!(pip_failure_kind(text2), PipFailureKind::NativeLoadFailure);
}
+ /// Der Einordner sitzt seit P3 HINTER der Umschrift, also sieht er ab jetzt
+ /// umgeschriebenen Text. Der Test darueber prueft ihn weiter allein und
+ /// bleibt richtig; dieser hier prueft die Reihenfolge.
+ #[test]
+ fn die_umschrift_nimmt_dem_einordner_nichts_und_gibt_ihm_etwas() {
+ // Die Marke bleibt stehen, nur der Satz dahinter wird getauscht, also
+ // findet der Einordner sein Futter unveraendert.
+ let roh = "OSError: [WinError 1114] Eine DLL-Initialisierungsroutine ist fehlgeschlagen.";
+ let umgeschrieben = crate::os_error::english_child_text(roh).into_owned();
+ assert!(umgeschrieben.contains("[WinError 1114]"), "{umgeschrieben}");
+ assert!(!umgeschrieben.contains("Initialisierungsroutine"), "{umgeschrieben}");
+ assert_eq!(pip_failure_kind(&umgeschrieben), PipFailureKind::NativeLoadFailure);
+
+ // Und der Gewinn: ein verweigerter Zugriff wird auf jedem Windows als
+ // solcher gelesen, nicht nur auf einem englischen.
+ let refused = crate::os_error::english_child_text(
+ "ERROR: Could not install packages due to an OSError: [WinError 5] Zugriff verweigert",
+ )
+ .into_owned();
+ assert!(reads_as_refused(&refused.to_lowercase()), "{refused}");
+ assert!(is_permission_denied_pip_error(&refused), "{refused}");
+ }
+
#[test]
fn an_access_violation_is_a_native_load_failure() {
assert_eq!(
@@ -1342,7 +1377,10 @@ mod tests {
assert_eq!(reason, "pip found no installable version for a package it names");
let line = requirements_fallback_log("C:\\Users\\ddrob\\ComfyUI", reason);
assert!(line.starts_with("requirements.txt in C:\\Users\\ddrob\\ComfyUI could not be used ("), "got: {line}");
- assert!(line.ends_with("installing LU's own package list instead."), "got: {line}");
+ assert!(
+ line.ends_with("checking the packages LU knows about and installing the ones that are missing."),
+ "got: {line}",
+ );
assert!(line.contains(reason), "got: {line}");
}
diff --git a/src-tauri/src/commands/install/python.rs b/src-tauri/src/commands/install/python.rs
index e08f05e2..a9c17e30 100644
--- a/src-tauri/src/commands/install/python.rs
+++ b/src-tauri/src/commands/install/python.rs
@@ -226,6 +226,11 @@ pub fn install_python(state: State<'_, AppState>) -> Result<serde_json::Value, S
if let Some(out) = stdout {
let reader = BufReader::new(out);
for line in reader.lines().map_while(Result::ok) {
+ // winget ist ein fremder Prozess, seine Zeilen
+ // stehen in unserer Fortschrittskarte, und ein
+ // Installationsfehler kommt vom Windows-Installer
+ // in der Systemsprache.
+ let line = os_error::english_child_text(&line).into_owned();
let trimmed = line.trim();
if !trimmed.is_empty() {
if let Ok(mut s) = stdout_state.lock() {
@@ -240,6 +245,7 @@ pub fn install_python(state: State<'_, AppState>) -> Result<serde_json::Value, S
if let Some(err) = stderr {
let reader = BufReader::new(err);
for line in reader.lines().map_while(Result::ok) {
+ let line = os_error::english_child_text(&line).into_owned();
let trimmed = line.trim();
if !trimmed.is_empty() {
if let Ok(mut s) = stderr_state.lock() {
diff --git a/src-tauri/src/commands/install/venv.rs b/src-tauri/src/commands/install/venv.rs
index f888a6b7..dc76fa12 100644
--- a/src-tauri/src/commands/install/venv.rs
+++ b/src-tauri/src/commands/install/venv.rs
@@ -14,11 +14,16 @@
//! ist: auf einer PEP-668-Distribution ist es der einzige Weg, überhaupt zu
//! installieren.
+use std::io::Read;
use std::path::{Path, PathBuf};
use crate::python::python_command;
use std::process::Stdio;
+use std::sync::atomic::AtomicBool;
+use std::sync::{Arc, Mutex};
+use tracing::warn;
+use super::children::{wait_or_cancel, TrackedInstallerChild};
use crate::os_error;
use crate::python::venv_python_path;
use crate::state::AppState;
@@ -59,7 +64,27 @@ pub fn is_pep668_protected(python_bin: &str) -> bool {
String::from_utf8_lossy(&out.stdout).trim() == "YES"
}
-pub fn create_comfyui_venv(comfyui_dir: &Path, python_bin: &str) -> Result<PathBuf, String> {
+/// Create a venv inside `comfyui_dir/venv` using the system `python_bin`.
+/// Returns the path to the venv's Python interpreter on success. On Arch
+/// boxes that haven't installed the `python-virtualenv` package this can
+/// fail with `No module named venv`, and we surface that with an actionable
+/// hint pointing at the right pacman / apt invocation.
+///
+/// `cancel` is read every 200 ms while the child runs, and it has to be:
+/// `python -m venv` pulls `ensurepip` in, which is tens of seconds on Windows.
+/// P3 (04.09.): cancelling a repair took 76 seconds, and part of that was this
+/// call being sat out to the end because it was a single blocking `output()`.
+///
+/// On a cancel the half-built venv is deleted again before `Err("cancelled")`
+/// goes back. `resolve_comfyui_venv_python` asks only whether the interpreter
+/// file exists, and `python -m venv` writes that file BEFORE it runs
+/// `ensurepip`, so leaving the ruin behind would have autostart launching
+/// ComfyUI out of an env with an empty site-packages.
+pub fn create_comfyui_venv(
+ comfyui_dir: &Path,
+ python_bin: &str,
+ cancel: Option<&Arc<AtomicBool>>,
+) -> Result<PathBuf, String> {
let venv_dir = comfyui_dir.join("venv");
// venv is idempotent: re-running on an existing dir just no-ops, but be
// explicit so the log reads cleanly.
@@ -70,15 +95,48 @@ pub fn create_comfyui_venv(comfyui_dir: &Path, python_bin: &str) -> Result<PathB
let mut cmd = python_command(python_bin);
cmd.args(["-m", "venv", venv_dir.to_string_lossy().as_ref()])
- .stdout(Stdio::piped())
+ // Only stderr is ever read. stdout went into a buffer nobody looked at
+ // even before this, and an unread pipe is one more way to block while
+ // we are supposed to be polling the cancel flag.
+ .stdout(Stdio::null())
.stderr(Stdio::piped());
- let out = cmd
- .output()
+ let mut child = cmd
+ .spawn()
.map_err(|e| format!("Could not spawn `python -m venv`: {}", os_error::english(&e)))?;
+ // Same registry every other installer child joins, so closing the app
+ // mid-build does not leave venv and ensurepip resident.
+ let _tracked = TrackedInstallerChild::register(child.id());
+
+ // Drained next to the wait, not after it: a full pipe would stall the
+ // child while the loop below thinks it is still working.
+ let stderr_pipe = child.stderr.take();
+ let stderr_buf = Arc::new(Mutex::new(String::new()));
+ let sink = stderr_buf.clone();
+ let reader = std::thread::spawn(move || {
+ if let Some(mut pipe) = stderr_pipe {
+ let mut text = String::new();
+ let _ = pipe.read_to_string(&mut text);
+ if let Ok(mut slot) = sink.lock() {
+ *slot = text;
+ }
+ }
+ });
- if !out.status.success() {
- let stderr = String::from_utf8_lossy(&out.stderr);
+ let waited = wait_or_cancel(&mut child, cancel, "`python -m venv`");
+ let _ = reader.join();
+ let stderr = stderr_buf.lock().map(|b| b.clone()).unwrap_or_default();
+
+ let exit_status = match waited {
+ Ok(s) => s,
+ Err(e) if e == "cancelled" => {
+ let _ = std::fs::remove_dir_all(&venv_dir);
+ return Err(e);
+ }
+ Err(e) => return Err(e),
+ };
+
+ if !exit_status.success() {
let lower = stderr.to_lowercase();
// Most common Arch / minimal-Python failure: stdlib venv module
// isn't available because the distro packages it separately.
@@ -110,6 +168,81 @@ pub fn create_comfyui_venv(comfyui_dir: &Path, python_bin: &str) -> Result<PathB
Ok(venv_py)
}
+// ── P3 (04.09.): the old venv is moved out of the way, not deleted in line ──
+
+/// The prefix every set-aside venv carries.
+///
+/// It starts with `venv` on purpose so it sorts next to the real one for
+/// anybody reading the folder, and it is NOT `venv` or `.venv`, which is the
+/// whole point: `python.rs::resolve_comfyui_venv_python` looks at exactly
+/// those two names, so a retired folder is invisible to the launcher, to
+/// autostart and to `resolve_lu_python`.
+pub(crate) const RETIRED_VENV_PREFIX: &str = "venv.lu-old-";
+
+/// Move `<comfy>/venv` out of the way and answer where it went.
+///
+/// Deleting it in line was the 76 seconds P3 measured: a venv holding PyTorch
+/// is tens of thousands of files, `remove_dir_all` walks all of them in one
+/// blocking call, and the cancel flag cannot be read inside it. The new name
+/// is a sibling in the same parent, so it is on the same drive, so this is one
+/// metadata operation no matter how much is inside. The deleting happens
+/// afterwards on a worker thread, and the caller is free again the moment this
+/// returns.
+///
+/// Nanoseconds plus our own process id in the name, so two runs never land on
+/// the same folder.
+pub(crate) fn retire_venv(venv_dir: &Path) -> std::io::Result<PathBuf> {
+ let parent = venv_dir.parent().ok_or_else(|| {
+ std::io::Error::new(
+ std::io::ErrorKind::InvalidInput,
+ "the venv path has no parent directory to move it into",
+ )
+ })?;
+ let stamp = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_nanos())
+ .unwrap_or(0);
+ let retired = parent.join(format!(
+ "{}{}-{}",
+ RETIRED_VENV_PREFIX,
+ stamp,
+ std::process::id()
+ ));
+ std::fs::rename(venv_dir, &retired)?;
+ Ok(retired)
+}
+
+/// Delete whatever [`retire_venv`] left lying around.
+///
+/// Quietly, over tracing only: these are folders nobody is looking for, and a
+/// failure to clear one must not colour a repair the user is watching. Every
+/// repair runs it on the same worker that deletes its own retired folder, and
+/// after that one, so an app that died between a rename and the end of its
+/// delete does not keep the space forever and two deleters never meet on the
+/// same tree.
+///
+/// Only names carrying [`RETIRED_VENV_PREFIX`] are touched. This runs inside
+/// the user's ComfyUI folder, next to models, outputs and custom nodes, so the
+/// match being too eager is the one way this could destroy something.
+pub(crate) fn sweep_retired_venvs(comfy_dir: &Path) {
+ let Ok(entries) = std::fs::read_dir(comfy_dir) else {
+ return;
+ };
+ for entry in entries.flatten() {
+ let path = entry.path();
+ let retired = path
+ .file_name()
+ .and_then(|n| n.to_str())
+ .is_some_and(|n| n.starts_with(RETIRED_VENV_PREFIX));
+ if !retired || !path.is_dir() {
+ continue;
+ }
+ if let Err(e) = std::fs::remove_dir_all(&path) {
+ warn!(error = %e, folder = %path.display(), "a retired venv could not be swept");
+ }
+ }
+}
+
// ── OI-3: the repair must not silently uninstall Voice ──────────────────────
/// A package LU installs into the ComfyUI venv that is NOT ComfyUI's.
@@ -224,11 +357,6 @@ pub fn resolve_lu_python(state: &AppState) -> String {
resolved
}
-/// Create a venv inside `comfyui_dir/venv` using the system `python_bin`.
-/// Returns the path to the venv's Python interpreter on success. On Arch
-/// boxes that haven't installed the `python-virtualenv` package this can
-/// fail with `No module named venv` — we surface that with an actionable
-/// hint pointing at the right pacman / apt invocation.
/// The card the user reads when Repair environment cannot delete the old venv.
///
/// A15, Windows Nachlauf 02.09.: this exact sentence carried the German
@@ -394,7 +522,7 @@ mod tests {
let _ = std::fs::remove_dir_all(&comfy_root);
std::fs::create_dir_all(&comfy_root).expect("temp dir create");
- let venv_py = create_comfyui_venv(&comfy_root, &fake_python)
+ let venv_py = create_comfyui_venv(&comfy_root, &fake_python, None)
.expect("create_comfyui_venv should succeed against fake python");
assert!(venv_py.exists(), "venv python at {} should exist", venv_py.display());
@@ -426,7 +554,7 @@ mod tests {
println!("[live E2E] ✓ nested venv pip runs without PEP 668 block");
// ── Phase 4: idempotency — second create_comfyui_venv must no-op ──
- let venv_py_again = create_comfyui_venv(&comfy_root, &fake_python)
+ let venv_py_again = create_comfyui_venv(&comfy_root, &fake_python, None)
.expect("second create_comfyui_venv should idempotently return existing venv");
assert_eq!(venv_py, venv_py_again);
println!("[live E2E] ✓ create_comfyui_venv is idempotent");
@@ -479,4 +607,233 @@ mod tests {
assert!(msg.starts_with("Could not remove the old venv at /tmp/ComfyUI/venv: "), "got: {msg}");
}
+ // ── P3 (04.09.): cancelling a repair took 76 seconds ──────────────────
+ //
+ // Two blocking calls with no way out sat between the click and the stop:
+ // `remove_dir_all` over a venv holding PyTorch, and `python -m venv`.
+ // These pin the first half. The second half is `wait_or_cancel` in
+ // children.rs, which is where its own tests live.
+
+ /// A folder tree with `dirs` subfolders holding `per_dir` files each.
+ fn tree_with_files(root: &Path, dirs: usize, per_dir: usize) {
+ for d in 0..dirs {
+ let sub = root.join(format!("pkg{d}"));
+ std::fs::create_dir_all(&sub).unwrap();
+ for f in 0..per_dir {
+ std::fs::write(sub.join(format!("mod{f}.py")), b"x").unwrap();
+ }
+ }
+ }
+
+ #[test]
+ fn retire_venv_moves_the_folder_instead_of_emptying_it() {
+ let tmp = tempfile::tempdir().unwrap();
+ let comfy = tmp.path().join("ComfyUI");
+ let venv = comfy.join("venv");
+ tree_with_files(&venv, 3, 4);
+ std::fs::write(venv.join("pyvenv.cfg"), b"home = /usr").unwrap();
+
+ let retired = retire_venv(&venv).expect("the venv could not be set aside");
+
+ assert!(!venv.exists(), "the old venv is still at its old name");
+ assert!(retired.is_dir(), "the retired folder is not there: {}", retired.display());
+ assert_eq!(retired.parent(), Some(comfy.as_path()), "it left the ComfyUI folder");
+ assert!(
+ retired
+ .file_name()
+ .and_then(|n| n.to_str())
+ .is_some_and(|n| n.starts_with(RETIRED_VENV_PREFIX)),
+ "the retired folder does not carry the prefix: {}",
+ retired.display()
+ );
+ // The whole point: nothing was walked, so nothing was lost. This is
+ // what separates a rename from a delete, and it is what makes it fast.
+ assert!(retired.join("pyvenv.cfg").exists(), "the contents were emptied out");
+ for d in 0..3 {
+ for f in 0..4 {
+ let file = retired.join(format!("pkg{d}")).join(format!("mod{f}.py"));
+ assert!(file.exists(), "a file did not survive: {}", file.display());
+ }
+ }
+ }
+
+ #[test]
+ fn retiring_a_venv_is_orders_of_magnitude_faster_than_deleting_it() {
+ // Self-calibrating rather than a fixed millisecond budget, so it says
+ // the same thing on a fast NVMe and on a tired laptop drive: a delete
+ // pays per file, a rename does not.
+ let tmp = tempfile::tempdir().unwrap();
+ let to_delete = tmp.path().join("delete-me").join("venv");
+ let to_retire = tmp.path().join("retire-me").join("venv");
+ tree_with_files(&to_delete, 40, 100);
+ tree_with_files(&to_retire, 40, 100);
+
+ let t0 = std::time::Instant::now();
+ std::fs::remove_dir_all(&to_delete).unwrap();
+ let deleting = t0.elapsed();
+
+ let t1 = std::time::Instant::now();
+ retire_venv(&to_retire).expect("the venv could not be set aside");
+ let retiring = t1.elapsed();
+
+ assert!(
+ retiring * 10 < deleting,
+ "setting aside took {retiring:?} against a delete of {deleting:?}. If the delete \
+ itself was too quick to measure, the tree is too small: raise the file count."
+ );
+ // And in absolute terms, because the promise to the user is a number:
+ // the cancel budget is five seconds and this step must not eat it.
+ assert!(retiring < std::time::Duration::from_millis(250), "took {retiring:?}");
+ }
+
+ #[test]
+ fn a_retired_venv_is_invisible_to_everything_that_looks_for_one() {
+ // The reason the delete may run in the background at all. If the
+ // launcher could still find the folder, a half-deleted venv would be
+ // offered to `start_comfyui` and autostart as a working environment.
+ let tmp = tempfile::tempdir().unwrap();
+ let comfy = tmp.path().join("ComfyUI");
+ let venv = comfy.join("venv");
+ let site = venv.join("lib").join("python3.12").join("site-packages");
+ std::fs::create_dir_all(site.join("faster_whisper")).unwrap();
+ let interpreter = venv_python_path(&comfy);
+ std::fs::create_dir_all(interpreter.parent().unwrap()).unwrap();
+ std::fs::write(&interpreter, b"#!/bin/sh\n").unwrap();
+
+ // Before: both finders see it, so the assertions below mean something.
+ assert!(crate::python::resolve_comfyui_venv_python(&comfy).is_some());
+ assert_eq!(detect_venv_passengers(&venv).len(), 1);
+
+ retire_venv(&venv).expect("the venv could not be set aside");
+
+ assert!(
+ crate::python::resolve_comfyui_venv_python(&comfy).is_none(),
+ "the launcher still offers a venv that is on its way to the bin"
+ );
+ assert!(
+ detect_venv_passengers(&venv).is_empty(),
+ "the passenger scan still reads the retired venv"
+ );
+ }
+
+ #[test]
+ fn the_sweep_takes_only_the_retired_folders() {
+ // This runs inside the user's ComfyUI folder. A pattern one character
+ // too short takes models with it, so the folders that must SURVIVE
+ // are the point of this test.
+ let tmp = tempfile::tempdir().unwrap();
+ let comfy = tmp.path().join("ComfyUI");
+ for keep in ["venv", "models", "custom_nodes", "output"] {
+ std::fs::create_dir_all(comfy.join(keep)).unwrap();
+ }
+ std::fs::write(comfy.join("requirements.txt"), b"torch\n").unwrap();
+ let gone = [
+ comfy.join(format!("{RETIRED_VENV_PREFIX}1")),
+ comfy.join(format!("{RETIRED_VENV_PREFIX}2")),
+ ];
+ for g in &gone {
+ tree_with_files(g, 2, 2);
+ }
+
+ sweep_retired_venvs(&comfy);
+
+ for g in &gone {
+ assert!(!g.exists(), "a retired venv survived the sweep: {}", g.display());
+ }
+ for keep in ["venv", "models", "custom_nodes", "output"] {
+ assert!(comfy.join(keep).is_dir(), "the sweep took {keep}");
+ }
+ assert!(comfy.join("requirements.txt").exists(), "the sweep took requirements.txt");
+ }
+
+ #[test]
+ fn creating_a_venv_gives_up_on_a_raised_flag_and_leaves_no_ruin() {
+ // The flag is raised before the call, so the outcome is the same on
+ // every machine. That the loop keeps reading it WHILE the child runs
+ // is the other half, and that is pinned deterministically in
+ // children.rs against a child that sleeps two minutes; racing a real
+ // `python -m venv` here would only be flaky.
+ let Some(python) = probe_python() else {
+ eprintln!("no usable Python on this box, skipping the live venv checks");
+ return;
+ };
+ let tmp = tempfile::tempdir().unwrap();
+ let comfy = tmp.path().join("ComfyUI");
+ // Half a venv, the way a killed `python -m venv` leaves one: a folder
+ // with something in it and no interpreter yet. Planted rather than
+ // raced for, because the child dies too fast to build one reliably.
+ let half_built = comfy.join("venv").join("lib");
+ std::fs::create_dir_all(&half_built).unwrap();
+ std::fs::write(half_built.join("half-written"), b"x").unwrap();
+
+ let flag = Arc::new(AtomicBool::new(true));
+ let out = create_comfyui_venv(&comfy, &python, Some(&flag));
+
+ assert_eq!(out.err().as_deref(), Some("cancelled"));
+ // A cancel that leaves the shell behind is worse than no cancel:
+ // `resolve_comfyui_venv_python` asks only whether `venv/bin/python`
+ // exists, `python -m venv` writes that file BEFORE the slow part, and
+ // autostart would then launch ComfyUI out of an empty env.
+ assert!(
+ !comfy.join("venv").exists(),
+ "the cancelled build left its half-finished venv behind"
+ );
+ assert!(
+ crate::python::resolve_comfyui_venv_python(&comfy).is_none(),
+ "the cancelled build left a startable ruin behind"
+ );
+ }
+
+ #[test]
+ #[ignore]
+ fn a_venv_nobody_cancels_is_still_built_and_found() {
+ // The control that has to stay green: a `create_comfyui_venv` that
+ // always answered "cancelled" would pass every test above while
+ // killing Repair and Install outright.
+ //
+ // `#[ignore]` for a reason that is about the product, not about this
+ // test. The venv child now joins `INSTALLER_CHILDREN`, and
+ // `kill_installer_children` walks that whole registry. Every dropped
+ // `AppState` runs `shutdown_subprocesses`, which calls it, and this
+ // test binary builds dozens of `AppState`s in parallel with this
+ // test. The child then dies mid-build and the run reads as
+ // "venv creation failed: " with empty stderr. Correct behaviour on a
+ // real quit, unrunnable next to a hundred simulated ones.
+ //
+ // The everyday guard against "always cancelled" is
+ // `a_child_left_alone_still_runs_to_its_own_end` in children.rs, which
+ // drives the same wait loop with no registry and no Python.
+ //
+ // Run with: cargo test --bins -- --ignored --test-threads=1 a_venv_nobody_cancels
+ let Some(python) = probe_python() else {
+ eprintln!("no usable Python on this box, skipping the live venv checks");
+ return;
+ };
+ let tmp = tempfile::tempdir().unwrap();
+ let comfy = tmp.path().join("ComfyUI");
+ std::fs::create_dir_all(&comfy).unwrap();
+
+ let down = Arc::new(AtomicBool::new(false));
+ let venv_py = create_comfyui_venv(&comfy, &python, Some(&down))
+ .expect("a venv nobody cancelled was not built");
+
+ assert!(venv_py.exists(), "no interpreter at {}", venv_py.display());
+ assert_eq!(
+ crate::python::resolve_comfyui_venv_python(&comfy).as_deref(),
+ Some(venv_py.to_string_lossy().as_ref()),
+ "the launcher does not find the venv that was just built"
+ );
+ // And a second call is still a no-op rather than a rebuild.
+ assert_eq!(
+ create_comfyui_venv(&comfy, &python, None).expect("second call"),
+ venv_py
+ );
+ }
+
+ /// The interpreter to run the two live checks against, or nothing.
+ fn probe_python() -> Option<String> {
+ let bin = crate::python::get_python_bin();
+ (!bin.is_empty() && crate::python::is_real_python(&bin)).then_some(bin)
+ }
+
}
diff --git a/src-tauri/src/commands/process.rs b/src-tauri/src/commands/process.rs
index 98b041b4..cc2acd20 100644
--- a/src-tauri/src/commands/process.rs
+++ b/src-tauri/src/commands/process.rs
@@ -244,6 +244,37 @@ pub fn comfy_starting_state(
}
}
+/// How long a start that is already over waits for the output readers.
+///
+/// Same number and same reason as the probe's settle window in
+/// `env_check::run_import_probe_bounded`.
+const COMFY_READER_SETTLE: std::time::Duration = std::time::Duration::from_millis(500);
+
+/// Wait, briefly, for both output readers to reach the end of their pipe.
+///
+/// The fastest crash is the one that reads as nothing at all. `try_wait` is
+/// asked BEFORE the first sleep of the startup watch, so a torch that dies on a
+/// DLL in 80 ms breaks that loop while the reader threads are still on their
+/// first line. Without this the tail is the `[start]` line alone, the message
+/// carries no reason, and the panel shows a start that failed for no stated
+/// cause: exactly what P3 reported.
+///
+/// The threads are deliberately not joined, for the reason `run_streamed`
+/// gives: a surviving grandchild can hold the pipe open and the join would
+/// never return. A budget that runs out is not an error, it just means the
+/// message is built from what did arrive.
+fn wait_for_output_readers(done: &std::sync::atomic::AtomicU32, budget: std::time::Duration) -> bool {
+ use std::sync::atomic::Ordering;
+ let deadline = std::time::Instant::now() + budget;
+ while done.load(Ordering::Acquire) < 2 {
+ if std::time::Instant::now() >= deadline {
+ return false;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(10));
+ }
+ true
+}
+
/// The message a start that is already over has to carry.
///
/// The traceback was never the missing part: `capture` has been putting every
@@ -263,9 +294,9 @@ pub fn comfy_startup_failure(
msg.push_str(").");
if !has_own_python_env {
msg.push_str(
- " This install has no python_embeded and no venv, so it ran on the system Python, \
- which usually does not have ComfyUI's dependencies. Settings, ComfyUI, Install \
- builds one.",
+ " This install has no python_embeded and no venv of its own, so it ran on the \
+ system Python, which usually does not have ComfyUI's dependencies. Repair \
+ environment, in Settings, AI Backends, builds one.",
);
}
let lines: Vec<&str> = tail
@@ -285,6 +316,30 @@ pub fn comfy_startup_failure(
msg
}
+/// What a start has to say when the venv is there and its interpreter is not.
+///
+/// P3: the tester renamed `venv\Scripts\python.exe`, LU quietly started
+/// `C:\Program Files\Python311\python.exe` instead, and what reached him was a
+/// torch traceback out of a stranger's site-packages plus a generic sentence
+/// about a broken Python environment. Neither named the file that was
+/// actually missing, and no other Python can stand in for this one, because
+/// every package this ComfyUI needs is inside that venv.
+///
+/// Deliberately without any operating-system error text: nothing failed to
+/// open here, a file is simply not there, and `exists()` has no error to pass
+/// on anyway.
+pub fn comfy_broken_venv_message(venv_dir: &Path, interpreter: &Path) -> String {
+ format!(
+ "ComfyUI has its own Python environment at {venv}, but the interpreter inside it is \
+ missing: {py}\n\nLU did not start ComfyUI with a different Python. This install's \
+ packages live in that environment, so any other interpreter would fail on the first \
+ import and report a problem that is not the real one.\n\nRepair environment, in \
+ Settings, AI Backends, rebuilds it. Models, outputs and custom nodes are left alone.",
+ venv = venv_dir.display(),
+ py = interpreter.display(),
+ )
+}
+
/// Whether a startup crash reads as a broken Python environment (GH #98,
/// joelnewswanger 2026-08-14). His torch lived in the shared system Python
/// and died inside `infer_schema.py` on import, so the tail shows a traceback
@@ -618,7 +673,12 @@ fn is_comfyui_install_complete_with(comfy_path: &Path, candidate_pythons: &[Stri
/// probe silently asked about a path on the user's desktop, and the Unix
/// probe below it was never reached at all, because `Path::new("").parent()`
/// is `None`.
-fn prefix_has_torch(prefix: &Path) -> bool {
+///
+/// `pub(crate)` since P3: `python::comfy_venv_state` asks the same question to
+/// decide whether a directory without an interpreter is a venv at all. It has
+/// to be the same question, or the launcher and the completeness check go on
+/// disagreeing about what a venv is, which is the bug they had.
+pub(crate) fn prefix_has_torch(prefix: &Path) -> bool {
if prefix.as_os_str().is_empty() {
return false;
}
@@ -1651,12 +1711,24 @@ fn start_comfyui_blocking(state: &AppState) -> Result<serde_json::Value, String>
// (which is what `state.python_bin` resolves to) never received those
// packages. Falls back to bundled portable (Windows) or system (Mac /
// older Linux without PEP 668) when no venv exists.
- let venv_python = crate::python::resolve_comfyui_venv_python(std::path::Path::new(&comfy_path));
+ // P3: the third answer. A venv whose interpreter is gone used to read as
+ // "no venv", and "no venv" means "system Python" one line down. That is
+ // the silent fallback that started ComfyUI on a foreign interpreter.
+ let venv_state = crate::python::comfy_venv_state(std::path::Path::new(&comfy_path));
+ let has_usable_venv = matches!(venv_state, crate::python::ComfyVenv::Usable(_));
+ let has_own_python_env = bundled_python.is_some() || has_usable_venv;
let system_python = state.python_bin.lock().unwrap().clone();
- let python = bundled_python
- .clone()
- .or_else(|| venv_python.clone())
- .unwrap_or(system_python.clone());
+ let python = match (&bundled_python, &venv_state) {
+ // Portable wins over everything: it ships the matching torch wheel,
+ // and a leftover venv beside it must not refuse that start.
+ (Some(p), _) => p.clone(),
+ (None, crate::python::ComfyVenv::Usable(p)) => p.clone(),
+ (None, crate::python::ComfyVenv::Broken { venv_dir, interpreter }) => {
+ error!(venv = %venv_dir.display(), "comfyui venv interpreter missing");
+ return Err(comfy_broken_venv_message(venv_dir, interpreter));
+ }
+ (None, crate::python::ComfyVenv::Absent) => system_python.clone(),
+ };
let port_str = port.to_string();
if python.is_empty() {
return Err(
@@ -1667,7 +1739,7 @@ fn start_comfyui_blocking(state: &AppState) -> Result<serde_json::Value, String>
}
if bundled_python.is_some() {
println!("[ComfyUI] Using bundled portable Python: {}", python);
- } else if venv_python.is_some() {
+ } else if has_usable_venv {
println!("[ComfyUI] Using ComfyUI venv Python (PEP 668 install): {}", python);
} else {
println!("[ComfyUI] Using system Python: {}", python);
@@ -1736,8 +1808,12 @@ fn start_comfyui_blocking(state: &AppState) -> Result<serde_json::Value, String>
// tree, so its own extra-model-paths mechanism is the way a LoRA on
// another drive becomes visible and loadable. Our own file, passed by
// flag: a hand written extra_model_paths.yaml in the ComfyUI folder is
- // never read, written or overwritten by us.
- let extra_paths_file = crate::commands::custom_models::extra_model_paths_arg()
+ // never read, written or overwritten by us. Written HERE and not only when
+ // the setting changes (P3): a subfolder the user creates afterwards used to
+ // be unreachable for ComfyUI forever, because the start path only asked
+ // whether the file existed. Before the spawn below, since ComfyUI reads the
+ // config once at startup.
+ let extra_paths_file = crate::commands::custom_models::refresh_extra_model_paths_arg()
.map(|p| p.to_string_lossy().to_string());
if let Some(file) = &extra_paths_file {
comfy_args.push("--extra-model-paths-config");
@@ -1795,35 +1871,55 @@ fn start_comfyui_blocking(state: &AppState) -> Result<serde_json::Value, String>
buf.push_back(note.clone());
}
}
+ // P3, on a German Windows: `main.py` died with "OSError: [WinError 126] Das
+ // angegebene Modul wurde nicht gefunden." and that sentence went straight
+ // into the panel of an English app. Every message built out of this ring
+ // buffer (`comfy_startup_failure`, `comfyui_last_output` and the two
+ // surfaces behind it) is served in one place, here, where the line is read.
+ // The log above keeps whatever the OS wrote, in whatever language: it is
+ // ours to read and the original wording helps support. Only the line the
+ // user sees is rewritten.
let capture = |line: String, sink: &Arc<Mutex<std::collections::VecDeque<String>>>| {
println!("[ComfyUI] {}", line);
if let Ok(mut buf) = sink.lock() {
if buf.len() >= 400 {
buf.pop_front();
}
- buf.push_back(line);
+ buf.push_back(os_error::english_child_text(&line).into_owned());
}
};
+ // How many of the two readers have seen their pipe close. The watch below
+ // reads the ring buffer the moment the child is gone, and without this it
+ // reads it before either reader has written a word.
+ let readers_done = Arc::new(std::sync::atomic::AtomicU32::new(0));
if let Some(stdout) = child.stdout.take() {
let sink = state.comfy_output.clone();
+ let done = readers_done.clone();
std::thread::spawn(move || {
use std::io::{BufRead, BufReader};
let reader = BufReader::new(stdout);
for line in reader.lines().map_while(Result::ok) {
capture(line, &sink);
}
+ done.fetch_add(1, std::sync::atomic::Ordering::Release);
});
+ } else {
+ readers_done.fetch_add(1, std::sync::atomic::Ordering::Release);
}
if let Some(stderr) = child.stderr.take() {
let sink = state.comfy_output.clone();
+ let done = readers_done.clone();
std::thread::spawn(move || {
use std::io::{BufRead, BufReader};
let reader = BufReader::new(stderr);
for line in reader.lines().map_while(Result::ok) {
capture(line, &sink);
}
+ done.fetch_add(1, std::sync::atomic::Ordering::Release);
});
+ } else {
+ readers_done.fetch_add(1, std::sync::atomic::Ordering::Release);
}
// A spawn is not a start (E16, measured on the Windows box 2026-08-14).
@@ -1850,17 +1946,13 @@ fn start_comfyui_blocking(state: &AppState) -> Result<serde_json::Value, String>
watched += COMFY_STARTUP_STEP;
};
if let Some(code) = early_exit {
+ wait_for_output_readers(&readers_done, COMFY_READER_SETTLE);
let tail: Vec<String> = state
.comfy_output
.lock()
.map(|b| b.iter().cloned().collect())
.unwrap_or_default();
- let msg = comfy_startup_failure(
- &python,
- code,
- &tail,
- bundled_python.is_some() || venv_python.is_some(),
- );
+ let msg = comfy_startup_failure(&python, code, &tail, has_own_python_env);
error!(python = %python, "comfyui exited during startup");
*state.comfy_start_at.lock().unwrap() = None;
return Err(msg);
@@ -2646,19 +2738,32 @@ pub fn auto_start_comfyui(state: &AppState) {
// creates (Arch / Debian 12+ / Fedora 38+ / Ubuntu 23.04+).
// Without this auto-start would launch with the system Python
// that doesn't have torch and crash on first import.
- let venv_python = crate::python::resolve_comfyui_venv_python(std::path::Path::new(&path));
+ // P3: the same three answers as the manual start. A boot that
+ // silently launches a foreign interpreter is the worse half of
+ // that bug, because there is no panel here to read the traceback
+ // in: the reason only reaches the log.
+ let venv_state = crate::python::comfy_venv_state(std::path::Path::new(&path));
+ let has_usable_venv = matches!(venv_state, crate::python::ComfyVenv::Usable(_));
let system_python = state.python_bin.lock().unwrap().clone();
- let python = portable_python
- .clone()
- .or_else(|| venv_python.clone())
- .unwrap_or_else(|| system_python.clone());
+ let python = match (&portable_python, &venv_state) {
+ (Some(p), _) => p.clone(),
+ (None, crate::python::ComfyVenv::Usable(p)) => p.clone(),
+ (None, crate::python::ComfyVenv::Broken { venv_dir, interpreter }) => {
+ println!(
+ "[ComfyUI] Auto-start skipped: {}",
+ comfy_broken_venv_message(venv_dir, interpreter)
+ );
+ return;
+ }
+ (None, crate::python::ComfyVenv::Absent) => system_python.clone(),
+ };
if python.is_empty() {
println!("[ComfyUI] Auto-start skipped: no Python available (install via P14 flow)");
return;
}
if portable_python.is_some() {
println!("[ComfyUI] Auto-start using bundled portable Python: {}", python);
- } else if venv_python.is_some() {
+ } else if has_usable_venv {
println!("[ComfyUI] Auto-start using ComfyUI venv Python (PEP 668 install): {}", python);
}
@@ -2669,6 +2774,13 @@ pub fn auto_start_comfyui(state: &AppState) {
let auto_needs_cpu = auto_decision.needs_cpu;
// Mirror of start_comfyui: expose the real launch mode to the UI.
*state.comfy_started_cpu.lock().unwrap() = Some(auto_needs_cpu);
+ // Wie im manuellen Start, und bis P3 fehlte das hier ganz: auf einer
+ // Maschine, auf der LU ComfyUI beim Programmstart selbst hochzieht,
+ // erreichte der Model-Storage-Ordner ComfyUI nie, auch bei
+ // brandaktueller Datei. Vor comfy_args, damit der Autostart dieselbe
+ // Form hat wie der Startpfad und wie port_str weiter oben.
+ let auto_extra = crate::commands::custom_models::refresh_extra_model_paths_arg()
+ .map(|p| p.to_string_lossy().to_string());
let mut comfy_args: Vec<&str> = vec![
"main.py",
"--listen", "127.0.0.1",
@@ -2691,6 +2803,11 @@ pub fn auto_start_comfyui(state: &AppState) {
comfy_args.push("--use-flash-attention");
println!("[ComfyUI] Auto-start: flash-attn detected — enabling Flash Attention");
}
+ if let Some(file) = &auto_extra {
+ comfy_args.push("--extra-model-paths-config");
+ comfy_args.push(file);
+ println!("[ComfyUI] Auto-start: extra model paths: {}", file);
+ }
let mut cmd = python_command(&python);
cmd.args(&comfy_args)
.current_dir(&path)
@@ -3005,6 +3122,11 @@ mod tests {
assert!(msg.contains("exit code 1"), "{msg}");
// And the one sentence that explains why it happened on THIS install.
assert!(msg.contains("no python_embeded and no venv"), "{msg}");
+ // P3: that sentence used to end on "Settings, ComfyUI, Install builds
+ // one". Install is not offered for an install LU just launched, and it
+ // is not what builds a venv. Repair environment is both.
+ assert!(msg.contains("Repair environment"), "{msg}");
+ assert!(!msg.contains("Install builds one"), "{msg}");
// With a proper environment the guess would be wrong, so it is not made.
let msg2 = comfy_startup_failure("C:\\ComfyUI\\venv\\Scripts\\python.exe", None, &tail, true);
@@ -3012,6 +3134,53 @@ mod tests {
assert!(msg2.contains("ModuleNotFoundError"), "{msg2}");
}
+ #[test]
+ fn a_child_that_dies_instantly_still_gets_its_last_words_into_the_message() {
+ // P3, zweiter Fall aus Abschnitt 5: Status ging Stopped, Starting,
+ // Stopped, und in der Oberflaeche stand GAR KEINE Meldung. Das Kind
+ // stirbt an einer DLL in Millisekunden, `try_wait` fragt vor dem ersten
+ // sleep, und der Ringpuffer haelt in diesem Augenblick nur die
+ // [start]-Zeile. Die Nachlauffrist ist der Unterschied zwischen einer
+ // Meldung mit Grund und einer ohne.
+ use std::sync::atomic::{AtomicU32, Ordering};
+ let done = Arc::new(AtomicU32::new(0));
+ let buf: Arc<Mutex<std::collections::VecDeque<String>>> =
+ Arc::new(Mutex::new(std::collections::VecDeque::new()));
+ buf.lock().unwrap().push_back("[start] python main.py --port 8188".to_string());
+ {
+ let done = done.clone();
+ let buf = buf.clone();
+ std::thread::spawn(move || {
+ std::thread::sleep(std::time::Duration::from_millis(80));
+ if let Ok(mut b) = buf.lock() {
+ b.push_back(
+ "OSError: [WinError 126] the specified module could not be found".to_string(),
+ );
+ }
+ // Beide Leser am Ende ihrer Rohrleitung.
+ done.fetch_add(2, Ordering::Release);
+ });
+ }
+ assert!(
+ wait_for_output_readers(&done, std::time::Duration::from_secs(2)),
+ "die Frist lief ab, obwohl die Leser fertig geworden sind"
+ );
+ let tail: Vec<String> = buf.lock().unwrap().iter().cloned().collect();
+ let msg = comfy_startup_failure("python", Some(1), &tail, true);
+ assert!(msg.contains("[WinError 126]"), "der Grund fehlt in der Meldung: {msg}");
+ }
+
+ #[test]
+ fn a_reader_that_never_ends_costs_the_budget_and_not_the_start() {
+ // Die Gegenprobe: ein Enkelkind haelt die Rohrleitung offen. Genau
+ // deshalb wird nicht gejoint, und genau deshalb ist die Frist kurz.
+ use std::sync::atomic::AtomicU32;
+ let done = Arc::new(AtomicU32::new(1));
+ let began = std::time::Instant::now();
+ assert!(!wait_for_output_readers(&done, std::time::Duration::from_millis(120)));
+ assert!(began.elapsed() < std::time::Duration::from_secs(1), "die Frist hat nicht gegriffen");
+ }
+
#[test]
fn the_failure_message_keeps_the_last_lines_not_the_first() {
// A crash prints its reason at the END. Keeping the head of a 400 line
@@ -4299,6 +4468,49 @@ mod comfy_adoption_tests {
);
}
+ /// Beide ComfyUI-Starts muessen den Model-Storage-Ordner uebergeben.
+ ///
+ /// P3: der Boot-Autostart hat --extra-model-paths-config nie angehaengt,
+ /// also erreichte der Ordner ComfyUI auf einer Maschine, auf der LU es
+ /// selbst hochzieht, ueberhaupt nicht. Der Tester konnte das nicht sehen,
+ /// weil auf seiner Box schon ein ComfyUI auf dem Port lief und der
+ /// Autostart deshalb vorher aussteigt. Ein Quelltexttest, weil kein Test
+ /// die Argumentliste erreicht, ohne ein ComfyUI zu starten.
+ #[test]
+ fn both_comfy_start_paths_hand_over_the_model_folder() {
+ let whole = include_str!("process.rs");
+ // Die ausgelieferte Haelfte, wie in utf8_start_waechter: sonst zaehlt
+ // dieser Test seine eigenen Zeichenketten mit.
+ let src = whole.split("#[cfg(test)]").next().expect("die ausgelieferte Haelfte");
+ assert_eq!(
+ src.matches("--extra-model-paths-config").count(),
+ 2,
+ "der Schalter steht nicht an beiden Startorten",
+ );
+ for name in ["fn start_comfyui_blocking", "fn auto_start_comfyui"] {
+ let start = src.find(name).unwrap_or_else(|| panic!("{name} ist weg"));
+ let rest = &src[start..];
+ let end = start + rest.find("\n}\n").expect("unterminated fn");
+ let body = &src[start..end];
+ assert!(
+ body.contains("refresh_extra_model_paths_arg("),
+ "{name} schreibt die Datei nicht neu, bevor es ComfyUI startet",
+ );
+ assert!(
+ body.contains("--extra-model-paths-config"),
+ "{name} baut die Datei und uebergibt sie nicht",
+ );
+ }
+ // Und der reine Existenztest von frueher darf nicht zurueckkommen. Der
+ // Name wird zur Laufzeit zusammengesetzt, damit diese Zeile sich nicht
+ // selbst findet, falls die Testhaelfte je mitgelesen wird.
+ let alt = format!("custom_models::{}", "extra_model_paths_arg");
+ assert!(
+ !src.contains(&alt),
+ "der alte Startpfad ist zurueck: er sieht nur nach, ob die Datei da ist",
+ );
+ }
+
/// Stop must not still be the no-op the finding describes.
#[test]
fn stop_no_longer_answers_not_running_without_looking() {
@@ -4318,6 +4530,62 @@ mod comfy_adoption_tests {
"stop_comfyui_blocking finds the orphan and does not stop it"
);
}
+
+ // ── P3: der stille Rueckfall auf ein fremdes Python ────────────────────
+
+ #[test]
+ fn die_meldung_nennt_den_interpreter_und_den_weg_hinaus() {
+ let venv = std::path::Path::new("C:\\Users\\ddrob\\ComfyUI\\venv");
+ let py = venv.join("Scripts").join("python.exe");
+ let msg = comfy_broken_venv_message(venv, &py);
+
+ // Die eine Tatsache, die von aussen niemand sieht.
+ assert!(msg.contains(&py.display().to_string()), "{msg}");
+ assert!(msg.contains(&venv.display().to_string()), "{msg}");
+ // Und der Knopf, der wirklich dasteht: Repair environment zeigt die
+ // Oberflaeche bei found && !running && installIdle.
+ assert!(msg.contains("Repair environment"), "{msg}");
+
+ // Was NICHT drinstehen darf: der allgemeine Satz, den der Tester
+ // stattdessen bekam, und ein Verweis auf Install. Installiert ist
+ // alles, es fehlt eine Datei.
+ assert!(!msg.contains("The Python environment looks broken"), "{msg}");
+ assert!(!msg.contains("Install ComfyUI"), "{msg}");
+ }
+
+ /// Kein Startweg greift noch still zum System-Python.
+ ///
+ /// P3, am laufenden Prozess gemessen: nach dem Umbenennen des
+ /// venv-Interpreters lief `"C:\Program Files\Python311\python.exe"
+ /// main.py`. Die Kette, die das getan hat, stand woertlich zweimal in
+ /// dieser Datei, einmal im Startknopf und einmal im Autostart. Ein
+ /// Quelltextanker, weil kein Test die Startentscheidung erreicht, ohne
+ /// ein ComfyUI zu starten.
+ #[test]
+ fn der_start_greift_an_keiner_stelle_mehr_still_zum_system_python() {
+ let whole = include_str!("process.rs");
+ let src = whole.split("#[cfg(test)]").next().expect("die ausgelieferte Haelfte");
+ for name in ["fn start_comfyui_blocking", "fn auto_start_comfyui"] {
+ let start = src.find(name).unwrap_or_else(|| panic!("{name} ist weg"));
+ let rest = &src[start..];
+ let end = start + rest.find("\n}\n").expect("unterminated fn");
+ let body = &src[start..end];
+ assert!(
+ body.contains("comfy_venv_state("),
+ "{name} kennt weiter nur zwei Antworten auf die venv-Frage",
+ );
+ assert!(
+ body.contains("comfy_broken_venv_message("),
+ "{name} erkennt das kaputte venv und sagt es niemandem",
+ );
+ for kette in ["unwrap_or(system_python", "unwrap_or_else(|| system_python"] {
+ assert!(
+ !body.contains(kette),
+ "{name} faellt wieder still auf das System-Python zurueck: {kette}",
+ );
+ }
+ }
+ }
}
/// A child that outlives its launcher — the `npx -y <package>` MCP server, and
diff --git a/src-tauri/src/commands/trainer.rs b/src-tauri/src/commands/trainer.rs
index 4247598b..94128724 100644
--- a/src-tauri/src/commands/trainer.rs
+++ b/src-tauri/src/commands/trainer.rs
@@ -720,6 +720,11 @@ fn run_streamed(
handles.push(std::thread::spawn(move || {
let reader = BufReader::new(stream);
for line in reader.lines().map_while(Result::ok) {
+ // Der Schwanz dieses Protokolls steht in der Oberflaeche, also
+ // gilt hier dieselbe Regel wie beim Installer: was das
+ // Betriebssystem geschrieben hat, steht englisch da, was der
+ // Trainer selbst schreibt, bleibt unangetastet.
+ let line = os_error::english_child_text(&line).into_owned();
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
diff --git a/src-tauri/src/commands/video.rs b/src-tauri/src/commands/video.rs
index 24eefb4e..067e714c 100644
--- a/src-tauri/src/commands/video.rs
+++ b/src-tauri/src/commands/video.rs
@@ -678,11 +678,14 @@ pub fn video_generate(state: &AppState, args: &Value) -> CmdResult {
// Stdout / stderr pumps → progress slot.
let p_out = progress.clone();
let p_err = progress.clone();
+ // Dieselbe Fortschrittskarte wie beim Installer, also dieselbe Regel:
+ // was das Betriebssystem geschrieben hat, steht dort englisch. Was der
+ // Encoder selbst schreibt, bleibt Zeichen fuer Zeichen stehen.
std::thread::spawn(move || {
use std::io::{BufRead, BufReader};
if let Some(s) = stdout {
for line in BufReader::new(s).lines().map_while(Result::ok) {
- p_out.log(line);
+ p_out.log(os_error::english_child_text(&line).into_owned());
}
}
});
@@ -690,7 +693,7 @@ pub fn video_generate(state: &AppState, args: &Value) -> CmdResult {
use std::io::{BufRead, BufReader};
if let Some(s) = stderr {
for line in BufReader::new(s).lines().map_while(Result::ok) {
- p_err.log(line);
+ p_err.log(os_error::english_child_text(&line).into_owned());
}
}
});
@@ -791,14 +794,14 @@ pub(crate) fn run_streamed(slot: &crate::install_state::InstallSlot, cmd: &mut C
let t1 = std::thread::spawn(move || {
if let Some(s) = stdout {
for line in BufReader::new(s).lines().map_while(Result::ok) {
- so.log(line);
+ so.log(os_error::english_child_text(&line).into_owned());
}
}
});
let t2 = std::thread::spawn(move || {
if let Some(s) = stderr {
for line in BufReader::new(s).lines().map_while(Result::ok) {
- se.log(line);
+ se.log(os_error::english_child_text(&line).into_owned());
}
}
});
diff --git a/src-tauri/src/os_error.rs b/src-tauri/src/os_error.rs
index dc890896..2cd1bc8e 100644
--- a/src-tauri/src/os_error.rs
+++ b/src-tauri/src/os_error.rs
@@ -14,10 +14,16 @@
//! carry everything the message was worth: what went wrong, and the number to
//! search for.
//!
-//! This does NOT touch the output of foreign processes (pip, git, ComfyUI).
-//! Their stderr is theirs, we only promise that OUR frame around it is English.
+//! The words of the operating system are ours to answer for even when a
+//! foreign process (pip, git, ComfyUI, the import probe) carried them to us:
+//! the user reads them inside our window, and P3 read two of them in German on
+//! his English app. What such a process wrote ITSELF stays untouched, down to
+//! the byte. Only the sentence Windows handed it is exchanged, and the code
+//! that names it rides along.
+use std::borrow::Cow;
use std::io::ErrorKind;
+use std::sync::OnceLock;
/// The English phrase for a language neutral `ErrorKind`.
///
@@ -193,6 +199,223 @@ pub fn sanitize_os_wording(text: &str) -> std::borrow::Cow<'_, str> {
out
}
+/// The Windows loader codes that reach a user through a child process, with
+/// our own English for each.
+///
+/// Same doctrine as `code_phrase` above and deliberately just as short: these
+/// are the codes that kill a torch import, a pip wheel or ComfyUI's `main.py`,
+/// and nothing else. A code that is not here is left alone, sentence and all,
+/// because inventing English for a code we have never seen would replace a
+/// true foreign message with a false familiar one.
+///
+/// Not gated on `cfg(windows)`. Behind the mark `[WinError N]` the number is a
+/// Windows code no matter which machine reads the line, and a Mac reading a
+/// log from the box has the same right to English.
+///
+/// Every phrase is lower case, carries no sentence break, and fits inside
+/// another sentence. The table test holds all three, and the second one is
+/// load bearing: the structural rule in `english_child_line` ends the foreign
+/// sentence at the first `". "` that is followed by a capital.
+const WIN_CODES: &[(i32, &str)] = &[
+ (2, "the file was not found"),
+ (3, "the path was not found"),
+ (5, "access is denied"),
+ (87, "a parameter is incorrect"),
+ (126, "the specified module could not be found"),
+ (127, "the entry point was not found"),
+ (193, "the file is not a valid Windows program (32 bit against 64 bit)"),
+ (998, "invalid access to that memory location"),
+ (1114, "a DLL initialization routine failed"),
+];
+
+/// Our English for one Windows code, or None for a code we do not name.
+fn win_code_phrase(code: i32) -> Option<&'static str> {
+ WIN_CODES.iter().find(|(c, _)| *c == code).map(|(_, p)| *p)
+}
+
+/// What THIS machine's Windows says for a code, normalised.
+///
+/// The trick `sanitize_os_wording` already uses, one step further: the app
+/// runs on the same Windows as the child process, so
+/// `from_raw_os_error(126).to_string()` is byte for byte what the child was
+/// handed. Nothing is parsed and no language is assumed.
+///
+/// The normalising is not cosmetic. Rust strips line ends, CPython strips
+/// trailing dots as well, and the import probe collapses every run of
+/// whitespace (`env_check.rs`). Both sides are compared in the same collapsed,
+/// dotless form or they never meet.
+#[cfg(windows)]
+fn os_sentence(code: i32) -> Option<String> {
+ let raw = std::io::Error::from_raw_os_error(code).to_string();
+ let body = match raw.rfind(" (os error ") {
+ Some(at) => &raw[..at],
+ None => raw.as_str(),
+ };
+ let collapsed = body.split_whitespace().collect::<Vec<_>>().join(" ");
+ let trimmed = collapsed.trim_end_matches('.').trim();
+ if trimmed.is_empty() {
+ None
+ } else {
+ Some(trimmed.to_string())
+ }
+}
+
+/// Off Windows there is no such sentence to ask for, and guessing one would be
+/// the translation table this module exists to avoid.
+#[cfg(not(windows))]
+fn os_sentence(_code: i32) -> Option<String> {
+ None
+}
+
+/// The sentences this machine would have written, built once per process.
+///
+/// Without the cache this is one `FormatMessageW` per table entry per line,
+/// and the readers this runs in carry tens of thousands of pip lines.
+fn win_sentence(code: i32) -> Option<String> {
+ static TABLE: OnceLock<Vec<(i32, String)>> = OnceLock::new();
+ let table = TABLE
+ .get_or_init(|| WIN_CODES.iter().filter_map(|&(c, _)| os_sentence(c).map(|s| (c, s))).collect());
+ table.iter().find(|(c, _)| *c == code).map(|(_, s)| s.clone())
+}
+
+/// The end of the first sentence in `s`: the index of a `.` that is followed by
+/// a space and a capital.
+///
+/// Byte-wise on purpose and safe: only ASCII bytes are compared, and no
+/// continuation byte of a multi-byte character can equal one of them, so the
+/// index that comes back is always a character boundary.
+fn sentence_end(s: &str) -> Option<usize> {
+ let b = s.as_bytes();
+ (0..b.len().saturating_sub(2))
+ .find(|&i| b[i] == b'.' && b[i + 1] == b' ' && b[i + 2].is_ascii_uppercase())
+}
+
+/// One line of a child process's output, with the operating system's own
+/// sentence replaced by ours and everything the process wrote left alone.
+///
+/// P3 on a German Windows saw two shapes, and only the first carries a number:
+///
+/// * `OSError: [WinError 126] Das angegebene Modul wurde nicht gefunden. Error
+/// loading "...\c10_cuda.dll" or one of its dependencies.`
+/// * `ImportError: DLL load failed while importing _core: Das angegebene Modul
+/// wurde nicht gefunden.`
+///
+/// So there are two passes. The first is anchored on the mark `[WinError N]`
+/// and ends the foreign sentence structurally, at the first `". "` before a
+/// capital, which is why it works on any host and in a unit test on a Mac.
+/// `lookup` is only the shortcut there: when this machine can name the exact
+/// sentence, exactly that many bytes are exchanged. The second pass is for the
+/// line without a number; it can only ask the machine, and it ADDS the code
+/// the text never had.
+///
+/// `lookup` is a parameter so a test can pretend to be a German Windows.
+/// Nothing else in the line is touched, and a line with nothing to fix comes
+/// back borrowed and unallocated.
+pub fn english_child_line<'a>(line: &'a str, lookup: impl Fn(i32) -> Option<String>) -> Cow<'a, str> {
+ let after_mark = replace_marked_sentences(line, &lookup);
+ replace_bare_sentences(after_mark, &lookup)
+}
+
+/// Pass one: `[WinError N] <sentence the OS wrote>`.
+fn replace_marked_sentences<'a>(line: &'a str, lookup: &impl Fn(i32) -> Option<String>) -> Cow<'a, str> {
+ const MARK: &str = "[WinError ";
+ if !line.contains(MARK) {
+ return Cow::Borrowed(line);
+ }
+ let mut out = String::new();
+ // How much of `line` has been copied into `out`, and where to look next.
+ let mut copied = 0usize;
+ let mut search = 0usize;
+ while let Some(rel) = line[search..].find(MARK) {
+ let at = search + rel;
+ let num_start = at + MARK.len();
+ let num_end = num_start
+ + line[num_start..]
+ .find(|c: char| !c.is_ascii_digit())
+ .unwrap_or(line.len() - num_start);
+ search = num_end;
+ if num_end == num_start || !line[num_end..].starts_with(']') {
+ continue;
+ }
+ let Ok(code) = line[num_start..num_end].parse::<i32>() else {
+ continue;
+ };
+ // A code we do not name keeps its own sentence: see WIN_CODES.
+ let Some(phrase) = win_code_phrase(code) else {
+ continue;
+ };
+ let mut body = num_end + 1;
+ if line[body..].starts_with(' ') {
+ body += 1;
+ }
+ // The shortcut: this machine knows the exact sentence, so exactly it
+ // goes. Covers a system sentence that carries a full stop of its own,
+ // which the structural rule below would cut short.
+ let named = lookup(code).filter(|s| line[body..].starts_with(s.as_str()));
+ let mut stop = match &named {
+ Some(s) => body + s.len(),
+ None => sentence_end(&line[body..]).map(|i| body + i).unwrap_or(line.len()),
+ };
+ // The full stop stays with the line, so a sentence that ends the line
+ // does not lose it and one that does not never gains it.
+ while stop > body && matches!(line.as_bytes()[stop - 1], b'.' | b' ') {
+ stop -= 1;
+ }
+ if stop <= body {
+ continue;
+ }
+ // Already our words: an English Windows writes this sentence itself,
+ // and rewriting it would only change its capital letter.
+ if line[body..stop].eq_ignore_ascii_case(phrase) {
+ continue;
+ }
+ out.push_str(&line[copied..body]);
+ out.push_str(phrase);
+ copied = stop;
+ search = stop;
+ }
+ if copied == 0 {
+ return Cow::Borrowed(line);
+ }
+ out.push_str(&line[copied..]);
+ Cow::Owned(out)
+}
+
+/// Pass two: the sentence without a number anywhere near it.
+fn replace_bare_sentences<'a>(text: Cow<'a, str>, lookup: &impl Fn(i32) -> Option<String>) -> Cow<'a, str> {
+ let mut out = text;
+ for &(code, phrase) in WIN_CODES {
+ let Some(sentence) = lookup(code) else {
+ continue;
+ };
+ let sentence = sentence.trim();
+ // This machine already speaks our words, so there is nothing to
+ // exchange and appending the code would only make the line longer.
+ if sentence.is_empty() || sentence.eq_ignore_ascii_case(phrase) {
+ continue;
+ }
+ if !out.contains(sentence) {
+ continue;
+ }
+ // The number is what the text was missing, and it is what anyone
+ // searches for.
+ let ours = format!("{phrase} (Windows error {code})");
+ out = Cow::Owned(out.replace(sentence, &ours));
+ }
+ out
+}
+
+/// The production entry: one line of foreign output, in our words.
+///
+/// Both marks in one pass through, so a line that carries a `[WinError N]` and
+/// an `(os error N)` comes out whole.
+pub fn english_child_text(text: &str) -> Cow<'_, str> {
+ match english_child_line(text, win_sentence) {
+ Cow::Borrowed(s) => sanitize_os_wording(s),
+ Cow::Owned(s) => Cow::Owned(sanitize_os_wording(&s).into_owned()),
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -403,6 +626,174 @@ mod tests {
assert_eq!(english(&w), "parse failed: bad json");
}
+ // ── Die Saetze, die ein fremder Prozess weitergereicht hat ──────────────
+ //
+ // P3 auf einem deutschen Windows, Punkt 7.2 und 7.3. Beide Zeilen stehen
+ // hier woertlich, und die Attrappe spielt die Maschine: so laeuft der
+ // Beweis auf dem Mac genauso wie auf der Box.
+
+ /// Was ein deutsches Windows fuer ERROR_MOD_NOT_FOUND schreibt, in der
+ /// Form, in der `os_sentence` ihn zurueckgibt: ohne Schlusspunkt.
+ const GERMAN_126: &str = "Das angegebene Modul wurde nicht gefunden";
+
+ fn german_windows(code: i32) -> Option<String> {
+ (code == 126).then(|| GERMAN_126.to_string())
+ }
+
+ /// Eine Maschine, die keinen dieser Saetze kennt: jeder Mac, jedes Linux,
+ /// und jeder Leser eines Protokolls von einer fremden Box.
+ fn machine_knows_nothing(_code: i32) -> Option<String> {
+ None
+ }
+
+ #[test]
+ fn the_line_from_7_2_loses_the_system_wording_and_keeps_everything_else() {
+ let line = r#"OSError: [WinError 126] Das angegebene Modul wurde nicht gefunden. Error loading "C:\Users\ddrob\ComfyUI\venv\Lib\site-packages\torch\lib\c10_cuda.dll" or one of its dependencies."#;
+ // Ohne Lookup, also ueber die Strukturregel allein. Das ist der Punkt:
+ // der Fall MIT Nummer haengt nicht daran, dass diese Maschine deutsch
+ // spricht.
+ let out = english_child_line(line, machine_knows_nothing);
+ assert!(out.contains("[WinError 126]"), "die Marke ist weg: {out}");
+ assert!(out.contains("the specified module could not be found"), "got: {out}");
+ assert!(!out.contains("Das angegebene Modul"), "der Systemsatz lebt noch: {out}");
+ // Was torch selbst geschrieben hat, bleibt Wort fuer Wort stehen.
+ assert!(
+ out.contains(r#"Error loading "C:\Users\ddrob\ComfyUI\venv\Lib\site-packages\torch\lib\c10_cuda.dll" or one of its dependencies."#),
+ "got: {out}"
+ );
+ }
+
+ #[test]
+ fn the_machines_own_sentence_wins_over_the_structural_rule() {
+ // Wofuer der Lookup in Durchgang 1 ueberhaupt noch gut ist: ein
+ // Systemsatz, der selbst aus zwei Saetzen besteht. Die Strukturregel
+ // wuerde am ersten Punkt abschneiden und die zweite Haelfte deutsch
+ // stehen lassen; die Maschine kennt die genaue Laenge.
+ //
+ // Nebenbei die Normalisierung: der Lookup liefert punktlos, das Kind
+ // hat mit Punkt gedruckt, und der Punkt gehoert der Zeile.
+ const TWO_SENTENCES: &str = "Modul fehlt. Bitte neu installieren";
+ let line = format!(r#"OSError: [WinError 126] {TWO_SENTENCES}. Error loading "c10.dll"."#);
+ let out = english_child_line(&line, |c| (c == 126).then(|| TWO_SENTENCES.to_string()));
+ assert_eq!(
+ out,
+ r#"OSError: [WinError 126] the specified module could not be found. Error loading "c10.dll"."#
+ );
+ }
+
+ #[test]
+ fn the_line_from_7_3_gains_the_number_it_never_had() {
+ // Kein "[WinError N]" im Text: hier kann nur die Maschine helfen, und
+ // die Nummer kommt hinzu statt verloren zu gehen.
+ let line = format!("ImportError: DLL load failed while importing _core: {GERMAN_126}");
+ let out = english_child_line(&line, german_windows);
+ assert_eq!(
+ out,
+ "ImportError: DLL load failed while importing _core: the specified module could not be found (Windows error 126)"
+ );
+ }
+
+ #[test]
+ fn a_french_windows_needs_no_second_table() {
+ // Die Probe gegen eine Wortliste: dasselbe Verfahren, eine Sprache,
+ // die in diesem Baum nirgends vorkommt. Wer hier durchfaellt, hat eine
+ // deutsche Wortliste gebaut statt eines Verfahrens.
+ const FRENCH: &str = "Le module specifie est introuvable";
+ let line = format!("ImportError: DLL load failed while importing _core: {FRENCH}");
+ let out = english_child_line(&line, |c| (c == 126).then(|| FRENCH.to_string()));
+ assert!(out.contains("the specified module could not be found (Windows error 126)"), "got: {out}");
+ assert!(!out.contains(FRENCH), "got: {out}");
+ }
+
+ #[test]
+ fn an_english_windows_line_is_not_reworded_into_a_lower_case_one() {
+ // Auf einem englischen Windows sagen Tabelle und Maschine dasselbe,
+ // nur mit grossem Anfangsbuchstaben. Wenn hier etwas Sichtbares
+ // passiert, ist die Normalisierung falsch gebaut.
+ let line = "OSError: [WinError 126] The specified module could not be found.";
+ let out = english_child_line(line, |c| {
+ (c == 126).then(|| "The specified module could not be found".to_string())
+ });
+ assert_eq!(out, line);
+ assert!(matches!(out, Cow::Borrowed(_)), "allocated for an English line");
+ }
+
+ #[test]
+ fn a_line_the_operating_system_never_wrote_comes_back_untouched() {
+ for line in [
+ // Eine gewoehnliche ComfyUI-Startzeile.
+ "Total VRAM 12288 MB, total RAM 32601 MB",
+ "Collecting torch==2.6.0",
+ // 9c: Umlaute und japanische Zeichen im Pfad sind bestanden und
+ // duerfen es bleiben. Eine ASCII-Wache haette genau das kaputt
+ // getestet.
+ r#" File "C:\lu-nightshift\Übung 日本語 äöüß\ComfyUI\venv\Lib\site-packages\torch\__init__.py", line 309, in <module>"#,
+ // Das Wort ohne die Klammer ist keine Marke.
+ "WinError is just a word here",
+ // Ein Code, den die Tabelle nicht kennt, behaelt seinen Satz.
+ "OSError: [WinError 4711] Ein unbekannter Code behaelt seinen Satz.",
+ ] {
+ let out = english_child_line(line, german_windows);
+ assert_eq!(out, line);
+ assert!(matches!(out, Cow::Borrowed(_)), "allocated for: {line}");
+ }
+ }
+
+ #[test]
+ fn the_old_sanitiser_cannot_do_any_of_this() {
+ // Die rote Gegenprobe zu den drei Faellen oben: `sanitize_os_wording`
+ // kennt nur die Marke "(os error N)" und laesst alle drei unveraendert.
+ // Sie bleibt trotzdem, `main.rs` braucht sie; dieser Test haelt fest,
+ // dass die neue Funktion etwas kann, was die alte nicht kann, und
+ // schuetzt gegen ein spaeteres Zusammenlegen.
+ for line in [
+ format!("OSError: [WinError 126] {GERMAN_126}. Error loading \"c10.dll\"."),
+ format!("ImportError: DLL load failed while importing _core: {GERMAN_126}"),
+ format!("[WinError 5] {GERMAN_126}"),
+ ] {
+ let out = sanitize_os_wording(&line);
+ assert_eq!(out, line);
+ assert!(matches!(out, Cow::Borrowed(_)), "allocated for: {line}");
+ }
+ }
+
+ #[test]
+ fn every_windows_phrase_is_a_sentence_part_and_carries_no_sentence_break() {
+ for &(code, phrase) in WIN_CODES {
+ assert!(!phrase.is_empty(), "code {code} has no phrase");
+ assert!(
+ phrase.chars().next().unwrap().is_lowercase(),
+ "code {code} is capitalised and would read wrong inside a sentence"
+ );
+ // Die tragende Zusicherung: die Strukturregel in Durchgang 1
+ // beendet den fremden Satz am ersten ". " vor einem Grossbuchstaben.
+ // Ein Eintrag mit zwei Saetzen wuerde sie stumm brechen.
+ assert!(sentence_end(phrase).is_none(), "code {code} carries a sentence break");
+ }
+ // Dieselbe Zusicherung fuer die Saetze DIESER Maschine, soweit es
+ // welche gibt. Gross geschrieben sind sie mit Recht, deshalb nur die
+ // Form, nicht der Anfangsbuchstabe.
+ #[cfg(windows)]
+ for &(code, _) in WIN_CODES {
+ if let Some(s) = os_sentence(code) {
+ assert!(!s.is_empty(), "code {code} normalised to nothing");
+ assert!(!s.ends_with('.'), "code {code} kept its full stop");
+ assert!(!s.contains(" "), "code {code} kept a double space");
+ }
+ }
+ }
+
+ #[test]
+ fn both_marks_in_one_line_are_repaired_together() {
+ // `english_child_text` ist der Produktionsweg und schickt die Zeile
+ // durch beide Tore, damit eine Zeile mit beiden Marken ganz wird.
+ let os_worded = Error::from_raw_os_error(REFUSED).to_string();
+ let line = format!("[WinError 126] Das angegebene Modul wurde nicht gefunden. Then: {os_worded}");
+ let out = english_child_text(&line);
+ assert!(out.contains("the specified module could not be found"), "got: {out}");
+ assert!(out.contains("connection refused"), "got: {out}");
+ }
+
#[test]
fn every_named_code_reads_as_a_sentence_and_none_is_empty() {
// A guard on the tables: an entry added with an empty or capitalised
@@ -544,6 +935,68 @@ mod drift_guard {
code.contains("\"error\"") && code.contains("e.to_string()")
}
+ /// The fourth shape: a reader of a CHILD's output that puts the line into
+ /// a sink the user reads.
+ ///
+ /// This is the shape that produced P3's finding, and none of the three
+ /// above can see it: there is no `map_err`, no match arm and no payload
+ /// field anywhere in it. The error was never a Rust value here. Python
+ /// caught it, worded it in the system language and printed it, and the
+ /// reader carried the line into the progress card, the ring buffer or the
+ /// installer log.
+ ///
+ /// `BufReader::new` is required alongside `.lines()` on purpose: `.lines()`
+ /// on a `String` is everywhere in this tree (parsing nvidia-smi, os-release,
+ /// a manifest) and none of it is a pipe.
+ /// `(line,` and `(line)` are the delegated sink: `process.rs` hands the
+ /// line to a `capture` closure that owns both the log and the buffer.
+ /// `println!("... {}", line)` does not read that way, which is what keeps
+ /// the log-only readers green.
+ const READER_SINKS: &[&str] = &[
+ "push(", "push_str(", "push_back(", "push_install_log", ".log(", ".send(", "(line,", "(line)",
+ ];
+
+ /// How far a reader may be from its sink. The trainer's loop counts steps
+ /// first and pushes twelve lines further down.
+ const READER_WINDOW: usize = 14;
+
+ /// How far back the pipe that feeds the loop may sit.
+ const READER_LOOKBACK: usize = 3;
+
+ /// Reader windows that carry no operating system wording, with the reason.
+ ///
+ /// A bare file name would be too broad, so the second field names the line
+ /// that makes this reader different: the next reader in the same file has
+ /// to pass the guard on its own. The third is what the FILE must still
+ /// contain for the excuse to hold, so an exception cannot outlive the
+ /// reason for it. Empty means no further condition.
+ const READER_EXCEPTIONS: &[(&str, &str, &str)] = &[
+ // whisper_server.py speaks JSON on stdout, and this reader forwards the
+ // PARSED value rather than the line. A localised sentence cannot
+ // survive `from_str`, and what does survive is our own protocol.
+ ("whisper.rs", "serde_json::from_str::<serde_json::Value>(trimmed)", ""),
+ // Both ComfyUI readers hand their line to one `capture` closure, which
+ // is where the split lives: the log keeps what the OS wrote, the ring
+ // buffer the user reads gets our words. The closure sits above the
+ // loops and out of any window, so the third field checks it instead.
+ // Take the rewrite out of it and both readers fail this guard again.
+ (
+ "process.rs",
+ "capture(line, &sink)",
+ "buf.push_back(os_error::english_child_text(&line).into_owned())",
+ ),
+ ];
+
+ fn is_suspect_reader(window: &str) -> bool {
+ if !window.contains(".lines()") || !window.contains("BufReader::new") {
+ return false;
+ }
+ if window.contains("english_child") {
+ return false;
+ }
+ READER_SINKS.iter().any(|s| window.contains(s))
+ }
+
fn rust_files(dir: &Path, out: &mut Vec<PathBuf>) {
for entry in std::fs::read_dir(dir).expect("src is readable").flatten() {
let path = entry.path();
@@ -563,6 +1016,7 @@ mod drift_guard {
assert!(files.len() > 10, "the file walk found almost nothing");
let mut found = Vec::new();
+ let mut readers = Vec::new();
for file in &files {
// This module's own tests talk about the shape on purpose.
if file.ends_with("os_error.rs") {
@@ -600,6 +1054,67 @@ mod drift_guard {
found.push(format!("{}:{}: {}", file.display(), i + 1, line.trim()));
}
}
+ // The reader shape, anchored on the line that opens the pipe.
+ for i in 0..lines.len() {
+ if !strip_comment(lines[i]).contains(".lines()") {
+ continue;
+ }
+ // The window stops at the NEXT reader, not only at the
+ // budget. Otherwise a repaired stdout reader vouches for the
+ // raw stderr reader six lines below it, which is exactly how
+ // the two halves of `run_streamed` sit in `video.rs`. And it
+ // counts CODE lines: a comment block above the sink would
+ // otherwise push the sink out of the window, which is how the
+ // pip reader hid from a first version of this guard.
+ let mut window = String::new();
+ let mut code_lines = 0usize;
+ for line in lines.iter().skip(i + 1) {
+ let code = strip_comment(line);
+ if code.contains(".lines()") {
+ break;
+ }
+ if code.trim().is_empty() {
+ continue;
+ }
+ window.push(' ');
+ window.push_str(code);
+ code_lines += 1;
+ if code_lines >= READER_WINDOW {
+ break;
+ }
+ }
+ // And a short run BACKWARDS, because `let reader =
+ // BufReader::new(stderr);` usually sits on the line above the
+ // loop, and without it half the readers in this tree read as
+ // an ordinary `str::lines()`. It stops at the previous reader
+ // for the same reason the forward run stops at the next one.
+ let mut before = String::new();
+ let mut back = 0usize;
+ for line in lines[..i].iter().rev() {
+ let code = strip_comment(line);
+ if code.contains(".lines()") {
+ break;
+ }
+ if code.trim().is_empty() {
+ continue;
+ }
+ before.push(' ');
+ before.push_str(code);
+ back += 1;
+ if back >= READER_LOOKBACK {
+ break;
+ }
+ }
+ let window = format!("{} {} {}", before, strip_comment(lines[i]), window);
+ let excused = READER_EXCEPTIONS.iter().any(|(f, needle, proof)| {
+ file.to_string_lossy().ends_with(f)
+ && window.contains(needle)
+ && text.contains(proof)
+ });
+ if !excused && is_suspect_reader(&window) {
+ readers.push(format!("{}:{}: {}", file.display(), i + 1, lines[i].trim()));
+ }
+ }
}
assert!(
found.is_empty(),
@@ -608,6 +1123,14 @@ mod drift_guard {
is a German error in an English app. Wrap the value in os_error::english(&e).\n\n{}",
found.join("\n")
);
+ assert!(
+ readers.is_empty(),
+ "these carry a child process's output into a message the user reads, unfiltered.\n\
+ Python and pip word an OSError in the system language, so on a German Windows this\n\
+ is a German sentence in an English app (P3, 7.2 and 7.3). Send the line through\n\
+ os_error::english_child_text(&line) first, or name it in READER_EXCEPTIONS.\n\n{}",
+ readers.join("\n")
+ );
}
#[test]
@@ -643,6 +1166,42 @@ mod drift_guard {
));
}
+ /// The reader shape, from both sides. The negative half is not optional:
+ /// a guard that also stops a reader which only logs or only counts gets
+ /// weakened the first time it stands in someone's way.
+ #[test]
+ fn the_guard_would_actually_catch_a_reader() {
+ // Die vier Formen, die es in diesem Baum wirklich gibt.
+ assert!(is_suspect_reader(
+ r#"let reader = BufReader::new(stdout); for line in reader.lines().map_while(Result::ok) { if let Ok(mut s) = st.lock() { s.logs.push(line); } }"#
+ ));
+ assert!(is_suspect_reader(
+ r#"for line in BufReader::new(s).lines().map_while(Result::ok) { so.log(line); }"#
+ ));
+ assert!(is_suspect_reader(
+ r#"let reader = BufReader::new(stdout); for line in reader.lines().map_while(Result::ok) { capture(line, &sink); }"#
+ ));
+ assert!(is_suspect_reader(
+ r#"for line in BufReader::new(stdout).lines().map_while(Result::ok) { buf.push_back(line); }"#
+ ));
+ // Und die, die durchgehen muessen.
+ assert!(!is_suspect_reader(
+ r#"for line in BufReader::new(s).lines().map_while(Result::ok) { so.log(os_error::english_child_text(&line).into_owned()); }"#
+ ));
+ // Nur ins Protokoll: das ist die ausdrueckliche Regel, die Zeile des
+ // Betriebssystems bleibt dort in ihrer eigenen Sprache stehen.
+ assert!(!is_suspect_reader(
+ r#"let reader = BufReader::new(stderr); for line in reader.lines().map_while(Result::ok) { println!("[ComfyUI] {}", line); }"#
+ ));
+ // Nur zaehlen.
+ assert!(!is_suspect_reader(
+ r#"for _line in BufReader::new(stdout).lines().map_while(Result::ok) { seen += 1; }"#
+ ));
+ // Eine Zeichenkette im Speicher ist keine Rohrleitung: nvidia-smi,
+ // os-release und jeder Katalog werden so gelesen.
+ assert!(!is_suspect_reader(r#"for line in text.lines() { out.push(line.to_string()); }"#));
+ }
+
/// The match shape, from both sides. These are the exact statements the
/// A15 round fixed, joined the way the scan joins them.
#[test]
diff --git a/src-tauri/src/python.rs b/src-tauri/src/python.rs
index c0bfc59e..fceaa956 100644
--- a/src-tauri/src/python.rs
+++ b/src-tauri/src/python.rs
@@ -103,24 +103,79 @@ pub fn venv_python_path_named(comfyui_dir: &Path, venv_name: &str) -> PathBuf {
}
}
-/// Resolve the venv Python for `comfyui_dir` iff it exists. Returns the
-/// path as a String (matching the API that `process::start_comfyui` already
-/// uses for its `bundled_python` / `system_python` slots), or None when
-/// no venv has been created — caller falls back to the system Python.
+/// Where this ComfyUI keeps its packages. Three answers, not two.
///
-/// Checks both the classic `venv` and the modern `.venv` directory (issue #51,
-/// adhney): a macOS/Linux ComfyUI installed into `.venv` was previously missed,
-/// so `start_comfyui` fell back to the system Python and crashed with
-/// `ModuleNotFoundError: torch`. `venv` is checked first to preserve the exact
-/// behavior for users whose env LU's own installer created.
-pub fn resolve_comfyui_venv_python(comfyui_dir: &Path) -> Option<String> {
+/// P3 (Windows box, 03.09.2026): `venv\Scripts\python.exe` was renamed and the
+/// launcher never noticed. It knew only "venv" and "no venv", a venv without
+/// its interpreter fell into the second box, and the answer to "no venv" is
+/// "use the system Python". So ComfyUI started on
+/// `C:\Program Files\Python311\python.exe` and died on a torch import out of a
+/// site-packages tree that has nothing to do with this install.
+///
+/// The missing answer is [`ComfyVenv::Broken`]: the packages live in that venv,
+/// so no other interpreter can start this ComfyUI, and falling back is not a
+/// rescue but a guaranteed error message about the wrong environment.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum ComfyVenv {
+ /// A venv whose interpreter is there.
+ Usable(String),
+ /// A venv directory without its interpreter. `interpreter` is the file
+ /// that is missing, which is the one fact the user cannot see from
+ /// outside.
+ Broken { venv_dir: PathBuf, interpreter: PathBuf },
+ /// No venv. The normal case on Windows and macOS: `install_comfyui` only
+ /// builds one when the system Python is PEP 668 protected, otherwise the
+ /// requirements go into the system Python and starting from it is right.
+ Absent,
+}
+
+/// Which of the three answers holds for `comfyui_dir`.
+///
+/// Both the classic `venv` and the modern `.venv` are checked (issue #51,
+/// adhney: a macOS/Linux ComfyUI installed into `.venv` was missed and started
+/// on the system Python). `venv` first, so LU's own installer keeps its exact
+/// behaviour. Usable beats Broken beats Absent.
+///
+/// What makes a directory a venv rather than a leftover folder: either its
+/// PEP 405 marker `pyvenv.cfg`, or torch sitting in its site-packages. The
+/// second half is deliberately the same question
+/// [`crate::commands::process::prefix_has_torch`] answers for the
+/// completeness check, because this module answering it differently is the
+/// whole bug: the panel called the install complete (it found torch in the
+/// venv) while the launcher called the venv absent (it found no interpreter).
+/// An empty folder called `venv` is neither, and must not block a start.
+pub fn comfy_venv_state(comfyui_dir: &Path) -> ComfyVenv {
+ let mut broken: Option<ComfyVenv> = None;
for venv_name in ["venv", ".venv"] {
- let candidate = venv_python_path_named(comfyui_dir, venv_name);
- if candidate.exists() {
- return Some(candidate.to_string_lossy().to_string());
+ let interpreter = venv_python_path_named(comfyui_dir, venv_name);
+ if interpreter.exists() {
+ return ComfyVenv::Usable(interpreter.to_string_lossy().to_string());
+ }
+ if broken.is_some() {
+ continue;
+ }
+ let venv_dir = comfyui_dir.join(venv_name);
+ if venv_dir.join("pyvenv.cfg").exists()
+ || crate::commands::process::prefix_has_torch(&venv_dir)
+ {
+ broken = Some(ComfyVenv::Broken { venv_dir, interpreter });
}
}
- None
+ broken.unwrap_or(ComfyVenv::Absent)
+}
+
+/// The venv Python for `comfyui_dir` iff it is usable, as a String (matching
+/// the API that `process::start_comfyui` uses for its `bundled_python` /
+/// `system_python` slots).
+///
+/// None still means "do not launch from a venv", which is what the installer,
+/// the updater and the custom-node path want. Only the launcher has to tell
+/// Broken from Absent, so only the launcher asks [`comfy_venv_state`].
+pub fn resolve_comfyui_venv_python(comfyui_dir: &Path) -> Option<String> {
+ match comfy_venv_state(comfyui_dir) {
+ ComfyVenv::Usable(p) => Some(p),
+ ComfyVenv::Broken { .. } | ComfyVenv::Absent => None,
+ }
}
/// Resolve the real Python binary path, filtering out the Microsoft Store stub
@@ -516,6 +571,100 @@ mod tests {
assert!(resolved.unwrap().contains(".venv"));
}
+ // ── P3: comfy_venv_state, die dritte Antwort ───────────────────────────
+ //
+ // Der Tester hat `venv\Scripts\python.exe` umbenannt und Start gedrueckt.
+ // Die App hat es nicht gemerkt und still
+ // `C:\Program Files\Python311\python.exe` gestartet, weil "venv ohne
+ // Interpreter" und "kein venv" bis dahin dieselbe Antwort waren.
+
+ /// Legt ein venv an, dem genau der Interpreter fehlt. `Lib/site-packages`
+ /// ist die Windows-Form, und `prefix_has_torch` prueft alle Formen auf
+ /// jeder Plattform, also braucht der Test keinen Plattformzweig.
+ fn broken_venv(tmp: &std::path::Path, venv_name: &str, marker: bool, torch: bool) {
+ let venv = tmp.join(venv_name);
+ fs::create_dir_all(&venv).unwrap();
+ if marker {
+ fs::write(venv.join("pyvenv.cfg"), "home = C:\\Program Files\\Python311\n").unwrap();
+ }
+ if torch {
+ fs::create_dir_all(venv.join("Lib").join("site-packages").join("torch")).unwrap();
+ }
+ }
+
+ #[test]
+ fn ein_venv_ohne_interpreter_ist_kaputt_und_nicht_abwesend() {
+ let tmp = crate::os_paths::test_dir("venv-broken");
+ broken_venv(&tmp, "venv", true, true);
+ assert_eq!(
+ comfy_venv_state(&tmp),
+ ComfyVenv::Broken {
+ venv_dir: tmp.join("venv"),
+ interpreter: venv_python_path_named(&tmp, "venv"),
+ },
+ "der Fall des Testers muss von 'kein venv' unterscheidbar sein",
+ );
+ // Der Vertrag der sechs anderen Aufrufer bleibt: kaputt heisst weiter
+ // "starte hier nicht heraus".
+ assert!(resolve_comfyui_venv_python(&tmp).is_none());
+ }
+
+ #[test]
+ fn ein_venv_ohne_marke_aber_mit_torch_ist_auch_kaputt() {
+ // process.rs:628-632 nennt die Form ausdruecklich: manche Werkzeuge
+ // legen site-packages ohne pyvenv.cfg an. Die Vollstaendigkeitspruefung
+ // zaehlt so ein Verzeichnis als fertige Installation, also darf der
+ // Launcher es nicht als abwesend lesen.
+ let tmp = crate::os_paths::test_dir("venv-broken-nomarker");
+ broken_venv(&tmp, "venv", false, true);
+ assert!(matches!(comfy_venv_state(&tmp), ComfyVenv::Broken { .. }));
+ }
+
+ #[test]
+ fn ein_leerer_ordner_namens_venv_ist_kein_venv() {
+ // Negativkontrolle zu den beiden darueber: wer `Broken` am blossen
+ // Ordnernamen festmacht, verweigert hier einen Start, der heute laeuft.
+ let tmp = crate::os_paths::test_dir("venv-empty");
+ broken_venv(&tmp, "venv", false, false);
+ assert_eq!(comfy_venv_state(&tmp), ComfyVenv::Absent);
+ assert!(resolve_comfyui_venv_python(&tmp).is_none());
+ }
+
+ #[test]
+ fn auch_ein_punkt_venv_kann_kaputt_sein() {
+ // Issue #51 noch einmal, eine Ebene tiefer: die uv-Form darf nicht
+ // durch dasselbe Raster fallen wie damals.
+ let tmp = crate::os_paths::test_dir("dotvenv-broken");
+ broken_venv(&tmp, ".venv", true, false);
+ assert_eq!(
+ comfy_venv_state(&tmp),
+ ComfyVenv::Broken {
+ venv_dir: tmp.join(".venv"),
+ interpreter: venv_python_path_named(&tmp, ".venv"),
+ },
+ );
+ }
+
+ #[test]
+ fn ein_benutzbares_venv_gewinnt_weiterhin() {
+ let tmp = crate::os_paths::test_dir("venv-usable-wins");
+ // Ein kaputtes `.venv` daneben, damit die Reihenfolge geprueft wird und
+ // nicht nur der Einzelfall.
+ broken_venv(&tmp, ".venv", true, false);
+ broken_venv(&tmp, "venv", true, true);
+ let py = venv_python_path_named(&tmp, "venv");
+ fs::create_dir_all(py.parent().unwrap()).unwrap();
+ fs::write(&py, "stub").unwrap();
+ assert_eq!(
+ comfy_venv_state(&tmp),
+ ComfyVenv::Usable(py.to_string_lossy().to_string()),
+ );
+ assert_eq!(
+ resolve_comfyui_venv_python(&tmp).as_deref(),
+ Some(py.to_string_lossy().as_ref()),
+ );
+ }
+
// ── is_real_python (Bug P14 — Microsoft Store stub filter) ──────────────
#[test]
diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs
index 262b30fe..996f3ad4 100644
--- a/src-tauri/src/state.rs
+++ b/src-tauri/src/state.rs
@@ -63,8 +63,9 @@ pub struct InstallState {
/// One sentence a finished run leaves behind, for the cases where "it
/// worked" is not the whole truth. A15, Windows Nachlauf 02.09.: a
/// requirements.txt that pip cannot install is skipped and the run carries
- /// on with LU's own package list, which is right, but the run then ended on
- /// a green panel with no word about the file that was passed over. The
+ /// on with the packages LU knows about, which is right, but the run then
+ /// ended on a green panel with no word about the file that was passed over.
+ /// The
/// panel already had a place for a closing line (the cancel notice); this
/// is how the backend fills it.
#[serde(default)]
diff --git a/src/api/__tests__/der-wegweiser-nennt-echte-reiter.test.ts b/src/api/__tests__/der-wegweiser-nennt-echte-reiter.test.ts
index 8b1b2a41..f76fe60a 100644
--- a/src/api/__tests__/der-wegweiser-nennt-echte-reiter.test.ts
+++ b/src/api/__tests__/der-wegweiser-nennt-echte-reiter.test.ts
@@ -11,11 +11,13 @@
* haelt jeden "Models -> X"-Wegweiser im Baum dagegen. Wird ein Reiter noch
* einmal umbenannt, faellt der Test, nicht der Kunde.
*
- * Bewusst NICHT abgedeckt: die Formulierung "the X tab". Die gibt es aktuell
- * noch einmal im Baum, in src/lib/constants.ts:349 ("pick bigger models from
- * the Discover tab once you're in.", die Beschreibung des Starter-Modells im
- * Onboarding). Diese Datei liegt ausserhalb dieser Aufgabe. Wer sie faengt,
- * nimmt das Muster hier dazu.
+ * Die zweite Satzform, "the X tab", ist seit der Nachlese dabei. Sie stand in
+ * src/lib/constants.ts:349, in der Beschreibung des Starter-Modells: "pick
+ * bigger models from the Discover tab once you're in." Das ist einer der
+ * ersten Saetze, die ein neuer Kunde ueberhaupt liest, und er nannte denselben
+ * verschwundenen Reiter. Geprueft wird dabei nur gegen Namen, die die
+ * Reiterleiste der Models-Seite frueher getragen hat: "the Create tab" und
+ * "the Code tab" zeigen auf andere Seiten und gehen niemanden hier etwas an.
*
* Der Nachbarwaechter fuer die andere Satzform ("Open Models, X and ...")
* steht in src/lib/__tests__/der-rat-nennt-nur-echte-knoepfe.test.ts.
@@ -66,6 +68,17 @@ function kundentexte(zeile: string): string[] {
}
const WEGWEISER = /Models\s*(?:→|->|&rarr;)\s*(.+)$/g
+const REITERSATZ = /\bthe ([A-Z][A-Za-z ]*?) tab\b/g
+
+/**
+ * Namen, die die Reiterleiste der Models-Seite frueher getragen hat.
+ *
+ * Ein Kundentext, der einen davon nennt, schickt den Kunden zu einem Reiter,
+ * den es auf der Seite nicht mehr gibt. Kommt der Name eines Tages zurueck,
+ * faellt er hier von allein wieder heraus, weil gegen die echte Leiste
+ * geprueft wird und nicht gegen diese Liste allein.
+ */
+const FRUEHERE_REITER = ['Discover']
describe('der Wegweiser auf die Models-Seite', () => {
const reiter = reiterBeschriftungen()
@@ -100,6 +113,32 @@ describe('der Wegweiser auf die Models-Seite', () => {
expect(reiter.some((r) => treffer[0][1].startsWith(r))).toBe(false)
})
+ it('und jeder "the X tab"-Wegweiser genauso', () => {
+ const suender: string[] = []
+ for (const f of [...dateien(src, /\.tsx?$/), ...dateien(rust, /\.rs$/)]) {
+ for (const [i, zeile] of readFileSync(f, 'utf8').split('\n').entries()) {
+ for (const text of kundentexte(zeile)) {
+ for (const treffer of text.matchAll(REITERSATZ)) {
+ const name = treffer[1]
+ if (FRUEHERE_REITER.includes(name) && !reiter.includes(name)) {
+ suender.push(`${f}:${i + 1} nennt "${name}"`)
+ }
+ }
+ }
+ }
+ }
+ expect(suender).toEqual([])
+ })
+
+ // Negativkontrolle: genau der Satz, den ein neuer Kunde im Onboarding las.
+ it('der Satz aus dem Onboarding waere aufgefallen', () => {
+ const alt = "Great to verify your setup; pick bigger models from the Discover tab once you're in."
+ const treffer = [...alt.matchAll(REITERSATZ)]
+ expect(treffer).toHaveLength(1)
+ expect(FRUEHERE_REITER).toContain(treffer[0][1])
+ expect(reiter).not.toContain(treffer[0][1])
+ })
+
it('die drei Meldungen im Bild- und Videoweg zeigen auf "Get new"', () => {
const datei = readFileSync(join(src, 'api', 'vram-handoff.ts'), 'utf8')
const wege = [...datei.matchAll(/Models\s*→\s*([A-Za-z][A-Za-z ]*)/g)].map((m) => m[1].trim())
diff --git a/src/api/__tests__/die-zeile-wartet-auf-ihren-leser.test.ts b/src/api/__tests__/die-zeile-wartet-auf-ihren-leser.test.ts
new file mode 100644
index 00000000..ebbac02d
--- /dev/null
+++ b/src/api/__tests__/die-zeile-wartet-auf-ihren-leser.test.ts
@@ -0,0 +1,131 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * Eine Zeile, die nur im Chat gezeichnet wird, darf nicht ablaufen, waehrend
+ * der Nutzer in den Einstellungen steht.
+ *
+ * Beide Ansagen ueber eine Wahl, die sich von selbst geaendert hat, werden von
+ * den Einstellungen aus ausgeloest. Der gemessene Fall G1 (04.09.2026) ist
+ * "Provider LM Studio wieder herausgenommen", der zweite ist "Enable auf der
+ * Standby-Karte". Gezeichnet wird die Zeile aber von `LuEngineSwitchBar`, und
+ * die haengt ueber dem Eingabefeld im Chat und auf der Models-Seite, nicht im
+ * Einstellungsblatt. Auf der gewoehnlichen Zwoelf-Sekunden-Uhr lief sie also
+ * genau dort ab, wo niemand sie sehen konnte, und der Kunde kam in einen Chat
+ * zurueck, in dem ein anderes Modell stand und kein Wort dazu. Das war der
+ * Befund, und die Zeile allein hat ihn nicht behoben.
+ *
+ * Run: npx vitest run src/api/__tests__/die-zeile-wartet-auf-ihren-leser.test.ts
+ */
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+
+vi.mock('../backend', () => ({
+ backendCall: vi.fn(async () => ({})),
+ isTauri: () => false,
+ isMacOS: () => false,
+ isWindows: () => true,
+ isLinux: () => false,
+ secretGet: vi.fn().mockRejectedValue(new Error('no vault')),
+ secretSet: vi.fn(),
+ secretDelete: vi.fn(),
+}))
+
+const {
+ announceChatModelReplaced, announceChatModelLostItsEngine, UNSEEN_NOTE_HOLD_MS,
+} = await import('../lu-engine-switch')
+const { useLuEngineSwitchStore, LU_ENGINE_SWITCH_NOTE_MS, HOLD_CHECK_MS } =
+ await import('../../stores/luEngineSwitchStore')
+const { useUIStore } = await import('../../stores/uiStore')
+
+const WEG = 'openai::Qwen3-4B-Q4_K_M'
+const STATT = 'openai::G1-Kaputt-Q4_K_M'
+
+const zeile = () => useLuEngineSwitchStore.getState().note
+const lies = (p: string) => readFileSync(resolve(__dirname, '..', '..', p), 'utf8')
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ useLuEngineSwitchStore.getState().dismiss()
+ useUIStore.setState({ currentView: 'settings' })
+})
+afterEach(() => {
+ useLuEngineSwitchStore.getState().dismiss()
+ useUIStore.setState({ currentView: 'chat' })
+ vi.useRealTimers()
+})
+
+describe('die Zeile ueber die selbst getauschte Wahl', () => {
+ it('steht noch, wenn der Nutzer nach 12,44 s immer noch in den Einstellungen ist', () => {
+ announceChatModelReplaced(WEG, STATT)
+ vi.advanceTimersByTime(12_440)
+ expect(zeile()).not.toBeNull()
+ })
+
+ it('und laeuft erst ab, nachdem er im Chat war', () => {
+ announceChatModelReplaced(WEG, STATT)
+ vi.advanceTimersByTime(30_000)
+ expect(zeile()).not.toBeNull()
+
+ useUIStore.setState({ currentView: 'chat' })
+ // Der Halt wird im Sekundentakt geprueft, danach beginnt die Lesezeit bei
+ // null.
+ vi.advanceTimersByTime(HOLD_CHECK_MS + LU_ENGINE_SWITCH_NOTE_MS - 1_000)
+ expect(zeile()).not.toBeNull()
+ vi.advanceTimersByTime(2 * LU_ENGINE_SWITCH_NOTE_MS)
+ expect(zeile()).toBeNull()
+ })
+
+ it('die Models-Seite zaehlt auch, die Zeile haengt dort ebenfalls', () => {
+ useUIStore.setState({ currentView: 'models' })
+ announceChatModelReplaced(WEG, STATT)
+ vi.advanceTimersByTime(2 * LU_ENGINE_SWITCH_NOTE_MS)
+ expect(zeile(), 'auf einer Seite, die sie zeigt, gilt die gewoehnliche Uhr').toBeNull()
+ })
+
+ it('bleibt nicht ewig stehen, wenn er nie zurueckkommt', () => {
+ announceChatModelReplaced(WEG, STATT)
+ vi.advanceTimersByTime(UNSEEN_NOTE_HOLD_MS + 3 * LU_ENGINE_SWITCH_NOTE_MS)
+ expect(zeile()).toBeNull()
+ })
+
+ // Negativkontrolle: genau die alte Ansage, an genau diesem Ablauf.
+ it('die alte Ansage ohne Halt waere in den Einstellungen verfallen', () => {
+ useLuEngineSwitchStore.getState().announce('irgendein Satz ohne Halt', 'info')
+ vi.advanceTimersByTime(12_440)
+ expect(zeile()).toBeNull()
+ })
+})
+
+describe('die Zeile ueber die mit dem Steckplatz gefallene Wahl', () => {
+ it('wartet genauso, sie wird sogar in den Einstellungen ausgeloest', () => {
+ announceChatModelLostItsEngine(WEG, 'LM Studio')
+ vi.advanceTimersByTime(12_440)
+ expect(zeile()).not.toBeNull()
+ useUIStore.setState({ currentView: 'chat' })
+ vi.advanceTimersByTime(HOLD_CHECK_MS + 2 * LU_ENGINE_SWITCH_NOTE_MS)
+ expect(zeile()).toBeNull()
+ })
+
+ it('ohne Namen des Uebernehmers bleibt der Satz trotzdem ein Satz', () => {
+ announceChatModelLostItsEngine(WEG, null)
+ expect(zeile()).toContain('another backend')
+ expect(zeile()).toContain('Qwen3-4B-Q4_K_M')
+ })
+})
+
+describe('warum genau diese beiden Seiten', () => {
+ it('die Zeile haengt im Chat und auf der Models-Seite', () => {
+ expect(lies('components/chat/ChatView.tsx')).toContain('<LuEngineSwitchBar />')
+ const models = lies('components/models/ModelManager.tsx') + lies('components/models/DiscoverModels.tsx')
+ expect(models).toContain('<LuEngineSwitchBar />')
+ })
+
+ it('und nicht im Einstellungsblatt, wo beide Ausloeser sitzen', () => {
+ const settings = lies('components/settings/SettingsPage.tsx') + lies('components/settings/ProviderConfig.tsx')
+ expect(settings).not.toContain('LuEngineSwitchBar')
+ // Beide Ausloeser stehen wirklich dort: Remove auf der Provider-Karte und
+ // Enable auf der Standby-Karte.
+ expect(lies('components/settings/ProviderConfig.tsx')).toContain('slotHandbackUpdate')
+ })
+})
diff --git a/src/api/__tests__/kein-toter-testausgang-im-backend.test.ts b/src/api/__tests__/kein-toter-testausgang-im-backend.test.ts
new file mode 100644
index 00000000..34b0e7dd
--- /dev/null
+++ b/src/api/__tests__/kein-toter-testausgang-im-backend.test.ts
@@ -0,0 +1,72 @@
+/**
+ * Ein Ausgang, den nur die Tests benutzen sollen, muss auch benutzt werden.
+ *
+ * Die Nachlese hat `__resetProxyWarnLogForTests` in src/api/backend.ts
+ * gefunden: exportiert, dokumentiert ("Test-only: forget which hosts have
+ * already had their warning"), und im ganzen Baum ohne einen einzigen Leser,
+ * Tests eingeschlossen. Ein solcher Ausgang ist schlimmer als kein Ausgang.
+ * Er behauptet, jemand raeume `proxyWarnSeen` zwischen zwei Laeufen auf, und
+ * wer das glaubt, schreibt einen Test, der von einer Isolation ausgeht, die es
+ * nicht gibt.
+ *
+ * Geprueft wird nur src/api/backend.ts. Es gibt zwei weitere tote Ausgaenge
+ * derselben Art im Baum (`__resetCivitaiVaultForTests`,
+ * `__resetProviderSlotDarkeningForTests`), beide in Dateien, die zu dieser
+ * Aufgabe nicht gehoeren.
+ *
+ * Run: npx vitest run src/api/__tests__/kein-toter-testausgang-im-backend.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { readdirSync, readFileSync, statSync } from 'node:fs'
+import { resolve, join } from 'node:path'
+
+const repo = resolve(__dirname, '..', '..', '..')
+const backend = join(repo, 'src', 'api', 'backend.ts')
+
+function dateien(dir: string, endung: RegExp): string[] {
+ const out: string[] = []
+ for (const e of readdirSync(dir)) {
+ if (e === 'node_modules' || e === 'dist' || e === 'target') continue
+ const p = join(dir, e)
+ if (statSync(p).isDirectory()) out.push(...dateien(p, endung))
+ else if (endung.test(e)) out.push(p)
+ }
+ return out
+}
+
+/**
+ * Jeder Leser im Baum ausser der Datei, in der die Funktion selbst steht, und
+ * ausser dieser hier: ein Waechter, der den Namen nennt, um ihn zu suchen,
+ * wuerde sonst jeden toten Ausgang am Leben halten, den er gerade meldet.
+ */
+const selbst = join(__dirname, 'kein-toter-testausgang-im-backend.test.ts')
+
+function leser(name: string): string[] {
+ const orte: string[] = []
+ for (const f of [...dateien(join(repo, 'src'), /\.tsx?$/), ...dateien(join(repo, 'e2e'), /\.tsx?$/)]) {
+ if (f === backend || f === selbst) continue
+ if (readFileSync(f, 'utf8').includes(name)) orte.push(f)
+ }
+ return orte
+}
+
+describe('die Test-Ausgaenge in api/backend.ts', () => {
+ const quelle = readFileSync(backend, 'utf8')
+ const ausgaenge = [...quelle.matchAll(/export (?:function|const) (__[A-Za-z]+ForTests)/g)].map((m) => m[1])
+
+ it('jeder von ihnen hat einen Leser', () => {
+ const tot = ausgaenge.filter((n) => leser(n).length === 0)
+ expect(tot).toEqual([])
+ })
+
+ it('und der gefundene ist wirklich weg, samt seiner Notiz', () => {
+ expect(quelle).not.toContain('__resetProxyWarnLogForTests')
+ expect(quelle).not.toContain('Test-only: forget which hosts')
+ })
+
+ // Negativkontrolle: der Sammelbehaelter, den er raeumen sollte, steht noch
+ // da und wird noch gebraucht. Entfernt wurde der Ausgang, nicht die Regel.
+ it('der Behaelter selbst bleibt, er tut ja etwas', () => {
+ expect(quelle).toContain('const proxyWarnSeen = new Map<string, number>()')
+ })
+})
diff --git a/src/api/backend.ts b/src/api/backend.ts
index baccae19..8438d9df 100644
--- a/src/api/backend.ts
+++ b/src/api/backend.ts
@@ -16,11 +16,6 @@ import { shouldLogRepeat } from "../lib/probe-backoff";
// a dead local backend from filling the console with the same line forever.
const proxyWarnSeen = new Map<string, number>();
-/** Test-only: forget which hosts have already had their warning. */
-export function __resetProxyWarnLogForTests(): void {
- proxyWarnSeen.clear();
-}
-
let _invoke: ((cmd: string, args?: Record<string, unknown>) => Promise<unknown>) | null = null;
/** True when running inside a Tauri WebView (.exe), false in browser dev mode */
diff --git a/src/api/engine.ts b/src/api/engine.ts
index a3170914..3cff9fc9 100644
--- a/src/api/engine.ts
+++ b/src/api/engine.ts
@@ -266,7 +266,10 @@ export function customModelDirs(): string[] {
* nobody waited for, as long as the panel says it is partial. */
export interface ScannedDir {
path: string
- status: 'ok' | 'truncated' | 'unreachable' | 'unusable'
+ /** `denied` is its own answer, not a shade of `unreachable`: the folder is
+ * there and this account may not read it, so telling the user to check the
+ * cable sends them after a fault that does not exist (P3, 7.4). */
+ status: 'ok' | 'truncated' | 'unreachable' | 'denied' | 'unusable'
}
// The folders the LAST listing walked, app dir first. Kept here rather than
diff --git a/src/api/lu-engine-switch.ts b/src/api/lu-engine-switch.ts
index cfb70385..b09a613b 100644
--- a/src/api/lu-engine-switch.ts
+++ b/src/api/lu-engine-switch.ts
@@ -20,6 +20,7 @@ import { useLuEngineSwitchStore } from '../stores/luEngineSwitchStore'
import { luEngineSwapInFlight } from './lu-engine-swap-lock'
import { useProviderStore } from '../stores/providerStore'
import { useModelStore } from '../stores/modelStore'
+import { useUIStore } from '../stores/uiStore'
import {
slotHandbackUpdate, standbyOccupant,
type HandoverSlot, type SlotOccupant,
@@ -204,9 +205,63 @@ function chatModelReplacedNote(gone: string, now: string): string {
* effect looks, the store already reads the replacement and the rule has
* nothing left to notice. That case is announced by whoever hands the list in
* (hooks/useModels), where the before and the after are both still there.
+ *
+ * NICHT der Halt der beiden Nachbarn eine Tuer weiter. Die halten, weil ihr
+ * Satz beim Ansagen noch nicht stimmt: der Steckplatz ist umgehaengt, die Wahl
+ * kommt erst an, wenn das fremde Backend geladen hat, auf der Box nach 12,4
+ * bzw. 16,8 s. Dieser Satz stimmt dagegen im selben Zug, in dem er geschrieben
+ * wird. Beide Tueren haben den Tausch schon vollzogen (`setModels` in
+ * derselben set(), AppShell eine Anweisung spaeter und ohne `await`
+ * dazwischen), er ist also wahr, bevor der erste Bildaufbau ihn zeigen kann.
+ * Ein Halt auf die Wahrheit haette hier nichts zu halten.
+ *
+ * WOHL ABER der Halt auf den Leser. Der gemessene Fall von G1 ist "Provider
+ * LM Studio in den Einstellungen wieder herausgenommen", und die Zeile wird
+ * ueber dem Eingabefeld im Chat und auf der Models-Seite gezeichnet, nicht in
+ * den Einstellungen (`LuEngineSwitchBar`). Sie stand also zwoelf Sekunden lang
+ * auf einer Seite, die es nicht gibt, und war weg, bevor der Kunde in den Chat
+ * zurueckkam und dort ACTIVE neben einer kaputten GGUF-Datei fand. Genau das
+ * war der Befund. `bisJemandHinsehenKann` haelt sie, solange keine Seite offen
+ * ist, die sie zeigt.
*/
export function announceChatModelReplaced(gone: string, now: string): void {
- useLuEngineSwitchStore.getState().announce(chatModelReplacedNote(gone, now), 'info')
+ useLuEngineSwitchStore.getState().announce(
+ chatModelReplacedNote(gone, now), 'info', bisJemandHinsehenKann(),
+ )
+}
+
+/**
+ * Was die stehende Zeile sagt, wenn der geteilte lokale Steckplatz an ein
+ * anderes Backend gegangen ist und die Wahl damit hinfaellig war.
+ */
+function chatModelLostItsEngineNote(gone: string, taker: string): string {
+ return `"${displayModelName(gone)}" was served by the LU Engine, and ${taker} has the local slot now, so it is no longer the chat model.`
+}
+
+/**
+ * Die dritte Tuer, und die einzige, die keinen Ersatz zu nennen hat.
+ *
+ * Nach der Uebergabe an ein fremdes Backend raeumt `dropDisplacedEnginePick`
+ * (lib/builtin-slot-eviction) die Wahl, weil auf 8127 nichts mehr liegt. Damit
+ * ist `activeModel` null, und `replacedBehindTheUsersBack` verlangt einen
+ * vorherigen Namen, den es nach dem Raeumen nicht mehr gibt: die Regel liefert
+ * false, und die Zeile fiel aus. Der Nutzer sah seinen Chip wechseln und
+ * bekam kein Wort dazu. Gesagt wird es deshalb dort, wo der alte Name noch
+ * dasteht, im selben Zug wie das Raeumen.
+ *
+ * Kein Halt auf die Wahrheit, aus demselben Grund wie bei
+ * `announceChatModelReplaced`: der Steckplatz ist schon umgehaengt und die
+ * Wahl schon gefallen, wenn dieser Satz geschrieben wird. Er stimmt sofort und
+ * bleibt wahr, auch wenn die naechste Inventarrunde von selbst eine andere
+ * Zeile waehlt. Der Halt auf den Leser dagegen ist hier noch noetiger als
+ * dort: der Knopf, der das ausloest, steht in den Einstellungen, und die Zeile
+ * wird dort nicht gezeichnet.
+ */
+export function announceChatModelLostItsEngine(gone: string, taker: string | null | undefined): void {
+ useLuEngineSwitchStore.getState().announce(
+ chatModelLostItsEngineNote(gone, taker?.trim() || 'another backend'), 'info',
+ bisJemandHinsehenKann(),
+ )
}
/** What the pick says when it moved the chat backend to `name`. */
@@ -252,9 +307,39 @@ export function announceChatProviderSwitch(name: string, modelName: string): voi
* Die Frist wird beim Ansagen festgelegt, nicht bei jeder Abfrage, sonst
* verschiebt sie sich mit jedem Blick und die Zeile bliebe fuer immer stehen.
*/
-function haltenBis(pruefung: () => boolean): () => boolean {
- const frist = Date.now() + CHAT_PROVIDER_SWITCH_HOLD_MS
- return () => Date.now() < frist && pruefung()
+function haltenBis(pruefung: () => boolean, frist = CHAT_PROVIDER_SWITCH_HOLD_MS): () => boolean {
+ const ende = Date.now() + frist
+ return () => Date.now() < ende && pruefung()
+}
+
+/** Die Seiten, auf denen `LuEngineSwitchBar` wirklich haengt. */
+const SEITEN_MIT_ZEILE: ReadonlySet<string> = new Set(['chat', 'models'])
+
+/**
+ * Wie lange eine Zeile auf ihren Leser wartet.
+ *
+ * Grosszuegig fuer eine Runde durch die Einstellungen und kurz genug, dass der
+ * Satz noch von etwas handelt, das der Nutzer selbst gerade getan hat. Ein
+ * Deckel muss sein: der Halt sieht im Sekundentakt nach, und ohne Frist liefe
+ * dieser Takt bis zum Ende der Sitzung.
+ */
+export const UNSEEN_NOTE_HOLD_MS = 5 * 60_000
+
+/**
+ * Halten, solange gar keine Seite offen ist, die diese Zeile zeichnet.
+ *
+ * Beide Ansagen ueber eine Wahl, die sich von selbst geaendert hat, werden von
+ * den Einstellungen aus ausgeloest: Provider entfernen, Enable auf der
+ * Standby-Karte. Die Zeile haengt aber ueber dem Eingabefeld im Chat und auf
+ * der Models-Seite. Auf der gewoehnlichen Uhr lief sie also ab, waehrend
+ * niemand sie sehen konnte, und der Nutzer kam in einen Chat zurueck, in dem
+ * ein anderes Modell stand und nichts dazu.
+ */
+function bisJemandHinsehenKann(): () => boolean {
+ return haltenBis(
+ () => !SEITEN_MIT_ZEILE.has(useUIStore.getState().currentView),
+ UNSEEN_NOTE_HOLD_MS,
+ )
}
/**
@@ -329,6 +414,41 @@ function isStandbyBackendRow(row: InstalledModelLike | null | undefined): boolea
return isRowOfBackend(row, standbyChatBackend()?.name)
}
+/**
+ * Die Zeile, auf die der Steckplatz gerade wartet, weil der Nutzer sie selbst
+ * angeklickt hat, und wie lange diese Auskunft gilt.
+ */
+let angefragteZeile: { name: string; frist: number } | null = null
+
+/**
+ * Wartet der Steckplatzwechsel noch auf die Zeile, die der Nutzer angeklickt
+ * hat.
+ *
+ * Dieselbe Uebergabe kommt aus zwei ganz verschiedenen Haenden. In den
+ * Einstellungen drueckt jemand Enable auf der Standby-Karte, und der Chip im
+ * Chat wechselt, ohne dass er den Waehler angefasst hat: darueber gehoert ein
+ * Satz. Im Waehler klickt er selbst eine Zeile des wartenden Backends an, und
+ * dann steht die Wechselzeile bereits auf dem Schirm und beschreibt genau
+ * diesen Vorgang. Ein zweiter Satz waere dort nicht nur Laerm, er wuerde den
+ * ersten auch loeschen, denn `announce` raeumt die vorige Zeile weg.
+ *
+ * Sofort gesetzt wird die Wahl dabei nicht immer. `useModels.activateModel`
+ * tut es ohne `await` gleich danach, der Waehler dagegen laedt das Modell
+ * erst in LM Studio, auf der Box gemessene 12,4 s, und setzt sie erst
+ * hinterher. Genau in diesem Fenster faellt die Wahl, und genau dort darf
+ * nichts gesagt werden. Die Frist ist dieselbe, die die Wechselzeile hoechstens
+ * stehen darf: laenger deckt sie nichts mehr zu.
+ */
+export function handbackAwaitsTheUsersPick(): boolean {
+ if (!angefragteZeile) return false
+ const angekommen = useModelStore.getState().activeModel === angefragteZeile.name
+ if (angekommen || Date.now() >= angefragteZeile.frist) {
+ angefragteZeile = null
+ return false
+ }
+ return true
+}
+
/**
* Hand the slot back when the picked row belongs to the backend on standby.
*
@@ -342,6 +462,10 @@ export function handBackChatProviderForRow(row: InstalledModelLike | null | unde
const slot = providers.openai as HandoverSlot
const update = slotHandbackUpdate(slot)
if (!update) return null
+ // Gemerkt, BEVOR der Steckplatz umgehaengt wird: das Schreiben stoesst die
+ // Raeumung der Wahl an, und die fragt gleich nach, aus wessen Hand der
+ // Wechsel kam.
+ angefragteZeile = { name: row?.name ?? '', frist: Date.now() + CHAT_PROVIDER_SWITCH_HOLD_MS }
setProviderConfig('openai', update)
return update.name ?? null
}
diff --git a/src/components/create/experimental/CreateContext.tsx b/src/components/create/experimental/CreateContext.tsx
index 5c384abe..71e5723c 100644
--- a/src/components/create/experimental/CreateContext.tsx
+++ b/src/components/create/experimental/CreateContext.tsx
@@ -10,9 +10,9 @@ import { backendCall, isMacOS, isLinux } from '../../../api/backend'
import { asComfyGpuMode, comfyCpuBannerText, type ComfyCpuBannerFacts } from '../../../lib/comfy-cpu-banner'
import { installMlxStack } from '../../../api/mlx-install'
import { useDownloadStore } from '../../../stores/downloadStore'
-import { downloadBundleFiles, waitOrAbort, waitForModelsVisible } from '../../../lib/bundle-install'
+import { downloadBundleFiles, waitOrAbort, waitForModelsVisible, InstallCancelled } from '../../../lib/bundle-install'
import { ensureLocalFilename } from './loadImage'
-import { comfyStartupError } from './comfyError'
+import { comfyStartupError, COMFY_INSTALLED_BUT_DEAD } from './comfyError'
import { restartComfyForNewNodes } from '../../../api/comfy-restart'
import type { CloudQuota } from '../../../lib/render/cloud-jobs'
@@ -268,7 +268,19 @@ export function CreateExpProvider({ children }: { children: ReactNode }) {
let r: 'up' | 'crashed' | 'timeout' | 'missing'
try {
r = await startAndAwait(60, onProgress, signal)
- } catch { r = 'missing' }
+ } catch (e) {
+ // P3: ein Start, der mit einer Meldung scheitert, ist kein fehlendes
+ // ComfyUI. Jedes Err aus start_comfyui landete hier als 'missing' und
+ // damit unten im Download-Zweig: mehrere Gigabyte fuer eine
+ // Installation, die vollstaendig auf der Platte liegt. Seit dem
+ // kaputten venv trifft das einen echten Fall, also entscheidet die
+ // Statusabfrage, ob wirklich etwas fehlt, und die Meldung des Starts
+ // erreicht sonst den Kunden.
+ if (e instanceof InstallCancelled) throw e
+ const st = await backendCall<{ found?: boolean; complete?: boolean }>('comfyui_status').catch(() => null)
+ if (st?.found && st?.complete !== false) throw e
+ r = 'missing'
+ }
for (;;) {
if (r === 'up') return
if (r === 'crashed') {
@@ -286,7 +298,7 @@ export function CreateExpProvider({ children }: { children: ReactNode }) {
// Der Hinweis aus dem Einordner des Installers, wenn es einen gibt.
// Der allgemeine Satz ueber die Reparatur gehoert hier nicht hin: der
// Knopf steht in den Einstellungen, nicht in diesem Ablauf.
- throw new Error(comfyStartupError(out?.lines, out?.hint))
+ throw new Error(comfyStartupError(COMFY_INSTALLED_BUT_DEAD, out?.lines, out?.hint))
}
if (r === 'missing' && !installedNow) {
installedNow = true
@@ -310,7 +322,7 @@ export function CreateExpProvider({ children }: { children: ReactNode }) {
// Timeout, or a state we already tried to fix once: report with the
// real output instead of guessing.
const out = await backendCall<{ lines?: string[]; hint?: string }>('comfyui_last_output').catch(() => null)
- throw new Error(comfyStartupError(out?.lines, out?.hint))
+ throw new Error(comfyStartupError(COMFY_INSTALLED_BUT_DEAD, out?.lines, out?.hint))
}
// `checkConnection` stand hier, ohne im Rumpf vorzukommen: aufgerufen wird
// es von `startAndAwait`, das selbst schon davon abhaengt. Der Eintrag war
diff --git a/src/components/create/experimental/__tests__/comfy-env-selfheal.test.ts b/src/components/create/experimental/__tests__/comfy-env-selfheal.test.ts
index e50ec349..7ca54187 100644
--- a/src/components/create/experimental/__tests__/comfy-env-selfheal.test.ts
+++ b/src/components/create/experimental/__tests__/comfy-env-selfheal.test.ts
@@ -42,6 +42,17 @@ describe('#98: die ComfyUI-Umgebung heilt sich selbst', () => {
expect(src).toMatch(/r === 'missing' && !installedNow/)
})
+ // P3: seit der Launcher einen Start mit kaputtem venv verweigert, trifft
+ // dieser Weg einen echten Fall. Jedes Err aus start_comfyui wurde hier zu
+ // 'missing' und damit zum Download von mehreren Gigabyte fuer eine
+ // Installation, die vollstaendig auf der Platte liegt.
+ it('ein gescheiterter Start ist kein fehlendes ComfyUI', () => {
+ const src = kontext()
+ expect(src, 'jeder Startfehler wird wieder als fehlende Installation gelesen')
+ .not.toMatch(/catch \{ r = 'missing' \}/)
+ expect(src).toMatch(/if \(st\?\.found && st\?\.complete !== false\) throw e/)
+ })
+
it('die Settings haben einen Repair-Knopf am selben Kommando', () => {
const src = settings()
expect(src).toMatch(/Repair environment/)
@@ -49,10 +60,23 @@ describe('#98: die ComfyUI-Umgebung heilt sich selbst', () => {
expect(installStore()).toMatch(/backendCall\('repair_comfyui_env'\)/)
})
- it('der Settings-Start meldet einen spaeten Absturz statt still auf Stopped zu kippen', () => {
+ // P3: hier stand ein Test, der nur nachsah, ob die Zeichenketten
+ // `comfyui_last_output` und `envBroken` irgendwo in SettingsPage.tsx
+ // vorkommen. Beides war unter dem einmaligen Blick nach 6 Sekunden wahr, und
+ // genau deshalb galt dieser Defekt als abgedeckt, waehrend ein Absturz nach
+ // 20 Sekunden gar nichts meldete. Was der Startversuch wirklich tut, steht
+ // jetzt in settings/__tests__/ein-spaeter-absturz-wird-noch-gemeldet.test.ts
+ // und laeuft dort gegen die gerenderte Oberflaeche. Hier bleibt der Anker
+ // gegen die Rueckkehr des Einmalblicks.
+ it('der Settings-Start sieht wiederholt hin, nicht einmal nach sechs Sekunden', () => {
const src = settings()
expect(src).toMatch(/comfyui_last_output/)
- expect(src).toMatch(/envBroken/)
+ expect(src).toMatch(/const watchForLateCrash/)
+ expect(src, 'der einmalige Blick nach 6 Sekunden ist zurueck').not.toMatch(/\}, 6000\)/)
+ // Das zweite stille Tor: der Puffer traegt immer die Kopfzeile `[start]`,
+ // also fiel ein Absturz ganz ohne Ausgabe auch dann durch, wenn `exited`
+ // stimmte.
+ expect(src).not.toMatch(/lines\.length > 1/)
})
})
@@ -74,7 +98,7 @@ describe('Ticket 007: der Rat unter der Ausgabe kommt aus einer Stelle', () => {
it('der Create-Pfad reicht den konkreten Hinweis an den Kunden durch', () => {
const src = kontext()
- expect(src).toMatch(/comfyStartupError\(out\?\.lines, out\?\.hint\)/)
+ expect(src).toMatch(/comfyStartupError\(COMFY_INSTALLED_BUT_DEAD, out\?\.lines, out\?\.hint\)/)
expect(src).toMatch(/hint\?: string/)
})
diff --git a/src/components/create/experimental/__tests__/comfy-startup-error.test.ts b/src/components/create/experimental/__tests__/comfy-startup-error.test.ts
index fa574b7b..36f79e94 100644
--- a/src/components/create/experimental/__tests__/comfy-startup-error.test.ts
+++ b/src/components/create/experimental/__tests__/comfy-startup-error.test.ts
@@ -1,13 +1,20 @@
import { describe, it, expect } from 'vitest'
-import { comfyStartupError, comfyCrashAdvice, REPAIR_ADVICE } from '../comfyError'
+import {
+ comfyStartupError,
+ comfyCrashAdvice,
+ REPAIR_ADVICE,
+ COMFY_INSTALLED_BUT_DEAD,
+ COMFY_START_FAILED,
+ comfyStartThrowText,
+} from '../comfyError'
// GH #98: "did not come up" used to be a dead end. The error must carry the
// crash tail when there is one, and stay the old pointer when there is not.
describe('comfyStartupError', () => {
it('falls back to the settings pointer without output', () => {
- expect(comfyStartupError()).toContain('Check Settings')
- expect(comfyStartupError([])).toContain('Check Settings')
- expect(comfyStartupError([' ', ''])).toContain('Check Settings')
+ expect(comfyStartupError(COMFY_INSTALLED_BUT_DEAD)).toContain('Check Settings')
+ expect(comfyStartupError(COMFY_INSTALLED_BUT_DEAD, [])).toContain('Check Settings')
+ expect(comfyStartupError(COMFY_INSTALLED_BUT_DEAD, [' ', ''])).toContain('Check Settings')
})
it('carries the last meaningful lines of a crash', () => {
@@ -17,14 +24,14 @@ describe('comfyStartupError', () => {
' File "main.py", line 1, in <module>',
"ModuleNotFoundError: No module named 'torch'",
]
- const msg = comfyStartupError(lines)
+ const msg = comfyStartupError(COMFY_INSTALLED_BUT_DEAD, lines)
expect(msg).toContain('did not come up')
expect(msg).toContain("ModuleNotFoundError: No module named 'torch'")
})
it('keeps only the tail of a long log', () => {
const lines = Array.from({ length: 50 }, (_, i) => `line ${i}`)
- const msg = comfyStartupError(lines)
+ const msg = comfyStartupError(COMFY_INSTALLED_BUT_DEAD, lines)
expect(msg).toContain('line 49')
expect(msg).not.toContain('line 40\n')
})
@@ -33,16 +40,17 @@ describe('comfyStartupError', () => {
// Satz, obwohl der Einordner des Installers wusste, was WinError 1114
// bedeutet. Jetzt reicht Rust den konkreten Rat mit, und er gewinnt.
it('haengt den mitgelieferten Rat unter die Ausgabe', () => {
- const msg = comfyStartupError(['OSError: [WinError 1114]'], 'Install the runtime.')
+ const msg = comfyStartupError(COMFY_INSTALLED_BUT_DEAD, ['OSError: [WinError 1114]'], 'Install the runtime.')
expect(msg).toContain('OSError: [WinError 1114]')
expect(msg).toContain('Install the runtime.')
})
it('bleibt ohne Rat genau die alte Meldung', () => {
const lines = ['boom']
- expect(comfyStartupError(lines, '')).toBe(comfyStartupError(lines))
- expect(comfyStartupError(lines, ' ')).toBe(comfyStartupError(lines))
- expect(comfyStartupError(undefined, '')).toContain('Check Settings')
+ const base = COMFY_INSTALLED_BUT_DEAD
+ expect(comfyStartupError(base, lines, '')).toBe(comfyStartupError(base, lines))
+ expect(comfyStartupError(base, lines, ' ')).toBe(comfyStartupError(base, lines))
+ expect(comfyStartupError(base, undefined, '')).toContain('Check Settings')
})
})
@@ -70,3 +78,84 @@ describe('comfyCrashAdvice', () => {
.not.toContain('rebuilds it in place')
})
})
+
+/**
+ * P3: derselbe Anfangssatz fuer beide Wege war fuer einen von beiden immer
+ * falsch. Der Tester hat in den Einstellungen auf Start gedrueckt und
+ * "Installed ComfyUI but it did not come up." bekommen; installiert hatte er
+ * nichts. Solange die Meldung im Startpfad ohnehin fast nie erschien, ist das
+ * niemandem aufgefallen.
+ */
+describe('der Anfang gehoert dem Aufrufer', () => {
+ it('der Startknopf spricht nicht von einer Installation', () => {
+ expect(COMFY_START_FAILED).not.toContain('Installed')
+ const msg = comfyStartupError(COMFY_START_FAILED, ['boom'])
+ expect(msg).toContain('boom')
+ expect(msg).not.toContain('Installed ComfyUI')
+ })
+
+ it('und der Create-Weg behaelt seinen', () => {
+ // Gegengewicht: der Satz ist nicht abgeschafft, er ist nur nicht mehr der
+ // einzige.
+ expect(comfyStartupError(COMFY_INSTALLED_BUT_DEAD, ['boom'])).toContain('Installed ComfyUI')
+ expect(COMFY_INSTALLED_BUT_DEAD).not.toBe(COMFY_START_FAILED)
+ })
+})
+
+/**
+ * P3, 7.2: sein torch starb an einem umbenannten c10.dll, also beim ersten
+ * Import und weit innerhalb der zwei Sekunden, die Rust dem Start zuschaut.
+ * Dieser Weg WIRFT, und ein Wurf plant keinen Beobachter, also blieb der
+ * Kunde bei "exited right after starting" stehen. Der Satz ueber die
+ * Visual-C++-Laufzeit lag die ganze Zeit im Einordner des Installers, und wer
+ * eine Sekunde spaeter abstuerzte, bekam ihn.
+ */
+describe('comfyStartThrowText', () => {
+ // Die Meldung, die `comfy_startup_failure` in den Wurf legt: Interpreter,
+ // Exit-Code und die letzten Zeilen des Kindes.
+ const geworfen = [
+ 'ComfyUI exited right after starting (python=C:\\ComfyUI\\venv\\Scripts\\python.exe, exit code 1).',
+ '',
+ 'Last output:',
+ 'OSError: [WinError 1114] a DLL initialization routine failed. Error loading "c10.dll"',
+ ].join('\n')
+
+ it('nennt die Visual-C++-Laufzeit auch beim Absturz binnen zwei Sekunden', () => {
+ const hint =
+ 'A Microsoft Visual C++ runtime library is missing on this machine: VCOMP140.DLL. ' +
+ 'Repair environment does not help here, it is not inside the venv.'
+ const msg = comfyStartThrowText(geworfen, { hint, envBroken: false })
+ expect(msg).toContain('Visual C++')
+ expect(msg).toContain('Repair environment does not help here')
+ // Und alles, was der Wurf selbst schon sagte, bleibt stehen.
+ expect(msg).toContain('exit code 1')
+ expect(msg).toContain('[WinError 1114]')
+ })
+
+ it('haengt nichts an, wenn der Einordner nichts zu sagen hat', () => {
+ // Die Gegenprobe: ohne sie stuende der Satz unter jedem Absturz.
+ const sauber = 'ComfyUI exited right after starting (python=python, exit code 1).'
+ expect(comfyStartThrowText(sauber, { hint: '', envBroken: false })).toBe(sauber)
+ expect(comfyStartThrowText(sauber, null)).toBe(sauber)
+ expect(comfyStartThrowText(sauber)).toBe(sauber)
+ })
+
+ it('eine kaputte Umgebung bekommt weiter den allgemeinen Satz, und nur einmal', () => {
+ const sauber = 'ComfyUI exited right after starting (python=python, exit code 1).'
+ expect(comfyStartThrowText(sauber, { envBroken: true })).toContain(REPAIR_ADVICE)
+ // Steht er schon in der Meldung, kommt er nicht ein zweites Mal.
+ const schon = `${sauber}\n\n${REPAIR_ADVICE}`
+ expect(comfyStartThrowText(schon, { envBroken: true })).toBe(schon)
+ })
+
+ /**
+ * Die Verantwortung bleibt in Rust. Wer hier einen zweiten Uebersetzer
+ * einbaut, hat zwei Tore fuer einen Strom, und eines davon ist irgendwann
+ * das schwaechere.
+ */
+ it('uebersetzt selbst nichts: eine deutsche Zeile geht unveraendert durch', () => {
+ const deutsch = 'OSError: [WinError 126] Das angegebene Modul wurde nicht gefunden.'
+ expect(comfyStartThrowText(deutsch)).toBe(deutsch)
+ expect(comfyStartupError(COMFY_START_FAILED, [deutsch])).toContain(deutsch)
+ })
+})
diff --git a/src/components/create/experimental/comfyError.ts b/src/components/create/experimental/comfyError.ts
index 6352dba6..992aedfc 100644
--- a/src/components/create/experimental/comfyError.ts
+++ b/src/components/create/experimental/comfyError.ts
@@ -1,12 +1,24 @@
+/** Der Anfang fuer den Create-Weg: dort hat LU gerade selbst installiert. */
+export const COMFY_INSTALLED_BUT_DEAD = 'Installed ComfyUI but it did not come up.'
+
+/** Der Anfang fuer den Startknopf in den Einstellungen.
+ *
+ * P3: dort hat niemand etwas installiert, dort wurde Start gedrueckt, und der
+ * Satz von der frischen Installation stand trotzdem darueber. Solange die
+ * Meldung nur alle sechs Sekunden einmal ueberhaupt erschien, ist das kaum
+ * jemandem untergekommen; ein Beobachter, der jeden spaeten Absturz meldet,
+ * wuerde die falsche Zeile zuverlaessig zeigen. */
+export const COMFY_START_FAILED = 'ComfyUI did not come up.'
+
/** Turn the ComfyUI output tail into an error a person can act on. The last
* lines of a startup crash name the real problem (a torch import error, a
* missing DLL, an OOM); without them the message was a dead end (GH #98).
- * `advice` is the sentence under the output, see comfyCrashAdvice. */
-export function comfyStartupError(lines?: string[], advice?: string): string {
+ * `opening` says which of the two ways in this was, `advice` is the sentence
+ * under the output, see comfyCrashAdvice. */
+export function comfyStartupError(opening: string, lines?: string[], advice?: string): string {
const tail = (lines ?? []).map((l) => l.trim()).filter(Boolean).slice(-6)
- const base = 'Installed ComfyUI but it did not come up.'
const rat = (advice ?? '').trim()
- const msg = tail.length ? `${base} Its last output:\n${tail.join('\n')}` : `${base} Check Settings → AI Backends.`
+ const msg = tail.length ? `${opening} Its last output:\n${tail.join('\n')}` : `${opening} Check Settings → AI Backends.`
return rat ? `${msg}\n\n${rat}` : msg
}
@@ -28,3 +40,27 @@ export function comfyCrashAdvice(out?: { hint?: string; envBroken?: boolean } |
if (hint) return hint
return out?.envBroken ? REPAIR_ADVICE : ''
}
+
+/** Die Meldung eines Starts, der schon vorbei war, bevor `start_comfyui`
+ * zurueckkam, mit dem Satz darunter, den der Einordner dazu hat.
+ *
+ * P3, 7.2: ein umbenanntes c10.dll toetet torch beim ersten Import, also weit
+ * innerhalb der zwei Sekunden, die Rust zuschaut. Dieser Weg wirft, und ein
+ * Wurf plant keinen Beobachter, also kam der Hinweis auf die Visual-C++-
+ * Laufzeit nie an, obwohl der Einordner ihn die ganze Zeit hatte. Wer eine
+ * Sekunde spaeter starb, bekam ihn.
+ *
+ * Kein zweiter Einordner und kein zweiter Text: `message` ist die Meldung, die
+ * Rust schon gebaut hat (Interpreterpfad, Exit-Code, die letzten acht Zeilen),
+ * und darunter kommt genau der Satz, den `comfyCrashAdvice` fuer beide
+ * Oberflaechen entscheidet. Steht er schon in der Meldung, bleibt es bei
+ * einem. */
+export function comfyStartThrowText(
+ message: string,
+ out?: { hint?: string; envBroken?: boolean } | null,
+): string {
+ const base = message.trim()
+ const advice = comfyCrashAdvice(out)
+ if (!advice || base.includes(advice)) return base
+ return `${base}\n\n${advice}`
+}
diff --git a/src/components/layout/Header.tsx b/src/components/layout/Header.tsx
index 65463309..8a635029 100644
--- a/src/components/layout/Header.tsx
+++ b/src/components/layout/Header.tsx
@@ -19,6 +19,7 @@ import { closeDialog, isTopDialog, nextFocusIndex, openDialog } from '../ui/dial
import { MONOGRAM, MONOGRAM_INVERT } from './brand'
import type { View } from '../../stores/uiStore'
import { WheelNav } from '../ui/WheelNav'
+import { modelListIsStale } from '../../lib/model-list-staleness'
/**
* Die Navigation als Daten, nicht als sechs abgeschriebene Knoepfe.
@@ -69,17 +70,17 @@ export function Header() {
// App-level model bootstrap. This used to ride on the header ModelSelector,
// which sat here always-mounted; the picker has moved into the composer
// (mounted only inside an active chat), so the header now owns the fetch.
- // Without it a fresh start never populates the list — and setModels' auto-
- // select of the first chat model never fires, so `activeModel` stays null and
- // New Chat dead-ends on the "pick a model" page. Refetch on provider changes
- // too (enable LM Studio / add a key in Settings), mirroring the old picker.
+ // Without it a fresh start never populates the list, setModels' auto-select
+ // of the first chat model never fires, `activeModel` stays null and New Chat
+ // dead-ends on the "pick a model" page. Refetch on provider changes too
+ // (enable LM Studio in Settings, hand the shared slot to another backend),
+ // mirroring the old picker. Welche Aenderung das ist, steht an genau einer
+ // Stelle (lib/model-list-staleness); sie stand hier und im Waehler
+ // wortgleich zweimal und kannte in beiden Fassungen `managed` nicht.
useEffect(() => { fetchModels() }, [fetchModels])
useEffect(() => {
const unsub = useProviderStore.subscribe((state, prev) => {
- const changed = (Object.keys(state.providers) as Array<keyof typeof state.providers>)
- .some((id) => state.providers[id]?.enabled !== prev.providers[id]?.enabled
- || state.providers[id]?.baseUrl !== prev.providers[id]?.baseUrl)
- if (changed) fetchModels()
+ if (modelListIsStale(state.providers, prev.providers)) fetchModels()
})
return () => unsub()
}, [fetchModels])
diff --git a/src/components/models/ModelSelector.tsx b/src/components/models/ModelSelector.tsx
index 14be67c7..5d3df429 100644
--- a/src/components/models/ModelSelector.tsx
+++ b/src/components/models/ModelSelector.tsx
@@ -25,6 +25,7 @@ import { cloudTeaserModels } from '../../lib/cloud-teaser-models'
import { splitBackendSwitchRows, needsBackendSwitchHeading, foldedRowsSentence } from '../../lib/lu-engine-rows'
import { isBuiltinEngineEntry, type InstalledModelLike } from '../../lib/lmstudio-match'
import type { HandoverSlot } from '../../lib/openai-slot-handover'
+import { modelListIsStale } from '../../lib/model-list-staleness'
import {
ensureLuEngineIsChatProvider, announceLuEngineSwitch, LU_ENGINE_SWAP_BUSY_NOTE,
clearEngineErrorAfterSuccess,
@@ -1041,16 +1042,15 @@ export function ModelSelector({ openUpward = false, surface = 'chat', answeredBy
return () => { cancelled = true }
}, [open])
- // Refetch when any provider's enabled state or baseUrl changes (e.g. user
- // enables LM Studio / adds Anthropic key in Settings, or the backend
- // picker activates an OpenAI-compatible provider). Without this the
- // dropdown stays stuck on whatever providers were enabled at mount time.
+ // Refetch when a provider change makes the list stale (the user enables LM
+ // Studio in Settings, the backend picker activates an OpenAI-compatible
+ // provider, a click hands the shared slot on). Without this the dropdown
+ // stays stuck on whatever providers were enabled at mount time. Die Regel
+ // steht in lib/model-list-staleness, dieselbe, die auch die Kopfleiste
+ // fragt.
useEffect(() => {
const unsub = useProviderStore.subscribe((state, prev) => {
- const changed = (Object.keys(state.providers) as Array<keyof typeof state.providers>)
- .some(id => state.providers[id]?.enabled !== prev.providers[id]?.enabled
- || state.providers[id]?.baseUrl !== prev.providers[id]?.baseUrl)
- if (changed) fetchModels()
+ if (modelListIsStale(state.providers, prev.providers)) fetchModels()
})
return () => unsub()
}, [fetchModels])
diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsx
index 330ad753..95e888ee 100644
--- a/src/components/settings/SettingsPage.tsx
+++ b/src/components/settings/SettingsPage.tsx
@@ -19,6 +19,11 @@ import { PersonaPanel } from '../personas/PersonaPanel'
import { AccountPanel } from '../auth/AccountPanel'
import { useVoiceStore } from '../../stores/voiceStore'
import { downloadSuffix } from '../../lib/formatters'
+// Der Satz zum Startfehler kommt fuer beide Oberflaechen aus dieser Stelle
+// (Ticket 007). Statisch geladen, weil ihn der Beobachter unten in dem
+// Augenblick braucht, in dem ein Start gescheitert ist: eine Meldung darf
+// nicht erst darauf warten, dass ein Stueck Programm nachgeladen wird.
+import { comfyStartupError, comfyCrashAdvice, comfyStartThrowText, COMFY_START_FAILED } from '../create/experimental/comfyError'
// AS-09: PIPER_VOICES und CLOUD_TTS_VOICES sind mit dem Abschnitt, der sie
// benutzt, nach ./SpeechSettings.tsx gezogen.
@@ -321,7 +326,8 @@ export function HfDownloadPathSetting() {
// same thing in different words. `truncated` is a different matter. The
// folder IS readable, the walk simply ran out of budget, and what LU hands
// to ComfyUI is unaffected by that, so both lines belong on screen.
- const scanHidesHandoff = scan?.status === 'unreachable' || scan?.status === 'unusable'
+ const scanHidesHandoff =
+ scan?.status === 'unreachable' || scan?.status === 'denied' || scan?.status === 'unusable'
// A16 (A14-2a), Windows counter-check 02.09.: the folder was stored on Enter
// or on blur and on nothing else. Type a path, walk away to another tab or
@@ -476,6 +482,12 @@ export function modelDirScanNote(status: ScannedDir['status'] | null | undefined
if (status === 'unreachable') {
return 'This folder cannot be reached right now (drive disconnected or path missing). Models in it are hidden until it is back.'
}
+ // P3, 7.4: this used to fall into the sentence above, which sent him looking
+ // for an unplugged drive while the drive was plugged in and the path was
+ // spelled right. Rust reports the reason now, so the panel can name it.
+ if (status === 'denied') {
+ return 'LU is not allowed to read that folder. The path is there; the account this app runs as has no access to it. Pick a folder your own account owns, or grant this app access to that one.'
+ }
if (status === 'unusable') {
return 'This path is not a folder LU can read.'
}
@@ -513,6 +525,13 @@ function CustomModelDirNote({ result }: { result: CustomModelDirResult }) {
</div>
)
}
+ if (result.status === 'denied') {
+ return (
+ <div className={`${cls} ${HINWEIS_TEXT.fehler}`}>
+ LU is not allowed to read that folder. The drive is connected and the path is right; the account this app runs as has no access to it. Pick a folder your own account owns, or grant this app access to that one.
+ </div>
+ )
+ }
if (result.status === 'unsupported') {
return (
<div className={`${cls} ${HINWEIS_TEXT.ruhig}`}>
@@ -524,8 +543,8 @@ function CustomModelDirNote({ result }: { result: CustomModelDirResult }) {
return (
<div className={`${cls} ${HINWEIS_TEXT.ruhig}`}>
{result.folders.length > 0
- ? <>Image and video: LU passes <code className="font-mono">{result.folders.join(', ')}</code> from this folder to ComfyUI. Takes effect the next time LU starts ComfyUI, and only for a ComfyUI that LU starts.</>
- : <>Image and video models in this folder stay invisible: ComfyUI lists only its own folders. Name the subfolders like ComfyUI does (<code className="font-mono">checkpoints</code>, <code className="font-mono">loras</code>, <code className="font-mono">vae</code>, …) and LU hands them over.</>}
+ ? <>Image and video: LU passes <code className="font-mono">{result.folders.join(', ')}</code> from this folder to ComfyUI. LU re-reads the subfolders every time it starts ComfyUI, so a subfolder you add later arrives with the next start. Only a ComfyUI that LU starts gets them.</>
+ : <>Image and video models in this folder stay invisible: ComfyUI lists only its own folders. Name the subfolders like ComfyUI does (<code className="font-mono">checkpoints</code>, <code className="font-mono">loras</code>, <code className="font-mono">vae</code>, …) and LU hands them over the next time it starts ComfyUI.</>}
</div>
)
}
@@ -748,6 +767,25 @@ export function ComfyUISettings() {
// stay reachable on `error` too, and the card carries a Dismiss.
const installIdle = installPhase === 'idle' || installPhase === 'error'
+ // Der Beobachter unten liest `running` und `stalled` von hier, statt eine
+ // zweite comfyui_status-Schleife aufzumachen: die Abfrage ist eine
+ // HTTP-Probe mit 3 s Frist, und sie raeumt nebenbei den Kindhandle ab.
+ //
+ // Ein Spiegel und nicht der Zustand selbst, weil der Beobachter zwischen
+ // zwei Renderdurchgaengen tickt: ein setState waere fuer ihn noch nicht da,
+ // und er wuerde auf einer Antwort arbeiten, die schon ueberholt ist.
+ // Geschrieben wird er an den zwei Stellen, die ueber diese beiden Felder
+ // entscheiden, dem Statuspoll und dem Stop-Knopf.
+ const statusNow = useRef<ComfyStatusResponse | null>(null)
+ // Zaehlt die Antworten des Backends, damit der Beobachter eine Antwort von
+ // NACH dem Startklick von der Aufnahme davor unterscheiden kann.
+ const statusTick = useRef(0)
+ // Die Generation des laufenden Startversuchs. Ein zweiter Klick, ein Stop
+ // und das Ummounten zaehlen sie hoch, und ein Beobachter mit einer alten
+ // Nummer sagt nichts mehr.
+ const startWatch = useRef(0)
+ useEffect(() => () => { startWatch.current += 1 }, [])
+
useEffect(() => {
let cancelled = false
const check = async () => {
@@ -755,6 +793,8 @@ export function ComfyUISettings() {
const { backendCall, setComfyPort, setComfyHost } = await import('../../api/backend')
const s = await backendCall<ComfyStatusResponse>('comfyui_status')
if (!cancelled) {
+ statusNow.current = s
+ statusTick.current += 1
setStatus(s)
// Mirror backend truth into the frontend URL builder so subsequent
// fetch() calls hit the right machine immediately, no restart needed.
@@ -775,30 +815,89 @@ export function ComfyUISettings() {
return () => { cancelled = true; clearInterval(interval) }
}, [])
+ /** Auf den Absturz warten, der nach dem Spawn kommt.
+ *
+ * P3: eine ComfyUI-Kopie mit fehlendem Modul starb beim Start, und in der
+ * Oberflaeche kam GAR KEINE Meldung. Rust schaut 2 s zu (process.rs), hier
+ * stand ein einziges setTimeout ueber 6 s, und ComfyUI importiert 20 bis 60
+ * Sekunden lang, bevor es den Port bindet. Wer dazwischen stirbt, ist zu
+ * spaet fuer beide, und danach fragt niemand mehr.
+ *
+ * Ein Fenster hochzudrehen haette das nur verschoben. Der Beobachter haengt
+ * jetzt am Startversuch statt an einem Augenblick und hoert auf, sobald
+ * einer dieser Punkte eintritt:
+ *
+ * - der Port antwortet (`running`): fertig, keine Meldung,
+ * - der Start haengt so lange, dass Rust ihn `stalled` nennt: die Zeile
+ * unter dem Status uebernimmt, und der Beobachter braucht kein eigenes
+ * Zeitbudget und damit keine zweite Zahl neben COMFY_STARTING_GRACE_SECS,
+ * - der Nutzer drueckt Stop oder noch einmal Start, oder das Panel geht:
+ * die Generation stimmt nicht mehr,
+ * - das Kind ist weg: melden.
+ *
+ * `exited` allein reicht nicht als Beweis: es ist auch wahr, wenn LU gar
+ * keinen Prozess haelt, also bei einem adoptierten Waisen und bei einem
+ * entfernten Host. Deshalb zaehlt nur eine Statusantwort, die NACH diesem
+ * Startklick eingetroffen ist. */
+ const watchForLateCrash = async (generation: number) => {
+ const { backendCall } = await import('../../api/backend')
+ const tickAtStart = statusTick.current
+ for (;;) {
+ await new Promise(resolve => setTimeout(resolve, 2000))
+ if (startWatch.current !== generation) return
+ // Noch keine frische Statusantwort: `exited` waere jetzt nur die
+ // Aufnahme von vor dem Start.
+ if (statusTick.current <= tickAtStart) continue
+ const s = statusNow.current
+ if (s?.running || s?.stalled) return
+ let out: ComfyLastOutput | null = null
+ try {
+ out = await backendCall<ComfyLastOutput>('comfyui_last_output')
+ } catch { continue }
+ if (startWatch.current !== generation) return
+ if (!out?.exited) continue
+ // Ticket 007: welcher Satz unter die Ausgabe gehoert, entscheidet
+ // comfyCrashAdvice fuer beide Oberflaechen. Vorher stand der
+ // allgemeine Satz hier fest verdrahtet, und der konkrete Hinweis
+ // aus dem Einordner des Installers erreichte den Kunden nie.
+ setStartError(comfyStartupError(COMFY_START_FAILED, out.lines, comfyCrashAdvice(out)))
+ return
+ }
+ }
+
const handleStart = async () => {
setStartError('')
+ // Die gruene Zeile eines beendeten Laufs ist keine Aussage mehr ueber das,
+ // was gerade passiert. Sie stand im Testbericht neben einem Start, der
+ // abgestuerzt war, und sagte weiter "ComfyUI is ready".
+ clearInstallNotice()
+ const generation = ++startWatch.current
try {
const { backendCall } = await import('../../api/backend')
await backendCall('start_comfyui')
setStatus(prev => prev ? { ...prev, starting: true } : null)
- // GH #98 (joelnewswanger): a crash AFTER the 2s spawn watch used to flip
- // the panel silently back to Stopped, which read as "the start button
- // does nothing". Look once, a few seconds in, and say what happened.
- setTimeout(async () => {
- try {
- const out = await backendCall<ComfyLastOutput>('comfyui_last_output')
- if (out?.exited && Array.isArray(out?.lines) && out.lines.length > 1) {
- // Ticket 007: welcher Satz unter die Ausgabe gehoert, entscheidet
- // comfyCrashAdvice fuer beide Oberflaechen. Vorher stand der
- // allgemeine Satz hier fest verdrahtet, und der konkrete Hinweis
- // aus dem Einordner des Installers erreichte den Kunden nie.
- const { comfyStartupError, comfyCrashAdvice } = await import('../create/experimental/comfyError')
- setStartError(comfyStartupError(out.lines, comfyCrashAdvice(out)))
- }
- } catch { /* status polling keeps the panel honest */ }
- }, 6000)
+ void watchForLateCrash(generation)
} catch (err) {
- setStartError(err instanceof Error ? err.message : String(err))
+ // Hier braucht es keine neue Generation: die Nummer ist eine Zeile
+ // weiter oben schon gestiegen, also ist ein Beobachter aus einem
+ // frueheren Versuch bereits abgeloest, und fuer diesen hier wurde nie
+ // einer gestartet.
+ const message = err instanceof Error ? err.message : String(err)
+ // P3, 7.2: ein Absturz binnen der zwei Sekunden, die Rust zuschaut, wirft
+ // hier heraus. Ein Wurf plant keinen Beobachter, also erreichte der Satz
+ // ueber die Visual-C++-Laufzeit den Kunden nur, wenn ComfyUI eine Sekunde
+ // laenger durchgehalten hatte. Derselbe Einordner, dieselbe Route, eine
+ // Zeile spaeter.
+ let out: ComfyLastOutput | null = null
+ try {
+ const { backendCall } = await import('../../api/backend')
+ out = await backendCall<ComfyLastOutput>('comfyui_last_output')
+ } catch {
+ // Ohne die Ausgabe bleibt es bei dem, was der Wurf selbst sagt. Das
+ // ist die Meldung aus `comfy_startup_failure` und die traegt den
+ // Traceback bereits.
+ }
+ setStartError(comfyStartThrowText(message, out))
}
}
@@ -819,9 +918,15 @@ export function ComfyUISettings() {
const handleStop = async () => {
setStartError('')
+ // Ohne diese Zeile erfindet der Restart-Knopf einen Absturz: nach einem
+ // Stop haelt LU keinen Prozess mehr, comfyui_last_output antwortet
+ // `exited: true` mit den Zeilen des vorigen Laufs, und der Ringpuffer wird
+ // erst beim naechsten Start geleert.
+ startWatch.current += 1
try {
const { backendCall } = await import('../../api/backend')
await backendCall('stop_comfyui')
+ statusNow.current = statusNow.current ? { ...statusNow.current, running: false } : null
setStatus(prev => prev ? { ...prev, running: false } : null)
} catch (e) {
// Level (c): a stop that failed leaves the panel showing "running", which
@@ -835,6 +940,9 @@ export function ComfyUISettings() {
if (!customPath.trim()) return
setPathError('')
setPathSuccess(false)
+ // Die Zeile nennt einen Ordner. Nach dem Wechsel redet sie ueber eine
+ // andere Installation als die, die im Feld steht.
+ clearInstallNotice()
try {
const { backendCall } = await import('../../api/backend')
await backendCall('set_comfyui_path', { path: customPath.trim() })
diff --git a/src/components/settings/__tests__/comfy-notice-reads-as-what-it-is.test.ts b/src/components/settings/__tests__/comfy-notice-reads-as-what-it-is.test.ts
index 07a75dd2..c9ccbd8f 100644
--- a/src/components/settings/__tests__/comfy-notice-reads-as-what-it-is.test.ts
+++ b/src/components/settings/__tests__/comfy-notice-reads-as-what-it-is.test.ts
@@ -113,6 +113,38 @@ describe('the closing line can be dismissed', () => {
expect(useComfyInstallStore.getState().notice).toBe('')
})
+ // P3: im Testbericht stand die gruene Zeile "Repair finished. ComfyUI is
+ // ready." neben einem Start, der gerade abgestuerzt war. Sie beschreibt
+ // einen beendeten Installerlauf und haengt an nichts, was mit einem
+ // ComfyUI-Start zu tun haette, also hat sie jeden Startversuch und jeden
+ // Ordnerwechsel ueberlebt.
+ it('a new start puts the line away, it is not about this attempt', async () => {
+ await panelShowing('Repair finished. ComfyUI is ready.', 'ok')
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Start' })) })
+ expect(screen.queryByTestId('comfy-install-notice')).toBeNull()
+ expect(useComfyInstallStore.getState().notice).toBe('')
+ })
+
+ it('so does pointing the panel at another folder', async () => {
+ await panelShowing('Repair finished. ComfyUI is ready.', 'ok')
+ const feld = screen.getByPlaceholderText('C:\\ComfyUI')
+ await act(async () => { fireEvent.change(feld, { target: { value: 'D:\\Andere\\ComfyUI' } }) })
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Connect' })) })
+ expect(useComfyInstallStore.getState().notice).toBe('')
+ })
+
+ it('but leaving the section and coming back does not', async () => {
+ // Gegengewicht zu den beiden darueber, und der ganze Zweck von A13 und
+ // A15: der Lauf wohnt im Store, damit ein Wechsel des
+ // Einstellungsbereichs nichts wegwirft. Wer die Zeile beim Ummounten
+ // raeumt, hat den alten Fehler zurueck.
+ await panelShowing('Repair finished. ComfyUI is ready.', 'ok')
+ cleanup()
+ render(createElement(ComfyUISettings))
+ await act(async () => { await Promise.resolve(); await Promise.resolve() })
+ expect(screen.getByTestId('comfy-install-notice').textContent).toBe('Repair finished. ComfyUI is ready.')
+ })
+
it('shows no dismiss control when there is nothing to dismiss', async () => {
// Negative control: an idle panel with no line carries no stray button.
render(createElement(ComfyUISettings))
diff --git a/src/components/settings/__tests__/ein-spaeter-absturz-wird-noch-gemeldet.test.ts b/src/components/settings/__tests__/ein-spaeter-absturz-wird-noch-gemeldet.test.ts
new file mode 100644
index 00000000..97ea806f
--- /dev/null
+++ b/src/components/settings/__tests__/ein-spaeter-absturz-wird-noch-gemeldet.test.ts
@@ -0,0 +1,207 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * P3, zweiter Teil des Befundes: eine ComfyUI-Kopie mit einem fehlenden Modul
+ * stuerzte beim Start ab, und in der Oberflaeche kam GAR KEINE Meldung. Der
+ * Grund waren zwei geschlossene Tore. Rust schaut nach dem Spawn 2 Sekunden zu,
+ * und hier stand ein einziges setTimeout ueber 6 Sekunden. ComfyUI importiert
+ * 20 bis 60 Sekunden, bevor es den Port bindet, also ist ein Absturz beim
+ * Import fuer beide zu spaet, und danach hat nie wieder jemand hingesehen.
+ *
+ * Diese Datei prueft nicht, ob eine Zeichenkette im Quelltext vorkommt. Sie
+ * stellt die Uhr.
+ *
+ * Der Takt, gegen den die Zeiten hier gerechnet sind: der Statuspoll des
+ * Panels laeuft ab dem Mounten alle 5 s, der Beobachter ab dem Startklick alle
+ * 2 s. Geklickt wird bei Sekunde 1, damit die beiden nicht auf demselben
+ * Zeitpunkt liegen.
+ *
+ * Run: npx vitest run src/components/settings/__tests__/ein-spaeter-absturz-wird-noch-gemeldet.test.ts
+ */
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { createElement } from 'react'
+import { render, screen, fireEvent, cleanup, act } from '@testing-library/react'
+
+const backendCall = vi.fn()
+vi.mock('../../../api/backend', () => ({
+ backendCall: (...args: unknown[]) => backendCall(...args),
+ isTauri: () => true,
+ isMacOS: () => false,
+ openExternal: vi.fn(),
+ secretGet: vi.fn().mockRejectedValue(new Error('no keychain here')),
+ secretSet: vi.fn(),
+ secretDelete: vi.fn(),
+ setComfyPort: vi.fn(),
+ setComfyHost: vi.fn(),
+}))
+
+const { ComfyUISettings } = await import('../SettingsPage')
+const { useComfyInstallStore } = await import('../../../stores/comfyInstallStore')
+
+const TRACEBACK = "ModuleNotFoundError: No module named 'comfy.ldm.models'"
+
+/** Die Ausgabe eines Starts, der noch importiert. Der Ringpuffer traegt immer
+ * die Kopfzeile, deshalb war "mehr als eine Zeile" nie ein Beweis. */
+const IMPORTING = { exited: false, lines: ['[start] python main.py --port 8188'], envBroken: false, hint: '' }
+const CRASHED = {
+ exited: true,
+ lines: ['[start] python main.py --port 8188', TRACEBACK],
+ envBroken: true,
+ hint: '',
+}
+
+/** Ab wann `comfyui_last_output` `exited` meldet. Unter falschen Uhren zieht
+ * `vi.advanceTimersByTimeAsync` auch `Date.now()` mit. */
+let exitedAb = Number.POSITIVE_INFINITY
+/** Was `comfyui_status` gerade antwortet. */
+let laeuft = false
+/** Womit `start_comfyui` wirft, wenn das Kind schon vor der Antwort tot war. */
+let startWirft: string | null = null
+/** Der Befund des Installers zu diesem Absturz, den Rust mitliefert. */
+let hinweis = ''
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ useComfyInstallStore.getState().reset()
+ exitedAb = Number.POSITIVE_INFINITY
+ laeuft = false
+ startWirft = null
+ hinweis = ''
+ backendCall.mockReset()
+ backendCall.mockImplementation(async (cmd: string) => {
+ if (cmd === 'comfyui_status') {
+ return { running: laeuft, found: true, complete: true, path: 'C:\\ComfyUI', isLocal: true }
+ }
+ if (cmd === 'start_comfyui' && startWirft) throw new Error(startWirft)
+ if (cmd === 'comfyui_last_output') {
+ return Date.now() >= exitedAb ? { ...CRASHED, hint: hinweis } : IMPORTING
+ }
+ if (cmd === 'install_comfyui_status') return { status: 'idle', logs: [] }
+ return {}
+ })
+})
+afterEach(() => {
+ cleanup()
+ useComfyInstallStore.getState().reset()
+ vi.useRealTimers()
+})
+
+async function uhrVor(ms: number) {
+ await act(async () => { await vi.advanceTimersByTimeAsync(ms) })
+}
+
+/** Panel mounten und bei Sekunde 1 auf Start druecken. */
+async function startGedruecktBeiSekundeEins() {
+ render(createElement(ComfyUISettings))
+ await uhrVor(1_000)
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Start' })) })
+}
+
+describe('ein Absturz nach dem Startfenster erreicht die Oberflaeche', () => {
+ it('meldet einen Absturz nach zehn Sekunden, und vorher nichts', async () => {
+ render(createElement(ComfyUISettings))
+ await uhrVor(1_000)
+ exitedAb = Date.now() + 10_000
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Start' })) })
+
+ // Der alte Blick sass genau hier, 6 Sekunden nach dem Klick. Zu diesem
+ // Zeitpunkt importiert das Kind noch, `exited` ist falsch, und es gibt
+ // nichts zu melden. Ein Fix, der die 6 Sekunden bloss hochdreht, kommt an
+ // dieser Haelfte des Tests vorbei.
+ await uhrVor(6_000)
+ expect(screen.queryByRole('alert')).toBeNull()
+
+ // Und dann stirbt es. Vorher hat das niemand mehr gesehen: das Panel fiel
+ // still auf Stopped zurueck und der Traceback blieb im Ringpuffer liegen.
+ await uhrVor(14_000)
+ const alarm = screen.getByRole('alert')
+ expect(alarm.textContent).toContain(TRACEBACK)
+ // Der Anfang gehoert dem Startknopf, nicht dem Installationsweg: hier hat
+ // niemand etwas installiert.
+ expect(alarm.textContent).not.toContain('Installed ComfyUI')
+ })
+
+ it('ein Start, der hochkommt, meldet nie einen Absturz', async () => {
+ // Der adoptierte Waise: LU haelt keinen Prozess, also ist `exited` wahr,
+ // obwohl auf dem Port ein einwandfreies ComfyUI antwortet. Ohne die
+ // Statusfrage vor der Meldung faerbt das Panel hier rot. Und ohne diesen
+ // Test ist der Test darueber auch mit "melde immer" zufrieden.
+ exitedAb = 0
+ await startGedruecktBeiSekundeEins()
+ laeuft = true
+
+ await uhrVor(60_000)
+ expect(screen.queryByRole('alert')).toBeNull()
+ })
+
+ it('ein Stop erfindet keinen Absturz aus der Ausgabe des vorigen Laufs', async () => {
+ // Nach einem Stop haelt LU keinen Prozess mehr, `exited` ist wahr, und der
+ // Ringpuffer traegt noch die Zeilen des Laufs, der gerade beendet wurde
+ // (geleert wird er erst beim naechsten Start). Ein Beobachter, den der
+ // Stop nicht abloest, meldet die als frischen Absturz. Der Restart-Knopf
+ // loest genau diese Reihenfolge bei jedem Klick aus.
+ // Das Zeitfenster ist genau ausgemessen, sonst prueft der Test nichts: der
+ // Beobachter hoert von selbst auf, sobald er running sieht. Hier importiert
+ // ComfyUI bis Sekunde 9,5, die Statusantwort bei Sekunde 10 bringt den
+ // Stop-Knopf, und der naechste Tick des Beobachters kommt bei Sekunde 11.
+ // Dazwischen wird geklickt, und genau das tut auch der Restart-Knopf.
+ await startGedruecktBeiSekundeEins()
+ await uhrVor(8_500)
+ laeuft = true
+ await uhrVor(1_000)
+
+ exitedAb = 0
+ laeuft = false
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Stop' })) })
+
+ await uhrVor(20_000)
+ expect(screen.queryByRole('alert')).toBeNull()
+ })
+
+ /**
+ * P3, 7.2: ein umbenanntes c10.dll toetet torch beim ersten Import, also weit
+ * innerhalb der zwei Sekunden, die Rust dem Start zuschaut. Dieser Weg wirft,
+ * und ein Wurf plant keinen Beobachter, also erreichte der Kunde nur
+ * "exited right after starting" plus Traceback. Der Satz ueber die
+ * Visual-C++-Laufzeit lag die ganze Zeit im Einordner des Installers, und wer
+ * eine Sekunde spaeter starb, bekam ihn.
+ */
+ it('ein Absturz binnen der zwei Sekunden nennt die Laufzeit, die fehlt', async () => {
+ startWirft = [
+ 'ComfyUI exited right after starting (python=C:\\ComfyUI\\venv\\Scripts\\python.exe, exit code 1).',
+ '',
+ 'Last output:',
+ 'OSError: [WinError 1114] a DLL initialization routine failed. Error loading "c10.dll"',
+ ].join('\n')
+ exitedAb = 0
+ hinweis =
+ 'A Microsoft Visual C++ runtime library is missing on this machine: VCOMP140.DLL. ' +
+ 'Repair environment does not help here, it is not inside the venv.'
+
+ await startGedruecktBeiSekundeEins()
+ await uhrVor(0)
+
+ const alarm = screen.getByRole('alert')
+ // Was der Wurf selbst schon sagte, steht weiter da.
+ expect(alarm.textContent).toContain('exit code 1')
+ expect(alarm.textContent).toContain('[WinError 1114]')
+ // Und der Satz, der bisher nur den spaeten Abstuerzen vorbehalten war.
+ expect(alarm.textContent).toContain('Visual C++')
+ expect(alarm.textContent).toContain('Repair environment does not help here')
+ })
+
+ it('und erfindet keinen Rat, wo der Einordner keinen hat', async () => {
+ // Die Gegenprobe: ohne sie haengt der Hinweis unter jedem Wurf, und dann
+ // sagt der Test darueber nichts mehr aus.
+ startWirft = 'Failed to start ComfyUI (python=python): the file was not found (os error 2)'
+ exitedAb = Number.POSITIVE_INFINITY
+
+ await startGedruecktBeiSekundeEins()
+ await uhrVor(0)
+
+ const alarm = screen.getByRole('alert')
+ expect(alarm.textContent).toContain('Failed to start ComfyUI')
+ expect(alarm.textContent).not.toContain('Visual C++')
+ expect(alarm.textContent).not.toContain('Repair environment')
+ })
+})
diff --git a/src/components/settings/__tests__/model-dir-scan-note.test.ts b/src/components/settings/__tests__/model-dir-scan-note.test.ts
index aa04115a..0ac9707d 100644
--- a/src/components/settings/__tests__/model-dir-scan-note.test.ts
+++ b/src/components/settings/__tests__/model-dir-scan-note.test.ts
@@ -74,6 +74,16 @@ describe('the sentence for each verdict', () => {
)
})
+ // P3, 7.4: ein Ordner ohne Leserecht bekam den Satz vom abgezogenen
+ // Laufwerk. Beides war falsch, und der Nutzer sucht danach an der falschen
+ // Stelle.
+ it('names the missing right instead of blaming the drive', () => {
+ const satz = modelDirScanNote('denied')
+ expect(satz).toContain('not allowed to read that folder')
+ expect(satz).not.toContain('drive disconnected')
+ expect(satz).not.toContain('path missing')
+ })
+
it('says a path that is no folder is no folder', () => {
expect(modelDirScanNote('unusable')).toBe('This path is not a folder LU can read.')
})
@@ -109,6 +119,13 @@ describe('Model Storage shows it under the path', () => {
expect(screen.queryByText(/Check that the drive is connected/)).toBeNull()
})
+ it('says one line about a folder without read rights, not two', async () => {
+ expect(await noteFor('denied')).toContain('not allowed to read that folder')
+ // Dieselbe Wache wie eine Zeile hoeher: ein vergessenes scanHidesHandoff
+ // stellt zwei Warnungen ueber denselben Ordner uebereinander.
+ expect(screen.queryByText(/passes/)).toBeNull()
+ })
+
it('says nothing twice about a path that is no folder either', async () => {
await noteFor('unusable')
expect(screen.queryByText(/That is not a full path/)).toBeNull()
diff --git a/src/lib/__tests__/custom-model-dir-comfy.test.ts b/src/lib/__tests__/custom-model-dir-comfy.test.ts
index fe634fab..81848672 100644
--- a/src/lib/__tests__/custom-model-dir-comfy.test.ts
+++ b/src/lib/__tests__/custom-model-dir-comfy.test.ts
@@ -80,12 +80,23 @@ describe('the Model Storage copy tells the truth', () => {
it('is honest that image and video go through ComfyUI', () => {
expect(src).toMatch(/passes <code className="font-mono">\{result\.folders\.join/)
- expect(src).toMatch(/only for a ComfyUI that LU starts/)
+ expect(src).toMatch(/Only a ComfyUI that LU starts gets them/)
+ // P3: the folder is scanned again on every ComfyUI start, so the copy is
+ // allowed to promise the next start. It was not before: the file was
+ // written when the setting changed and never again, and a subfolder
+ // created afterwards never reached ComfyUI at all.
+ expect(src).toMatch(/re-reads the subfolders every time it starts ComfyUI/)
// And says plainly what happens when the folder is not ComfyUI-shaped,
// instead of leaving a silent no-op behind.
expect(src).toMatch(/stay invisible/)
})
+ // Negative control, and the load-bearing half of the one above: without it
+ // the true sentence could sit next to the false one and both would pass.
+ it('no longer says the setting alone takes effect on the next start', () => {
+ expect(src).not.toMatch(/Takes effect the next time LU starts ComfyUI/)
+ })
+
it('does not promise ComfyUI on a host that never starts one', () => {
// The Mac runs local media on MLX. The promise used to render there too.
expect(src).toMatch(/result\.status === 'unsupported'/)
diff --git a/src/lib/__tests__/der-kopf-nennt-beide-antworten.test.ts b/src/lib/__tests__/der-kopf-nennt-beide-antworten.test.ts
new file mode 100644
index 00000000..f6c02731
--- /dev/null
+++ b/src/lib/__tests__/der-kopf-nennt-beide-antworten.test.ts
@@ -0,0 +1,62 @@
+/**
+ * Der Kopf einer Datei darf nicht etwas anderes sagen als die Datei.
+ *
+ * src/lib/local-backend-transport.ts trug bis zur Nachlese den Kopf aus der
+ * Runde davor: "One reading of 'the local backend did not answer', shared by
+ * everyone who talks to a server on this machine or on the LAN." In derselben
+ * Datei steht seit derselben Runde `remoteBackendUnreachableMessage`, deren
+ * eigener Block mit "The same answer for a backend that is NOT on this machine
+ * or the LAN" anfaengt. Wer den Kopf liest und danach eine Antwort fuer einen
+ * fremden Host sucht, sucht sie woanders, weil der Kopf ihm gesagt hat, hier
+ * gebe es sie nicht.
+ *
+ * Der Test haelt den Kopf gegen das, was die Datei wirklich anbietet.
+ *
+ * Run: npx vitest run src/lib/__tests__/der-kopf-nennt-beide-antworten.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+
+const datei = resolve(__dirname, '..', 'local-backend-transport.ts')
+const quelle = readFileSync(datei, 'utf8')
+
+/** Der Modulkopf, als fortlaufender Satz statt als Sternchenspalte. */
+const kopf = quelle
+ .slice(0, quelle.indexOf('*/'))
+ .split('\n')
+ .map((z) => z.replace(/^\s*\/?\*+/, '').trim())
+ .join(' ')
+ .replace(/\s+/g, ' ')
+
+describe('der Kopf von local-backend-transport.ts', () => {
+ it('die Datei gibt wirklich zwei Antworten, eine nahe und eine ferne', () => {
+ expect(quelle).toContain('export function localBackendUnreachableMessage')
+ expect(quelle).toContain('export function remoteBackendUnreachableMessage')
+ })
+
+ it('und der Kopf nennt beide', () => {
+ expect(kopf).toContain('localBackendUnreachableMessage')
+ expect(kopf).toContain('remoteBackendUnreachableMessage')
+ })
+
+ it('er sperrt die Datei nicht mehr auf diese Maschine und das LAN ein', () => {
+ // Genau der Satz, der dort stand. Er beschreibt die Datei von vor der
+ // letzten Runde.
+ expect(kopf).not.toContain('talks to a server on this machine or on the LAN')
+ })
+
+ it('die ferne Antwort schickt niemanden zu einem Server, den er nicht betreibt', () => {
+ // Die Gegenprobe zur Aussage des Kopfes: die beiden Saetze sind wirklich
+ // verschieden, sonst waere die ganze Unterscheidung Schmuck.
+ const fern = quelle.slice(quelle.indexOf('export function remoteBackendUnreachableMessage'))
+ expect(fern).not.toContain('Start it and send again')
+ expect(fern).toContain('check your network')
+ const nah = quelle.slice(
+ quelle.indexOf('export function localBackendUnreachableMessage'),
+ quelle.indexOf('export function remoteBackendUnreachableMessage'),
+ )
+ expect(nah).toContain('Start it and send again')
+ expect(nah).not.toContain('check your network')
+ })
+})
diff --git a/src/lib/__tests__/die-liste-folgt-dem-halter-des-steckplatzes.test.ts b/src/lib/__tests__/die-liste-folgt-dem-halter-des-steckplatzes.test.ts
new file mode 100644
index 00000000..efd4cac2
--- /dev/null
+++ b/src/lib/__tests__/die-liste-folgt-dem-halter-des-steckplatzes.test.ts
@@ -0,0 +1,109 @@
+/**
+ * Wechselt der Halter des geteilten Steckplatzes, muss die Modelliste neu
+ * geholt werden.
+ *
+ * Die Regel dafuer stand wortgleich zweimal im Baum, in
+ * components/models/ModelSelector.tsx und in components/layout/Header.tsx,
+ * und beide Fassungen verglichen nur `enabled` und `baseUrl`. `useModels`
+ * haengt die QUELLE der ganzen Liste aber an `managed`: haelt unsere eigene
+ * Engine den `openai`-Steckplatz, kommen die Zeilen aus
+ * `list_bundled_models`, der Steckplatz faellt aus der Provider-Runde heraus,
+ * und die Zeilen des verdraengten Backends bekommen eine eigene Ueberschrift.
+ * Ein Schreiben, das nur den Halter dreht, schrieb die Liste also am
+ * staerksten um und loeste als Einziges kein Nachladen aus.
+ *
+ * Run: npx vitest run src/lib/__tests__/die-liste-folgt-dem-halter-des-steckplatzes.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import { modelListIsStale } from '../model-list-staleness'
+import type { ProviderConfig, ProviderId } from '../../api/providers/types'
+
+const lies = (p: string) => readFileSync(resolve(__dirname, '..', '..', p), 'utf8')
+
+function slot(over: Partial<ProviderConfig> = {}): ProviderConfig {
+ return {
+ id: 'openai', name: 'LU Engine', enabled: true,
+ baseUrl: 'http://127.0.0.1:8127/v1', apiKey: '', isLocal: true, managed: true,
+ ...over,
+ }
+}
+
+/** Die vier Steckplaetze, so wie der Store sie haelt. */
+function alle(openai: ProviderConfig): Record<ProviderId, ProviderConfig> {
+ return {
+ ollama: slot({ id: 'ollama', name: 'Ollama', baseUrl: 'http://localhost:11434', managed: undefined }),
+ openai,
+ anthropic: slot({ id: 'anthropic', name: 'Anthropic', enabled: false, isLocal: false, managed: undefined }),
+ 'lu-cloud': slot({ id: 'lu-cloud', name: 'LU Cloud', enabled: false, isLocal: false, managed: undefined }),
+ }
+}
+
+const ENGINE = slot()
+/** Was `slotHandbackUpdate` schreibt: derselbe Steckplatz, anderer Halter. */
+const LM_STUDIO = slot({ name: 'LM Studio', baseUrl: 'http://localhost:1234/v1', managed: false })
+
+describe('DER BEFUND: der Halterwechsel laedt jetzt nach', () => {
+ it('nur `managed` gedreht, und die Liste ist eine andere', () => {
+ expect(modelListIsStale(alle(slot({ managed: false })), alle(ENGINE))).toBe(true)
+ })
+
+ it('nur der Anzeigename gedreht, und die Ueberschriften stimmen nicht mehr', () => {
+ expect(modelListIsStale(alle(slot({ name: 'Jan' })), alle(ENGINE))).toBe(true)
+ })
+
+ it('die Uebergabe, wie sie wirklich geschrieben wird', () => {
+ expect(modelListIsStale(alle(LM_STUDIO), alle(ENGINE))).toBe(true)
+ expect(modelListIsStale(alle(ENGINE), alle(LM_STUDIO))).toBe(true)
+ })
+
+ it('und die beiden alten Felder zaehlen unveraendert', () => {
+ expect(modelListIsStale(alle(slot({ enabled: false })), alle(ENGINE))).toBe(true)
+ expect(modelListIsStale(alle(slot({ baseUrl: 'http://127.0.0.1:9999/v1' })), alle(ENGINE))).toBe(true)
+ })
+})
+
+describe('NEGATIVKONTROLLE: was die Liste in Ruhe laesst', () => {
+ it('ein unveraenderter Store laedt nichts nach', () => {
+ expect(modelListIsStale(alle(ENGINE), alle(ENGINE))).toBe(false)
+ })
+
+ it('ein getippter Schluessel nicht, sonst eine Anfrage pro Buchstabe', () => {
+ const mit = alle(ENGINE)
+ mit.anthropic = { ...mit.anthropic, apiKey: 'sk-ant-abc' }
+ expect(modelListIsStale(mit, alle(ENGINE))).toBe(false)
+ })
+
+ it('und die Standby-Karte allein auch nicht, sie listet nichts', () => {
+ // `displaced` merkt sich, wer verdraengt wurde. Gelistet wird das Wartende
+ // ueber den Steckplatz selbst, nicht ueber dieses Feld.
+ const mit = alle(slot({ displaced: { name: 'LM Studio', baseUrl: 'http://localhost:1234/v1', isLocal: true } }))
+ expect(modelListIsStale(mit, alle(ENGINE))).toBe(false)
+ })
+})
+
+describe('die Regel steht an EINER Stelle', () => {
+ const waehler = lies('components/models/ModelSelector.tsx')
+ const kopfleiste = lies('components/layout/Header.tsx')
+
+ it('beide Tueren fragen dieselbe Stelle', () => {
+ for (const datei of [waehler, kopfleiste]) {
+ expect(datei).toContain("from '../../lib/model-list-staleness'")
+ expect(datei).toContain('modelListIsStale(state.providers, prev.providers)')
+ }
+ })
+
+ it('und keine von beiden traegt die abgeschriebene Fassung noch', () => {
+ for (const datei of [waehler, kopfleiste]) {
+ expect(datei).not.toContain('?.enabled !== prev.providers[id]?.enabled')
+ expect(datei).not.toContain('?.baseUrl !== prev.providers[id]?.baseUrl')
+ }
+ })
+
+ it('der Grund, warum `managed` dazugehoert, steht noch in useModels', () => {
+ const models = lies('hooks/useModels.ts')
+ expect(models).toContain('const managedBuiltin = isManagedBuiltinActive()')
+ expect(models).toContain('const standby = managedBuiltin ? standbyChatBackend() : null')
+ })
+})
diff --git a/src/lib/__tests__/die-verdraengte-wahl-wird-angesagt.test.ts b/src/lib/__tests__/die-verdraengte-wahl-wird-angesagt.test.ts
new file mode 100644
index 00000000..69f1e3d6
--- /dev/null
+++ b/src/lib/__tests__/die-verdraengte-wahl-wird-angesagt.test.ts
@@ -0,0 +1,214 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * Faellt die Wahl mit dem Steckplatz, muss jemand es sagen.
+ *
+ * Die letzte Runde hat `dropDisplacedEnginePick` gebaut: uebernimmt ein
+ * fremdes Backend den geteilten lokalen Steckplatz, wird die Wahl geraeumt,
+ * weil auf 8127 nichts mehr liegt. Danach ist `activeModel` null. Und genau
+ * das schaltet die einzige Stelle ab, die so etwas sonst ansagt:
+ * `replacedBehindTheUsersBack` (lib/active-model-mode) verlangt einen
+ * vorherigen Namen, und den gibt es nach dem Raeumen nicht mehr. Der Nutzer
+ * druckt in den Einstellungen Enable auf der Standby-Karte, sieht seinen Chip
+ * von einem GGUF auf "Select Model" springen und liest kein Wort dazu.
+ *
+ * Gesagt wird es deshalb dort, wo der alte Name noch dasteht: im selben Zug
+ * wie das Raeumen. Und NUR dort, wo der Nutzer den Wechsel nicht selbst
+ * ausgeloest hat: wer im Waehler eine Zeile des wartenden Backends anklickt,
+ * liest die Wechselzeile ueber genau diesen Vorgang schon, und ein zweiter
+ * Satz wuerde sie loeschen statt ergaenzen.
+ *
+ * Run: npx vitest run src/lib/__tests__/die-verdraengte-wahl-wird-angesagt.test.ts
+ */
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+
+const backendCall = vi.fn(async (..._args: unknown[]) => ({}))
+vi.mock('../../api/backend', () => ({
+ backendCall: (...a: unknown[]) => backendCall(...a),
+ isTauri: () => true,
+ isMacOS: () => false,
+ isWindows: () => true,
+ isLinux: () => false,
+ secretGet: vi.fn().mockRejectedValue(new Error('no vault')),
+ secretSet: vi.fn(),
+ secretDelete: vi.fn(),
+}))
+
+const { __resetBuiltinSlotOffloadForTests } = await import('../builtin-slot-eviction')
+const { slotHandbackUpdate } = await import('../openai-slot-handover')
+const { pickForMode, replacedBehindTheUsersBack } = await import('../active-model-mode')
+const {
+ handBackChatProviderForRow, handbackAwaitsTheUsersPick,
+ announceChatProviderSwitch, chatProviderSwitchNote, CHAT_PROVIDER_SWITCH_HOLD_MS,
+} = await import('../../api/lu-engine-switch')
+const { useModelStore } = await import('../../stores/modelStore')
+const { useProviderStore } = await import('../../stores/providerStore')
+const { useLuEngineSwitchStore } = await import('../../stores/luEngineSwitchStore')
+
+const LU_ROW = 'openai::Qwen3-4B-Q4_K_M'
+const LMS_ROW = 'openai::qwen2.5-0.5b-instruct@q4_k_m'
+const OLLAMA_ROW = 'llama3:8b'
+const LMS_URL = 'http://localhost:1234/v1'
+
+const ROWS = [
+ { name: LU_ROW, model: 'Qwen3-4B-Q4_K_M', size: 2_300_000_000, type: 'text', provider: 'openai', providerName: 'LU Engine' },
+ { name: LMS_ROW, model: 'qwen2.5-0.5b-instruct@q4_k_m', size: 0, type: 'text', provider: 'openai', providerName: 'LM Studio' },
+ { name: OLLAMA_ROW, model: OLLAMA_ROW, size: 0, type: 'text', provider: 'ollama', providerName: 'Ollama' },
+]
+
+/** Der Steckplatz nach einem Wechsel zur LU Engine: unsere Engine drin, LM
+ * Studio auf der Standby-Karte. */
+function luEngineImSteckplatz(): void {
+ useProviderStore.getState().setProviderConfig('openai', {
+ enabled: true, managed: true, name: 'LU Engine', baseUrl: 'http://127.0.0.1:8127/v1',
+ isLocal: true, displaced: { name: 'LM Studio', baseUrl: LMS_URL, isLocal: true },
+ })
+}
+
+/** Genau der Druck auf Enable der Standby-Karte (ProviderConfig.tsx). */
+function enableAufDerStandbyKarte(): void {
+ const update = slotHandbackUpdate(useProviderStore.getState().providers.openai)
+ useProviderStore.getState().setProviderConfig('openai', update!)
+}
+
+/** Mikrotasks durchlassen: Raeumung und Ansage haengen an dynamischen
+ * Importen. */
+async function durchlassen(): Promise<void> {
+ for (let i = 0; i < 4; i++) await vi.advanceTimersByTimeAsync(0)
+}
+
+const zeile = () => useLuEngineSwitchStore.getState().note
+
+beforeEach(async () => {
+ vi.useFakeTimers()
+ // Eine gemerkte Klick-Rueckgabe aus einem vorigen Fall verjaehren lassen,
+ // sonst schweigt der naechste zu Unrecht.
+ await vi.advanceTimersByTimeAsync(CHAT_PROVIDER_SWITCH_HOLD_MS + 1)
+ handbackAwaitsTheUsersPick()
+ backendCall.mockClear()
+ __resetBuiltinSlotOffloadForTests()
+ useLuEngineSwitchStore.getState().dismiss()
+ useModelStore.setState({ activeModel: null })
+ useProviderStore.getState().resetProvidersToDefaults()
+ await durchlassen()
+ useModelStore.setState({ models: ROWS as never, activeModel: null })
+ __resetBuiltinSlotOffloadForTests()
+ useLuEngineSwitchStore.getState().dismiss()
+ backendCall.mockClear()
+})
+afterEach(() => {
+ __resetBuiltinSlotOffloadForTests()
+ vi.useRealTimers()
+})
+
+describe('DER BEFUND: Enable auf der Standby-Karte sagt jetzt etwas', () => {
+ it('die geraeumte Wahl bekommt eine Zeile, mit beiden Namen', async () => {
+ luEngineImSteckplatz()
+ await durchlassen()
+ useModelStore.setState({ activeModel: LU_ROW })
+
+ enableAufDerStandbyKarte()
+ await durchlassen()
+
+ expect(useModelStore.getState().activeModel).toBeNull()
+ const satz = zeile()
+ expect(satz, 'kein Wort zum gewechselten Chip').not.toBeNull()
+ expect(satz).toContain('Qwen3-4B-Q4_K_M')
+ expect(satz).toContain('LM Studio')
+ expect(useLuEngineSwitchStore.getState().tone).toBe('info')
+ })
+
+ it('und die Zeile stimmt sofort, gehalten wird nur auf den Leser', async () => {
+ luEngineImSteckplatz()
+ await durchlassen()
+ useModelStore.setState({ activeModel: LU_ROW })
+
+ enableAufDerStandbyKarte()
+ await durchlassen()
+
+ // Wahr, sobald sie dasteht: der Steckplatz ist umgehaengt und die Wahl
+ // gefallen, BEVOR der Satz geschrieben wird. Gehalten wird sie trotzdem,
+ // aber nur, solange keine Seite offen ist, die sie zeichnet
+ // (die-zeile-wartet-auf-ihren-leser.test.ts).
+ expect(useProviderStore.getState().providers.openai.managed).toBe(false)
+ expect(useModelStore.getState().activeModel).toBeNull()
+ expect(zeile()).not.toBeNull()
+ })
+
+ it('warum die Modusregel das nicht auffangen kann', () => {
+ // Nach dem Raeumen ist der alte Name weg. Die Regel in AppShell hat
+ // nichts mehr zu nennen und schweigt zu Recht.
+ const pick = pickForMode(null, [{ name: LMS_ROW, provider: 'openai' }], 'local')
+ expect(pick.change).toBe(true)
+ expect(replacedBehindTheUsersBack(null, pick, false)).toBe(false)
+ })
+})
+
+describe('NEGATIVKONTROLLE: wer den Wechsel selbst ausgeloest hat, liest nichts Neues', () => {
+ it('der Klick im Waehler behaelt seine eigene Wechselzeile', async () => {
+ // Die Reihenfolge aus ModelSelector.selectModelInner: erst den Steckplatz
+ // zurueckgeben und es ansagen, dann das Modell in LM Studio laden, und
+ // erst nach der Ladung die Wahl setzen. In diesem Fenster faellt die Wahl.
+ luEngineImSteckplatz()
+ await durchlassen()
+ useModelStore.setState({ activeModel: LU_ROW })
+
+ const zurueckAn = handBackChatProviderForRow(ROWS[1])
+ expect(zurueckAn).toBe('LM Studio')
+ announceChatProviderSwitch('LM Studio', LMS_ROW)
+ await durchlassen()
+
+ expect(useModelStore.getState().activeModel, 'die Wahl faellt hier wirklich').toBeNull()
+ expect(zeile(), 'die eigene Wechselzeile wurde verdraengt')
+ .toBe(chatProviderSwitchNote('LM Studio'))
+ })
+
+ it('setzt der Aufrufer die Wahl sofort neu, faellt sie gar nicht erst', async () => {
+ // useModels.activateModel: Steckplatz abgeben, ohne await die neue Zeile
+ // setzen. Hier ist nichts zu raeumen und nichts zu sagen.
+ luEngineImSteckplatz()
+ await durchlassen()
+ useModelStore.setState({ activeModel: LU_ROW })
+
+ handBackChatProviderForRow(ROWS[1])
+ useModelStore.setState({ activeModel: LMS_ROW })
+ await durchlassen()
+
+ expect(useModelStore.getState().activeModel).toBe(LMS_ROW)
+ expect(zeile()).toBeNull()
+ })
+
+ it('eine Ollama-Wahl ueberlebt die Uebergabe und bekommt kein Wort', async () => {
+ luEngineImSteckplatz()
+ await durchlassen()
+ useModelStore.setState({ activeModel: OLLAMA_ROW })
+
+ enableAufDerStandbyKarte()
+ await durchlassen()
+
+ expect(useModelStore.getState().activeModel).toBe(OLLAMA_ROW)
+ expect(zeile()).toBeNull()
+ })
+
+ it('ohne Wahl gibt es nichts zu raeumen und nichts zu sagen', async () => {
+ luEngineImSteckplatz()
+ await durchlassen()
+
+ enableAufDerStandbyKarte()
+ await durchlassen()
+
+ expect(useModelStore.getState().activeModel).toBeNull()
+ expect(zeile()).toBeNull()
+ })
+
+ it('die gemerkte Klick-Rueckgabe verjaehrt, sie schweigt nicht fuer immer', async () => {
+ luEngineImSteckplatz()
+ await durchlassen()
+ useModelStore.setState({ activeModel: LU_ROW })
+
+ handBackChatProviderForRow(ROWS[1])
+ expect(handbackAwaitsTheUsersPick()).toBe(true)
+ await vi.advanceTimersByTimeAsync(CHAT_PROVIDER_SWITCH_HOLD_MS + 1)
+ expect(handbackAwaitsTheUsersPick()).toBe(false)
+ })
+})
diff --git a/src/lib/active-model-mode.ts b/src/lib/active-model-mode.ts
index a12bdb5c..085cff83 100644
--- a/src/lib/active-model-mode.ts
+++ b/src/lib/active-model-mode.ts
@@ -95,6 +95,14 @@ export function pickForMode(
* Schalter steht sichtbar auf dem Schirm, und eine Zeile darueber waere Laerm.
* Gemeint ist allein der Fall, in dem sich die Liste unter dem Nutzer bewegt
* hat, ohne dass er den Waehler angefasst hat.
+ *
+ * `activeModel` muss dafuer da sein, und das ist keine Luecke, sondern die
+ * Grenze dieser Regel: der Satz nennt beide Namen, und ohne den alten gibt es
+ * keinen Satz. Der Fall, in dem die Wahl vorher schon geraeumt wurde, weil ein
+ * fremdes Backend den lokalen Steckplatz uebernommen hat, wird deshalb dort
+ * angesagt, wo der alte Name noch dasteht: in `dropDisplacedEnginePick`
+ * (lib/builtin-slot-eviction), im selben Zug wie das Raeumen. Wer ihn hier
+ * einzufangen versucht, kommt immer zu spaet.
*/
export function replacedBehindTheUsersBack(
activeModel: string | null,
diff --git a/src/lib/builtin-slot-eviction.ts b/src/lib/builtin-slot-eviction.ts
index 9462e555..b2ad9b4f 100644
--- a/src/lib/builtin-slot-eviction.ts
+++ b/src/lib/builtin-slot-eviction.ts
@@ -45,7 +45,8 @@
* das nichts mehr bedient. Ausgerechnet hier faellt auch die Selbstheilung
* des Absendewegs aus: der ruft `ensureBuiltinEngineAlive` nur hinter
* `config.managed === true`, und managed ist jetzt false. Also raeumt dieses
- * Modul die Wahl, und der Waehler sagt wieder "Select Model".
+ * Modul die Wahl, der Waehler sagt wieder "Select Model", und wer den Wechsel
+ * nicht selbst im Waehler ausgeloest hat, liest eine Zeile darueber.
*/
import { backendCall, isTauri } from '../api/backend'
@@ -57,6 +58,10 @@ export interface BuiltinSlotView {
enabled: boolean
/** True only for the app's own bundled llama.cpp engine. */
managed?: boolean
+ /** Der Anzeigename des Backends, das den Steckplatz haelt. Fuer die
+ * Entscheidung selbst bedeutungslos, aber die Zeile, die der Nutzer danach
+ * liest, nennt den, der uebernommen hat. */
+ name?: string
}
/**
@@ -156,7 +161,7 @@ export function onLocalSlotChanged(
}
return
}
- if (builtinSlotHandedToForeignBackend(before, after)) void dropDisplacedEnginePick()
+ if (builtinSlotHandedToForeignBackend(before, after)) void dropDisplacedEnginePick(after?.name)
if (!isTauri()) return
cancelPending()
const mine = generation
@@ -201,37 +206,56 @@ async function bringEngineBack(): Promise<void> {
}
/**
- * Die Wahl faellt mit dem Steckplatz.
+ * Die Wahl faellt mit dem Steckplatz, und der Nutzer erfaehrt es.
*
* Der Chip im Chat nennt nach der Uebergabe weiter das GGUF, das auf 8127
* lag. Auf dem Port liegt nichts mehr, und die Selbstheilung des Absendewegs
* haengt hinter `config.managed === true`, das jetzt false ist. Bleibt die
* Wahl stehen, ist die einzige Antwort auf ein Absenden eine Fremdmeldung
* ueber eine unbekannte Modell-Kennung. Steht sie nicht mehr, sagt der Waehler
- * "Select Model" und die Eingangsseite sagt, was zu tun ist.
+ * wieder "Select Model".
*
- * Entschieden wird nach der ZEILE, nicht nach dem Steckplatz. Der Aufrufer
- * darf im selben Durchlauf eine neue Wahl setzen, und genau das tut er:
- * `useModels` gibt den Steckplatz ab und setzt die Zeile des uebernehmenden
- * Backends unmittelbar danach, ohne `await` dazwischen. Diese Funktion liest
- * den Zustand erst nach ihrem ersten `await import(...)`, also mindestens eine
- * Mikrotask spaeter, und findet dann eine LM-Studio-Zeile vor, die sie nichts
- * angeht. Der dynamische Import ist derselbe Ladekreis-Schutz, den auch
- * `bringEngineBack` braucht.
+ * Entschieden wird nach der ZEILE, nicht nach dem Steckplatz, und gelesen wird
+ * sie erst hinter dem ersten `await import(...)`, also mindestens eine
+ * Mikrotask nach dem Steckplatzwechsel. Das deckt genau EINEN der beiden
+ * Klickwege ab, nicht den Aufrufer im Allgemeinen:
+ * `useModels.activateModel` gibt den Steckplatz ab und setzt die Zeile des
+ * uebernehmenden Backends ohne `await` unmittelbar danach, dort findet diese
+ * Funktion also eine fremde Zeile vor, die sie nichts angeht. Der zweite Weg,
+ * die Auto-Ladung im Waehler, laedt das Modell erst in LM Studio und setzt die
+ * Wahl erst hinterher, auf der Box 12,4 s spaeter. Dort faellt die Wahl also
+ * wirklich, und der Waehler steht bis zum Ende der Ladung auf "Select Model".
+ * Das ist richtig so: bis dahin bedient wirklich niemand das GGUF.
+ *
+ * GESAGT wird es aber nur auf dem einen Weg. Wer in den Einstellungen Enable
+ * auf der Standby-Karte drueckt, sieht seinen Chip wechseln, ohne den Waehler
+ * angefasst zu haben, und bekam bisher kein Wort dazu: `activeModel` ist nach
+ * dem Raeumen null, und `replacedBehindTheUsersBack` (lib/active-model-mode)
+ * verlangt einen vorherigen Namen, den es dann nicht mehr gibt. Wer dagegen
+ * selbst eine Zeile des wartenden Backends angeklickt hat, liest die
+ * Wechselzeile ueber genau diesen Vorgang schon; ein zweiter Satz wuerde sie
+ * nur verdraengen. `handbackAwaitsTheUsersPick` trennt die beiden.
+ *
+ * Der dynamische Import ist derselbe Ladekreis-Schutz, den auch
+ * `bringEngineBack` braucht: der providerStore zeigt auf dieses Modul.
*
* Geraeumt wird mit `setState`, NICHT ueber `setActiveModel`: an dessen Weg
* weg von einer Engine-Zeile haengt ein sofortiges `stop_bundled_engine`, und
* das wuerde die Nachsicht ueberholen, die dieses Modul selbst verwaltet.
*/
-async function dropDisplacedEnginePick(): Promise<void> {
+async function dropDisplacedEnginePick(uebernehmer: string | undefined): Promise<void> {
try {
const { useModelStore } = await import('../stores/modelStore')
const gewaehlt = useModelStore.getState().activeModel
if (!gewaehlt) return
const zeile = useModelStore.getState().models.find((m) => m.name === gewaehlt)
if (!isBuiltinEngineEntry(zeile as unknown as InstalledModelLike | undefined)) return
+ // Zuerst raeumen, dann reden. Die Ansage haengt an einem zweiten
+ // dynamischen Import, und was danach kommt, darf das Raeumen weder
+ // verzoegern noch mit sich reissen, wenn es scheitert.
useModelStore.setState({ activeModel: null })
log.info('[builtin-slot] engine lost the local slot, dropped the pick it was serving')
+ void sagenDassDieWahlFiel(gewaehlt, uebernehmer)
} catch (e) {
// Wie beim Rueckweg: der Steckplatzwechsel selbst darf daran nicht
// scheitern. Die naechste Modelliste prueft die Wahl ohnehin erneut.
@@ -239,6 +263,26 @@ async function dropDisplacedEnginePick(): Promise<void> {
}
}
+/**
+ * Die Zeile ueber die gefallene Wahl, aber nur an den, der sie nicht selbst
+ * ausgeloest hat.
+ *
+ * `handbackAwaitsTheUsersPick` ist wahr, solange der Steckplatz noch auf die
+ * Zeile wartet, die der Nutzer im Waehler angeklickt hat. Dann steht die
+ * Wechselzeile ueber genau diesen Vorgang schon auf dem Schirm, und ein
+ * zweiter Satz wuerde sie loeschen statt ergaenzen.
+ */
+async function sagenDassDieWahlFiel(gewaehlt: string, uebernehmer: string | undefined): Promise<void> {
+ try {
+ const { announceChatModelLostItsEngine, handbackAwaitsTheUsersPick } =
+ await import('../api/lu-engine-switch')
+ if (handbackAwaitsTheUsersPick()) return
+ announceChatModelLostItsEngine(gewaehlt, uebernehmer)
+ } catch (e) {
+ log.warn('[builtin-slot] could not say that the pick fell with the slot', { err: e })
+ }
+}
+
/** Test-only: forget a pending unload so tests stay isolated. */
export function __resetBuiltinSlotOffloadForTests(): void {
cancelPending()
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index ab14e567..188c9774 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -340,11 +340,11 @@ export const ONBOARDING_EMBED_MODEL = {
}
export const ONBOARDING_MODELS: OnboardingModel[] = [
- // P4 / LU-Aufgaben: ONBOARDING shows exactly ONE model — the tiny ~400 MB
- // Qwen 2.5 0.5B starter. The previous list of 22 entries (5–42 GB) was
+ // P4 / LU-Aufgaben: ONBOARDING shows exactly ONE model, the tiny ~400 MB
+ // Qwen 2.5 0.5B starter. The previous list of 22 entries (5 to 42 GB) was
// pure noise on first launch. Discoverability for everything else lives
- // in the Model Manager → Discover tab (curated list + HuggingFace
+ // in the Model Manager → Get new tab (curated list + HuggingFace
// search). Onboarding is "give the user a working chat in 30 seconds";
// anything heavier comes after they've made it past the wizard.
- { name: 'qwen2.5-0.5b', label: 'Qwen 2.5 0.5B (Starter)', description: 'Tiny instant-chat model, 400 MB, runs on anything. Great to verify your setup; pick bigger models from the Discover tab once you\'re in.', size: '0.4 GB', vram: '1 GB', vramGB: 1, recommended: true, agent: false, downloadUrl: HF_OB('bartowski/Qwen2.5-0.5B-Instruct-GGUF', 'Qwen2.5-0.5B-Instruct-Q4_K_M.gguf'), filename: 'Qwen2.5-0.5B-Instruct-Q4_K_M.gguf', sizeGB: 0.4 },
+ { name: 'qwen2.5-0.5b', label: 'Qwen 2.5 0.5B (Starter)', description: 'Tiny instant-chat model, 400 MB, runs on anything. Great to verify your setup; pick bigger models from the Get new tab once you\'re in.', size: '0.4 GB', vram: '1 GB', vramGB: 1, recommended: true, agent: false, downloadUrl: HF_OB('bartowski/Qwen2.5-0.5B-Instruct-GGUF', 'Qwen2.5-0.5B-Instruct-Q4_K_M.gguf'), filename: 'Qwen2.5-0.5B-Instruct-Q4_K_M.gguf', sizeGB: 0.4 },
]
diff --git a/src/lib/custom-model-dir.ts b/src/lib/custom-model-dir.ts
index 9aa473bd..8041299f 100644
--- a/src/lib/custom-model-dir.ts
+++ b/src/lib/custom-model-dir.ts
@@ -11,8 +11,10 @@
* So this is the handover. Rust writes ComfyUI's own extra-model-paths file
* for the ComfyUI-shaped subfolders it finds and passes it at start; a
* hand written `extra_model_paths.yaml` in the user's ComfyUI folder is never
- * touched. Two limits are real and the Settings copy names both: a ComfyUI
- * that LU starts, and the next start of it.
+ * touched. One limit is real and the Settings copy names it: only a ComfyUI
+ * that LU starts is handed the folder. The subfolders are scanned again on
+ * every one of those starts, so a subfolder added later arrives with the next
+ * start.
*/
import { backendCall } from '../api/backend'
@@ -22,14 +24,17 @@ import { log } from './logger'
* What the folder is worth right now.
*
* `unusable` is a relative path or a `~` the OS never expands, `unreachable` is
- * a folder LU cannot read (an unplugged drive, a dead network mount). Both used
- * to be silence: no folders, no file, no word about it.
+ * a folder that is not there (an unplugged drive, a dead network mount), and
+ * `denied` is one that is there and closed to the account this app runs as.
+ * All three used to be silence, and the middle two used to be one answer, so a
+ * folder without read rights was reported as a missing drive.
*/
export type CustomModelDirStatus =
| 'off'
| 'ok'
| 'unusable'
| 'unreachable'
+ | 'denied'
/** This host never starts a ComfyUI, so there is nobody to hand the folder
* to. The Mac, where local media is MLX. */
| 'unsupported'
diff --git a/src/lib/local-backend-transport.ts b/src/lib/local-backend-transport.ts
index c0bb6e72..a5db6c85 100644
--- a/src/lib/local-backend-transport.ts
+++ b/src/lib/local-backend-transport.ts
@@ -1,6 +1,7 @@
/**
- * One reading of "the local backend did not answer", shared by everyone who
- * talks to a server on this machine or on the LAN.
+ * One reading of "the backend did not answer", shared by every provider that
+ * reaches its server through the Rust proxy: on this machine, on the LAN, or
+ * on a host of the user's own out on the internet.
*
* The Rust proxy hands a refused connection back as
* `Response(503, {"error": "proxy_localhost_stream_chunked: error sending
@@ -12,6 +13,12 @@
* worse, because it was wrong. With that race closed (see proxy.rs) the real
* message arrives, and every provider needs the same two answers about it:
* is this a transport failure against MY host, and what do I say instead.
+ *
+ * The second answer splits by where that host is, so there are two sentences
+ * below and not one. `localBackendUnreachableMessage` talks to somebody who
+ * runs the server himself and can start it; `remoteBackendUnreachableMessage`
+ * talks to somebody whose address may simply be wrong or whose line may be
+ * down. The first question, `isLocalTransportFailure`, is the same for both.
*/
/** The shapes a refused or broken local connection arrives in. */
diff --git a/src/lib/model-list-staleness.ts b/src/lib/model-list-staleness.ts
new file mode 100644
index 00000000..1883e440
--- /dev/null
+++ b/src/lib/model-list-staleness.ts
@@ -0,0 +1,50 @@
+/**
+ * Welche Aenderung an einem Backend die Modelliste veralten laesst.
+ *
+ * Die Regel stand wortgleich zweimal im Baum, im Waehler ueber dem
+ * Eingabefeld und in der Kopfleiste, und beide Fassungen kannten genau zwei
+ * Felder: `enabled` und `baseUrl`. Die Quelle der ganzen Liste haengt aber an
+ * `managed`. Haelt unsere eigene Engine den geteilten `openai`-Steckplatz,
+ * fragt `useModels` `list_bundled_models` statt `/v1/models`, nimmt den
+ * Steckplatz aus der Provider-Runde heraus und stellt die Zeilen des
+ * verdraengten Backends unter eine eigene Ueberschrift daneben
+ * (`isManagedBuiltinActive`, `standbyChatBackend`). Ein Schreiben, das nur den
+ * Halter des Steckplatzes dreht, schreibt die Liste also am staerksten um, und
+ * genau das loeste kein Nachladen aus.
+ *
+ * `name` ist aus demselben Grund dabei: er ist das Einzige, was die Zeilen
+ * zweier Backends unterscheidet, die sich einen Steckplatz teilen
+ * (`isRowOfBackend`), und er steht als Ueberschrift ueber der wartenden
+ * Gruppe.
+ *
+ * NICHT dabei ist der Schluessel. Das Feld im Einstellungsblatt schreibt bei
+ * jedem Tastendruck in den Store, und ein Nachladen pro Buchstabe waere eine
+ * Anfrage-Lawine gegen einen Anbieter, der den halb getippten Schluessel
+ * ohnehin ablehnt. Eingeschaltet wird der Anbieter danach ohnehin, und das
+ * steht hier oben in der ersten Zeile.
+ */
+
+import type { ProviderConfig, ProviderId } from '../api/providers/types'
+
+/** Die Felder, an denen die Liste haengt. */
+const FELDER = ['enabled', 'baseUrl', 'name', 'managed'] as const
+
+type Steckplaetze = Record<ProviderId, ProviderConfig>
+
+/**
+ * Hat sich an irgendeinem Steckplatz etwas geaendert, das die Modelliste
+ * anders aussehen laesst.
+ *
+ * Beide Seiten kommen aus demselben Store, also haben sie dieselben
+ * Schluessel; gelesen werden trotzdem beide, damit ein neu hinzugekommener
+ * Steckplatz nicht uebersehen wird.
+ */
+export function modelListIsStale(next: Steckplaetze, prev: Steckplaetze): boolean {
+ const ids = new Set([...Object.keys(next), ...Object.keys(prev)] as ProviderId[])
+ for (const id of ids) {
+ for (const feld of FELDER) {
+ if (next[id]?.[feld] !== prev[id]?.[feld]) return true
+ }
+ }
+ return false
+}
diff --git a/src/stores/__tests__/comfy-install-notice.test.ts b/src/stores/__tests__/comfy-install-notice.test.ts
index beef9d60..18deab45 100644
--- a/src/stores/__tests__/comfy-install-notice.test.ts
+++ b/src/stores/__tests__/comfy-install-notice.test.ts
@@ -1,7 +1,7 @@
/**
* A15, Windows Nachlauf 02.09., Befund 5b: a ComfyUI requirements.txt with an
* invented package on line 1 made `pip install -r` fail, the repair carried on
- * with LU's own package list, and the run ended after 377 seconds on a green
+ * with the packages LU knows about, and the run ended after 377 seconds on a green
* panel. No error card, no hint, nothing in the log about the file that had
* been passed over, so the user is left with a ComfyUI that is quietly short of
* whatever that file asked for.
@@ -28,8 +28,9 @@ const store = () => useComfyInstallStore.getState()
const SKIPPED =
"The requirements.txt in C:\\Users\\ddrob\\ComfyUI could not be used (pip found no " +
- 'installable version for a package it names), so LU installed its own package list ' +
- 'instead. Anything that file asks for on top of that list is not installed.'
+ 'installable version for a package it names), so LU checked the packages it knows ' +
+ 'about and installed the ones that were missing. Anything that file asks for on top ' +
+ 'of that list is not installed.'
beforeEach(() => {
store().reset()
diff --git a/src/stores/comfyInstallStore.ts b/src/stores/comfyInstallStore.ts
index 9a05d9e5..b04a08e5 100644
--- a/src/stores/comfyInstallStore.ts
+++ b/src/stores/comfyInstallStore.ts
@@ -121,8 +121,8 @@ interface InstallStatusPayload {
logs?: string[]
/** One closing line the backend wants kept after the run. A15, Windows
* Nachlauf 02.09.: a ComfyUI requirements.txt pip cannot install is skipped
- * and the run finishes on LU's own package list, which used to end in a
- * green idle panel that said nothing about the file it passed over. */
+ * and the run finishes on the packages LU knows about, which used to end in
+ * a green idle panel that said nothing about the file it passed over. */
notice?: string
/** How that line reads: 'ok' for a run that simply worked, 'warn' for one
* that finished with something the user has to know. */