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(create): a busy ComfyUI is not a stalled one, and a late result lands

purpleeec223379a28
diff --git a/src/api/comfyui.ts b/src/api/comfyui.ts
index 08208bc7..6dc10771 100644
--- a/src/api/comfyui.ts
+++ b/src/api/comfyui.ts
@@ -2465,15 +2465,23 @@ export async function getHistory(promptId: string): Promise<ComfyHistoryEntry |
* not a stall — only silence from BOTH the socket and the queue aborts.
* Queue entries are `[number, prompt_id, ...]` tuples. */
export async function isPromptQueued(promptId: string): Promise<boolean> {
+ return (await promptQueueState(promptId)) === 'queued'
+}
+
+/** Like isPromptQueued, but says when ComfyUI gave no answer. A busy ComfyUI
+ * can leave HTTP unanswered for minutes (I1, 12 GB box: a Z-Image VAE decode
+ * through shared memory, 22 min), and "no answer" is not "gone": only
+ * 'gone' lets the Create watchdog call a render stalled. */
+export async function promptQueueState(promptId: string): Promise<'queued' | 'gone' | 'unknown'> {
try {
const res = await localFetch(comfyuiUrl('/queue'), { timeoutMs: COMFY_POLL_TIMEOUT_MS })
- if (!res.ok) return false
+ if (!res.ok) return 'unknown'
const q = await res.json()
const inList = (list: unknown) => Array.isArray(list)
&& list.some((e) => Array.isArray(e) && e[1] === promptId)
- return inList(q.queue_running) || inList(q.queue_pending)
+ return inList(q.queue_running) || inList(q.queue_pending) ? 'queued' : 'gone'
} catch {
- return false
+ return 'unknown'
}
}
diff --git a/src/hooks/__tests__/useCreate-late-result.test.ts b/src/hooks/__tests__/useCreate-late-result.test.ts
new file mode 100644
index 00000000..abc1812c
--- /dev/null
+++ b/src/hooks/__tests__/useCreate-late-result.test.ts
@@ -0,0 +1,172 @@
+// @vitest-environment jsdom
+/**
+ * I1 on the 12 GB box (30.10.2026): a second Z-Image bf16 run took 22 min.
+ * Its VAE decode went through shared memory and ComfyUI left HTTP unanswered
+ * for all of it; LU called the run stalled at 20 min and the four finished
+ * pictures never reached the gallery. Through the real generate path, with
+ * ComfyUI simulated at the HTTP level (so the test reads the same before and
+ * after the fix):
+ * - a ComfyUI that does not answer is busy, not stalled;
+ * - a run LU did give up on still lands in the gallery when ComfyUI
+ * finishes it later, and its prompt is not taken off ComfyUI's queue.
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { renderHook, waitFor } from '@testing-library/react'
+
+type Listener = (event: { type: string; data: Record<string, unknown> }) => void
+const ws = vi.hoisted(() => ({ listener: null as Listener | null }))
+
+vi.mock('../../api/mlx-image', () => ({
+ isMlxImageHost: () => false,
+ isMlxImageModel: () => false,
+ mlxStatus: vi.fn(async () => ({ installed: false })),
+ listMlxImageModels: vi.fn(async () => []),
+ buildMlxImageModels: vi.fn(() => []),
+ mergeImageModels: vi.fn((a: unknown[]) => a),
+ mlxModelIdFor: vi.fn(() => ''),
+ generateMlxImageDataUrl: vi.fn(),
+}))
+vi.mock('../../api/cutout-model', async (orig) => ({
+ ...((await orig()) as Record<string, unknown>),
+ cutoutDownloadLine: vi.fn(async () => null),
+}))
+vi.mock('../../api/comfyui', async (orig) => ({
+ ...((await orig()) as Record<string, unknown>),
+ checkComfyConnection: vi.fn(async () => true),
+ submitWorkflow: vi.fn(async () => 'p1'),
+}))
+vi.mock('../../api/comfyui-ws', async (orig) => ({
+ ...((await orig()) as Record<string, unknown>),
+ CLIENT_ID: 'lu-test',
+ comfyWS: {
+ connect: vi.fn(async () => {}),
+ mark: () => 0,
+ onPreview: () => () => {},
+ on: (l: Listener) => { ws.listener = l; return () => { ws.listener = null } },
+ },
+}))
+vi.mock('../../api/vram-handoff', async (orig) => ({
+ ...((await orig()) as Record<string, unknown>),
+ evictChatBackendsForRender: vi.fn(async () => null),
+ restoreChatBackendsAfterRender: vi.fn(),
+}))
+vi.mock('../../api/dynamic-workflow', async (orig) => ({
+ ...((await orig()) as Record<string, unknown>),
+ buildDynamicWorkflow: vi.fn(async () => ({
+ '1': { class_type: 'LoadImage', inputs: { image: 'woman-b.png' } },
+ '2': { class_type: 'RMBG', inputs: { image: ['1', 0], model: 'RMBG-2.0' } },
+ '3': { class_type: 'SaveImage', inputs: { images: ['2', 0] } },
+ })),
+}))
+
+import { useCreate } from '../useCreate'
+import { useCreateStore } from '../../stores/createStore'
+import { useSettingsStore } from '../../stores/settingsStore'
+
+const MODEL = 'sd_turbo.safetensors'
+const MIN = 60_000
+
+/** What the simulated ComfyUI does with /queue and /history. */
+type Comfy = 'busy' | 'lost' | 'done'
+const comfy = { mode: 'busy' as Comfy, queueDeletes: 0 }
+
+const DONE = {
+ p1: {
+ status: { status_str: 'success', completed: true, messages: [] },
+ outputs: { '3': { images: [{ filename: 'late_00001_.png', subfolder: '', type: 'output' }] } },
+ },
+}
+
+function fakeFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
+ const url = String(input)
+ const json = (v: unknown) => Promise.resolve(new Response(JSON.stringify(v), { status: 200 }))
+ if (url.includes('/queue')) {
+ if (init?.method === 'POST') { comfy.queueDeletes += 1; return json({}) }
+ // A ComfyUI deep in a VAE decode through shared memory: no answer.
+ if (comfy.mode === 'busy') return Promise.reject(new TypeError('timed out'))
+ return json({ queue_running: [], queue_pending: [] })
+ }
+ if (url.includes('/history/')) {
+ if (comfy.mode === 'busy') return Promise.reject(new TypeError('timed out'))
+ return json(comfy.mode === 'done' ? DONE : {})
+ }
+ return json({})
+}
+
+beforeEach(() => {
+ vi.useFakeTimers({ shouldAdvanceTime: true, toFake: ['setInterval', 'clearInterval', 'Date'] })
+ vi.stubGlobal('fetch', vi.fn(fakeFetch))
+ ws.listener = null
+ comfy.mode = 'busy'
+ comfy.queueDeletes = 0
+ useCreateStore.setState({
+ backend: 'local', isGenerating: false, error: null, gallery: [], promptHistory: [],
+ improvePrompt: false, cloudOp: null, utilityOp: null, mask: null, references: [],
+ selectedLoras: [], hiresFixEnabled: false, transparentBackground: false, seed: 42,
+ imageModel: MODEL, imageModelList: [{ name: MODEL, type: 'sd15' }],
+ caps: { rmbg: true },
+ } as never)
+ const s = useCreateStore.getState()
+ s.setIntent('removebg')
+ s.setSource({ filename: 'woman-b.png', url: 'data:image/png;base64,AA', width: 512, height: 512 } as never)
+})
+
+afterEach(() => {
+ vi.unstubAllGlobals()
+ vi.useRealTimers()
+})
+
+async function startAndGoSilent() {
+ const { result } = renderHook(() => useCreate())
+ const done = result.current.generate()
+ await waitFor(() => {
+ const st = useCreateStore.getState()
+ if (st.error) throw new Error(`run ended: ${st.error}`)
+ expect(ws.listener).not.toBeNull()
+ })
+ return { done }
+}
+
+async function silence(minutes: number) {
+ for (let t = 0; t < minutes * MIN; t += 15_000) {
+ await vi.advanceTimersByTimeAsync(15_000)
+ }
+}
+
+const lateFiles = () => useCreateStore.getState().gallery.map((g) => g.filename)
+
+describe('a ComfyUI too busy to answer (I1, 22 min Z-Image on 12 GB)', () => {
+ it('is not called stalled at the 20 minute limit, and its pictures arrive when it answers again', async () => {
+ useSettingsStore.setState((s) => ({ settings: { ...s.settings, imageGenTimeoutMinutes: 20 } }))
+ const { done } = await startAndGoSilent()
+ await silence(23)
+ expect(useCreateStore.getState().error).toBeNull()
+ expect(useCreateStore.getState().isGenerating).toBe(true)
+ // The decode ends at 22-23 min and ComfyUI answers again.
+ comfy.mode = 'done'
+ await silence(0.5)
+ await done
+ expect(lateFiles()).toEqual(['late_00001_.png'])
+ expect(useCreateStore.getState().error).toBeNull()
+ }, 60_000)
+})
+
+describe('a run LU gave up on', () => {
+ it('still lands in the gallery when ComfyUI finishes it later, and its prompt is left alone', async () => {
+ useSettingsStore.setState((s) => ({ settings: { ...s.settings, imageGenTimeoutMinutes: 2 } }))
+ comfy.mode = 'lost'
+ const { done } = await startAndGoSilent()
+ await silence(3)
+ await done
+ const error = useCreateStore.getState().error ?? ''
+ expect(error).toMatch(/Generation stalled: no progress from ComfyUI for 2 minutes\./)
+ expect(error).toMatch(/lands in your gallery/)
+ expect(comfy.queueDeletes).toBe(0)
+ expect(lateFiles()).toEqual([])
+ // ComfyUI finishes it after all.
+ comfy.mode = 'done'
+ await silence(1)
+ expect(lateFiles()).toEqual(['late_00001_.png'])
+ expect(useCreateStore.getState().error).toBeNull()
+ }, 60_000)
+})
diff --git a/src/hooks/__tests__/useCreate-stall-limit-reads-the-setting.test.ts b/src/hooks/__tests__/useCreate-stall-limit-reads-the-setting.test.ts
index 85f95bc6..f1a85556 100644
--- a/src/hooks/__tests__/useCreate-stall-limit-reads-the-setting.test.ts
+++ b/src/hooks/__tests__/useCreate-stall-limit-reads-the-setting.test.ts
@@ -31,6 +31,7 @@ vi.mock('../../api/comfyui', async (orig) => ({
checkComfyConnection: vi.fn(async () => true),
submitWorkflow: vi.fn(async () => 'p1'),
isPromptQueued: vi.fn(async () => false),
+ promptQueueState: vi.fn(async () => 'gone'),
getHistory: vi.fn(async () => null),
}))
vi.mock('../../api/comfyui-ws', async (orig) => ({
@@ -127,21 +128,21 @@ describe('the Create stall watchdog', () => {
describe('a run ComfyUI still holds (d308-a)', () => {
it('is not called stalled at a 1 minute limit while it sits in the queue, and the message says "1 minute"', async () => {
const comfy = await import('../../api/comfyui')
- const queued = vi.mocked(comfy.isPromptQueued)
+ const queued = vi.mocked(comfy.promptQueueState)
// A long VAE decode on the Windows box: no event for 100 s, the prompt
// still running in ComfyUI. At a 1 minute limit it was dropped.
- queued.mockResolvedValue(true)
+ queued.mockResolvedValue('queued')
useSettingsStore.setState((s) => ({ settings: { ...s.settings, imageGenTimeoutMinutes: 1 } }))
const { done } = await startAndGoSilent()
await silence(4)
expect(useCreateStore.getState().error).toBeNull()
expect(useCreateStore.getState().isGenerating).toBe(true)
// Then ComfyUI loses it: gone from the queue, no event, no history.
- queued.mockResolvedValue(false)
+ queued.mockResolvedValue('gone')
await silence(2)
expect(useCreateStore.getState().error ?? '').toMatch(/Generation stalled: no progress from ComfyUI for 1 minute\./)
await done
- queued.mockResolvedValue(false)
+ queued.mockResolvedValue('gone')
}, 60_000)
})
diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.ts
index 6596a4b7..90b76e86 100644
--- a/src/hooks/useCreate.ts
+++ b/src/hooks/useCreate.ts
@@ -23,6 +23,7 @@ import {
submitWorkflow,
getHistory,
isPromptQueued,
+ promptQueueState,
buildTxt2ImgWorkflow,
buildTxt2VidWorkflow,
legacyBuilderFits,
@@ -90,6 +91,7 @@ import { macEditReferenceRoom } from '../lib/mac-edit-memory'
import { getSharedMemoryGb } from '../lib/hardware'
import { resolveRunSeed } from '../lib/run-seed'
import { bumpSeed } from '../lib/render/image-count'
+import { collectLateResult, LATE_RESULT_PROMISE } from '../lib/render/late-result'
import {
clearTrainingSet, stageTrainingImage, startCharacterTraining,
characterTrainingStatus, cancelCharacterTraining,
@@ -1758,6 +1760,8 @@ export function useCreate() {
let renderEviction: RenderEviction | null = null
// B28: the live preview of a video run, taken down in the finally below.
let offPreview: (() => void) | null = null
+ // Set once the run is in ComfyUI: hands a finished history entry's files to the gallery.
+ let toGallery: ((outputs: ComfyHistoryEntry['outputs']) => boolean) | null = null
const handoff = elapsedLine((text) => setProgress(0, text), HANDOFF_LINE.freeing)
try {
renderEviction = await evictChatBackendsForRender((phase) => handoff.setLabel(HANDOFF_LINE[phase]))
@@ -2179,6 +2183,40 @@ export function useCreate() {
// customer blames his settings for a hardware switch.
void cpuRenderFacts()
+ // A finished history entry's files into the gallery. The heartbeat
+ // uses it, and so does the late look after a stall verdict.
+ const galleryFromOutputs = (outputs: ComfyHistoryEntry['outputs']): boolean => {
+ let found = false
+ for (const nodeId of Object.keys(outputs ?? {})) {
+ // Extract files from ANY keyed array, not just images/gifs/
+ // videos — custom save nodes post under other keys (audio,
+ // result, files, …); previously those outputs were dropped
+ // even though they existed on disk.
+ const files: ComfyUIOutput[] = extractComfyOutputFiles(outputs![nodeId])
+ for (const file of files) {
+ found = true
+ addToGallery({
+ id: uuid(), type: galleryTypeForFile(file.filename, mode),
+ filename: file.filename, subfolder: file.subfolder ?? '', comfyType: file.type ?? 'output',
+ prompt, ...improveFields, ...transparentFields(), negativePrompt, model: activeModel,
+ modelType: mode === 'image' ? imageModelType : (videoModelsList.find(m => m.name === activeModel)?.type ?? 'wan'),
+ seed: runSeed,
+ steps, cfgScale, sampler, scheduler, width: outputWidth, height: outputHeight, batchSize,
+ createdAt: Date.now(), builderUsed, intent, ...toolFields, ...(skippedNote ? { runNote: skippedNote } : {}),
+ })
+ }
+ }
+ return found
+ }
+ toGallery = galleryFromOutputs
+ // The stall verdict. ComfyUI has said the prompt is not in its queue
+ // and has no history for it, so there is nothing to take off the queue;
+ // its pictures are still looked for (lib/render/late-result).
+ const stalled = () => {
+ const message = `${renderStallMessage(maxTime)}${cpuCauseSuffix(lastCpuRenderFacts())} ${LATE_RESULT_PROMISE}`
+ return Object.assign(new Error(message), { lateLook: promptId })
+ }
+
if (useWS) {
// ── WebSocket-driven progress ──
await new Promise<void>((resolve, reject) => {
@@ -2218,15 +2256,22 @@ export function useCreate() {
if (stallCheck || Date.now() - lastActivity <= maxTime) return
stallCheck = true
try {
- if (await isPromptQueued(promptId).catch(() => false)) {
+ const state = await promptQueueState(promptId).catch(() => 'unknown' as const)
+ if (state === 'queued') {
lastActivity = Date.now()
return
}
+ // I1 (30.10.2026, 12 GB box): no answer at all is a ComfyUI too
+ // busy to serve HTTP (a 22 min VAE decode through shared
+ // memory), not a lost prompt. Only its own "not in my queue"
+ // ends the run; a ComfyUI that is really gone refuses the
+ // connection, and the heartbeat says so.
+ if (state === 'unknown') return
// Finished a moment ago: the heartbeat's next history poll
// collects the pictures, so this is no stall either.
if (completionHandled || await getHistory(promptId).catch(() => null)) return
cleanup()
- reject(new Error(`${renderStallMessage(maxTime)}${cpuCauseSuffix(lastCpuRenderFacts())}`))
+ reject(stalled())
} finally {
stallCheck = false
}
@@ -2265,28 +2310,7 @@ export function useCreate() {
? ((endMsg[1].timestamp - startMsg[1].timestamp) / 1000).toFixed(1) : null
setProgress(100, 'Complete!')
useCreateStore.getState().setLastGenTime(comfyTime ? `${comfyTime}s` : null)
- const outputs = history.outputs ?? {}
- let found = false
- for (const nodeId of Object.keys(outputs)) {
- // Extract files from ANY keyed array, not just images/gifs/
- // videos — custom save nodes post under other keys (audio,
- // result, files, …); previously those outputs were dropped
- // even though they existed on disk.
- const files: ComfyUIOutput[] = extractComfyOutputFiles(outputs[nodeId])
- for (const file of files) {
- found = true
- addToGallery({
- id: uuid(), type: galleryTypeForFile(file.filename, mode),
- filename: file.filename, subfolder: file.subfolder ?? '', comfyType: file.type ?? 'output',
- prompt, ...improveFields, ...transparentFields(), negativePrompt, model: activeModel,
- modelType: mode === 'image' ? imageModelType : (videoModelsList.find(m => m.name === activeModel)?.type ?? 'wan'),
- seed: runSeed,
- steps, cfgScale, sampler, scheduler, width: outputWidth, height: outputHeight, batchSize,
- createdAt: Date.now(), builderUsed, intent, ...toolFields, ...(skippedNote ? { runNote: skippedNote } : {}),
- })
- }
- }
- if (!found) setError('Generation completed but no output was produced.')
+ if (!galleryFromOutputs(history.outputs)) setError('Generation completed but no output was produced.')
resolve()
} else if (statusStr === 'error') {
completionHandled = true
@@ -2435,11 +2459,12 @@ export function useCreate() {
const elapsed = Date.now() - startTime
if (Date.now() - lastActivity > maxTime) {
- if (await isPromptQueued(promptId).catch(() => false)) {
+ const state = await promptQueueState(promptId).catch(() => 'unknown' as const)
+ if (state === 'queued') {
lastActivity = Date.now()
- } else {
+ } else if (state === 'gone' && !(await getHistory(promptId).catch(() => null))) {
if (pollRef.current) clearInterval(pollRef.current)
- reject(new Error(`${renderStallMessage(maxTime)}${cpuCauseSuffix(lastCpuRenderFacts())}`))
+ reject(stalled())
return
}
}
@@ -2527,9 +2552,22 @@ export function useCreate() {
// /interrupt here would kill the Create render or the external ComfyUI
// tab that is actually running.
const ownPromptId = useCreateStore.getState().currentPromptId
- if (ownPromptId) {
+ const lateLook = (err as { lateLook?: string } | null)?.lateLook
+ if (ownPromptId && !lateLook) {
try { await abandonPrompt(ownPromptId) } catch { /* best effort */ }
}
+ // A stall verdict is LU giving up, not ComfyUI: what it still delivers
+ // goes to the gallery, and the stall line goes away with it.
+ if (lateLook && toGallery) {
+ const errorShown = `Generation failed: ${err instanceof Error ? err.message : String(err)}`
+ const add = toGallery
+ collectLateResult(lateLook, {
+ getHistory,
+ onSuccess: (h) => {
+ if (add(h.outputs) && useCreateStore.getState().error === errorShown) useCreateStore.getState().setError(null)
+ },
+ })
+ }
if (err instanceof Error && err.message === 'Cancelled') {
// User cancelled, not an error
} else if (err instanceof Error && wasDeclined(err)) {
diff --git a/src/lib/__tests__/render-budget.test.ts b/src/lib/__tests__/render-budget.test.ts
index 7226065c..18dac001 100644
--- a/src/lib/__tests__/render-budget.test.ts
+++ b/src/lib/__tests__/render-budget.test.ts
@@ -427,6 +427,8 @@ describe('the CPU cause is wired into all five failure exits (Runde 12)', () =>
// They fire from a timer and cannot await, so the answer is fetched when
// the render starts and read from the cache here.
expect(create).toContain('void cpuRenderFacts()')
- expect(create.match(/cpuCauseSuffix\(lastCpuRenderFacts\(\)\)/g)?.length).toBe(2)
+ // One stall verdict (Q3, late result) that both watchdogs give.
+ expect(create.match(/cpuCauseSuffix\(lastCpuRenderFacts\(\)\)/g)?.length).toBe(1)
+ expect(create.match(/reject\(stalled\(\)\)/g)?.length).toBe(2)
})
})
diff --git a/src/lib/render/late-result.ts b/src/lib/render/late-result.ts
new file mode 100644
index 00000000..99563b50
--- /dev/null
+++ b/src/lib/render/late-result.ts
@@ -0,0 +1,74 @@
+/**
+ * A render the Create watchdog gave up on can still finish. I1 on the 12 GB
+ * box (30.10.2026): a second Z-Image bf16 run took 22 min, its VAE decode
+ * went through shared memory and ComfyUI left HTTP unanswered all that time;
+ * LU called it stalled at 20 min and the four finished pictures never
+ * reached the gallery. After a stall verdict LU keeps asking ComfyUI's
+ * history for that prompt for a while and hands over what still arrives.
+ */
+
+import { log } from '../logger'
+
+/** How long a given-up prompt is still looked for. */
+export const LATE_RESULT_WINDOW_MS = 60 * 60_000
+/** How often its history is asked for. */
+export const LATE_RESULT_EVERY_MS = 30_000
+
+/** The sentence after the stall message: the user knows the run is not lost yet. */
+export const LATE_RESULT_PROMISE = 'LU keeps looking for this render for another hour: if ComfyUI still finishes it, it lands in your gallery.'
+
+interface HistoryLike {
+ status?: { status_str?: string; completed?: boolean }
+}
+
+export interface LateResultOptions<H extends HistoryLike> {
+ getHistory: (promptId: string) => Promise<H | null>
+ /** The finished history entry: the caller adds its outputs. */
+ onSuccess: (history: H) => void
+ windowMs?: number
+ everyMs?: number
+}
+
+const watching = new Map<string, () => void>()
+
+/** Watch one prompt's history until it succeeds, fails or the window ends.
+ * Returns the stop. Asking twice for the same prompt keeps one watcher. */
+export function collectLateResult<H extends HistoryLike>(promptId: string, opts: LateResultOptions<H>): () => void {
+ watching.get(promptId)?.()
+ const windowMs = opts.windowMs ?? LATE_RESULT_WINDOW_MS
+ const started = Date.now()
+ let busy = false
+ const stop = () => {
+ clearInterval(timer)
+ if (watching.get(promptId) === stop) watching.delete(promptId)
+ }
+ const timer = setInterval(async () => {
+ if (busy) return
+ if (Date.now() - started > windowMs) {
+ stop()
+ log.info('render.late_result_none', { promptId })
+ return
+ }
+ busy = true
+ try {
+ const h = await opts.getHistory(promptId).catch(() => null)
+ if (!h) return
+ if (h.status?.status_str === 'success' || (h.status?.completed && h.status?.status_str !== 'error')) {
+ stop()
+ log.info('render.late_result', { promptId, afterMs: Date.now() - started })
+ opts.onSuccess(h)
+ } else if (h.status?.status_str === 'error') {
+ stop()
+ }
+ } finally {
+ busy = false
+ }
+ }, opts.everyMs ?? LATE_RESULT_EVERY_MS)
+ watching.set(promptId, stop)
+ return stop
+}
+
+/** Is LU still looking for this prompt? */
+export function lateResultPending(promptId: string): boolean {
+ return watching.has(promptId)
+}