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): der erste Render nach App-Start verliert seine Ladetexte nicht mehr

Davida90e251a3b13
diff --git a/src/api/__tests__/ws-first-render-loses-nothing.test.ts b/src/api/__tests__/ws-first-render-loses-nothing.test.ts
new file mode 100644
index 00000000..e63b82e0
--- /dev/null
+++ b/src/api/__tests__/ws-first-render-loses-nothing.test.ts
@@ -0,0 +1,135 @@
+/**
+ * R16 Befund 1, measured on the Windows box (2026-08-30): on the FIRST image
+ * render after an app start, not one loading line appeared. The waiting area
+ * went "Preparing workflow" (+0.8 s), "Building workflow" (+9.1 s),
+ * "Submitting to ComfyUI" (+9.9 s), "Queued" (+14.1 s) and then said nothing
+ * until +34 s. From the SECOND render on, "Loading VAE", "Loading text
+ * encoder" and "Loading the model into memory" all showed up. Restarting
+ * ComfyUI under a running app also showed them, so it hung on the app start,
+ * not on ComfyUI.
+ *
+ * Root cause, read off useCreate: `comfyWS.connect()` sat AFTER
+ * `submitWorkflow`. The first connect of an app run pays a dynamic import, two
+ * Tauri listener registrations and the Rust websocket handshake (up to 5 s),
+ * while ComfyUI starts executing the moment the submit lands and addresses
+ * this run's frames at our client id alone. ComfyUI buffers nothing, so those
+ * frames were destroyed, not delayed.
+ *
+ * Two things are proven here: the socket is opened before the submit, and a
+ * listener that registers a moment late is still told what it missed.
+ *
+ * Run: npx vitest run src/api/__tests__/ws-first-render-loses-nothing.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 { comfyWS, WS_REPLAY_BUFFER, type ComfyWSEvent } from '../comfyui-ws'
+
+const here = dirname(fileURLToPath(import.meta.url))
+const repo = resolve(here, '../../..')
+const read = (rel: string) => readFileSync(resolve(repo, rel), 'utf8')
+
+/** Push a frame through the client the way the transport does. */
+const feed = (event: ComfyWSEvent) => {
+ ;(comfyWS as unknown as { dispatch: (e: ComfyWSEvent) => void }).dispatch(event)
+}
+
+const executing = (node: string, prompt_id = 'p1'): ComfyWSEvent =>
+ ({ type: 'executing', data: { node, prompt_id } })
+
+const flush = () => new Promise<void>((r) => queueMicrotask(() => r()))
+
+describe('a listener that registers late (Befund 1)', () => {
+ it('is told the frames that arrived after its mark', async () => {
+ const mark = comfyWS.mark()
+ // The submit lands, ComfyUI walks straight into the loaders, and the
+ // caller is still building its closure.
+ feed(executing('1'))
+ feed(executing('2'))
+ const seen: string[] = []
+ const off = comfyWS.on((e) => { if (e.type === 'executing') seen.push(e.data.node!) }, mark)
+ await flush()
+ expect(seen).toEqual(['1', '2'])
+ // and it keeps listening for what comes next
+ feed(executing('3'))
+ expect(seen).toEqual(['1', '2', '3'])
+ off()
+ })
+
+ it('NEGATIVE: without a mark nothing is replayed, which is the old behaviour', async () => {
+ feed(executing('9'))
+ const seen: string[] = []
+ const off = comfyWS.on((e) => { if (e.type === 'executing') seen.push(e.data.node!) })
+ await flush()
+ expect(seen).toEqual([])
+ off()
+ })
+
+ it('NEGATIVE: a mark taken after the frames replays nothing older than itself', async () => {
+ feed(executing('a'))
+ const mark = comfyWS.mark()
+ const seen: string[] = []
+ const off = comfyWS.on((e) => { if (e.type === 'executing') seen.push(e.data.node!) }, mark)
+ await flush()
+ expect(seen).toEqual([])
+ off()
+ })
+
+ it('NEGATIVE: a listener removed before the replay runs is never called', async () => {
+ const mark = comfyWS.mark()
+ feed(executing('x'))
+ const listener = vi.fn()
+ const off = comfyWS.on(listener, mark)
+ off()
+ await flush()
+ expect(listener).not.toHaveBeenCalled()
+ })
+
+ it('the replay is not delivered inside the on() call itself', async () => {
+ // The caller writes `const off = comfyWS.on(...)` and its teardown closes
+ // over `off`. A replay delivered during the call would reach a teardown
+ // whose `off` is still in its temporal dead zone.
+ const mark = comfyWS.mark()
+ feed(executing('y'))
+ let duringTheCall = false
+ let assigned = false
+ const off = comfyWS.on(() => { if (!assigned) duringTheCall = true }, mark)
+ assigned = true
+ await flush()
+ expect(duringTheCall).toBe(false)
+ off()
+ })
+
+ it('the buffer is bounded', () => {
+ const mark = comfyWS.mark()
+ for (let i = 0; i < WS_REPLAY_BUFFER + 50; i++) feed(executing(String(i)))
+ const buf = (comfyWS as unknown as { buffer: unknown[] }).buffer
+ expect(buf.length).toBe(WS_REPLAY_BUFFER)
+ void mark
+ })
+})
+
+describe('the Create render opens the socket before it submits', () => {
+ const src = read('src/hooks/useCreate.ts')
+ const connectAt = src.indexOf('await comfyWS.connect(3000)')
+ const markAt = src.indexOf('wsMark = comfyWS.mark()')
+ const submitAt = src.indexOf('await submitWorkflow(workflow, CLIENT_ID)')
+
+ it('connect and mark both come before the submit', () => {
+ expect(connectAt).toBeGreaterThan(-1)
+ expect(markAt).toBeGreaterThan(-1)
+ expect(submitAt).toBeGreaterThan(-1)
+ expect(connectAt).toBeLessThan(submitAt)
+ expect(markAt).toBeLessThan(submitAt)
+ })
+
+ it('the run listener is handed the mark, so the gap to the submit is replayed', () => {
+ expect(src).toMatch(/\}, wsMark\)/)
+ })
+
+ it('NEGATIVE: the connect is not attempted a second time after the submit', () => {
+ expect(src.indexOf('await comfyWS.connect(3000)', submitAt)).toBe(-1)
+ })
+})
diff --git a/src/api/comfyui-ws.ts b/src/api/comfyui-ws.ts
index be29716c..192096e6 100644
--- a/src/api/comfyui-ws.ts
+++ b/src/api/comfyui-ws.ts
@@ -52,9 +52,23 @@ export const LU_CLIENT_PREFIX = 'lu-'
/** Shared client ID used for both WS connection and workflow submission */
export const CLIENT_ID = `${LU_CLIENT_PREFIX}${uuid()}`
+/**
+ * How many frames the replay buffer keeps.
+ *
+ * A render's own events are a handful (`execution_start`, one `executing` per
+ * node, one `progress` per step, `execution_complete`), so the only way to
+ * push a run's opening events out of a 400 entry window is a long sampling run
+ * whose steps have already been seen. Which is exactly when nothing needs
+ * replaying.
+ */
+export const WS_REPLAY_BUFFER = 400
+
class ComfyWSClient {
private ws: WebSocket | null = null
private listeners = new Set<ComfyWSListener>()
+ /** The last frames that came in, newest last, for `on(listener, since)`. */
+ private buffer: { seq: number; event: ComfyWSEvent }[] = []
+ private seq = 0
private reconnectTimer: ReturnType<typeof setTimeout> | null = null
private reconnectDelay = 1000
private maxReconnectDelay = 30000
@@ -115,12 +129,7 @@ class ComfyWSClient {
await listen<string>('comfy-ws-message', (ev) => {
try {
const msg = JSON.parse(ev.payload)
- if (msg.type && msg.data) {
- const event = msg as ComfyWSEvent
- for (const listener of this.listeners) {
- listener(event)
- }
- }
+ if (msg.type && msg.data) this.dispatch(msg as ComfyWSEvent)
} catch { /* ignore non-JSON messages */ }
})
await listen('comfy-ws-closed', () => {
@@ -158,12 +167,7 @@ class ComfyWSClient {
this.ws.onmessage = (ev) => {
try {
const msg = JSON.parse(ev.data)
- if (msg.type && msg.data) {
- const event = msg as ComfyWSEvent
- for (const listener of this.listeners) {
- listener(event)
- }
- }
+ if (msg.type && msg.data) this.dispatch(msg as ComfyWSEvent)
} catch { /* ignore non-JSON messages */ }
}
@@ -210,8 +214,53 @@ class ComfyWSClient {
}, this.reconnectDelay)
}
- on(listener: ComfyWSListener) {
+ /** Hand one frame to everyone listening, and keep it for a late listener. */
+ private dispatch(event: ComfyWSEvent) {
+ this.buffer.push({ seq: ++this.seq, event })
+ if (this.buffer.length > WS_REPLAY_BUFFER) {
+ this.buffer.splice(0, this.buffer.length - WS_REPLAY_BUFFER)
+ }
+ for (const listener of this.listeners) {
+ listener(event)
+ }
+ }
+
+ /**
+ * A token for "everything from here on", to be handed back to `on`.
+ *
+ * R16 Befund 1: a render's caller cannot register its listener until the
+ * submit has told it which prompt id to filter on, and ComfyUI starts
+ * executing the moment the submit lands. Marking before the submit and
+ * replaying after it closes that window instead of hoping to win the race.
+ */
+ mark(): number {
+ return this.seq
+ }
+
+ /**
+ * Listen. With `since` from `mark()`, the frames that arrived in between are
+ * handed over, in the order they came in.
+ *
+ * The replay runs in a microtask, not inline: a caller typically writes
+ * `const off = comfyWS.on(...)` and its own teardown closes over `off`, so a
+ * replayed completion or error delivered DURING the call would reach a
+ * teardown whose `off` is not assigned yet. The microtask also means a
+ * listener that is removed again straight away is never replayed to.
+ */
+ on(listener: ComfyWSListener, since?: number) {
this.listeners.add(listener)
+ if (typeof since === 'number') {
+ const held = this.buffer.filter((b) => b.seq > since)
+ if (held.length) {
+ queueMicrotask(() => {
+ if (!this.listeners.has(listener)) return
+ for (const b of held) {
+ if (!this.listeners.has(listener)) return
+ listener(b.event)
+ }
+ })
+ }
+ }
return () => { this.listeners.delete(listener) }
}
diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.ts
index 31054193..292223e9 100644
--- a/src/hooks/useCreate.ts
+++ b/src/hooks/useCreate.ts
@@ -1023,6 +1023,34 @@ export function useCreate() {
outputHeight = hires.height
}
+ // Open the progress socket BEFORE the submit, and remember where the
+ // stream stands, because ComfyUI starts executing the instant the submit
+ // lands and addresses this run's frames at our client id alone.
+ //
+ // R16 Befund 1: the connect used to sit AFTER the submit. On the first
+ // render of an app run that costs a dynamic import, two Tauri listener
+ // registrations and the Rust websocket handshake, and every frame
+ // ComfyUI sent in that window went to a socket that did not exist yet.
+ // ComfyUI buffers nothing, so the three load lines (model, text encoder,
+ // VAE) were simply gone, and the waiting area showed nothing at all
+ // until the render was 34 s old. From the second render on the socket
+ // was already up, the connect returned at once, and the lines appeared,
+ // which is why this only ever hit the first picture after a start.
+ //
+ // The mark closes the rest of the window: the listener below cannot be
+ // registered until the submit has returned the prompt id it filters on,
+ // so anything that arrives in between is replayed instead of raced for.
+ const maxTime = mode === 'video' ? 60 * 60 * 1000 : 20 * 60 * 1000
+ let useWS = false
+ let wsMark = 0
+ try {
+ await comfyWS.connect(3000)
+ useWS = true
+ wsMark = comfyWS.mark()
+ } catch {
+ console.warn('[useCreate] WebSocket unavailable, using polling fallback')
+ }
+
setProgress(10, 'Submitting to ComfyUI...')
let promptId: string
try {
@@ -1049,16 +1077,6 @@ export function useCreate() {
// customer blames his settings for a hardware switch.
void cpuRenderFacts()
- // Try WebSocket-driven progress, fall back to polling
- const maxTime = mode === 'video' ? 60 * 60 * 1000 : 20 * 60 * 1000
- let useWS = false
- try {
- await comfyWS.connect(3000)
- useWS = true
- } catch {
- console.warn('[useCreate] WebSocket unavailable, using polling fallback')
- }
-
if (useWS) {
// ── WebSocket-driven progress ──
await new Promise<void>((resolve, reject) => {
@@ -1178,6 +1196,8 @@ export function useCreate() {
removeListener()
}
+ // `wsMark` was taken before the submit, so the frames ComfyUI sent
+ // while this closure was being built are handed over first.
const removeListener = comfyWS.on((event: ComfyWSEvent) => {
// Only handle events for our prompt
if ('prompt_id' in event.data && event.data.prompt_id !== promptId) return
@@ -1257,7 +1277,7 @@ export function useCreate() {
break
}
}
- })
+ }, wsMark)
// Also check abort
abortCheck = setInterval(() => {