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(install): LU picks the torch-compatible interpreter itself (B1)
purpleb75a1323e82f
diff --git a/src-tauri/src/commands/install/comfy_install.rs b/src-tauri/src/commands/install/comfy_install.rsindex 6eb34d9f..e891ba74 100644--- a/src-tauri/src/commands/install/comfy_install.rs+++ b/src-tauri/src/commands/install/comfy_install.rs@@ -466,6 +466,16 @@ pub fn install_comfyui(}crate::python::ComfyVenv::Absent => None,};++ // Step 2's GPU probe + wheel choice, pulled up here (Runde 3,+ // Nachbesserung 6): a venv must never be built from an interpreter+ // the preflight below is about to reject, so the channel has to be+ // known BEFORE any venv decision, not after. `plan_pytorch_install`+ // does not touch disk or venv state, only nvidia-smi/GPU facts, so+ // moving it earlier is free.+ let (torch_args, gpu_info, torch_index, torch_packages) = plan_pytorch_install();+ let torch_package_refs: Vec<&str> = torch_packages.iter().map(|s| s.as_str()).collect();+let effective_python = if let Some(venv_py) = existing_venv {update("installing",@@ -473,56 +483,70 @@ pub fn install_comfyui("This ComfyUI already has its own environment. Installing into {venv_py}."),);+ // An existing venv is not silently rebuilt here (it may carry+ // custom nodes' own state): B1(b)'s auto-selection is for a+ // venv this run is about to build, not one that already exists.venv_py- } else 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, Some(&cancel_flag)) {- Ok(venv_py) => {- let p = venv_py.to_string_lossy().to_string();+ } else {+ // B1(b): LU picks the interpreter itself, no Settings picker.+ // Runs BEFORE `create_comfyui_venv`/PEP-668 detection so a+ // healthy choice never gets discarded for one that cannot serve+ // torch (Nachbesserung 6).+ let chosen_python = match super::torch::choose_torch_python(&python_bin, torch_index.as_deref(), &torch_package_refs) {+ super::torch::TorchPythonDecision::Proceed => python_bin.clone(),+ super::torch::TorchPythonDecision::UseInstead(p) => {update("installing",- &format!("venv ready, using {} for the install.", p),+ &format!(+ "The default Python ({python_bin}) does not have a PyTorch wheel for \+ this machine yet; using {p} instead, found on this machine already."+ ),);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.");+ super::torch::TorchPythonDecision::Blocked(msg) => {+ update("error", &msg);return;}- Err(e) => {- update("error", &format!("venv creation failed.\n\n{}", e));- return;+ };+ if is_pep668_protected(&chosen_python) {+ 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, &chosen_python, Some(&cancel_flag)) {+ Ok(venv_py) => {+ let p = venv_py.to_string_lossy().to_string();+ update(+ "installing",+ &format!("venv ready, using {} for the install.", p),+ );+ 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;+ }}+ } else {+ chosen_python}- } else {- python_bin.clone()};- // Step 2: Detect GPU and install PyTorch (probe + wheel choice shared- // with repair_comfyui_env via plan_pytorch_install).- let (torch_args, gpu_info, torch_index, torch_packages) = plan_pytorch_install();println!("[Install] {}", gpu_info);update("installing", &format!("Step 2/4: {}", gpu_info));- // Runde 2, Nachbesserung 12: before spending 2 GB and several minutes- // on a download pip would refuse anyway, check whether this Python- // is even on the chosen channel's version list.- let torch_package_refs: Vec<&str> = torch_packages.iter().map(|s| s.as_str()).collect();- if let Some(msg) = super::torch::torch_python_preflight(&effective_python, torch_index.as_deref(), &torch_package_refs) {- update("error", &msg);- return;- }-update("installing","Downloading PyTorch + Torchvision + Torchaudio (~2 GB total). \diff --git a/src-tauri/src/commands/install/comfy_repair.rs b/src-tauri/src/commands/install/comfy_repair.rsindex c9ce1e40..a92b67dc 100644--- a/src-tauri/src/commands/install/comfy_repair.rs+++ b/src-tauri/src/commands/install/comfy_repair.rs@@ -179,6 +179,38 @@ pub fn repair_comfyui_env(state: State<'_, AppState>) -> Result<serde_json::Valuupdate("installing", &warning);}+ // Runde 3, Nachbesserung 6: the torch/Python preflight used to run+ // AFTER the old venv was already gone (`torch_python_preflight` sat+ // right before Step 2's download, well past the delete below). A+ // repair that then turned out to have no usable interpreter left the+ // customer with a freshly emptied venv folder and a failed run, the+ // exact "a healthy venv must never be destroyed for a run that then+ // fails anyway" case. Moving the check here, before `venv_dir` is+ // touched at all, means a repair that cannot proceed leaves the old+ // venv exactly as it was. Also folds in B1(b): LU picks the newest+ // interpreter that actually has a torch wheel itself, no Settings+ // picker, and the picked interpreter is what builds the new venv+ // further down instead of always `python_bin`.+ let (torch_args, gpu_info, torch_index, torch_packages) = plan_pytorch_install();+ let torch_package_refs: Vec<&str> = torch_packages.iter().map(|s| s.as_str()).collect();+ let chosen_python = match super::torch::choose_torch_python(&python_bin, torch_index.as_deref(), &torch_package_refs) {+ super::torch::TorchPythonDecision::Proceed => python_bin.clone(),+ super::torch::TorchPythonDecision::UseInstead(p) => {+ update(+ "installing",+ &format!(+ "The default Python ({python_bin}) does not have a PyTorch wheel for \+ this machine yet; using {p} instead, found on this machine already."+ ),+ );+ p+ }+ super::torch::TorchPythonDecision::Blocked(msg) => {+ update("error", &msg);+ return;+ }+ };+// 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.@@ -301,7 +333,7 @@ pub fn repair_comfyui_env(state: State<'_, AppState>) -> Result<serde_json::Valu"installing","Step 1/4: Creating a fresh isolated venv inside the ComfyUI folder...",);- let venv_py = match create_comfyui_venv(&comfy_dir, &python_bin, Some(&cancel_flag)) {+ let venv_py = match create_comfyui_venv(&comfy_dir, &chosen_python, 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.");@@ -340,17 +372,8 @@ pub fn repair_comfyui_env(state: State<'_, AppState>) -> Result<serde_json::Valulet _ = deleting.join();}- let (torch_args, gpu_info, torch_index, torch_packages) = plan_pytorch_install();update("installing", &format!("Step 2/4: {}", gpu_info));- // Runde 2, Nachbesserung 12: same preflight as the first install,- // before the repair spends 2 GB on a download that cannot land.- let torch_package_refs: Vec<&str> = torch_packages.iter().map(|s| s.as_str()).collect();- if let Some(msg) = super::torch::torch_python_preflight(&venv_py, torch_index.as_deref(), &torch_package_refs) {- update("error", &msg);- return;- }-update("installing","Downloading PyTorch into the fresh venv (~2 GB). Live pip output below.",diff --git a/src-tauri/src/commands/install/torch.rs b/src-tauri/src/commands/install/torch.rsindex 5627b518..4ed13569 100644--- a/src-tauri/src/commands/install/torch.rs+++ b/src-tauri/src/commands/install/torch.rs@@ -220,63 +220,129 @@ fn fetch_index_python_versions(index_url: Option<&str>, package: &str) -> ResultOk(python_versions_from_index_html(&html))}-/// One line per interpreter found on the box, for the "here is what LU can-/// see instead" half of the preflight message.-fn interpreter_inventory_lines() -> Vec<String> {+/// One `(path, version)` pair per interpreter `python_interpreters()` found,+/// the version resolved eagerly so both the picker and the message below+/// read it once instead of re-spawning each interpreter a second time.+fn interpreter_inventory() -> Vec<(String, Option<(u32, u32)>)> {crate::python::python_interpreters().into_iter()- .map(|path| match python_version_tuple(&path) {+ .map(|path| {+ let v = python_version_tuple(&path);+ (path, v)+ })+ .collect()+}++fn format_interpreter_lines(interpreters: &[(String, Option<(u32, u32)>)]) -> String {+ if interpreters.is_empty() {+ return " (none found)".to_string();+ }+ interpreters+ .iter()+ .map(|(path, v)| match v {Some((maj, min)) => format!(" - {path} (Python {maj}.{min})"),None => format!(" - {path} (version unknown)"),})- .collect()+ .collect::<Vec<_>>()+ .join("\n")}-/// Runs right before the real `pip install` for PyTorch. `None` means-/// proceed; `Some(message)` means the venv's Python is not on the channel-/// `plan_pytorch_install` chose and pip's own generic "no matching-/// distribution" would send the user chasing a PATH or proxy problem that-/// does not exist.-///-/// Fails OPEN on anything it cannot establish (offline, index unreachable,-/// version probe failed): a preflight that blocks installs whenever the-/// network hiccups is worse than the gap it closes. This is the "was du-/// ohne Netz nicht messen kannst, als solches markieren" rule applied to a-/// live check instead of a written report: the honest answer to "can I-/// tell" is sometimes "no", and the function returns exactly that as-/// `None`, not a false pass dressed up as a positive one.-pub(crate) fn torch_python_preflight(python_bin: &str, index_url: Option<&str>, packages: &[&str]) -> Option<String> {- let (maj, min) = python_version_tuple(python_bin)?;+/// Runde 3, B1: the newest interpreter this machine has for which the live+/// index actually serves a wheel, among the ones `python_interpreters`+/// found; `None` when nothing qualifies. Pure over an already-resolved+/// inventory so it is testable without spawning anything.+pub(crate) fn pick_newest_supported_interpreter(+ interpreters: &[(String, Option<(u32, u32)>)],+ supported: &std::collections::BTreeSet<(u32, u32)>,+) -> Option<String> {+ interpreters+ .iter()+ .filter_map(|(path, v)| v.filter(|v| supported.contains(v)).map(|v| (v, path.clone())))+ .max_by_key(|(v, _)| *v)+ .map(|(_, path)| path)+}++/// The honest end of B1(c): no Settings claim (there is no picker), no+/// invented button. States what was found, what torch actually serves today+/// (from the live query, never a hardcoded table), and a concrete next step+/// that does not name a distro package this code never verified: `uv+/// python install` and `pyenv install` are cross-distro and both take the+/// exact version string already in hand. `python312`-style package names are+/// deliberately NOT suggested: on Arch that name is in the AUR, not pacman,+/// and no other distro's naming was checked either.+pub(crate) fn no_compatible_interpreter_message(+ current: (u32, u32),+ interpreters: &[(String, Option<(u32, u32)>)],+ supported: &std::collections::BTreeSet<(u32, u32)>,+) -> String {+ let mut versions: Vec<String> = supported.iter().map(|(a, b)| format!("{a}.{b}")).collect();+ versions.sort();+ let newest = versions.last().cloned().unwrap_or_else(|| "a supported version".to_string());+ format!(+ "This environment's Python is {maj}.{min}, and the PyTorch build LU needs for this \+ machine currently ships wheels only for Python {versions_joined}. LU checked every \+ Python interpreter it could find on this machine and none of them is on that list, so \+ it cannot pick one for you automatically.\n\n\+ Python interpreters LU found:\n{interpreters_block}\n\n\+ Install one of the versions above, for example \"uv python install {newest}\" (uv finds \+ it on its own after that) or \"pyenv install {newest}\" if you use pyenv - not a \+ distro package name, those are not verified here and vary by distro (python312, for \+ example, is on Arch's AUR, not in pacman). Once a supported interpreter is on this \+ machine, press Repair again; LU finds it and uses it automatically, nothing else to \+ configure.",+ maj = current.0,+ min = current.1,+ versions_joined = versions.join(", "),+ interpreters_block = format_interpreter_lines(interpreters),+ newest = newest,+ )+}++/// What the caller should do about the venv it is about to build (or is+/// already using) for the PyTorch install.+pub(crate) enum TorchPythonDecision {+ /// This interpreter serves torch fine, or the check could not be made+ /// (offline, index unreachable, version probe failed) and therefore+ /// fails open rather than blocking on a network hiccup, same rule as+ /// the old `torch_python_preflight` documented.+ Proceed,+ /// A DIFFERENT interpreter this machine already has serves torch and+ /// `current` does not; the caller should build (or rebuild) the venv+ /// from this path instead: B1(b), no Settings picker, LU decides.+ UseInstead(String),+ /// Nothing on this machine serves torch for the chosen channel. The+ /// message is ready to show as-is.+ Blocked(String),+}++/// Runde 3, B1: replaces the old report-only `torch_python_preflight`. Where+/// that function only ever said "this is broken, here is what LU found",+/// this one first asks whether something ELSE LU found would work, and only+/// falls back to the message when nothing does: the Sackgasse Opus found+/// (Runde 2 left the customer at a Settings picker that does not exist).+pub(crate) fn choose_torch_python(current_python: &str, index_url: Option<&str>, packages: &[&str]) -> TorchPythonDecision {+ let Some(current) = python_version_tuple(current_python) else {+ return TorchPythonDecision::Proceed;+ };+ let Some(first_package) = packages.first() else {+ return TorchPythonDecision::Proceed;+ };// The AMD Windows channel serves "torch[device-all]"; strip any extra so// the index lookup is against the real package directory.- let package = packages.first()?.split('[').next().unwrap_or("torch");+ let package = first_package.split('[').next().unwrap_or("torch");let supported = match fetch_index_python_versions(index_url, package) {Ok(s) if !s.is_empty() => s,// Empty or unreachable: cannot tell, so do not block (see doc above).- _ => return None,+ _ => return TorchPythonDecision::Proceed,};- if supported.contains(&(maj, min)) {- return None;+ if supported.contains(¤t) {+ return TorchPythonDecision::Proceed;+ }+ let interpreters = interpreter_inventory();+ match pick_newest_supported_interpreter(&interpreters, &supported) {+ Some(path) => TorchPythonDecision::UseInstead(path),+ None => TorchPythonDecision::Blocked(no_compatible_interpreter_message(current, &interpreters, &supported)),}- let mut versions: Vec<String> = supported.iter().map(|(a, b)| format!("{a}.{b}")).collect();- versions.sort();- let interpreters = interpreter_inventory_lines();- let interpreters_block = if interpreters.is_empty() {- " (none found)".to_string()- } else {- interpreters.join("\n")- };- Some(format!(- "This environment's Python is {maj}.{min}, and the PyTorch build LU needs for this \- machine currently ships wheels only for Python {versions}. Installing torch would \- fail with a generic pip error, so LU is stopping before that and offering to rebuild \- the virtual environment with a supported interpreter instead - your models and custom \- nodes are untouched either way, only the venv folder is recreated.\n\n\- Python interpreters LU found on this machine:\n{interpreters_block}\n\n\- Pick one of the versions above in Settings and press Repair, or install a supported \- Python and press Repair again.",- versions = versions.join(", "),- ))}#[cfg(test)]@@ -472,4 +538,84 @@ mod tests {let html = r#"<a href="/cp312/some-other-thing">not a wheel</a>"#;assert!(python_versions_from_index_html(html).is_empty());}++ // ── Runde 3, B1: auto-selection instead of a Settings picker ────────++ fn supported_3_10_through_13() -> std::collections::BTreeSet<(u32, u32)> {+ [(3, 10), (3, 11), (3, 12), (3, 13)].into_iter().collect()+ }++ /// Required test from the coordinator's Runde 3 instructions: only 3.14+ /// on the box, nothing torch serves today, message required.+ #[test]+ fn only_3_14_present_yields_no_pick_and_a_message() {+ let interpreters = vec![("/usr/bin/python3".to_string(), Some((3, 14)))];+ let supported = supported_3_10_through_13();+ assert_eq!(pick_newest_supported_interpreter(&interpreters, &supported), None);+ let msg = no_compatible_interpreter_message((3, 14), &interpreters, &supported);+ assert!(msg.contains("3.14"), "{msg}");+ assert!(msg.contains("3.10, 3.11, 3.12, 3.13"), "{msg}");+ assert!(msg.contains("uv python install 3.13"), "{msg}");+ assert!(msg.contains("pyenv install 3.13"), "{msg}");+ assert!(msg.contains("Repair"), "{msg}");+ // B1(c): no Settings claim, no distro package name asserted as real.+ assert!(!msg.to_lowercase().contains("settings"), "{msg}");+ assert!(!msg.contains("pacman -S"), "{msg}");+ assert!(!msg.contains("apt install"), "{msg}");+ }++ /// Required test from the coordinator's Runde 3 instructions: 3.14 plus+ /// 3.12 (the pyenv shape) on the box picks 3.12 silently, no message.+ #[test]+ fn a_14_plus_pyenv_12_picks_12_without_a_message() {+ let interpreters = vec![+ ("/usr/bin/python3".to_string(), Some((3, 14))),+ (+ "/home/user/.pyenv/versions/3.12.7/bin/python3".to_string(),+ Some((3, 12)),+ ),+ ];+ let supported = supported_3_10_through_13();+ assert_eq!(+ pick_newest_supported_interpreter(&interpreters, &supported),+ Some("/home/user/.pyenv/versions/3.12.7/bin/python3".to_string())+ );+ }++ /// Two compatible interpreters: the NEWEST one wins, not the first one+ /// `python_interpreters()` happened to list.+ #[test]+ fn the_newest_compatible_interpreter_wins_over_an_older_one() {+ let interpreters = vec![+ ("/usr/bin/python3.10".to_string(), Some((3, 10))),+ ("/usr/local/bin/python3.13".to_string(), Some((3, 13))),+ ("/usr/bin/python3.11".to_string(), Some((3, 11))),+ ];+ let supported = supported_3_10_through_13();+ assert_eq!(+ pick_newest_supported_interpreter(&interpreters, &supported),+ Some("/usr/local/bin/python3.13".to_string())+ );+ }++ /// An interpreter whose version could not be read (`None`) must never be+ /// picked, and must never panic the max-by-key comparison.+ #[test]+ fn an_interpreter_with_an_unknown_version_is_never_picked() {+ let interpreters = vec![+ ("/broken/python".to_string(), None),+ ("/usr/bin/python3.12".to_string(), Some((3, 12))),+ ];+ let supported = supported_3_10_through_13();+ assert_eq!(+ pick_newest_supported_interpreter(&interpreters, &supported),+ Some("/usr/bin/python3.12".to_string())+ );+ }++ #[test]+ fn no_interpreters_at_all_still_yields_a_readable_message() {+ let msg = no_compatible_interpreter_message((3, 14), &[], &supported_3_10_through_13());+ assert!(msg.contains("(none found)"), "{msg}");+ }}diff --git a/src-tauri/src/python.rs b/src-tauri/src/python.rsindex cb9e7b2b..8390f2a9 100644--- a/src-tauri/src/python.rs+++ b/src-tauri/src/python.rs@@ -442,17 +442,71 @@ pub fn python_version(exe: &str) -> Option<String> {/// Python was 3.14 built the trainer venv from 3.14 and died at step 4/4/// (sockenmonster, Discord, August and ticket 0004 on 2026-09-05).///+/// Runde 3, B1(a): PATH alone missed the exact boxes the torch preflight+/// exists for. `uv python install` and `pyenv install`, the two commands+/// the preflight message itself now suggests, put their interpreters+/// somewhere PATH never sees unless the user also runs `pyenv init` or+/// `uv python pin`, so a machine that just followed the suggested command+/// would still show up as "no compatible interpreter found" on the very+/// next Repair. This walks those install locations directly, plus the+/// explicit `python3.10`..`python3.13` names (torch's usual served range),+/// so the install-then-repair loop the message promises actually closes.+////// Nothing here starts an interpreter beyond the `--version` gate the/// existing scans apply; the caller asks each hit for its version.#[cfg(not(target_os = "windows"))]pub fn python_interpreters() -> Vec<String> {let mut found: Vec<String> = Vec::new();- for name in crate::os_paths::unix_python_candidates() {- let Ok(path) = which::which(name) else { continue };+ let mut push = |path: PathBuf| {+ if !path.exists() {+ return;+ }let path = path.to_string_lossy().to_string();if !found.contains(&path) {found.push(path);}+ };+ for name in crate::os_paths::unix_python_candidates() {+ if let Ok(path) = which::which(name) {+ push(path);+ }+ }+ // Explicit names beyond what `unix_python_candidates` orders for the+ // default picker (that list stops at 3.11/3.12/3.13 by design, oldest+ // first is never its job): 3.10 through 3.13 is the range the torch+ // preflight message actually needs to reason about.+ for minor in 10..=13 {+ if let Ok(path) = which::which(format!("python3.{minor}")) {+ push(path);+ }+ }+ let home = crate::os_paths::home();+ // pyenv: every installed version keeps its own bin/ under versions/.+ for pattern in [+ home.join(".pyenv/versions/*/bin/python3"),+ home.join(".pyenv/versions/*/bin/python"),+ // uv-managed interpreters: `uv python install 3.12` lands here,+ // named after the exact version instead of a generic "python3".+ home.join(".local/share/uv/python/*/bin/python3"),+ home.join(".local/share/uv/python/*/bin/python3.*"),+ ] {+ for entry in glob::glob(&pattern.to_string_lossy()).into_iter().flatten().flatten() {+ push(entry);+ }+ }+ // Fixed, non-PATH-guaranteed locations named in the review: a user's own+ // pip-installed interpreter (`~/.local/bin`), a distro's optional package+ // prefix (`/opt/<name>/bin`), and the common source-build prefix+ // (`/usr/local/bin`), none of which every shell's PATH carries by default.+ for base in [home.join(".local/bin"), PathBuf::from("/usr/local/bin")] {+ for minor in 10..=13 {+ push(base.join(format!("python3.{minor}")));+ }+ }+ for pattern in ["/opt/*/bin/python3", "/opt/*/bin/python3.*"] {+ for entry in glob::glob(pattern).into_iter().flatten().flatten() {+ push(entry);+ }}found}