The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(comfyui): a broken Python environment repairs itself (#98)
David00e284df44e7
diff --git a/src-tauri/src/commands/install.rs b/src-tauri/src/commands/install.rsindex 0dcde136..7b8e8aea 100644--- a/src-tauri/src/commands/install.rs+++ b/src-tauri/src/commands/install.rs@@ -519,6 +519,61 @@ pub fn pip_install_streaming_with_retry_cancellable())}+/// Pure: the pip argument set for the PyTorch install, for a given wheel+/// index. Split from the probe so the arg shapes are testable without+/// nvidia-smi on the machine.+pub(crate) fn pytorch_pip_args(index_url: Option<&str>) -> Vec<String> {+ let mut args: Vec<String> = [+ "-m", "pip", "install",+ "--progress-bar", "off",+ "--no-input",+ "torch", "torchvision", "torchaudio",+ ]+ .iter()+ .map(|s| s.to_string())+ .collect();+ if let Some(u) = index_url {+ args.push("--index-url".to_string());+ args.push(u.to_string());+ }+ args+}++/// GPU probe + wheel choice + pip args, shared between the first install and+/// `repair_comfyui_env` so the two can never drift apart (same cu128/cu121/+/// CPU decision, same flags).+///+/// Bug #10 (vokurta — RTX 6000 Blackwell, 2026-05-11): SM 12.0 GPUs need+/// PyTorch cu128 wheels. cu121 stops at sm_90 (Hopper); on Blackwell the+/// kernel simply isn't shipped and the first compute call dies with "CUDA+/// error: no kernel image is available for execution on the device". We probe+/// `--query-gpu=compute_cap` and pick the wheel set accordingly. Falls back+/// to cu121 if the probe fails for any reason — that's the previous+/// behaviour, so we never regress existing setups.+pub(crate) fn plan_pytorch_install() -> (Vec<String>, String) {+ let mut nv = Command::new("nvidia-smi");+ nv.stdout(Stdio::piped()).stderr(Stdio::piped());+ #[cfg(target_os = "windows")]+ nv.creation_flags(CREATE_NO_WINDOW);+ let has_nvidia = nv.output().map(|o| o.status.success()).unwrap_or(false);++ let compute_cap_major = if has_nvidia { detect_nvidia_compute_cap_major() } else { None };+ let pytorch_index = match compute_cap_major {+ Some(major) if major >= 12 => Some("https://download.pytorch.org/whl/cu128"),+ Some(_) => Some("https://download.pytorch.org/whl/cu121"),+ None if has_nvidia => Some("https://download.pytorch.org/whl/cu121"),+ None => None,+ };++ let gpu_info = match (has_nvidia, compute_cap_major) {+ (true, Some(major)) if major >= 12 => "NVIDIA Blackwell GPU detected (SM 12.0+) — installing PyTorch cu128",+ (true, Some(_)) => "NVIDIA GPU detected — installing CUDA PyTorch (cu121)",+ (true, None) => "NVIDIA GPU detected (compute capability probe failed) — falling back to cu121",+ (false, _) => "No NVIDIA GPU — installing CPU PyTorch",+ };+ (pytorch_pip_args(pytorch_index), gpu_info.to_string())+}+#[tauri::command]pub fn install_comfyui(install_path: Option<String>,@@ -737,35 +792,9 @@ pub fn install_comfyui(python_bin.clone()};- // Step 2: Detect GPU and install PyTorch- let mut nv = Command::new("nvidia-smi");- nv.stdout(Stdio::piped()).stderr(Stdio::piped());- #[cfg(target_os = "windows")]- nv.creation_flags(CREATE_NO_WINDOW);- let has_nvidia = nv.output().map(|o| o.status.success()).unwrap_or(false);-- // Bug #10 (vokurta — RTX 6000 Blackwell, 2026-05-11): SM 12.0 GPUs- // need PyTorch cu128 wheels. cu121 stops at sm_90 (Hopper); on- // Blackwell the kernel simply isn't shipped and the first compute- // call dies with "CUDA error: no kernel image is available for- // execution on the device". We probe `--query-gpu=compute_cap` and- // pick the wheel set accordingly. Falls back to cu121 if the probe- // fails for any reason — that's the previous behaviour, so we- // never regress existing setups.- let compute_cap_major = if has_nvidia { detect_nvidia_compute_cap_major() } else { None };- let pytorch_index = match compute_cap_major {- Some(major) if major >= 12 => Some("https://download.pytorch.org/whl/cu128"),- Some(_) => Some("https://download.pytorch.org/whl/cu121"),- None if has_nvidia => Some("https://download.pytorch.org/whl/cu121"),- None => None,- };-- let gpu_info = match (has_nvidia, compute_cap_major) {- (true, Some(major)) if major >= 12 => "NVIDIA Blackwell GPU detected (SM 12.0+) — installing PyTorch cu128",- (true, Some(_)) => "NVIDIA GPU detected — installing CUDA PyTorch (cu121)",- (true, None) => "NVIDIA GPU detected (compute capability probe failed) — falling back to cu121",- (false, _) => "No NVIDIA GPU — installing CPU PyTorch",- };+ // Step 2: Detect GPU and install PyTorch (probe + wheel choice shared+ // with repair_comfyui_env via plan_pytorch_install).+ let (torch_args, gpu_info) = plan_pytorch_install();println!("[Install] {}", gpu_info);update("installing", &format!("Step 2/3: {}", gpu_info));update(@@ -776,24 +805,8 @@ pub fn install_comfyui(lines appearing, the install is making progress, not hung.",);- let torch_args: Vec<&str> = if let Some(index_url) = pytorch_index {- vec![- "-m", "pip", "install",- "--progress-bar", "off",- "--no-input",- "torch", "torchvision", "torchaudio",- "--index-url", index_url,- ]- } else {- vec![- "-m", "pip", "install",- "--progress-bar", "off",- "--no-input",- "torch", "torchvision", "torchaudio",- ]- };-- match pip_install_streaming_with_retry_cancellable(&torch_args, &effective_python, 3, &install_status, Some(&cancel_flag)) {+ let torch_arg_refs: Vec<&str> = torch_args.iter().map(|s| s.as_str()).collect();+ match pip_install_streaming_with_retry_cancellable(&torch_arg_refs, &effective_python, 3, &install_status, Some(&cancel_flag)) {Ok(()) => {update("installing", "PyTorch installed successfully.");}@@ -876,6 +889,180 @@ pub fn install_comfyui(Ok(serde_json::json!({"status": "installing"}))}+/// GH #98 (joelnewswanger, 2026-08-14): ComfyUI installed once, then died at+/// import time on every start. His torch lived in the SHARED system Python's+/// site-packages, where anything the user ever pip-installed can break us,+/// and clicking install again changed nothing because pip saw every package+/// as "already satisfied". kryptoxide's night (same issue) was the same trap+/// from the other side: a stray `comfy 0.0.1` on the system Python shadowed+/// ComfyUI's own package.+///+/// The repair builds what those installs never had: a fresh venv inside the+/// ComfyUI folder, with PyTorch and the requirements installed into it. The+/// launcher already prefers ComfyUI/venv over the system Python, so the next+/// start picks it up with no further wiring. The system Python, models,+/// outputs and custom nodes are left alone. Progress goes through the same+/// install_status slot, so install_comfyui_status polling just works.+#[tauri::command]+pub fn repair_comfyui_env(state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ if !crate::commands::process::comfy_supported_here() {+ return Err(crate::commands::process::MACOS_COMFY_REFUSAL.to_string());+ }+ let comfy_dir = {+ let p = state.comfy_path.lock().unwrap().clone();+ p.or_else(crate::commands::process::find_comfyui_path)+ };+ let Some(comfy_dir) = comfy_dir else {+ return Err(+ "ComfyUI is not installed, so there is no environment to repair. Use Install ComfyUI instead."+ .to_string(),+ );+ };+ let comfy_dir = PathBuf::from(comfy_dir);+ // Portable installs bring their own python_embeded and the launcher+ // prefers it over any venv, so a rebuilt venv would never be used.+ let embeded_here = comfy_dir.join("python_embeded").join("python.exe").exists();+ let embeded_beside = comfy_dir+ .parent()+ .map(|p| p.join("python_embeded").join("python.exe").exists())+ .unwrap_or(false);+ if embeded_here || embeded_beside {+ return Err(+ "This is a portable ComfyUI with its own bundled Python. Re-extract the portable \+ package to repair it; the app cannot rebuild that environment."+ .to_string(),+ );+ }+ let python_bin = state.python_bin.lock().unwrap().clone();+ if python_bin.is_empty() || !crate::python::is_real_python(&python_bin) {+ return Err(+ "no_python: Python must be installed before the environment can be rebuilt. Call install_python first."+ .to_string(),+ );+ }+ {+ let mut install = state.install_status.lock().unwrap();+ if install.status == "installing" {+ return Ok(serde_json::json!({"status": "already_installing"}));+ }+ install.status = "installing".to_string();+ install.logs.clear();+ install.logs.push("Repairing the ComfyUI environment...".to_string());+ }+ info!("comfyui env repair start");+ // A tracked child would hold venv files open on Windows; it is dead or+ // dying anyway (the repair only runs after a startup crash).+ {+ let mut proc = state.comfy_process.lock().unwrap();+ if let Some(mut child) = proc.take() {+ let _ = child.kill();+ let _ = child.wait();+ }+ }+ state.comfyui_install_cancel.store(false, Ordering::SeqCst);+ let cancel_flag = state.comfyui_install_cancel.clone();+ let install_status = state.install_status.clone();++ std::thread::spawn(move || {+ let update = |status: &str, msg: &str| {+ if let Ok(mut s) = install_status.lock() {+ s.status = status.to_string();+ s.logs.push(msg.to_string());+ }+ };++ // 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");+ if venv_dir.exists() {+ update(+ "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",+ &format!(+ "Could not remove the old venv at {}: {}. Close anything using it and retry.",+ venv_dir.display(),+ e+ ),+ );+ return;+ }+ }++ update(+ "installing",+ "Step 1/3: Creating a fresh isolated venv inside the ComfyUI folder...",+ );+ let venv_py = match create_comfyui_venv(&comfy_dir, &python_bin) {+ Ok(p) => p.to_string_lossy().to_string(),+ Err(e) => {+ update("error", &format!("venv creation failed.\n\n{}", e));+ return;+ }+ };+ if cancel_flag.load(Ordering::SeqCst) {+ update("cancelled", "Repair cancelled.");+ return;+ }++ let (torch_args, gpu_info) = plan_pytorch_install();+ update("installing", &format!("Step 2/3: {}", gpu_info));+ update(+ "installing",+ "Downloading PyTorch into the fresh venv (~2 GB). Live pip output below.",+ );+ let refs: Vec<&str> = torch_args.iter().map(|s| s.as_str()).collect();+ match pip_install_streaming_with_retry_cancellable(&refs, &venv_py, 3, &install_status, Some(&cancel_flag)) {+ Ok(()) => update("installing", "PyTorch installed."),+ Err(d) if d == "cancelled" => {+ update("cancelled", "Repair cancelled during the PyTorch download.");+ return;+ }+ Err(d) => {+ update("error", &format!("PyTorch installation failed.\n\n{}", d));+ return;+ }+ }++ let reqs = comfy_dir.join("requirements.txt");+ if reqs.exists() {+ update(+ "installing",+ "Step 3/3: Installing ComfyUI dependencies into the venv...",+ );+ let reqs_str = reqs.to_string_lossy().to_string();+ let req_args = vec![+ "-m", "pip", "install",+ "--progress-bar", "off",+ "--no-input",+ "-r", reqs_str.as_str(),+ ];+ match pip_install_streaming_with_retry_cancellable(&req_args, &venv_py, 3, &install_status, Some(&cancel_flag)) {+ Ok(()) => update("installing", "Dependencies installed."),+ Err(d) if d == "cancelled" => {+ update("cancelled", "Repair cancelled during the requirements install.");+ return;+ }+ Err(d) => update(+ "installing",+ &format!("Some optional dependencies had warnings (non-critical): {}", d),+ ),+ }+ }++ update(+ "complete",+ "Environment repaired. ComfyUI now runs from its own venv; start it again.",+ );+ });++ Ok(serde_json::json!({"status": "installing"}))+}+#[tauri::command]pub fn install_comfyui_status(state: State<'_, AppState>) -> Result<serde_json::Value, String> {let install = state.install_status.lock().unwrap();@@ -3276,6 +3463,27 @@ fn is_permission_denied_pip_error(output: &str) -> bool {mod tests {use super::*;+ // ── PyTorch-Args, geteilt zwischen Install und Repair (GH #98) ──────++ #[test]+ fn pytorch_args_carry_the_wheel_index_when_given() {+ let args = pytorch_pip_args(Some("https://download.pytorch.org/whl/cu128"));+ assert_eq!(args.first().map(String::as_str), Some("-m"));+ assert!(args.contains(&"torch".to_string()));+ assert!(args.contains(&"torchvision".to_string()));+ assert!(args.contains(&"torchaudio".to_string()));+ assert!(args.contains(&"--no-input".to_string()));+ let idx = args.iter().position(|a| a == "--index-url").expect("index flag");+ assert_eq!(args.get(idx + 1).map(String::as_str), Some("https://download.pytorch.org/whl/cu128"));+ }++ #[test]+ fn pytorch_args_without_index_stay_on_pypi() {+ let args = pytorch_pip_args(None);+ assert!(!args.iter().any(|a| a == "--index-url"));+ assert!(args.contains(&"torch".to_string()));+ }+// ── install_custom_node helpers (#72 bob: VHS install loop) ─────────#[test]diff --git a/src-tauri/src/commands/process.rs b/src-tauri/src/commands/process.rsindex bb4b8468..459a1653 100644--- a/src-tauri/src/commands/process.rs+++ b/src-tauri/src/commands/process.rs@@ -218,6 +218,31 @@ pub fn comfy_startup_failure(msg}+/// 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+/// running through site-packages with no ModuleNotFoundError anywhere;+/// kryptoxide's variant was a shadowing `comfy` package ("No module named+/// 'comfy.options'"). Both are exactly what a fresh venv fixes.+///+/// Excluded on purpose, because a rebuild cannot fix them and their own+/// messages are better: a port collision and a full disk.+pub fn comfy_env_failure(tail: &[String]) -> bool {+ let joined = tail.join("\n");+ if joined.contains("Address already in use")+ || joined.contains("only one usage of each socket address")+ || joined.contains("No space left on device")+ || joined.contains("not enough space on the disk")+ {+ return false;+ }+ joined.contains("ModuleNotFoundError")+ || joined.contains("No module named")+ || joined.contains("ImportError")+ || joined.contains("DLL load failed")+ || (joined.contains("Traceback (most recent call last)") && joined.contains("site-packages"))+}+/// Pure decision (all probes done by the caller): pass `--cpu` to ComfyUI?////// - `baseline_needs_cpu`: `needs_cpu_fallback()` — false when NVIDIA present or macOS.@@ -1519,7 +1544,11 @@ pub fn comfyui_last_output(state: State<'_, AppState>) -> Result<serde_json::ValNone => true,}};- Ok(serde_json::json!({ "lines": lines, "exited": exited }))+ // envBroken drives the self-repair (GH #98): only a crash that looks like+ // a dead Python environment may trigger the venv rebuild, everything else+ // keeps its own message.+ let env_broken = exited && comfy_env_failure(&lines);+ Ok(serde_json::json!({ "lines": lines, "exited": exited, "envBroken": env_broken }))}#[tauri::command]@@ -2235,6 +2264,62 @@ mod tests {assert_eq!(a, b, "needs_cpu_fallback returned inconsistent results");}+ // ── Broken-env classifier fuer die Selbstheilung (GH #98) ────────────++ fn zeilen(v: &[&str]) -> Vec<String> {+ v.iter().map(|s| s.to_string()).collect()+ }++ #[test]+ fn joels_torch_import_death_reads_as_broken_env() {+ // 14.08.: kein ModuleNotFoundError im Tail, nur ein Traceback durch+ // site-packages\torch — genau der Fall, den nur die Frame-Regel faengt.+ let tail = zeilen(&[+ "[start] python main.py --port 8188",+ "Traceback (most recent call last):",+ r#" File "C:\Users\joeln\AppData\Local\Python\pythoncore-3.12-64\Lib\site-packages\torch\_library\infer_schema.py", line 106, in infer_schema"#,+ " error_fn(",+ "RuntimeError: infer_schema(func): Parameter dtype has unsupported type",+ ]);+ assert!(comfy_env_failure(&tail));+ }++ #[test]+ fn kryptoxides_shadowing_package_reads_as_broken_env() {+ let tail = zeilen(&[+ "Traceback (most recent call last):",+ r#" File "I:\comfyui\main.py", line 1, in <module>"#,+ " import comfy.options",+ "ModuleNotFoundError: No module named 'comfy.options'",+ ]);+ assert!(comfy_env_failure(&tail));+ }++ #[test]+ fn a_port_collision_is_not_an_env_failure() {+ // Ein venv-Neubau kann den Port nicht freimachen; die eigene Meldung+ // ist besser. Der Frame laeuft trotzdem durch site-packages (aiohttp),+ // deshalb braucht es den expliziten Ausschluss.+ let tail = zeilen(&[+ "Traceback (most recent call last):",+ r#" File "C:\Python312\Lib\site-packages\aiohttp\web_runner.py", line 119, in start"#,+ "OSError: [Errno 10048] error while attempting to bind on address ('127.0.0.1', 8188): only one usage of each socket address",+ ]);+ assert!(!comfy_env_failure(&tail));+ }++ #[test]+ fn a_full_disk_and_a_clean_tail_are_not_env_failures() {+ let voll = zeilen(&[+ "Traceback (most recent call last):",+ r#" File "C:\Python312\Lib\site-packages\torch\serialization.py", line 998"#,+ "OSError: [Errno 28] No space left on device",+ ]);+ assert!(!comfy_env_failure(&voll));+ let sauber = zeilen(&["[start] python main.py --port 8188", "Total VRAM 12288 MB"]);+ assert!(!comfy_env_failure(&sauber));+ }+// ── AMD/ROCm ComfyUI GPU decision (rhodium92, 2026-07-01) ────────────#[test]diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 48efc2c6..7b1be5de 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -124,6 +124,7 @@ fn main() {// Installationcommands::install::install_comfyui,commands::install::install_comfyui_status,+ commands::install::repair_comfyui_env,commands::install::update_comfyui,commands::install::cancel_comfyui_install,commands::install::install_ollama,diff --git a/src/components/create/experimental/CreateContext.tsx b/src/components/create/experimental/CreateContext.tsxindex 16dd6e9d..a8525691 100644--- a/src/components/create/experimental/CreateContext.tsx+++ b/src/components/create/experimental/CreateContext.tsx@@ -195,55 +195,97 @@ export function CreateExpProvider({ children }: { children: ReactNode }) {}, [connected, setCaps])useEffect(() => { void refreshModelLists() }, [refreshModelLists])- // One-click prerequisite: make sure a local ComfyUI is actually running —- // start it if it's merely stopped, INSTALL it first if it's missing (the- // "complete noob PC" case: every Create tab's Download & install button must- // deliver a 100% functional run, not assume ComfyUI exists).- // Every wait in here reports a ticking second count. A line that never- // changes for 40s reads as frozen, which is exactly what David hit on the- // Motion Control card: the only feedback was a spinner, so "is it doing- // anything" had no answer. A counter answers it without promising a duration- // we cannot know.- const ensureComfyRunning = useCallback(async (onProgress?: (msg: string) => void, signal?: AbortSignal) => {- if (await checkComfyConnection()) return- onProgress?.('Starting ComfyUI…')- try { await backendCall('start_comfyui') } catch { /* not installed yet — handled below */ }- for (let i = 0; i < 15; i++) {- onProgress?.(`Starting ComfyUI… ${i * 2}s`)- await waitOrAbort(2000, signal)- if (await checkComfyConnection()) { checkConnection(); return }- }- onProgress?.('ComfyUI is not installed. Downloading and installing it now, this is a one time step of a few GB…')- await backendCall('install_comfyui')- // Poll the same status contract the Settings installer uses. Generous cap:- // a slow connection legitimately needs a while for the one-time install.+ // Rebuild the ComfyUI venv via the same status contract the installer uses,+ // narrating pip's progress (GH #98). Throws with the last log line on error.+ const repairComfyEnv = useCallback(async (onProgress?: (msg: string) => void, signal?: AbortSignal) => {+ onProgress?.("ComfyUI's Python environment is broken. Rebuilding it as an isolated venv now (~2 GB download). Models, outputs and custom nodes are left alone…")+ await backendCall('repair_comfyui_env')for (let i = 0; i < 2700; i++) {await waitOrAbort(2000, signal)const st = await backendCall<{ status?: string; logs?: string[] }>('install_comfyui_status').catch(() => null)const lastLog = st?.logs?.length ? String(st.logs[st.logs.length - 1]) : ''if (lastLog) onProgress?.(lastLog)- if (st?.status === 'complete') break- if (st?.status === 'error') {- throw new Error(lastLog || 'ComfyUI install failed. See Settings → AI Backends for details.')+ if (st?.status === 'complete') return+ if (st?.status === 'error' || st?.status === 'cancelled') {+ throw new Error(lastLog || 'The environment repair failed. See Settings, AI Backends for details.')}}+ throw new Error('The environment repair did not finish. See Settings, AI Backends for details.')+ }, [])++ // Start ComfyUI and wait for its port, reporting 'crashed' the moment the+ // child exits: polling a port that will never open hid every startup crash+ // behind a spinner (GH #98). The ticking counter stays, a line that never+ // changes for 40s reads as frozen (David, Motion Control card).+ const startAndAwait = useCallback(async (rounds: number, onProgress?: (msg: string) => void, signal?: AbortSignal): Promise<'up' | 'crashed' | 'timeout'> => {onProgress?.('Starting ComfyUI…')await backendCall('start_comfyui')- for (let i = 0; i < 30; i++) {+ for (let i = 0; i < rounds; i++) {onProgress?.(`Starting ComfyUI… ${i * 2}s`)await waitOrAbort(2000, signal)- if (await checkComfyConnection()) { checkConnection(); return }- // The process died — every further poll waits on a port that will- // never open. Fail now, with the crash instead of a guess (GH #98:- // the shipped app has no console, so "did not come up" was a dead- // end with nothing behind it).- const out = await backendCall<{ lines?: string[]; exited?: boolean }>('comfyui_last_output').catch(() => null)- if (out?.exited) throw new Error(comfyStartupError(out.lines))+ if (await checkComfyConnection()) { checkConnection(); return 'up' }+ const out = await backendCall<{ exited?: boolean }>('comfyui_last_output').catch(() => null)+ if (out?.exited) return 'crashed'}- const out = await backendCall<{ lines?: string[] }>('comfyui_last_output').catch(() => null)- throw new Error(comfyStartupError(out?.lines))+ return 'timeout'}, [checkConnection])+ // One-click prerequisite: make sure a local ComfyUI is actually running —+ // start it if it's merely stopped, INSTALL it first if it's missing (the+ // "complete noob PC" case: every Create tab's Download & install button must+ // deliver a 100% functional run, not assume ComfyUI exists).+ //+ // joelnewswanger's loop (GH #98): torch in the shared system Python was+ // broken, every start died at import, the crash read as "not installed",+ // and the re-install changed nothing because pip saw each package as+ // already satisfied. A crash now gets ONE venv rebuild; only a start that+ // cannot find an install at all goes down the one-time download path.+ const ensureComfyRunning = useCallback(async (onProgress?: (msg: string) => void, signal?: AbortSignal) => {+ if (await checkComfyConnection()) return+ let repaired = false+ let installedNow = false+ let r: 'up' | 'crashed' | 'timeout' | 'missing'+ try {+ r = await startAndAwait(60, onProgress, signal)+ } catch { r = 'missing' }+ for (;;) {+ if (r === 'up') return+ if (r === 'crashed') {+ const out = await backendCall<{ lines?: string[]; envBroken?: boolean }>('comfyui_last_output').catch(() => null)+ if (out?.envBroken && !repaired) {+ repaired = true+ await repairComfyEnv(onProgress, signal)+ r = await startAndAwait(60, onProgress, signal)+ continue+ }+ throw new Error(comfyStartupError(out?.lines))+ }+ if (r === 'missing' && !installedNow) {+ installedNow = true+ onProgress?.('ComfyUI is not installed. Downloading and installing it now, this is a one time step of a few GB…')+ await backendCall('install_comfyui')+ // Poll the same status contract the Settings installer uses. Generous cap:+ // a slow connection legitimately needs a while for the one-time install.+ for (let i = 0; i < 2700; i++) {+ await waitOrAbort(2000, signal)+ const st = await backendCall<{ status?: string; logs?: string[] }>('install_comfyui_status').catch(() => null)+ const lastLog = st?.logs?.length ? String(st.logs[st.logs.length - 1]) : ''+ if (lastLog) onProgress?.(lastLog)+ if (st?.status === 'complete') break+ if (st?.status === 'error') {+ throw new Error(lastLog || 'ComfyUI install failed. See Settings → AI Backends for details.')+ }+ }+ r = await startAndAwait(60, onProgress, signal)+ continue+ }+ // Timeout, or a state we already tried to fix once: report with the+ // real output instead of guessing.+ const out = await backendCall<{ lines?: string[] }>('comfyui_last_output').catch(() => null)+ throw new Error(comfyStartupError(out?.lines))+ }+ }, [checkConnection, repairComfyEnv, startAndAwait])+// Install a capability in place — mirrors the VHS one-click flow (#72):// ensure ComfyUI runs, clone the custom node + pip install where one is// needed, restart ComfyUI so it registers, then poll /object_info (clearingdiff --git a/src/components/create/experimental/__tests__/comfy-env-selfheal.test.ts b/src/components/create/experimental/__tests__/comfy-env-selfheal.test.tsnew file mode 100644index 00000000..e9bbe59f--- /dev/null+++ b/src/components/create/experimental/__tests__/comfy-env-selfheal.test.ts@@ -0,0 +1,52 @@+/**+ * GH #98, zweite Welle (joelnewswanger 14.08.): sein torch lebte im geteilten+ * System-Python und starb beim Import. Der Absturz las sich als "nicht+ * installiert", der Re-Install aenderte nichts (pip: already satisfied), und+ * der Settings-Startknopf kippte still auf Stopped, weil der Crash erst nach+ * dem 2-Sekunden-Spawn-Fenster kam.+ *+ * Der Fix: ein Absturz wird sofort erkannt, ein env-kaputter Absturz baut+ * GENAU EINMAL ein frisches venv (repair_comfyui_env) und startet neu, und+ * der Download-Pfad laeuft nur noch, wenn wirklich keine Installation da ist.+ * Quellgepinnt, weil jede dieser Weichen eine Bedingung ist, die kein+ * bestehender Test sieht.+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { resolve, dirname } from 'node:path'+import { fileURLToPath } from 'node:url'++const hier = dirname(fileURLToPath(import.meta.url))+const kontext = () => readFileSync(resolve(hier, '..', 'CreateContext.tsx'), 'utf8')+const settings = () => readFileSync(resolve(hier, '..', '..', '..', 'settings', 'SettingsPage.tsx'), 'utf8')++describe('#98: die ComfyUI-Umgebung heilt sich selbst', () => {+ it('ein Absturz in der Wartschleife wird sofort erkannt, nicht als Timeout verbrannt', () => {+ const src = kontext()+ expect(src).toMatch(/const startAndAwait = useCallback/)+ expect(src).toMatch(/if \(out\?\.exited\) return 'crashed'/)+ })++ it('ein env-kaputter Absturz repariert genau einmal und startet dann neu', () => {+ const src = kontext()+ expect(src).toMatch(/out\?\.envBroken && !repaired/)+ expect(src).toMatch(/backendCall\('repair_comfyui_env'\)/)+ })++ it('der Download-Pfad laeuft nur noch fuer eine wirklich fehlende Installation', () => {+ const src = kontext()+ expect(src).toMatch(/r === 'missing' && !installedNow/)+ })++ it('die Settings haben einen Repair-Knopf am selben Kommando', () => {+ const src = settings()+ expect(src).toMatch(/repair_comfyui_env/)+ expect(src).toMatch(/Repair environment/)+ })++ it('der Settings-Start meldet einen spaeten Absturz statt still auf Stopped zu kippen', () => {+ const src = settings()+ expect(src).toMatch(/comfyui_last_output/)+ expect(src).toMatch(/envBroken/)+ })+})diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsxindex 074ec361..a4474214 100644--- a/src/components/settings/SettingsPage.tsx+++ b/src/components/settings/SettingsPage.tsx@@ -318,7 +318,7 @@ function ComfyUISettings() {const [hostError, setHostError] = useState('')const [hostSuccess, setHostSuccess] = useState(false)// P14 Python install state for the Settings Install-ComfyUI flow.- const [installPhase, setInstallPhase] = useState<'idle' | 'python' | 'comfyui' | 'error'>('idle')+ const [installPhase, setInstallPhase] = useState<'idle' | 'python' | 'comfyui' | 'repair' | 'error'>('idle')const [installLogs, setInstallLogs] = useState<string[]>([])const [installErr, setInstallErr] = useState('')@@ -349,11 +349,56 @@ function ComfyUISettings() {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: any = await backendCall('comfyui_last_output')+ if (out?.exited && Array.isArray(out?.lines) && out.lines.length > 1) {+ const { comfyStartupError } = await import('../create/experimental/comfyError')+ setStartError(+ comfyStartupError(out.lines) ++ (out.envBroken ? '\n\nThe Python environment looks broken. Repair environment below rebuilds it in place; models, outputs and custom nodes are left alone.' : ''),+ )+ }+ } catch { /* status polling keeps the panel honest */ }+ }, 6000)} catch (err) {setStartError(err instanceof Error ? err.message : String(err))}}+ // GH #98: rebuild the ComfyUI venv (fresh isolated env, ~2 GB) through the+ // same status contract the installer uses, so the progress card just works.+ const handleRepair = async () => {+ setStartError('')+ setInstallPhase('repair')+ setInstallLogs(['Repairing the ComfyUI environment…'])+ try {+ const { backendCall } = await import('../../api/backend')+ await backendCall('repair_comfyui_env')+ const poll = setInterval(async () => {+ try {+ const data: any = await backendCall('install_comfyui_status')+ setInstallLogs(data.logs || [])+ if (data.status === 'complete') {+ clearInterval(poll)+ setInstallPhase('idle')+ } else if (data.status === 'error' || data.status === 'cancelled') {+ clearInterval(poll)+ const lastLog = (data.logs?.length ? data.logs[data.logs.length - 1] : '') as string+ setInstallErr(lastLog || 'Environment repair failed')+ setInstallPhase('error')+ }+ } catch { /* keep polling */ }+ }, 2000)+ } catch (err) {+ setInstallPhase('error')+ setInstallErr(err instanceof Error ? err.message : 'Failed to start the repair')+ }+ }+const handleStop = async () => {try {const { backendCall } = await import('../../api/backend')@@ -527,6 +572,14 @@ function ComfyUISettings() {Restart</button>)}+ {/* GH #98: a from-source install whose Python env broke (shared system+ Python, dead torch) needs a rebuild, not a re-install — pip reports+ broken packages as already satisfied. Rebuilds ComfyUI/venv. */}+ {status?.found && !status?.running && installPhase === 'idle' && (+ <button onClick={handleRepair} title="Rebuild the Python environment in an isolated venv (~2 GB). Models, outputs and custom nodes are left alone." className="px-2 py-1 rounded text-[0.6rem] bg-amber-500/10 text-amber-400 hover:bg-amber-500/20 transition-colors">+ Repair environment+ </button>+ )}{(!status?.found || status?.complete === false) && installPhase === 'idle' && (<buttononClick={async () => {@@ -657,6 +710,7 @@ function ComfyUISettings() {<span>{installPhase === 'python' && 'Installing Python 3.12 (~30 MB)…'}{installPhase === 'comfyui' && 'Installing ComfyUI…'}+ {installPhase === 'repair' && 'Rebuilding the ComfyUI environment…'}{installPhase === 'error' && 'Install failed'}</span></div>