comfyui-mcp
Version:
Local-first, agent-native control plane for ComfyUI — MCP server + autonomous sidebar agent that drives your live graph in natural language on ANY LLM: Claude/ChatGPT/Gemini on your subscription (no API key), free local models via Ollama (fully offline),
995 lines • 39 kB
JavaScript
import { execSync, spawn } from "node:child_process";
import { existsSync } from "node:fs";
import { platform } from "node:os";
import { isAbsolute, join } from "node:path";
import { getSystemStats, resetClient, resetObjectInfoCache } from "../comfyui/client.js";
import { config, getComfyUIBaseUrl, isRemoteMode } from "../config.js";
import { comfyuiFetch } from "../comfyui/fetch.js";
import { ProcessControlError } from "../utils/errors.js";
import { logger } from "../utils/logger.js";
import { findComfyuiPython } from "./env-capabilities.js";
// ---------------------------------------------------------------------------
// Module-level state — persists between MCP tool calls within a session
// ---------------------------------------------------------------------------
let lastProcessInfo = null;
let supervisedChild = null;
let supervisedExitHandler = null;
let supervisedErrorHandler = null;
let supervisorRestartCount = 0;
let supervisorWindowStartedAt = 0;
let supervisorGaveUp = false;
// ---------------------------------------------------------------------------
// Cross-platform helpers
// ---------------------------------------------------------------------------
const IS_WIN = platform() === "win32";
function findPidByPort(port) {
try {
if (IS_WIN) {
// netstat -ano | findstr :PORT | findstr LISTENING
const out = execSync(`netstat -ano | findstr :${port} | findstr LISTENING`, { encoding: "utf-8", timeout: 5000 }).trim();
// Lines look like: TCP 0.0.0.0:8188 0.0.0.0:0 LISTENING 12345
for (const line of out.split("\n")) {
const parts = line.trim().split(/\s+/);
if (parts.length >= 5) {
const pid = parseInt(parts[parts.length - 1], 10);
if (!isNaN(pid) && pid > 0)
return pid;
}
}
}
else {
const out = execSync(`lsof -ti :${port}`, {
encoding: "utf-8",
timeout: 5000,
}).trim();
const pid = parseInt(out.split("\n")[0], 10);
if (!isNaN(pid) && pid > 0)
return pid;
}
}
catch {
// Command failed — no process on that port
}
return null;
}
/**
* Find PIDs of the Desktop app's Electron shell — current branding
* ("Comfy Desktop.exe" / "Comfy Desktop.app") and legacy ("ComfyUI.exe" /
* "ComfyUI.app"). The Python backend is a child of the Electron app, so we
* need to kill the parent to fully stop the Desktop app.
*/
function findDesktopAppPids() {
const pids = [];
if (IS_WIN) {
for (const exe of ["ComfyUI.exe", "Comfy Desktop.exe"]) {
try {
const out = execSync(`tasklist /FI "IMAGENAME eq ${exe}" /FO CSV /NH`, { encoding: "utf-8", timeout: 5000 }).trim();
for (const line of out.split("\n")) {
// CSV format: "ComfyUI.exe","12345","Console","1","206,248 K"
// (the image name is already filtered — match any first column)
const match = line.match(/^"[^"]+","(\d+)"/);
if (match)
pids.push(parseInt(match[1], 10));
}
}
catch {
// No processes with this image name
}
}
}
else {
try {
const out = execSync(`pgrep -f "ComfyUI.app|Comfy Desktop.app"`, {
encoding: "utf-8",
timeout: 5000,
}).trim();
for (const line of out.split("\n")) {
const pid = parseInt(line, 10);
if (!isNaN(pid) && pid > 0)
pids.push(pid);
}
}
catch {
// No Desktop app processes found
}
}
return pids;
}
function killProcessTree(pid) {
try {
if (IS_WIN) {
execSync(`taskkill /PID ${pid} /T /F`, {
encoding: "utf-8",
timeout: 10000,
});
}
else {
// Try SIGTERM first, then SIGKILL after a short wait
try {
process.kill(-pid, "SIGTERM");
}
catch {
process.kill(pid, "SIGTERM");
}
// Give it a moment, then force kill
try {
execSync(`sleep 1 && kill -9 ${pid} 2>/dev/null`, {
encoding: "utf-8",
timeout: 5000,
});
}
catch {
// Already dead — that's fine
}
}
}
catch (err) {
const msg = err instanceof Error ? err.message : String(err);
// "not found" / "no such process" are fine — process already dead
if (!/not found|no such process|does not exist/i.test(msg)) {
throw new ProcessControlError(`Failed to kill process ${pid}: ${msg}`);
}
}
}
/**
* Kill the Desktop app entirely — find all Electron shell PIDs and kill each tree.
* Falls back to killing just the port PID if no Desktop processes found.
*/
function killDesktopApp(portPid) {
const desktopPids = findDesktopAppPids();
if (desktopPids.length > 0) {
logger.info(`Killing Desktop app processes: ${desktopPids.join(", ")}`);
for (const pid of desktopPids) {
killProcessTree(pid);
}
}
else {
// Fallback — just kill the port process
killProcessTree(portPid);
}
}
function isDesktopApp(argv) {
const joined = argv.join(" ").toLowerCase();
return (joined.includes("programs/comfyui/resources") ||
joined.includes("programs\\comfyui\\resources") ||
joined.includes("comfyui.app") ||
// Current branding ("Comfy Desktop\Comfy Desktop.exe", "Comfy Desktop.app")
// and the electron-era install dir.
joined.includes("comfy desktop") ||
joined.includes("@comfyorgcomfyui-electron"));
}
/**
* Try to find the ComfyUI Desktop exe from common install locations.
* Used as a fallback when no process info was previously captured.
*/
function findDesktopExeFromCommonPaths() {
if (IS_WIN) {
const home = process.env.LOCALAPPDATA || process.env.USERPROFILE || "";
const candidates = [
// Current branding: "Comfy Desktop" (per-machine and per-user installs)
`C:\\Program Files\\Comfy Desktop\\Comfy Desktop.exe`,
`${process.env.LOCALAPPDATA}\\Programs\\Comfy Desktop\\Comfy Desktop.exe`,
// Electron-era install dir
`${process.env.LOCALAPPDATA}\\Programs\\@comfyorgcomfyui-electron\\ComfyUI.exe`,
// Legacy names
`${home}\\Programs\\ComfyUI\\ComfyUI.exe`,
`${process.env.LOCALAPPDATA}\\Programs\\ComfyUI\\ComfyUI.exe`,
`C:\\Program Files\\ComfyUI\\ComfyUI.exe`,
];
for (const p of candidates) {
try {
const result = execSync(`if exist "${p}" echo found`, { encoding: "utf-8", timeout: 2000 });
if (result.includes("found"))
return p;
}
catch {
// Not found
}
}
}
else {
// macOS
const candidates = [
"/Applications/Comfy Desktop.app",
`${process.env.HOME}/Applications/Comfy Desktop.app`,
"/Applications/ComfyUI.app",
`${process.env.HOME}/Applications/ComfyUI.app`,
];
for (const p of candidates) {
try {
execSync(`test -d "${p}"`, { timeout: 2000 });
return p;
}
catch {
// Not found
}
}
}
return undefined;
}
function findDesktopExePath(argv) {
const joined = argv.join(" ");
if (IS_WIN) {
// Look for the main ComfyUI Desktop exe by walking up from the python/main.py path
// Typical: C:\Users\X\AppData\Local\Programs\ComfyUI\resources\ComfyUI\main.py
// Desktop exe: C:\Users\X\AppData\Local\Programs\ComfyUI\ComfyUI.exe
const match = joined.match(/([A-Za-z]:[\\\/].*?[\\\/]Programs[\\\/]ComfyUI)[\\\/]resources/i);
if (match)
return `${match[1]}\\ComfyUI.exe`;
}
else {
// macOS: /Applications/ComfyUI.app/...
const match = joined.match(/(\/.*?ComfyUI\.app)/);
if (match)
return match[1];
}
return undefined;
}
async function waitForPortFree(port, timeoutMs = 15000) {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
if (findPidByPort(port) === null)
return;
await sleep(500);
}
throw new ProcessControlError(`Port ${port} still in use after ${timeoutMs / 1000}s`);
}
function parsePositiveNumberEnv(name, fallback) {
const raw = process.env[name];
if (raw === undefined || raw.trim() === "")
return fallback;
const parsed = Number(raw);
return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
}
function parsePositiveIntEnv(name, fallback) {
const raw = process.env[name];
if (raw === undefined || raw.trim() === "")
return fallback;
const parsed = Number(raw);
return Number.isFinite(parsed) && parsed >= 1 ? Math.floor(parsed) : fallback;
}
function getStartupReadinessConfig() {
return {
intervalMs: Math.round(parsePositiveNumberEnv("COMFYUI_STARTUP_CHECK_INTERVAL_S", 1) * 1000),
// Default budget is 60s (was 20s). ComfyUI with a normal set of custom nodes
// routinely takes >20s to answer /system_stats on a cold start, so a 20-probe
// budget reported `started:false` moments before a healthy instance became
// ready (issue #367). Tunable via COMFYUI_STARTUP_CHECK_MAX_TRIES.
maxTries: parsePositiveIntEnv("COMFYUI_STARTUP_CHECK_MAX_TRIES", 60),
};
}
function getRestartPolicy() {
const enabled = /^(1|true|yes)$/i.test(process.env.COMFYUI_ALWAYS_RESTART ?? "");
return {
enabled,
maxRestarts: parsePositiveIntEnv("COMFYUI_RESTART_MAX_ATTEMPTS", 3),
windowMs: Math.round(parsePositiveNumberEnv("COMFYUI_RESTART_WINDOW_S", 60) * 1000),
};
}
/**
* Poll `/system_stats` until ComfyUI answers 2xx. This poller is TOLERANT of the
* down window: a thrown fetch error (ECONNRESET / socket hang up / fetch failed)
* and any non-2xx (including a 502/503/504 from a proxy/tunnel in front of a
* killed origin) are all swallowed and treated as "not ready yet — keep polling".
* That property is what lets the same routine cover both a locally-spawned start
* and a remote ComfyUI-Manager reboot (where ComfyUI briefly disappears).
*
* `cfg` overrides the interval/try budget — the local start uses the short
* env-tuned default; the remote reboot passes a longer budget.
*/
async function waitForApiReady(cfg) {
const { intervalMs, maxTries } = cfg ?? getStartupReadinessConfig();
const probeUrl = `${getComfyUIBaseUrl()}/system_stats`;
const start = Date.now();
let attempts = 0;
for (; attempts < maxTries; attempts++) {
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 2000);
let res;
try {
res = await comfyuiFetch(probeUrl, { signal: controller.signal });
}
finally {
clearTimeout(timeout);
}
if (res.ok) {
logger.info("ComfyUI API is ready");
return {
ready: true,
timed_out: false,
attempts: attempts + 1,
max_tries: maxTries,
interval_ms: intervalMs,
waited_ms: Date.now() - start,
probe_url: probeUrl,
};
}
}
catch {
// Not ready yet
}
if (attempts < maxTries - 1)
await sleep(intervalMs);
}
return {
ready: false,
timed_out: true,
attempts,
max_tries: maxTries,
interval_ms: intervalMs,
waited_ms: Date.now() - start,
probe_url: probeUrl,
};
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function detachSupervisor() {
if (supervisedChild && supervisedExitHandler) {
supervisedChild.off("exit", supervisedExitHandler);
}
if (supervisedChild && supervisedErrorHandler) {
supervisedChild.off("error", supervisedErrorHandler);
}
supervisedChild = null;
supervisedExitHandler = null;
supervisedErrorHandler = null;
}
function childProcessErrorDetails(err) {
if (!(err instanceof Error))
return { message: String(err) };
const nodeErr = err;
return {
message: err.message,
code: typeof nodeErr.code === "string" ? nodeErr.code : undefined,
errno: typeof nodeErr.errno === "number" ? nodeErr.errno : undefined,
syscall: typeof nodeErr.syscall === "string" ? nodeErr.syscall : undefined,
path: typeof nodeErr.path === "string" ? nodeErr.path : undefined,
};
}
function supervisorResult(info) {
const policy = getRestartPolicy();
return {
enabled: policy.enabled,
supported: Boolean(info && !info.isDesktopApp),
max_restarts: policy.maxRestarts,
window_ms: policy.windowMs,
restart_count: supervisorRestartCount,
gave_up: supervisorGaveUp,
message: !policy.enabled
? "Auto-restart is disabled."
: info?.isDesktopApp
? "Auto-restart supervision is only supported for directly spawned Python ComfyUI processes."
: undefined,
};
}
function rememberRestartAttempt(policy) {
const now = Date.now();
if (supervisorWindowStartedAt === 0 || now - supervisorWindowStartedAt > policy.windowMs) {
supervisorWindowStartedAt = now;
supervisorRestartCount = 0;
supervisorGaveUp = false;
}
if (supervisorRestartCount >= policy.maxRestarts) {
supervisorGaveUp = true;
return false;
}
supervisorRestartCount += 1;
return true;
}
function spawnFromProcessInfo(info) {
if (info.isDesktopApp) {
if (IS_WIN) {
const exe = info.desktopExePath;
if (!exe)
return null;
return spawn(exe, [], {
detached: true,
stdio: "ignore",
shell: false,
});
}
const appPath = info.desktopExePath ?? "ComfyUI";
return spawn("open", ["-a", appPath], {
detached: true,
stdio: "ignore",
});
}
const cmd = resolveLaunchCommand(info);
if (!cmd)
return null;
return spawn(cmd.exe, cmd.args, {
detached: true,
stdio: "ignore",
cwd: config.comfyuiPath ?? undefined,
shell: false,
windowsHide: true,
});
}
/**
* Turn captured process info into a spawnable (executable, args) pair.
*
* The argv we save comes from ComfyUI's `/system_stats` — i.e. Python's
* `sys.argv`, whose argv[0] is the SCRIPT path (`…/main.py`), NOT the Python
* interpreter. Spawning that script directly with `shell:false` fails on
* Windows with `spawn EFTYPE` (the OS cannot exec a `.py` as a PE binary),
* which is exactly the restart_comfyui relaunch failure in #330. When argv[0]
* is a script we resolve the real ComfyUI Python interpreter and pass the whole
* argv (main.py + flags) as its args. When argv[0] is already an interpreter
* (e.g. a supervised child we spawned ourselves), we spawn it verbatim.
*/
function resolveLaunchCommand(info) {
if (info.argv.length === 0)
return null;
const [first, ...rest] = info.argv;
// Strip surrounding quotes a launcher may leave on the script path BEFORE the
// suffix test — otherwise `"C:\…\main.py"` fails the `.py` check, bypasses the
// unified live-first resolver, and gets treated as the executable (#401 / PR #433
// round 3). Kept in sync with liveRootFromArgv's quote handling.
const firstUnquoted = first.trim().replace(/^["']+/, "").replace(/["']+$/, "");
const looksLikeScript = /\.pyw?$/i.test(firstUnquoted);
if (looksLikeScript) {
const python = findComfyuiPython(config.comfyuiPath ?? undefined, info.argv);
if (!python)
return null;
// sys.argv[0] can be RELATIVE (the standard Windows portable launcher runs
// `python ComfyUI\main.py` from the portable root). We force cwd to
// config.comfyuiPath — the ComfyUI dir that directly holds main.py — so a
// relative script would resolve against the wrong dir (…/ComfyUI/ComfyUI/
// main.py). Anchor it: use the absolute path as-is, otherwise main.py under
// the resolved ComfyUI root.
//
// The argv mirrors the running ComfyUI's sys.argv, which is Windows-flavored
// when ComfyUI runs on Windows — regardless of what OS this process is on.
// So detect absoluteness and the script basename in a separator-agnostic way
// rather than trusting the host `path` module (which mangles `C:\…` / `\`
// paths on POSIX). The final join stays host-native to match comfyuiPath.
const isWindowsAbsolute = /^[a-zA-Z]:[\\/]/.test(firstUnquoted) || /^\\\\/.test(firstUnquoted);
const scriptBasename = firstUnquoted.split(/[\\/]/).pop() || firstUnquoted;
const script = isAbsolute(firstUnquoted) || isWindowsAbsolute || !config.comfyuiPath
? firstUnquoted
: join(config.comfyuiPath, scriptBasename);
return { exe: python, args: [script, ...rest] };
}
return { exe: first, args: rest };
}
function fileExists(p) {
if (!p)
return false;
try {
return existsSync(p);
}
catch {
return false;
}
}
/** True when a token looks like a filesystem path (has a separator or a drive). */
function looksLikePath(s) {
return /[\\/]/.test(s) || /^[a-zA-Z]:/.test(s);
}
/**
* Can we actually relaunch this instance? A restart must be atomic-ish: if we
* can't build (and validate) a relaunch command, we must NOT stop the running
* server — losing a restart is cheap, losing the server is not (issues
* #368/#370). For a Desktop app this also RESOLVES + validates the launcher exe
* (mutating `info.desktopExePath`) so the subsequent spawn uses a real path
* rather than a regex guess that never matched the current "Comfy Desktop"
* branding. For a script-based install it confirms the resolved interpreter and
* `main.py` exist on disk — catching a stale COMFYUI_PATH that points at an
* install with no runnable server.
*/
function assessRelaunch(info) {
if (info.isDesktopApp) {
if (IS_WIN) {
const exe = fileExists(info.desktopExePath)
? info.desktopExePath
: findDesktopExeFromCommonPaths();
if (!exe || !fileExists(exe)) {
return {
ok: false,
reason: "Could not determine (or locate on disk) the ComfyUI Desktop executable to relaunch.",
};
}
info.desktopExePath = exe;
return { ok: true };
}
// macOS: relaunch via `open -a`, which accepts an app bundle path or name.
// Prefer a bundle that still exists on disk; fall back to a located one.
const appPath = fileExists(info.desktopExePath)
? info.desktopExePath
: findDesktopExeFromCommonPaths();
if (!appPath || !fileExists(appPath)) {
return {
ok: false,
reason: "Could not determine (or locate on disk) the ComfyUI Desktop app to relaunch.",
};
}
info.desktopExePath = appPath;
return { ok: true };
}
const cmd = resolveLaunchCommand(info);
if (!cmd) {
return {
ok: false,
reason: "Could not build a relaunch command from the running server's launch arguments.",
};
}
if (looksLikePath(cmd.exe) && !fileExists(cmd.exe)) {
return {
ok: false,
reason: `Resolved Python interpreter does not exist on disk: ${cmd.exe}.`,
};
}
const script = cmd.args[0];
if (script && /\.pyw?$/i.test(script) && looksLikePath(script) && !fileExists(script)) {
return {
ok: false,
reason: `Resolved ComfyUI script does not exist on disk: ${script} — ` +
"COMFYUI_PATH may point at a stale/old install that has no runnable server.",
};
}
return { ok: true };
}
/**
* Resolve the running instance to control: ComfyUI's /system_stats argv + the
* PID on the port, falling back to OS-level Desktop-app detection when the API
* and port are unreachable. Returns null when nothing can be found.
*/
async function acquireProcessInfo() {
try {
return await gatherProcessInfo();
}
catch {
const desktopPids = findDesktopAppPids();
if (desktopPids.length > 0) {
logger.info(`API unreachable but found Desktop app PIDs: ${desktopPids.join(", ")}`);
return {
pid: desktopPids[0],
port: config.resolvedPort,
argv: [],
isDesktopApp: true,
desktopExePath: findDesktopExeFromCommonPaths(),
};
}
return null;
}
}
function handleSupervisedChildStop(child, reason) {
if (supervisedChild !== child)
return;
detachSupervisor();
if (!lastProcessInfo)
return;
const currentPolicy = getRestartPolicy();
if (!currentPolicy.enabled)
return;
if (!rememberRestartAttempt(currentPolicy)) {
logger.warn("ComfyUI exited unexpectedly; auto-restart limit reached", {
code: reason.code,
signal: reason.signal,
error: reason.error,
maxRestarts: currentPolicy.maxRestarts,
windowMs: currentPolicy.windowMs,
});
return;
}
logger.warn("ComfyUI exited unexpectedly; restarting", {
code: reason.code,
signal: reason.signal,
error: reason.error,
restartCount: supervisorRestartCount,
maxRestarts: currentPolicy.maxRestarts,
});
const restarted = spawnFromProcessInfo(lastProcessInfo);
if (!restarted) {
logger.warn("Could not auto-restart ComfyUI because launch info was incomplete");
return;
}
restarted.unref();
superviseChild(restarted, lastProcessInfo);
}
function captureChildProcessError(child) {
return new Promise((resolve) => {
child.once("error", (err) => {
const error = childProcessErrorDetails(err);
logger.error("ComfyUI child process emitted an error", { error });
resolve(error);
});
});
}
function superviseChild(child, info) {
detachSupervisor();
const policy = getRestartPolicy();
if (!policy.enabled || info.isDesktopApp)
return;
supervisedChild = child;
supervisedExitHandler = (code, signal) => {
handleSupervisedChildStop(child, { code, signal });
};
supervisedErrorHandler = (err) => {
const error = childProcessErrorDetails(err);
logger.error("ComfyUI child process emitted an error", { error });
handleSupervisedChildStop(child, { error });
};
child.on("exit", supervisedExitHandler);
child.once("error", supervisedErrorHandler);
}
// ---------------------------------------------------------------------------
// Gather process info from running ComfyUI
// ---------------------------------------------------------------------------
async function gatherProcessInfo() {
const port = config.resolvedPort;
// 1. Get argv from /system_stats
let argv = [];
try {
const stats = await getSystemStats();
argv = stats.system.argv ?? [];
}
catch {
logger.warn("Could not fetch system_stats — will rely on PID detection");
}
// 2. Find PID by port
const pid = findPidByPort(port);
if (!pid) {
throw new ProcessControlError(`No process found listening on port ${port}. Is ComfyUI running?`);
}
const desktop = isDesktopApp(argv);
const desktopExe = desktop ? findDesktopExePath(argv) : undefined;
return { pid, port, argv, isDesktopApp: desktop, desktopExePath: desktopExe };
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
export async function stopComfyUI(preInfo) {
if (isRemoteMode()) {
throw new ProcessControlError("stop_comfyui operates on the local machine's ComfyUI process and is not " +
"available when targeting a remote instance via --comfyui-url.");
}
logger.info("Stopping ComfyUI...");
detachSupervisor();
// Gather info before we kill it (or reuse the caller's pre-validated info so a
// relaunch preflight in restartComfyUI is not discarded).
const info = preInfo ?? (await acquireProcessInfo());
if (!info) {
return {
stopped: false,
message: `No ComfyUI process found on port ${config.resolvedPort}. Is ComfyUI running?`,
has_restart_info: false,
};
}
// Save for later start
lastProcessInfo = info;
logger.info("Captured process info", {
pid: info.pid,
port: info.port,
isDesktopApp: info.isDesktopApp,
argv: info.argv.join(" "),
});
// Kill process tree (for Desktop app, kill the Electron shell too)
if (info.isDesktopApp) {
killDesktopApp(info.pid);
}
else {
killProcessTree(info.pid);
}
// Reset the WebSocket client singleton + the memoized /object_info —
// a restart is exactly when the node set may have changed.
resetClient();
resetObjectInfoCache();
// Wait for port to actually free
try {
await waitForPortFree(info.port);
}
catch {
logger.warn("Port did not free in time, but process kill was sent");
}
return {
stopped: true,
message: `ComfyUI (PID ${info.pid}) stopped on port ${info.port}`,
has_restart_info: true,
auto_restart: supervisorResult(info),
};
}
export async function startComfyUI() {
if (isRemoteMode()) {
throw new ProcessControlError("start_comfyui launches ComfyUI on the local machine and is not " +
"available when targeting a remote instance via --comfyui-url.");
}
const port = config.resolvedPort;
// Check if already running
const existingPid = findPidByPort(port);
if (existingPid) {
return {
started: false,
message: `ComfyUI is already running on port ${port} (PID ${existingPid})`,
pid: existingPid,
};
}
let info = lastProcessInfo;
if (!info) {
// No saved info — try to detect and launch the Desktop app
const desktopExe = findDesktopExeFromCommonPaths();
if (desktopExe) {
logger.info(`No saved process info, but found Desktop app at: ${desktopExe}`);
info = {
pid: 0,
port,
argv: [],
isDesktopApp: true,
desktopExePath: desktopExe,
};
}
else {
return {
started: false,
message: "No previous process info and could not find ComfyUI Desktop app. Start ComfyUI manually.",
};
}
}
logger.info("Starting ComfyUI...", {
isDesktopApp: info.isDesktopApp,
argv: info.argv.join(" "),
});
const launched = spawnFromProcessInfo(info);
if (!launched) {
return {
started: false,
message: info.isDesktopApp
? "Could not determine ComfyUI Desktop executable path. Please start it manually."
: "No command-line info captured from previous run. Start ComfyUI manually.",
auto_restart: supervisorResult(info),
};
}
const spawnError = captureChildProcessError(launched);
launched.unref();
lastProcessInfo = info;
superviseChild(launched, info);
// Wait for API to become ready
const startupResult = await Promise.race([
waitForApiReady().then((readiness) => ({ readiness })),
spawnError.then((error) => ({ spawn_error: error })),
]);
if ("spawn_error" in startupResult) {
return {
started: false,
ready: false,
message: `ComfyUI process failed to launch: ${startupResult.spawn_error.message}`,
spawn_error: startupResult.spawn_error,
auto_restart: supervisorResult(info),
};
}
const readiness = startupResult.readiness;
if (!readiness.ready) {
return {
started: false,
ready: false,
readiness,
message: `ComfyUI process was launched but the API did not become ready after ${readiness.waited_ms}ms (${readiness.attempts}/${readiness.max_tries} probes). Check the ComfyUI logs.`,
auto_restart: supervisorResult(info),
};
}
const newPid = findPidByPort(port);
return {
started: true,
ready: true,
readiness,
message: `ComfyUI started on port ${port}${newPid ? ` (PID ${newPid})` : ""}`,
pid: newPid ?? undefined,
auto_restart: supervisorResult(info),
};
}
// Match the repo's Manager path convention (node-management.ts appends these to
// getComfyUIBaseUrl() with no `/api` prefix — the panel's `/api/...` form is only
// because its browser `api.fetchApi` prepends `/api`). Canonical v4 POST route
// first, then the legacy GET route for older Manager builds.
const REBOOT_ROUTES = [
{ path: "/v2/manager/reboot", method: "POST" },
{ path: "/manager/reboot", method: "GET" },
];
/**
* A dropped/aborted connection is the SUCCESS signal for a reboot: the Manager
* handler calls exit(0) the instant it accepts the request, so the origin dies
* before it can send an HTTP response and `fetch` rejects.
*/
function isConnectionDrop(err) {
const msg = err instanceof Error ? err.message : String(err);
// NOTE: ECONNREFUSED is deliberately absent — it means "nothing is listening"
// (the origin was ALREADY down before we called), not "we killed it mid-request".
// A process reboot we caused surfaces as ECONNRESET / socket-hang-up / terminated.
return /ECONNRESET|socket hang up|fetch failed|network|ECONNABORTED|EPIPE|terminated|premature close|other side closed|aborted/i.test(msg);
}
/**
* Fire a ComfyUI-Manager reboot over HTTP against the connected (remote) base URL.
* Classification:
* FIRED (rebooting:true) — res.ok (2xx) OR a connection drop OR HTTP 502/503/504.
* A killed origin behind a proxy/Cloudflare surfaces
* as a 5xx bad-gateway (NOT a raw socket drop), so we
* must treat those as "reboot fired" too.
* REFUSED (rebooting:false) — HTTP 403 → Manager security forbids remote reboot.
* NO-ENDPOINT (rebooting:false) — every route gave a non-firing failure (e.g. 404).
*/
async function rebootViaManager() {
const base = getComfyUIBaseUrl();
const failures = [];
for (const { path, method } of REBOOT_ROUTES) {
const url = `${base}${path}`;
try {
const res = await comfyuiFetch(url, { method });
if (res.ok)
return { rebooting: true, endpoint: path, method };
if (res.status === 403) {
return {
rebooting: false,
reason: "manager-security",
note: "Reboot refused (HTTP 403) — ComfyUI-Manager's security level (or an " +
"access proxy in front) forbids it; lower the Manager security level or reboot on the host.",
};
}
if (res.status === 502 || res.status === 503 || res.status === 504) {
return {
rebooting: true,
endpoint: path,
method,
note: `reboot fired — the origin dropped behind a proxy (HTTP ${res.status}) as it went down`,
};
}
// 404 / other non-OK: wrong route for this Manager build — try the next.
failures.push(`${method} ${path} → HTTP ${res.status}`);
}
catch (err) {
if (isConnectionDrop(err)) {
return {
rebooting: true,
endpoint: path,
method,
note: "connection dropped (origin going down) — reboot fired",
};
}
failures.push(`${method} ${path} → ${err instanceof Error ? err.message : String(err)}`);
}
}
return {
rebooting: false,
reason: "no-endpoint",
note: `No reachable ComfyUI-Manager reboot endpoint.${failures.length ? ` Tried: ${failures.join("; ")}` : ""}`,
};
}
let remoteRebootTimingOverride = null;
function getRemoteRebootTiming() {
if (remoteRebootTimingOverride)
return remoteRebootTimingOverride;
return {
settleMs: Math.round(parsePositiveNumberEnv("COMFYUI_REMOTE_REBOOT_SETTLE_S", 3) * 1000),
budgetMs: Math.round(parsePositiveNumberEnv("COMFYUI_REMOTE_REBOOT_BUDGET_S", 120) * 1000),
intervalMs: Math.round(parsePositiveNumberEnv("COMFYUI_REMOTE_REBOOT_INTERVAL_S", 2) * 1000),
};
}
async function restartRemoteViaManager() {
logger.info("Restarting remote ComfyUI via ComfyUI-Manager reboot...");
const reboot = await rebootViaManager();
if (!reboot.rebooting) {
return {
stopped: false,
started: false,
message: reboot.note ?? "ComfyUI-Manager reboot could not be triggered.",
};
}
logger.info("ComfyUI-Manager reboot fired", {
endpoint: reboot.endpoint,
method: reboot.method,
note: reboot.note,
});
const timing = getRemoteRebootTiming();
if (timing.settleMs > 0)
await sleep(timing.settleMs);
// Clamp the interval to a sane floor: a 0 (or tiny) env value would make
// maxTries unbounded (ceil(budget/0) = Infinity) and hot-loop the poller,
// hanging the tool call if the host never returns.
const intervalMs = Math.max(250, timing.intervalMs);
const maxTries = Math.max(1, Math.ceil(timing.budgetMs / intervalMs));
const readiness = await waitForApiReady({ intervalMs, maxTries });
if (!readiness.ready) {
return {
stopped: true,
started: false,
ready: false,
readiness,
message: `Reboot was triggered but ComfyUI did not come back within ${timing.budgetMs}ms — ` +
"check the host (is it the Desktop app / supervised?).",
};
}
// Back and ready — refresh the WS client singleton + memoized /object_info,
// since a reboot is exactly when the node set may have changed.
resetClient();
resetObjectInfoCache();
return {
stopped: true,
started: true,
ready: true,
readiness,
message: `ComfyUI rebooted via ComfyUI-Manager and came back ready (${readiness.waited_ms}ms) — ` +
"remote/supervised restart.",
};
}
export async function restartComfyUI() {
if (isRemoteMode()) {
// Remote target: can't process-control it, but a Manager HTTP reboot brings
// back a self-supervised ComfyUI (e.g. the tunnelled Desktop app).
return restartRemoteViaManager();
}
logger.info("Restarting ComfyUI...");
// Preflight: resolve the RUNNING instance and confirm we can relaunch it
// BEFORE stopping anything. A restart must be atomic-ish — if the relaunch
// command can't be built/validated (stale COMFYUI_PATH, unknown Desktop exe),
// refuse and leave the server up rather than take it down with no way back
// (issues #368/#370).
const info = await acquireProcessInfo();
if (!info) {
return {
stopped: false,
started: false,
message: `No ComfyUI process found on port ${config.resolvedPort} to restart. Is ComfyUI running?`,
};
}
const relaunch = assessRelaunch(info);
if (!relaunch.ok) {
return {
stopped: false,
started: false,
message: `Refusing to restart: ${relaunch.reason} ComfyUI was left running (not stopped) ` +
"so you don't lose the server. Fix the launch path (e.g. COMFYUI_PATH) and try again.",
};
}
// Stop — hand it the pre-validated info so the relaunch details (incl. the
// resolved Desktop exe) survive into startComfyUI's lastProcessInfo.
const stopResult = await stopComfyUI(info);
if (!stopResult.stopped) {
return {
stopped: false,
started: false,
message: `Could not stop ComfyUI: ${stopResult.message}`,
};
}
// Brief pause to let OS fully release resources
await sleep(1000);
// Start
const startResult = await startComfyUI();
if (!startResult.started) {
return {
stopped: true,
started: false,
ready: startResult.ready,
readiness: startResult.readiness,
message: `ComfyUI was stopped but could not be started: ${startResult.message}`,
auto_restart: startResult.auto_restart,
spawn_error: startResult.spawn_error,
};
}
return {
stopped: true,
started: true,
ready: startResult.ready,
readiness: startResult.readiness,
message: `ComfyUI restarted successfully. ${startResult.message}`,
auto_restart: startResult.auto_restart,
};
}
export const __processControlTestHooks = {
reset() {
detachSupervisor();
lastProcessInfo = null;
supervisorRestartCount = 0;
supervisorWindowStartedAt = 0;
supervisorGaveUp = false;
remoteRebootTimingOverride = null;
},
setLastProcessInfo(info) {
lastProcessInfo = info;
},
/** Inject fast remote-reboot timing so tests don't wait the real ~120s budget. */
setRemoteRebootTimingForTests(timing) {
remoteRebootTimingOverride = timing;
},
};
//# sourceMappingURL=process-control.js.map