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): give ComfyUI's memory back after a render, as a setting (B27)

purplec12bcc30c440
diff --git a/src/api/vram-handoff.ts b/src/api/vram-handoff.ts
index a81bedf4..5c52d16f 100644
--- a/src/api/vram-handoff.ts
+++ b/src/api/vram-handoff.ts
@@ -89,6 +89,7 @@ import { renderStallLimitMs } from '../lib/tool-timeout'
import { aspectFrame, parseAspectRatio } from '../lib/aspect-frame'
import { buildWithFixups, wasDeclined } from '../lib/render-fixups'
import { renderFixupDeps } from './render-fixup-deps'
+import { cancelFreeAfterRender, freeAfterRenderMode, scheduleFreeAfterRender } from '../lib/free-after-render'
/**
* Is the ComfyUI we are about to render on running on the processor?
@@ -1195,6 +1196,7 @@ async function runHandoff(
// counter and a later plain-chat Stop would wrongly /interrupt + clear an
// unrelated Create-tab render (the exact bug this counter prevents).
_activeHandoffs++
+ cancelFreeAfterRender() // B27: about to use what was planned to be freed
if (willUnload || willUnloadLms || willUnloadBundled) {
releaseChatHold = holdChatBackends(kind === 'video' ? 'video' : 'image')
}
@@ -1393,6 +1395,9 @@ async function runHandoff(
}
releaseChatHold?.()
emitHandoff('done', { kind })
+ // B27: ComfyUI's memory goes back when the setting says so, unless
+ // another generation is running by then.
+ scheduleFreeAfterRender(freeAfterRenderMode(useSettingsStore.getState().settings.freeAfterRender), () => _activeHandoffs > 0)
}
}
diff --git a/src/components/settings/HardwareSettings.tsx b/src/components/settings/HardwareSettings.tsx
index 6648b571..8fb50073 100644
--- a/src/components/settings/HardwareSettings.tsx
+++ b/src/components/settings/HardwareSettings.tsx
@@ -4,6 +4,7 @@
// next Ollama / ComfyUI spawn (current processes need a restart).
import { useEffect, useMemo, useState } from 'react'
+import { freeAfterRenderMode } from '../../lib/free-after-render'
import { useSettingsStore } from '../../stores/settingsStore'
import { backendCall, isTauri } from '../../api/backend'
import { isMlxImageHost } from '../../api/mlx-image'
@@ -119,6 +120,7 @@ export function HardwareSettings() {
}, [])
const comfyGpuMode = (settings.comfyGpuMode || 'auto') as 'auto' | 'cpu' | 'gpu'
+ const freeAfter = freeAfterRenderMode(settings.freeAfterRender)
const setComfyGpuMode = (mode: 'auto' | 'cpu' | 'gpu') => {
updateSettings({ comfyGpuMode: mode })
// Desktop-only command; the web build points at a remote ComfyUI and never
@@ -333,6 +335,35 @@ export function HardwareSettings() {
</div>
)}
+ {/* B27 (3.0.9): give ComfyUI's memory back after a render. Not on the
+ 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="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.'],
+ ['now', 'Free memory right away', 'The models leave the graphics card and the RAM a few seconds after each render. The next render loads them again, which can take a minute.'],
+ ['keep', 'Keep the models loaded', 'The fastest next render. The memory stays taken until ComfyUI stops.'],
+ ] as const).map(([val, label, help]) => (
+ <label key={val} className="flex items-start gap-2 cursor-pointer p-1.5 rounded hover:bg-white/[0.04] border border-transparent has-[input:checked]:border-white/10 has-[input:checked]:bg-white/[0.03]">
+ <input
+ type="radio"
+ name="free-after-render"
+ checked={freeAfter === val}
+ onChange={() => updateSettings({ freeAfterRender: val })}
+ 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>
+ </label>
+ ))}
+ </div>
+ </div>
+ )}
+
{showRestartHint && (vendor !== 'auto' || indices.length > 0) && (
<Hinweis className="italic">
GPU pick takes effect on next Ollama / ComfyUI spawn. Restart ComfyUI under AI Backends, ComfyUI (Image &amp; Video), or close LU to apply it to both.
diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.ts
index f4b71dd9..91b2154f 100644
--- a/src/hooks/useCreate.ts
+++ b/src/hooks/useCreate.ts
@@ -78,6 +78,7 @@ import { knownMacMemoryGb } from '../lib/mac-memory'
import { MIN_TRAIN_IMAGES, maxTrainImages, tooFewTrainPhotosLine } from '../lib/train-image-cap'
import { improveKindForIntent, IMPROVING_PROMPT, type ImproveOutcome } from '../lib/render/improve-prompt'
import { elapsedLine } from '../lib/elapsed-line'
+import { cancelFreeAfterRender, freeAfterRenderMode, scheduleFreeAfterRender } from '../lib/free-after-render'
import { improvePrompt } from '../lib/render/improve-prompt-run'
import { currentChatModelList, currentHelperModel } from '../lib/cloud-helper-model'
import { enhancerLine, enhancerNames, pickQwenEnhancer, rewrittenByName, type ImproveWriter } from '../lib/render/qwen-enhancer'
@@ -1733,6 +1734,8 @@ export function useCreate() {
}
abortRef.current = new AbortController()
+ // B27: a render starts, so a planned free of ComfyUI's memory is off.
+ cancelFreeAfterRender()
// Make VRAM room for the render. On a single local GPU a resident chat LLM
// (Ollama / LM Studio / the bundled engine) squats the card, which forces
@@ -2537,6 +2540,11 @@ 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)
+ // B27: and ComfyUI's memory goes back when the setting says so.
+ scheduleFreeAfterRender(
+ freeAfterRenderMode(useSettingsStore.getState().settings.freeAfterRender),
+ () => useCreateStore.getState().isGenerating,
+ )
}
// `videoModelsList` ist State: seine Referenz wechselt nur, wenn
// setVideoModelsList wirklich eine neue Liste schreibt (fetchModels), und
diff --git a/src/lib/__tests__/free-after-render.test.tsx b/src/lib/__tests__/free-after-render.test.tsx
new file mode 100644
index 00000000..168865e5
--- /dev/null
+++ b/src/lib/__tests__/free-after-render.test.tsx
@@ -0,0 +1,104 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * B27 (3.0.9): Discord .molot, 28.10.2026, "free RAM and unload the model
+ * after rendering". ComfyUI kept every model on the card and in RAM after a
+ * render until it was closed. Now a setting decides, and the default gives
+ * the memory back five minutes after the last render.
+ *
+ * Run: npx vitest run src/lib/__tests__/free-after-render.test.tsx
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+
+vi.mock('../../api/backend', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../../api/backend')>()),
+ isTauri: () => false,
+ backendCall: vi.fn(async () => []),
+}))
+vi.mock('../../api/mlx-image', () => ({ isMlxImageHost: () => false }))
+
+const {
+ scheduleFreeAfterRender, cancelFreeAfterRender, freeAfterRenderMode, freeAfterRenderPending,
+ FREE_AFTER_IDLE_MS, FREE_AFTER_NOW_GRACE_MS,
+} = await import('../free-after-render')
+const { DEFAULT_SETTINGS } = await import('../constants')
+const { HardwareSettings } = await import('../../components/settings/HardwareSettings')
+const { useSettingsStore } = await import('../../stores/settingsStore')
+
+describe('when the memory goes back', () => {
+ beforeEach(() => { vi.useFakeTimers(); cancelFreeAfterRender() })
+ afterEach(() => { vi.useRealTimers() })
+
+ it('the default frees five minutes after the render, and a profile without the key gets it', async () => {
+ expect(DEFAULT_SETTINGS.freeAfterRender).toBe('idle')
+ expect(freeAfterRenderMode(undefined)).toBe('idle')
+ const free = vi.fn(async () => {})
+ scheduleFreeAfterRender(freeAfterRenderMode(undefined), () => false, free)
+ await vi.advanceTimersByTimeAsync(FREE_AFTER_IDLE_MS - 1000)
+ expect(free).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(free).toHaveBeenCalledTimes(1)
+ expect(FREE_AFTER_IDLE_MS).toBe(5 * 60_000)
+ })
+
+ it('a render that starts in between keeps the models', async () => {
+ const free = vi.fn(async () => {})
+ scheduleFreeAfterRender('idle', () => false, free)
+ await vi.advanceTimersByTimeAsync(60_000)
+ cancelFreeAfterRender()
+ expect(freeAfterRenderPending()).toBe(false)
+ await vi.advanceTimersByTimeAsync(FREE_AFTER_IDLE_MS)
+ expect(free).not.toHaveBeenCalled()
+ })
+
+ it('a render running elsewhere when the time comes keeps them too', async () => {
+ const free = vi.fn(async () => {})
+ scheduleFreeAfterRender('now', () => true, free)
+ await vi.advanceTimersByTimeAsync(FREE_AFTER_NOW_GRACE_MS)
+ expect(free).not.toHaveBeenCalled()
+ })
+
+ it('"now" frees after a short grace, "keep" never', async () => {
+ const free = vi.fn(async () => {})
+ scheduleFreeAfterRender('now', () => false, free)
+ await vi.advanceTimersByTimeAsync(FREE_AFTER_NOW_GRACE_MS)
+ expect(free).toHaveBeenCalledTimes(1)
+ expect(FREE_AFTER_NOW_GRACE_MS).toBeLessThanOrEqual(15_000)
+ scheduleFreeAfterRender('keep', () => false, free)
+ expect(freeAfterRenderPending()).toBe(false)
+ await vi.advanceTimersByTimeAsync(FREE_AFTER_IDLE_MS * 2)
+ expect(free).toHaveBeenCalledTimes(1)
+ })
+})
+
+describe('both render paths plan it and call it off', () => {
+ const src = (f: string) => readFileSync(resolve(__dirname, '..', '..', f), 'utf8')
+ 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\(/)
+ })
+ it('a picture or video the chat asked for', () => {
+ const handoff = src('api/vram-handoff.ts')
+ expect(handoff).toMatch(/_activeHandoffs\+\+\n\s+cancelFreeAfterRender\(\)/)
+ expect(handoff).toMatch(/emitHandoff\('done', \{ kind \}\)\n(\s+\/\/[^\n]*\n)+\s+scheduleFreeAfterRender\(/)
+ })
+})
+
+describe('the setting in Hardware', () => {
+ afterEach(() => cleanup())
+ it('shows the three choices with the default picked, and a click stores the choice', () => {
+ useSettingsStore.getState().updateSettings({ freeAfterRender: undefined })
+ render(<HardwareSettings />)
+ const box = screen.getByTestId('free-after-render')
+ const radios = box.querySelectorAll('input[type=radio]')
+ expect(radios).toHaveLength(3)
+ expect((radios[0] as HTMLInputElement).checked).toBe(true)
+ expect(box.textContent).toContain('Free memory after 5 minutes (recommended)')
+ fireEvent.click(radios[1])
+ expect(useSettingsStore.getState().settings.freeAfterRender).toBe('now')
+ })
+})
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index f0796e27..e036b0d7 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -138,6 +138,8 @@ export const DEFAULT_SETTINGS: Settings = {
// 'auto' = evict the local text model only when it wouldn't co-exist with the
// ComfyUI model in VRAM. Safest default (no eviction on unknown sizes).
exclusiveVramMode: 'auto',
+ // 3.0.9 (B27): ComfyUI's memory goes back five minutes after the last render.
+ freeAfterRender: 'idle',
// 3.0.8 (A2): long generations from the chat go on in the background.
backgroundMediaTools: true,
// 3.0.8 (A2): no card per service until the user picks one.
diff --git a/src/lib/free-after-render.ts b/src/lib/free-after-render.ts
new file mode 100644
index 00000000..2e416829
--- /dev/null
+++ b/src/lib/free-after-render.ts
@@ -0,0 +1,76 @@
+/**
+ * B27 (3.0.9): give the memory back after a render. Discord .molot, 28.10.2026:
+ * after a picture or a video, ComfyUI kept its models in graphics memory and
+ * in RAM until it was closed.
+ *
+ * That was on purpose (vram-handoff, "bug C"): the next render reuses the warm
+ * model instead of reading 10 to 20 GB again, 70 s on the test box. So the
+ * choice is the user's, with a default that keeps both: a run of renders stays
+ * warm, a machine left alone gets its memory back.
+ *
+ * 'idle' (default) frees five minutes after the last render, unless another
+ * one started in between
+ * 'now' frees right after the render; a short grace keeps a chain (a long
+ * clip in sections, the character image then its video) from
+ * reloading between its steps
+ * 'keep' never frees, the behaviour before 3.0.9
+ *
+ * What is freed is ComfyUI's: `/free` with unload_models and free_memory
+ * unloads every model from the card and drops ComfyUI's node cache, which is
+ * what holds the weights in RAM (ComfyUI main.py, prompt_worker). The chat
+ * models are not touched here: the hand-off already gives them back after a
+ * render, and Ollama's own keep_alive unloads them when nobody chats.
+ */
+
+import { freeMemory } from '../api/comfyui'
+import { log } from './logger'
+
+export type FreeAfterRender = 'idle' | 'now' | 'keep'
+
+export const FREE_AFTER_RENDER_DEFAULT: FreeAfterRender = 'idle'
+/** 'idle': how long nothing has to render before the memory goes back. */
+export const FREE_AFTER_IDLE_MS = 5 * 60_000
+/** 'now': the grace that lets the next step of a chain start warm. */
+export const FREE_AFTER_NOW_GRACE_MS = 15_000
+
+/** The setting as stored, with the default for a profile that never had it. */
+export function freeAfterRenderMode(value: unknown): FreeAfterRender {
+ return value === 'now' || value === 'keep' || value === 'idle' ? value : FREE_AFTER_RENDER_DEFAULT
+}
+
+/** How long after a render the memory goes back, or null for never. */
+export function freeAfterDelayMs(mode: FreeAfterRender): number | null {
+ if (mode === 'keep') return null
+ return mode === 'now' ? FREE_AFTER_NOW_GRACE_MS : FREE_AFTER_IDLE_MS
+}
+
+let pending: ReturnType<typeof setTimeout> | null = null
+
+/** A render starts: whatever was planned to be freed stays, it is about to be used. */
+export function cancelFreeAfterRender(): void {
+ if (pending) clearTimeout(pending)
+ pending = null
+}
+
+/**
+ * A ComfyUI render ended (done, failed or cancelled). Plans the free for the
+ * mode. `busy` is asked again when the time comes: a render that started in
+ * between without passing cancelFreeAfterRender (another surface) keeps its
+ * models. Never throws.
+ */
+export function scheduleFreeAfterRender(mode: FreeAfterRender, busy: () => boolean, free: () => Promise<void> = freeMemory): void {
+ cancelFreeAfterRender()
+ const delay = freeAfterDelayMs(mode)
+ if (delay === null) return
+ pending = setTimeout(() => {
+ pending = null
+ if (busy()) return
+ log.info('render.free_after', { mode })
+ void free().catch(() => { /* best effort */ })
+ }, delay)
+}
+
+/** Tests: is a free planned? */
+export function freeAfterRenderPending(): boolean {
+ return pending !== null
+}
diff --git a/src/lib/settings-catalog.ts b/src/lib/settings-catalog.ts
index 2ac76f0e..a9c2edc0 100644
--- a/src/lib/settings-catalog.ts
+++ b/src/lib/settings-catalog.ts
@@ -229,6 +229,7 @@ export const CATALOG: readonly CatalogEntry[] = [
e('builtinEngine.cacheTypeK', 'KV cache K (LU Engine)', 'backends', 'K cache type, f16 = unquantized.', oneOf(['f16', 'bf16', 'q8_0', 'q4_0'])),
e('builtinEngine.cacheTypeV', 'KV cache V (LU Engine)', 'backends', 'V cache type; quantized needs flash attention.', oneOf(['f16', 'bf16', 'q8_0', 'q4_0'])),
e('exclusiveVramMode', 'Free VRAM for images', 'backends', 'Unload the chat model while an image or video renders.', oneOf(['auto', 'always', 'never'])),
+ e('freeAfterRender', 'Free memory after a render', 'backends', 'Unload the image and video models from VRAM and RAM: idle = after 5 minutes without a new render, now = right after, keep = never.', oneOf(['idle', 'now', 'keep'])),
e('comfyGpuMode', 'ComfyUI device', 'backends', 'Run ComfyUI on the GPU or the CPU.', oneOf(['auto', 'cpu', 'gpu'])),
e('downloadLimitMBps', 'Download limit', 'backends', 'Cap for model downloads.', int(0, 10_000, 'MB/s', 'no limit')),
// Code
diff --git a/src/types/settings.ts b/src/types/settings.ts
index 2e180257..eaadb15e 100644
--- a/src/types/settings.ts
+++ b/src/types/settings.ts
@@ -367,6 +367,13 @@ export interface Settings {
// local VRAM and are always skipped.
/** VRAM exclusivity policy for image/video generation. Default 'auto'. */
exclusiveVramMode: 'auto' | 'always' | 'never'
+ /**
+ * B27 (3.0.9): give ComfyUI's memory back after a render
+ * (lib/free-after-render). 'idle' (default) after five minutes without a
+ * new render, 'now' right after it, 'keep' never. Optional: a profile from
+ * before 3.0.9 reads as the default, no store version bump.
+ */
+ freeAfterRender?: 'idle' | 'now' | 'keep'
/**
* A picture or video the chat asked for that takes longer than a few
* seconds goes on in the background (3.0.8, A2). The turn ends, the chat can