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
feat(create): ein zur Laufzeit gestorbenes ComfyUI wird selbst neu gestartet
Davidf0dc1a5caad7
diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.tsindex 292223e9..edd64812 100644--- a/src/hooks/useCreate.ts+++ b/src/hooks/useCreate.ts@@ -39,6 +39,10 @@ import {type RenderEviction,} from '../api/vram-handoff'import { cpuCauseSuffix } from '../lib/render-budget'+import { backendCall } from '../api/backend'+import {+ ensureComfyForRender, comfyGuardMessage, type ComfyGuardStatus,+} from '../lib/comfy-restart-guard'import {comfyWS, CLIENT_ID,type ComfyWSEvent,@@ -777,13 +781,32 @@ export function useCreate() {}}- const isRunning = await checkComfyConnection()- if (!isRunning) {- setError('ComfyUI is not running. Wait for it to start.')+ // R16 Befund 5: this used to be a bare probe with the line "ComfyUI is not+ // running. Wait for it to start." Nothing was waiting to start it. LU+ // starts ComfyUI at app launch and never again, so a ComfyUI killed+ // mid-session stayed dead, and the box sat on that sentence for ten+ // minutes with port 8188 shut. If LU started it, LU restarts it, and if it+ // is not LU's to start, the line says so instead of promising an actor+ // that does not exist.+ //+ // The waiting area is opened BEFORE the guard runs, because a restart can+ // take a minute and the line explaining it has to be somewhere the user+ // can read it.+ setIsGenerating(true)+ setProgress(0, 'Checking ComfyUI...')+ const guard = await ensureComfyForRender({+ probe: () => checkComfyConnection(),+ status: () => backendCall<ComfyGuardStatus>('comfyui_status').catch(() => null),+ start: async () => { await backendCall('start_comfyui') },+ onProgress: (line) => setProgress(0, line),+ })+ if (guard === 'unmanaged' || guard === 'failed') {+ setIsGenerating(false)+ setProgress(0)+ setError(comfyGuardMessage(guard))return}- setIsGenerating(true)setProgress(0, 'Preparing workflow...')abortRef.current = new AbortController()diff --git a/src/lib/__tests__/comfy-restart-guard.test.ts b/src/lib/__tests__/comfy-restart-guard.test.tsnew file mode 100644index 00000000..6f9362a1--- /dev/null+++ b/src/lib/__tests__/comfy-restart-guard.test.ts@@ -0,0 +1,151 @@+/**+ * R16 Befund 5, measured on the Windows box (2026-08-30): ComfyUI was killed+ * while the app kept running. Create then answered "ComfyUI is not running.+ * Wait for it to start." on every press, and nothing ever started it. Ten+ * minutes later port 8188 was still shut. LU starts ComfyUI at app launch and+ * nowhere else, so the sentence promised an actor that did not exist.+ *+ * House rule: self healing before an error message.+ *+ * Run: npx vitest run src/lib/__tests__/comfy-restart-guard.test.ts+ */+import { describe, it, expect, vi } from 'vitest'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'++import {+ ensureComfyForRender, comfyIsManaged, comfyGuardMessage, RESTARTING_LINE,+ RESTART_ATTEMPTS, type ComfyGuardStatus,+} from '../comfy-restart-guard'++const here = dirname(fileURLToPath(import.meta.url))+const repo = resolve(here, '../../..')+const read = (rel: string) => readFileSync(resolve(repo, rel), 'utf8')++const managed: ComfyGuardStatus = { isLocal: true, found: true, complete: true, running: false }++/** A probe that answers false a few times and then true, like a booting port. */+const portUpAfter = (n: number) => {+ let calls = 0+ return vi.fn(async () => ++calls > n)+}++const noWait = async () => {}++describe('what counts as ours to restart', () => {+ it('a local, found, complete install is ours', () => {+ expect(comfyIsManaged(managed)).toBe(true)+ })++ it('NEGATIVE: a remote host, a missing install and a carcass are not', () => {+ expect(comfyIsManaged({ ...managed, isLocal: false })).toBe(false)+ expect(comfyIsManaged({ ...managed, found: false })).toBe(false)+ // GH #98: the install is there but torch is broken. Starting it again only+ // reproduces the same crash.+ expect(comfyIsManaged({ ...managed, complete: false })).toBe(false)+ expect(comfyIsManaged(null)).toBe(false)+ })+})++describe('the guard in front of a render', () => {+ it('a running ComfyUI is left alone, and nothing is started', async () => {+ const start = vi.fn()+ const out = await ensureComfyForRender({+ probe: async () => true, status: async () => managed, start, wait: noWait,+ })+ expect(out).toBe('running')+ expect(start).not.toHaveBeenCalled()+ })++ it('a ComfyUI that died mid session is started again (Befund 5)', async () => {+ const start = vi.fn(async () => {})+ const lines: string[] = []+ const out = await ensureComfyForRender({+ probe: portUpAfter(3), status: async () => managed, start, wait: noWait,+ onProgress: (l) => lines.push(l),+ })+ expect(out).toBe('restarted')+ expect(start).toHaveBeenCalledTimes(1)+ // and it said what it was doing, with a counter that moves+ expect(lines[0]).toBe(RESTARTING_LINE)+ expect(lines.some((l) => /^Restarting ComfyUI\.\.\. \d+s$/.test(l))).toBe(true)+ })++ it('a start already under way is waited out, never doubled', async () => {+ // Two ComfyUI processes on one port is worse than none.+ const start = vi.fn()+ const out = await ensureComfyForRender({+ probe: portUpAfter(2), status: async () => ({ ...managed, starting: true }), start,+ wait: noWait,+ })+ expect(out).toBe('running')+ expect(start).not.toHaveBeenCalled()+ })++ it('NEGATIVE: a ComfyUI that is not ours is not touched, and the line says so', async () => {+ const start = vi.fn()+ const out = await ensureComfyForRender({+ probe: async () => false, status: async () => ({ ...managed, isLocal: false }), start,+ wait: noWait,+ })+ expect(out).toBe('unmanaged')+ expect(start).not.toHaveBeenCalled()+ const msg = comfyGuardMessage('unmanaged')+ expect(msg).toMatch(/not managed by LU/)+ // It must not promise that something is on its way.+ expect(msg).not.toMatch(/wait for it to start/i)+ })++ it('NEGATIVE: a ComfyUI that will not come up is tried a bounded number of times', async () => {+ // A crash on boot must not turn one click into an endless restart loop.+ const start = vi.fn(async () => {})+ const out = await ensureComfyForRender({+ probe: async () => false, status: async () => managed, start, wait: noWait, rounds: 2,+ })+ expect(out).toBe('failed')+ expect(start).toHaveBeenCalledTimes(RESTART_ATTEMPTS)+ expect(comfyGuardMessage('failed')).toMatch(/could not be restarted/)+ expect(comfyGuardMessage('failed')).not.toMatch(/wait for it to start/i)+ })++ it('a probe or status that throws does not take the render down with it', async () => {+ const out = await ensureComfyForRender({+ probe: async () => { throw new Error('proxy down') },+ status: async () => { throw new Error('no such command') },+ start: vi.fn(), wait: noWait,+ })+ // Nothing known about it, so nothing is claimed about it.+ expect(out).toBe('unmanaged')+ })++ it('a start command that will not even dispatch stops after the first try', async () => {+ const start = vi.fn(async () => { throw new Error('unknown command') })+ const out = await ensureComfyForRender({+ probe: async () => false, status: async () => managed, start, wait: noWait, rounds: 1,+ })+ expect(out).toBe('failed')+ expect(start).toHaveBeenCalledTimes(1)+ })+})++describe('the Create render uses the guard', () => {+ const src = read('src/hooks/useCreate.ts')++ it('the bare probe is gone and the guard stands in its place', () => {+ expect(src).toMatch(/const guard = await ensureComfyForRender\(\{/)+ expect(src).toMatch(/setError\(comfyGuardMessage\(guard\)\)/)+ })++ it('NEGATIVE: the empty promise is nowhere in the app any more', () => {+ expect(src).not.toContain('ComfyUI is not running. Wait for it to start.')+ })++ it('the waiting area is open while the restart runs, so the line can be read', () => {+ const openAt = src.indexOf("setProgress(0, 'Checking ComfyUI...')")+ const guardAt = src.indexOf('const guard = await ensureComfyForRender')+ expect(openAt).toBeGreaterThan(-1)+ expect(openAt).toBeLessThan(guardAt)+ expect(src).toMatch(/onProgress: \(line\) => setProgress\(0, line\)/)+ })+})diff --git a/src/lib/comfy-restart-guard.ts b/src/lib/comfy-restart-guard.tsnew file mode 100644index 00000000..bebd422f--- /dev/null+++ b/src/lib/comfy-restart-guard.ts@@ -0,0 +1,151 @@+/**+ * Start ComfyUI again when a render finds it gone.+ *+ * R16 Befund 5, measured on the Windows box (2026-08-30): ComfyUI was killed+ * while the app kept running. Every press of Create then answered "ComfyUI is+ * not running. Wait for it to start." and nothing ever started it. Ten minutes+ * later port 8188 was still shut. The sentence was not just unhelpful, it was+ * untrue: nobody was going to start it. The app boots ComfyUI itself at launch+ * (process.rs::auto_start_comfyui), and that is the one and only moment it+ * ever did, so a ComfyUI that dies later stays dead for the rest of the+ * session.+ *+ * House rule, self healing before an error message: if LU started it, LU can+ * start it again. The rules this file follows:+ *+ * - Only a ComfyUI LU could have started is restarted. A remote host and a+ * missing or half installed local one are somebody else's to fix, and+ * saying so beats pretending to work on it.+ * - A start that is already under way is waited out, never doubled. Two+ * ComfyUI processes on one port is a worse state than none.+ * - Attempts are bounded and spaced. A ComfyUI that crashes on boot must not+ * turn one click into an endless restart loop.+ * - Every state has its own words, and every one of them says what is+ * happening or what the user has to do. No line promises an actor that+ * does not exist.+ */++/** The fields of `comfyui_status` this guard reads. */+export interface ComfyGuardStatus {+ /** The port answers. */+ running?: boolean+ /** A process is alive but has not bound the port yet. */+ starting?: boolean+ /** The configured host is this machine. A remote ComfyUI is not ours. */+ isLocal?: boolean+ /** An install was found on disk. */+ found?: boolean+ /** That install is usable (torch reachable), not a carcass. */+ complete?: boolean+}++/** How the guard left things. Every one of them is an answer, not a shrug. */+export type ComfyGuardOutcome =+ /** It was up, or it came up on its own while we watched. */+ | 'running'+ /** It was down, we started it, and the port answered. */+ | 'restarted'+ /** Not ours to start: a remote host, or no usable local install. */+ | 'unmanaged'+ /** Ours, we tried, and it did not come up. */+ | 'failed'++/** How many starts one click may cost. */+export const RESTART_ATTEMPTS = 3+/** Rounds of `RESTART_DELAY_MS` spent waiting for the port after each start. */+export const RESTART_ROUNDS = 30+export const RESTART_DELAY_MS = 2000+/** The pause before a second and third attempt. Index 0 is the first try. */+export const RESTART_BACKOFF_MS = [0, 3000, 10_000]++const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))++/**+ * Is this a ComfyUI LU is allowed to start.+ *+ * All three have to hold. `isLocal` false is a ComfyUI on another machine,+ * `found` false is nothing to start, and `complete` false is the carcass case+ * from GH #98, where starting it only produces the same crash again.+ */+export function comfyIsManaged(status: ComfyGuardStatus | null): boolean {+ if (!status) return false+ return status.isLocal === true && status.found === true && status.complete === true+}++/**+ * What to tell the user when the guard could not get ComfyUI up.+ *+ * Both lines name the next move. The unmanaged one does not claim LU is+ * working on it, because LU is not.+ */+export function comfyGuardMessage(outcome: 'unmanaged' | 'failed'): string {+ return outcome === 'unmanaged'+ ? 'ComfyUI is not running, and this one is not managed by LU. Start it yourself, or set it up under Settings, AI Backends.'+ : 'ComfyUI is not running and could not be restarted. See Settings, AI Backends for what it said on the way down.'+}++/** The line shown while the guard is working. Said once, so tests can hold it. */+export const RESTARTING_LINE = 'Restarting ComfyUI...'++/**+ * Make sure ComfyUI is up, starting it if it is ours and it is down.+ *+ * `probe` is the port check, `status` is `comfyui_status`, `start` is+ * `start_comfyui`. `onProgress` gets a line for every second of waiting, so a+ * minute of booting never looks frozen (the same reason CreateContext's+ * startAndAwait ticks its counter).+ */+export async function ensureComfyForRender(deps: {+ probe: () => Promise<boolean>+ status: () => Promise<ComfyGuardStatus | null>+ start: () => Promise<void>+ onProgress?: (line: string) => void+ wait?: (ms: number) => Promise<void>+ attempts?: number+ rounds?: number+ delayMs?: number+}): Promise<ComfyGuardOutcome> {+ const { probe, status, start } = deps+ const wait = deps.wait ?? sleep+ const attempts = deps.attempts ?? RESTART_ATTEMPTS+ const rounds = deps.rounds ?? RESTART_ROUNDS+ const delayMs = deps.delayMs ?? RESTART_DELAY_MS+ const say = deps.onProgress ?? (() => {})++ if (await probe().catch(() => false)) return 'running'++ const s = await status().catch(() => null)++ // Already on its way up, from the app's own boot or an earlier click. Wait+ // it out rather than starting a second process on the same port.+ if (s?.starting === true) {+ say(RESTARTING_LINE)+ for (let i = 0; i < rounds; i++) {+ await wait(delayMs)+ say(`${RESTARTING_LINE} ${(i + 1) * Math.round(delayMs / 1000)}s`)+ if (await probe().catch(() => false)) return 'running'+ }+ return 'failed'+ }++ if (!comfyIsManaged(s)) return 'unmanaged'++ for (let attempt = 0; attempt < attempts; attempt++) {+ const backoff = RESTART_BACKOFF_MS[attempt] ?? RESTART_BACKOFF_MS[RESTART_BACKOFF_MS.length - 1]+ if (backoff > 0) await wait(backoff)+ say(RESTARTING_LINE)+ try {+ await start()+ } catch {+ // A start that will not even dispatch is not going to dispatch on the+ // next round either.+ return 'failed'+ }+ for (let i = 0; i < rounds; i++) {+ await wait(delayMs)+ say(`${RESTARTING_LINE} ${(i + 1) * Math.round(delayMs / 1000)}s`)+ if (await probe().catch(() => false)) return 'restarted'+ }+ }+ return 'failed'+}