Skip to content

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

fix(comfyui): close five review blockers on Update ComfyUI (ENG-18)

purple13954ea6caa5
diff --git a/dev-server/comfy.ts b/dev-server/comfy.ts
index 02d5be0d..ff6995a8 100644
--- a/dev-server/comfy.ts
+++ b/dev-server/comfy.ts
@@ -527,6 +527,13 @@ export function registerComfyInstallRoutes(routes: RouteMount, comfy: ComfyLaunc
path: comfyPath,
logs: comfy.recentLogs(),
processAlive,
+ // The dev server has no cross-session orphan case (Rust's
+ // `find_orphaned_comfyui`, box-gruen/n9 punkt 87 final review B2): a
+ // Node process here either holds the child handle or it does not, so
+ // this is always the same value as `processAlive`. Sent anyway so the
+ // panel's ownership label and Update's confirm-dialog guard behave the
+ // same in browser dev mode as in the real app.
+ ownedByApp: processAlive,
}))
})
}
diff --git a/src-tauri/src/commands/install/comfy_repair.rs b/src-tauri/src/commands/install/comfy_repair.rs
index c4978714..d9b679a9 100644
--- a/src-tauri/src/commands/install/comfy_repair.rs
+++ b/src-tauri/src/commands/install/comfy_repair.rs
@@ -654,18 +654,61 @@ fn foreign_comfyui_blocks_update(port: u16) -> String {
)
}
+/// What the customer is told when Update refuses to interrupt a render.
+/// box-gruen/n9 punkt 87, final review (B3): an own or adoptable ComfyUI used
+/// to be killed on the spot, mid-render or not, and the work was gone with
+/// nothing on screen to say so.
+const COMFYUI_BUSY_REFUSAL: &str =
+ "ComfyUI is generating something right now. Wait for it to finish, or stop the render \
+ yourself, then run Update ComfyUI again. Nothing was changed.";
+
+/// Whether ComfyUI's own `/queue` response (`{"queue_running": [...],
+/// "queue_pending": [...]}`, the same shape `isPromptQueued` in
+/// `comfyui.ts` reads) names any work at all. Pure and separate from the
+/// HTTP call below so both directions are provable with a literal
+/// `serde_json::Value`, no server required.
+fn queue_has_work(body: &serde_json::Value) -> bool {
+ let non_empty = |key: &str| {
+ body.get(key)
+ .and_then(serde_json::Value::as_array)
+ .is_some_and(|a| !a.is_empty())
+ };
+ non_empty("queue_running") || non_empty("queue_pending")
+}
+
+/// Is ComfyUI on `port` doing anything right now? Read straight from its own
+/// `/queue` endpoint, because Update is about to stop this process and a
+/// customer mid-render has no other warning that the run is about to die.
+///
+/// Errs on the side of caution: a `/queue` that cannot be reached or parsed
+/// answers `Err`, and the caller refuses the update rather than risk killing
+/// a render it could not see.
+fn comfyui_queue_busy(port: u16) -> Result<bool, String> {
+ let resp = reqwest::blocking::get(format!("http://localhost:{port}/queue"))
+ .map_err(|e| format!("could not reach ComfyUI's queue: {e}"))?;
+ if !resp.status().is_success() {
+ return Err(format!("ComfyUI's queue endpoint answered with {}", resp.status()));
+ }
+ let body: serde_json::Value = resp
+ .json()
+ .map_err(|e| format!("could not read ComfyUI's queue: {e}"))?;
+ Ok(queue_has_work(&body))
+}
+
/// Stop whatever ComfyUI this app itself is responsible for before Update
/// touches the checkout, and refuse outright if the port is held by anything
-/// else.
+/// else or by a render in progress.
///
-/// Three shapes, the same ones Stop (`stop_comfyui_blocking`) already tells
-/// apart:
-/// * a live tracked child from this run, killed and reaped, same as Stop;
-/// * an orphan on the configured port this app started in an earlier run and
-/// lost the handle to (`find_orphaned_comfyui`), adopted and killed, same
-/// as Stop;
-/// * anything else answering on the port, left running, with the update
-/// refused instead.
+/// The own-vs-foreign line is `classify_comfyui_ownership`, the exact
+/// question `comfyui_status`'s `ownedByApp` field answers for the panel, so
+/// the two cannot disagree about the same ComfyUI (box-gruen/n9 punkt 87,
+/// final review B2). The actual stop, once the ComfyUI is confirmed to be
+/// ours, is `stop_comfyui_blocking` itself, the same function the Stop
+/// button calls (final review B1): a bare `child.kill()` only signals the
+/// direct child, and on Windows that can leave the real ComfyUI process
+/// (a grandchild through a launcher) holding the port while the checkout
+/// underneath it is rewritten. After the stop, the port is probed again: a
+/// ComfyUI that refuses to die is not silently worked around.
///
/// Remote hosts are not this function's concern: `comfyui_status` never
/// offers the Update button once `isLocal` is false, and this app manages no
@@ -676,10 +719,13 @@ fn ensure_comfyui_stopped_for_update(state: &State<'_, AppState>) -> Result<(),
return Ok(());
}
let port = *state.comfy_port.lock().unwrap();
+ if !crate::commands::process::is_comfyui_running_on_port(port) {
+ return Ok(());
+ }
- // Our own tracked child, if this run's Start ever produced one and it is
- // still alive. `try_wait` also reaps a child that already exited on its
- // own, so this never lingers on a stale handle.
+ // Peeked, never taken: the actual stop happens inside
+ // `stop_comfyui_blocking` below, in its own single lock. Reading the
+ // handle here decides only whether this ComfyUI is ours to stop at all.
let own_child_alive = {
let mut proc = state.comfy_process.lock().unwrap();
match proc.as_mut() {
@@ -694,33 +740,53 @@ fn ensure_comfyui_stopped_for_update(state: &State<'_, AppState>) -> Result<(),
None => false,
}
};
- if own_child_alive {
- let mut proc = state.comfy_process.lock().unwrap();
- if let Some(mut child) = proc.take() {
- let _ = child.kill();
- let _ = child.wait();
- }
- drop(proc);
- *state.comfy_start_at.lock().unwrap() = None;
- info!(port = port, "update_comfyui stopped its own tracked ComfyUI before updating");
- return Ok(());
- }
+ let orphan_pid = if own_child_alive {
+ None
+ } else {
+ crate::commands::process::find_orphaned_comfyui(port)
+ };
- if !crate::commands::process::is_comfyui_running_on_port(port) {
- return Ok(());
- }
- match crate::commands::process::find_orphaned_comfyui(port) {
- Some(pid) => {
- println!("[Update] Adopting orphan pid {pid} on port {port} and stopping it before updating");
- info!(pid = pid, port = port, "update_comfyui adopted and stopped an orphaned ComfyUI");
- crate::process_util::kill_pid_tree(pid);
- *state.comfy_start_at.lock().unwrap() = None;
- Ok(())
- }
- None => {
+ match crate::commands::process::classify_comfyui_ownership(true, own_child_alive, orphan_pid) {
+ crate::commands::process::ComfyOwnership::NotRunning => Ok(()),
+ crate::commands::process::ComfyOwnership::Foreign => {
println!("[Update] Refusing: port {port} is served by a ComfyUI this app did not start");
Err(foreign_comfyui_blocks_update(port))
}
+ crate::commands::process::ComfyOwnership::Own => {
+ match comfyui_queue_busy(port) {
+ Ok(true) => {
+ println!("[Update] Refusing: ComfyUI on port {port} is generating something");
+ Err(COMFYUI_BUSY_REFUSAL.to_string())
+ }
+ Err(e) => {
+ println!("[Update] Refusing: could not check ComfyUI's queue on port {port}: {e}");
+ Err(format!(
+ "Could not check whether ComfyUI is generating something right now, so the \
+ update was refused rather than risk interrupting a render ({e}). Nothing \
+ was changed."
+ ))
+ }
+ Ok(false) => {
+ let result = crate::commands::process::stop_comfyui_blocking(state)?;
+ let status = result.get("status").and_then(|s| s.as_str()).unwrap_or("");
+ if status == "not_ours" {
+ // A race between the classify above and the stop: the
+ // handle exited and something else grabbed the port
+ // in between. Rare, and refused exactly like a plain
+ // foreign ComfyUI would be.
+ return Err(foreign_comfyui_blocks_update(port));
+ }
+ info!(port = port, status = status, "update_comfyui stopped its own ComfyUI before updating");
+ if crate::commands::process::is_comfyui_running_on_port(port) {
+ return Err(format!(
+ "ComfyUI on port {port} did not stop, so the update was not started. Try \
+ Stop in Settings, then run Update ComfyUI again. Nothing was changed."
+ ));
+ }
+ Ok(())
+ }
+ }
+ }
}
}
@@ -892,8 +958,8 @@ pub fn update_comfyui(state: State<'_, AppState>) -> Result<serde_json::Value, S
// dirty checkout would erase whatever the customer changed by hand,
// and that is worse than refusing the update outright and saying
// why, so a dirty tree never gets this far.
- let old_commit = match git_working_tree_clean(&comfy_dir) {
- Ok(true) => match git_current_commit(&comfy_dir) {
+ let old_commit = match git_dirty_lines(&comfy_dir) {
+ Ok(dirty) if dirty.is_empty() => match git_current_commit(&comfy_dir) {
Ok(commit) => commit,
Err(e) => {
update(
@@ -907,12 +973,21 @@ pub fn update_comfyui(state: State<'_, AppState>) -> Result<serde_json::Value, S
return;
}
},
- Ok(false) => {
+ Ok(dirty) => {
+ // box-gruen/n9 punkt 87, final review (B5): `dirty` already
+ // excludes LU's own venv rebuild siblings
+ // (`venv.lu-old-*`/`venv.lu-new-*`/`venv.lu-failed-*`), so
+ // whatever is left here is genuinely the customer's, and the
+ // message names it instead of a blanket "you changed
+ // something".
update(
"error",
- "The ComfyUI folder has local changes, so a failed or cancelled update could \
- not be rolled back safely without erasing them. Commit or discard those \
- changes, then retry. Nothing was changed.",
+ &format!(
+ "The ComfyUI folder has local changes, so a failed or cancelled update could \
+ not be rolled back safely without erasing them. Commit or discard these, \
+ then retry. Nothing was changed.\n\n{}",
+ dirty.join("\n"),
+ ),
);
return;
}
@@ -1048,14 +1123,38 @@ pub fn update_comfyui(state: State<'_, AppState>) -> Result<serde_json::Value, S
Ok(serde_json::json!({"status": "installing"}))
}
-/// Whether `dir`'s working tree has nothing to lose: no staged or unstaged
-/// changes and no untracked files, i.e. `git status --porcelain` prints
-/// nothing. `update_comfyui` records a rollback point (`git_current_commit`)
-/// and pulls only when this is true: a `git reset --hard` after a cancelled
-/// or failed dependency install would otherwise erase whatever the customer
-/// changed by hand inside the checkout, which is worse than refusing the
-/// update outright.
-fn git_working_tree_clean(dir: &Path) -> Result<bool, String> {
+/// LU's own throwaway siblings inside a ComfyUI checkout, none of them named
+/// in ComfyUI's own `.gitignore`.
+///
+/// box-gruen/n9 punkt 87, final review (B5): `retire_venv` (`venv.rs`) parks
+/// the previous venv at `venv.lu-old-<stamp>` right next to the checkout
+/// while the new one is built, and a rebuild that fails leaves a half-built
+/// one at `venv.lu-failed-<stamp>` until a background thread deletes it
+/// (`restore_after_failed_rebuild`); `venv.lu-new-*` is the same idea during
+/// a build that has not yet been renamed to plain `venv`. A crash or a
+/// cancelled Repair can leave one of these sitting in the checkout, and
+/// without this list `git status --porcelain` sees it as a local change:
+/// Update would then refuse every single time afterwards and blame the
+/// customer for LU's own leftovers, on exactly the boxes where something
+/// already went wrong once.
+const LU_VENV_SCRATCH_PREFIXES: [&str; 3] = ["venv.lu-old-", "venv.lu-new-", "venv.lu-failed-"];
+
+/// Does this one `git status --porcelain` line belong to one of LU's own
+/// venv rebuild siblings? Porcelain lines are two status characters, a
+/// space, then the path (`"?? venv.lu-old-171.../"` for an untracked
+/// directory), so the path starts at byte 3; that slice is always a valid
+/// UTF-8 boundary because the status characters and the separator are ASCII.
+fn is_lu_venv_scratch_status_line(line: &str) -> bool {
+ let path = line.get(3..).unwrap_or("").trim_start();
+ LU_VENV_SCRATCH_PREFIXES.iter().any(|prefix| path.starts_with(prefix))
+}
+
+/// The `git status --porcelain` lines that count as "dirty" for Update's
+/// rollback safety check: every real line except LU's own venv rebuild
+/// siblings (`LU_VENV_SCRATCH_PREFIXES`), which Update and Repair produce
+/// themselves and must never blame on the customer. Empty means the tree is
+/// safe to pull and, if needed later, safe to `git reset --hard` back out of.
+fn git_dirty_lines(dir: &Path) -> Result<Vec<String>, String> {
let mut cmd = crate::process_util::foreign_system_command("git");
cmd.args(["status", "--porcelain"])
.current_dir(dir)
@@ -1067,7 +1166,12 @@ fn git_working_tree_clean(dir: &Path) -> Result<bool, String> {
if !out.status.success() {
return Err(String::from_utf8_lossy(&out.stderr).trim().to_string());
}
- Ok(out.stdout.iter().all(u8::is_ascii_whitespace))
+ let text = String::from_utf8_lossy(&out.stdout);
+ Ok(text
+ .lines()
+ .filter(|line| !line.trim().is_empty() && !is_lu_venv_scratch_status_line(line))
+ .map(str::to_string)
+ .collect())
}
/// The commit `dir` is on right now, as `git rev-parse HEAD` reports it.
@@ -1093,10 +1197,10 @@ fn git_current_commit(dir: &Path) -> Result<String, String> {
/// Move `dir` back to `commit` with `git reset --hard`.
///
/// Only ever called from `update_comfyui`, and only on a checkout
-/// `git_working_tree_clean` found clean right before the pull that moved it
-/// away from `commit`: a hard reset otherwise destroys uncommitted work,
-/// which is exactly what recording the commit only on a clean tree exists to
-/// prevent.
+/// `git_dirty_lines` found empty (LU's own venv scratch siblings aside)
+/// right before the pull that moved it away from `commit`: a hard reset
+/// otherwise destroys uncommitted work, which is exactly what recording the
+/// commit only on a clean tree exists to prevent.
fn git_reset_hard(dir: &Path, commit: &str) -> Result<(), String> {
let mut cmd = crate::process_util::foreign_system_command("git");
cmd.args(["reset", "--hard", commit])
@@ -1470,18 +1574,45 @@ mod tests {
}
#[test]
- fn git_working_tree_clean_tells_a_clean_checkout_from_a_dirty_one() {
+ fn git_dirty_lines_tells_a_clean_checkout_from_a_dirty_one() {
let (_tmp, dir, _a, _b) = two_commit_repo();
- assert!(git_working_tree_clean(&dir).expect("status failed"), "a freshly committed checkout is not clean");
+ assert!(git_dirty_lines(&dir).expect("status failed").is_empty(), "a freshly committed checkout is not clean");
// An untracked file counts as dirty: it is exactly what a hard reset
// would erase.
std::fs::write(dir.join("a_new_file.txt"), "custom node config").unwrap();
- assert!(!git_working_tree_clean(&dir).expect("status failed"), "an untracked file was not seen as a local change");
+ let dirty = git_dirty_lines(&dir).expect("status failed");
+ assert!(!dirty.is_empty(), "an untracked file was not seen as a local change");
+ assert!(dirty.iter().any(|l| l.contains("a_new_file.txt")), "the dirty file is not named: {dirty:?}");
// Negative control the other way: removing it restores clean.
std::fs::remove_file(dir.join("a_new_file.txt")).unwrap();
- assert!(git_working_tree_clean(&dir).expect("status failed"), "clean again after the untracked file is gone");
+ assert!(git_dirty_lines(&dir).expect("status failed").is_empty(), "clean again after the untracked file is gone");
+ }
+
+ #[test]
+ fn lu_own_venv_scratch_siblings_never_count_as_dirty() {
+ // box-gruen/n9 punkt 87, final review (B5): a crashed or cancelled
+ // Repair can leave one of these next to the checkout. Update must
+ // treat the tree as clean anyway, or it refuses forever afterwards
+ // and blames the customer for LU's own leftovers.
+ let (_tmp, dir, _a, _b) = two_commit_repo();
+ for name in ["venv.lu-old-1737400000", "venv.lu-new-1737400001", "venv.lu-failed-1737400002"] {
+ std::fs::create_dir(dir.join(name)).unwrap();
+ std::fs::write(dir.join(name).join("marker"), "x").unwrap();
+ }
+
+ let dirty = git_dirty_lines(&dir).expect("status failed");
+ assert!(dirty.is_empty(), "LU's own venv rebuild siblings were treated as customer changes: {dirty:?}");
+
+ // Gegenprobe: a look-alike name that is NOT one of the three exact
+ // prefixes still counts as dirty, so the filter is not accidentally
+ // matching every "venv.*" folder. (git does not track empty
+ // directories at all, hence the marker file, same as the three above.)
+ std::fs::create_dir(dir.join("venv.customer-backup")).unwrap();
+ std::fs::write(dir.join("venv.customer-backup").join("marker"), "x").unwrap();
+ let dirty = git_dirty_lines(&dir).expect("status failed");
+ assert!(dirty.iter().any(|l| l.contains("venv.customer-backup")), "an unrelated venv.* folder was wrongly exempted: {dirty:?}");
}
#[test]
@@ -1495,7 +1626,7 @@ mod tests {
assert_eq!(git_current_commit(&dir).unwrap(), commit_a, "reset did not move HEAD back");
let contents = std::fs::read_to_string(dir.join("requirements.txt")).unwrap();
assert_eq!(contents, "a\n", "the working tree still shows the newer commit's content after reset");
- assert!(git_working_tree_clean(&dir).unwrap(), "a hard reset should leave a clean tree");
+ assert!(git_dirty_lines(&dir).unwrap().is_empty(), "a hard reset should leave a clean tree");
}
#[test]
@@ -1537,7 +1668,7 @@ mod tests {
let needle = |head: &str, tail: &str| format!("{head}{tail}");
let update_fn_start = src.find("pub fn update_comfyui(").expect("update_comfyui is gone");
- let clean_check = needle("match git_working_tree_cl", "ean(&comfy_dir) {");
+ let clean_check = needle("match git_dirty_l", "ines(&comfy_dir) {");
let pull_start = needle("Pulling the latest Comfy", "UI...");
let cancelled_pip = needle("rollback_after_cancelled_update(&comfy_d", "ir, &old_commit, \"the requirements install\")");
let cancelled_verify = needle("rollback_after_cancelled_update(&comfy_d", "ir, &old_commit, \"the environment check\")");
@@ -1578,6 +1709,26 @@ mod tests {
assert!(at_guard < at_installing, "the running-instance guard must run before the status slot is claimed");
}
+ #[test]
+ fn the_queue_is_checked_before_anything_is_stopped() {
+ // box-gruen/n9 punkt 87, final review (B3): a check that runs AFTER
+ // the kill is not a guard, it is a post-mortem. `stop_comfyui_blocking`
+ // must not be called until `comfyui_queue_busy` has already answered.
+ let src = include_str!("comfy_repair.rs");
+ let needle = |head: &str, tail: &str| format!("{head}{tail}");
+
+ let guard_fn_start = src.find("fn ensure_comfyui_stopped_for_update(").expect("the running-instance guard is gone");
+ let queue_check = needle("comfyui_queue_bus", "y(port)");
+ let stop_call = needle("process::stop_comfyui_bloc", "king(state)?;");
+
+ let at_queue_check = src[guard_fn_start..].find(&queue_check).map(|i| i + guard_fn_start)
+ .expect("the guard no longer checks whether ComfyUI is busy");
+ let at_stop_call = src[guard_fn_start..].find(&stop_call).map(|i| i + guard_fn_start)
+ .expect("the guard no longer stops ComfyUI through stop_comfyui_blocking");
+
+ assert!(at_queue_check < at_stop_call, "the queue must be checked before anything is stopped");
+ }
+
#[test]
fn foreign_comfyui_message_names_the_port_and_refuses_without_a_close_command() {
let msg = foreign_comfyui_blocks_update(8188);
@@ -1586,4 +1737,17 @@ mod tests {
assert!(msg.contains("Close that ComfyUI first"), "does not tell the customer what to do: {msg}");
assert!(msg.contains("Nothing was changed"), "does not say nothing was touched: {msg}");
}
+
+ // ── box-gruen/n9 Punkt 87, final review (B3): the queue-busy guard's
+ // JSON-parsing half, kept pure and provable with literal values ─────
+
+ #[test]
+ fn queue_has_work_reads_comfyuis_own_shape() {
+ assert!(!queue_has_work(&serde_json::json!({"queue_running": [], "queue_pending": []})));
+ assert!(queue_has_work(&serde_json::json!({"queue_running": [[0, "abc"]], "queue_pending": []})));
+ assert!(queue_has_work(&serde_json::json!({"queue_running": [], "queue_pending": [[0, "abc"]]})));
+ // A shape ComfyUI has never actually sent, kept as the honest
+ // fallback: neither key present reads as no work, not as an error.
+ assert!(!queue_has_work(&serde_json::json!({})));
+ }
}
diff --git a/src-tauri/src/commands/process.rs b/src-tauri/src/commands/process.rs
index c4cb89f1..2300e3cc 100644
--- a/src-tauri/src/commands/process.rs
+++ b/src-tauri/src/commands/process.rs
@@ -2095,6 +2095,49 @@ pub(crate) fn find_orphaned_comfyui_in(sys: &sysinfo::System, port: u16) -> Opti
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
@@ -2159,7 +2202,7 @@ pub(crate) fn kill_process_tree_blocking(pid: u32) -> Result<serde_json::Value,
Ok(serde_json::json!({ "killed": true, "pid": pid, "processes": tree }))
}
-fn stop_comfyui_blocking(state: &AppState) -> Result<serde_json::Value, String> {
+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();
@@ -2338,6 +2381,20 @@ pub async fn comfyui_status(state: State<'_, AppState>) -> Result<serde_json::Va
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.
+ let owned_by_app = is_local && running && matches!(
+ classify_comfyui_ownership(
+ running,
+ process_alive,
+ if process_alive { None } else { find_orphaned_comfyui(port) },
+ ),
+ ComfyOwnership::Own,
+ );
+
Ok(serde_json::json!({
"running": running,
"starting": starting,
@@ -2349,6 +2406,10 @@ pub async fn comfyui_status(state: State<'_, AppState>) -> Result<serde_json::Va
"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,
}))
}
@@ -4610,6 +4671,39 @@ mod comfy_adoption_tests {
}
}
}
+
+ // ── 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
diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsx
index 5d8819dc..61895672 100644
--- a/src/components/settings/SettingsPage.tsx
+++ b/src/components/settings/SettingsPage.tsx
@@ -717,12 +717,20 @@ interface ComfyStatusResponse {
port?: number
host?: string
isLocal?: boolean
- /** T-68/ENG-18: true only while THIS app holds a live child process handle
- * for ComfyUI. `running` alone cannot tell an instance LU started from
- * one merely answering on the configured port, and box-gruen/n9 punkt 87
- * found real damage in that gap: a foreign ComfyUI read as plain
- * "Running", and "Update ComfyUI" started on it with no warning. */
- processAlive?: boolean
+ /** Final review 19.09.2026 (B2): whether THIS app may treat the ComfyUI on
+ * the configured port as its own, per the one shared decision
+ * (`classify_comfyui_ownership` in `process.rs`) the status panel and
+ * Update's confirm dialog both read. `running` alone cannot tell an
+ * instance LU started from one merely answering on the port, and a plain
+ * "is there a live child handle from THIS run" is not enough either: a
+ * ComfyUI LU started in an earlier session and never lost track of
+ * (T-68's orphan, exactly what a live ComfyUI looks like after every app
+ * restart) still counts as ours. box-gruen/n9 punkt 87 found real damage
+ * in the first gap (a foreign ComfyUI read as plain "Running") and the
+ * final review found the second one (an own, orphaned ComfyUI wrongly
+ * read as foreign after a restart, blocking Update on the customer's own
+ * process). */
+ ownedByApp?: boolean
}
/** Antwort von `comfyui_last_output` (`process.rs`). Alle vier Schluessel
@@ -761,7 +769,7 @@ function ComfyUpdateConfirmModal({
<Modal open={open} onClose={onClose} title="Update ComfyUI?">
<div className="space-y-4 text-sm text-gray-200">
<p className="t-body leading-relaxed text-gray-300">
- This pulls the latest ComfyUI and reinstalls its Python packages. It can take a few minutes, and ComfyUI must not be running while it happens.
+ This pulls the latest ComfyUI and reinstalls its Python packages. It can take a few minutes. If ComfyUI is running and this app started it, it will be stopped first; a ComfyUI this app did not start blocks the update instead.
</p>
{path && <p className="t-label text-gray-500 text-center">ComfyUI folder: {path}</p>}
<div className="flex flex-col gap-2 pt-1">
@@ -806,6 +814,14 @@ export function ComfyUISettings() {
// ComfyUI". Closed by default; opened only by the button below, and the
// backend call itself only ever runs from the dialog's own Update button.
const [updateConfirmOpen, setUpdateConfirmOpen] = useState(false)
+ // K2 (final review 19.09.2026): two fast clicks on the dialog's own Update
+ // button, before React re-renders it away, could otherwise fire
+ // `runUpdate()` twice. `COMFY_JOB`'s lock in Rust would answer the second
+ // one with "already_installing" and cause no real harm, but a ref that
+ // reset only when the dialog re-opens is one line cheaper than relying on
+ // that. A ref, not state: the guard must take effect on the very first
+ // click, before any re-render.
+ const updateConfirmedRef = useRef(false)
// A13 (Windows counter-check 2026-09-02): install, update and repair used to
// keep their phase, their log lines and their byte counters in this
// component. Switching to another settings section threw all of it away
@@ -984,15 +1000,26 @@ export function ComfyUISettings() {
// backend (`update_comfyui`) checks the same thing again and is the real
// gate (defense in depth), since the status here is only ever a mirror of
// the last 5 s poll.
+ //
+ // Final review 19.09.2026 (B2): this used to ask `processAlive === false`,
+ // which only answers for a live handle from THIS run. A ComfyUI LU started
+ // in an earlier session (T-68's orphan, exactly what a live ComfyUI looks
+ // like after every app restart) then read as foreign, blocking Update on
+ // the customer's own process with an untrue message. `ownedByApp` asks the
+ // one question that actually matters: would the backend's own guard
+ // (`ensure_comfyui_stopped_for_update`) stop this, or refuse it.
const handleUpdateClick = () => {
- if (status?.running && status?.processAlive === false) {
+ if (status?.running && status?.ownedByApp === false) {
setStartError('A ComfyUI this app did not start is using this folder. Close that ComfyUI first, then try Update ComfyUI again.')
return
}
+ updateConfirmedRef.current = false
setUpdateConfirmOpen(true)
}
const handleConfirmUpdate = () => {
+ if (updateConfirmedRef.current) return
+ updateConfirmedRef.current = true
setUpdateConfirmOpen(false)
setStartError('')
void useComfyInstallStore.getState().runUpdate()
@@ -1054,14 +1081,19 @@ export function ComfyUISettings() {
<div className={`w-1.5 h-1.5 rounded-full ${status?.running ? PUNKT_FARBE.an : status?.stalled ? PUNKT_FARBE.kaputt : PUNKT_FARBE.aus}`} />
<span className="text-[0.65rem] text-gray-500">
{/* box-gruen/n9 Punkt 87 (ENG-18): "Running" alone does not say
- WHOSE ComfyUI is on the port. `processAlive === false` while
- `running` is true means the port answers but this app holds
- no child handle for it -- a copy started outside LU, exactly
+ WHOSE ComfyUI is on the port. `ownedByApp === false` while
+ `running` is true means a copy started outside LU, exactly
the shape a foreign "Update ComfyUI" click damaged for real
on a Windows box. Kept to the strict `=== false` check so a
path that simply never sends the field (undefined) still
- reads as plain "Running", not a false alarm. */}
- {status?.running ? (status?.processAlive === false ? 'Running (started outside LU)' : 'Running')
+ reads as plain "Running", not a false alarm.
+
+ Final review 19.09.2026 (B2): this used to key off
+ `processAlive`, which only answers for a live handle from
+ THIS run and reads LU's own orphaned ComfyUI from an earlier
+ session as foreign after every app restart.
+ `ownedByApp` is the backend's one shared answer instead. */}
+ {status?.running ? (status?.ownedByApp === false ? 'Running (started outside LU)' : 'Running')
: status?.stalled ? 'Not responding'
: status?.starting ? 'Starting'
: status?.found ? 'Stopped' : 'Not Installed'}
diff --git a/src/components/settings/__tests__/comfy-update-confirm-dialog.test.ts b/src/components/settings/__tests__/comfy-update-confirm-dialog.test.ts
index 4ec443f7..8d9b0a2c 100644
--- a/src/components/settings/__tests__/comfy-update-confirm-dialog.test.ts
+++ b/src/components/settings/__tests__/comfy-update-confirm-dialog.test.ts
@@ -15,6 +15,12 @@
* button calls `update_comfyui`. Separately, a ComfyUI this app did not
* start blocks the click before the dialog even opens.
*
+ * Final review 19.09.2026 added two more cases: `ownedByApp` (not
+ * `processAlive`, which lies about LU's own ComfyUI after an app restart,
+ * B2) decides ownership, the dialog text says LU stops its own ComfyUI
+ * first (B4), and a fast double click on the dialog's own Update button
+ * fires the backend only once (K2).
+ *
* Run: npx vitest run src/components/settings/__tests__/comfy-update-confirm-dialog.test.ts
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
@@ -40,12 +46,12 @@ const { useComfyInstallStore } = await import('../../../stores/comfyInstallStore
/** What `comfyui_status` answers next. Own, idle ComfyUI by default. */
let comfyStatus: Record<string, unknown> = {
- running: false, found: true, complete: true, path: 'C:\\ComfyUI', isLocal: true, processAlive: false,
+ running: false, found: true, complete: true, path: 'C:\\ComfyUI', isLocal: true, ownedByApp: false,
}
beforeEach(() => {
useComfyInstallStore.getState().reset()
- comfyStatus = { running: false, found: true, complete: true, path: 'C:\\ComfyUI', isLocal: true, processAlive: false }
+ comfyStatus = { running: false, found: true, complete: true, path: 'C:\\ComfyUI', isLocal: true, ownedByApp: false }
backendCall.mockReset()
backendCall.mockImplementation(async (cmd: string) => {
if (cmd === 'comfyui_status') return comfyStatus
@@ -70,11 +76,13 @@ describe('the Update ComfyUI confirmation dialog', () => {
expect(backendCall.mock.calls.some(([cmd]) => cmd === 'update_comfyui')).toBe(false)
})
- it('names the folder as read-only text and says ComfyUI must not be running', async () => {
+ it('names the folder as read-only text and says LU stops its own ComfyUI first (B4)', async () => {
await mountPanel()
await act(async () => { fireEvent.click(screen.getByText('Update ComfyUI')) })
- expect(screen.getByText(/must not be running/)).toBeTruthy()
+ // B4: the old wording ("ComfyUI must not be running") hid the fact that
+ // LU itself kills a running, own ComfyUI as part of the update.
+ expect(screen.getByText(/it will be stopped first/)).toBeTruthy()
expect(screen.getByText(/C:\\ComfyUI/)).toBeTruthy()
// Read-only: no textbox for the folder, unlike the Path field above it.
expect(screen.queryByRole('textbox', { name: /ComfyUI folder/ })).toBeNull()
@@ -121,11 +129,25 @@ describe('the Update ComfyUI confirmation dialog', () => {
await waitFor(() => expect(backendCall.mock.calls.some(([cmd]) => cmd === 'update_comfyui')).toBe(true))
await waitFor(() => expect(screen.queryByRole('dialog', { name: /Update ComfyUI\?/ })).toBeNull())
})
+
+ it('K2: two fast clicks on the dialog Update button call the backend only once', async () => {
+ await mountPanel()
+ await act(async () => { fireEvent.click(screen.getByText('Update ComfyUI')) })
+
+ const updateButton = screen.getByRole('button', { name: 'Update' })
+ // Both clicks fire before any state update is flushed, exactly the race
+ // the ref guard in `handleConfirmUpdate` exists to close.
+ fireEvent.click(updateButton)
+ fireEvent.click(updateButton)
+
+ await waitFor(() => expect(backendCall.mock.calls.some(([cmd]) => cmd === 'update_comfyui')).toBe(true))
+ expect(backendCall.mock.calls.filter(([cmd]) => cmd === 'update_comfyui').length).toBe(1)
+ })
})
describe('a ComfyUI this app did not start blocks the click, negative control included', () => {
it('a foreign, running ComfyUI shows a message instead of opening the dialog', async () => {
- comfyStatus = { running: true, found: true, complete: true, path: 'C:\\ComfyUI', isLocal: true, processAlive: false }
+ comfyStatus = { running: true, found: true, complete: true, path: 'C:\\ComfyUI', isLocal: true, ownedByApp: false }
await mountPanel()
await act(async () => { fireEvent.click(screen.getByText('Update ComfyUI')) })
@@ -133,14 +155,14 @@ describe('a ComfyUI this app did not start blocks the click, negative control in
expect(screen.queryByRole('dialog', { name: /Update ComfyUI\?/ })).toBeNull()
expect(screen.getByText(/did not start is using this folder/)).toBeTruthy()
expect(backendCall.mock.calls.some(([cmd]) => cmd === 'update_comfyui')).toBe(false)
- // The status line itself says so too (processAlive: false while running).
+ // The status line itself says so too (ownedByApp: false while running).
expect(screen.getByText('Running (started outside LU)')).toBeTruthy()
})
it('GEGENPROBE: the app\'s own running ComfyUI opens the dialog like any other case', async () => {
// Negative control for the guard above: same `running: true`, but this
- // time LU holds the child handle. Must NOT be treated as foreign.
- comfyStatus = { running: true, found: true, complete: true, path: 'C:\\ComfyUI', isLocal: true, processAlive: true }
+ // time the backend says it is ours.
+ comfyStatus = { running: true, found: true, complete: true, path: 'C:\\ComfyUI', isLocal: true, ownedByApp: true }
await mountPanel()
await act(async () => { fireEvent.click(screen.getByText('Update ComfyUI')) })
@@ -148,5 +170,12 @@ describe('a ComfyUI this app did not start blocks the click, negative control in
expect(screen.getByRole('dialog', { name: /Update ComfyUI\?/ })).toBeTruthy()
expect(screen.queryByText(/did not start is using this folder/)).toBeNull()
expect(screen.getByText('Running')).toBeTruthy()
+ // Final review 19.09.2026, B2: `ownedByApp: true` is exactly the answer
+ // the backend now gives for BOTH a live handle from this run AND an
+ // orphan adopted from an earlier one (`find_orphaned_comfyui`) -- the
+ // frontend cannot and must not tell those two apart on its own, it only
+ // reads the one shared verdict. The Rust-side distinction itself is
+ // proven in `process.rs`'s `comfy_adoption_tests` (`classify_comfyui_ownership`).
+ expect(screen.queryByText('Running (started outside LU)')).toBeNull()
})
})