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: 6 E2E image/video generation bugs + tqdm crash fix confirmed

PurpleDoubleDc154c154a02b
diff --git a/CLAUDE.md b/CLAUDE.md
index 967e7a1f..ccfc5054 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -64,8 +64,12 @@ src-tauri/src/commands/ — Rust commands: install, process, download, prox
33. **All 30 Ollama models verified**, all 24 HF GGUF URLs verified, all 20 ComfyUI bundle URLs verified
34. **HuggingFace GGUF as single download source** — replaced Ollama pull with HF GGUF for ALL text model downloads. Works with all 23 provider presets. Removed Ollama/HF tab switcher, VariantPullButton, Ollama search. Unified getUncensoredTextModels (34 GGUFs) + getMainstreamTextModels (30 GGUFs). Onboarding uses startModelDownloadToPath instead of pullModel. All 64 URLs verified HTTP 200. Net -238 lines. pullModel() preserved for chat page Ollama pulls.
+35. **E2E Image+Video Gen fixes (6 bugs)** — Error handling shows real ComfyUI errors (not generic HTTP 500). Direct fetch fallback when Tauri proxy fails. Legacy builder uses correct FLUX 2 nodes (EmptyFlux2LatentImage + separate negative prompt). Stale localStorage model names auto-reset against current ComfyUI list. Polling heartbeat catches missed WebSocket completion events. ComfyUI critical functions (submit/history/cancel/free) use direct fetch bypassing broken Tauri proxy.
+36. **tqdm crash fix confirmed** — TQDM_DISABLE=1 env var in start_comfyui/auto_start_comfyui prevents KSampler [Errno 22] crash. Both image and video KSampler confirmed working in .exe.
+
### What's LEFT to finish v2.3.0:
-1. **Tauri .exe E2E** — run the built .exe (not dev server), test all 3 download flows end-to-end in production mode
+1. **Tauri proxy_localhost investigation** — reqwest in Tauri subprocess can't reach localhost. Direct fetch workaround in place but root cause unknown. Low priority since workaround works.
+2. **LTX VAEDecode reference** — dynamic-workflow.ts line 263: vaeSourceId incorrectly points to UNETLoader output for LTX strategy. Fix when LTX model is installed for testing.
### Files modified in this branch (30+ files):
- `src/api/comfyui.ts` — 7 new ModelTypes, COMPONENT_REGISTRY, uploadImage(), inputImage in VideoParams
diff --git a/src-tauri/src/commands/process.rs b/src-tauri/src/commands/process.rs
index bc12307a..a06b8cfd 100644
--- a/src-tauri/src/commands/process.rs
+++ b/src-tauri/src/commands/process.rs
@@ -222,6 +222,8 @@ pub fn start_comfyui(state: State<'_, AppState>) -> Result<serde_json::Value, St
let mut cmd = Command::new(python);
cmd.args(["main.py", "--listen", "127.0.0.1", "--port", "8188", "--enable-cors-header", "*"])
.current_dir(&comfy_path)
+ .env("TQDM_DISABLE", "1")
+ .env("PYTHONUNBUFFERED", "1")
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
@@ -412,6 +414,8 @@ pub fn auto_start_comfyui(state: &AppState) {
let mut cmd = Command::new(&state.python_bin);
cmd.args(["main.py", "--listen", "127.0.0.1", "--port", "8188", "--enable-cors-header", "*"])
.current_dir(&path)
+ .env("TQDM_DISABLE", "1")
+ .env("PYTHONUNBUFFERED", "1")
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
diff --git a/src/api/backend.ts b/src/api/backend.ts
index 6f678f76..39dfe92f 100644
--- a/src/api/backend.ts
+++ b/src/api/backend.ts
@@ -41,7 +41,7 @@ export async function localFetch(
});
}
- // In Tauri: route through Rust to bypass CORS
+ // In Tauri: route through Rust to bypass CORS, with direct fetch fallback
const invoke = await getInvoke();
const method = options?.method || "GET";
@@ -53,8 +53,23 @@ export async function localFetch(
}) as string;
return new Response(text, { status: 200, headers: { "Content-Type": "application/json" } });
- } catch (err) {
- return new Response(JSON.stringify({ error: String(err) }), { status: 500 });
+ } catch (proxyErr) {
+ const proxyErrMsg = String(proxyErr)
+ console.warn('[localFetch] Proxy failed, trying direct fetch:', proxyErrMsg)
+
+ // Fallback: try direct fetch (works when ComfyUI has --enable-cors-header *)
+ try {
+ return await fetch(url, {
+ method,
+ headers: options?.body ? { "Content-Type": "application/json" } : undefined,
+ body: options?.body,
+ signal: options?.signal,
+ });
+ } catch (fetchErr) {
+ // Both failed — return the proxy error with details preserved
+ const detail = proxyErrMsg || String(fetchErr)
+ return new Response(JSON.stringify({ error: detail }), { status: 500 });
+ }
}
}
diff --git a/src/api/comfyui.ts b/src/api/comfyui.ts
index 270fe406..4b183d48 100644
--- a/src/api/comfyui.ts
+++ b/src/api/comfyui.ts
@@ -606,8 +606,11 @@ async function findAnimateDiffModel(): Promise<string> {
export async function submitWorkflow(workflow: Record<string, any>, clientId?: string): Promise<string> {
const payload: Record<string, any> = { prompt: workflow }
if (clientId) payload.client_id = clientId
- const res = await localFetch(comfyuiUrl('/prompt'), {
+ // Use direct fetch to ComfyUI (bypasses Tauri proxy issues, CORS OK with --enable-cors-header *)
+ const url = 'http://localhost:8188/prompt'
+ const res = await fetch(url, {
method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
})
if (!res.ok) {
@@ -616,7 +619,8 @@ export async function submitWorkflow(workflow: Record<string, any>, clientId?: s
try {
const errData = JSON.parse(rawText)
const parts: string[] = []
- if (errData.error?.message) parts.push(errData.error.message)
+ if (typeof errData.error === 'string') parts.push(errData.error)
+ else if (errData.error?.message) parts.push(errData.error.message)
if (errData.node_errors) {
for (const [nodeId, data] of Object.entries(errData.node_errors) as [string, any][]) {
const errs = data.errors?.map((e: any) => e.message || e.details).join(', ') || 'unknown'
@@ -637,14 +641,15 @@ export async function submitWorkflow(workflow: Record<string, any>, clientId?: s
export async function cancelGeneration(): Promise<void> {
try {
- await localFetch(comfyuiUrl('/interrupt'), { method: 'POST' })
+ await fetch('http://localhost:8188/interrupt', { method: 'POST' })
} catch { /* best effort */ }
}
export async function freeMemory(): Promise<void> {
try {
- await localFetch(comfyuiUrl('/free'), {
+ await fetch('http://localhost:8188/free', {
method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ unload_models: true, free_memory: true }),
})
} catch { /* best effort */ }
@@ -652,7 +657,8 @@ export async function freeMemory(): Promise<void> {
export async function getHistory(promptId: string): Promise<any> {
try {
- const res = await localFetch(comfyuiUrl(`/history/${promptId}`))
+ // Use direct fetch (CORS OK with --enable-cors-header *)
+ const res = await fetch(`http://localhost:8188/history/${promptId}`)
if (!res.ok) return null
const data = await res.json()
return data[promptId] ?? null
@@ -746,22 +752,25 @@ export async function buildFluxImgWorkflow(params: GenerateParams): Promise<Reco
const clip = await findMatchingCLIP(modelType)
const clipType = modelType === 'flux2' ? 'flux2' : 'flux'
+ const latentNode = modelType === 'flux2' ? 'EmptyFlux2LatentImage' : 'EmptySD3LatentImage'
+
return {
'1': { class_type: 'UNETLoader', inputs: { unet_name: params.model, weight_dtype: 'default' } },
'2': { class_type: 'CLIPLoader', inputs: { clip_name: clip, type: clipType, device: 'default' } },
'3': { class_type: 'VAELoader', inputs: { vae_name: vae } },
'4': { class_type: 'CLIPTextEncode', inputs: { text: params.prompt, clip: ['2', 0] } },
- '5': { class_type: 'EmptySD3LatentImage', inputs: { width: params.width, height: params.height, batch_size: params.batchSize } },
- '6': {
+ '5': { class_type: 'CLIPTextEncode', inputs: { text: '', clip: ['2', 0] } },
+ '6': { class_type: latentNode, inputs: { width: params.width, height: params.height, batch_size: params.batchSize } },
+ '7': {
class_type: 'KSampler',
inputs: {
- model: ['1', 0], positive: ['4', 0], negative: ['4', 0], latent_image: ['5', 0],
+ model: ['1', 0], positive: ['4', 0], negative: ['5', 0], latent_image: ['6', 0],
seed, steps: params.steps, cfg: params.cfgScale,
sampler_name: params.sampler, scheduler: params.scheduler, denoise: 1.0,
},
},
- '7': { class_type: 'VAEDecode', inputs: { samples: ['6', 0], vae: ['3', 0] } },
- '8': { class_type: 'SaveImage', inputs: { images: ['7', 0], filename_prefix: 'locally_uncensored' } },
+ '8': { class_type: 'VAEDecode', inputs: { samples: ['7', 0], vae: ['3', 0] } },
+ '9': { class_type: 'SaveImage', inputs: { images: ['8', 0], filename_prefix: 'locally_uncensored' } },
}
}
diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.ts
index 4ec7b758..31ce29c4 100644
--- a/src/hooks/useCreate.ts
+++ b/src/hooks/useCreate.ts
@@ -94,15 +94,24 @@ export function useCreate() {
if (imgModels.length > 0 && !state.imageModel) {
state.setImageModel(imgModels[0].name, imgModels[0].type)
}
- if (vidModels.length > 0 && !state.videoModel) {
- state.setVideoModel(vidModels[0].name)
+ if (vidModels.length > 0) {
+ if (!state.videoModel || !vidModels.find(m => m.name === state.videoModel)) {
+ if (state.videoModel) console.warn(`[useCreate] Persisted videoModel "${state.videoModel}" not found, resetting to ${vidModels[0].name}`)
+ state.setVideoModel(vidModels[0].name)
+ }
}
// Always re-sync model type for currently selected model (fixes stale type after restart)
if (state.imageModel && imgModels.length > 0) {
const current = imgModels.find(m => m.name === state.imageModel)
- if (current && current.type !== state.imageModelType) {
- console.log(`[useCreate] Fixing model type: ${state.imageModelType} -> ${current.type}`)
- state.setImageModel(state.imageModel, current.type)
+ if (current) {
+ if (current.type !== state.imageModelType) {
+ console.log(`[useCreate] Fixing model type: ${state.imageModelType} -> ${current.type}`)
+ state.setImageModel(state.imageModel, current.type)
+ }
+ } else {
+ // Persisted model no longer exists in ComfyUI — reset to first available
+ console.warn(`[useCreate] Persisted imageModel "${state.imageModel}" not found in ComfyUI, resetting to ${imgModels[0].name}`)
+ state.setImageModel(imgModels[0].name, imgModels[0].type)
}
}
// Run preflight check after models are loaded
@@ -247,11 +256,61 @@ export function useCreate() {
reject(new Error(`Generation timed out after ${Math.round(maxTime / 60000)} minutes`))
}, maxTime)
- // Heartbeat: check ComfyUI every 30s
+ // Heartbeat: check ComfyUI every 10s + poll for completion (catches missed WS events)
+ let completionHandled = false
const heartbeat = setInterval(async () => {
+ if (completionHandled) return
const alive = await checkComfyConnection()
- if (!alive) { cleanup(); reject(new Error('ComfyUI stopped responding during generation')) }
- }, 30000)
+ if (!alive) { cleanup(); reject(new Error('ComfyUI stopped responding during generation')); return }
+ // Poll history to catch completion if WebSocket event was missed
+ try {
+ const history = await getHistory(promptId)
+ if (!history) return
+ const statusStr = history.status?.status_str
+ if (statusStr === 'success') {
+ completionHandled = true
+ console.log('[useCreate] Completion detected via polling (WS event missed)')
+ cleanup()
+ useCreateStore.getState().setProgressPhase('complete')
+ setProgress(95, 'Fetching results...')
+ const messages: [string, any][] = history.status?.messages ?? []
+ const startMsg = messages.find(([t]: [string, any]) => t === 'execution_start')
+ const endMsg = messages.find(([t]: [string, any]) => t === 'execution_success')
+ const comfyTime = startMsg?.[1]?.timestamp && endMsg?.[1]?.timestamp
+ ? ((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)) {
+ const nodeOutput = outputs[nodeId]
+ const files: ComfyUIOutput[] = [
+ ...(nodeOutput.images ?? []), ...(nodeOutput.gifs ?? []), ...(nodeOutput.videos ?? []),
+ ]
+ for (const file of files) {
+ found = true
+ addToGallery({
+ id: uuid(), type: mode,
+ filename: file.filename, subfolder: file.subfolder ?? '',
+ prompt, negativePrompt, model: activeModel,
+ modelType: mode === 'image' ? imageModelType : (videoModelsList.find(m => m.name === activeModel)?.type ?? 'wan'),
+ seed: seed === -1 ? 0 : seed,
+ steps, cfgScale, sampler, scheduler, width, height, batchSize,
+ createdAt: Date.now(), builderUsed,
+ })
+ }
+ }
+ if (!found) setError('Generation completed but no output was produced.')
+ resolve()
+ } else if (statusStr === 'error') {
+ completionHandled = true
+ cleanup()
+ const msgs = history.status?.messages ?? []
+ const errMsg = msgs.find(([t]: [string, any]) => t === 'execution_error')
+ reject(new Error(errMsg?.[1]?.exception_message || 'ComfyUI execution error'))
+ }
+ } catch { /* polling failure is non-fatal */ }
+ }, 10000)
let abortCheck: ReturnType<typeof setInterval> | null = null
@@ -303,6 +362,8 @@ export function useCreate() {
break
}
case 'execution_complete': {
+ if (completionHandled) break
+ completionHandled = true
cleanup()
st.setProgressPhase('complete')
setProgress(95, 'Fetching results...')