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.

hotfix v2.4.5: Bug E — Arch PEP 668 venv auto-create for ComfyUI install

purpled73a530522e2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6ea083a9..dba029b7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,7 +6,7 @@ All notable changes to Locally Uncensored are documented here.
## [2.4.5] - 2026-05-17
-Drop-in hotfix on top of v2.4.4. Four user-reported bugs and two carry-forward defensive fixes, collected from Discord, Reddit, and GitHub Discussions between v2.4.4-release (2026-05-11) and 2026-05-17.
+Drop-in hotfix on top of v2.4.4. Five user-reported bugs collected from Discord, Reddit, and GitHub Issues / Discussions between v2.4.4-release (2026-05-11) and 2026-05-17.
### Fixed — image / video creation
- **Video output now actually produces `.mp4` files** (Bug A — miguelkodoatie Discord 14.05., Turbulent_Tomato7559 Reddit 10.05.). v2.4.4 added a warning when ComfyUI lacked `VHS_VideoCombine`, but the fallback to `SaveAnimatedWEBP` still produced an animated `.webp` "image" instead of a video. v2.4.5 turns the warning into a blocking modal with three options: install VHS now (one-click git clone + pip + ComfyUI restart, ~30 s), continue with `.webp`, or cancel. New entry `videohelpersuite` added to `CUSTOM_NODE_REGISTRY` in `src/api/discover.ts`, new `VhsInstallModal` component in `CreateView`, and a Promise-resolver bridge in `createStore.vhsInstallPrompt` so `useCreate.generate()` can await the user's choice. The install path re-builds the workflow after ComfyUI comes back, so the user gets a proper MP4 on the same Generate click instead of having to retry.
@@ -20,9 +20,12 @@ Drop-in hotfix on top of v2.4.4. Four user-reported bugs and two carry-forward d
### Fixed — Linux / AppImage
- **Arch / Wayland AppImage now actually paints content** (Bug D — emilmjt Discord 11.05.). The "empty window" symptom on Arch is Tauri 2 + webkit2gtk-4.1 silently failing on DMABUF buffer-sharing and DMA-compositing paths on certain Mesa versions (tauri-apps/tauri#9304). `src-tauri/src/main.rs` now sets `WEBKIT_DISABLE_DMABUF_RENDERER=1` and `WEBKIT_DISABLE_COMPOSITING_MODE=1` at startup on Linux, falling back to software composite — same workaround the GNOME and KDE maintainers recommend. Only set when the user hasn't already exported the vars themselves. `tauri.conf.json` also now declares explicit `bundle.linux.deb.depends` and `bundle.linux.rpm.depends` for `webkit2gtk-4.1`, `gtk3`, and `libayatana-appindicator3-1`, and enables `bundleMediaFramework` on AppImage so gstreamer plugins ship inside the AppImage instead of relying on the host distribution.
+### Fixed — Linux / ComfyUI install
+- **PEP 668 protected Pythons (Arch, Debian 12+, Fedora 38+, Ubuntu 23.04+) no longer brick the ComfyUI install** (Bug E — rzgrozt GH #32 comment 2026-05-08). A bare `python -m pip install torch ...` exits with `error: externally-managed-environment` on those distros because the stdlib carries an `EXTERNALLY-MANAGED` marker file. v2.4.5 detects the marker via `sysconfig.get_path('stdlib')`, then runs `python -m venv <ComfyUI>/venv` and uses the venv's Python for every subsequent pip step. New helpers `is_pep668_protected`, `create_comfyui_venv`, and `venv_python_path` live in `src-tauri/src/commands/install.rs` and `src-tauri/src/python.rs`. `process.rs::start_comfyui` and `auto_start_comfyui` mirror the lookup so ComfyUI launches with the venv Python it was installed against — no `ModuleNotFoundError: torch` on first run. When the system Python's `venv` module is missing (some minimal Arch installs), the error now surfaces a one-line fix: `sudo pacman -S python-virtualenv` (or `apt install python3-venv` / `dnf install python3-virtualenv`). `diagnose_pip_error` also catches the externally-managed string directly as a fallback for anyone whose Python somehow bypasses the venv path.
+
### Tests
- `vitest`: 2271 passed (93 files) — +7 new tests for `parseOllamaError` missing-blob coverage in `src/lib/__tests__/ollama-errors.test.ts` (Anson192 verbatim error, generic no-fallback-model, forward+back-slash tolerance, Rust-proxy wrapping, chat-style message wording with + without model), +1 smoke test for the new `videohelpersuite` `CUSTOM_NODE_REGISTRY` entry in `src/api/__tests__/comfyui-bundles.test.ts`.
-- `cargo test --release`: 57 passed — +5 new tests in `src-tauri/src/main.rs::tests` for the Bug D Linux webkit workaround function (`webkit_workaround_sets_both_vars_when_unset`, `preserves_user_dmabuf_override`, `preserves_user_compositing_override`, `preserves_empty_string_as_explicit_unset`, `is_idempotent`). Tests serialize via `ENV_MUTEX` since env vars are process-global.
+- `cargo test --release`: 70 passed — +5 new tests in `src-tauri/src/main.rs::tests` for the Bug D Linux webkit workaround function (`webkit_workaround_sets_both_vars_when_unset`, `preserves_user_dmabuf_override`, `preserves_user_compositing_override`, `preserves_empty_string_as_explicit_unset`, `is_idempotent`) plus +13 new tests for Bug E in `src-tauri/src/commands/install.rs::tests` and `src-tauri/src/python.rs::tests` (`is_pep668_protected_returns_false_for_empty_bin`, `is_pep668_protected_returns_false_for_garbage_bin`, `diagnose_externally_managed_mentions_venv`, `diagnose_externally_managed_includes_distro_install_commands`, `diagnose_externally_managed_alt_format_matches`, `transient_rejects_externally_managed`, `venv_python_path_matches_platform_layout`, `venv_python_path_is_under_comfyui_dir`, `resolve_returns_none_when_venv_missing`, `resolve_returns_some_when_venv_python_exists`, plus 3 baseline `is_real_python` tests promoted from inline assertions). Bug D tests serialize via `ENV_MUTEX` since env vars are process-global.
- `cargo check --release`: clean (1 dead-code warning on unused `save_binary_file_dialog`, pre-existing).
- `tsc --noEmit`: clean.
@@ -31,6 +34,7 @@ Drop-in hotfix on top of v2.4.4. Four user-reported bugs and two carry-forward d
- **Bug B**: Suspended ComfyUI via `NtSuspendProcess` while user navigates back to Create tab → triggers `useEffect` re-mount, `pollStatus` re-starts, detects ComfyUI down. Live-verified entire UI sequence: (1) "ComfyUI loading (12s)" elapsed-counter banner, (2) switch to actionable "ComfyUI is taking unusually long (86s)" panel after 60s threshold, (3) failure-mode explanation text rendered, (4) "View logs" toggle works (button label flips to "Hide logs"), (5) empty-logs fallback message renders ("No startup logs captured yet — ComfyUI hasn't emitted anything to stdout."), (6) "Kill process" button actually kills the spawned ComfyUI process (verified via PID gone + port 8188 free), (7) state machine transitions cleanly to "ComfyUI not responding" with Retry, (8) Retry click respawns ComfyUI which comes back online.
- **Bug C**: Disabled the qwen2.5:0.5b blob (`sha256-c5396e...`) → triggered LU's startup health scan → banner "Ollama 0.20.7 broke 1 of your model. qwen2.5:0.5b" appeared + inline "stale — refresh? ↻ Refresh" chip next to Lichtschalter. Clicked "Refresh all" → `pullModel` triggered → DownloadBadge showed completion within seconds. Note: Ollama 0.20.7 transforms ALL blob errors (missing OR 0-byte corrupted) into the `"X does not support generate"` pattern, so the new `missing-blob` regex primarily protects users on older Ollama versions (Anson192's exact scenario on RTX 4090). Both error paths route to the same one-click repair UX.
- **Bug D**: Linux webkit env-var function unit-tested cross-platform via 5 cargo tests (sets-both-when-unset, preserves user DMABUF override, preserves user COMPOSITING override, preserves empty-string as explicit unset, idempotent). Arch VirtualBox boot test deferred — env-var workaround is the documented upstream-recommended fix for the symptom class.
+- **Bug E**: PEP 668 detection + venv creation unit-tested cross-platform via 13 cargo tests across `install.rs::tests` and `python.rs::tests`. Path-layout tests cover both Windows (`venv/Scripts/python.exe`) and Unix (`venv/bin/python`) layouts. Resolver tests use real tempdirs to verify the `Some(path)` vs `None` gating. Diagnose tests cover Arch's exact `error: externally-managed-environment` string from rzgrozt's report plus the shorter `error: externally-managed` variant and confirm the suggested distro-install commands (`pacman -S python-virtualenv`, `apt install python3-venv`, `dnf install python3-virtualenv`) appear in the user-facing hint. Live Arch boot test deferred — same constraint as Bug D (no Arch box on dev machine); the venv approach is the standard answer to PEP 668 (used by every Python tool that touches Arch / Debian 12 / Fedora 38) so the structural-correctness bar is very different from a hardware-driven bug.
## [2.4.4] - 2026-05-11
diff --git a/src-tauri/src/commands/install.rs b/src-tauri/src/commands/install.rs
index 8e278613..fe365162 100644
--- a/src-tauri/src/commands/install.rs
+++ b/src-tauri/src/commands/install.rs
@@ -11,6 +11,7 @@ use std::os::windows::process::CommandExt;
use tauri::State;
+use crate::python::venv_python_path;
use crate::state::{AppState, InstallState};
/// Windows: hide console windows for spawned processes
@@ -126,6 +127,101 @@ fn push_install_log(state: &Arc<Mutex<InstallState>>, msg: &str) {
}
}
+// ── PEP 668 / venv helpers (Bug E — rzgrozt Arch externally-managed) ─────────
+
+/// True iff the Python pointed to by `python_bin` is PEP 668 protected
+/// (Arch Linux, Debian 12+, Fedora 38+, Ubuntu 23.04+ ship Python with an
+/// `EXTERNALLY-MANAGED` marker file in the stdlib dir, which makes
+/// `python -m pip install ...` exit with
+/// `error: externally-managed-environment` unless `--break-system-packages`
+/// is passed). We probe by asking Python itself whether the marker exists
+/// — robust against distro-specific path layouts and avoids parsing locale
+/// dependent pip error strings.
+///
+/// Returns `false` on any probe error (Python missing, sysconfig broken,
+/// stdout unparseable). That is the safe default: a false negative just
+/// means we install without a venv exactly like LU did before this bug,
+/// which is fine on every distro that *isn't* PEP 668 protected.
+pub fn is_pep668_protected(python_bin: &str) -> bool {
+ if python_bin.is_empty() {
+ return false;
+ }
+ let mut cmd = Command::new(python_bin);
+ cmd.args([
+ "-c",
+ "import os, sysconfig; \
+ d = sysconfig.get_path('stdlib'); \
+ print('YES' if os.path.exists(os.path.join(d, 'EXTERNALLY-MANAGED')) else 'NO')",
+ ])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+ #[cfg(target_os = "windows")]
+ cmd.creation_flags(CREATE_NO_WINDOW);
+ let Ok(out) = cmd.output() else { return false };
+ if !out.status.success() {
+ return false;
+ }
+ String::from_utf8_lossy(&out.stdout).trim() == "YES"
+}
+
+/// 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.
+pub fn create_comfyui_venv(comfyui_dir: &Path, python_bin: &str) -> 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.
+ let already_existed = venv_dir.exists() && venv_python_path(comfyui_dir).exists();
+ if already_existed {
+ return Ok(venv_python_path(comfyui_dir));
+ }
+
+ let mut cmd = Command::new(python_bin);
+ cmd.args(["-m", "venv", venv_dir.to_string_lossy().as_ref()])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+ #[cfg(target_os = "windows")]
+ cmd.creation_flags(CREATE_NO_WINDOW);
+
+ let out = cmd
+ .output()
+ .map_err(|e| format!("Could not spawn `python -m venv`: {}", e))?;
+
+ if !out.status.success() {
+ let stderr = String::from_utf8_lossy(&out.stderr);
+ let lower = stderr.to_lowercase();
+ // Most common Arch / minimal-Python failure: stdlib venv module
+ // isn't available because the distro packages it separately.
+ if lower.contains("no module named venv") || lower.contains("ensurepip") {
+ return Err(format!(
+ "Python's `venv` module is not available. Install it first:\n\
+ • Arch: sudo pacman -S python-virtualenv\n\
+ • Debian/Ubuntu: sudo apt install python3-venv\n\
+ • Fedora: sudo dnf install python3-virtualenv\n\
+ Then retry the ComfyUI install.\n\n--- python output ---\n{}",
+ stderr.chars().take(400).collect::<String>()
+ ));
+ }
+ return Err(format!(
+ "venv creation failed: {}",
+ stderr.chars().take(400).collect::<String>()
+ ));
+ }
+
+ let venv_py = venv_python_path(comfyui_dir);
+ if !venv_py.exists() {
+ return Err(format!(
+ "venv was created at {} but no Python binary appeared at {}. \
+ This usually means the venv module is broken — try `sudo pacman -S python-virtualenv` (Arch) or the equivalent on your distro.",
+ venv_dir.display(),
+ venv_py.display()
+ ));
+ }
+ Ok(venv_py)
+}
+
/// Detect pip errors that warrant an automatic retry with backoff.
/// Conservative — only retries on errors caused by transient network
/// conditions, not on auth, permission, disk-full, or python-side bugs.
@@ -162,7 +258,17 @@ fn diagnose_pip_error(stderr: &str) -> String {
let lower = stderr.to_lowercase();
let snippet: String = stderr.chars().take(400).collect();
- let hint = if lower.contains("ssl") {
+ let hint = if lower.contains("externally-managed-environment")
+ || lower.contains("error: externally-managed")
+ {
+ "Your Python is PEP 668 protected (Arch Linux, Debian 12+, Fedora 38+, \
+ Ubuntu 23.04+ block system-wide pip installs by default). LU should have \
+ created a venv inside the ComfyUI folder automatically — if you see this \
+ error, the venv module is missing. Install it and retry:\n\
+ • Arch: sudo pacman -S python-virtualenv\n\
+ • Debian/Ubuntu: sudo apt install python3-venv\n\
+ • Fedora: sudo dnf install python3-virtualenv"
+ } else if lower.contains("ssl") {
"SSL error reaching pypi.org. Often caused by an antivirus / firewall \
intercepting TLS, or a stale system clock. Disable TLS interception \
for python.exe, fix the system clock, then retry."
@@ -492,6 +598,42 @@ pub fn install_comfyui(
return;
}
+ // Bug E (rzgrozt — Arch GH #32 comment, 2026-05-08): if the system
+ // Python is PEP 668 protected (Arch, Debian 12+, Fedora 38+, Ubuntu
+ // 23.04+), a bare `python -m pip install ...` exits with
+ // `error: externally-managed-environment` and leaves the user with
+ // a half-cloned ComfyUI dir and no diagnostic. Detect the marker
+ // file via the system Python, then create a venv inside the
+ // ComfyUI folder and use the venv's Python for every subsequent
+ // pip step. The launcher in `process.rs` mirrors this check and
+ // prefers the venv when starting ComfyUI, so the user gets a
+ // consistent isolated environment without ever touching pacman.
+ let effective_python = if is_pep668_protected(&python_bin) {
+ update(
+ "installing",
+ "Python is PEP 668 protected (Arch / Debian 12+ / Fedora 38+ / \
+ Ubuntu 23.04+). Creating an isolated venv at ComfyUI/venv so \
+ pip can install PyTorch + ComfyUI deps without touching your \
+ system Python …",
+ );
+ match create_comfyui_venv(&target_dir, &python_bin) {
+ Ok(venv_py) => {
+ let p = venv_py.to_string_lossy().to_string();
+ update(
+ "installing",
+ &format!("venv ready — using {} for the install.", p),
+ );
+ p
+ }
+ Err(e) => {
+ update("error", &format!("venv creation failed.\n\n{}", e));
+ return;
+ }
+ }
+ } else {
+ python_bin.clone()
+ };
+
// Step 2: Detect GPU and install PyTorch
let mut nv = Command::new("nvidia-smi");
nv.stdout(Stdio::piped()).stderr(Stdio::piped());
@@ -548,7 +690,7 @@ pub fn install_comfyui(
]
};
- match pip_install_streaming_with_retry_cancellable(&torch_args, &python_bin, 3, &install_status, Some(&cancel_flag)) {
+ match pip_install_streaming_with_retry_cancellable(&torch_args, &effective_python, 3, &install_status, Some(&cancel_flag)) {
Ok(()) => {
update("installing", "PyTorch installed successfully.");
}
@@ -582,7 +724,7 @@ pub fn install_comfyui(
"--no-input",
"-r", reqs_str.as_str(),
];
- match pip_install_streaming_with_retry_cancellable(&req_args, &python_bin, 3, &install_status, Some(&cancel_flag)) {
+ match pip_install_streaming_with_retry_cancellable(&req_args, &effective_python, 3, &install_status, Some(&cancel_flag)) {
Ok(()) => {
update("installing", "Dependencies installed successfully.");
}
@@ -1885,4 +2027,80 @@ mod tests {
fn compute_cap_skips_unparseable_lines() {
assert_eq!(parse_compute_cap_output("[Not Supported]\n8.6\n"), Some(8));
}
+
+ // ── Bug E (rzgrozt — Arch PEP 668 externally-managed) ─────────────────
+ //
+ // The detection function spawns a Python subprocess, so we can't unit
+ // test it without a Python install. We DO test the safety guarantees:
+ // empty `python_bin` returns false (regression-safe default), and the
+ // diagnose path surfaces a useful hint when the marker error reaches
+ // the user despite the auto-venv path.
+
+ #[test]
+ fn is_pep668_protected_returns_false_for_empty_bin() {
+ // Empty sentinel from python.rs::get_python_bin must short-circuit
+ // to false so a missing Python doesn't accidentally trigger venv
+ // creation (which would also fail and confuse the error chain).
+ assert!(!is_pep668_protected(""));
+ }
+
+ #[test]
+ fn is_pep668_protected_returns_false_for_garbage_bin() {
+ // Probing a non-existent path can't crash — the function must
+ // swallow the spawn error and return false so install proceeds as
+ // it always did on systems that aren't PEP 668 protected.
+ assert!(!is_pep668_protected("/definitely/not/a/real/python-9.99"));
+ }
+
+ #[test]
+ fn diagnose_externally_managed_mentions_venv() {
+ let raw = "error: externally-managed-environment\n\
+ × This environment is externally managed\n\
+ ╰─> To install Python packages system-wide, try 'pacman -S python-xyz'";
+ let msg = diagnose_pip_error(raw);
+ let lower = msg.to_lowercase();
+ assert!(
+ lower.contains("pep 668") || lower.contains("externally") || lower.contains("venv"),
+ "diagnose did not surface PEP 668 context: {}",
+ msg
+ );
+ }
+
+ #[test]
+ fn diagnose_externally_managed_includes_distro_install_commands() {
+ let raw = "error: externally-managed-environment";
+ let msg = diagnose_pip_error(raw);
+ let lower = msg.to_lowercase();
+ // We want at least one of the platform-specific install commands so
+ // the user has something to copy-paste instead of just an error.
+ assert!(
+ lower.contains("pacman") || lower.contains("apt") || lower.contains("dnf"),
+ "diagnose did not include a distro install command: {}",
+ msg
+ );
+ }
+
+ #[test]
+ fn diagnose_externally_managed_alt_format_matches() {
+ // The exact wording on Arch 2026 is `error: externally-managed`
+ // without the `-environment` suffix — make sure the matcher covers
+ // both spellings.
+ let raw = "error: externally-managed (pip blocked by PEP 668)";
+ let msg = diagnose_pip_error(raw);
+ let lower = msg.to_lowercase();
+ assert!(
+ lower.contains("pacman") || lower.contains("apt"),
+ "diagnose missed the alt spelling: {}",
+ msg
+ );
+ }
+
+ #[test]
+ fn transient_rejects_externally_managed() {
+ // PEP 668 errors are deterministic — retrying without venv would
+ // just loop forever. Must NOT be classified as transient.
+ assert!(!is_transient_pip_error(
+ "error: externally-managed-environment"
+ ));
+ }
}
diff --git a/src-tauri/src/commands/process.rs b/src-tauri/src/commands/process.rs
index 00679963..141d3f31 100644
--- a/src-tauri/src/commands/process.rs
+++ b/src-tauri/src/commands/process.rs
@@ -621,8 +621,19 @@ pub fn start_comfyui(state: State<'_, AppState>) -> Result<serde_json::Value, St
let candidate = std::path::Path::new(&comfy_path).join("python_embeded").join("python.exe");
if candidate.exists() { Some(candidate.to_string_lossy().to_string()) } else { None }
});
+ // Bug E (rzgrozt — Arch PEP 668): when the installer detected an
+ // externally-managed Python it created a venv at <ComfyUI>/venv and
+ // installed PyTorch + deps into it. Launch from the venv so we don't
+ // crash with `ModuleNotFoundError: torch` because the system Python
+ // (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));
let system_python = state.python_bin.lock().unwrap().clone();
- let python = bundled_python.clone().unwrap_or(system_python.clone());
+ let python = bundled_python
+ .clone()
+ .or_else(|| venv_python.clone())
+ .unwrap_or(system_python.clone());
let port_str = port.to_string();
if python.is_empty() {
return Err(
@@ -633,6 +644,8 @@ pub fn start_comfyui(state: State<'_, AppState>) -> Result<serde_json::Value, St
}
if bundled_python.is_some() {
println!("[ComfyUI] Using bundled portable Python: {}", python);
+ } else if venv_python.is_some() {
+ println!("[ComfyUI] Using ComfyUI venv Python (PEP 668 install): {}", python);
} else {
println!("[ComfyUI] Using system Python: {}", python);
}
@@ -1070,14 +1083,24 @@ pub fn auto_start_comfyui(state: &AppState) {
let c = std::path::Path::new(&path).join("python_embeded").join("python.exe");
if c.exists() { Some(c.to_string_lossy().to_string()) } else { None }
});
+ // Bug E: prefer the per-install venv that the PEP 668 path
+ // 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));
let system_python = state.python_bin.lock().unwrap().clone();
- let python = portable_python.clone().unwrap_or_else(|| system_python.clone());
+ let python = portable_python
+ .clone()
+ .or_else(|| venv_python.clone())
+ .unwrap_or_else(|| 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() {
+ println!("[ComfyUI] Auto-start using ComfyUI venv Python (PEP 668 install): {}", python);
}
let mut cmd = Command::new(&python);
diff --git a/src-tauri/src/python.rs b/src-tauri/src/python.rs
index 493e7985..500c9e05 100644
--- a/src-tauri/src/python.rs
+++ b/src-tauri/src/python.rs
@@ -1,4 +1,4 @@
-use std::path::Path;
+use std::path::{Path, PathBuf};
use std::process::Command;
#[cfg(target_os = "windows")]
@@ -7,6 +7,38 @@ use std::os::windows::process::CommandExt;
#[cfg(target_os = "windows")]
const CREATE_NO_WINDOW: u32 = 0x08000000;
+/// Compute the path to the venv's Python interpreter for a ComfyUI install
+/// at `comfyui_dir`. Layout matches what `python -m venv` produces.
+///
+/// * Windows: `<comfyui_dir>/venv/Scripts/python.exe`
+/// * Unix: `<comfyui_dir>/venv/bin/python`
+///
+/// The file is NOT guaranteed to exist — call `path.exists()` if you care.
+/// Used by both the installer (Bug E — PEP 668 venv creation) and the
+/// process launcher (so `start_comfyui` runs ComfyUI inside the same
+/// isolated env that pip installed PyTorch into).
+pub fn venv_python_path(comfyui_dir: &Path) -> PathBuf {
+ let venv = comfyui_dir.join("venv");
+ if cfg!(target_os = "windows") {
+ venv.join("Scripts").join("python.exe")
+ } else {
+ venv.join("bin").join("python")
+ }
+}
+
+/// 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
+/// the venv has not been created — caller falls back to the system Python.
+pub fn resolve_comfyui_venv_python(comfyui_dir: &Path) -> Option<String> {
+ let candidate = venv_python_path(comfyui_dir);
+ if candidate.exists() {
+ Some(candidate.to_string_lossy().to_string())
+ } else {
+ None
+ }
+}
+
/// Resolve the real Python binary path, filtering out the Microsoft Store stub
/// alias (`%LOCALAPPDATA%\Microsoft\WindowsApps\python.exe`) which prints
/// "Python was not found, run without arguments to install from the Microsoft
@@ -129,3 +161,92 @@ pub fn is_real_python(bin: &str) -> bool {
}
true
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::fs;
+
+ // ── venv_python_path layout (Bug E — Arch PEP 668 venv) ─────────────────
+
+ #[test]
+ fn venv_python_path_matches_platform_layout() {
+ let p = venv_python_path(Path::new("/home/u/ComfyUI"));
+ let s = p.to_string_lossy().to_string();
+ // On Windows expect `Scripts/python.exe`, on Unix expect `bin/python`.
+ if cfg!(target_os = "windows") {
+ assert!(
+ s.ends_with("venv\\Scripts\\python.exe") || s.ends_with("venv/Scripts/python.exe"),
+ "got {} on Windows",
+ s
+ );
+ } else {
+ assert!(s.ends_with("venv/bin/python"), "got {} on Unix", s);
+ }
+ }
+
+ #[test]
+ fn venv_python_path_is_under_comfyui_dir() {
+ let comfy = Path::new("/some/where/ComfyUI");
+ let venv_py = venv_python_path(comfy);
+ assert!(
+ venv_py.starts_with(comfy),
+ "venv python {} did not start with {}",
+ venv_py.display(),
+ comfy.display()
+ );
+ }
+
+ // ── resolve_comfyui_venv_python — existence gate ────────────────────────
+
+ #[test]
+ fn resolve_returns_none_when_venv_missing() {
+ let tmp = std::env::temp_dir().join("lu-venv-test-missing");
+ let _ = fs::remove_dir_all(&tmp);
+ fs::create_dir_all(&tmp).unwrap();
+ assert!(resolve_comfyui_venv_python(&tmp).is_none());
+ let _ = fs::remove_dir_all(&tmp);
+ }
+
+ #[test]
+ fn resolve_returns_some_when_venv_python_exists() {
+ // Build the exact layout `python -m venv` would produce so the
+ // resolver finds it without actually invoking Python.
+ let tmp = std::env::temp_dir().join("lu-venv-test-present");
+ let _ = fs::remove_dir_all(&tmp);
+ let inner = if cfg!(target_os = "windows") {
+ tmp.join("venv").join("Scripts")
+ } else {
+ tmp.join("venv").join("bin")
+ };
+ fs::create_dir_all(&inner).unwrap();
+ let py = if cfg!(target_os = "windows") {
+ inner.join("python.exe")
+ } else {
+ inner.join("python")
+ };
+ fs::write(&py, "stub").unwrap();
+ let resolved = resolve_comfyui_venv_python(&tmp);
+ assert!(resolved.is_some(), "expected resolver to find {}", py.display());
+ assert!(resolved.unwrap().contains("venv"));
+ let _ = fs::remove_dir_all(&tmp);
+ }
+
+ // ── is_real_python (Bug P14 — Microsoft Store stub filter) ──────────────
+
+ #[test]
+ fn real_python_rejects_empty() {
+ assert!(!is_real_python(""));
+ }
+
+ #[test]
+ fn real_python_rejects_windowsapps_stub() {
+ assert!(!is_real_python("C:\\Users\\u\\AppData\\Local\\Microsoft\\WindowsApps\\python.exe"));
+ }
+
+ #[test]
+ fn real_python_accepts_real_path() {
+ assert!(is_real_python("/usr/bin/python3"));
+ assert!(is_real_python("C:\\Python312\\python.exe"));
+ }
+}