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): ein ComfyUI auf der CPU laesst den Chat-Motor in Ruhe

purplea017fcbd4661
diff --git a/src/api/__tests__/cpu-comfy-keeps-the-chat-engine.test.ts b/src/api/__tests__/cpu-comfy-keeps-the-chat-engine.test.ts
new file mode 100644
index 00000000..4fde6580
--- /dev/null
+++ b/src/api/__tests__/cpu-comfy-keeps-the-chat-engine.test.ts
@@ -0,0 +1,232 @@
+/**
+ * R14 Nebenbefund 1 (2026-08-30, ergebnis-r14-nachmessung.md): every image
+ * generation evicted the chat engine, including generations on a ComfyUI that
+ * LU had started with `--cpu`.
+ *
+ * Measured on the Windows box, Force CPU run: engine PID 4420 was alive before
+ * the render, PID 16896 after it, started 20:19:32, the moment the CPU render
+ * ended. ComfyUI's command line was
+ * `main.py --listen 127.0.0.1 --port 8188 --enable-cors-header * --cpu`,
+ * so nothing on the card was freed and nothing on the card was needed. The
+ * user paid a full cold reload of his chat model for a picture the processor
+ * rendered.
+ *
+ * Both hand-off paths get the same guard: the agent path in runHandoff and the
+ * Create tab path in evictBody. The GPU case is the negative control in every
+ * test below and must behave exactly as it did before.
+ *
+ * Run: npx vitest run src/api/__tests__/cpu-comfy-keeps-the-chat-engine.test.ts
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const localFetch = vi.fn()
+const listRunningModels = vi.fn()
+const loadModel = vi.fn()
+const unloadModel = vi.fn()
+const getImageModels = vi.fn()
+const getSystemVRAM = vi.fn()
+const submitWorkflow = vi.fn()
+const getHistory = vi.fn()
+const freeMemory = vi.fn()
+const buildDynamicWorkflow = vi.fn()
+const backendCall = vi.fn()
+const getActiveAgentModel = vi.fn()
+let isOllamaLocalReturn = true
+
+vi.mock('../backend', () => ({
+ backendCall: (...a: unknown[]) => backendCall(...a),
+ localFetch: (...a: unknown[]) => localFetch(...a),
+ ollamaUrl: (p: string) => `http://localhost:11434/api${p.startsWith('/') ? p : '/' + p}`,
+ comfyuiUrl: (p: string) => `http://localhost:8188${p}`,
+ isOllamaLocal: () => isOllamaLocalReturn,
+ isWindows: () => true,
+}))
+
+vi.mock('../ollama', () => ({
+ listRunningModels: (...a: unknown[]) => listRunningModels(...a),
+ loadModel: (...a: unknown[]) => loadModel(...a),
+ unloadModel: (...a: unknown[]) => unloadModel(...a),
+}))
+
+vi.mock('../comfyui', async () => {
+ const actual = await vi.importActual<typeof import('../comfyui')>('../comfyui')
+ return {
+ ...actual,
+ getImageModels: (...a: unknown[]) => getImageModels(...a),
+ getSystemVRAM: (...a: unknown[]) => getSystemVRAM(...a),
+ submitWorkflow: (...a: unknown[]) => submitWorkflow(...a),
+ getHistory: (...a: unknown[]) => getHistory(...a),
+ freeMemory: (...a: unknown[]) => freeMemory(...a),
+ }
+})
+
+vi.mock('../dynamic-workflow', () => ({
+ buildDynamicWorkflow: (...a: unknown[]) => buildDynamicWorkflow(...a),
+}))
+
+vi.mock('../agent-context', () => ({
+ getActiveAgentModel: () => getActiveAgentModel(),
+}))
+
+vi.mock('../comfyui-ws', () => ({
+ comfyWS: { on: () => () => {}, connect: () => Promise.resolve(), connected: false },
+ CLIENT_ID: 'lu-test-client',
+}))
+
+import {
+ vramHandoffGenerate,
+ evictChatBackendsForRender,
+ __resetGenerationStateForTests,
+ __resetRenderJuggleForTests,
+} from '../vram-handoff'
+import { comfyHoldsNoVram } from '../../lib/comfy-device'
+import { useSettingsStore } from '../../stores/settingsStore'
+
+const GB = 1024 * 1024 * 1024
+
+/** What `get_comfy_gpu_status` answers in this test run. */
+let gpuStatus: { startedCpu: boolean; mode: string; hasAmd: boolean } = {
+ startedCpu: false,
+ mode: 'auto',
+ hasAmd: false,
+}
+
+/** The box's layout: built-in engine up with a GGUF, one Ollama model resident. */
+function mockBackends() {
+ backendCall.mockImplementation(async (cmd: unknown, args?: unknown) => {
+ if (cmd === 'get_comfy_gpu_status') return gpuStatus
+ if (cmd === 'bundled_engine_status') {
+ return { running: true, port: 8127, model_path: 'C:/models/qwen3-8b.gguf', modelBytes: 5 * GB }
+ }
+ if (cmd === 'kv_slot_action') {
+ const a = args as { action?: string } | undefined
+ return a?.action === 'save' ? { ok: true } : { ok: true }
+ }
+ if (cmd === 'lmstudio_list_loaded') return { loaded: [] }
+ if (cmd === 'comfyui_status') return { running: true }
+ return {}
+ })
+}
+
+function completedHistory() {
+ return {
+ status: { completed: true },
+ outputs: { '9': { images: [{ filename: 'out.png', subfolder: '', type: 'output' }] } },
+ }
+}
+
+const callsTo = (cmd: string) => backendCall.mock.calls.filter((c) => c[0] === cmd)
+
+beforeEach(() => {
+ for (const m of [localFetch, listRunningModels, loadModel, unloadModel, getImageModels, getSystemVRAM, submitWorkflow, getHistory, freeMemory, buildDynamicWorkflow, backendCall, getActiveAgentModel]) m.mockReset()
+ __resetGenerationStateForTests()
+ __resetRenderJuggleForTests()
+ isOllamaLocalReturn = true
+ gpuStatus = { startedCpu: false, mode: 'auto', hasAmd: false }
+ loadModel.mockResolvedValue(undefined)
+ unloadModel.mockResolvedValue(undefined)
+ freeMemory.mockResolvedValue(undefined)
+ getActiveAgentModel.mockReturnValue({ name: 'qwen:14b', providerId: 'ollama', remote: false })
+ // A model with a KNOWN footprint, so the fits-or-not math really says
+ // "evict" and the CPU guard is the only thing that can stop it.
+ getImageModels.mockResolvedValue([{ name: 'flux1-dev.safetensors', type: 'flux', source: 'diffusion_model' }])
+ getSystemVRAM.mockResolvedValue(12)
+ buildDynamicWorkflow.mockResolvedValue({ '9': { class_type: 'SaveImage' } })
+ submitWorkflow.mockResolvedValue('pid-1')
+ getHistory.mockResolvedValue(completedHistory())
+ // /api/ps: the 14 B chat model sits in 9 GB of VRAM on a 12 GB card, so the
+ // fits-or-not math says evict whenever it is asked.
+ localFetch.mockImplementation(async (url: string) => {
+ if (String(url).endsWith('/api/ps')) {
+ return new Response(JSON.stringify({ models: [{ name: 'qwen:14b', size_vram: 9 * GB }] }), { status: 200 })
+ }
+ return new Response('{}', { status: 200 })
+ })
+ listRunningModels.mockResolvedValueOnce(['qwen:14b']).mockResolvedValue([])
+ mockBackends()
+ useSettingsStore.getState().updateSettings({ exclusiveVramMode: 'auto' })
+})
+
+// ── The rule itself ───────────────────────────────────────────────
+
+describe('comfyHoldsNoVram', () => {
+ it('a --cpu start LU performed is proof, whichever pick led to it', () => {
+ expect(comfyHoldsNoVram({ startedCpu: true, mode: 'cpu' })).toBe(true)
+ // Auto that fell back to the processor holds no VRAM either.
+ expect(comfyHoldsNoVram({ startedCpu: true, mode: 'auto' })).toBe(true)
+ })
+
+ it('NEGATIVE: a pick without a restart is NOT proof, and neither is nothing', () => {
+ // Force CPU chosen, ComfyUI not restarted: that server is still on the
+ // card, and skipping the hand-off here is the OOM this all exists to stop.
+ expect(comfyHoldsNoVram({ startedCpu: false, mode: 'cpu' })).toBe(false)
+ expect(comfyHoldsNoVram({ startedCpu: false, mode: 'auto' })).toBe(false)
+ expect(comfyHoldsNoVram({ startedCpu: false, mode: 'gpu' })).toBe(false)
+ expect(comfyHoldsNoVram(null)).toBe(false)
+ expect(comfyHoldsNoVram(undefined)).toBe(false)
+ })
+})
+
+// ── Agent path (chat tool) ────────────────────────────────────────
+
+describe('vramHandoffGenerate on a CPU ComfyUI', () => {
+ it('leaves the chat engine alone and still renders', async () => {
+ gpuStatus = { startedCpu: true, mode: 'cpu', hasAmd: false }
+
+ const out = await vramHandoffGenerate('image', { prompt: 'a small red cube' })
+
+ expect(out).toContain('Image generated: out.png')
+ // Nothing was evicted, so nothing has to be reloaded afterwards.
+ expect(unloadModel).not.toHaveBeenCalled()
+ expect(loadModel).not.toHaveBeenCalled()
+ expect(callsTo('stop_bundled_engine')).toHaveLength(0)
+ expect(callsTo('kv_slot_action')).toHaveLength(0)
+ })
+
+ it('NEGATIVE: on the card the hand-off runs exactly as before', async () => {
+ gpuStatus = { startedCpu: false, mode: 'auto', hasAmd: false }
+
+ const out = await vramHandoffGenerate('image', { prompt: 'a small red cube' })
+
+ expect(out).toContain('Image generated: out.png')
+ expect(unloadModel).toHaveBeenCalledWith('qwen:14b')
+ expect(loadModel).toHaveBeenCalledWith('qwen:14b')
+ expect(callsTo('stop_bundled_engine')).toHaveLength(1)
+ })
+
+ it('NEGATIVE: Force CPU picked but ComfyUI never restarted still hands over', async () => {
+ // The user's pick alone says nothing about the server that is running.
+ gpuStatus = { startedCpu: false, mode: 'cpu', hasAmd: false }
+
+ await vramHandoffGenerate('image', { prompt: 'a small red cube' })
+
+ expect(unloadModel).toHaveBeenCalledWith('qwen:14b')
+ expect(callsTo('stop_bundled_engine')).toHaveLength(1)
+ })
+})
+
+// ── Create tab path ───────────────────────────────────────────────
+
+describe('evictChatBackendsForRender on a CPU ComfyUI', () => {
+ it('evicts nothing, so there is nothing to restore', async () => {
+ gpuStatus = { startedCpu: true, mode: 'cpu', hasAmd: false }
+
+ const haul = await evictChatBackendsForRender()
+
+ expect(haul).toEqual({ ollamaModel: null, lms: null, bundled: null })
+ expect(callsTo('offload_local_models')).toHaveLength(0)
+ expect(callsTo('lmstudio_unload_model')).toHaveLength(0)
+ expect(callsTo('kv_slot_action')).toHaveLength(0)
+ })
+
+ it('NEGATIVE: on the card the eviction pair fires exactly as before', async () => {
+ gpuStatus = { startedCpu: false, mode: 'auto', hasAmd: false }
+
+ const haul = await evictChatBackendsForRender()
+
+ expect(haul.ollamaModel).toBe('qwen:14b')
+ expect(haul.bundled?.modelPath).toBe('C:/models/qwen3-8b.gguf')
+ expect(callsTo('offload_local_models')[0][1]).toEqual({ includeComfyui: false })
+ expect(callsTo('lmstudio_unload_model')).toHaveLength(1)
+ })
+})
diff --git a/src/api/vram-handoff.ts b/src/api/vram-handoff.ts
index 2f3e8ca9..60e4c124 100644
--- a/src/api/vram-handoff.ts
+++ b/src/api/vram-handoff.ts
@@ -77,8 +77,28 @@ import { getActiveAgentModel } from './agent-context'
import { comfyWS, CLIENT_ID } from './comfyui-ws'
import { PaceTracker, overBudget, renderBudgetNotice, renderTimeoutNotice, warmupExceeded, swapWarmupNotice, loadPhaseGraceMs, finishGraceMs, warmupBudgetMs, SWAP_WARMUP_BUDGET_MS, type CpuRenderFacts } from '../lib/render-budget'
import { asComfyGpuMode } from '../lib/comfy-cpu-banner'
+import { comfyHoldsNoVram } from '../lib/comfy-device'
import { log } from '../lib/logger'
+/**
+ * Is the ComfyUI we are about to render on running on the processor?
+ *
+ * R14 Nebenbefund 1: both hand-off paths below evicted the chat engine before
+ * every render, including renders on a ComfyUI started with `--cpu`, which
+ * holds no VRAM at all. Same reply `cpuRenderFacts` reads, asked separately so
+ * this decision never disturbs the cached facts the failure notices use, and
+ * so a missing reply (web build, ComfyUI never started by LU) answers `false`
+ * and leaves the hand-off exactly as it was.
+ */
+async function comfyRendersOnCpu(): Promise<boolean> {
+ try {
+ const s = await backendCall<{ startedCpu?: boolean | null; mode?: string | null }>('get_comfy_gpu_status')
+ return comfyHoldsNoVram({ startedCpu: s?.startedCpu === true, mode: asComfyGpuMode(s?.mode) })
+ } catch {
+ return false
+ }
+}
+
/**
* Resolve a casual model name the user/LLM typed (e.g. "FramePack", "wan",
* "sdxl") to an actually-installed model FILENAME. David 2026-06-04: no end user
@@ -793,7 +813,21 @@ async function runHandoff(kind: 'image' | 'video', args: VramHandoffArgs, seq: n
let willUnload = false
let willUnloadLms = false
let willUnloadBundled = false
- if (textModel || lmsTarget || bundledTarget) {
+ // R14 Nebenbefund 1: a ComfyUI LU started with `--cpu` never touches the
+ // card, so there is no VRAM to hand over. Evicting the chat engine for it
+ // buys nothing and costs a full cold reload after every picture. Asked once
+ // per generation, and only when there is something that WOULD be evicted.
+ const comfyOnCpu = (textModel || lmsTarget || bundledTarget) ? await comfyRendersOnCpu() : false
+ if (comfyOnCpu) {
+ log.info('vram_handoff.skipped_cpu_comfy', {
+ kind,
+ targetModel,
+ textModel,
+ lmsModel: lmsTarget?.id ?? null,
+ bundledModel: bundledTarget?.modelPath ?? null,
+ })
+ }
+ if (!comfyOnCpu && (textModel || lmsTarget || bundledTarget)) {
try {
const [footprint, systemVram, mode] = await Promise.all([
Promise.resolve(estimateModelFootprintGB(targetModel)),
@@ -1897,6 +1931,15 @@ async function evictBody(): Promise<RenderEviction> {
return inherited ?? { ...EMPTY_EVICTION }
}
+ // R14 Nebenbefund 1: a ComfyUI LU started with `--cpu` renders without ever
+ // claiming the card, so the eager eviction above has nothing to make room
+ // for. On the box this cost a full reload of the chat model after every
+ // picture. An inherited haul still gets restored after this render.
+ if (await comfyRendersOnCpu()) {
+ log.info('render_juggle.skipped_cpu_comfy', {})
+ return inherited ?? { ...EMPTY_EVICTION }
+ }
+
const result: RenderEviction = { ...EMPTY_EVICTION }
// Capture BEFORE the kill so the restore list is honest.
diff --git a/src/lib/comfy-device.ts b/src/lib/comfy-device.ts
new file mode 100644
index 00000000..260631c0
--- /dev/null
+++ b/src/lib/comfy-device.ts
@@ -0,0 +1,51 @@
+/**
+ * Does the ComfyUI we are about to render on hold any VRAM at all?
+ *
+ * Nebenbefund 1 of the R14 re-measure on the real 2.6.7 Windows build
+ * (2026-08-30, ergebnis-r14-nachmessung.md): every image generation evicts the
+ * chat engine before the render and reloads it after. That trade is the whole
+ * point of the VRAM hand-off when ComfyUI is about to claim the card. It is
+ * pure loss when ComfyUI was started with `--cpu`, because then ComfyUI never
+ * touches the card and the user pays a full cold reload of his chat model for
+ * every single picture.
+ *
+ * Measured on the box, Force CPU run: engine PID 4420 was alive before the
+ * generation and PID 16896 after it, started at 20:19:32, the moment the CPU
+ * render ended. Nothing was gained by the eviction, since the ComfyUI command
+ * line was `main.py ... --cpu`.
+ *
+ * The one fact that carries this decision is `startedCpu` from
+ * `get_comfy_gpu_status`: LU started THIS ComfyUI with `--cpu` itself, so it
+ * knows, rather than guesses, that no VRAM is in play. `mode` is deliberately
+ * NOT part of the condition, see below.
+ */
+import type { ComfyGpuModeName } from './comfy-cpu-banner'
+
+/** The two facts `get_comfy_gpu_status` reports about the running ComfyUI. */
+export interface ComfyDeviceFacts {
+ /** LU itself started ComfyUI with `--cpu` this session. */
+ startedCpu: boolean
+ /** Settings, Hardware, ComfyUI GPU. `cpu` is the Force CPU entry. */
+ mode: ComfyGpuModeName
+}
+
+/**
+ * True when this ComfyUI provably holds no VRAM, so freeing VRAM for it is
+ * pointless work.
+ *
+ * Only a `--cpu` start LU performed itself counts. Two cases are deliberately
+ * left out, both of which would break the hand-off if they were let in:
+ *
+ * - `mode === 'cpu'` on its own. A user who picks Force CPU and does NOT
+ * restart ComfyUI still has a ComfyUI on the card. Skipping the hand-off
+ * there brings back the OOM the mechanism exists to prevent.
+ * - a ComfyUI LU did not start (someone else's server on port 8188). LU
+ * cannot know what that one was started with, so it stays on the safe
+ * side and keeps handing VRAM over.
+ *
+ * `startedCpu` with `mode === 'auto'` DOES count: that is the automatic CPU
+ * fallback on a machine with no usable GPU path, and it holds no VRAM either.
+ */
+export function comfyHoldsNoVram(facts: ComfyDeviceFacts | null | undefined): boolean {
+ return facts?.startedCpu === true
+}