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
Fix chat-agent image/video MCP handoff hang: bound ComfyUI control-plane fetches
purple0b388b613760
diff --git a/src/api/__tests__/comfyui-timeouts.test.ts b/src/api/__tests__/comfyui-timeouts.test.tsnew file mode 100644index 00000000..ed5235b5--- /dev/null+++ b/src/api/__tests__/comfyui-timeouts.test.ts@@ -0,0 +1,127 @@+/**+ * Regression guard for the chat-agent MCP image/video hand-off hang (2026-06-03).+ *+ * ROOT CAUSE: every ComfyUI control-plane fetch (/object_info, /prompt,+ * /history, /free, /system_stats, /object_info/<Node>) went through localFetch+ * WITHOUT a `timeoutMs`, so each inherited the Rust proxy's 300 s default. One+ * wedged control call (e.g. /object_info right after a ComfyUI restart, or a+ * /prompt that never returns) froze the whole VRAM hand-off for minutes with+ * the text model left unloaded — the agent looked permanently stuck.+ *+ * These tests pin the contract: each control-plane call MUST pass a bounded,+ * finite `timeoutMs`. They DON'T prove the real network behaviour (mocked+ * localFetch) — they prove the timeout is actually plumbed through, so a future+ * refactor can't silently drop it and reintroduce the infinite hang.+ *+ * Run: npx vitest run src/api/__tests__/comfyui-timeouts.test.ts+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'++const localFetch = vi.fn()++vi.mock('../backend', () => ({+ localFetch: (...a: unknown[]) => localFetch(...a),+ comfyuiUrl: (p: string) => `http://localhost:8188${p}`,+}))++import {+ submitWorkflow,+ getHistory,+ getCheckpoints,+ getDiffusionModels,+ getVAEModels,+ freeMemory,+ cancelGeneration,+ getSystemVRAM,+} from '../comfyui'+import { getAllNodeInfo, clearNodeCache } from '../comfyui-nodes'++/** Build a 200 Response with a JSON body shaped for whichever endpoint is hit. */+function respondFor(url: string): Response {+ if (url.endsWith('/prompt')) return new Response(JSON.stringify({ prompt_id: 'p1' }), { status: 200 })+ if (url.includes('/history/')) return new Response(JSON.stringify({ p1: { status: { completed: true } } }), { status: 200 })+ if (url.endsWith('/object_info/CheckpointLoaderSimple')) {+ return new Response(JSON.stringify({ CheckpointLoaderSimple: { input: { required: { ckpt_name: [['a.safetensors']] } } } }), { status: 200 })+ }+ if (url.endsWith('/object_info/UNETLoader')) {+ return new Response(JSON.stringify({ UNETLoader: { input: { required: { unet_name: [['u.safetensors']] } } } }), { status: 200 })+ }+ if (url.endsWith('/object_info/VAELoader')) {+ return new Response(JSON.stringify({ VAELoader: { input: { required: { vae_name: [['v.safetensors']] } } } }), { status: 200 })+ }+ if (url.endsWith('/object_info')) return new Response(JSON.stringify({ KSampler: { input: { required: {} }, output: [] } }), { status: 200 })+ if (url.endsWith('/system_stats')) return new Response(JSON.stringify({ devices: [{ vram_total: 12 * 1024 * 1024 * 1024 }] }), { status: 200 })+ // /free, /interrupt, fallback+ return new Response('{}', { status: 200 })+}++beforeEach(() => {+ localFetch.mockReset()+ localFetch.mockImplementation(async (url: string) => respondFor(url))+ clearNodeCache()+})++/** Pull the options object from the localFetch call whose URL matches `frag`. */+function optsForUrl(frag: string): Record<string, unknown> | undefined {+ const call = localFetch.mock.calls.find((c) => typeof c[0] === 'string' && (c[0] as string).includes(frag))+ return call?.[1] as Record<string, unknown> | undefined+}++function expectBoundedTimeout(frag: string, max = 60_000) {+ const opts = optsForUrl(frag)+ expect(opts, `localFetch for "${frag}" must receive an options object`).toBeTruthy()+ const t = opts!.timeoutMs+ expect(typeof t, `"${frag}" must pass a numeric timeoutMs`).toBe('number')+ expect(Number.isFinite(t as number)).toBe(true)+ expect(t as number).toBeGreaterThan(0)+ // A control-plane call must never get a multi-minute budget — that is exactly+ // the proxy default that caused the hang.+ expect(t as number).toBeLessThanOrEqual(max)+}++describe('ComfyUI control-plane fetches are timeout-bounded (chat-agent hang regression)', () => {+ it('submitWorkflow (POST /prompt) passes a bounded timeoutMs', async () => {+ await submitWorkflow({ '1': { class_type: 'SaveImage', inputs: {} } })+ expectBoundedTimeout('/prompt')+ })++ it('getHistory (GET /history/<id>) passes a bounded timeoutMs', async () => {+ await getHistory('p1')+ expectBoundedTimeout('/history/')+ })++ it('getCheckpoints (/object_info/CheckpointLoaderSimple) passes a bounded timeoutMs', async () => {+ await getCheckpoints()+ expectBoundedTimeout('/object_info/CheckpointLoaderSimple')+ })++ it('getDiffusionModels (/object_info/UNETLoader) passes a bounded timeoutMs', async () => {+ await getDiffusionModels()+ expectBoundedTimeout('/object_info/UNETLoader')+ })++ it('getVAEModels (/object_info/VAELoader) passes a bounded timeoutMs', async () => {+ await getVAEModels()+ expectBoundedTimeout('/object_info/VAELoader')+ })++ it('freeMemory (POST /free) passes a bounded timeoutMs (runs in the finally → must not stall the reload)', async () => {+ await freeMemory()+ expectBoundedTimeout('/free')+ })++ it('cancelGeneration (POST /interrupt) passes a bounded timeoutMs', async () => {+ await cancelGeneration()+ expectBoundedTimeout('/interrupt')+ })++ it('getSystemVRAM (/system_stats) passes a bounded timeoutMs', async () => {+ await getSystemVRAM()+ expectBoundedTimeout('/system_stats')+ })++ it('getAllNodeInfo (full /object_info — the heaviest call, hit first by buildDynamicWorkflow) passes a bounded timeoutMs', async () => {+ await getAllNodeInfo(true)+ expectBoundedTimeout('/object_info')+ })+})diff --git a/src/api/comfyui-nodes.ts b/src/api/comfyui-nodes.tsindex be75b7fc..cc13ee9b 100644--- a/src/api/comfyui-nodes.ts+++ b/src/api/comfyui-nodes.ts@@ -49,7 +49,14 @@ export async function getAllNodeInfo(forceRefresh = false): Promise<Record<strinreturn nodeInfoCache}- const res = await localFetch(comfyuiUrl('/object_info'))+ // Bound this fetch. /object_info is the heaviest control-plane call (the full+ // node catalogue) and is the FIRST thing buildDynamicWorkflow hits. Without an+ // explicit cap it inherits the Rust proxy's 300 s default — and a single wedged+ // /object_info right after a ComfyUI (re)start froze the whole image-MCP VRAM+ // hand-off for minutes with the text model left unloaded (chat-agent hang,+ // 2026-06-03). 30 s is far beyond a healthy localhost response; on timeout we+ // throw a clean error so the hand-off's finally can free VRAM + reload the model.+ const res = await localFetch(comfyuiUrl('/object_info'), { timeoutMs: 30_000 })if (!res.ok) throw new Error(`Failed to fetch node info: ${res.status}`)const data = await res.json()diff --git a/src/api/comfyui.ts b/src/api/comfyui.tsindex a70521c2..cce11ab0 100644--- a/src/api/comfyui.ts+++ b/src/api/comfyui.ts@@ -1,6 +1,25 @@import { comfyuiUrl, localFetch } from "./backend"import { log } from "../lib/logger"+// ─── Control-plane fetch timeouts ───+//+// These ComfyUI endpoints enqueue / list / poll / free and MUST answer in well+// under a few seconds on localhost: ComfyUI serves them on its asyncio event+// loop while the actual generation runs on a SEPARATE worker thread, so HTTP+// stays responsive even mid-render. A generation's real compute time is observed+// by repeatedly polling /history (each poll quick), NOT by any single long-lived+// fetch. Without an explicit cap every call below inherits the Rust proxy's+// 300 s default — and ONE wedged control call (e.g. /object_info right after a+// ComfyUI restart, or a /prompt POST that never returns) froze the whole image-+// MCP VRAM hand-off for minutes with the text model left unloaded (chat-agent+// hang, 2026-06-03). Bounding each call converts that infinite stall into a fast,+// clean error so the hand-off's `finally` can always free VRAM + reload the model.+const COMFY_LIST_TIMEOUT_MS = 15_000 // /object_info/<Node> single-node listings+const COMFY_SUBMIT_TIMEOUT_MS = 30_000 // POST /prompt — validates + enqueues, returns prompt_id only+const COMFY_POLL_TIMEOUT_MS = 15_000 // GET /history/<id> per status poll+const COMFY_STATS_TIMEOUT_MS = 10_000 // /system_stats, /api/refresh, /interrupt+const COMFY_FREE_TIMEOUT_MS = 20_000 // POST /free — VRAM release+// ─── Types ───export interface GenerateParams {@@ -320,7 +339,7 @@ export async function checkComfyConnection(): Promise<boolean> {export async function refreshComfyModels(maxAttempts = 3): Promise<boolean> {for (let attempt = 0; attempt < maxAttempts; attempt++) {try {- const res = await localFetch(comfyuiUrl('/api/refresh'), { method: 'POST' })+ const res = await localFetch(comfyuiUrl('/api/refresh'), { method: 'POST', timeoutMs: COMFY_STATS_TIMEOUT_MS })if (res.ok) return true} catch { /* network blip — retry */ }if (attempt < maxAttempts - 1) {@@ -337,7 +356,7 @@ let cachedVRAM: number | null = nullexport async function getSystemVRAM(): Promise<number | null> {if (cachedVRAM !== null) return cachedVRAMtry {- const res = await localFetch(comfyuiUrl('/system_stats'))+ const res = await localFetch(comfyuiUrl('/system_stats'), { timeoutMs: COMFY_STATS_TIMEOUT_MS })if (!res.ok) return nullconst data = await res.json()// ComfyUI returns top-level devices[].vram_total in bytes@@ -354,7 +373,7 @@ export async function getSystemVRAM(): Promise<number | null> {// Check if a specific node exists in ComfyUI (lightweight, single node check)async function nodeExists(nodeName: string): Promise<boolean> {try {- const res = await localFetch(comfyuiUrl(`/object_info/${nodeName}`))+ const res = await localFetch(comfyuiUrl(`/object_info/${nodeName}`), { timeoutMs: COMFY_LIST_TIMEOUT_MS })if (!res.ok) return falseconst data = await res.json()return !!(data && data[nodeName])@@ -364,14 +383,14 @@ async function nodeExists(nodeName: string): Promise<boolean> {}export async function getCheckpoints(): Promise<string[]> {- const res = await localFetch(comfyuiUrl('/object_info/CheckpointLoaderSimple'))+ const res = await localFetch(comfyuiUrl('/object_info/CheckpointLoaderSimple'), { timeoutMs: COMFY_LIST_TIMEOUT_MS })if (!res.ok) throw new Error(`ComfyUI /object_info/CheckpointLoaderSimple failed (HTTP ${res.status})`)const data = await res.json()return data?.CheckpointLoaderSimple?.input?.required?.ckpt_name?.[0] ?? []}export async function getDiffusionModels(): Promise<string[]> {- const res = await localFetch(comfyuiUrl('/object_info/UNETLoader'))+ const res = await localFetch(comfyuiUrl('/object_info/UNETLoader'), { timeoutMs: COMFY_LIST_TIMEOUT_MS })if (!res.ok) throw new Error(`ComfyUI /object_info/UNETLoader failed (HTTP ${res.status})`)const data = await res.json()return data?.UNETLoader?.input?.required?.unet_name?.[0] ?? []@@ -379,7 +398,7 @@ export async function getDiffusionModels(): Promise<string[]> {export async function getVAEModels(): Promise<string[]> {try {- const res = await localFetch(comfyuiUrl('/object_info/VAELoader'))+ const res = await localFetch(comfyuiUrl('/object_info/VAELoader'), { timeoutMs: COMFY_LIST_TIMEOUT_MS })if (!res.ok) return []const data = await res.json()return data?.VAELoader?.input?.required?.vae_name?.[0] ?? []@@ -391,7 +410,7 @@ export async function getVAEModels(): Promise<string[]> {export async function getCLIPModels(): Promise<string[]> {try {- const res = await localFetch(comfyuiUrl('/object_info/CLIPLoader'))+ const res = await localFetch(comfyuiUrl('/object_info/CLIPLoader'), { timeoutMs: COMFY_LIST_TIMEOUT_MS })if (!res.ok) return []const data = await res.json()return data?.CLIPLoader?.input?.required?.clip_name?.[0] ?? []@@ -409,7 +428,7 @@ export async function getCLIPModels(): Promise<string[]> {*/export async function getLoraModels(): Promise<string[]> {try {- const res = await localFetch(comfyuiUrl('/object_info/LoraLoader'))+ const res = await localFetch(comfyuiUrl('/object_info/LoraLoader'), { timeoutMs: COMFY_LIST_TIMEOUT_MS })if (!res.ok) return []const data = await res.json()return data?.LoraLoader?.input?.required?.lora_name?.[0] ?? []@@ -421,7 +440,7 @@ export async function getLoraModels(): Promise<string[]> {export async function getSamplers(): Promise<string[]> {try {- const res = await localFetch(comfyuiUrl('/object_info/KSampler'))+ const res = await localFetch(comfyuiUrl('/object_info/KSampler'), { timeoutMs: COMFY_LIST_TIMEOUT_MS })if (!res.ok) throw new Error('Failed')const data = await res.json()return data?.KSampler?.input?.required?.sampler_name?.[0] ?? []@@ -432,7 +451,7 @@ export async function getSamplers(): Promise<string[]> {export async function getSchedulers(): Promise<string[]> {try {- const res = await localFetch(comfyuiUrl('/object_info/KSampler'))+ const res = await localFetch(comfyuiUrl('/object_info/KSampler'), { timeoutMs: COMFY_LIST_TIMEOUT_MS })if (!res.ok) throw new Error('Failed')const data = await res.json()return data?.KSampler?.input?.required?.scheduler?.[0] ?? []@@ -789,6 +808,10 @@ export async function submitWorkflow(workflow: Record<string, any>, clientId?: smethod: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(payload),+ // /prompt only validates + enqueues and returns the prompt_id immediately —+ // it does NOT block on the render. Cap it so a wedged submit can't strand the+ // VRAM hand-off (text model stays unloaded) for the 5-min proxy default.+ timeoutMs: COMFY_SUBMIT_TIMEOUT_MS,})if (!res.ok) {const rawText = await res.text().catch(() => '')@@ -817,7 +840,7 @@ export async function submitWorkflow(workflow: Record<string, any>, clientId?: sexport async function cancelGeneration(): Promise<void> {try {- await localFetch(comfyuiUrl('/interrupt'), { method: 'POST' })+ await localFetch(comfyuiUrl('/interrupt'), { method: 'POST', timeoutMs: COMFY_STATS_TIMEOUT_MS })} catch { /* best effort */ }}@@ -827,6 +850,9 @@ export async function freeMemory(): Promise<void> {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ unload_models: true, free_memory: true }),+ // Bounded: this runs in the hand-off's `finally` right before reloading the+ // text model. A wedged /free must not delay that reload by 5 min.+ timeoutMs: COMFY_FREE_TIMEOUT_MS,})} catch { /* best effort */ }}@@ -837,7 +863,7 @@ export async function getHistory(promptId: string): Promise<any> {// reason as submitWorkflow above. Without this, a user-run ComfyUI// Portable would accept the /prompt POST but the polling /history GETs// would silently 0-out and the UI hangs in "generating…" forever.- const res = await localFetch(comfyuiUrl(`/history/${promptId}`))+ const res = await localFetch(comfyuiUrl(`/history/${promptId}`), { timeoutMs: COMFY_POLL_TIMEOUT_MS })if (!res.ok) return nullconst data = await res.json()return data[promptId] ?? nulldiff --git a/src/api/vram-handoff.ts b/src/api/vram-handoff.tsindex f5b44a60..c6591c55 100644--- a/src/api/vram-handoff.ts+++ b/src/api/vram-handoff.ts@@ -149,7 +149,9 @@ interface ResidentModel {async function getResidentModels(): Promise<ResidentModel[]> {try {- const res = await localFetch(ollamaUrl('/ps'))+ // Short cap: /api/ps is a quick status read. Bounding it keeps the DECIDE+ // phase from inheriting the proxy's 5-min default if Ollama is wedged.+ const res = await localFetch(ollamaUrl('/ps'), { timeoutMs: 8_000 })if (!res.ok) return []const data = await res.json()return (data.models || []).map((m: any) => ({@@ -558,7 +560,13 @@ async function generateImage(prompt: string, model: string, args: VramHandoffArg},classifyModel(model),)+ // Phase markers (chat-agent hang 2026-06-03): make it obvious in the log+ // whether a stall is in the workflow build (/object_info) or the submit+ // (/prompt). Both are now timeout-bounded, so neither can strand the+ // hand-off with the text model unloaded — these logs just pinpoint where.+ log.info('vram_handoff.image.submit', { model, i2i: !!inputImage })const promptId = await submitWorkflow(workflow)+ log.info('vram_handoff.image.submitted', { promptId })return await pollAndExtract(promptId, prompt, label('image'), getImageTimeoutMs())} catch (err) {// Surface ComfyUI's message verbatim — an OOM must NOT be masked.@@ -604,7 +612,9 @@ async function generateVideo(},type,)+ log.info('vram_handoff.video.submit', { model, i2v: true })const promptId = await submitWorkflow(workflow)+ log.info('vram_handoff.video.submitted', { promptId })return await pollAndExtract(promptId, prompt, label('video'), getVideoTimeoutMs())}@@ -632,7 +642,9 @@ async function generateVideo(},backend,)+ log.info('vram_handoff.video.submit', { model, i2v: false, backend })const promptId = await submitWorkflow(workflow)+ log.info('vram_handoff.video.submitted', { promptId })return await pollAndExtract(promptId, prompt, label('video'), getVideoTimeoutMs())} catch (err) {return `${label('video')} generation failed: ${err instanceof Error ? err.message : String(err)}`