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
use crate::os_error;
use crate::commands::comfy_attention;
use crate::python::python_command;
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::{Arc, Mutex};
use tauri::{Manager, State};
use tracing::{error, info};
#[cfg(target_os = "windows")]
use std::os::windows::process::CommandExt;
use crate::state::AppState;
/// What every ComfyUI entry point answers on macOS. Local media there is Apple
/// MLX and nothing else, so the honest answer names the surface that does work
/// instead of failing with a bare error.
pub const MACOS_COMFY_REFUSAL: &str =
"ComfyUI is not used on macOS. Local image and video run on Apple MLX — set it up in Settings → AI Backends → Local Media (Apple MLX).";
/// One definition of "may this machine run a local ComfyUI at all". Every entry
/// point asks this rather than testing the target itself, so the rule has a
/// single place to be read, tested, and changed.
pub fn comfy_supported_here() -> bool {
!cfg!(target_os = "macos")
}
/// Windows: hide console windows for spawned processes
#[cfg(target_os = "windows")]
const CREATE_NO_WINDOW: u32 = 0x08000000;
/// Assign a child process to the app-wide Windows Job Object with
/// KILL_ON_JOB_CLOSE. When the Tauri parent process dies (even via Task
/// Manager, even via a hard kill from a build script), the OS kernel
/// automatically terminates every process in the job, with no Drop needed.
#[cfg(target_os = "windows")]
fn assign_to_kill_on_close_job(child: &std::process::Child) {
assign_pid_to_kill_on_close_job(child.id());
}
/// The ONE kill-on-close job object of this process, created on first use.
///
/// It used to be one fresh job per child, with the handle leaked on purpose so
/// the job outlived the call. That is correct for a child spawned once, and a
/// slow leak for one spawned again and again: the built-in engine is restarted
/// on every model swap, and a session that switches models a few dozen times
/// (measured on the Windows box on 2026-08-29: 30 restarts in eleven minutes)
/// leaked a kernel job handle every single time. A process may belong to
/// several jobs on Windows 8 and later, so one shared job holds every child
/// just as well and leaks exactly one handle for the whole run.
#[cfg(target_os = "windows")]
fn kill_on_close_job() -> isize {
use std::sync::OnceLock;
use windows_sys::Win32::System::JobObjects::*;
// The raw HANDLE is a pointer and therefore not `Sync`; the numeric value
// is, and it is what every call site needs.
static JOB: OnceLock<isize> = OnceLock::new();
*JOB.get_or_init(|| unsafe {
let job = CreateJobObjectW(std::ptr::null(), std::ptr::null());
if job.is_null() {
return 0;
}
let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = std::mem::zeroed();
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
SetInformationJobObject(
job,
JobObjectExtendedLimitInformation,
&info as *const _ as *const _,
std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
);
// Intentionally never closed. The handle must stay alive for the
// lifetime of the app. When the app dies the OS closes it and
// KILL_ON_JOB_CLOSE takes the children with it.
job as isize
})
}
/// The app-wide job handle, for the Windows tests that have to prove a child
/// really joined it — `bg_tasks.rs` asserts that a background task's shell AND
/// the process it starts are both inside this job, which is what makes LU's
/// death take them along. Test-only: production never needs the raw handle, it
/// only ever adds pids to it.
#[cfg(all(target_os = "windows", test))]
pub(crate) fn kill_on_close_job_for_tests() -> isize {
kill_on_close_job()
}
/// PID-based variant of [`assign_to_kill_on_close_job`]. Usable from spawn paths
/// that don't own a `std::process::Child`, notably `tokio::process::Child`
/// (whose `id()` is `Option<u32>`) in the background-task runner (bg_tasks.rs).
/// Same KILL_ON_JOB_CLOSE semantics; a pid of 0 is ignored.
#[cfg(target_os = "windows")]
pub(crate) fn assign_pid_to_kill_on_close_job(pid: u32) {
use windows_sys::Win32::System::JobObjects::*;
use windows_sys::Win32::Foundation::*;
if pid == 0 { return; }
let job = kill_on_close_job();
if job == 0 { return; }
unsafe {
let handle = windows_sys::Win32::System::Threading::OpenProcess(
windows_sys::Win32::System::Threading::PROCESS_SET_QUOTA
| windows_sys::Win32::System::Threading::PROCESS_TERMINATE,
0, // FALSE
pid,
);
if !handle.is_null() {
AssignProcessToJobObject(job as _, handle);
CloseHandle(handle);
}
}
}
/// Tie a spawned child to the lifetime of the app: on Windows it joins the
/// kill-on-close job object, everywhere else this is a no-op (Unix children of
/// a dead parent are reparented, and the graceful shutdown path plus the
/// process-group kill in `process_util` cover what matters there).
///
/// macOS has no job object and no parent-death signal, so nothing can be done
/// at spawn time there. The llama-server sidecars a dead app leaves behind
/// are ended at the next start instead, see
/// `engine::reap_orphaned_sidecars` (Fehlerkontrolle Mac 2, Fund 9).
///
/// Every long lived child goes through here: the bundled llama-server (chat
/// and embeddings), Ollama, the whisper server, the trainer, ComfyUI. Before
/// 2.6.7 only ComfyUI, Ollama-by-Drop and the background-task runner were
/// covered, so an app that died without running its shutdown path left a
/// llama-server behind holding the whole model in VRAM. Proved on the Windows
/// box on 2026-08-29: the app was terminated at 09:48:19, both ComfyUI
/// processes went with it, and lu-llama-server stayed up on 3633 MiB.
///
/// Cross platform on purpose (no `#[cfg]` at the call sites) so the call is
/// visible and testable on every platform, not only the one that needs it.
pub(crate) fn tie_child_to_app_lifetime(pid: u32) {
#[cfg(target_os = "windows")]
assign_pid_to_kill_on_close_job(pid);
#[cfg(not(target_os = "windows"))]
let _ = pid;
}
/// Show the CALLING window (called from a frontend once React has rendered).
///
/// Every window starts hidden, so this is the one place a window becomes
/// visible — and whether it may is a question of who else is on screen: the
/// main window stays hidden while the onboarding runs in its own window, and
/// once the onboarding is done, showing the main window is what closes the
/// small one. The rule lives in `onboarding_window::reveal`.
#[tauri::command]
pub fn show_window(window: tauri::WebviewWindow) {
crate::onboarding_window::reveal(&window);
}
/// Bug J: does this system need ComfyUI's --cpu fallback flag?
///
/// ComfyUI 0.21.x's `main.py` calls `get_torch_device()` which calls
/// `torch.cuda.current_device()` unconditionally during import. On systems
/// without an NVIDIA driver, that raises `RuntimeError: Found no NVIDIA
/// driver on your system` and main.py crashes before binding the port.
///
/// We pass `--cpu` to fall back to CPU inference when:
/// - Not on macOS (Mac PyTorch uses MPS, which doesn't touch cuda APIs), AND
/// - `nvidia-smi` is missing or exits non-zero (no NVIDIA card present).
///
/// This is only the BASELINE, and reading it as the whole decision is how the
/// output panel came to tell an AMD user his NVIDIA driver was missing. The
/// decision is `decide_comfy_cpu_flag`, which asks the comfy python's own torch
/// when this baseline says yes: a ROCm or ZLUDA torch answers
/// `torch.cuda.is_available() == True` and keeps `--cpu` off the command line.
/// rhodium92 (AMD RX 6600 XT, 2026-07-01) is the report that added that step.
/// So an AMD or Intel box only lands on the processor when its torch says it
/// has no card, which is a different sentence and now says so.
pub fn needs_cpu_fallback() -> bool {
if cfg!(target_os = "macos") {
return false;
}
!nvidia_present()
}
/// Is an NVIDIA driver present (nvidia-smi exits 0)?
fn nvidia_present() -> bool {
// CREATE_NO_WINDOW: this probe runs on every ComfyUI start, without it an
// NVIDIA Windows box flashes a console window each time. End users must
// never see a terminal pop up.
//
// K14 Runde 2, Punkt 5: this exact spot was the one the review found
// still using a bare Command::new for nvidia-smi (a foreign vendor CLI)
// after the K14 commit claimed the app's nvidia-smi call sites were
// covered.
let mut cmd = crate::process_util::foreign_system_command("nvidia-smi");
crate::process_util::suppress_window(&mut cmd);
cmd.output()
.map(|o| o.status.success())
.unwrap_or(false)
}
/// User override for the ComfyUI CPU/GPU decision (settings.comfyGpuMode).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ComfyGpuMode {
/// Probe: NVIDIA fast-path, else the comfy python's torch GPU availability.
Auto,
/// Always pass `--cpu` (stable but slow — e.g. a card that OOMs on image gen).
ForceCpu,
/// Never pass `--cpu` (user vouches for a non-NVIDIA accel, e.g. DirectML).
ForceGpu,
}
impl ComfyGpuMode {
pub fn parse(s: &str) -> Self {
match s.trim().to_ascii_lowercase().as_str() {
"cpu" => ComfyGpuMode::ForceCpu,
"gpu" => ComfyGpuMode::ForceGpu,
_ => ComfyGpuMode::Auto,
}
}
}
/// How long after a spawn a still-living child counts as proof of a start.
/// ComfyUI imports for 20 to 60 seconds before it binds the port, so we cannot
/// wait for the port here. We can wait for the crash: a bad dependency kills
/// main.py on the first import, well inside this window.
const COMFY_STARTUP_WATCH: std::time::Duration = std::time::Duration::from_millis(2_000);
const COMFY_STARTUP_STEP: std::time::Duration = std::time::Duration::from_millis(200);
/// After this long without the port opening, "starting" is a lie.
/// The slowest honest start measured on the 3060 box is about a minute; a
/// custom-node-heavy install can take longer, so this is deliberately generous.
const COMFY_STARTING_GRACE_SECS: u64 = 300;
/// What the panel should say about a child that is alive but has not bound the
/// port: `(starting, stalled)`.
///
/// Measured on the Windows box on 2026-08-14: `starting` was
/// `process_alive && !running` and nothing else, so a handle that never
/// resolved left the panel claiming a start that had been over for six
/// minutes. `starting` now expires, and the caller reports `stalled` so the UI
/// can offer the output instead of a spinner.
pub fn comfy_starting_state(
process_alive: bool,
running: bool,
since_start: Option<std::time::Duration>,
) -> (bool, bool) {
if running || !process_alive {
return (false, false);
}
match since_start {
// A handle we cannot date (kept from an earlier call, or a start we did
// not make) gets the old reading rather than a stall we cannot prove.
None => (true, false),
Some(waited) if waited.as_secs() > COMFY_STARTING_GRACE_SECS => (false, true),
Some(_) => (true, false),
}
}
/// 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
/// line into `comfy_output` since GH #98. The missing part was anyone reading
/// it at the moment the start failed, which is why the box showed `Stopped`
/// with no reason while `main.py`'s ImportError sat in the ring buffer.
pub fn comfy_startup_failure(
python: &str,
code: Option<i32>,
tail: &[String],
has_own_python_env: bool,
) -> String {
let mut msg = format!("ComfyUI exited right after starting (python={python}");
if let Some(c) = code {
msg.push_str(&format!(", exit code {c}"));
}
msg.push_str(").");
if !has_own_python_env {
msg.push_str(
" This install has no python_embeded and no venv of its own, so it ran on the \
Python of this machine that holds PyTorch, shared with every other program that \
uses it. Repair environment, in Settings, AI Backends, builds ComfyUI an \
environment of its own.",
);
}
let lines: Vec<&str> = tail
.iter()
.map(|l| l.trim_end())
.filter(|l| !l.is_empty())
.rev()
.take(8)
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect();
if !lines.is_empty() {
msg.push_str("\n\nLast output:\n");
msg.push_str(&lines.join("\n"));
}
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,
/// A user 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"))
}
/// Was die letzte Ausgabe eines Startversuchs bedeutet: darf die Selbstheilung
/// laufen, und welcher Satz gehoert unter die Ausgabe.
pub(crate) struct ComfyCrashVerdict {
/// Ein Absturz, den ein Neubau des venv beheben kann (GH #98).
pub env_broken: bool,
/// Der konkrete Rat aus dem Einordner des Installers, sonst leer.
pub hint: String,
}
/// Die Einordnung eines Startabsturzes, mit genau dem Einordner, den der
/// Installer schon hat. Kein zweiter Einordner und kein zweiter Hinweistext:
/// `pip_failure_kind` und `pip_failure_hint` wissen seit 2.6.7, was WinError
/// 1114 bedeutet, sie wurden auf diesem Weg nur nie gefragt.
///
/// a user (Ticket 007, 01.09. bis 02.09.): sein torch starb an einem
/// c10.dll im venv, LU nannte das eine kaputte Umgebung und baute das venv
/// automatisch neu. Ein nativer Ladefehler hat seine Ursache AUSSERHALB des
/// venv, in der Visual-C++-Laufzeit oder im Grafiktreiber, also endet der
/// Neubau nach Minuten auf derselben Meldung. Genau diese Schleife hat er
/// berichtet. Alle uebrigen Faelle heilen sich weiter selbst.
pub(crate) fn comfy_crash_verdict(lines: &[String], exited: bool) -> ComfyCrashVerdict {
use crate::commands::install::pip::{pip_failure_hint, pip_failure_kind, PipFailureKind};
let joined = lines.join("\n");
let kind = pip_failure_kind(&joined);
// Eine Auswahl ueber den vorhandenen Einordner, kein zweiter Einordner:
// diese vier Saetze beschreiben die Maschine selbst und stimmen deshalb
// auch, wenn nicht pip sie gedruckt hat, sondern ComfyUI beim Start. Die
// uebrigen Saetze reden von pip und vom Paketindex, die hier gar nicht
// gelaufen sind. Der schlimmste davon ist PipBroken: ein fehlendes
// sqlalchemy wuerde damit ein "Reinstall Python 3.10+ from python.org"
// bekommen, obwohl sein Python heil ist und die Reparatur der Weg ist.
let hint = match kind {
PipFailureKind::MissingRuntimeLibrary
| PipFailureKind::NativeLoadFailure
| PipFailureKind::TorchWithoutGpuSupport
| PipFailureKind::DiskFull => pip_failure_hint(kind, &joined),
_ => String::new(),
};
ComfyCrashVerdict {
env_broken: exited && comfy_env_failure(lines) && venv_rebuild_can_fix(kind),
hint,
}
}
/// Kann ein Neubau des venv dieses Fehlerbild ueberhaupt beheben?
///
/// Nein, sobald das fehlende Stueck ausserhalb des venv liegt: die
/// Visual-C++-Laufzeit und der Grafiktreiber wohnen in Windows, und ein
/// frisches venv laedt dieselben Wheels an dieselbe Stelle. Alles andere
/// bleibt bei Ja, damit die Selbstheilung aus GH #98 nur enger wird und nicht
/// verschwindet.
pub(crate) fn venv_rebuild_can_fix(kind: crate::commands::install::pip::PipFailureKind) -> bool {
use crate::commands::install::pip::PipFailureKind as K;
!matches!(kind, K::NativeLoadFailure | K::MissingRuntimeLibrary)
}
/// Pure decision (all probes done by the caller): pass `--cpu` to ComfyUI?
///
/// - `baseline_needs_cpu`: `needs_cpu_fallback()` — false when NVIDIA present or macOS.
/// - `torch_gpu`: Some(true) = the comfy python's torch reports a usable GPU
/// (CUDA / ROCm / ZLUDA answer via `torch.cuda.is_available()`, Intel Arc
/// via `torch.xpu.is_available()`, see `COMFY_GPU_PROBE`),
/// Some(false) = no usable GPU, None = not probed / probe failed.
///
/// rhodium92 (AMD RX 6600 XT, 2026-07-01): before this, ANY non-NVIDIA box was
/// force-dropped to `--cpu`, so a ROCm/ZLUDA ComfyUI never used the AMD card.
pub fn decide_comfy_cpu_flag(
mode: ComfyGpuMode,
baseline_needs_cpu: bool,
torch_gpu: Option<bool>,
) -> bool {
match mode {
ComfyGpuMode::ForceCpu => true,
ComfyGpuMode::ForceGpu => false,
ComfyGpuMode::Auto => {
if !baseline_needs_cpu {
// NVIDIA present (or macOS MPS) — the GPU is already fine.
false
} else {
// No NVIDIA driver: a torch that reports a usable GPU (ROCm/ZLUDA)
// means main.py won't crash on torch.cuda → run on the GPU.
match torch_gpu {
Some(true) => false,
_ => true, // Some(false) = no GPU, None = probe failed → conservative --cpu
}
}
}
}
}
/// Force GPU is a promise LU keeps, not a claim LU checks: the flag drops
/// `--cpu` and ComfyUI then asks torch for a device. On a venv holding
/// CUDA-only wheels and an AMD card that ends in
/// "Torch not compiled with CUDA enabled" and nothing else, which is what
/// A user all saw. The flag still
/// wins, the user asked for it, but the reason is in the output panel before
/// the traceback is.
///
/// `torch_gpu`: Some(false) = the venv's torch reports no usable GPU,
/// Some(true) = it does, None = the probe did not answer and we say nothing
/// rather than guess.
// Only the tests read it, the app asks `force_gpu_warning_for`.
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn force_gpu_warning(
mode: ComfyGpuMode,
torch_gpu: Option<bool>,
has_amd: bool,
os: &str,
) -> Option<String> {
force_gpu_warning_for(mode, torch_gpu, has_amd, false, os)
}
/// `force_gpu_warning`, knowing whether LU installs the ROCm build for the AMD
/// card on this machine (`amd_rocm_served`, torch_wheels). Where it does, the
/// way out is Repair environment, and saying "use a ComfyUI of your own" there
/// sends the user away from the fix LU has. That was kinghebes' case in 3.0.7:
/// an RX 9070 XT, an environment with processor wheels, and a warning that told
/// him no rebuild would help.
pub(crate) fn force_gpu_warning_for(
mode: ComfyGpuMode,
torch_gpu: Option<bool>,
has_amd: bool,
amd_rocm_served: bool,
os: &str,
) -> Option<String> {
if mode != ComfyGpuMode::ForceGpu || torch_gpu != Some(false) {
return None;
}
// A torch that offers Intel XPU answers Some(true) and never gets here, so
// naming CUDA as the error is right for every box that does.
let head = "ComfyUI GPU is set to Force GPU, but the PyTorch in this ComfyUI \
environment reports no usable GPU, neither CUDA nor Intel XPU. ComfyUI \
will stop with \"Torch not compiled with CUDA enabled\" instead of rendering.";
let fix = match (has_amd, os) {
(true, "windows") if amd_rocm_served => {
"Your card is AMD, and LU installs AMD's own ROCm build of PyTorch for it on \
Windows, but this ComfyUI environment holds processor wheels: it was built \
before LU could do that, or AMD's index did not answer then. Press Repair \
environment in Settings > ComfyUI. It rebuilds the environment with the ROCm \
build for your card (about 1.5 GB) and leaves models, outputs and custom nodes \
alone. Keep a current AMD Software: Adrenalin Edition driver, the ROCm build \
needs it."
}
(true, "linux") => {
"Your card is AMD and this environment holds CUDA-only wheels. Reinstall the \
ComfyUI environment from Settings > ComfyUI: LU now installs the ROCm build \
of PyTorch when it sees an AMD card."
}
(true, "windows") => {
// Since Runde 12 LU does install AMD's own Windows ROCm wheels for
// the RDNA 3, 3.5 and 4 cards AMD supports, so the old absolute
// "PyTorch ships no ROCm wheels for Windows" is no longer true.
// What IS true whenever this branch fires is that the environment
// ended up with processor wheels anyway, either because the card is
// outside that list or because the index did not answer. Still no
// reinstall advice: on the cards that reach this message a rebuild
// lands in the same place.
"Your card is AMD, and this ComfyUI environment holds processor wheels: \
pytorch.org publishes no Windows ROCm wheels, and AMD's own Windows ROCm \
index either does not cover this card or did not answer when the \
environment was built. Use a ComfyUI of your own on ZLUDA or DirectML, or \
set ComfyUI GPU back to Auto and render on the processor."
}
_ => {
"Reinstall the ComfyUI environment from Settings > ComfyUI (Repair environment) \
so PyTorch is rebuilt for the card LU detects, or set ComfyUI GPU back to Auto. For an Intel Arc card LU now \
installs the XPU build of PyTorch (download.pytorch.org/whl/xpu) when it \
builds the environment."
}
};
Some(format!("[LU] {head} {fix}"))
}
/// Warum laeuft ComfyUI gleich auf dem Prozessor? Ein Satz, oder None, wenn es
/// gar nicht dazu kommt.
///
/// Die Zeile, die hier vorher stand, hiess "No NVIDIA driver detected" und war
/// die einzige Erklaerung im Ausgabefenster. Fuer einen AMD-Nutzer benennt sie
/// die falsche Hardware: er hat keinen NVIDIA-Treiber und wird auch nie einen
/// haben, und der eigentliche Grund steht daneben, naemlich dass das torch in
/// dieser Umgebung keine brauchbare Karte meldet. Das Band im Create-Tab sagt
/// seit Runde 12 das Richtige, das Ausgabefenster sagte weiter das Falsche,
/// und das Ausgabefenster ist die Stelle, an die jemand geht, wenn etwas
/// klemmt.
///
/// Bewusst OHNE eine zweite Hardware-Abfrage: `gpu_vendors_present` schickt
/// rocm-smi und lspci los, und der Start von ComfyUI ist genau der Moment, in
/// dem der Nutzer wartet. Der Grund laesst sich ohne den Hersteller genau
/// benennen, und der Weg zur AMD-Antwort steht im Band, das ohnehin erscheint.
pub(crate) fn cpu_flag_reason(
mode: ComfyGpuMode,
baseline_needs_cpu: bool,
torch_gpu: Option<bool>,
) -> Option<String> {
if !decide_comfy_cpu_flag(mode, baseline_needs_cpu, torch_gpu) {
return None;
}
Some(match mode {
ComfyGpuMode::ForceCpu => "ComfyUI GPU is set to Force CPU, so ComfyUI starts with --cpu. \
Set it back to Auto in Settings > Hardware to use the card again."
.to_string(),
// ForceGpu never passes --cpu, so the arm is unreachable through the
// guard above and says so instead of inventing a reason.
ComfyGpuMode::ForceGpu => "ComfyUI starts with --cpu.".to_string(),
ComfyGpuMode::Auto => match torch_gpu {
Some(false) => "The PyTorch in this ComfyUI environment reports no usable GPU, \
so ComfyUI starts with --cpu. Reinstall the ComfyUI environment from \
Settings > ComfyUI to rebuild PyTorch for the card LU detects."
.to_string(),
None => "The GPU probe in this ComfyUI environment did not answer, so ComfyUI \
starts with --cpu for this start and the probe runs again next time."
.to_string(),
// Some(true) cannot reach this point: it is the one answer that
// drops the flag.
Some(true) => "ComfyUI starts with --cpu.".to_string(),
},
})
}
/// Skip these directories during ComfyUI search
const SKIP_DIRS: &[&str] = &[
"node_modules", ".git", "__pycache__", "venv", ".venv", "site-packages",
"Windows", "Program Files", "Program Files (x86)", "$Recycle.Bin", "AppData",
];
fn scan_for_comfyui(dir: &Path, depth: u32) -> Option<PathBuf> {
if depth == 0 {
return None;
}
let entries = match fs::read_dir(dir) {
Ok(e) => e,
Err(_) => return None,
};
for entry in entries.flatten() {
let file_type = match entry.file_type() {
Ok(ft) => ft,
Err(_) => continue, // Skip entries with permission errors
};
if !file_type.is_dir() {
continue;
}
let name = entry.file_name();
let name_str = name.to_string_lossy();
if name_str.starts_with('.') || SKIP_DIRS.contains(&name_str.as_ref()) {
continue;
}
let full = entry.path();
// Check if this directory IS ComfyUI
if name_str.eq_ignore_ascii_case("comfyui") && is_comfyui_dir(&full) {
return Some(full);
}
// Or holds it one level down under any name, the portable layout
if let Some(inner) = nested_comfyui_dir(&full) {
return Some(inner);
}
// Recurse deeper
if let Some(found) = scan_for_comfyui(&full, depth - 1) {
return Some(found);
}
}
None
}
/// Heuristic: does this ComfyUI directory look like a *complete* install,
/// i.e. one that will actually start when we run `python main.py`?
///
/// "Complete" here means: torch is reachable. Three environments qualify,
/// and the order below is the order LU itself creates them in:
///
/// 1. ComfyUI's OWN venv — `ComfyUI/venv` (what LU's PEP 668 installer and
/// `repair_comfyui_env` build) or `ComfyUI/.venv` (uv, modern
/// `python -m venv .venv`). This is where torch lives for every install
/// LU has made since Bug E, and for every install that has ever been
/// through a repair.
/// 2. Portable variants ship a `python_embeded/` directory with the
/// matching torch wheel pre-baked.
/// 3. From-source installs that predate the venv path depend on the system
/// Python having torch, so the system interpreters' prefixes are read.
///
/// All three are directory probes, never `python -c "import torch"`: the
/// scan runs over every candidate directory on the box and importing torch
/// costs seconds each.
///
/// OI-1 (2.6.7 audit): case 1 did not exist and case 3 could not fire on
/// Unix, so on Linux the answer was `false` for every from-source install and
/// for every install on any platform that had been repaired. The user was
/// told a working ComfyUI was broken, permanently — the onboarding step was
/// passable only via "Skip for now" and Settings offered only "Re-install"
/// (another 2 GB of PyTorch). See `python_prefix_has_torch` for the exact
/// mechanism that made the Unix branch dead code.
///
/// Returning `false` for a `main.py`-only carcass is still the point of
/// P14: a half-cloned ComfyUI dir from a previous abort (Python missing,
/// pip 403, network drop) used to be detected as "installed", which left
/// the user staring at "ComfyUI not responding" forever. Reporting it as
/// incomplete instead lets the install flow retry cleanly.
fn is_comfyui_install_complete(comfy_path: &Path) -> bool {
is_comfyui_install_complete_with(comfy_path, &collect_candidate_pythons())
}
/// Testable core of [`is_comfyui_install_complete`]. The interpreter list is
/// injected because the probe's platform branches cannot otherwise be checked:
/// the box running the tests has exactly one of the two prefix layouts, and
/// the layout that broke (Unix) is not the one CI happens to be on. With the
/// list injected, both layouts are exercised from fixture directories.
fn is_comfyui_install_complete_with(comfy_path: &Path, candidate_pythons: &[String]) -> bool {
if !comfy_path.join("main.py").exists() {
return false;
}
// 1. ComfyUI's own venv — the environment LU builds itself.
for venv_name in ["venv", ".venv"] {
if prefix_has_torch(&comfy_path.join(venv_name)) {
return true;
}
}
// 2. Portable layouts (next-to or inside the ComfyUI dir).
let portable_candidates = [
comfy_path.parent().map(|p| p.join("python_embeded")),
Some(comfy_path.join("python_embeded")),
];
for c in portable_candidates.into_iter().flatten() {
if prefix_has_torch(&c) {
return true;
}
}
// 3. System Python — derive each interpreter's prefix and look for torch
// in the standard sysconfig locations. Catches the pre-venv from-source
// case where pip dropped torch into the system Python's site-packages.
candidate_pythons
.iter()
.any(|py| python_prefix_has_torch(Path::new(py)))
}
/// Does the environment rooted at `prefix` hold a `torch` package?
///
/// `prefix` is a Python *prefix*: a venv root, a `python_embeded` dir, or the
/// `sys.prefix` of a system install. Both layouts are probed because LU has
/// to answer for boxes it is not running on:
///
/// * Windows: `<prefix>/Lib/site-packages/torch`
/// * Unix: `<prefix>/lib/python3.X/site-packages/torch` (and `lib64`),
/// with the minor version unknown, so the version dirs are enumerated.
///
/// An empty prefix is refused up front. That is not defensive noise: it is
/// exactly the OI-1 bug. `Path::new("python3").parent()` is `Some("")`, and
/// joining onto `""` yields a RELATIVE path — `Lib/site-packages/torch` —
/// which `exists()` resolves against LU's working directory. So the Windows
/// 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`.
///
/// `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;
}
if prefix.join("Lib").join("site-packages").join("torch").exists() {
return true;
}
// A venv's own `pyvenv.cfg`-less sibling layout: some tools drop
// site-packages directly under the prefix.
if prefix.join("site-packages").join("torch").exists() {
return true;
}
for lib_name in ["lib", "lib64"] {
let lib = prefix.join(lib_name);
if lib.join("site-packages").join("torch").exists() {
return true;
}
// <prefix>/lib/python3.X/site-packages/torch — the minor version is
// whatever built the env, so enumerate rather than guess.
if let Ok(entries) = std::fs::read_dir(&lib) {
for e in entries.flatten() {
if e.path().join("site-packages").join("torch").exists() {
return true;
}
}
}
}
false
}
/// Does the interpreter at `interpreter` have torch on its prefix?
///
/// The interpreter sits one or two levels below its prefix depending on the
/// platform — `<prefix>/python.exe` on Windows, `<prefix>/bin/python3` on
/// Unix — so both the containing directory and its parent are tried. A
/// relative interpreter name (no directory component at all) yields no
/// prefix and is refused rather than silently probed against the cwd.
pub(crate) fn python_prefix_has_torch(interpreter: &Path) -> bool {
let Some(bin_dir) = interpreter.parent() else {
return false;
};
if bin_dir.as_os_str().is_empty() {
return false;
}
if prefix_has_torch(bin_dir) {
return true;
}
match bin_dir.parent() {
Some(p) if !p.as_os_str().is_empty() => prefix_has_torch(p),
_ => false,
}
}
/// Where the Python a ComfyUI without a venv of its own was found to run on
/// is remembered: `{"comfyui": <folder>, "python": <interpreter>}` in the
/// app's config.json, next to `comfyui_path`.
const BOUND_PYTHON_KEY: &str = "comfyui_python";
/// The interpreter remembered for `comfy_dir`, if one was, and for exactly
/// this folder: a second ComfyUI elsewhere does not inherit it.
pub(crate) fn remembered_bound_python_in(config: &Path, comfy_dir: &Path) -> Option<String> {
let json: serde_json::Value = serde_json::from_str(&fs::read_to_string(config).ok()?).ok()?;
let entry = json.get(BOUND_PYTHON_KEY)?;
let folder = entry.get("comfyui")?.as_str()?;
let python = entry.get("python")?.as_str()?.trim();
(Path::new(folder) == comfy_dir && !python.is_empty()).then(|| python.to_string())
}
/// Remember `python` for `comfy_dir`. Every other key in the file stays, the
/// same read, change, write `custom_models::remember_root_in` does.
pub(crate) fn remember_bound_python_in(config: &Path, comfy_dir: &Path, python: &str) {
if let Some(parent) = config.parent() {
let _ = fs::create_dir_all(parent);
}
let mut json: serde_json::Value = fs::read_to_string(config)
.ok()
.and_then(|s| serde_json::from_str(&s).ok())
.unwrap_or_else(|| serde_json::json!({}));
json[BOUND_PYTHON_KEY] = serde_json::json!({
"comfyui": comfy_dir.to_string_lossy(),
"python": python,
});
let _ = fs::write(config, serde_json::to_string_pretty(&json).unwrap_or_default());
}
fn same_interpreter(a: &str, b: &str) -> bool {
if cfg!(target_os = "windows") {
a.eq_ignore_ascii_case(b)
} else {
a == b
}
}
/// The pure half of [`bound_comfy_python`]: which interpreter holds this
/// ComfyUI's torch. The remembered one first, then LU's default, then every
/// other one on the machine (`others` is only asked when the first two have
/// no torch on disk, it starts a scan). Two rounds: torch in the
/// interpreter's own prefix (a file check, no process), and only when no
/// candidate has that, whether the interpreter finds torch at all (a user
/// site install). None when no interpreter has torch.
pub(crate) fn pick_torch_python(
saved: Option<&str>,
default: &str,
others: impl FnOnce() -> Vec<String>,
on_disk: impl Fn(&str) -> bool,
finds: impl Fn(&str) -> bool,
) -> Option<String> {
let mut list: Vec<String> = Vec::new();
let add = |list: &mut Vec<String>, p: &str| {
let p = p.trim();
if !p.is_empty() && !list.iter().any(|q| same_interpreter(q, p)) {
list.push(p.to_string());
}
};
for p in saved.into_iter().chain(std::iter::once(default)) {
add(&mut list, p);
}
if let Some(hit) = list.iter().find(|p| on_disk(p)) {
return Some(hit.clone());
}
for p in others() {
add(&mut list, &p);
}
if let Some(hit) = list.iter().find(|p| on_disk(p)) {
return Some(hit.clone());
}
list.into_iter().find(|p| finds(p))
}
/// The Python a ComfyUI WITHOUT a venv of its own starts and installs with.
///
/// Discord 14.10.2026: such a ComfyUI used to take `state.python_bin`, the
/// interpreter LU resolves as its default at app start. A machine that got a
/// Python 3.15 next to the 3.12 that holds torch could resolve the new one,
/// and ComfyUI died at `import torch` after an update of nothing but the
/// app. The interpreter that holds torch is the one this install belongs to,
/// so that is the one asked for, and it is remembered per ComfyUI folder so
/// the next default change cannot move it again.
///
/// None: no interpreter on this machine has torch; [`comfy_no_torch_python_message`]
/// says what to do (Repair environment builds the venv).
pub(crate) fn bound_comfy_python(comfy_dir: &Path, default: &str) -> Option<String> {
let config = crate::os_paths::app_config_json();
let saved = remembered_bound_python_in(&config, comfy_dir);
let chosen = pick_torch_python(
saved.as_deref(),
default,
|| {
let mut all = crate::python::python_interpreters();
all.extend(collect_candidate_pythons());
all
},
|p| python_prefix_has_torch(Path::new(p)),
crate::commands::install::python_finds_torch,
)?;
if saved.as_deref() != Some(chosen.as_str()) {
info!(python = %chosen, comfyui = %comfy_dir.display(), "comfyui without venv bound to the python that holds torch");
remember_bound_python_in(&config, comfy_dir, &chosen);
}
Some(chosen)
}
/// A ComfyUI without a venv, and no Python on this machine has torch. Not a
/// reinstall-Python sentence: Repair environment builds ComfyUI a venv of its
/// own, from a Python of the machine that PyTorch serves or from LU's own.
pub(crate) fn comfy_no_torch_python_message(comfy_dir: &Path) -> String {
format!(
"ComfyUI at {} has no environment of its own, and none of the Python installations \
LU found on this machine has PyTorch. Press \"Repair environment\" in Settings, \
AI Backends: LU builds ComfyUI its own environment (with LU's own Python 3.12 if no \
Python here fits) and leaves models and custom nodes untouched.",
comfy_dir.display()
)
}
/// Which interpreter a ComfyUI start uses, one decision for the start button
/// and the auto-start. Portable wins over everything (it ships the matching
/// torch wheel, a leftover venv beside it must not refuse that start), then
/// the install's own venv, and only without a venv the Python that holds
/// torch (`bind`, in production [`bound_comfy_python`]). A venv without its
/// interpreter is P3's third answer and stops the start; no venv and no
/// Python with torch stops it too, with the button that builds one.
pub(crate) fn launch_python(
bundled: Option<&str>,
venv: &crate::python::ComfyVenv,
comfy_dir: &Path,
bind: impl FnOnce() -> Option<String>,
) -> Result<String, String> {
match (bundled, venv) {
(Some(p), _) => Ok(p.to_string()),
(None, crate::python::ComfyVenv::Usable(p)) => Ok(p.clone()),
(None, crate::python::ComfyVenv::Broken { venv_dir, interpreter }) => {
Err(comfy_broken_venv_message(venv_dir, interpreter))
}
(None, crate::python::ComfyVenv::Absent) => bind().ok_or_else(|| comfy_no_torch_python_message(comfy_dir)),
}
}
/// The interpreter a ComfyUI start in `comfy_dir` would use, for a helper
/// script that needs ComfyUI's packages (numpy, av) and nothing of its own,
/// such as the colour settle of a long video (commands/video_settle.rs). The
/// same order as both start paths: the portable's `python_embeded` (beside
/// the folder or inside it), the install's venv, the Python that holds its
/// torch. Errors carry the same sentences the start would show.
pub(crate) fn comfy_tool_python(state: &AppState, comfy_dir: &Path) -> Result<String, String> {
let embedded = |base: &Path| {
let candidate = base.join("python_embeded").join("python.exe");
candidate.exists().then(|| candidate.to_string_lossy().to_string())
};
let bundled = comfy_dir.parent().and_then(embedded).or_else(|| embedded(comfy_dir));
let venv_state = crate::python::comfy_venv_state(comfy_dir);
let system_python = state.python_bin.lock().unwrap().clone();
launch_python(bundled.as_deref(), &venv_state, comfy_dir, || bound_comfy_python(comfy_dir, &system_python))
}
/// Collect the system Python paths we might want to probe. Mirrors the
/// search order in `python::get_python_bin` but returns *all* hits, not
/// just the first — so the carcass check works even when the user has
/// torch installed in a non-default Python.
///
/// Every entry is an ABSOLUTE interpreter path. That is a hard requirement of
/// the callers, not a nicety: they read the interpreter's prefix off the path,
/// and a bare name has none (OI-1). The old Unix branch pushed the literal
/// strings `"python3"` and `"python"`.
fn collect_candidate_pythons() -> Vec<String> {
// Same two-block shape as `os_paths::find_python`: exactly one is
// compiled, and it is the function's tail.
#[cfg(not(target_os = "windows"))]
{
// Same ordered candidate list the installer resolves through
// (BUG-008: a bare `python3` can be a 3.14 with no ML wheels), so the
// probe and the install path cannot disagree about which interpreter
// "the system Python" is. `which` turns each name into a real path.
let mut out: Vec<String> = Vec::new();
for name in crate::os_paths::unix_python_candidates() {
if let Ok(p) = which::which(name) {
let s = p.to_string_lossy().to_string();
if !out.contains(&s) {
out.push(s);
}
}
}
out
}
#[cfg(target_os = "windows")]
{
let mut out: Vec<String> = Vec::new();
// `where python` candidates (excluding WindowsApps stub).
let mut where_cmd = crate::process_util::foreign_system_command("where");
where_cmd.arg("python");
crate::process_util::suppress_window(&mut where_cmd);
if let Ok(output) = where_cmd.output() {
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout);
for line in stdout.lines() {
let path = line.trim();
if !path.is_empty() && !path.contains("WindowsApps") {
out.push(path.to_string());
}
}
}
}
for p in [
"C:\\Python313\\python.exe",
"C:\\Python312\\python.exe",
"C:\\Python311\\python.exe",
"C:\\Python310\\python.exe",
"C:\\Python39\\python.exe",
] {
if Path::new(p).exists() {
out.push(p.to_string());
}
}
if let Ok(localappdata) = std::env::var("LOCALAPPDATA") {
let programs = Path::new(&localappdata).join("Programs").join("Python");
if let Ok(entries) = std::fs::read_dir(&programs) {
for e in entries.flatten() {
let py = e.path().join("python.exe");
if py.exists() {
out.push(py.to_string_lossy().to_string());
}
}
}
}
out
}
}
/// Probe order for the ComfyUI Desktop App's Working Directory when the
/// user-supplied path is the binary install dir (contains `ComfyUI.exe` but
/// no `main.py`). Comfy-Org/desktop lets the user pick this dir at install
/// time and defaults to `~\Documents\ComfyUI`. We additionally try the
/// `%APPDATA%\ComfyUI\config.json` `basePath` hint which the desktop app
/// writes after the picker, and the legacy `electron-userdata` location.
fn desktop_app_working_dir_candidates() -> Vec<PathBuf> {
let mut out: Vec<PathBuf> = Vec::new();
let home = dirs::home_dir().unwrap_or_default();
out.push(home.join("Documents").join("ComfyUI"));
out.push(home.join("Documents").join("ComfyUI").join("ComfyUI"));
if cfg!(target_os = "windows") {
if let Ok(appdata) = std::env::var("APPDATA") {
// 1. config.json basePath hint, if present
let cfg = PathBuf::from(&appdata).join("ComfyUI").join("config.json");
if let Ok(raw) = std::fs::read_to_string(&cfg) {
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&raw) {
if let Some(p) = v.get("basePath").and_then(|x| x.as_str()) {
out.push(PathBuf::from(p));
}
}
}
// 2. %APPDATA%\ComfyUI itself (some installer variants)
out.push(PathBuf::from(&appdata).join("ComfyUI"));
}
if let Ok(localappdata) = std::env::var("LOCALAPPDATA") {
out.push(PathBuf::from(&localappdata).join("ComfyUI"));
// The desktop installer also bundles a ComfyUI tree under the
// app's resources for first-launch seeding.
out.push(PathBuf::from(&localappdata).join("Programs").join("ComfyUI").join("resources").join("ComfyUI"));
}
}
out
}
/// The ComfyUI one level below `dir`, if that is where `main.py` sits.
///
/// The Windows portable builds (NVIDIA, AMD and Intel alike) unpack as
/// `ComfyUI_windows_portable\{ComfyUI, python_embeded}`, and people pick the
/// outer folder, often renamed. `main.py` lives in the inner one, and
/// `python_embeded` stays found as its sibling exactly as before.
fn nested_comfyui_dir(dir: &Path) -> Option<PathBuf> {
let inner = dir.join("ComfyUI");
is_comfyui_dir(&inner).then_some(inner)
}
/// A folder ComfyUI starts from: `main.py` beside the `comfy` package.
///
/// `main.py` alone proved nothing (Discord 25.10.2026, Comfy Desktop): the
/// Python that Comfy Desktop bundles carries `Lib\_pyrepl\main.py`, LU took
/// that folder for ComfyUI, and every start "exited early" with code 0 while
/// downloads and the trainer looked in `_pyrepl\models`.
pub(crate) fn is_comfyui_dir(dir: &Path) -> bool {
dir.join("main.py").is_file() && dir.join("comfy").is_dir()
}
/// The installs of Comfy Desktop, the launcher that keeps several ComfyUI
/// installs side by side: `%LOCALAPPDATA%\Comfy-Desktop\ComfyUI-Installs\<name>\ComfyUI`
/// (the layout of the Discord report of 25.10.2026). Its program folder,
/// `%LOCALAPPDATA%\Programs\Comfy Desktop`, holds no ComfyUI of its own.
fn comfy_desktop_installs() -> Vec<PathBuf> {
let Ok(localappdata) = std::env::var("LOCALAPPDATA") else { return Vec::new() };
comfy_desktop_installs_in(&PathBuf::from(localappdata).join("Comfy-Desktop").join("ComfyUI-Installs"))
}
fn comfy_desktop_installs_in(installs: &Path) -> Vec<PathBuf> {
let Ok(list) = fs::read_dir(installs) else { return Vec::new() };
let mut out: Vec<PathBuf> = list
.flatten()
.map(|e| e.path())
.filter_map(|p| if is_comfyui_dir(&p) { Some(p) } else { nested_comfyui_dir(&p) })
.collect();
out.sort();
out
}
/// Inside Comfy Desktop's program folder (`...\Programs\Comfy Desktop`)?
fn in_comfy_desktop_program(p: &Path) -> bool {
p.to_string_lossy().split(['\\', '/']).any(|seg| seg.eq_ignore_ascii_case("Comfy Desktop"))
}
/// Best-effort: turn whatever the user/auto-detector handed us into a
/// directory that contains `main.py`. Accepts either:
/// - A directory with `main.py` (classic / portable / from-source install)
/// - A directory whose `ComfyUI` subfolder has `main.py` (the portable
/// archive's outer folder, see `nested_comfyui_dir`)
/// - A directory with `ComfyUI.exe` (Comfy-Org desktop app binary dir) —
/// we then look up the Working Directory via the probe order above.
fn resolve_comfyui_path(input: &str) -> Option<String> {
let p = Path::new(input);
if is_comfyui_dir(p) {
return Some(input.to_string());
}
if let Some(inner) = nested_comfyui_dir(p) {
return Some(inner.to_string_lossy().to_string());
}
if p.join("ComfyUI.exe").exists() {
for candidate in desktop_app_working_dir_candidates() {
if is_comfyui_dir(&candidate) {
return Some(candidate.to_string_lossy().to_string());
}
}
}
if in_comfy_desktop_program(p) {
if let Some(first) = comfy_desktop_installs().into_iter().next() {
return Some(first.to_string_lossy().to_string());
}
}
None
}
/// Whether find_comfyui_path may look beyond the explicit sources (env var,
/// app config) and search the disk. False on macOS: ComfyUI is never used
/// there, and the search would trip the Desktop and Music permission dialogs.
pub(crate) fn comfyui_disk_search_allowed() -> bool {
!cfg!(target_os = "macos")
}
pub fn find_comfyui_path() -> Option<String> {
// 1. Check environment variable
if let Ok(env_path) = std::env::var("COMFYUI_PATH") {
if let Some(p) = resolve_comfyui_path(&env_path) {
return Some(p);
}
}
// 2. Read from app config
{
let config_file = crate::os_paths::app_config_json();
if config_file.exists() {
if let Ok(content) = fs::read_to_string(&config_file) {
if let Ok(config) = serde_json::from_str::<serde_json::Value>(&content) {
if let Some(path) = config.get("comfyui_path").and_then(|v| v.as_str()) {
if let Some(resolved) = resolve_comfyui_path(path) {
return Some(resolved);
}
}
}
}
}
}
// 3. Filesystem search. macOS never runs ComfyUI (local media is MLX
// only, see auto_start_comfyui), so on a Mac the search ends with the
// explicit sources above. Walking the disk there is not only wasted
// time: the deep home walk below crosses ~/Desktop and ~/Music, and
// macOS answers the first touch of each with a permission dialog ("LU
// wants to access Apple Music" / "the Desktop folder"). Seen on the
// 2.6.8 test bundle at launch, while the window still said LOADING,
// because check_model_sizes and find_comfyui both land here.
if !comfyui_disk_search_allowed() {
return None;
}
let home = dirs::home_dir().unwrap_or_default();
// 3. Check common fixed locations (including Stability Matrix, portable installs)
let mut fixed: Vec<PathBuf> = vec![
home.join("ComfyUI"),
home.join("Desktop").join("ComfyUI"),
home.join("Documents").join("ComfyUI"),
PathBuf::from("C:\\ComfyUI"),
PathBuf::from("D:\\ComfyUI"),
];
if cfg!(target_os = "windows") {
// Stability Matrix stores ComfyUI in AppData
if let Ok(appdata) = std::env::var("APPDATA") {
fixed.push(PathBuf::from(&appdata).join("StabilityMatrix").join("Packages").join("ComfyUI"));
// Comfy-Org/desktop app working dir (GH #47 2026-05-24)
fixed.push(PathBuf::from(&appdata).join("ComfyUI"));
}
if let Ok(localappdata) = std::env::var("LOCALAPPDATA") {
fixed.push(PathBuf::from(&localappdata).join("StabilityMatrix").join("Packages").join("ComfyUI"));
fixed.push(PathBuf::from(&localappdata).join("ComfyUI"));
}
// Common Program Files locations
fixed.push(PathBuf::from("C:\\Program Files\\ComfyUI"));
fixed.push(PathBuf::from("C:\\AI\\ComfyUI"));
fixed.push(PathBuf::from("D:\\AI\\ComfyUI"));
fixed.extend(comfy_desktop_installs());
}
for p in &fixed {
if is_comfyui_dir(p) {
return Some(p.to_string_lossy().to_string());
}
}
// 3b. Deep scan of the user home (finds ComfyUI in non-standard paths like
// Desktop/bs/IMage Gen/ComfyUI). Runs AFTER config + fixed locations: as a
// FIRST candidate its directory-walk order could pick a stale second copy
// over the standard install — LU then downloads/checks models in a folder
// the running ComfyUI never scans ("installed but not recognized",
// Discord 2026-07-27). Same lesson as d9146e3 ("deep home scan
// last").
if let Some(found) = scan_for_comfyui(&home, 7) {
println!("[ComfyUI] Found via deep home scan: {}", found.display());
return Some(found.to_string_lossy().to_string());
}
// 4. Recursive scan of Desktop, Documents, Downloads, and drive roots
let mut scan_roots: Vec<PathBuf> = vec![
home.join("Desktop"),
home.join("Documents"),
home.join("Downloads"),
];
if cfg!(target_os = "windows") {
scan_roots.push(PathBuf::from("C:\\"));
scan_roots.push(PathBuf::from("D:\\"));
scan_roots.push(PathBuf::from("E:\\"));
} else {
scan_roots.push(PathBuf::from("/opt"));
scan_roots.push(PathBuf::from("/usr/local"));
}
for root in &scan_roots {
if root.exists() {
if let Some(found) = scan_for_comfyui(root, 5) {
return Some(found.to_string_lossy().to_string());
}
}
}
None
}
/// Information about a discovered ComfyUI install — surfaced to the
/// frontend so the user picks the right one when multiple coexist.
///
/// Background (Bug #3 — v2.4.3): a user with both a manual
/// `C:\Users\admin\ComfyUI` install (complete, with its own python_embeded)
/// AND an empty `C:\ComfyUI-ai` directory hit `find_comfyui_path()` which
/// returned only the first hit (their manual install). LU then tried to
/// drive that install using the system Python — incompatible with the
/// dir's bundled python_embeded — and ComfyUI loaded indefinitely. The
/// "complete + has_embedded_python" fields let the onboarding UI explain
/// which path to pick and why.
#[derive(serde::Serialize, Clone, Debug)]
pub struct ComfyUIInstall {
pub path: String,
/// True when this directory looks ready to start without any further
/// pip steps (main.py + torch reachable). Same heuristic as
/// `is_comfyui_install_complete`.
pub complete: bool,
/// True when the directory ships its own `python_embeded\python.exe`.
/// Portable ComfyUI builds (and Stability Matrix packages) ship one;
/// from-source clones don't. We start ComfyUI with this Python when
/// present — using the system Python on a portable install was the
/// exact failure mode a user hit.
pub has_embedded_python: bool,
/// Where we found this install. Helps the user disambiguate.
pub source: String,
}
fn classify_comfy_install(path: &Path, source: &str) -> ComfyUIInstall {
let has_embed = path.join("python_embeded").join("python.exe").exists()
|| path
.parent()
.map(|p| p.join("python_embeded").join("python.exe").exists())
.unwrap_or(false);
ComfyUIInstall {
path: path.to_string_lossy().to_string(),
complete: is_comfyui_install_complete(path),
has_embedded_python: has_embed,
source: source.to_string(),
}
}
/// Enumerate every plausible ComfyUI install on the box. Used by the
/// onboarding UI to decide between auto-pick (one hit) and an explicit
/// picker (multiple hits).
///
/// Performance contract: this MUST finish in under ~3 s even on machines
/// with deep file trees. The implementation is `async` so it runs on
/// tokio's blocking-thread pool instead of the IPC main thread — without
/// that the Tauri WebView lock-up on a 200k-file home dir made the whole
/// app report "Not responding" during the ComfyUI step. (Bug #3 sweep,
/// found during E2E 2026-05-11.)
///
/// Scan tiers, in order:
/// 1. Explicit pointers — env var, config.json
/// 2. Well-known fixed locations (home/Desktop/Documents/StabilityMatrix/…)
/// 3. Bounded deep scan of the user's data dirs (depth 4, skip noise)
/// We DO NOT walk C:\, D:\, E:\ from their roots anymore — that path was
/// the locker. find_comfyui_path keeps its drive-root fallback for the
/// single-hit auto-pick case which can afford a slow first-match exit.
#[tauri::command]
pub async fn detect_all_comfyui_installs() -> Vec<ComfyUIInstall> {
tokio::task::spawn_blocking(detect_all_comfyui_installs_sync)
.await
.unwrap_or_default()
}
const MAX_MULTI_DETECT_HITS: usize = 16;
const MULTI_DETECT_DEPTH: i32 = 4;
fn detect_all_comfyui_installs_sync() -> Vec<ComfyUIInstall> {
let mut out: Vec<ComfyUIInstall> = Vec::new();
let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
let push_if_new = |path: PathBuf, source: &str, out: &mut Vec<ComfyUIInstall>, seen: &mut std::collections::HashSet<String>| -> bool {
if !is_comfyui_dir(&path) {
return false;
}
// Canonicalise to dedupe symlinks / case-different paths on Windows
let key = std::fs::canonicalize(&path)
.map(|c| c.to_string_lossy().to_string())
.unwrap_or_else(|_| path.to_string_lossy().to_string())
.to_lowercase();
if seen.insert(key) {
out.push(classify_comfy_install(&path, source));
return true;
}
false
};
// 1. COMFYUI_PATH env var
if let Ok(env_path) = std::env::var("COMFYUI_PATH") {
push_if_new(PathBuf::from(&env_path), "COMFYUI_PATH env var", &mut out, &mut seen);
}
// 2. app config.json
{
let config_file = crate::os_paths::app_config_json();
if let Ok(content) = fs::read_to_string(&config_file) {
if let Ok(config) = serde_json::from_str::<serde_json::Value>(&content) {
if let Some(path) = config.get("comfyui_path").and_then(|v| v.as_str()) {
push_if_new(PathBuf::from(path), "config.json", &mut out, &mut seen);
}
}
}
}
let home = dirs::home_dir().unwrap_or_default();
// 3. Well-known fixed locations
let mut fixed: Vec<(PathBuf, &str)> = vec![
(home.join("ComfyUI"), "home"),
(home.join("Desktop").join("ComfyUI"), "Desktop"),
(home.join("Documents").join("ComfyUI"), "Documents"),
(PathBuf::from("C:\\ComfyUI"), "C:\\"),
(PathBuf::from("D:\\ComfyUI"), "D:\\"),
];
if cfg!(target_os = "windows") {
if let Ok(appdata) = std::env::var("APPDATA") {
fixed.push((PathBuf::from(&appdata).join("StabilityMatrix").join("Packages").join("ComfyUI"), "StabilityMatrix"));
// Comfy-Org/desktop default Working Directory hint (GH #47).
fixed.push((PathBuf::from(&appdata).join("ComfyUI"), "Desktop App data"));
}
if let Ok(localappdata) = std::env::var("LOCALAPPDATA") {
fixed.push((PathBuf::from(&localappdata).join("StabilityMatrix").join("Packages").join("ComfyUI"), "StabilityMatrix"));
fixed.push((PathBuf::from(&localappdata).join("ComfyUI"), "Desktop App data"));
}
fixed.push((PathBuf::from("C:\\Program Files\\ComfyUI"), "Program Files"));
fixed.push((PathBuf::from("C:\\AI\\ComfyUI"), "C:\\AI"));
fixed.push((PathBuf::from("D:\\AI\\ComfyUI"), "D:\\AI"));
// ComfyUI Desktop App often pairs its `%LOCALAPPDATA%\Programs\ComfyUI`
// binary with a `%APPDATA%\ComfyUI\config.json` whose `basePath` field
// points at the Working Directory. Honour the hint so users with a
// non-default Working Dir (e.g. on D:\ for space) are still found.
if let Ok(appdata) = std::env::var("APPDATA") {
let cfg = PathBuf::from(&appdata).join("ComfyUI").join("config.json");
if let Ok(raw) = std::fs::read_to_string(&cfg) {
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&raw) {
if let Some(base) = v.get("basePath").and_then(|x| x.as_str()) {
fixed.push((PathBuf::from(base), "Desktop App basePath"));
}
}
}
}
for p in comfy_desktop_installs() {
fixed.push((p, "Comfy Desktop"));
}
}
for (p, source) in fixed {
push_if_new(p, source, &mut out, &mut seen);
}
// 4. Bounded deep scan — user data dirs only. Drive roots (C:\, D:\, E:\)
// are intentionally NOT walked here: the deep walk through hundreds of
// thousands of system files made `detect_all_comfyui_installs` lock
// Tauri for 30+ s on real Windows boxes. Power users with ComfyUI in
// `D:\AI\projects\custom\dir\` still get auto-picked by find_comfyui_path
// (single-hit, slow first-match-exit) — they just don't surface in the
// Multi-ComfyUI picker, which is acceptable: that picker exists for
// accidental multi-install collisions, not exhaustive enumeration.
let scan_roots: Vec<(PathBuf, &str)> = vec![
(home.clone(), "home (deep scan)"),
(home.join("Desktop"), "Desktop"),
(home.join("Documents"), "Documents"),
(home.join("Downloads"), "Downloads"),
];
for (root, source) in &scan_roots {
if out.len() >= MAX_MULTI_DETECT_HITS {
break;
}
if root.exists() {
walk_for_comfyui(root, MULTI_DETECT_DEPTH, &mut |p| {
if out.len() >= MAX_MULTI_DETECT_HITS {
return;
}
push_if_new(p, source, &mut out, &mut seen);
});
}
}
out
}
fn walk_for_comfyui<F: FnMut(PathBuf)>(dir: &Path, depth: i32, cb: &mut F) {
if depth < 0 {
return;
}
if dir.join("main.py").exists() && dir.join("comfy").exists() {
cb(dir.to_path_buf());
// Don't recurse into a confirmed install — its subdirs aren't
// independent installs.
return;
}
let entries = match fs::read_dir(dir) {
Ok(e) => e,
Err(_) => return,
};
for entry in entries.flatten() {
let p = entry.path();
if !p.is_dir() {
continue;
}
// Skip the obvious noise dirs that blow up walk time. node_modules
// and .git are common in dev projects; the rest are system locations
// that should never own a ComfyUI install anyway.
if let Some(name) = p.file_name().and_then(|n| n.to_str()) {
if matches!(name,
"node_modules" | ".git" | "AppData" | "$Recycle.Bin"
| "Windows" | "System32" | "ProgramData" | ".cache"
| "target" | ".cargo" | ".rustup" | ".npm" | ".pnpm"
| "Library" // macOS, harmless on Windows
| "OneDrive" // huge synced trees; ComfyUI shouldn't live there
) {
continue;
}
// Hidden dirs (Linux/macOS dotfiles) are almost never ComfyUI roots.
if name.starts_with('.') && name.len() > 1 {
continue;
}
}
walk_for_comfyui(&p, depth - 1, cb);
}
}
pub(crate) fn is_comfyui_running_on_port(port: u16) -> bool {
reqwest::blocking::get(format!("http://localhost:{}/system_stats", port))
.map(|r| r.status().is_success())
.unwrap_or(false)
}
/// Kill whatever process listens on `port` (2026-07-17, "Let me do it
/// for you" CORS-fix button). Only ever called with the user-configured
/// ComfyUI port, on an explicit button press — LU is about to relaunch that
/// ComfyUI under its own management with the CORS flag. Best effort: a port
/// nobody listens on is a no-op.
fn kill_port_owner(port: u16) {
let own_pid = std::process::id();
#[cfg(target_os = "windows")]
{
let mut cmd = crate::process_util::foreign_system_command("netstat");
cmd.args(["-ano", "-p", "tcp"]);
crate::process_util::suppress_window(&mut cmd);
let Ok(out) = cmd.output() else { return };
let text = String::from_utf8_lossy(&out.stdout);
let needle = format!(":{}", port);
let mut pids: Vec<u32> = Vec::new();
for line in text.lines() {
// Match on the LOCAL address column only; the state column is
// locale-dependent ("LISTENING" / "ABHÖREN"), so don't parse it.
let cols: Vec<&str> = line.split_whitespace().collect();
if cols.len() >= 5 && cols[0].eq_ignore_ascii_case("tcp") && cols[1].ends_with(&needle) {
if let Ok(pid) = cols[cols.len() - 1].parse::<u32>() {
if pid != 0 && pid != own_pid && !pids.contains(&pid) {
pids.push(pid);
}
}
}
}
for pid in pids {
println!("[ComfyUI] CORS fix: killing port {} owner pid {}", port, pid);
let mut kill = crate::process_util::foreign_system_command("taskkill");
kill.args(["/pid", &pid.to_string(), "/T", "/F"]);
crate::process_util::suppress_window(&mut kill);
let _ = kill.output();
}
}
#[cfg(not(target_os = "windows"))]
{
if let Ok(out) = crate::process_util::foreign_system_command("lsof").args(["-ti", &format!("tcp:{}", port), "-sTCP:LISTEN"]).output() {
for line in String::from_utf8_lossy(&out.stdout).lines() {
if let Ok(pid) = line.trim().parse::<u32>() {
if pid != 0 && pid != own_pid {
let _ = crate::process_util::foreign_system_command("kill").args(["-9", &pid.to_string()]).output();
}
}
}
}
}
}
/// Pure: may the CORS fix end the listener on the ComfyUI port? Only when the
/// port answers as ComfyUI, and never from a test build.
fn comfy_port_may_be_freed(answers_as_comfyui: bool, test_build: bool) -> bool {
answers_as_comfyui && !test_build
}
/// One-click fix for the ComfyUI 0.19+ cross-origin block banner (#75/#82
/// follow-up, 2026-07-17): stop the user-managed ComfyUI on the
/// configured port and relaunch it under LU's management — LU-started
/// ComfyUI always carries `--enable-cors-header`, so direct media loads and
/// the native progress feed work again. Requires a known install path; on a
/// remote host LU can't manage the process at all.
// ASYNC + spawn_blocking: a SYNCHRONOUS Tauri command runs on the MAIN thread.
// The State borrow cannot cross into the blocking pool, so the handle is
// re-resolved there from the AppHandle (same pattern as engine.rs/whisper.rs).
#[tauri::command]
pub async fn fix_comfyui_cors(app: tauri::AppHandle) -> Result<serde_json::Value, String> {
tokio::task::spawn_blocking(move || {
let state = app.state::<AppState>();
fix_comfyui_cors_blocking(&state)
})
.await
.map_err(|e| format!("fix_comfyui_cors task: {e}"))?
}
fn fix_comfyui_cors_blocking(state: &AppState) -> Result<serde_json::Value, String> {
let host = state.comfy_host.lock().unwrap().clone();
if !is_local_host(&host) {
return Err(
format!("ComfyUI runs on a remote host, so LU can't restart it from here. Add --enable-cors-header {} to the launch command on that machine instead.", comfy_cors_origin()),
);
}
let path_known = state
.comfy_path
.lock()
.unwrap()
.clone()
.or_else(find_comfyui_path)
.is_some();
if !path_known {
return Err(
format!("LU doesn't know this ComfyUI's folder yet. Set it under Settings → AI Backends → ComfyUI → Path, then press the button again. Or add --enable-cors-header {} to your own launch script.", comfy_cors_origin()),
);
}
let port = *state.comfy_port.lock().unwrap();
// Stop our own child cleanly first (if any), then whatever else owns the port.
{
let mut proc = state.comfy_process.lock().unwrap();
if let Some(ref mut child) = *proc {
let pid = child.id();
#[cfg(target_os = "windows")]
{
let mut cmd = crate::process_util::foreign_system_command("taskkill");
cmd.args(["/pid", &pid.to_string(), "/T", "/F"]);
crate::process_util::suppress_window(&mut cmd);
let _ = cmd.output();
}
#[cfg(not(target_os = "windows"))]
let _ = child.kill();
info!(pid = pid, "cors fix: stopped LU-managed comfyui");
*proc = None;
}
}
// Only a ComfyUI. The button exists for the ComfyUI behind the CORS
// banner; whatever else listens on the port (another app, a second LU's
// ComfyUI that stopped answering) is not this click's to end (N3, 3.1.0).
if comfy_port_may_be_freed(is_comfyui_running_on_port(port), cfg!(test)) {
kill_port_owner(port);
}
// Wait for the port to actually free up — start_comfyui short-circuits
// with "already_running" while the old process is still winding down.
for _ in 0..20 {
if !is_comfyui_running_on_port(port) {
break;
}
std::thread::sleep(std::time::Duration::from_millis(400));
}
start_comfyui_blocking(state)
}
// ASYNC + spawn_blocking: a SYNCHRONOUS Tauri command runs on the MAIN thread.
// The State borrow cannot cross into the blocking pool, so the handle is
// re-resolved there from the AppHandle (same pattern as engine.rs/whisper.rs).
#[tauri::command]
pub async fn start_ollama(app: tauri::AppHandle) -> Result<serde_json::Value, String> {
tokio::task::spawn_blocking(move || {
let state = app.state::<AppState>();
start_ollama_blocking(&state)
})
.await
.map_err(|e| format!("start_ollama task: {e}"))?
}
/// Serialise a "check that nothing runs, then spawn it" path.
///
/// These used to be serialised BY ACCIDENT: a synchronous `#[tauri::command]`
/// runs on the Tauri main thread, so two invocations could never overlap. Now
/// that the bodies run on the blocking pool, two triggers close together (a
/// mount effect alongside a click, a double click, onboarding's retry loop) can
/// BOTH pass the "nothing is running" check — the window between that check and
/// storing the child is long, it contains a filesystem search — and both spawn a
/// server. Only the second child gets stored, so the first is an orphan holding
/// VRAM that no stop_* will ever kill. That orphan is exactly the zombie
/// `start_comfyui` warns about a few lines below.
///
/// The second caller waits instead of being turned away, so once it proceeds the
/// normal "already running" check answers it — no new status value, no change
/// for the frontend.
pub(crate) fn start_gate(lock: &'static Mutex<()>) -> std::sync::MutexGuard<'static, ()> {
lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
pub(crate) static COMFY_START: Mutex<()> = Mutex::new(());
pub(crate) static OLLAMA_START: Mutex<()> = Mutex::new(());
pub(crate) static ENGINE_START: Mutex<()> = Mutex::new(());
pub(crate) static EMBED_START: Mutex<()> = Mutex::new(());
/// Is an Ollama server already listening?
///
/// This used to shell out to `tasklist /FI "IMAGENAME eq ollama.exe"` — a
/// WINDOWS-only command, run unconditionally on every platform. Observed live
/// on macOS 2026-07-28: the spawn fails, `if let Ok(output)` is false, the
/// check is skipped entirely, and the app starts a SECOND `ollama serve` that
/// cannot bind 11434 and dies within milliseconds. The dead child is then
/// stored in AppState as the tracked server, and the log claims "Started".
///
/// The port is what actually matters — an Ollama started by launchd, a service
/// or Docker counts just as much as one whose process happens to be named
/// ollama.exe — so probe that instead. Same shape as lmstudio_port_open.
fn ollama_port_open() -> bool {
use std::net::{SocketAddr, TcpStream};
let addr: SocketAddr = ([127, 0, 0, 1], 11434).into();
TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(300)).is_ok()
}
/// The Ollama CLI inside the app bundle, for a Mac where Ollama.app is
/// installed but its command line link was never created: system-wide first,
/// then the per-user Applications folder.
#[cfg(any(target_os = "macos", test))]
pub(crate) fn ollama_bundle_candidates(home: &std::path::Path) -> Vec<PathBuf> {
const INSIDE: &str = "Ollama.app/Contents/Resources/ollama";
vec![
PathBuf::from("/Applications").join(INSIDE),
home.join("Applications").join(INSIDE),
]
}
/// Where the Ollama CLI is on this Mac, or `None` when it is not installed.
///
/// Fehlerkontrolle Mac 2, Fund 2: every start went through a bare
/// `Command::new("ollama")`. An app opened from the Finder has the launchd
/// PATH (`/usr/bin:/bin:/usr/sbin:/sbin`), Ollama.app puts its CLI into
/// `/usr/local/bin` and Homebrew into `/opt/homebrew/bin`, so the start
/// failed with "No such file or directory" and the onboarding told a user
/// with Ollama installed to go and download it. PATH is still asked first.
///
/// `open -a Ollama` was the other way to start it and is not used: it starts
/// the menu bar app, which this app would neither hold as a child nor stop on
/// quit, while `serve` from the same bundle is the process `ollama_process`
/// already tracks and reaps.
#[cfg(target_os = "macos")]
pub(crate) fn find_ollama() -> Option<PathBuf> {
crate::finder_path::resolve_tool(
"ollama",
&ollama_bundle_candidates(&crate::os_paths::home()),
)
}
/// The program every `ollama serve` is started with: the resolved full path
/// on a Mac, the bare name everywhere else (and on a Mac without Ollama, so
/// the spawn fails with the same "not found" it always did).
pub(crate) fn ollama_program() -> std::ffi::OsString {
#[cfg(target_os = "macos")]
if let Some(found) = find_ollama() {
return found.into_os_string();
}
"ollama".into()
}
fn start_ollama_blocking(state: &AppState) -> Result<serde_json::Value, String> {
let _gate = start_gate(&OLLAMA_START);
if ollama_port_open() {
println!("[Ollama] Already running");
return Ok(serde_json::json!({"status": "already_running"}));
}
println!("[Ollama] Starting...");
// K14: a foreign program, never something LU bundles.
let mut cmd = crate::process_util::foreign_system_command(ollama_program());
cmd.arg("serve")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
// Bug BB v2.5.0 — a user. Forward the user's GPU pick as
// CUDA_VISIBLE_DEVICES / HIP_VISIBLE_DEVICES / ONEAPI_DEVICE_SELECTOR
// so Ollama uses the pinned card on multi-vendor / multi-GPU machines.
// No-op when the pick is "auto" (default).
// B2 fix (review-w2rust.md): apply_gpu_env can now shell out to
// nvidia-smi (GPU-UUID resolution) instead of doing zero I/O, so the
// lock is held only long enough to clone the small selection out --
// never across the detection call, which would freeze the Hardware
// tab's set_gpu_selection/get_gpu_selection (same mutex) for however
// long that subprocess I/O takes.
// 3.0.8 (A2): the chat role's card when one is set, the global pick
// otherwise (commands/gpu_roles.rs).
// 3.1.0: through apply_role_env, the one helper the boot start uses too.
crate::commands::gpu_roles::apply_role_env(state, crate::commands::gpu_roles::GpuRole::Chat, &mut cmd);
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
let result = cmd.spawn();
match result {
Ok(child) => {
// Store the Child so AppState::Drop kills our spawned ollama on
// shutdown (a user — Discord 2026-05-23 #help-chat 1507756765612216411).
// Note: tasklist check above means we only get here if WE start it,
// so we never kill a user-managed ollama serve.
//
// The Drop only covers a shutdown that runs. A hard kill of the app
// does not run one, so the child also joins the kill-on-close job.
tie_child_to_app_lifetime(child.id());
*state.ollama_process.lock().unwrap() = Some(child);
println!("[Ollama] Started");
info!("ollama spawned");
Ok(serde_json::json!({"status": "started"}))
}
Err(e) => {
println!("[Ollama] Failed to start: {}", e);
error!(error = %e, "ollama spawn failed");
Ok(serde_json::json!({"status": "error", "error": os_error::english(&e)}))
}
}
}
/// Does `python` have a working flash-attn? Real import test (not pip-list):
/// a half-installed or ABI-mismatched wheel fails the import, and we must
/// never pass `--use-flash-attention` then — ComfyUI would error at startup.
///
/// Three-state result: Some(true) = import OK, Some(false) = the process
/// DEFINITIVELY failed (ImportError etc.), None = timeout / couldn't spawn.
/// The distinction matters for caching: importing flash_attn loads torch,
/// which is ~4 s warm but can blow well past 25 s during an app-boot disk
/// storm (live miss 2026-06-11: flag silently absent for the whole session
/// because a cold-start timeout was cached as "not installed").
pub(crate) fn probe_flash_attention(python: &str) -> Option<bool> {
if python.is_empty() {
return Some(false);
}
let mut cmd = python_command(python);
cmd.args(["-c", "from flash_attn import flash_attn_func"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
let mut child = match cmd.spawn() {
Ok(c) => c,
Err(_) => return None,
};
// 90 s ceiling: an ABSENT package fails fast (ModuleNotFoundError in
// seconds), so the long window only ever delays a start where flash-attn
// exists but the disk is busy — exactly the case worth waiting for.
for _ in 0..450 {
match child.try_wait() {
Ok(Some(status)) => return Some(status.success()),
Ok(None) => std::thread::sleep(std::time::Duration::from_millis(200)),
Err(_) => return None,
}
}
let _ = child.kill();
None
}
/// Probe with per-python cache. Only DEFINITIVE results are cached — a
/// timeout returns false for this call but is retried on the next start,
/// so one slow boot can't disable Flash Attention for the whole session.
fn flash_attention_cached(state: &AppState, python: &str) -> bool {
if let Some(v) = state.flash_attn_cache.lock().unwrap().get(python).copied() {
return v;
}
match probe_flash_attention(python) {
Some(v) => {
state
.flash_attn_cache
.lock()
.unwrap()
.insert(python.to_string(), v);
v
}
None => {
println!("[ComfyUI] flash-attn probe timed out — starting without the flag (will retry next start)");
false
}
}
}
/// GPU-aware version of the Bug J `--cpu` check used at ComfyUI start. Only
/// probes the comfy python's torch when it might change the answer (Auto + no
/// NVIDIA driver), so NVIDIA machines keep the EXACT fast-path they had before.
fn comfy_needs_cpu(
python: &str,
mode: ComfyGpuMode,
cache: Option<&Mutex<HashMap<String, Option<&'static str>>>>,
) -> ComfyCpuDecision {
let baseline = needs_cpu_fallback();
let torch_gpu = if mode == ComfyGpuMode::Auto && baseline && !python.is_empty() {
comfy_gpu_available_cached(python, cache)
} else {
None
};
ComfyCpuDecision {
needs_cpu: decide_comfy_cpu_flag(mode, baseline, torch_gpu),
baseline,
torch_gpu,
}
}
/// Das Ergebnis der Entscheidung samt der zwei Tatsachen, aus denen sie
/// entstand. Die beiden wurden vorher weggeworfen, und genau deshalb musste
/// die Zeile im Ausgabefenster raten, warum der Prozessor drankommt.
struct ComfyCpuDecision {
/// Kommt `--cpu` an die Kommandozeile?
needs_cpu: bool,
/// `needs_cpu_fallback()`: kein NVIDIA-Treiber und kein macOS.
baseline: bool,
/// Was das torch dieser Umgebung ueber eine brauchbare Karte sagt.
torch_gpu: Option<bool>,
}
/// torch-GPU probe with an optional per-python cache (mirrors flash_attention_cached).
/// Only DEFINITIVE results are cached; a timeout returns None and is retried next start.
fn comfy_gpu_available_cached(
python: &str,
cache: Option<&Mutex<HashMap<String, Option<&'static str>>>>,
) -> Option<bool> {
comfy_gpu_device_cached(python, cache).map(|d| d.is_some())
}
/// The same probe, keeping which device answered, so the start can tell a
/// DirectML environment (needs `--directml`) from a CUDA/ROCm/XPU one.
fn comfy_gpu_device_cached(
python: &str,
cache: Option<&Mutex<HashMap<String, Option<&'static str>>>>,
) -> Option<Option<&'static str>> {
if let Some(c) = cache {
if let Some(v) = c.lock().unwrap().get(python).copied() {
return Some(v);
}
}
match probe_comfy_device(python) {
Some(v) => {
if let Some(c) = cache {
c.lock().unwrap().insert(python.to_string(), v);
}
Some(v)
}
None => {
println!("[ComfyUI] GPU probe timed out — treating as no accel for this start (will retry)");
None
}
}
}
/// The device flag ComfyUI needs beyond dropping `--cpu`, if any.
///
/// Only DirectML needs one: ComfyUI asks `torch.cuda` unless `--directml` is
/// given, and a DirectML torch has no CUDA. Without the flag Auto read such an
/// environment as "no GPU" and started it with `--cpu`. Never on a machine
/// with an NVIDIA driver (baseline false), never under Force CPU.
pub(crate) fn comfy_device_flag(
mode: ComfyGpuMode,
baseline_needs_cpu: bool,
device: Option<&str>,
) -> Option<&'static str> {
if mode == ComfyGpuMode::ForceCpu || !baseline_needs_cpu {
return None;
}
(device == Some("directml")).then_some("--directml")
}
/// What the start asks before it builds the command line: the device flag, if
/// one is needed. Probes only where it can matter (no NVIDIA driver, not Force
/// CPU), from the same cache as the --cpu decision, so it costs no second
/// torch import.
fn comfy_launch_device_flag(
python: &str,
mode: ComfyGpuMode,
baseline_needs_cpu: bool,
cache: Option<&Mutex<HashMap<String, Option<&'static str>>>>,
) -> Option<&'static str> {
if mode == ComfyGpuMode::ForceCpu || !baseline_needs_cpu || python.is_empty() {
return None;
}
let device = comfy_gpu_device_cached(python, cache).flatten();
comfy_device_flag(mode, baseline_needs_cpu, device)
}
/// What the probe asks torch. CUDA covers NVIDIA, ROCm and ZLUDA, which all
/// answer through `torch.cuda`. Intel Arc answers through `torch.xpu`, which
/// only exists in torch 2.4 and later, hence the `hasattr` guard.
///
/// 3.0.7: the probe asked `torch.cuda` alone, so an Intel XPU torch read as
/// "no GPU" and Auto started ComfyUI with --cpu on a working Arc card, while
/// ComfyUI itself would have found the card without any flag.
///
/// 3.0.8: a torch-directml environment answers 'directml'. Its torch is a
/// processor build with DirectML bolted on, so `torch.cuda` says no, and
/// ComfyUI only reaches the card when it is started with `--directml`. Asked
/// last and through `find_spec`, so it costs nothing on any other box.
const COMFY_GPU_PROBE: &str = "import torch, importlib.util as u; print('cuda' if torch.cuda.is_available() else \
'xpu' if hasattr(torch, 'xpu') and torch.xpu.is_available() else \
'directml' if u.find_spec('torch_directml') else 'none')";
/// The device the probe printed, or None when it named none. Reads the last
/// line that says anything, because a torch import can print a warning first.
pub(crate) fn parse_comfy_gpu_probe(stdout: &str) -> Option<&'static str> {
match stdout.lines().map(str::trim).rfind(|l| !l.is_empty())? {
"cuda" => Some("cuda"),
"xpu" => Some("xpu"),
"directml" => Some("directml"),
_ => None,
}
}
/// Does `python`'s torch report a usable GPU (CUDA / ROCm / ZLUDA / Intel XPU)?
///
/// `torch.cuda.is_available()` and `torch.xpu.is_available()` are SAFE, they
/// never raise (unlike `current_device()`): on a stock-CUDA torch on an AMD box
/// they simply return False. So this cleanly separates "GPU torch → run on the
/// GPU" from "stock torch, no GPU → --cpu". A torch that fails to import prints
/// nothing and reads as no GPU, as before. Some(true/false) = definitive,
/// None = timeout / spawn fail.
pub(crate) fn probe_comfy_gpu(python: &str) -> Option<bool> {
probe_comfy_device(python).map(|d| d.is_some())
}
/// The device the environment's torch offers: Some(Some("cuda" | "xpu" |
/// "directml")), Some(None) for none, None when the probe did not answer.
pub(crate) fn probe_comfy_device(python: &str) -> Option<Option<&'static str>> {
if python.is_empty() {
return Some(None);
}
let mut cmd = python_command(python);
cmd.args(["-c", COMFY_GPU_PROBE])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null());
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
let mut child = match cmd.spawn() {
Ok(c) => c,
Err(_) => return None,
};
// 60 s ceiling: torch import is ~4 s warm but can lag during an app-boot disk
// storm; a missing/broken torch exits non-zero fast.
// The answer is one short word, far below a pipe buffer, so waiting for
// the exit before reading cannot block the child.
for _ in 0..300 {
match child.try_wait() {
Ok(Some(_)) => {
let mut out = String::new();
if let Some(mut pipe) = child.stdout.take() {
use std::io::Read;
let _ = pipe.read_to_string(&mut out);
}
let device = parse_comfy_gpu_probe(&out);
println!("[ComfyUI] GPU probe: torch reports {}", device.unwrap_or("no GPU"));
return Some(device);
}
Ok(None) => std::thread::sleep(std::time::Duration::from_millis(200)),
Err(_) => return None,
}
}
let _ = child.kill();
None
}
// The `check_flash_attention` Tauri command + its `resolve_comfyui_python`
// helper were removed in 2.5.8: the 2.5.7 Create redesign dropped the flash-attn
// hint UI that was their only caller, leaving them orphaned (#74). The probe
// itself (probe_flash_attention / flash_attention_cached, above) stays — both
// start_comfyui and the boot auto-start use it to gate `--use-flash-attention`.
// Note: ComfyUI's flash path is FA2-only (`from flash_attn import ...`); FA3
// (module `flash_attn_3`) is a different API ComfyUI does not consume, so the
// FA2 import probe is the correct signal.
// ASYNC + spawn_blocking: a SYNCHRONOUS Tauri command runs on the MAIN thread.
// The State borrow cannot cross into the blocking pool, so the handle is
// re-resolved there from the AppHandle (same pattern as engine.rs/whisper.rs).
#[tauri::command]
pub async fn start_comfyui(app: tauri::AppHandle) -> Result<serde_json::Value, String> {
tokio::task::spawn_blocking(move || {
let state = app.state::<AppState>();
start_comfyui_blocking(&state)
})
.await
.map_err(|e| format!("start_comfyui task: {e}"))?
}
pub(crate) fn start_comfyui_blocking(state: &AppState) -> Result<serde_json::Value, String> {
let gate = start_gate(&COMFY_START);
// If user pointed LU at a remote ComfyUI, we have no local process to spawn.
// Just report status — the remote side is responsible for running ComfyUI.
{
let host = state.comfy_host.lock().unwrap().clone();
if !is_local_host(&host) {
return Ok(serde_json::json!({
"status": "remote",
"host": host,
"message": "Remote ComfyUI — manage the Python process on the server itself"
}));
}
}
// macOS is MLX-only for local media — a hard product rule, not a preference.
// The frontend hides every ComfyUI surface there, but the frontend is not
// the only caller: the remote/mobile control surface reaches these commands
// directly, and any future caller would too. Refusing here is what actually
// makes the rule true. The remote-host branch above still answers, so a Mac
// pointed at someone else's ComfyUI keeps working — only spawning a local
// one is refused.
if !comfy_supported_here() {
return Err(MACOS_COMFY_REFUSAL.to_string());
}
let port = *state.comfy_port.lock().unwrap();
if is_comfyui_running_on_port(port) {
// T-68: say WHOSE ComfyUI that is. "already_running" alone is what let
// an orphan of a hard-killed session look identical to a ComfyUI the
// user started — and Stop behaved as if both were untouchable.
let orphan = find_orphaned_comfyui(port);
if let Some(pid) = orphan {
println!("[ComfyUI] Already running on port {port} — orphan of an earlier session (pid {pid}); Stop can adopt it");
info!(pid = pid, port = port, "comfyui orphan found on start");
}
return Ok(serde_json::json!({
"status": "already_running",
"adoptable": orphan.is_some(),
}));
}
// The port probe alone misses a ComfyUI that is STARTING: it imports for
// 20-60s before it binds the port. Spawning a second copy in that window
// overwrites the tracked child handle — the first child keeps running
// untracked, wins the port bind, and every later stop/restart kills only
// the tracked twin while the zombie keeps serving the stale node list
// (the "install spinner never ends" chain). Report 'starting' instead;
// callers already poll the connection afterwards.
{
let mut proc = state.comfy_process.lock().unwrap();
if let Some(child) = proc.as_mut() {
match child.try_wait() {
Ok(None) => return Ok(serde_json::json!({"status": "starting"})),
_ => *proc = None, // exited or unreapable — clear and start fresh
}
}
}
let comfy_path = {
let path = state.comfy_path.lock().unwrap();
path.clone()
};
let comfy_path = comfy_path
.or_else(find_comfyui_path)
.ok_or_else(|| "ComfyUI not found".to_string())?;
// Store the path for future use
{
let mut path = state.comfy_path.lock().unwrap();
*path = Some(comfy_path.clone());
}
// Prefer the portable's bundled Python over the system one. ComfyUI
// Portable (NVIDIA, AMD, CPU variants) ships its own Python with the
// matching torch wheel pre-installed — using the system Python instead
// wastes that and on AMD it actively fails because system Python lacks
// the DirectML / ROCm bindings the portable installer prepared. Layout:
// <ComfyUI>/python_embeded/python.exe ← what we want
// <ComfyUI>/main.py
// Fixed Discord report from: AMD Portable launchte nicht.
let portable_python = std::path::Path::new(&comfy_path)
.parent()
.and_then(|p| {
let candidate = p.join("python_embeded").join("python.exe");
if candidate.exists() { Some(candidate.to_string_lossy().to_string()) } else { None }
});
let bundled_python = portable_python.or_else(|| {
// Some portable variants nest python_embeded inside the ComfyUI dir
// itself rather than alongside it.
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 (a user — 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.
// 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 comfy_dir = std::path::Path::new(&comfy_path);
// Discord 14.10.2026: without a venv not blindly the default Python, but
// the one that holds this install's torch, remembered per folder.
let python = launch_python(bundled_python.as_deref(), &venv_state, comfy_dir, || {
bound_comfy_python(comfy_dir, &system_python)
})
.inspect_err(|e| error!(comfyui = %comfy_path, "comfyui start refused: {e}"))?;
let port_str = port.to_string();
if bundled_python.is_some() {
println!("[ComfyUI] Using bundled portable Python: {}", python);
} else if has_usable_venv {
println!("[ComfyUI] Using ComfyUI venv Python: {}", python);
} else {
println!("[ComfyUI] No venv here, using the Python that holds torch: {}", python);
}
println!("[ComfyUI] Starting from: {} on port {}", comfy_path, port);
info!(port = port, "comfyui start");
// Bug J (discovered during 2026-05-17 Arch live test): on systems without
// an NVIDIA driver (most Linux non-NVIDIA setups: AMD, Intel, CPU-only;
// also Windows boxes without an NVIDIA card), ComfyUI's main.py calls
// get_torch_device() → torch.cuda.current_device() → which raises
// `RuntimeError: Found no NVIDIA driver on your system` before
// main.py ever binds the port. The user sees LU stuck on "ComfyUI
// loading..." (which Bug B's 60-s panel now correctly surfaces, but
// the underlying spawn-then-crash loop wastes the user's time on every
// start). Detect NVIDIA via `nvidia-smi` and pass --cpu when absent,
// except on macOS where PyTorch uses MPS and never calls cuda APIs.
let gpu_mode = ComfyGpuMode::parse(&state.comfy_gpu_mode.lock().unwrap());
let cpu_decision = comfy_needs_cpu(&python, gpu_mode, Some(&state.comfy_gpu_cache));
let needs_cpu_fallback = cpu_decision.needs_cpu;
// A user (RX 7900 XTX): remember what we actually launched with so
// the Create tab can warn instead of letting a CPU gen time out silently.
*state.comfy_started_cpu.lock().unwrap() = Some(needs_cpu_fallback);
// Force GPU skips the probe above on purpose, so ask separately and only
// in that mode: the answer costs a torch import once per python path and
// buys the sentence that explains the crash that is about to happen.
let force_gpu_note = if gpu_mode == ComfyGpuMode::ForceGpu {
let (_, has_amd, amd_names) = crate::commands::torch_wheels::gpu_vendor_facts();
let amd_refs: Vec<&str> = amd_names.iter().map(String::as_str).collect();
force_gpu_warning_for(
gpu_mode,
comfy_gpu_available_cached(&python, Some(&state.comfy_gpu_cache)),
has_amd,
crate::commands::torch_wheels::amd_rocm_served(&amd_refs, std::env::consts::OS),
std::env::consts::OS,
)
} else {
None
};
if let Some(note) = &force_gpu_note {
println!("[ComfyUI] {note}");
}
let mut comfy_args: Vec<&str> = vec![
"main.py",
"--listen", "127.0.0.1",
"--port", &port_str,
"--enable-cors-header", comfy_cors_origin(),
];
let mut device_flag: Option<&'static str> = None;
if needs_cpu_fallback {
comfy_args.push("--cpu");
if let Some(reason) = cpu_flag_reason(gpu_mode, cpu_decision.baseline, cpu_decision.torch_gpu) {
println!("[ComfyUI] {reason}");
}
} else if let Some(flag) =
comfy_launch_device_flag(&python, gpu_mode, cpu_decision.baseline, Some(&state.comfy_gpu_cache))
{
comfy_args.push(flag);
device_flag = Some(flag);
println!("[ComfyUI] torch-directml found in this environment, starting ComfyUI with {flag}");
}
// One attention flag at most (comfy_attention.rs): Comfy Kitchen on a
// CUDA or ROCm torch with ComfyUI 0.32.0+, otherwise Flash Attention when
// the package actually imports in THIS python (2026-06-11: measured 4-5x
// faster WAN video sampling vs pytorch SDPA on a 12 GB 3060). ComfyUI only
// uses FA2 with the flag, so an installed wheel does nothing without it.
// The real-import probes guarantee we never pass a flag on a broken
// install (ComfyUI would error at startup); results are cached per python
// path. CPU mode skips both, flash-attn is CUDA-only.
let attention = comfy_attention_choice(
state,
&python,
comfy_dir,
needs_cpu_fallback,
device_flag,
cpu_decision.baseline,
);
if let Some(flag) = attention.flag {
comfy_args.push(flag);
if flag == comfy_attention::CK_FLAG {
println!("[ComfyUI] comfy_kitchen imports in {python}, enabling Comfy Kitchen attention ({flag})");
} else {
println!("[ComfyUI] flash-attn detected in {python}, enabling Flash Attention");
}
}
// The folder under Settings -> Storage, when it holds ComfyUI-shaped
// subfolders (GH #122). ComfyUI lists only what sits under its own models
// 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. 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");
comfy_args.push(file);
println!("[ComfyUI] Extra model paths: {}", file);
}
// GH #183: what the user's own start script hands ComfyUI (more model
// path configs, input and output folders). LU starts `main.py` directly,
// so without this a ComfyUI that LU starts ignored all of it.
let user_args = crate::commands::comfy_user_paths::UserComfyPaths::discover(Path::new(&comfy_path)).launch_args();
if !user_args.is_empty() {
println!("[ComfyUI] From the start script: {}", user_args.join(" "));
}
comfy_args.extend(user_args.iter().map(String::as_str));
let mut cmd = python_command(&python);
cmd.args(&comfy_args)
.current_dir(&comfy_path)
.env("TQDM_DISABLE", "1")
.env("PYTHONUNBUFFERED", "1")
// Die UTF-8-Umgebung fuer dieses Kind setzt python_command oben, nicht
// diese Kette. Warum sie hier lebensnotwendig ist (Discord
// 07.06.2026): ComfyUI und seine Knoten drucken Unicode-Zeichen fuer den
// Fortschritt nach stdout. Auf einer Windows-Konsole ohne UTF-8 nimmt
// Pythons umgeleitetes stdout den Codec der Systemsprache und wirft
// einen UnicodeEncodeError, der aus dem Fortschrittsaufruf des KSampler
// herausfaellt und die Erzeugung abbricht. Ausserdem haelt es die
// Annahme des Zeilenlesers auf der Rust-Seite gueltig, dass die Ausgabe
// UTF-8 ist.
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
// Bug BB v2.5.0 — same GPU env forwarding as start_ollama. ComfyUI's
// backend (torch / DirectML / IPEX) reads these on import, so the pick
// takes effect on next spawn (current process must be restarted for a
// change to apply — surfaced as a hint in the Settings UI).
// B2 fix (review-w2rust.md): apply_gpu_env can now shell out to
// nvidia-smi (GPU-UUID resolution) instead of doing zero I/O, so the
// lock is held only long enough to clone the small selection out --
// never across the detection call, which would freeze the Hardware
// tab's set_gpu_selection/get_gpu_selection (same mutex) for however
// long that subprocess I/O takes.
// 3.0.8 (A2): the ComfyUI role's card when one is set, the global pick
// otherwise. With a role set, ComfyUI sees that one card only, so a video
// can never spill onto the chat's card.
// 3.1.0 (C56): with "One model across two cards" ComfyUI sees both
// cards, the model card first (gpu_roles.rs, ComfySplit).
// 3.1.0: through apply_role_env, the one helper the boot start uses too.
if let Some(split) = crate::commands::gpu_roles::apply_role_env(state, crate::commands::gpu_roles::GpuRole::Comfy, &mut cmd) {
println!("[ComfyUI] [start] {}", crate::commands::gpu_roles::split_note(&split));
info!(model = split.model.index, helper = split.helper.index, "comfyui split over two cards");
}
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
let mut child = cmd.spawn()
.map_err(|e| {
// The log 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.
error!(error = %e, python = %python, "comfyui start failed");
format!("Failed to start ComfyUI (python={}): {}", python, os_error::english(&e))
})?;
// Assign to Job Object so child dies when parent dies (even via Task Manager)
#[cfg(target_os = "windows")]
assign_to_kill_on_close_job(&child);
// Drain stdout/stderr in background threads to prevent buffer deadlock.
// Each line also lands in the comfy_output ring buffer (GH #98): the
// shipped app has no console, so a startup crash printed here was
// invisible and every "did not come up" report ended in a blind spot.
{
let mut buf = state.comfy_output.lock().unwrap();
buf.clear();
buf.push_back(format!("[start] {} main.py --port {}", python, port_str));
if let Some(note) = &force_gpu_note {
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(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).
// That install had ComfyUI's source but neither python_embeded nor a venv,
// so this fell back to the system Python, which has none of the
// dependencies: main.py died on its first import inside a second. We
// reported {"status":"started"} anyway, the panel showed `Stopped` with no
// reason, and the traceback sat unread in our own ring buffer.
//
// The port cannot be the test here, ComfyUI imports for 20 to 60 seconds
// before it binds. The crash can: it happens far inside this window. So
// watch briefly, and if the child is already gone, fail with what it said.
let mut watched = std::time::Duration::ZERO;
let early_exit = loop {
match child.try_wait() {
Ok(Some(status)) => break Some(status.code()),
Ok(None) => {}
Err(_) => break None,
}
if watched >= COMFY_STARTUP_WATCH {
break None;
}
std::thread::sleep(COMFY_STARTUP_STEP);
watched += COMFY_STARTUP_STEP;
};
if let Some(code) = early_exit {
wait_for_output_readers(&readers_done, COMFY_READER_SETTLE);
// The same fallback as the longer watch further down, for a ComfyUI
// that refused the ck flag right in argparse: one start without it.
if attention.ck_unproven {
attention.remember(comfy_dir, false);
*state.comfy_start_at.lock().unwrap() = None;
error!(python = %python, "comfyui exited at once with the ck attention flag, starting again without it");
println!(
"[ComfyUI] Exited within the first seconds with {}, starting again without it",
comfy_attention::CK_FLAG
);
// Gate handed back for the second start, as further down.
drop(gate);
return start_comfyui_blocking(state);
}
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, has_own_python_env);
error!(python = %python, "comfyui exited during startup");
*state.comfy_start_at.lock().unwrap() = None;
return Err(msg);
}
// Store process
{
let mut proc = state.comfy_process.lock().unwrap();
*proc = Some(child);
}
*state.comfy_start_at.lock().unwrap() = Some(std::time::Instant::now());
// A ck start that has not proven itself on this folder and version is
// watched until its port answers. The two second watch above cannot see
// the failure: ComfyUI rejects the attention backend only after the torch
// import, many seconds in. The child already sits in `comfy_process`, so
// the panel reads "starting" meanwhile and Stop still reaches it.
if attention.ck_unproven {
match watch_own_ck_start(state, port) {
comfy_attention::CkWatch::Proven => attention.remember(comfy_dir, true),
comfy_attention::CkWatch::DiedEarly => {
wait_for_output_readers(&readers_done, COMFY_READER_SETTLE);
attention.remember(comfy_dir, false);
*state.comfy_start_at.lock().unwrap() = None;
error!(python = %python, "comfyui died with the ck attention flag, starting again without it");
println!(
"[ComfyUI] Exited before the port answered with {}, starting again without it",
comfy_attention::CK_FLAG
);
// `remember` also marks the flag failed for this run, so the
// second start goes without it even when config.json could
// not be written. The gate is handed back first, the second
// start takes it again: a click that slips in between finds
// the same "no ck" and the second start then reports it.
drop(gate);
return start_comfyui_blocking(state);
}
comfy_attention::CkWatch::Undecided => {}
}
}
println!("[ComfyUI] Started");
info!("comfyui started");
Ok(serde_json::json!({"status": "started", "path": comfy_path}))
}
/// What the start decided about attention, and what it must remember after.
struct AttentionChoice {
/// The one attention flag on the command line, if any.
flag: Option<&'static str>,
/// The flag is `--use-ck-attention` and no earlier start of this folder
/// and version has shown whether it works.
ck_unproven: bool,
/// The ComfyUI version the decision was made for.
version: Option<comfy_attention::ComfyVersion>,
}
impl AttentionChoice {
/// Write the outcome of an unproven ck start to the app's config.json.
/// A failure is also noted for the rest of this run, which is what keeps
/// the retry from looping when the file cannot be written.
fn remember(&self, comfy_dir: &Path, works: bool) {
if !works {
comfy_attention::note_ck_failed_this_run();
}
if let Some(v) = self.version {
comfy_attention::remember_ck_in(&crate::os_paths::app_config_json(), comfy_dir, v, works);
}
}
}
/// The attention decision both start paths share (comfy_attention.rs has the
/// rule). Gathers the facts, asks the cheap ones first and probes an import
/// only when the answer still matters.
fn comfy_attention_choice(
state: &AppState,
python: &str,
comfy_dir: &Path,
needs_cpu: bool,
device_flag: Option<&str>,
baseline_needs_cpu: bool,
) -> AttentionChoice {
let version = comfy_attention::read_comfyui_version(comfy_dir);
let remembered = version
.and_then(|v| comfy_attention::remembered_ck_in(&crate::os_paths::app_config_json(), comfy_dir, v));
// Without an NVIDIA driver the torch device tells ROCm ("cuda") from XPU
// and the rest. Same cache as the --cpu decision, so Auto pays nothing
// extra; only asked when it can still change the answer.
let torch_device = if baseline_needs_cpu && !needs_cpu && device_flag.is_none() {
comfy_gpu_device_cached(python, Some(&state.comfy_gpu_cache)).flatten()
} else {
None
};
let facts = comfy_attention::CkFacts {
os: std::env::consts::OS,
needs_cpu,
device_flag,
nvidia_driver: !baseline_needs_cpu,
torch_device,
comfy_version: version,
switched_off: comfy_attention::ck_switched_off() || comfy_attention::ck_failed_this_run(),
remembered,
};
if remembered == Some(false) {
println!(
"[ComfyUI] {} is off for this ComfyUI: an earlier start with it exited before the port answered",
comfy_attention::CK_FLAG
);
}
let flag = comfy_attention::pick_attention_flag(
needs_cpu,
comfy_attention::ck_attention_eligible(&facts),
|| comfy_attention::comfy_kitchen_cached(python, version),
|| flash_attention_cached(state, python),
);
AttentionChoice {
flag,
ck_unproven: flag == Some(comfy_attention::CK_FLAG) && remembered != Some(true),
version,
}
}
/// Watch the ComfyUI in `comfy_process` until the port answers or the child
/// exits, for [`comfy_attention::CK_PROOF_WATCH`] at most. The lock is held
/// only for one `try_wait` per round, never across the HTTP probe or the
/// sleep. A child that Stop took away reads as undecided.
fn watch_own_ck_start(state: &AppState, port: u16) -> comfy_attention::CkWatch {
comfy_attention::watch_ck_start(
|| {
let mut proc = state.comfy_process.lock().unwrap();
let child = proc.as_mut()?;
match child.try_wait() {
Ok(Some(_)) => {
*proc = None;
Some(true)
}
Ok(None) => Some(false),
Err(_) => None,
}
},
|| is_comfyui_running_on_port(port),
comfy_attention::CK_PROOF_WATCH,
std::time::Duration::from_secs(1),
)
}
// ASYNC + spawn_blocking: a SYNCHRONOUS Tauri command runs on the MAIN thread.
// The State borrow cannot cross into the blocking pool, so the handle is
// re-resolved there from the AppHandle (same pattern as engine.rs/whisper.rs).
#[tauri::command]
pub async fn stop_comfyui(app: tauri::AppHandle) -> Result<serde_json::Value, String> {
tokio::task::spawn_blocking(move || {
let state = app.state::<AppState>();
stop_comfyui_blocking(&state)
})
.await
.map_err(|e| format!("stop_comfyui task: {e}"))?
}
// ── T-68: the orphan a hard kill leaves behind ──────────────────────────────
//
// `tie_child_to_app_lifetime` prevents orphans on Windows (kill-on-close job
// object) and the graceful shutdown path covers the normal quit. Neither
// covers the case in the finding: LU is SIGKILLed (or the box loses power on
// the app, or a dev session is hard-stopped), the ComfyUI child is reparented
// to init and keeps the GPU. On the next launch `state.comfy_process` is
// `None`, so the port probe reports "Already running", the status panel says
// running — and Stop returned `{"status":"not_running"}` and did nothing, for
// as long as that install lived. That is the read-only adoption the audit
// names: LU could see the orphan and not touch it.
//
// The missing half is a way back to control. `find_orphaned_comfyui` looks for
// a ComfyUI process that LU itself started, on LU's own configured port, and
// `stop_comfyui` kills that tree instead of lying.
/// The one origin a ComfyUI started by LU answers to: the app's own page.
///
/// Until 3.0.6 the flag carried `*`. ComfyUI has no login, and with the flag
/// set it also drops its own check that a request comes from its own page
/// (server.py, `create_origin_only_middleware`). Together that let any web
/// page open in the user's browser read `http://127.0.0.1:8188`: the queue,
/// the history and every picture in the output folder. With the app's origin
/// in the header a browser hands those answers to the app and to nobody else.
///
/// What this does not close: ComfyUI still takes a request a foreign page
/// sends blind, it only keeps the answer from it. Closing that takes ComfyUI
/// without the flag and every media load through the Rust side.
pub(crate) fn comfy_cors_origin() -> &'static str {
app_page_origin(tauri::is_dev(), cfg!(any(windows, target_os = "android")))
}
/// The origin of the app's page. Tauri serves it from `http://tauri.localhost`
/// where the webview takes no custom scheme (Windows, Android) and from
/// `tauri://localhost` elsewhere. A dev run loads the Vite server instead
/// (`build.devUrl` in tauri.conf.json).
fn app_page_origin(dev: bool, http_scheme: bool) -> &'static str {
if dev {
"http://localhost:5273"
} else if http_scheme {
"http://tauri.localhost"
} else {
"tauri://localhost"
}
}
/// Is this command line a ComfyUI that LU started on `port`?
///
/// Three conditions, all of them required:
///
/// * it is a ComfyUI (`main.py`, the only entry point LU ever launches),
/// * it carries `--enable-cors-header`, which LU passes on EVERY start and a
/// user-managed ComfyUI does not — the "Fix CORS" button in Settings exists
/// precisely because a hand-started ComfyUI lacks it,
/// * it serves exactly `port`, not a port whose number merely starts the same
/// way (`--port 8188` must not match a ComfyUI on 81880).
///
/// Narrow on purpose: this decides whether LU may kill a process it did not
/// spawn in this run. A ComfyUI the user started themselves fails the CORS
/// test and is left alone, and Stop says so instead of killing it.
///
/// Pure, so the rule is testable without a process table.
pub(crate) fn is_lu_started_comfyui(cmd: &[String], port: u16) -> bool {
let joined = cmd.join(" ");
let lower = joined.to_ascii_lowercase();
if !lower.contains("main.py") || !lower.contains("--enable-cors-header") {
return false;
}
cmdline_names_port(&lower, port)
}
/// Does this command line pass exactly `port` as `--port`?
///
/// `contains("--port 8188")` is also true of `--port 81880`, and this decides
/// a kill — so the whole digit run has to equal the port. Both spellings
/// (`--port 8188` and `--port=8188`) are accepted because argv joining is not
/// the only way this string can be produced.
fn cmdline_names_port(lower: &str, port: u16) -> bool {
let wanted = port.to_string();
for sep in ["--port ", "--port="] {
let mut rest = lower;
while let Some(at) = rest.find(sep) {
let tail = &rest[at + sep.len()..];
let digits: String = tail.chars().take_while(char::is_ascii_digit).collect();
if digits == wanted {
return true;
}
rest = &rest[at + sep.len()..];
}
}
false
}
/// The pid of an LU-started ComfyUI on `port` that this process has no handle
/// for. `None` when nothing matches — including when the ComfyUI on that port
/// belongs to the user.
pub(crate) fn find_orphaned_comfyui(port: u16) -> Option<u32> {
// The table MUST come from this helper: a bare `refresh_processes` does not
// fetch command lines, and every match here would silently be against "".
// See the note above `process_table_with_cmdlines`.
find_orphaned_comfyui_in(&crate::process_util::process_table_with_cmdlines(), port)
}
/// The same scan, against a table the caller already holds.
///
/// Split out for the test that proves the scan is wired to real data. Taking the
/// snapshot as an argument is what lets that test assert on a table
/// `test_support::checked_table` has already vouched for, with no clock and no
/// second enumeration between the check and the assertion. `remote.rs` split
/// `find_stale_tunnels` the same way and for the same reason.
pub(crate) fn find_orphaned_comfyui_in(sys: &sysinfo::System, port: u16) -> Option<u32> {
let own = std::process::id();
for (pid, process) in sys.processes() {
let pid = pid.as_u32();
if pid == own {
continue;
}
if is_lu_started_comfyui(&crate::process_util::cmdline_of(process), port) {
return Some(pid);
}
}
None
}
/// The one answer to "is this app allowed to treat the ComfyUI on this port
/// as its own", shared by every caller that needs it instead of each one
/// drawing the line itself.
///
/// box-gruen/n9 punkt 87, final review 19.09.2026 (B2): Update's confirmation
/// dialog used to ask only whether THIS run's child handle is alive, so a
/// ComfyUI LU started in an EARLIER run and never lost track of (T-68's
/// orphan, exactly what a live ComfyUI looks like after every LU restart)
/// read as foreign, the status line lied ("started outside LU" about LU's
/// own process), and the customer could no longer reach Update at all. Both
/// `comfyui_status`'s `ownedByApp` field and `update_comfyui`'s running-
/// instance guard now ask this one function the same three questions, so
/// they cannot answer differently for the same ComfyUI.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ComfyOwnership {
/// Nothing is listening on the port.
NotRunning,
/// This app started it: a live tracked child from this run, or an
/// earlier one it can still identify as its own (`find_orphaned_comfyui`).
Own,
/// Something answers on the port, and it is neither of the above.
Foreign,
}
/// Pure decision over three inputs: is the port occupied at all, does this
/// run hold a live child handle for it, and did a scan of the process table
/// find an LU-started orphan on it. Kept free of any I/O of its own so both
/// directions (a ComfyUI that counts as ours, and one that does not) are
/// cheap to prove without a real process table or a real HTTP probe.
pub(crate) fn classify_comfyui_ownership(
port_occupied: bool,
own_child_alive: bool,
orphan_pid: Option<u32>,
) -> ComfyOwnership {
if !port_occupied {
ComfyOwnership::NotRunning
} else if own_child_alive || orphan_pid.is_some() {
ComfyOwnership::Own
} else {
ComfyOwnership::Foreign
}
}
// ── The same shape, one step out: a child that outlives its launcher ────────
//
// `tauri-plugin-shell`'s `CommandChild::kill` is `SharedChild::kill`, i.e. one
// signal to the DIRECT child (verified in tauri-plugin-shell-2.3.5,
// `src/process/mod.rs:78`). For an MCP server the frontend starts as
// `npx -y <package>` (Windows: `npx.cmd`, which runs through cmd.exe), the
// direct child is the launcher and the `node` process behind it is a
// grandchild — so `child.kill()` reaps the shim and leaves the server running.
//
// That is T-68's sachverhalt one level out, so it gets T-68's machinery rather
// than a second kill path: `process_util::kill_pid_tree` walks the tree, and
// the command below is the door the frontend uses to reach it.
/// May this app kill `pid`?
///
/// Only a process inside THIS app's own subtree. The pid is an argument from
/// the frontend, and a command that kills any pid it is handed is a much
/// bigger hole than the orphan it was meant to close — the caller could stop
/// the user's editor, or LU itself.
///
/// Pure so the rule is testable without a process table.
pub(crate) fn may_kill_pid(pid: u32, own: u32, own_descendants: &[u32]) -> Result<(), String> {
if pid == 0 || pid == own {
return Err(format!("refused: pid {pid} is this app itself"));
}
if !own_descendants.contains(&pid) {
return Err(format!(
"refused: pid {pid} is not a process this app started (it may have already \
exited, in which case its own children are init's now — kill the tree \
INSTEAD of the child, not after it)"
));
}
Ok(())
}
/// Kill a process tree this app spawned, addressed by the pid of its root.
///
/// ORDERING, and it matters: call this INSTEAD of the shell plugin's
/// `child.kill()`, never after it. Once the direct child is dead its own
/// children are reparented to init and are no longer this app's descendants —
/// the guard above will then (correctly) refuse, and the grandchild survives
/// exactly as before.
#[tauri::command]
pub async fn kill_process_tree(pid: u32) -> Result<serde_json::Value, String> {
tokio::task::spawn_blocking(move || kill_process_tree_blocking(pid))
.await
.map_err(|e| format!("kill_process_tree task: {e}"))?
}
pub(crate) fn kill_process_tree_blocking(pid: u32) -> Result<serde_json::Value, String> {
use sysinfo::{ProcessesToUpdate, System};
let own = std::process::id();
let mut sys = System::new();
sys.refresh_processes(ProcessesToUpdate::All, true);
let mine = crate::commands::shell::descendants(own, &sys);
may_kill_pid(pid, own, &mine)?;
let tree = crate::commands::shell::descendants(pid, &sys).len() + 1;
println!("[Process] killing tree of pid {pid} ({tree} process(es))");
info!(pid = pid, processes = tree, "killing a spawned process tree");
crate::process_util::kill_pid_tree(pid);
Ok(serde_json::json!({ "killed": true, "pid": pid, "processes": tree }))
}
pub(crate) fn stop_comfyui_blocking(state: &AppState) -> Result<serde_json::Value, String> {
let mut proc = state.comfy_process.lock().unwrap();
if let Some(ref mut child) = *proc {
let pid = child.id();
if cfg!(target_os = "windows") {
let mut cmd = crate::process_util::foreign_system_command("taskkill");
cmd.args(["/pid", &pid.to_string(), "/T", "/F"]);
crate::process_util::suppress_window(&mut cmd);
let _ = cmd.output();
} else {
let _ = child.kill();
}
// Reap before returning: guarantees the listen socket is released, so
// a start_comfyui right after us cannot lose the port bind (10048) to
// the dying process and silently leave the OLD node list being served.
let _ = child.wait();
*proc = None;
*state.comfy_start_at.lock().unwrap() = None;
println!("[ComfyUI] Stopped");
info!(pid = pid, "comfyui stopped");
return Ok(serde_json::json!({"status": "stopped"}));
}
drop(proc);
// No handle. Before 2.6.7 this was the end of the function and Stop was a
// no-op — see the T-68 note above.
let host = state
.comfy_host
.lock()
.map(|g| g.clone())
.unwrap_or_else(|_| "localhost".to_string());
if !is_local_host(&host) {
// A remote ComfyUI has never been ours to stop, and saying
// "not_running" about a server that IS running was the same lie in a
// smaller size.
return Ok(serde_json::json!({
"status": "remote",
"host": host,
"message": "ComfyUI runs on another host — stop it on that machine."
}));
}
let port = *state.comfy_port.lock().unwrap();
if !is_comfyui_running_on_port(port) {
return Ok(serde_json::json!({"status": "not_running"}));
}
// Something IS serving ComfyUI on our port and it is not a child of this
// run. Adopt it only if LU started it (see `is_lu_started_comfyui`).
match find_orphaned_comfyui(port) {
Some(pid) => {
println!("[ComfyUI] Adopting orphan pid {pid} on port {port} and stopping it");
info!(pid = pid, port = port, "comfyui orphan adopted and stopped");
crate::process_util::kill_pid_tree(pid);
*state.comfy_start_at.lock().unwrap() = None;
Ok(serde_json::json!({"status": "stopped", "adopted": true, "pid": pid}))
}
None => {
// A ComfyUI the user runs themselves. Killing it would be LU
// reaching outside its own process tree; saying "not_running"
// would be false. Say what is actually true.
println!("[ComfyUI] Port {port} is served by a ComfyUI this app did not start");
Ok(serde_json::json!({
"status": "not_ours",
"port": port,
"message": "A ComfyUI this app did not start is serving that port. Stop it where you started it."
}))
}
}
}
/// The last lines ComfyUI printed (GH #98). This is what "Check Settings →
/// AI Backends" could never show: the actual crash. Also reports whether the
/// tracked child has exited, so the frontend can say "crashed" instead of
/// "still starting" while it polls a port that will never open.
#[tauri::command]
pub fn comfyui_last_output(state: State<'_, AppState>) -> Result<serde_json::Value, String> {
let lines: Vec<String> = state
.comfy_output
.lock()
.map(|b| b.iter().cloned().collect())
.unwrap_or_default();
let exited = {
let mut proc = state.comfy_process.lock().unwrap();
match proc.as_mut() {
Some(child) => matches!(child.try_wait(), Ok(Some(_)) | Err(_)),
None => true,
}
};
// envBroken drives the self-repair (GH #98): only a crash that looks like
// a dead Python environment AND can be fixed by a fresh venv may trigger
// the rebuild, everything else keeps its own message. hint carries the
// installer's own verdict about this crash, empty when it has none.
let verdict = comfy_crash_verdict(&lines, exited);
Ok(serde_json::json!({
"lines": lines,
"exited": exited,
"envBroken": verdict.env_broken,
"hint": verdict.hint,
}))
}
#[tauri::command]
pub async fn comfyui_status(state: State<'_, AppState>) -> Result<serde_json::Value, String> {
// B9: a Comfy Desktop that came up after LU is found on the panel's next
// poll, not only at the next launch.
let port = follow_comfy_port_async(&state).await;
let host = state.comfy_host.lock().unwrap().clone();
let is_local = is_local_host(&host);
// Probe the configured host (not just localhost). Remote ComfyUI
// still reports running: true if the /system_stats endpoint responds.
let running = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(3))
.build()
.ok().map(|c| c.get(format!("http://{}:{}/system_stats", host, port)))
.map(|req| async move { req.send().await.map(|r| r.status().is_success()).unwrap_or(false) })
;
let running = match running {
Some(fut) => fut.await,
None => false,
};
// Reap the spawned child so a crash-on-startup doesn't read as "alive".
// We store the Child from start_comfyui in state.comfy_process. If that
// process exits early (the classic case: ComfyUI's main.py aborts on a bad
// dependency / missing torch / SQLAlchemy<2.0 / "no NVIDIA driver" before it
// binds the port), the handle would otherwise linger as Some(_) forever —
// making process_alive=true and therefore `starting` (process_alive &&
// !running) STICK TRUE INDEFINITELY. The user then stares at an endless
// "ComfyUI starting…" with no error. try_wait() detects the early exit so we
// clear the handle and report "stopped", letting the UI re-offer "click to
// start" + the troubleshoot panel instead of a phantom loading state.
let process_alive = {
let mut proc = state.comfy_process.lock().unwrap();
match proc.as_mut() {
Some(child) => match child.try_wait() {
Ok(Some(status)) => {
error!(exit = ?status, "comfyui process exited early (crash on startup?) — clearing handle");
*proc = None;
false
}
Ok(None) => true, // still running; just hasn't bound the port yet
Err(_) => true, // can't determine — assume alive, don't thrash
},
None => false,
}
};
let path = {
let p = state.comfy_path.lock().unwrap();
p.clone()
};
// For remote hosts we don't care whether a local install path exists.
let resolved_path: Option<String> = if is_local {
path.clone().or_else(find_comfyui_path)
} else {
None
};
let found = if is_local {
resolved_path.is_some()
} else {
true // the remote side handles its own install
};
// Carcass detection: a local install is only "complete" if torch is
// actually reachable. Remote hosts are reported complete by definition
// — the remote side owns its own install state.
let complete = if is_local {
match &resolved_path {
Some(p) => is_comfyui_install_complete(Path::new(p)),
None => false,
}
} else {
true
};
let since_start = state.comfy_start_at.lock().unwrap().map(|t| t.elapsed());
let (starting, stalled) = comfy_starting_state(process_alive, running, since_start);
// B2 (final review 19.09.2026): only scan the process table when the
// cheap answer (this run's own handle) does not already settle it. A
// live `process_alive` is always `Own`, and nothing running at all is
// always `NotRunning`, so the sysinfo walk only ever runs for the one
// case that needs it, a port answering with no handle from this run.
//
// R2-k2 (final review Runde 2, 19.09.2026): that walk is
// `process_table_with_cmdlines`, a full sysinfo snapshot with command
// lines, and it used to run straight on this `async fn`'s own thread.
// The panel polls this command every 5 s, and the case that needs the
// scan is not rare: it holds for the whole time a customer's own
// ComfyUI keeps running, and again after every app restart until the
// customer's next click. `spawn_blocking` moves the scan off the async
// worker so it cannot stall other commands sharing that thread.
let orphan_pid = if is_local && running && !process_alive {
tokio::task::spawn_blocking(move || find_orphaned_comfyui(port))
.await
.unwrap_or(None)
} else {
None
};
let owned_by_app = is_local && running && matches!(
classify_comfyui_ownership(running, process_alive, orphan_pid),
ComfyOwnership::Own,
);
Ok(serde_json::json!({
"running": running,
"starting": starting,
"stalled": stalled,
"found": found,
"complete": complete,
"path": path,
"port": port,
"host": host,
"isLocal": is_local,
"processAlive": process_alive,
// The one field the panel and Update's confirm dialog both read to
// tell an LU-owned ComfyUI (this run's, or an earlier run's orphan)
// from one this app never started -- see `classify_comfyui_ownership`.
"ownedByApp": owned_by_app,
// The "Start ComfyUI when LU starts" switch (comfy_boot_plan).
"autostart": comfy_autostart_enabled(),
}))
}
/// Returns true when `host` refers to the local machine.
/// Anything else = remote and LU won't try to manage the process.
pub fn is_local_host(host: &str) -> bool {
let h = host.trim().to_ascii_lowercase();
matches!(h.as_str(), "localhost" | "127.0.0.1" | "::1" | "0.0.0.0" | "")
}
// `async`: find_comfyui_path can walk the whole home directory (minutes on
// a big disk). As a plain command it ran on the main thread and froze the
// window at LOADING for as long as the walk took.
#[tauri::command(async)]
pub fn find_comfyui() -> Result<serde_json::Value, String> {
match find_comfyui_path() {
Some(path) => {
// Surface install completeness so the UI can distinguish a
// working ComfyUI from a half-cloned carcass and offer the
// right action (Continue vs. Re-install). See
// is_comfyui_install_complete for the definition of "complete".
let complete = is_comfyui_install_complete(Path::new(&path));
Ok(serde_json::json!({
"found": true,
"path": path,
"complete": complete,
}))
}
None => Ok(serde_json::json!({
"found": false,
"path": null,
"complete": false,
})),
}
}
/// Frontend-owned override for the ComfyUI CPU/GPU device decision
/// (settings.comfyGpuMode). "auto" | "cpu" | "gpu". Desktop-relevant only — the
/// web build points at a remote ComfyUI and never starts a local one.
#[tauri::command]
pub fn set_comfy_gpu_mode(mode: String, state: State<'_, AppState>) -> Result<serde_json::Value, String> {
let normalized = match mode.trim().to_ascii_lowercase().as_str() {
"cpu" => "cpu",
"gpu" => "gpu",
_ => "auto",
};
*state.comfy_gpu_mode.lock().unwrap() = normalized.to_string();
// The mode can flip the target device, so drop cached probe results; the
// next start re-probes cleanly under the new mode.
state.comfy_gpu_cache.lock().unwrap().clear();
println!("[ComfyUI] GPU mode = {}", normalized);
Ok(serde_json::json!({ "mode": normalized }))
}
/// A user (Discord 2026-07-03, RX 7900 XTX): a forced-CPU ComfyUI showed
/// "Ready to generate" and then died with "timed out after 20 minutes" — no
/// hint it never used the GPU. Lets the Create tab render an honest warning.
/// `startedCpu` is None until LU itself has (re)started ComfyUI this session
/// (an externally started ComfyUI is the user's own device choice).
#[tauri::command]
pub fn get_comfy_gpu_status(state: State<'_, AppState>) -> Result<serde_json::Value, String> {
let mode = state.comfy_gpu_mode.lock().unwrap().clone();
let started_cpu = *state.comfy_started_cpu.lock().unwrap();
// The vendor is what turns "this ran on the processor" into a sentence the
// user can act on: an AMD card on Linux wants a rebuilt environment, the
// same card on Windows wants to be told no rebuild can help. Same probe the
// hardware picker and the installers use.
let (_, has_amd, amd_names) = crate::commands::torch_wheels::gpu_vendor_facts();
let amd_refs: Vec<&str> = amd_names.iter().map(String::as_str).collect();
let amd_rocm = crate::commands::torch_wheels::amd_rocm_served(&amd_refs, std::env::consts::OS);
Ok(serde_json::json!({ "mode": mode, "startedCpu": started_cpu, "hasAmd": has_amd, "amdRocmServed": amd_rocm }))
}
/// What LU installs into a ComfyUI environment on THIS machine, for the line
/// under Settings > Hardware > ComfyUI GPU. No network: the plan as decided
/// from the cards, before any index is asked. `kind` is cuda, rocm, xpu or
/// cpu; `summary` is the plan's own sentence, the one the install prints.
#[tauri::command]
pub async fn comfy_torch_plan() -> Result<serde_json::Value, String> {
tokio::task::spawn_blocking(|| {
let plan = crate::commands::torch_wheels::comfy_wheel_plan_here();
let (index, summary) = match &plan {
crate::commands::torch_wheels::WheelPlan::Cpu { note } => (None, note.clone()),
crate::commands::torch_wheels::WheelPlan::Index { candidates, note }
| crate::commands::torch_wheels::WheelPlan::IndexOrCpu { candidates, note, .. } => {
(candidates.first().copied(), note.clone())
}
};
serde_json::json!({
"kind": crate::commands::torch_wheels::plan_kind(&plan),
"summary": summary,
"index": index,
})
})
.await
.map_err(|e| format!("comfy_torch_plan task: {e}"))
}
#[tauri::command]
pub fn set_comfyui_path(path: String, state: State<'_, AppState>) -> Result<serde_json::Value, String> {
// Resolve the path the user gave us to a directory that actually contains
// `main.py`. Direct hit short-circuits; otherwise we look at the ComfyUI
// Desktop App layout (Comfy-Org/desktop, GH #47 2026-05-24): the
// user typically points at `%LOCALAPPDATA%\Programs\ComfyUI` (the binary
// dir with `ComfyUI.exe` next to no `main.py`) because that's what their
// shortcut targets, but the actual Working Directory with `main.py` +
// `models/` + `custom_nodes/` lives under `~\Documents\ComfyUI` or
// `%APPDATA%\ComfyUI` depending on the install picker. We transparently
// re-route in that case so the error doesn't look unfixable.
let resolved = resolve_comfyui_path(&path)
.ok_or_else(|| {
if Path::new(&path).join("main.py").is_file() {
// Discord 25.10.2026: Comfy Desktop's bundled Python has a
// main.py of its own (Lib\_pyrepl), and LU took it.
format!(
"{} has a main.py, but it is not ComfyUI (there is no comfy folder next to it). Pick the folder that holds ComfyUI's main.py together with its comfy and models folders. With Comfy Desktop that is %LOCALAPPDATA%\\Comfy-Desktop\\ComfyUI-Installs\\<name>\\ComfyUI.",
path
)
} else if Path::new(&path).join("ComfyUI.exe").exists() {
format!(
"Looks like the ComfyUI Desktop App binary folder ({}). LU needs the ComfyUI Working Directory (with main.py, models/, custom_nodes/) — by default `~\\Documents\\ComfyUI` or wherever you picked during install. Open the Desktop App once, check Settings → ComfyUI Working Directory, and paste that path here.",
path
)
} else {
format!(
"main.py not found in {} or in its ComfyUI subfolder. Pick the folder that holds ComfyUI's main.py.",
path
)
}
})?;
let path = resolved;
// Store in memory
{
let mut p = state.comfy_path.lock().unwrap();
*p = Some(path.clone());
}
// A different install answers differently about its model folders.
crate::commands::comfy_folders::forget();
// Persist to config file
{
let app_config = crate::os_paths::app_config_dir();
let _ = fs::create_dir_all(&app_config);
let config_file = app_config.join("config.json");
let mut config: serde_json::Value = if config_file.exists() {
fs::read_to_string(&config_file)
.ok()
.and_then(|s| serde_json::from_str(&s).ok())
.unwrap_or_else(|| serde_json::json!({}))
} else {
serde_json::json!({})
};
config["comfyui_path"] = serde_json::json!(path);
let _ = fs::write(&config_file, serde_json::to_string_pretty(&config).unwrap());
}
Ok(serde_json::json!({"status": "saved", "path": path}))
}
/// Split a trailing `:port` off a host the user typed. The neighbouring Ollama
/// field accepts `host:port`, so people type it here too — and it broke
/// everything downstream without saying so: the proxy allow-list compares
/// against the PARSED host (no port) and refused the request, while the progress
/// socket built `ws://host:port:port`. The user then read "host not allowed,
/// configure it in Settings" about the field they had just filled in.
/// IPv6 literals (more than one colon) are left alone.
fn split_host_port(input: &str) -> (String, Option<u16>) {
if input.matches(':').count() == 1 {
if let Some((h, p)) = input.rsplit_once(':') {
if !h.is_empty() && !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()) {
if let Ok(port) = p.parse::<u16>() {
if port > 0 {
return (h.to_string(), Some(port));
}
}
}
}
}
(input.to_string(), None)
}
#[tauri::command]
pub fn set_comfyui_host(host: String, state: State<'_, AppState>) -> Result<serde_json::Value, String> {
let trimmed = host.trim();
if trimmed.is_empty() {
return Err("Host must not be empty".to_string());
}
// Reject obviously invalid chars — helps avoid URL-injection style typos.
if trimmed.contains('/') || trimmed.contains(' ') || trimmed.contains('?') {
return Err("Host must be a plain hostname or IP, no slashes/spaces".to_string());
}
let (final_host, typed_port) = split_host_port(trimmed);
{
let mut h = state.comfy_host.lock().unwrap();
*h = final_host.clone();
}
if let Some(port) = typed_port {
let mut p = state.comfy_port.lock().unwrap();
*p = port;
}
// Another engine, another set of model folders.
crate::commands::comfy_folders::forget();
// Persist to config file
{
let app_config = crate::os_paths::app_config_dir();
let _ = fs::create_dir_all(&app_config);
let config_file = app_config.join("config.json");
let mut config: serde_json::Value = if config_file.exists() {
fs::read_to_string(&config_file)
.ok()
.and_then(|s| serde_json::from_str(&s).ok())
.unwrap_or_else(|| serde_json::json!({}))
} else {
serde_json::json!({})
};
config["comfyui_host"] = serde_json::json!(final_host);
if let Some(port) = typed_port {
config["comfyui_port"] = serde_json::json!(port);
}
let _ = fs::write(&config_file, serde_json::to_string_pretty(&config).unwrap());
}
let is_local = is_local_host(&final_host);
println!("[ComfyUI] Host set to {} (local={})", final_host, is_local);
Ok(serde_json::json!({"status": "saved", "host": final_host, "isLocal": is_local}))
}
#[tauri::command]
pub fn set_comfyui_port(port: u16, state: State<'_, AppState>) -> Result<serde_json::Value, String> {
if port == 0 {
return Err("Port must be greater than 0".to_string());
}
{
let mut p = state.comfy_port.lock().unwrap();
*p = port;
}
crate::commands::comfy_folders::forget();
// Persist to config file
{
let app_config = crate::os_paths::app_config_dir();
let _ = fs::create_dir_all(&app_config);
let config_file = app_config.join("config.json");
let mut config: serde_json::Value = if config_file.exists() {
fs::read_to_string(&config_file)
.ok()
.and_then(|s| serde_json::from_str(&s).ok())
.unwrap_or_else(|| serde_json::json!({}))
} else {
serde_json::json!({})
};
config["comfyui_port"] = serde_json::json!(port);
let _ = fs::write(&config_file, serde_json::to_string_pretty(&config).unwrap());
}
println!("[ComfyUI] Port set to {}", port);
Ok(serde_json::json!({"status": "saved", "port": port}))
}
/// Normalize user input into a full Ollama base URL.
/// Accepts bare `host:port`, scheme-less host, or full URL.
/// Returns full URL without trailing slash, or Err for obviously bad input.
fn normalize_ollama_base(input: &str) -> Result<String, String> {
let trimmed = input.trim().trim_end_matches('/');
if trimmed.is_empty() {
return Err("Endpoint must not be empty".into());
}
// Reject whitespace / newlines inside the URL.
if trimmed.chars().any(|c| c.is_whitespace()) {
return Err("Endpoint must not contain whitespace".into());
}
let with_scheme = if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
trimmed.to_string()
} else {
format!("http://{}", trimmed)
};
// Sanity-check with a URL parse so "http://" alone or "http://:1234" can't pass.
match url::Url::parse(&with_scheme) {
Ok(u) if u.host_str().is_some_and(|h| !h.is_empty()) => Ok(with_scheme),
_ => Err(format!("Not a valid URL: {}", input)),
}
}
#[tauri::command]
pub fn set_ollama_host(host: String, state: State<'_, AppState>) -> Result<serde_json::Value, String> {
let final_base = normalize_ollama_base(&host)?;
{
let mut b = state.ollama_base.lock().unwrap();
*b = final_base.clone();
}
// Persist to config file under ollama_base — next startup will pick it
// up via load_ollama_base() before any request fires.
{
let app_config = crate::os_paths::app_config_dir();
let _ = fs::create_dir_all(&app_config);
let config_file = app_config.join("config.json");
let mut config: serde_json::Value = if config_file.exists() {
fs::read_to_string(&config_file)
.ok()
.and_then(|s| serde_json::from_str(&s).ok())
.unwrap_or_else(|| serde_json::json!({}))
} else {
serde_json::json!({})
};
config["ollama_base"] = serde_json::json!(final_base);
let _ = fs::write(&config_file, serde_json::to_string_pretty(&config).unwrap());
}
let is_local = url::Url::parse(&final_base)
.ok()
.and_then(|u| u.host_str().map(|h| h.to_lowercase()))
.map(|h| matches!(h.as_str(), "localhost" | "127.0.0.1" | "::1" | "0.0.0.0"))
.unwrap_or(false);
println!("[Ollama] Base URL set to {} (local={})", final_base, is_local);
Ok(serde_json::json!({"status": "saved", "base": final_base, "isLocal": is_local}))
}
// ASYNC + spawn_blocking: a SYNCHRONOUS Tauri command runs on the MAIN thread.
// The State borrow cannot cross into the blocking pool, so the handle is
// re-resolved there from the AppHandle (same pattern as engine.rs/whisper.rs).
#[tauri::command]
pub async fn get_ollama_host(app: tauri::AppHandle) -> Result<serde_json::Value, String> {
tokio::task::spawn_blocking(move || {
let state = app.state::<AppState>();
get_ollama_host_blocking(&state)
})
.await
.map_err(|e| format!("get_ollama_host task: {e}"))?
}
fn get_ollama_host_blocking(state: &AppState) -> Result<serde_json::Value, String> {
let base = state.ollama_base.lock().unwrap().clone();
let is_local = url::Url::parse(&base)
.ok()
.and_then(|u| u.host_str().map(|h| h.to_lowercase()))
.map(|h| matches!(h.as_str(), "localhost" | "127.0.0.1" | "::1" | "0.0.0.0"))
.unwrap_or(false);
// `defaultBase`: where "Reset AI Backends" points Ollama (OLLAMA_HOST,
// else the default), see state::ollama_default_base.
Ok(serde_json::json!({
"base": base,
"isLocal": is_local,
"defaultBase": crate::state::ollama_default_base(),
}))
}
/// Auto-start Ollama on app launch (called from setup)
pub fn auto_start_ollama(state: &AppState) {
if ollama_port_open() {
println!("[Ollama] Already running");
return;
}
println!("[Ollama] Starting...");
// K14: a foreign program, never something LU bundles.
let mut cmd = crate::process_util::foreign_system_command(ollama_program());
cmd.arg("serve")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
// 3.1.0: the chat card, like start_ollama. This start applied none.
crate::commands::gpu_roles::apply_role_env(state, crate::commands::gpu_roles::GpuRole::Chat, &mut cmd);
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
match cmd.spawn() {
Ok(child) => {
// Same orphan-prevention rationale as `start_ollama` above.
tie_child_to_app_lifetime(child.id());
*state.ollama_process.lock().unwrap() = Some(child);
println!("[Ollama] Started");
}
Err(e) => println!("[Ollama] Failed to start: {}", os_error::english(&e)),
}
}
/// What the boot path does with the local ComfyUI.
///
/// Until 3.0.9 the boot path started whatever ComfyUI the disk search found,
/// unasked. The search finds the user's own installs too (`~/ComfyUI`, Comfy
/// Desktop, Stability Matrix), and on the box click-through of 27.10.2026 LU
/// brought up the owner's own ComfyUI from his home folder unasked. A
/// ComfyUI that already answers is used as it is; one that does not is only
/// started when the user said so (`comfyui_autostart` in config.json, the
/// "Start ComfyUI when LU starts" switch, which LU's own installer turns on).
/// Everything else waits for a click: Start in Settings, or the first job in
/// Create, which starts it on demand.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ComfyBootPlan {
/// Something answers on the port: connect, start nothing.
Connect,
/// Installed, not running, and the user wants it started with LU.
Start,
/// Installed and not running, and nobody asked for a start.
LeaveStopped,
/// No install found: nothing to start.
NoInstall,
}
pub(crate) fn comfy_boot_plan(running: bool, install_found: bool, autostart: bool) -> ComfyBootPlan {
if running {
ComfyBootPlan::Connect
} else if !install_found {
ComfyBootPlan::NoInstall
} else if autostart {
ComfyBootPlan::Start
} else {
ComfyBootPlan::LeaveStopped
}
}
/// The user's "Start ComfyUI when LU starts" switch. Off unless set: a missing
/// key is an install nobody has told LU anything about.
pub(crate) fn comfy_autostart_enabled() -> bool {
read_app_config()
.and_then(|c| c.get("comfyui_autostart").and_then(|v| v.as_bool()))
.unwrap_or(false)
}
/// Whether the user ever saved a ComfyUI port. Only an unset port may follow
/// a ComfyUI that answers somewhere else (Comfy Desktop, port 8000).
fn comfy_port_user_set() -> bool {
read_app_config().is_some_and(|c| c.get("comfyui_port").is_some())
}
fn read_app_config() -> Option<serde_json::Value> {
let raw = fs::read_to_string(crate::os_paths::app_config_json()).ok()?;
serde_json::from_str(&raw).ok()
}
/// Write one key into config.json, keeping the rest.
pub(crate) fn write_app_config_key(key: &str, value: serde_json::Value) {
let app_config = crate::os_paths::app_config_dir();
let _ = fs::create_dir_all(&app_config);
let config_file = app_config.join("config.json");
let mut config = read_app_config().unwrap_or_else(|| serde_json::json!({}));
config[key] = value;
let _ = fs::write(&config_file, serde_json::to_string_pretty(&config).unwrap_or_default());
}
/// ComfyUI's default port, and the one Comfy Desktop serves on.
pub(crate) const COMFY_DEFAULT_PORT: u16 = 8188;
pub(crate) const COMFY_DESKTOP_PORT: u16 = 8000;
/// Which port the app should talk to ComfyUI on.
///
/// Comfy Desktop (Comfy-Org/desktop) runs its server on 8000, not 8188 (B9).
/// A user who never saved a port and runs Desktop got "ComfyUI not running"
/// next to a ComfyUI that was running. A saved port is never second-guessed,
/// and 8000 only wins when 8188 is silent and 8000 answers like a ComfyUI.
pub(crate) fn pick_comfy_port(current: u16, user_set: bool, answers: impl Fn(u16) -> bool) -> u16 {
if user_set {
return current;
}
if answers(current) {
return current;
}
for candidate in [COMFY_DEFAULT_PORT, COMFY_DESKTOP_PORT] {
if candidate != current && answers(candidate) {
return candidate;
}
}
// Neither answers: back to the default, so a start LU makes itself does
// not land on Desktop's port after Desktop was closed.
COMFY_DEFAULT_PORT
}
/// `/system_stats` answers AND looks like ComfyUI's. Port 8000 is every dev
/// server's favourite, and a 200 from one of them is not a ComfyUI.
pub(crate) fn looks_like_comfyui_on_port(port: u16) -> bool {
let Ok(client) = reqwest::blocking::Client::builder()
.timeout(std::time::Duration::from_secs(2))
.build()
else {
return false;
};
client
.get(format!("http://localhost:{port}/system_stats"))
.send()
.ok()
.filter(|r| r.status().is_success())
.and_then(|r| r.json::<serde_json::Value>().ok())
.is_some_and(|v| is_comfy_system_stats(&v))
}
pub(crate) fn is_comfy_system_stats(v: &serde_json::Value) -> bool {
v.get("system").is_some_and(|s| s.is_object()) && v.get("devices").is_some_and(|d| d.is_array())
}
/// Follow a ComfyUI that answers on the other well-known port, for a local
/// host with no saved port. Returns the port now in use.
pub(crate) fn follow_comfy_port(state: &AppState) -> u16 {
let current = *state.comfy_port.lock().unwrap();
let host = state.comfy_host.lock().unwrap().clone();
if !is_local_host(&host) {
return current;
}
let picked = pick_comfy_port(current, comfy_port_user_set(), looks_like_comfyui_on_port);
if picked != current {
println!("[ComfyUI] Answers on port {picked}, not {current} (no port saved) — following it");
*state.comfy_port.lock().unwrap() = picked;
crate::commands::comfy_folders::forget();
}
picked
}
/// `follow_comfy_port` for the async status poll: the same decision, the
/// probes over the async client, and only one probe while the current port
/// answers.
async fn follow_comfy_port_async(state: &AppState) -> u16 {
let current = *state.comfy_port.lock().unwrap();
let host = state.comfy_host.lock().unwrap().clone();
if !is_local_host(&host) || comfy_port_user_set() {
return current;
}
let Ok(client) = reqwest::Client::builder().timeout(std::time::Duration::from_secs(2)).build() else {
return current;
};
let probe = |port: u16| {
let client = client.clone();
async move {
match client.get(format!("http://localhost:{port}/system_stats")).send().await {
Ok(r) if r.status().is_success() => {
r.json::<serde_json::Value>().await.is_ok_and(|v| is_comfy_system_stats(&v))
}
_ => false,
}
}
};
let mut answering: Vec<u16> = Vec::new();
if probe(current).await {
answering.push(current);
} else {
for candidate in [COMFY_DEFAULT_PORT, COMFY_DESKTOP_PORT] {
if candidate != current && probe(candidate).await {
answering.push(candidate);
break;
}
}
}
let picked = pick_comfy_port(current, false, |p| answering.contains(&p));
if picked != current {
println!("[ComfyUI] Answers on port {picked}, not {current} (no port saved) — following it");
*state.comfy_port.lock().unwrap() = picked;
crate::commands::comfy_folders::forget();
}
picked
}
/// The "Start ComfyUI when LU starts" switch in Settings.
#[tauri::command]
pub fn set_comfyui_autostart(enabled: bool) -> Result<serde_json::Value, String> {
write_app_config_key("comfyui_autostart", serde_json::json!(enabled));
println!("[ComfyUI] Start with LU: {}", if enabled { "on" } else { "off" });
Ok(serde_json::json!({"status": "saved", "autostart": enabled}))
}
/// Boot path for ComfyUI on app launch (called from setup). Connects to a
/// running one, starts one only per `comfy_boot_plan`.
pub fn auto_start_comfyui(state: &AppState) {
// Hard rule: macOS local media is MLX only, NEVER ComfyUI (see
// commands::mlx / commands::video). Auto-starting ComfyUI on Mac violated
// that rule (2026-07-23 log: "[ComfyUI] Already running on port 8188").
// ComfyUI itself stays fully intact for Windows/Linux and for a user who
// manually invokes `start_comfyui` — only the unattended boot path skips it.
if cfg!(target_os = "macos") {
println!("[ComfyUI] Auto-start skipped on macOS — local media is MLX-only");
return;
}
// If user configured a remote host, don't try to auto-start anything locally.
{
let host = state.comfy_host.lock().unwrap().clone();
if !is_local_host(&host) {
println!("[ComfyUI] Remote host configured ({}), skipping local auto-start", host);
return;
}
}
// Always try to find and store the ComfyUI path (needed for downloads)
if state.comfy_path.lock().unwrap().is_none() {
if let Some(path) = find_comfyui_path() {
println!("[ComfyUI] Found at: {}", path);
*state.comfy_path.lock().unwrap() = Some(path);
}
}
let port = follow_comfy_port(state);
let running = is_comfyui_running_on_port(port);
let found = if running { None } else { find_comfyui_path() };
let plan = comfy_boot_plan(running, found.is_some(), comfy_autostart_enabled());
if plan == ComfyBootPlan::Connect {
// T-68: a ComfyUI on our port at launch is either the user's own or an
// orphan this app left behind when it was killed. Naming which one in
// the log is what makes a later "Stop did nothing" diagnosable.
match find_orphaned_comfyui(port) {
Some(pid) => println!(
"[ComfyUI] Already running on port {port} — orphan of an earlier session (pid {pid}); Stop can adopt it"
),
None => println!("[ComfyUI] Already running on port {} (not started by this app)", port),
}
return;
}
if plan == ComfyBootPlan::LeaveStopped {
println!(
"[ComfyUI] Found at {}, not running — not started (Start ComfyUI when LU starts is off)",
found.as_deref().unwrap_or("?")
);
return;
}
match found {
Some(path) => {
let port_str = port.to_string();
println!("[ComfyUI] Auto-starting from: {} on port {}", path, port);
*state.comfy_path.lock().unwrap() = Some(path.clone());
// Mirror the start_comfyui Python preference: use the portable's
// bundled Python when present so AMD / cu126 / CPU portables boot
// with the right torch wheel. See start_comfyui for full context.
let portable_python = std::path::Path::new(&path)
.parent()
.and_then(|p| {
let c = p.join("python_embeded").join("python.exe");
if c.exists() { Some(c.to_string_lossy().to_string()) } else { None }
})
.or_else(|| {
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.
// 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 comfy_dir = std::path::Path::new(&path);
let python = match launch_python(portable_python.as_deref(), &venv_state, comfy_dir, || {
bound_comfy_python(comfy_dir, &system_python)
}) {
Ok(p) => p,
Err(why) => {
println!("[ComfyUI] Auto-start skipped: {why}");
return;
}
};
if portable_python.is_some() {
println!("[ComfyUI] Auto-start using bundled portable Python: {}", python);
} else if has_usable_venv {
println!("[ComfyUI] Auto-start using ComfyUI venv Python: {}", python);
} else {
println!("[ComfyUI] Auto-start without a venv, using the Python that holds torch: {}", python);
}
// Bug J: same --cpu fallback as start_comfyui to avoid the
// "Found no NVIDIA driver" crash loop on non-NVIDIA systems.
let auto_gpu_mode = ComfyGpuMode::parse(&state.comfy_gpu_mode.lock().unwrap());
let auto_decision = comfy_needs_cpu(&python, auto_gpu_mode, Some(&state.comfy_gpu_cache));
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",
"--port", &port_str,
"--enable-cors-header", comfy_cors_origin(),
];
let mut auto_device_flag: Option<&'static str> = None;
if auto_needs_cpu {
comfy_args.push("--cpu");
if let Some(reason) = cpu_flag_reason(auto_gpu_mode, auto_decision.baseline, auto_decision.torch_gpu) {
println!("[ComfyUI] Auto-start: {reason}");
}
} else if let Some(flag) = comfy_launch_device_flag(
&python,
auto_gpu_mode,
auto_decision.baseline,
Some(&state.comfy_gpu_cache),
) {
comfy_args.push(flag);
auto_device_flag = Some(flag);
println!("[ComfyUI] Auto-start: torch-directml found, starting with {flag}");
}
// Mirror start_comfyui: the same single attention flag (Comfy
// Kitchen, else Flash Attention when it actually imports in this
// python). Boot auto-start previously never passed the flash flag,
// so auto-started ComfyUI ran WAN video 4-5x slower than a manual
// start even with flash-attn installed. The probes are cached per
// python; an absent package fails fast, so the rare cost is one
// slow first-probe on a cold boot with the package present.
let auto_attention = comfy_attention_choice(
state,
&python,
comfy_dir,
auto_needs_cpu,
auto_device_flag,
auto_decision.baseline,
);
if let Some(flag) = auto_attention.flag {
comfy_args.push(flag);
println!("[ComfyUI] Auto-start: enabling {flag}");
}
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);
}
// GH #183: the same flags from the user's start script as the
// manual start.
let user_args = crate::commands::comfy_user_paths::UserComfyPaths::discover(std::path::Path::new(&path)).launch_args();
if !user_args.is_empty() {
println!("[ComfyUI] Auto-start: from the start script: {}", user_args.join(" "));
}
comfy_args.extend(user_args.iter().map(String::as_str));
let mut cmd = python_command(&python);
cmd.args(&comfy_args)
.current_dir(&path)
.env("TQDM_DISABLE", "1")
.env("PYTHONUNBUFFERED", "1")
// UTF-8 kommt aus python_command, siehe start_comfyui. Ohne
// das stirbt ComfyUI auf einer Windows-Konsole ohne UTF-8 an
// einem UnicodeEncodeError, sobald es Fortschrittszeichen
// druckt (07.06.2026).
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
// 3.1.0: the card, like the manual start. Until now this path
// applied none, so "Card per task" (3.0.8) never reached a
// ComfyUI started with LU, and LU's own ComfyUI install turns this
// start on. The pick comes from config.json (AppState::new).
if let Some(split) = crate::commands::gpu_roles::apply_role_env(state, crate::commands::gpu_roles::GpuRole::Comfy, &mut cmd) {
println!("[ComfyUI] Auto-start: {}", crate::commands::gpu_roles::split_note(&split));
info!(model = split.model.index, helper = split.helper.index, "comfyui split over two cards");
}
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
match cmd.spawn() {
Ok(mut child) => {
// Assign to Job Object so child dies when parent dies (even via Task Manager)
#[cfg(target_os = "windows")]
assign_to_kill_on_close_job(&child);
// Drain stdout/stderr in background threads to prevent buffer deadlock
if let Some(stdout) = child.stdout.take() {
std::thread::spawn(move || {
use std::io::{BufRead, BufReader};
let reader = BufReader::new(stdout);
for line in reader.lines().map_while(Result::ok) {
println!("[ComfyUI] {}", line);
}
});
}
if let Some(stderr) = child.stderr.take() {
std::thread::spawn(move || {
use std::io::{BufRead, BufReader};
let reader = BufReader::new(stderr);
for line in reader.lines().map_while(Result::ok) {
println!("[ComfyUI] {}", line);
}
});
}
*state.comfy_process.lock().unwrap() = Some(child);
// Same proof as the manual start: an unproven ck start is
// watched until its port answers. This runs on the setup
// thread, so the wait blocks nothing the user sees.
if auto_attention.ck_unproven {
match watch_own_ck_start(state, port) {
comfy_attention::CkWatch::Proven => auto_attention.remember(comfy_dir, true),
comfy_attention::CkWatch::DiedEarly => {
auto_attention.remember(comfy_dir, false);
println!(
"[ComfyUI] Auto-start: exited before the port answered with {}, starting again without it",
comfy_attention::CK_FLAG
);
// `remember` marked the flag failed for this
// run, so this second pass goes without it.
return auto_start_comfyui(state);
}
comfy_attention::CkWatch::Undecided => {}
}
}
println!("[ComfyUI] Started");
}
Err(e) => println!("[ComfyUI] Failed to start: {}", e),
}
}
None => println!("[ComfyUI] Not found. Install ComfyUI or set path in settings."),
}
}
#[cfg(test)]
mod comfy_boot_tests {
use super::*;
/// Box click-through 27.10.2026: David's own ComfyUI, found by the disk
/// search and not running, was started by LU at launch. Found but not
/// asked for is LeaveStopped now.
#[test]
fn a_found_comfyui_is_not_started_unasked() {
assert_eq!(comfy_boot_plan(false, true, false), ComfyBootPlan::LeaveStopped);
}
#[test]
fn a_running_comfyui_is_used_and_never_started() {
assert_eq!(comfy_boot_plan(true, true, false), ComfyBootPlan::Connect);
assert_eq!(comfy_boot_plan(true, true, true), ComfyBootPlan::Connect);
assert_eq!(comfy_boot_plan(true, false, false), ComfyBootPlan::Connect);
}
#[test]
fn the_switch_starts_it_and_nothing_to_start_stays_nothing() {
assert_eq!(comfy_boot_plan(false, true, true), ComfyBootPlan::Start);
assert_eq!(comfy_boot_plan(false, false, true), ComfyBootPlan::NoInstall);
}
/// The boot path has to ask the plan before it spawns. A plan nobody
/// calls would leave these tests green over the old behaviour.
#[test]
fn the_boot_path_asks_the_plan_before_any_spawn() {
let src = include_str!("process.rs");
let body = &src[src.find("pub fn auto_start_comfyui(").unwrap()..];
let body = &body[..body.find("\n}\n").unwrap()];
let plan = body.find("comfy_boot_plan(").expect("auto_start_comfyui does not ask comfy_boot_plan");
let leave = body.find("ComfyBootPlan::LeaveStopped").expect("LeaveStopped is not handled");
let spawn = body.find(".spawn()").expect("no spawn in auto_start_comfyui");
assert!(plan < spawn && leave < spawn);
assert!(body.contains("comfy_autostart_enabled()"));
}
#[test]
fn lus_own_installer_turns_the_switch_on() {
let src = include_str!("install/comfy_install.rs");
assert!(src.contains(r#"config["comfyui_autostart"] = serde_json::json!(true)"#));
}
/// B9: Comfy Desktop serves on 8000.
#[test]
fn desktop_on_8000_is_followed_when_no_port_is_saved() {
assert_eq!(pick_comfy_port(8188, false, |p| p == 8000), 8000);
}
#[test]
fn a_saved_port_is_never_second_guessed() {
assert_eq!(pick_comfy_port(8188, true, |p| p == 8000), 8188);
assert_eq!(pick_comfy_port(9000, true, |_| false), 9000);
}
#[test]
fn the_default_wins_when_both_answer_and_silence_goes_back_to_8188() {
assert_eq!(pick_comfy_port(8188, false, |_| true), 8188);
assert_eq!(pick_comfy_port(8000, false, |p| p == 8188), 8188);
assert_eq!(pick_comfy_port(8000, false, |_| false), 8188);
assert_eq!(pick_comfy_port(8000, false, |p| p == 8000), 8000);
}
/// One HTTP answer on a free local port, the way a server would give it.
fn answer_once(body: &'static str) -> u16 {
use std::io::{Read, Write};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
std::thread::spawn(move || {
if let Ok((mut s, _)) = listener.accept() {
let mut buf = [0u8; 2048];
let _ = s.read(&mut buf);
let _ = write!(s, "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", body.len(), body);
}
});
port
}
/// Over a real socket: a ComfyUI's /system_stats counts, another server's
/// 200 on the same path does not, and a silent port is no ComfyUI.
#[test]
fn the_probe_tells_a_comfyui_from_another_server_over_http() {
let comfy = answer_once(r#"{"system":{"os":"posix","comfyui_version":"0.3.60"},"devices":[{"name":"mps"}]}"#);
assert!(looks_like_comfyui_on_port(comfy));
let other = answer_once(r#"{"status":"ok"}"#);
assert!(!looks_like_comfyui_on_port(other));
let silent = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
assert!(!looks_like_comfyui_on_port(silent));
}
#[test]
fn only_a_comfyui_shaped_answer_counts() {
let comfy = serde_json::json!({"system": {"os": "nt", "comfyui_version": "0.3.60"}, "devices": []});
assert!(is_comfy_system_stats(&comfy));
assert!(!is_comfy_system_stats(&serde_json::json!({"status": "ok"})));
assert!(!is_comfy_system_stats(&serde_json::json!({"system": "x", "devices": []})));
}
}
#[cfg(test)]
mod utf8_start_waechter {
/// Dieselbe Regel wie in install.rs, eine Datei weiter.
///
/// Ticket 003 (03.09.) hat gezeigt, wie teuer eine halb
/// durchgezogene Regel ist: ein Windows-Benutzername ausserhalb von ASCII
/// laesst jedes Python-Kind mit umgeleiteter Ausgabe auf einen
/// UnicodeEncodeError laufen, sobald es einen Pfad druckt. install.rs ist
/// seitdem geschlossen. process.rs war es nicht, obwohl hier der Prozess
/// startet, dessen Ausgabe der Kunde tatsaechlich zu sehen bekommt.
///
/// Die beiden ComfyUI-Starts hatten die Variablen schon seit dem Bericht
/// von einem Nutzer (07.06.), aber von Hand und an zwei Stellen. Genau das ist
/// "zwei Pfade, einer gepflegt": die eine Stelle wuchs mit, die andere
/// haette es nicht muessen. Jetzt fuehrt eine Hilfsfunktion die Regel.
#[test]
fn every_python_start_in_this_file_goes_through_python_command() {
let whole = include_str!("process.rs");
let src = whole.split("#[cfg(test)]").next().expect("die ausgelieferte Haelfte");
let mut daneben: Vec<&str> = Vec::new();
for line in src.lines() {
let Some(at) = line.find("Command::new(") else { continue };
let rest = &line[at + "Command::new(".len()..];
let arg = rest.split(')').next().unwrap_or(rest).to_ascii_lowercase();
if arg.contains("python") || arg.contains("pip") {
daneben.push(line.trim());
}
}
assert!(
daneben.is_empty(),
"diese Python-Starts gehen an python_command vorbei und laufen ohne \
PYTHONIOENCODING/PYTHONUTF8:\n{}",
daneben.join("\n"),
);
for name in ["PYTHONIOENCODING", "PYTHONUTF8"] {
assert!(
!src.contains(name),
"{name} wird in process.rs von Hand gesetzt statt in python_command",
);
}
assert!(
src.contains("python_command("),
"kein einziger Aufruf von python_command in process.rs, \
der Waechter wuerde ein Zurueckdrehen nicht bemerken",
);
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The Mac never runs ComfyUI, so it must never search the disk for one:
/// the home walk crosses ~/Desktop and ~/Music and macOS turns the first
/// touch of each into a permission dialog at launch.
#[test]
fn comfyui_disk_search_is_off_on_macos_and_on_elsewhere() {
assert_eq!(comfyui_disk_search_allowed(), !cfg!(target_os = "macos"));
}
// ── 3.0.7: the portable archive's outer folder ───────────────────────
//
// ComfyUI_windows_portable(_intel|_amd) unpacks as
// <outer>/{ComfyUI, python_embeded}. Picking <outer> answered
// "main.py not found", and the disk search only knew folders named
// ComfyUI, so a renamed outer folder needed one level more of depth.
fn file(root: &Path, rel: &str) {
let f = root.join(rel);
std::fs::create_dir_all(f.parent().unwrap()).unwrap();
std::fs::write(f, b"").unwrap();
}
/// A ComfyUI as ComfyUI ships it: `main.py` beside the `comfy` package.
fn comfyui(root: &Path, rel: &str) {
file(root, &format!("{rel}/main.py"));
file(root, &format!("{rel}/comfy/__init__.py"));
}
fn resolved(p: &Path) -> Option<PathBuf> {
resolve_comfyui_path(&p.to_string_lossy()).map(PathBuf::from)
}
#[test]
fn a_folder_with_main_py_is_taken_as_it_is() {
let tmp = tempfile::tempdir().unwrap();
comfyui(tmp.path(), ".");
// Even with a ComfyUI subfolder below it: the direct hit wins.
comfyui(tmp.path(), "ComfyUI");
assert_eq!(resolved(tmp.path()), Some(tmp.path().to_path_buf()));
}
#[test]
fn the_portable_outer_folder_resolves_to_its_comfyui_and_keeps_python_embeded_beside_it() {
let tmp = tempfile::tempdir().unwrap();
let outer = tmp.path().join("ComfyUI_windows_portable");
comfyui(&outer, "ComfyUI");
file(&outer, "python_embeded/python.exe");
let got = resolved(&outer).expect("the outer folder must resolve");
assert_eq!(got, outer.join("ComfyUI"));
assert!(got.parent().unwrap().join("python_embeded").join("python.exe").is_file());
}
#[test]
fn a_renamed_outer_folder_resolves_too() {
let tmp = tempfile::tempdir().unwrap();
let outer = tmp.path().join("Bilder KI");
comfyui(&outer, "ComfyUI");
assert_eq!(resolved(&outer), Some(outer.join("ComfyUI")));
}
#[test]
fn a_folder_without_comfyui_still_resolves_to_nothing() {
let tmp = tempfile::tempdir().unwrap();
assert_eq!(resolved(tmp.path()), None);
// A ComfyUI folder without main.py is no ComfyUI either.
std::fs::create_dir_all(tmp.path().join("ComfyUI")).unwrap();
file(tmp.path(), "ComfyUI/README.md");
assert_eq!(resolved(tmp.path()), None);
// And main.py two levels down is not taken: only the portable layout.
comfyui(tmp.path(), "x/ComfyUI");
assert_eq!(resolved(tmp.path()), None);
}
#[test]
fn the_disk_search_finds_comfyui_inside_a_renamed_outer_folder() {
let tmp = tempfile::tempdir().unwrap();
comfyui(tmp.path(), "KI Kram/ComfyUI");
// Depth 1 only looks at the direct children of the root. Before 3.0.7
// a child had to be NAMED ComfyUI, so "KI Kram" was missed here.
assert_eq!(
scan_for_comfyui(tmp.path(), 1),
Some(tmp.path().join("KI Kram").join("ComfyUI")),
);
}
#[test]
fn the_disk_search_still_ignores_folders_that_only_have_a_main_py() {
let tmp = tempfile::tempdir().unwrap();
file(tmp.path(), "some-python-project/main.py");
assert_eq!(scan_for_comfyui(tmp.path(), 3), None);
}
// ── Discord 25.10.2026: Comfy Desktop ────────────────────────────────
//
// LU ran "ComfyUI" from Comfy Desktop's bundled Python
// (`resources\bootstrap-python\Lib\_pyrepl`, which has a main.py), the
// start ended at once with exit 0, and the trainer looked for its base
// files in `_pyrepl\models`.
#[test]
fn a_main_py_without_the_comfy_package_is_not_comfyui() {
let tmp = tempfile::tempdir().unwrap();
let pyrepl = tmp.path().join("Comfy Desktop/resources/bootstrap-python/Lib/_pyrepl");
file(&pyrepl, "main.py");
file(&pyrepl, "__main__.py");
assert!(!is_comfyui_dir(&pyrepl));
assert_eq!(resolved(&pyrepl), None);
comfyui(tmp.path(), "ComfyUI");
assert!(is_comfyui_dir(&tmp.path().join("ComfyUI")));
}
#[test]
fn a_folder_named_comfyui_with_only_a_main_py_is_not_taken_by_the_disk_search() {
let tmp = tempfile::tempdir().unwrap();
file(tmp.path(), "old/ComfyUI/main.py");
assert_eq!(scan_for_comfyui(tmp.path(), 3), None);
}
#[test]
fn comfy_desktop_installs_are_found_under_comfyui_installs() {
let tmp = tempfile::tempdir().unwrap();
let installs = tmp.path().join("Comfy-Desktop/ComfyUI-Installs");
comfyui(&installs, "ComfyUI/ComfyUI");
comfyui(&installs, "Second");
file(&installs, "Broken/ComfyUI/main.py");
assert_eq!(
comfy_desktop_installs_in(&installs),
vec![installs.join("ComfyUI").join("ComfyUI"), installs.join("Second")],
);
assert!(comfy_desktop_installs_in(&tmp.path().join("missing")).is_empty());
}
#[test]
fn a_path_in_the_comfy_desktop_program_folder_is_recognised() {
assert!(in_comfy_desktop_program(Path::new(r"C:\Users\m\AppData\Local\Programs\Comfy Desktop\resources")));
assert!(in_comfy_desktop_program(Path::new("/x/comfy desktop")));
assert!(!in_comfy_desktop_program(Path::new(r"C:\Users\m\AppData\Local\Comfy-Desktop\ComfyUI-Installs")));
}
// ── OI-1: "your working ComfyUI is a broken torso" ───────────────────
//
// The probe answered `false` for every from-source Linux install and for
// every install on any platform that had been through `repair_comfyui_env`,
// because (a) it never looked inside ComfyUI's own venv, which is where
// both of those put torch, and (b) its system-Python branch was dead code:
// the candidate list held the bare string "python3",
// `Path::new("python3").parent()` is `Some("")`, and `"".parent()` is
// `None`, so the Unix arm could not be reached and the Windows arm
// degenerated to the relative path `Lib/site-packages/torch`.
//
// Both prefix layouts are built as fixture directories and the interpreter
// list is injected, so the Windows layout is checked on Unix and vice
// versa. What is NOT checked here: that a real ComfyUI with a real torch
// starts, which needs an actual 2 GB install.
/// Lay out `<root>/<rel>/torch` as a directory, creating parents.
fn touch_torch(root: &Path, rel: &str) {
let dir = root.join(rel).join("torch");
std::fs::create_dir_all(&dir).unwrap();
}
fn comfy_fixture() -> (tempfile::TempDir, PathBuf) {
let tmp = tempfile::tempdir().unwrap();
let comfy = tmp.path().join("ComfyUI");
std::fs::create_dir_all(&comfy).unwrap();
std::fs::write(comfy.join("main.py"), b"# comfy").unwrap();
(tmp, comfy)
}
#[test]
fn a_main_py_only_carcass_is_still_incomplete() {
// P14's guarantee must survive the OI-1 fix: a half-cloned dir with
// nothing but main.py has no torch anywhere and stays incomplete.
let (_tmp, comfy) = comfy_fixture();
assert!(!is_comfyui_install_complete_with(&comfy, &[]));
}
#[test]
fn a_directory_without_main_py_is_not_a_comfyui_at_all() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("NotComfy");
// Even with a fully populated venv: no main.py, nothing to start.
touch_torch(&dir, "venv/lib/python3.12/site-packages");
assert!(!is_comfyui_install_complete_with(&dir, &[]));
}
#[test]
fn torch_in_comfyuis_own_venv_unix_layout_is_complete() {
// The Linux from-source install and EVERY repaired install. This is
// the case that reported "broken torso" to every affected user.
let (_tmp, comfy) = comfy_fixture();
touch_torch(&comfy, "venv/lib/python3.12/site-packages");
assert!(is_comfyui_install_complete_with(&comfy, &[]));
}
#[test]
fn torch_in_comfyuis_own_venv_windows_layout_is_complete() {
let (_tmp, comfy) = comfy_fixture();
touch_torch(&comfy, "venv/Lib/site-packages");
assert!(is_comfyui_install_complete_with(&comfy, &[]));
}
#[test]
fn a_dot_venv_counts_like_a_venv() {
// `uv` and a modern `python -m venv .venv`: same install, other name
// (issue #51; `resolve_comfyui_venv_python` already knows it).
let (_tmp, comfy) = comfy_fixture();
touch_torch(&comfy, ".venv/lib/python3.11/site-packages");
assert!(is_comfyui_install_complete_with(&comfy, &[]));
}
#[test]
fn a_venv_without_torch_is_not_complete() {
// Negative control: the venv exists (a repair that died during the
// PyTorch download) but holds no torch, so it cannot start.
let (_tmp, comfy) = comfy_fixture();
std::fs::create_dir_all(comfy.join("venv").join("lib").join("python3.12").join("site-packages")).unwrap();
assert!(!is_comfyui_install_complete_with(&comfy, &[]));
}
#[test]
fn a_portable_python_embeded_still_counts_inside_or_beside() {
let (_tmp, comfy) = comfy_fixture();
touch_torch(&comfy, "python_embeded/Lib/site-packages");
assert!(is_comfyui_install_complete_with(&comfy, &[]));
// The other portable shape: python_embeded is a SIBLING of ComfyUI.
let (_tmp2, comfy2) = comfy_fixture();
let beside = comfy2.parent().unwrap().to_path_buf();
touch_torch(&beside, "python_embeded/Lib/site-packages");
assert!(is_comfyui_install_complete_with(&comfy2, &[]));
}
#[test]
fn a_unix_system_python_prefix_is_read_through_bin() {
// /usr/bin/python3 → prefix /usr → /usr/lib/python3.12/site-packages.
// The interpreter is one level BELOW its prefix on Unix, which is why
// the probe has to try the parent too.
let (_tmp, comfy) = comfy_fixture();
let root = comfy.parent().unwrap().join("usr");
std::fs::create_dir_all(root.join("bin")).unwrap();
let py = root.join("bin").join("python3");
std::fs::write(&py, b"stub").unwrap();
touch_torch(&root, "lib/python3.12/site-packages");
assert!(is_comfyui_install_complete_with(
&comfy,
&[py.to_string_lossy().to_string()]
));
}
#[test]
fn a_windows_system_python_prefix_is_read_next_to_the_exe() {
// C:\Python312\python.exe → C:\Python312\Lib\site-packages. Here the
// interpreter sits IN its prefix, not one below it.
let (_tmp, comfy) = comfy_fixture();
let root = comfy.parent().unwrap().join("Python312");
std::fs::create_dir_all(&root).unwrap();
let py = root.join("python.exe");
std::fs::write(&py, b"stub").unwrap();
touch_torch(&root, "Lib/site-packages");
assert!(is_comfyui_install_complete_with(
&comfy,
&[py.to_string_lossy().to_string()]
));
}
#[test]
fn a_bare_interpreter_name_can_never_answer_yes() {
// The mechanism of the bug, pinned. `Path::new("python3").parent()`
// is `Some("")`; joining onto it makes a RELATIVE path that resolves
// against LU's working directory, and `"".parent()` is `None`, which
// is what made the Unix arm unreachable.
assert_eq!(Path::new("python3").parent(), Some(Path::new("")));
assert_eq!(Path::new("").parent(), None);
assert!(!python_prefix_has_torch(Path::new("python3")));
assert!(!python_prefix_has_torch(Path::new("python")));
assert!(!prefix_has_torch(Path::new("")));
}
#[test]
fn every_candidate_python_is_an_absolute_path() {
// The callers derive a prefix from these strings, so a bare name is
// not a weaker answer, it is a wrong one.
for p in collect_candidate_pythons() {
assert!(
Path::new(&p).is_absolute(),
"candidate python is not absolute: {p}"
);
}
}
// ── E16: a start that fails has to say so ────────────────────────────
//
// Measured on the Windows box on 2026-08-14. The install had ComfyUI's
// source but neither python_embeded nor a venv, so the launch fell back to
// the system Python, which has none of the dependencies. main.py died on
// its first import inside a second. What the user got: `start_comfyui`
// answered {"status":"started"}, `comfyui_status` answered
// processAlive true / running false / starting true, the panel showed
// `Stopped`, and six minutes later it still showed `Stopped` with no
// reason anywhere, while the ImportError sat in our own ring buffer.
#[test]
fn a_start_that_is_already_over_stops_claiming_to_be_starting() {
// Inside the grace period a slow import is a normal start.
assert_eq!(
comfy_starting_state(true, false, Some(std::time::Duration::from_secs(30))),
(true, false),
);
// Past it, the handle is not proof of anything. `starting` has to end,
// and the caller needs to know it ended badly rather than quietly.
assert_eq!(
comfy_starting_state(true, false, Some(std::time::Duration::from_secs(COMFY_STARTING_GRACE_SECS + 1))),
(false, true),
);
// A port that answers is the end of the question, however long it took.
assert_eq!(
comfy_starting_state(true, true, Some(std::time::Duration::from_secs(9_999))),
(false, false),
);
// No child, nothing to wait for.
assert_eq!(comfy_starting_state(false, false, None), (false, false));
// Unknown start time (handle from an earlier session): fall back to the
// old reading rather than declaring a stall we cannot date.
assert_eq!(comfy_starting_state(true, false, None), (true, false));
}
#[test]
fn the_failure_message_carries_the_traceback_and_the_likely_cause() {
let tail = vec![
"[start] C:\\Python313\\python.exe main.py --port 8188".to_string(),
"Traceback (most recent call last):".to_string(),
" File \"main.py\", line 25, in <module>".to_string(),
" from app.assets.seeder import asset_seeder".to_string(),
"ModuleNotFoundError: No module named 'app'".to_string(),
];
let msg = comfy_startup_failure("C:\\Python313\\python.exe", Some(1), &tail, false);
// The reason the user can act on, verbatim from the child.
assert!(msg.contains("ModuleNotFoundError: No module named 'app'"), "{msg}");
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);
assert!(!msg2.contains("no python_embeded"), "{msg2}");
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
// ring buffer would show the banner and hide the error.
let mut tail: Vec<String> = (0..50).map(|i| format!("line {i}")).collect();
tail.push("RuntimeError: the actual reason".to_string());
let msg = comfy_startup_failure("python", Some(1), &tail, true);
assert!(msg.contains("RuntimeError: the actual reason"), "{msg}");
assert!(!msg.contains("line 0"), "{msg}");
}
#[test]
fn a_host_typed_with_its_port_keeps_both() {
assert_eq!(split_host_port("192.168.1.50:8188"), ("192.168.1.50".into(), Some(8188)));
assert_eq!(split_host_port("comfy.local:7860"), ("comfy.local".into(), Some(7860)));
}
#[test]
fn a_plain_host_is_left_alone() {
assert_eq!(split_host_port("192.168.1.50"), ("192.168.1.50".into(), None));
assert_eq!(split_host_port("localhost"), ("localhost".into(), None));
// Not a port: no digits, empty, or out of range.
assert_eq!(split_host_port("host:abc"), ("host:abc".into(), None));
assert_eq!(split_host_port("host:"), ("host:".into(), None));
assert_eq!(split_host_port("host:0"), ("host:0".into(), None));
assert_eq!(split_host_port("host:99999"), ("host:99999".into(), None));
// IPv6 literals must survive untouched.
assert_eq!(split_host_port("fd00::1"), ("fd00::1".into(), None));
}
// ── Bug J: needs_cpu_fallback platform short-circuit ─────────────────
#[test]
fn comfy_is_refused_on_macos_and_allowed_elsewhere() {
// "Mac local media is MLX, never ComfyUI" is a product rule, and the
// UI-side hiding of the buttons is not where a rule is kept — the
// remote/mobile control surface calls these commands directly.
if cfg!(target_os = "macos") {
assert!(!comfy_supported_here(), "macOS must refuse a local ComfyUI");
// The refusal has to say where the working surface is; a bare
// "unsupported" leaves the user with nothing to do next.
assert!(MACOS_COMFY_REFUSAL.contains("MLX"));
assert!(MACOS_COMFY_REFUSAL.contains("Settings"));
} else {
assert!(comfy_supported_here(), "Windows/Linux keep ComfyUI");
}
}
#[test]
fn needs_cpu_fallback_is_false_on_macos() {
// On macOS, PyTorch uses MPS and never calls cuda APIs that crash
// the way Linux+no-NVIDIA does. The fallback must be a no-op there
// so we don't downgrade real Mac users (M1/M2/etc) to CPU inference.
if cfg!(target_os = "macos") {
assert!(!needs_cpu_fallback(), "macOS must short-circuit to false");
} else {
// On non-macOS, the result depends on whether nvidia-smi is
// installed + returns success. The function is total — it must
// not panic in either branch. We just call it and assert it
// returns a bool (compiler-enforced anyway).
let _ = needs_cpu_fallback();
}
}
#[test]
fn needs_cpu_fallback_is_deterministic_for_repeat_calls() {
// Two consecutive calls must agree — no time-based or random
// behaviour smuggled in (Bug J's fix probes nvidia-smi each call,
// so if nvidia-smi state doesn't change, the answer doesn't either).
let a = needs_cpu_fallback();
let b = needs_cpu_fallback();
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));
}
// ── Ticket 007 (a user, 01.09. bis 02.09.) ─────────────────────────
//
// Windows 10 Home 20H2, Radeon R9 200 mit 3 GB. Er bekam den allgemeinen
// Satz ueber die kaputte Umgebung, drueckte Repair, wartete den Neubau ab
// und stand vor derselben Meldung: "I tried running the comfy repair
// directive from the settings area and that did not work either."
/// Der Puffer, den comfyui_last_output bei ihm gehalten hat. Die letzten
/// sechs Zeilen sind die aus seinem Bildschirmabzug; die Traceback-Zeile
/// davor steht hier, weil der Puffer mehr haelt als die Meldung zeigt und
/// die alte Regel genau an ihr angeschlagen hat.
fn falcon_bobs_tail() -> Vec<String> {
zeilen(&[
"Traceback (most recent call last):",
r#" File "C:\Users\xavie\ComfyUI\main.py", line 89, in <module>"#,
"import torch",
r#" File "C:\Users\xavie\ComfyUI\venv\Lib\site-packages\torch\__init__.py", line 309, in <module>"#,
" _load_dll_libraries()",
r#" File "C:\Users\xavie\ComfyUI\venv\Lib\site-packages\torch\__init__.py", line 292, in _load_dll_libraries"#,
" raise err",
r#"OSError: [WinError 1114] A dynamic link library (DLL) initialization routine failed. Error loading "C:\Users\xavie\ComfyUI\venv\Lib\site-packages\torch\lib\c10.dll" or one of its dependencies."#,
])
}
#[test]
fn falcon_bobs_dll_crash_does_not_start_a_rebuild_that_cannot_help() {
let tail = falcon_bobs_tail();
// Die alte Regel allein haette genau hier neu gebaut, deshalb steht
// sie als Ausgangslage im Test.
assert!(comfy_env_failure(&tail), "der Ausgangsbefund stimmt nicht mehr");
let verdict = comfy_crash_verdict(&tail, true);
assert!(
!verdict.env_broken,
"ein nativer Ladefehler loest weiter die Reparatur aus, die ihn nicht beheben kann",
);
}
#[test]
fn falcon_bobs_dll_crash_carries_the_hint_the_installer_already_had() {
let verdict = comfy_crash_verdict(&falcon_bobs_tail(), true);
assert!(
verdict.hint.contains("Visual C++"),
"die erste Ursache wird nicht genannt: {}",
verdict.hint,
);
assert!(
verdict.hint.to_lowercase().contains("driver"),
"die zweite Ursache wird nicht genannt: {}",
verdict.hint,
);
assert!(
!verdict.hint.contains("press Repair environment"),
"der Hinweis schickt weiter in die Reparatur: {}",
verdict.hint,
);
assert!(
verdict.hint.contains("Repair environment does not help here"),
"der Hinweis sagt nicht, dass die Reparatur hier nichts aendert: {}",
verdict.hint,
);
}
#[test]
fn a_missing_visual_cpp_library_at_startup_also_stops_the_rebuild() {
let tail = zeilen(&[
"Traceback (most recent call last):",
r#" File "C:\Users\xavie\ComfyUI\venv\Lib\site-packages\torch\__init__.py", line 309, in <module>"#,
r#"ImportError: VCOMP140.DLL was not found. Error loading "C:\Users\xavie\ComfyUI\venv\Lib\site-packages\torch\lib\c10.dll""#,
]);
let verdict = comfy_crash_verdict(&tail, true);
assert!(!verdict.env_broken, "eine fehlende Systembibliothek loest die Reparatur aus");
assert!(
verdict.hint.contains("VCOMP140.DLL"),
"die fehlende Datei wird nicht beim Namen genannt: {}",
verdict.hint,
);
}
#[test]
fn the_self_healing_from_gh_98_still_fires_for_everything_else() {
// Die Faehigkeit darf nicht versehentlich verschwinden: beide Faelle,
// die sie ueberhaupt erst gebaut haben, muessen weiter heilen, und
// ein fehlendes sqlalchemy (Ticket 003) auch.
for (was, tail) in [
("joels torch-import", zeilen(&[
"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"#,
"RuntimeError: infer_schema(func): Parameter dtype has unsupported type",
])),
("kryptoxides comfy-paket", zeilen(&[
"Traceback (most recent call last):",
r#" File "I:\comfyui\main.py", line 1, in <module>"#,
"ModuleNotFoundError: No module named 'comfy.options'",
])),
("missing sqlalchemy", zeilen(&[
"Traceback (most recent call last):",
r#" File "C:\Users\1 בוגר\ComfyUI\app\database\db.py", line 3, in <module>"#,
"ModuleNotFoundError: No module named 'sqlalchemy'",
])),
] {
let verdict = comfy_crash_verdict(&tail, true);
assert!(verdict.env_broken, "{was}: die Selbstheilung ist weg");
assert!(
verdict.hint.is_empty(),
"{was}: ein Hinweistext ueber pip verdraengt den richtigen Satz ueber die Reparatur: {}",
verdict.hint,
);
}
}
#[test]
fn a_process_that_still_runs_is_never_called_broken() {
// Negativprobe: der Befund haengt weiter am beendeten Kind, sonst
// repariert die Oberflaeche einen laufenden Start weg.
assert!(!comfy_crash_verdict(&falcon_bobs_tail(), false).env_broken);
}
// ── AMD/ROCm ComfyUI GPU decision (rhodium92, 2026-07-01) ────────────
#[test]
fn comfy_gpu_mode_parse_maps_known_values_and_defaults_to_auto() {
assert_eq!(ComfyGpuMode::parse("auto"), ComfyGpuMode::Auto);
assert_eq!(ComfyGpuMode::parse("cpu"), ComfyGpuMode::ForceCpu);
assert_eq!(ComfyGpuMode::parse("gpu"), ComfyGpuMode::ForceGpu);
assert_eq!(ComfyGpuMode::parse("GPU"), ComfyGpuMode::ForceGpu);
assert_eq!(ComfyGpuMode::parse(" Cpu "), ComfyGpuMode::ForceCpu);
assert_eq!(ComfyGpuMode::parse("nonsense"), ComfyGpuMode::Auto);
assert_eq!(ComfyGpuMode::parse(""), ComfyGpuMode::Auto);
}
#[test]
fn decide_force_modes_ignore_baseline_and_probe() {
// ForceCpu is always --cpu; ForceGpu is never --cpu, no matter what the
// baseline check or the torch probe report.
for &baseline in &[true, false] {
for torch in [Some(true), Some(false), None] {
assert!(
decide_comfy_cpu_flag(ComfyGpuMode::ForceCpu, baseline, torch),
"ForceCpu must always request --cpu"
);
assert!(
!decide_comfy_cpu_flag(ComfyGpuMode::ForceGpu, baseline, torch),
"ForceGpu must never request --cpu"
);
}
}
}
#[test]
fn decide_auto_nvidia_or_macos_never_uses_cpu() {
// baseline_needs_cpu == false means NVIDIA present (or macOS MPS): the GPU
// is already fine, so the torch probe is irrelevant and it's never --cpu.
assert!(!decide_comfy_cpu_flag(ComfyGpuMode::Auto, false, None));
assert!(!decide_comfy_cpu_flag(ComfyGpuMode::Auto, false, Some(false)));
assert!(!decide_comfy_cpu_flag(ComfyGpuMode::Auto, false, Some(true)));
}
#[test]
fn decide_auto_amd_rocm_or_zluda_torch_skips_cpu() {
// No NVIDIA driver (baseline == true) but the comfy python's torch reports
// a usable GPU (ROCm/ZLUDA) → run on the GPU, no --cpu. The rhodium92 fix.
assert!(!decide_comfy_cpu_flag(ComfyGpuMode::Auto, true, Some(true)));
}
#[test]
fn decide_auto_no_usable_gpu_falls_back_to_cpu() {
// No NVIDIA and torch has no usable GPU (stock CUDA torch on an AMD box,
// or a CPU-only install) → --cpu, exactly the pre-fix safe behaviour.
assert!(decide_comfy_cpu_flag(ComfyGpuMode::Auto, true, Some(false)));
// Probe failed / timed out → conservative --cpu (never risk the main.py
// "Found no NVIDIA driver" crash loop).
assert!(decide_comfy_cpu_flag(ComfyGpuMode::Auto, true, None));
}
#[test]
fn probe_comfy_gpu_on_empty_python_is_definitive_false() {
assert_eq!(probe_comfy_gpu(""), Some(false));
}
// ── 3.0.8: DirectML is found, and gets the flag it needs ─────────────
#[test]
fn the_probe_names_directml_last_and_cheaply() {
assert_eq!(parse_comfy_gpu_probe("directml\n"), Some("directml"));
let xpu = COMFY_GPU_PROBE.find("torch.xpu.is_available()").expect("xpu is asked");
let dml = COMFY_GPU_PROBE.find("find_spec('torch_directml')").expect("directml is asked");
assert!(xpu < dml, "a real CUDA/ROCm/XPU torch must win over a DirectML add-on: {COMFY_GPU_PROBE}");
// find_spec, not an import: the probe may not load DirectML just to ask.
assert!(!COMFY_GPU_PROBE.contains("import torch_directml"), "{COMFY_GPU_PROBE}");
}
#[test]
fn auto_starts_a_directml_environment_with_directml_and_not_with_cpu() {
let dml = parse_comfy_gpu_probe("directml");
// Auto, no NVIDIA driver: the environment has a GPU path, so no --cpu ...
assert!(!decide_comfy_cpu_flag(ComfyGpuMode::Auto, true, Some(dml.is_some())));
// ... and the one flag ComfyUI needs to take it.
assert_eq!(comfy_device_flag(ComfyGpuMode::Auto, true, dml), Some("--directml"));
assert_eq!(comfy_device_flag(ComfyGpuMode::ForceGpu, true, dml), Some("--directml"));
// NEGATIVE CONTROLS: Force CPU, an NVIDIA box, and every other device.
assert_eq!(comfy_device_flag(ComfyGpuMode::ForceCpu, true, dml), None);
assert_eq!(comfy_device_flag(ComfyGpuMode::Auto, false, dml), None);
for other in [Some("cuda"), Some("xpu"), None] {
assert_eq!(comfy_device_flag(ComfyGpuMode::Auto, true, other), None, "{other:?}");
}
}
#[test]
fn force_gpu_on_a_served_amd_card_points_at_repair_and_the_rest_stays() {
let served = force_gpu_warning_for(ComfyGpuMode::ForceGpu, Some(false), true, true, "windows").unwrap();
assert!(served.contains("Repair environment"), "{served}");
assert!(served.contains("ROCm build"), "{served}");
assert!(served.contains("driver"), "{served}");
assert!(!served.contains("ZLUDA"), "{served}");
// NEGATIVE CONTROL: a card LU does not serve keeps the 3.0.7 answer.
let unserved = force_gpu_warning_for(ComfyGpuMode::ForceGpu, Some(false), true, false, "windows").unwrap();
assert_eq!(Some(unserved.clone()), force_gpu_warning(ComfyGpuMode::ForceGpu, Some(false), true, "windows"));
assert!(unserved.contains("ZLUDA"), "{unserved}");
// and a working torch still gets no warning at all
assert_eq!(force_gpu_warning_for(ComfyGpuMode::ForceGpu, Some(true), true, true, "windows"), None);
}
// ── 3.0.7: Intel XPU counts as a GPU ─────────────────────────────────
#[test]
fn the_probe_output_names_cuda_xpu_or_nothing() {
assert_eq!(parse_comfy_gpu_probe("cuda\n"), Some("cuda"));
assert_eq!(parse_comfy_gpu_probe("xpu\r\n"), Some("xpu"));
assert_eq!(parse_comfy_gpu_probe("none\n"), None);
// A torch that did not import prints nothing to stdout.
assert_eq!(parse_comfy_gpu_probe(""), None);
// A warning printed before the answer does not hide it.
assert_eq!(parse_comfy_gpu_probe("UserWarning: something\nxpu\n\n"), Some("xpu"));
// Only the answer itself counts, not a line that mentions a device.
assert_eq!(parse_comfy_gpu_probe("cuda is not here\nnone"), None);
}
#[test]
fn the_probe_asks_xpu_behind_a_hasattr_guard_and_cuda_first() {
let cuda = COMFY_GPU_PROBE.find("torch.cuda.is_available()").expect("cuda is asked");
let guard = COMFY_GPU_PROBE.find("hasattr(torch, 'xpu')").expect("xpu is guarded");
let xpu = COMFY_GPU_PROBE.find("torch.xpu.is_available()").expect("xpu is asked");
assert!(cuda < guard && guard < xpu, "{COMFY_GPU_PROBE}");
// Every word the parser accepts is one the script can print.
for word in ["'cuda'", "'xpu'", "'none'"] {
assert!(COMFY_GPU_PROBE.contains(word), "{word} missing: {COMFY_GPU_PROBE}");
}
}
#[test]
fn auto_keeps_an_intel_xpu_card_off_the_processor() {
// No NVIDIA driver (baseline true), torch answered xpu: Some(true).
let xpu = parse_comfy_gpu_probe("xpu").is_some();
assert!(!decide_comfy_cpu_flag(ComfyGpuMode::Auto, true, Some(xpu)));
assert_eq!(cpu_flag_reason(ComfyGpuMode::Auto, true, Some(xpu)), None);
// NEGATIVE CONTROL: the same box with a processor torch stays on --cpu.
let none = parse_comfy_gpu_probe("none").is_some();
assert!(decide_comfy_cpu_flag(ComfyGpuMode::Auto, true, Some(none)));
}
#[test]
fn force_gpu_on_an_xpu_torch_says_nothing_and_without_one_names_both() {
// An Intel box: no AMD card, torch reported xpu.
let xpu = parse_comfy_gpu_probe("xpu").is_some();
assert_eq!(force_gpu_warning(ComfyGpuMode::ForceGpu, Some(xpu), false, "windows"), None);
// Without an XPU torch the note says what was asked and how an Arc card gets there.
let warn = force_gpu_warning(ComfyGpuMode::ForceGpu, Some(false), false, "windows")
.expect("a dead torch is still worth a word");
assert!(warn.contains("neither CUDA nor Intel XPU"), "{warn}");
assert!(warn.contains("download.pytorch.org/whl/xpu"), "{warn}");
// The continuation lines no longer leave runs of spaces in the text.
for amd_os in ["linux", "windows"] {
let w = force_gpu_warning(ComfyGpuMode::ForceGpu, Some(false), true, amd_os).unwrap();
assert!(!w.contains(" "), "double space in {w}");
assert!(!w.contains("Arc card"), "the AMD note sends nobody to the XPU build: {w}");
}
assert!(!warn.contains(" "), "double space in {warn}");
}
#[test]
fn force_gpu_on_a_torch_without_a_gpu_says_why_before_the_crash() {
let linux = force_gpu_warning(ComfyGpuMode::ForceGpu, Some(false), true, "linux")
.expect("an AMD Linux box with CUDA wheels must be told");
assert!(linux.contains("Torch not compiled with CUDA enabled"), "{linux}");
assert!(linux.contains("ROCm"), "the Linux way out is a reinstall: {linux}");
let win = force_gpu_warning(ComfyGpuMode::ForceGpu, Some(false), true, "windows")
.expect("an AMD Windows box must be told too");
assert!(win.contains("DirectML"), "{win}");
// Never promise a reinstall that cannot exist: there are no ROCm
// wheels for Windows, so the message must not send the user there.
assert!(!win.contains("Reinstall the ComfyUI environment"), "{win}");
let other = force_gpu_warning(ComfyGpuMode::ForceGpu, Some(false), false, "windows")
.expect("a non-AMD box with a dead torch is still worth a word");
assert!(!other.contains("AMD"), "{other}");
}
#[test]
fn nothing_is_said_when_there_is_nothing_to_say() {
// Negative controls: the note only belongs to Force GPU on a torch
// that answered "no GPU". Everything else stays quiet.
assert_eq!(force_gpu_warning(ComfyGpuMode::ForceGpu, Some(true), true, "linux"), None);
assert_eq!(force_gpu_warning(ComfyGpuMode::ForceGpu, None, true, "linux"), None);
assert_eq!(force_gpu_warning(ComfyGpuMode::Auto, Some(false), true, "linux"), None);
assert_eq!(force_gpu_warning(ComfyGpuMode::ForceCpu, Some(false), true, "linux"), None);
}
/// Der Satz, der bis 2.6.8 im Ausgabefenster stand, sobald ComfyUI mit
/// --cpu startete. Steht hier als Negativkontrolle: er darf nirgends mehr
/// herauskommen.
const ALTE_ZEILE: &str = "No NVIDIA driver detected";
#[test]
fn the_cpu_line_names_the_real_reason_and_never_a_missing_nvidia_driver() {
// Der Fall, den ein AMD-Nutzer wirklich trifft: kein NVIDIA-Treiber,
// Auto, und das torch dieser Umgebung meldet keine Karte.
let auto = cpu_flag_reason(ComfyGpuMode::Auto, true, Some(false))
.expect("hier kommt --cpu, also braucht es einen Grund");
assert!(!auto.contains(ALTE_ZEILE), "{auto}");
assert!(auto.contains("no usable GPU"), "{auto}");
assert!(auto.contains("Settings > ComfyUI"), "der Weg raus fehlt: {auto}");
// Die Sonde hat nicht geantwortet. Das ist etwas anderes als "keine
// Karte" und wird auch so gesagt, sonst schickt der Satz jemanden auf
// eine Neuinstallation, die nichts zu heilen hat.
let stumm = cpu_flag_reason(ComfyGpuMode::Auto, true, None)
.expect("auch hier kommt --cpu");
assert!(!stumm.contains(ALTE_ZEILE), "{stumm}");
assert!(stumm.contains("did not answer"), "{stumm}");
assert!(!stumm.contains("no usable GPU"), "keine falsche Gewissheit: {stumm}");
// Der Nutzer hat es selbst so eingestellt. Dann ist der Schalter der
// Grund, nicht die Hardware.
let gewollt = cpu_flag_reason(ComfyGpuMode::ForceCpu, true, None)
.expect("Force CPU heisst immer --cpu");
assert!(gewollt.contains("Force CPU"), "{gewollt}");
assert!(gewollt.contains("Auto"), "der Weg raus fehlt: {gewollt}");
}
#[test]
fn a_start_that_never_passes_cpu_says_nothing_at_all() {
// Kein Grund ohne Flagge. Sonst steht im Fenster eine Erklaerung fuer
// etwas, das gar nicht passiert.
assert_eq!(cpu_flag_reason(ComfyGpuMode::Auto, false, None), None, "NVIDIA da");
assert_eq!(cpu_flag_reason(ComfyGpuMode::Auto, true, Some(true)), None, "ROCm-torch sieht die Karte");
assert_eq!(cpu_flag_reason(ComfyGpuMode::ForceGpu, true, Some(false)), None, "Force GPU laesst --cpu weg");
}
}
/// Cloud mode = cloud-only inference: release every LOCAL model backend so
/// nothing sits in RAM/VRAM while the app talks to the cloud (2026-07-11).
/// Best-effort per backend — one failing step never blocks the others. Local
/// mode reloads everything LAZILY on first use, so this is safe to run on every
/// switch into cloud and on launch-in-cloud. (LM Studio is offloaded separately
/// by the frontend via `lmstudio_unload_model("--all")`.)
/// `include_comfyui` = whether to also free ComfyUI's VRAM. Cloud switch passes
/// nothing (defaults true — release everything). A LOCAL render passes `false`:
/// it wants the chat LLMs out of VRAM to make room, but ComfyUI keeps its own
/// checkpoint cached across consecutive Create runs (freeing it here would force
/// a slow reload between every generate).
// ASYNC + spawn_blocking: a SYNCHRONOUS Tauri command runs on the MAIN thread.
// The State borrow cannot cross into the blocking pool, so the handle is
// re-resolved there from the AppHandle (same pattern as engine.rs/whisper.rs).
#[tauri::command]
pub async fn offload_local_models(app: tauri::AppHandle, include_comfyui: Option<bool>) -> Result<serde_json::Value, String> {
tokio::task::spawn_blocking(move || {
let state = app.state::<AppState>();
offload_local_models_blocking(&state, include_comfyui)
})
.await
.map_err(|e| format!("offload_local_models task: {e}"))?
}
pub(crate) fn offload_local_models_blocking(state: &AppState, include_comfyui: Option<bool>) -> Result<serde_json::Value, String> {
let free_comfy = include_comfyui.unwrap_or(true);
let mut freed: Vec<&str> = Vec::new();
// 1) Whisper STT — the python server holds the model resident; stopping it
// frees ~360 MB. transcribe() lazily restarts it on the next local use.
if let Ok(mut w) = state.whisper.lock() {
if w.is_running() {
w.stop();
freed.push("whisper");
}
}
// 2) Bundled llama.cpp chat + embeddings sidecars (managed GGUF in RAM).
// Both are graceful no-ops when not running, and lazy-start on next use.
// Call the lifecycle helpers directly — the #[command] wrappers are async
// now (they moved off the Tauri main thread) and this caller is sync.
if crate::commands::engine::stop_engine_on_request(state) {
freed.push("bundled-engine");
}
if crate::commands::engine::stop_embed_locked(state) {
freed.push("bundled-embed");
}
// T-65: `not_ours` carries the backends LU did NOT free and why. Before,
// both of these returned a bare `false` for "nothing was loaded" and for
// "that address is not mine", and the caller was told the same thing in
// both cases. The result now says which it was.
let mut not_ours: Vec<serde_json::Value> = Vec::new();
let mut note = |backend: &str, outcome: &VramRelease| {
if let Some((target, why)) = outcome.not_responsible() {
tracing::info!(target: "engine", backend, addr = %target, reason = %why, "not this app's to free");
not_ours.push(serde_json::json!({
"backend": backend,
"target": target,
"why": why,
}));
}
};
// 3) Ollama — keep `serve` up (cheap, idle) but evict every loaded model.
let ollama = offload_ollama_loaded_models(state);
if ollama.released() {
freed.push("ollama");
}
note("ollama", &ollama);
// 4) ComfyUI — free VRAM/RAM without killing the server, so the next local
// render just reloads the checkpoint (no slow process restart). Skipped
// when a local render is the caller (it keeps its own checkpoint cached).
if free_comfy {
let comfy = free_comfyui_memory(state);
if comfy.released() {
freed.push("comfyui");
}
note("comfyui", &comfy);
}
tracing::info!(
target: "engine",
comfyui = free_comfy,
freed = ?freed,
not_ours = not_ours.len(),
"released local model backends"
);
Ok(serde_json::json!({ "offloaded": freed, "notOurs": not_ours }))
}
// ── T-65: the make-room-for-VRAM step, at the address the app actually uses ──
//
// Both helpers below used to hardcode `http://localhost:8188` and
// `http://localhost:11434`, so on a user-configured ComfyUI port or a
// non-default Ollama base they asked a machine nobody was listening on. The
// address is not a second source of truth to invent: `AppState::comfy_host` /
// `comfy_port` (config.json, `set_comfyui_port`) and `AppState::ollama_base`
// (config.json `ollama_base`, then `OLLAMA_HOST`, then the default — see
// `state::load_ollama_base`) already are that source, and every other caller in
// the app reads them. These now do too.
//
// The second half of the finding is the return type. `bool` made "the backend
// let nothing go" and "LU asked an address it does not own" the same answer,
// `false` — so a user on a custom port got the exact silence a user with an
// idle backend got. Fixing the address without fixing that would only move the
// silence one case further out: a ComfyUI on another machine still holds VRAM
// that freeing cannot help with, and that has to READ as "not LU's to free",
// not as "nothing found".
/// The outcome of asking one backend to let go of its memory.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum VramRelease {
/// The backend answered and released something.
Released,
/// The backend answered; it was holding nothing to release.
NothingLoaded,
/// LU did not release anything and this memory is not LU's to free —
/// the backend is configured on another machine, or nothing answered at
/// the address LU owns.
NotResponsible {
/// The address that was asked (or would have been), for the log.
target: String,
why: String,
},
}
impl VramRelease {
/// Did this actually free memory? The one question the old `bool` could
/// answer — kept, so callers that only branch on it stay readable.
pub(crate) fn released(&self) -> bool {
matches!(self, VramRelease::Released)
}
/// Short reason for the log / the command result. `None` when LU was
/// responsible and did its part.
pub(crate) fn not_responsible(&self) -> Option<(&str, &str)> {
match self {
VramRelease::NotResponsible { target, why } => Some((target, why)),
_ => None,
}
}
}
/// Is this base URL pointed at this machine?
///
/// A backend on another host holds another machine's memory: asking it to
/// unload cannot make room here, so the honest answer is "not responsible"
/// rather than a silent no-op. Falls back to "not local" for a URL that will
/// not parse — refusing to guess is the safe direction here.
pub(crate) fn base_url_is_local(base: &str) -> bool {
match url::Url::parse(base) {
Ok(u) => match u.host_str() {
// `host_str` keeps the brackets on an IPv6 literal (`[::1]`),
// which `is_local_host` does not know about.
Some(h) => is_local_host(h.trim_start_matches('[').trim_end_matches(']')),
// No host at all (e.g. a bare path) — nothing to reach.
None => false,
},
Err(_) => false,
}
}
/// Where THIS machine's ComfyUI is, or why there is nothing here to free.
///
/// Split from the state read so the rule itself is testable without an
/// `AppState`: everything that decides an address lives in `_for`.
pub(crate) fn comfy_vram_target_for(host: &str, port: u16) -> Result<String, (String, String)> {
let base = format!("http://{}:{}", host, port);
if !is_local_host(host) {
return Err((
base,
"ComfyUI is configured on another host, so its VRAM is not this machine's to free"
.to_string(),
));
}
Ok(base)
}
pub(crate) fn comfy_vram_target(state: &AppState) -> Result<String, (String, String)> {
let host = state
.comfy_host
.lock()
.map(|g| g.clone())
.unwrap_or_else(|_| "localhost".to_string());
let port = state.comfy_port.lock().map(|g| *g).unwrap_or(8188);
comfy_vram_target_for(&host, port)
}
/// Where THIS machine's Ollama is, or why there is nothing here to free.
pub(crate) fn ollama_vram_target_for(base: &str) -> Result<String, (String, String)> {
if !base_url_is_local(base) {
return Err((
base.to_string(),
"Ollama is configured on another host, so its RAM/VRAM is not this machine's to free"
.to_string(),
));
}
Ok(base.trim_end_matches('/').to_string())
}
pub(crate) fn ollama_vram_target(state: &AppState) -> Result<String, (String, String)> {
let base = state
.ollama_base
.lock()
.map(|g| g.clone())
.unwrap_or_else(|_| "http://localhost:11434".to_string());
ollama_vram_target_for(&base)
}
/// Evict every model Ollama currently holds in memory via `keep_alive: 0`,
/// leaving `ollama serve` running (idle serve is cheap). Best-effort.
///
/// `base` comes from `AppState::ollama_base` via [`ollama_vram_target`] — see
/// the T-65 note above for why it is not a constant here.
pub(crate) fn offload_ollama_loaded_models_at(base: &str) -> VramRelease {
let unreachable = |why: &str| VramRelease::NotResponsible {
target: base.to_string(),
why: why.to_string(),
};
let client = match reqwest::blocking::Client::builder()
.timeout(std::time::Duration::from_secs(2))
.build()
{
Ok(c) => c,
Err(e) => return unreachable(&format!("no HTTP client: {e}")),
};
let ps = match client
.get(format!("{base}/api/ps"))
.send()
.ok()
.and_then(|r| r.json::<serde_json::Value>().ok())
{
Some(v) => v,
None => return unreachable("nothing answered /api/ps there"),
};
// Ollama answered — from here on LU IS responsible, so "no models" is
// NothingLoaded and not a shrug.
let models = match ps.get("models").and_then(|m| m.as_array()) {
Some(a) => a,
None => return VramRelease::NothingLoaded,
};
let mut any = false;
for m in models {
if let Some(name) = m
.get("name")
.or_else(|| m.get("model"))
.and_then(|n| n.as_str())
{
let _ = client
.post(format!("{base}/api/generate"))
.json(&serde_json::json!({ "model": name, "keep_alive": 0 }))
.send();
any = true;
}
}
if any {
VramRelease::Released
} else {
VramRelease::NothingLoaded
}
}
/// Ask ComfyUI to unload checkpoints and free memory, keeping the server up so
/// the next local render reloads on demand. Best-effort.
/// Also used by the character trainer — on a 12 GB card a cached video
/// checkpoint next door is the difference between training and CUDA OOM.
///
/// `base` comes from `AppState::comfy_host`/`comfy_port` via
/// [`comfy_vram_target`]; the port is user-configurable and the default 8188 is
/// only a default.
pub(crate) fn free_comfyui_memory_at(base: &str) -> VramRelease {
let client = match reqwest::blocking::Client::builder()
.timeout(std::time::Duration::from_secs(2))
.build()
{
Ok(c) => c,
Err(e) => {
return VramRelease::NotResponsible {
target: base.to_string(),
why: format!("no HTTP client: {e}"),
}
}
};
match client
.post(format!("{base}/free"))
.json(&serde_json::json!({ "unload_models": true, "free_memory": true }))
.send()
{
// ComfyUI answers 200 to /free whether or not anything was cached, so
// there is no NothingLoaded to distinguish here — a 200 means it did
// what it could.
Ok(r) if r.status().is_success() => VramRelease::Released,
Ok(r) => VramRelease::NotResponsible {
target: base.to_string(),
why: format!("/free answered HTTP {}", r.status().as_u16()),
},
Err(e) => VramRelease::NotResponsible {
target: base.to_string(),
why: format!("nothing answered /free there ({e})"),
},
}
}
/// State-aware wrappers: resolve the address first, then ask. A backend the
/// user put on another machine never gets asked and never reads as a failure.
pub(crate) fn free_comfyui_memory(state: &AppState) -> VramRelease {
match comfy_vram_target(state) {
Ok(base) => free_comfyui_memory_at(&base),
Err((target, why)) => VramRelease::NotResponsible { target, why },
}
}
pub(crate) fn offload_ollama_loaded_models(state: &AppState) -> VramRelease {
match ollama_vram_target(state) {
Ok(base) => offload_ollama_loaded_models_at(&base),
Err((target, why)) => VramRelease::NotResponsible { target, why },
}
}
#[cfg(test)]
mod start_gate_tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
static TEST_GATE: Mutex<()> = Mutex::new(());
/// The window that matters: two threads both pass a "nothing is running"
/// check and both spawn. With the gate, the second one cannot enter until
/// the first has finished storing its child.
#[test]
fn two_concurrent_starts_never_overlap() {
static INSIDE: AtomicUsize = AtomicUsize::new(0);
static MAX_SEEN: AtomicUsize = AtomicUsize::new(0);
let threads: Vec<_> = (0..8)
.map(|_| {
std::thread::spawn(|| {
let _gate = start_gate(&TEST_GATE);
let now = INSIDE.fetch_add(1, Ordering::AcqRel) + 1;
MAX_SEEN.fetch_max(now, Ordering::AcqRel);
std::thread::sleep(std::time::Duration::from_millis(5));
INSIDE.fetch_sub(1, Ordering::AcqRel);
})
})
.collect();
for t in threads {
t.join().unwrap();
}
assert_eq!(MAX_SEEN.load(Ordering::Acquire), 1, "two starts ran at once");
}
/// A panic inside a start must not wedge every later start.
#[test]
fn a_poisoned_gate_still_opens() {
static POISON_ME: Mutex<()> = Mutex::new(());
let _ = std::thread::spawn(|| {
let _gate = start_gate(&POISON_ME);
panic!("start blew up");
})
.join();
let _gate = start_gate(&POISON_ME); // would panic on a plain .unwrap()
}
}
#[cfg(test)]
mod ollama_probe_tests {
use super::*;
/// Fehlerkontrolle Mac 2, Fund 2: no start of Ollama may go through the
/// bare name again. From the Finder the name resolves against the launchd
/// PATH, which has neither /usr/local/bin nor /opt/homebrew/bin.
#[test]
fn no_ollama_start_uses_the_bare_name() {
let bare = ["foreign_system_command(", "\"ollama\")"].concat();
for (name, src) in [
("process.rs", include_str!("process.rs")),
("install/ollama.rs", include_str!("install/ollama.rs")),
] {
assert!(!src.contains(&bare), "{name} starts Ollama off the bare PATH again");
}
let which = ["foreign_system_command(\"which\")", ".arg(\"ollama\")"].concat();
assert!(
!include_str!("install/ollama.rs").contains(&which),
"the Mac installer asks `which ollama` again, which a Finder-started app cannot answer"
);
}
#[test]
fn the_cli_inside_ollama_app_is_looked_for_system_wide_and_per_user() {
let found = super::ollama_bundle_candidates(std::path::Path::new("/Users/someone"));
assert_eq!(
found,
vec![
std::path::PathBuf::from("/Applications/Ollama.app/Contents/Resources/ollama"),
std::path::PathBuf::from("/Users/someone/Applications/Ollama.app/Contents/Resources/ollama"),
]
);
}
/// Whatever is found is handed to the spawn as a full path, so the PATH of
/// the process no longer decides whether Ollama starts.
#[cfg(target_os = "macos")]
#[test]
fn a_found_ollama_is_started_by_its_full_path() {
match super::find_ollama() {
Some(found) => {
assert!(found.is_absolute() && found.is_file(), "{found:?}");
assert_eq!(super::ollama_program(), found.into_os_string());
}
None => assert_eq!(super::ollama_program(), std::ffi::OsString::from("ollama")),
}
}
/// Observed on macOS 2026-07-28: the "is Ollama already running?" check
/// shelled out to `tasklist`, which does not exist outside Windows, so the
/// check was skipped and a second server was spawned on every launch. The
/// probe must answer on THIS platform, not just on Windows.
#[test]
fn the_probe_answers_without_shelling_out() {
let started = std::time::Instant::now();
let _ = ollama_port_open();
assert!(
started.elapsed() < std::time::Duration::from_millis(500),
"probe took {:?} — is it spawning a process again?",
started.elapsed()
);
}
/// A listener on the port must be seen as "already running" on every
/// platform. Binds a throwaway listener to prove the probe mechanism
/// itself works here, without touching the real Ollama port.
#[test]
fn a_listening_socket_is_detected() {
use std::net::{SocketAddr, TcpListener, TcpStream};
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let addr: SocketAddr = listener.local_addr().unwrap();
assert!(
TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(300)).is_ok(),
"the probe cannot see a socket that is demonstrably listening",
);
drop(listener);
}
}
/// Orphan safety: every long lived child the app spawns has to die with the
/// app, including the deaths that never reach `shutdown_subprocesses` (a hard
/// kill, Task Manager, a build script that clears the way for itself).
///
/// The evidence these tests were written from, Windows box 2026-08-29: the app
/// was terminated at 09:48:19, both ComfyUI processes went with it because
/// ComfyUI was in the kill-on-close job, and lu-llama-server survived holding
/// 3633 MiB of VRAM because the engine spawn was not.
#[cfg(test)]
mod orphan_safety_tests {
use super::*;
/// Source of the files that spawn a long lived child, read at compile
/// time. A grep in a test is a blunt instrument, but it is the only guard
/// available for a Windows kernel behaviour that cannot be exercised on
/// this machine, and it fails loudly when a NEW spawn path forgets the
/// call rather than after the next VRAM leak in the field.
const ENGINE_RS: &str = include_str!("engine.rs");
const WHISPER_RS: &str = include_str!("whisper.rs");
const TRAINER_RS: &str = include_str!("trainer.rs");
const PROCESS_RS: &str = include_str!("process.rs");
fn ties(src: &str) -> usize {
src.matches("tie_child_to_app_lifetime(").count()
- src.matches("fn tie_child_to_app_lifetime(").count()
}
#[test]
fn the_bundled_engine_and_the_embeddings_server_are_both_tied_to_the_app() {
// Two spawns in engine.rs: the chat server and the embeddings server.
// Neither was tied before 2.6.7, and the chat one is the orphan that
// was measured holding 3633 MiB after the app was gone.
assert!(
ENGINE_RS.contains("tie_child_to_app_lifetime(child.id())"),
"the bundled engine spawn must tie its child to the app lifetime"
);
// A third since 3.0.8 (A14): the llama-server the refusal-removal
// tool checks a model with (`spawn_private_server`). Short lived, but
// it holds a whole model on the card while it runs, so it is tied too.
assert_eq!(
ties(ENGINE_RS),
3,
"engine.rs has three llama-server spawns (chat, embeddings, the check); all must be tied"
);
}
/// process.rs up to this test module. The assertions below mention the
/// call by name many times over, and counting those as call sites would
/// make the guard meaningless.
fn process_rs_production_code() -> &'static str {
PROCESS_RS
.split_once("mod orphan_safety_tests {")
.map(|(head, _)| head)
.expect("this module is part of process.rs")
}
#[test]
fn the_other_long_lived_children_are_tied_too() {
assert_eq!(ties(WHISPER_RS), 1, "the persistent whisper server must be tied");
assert_eq!(ties(TRAINER_RS), 1, "the trainer must be tied");
// Ollama is spawned twice: the command and the auto-start path.
assert_eq!(
ties(process_rs_production_code()),
2,
"both ollama spawns must be tied"
);
}
#[test]
fn comfyui_keeps_the_job_it_already_had() {
// Negative control: the fix must not have moved ComfyUI off the
// mechanism that demonstrably worked on 2026-08-29.
assert_eq!(
process_rs_production_code()
.matches("assign_to_kill_on_close_job(&child)")
.count(),
2,
"both ComfyUI spawns must stay on the kill-on-close job"
);
}
#[test]
fn tying_a_child_leaves_it_running_and_a_zero_pid_is_ignored() {
// The call is a no-op off Windows and must never be a way to kill
// something by accident. A pid of 0 means "no process" on both
// families and must not be handed to the OS at all.
tie_child_to_app_lifetime(0);
#[cfg(not(target_os = "windows"))]
{
let mut child = std::process::Command::new("sleep")
.arg("5")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.expect("spawn a sleeper");
tie_child_to_app_lifetime(child.id());
std::thread::sleep(std::time::Duration::from_millis(200));
assert!(
child.try_wait().expect("try_wait").is_none(),
"tying a child must not disturb it"
);
let _ = child.kill();
let _ = child.wait();
}
}
#[test]
fn the_job_object_is_created_once_and_shared() {
// The old code made a fresh job per child and leaked the handle every
// time; the engine restarts on every model swap (30 restarts in eleven
// minutes were logged on 2026-08-29), so that leaked 30 handles.
assert_eq!(
process_rs_production_code().matches("CreateJobObjectW(").count(),
1,
"there must be exactly one place that creates the job object"
);
assert!(
PROCESS_RS.contains("static JOB: OnceLock<isize>"),
"the job handle must be created once and reused"
);
}
}
/// T-65 — the make-room-for-VRAM step must ask the address the user configured,
/// and must say which of "nothing to free" / "not mine to free" happened.
///
/// The two `_at` helpers are exercised against a REAL HTTP server on a real
/// loopback port (`127.0.0.1:0`, so never 8188 or 11434) — that is the whole
/// point: a test that only ever succeeds on the default port could not tell
/// the fix from the bug.
#[cfg(test)]
mod vram_release_tests {
use super::*;
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use std::sync::mpsc;
/// A one-shot HTTP server on an ephemeral port. Returns the base URL and a
/// receiver that yields the request line + body of the first request.
fn one_shot(status: &'static str, body: &'static str) -> (String, mpsc::Receiver<String>) {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let port = listener.local_addr().unwrap().port();
let (tx, rx) = mpsc::channel();
std::thread::spawn(move || {
// Serve until the client is done with us; /api/ps is followed by
// one /api/generate per loaded model.
for stream in listener.incoming().take(4) {
let Ok(mut stream) = stream else { break };
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut request_line = String::new();
let _ = reader.read_line(&mut request_line);
let mut len = 0usize;
loop {
let mut line = String::new();
if reader.read_line(&mut line).unwrap_or(0) == 0 {
break;
}
if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") {
len = v.trim().parse().unwrap_or(0);
}
if line.trim().is_empty() {
break;
}
}
let mut payload = vec![0u8; len];
if len > 0 {
use std::io::Read;
let _ = reader.read_exact(&mut payload);
}
let _ = tx.send(format!(
"{} | {}",
request_line.trim(),
String::from_utf8_lossy(&payload)
));
let _ = write!(
stream,
"HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
let _ = stream.flush();
}
});
(format!("http://127.0.0.1:{port}"), rx)
}
#[test]
fn comfyui_is_asked_on_the_configured_port_not_8188() {
let (base, rx) = one_shot("200 OK", "{}");
assert!(!base.ends_with(":8188"), "the ephemeral port must not be the default");
assert_eq!(free_comfyui_memory_at(&base), VramRelease::Released);
let seen = rx.recv_timeout(std::time::Duration::from_secs(5)).expect("no request arrived");
assert!(seen.starts_with("POST /free "), "{seen}");
assert!(seen.contains("\"unload_models\":true"), "{seen}");
}
#[test]
fn ollama_is_asked_on_the_configured_base_not_11434() {
let (base, rx) = one_shot("200 OK", r#"{"models":[{"name":"qwen3:8b"}]}"#);
assert!(!base.ends_with(":11434"), "the ephemeral port must not be the default");
assert_eq!(offload_ollama_loaded_models_at(&base), VramRelease::Released);
let ps = rx.recv_timeout(std::time::Duration::from_secs(5)).expect("no /api/ps");
assert!(ps.starts_with("GET /api/ps "), "{ps}");
let evict = rx.recv_timeout(std::time::Duration::from_secs(5)).expect("no eviction");
assert!(evict.starts_with("POST /api/generate "), "{evict}");
assert!(evict.contains("\"keep_alive\":0"), "{evict}");
assert!(evict.contains("qwen3:8b"), "{evict}");
}
/// The half of the finding the address fix alone does not close: a backend
/// that answered and held nothing must NOT read the same as a backend LU
/// could not ask.
#[test]
fn nothing_loaded_and_not_ours_are_different_answers() {
let (base, _rx) = one_shot("200 OK", r#"{"models":[]}"#);
assert_eq!(offload_ollama_loaded_models_at(&base), VramRelease::NothingLoaded);
let (dead_port, _held) = crate::test_support::refusing_port();
let dead = format!("http://127.0.0.1:{dead_port}");
let verdict = offload_ollama_loaded_models_at(&dead);
let (target, why) = verdict
.not_responsible()
.unwrap_or_else(|| panic!("a dead port read as {verdict:?}"));
assert_eq!(target, dead);
assert!(!why.is_empty());
assert!(!verdict.released());
// Both are "did not free anything", and that is exactly why `bool`
// was not enough.
assert!(!VramRelease::NothingLoaded.released());
assert_ne!(VramRelease::NothingLoaded, verdict);
}
#[test]
fn a_comfyui_that_answers_with_an_error_is_not_a_success() {
let (base, _rx) = one_shot("500 Internal Server Error", "boom");
let verdict = free_comfyui_memory_at(&base);
assert!(!verdict.released());
assert!(verdict.not_responsible().unwrap().1.contains("500"), "{verdict:?}");
}
#[test]
fn a_remote_backend_is_never_asked_and_says_so() {
// ComfyUI on the LAN: its VRAM is another machine's.
let (target, why) = comfy_vram_target_for("192.168.1.50", 8188).unwrap_err();
assert_eq!(target, "http://192.168.1.50:8188");
assert!(why.contains("another host"), "{why}");
let (target, why) = ollama_vram_target_for("http://192.168.1.54:11434").unwrap_err();
assert_eq!(target, "http://192.168.1.54:11434");
assert!(why.contains("another host"), "{why}");
}
#[test]
fn a_local_backend_on_a_custom_port_resolves_to_that_port() {
assert_eq!(comfy_vram_target_for("localhost", 9999).unwrap(), "http://localhost:9999");
assert_eq!(comfy_vram_target_for("127.0.0.1", 8189).unwrap(), "http://127.0.0.1:8189");
assert_eq!(
ollama_vram_target_for("http://127.0.0.1:12345").unwrap(),
"http://127.0.0.1:12345"
);
// state::load_ollama_base normalises away the trailing slash, but a
// hand-edited config.json can still carry one and `{base}/api/ps`
// would then be a double slash.
assert_eq!(
ollama_vram_target_for("http://localhost:11434/").unwrap(),
"http://localhost:11434"
);
}
#[test]
fn locality_is_decided_on_the_resolved_host_not_the_string() {
assert!(base_url_is_local("http://localhost:11434"));
assert!(base_url_is_local("http://127.0.0.1:11434"));
assert!(base_url_is_local("http://[::1]:11434"));
assert!(!base_url_is_local("http://192.168.1.54:11434"));
assert!(!base_url_is_local("http://ollama.example.com"));
// A host that merely CONTAINS a local name is not local.
assert!(!base_url_is_local("http://localhost.evil.example"));
assert!(!base_url_is_local("not a url"));
}
/// No hardcoded default address survives in the make-room path.
#[test]
fn the_vram_path_carries_no_hardcoded_backend_address() {
const SRC: &str = include_str!("process.rs");
let start = SRC
.find("pub(crate) fn offload_ollama_loaded_models_at")
.expect("offload helper is gone");
let end = SRC
.find(concat!("#[cfg(test)]\nmod vram_release", "_tests"))
.expect("test module marker is gone");
let body = &SRC[start..end];
for needle in ["localhost:8188", "localhost:11434", "127.0.0.1:8188", "127.0.0.1:11434"] {
assert!(
!body.contains(needle),
"'{needle}' is hardcoded again in the make-room-for-VRAM path"
);
}
}
}
/// T-68 — the orphan of a hard-killed session, and the line between it and a
/// ComfyUI the user runs themselves.
///
/// VERIFICATION LIMIT, stated here and not only in a report: the failure this
/// closes needs a SIGKILLed LU on Linux with a live ComfyUI child. That cannot
/// be produced on the Mac this branch is developed on — macOS never
/// auto-starts ComfyUI (local media is MLX-only) and there is no ComfyUI
/// install here at all. What IS tested is every part that does not need one:
/// the classifier that decides whether LU may kill a process it did not spawn,
/// and the process-table scan against a REAL process this test starts and then
/// finds by its command line. The kill escalation itself and the end-to-end
/// hard-kill sequence are unproven here.
#[cfg(test)]
mod comfy_adoption_tests {
use super::*;
fn argv(line: &str) -> Vec<String> {
line.split(' ').map(str::to_string).collect()
}
/// Exactly what `start_comfyui_blocking` spawns, in argv order.
fn lu_argv(port: u16) -> Vec<String> {
argv(&format!(
"/usr/bin/python3 main.py --listen 127.0.0.1 --port {port} --enable-cors-header *"
))
}
/// Found in the security pass of 2026-10-13: the flag carried `*`, and
/// with it any web page could read the local ComfyUI. The start names the
/// app's own origin, and no build names every origin.
#[test]
fn a_comfyui_started_here_answers_to_the_app_and_to_no_other_page() {
assert_eq!(app_page_origin(false, true), "http://tauri.localhost");
assert_eq!(app_page_origin(false, false), "tauri://localhost");
let conf: serde_json::Value =
serde_json::from_str(include_str!("../../tauri.conf.json")).unwrap();
assert_eq!(app_page_origin(true, true), conf["build"]["devUrl"].as_str().unwrap());
assert_eq!(app_page_origin(true, false), conf["build"]["devUrl"].as_str().unwrap());
assert_ne!(comfy_cors_origin(), "*");
let source = include_str!("process.rs");
let wildcard = ["\"--enable-cors-header\", ", "\"*\""].concat();
assert!(!source.contains(&wildcard), "a ComfyUI start passes the wildcard origin again");
assert!(is_lu_started_comfyui(
&argv(&format!("python main.py --listen 127.0.0.1 --port 8188 --enable-cors-header {}", comfy_cors_origin())),
8188
));
}
#[test]
fn the_argv_this_app_actually_spawns_is_recognised() {
assert!(is_lu_started_comfyui(&lu_argv(8188), 8188));
assert!(is_lu_started_comfyui(&lu_argv(9001), 9001));
// …and the CPU-fallback / flash-attention variants of the same start.
assert!(is_lu_started_comfyui(
&argv("python main.py --listen 127.0.0.1 --port 8188 --enable-cors-header * --cpu"),
8188
));
assert!(is_lu_started_comfyui(
&argv("python main.py --listen 127.0.0.1 --port 8188 --enable-cors-header * --use-flash-attention"),
8188
));
}
/// The whole reason the classifier is narrow: this decides whether LU
/// kills a process it did not spawn.
#[test]
fn a_comfyui_the_user_started_is_never_adopted() {
// No --enable-cors-header: this is the shape the "Fix CORS" button in
// Settings exists for, i.e. a hand-started ComfyUI.
assert!(!is_lu_started_comfyui(
&argv("python main.py --listen 0.0.0.0 --port 8188"),
8188
));
// ComfyUI Desktop / a launcher script — not main.py.
assert!(!is_lu_started_comfyui(
&argv("/Applications/ComfyUI.app/Contents/MacOS/ComfyUI --port 8188"),
8188
));
// Not a ComfyUI at all.
assert!(!is_lu_started_comfyui(&argv("node server.js --port 8188"), 8188));
assert!(!is_lu_started_comfyui(&[], 8188));
}
/// A second ComfyUI, on a port that merely starts with our digits, is a
/// stranger. `contains("--port 8188")` would have killed it.
#[test]
fn a_neighbouring_port_is_not_our_port() {
// 61880 starts with the digits of 6188 — a substring test would
// have called this ours and killed it.
let neighbour = argv("python main.py --port 61880 --enable-cors-header *");
assert!(!is_lu_started_comfyui(&neighbour, 6188));
assert!(is_lu_started_comfyui(&neighbour, 61880));
let shorter = argv("python main.py --port 618 --enable-cors-header *");
assert!(!is_lu_started_comfyui(&shorter, 6188));
// Both spellings of the flag resolve to the same port.
assert!(is_lu_started_comfyui(
&argv("python main.py --port=8188 --enable-cors-header *"),
8188
));
assert!(!is_lu_started_comfyui(
&argv("python main.py --port=61880 --enable-cors-header *"),
6188
));
}
/// A live process carrying exactly the argv `start_comfyui_blocking` spawns.
///
/// `examples/park`, run directly. It ignores its arguments and blocks on
/// stdin, so it carries the argv this test chose, lives exactly as long as
/// the test holds the pipe, and forks nothing that could be orphaned.
///
/// What it replaced was `/bin/sh -c "sleep 30; :" main.py …`, and both
/// halves of that were a liability:
///
/// * `sleep 30` is a wall-clock budget on a test, and it forks a
/// grandchild that `child.kill()` does not reach.
/// * `sh` is a SIP platform binary. This one was invoked rather than
/// copied, so it escaped the SIGKILL that `examples/park.rs` documents —
/// but the next person to reach for "make a copy and rename it" would
/// not, and the stand-in that does not have the problem is right here.
#[cfg(unix)]
fn live_comfy_stand_in(port: u16) -> std::process::Child {
std::process::Command::new(crate::test_support::park_binary())
.args([
"main.py",
"--listen",
"127.0.0.1",
"--port",
&port.to_string(),
"--enable-cors-header",
"*",
])
// Piped, not null: closing this pipe is how the stand-in is ended.
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.expect("spawn the stand-in")
}
/// The scan runs against the real process table. A process whose argv
/// matches must be found by pid; the same process on another port must
/// not.
///
/// Unix only: the finding is a Linux/macOS one — Windows children join the
/// kill-on-close job object and do not orphan in the first place. (The old
/// reason, "`sh -c` is the portable way to get a stand-in", is gone with the
/// stand-in; what keeps the gate is that `park_binary()` would need the
/// `.exe` suffix there and no Windows machine was available to check it.)
///
/// ── Why this test looked like it worked and did not ──
///
/// It used to sleep a fixed 300 ms, take exactly one snapshot, and assert on
/// it, with a hard-coded port 61888. Measured on 01.09.2026 over a delay
/// series under three concurrent copies of the whole suite — the shape the
/// flake was reported in — it failed 0/25 at 0 ms, 1/25 at 300 ms, 2/25 at
/// 600 ms and 6/25 at 1000 ms, and every single one of those nine failures
/// was the same thing: `find_orphaned_comfyui` returned a pid HIGHER than
/// this test's own child. A stranger's. A second suite running this very
/// test had its own stand-in on 61888, and the scan returned whichever of
/// the two the table iteration reached first.
///
/// That the failure rate RISES with the sleep is the proof of which
/// mechanism it was: a longer sleep is a longer window in which a concurrent
/// copy's stand-in is alive at the same time as this one's. A settle-time
/// problem would have behaved the other way round.
///
/// So the port is no longer written down. It is leased from the kernel, and
/// the lease is held for the whole test, which is what makes it impossible
/// for a concurrent copy to draw the same number.
///
/// Turned up to the maximum — 30 copies of this one test started at the same
/// instant, three rounds — the old body failed 87 of 90 and this one 0 of 90
/// (0 of 150 at 50 copies). And with everything else here left alone and
/// only `reserved_port()` swapped back for the constant 61888, this body
/// fails 79 of 90 again. The lease is the fix; the stand-in and the checked
/// snapshot are what stop the OTHER two ways it could rot.
#[cfg(unix)]
#[test]
fn the_scan_finds_a_real_process_by_the_argv_lu_would_have_used() {
use crate::test_support::{checked_table, reserved_port};
// Held to the end of the test: while these sockets are bound, no other
// process on this machine is handed either number.
let (ours, _ours_lease) = reserved_port();
let (stranger, _stranger_lease) = reserved_port();
let mut child = live_comfy_stand_in(ours);
let pid = child.id();
// One snapshot that has shown it contains this process AND the stand-in.
// Everything asserted below is a pure function of it — no clock, no
// second enumeration, nothing that can change under the assertions.
let table = checked_table(pid);
let _ = child.kill();
let _ = child.wait();
let sys = table.unwrap_or_else(|why| panic!("{why}"));
let entry = sys
.process(sysinfo::Pid::from_u32(pid))
.expect("checked_table only returns a table containing this pid");
// If this fails the rest means nothing: the stand-in would not be
// carrying the argv the scan matches on.
let argv = crate::process_util::cmdline_of(entry);
assert!(
argv.iter().any(|a| a == "main.py"),
"the stand-in is not carrying LU's argv at all: {argv:?}",
);
assert_eq!(
find_orphaned_comfyui_in(&sys, ours),
Some(pid),
"the scan did not find the stand-in. argv={argv:?}",
);
assert_ne!(
find_orphaned_comfyui_in(&sys, stranger),
Some(pid),
"the scan matched this process while looking for another port ({stranger})",
);
}
/// 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",
);
// GH #183: die Schalter aus dem Startskript des Nutzers.
assert!(
body.contains("UserComfyPaths::discover(") && body.contains(".launch_args()"),
"{name} reicht die Ordner aus dem Startskript nicht weiter",
);
}
// 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() {
const SRC: &str = include_str!("process.rs");
let start = SRC
.find("fn stop_comfyui_blocking")
.expect("stop_comfyui_blocking is gone");
let body = &SRC[start..];
let end = start + body.find("\n}\n").expect("unterminated fn");
let body = &SRC[start..end];
assert!(
body.contains("find_orphaned_comfyui("),
"stop_comfyui_blocking no longer looks for the orphan"
);
assert!(
body.contains("kill_pid_tree("),
"stop_comfyui_blocking finds the orphan and does not stop it"
);
}
// ── 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\\alice\\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",
);
// 3.0.7: beide Wege entscheiden ueber `launch_python`, und dort
// steht das kaputte venv als eigene Antwort (unten geprueft).
assert!(
body.contains("launch_python("),
"{name} entscheidet am gemeinsamen Weg vorbei",
);
for kette in ["unwrap_or(system_python", "unwrap_or_else(|| system_python", "=> system_python.clone()"] {
assert!(
!body.contains(kette),
"{name} faellt wieder still auf das System-Python zurueck: {kette}",
);
}
}
let start = src.find("pub(crate) fn launch_python(").expect("launch_python ist weg");
let end = start + src[start..].find("\n}\n").expect("unterminated fn");
assert!(
src[start..end].contains("comfy_broken_venv_message("),
"launch_python erkennt das kaputte venv und sagt es niemandem",
);
}
// ── Discord 14.10.2026: welches Python ein ComfyUI startet ─────────────
fn usable(p: &str) -> crate::python::ComfyVenv {
crate::python::ComfyVenv::Usable(p.to_string())
}
#[test]
fn a_venv_starts_from_the_venv_and_nobody_scans_the_machine() {
let dir = Path::new("/c/ComfyUI");
let got = launch_python(None, &usable("/c/ComfyUI/venv/bin/python"), dir, || panic!("bound without need"));
assert_eq!(got.as_deref(), Ok("/c/ComfyUI/venv/bin/python"));
// Portable still wins over a leftover venv.
let got = launch_python(Some("/c/python_embeded/python.exe"), &usable("/v"), dir, || panic!("bound without need"));
assert_eq!(got.as_deref(), Ok("/c/python_embeded/python.exe"));
}
#[test]
fn a_broken_venv_still_stops_the_start() {
let venv = crate::python::ComfyVenv::Broken {
venv_dir: PathBuf::from("/c/ComfyUI/venv"),
interpreter: PathBuf::from("/c/ComfyUI/venv/bin/python"),
};
let err = launch_python(None, &venv, Path::new("/c/ComfyUI"), || panic!("bound past a broken venv")).unwrap_err();
assert!(err.contains("/c/ComfyUI/venv/bin/python"), "{err}");
}
#[test]
fn without_a_venv_the_python_that_holds_torch_starts_comfyui() {
let got = launch_python(None, &crate::python::ComfyVenv::Absent, Path::new("/c"), || Some("/py312".to_string()));
assert_eq!(got.as_deref(), Ok("/py312"));
let err = launch_python(None, &crate::python::ComfyVenv::Absent, Path::new("/c/ComfyUI"), || None).unwrap_err();
assert!(err.contains("Repair environment"), "{err}");
assert!(err.contains("LU's own Python 3.12"), "{err}");
assert!(!err.to_lowercase().contains("reinstall"), "{err}");
}
/// The Discord case itself: no venv, torch in 3.12, LU's default is now
/// 3.15. The 3.12 is found, and only after the default had no torch.
#[test]
fn default_3_15_without_torch_binds_the_3_12_that_has_it() {
let asked_for_others = std::cell::Cell::new(false);
let got = pick_torch_python(
None,
"C:\\Python315\\python.exe",
|| {
asked_for_others.set(true);
vec!["C:\\Python315\\python.exe".to_string(), "C:\\Python312\\python.exe".to_string()]
},
|p| p.contains("Python312"),
|_| panic!("the import probe runs only when no prefix has torch"),
);
assert_eq!(got.as_deref(), Some("C:\\Python312\\python.exe"));
assert!(asked_for_others.get());
}
#[test]
fn the_remembered_python_wins_and_the_machine_is_not_scanned() {
let got = pick_torch_python(
Some("/py312"),
"/py315",
|| panic!("scanned although the remembered one has torch"),
|p| p == "/py312" || p == "/py315",
|_| false,
);
assert_eq!(got.as_deref(), Some("/py312"), "a default that also has torch does not move the binding");
// A remembered Python that lost its torch is passed over.
let got = pick_torch_python(Some("/gone"), "/py315", Vec::new, |p| p == "/py315", |_| false);
assert_eq!(got.as_deref(), Some("/py315"));
}
#[test]
fn torch_in_a_user_site_is_found_by_the_second_round() {
let got = pick_torch_python(None, "/py315", || vec!["/py311".to_string()], |_| false, |p| p == "/py311");
assert_eq!(got.as_deref(), Some("/py311"));
let none = pick_torch_python(None, "/py315", || vec!["/py311".to_string()], |_| false, |_| false);
assert_eq!(none, None);
// Empty entries and duplicates are never asked.
let asked = std::cell::RefCell::new(Vec::new());
let _ = pick_torch_python(Some(""), "/a", || vec!["/a".to_string(), " ".to_string()], |_| false, |p| {
asked.borrow_mut().push(p.to_string());
false
});
assert_eq!(*asked.borrow(), vec!["/a".to_string()]);
}
#[test]
fn the_binding_is_remembered_per_folder_next_to_the_other_settings() {
let tmp = tempfile::tempdir().unwrap();
let config = tmp.path().join("cfg").join("config.json");
std::fs::create_dir_all(config.parent().unwrap()).unwrap();
std::fs::write(&config, r#"{"comfyui_path": "/c/ComfyUI", "comfyui_port": 8188}"#).unwrap();
let comfy = Path::new("/c/ComfyUI");
assert_eq!(remembered_bound_python_in(&config, comfy), None);
remember_bound_python_in(&config, comfy, "/py312");
assert_eq!(remembered_bound_python_in(&config, comfy).as_deref(), Some("/py312"));
// Another ComfyUI does not inherit it.
assert_eq!(remembered_bound_python_in(&config, Path::new("/d/ComfyUI")), None);
// The other keys survive the write.
let json: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&config).unwrap()).unwrap();
assert_eq!(json["comfyui_port"], 8188);
assert_eq!(json["comfyui_path"], "/c/ComfyUI");
}
// ── box-gruen/n9 Punkt 87, final review (B2/K3): one pure decision for
// "is this ComfyUI ours", shared by the status panel and Update's
// running-instance guard ──────────────────────────────────────────
#[test]
fn nothing_on_the_port_is_never_running() {
assert_eq!(classify_comfyui_ownership(false, false, None), ComfyOwnership::NotRunning);
// A stale handle or a stale orphan pid must not override an empty
// port: if nothing answers, there is nothing to own or refuse.
assert_eq!(classify_comfyui_ownership(false, true, Some(123)), ComfyOwnership::NotRunning);
}
#[test]
fn a_live_handle_from_this_run_is_always_ours() {
assert_eq!(classify_comfyui_ownership(true, true, None), ComfyOwnership::Own);
}
#[test]
fn an_orphan_from_an_earlier_run_is_ours_too() {
// box-gruen/n9 punkt 87 B2: this is exactly what a live ComfyUI looks
// like after an LU restart, own_child_alive is false, but the orphan
// scan still finds it.
assert_eq!(classify_comfyui_ownership(true, false, Some(4242)), ComfyOwnership::Own);
}
#[test]
fn a_port_answering_with_neither_is_foreign() {
// The n9 shape itself: `python.exe main.py --port 8188` with no
// `--enable-cors-header`, so neither the handle nor the orphan scan
// claims it.
assert_eq!(classify_comfyui_ownership(true, false, None), ComfyOwnership::Foreign);
}
}
/// A child that outlives its launcher — the `npx -y <package>` MCP server, and
/// anything else the shell plugin starts through a shim.
///
/// VERIFICATION LIMIT: the Unix half is proved here against real processes.
/// The Windows half (`taskkill /T /F`) and the `npx.cmd` → cmd.exe → node
/// chain it has to walk are NOT exercised on this machine.
#[cfg(test)]
mod process_tree_kill_tests {
use super::*;
#[test]
fn only_this_apps_own_processes_may_be_killed() {
let own = std::process::id();
let mine = vec![4242u32, 4243];
assert!(may_kill_pid(4242, own, &mine).is_ok());
// init / the session leader / the user's editor: not ours.
for stranger in [1u32, 999_999, own] {
let err = may_kill_pid(stranger, own, &mine)
.expect_err("a pid outside our subtree was accepted");
assert!(err.starts_with("refused:"), "{err}");
}
assert!(may_kill_pid(0, own, &mine).is_err());
// The ordering trap gets named in the message, because the misuse
// (kill the child first, then ask for its tree) looks like a bug in
// this command rather than in the call order.
let err = may_kill_pid(4244, own, &mine).unwrap_err();
assert!(err.contains("INSTEAD of the child"), "{err}");
}
/// The whole point: the grandchild dies too. `child.kill()` from the shell
/// plugin would have left it running.
#[cfg(unix)]
#[test]
fn killing_the_launcher_takes_the_grandchild_with_it() {
use sysinfo::{Pid, ProcessesToUpdate, System};
// A launcher that spawns a long-lived grandchild and then waits —
// the shape `npx -y <pkg>` has (shim in front, real server behind).
let mut launcher = std::process::Command::new("/bin/sh")
.args(["-c", "sleep 60 & wait"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.expect("spawn the launcher");
let launcher_pid = launcher.id();
let grandchild = {
let mut found = None;
for _ in 0..40 {
std::thread::sleep(std::time::Duration::from_millis(50));
let mut sys = System::new();
sys.refresh_processes(ProcessesToUpdate::All, true);
let kids = crate::commands::shell::descendants(launcher_pid, &sys);
if let Some(pid) = kids.first() {
found = Some(*pid);
break;
}
}
found.expect("the launcher never spawned its grandchild")
};
assert_ne!(grandchild, launcher_pid);
let out = kill_process_tree_blocking(launcher_pid).expect("the tree kill was refused");
assert_eq!(out["killed"], serde_json::json!(true));
assert!(out["processes"].as_u64().unwrap() >= 2, "{out}");
// SIGTERM goes out immediately; give the escalation room anyway.
let mut still_there = true;
for _ in 0..40 {
std::thread::sleep(std::time::Duration::from_millis(50));
let mut sys = System::new();
sys.refresh_processes(ProcessesToUpdate::All, true);
if sys.process(Pid::from_u32(grandchild)).is_none() {
still_there = false;
break;
}
}
let _ = launcher.kill();
let _ = launcher.wait();
assert!(
!still_there,
"the grandchild (pid {grandchild}) outlived the kill — this is exactly the \
npx orphan the plugin's own kill leaves behind"
);
}
/// One kill path, not two: the command must go through the same helper the
/// ComfyUI adoption uses.
#[test]
fn there_is_one_tree_kill_path() {
const SRC: &str = include_str!("process.rs");
let start = SRC.find("pub(crate) fn kill_process_tree_blocking").expect("gone");
let body = &SRC[start..start + 1400];
assert!(
body.contains("process_util::kill_pid_tree("),
"kill_process_tree grew its own kill instead of using the shared one"
);
}
}
#[cfg(test)]
mod boot_start_gpu_tests {
/// 3.1.0: the boot starts of ComfyUI and Ollama applied no card at all
/// since 3.0.8, so "Card per task" never reached a ComfyUI or Ollama LU
/// started together with itself. Every start, manual and boot, now goes
/// through the one helper with its service's role. Read as source, like
/// the extra-model-paths guard above, because the property is "what does
/// each spawn site call"; the helper itself is tested in gpu_roles.rs.
#[test]
fn every_comfyui_and_ollama_start_applies_its_card() {
let src = std::fs::read_to_string(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/commands/process.rs")).unwrap();
let src = &src[..src.find("#[cfg(test)]").unwrap()];
for (name, role) in [
("fn start_comfyui_blocking", "GpuRole::Comfy"),
("pub fn auto_start_comfyui", "GpuRole::Comfy"),
("fn start_ollama_blocking", "GpuRole::Chat"),
("pub fn auto_start_ollama", "GpuRole::Chat"),
] {
let start = src.find(name).unwrap_or_else(|| panic!("{name} is gone"));
let body = &src[start..start + src[start..].find("\n}\n").expect("unterminated fn")];
let call = body.find("gpu_roles::apply_role_env(state,").unwrap_or_else(|| panic!("{name} applies no card"));
assert!(body[call..].starts_with(&format!("gpu_roles::apply_role_env(state, crate::commands::gpu_roles::{role}")), "{name} applies the wrong role");
let spawn = body.rfind(".spawn()").unwrap_or_else(|| panic!("{name} spawns nothing"));
assert!(call < spawn, "{name} applies the card after the spawn");
}
}
#[test]
fn the_cors_fix_ends_only_a_comfyui_and_never_from_a_test() {
use super::comfy_port_may_be_freed;
assert!(comfy_port_may_be_freed(true, false), "the ComfyUI behind the banner");
assert!(!comfy_port_may_be_freed(false, false), "a stranger on the port");
assert!(!comfy_port_may_be_freed(true, true), "a test build ends nothing");
}
}