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.

feat(create): live preview while a video renders (B28)

purplee440fb22dcdf
diff --git a/src-tauri/src/commands/comfy_ws.rs b/src-tauri/src/commands/comfy_ws.rs
index 8787b8bd..66e976d0 100644
--- a/src-tauri/src/commands/comfy_ws.rs
+++ b/src-tauri/src/commands/comfy_ws.rs
@@ -12,16 +12,18 @@
//
// Receive-only by design: the frontend never sends application frames on this
// socket (see src/api/comfyui-ws.ts), so no send command is exposed. Binary
-// frames (live preview images) are skipped — the old direct-WS path dropped
-// them too (JSON.parse on a Blob throws → ignored). Host + port come from
+// frames: a live preview image (B28, 3.0.9) goes on as a `comfy-ws-preview`
+// event, everything else binary is dropped. Host + port come from
// AppState (same user-validated values the HTTP proxy allow-lists), never
// from the frontend, so this opens no new SSRF surface.
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
+use base64::Engine;
use futures_util::StreamExt;
use once_cell::sync::Lazy;
+use serde::Serialize;
use tauri::{AppHandle, Emitter, State};
use tokio_tungstenite::tungstenite::Message;
@@ -40,6 +42,37 @@ static CONN: Lazy<tokio::sync::Mutex<Option<ConnHandle>>> =
Lazy::new(|| tokio::sync::Mutex::new(None));
static NEXT_GEN: AtomicU64 = AtomicU64::new(1);
+/// A live preview from the sampler, as the WebView gets it (B28).
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct PreviewPayload {
+ pub mime: &'static str,
+ /// The image, base64.
+ pub data: String,
+}
+
+/// ComfyUI's PREVIEW_IMAGE frame (server.py `send_image`): a big-endian u32
+/// event type 1, a big-endian u32 image type (1 JPEG, 2 PNG), then the image.
+/// Anything else, including the metadata variant only sent to clients that
+/// announce it, is not a preview here.
+pub fn preview_payload(frame: &[u8]) -> Option<PreviewPayload> {
+ if frame.len() <= 8 {
+ return None;
+ }
+ let event = u32::from_be_bytes(frame[0..4].try_into().ok()?);
+ if event != 1 {
+ return None;
+ }
+ let mime = match u32::from_be_bytes(frame[4..8].try_into().ok()?) {
+ 1 => "image/jpeg",
+ 2 => "image/png",
+ _ => return None,
+ };
+ Some(PreviewPayload {
+ mime,
+ data: base64::engine::general_purpose::STANDARD.encode(&frame[8..]),
+ })
+}
+
/// Open (or replace) the proxied ComfyUI progress socket. Resolves once the
/// upstream handshake succeeded — the frontend treats resolution like
/// `ws.onopen` and rejection like `ws.onerror` (falls back to /history
@@ -90,8 +123,13 @@ pub async fn comfy_ws_connect(
Some(Ok(Message::Text(text))) => {
let _ = app.emit("comfy-ws-message", text.as_str());
}
+ Some(Ok(Message::Binary(bytes))) => {
+ if let Some(preview) = preview_payload(&bytes) {
+ let _ = app.emit("comfy-ws-preview", preview);
+ }
+ }
Some(Ok(Message::Close(_))) | Some(Err(_)) | None => break,
- // Binary previews, ping/pong, raw frames: intentionally dropped.
+ // Ping/pong, raw frames: intentionally dropped.
Some(Ok(_)) => {}
}
}
@@ -120,3 +158,30 @@ pub async fn comfy_ws_disconnect() -> Result<(), String> {
}
Ok(())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn frame(event: u32, kind: u32, image: &[u8]) -> Vec<u8> {
+ let mut v = event.to_be_bytes().to_vec();
+ v.extend_from_slice(&kind.to_be_bytes());
+ v.extend_from_slice(image);
+ v
+ }
+
+ #[test]
+ fn a_jpeg_preview_goes_on_as_base64() {
+ let p = preview_payload(&frame(1, 1, &[0xff, 0xd8, 0xff])).unwrap();
+ assert_eq!(p, PreviewPayload { mime: "image/jpeg", data: "/9j/".into() });
+ assert_eq!(preview_payload(&frame(1, 2, b"PNG")).unwrap().mime, "image/png");
+ }
+
+ #[test]
+ fn other_binary_frames_are_not_previews() {
+ assert!(preview_payload(&frame(4, 1, b"meta")).is_none());
+ assert!(preview_payload(&frame(1, 9, b"x")).is_none());
+ assert!(preview_payload(&frame(1, 1, b"")).is_none());
+ assert!(preview_payload(&[0, 0, 0]).is_none());
+ }
+}
diff --git a/src/api/__tests__/orphan-sweep.test.ts b/src/api/__tests__/orphan-sweep.test.ts
index 76b51c1d..5104bfef 100644
--- a/src/api/__tests__/orphan-sweep.test.ts
+++ b/src/api/__tests__/orphan-sweep.test.ts
@@ -119,7 +119,7 @@ describe('ownership marker and wiring', () => {
})
it('NEGATIVE CONTROL: the Create tab still submits under the same live id', () => {
- expect(read('../../hooks/useCreate.ts')).toContain('submitWorkflow(workflow, CLIENT_ID)')
+ expect(read('../../hooks/useCreate.ts')).toContain('submitWorkflow(workflow, CLIENT_ID,')
})
it('NEGATIVE CONTROL: the user Stop path and the G19-1 budget path still work by owner', () => {
diff --git a/src/api/__tests__/video-live-preview.test.tsx b/src/api/__tests__/video-live-preview.test.tsx
new file mode 100644
index 00000000..e6447815
--- /dev/null
+++ b/src/api/__tests__/video-live-preview.test.tsx
@@ -0,0 +1,92 @@
+// @vitest-environment jsdom
+/**
+ * B28 (3.0.9): Discord .molot, 28.10.2026, "a preview while the video
+ * renders, to stop early". ComfyUI can send a picture per sampling step, but
+ * it starts with previews off, LU never asked for them, and the desktop's
+ * socket proxy dropped every binary frame. Now a video run asks for them in
+ * its own prompt (extra_data.preview_method), the frame reaches the page, and
+ * the waiting area shows the newest one.
+ *
+ * Run: npx vitest run src/api/__tests__/video-live-preview.test.tsx
+ */
+import { describe, expect, it, vi, beforeEach } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import { render, screen, cleanup } from '@testing-library/react'
+
+const fetched = vi.hoisted(() => ({ bodies: [] as unknown[] }))
+vi.mock('../backend', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../backend')>()),
+ comfyuiUrl: (p: string) => `http://test${p}`,
+ localFetch: vi.fn(async (_url: string, init?: { body?: string }) => {
+ fetched.bodies.push(init?.body ? JSON.parse(init.body) : null)
+ return new Response(JSON.stringify({ prompt_id: 'p-1', node_errors: {} }), { status: 200 })
+ }),
+}))
+
+const { previewDataUrl } = await import('../comfyui-ws')
+const { submitWorkflow } = await import('../comfyui')
+const { GeneratingView } = await import('../../components/create/experimental/OutputView')
+const { useRenderPreviewStore } = await import('../../stores/renderPreviewStore')
+
+const frame = (event: number, kind: number, image: number[]) => {
+ const b = new Uint8Array(8 + image.length)
+ const v = new DataView(b.buffer)
+ v.setUint32(0, event)
+ v.setUint32(4, kind)
+ b.set(image, 8)
+ return b.buffer
+}
+
+describe('the preview frame', () => {
+ it('a JPEG or PNG preview becomes a data URL', () => {
+ expect(previewDataUrl(frame(1, 1, [0xff, 0xd8, 0xff]))).toBe('data:image/jpeg;base64,/9j/')
+ expect(previewDataUrl(frame(1, 2, [0x89, 0x50]))).toMatch(/^data:image\/png;base64,/)
+ })
+ it('any other binary frame is not a preview', () => {
+ expect(previewDataUrl(frame(4, 1, [1, 2]))).toBeNull()
+ expect(previewDataUrl(frame(1, 7, [1]))).toBeNull()
+ expect(previewDataUrl(new Uint8Array([0, 0, 0, 1]))).toBeNull()
+ })
+})
+
+describe('the prompt asks ComfyUI for previews', () => {
+ beforeEach(() => { fetched.bodies.length = 0 })
+ it('with previewMethod the prompt carries extra_data.preview_method', async () => {
+ await submitWorkflow({ '1': { class_type: 'SaveImage', inputs: {} } }, 'lu-x', { previewMethod: 'auto' })
+ expect(fetched.bodies[0]).toMatchObject({ client_id: 'lu-x', extra_data: { preview_method: 'auto' } })
+ })
+ it('without it nothing changes for a picture', async () => {
+ await submitWorkflow({ '1': { class_type: 'SaveImage', inputs: {} } }, 'lu-x')
+ expect(fetched.bodies[0]).not.toHaveProperty('extra_data')
+ })
+ it('Create asks for it on a video run, follows the previews and drops the last one at the end', () => {
+ const src = readFileSync(resolve(__dirname, '..', '..', 'hooks', 'useCreate.ts'), 'utf8')
+ expect(src).toMatch(/const livePreview = mode === 'video'/)
+ expect(src).toMatch(/offPreview = comfyWS\.onPreview\(\(url\) => useRenderPreviewStore\.getState\(\)\.setUrl\(url\)\)/)
+ expect(src).toMatch(/submitWorkflow\(workflow, CLIENT_ID, livePreview \? \{ previewMethod: 'auto' \} : \{\}\)/)
+ expect(src).toMatch(/offPreview\?\.\(\)\n\s+useRenderPreviewStore\.getState\(\)\.setUrl\(null\)/)
+ })
+ it('the desktop proxy passes preview frames on instead of dropping them', () => {
+ const rs = readFileSync(resolve(__dirname, '..', '..', '..', 'src-tauri', 'src', 'commands', 'comfy_ws.rs'), 'utf8')
+ expect(rs).toMatch(/Message::Binary\(bytes\)\)\) => \{\n\s+if let Some\(preview\) = preview_payload\(&bytes\)/)
+ const ws = readFileSync(resolve(__dirname, '..', 'comfyui-ws.ts'), 'utf8')
+ expect(ws).toMatch(/listen<[^>]*>\('comfy-ws-preview'/)
+ })
+})
+
+describe('the waiting area shows it', () => {
+ beforeEach(() => cleanup())
+ it('the newest preview, with what it is and what to do', () => {
+ useRenderPreviewStore.getState().setUrl('data:image/jpeg;base64,/9j/')
+ render(<GeneratingView />)
+ const fig = screen.getByTestId('render-live-preview')
+ expect(fig.querySelector('img')?.getAttribute('src')).toBe('data:image/jpeg;base64,/9j/')
+ expect(fig.textContent).toContain('Cancel if it is going the wrong way')
+ })
+ it('nothing while there is none', () => {
+ useRenderPreviewStore.getState().setUrl(null)
+ render(<GeneratingView />)
+ expect(screen.queryByTestId('render-live-preview')).toBeNull()
+ })
+})
diff --git a/src/api/__tests__/ws-first-render-loses-nothing.test.ts b/src/api/__tests__/ws-first-render-loses-nothing.test.ts
index e63b82e0..79d21623 100644
--- a/src/api/__tests__/ws-first-render-loses-nothing.test.ts
+++ b/src/api/__tests__/ws-first-render-loses-nothing.test.ts
@@ -115,7 +115,7 @@ 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)')
+ const submitAt = src.indexOf('await submitWorkflow(workflow, CLIENT_ID,')
it('connect and mark both come before the submit', () => {
expect(connectAt).toBeGreaterThan(-1)
diff --git a/src/api/comfyui-ws.ts b/src/api/comfyui-ws.ts
index bfe35c0e..c53474f5 100644
--- a/src/api/comfyui-ws.ts
+++ b/src/api/comfyui-ws.ts
@@ -25,6 +25,28 @@ export type ComfyWSEvent =
| { type: 'execution_cached'; data: { prompt_id: string; nodes: string[] } }
export type ComfyWSListener = (event: ComfyWSEvent) => void
+/** A live preview from the sampler, as a data URL (B28). */
+export type ComfyPreviewListener = (dataUrl: string) => void
+
+/**
+ * ComfyUI's PREVIEW_IMAGE frame as a data URL, or null for any other binary
+ * frame. Layout (server.py `send_image`): a big-endian u32 event type 1, a
+ * big-endian u32 image type (1 JPEG, 2 PNG), then the image. The desktop gets
+ * the same frame decoded by Rust (commands/comfy_ws.rs `preview_payload`).
+ */
+export function previewDataUrl(frame: ArrayBuffer | Uint8Array): string | null {
+ const bytes = frame instanceof Uint8Array ? frame : new Uint8Array(frame)
+ if (bytes.length <= 8) return null
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
+ if (view.getUint32(0) !== 1) return null
+ const kind = view.getUint32(4)
+ const mime = kind === 1 ? 'image/jpeg' : kind === 2 ? 'image/png' : null
+ if (!mime) return null
+ let text = ''
+ const image = bytes.subarray(8)
+ for (let i = 0; i < image.length; i += 0x8000) text += String.fromCharCode(...image.subarray(i, i + 0x8000))
+ return `data:${mime};base64,${btoa(text)}`
+}
// Loader node class types that indicate model loading. The GGUF loaders must
// be here too: without them a GGUF video run never shows "Loading model" and
@@ -69,6 +91,9 @@ export const WS_REPLAY_BUFFER = 400
class ComfyWSClient {
private ws: WebSocket | null = null
private listeners = new Set<ComfyWSListener>()
+ /** Previews are not kept for replay: only the newest one is ever shown,
+ * and 400 pictures in the buffer would be megabytes. */
+ private previewListeners = new Set<ComfyPreviewListener>()
/** The last frames that came in, newest last, for `on(listener, since)`. */
private buffer: { seq: number; event: ComfyWSEvent }[] = []
private seq = 0
@@ -135,6 +160,10 @@ class ComfyWSClient {
if (msg.type && msg.data) this.dispatch(msg as ComfyWSEvent)
} catch { /* ignore non-JSON messages */ }
})
+ await listen<{ mime?: string; data?: string }>('comfy-ws-preview', (ev) => {
+ const { mime, data } = ev.payload ?? {}
+ if (mime && data) this.dispatchPreview(`data:${mime};base64,${data}`)
+ })
await listen('comfy-ws-closed', () => {
// Upstream socket died (ComfyUI stopped/restarted) — mirror onclose.
if (!this._connected) return
@@ -157,6 +186,7 @@ class ComfyWSClient {
try {
this.ws = new WebSocket(`${comfyuiWsUrl()}?clientId=${CLIENT_ID}`)
+ this.ws.binaryType = 'arraybuffer'
this.ws.onopen = () => {
clearTimeout(timer)
@@ -168,6 +198,11 @@ class ComfyWSClient {
}
this.ws.onmessage = (ev) => {
+ if (ev.data instanceof ArrayBuffer) {
+ const preview = previewDataUrl(ev.data)
+ if (preview) this.dispatchPreview(preview)
+ return
+ }
try {
const msg = JSON.parse(ev.data)
if (msg.type && msg.data) this.dispatch(msg as ComfyWSEvent)
@@ -217,6 +252,17 @@ class ComfyWSClient {
}, this.reconnectDelay)
}
+ private dispatchPreview(dataUrl: string) {
+ for (const listener of this.previewListeners) listener(dataUrl)
+ }
+
+ /** Listen for live previews (B28). ComfyUI sends them only to the client
+ * that queued the prompt, and only when the prompt asked for them. */
+ onPreview(listener: ComfyPreviewListener) {
+ this.previewListeners.add(listener)
+ return () => { this.previewListeners.delete(listener) }
+ }
+
/** Hand one frame to everyone listening, and keep it for a late listener. */
private dispatch(event: ComfyWSEvent) {
this.buffer.push({ seq: ++this.seq, event })
diff --git a/src/api/comfyui.ts b/src/api/comfyui.ts
index e1d37d5c..08208bc7 100644
--- a/src/api/comfyui.ts
+++ b/src/api/comfyui.ts
@@ -2245,10 +2245,19 @@ async function findAnimateDiffModel(): Promise<string> {
// ─── Workflow Submission ───
-export async function submitWorkflow(workflow: ComfyApiGraph, clientId?: string): Promise<string> {
+export async function submitWorkflow(
+ workflow: ComfyApiGraph,
+ clientId?: string,
+ opts: { previewMethod?: 'auto' | 'latent2rgb' | 'taesd' } = {},
+): Promise<string> {
// Every run its own output names (comfyui-graph tagOutputPrefixes).
const payload: Record<string, unknown> = { prompt: tagOutputPrefixes(workflow, newRunTag()) }
if (clientId) payload.client_id = clientId
+ // B28: live previews for this prompt only. ComfyUI starts with previews off
+ // (--preview-method none) and takes a per-prompt override in extra_data
+ // since PR 11261 (2025-12-15, execution.py set_preview_method); an older
+ // one ignores the key and renders as before, without pictures.
+ if (opts.previewMethod) payload.extra_data = { preview_method: opts.previewMethod }
// Use localFetch (Rust proxy in Tauri, direct fetch in dev). The previous
// direct-only fetch broke for any ComfyUI not started by LU itself —
// `--enable-cors-header` is the LU spawn flag, but a user-run ComfyUI
diff --git a/src/components/create/experimental/OutputView.tsx b/src/components/create/experimental/OutputView.tsx
index 24ea58cc..885b6d30 100644
--- a/src/components/create/experimental/OutputView.tsx
+++ b/src/components/create/experimental/OutputView.tsx
@@ -1,4 +1,5 @@
import { itemHasAlpha } from '../../../lib/transparent-image'
+import { useRenderPreviewStore } from '../../../stores/renderPreviewStore'
import { Fragment, useEffect, useMemo, useState, type ReactNode } from 'react'
import { motion } from 'framer-motion'
import { Cpu, Sparkles, ImageDown, Maximize2, Download, Wand2, MonitorOff, AudioLines, Film, Trash2, UserRoundPlus } from 'lucide-react'
@@ -91,6 +92,8 @@ export function GeneratingView() {
const progressPhase = useCreateStore((s) => s.progressPhase)
const progressText = useCreateStore((s) => s.progressText)
const progress = useCreateStore((s) => s.progress)
+ // B28: the sampler's newest picture while a video renders.
+ const preview = useRenderPreviewStore((s) => s.url)
const isLoading = progressPhase === 'loading-model' || progressPhase === 'loading-clip' || progressPhase === 'loading-vae'
const beat = phaseBeat(progressPhase)
@@ -123,6 +126,14 @@ export function GeneratingView() {
</div>
</div>
<BatchQueue />
+ {preview && (
+ <figure className="flex flex-col items-center gap-1" data-testid="render-live-preview">
+ <img src={preview} alt="Live preview of the video being rendered" className="max-h-56 max-w-[22rem] rounded-lg border border-white/10 object-contain" />
+ <figcaption className="t-micro text-gray-500 text-center max-w-[22rem]">
+ Rough preview of the first frame, sharper with every step. Cancel if it is going the wrong way.
+ </figcaption>
+ </figure>
+ )}
<p className="t-body text-gray-300 tracking-wide">{progressText || 'Generating…'}</p>
{isLoading && !isMlxImageHost() && <ColdLoadLine />}
{progress > 0 && (
diff --git a/src/components/settings/HardwareSettings.tsx b/src/components/settings/HardwareSettings.tsx
index 8fb50073..debf313b 100644
--- a/src/components/settings/HardwareSettings.tsx
+++ b/src/components/settings/HardwareSettings.tsx
@@ -339,7 +339,7 @@ export function HardwareSettings() {
Mac: its image engine lets go of its model when the picture is out. */}
{!isMlxImageHost() && (
<div className="pt-2 border-t border-white/[0.06]" data-testid="free-after-render">
- <div className="text-[0.7rem] text-gray-700 dark:text-gray-300 font-medium mb-1">After a render</div>
+ <div className="t-label text-gray-700 dark:text-gray-300 font-medium mb-1">After a render</div>
<div className="grid grid-cols-1 gap-1">
{([
['idle', 'Free memory after 5 minutes (recommended)', 'Renders in a row stay fast. When nothing renders for 5 minutes, the image and video models leave the graphics card and the RAM.'],
@@ -355,8 +355,8 @@ export function HardwareSettings() {
className="mt-0.5"
/>
<div className="flex-1 min-w-0">
- <div className="text-[0.65rem] text-gray-300">{label}</div>
- <div className="text-[0.55rem] text-gray-500 mt-0.5 leading-relaxed">{help}</div>
+ <div className="t-micro text-gray-300">{label}</div>
+ <div className="t-micro text-gray-500 mt-0.5 leading-relaxed">{help}</div>
</div>
</label>
))}
diff --git a/src/hooks/__tests__/useCreate-a-character-does-not-run-on-another-model.test.ts b/src/hooks/__tests__/useCreate-a-character-does-not-run-on-another-model.test.ts
index a4e6e014..91cf425d 100644
--- a/src/hooks/__tests__/useCreate-a-character-does-not-run-on-another-model.test.ts
+++ b/src/hooks/__tests__/useCreate-a-character-does-not-run-on-another-model.test.ts
@@ -30,7 +30,7 @@ vi.mock('../../api/comfyui', async (orig) => ({
}))
vi.mock('../../api/comfyui-ws', () => ({
CLIENT_ID: 'lu-test',
- comfyWS: { connect: vi.fn(async () => { throw new Error('no socket') }), mark: () => 0 },
+ comfyWS: { connect: vi.fn(async () => { throw new Error('no socket') }), mark: () => 0, onPreview: () => () => {} },
}))
vi.mock('../../api/vram-handoff', async (orig) => ({
...((await orig()) as Record<string, unknown>),
diff --git a/src/hooks/__tests__/useCreate-a-waiting-question-is-said-on-the-stage.test.tsx b/src/hooks/__tests__/useCreate-a-waiting-question-is-said-on-the-stage.test.tsx
index 9c435387..974027f6 100644
--- a/src/hooks/__tests__/useCreate-a-waiting-question-is-said-on-the-stage.test.tsx
+++ b/src/hooks/__tests__/useCreate-a-waiting-question-is-said-on-the-stage.test.tsx
@@ -28,7 +28,7 @@ vi.mock('../../api/comfyui', async (orig) => ({
}))
vi.mock('../../api/comfyui-ws', () => ({
CLIENT_ID: 'lu-test',
- comfyWS: { connect: vi.fn(async () => { throw new Error('no socket') }), mark: () => 0 },
+ comfyWS: { connect: vi.fn(async () => { throw new Error('no socket') }), mark: () => 0, onPreview: () => () => {} },
}))
vi.mock('../../api/vram-handoff', async (orig) => ({
...((await orig()) as Record<string, unknown>),
diff --git a/src/hooks/__tests__/useCreate-character-chain.test.ts b/src/hooks/__tests__/useCreate-character-chain.test.ts
index ff3f4bb8..72007ae0 100644
--- a/src/hooks/__tests__/useCreate-character-chain.test.ts
+++ b/src/hooks/__tests__/useCreate-character-chain.test.ts
@@ -50,6 +50,7 @@ vi.mock('../../api/comfyui-ws', () => ({
comfyWS: {
connect: vi.fn(async () => {}),
mark: () => 0,
+ onPreview: () => () => {},
on: (cb: (e: unknown) => void) => {
const id = `p${seen.submits}`
setTimeout(() => cb({ type: 'execution_complete', data: { prompt_id: id } }), 0)
diff --git a/src/hooks/__tests__/useCreate-cutout-says-its-model.test.ts b/src/hooks/__tests__/useCreate-cutout-says-its-model.test.ts
index 894e596f..034f2e03 100644
--- a/src/hooks/__tests__/useCreate-cutout-says-its-model.test.ts
+++ b/src/hooks/__tests__/useCreate-cutout-says-its-model.test.ts
@@ -43,6 +43,7 @@ vi.mock('../../api/comfyui-ws', async (orig) => ({
comfyWS: {
connect: vi.fn(async () => {}),
mark: () => 0,
+ onPreview: () => () => {},
on: (l: Listener) => { ws.listener = l; return () => { ws.listener = null } },
},
}))
diff --git a/src/hooks/__tests__/useCreate-handoff-line.test.ts b/src/hooks/__tests__/useCreate-handoff-line.test.ts
index 6cd206ac..0d679ef1 100644
--- a/src/hooks/__tests__/useCreate-handoff-line.test.ts
+++ b/src/hooks/__tests__/useCreate-handoff-line.test.ts
@@ -28,7 +28,7 @@ vi.mock('../../api/comfyui', async (orig) => ({
}))
vi.mock('../../api/comfyui-ws', () => ({
CLIENT_ID: 'lu-test',
- comfyWS: { connect: vi.fn(async () => { throw new Error('no socket') }), mark: () => 0 },
+ comfyWS: { connect: vi.fn(async () => { throw new Error('no socket') }), mark: () => 0, onPreview: () => () => {} },
}))
vi.mock('../../api/vram-handoff', async (orig) => ({
...((await orig()) as Record<string, unknown>),
diff --git a/src/hooks/__tests__/useCreate-kein-rest-prompt.test.ts b/src/hooks/__tests__/useCreate-kein-rest-prompt.test.ts
index 6953d897..eb44f353 100644
--- a/src/hooks/__tests__/useCreate-kein-rest-prompt.test.ts
+++ b/src/hooks/__tests__/useCreate-kein-rest-prompt.test.ts
@@ -29,7 +29,7 @@ vi.mock('../../api/comfyui', async (orig) => ({
}))
vi.mock('../../api/comfyui-ws', () => ({
CLIENT_ID: 'lu-test',
- comfyWS: { connect: vi.fn(async () => { throw new Error('no socket') }), mark: () => 0 },
+ comfyWS: { connect: vi.fn(async () => { throw new Error('no socket') }), mark: () => 0, onPreview: () => () => {} },
}))
vi.mock('../../api/vram-handoff', async (orig) => ({
...((await orig()) as Record<string, unknown>),
diff --git a/src/hooks/__tests__/useCreate-local-upscale.test.ts b/src/hooks/__tests__/useCreate-local-upscale.test.ts
index 308f88ee..2c7a99c8 100644
--- a/src/hooks/__tests__/useCreate-local-upscale.test.ts
+++ b/src/hooks/__tests__/useCreate-local-upscale.test.ts
@@ -46,6 +46,7 @@ vi.mock('../../api/comfyui-ws', async (orig) => ({
comfyWS: {
connect: vi.fn(async () => {}),
mark: () => 0,
+ onPreview: () => () => {},
on: (l: Listener) => { ws.listener = l; return () => { ws.listener = null } },
},
}))
diff --git a/src/hooks/__tests__/useCreate-motion-runs-the-own-workflow.test.ts b/src/hooks/__tests__/useCreate-motion-runs-the-own-workflow.test.ts
index c2300bf5..9b799ed7 100644
--- a/src/hooks/__tests__/useCreate-motion-runs-the-own-workflow.test.ts
+++ b/src/hooks/__tests__/useCreate-motion-runs-the-own-workflow.test.ts
@@ -34,7 +34,7 @@ vi.mock('../../api/comfyui', async (orig) => ({
}))
vi.mock('../../api/comfyui-ws', () => ({
CLIENT_ID: 'lu-test',
- comfyWS: { connect: vi.fn(async () => { throw new Error('no socket') }), mark: () => 0 },
+ comfyWS: { connect: vi.fn(async () => { throw new Error('no socket') }), mark: () => 0, onPreview: () => () => {} },
}))
vi.mock('../../api/vram-handoff', async (orig) => ({
...((await orig()) as Record<string, unknown>),
diff --git a/src/hooks/__tests__/useCreate-qwen-enhancer.test.ts b/src/hooks/__tests__/useCreate-qwen-enhancer.test.ts
index 6fcda288..705d411e 100644
--- a/src/hooks/__tests__/useCreate-qwen-enhancer.test.ts
+++ b/src/hooks/__tests__/useCreate-qwen-enhancer.test.ts
@@ -39,7 +39,7 @@ vi.mock('../../api/comfyui', async (orig) => ({
}))
vi.mock('../../api/comfyui-ws', () => ({
CLIENT_ID: 'lu-test',
- comfyWS: { connect: vi.fn(async () => { throw new Error('no socket') }), mark: () => 0 },
+ comfyWS: { connect: vi.fn(async () => { throw new Error('no socket') }), mark: () => 0, onPreview: () => () => {} },
}))
vi.mock('../../api/vram-handoff', async (orig) => ({
...((await orig()) as Record<string, unknown>),
diff --git a/src/hooks/__tests__/useCreate-qwen-text-encoder.test.ts b/src/hooks/__tests__/useCreate-qwen-text-encoder.test.ts
index c6740705..1d14f7d8 100644
--- a/src/hooks/__tests__/useCreate-qwen-text-encoder.test.ts
+++ b/src/hooks/__tests__/useCreate-qwen-text-encoder.test.ts
@@ -37,7 +37,7 @@ vi.mock('../../api/comfyui', async (orig) => ({
}))
vi.mock('../../api/comfyui-ws', () => ({
CLIENT_ID: 'lu-test',
- comfyWS: { connect: vi.fn(async () => { throw new Error('no socket') }), mark: () => 0 },
+ comfyWS: { connect: vi.fn(async () => { throw new Error('no socket') }), mark: () => 0, onPreview: () => () => {} },
}))
vi.mock('../../api/vram-handoff', async (orig) => ({
...((await orig()) as Record<string, unknown>),
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 46cd3fce..85f95bc6 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
@@ -39,6 +39,7 @@ vi.mock('../../api/comfyui-ws', async (orig) => ({
comfyWS: {
connect: vi.fn(async () => {}),
mark: () => 0,
+ onPreview: () => () => {},
on: (l: Listener) => { ws.listener = l; return () => { ws.listener = null } },
},
}))
diff --git a/src/hooks/__tests__/useCreate-version-gate-asks-in-every-lane.test.ts b/src/hooks/__tests__/useCreate-version-gate-asks-in-every-lane.test.ts
index 9b4dfb97..3aee106b 100644
--- a/src/hooks/__tests__/useCreate-version-gate-asks-in-every-lane.test.ts
+++ b/src/hooks/__tests__/useCreate-version-gate-asks-in-every-lane.test.ts
@@ -41,7 +41,7 @@ vi.mock('../../api/comfyui', async (orig) => ({
}))
vi.mock('../../api/comfyui-ws', () => ({
CLIENT_ID: 'lu-test',
- comfyWS: { connect: vi.fn(async () => { throw new Error('no socket') }), mark: () => 0 },
+ comfyWS: { connect: vi.fn(async () => { throw new Error('no socket') }), mark: () => 0, onPreview: () => () => {} },
}))
vi.mock('../../api/vram-handoff', async (orig) => ({
...((await orig()) as Record<string, unknown>),
diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.ts
index 91b2154f..6596a4b7 100644
--- a/src/hooks/useCreate.ts
+++ b/src/hooks/useCreate.ts
@@ -102,6 +102,7 @@ import { buildStyleCaption, missingNameLine, trainedLine, trainedLoraFile } from
import { useCreateStore, EDIT_MAX_DENOISE, characterImageRun, deriveIntent, type CreateState, type GalleryItem } from '../stores/createStore'
import { useWorkflowStore } from '../stores/workflowStore'
import { useSettingsStore } from '../stores/settingsStore'
+import { useRenderPreviewStore } from '../stores/renderPreviewStore'
import { renderStallLimitMs, renderStallMessage } from '../lib/tool-timeout'
import { injectParameters, injectLaneParameters } from '../api/workflows'
import { applyNativeHiresFix, latentDownscale } from '../api/hires-fix'
@@ -1755,6 +1756,8 @@ export function useCreate() {
// render's restore to finish reading the chat model back in. The line
// says which it is and counts like every other waiting line.
let renderEviction: RenderEviction | null = null
+ // B28: the live preview of a video run, taken down in the finally below.
+ let offPreview: (() => void) | null = null
const handoff = elapsedLine((text) => setProgress(0, text), HANDOFF_LINE.freeing)
try {
renderEviction = await evictChatBackendsForRender((phase) => handoff.setLabel(HANDOFF_LINE[phase]))
@@ -2141,9 +2144,18 @@ export function useCreate() {
: {}
setProgress(10, 'Submitting to ComfyUI...')
+ // B28: a video asks ComfyUI for a picture per sampling step, so a wrong
+ // start shows long before the end and Cancel can stop it. ComfyUI sends
+ // previews only to this client and one prompt runs at a time here, so
+ // every preview that arrives belongs to this run.
+ const livePreview = mode === 'video'
+ if (livePreview) {
+ useRenderPreviewStore.getState().setUrl(null)
+ offPreview = comfyWS.onPreview((url) => useRenderPreviewStore.getState().setUrl(url))
+ }
let promptId: string
try {
- promptId = await submitWorkflow(workflow, CLIENT_ID)
+ promptId = await submitWorkflow(workflow, CLIENT_ID, livePreview ? { previewMethod: 'auto' } : {})
} catch (err) {
setError(`Failed to submit: ${err instanceof Error ? err.message : String(err)}`)
setIsGenerating(false)
@@ -2540,6 +2552,8 @@ export function useCreate() {
// next render (the helper serialises and a follow-up render inherits
// the haul instead of waiting for it to load).
if (renderEviction) void restoreChatBackendsAfterRender(renderEviction)
+ offPreview?.()
+ useRenderPreviewStore.getState().setUrl(null)
// B27: and ComfyUI's memory goes back when the setting says so.
scheduleFreeAfterRender(
freeAfterRenderMode(useSettingsStore.getState().settings.freeAfterRender),
diff --git a/src/lib/__tests__/free-after-render.test.tsx b/src/lib/__tests__/free-after-render.test.tsx
index 168865e5..71f94a1f 100644
--- a/src/lib/__tests__/free-after-render.test.tsx
+++ b/src/lib/__tests__/free-after-render.test.tsx
@@ -79,7 +79,7 @@ describe('both render paths plan it and call it off', () => {
it('Create', () => {
const create = src('hooks/useCreate.ts')
expect(create).toMatch(/abortRef\.current = new AbortController\(\)\n\s+\/\/ B27[^\n]*\n\s+cancelFreeAfterRender\(\)/)
- expect(create).toMatch(/if \(renderEviction\) void restoreChatBackendsAfterRender\(renderEviction\)\n\s+\/\/ B27[^\n]*\n\s+scheduleFreeAfterRender\(/)
+ expect(create).toMatch(/if \(renderEviction\) void restoreChatBackendsAfterRender\(renderEviction\)\n(.*\n){0,3}\s+\/\/ B27[^\n]*\n\s+scheduleFreeAfterRender\(/)
})
it('a picture or video the chat asked for', () => {
const handoff = src('api/vram-handoff.ts')
diff --git a/src/stores/renderPreviewStore.ts b/src/stores/renderPreviewStore.ts
new file mode 100644
index 00000000..3ef2a725
--- /dev/null
+++ b/src/stores/renderPreviewStore.ts
@@ -0,0 +1,21 @@
+import { create } from 'zustand'
+
+/**
+ * B28 (3.0.9): the newest live preview of the render that runs now, as a data
+ * URL. Discord .molot, 28.10.2026: a video ran for minutes with no picture,
+ * so a wrong start was only seen at the end. ComfyUI sends a preview per
+ * sampling step when the prompt asks for it (api/comfyui submitWorkflow);
+ * Create keeps the newest here and drops it when the run ends.
+ *
+ * Its own store, not createStore: that one is persisted, and a picture of a
+ * run in flight must never reach storage or survive a restart.
+ */
+interface RenderPreviewState {
+ url: string | null
+ setUrl: (url: string | null) => void
+}
+
+export const useRenderPreviewStore = create<RenderPreviewState>((set) => ({
+ url: null,
+ setUrl: (url) => set({ url }),
+}))