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): a render evicts with manners and the chat comes back warm

purple165bdc136789
diff --git a/src/api/__tests__/create-render-handoff.test.ts b/src/api/__tests__/create-render-handoff.test.ts
new file mode 100644
index 00000000..7b4ba47c
--- /dev/null
+++ b/src/api/__tests__/create-render-handoff.test.ts
@@ -0,0 +1,232 @@
+/**
+ * Z36 finding 1 (W3 run 2026-08-16): a Create-tab render freed VRAM with one
+ * bare `offload_local_models` call. Both llama processes died with no KV
+ * save, nobody reloaded them, and the next chat turn paid a measured 62 s
+ * cold start. evictChatBackendsForRender / restoreChatBackendsAfterRender
+ * give that path the agent hand-off's manners: capture, KV-save, evict,
+ * restore. These tests pin the capture list, the save-before-kill order, the
+ * restore calls, the exclusiveVramMode 'never' opt-out (negative control)
+ * and the grace-window takeover for back-to-back renders.
+ *
+ * Run: npx vitest run src/api/__tests__/create-render-handoff.test.ts
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import fs from 'node:fs'
+import path from 'node:path'
+
+const localFetch = vi.fn()
+const listRunningModels = vi.fn()
+const loadModel = vi.fn()
+const unloadModel = vi.fn()
+const freeMemory = 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,
+}))
+
+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,
+ freeMemory: (...a: unknown[]) => freeMemory(...a),
+ }
+})
+
+vi.mock('../agent-context', () => ({
+ getActiveAgentModel: () => getActiveAgentModel(),
+}))
+
+vi.mock('../comfyui-ws', () => ({
+ comfyWS: { on: () => () => {}, connect: () => Promise.resolve(), connected: false },
+ CLIENT_ID: 'lu-test-client',
+}))
+
+import {
+ evictChatBackendsForRender,
+ restoreChatBackendsAfterRender,
+ __resetRenderJuggleForTests,
+ type RenderEviction,
+} from '../vram-handoff'
+import { useSettingsStore } from '../../stores/settingsStore'
+
+const GB = 1024 * 1024 * 1024
+
+/** backendCall programmed like the live box: engine up, save works. */
+function mockBackends(opts?: { engineRunning?: boolean; saveOk?: boolean }) {
+ backendCall.mockImplementation(async (cmd: unknown, args?: unknown) => {
+ if (cmd === 'bundled_engine_status') {
+ return (opts?.engineRunning ?? true)
+ ? { running: true, port: 8127, model_path: 'C:/models/qwen3-8b.gguf', modelBytes: 5 * GB }
+ : { running: false }
+ }
+ if (cmd === 'kv_slot_action') {
+ const a = args as { action?: string } | undefined
+ if (a?.action === 'save') return { ok: opts?.saveOk ?? true }
+ return { ok: true }
+ }
+ if (cmd === 'lmstudio_list_loaded') return { loaded: [] }
+ return {}
+ })
+}
+
+const callsTo = (cmd: string) =>
+ backendCall.mock.calls.filter((c) => c[0] === cmd)
+const callIndex = (cmd: string, pred?: (args: unknown) => boolean) =>
+ backendCall.mock.calls.findIndex((c) => c[0] === cmd && (!pred || pred(c[1])))
+
+beforeEach(() => {
+ localFetch.mockReset()
+ listRunningModels.mockReset()
+ loadModel.mockReset()
+ unloadModel.mockReset()
+ freeMemory.mockReset()
+ backendCall.mockReset()
+ getActiveAgentModel.mockReset()
+ __resetRenderJuggleForTests()
+ isOllamaLocalReturn = true
+ getActiveAgentModel.mockReturnValue(null)
+ loadModel.mockResolvedValue(undefined)
+ freeMemory.mockResolvedValue(undefined)
+ // One Ollama model resident in VRAM.
+ localFetch.mockResolvedValue({
+ ok: true,
+ json: async () => ({ models: [{ name: 'qwen:14b', size_vram: 9 * GB }] }),
+ })
+ mockBackends()
+ useSettingsStore.getState().updateSettings({ exclusiveVramMode: 'auto' })
+})
+
+afterEach(() => {
+ vi.useRealTimers()
+})
+
+describe('evictChatBackendsForRender', () => {
+ it('captures the resident backends and saves the KV slot BEFORE the kill', async () => {
+ const haul = await evictChatBackendsForRender()
+ expect(haul.ollamaModel).toBe('qwen:14b')
+ expect(haul.bundled?.modelPath).toBe('C:/models/qwen3-8b.gguf')
+ expect(haul.bundled?.slotSaved).toBe(true)
+ // The save must land before offload_local_models stops the engine, or
+ // there is nothing left to save.
+ const saveIdx = callIndex('kv_slot_action', (a) => (a as { action?: string })?.action === 'save')
+ const killIdx = callIndex('offload_local_models')
+ expect(saveIdx).toBeGreaterThanOrEqual(0)
+ expect(killIdx).toBeGreaterThanOrEqual(0)
+ expect(saveIdx).toBeLessThan(killIdx)
+ // The eviction pair still fires exactly as the Create tab always did.
+ expect(callsTo('offload_local_models')[0][1]).toEqual({ includeComfyui: false })
+ expect(callsTo('lmstudio_unload_model')).toHaveLength(1)
+ })
+
+ it('NEGATIVE: exclusiveVramMode never means no eviction at all', async () => {
+ useSettingsStore.getState().updateSettings({ exclusiveVramMode: 'never' })
+ 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('a failed KV save is honest: slotSaved false, eviction still happens', async () => {
+ mockBackends({ saveOk: false })
+ const haul = await evictChatBackendsForRender()
+ expect(haul.bundled?.slotSaved).toBe(false)
+ expect(callsTo('offload_local_models')).toHaveLength(1)
+ })
+})
+
+describe('restoreChatBackendsAfterRender', () => {
+ const fullHaul = (): RenderEviction => ({
+ ollamaModel: 'qwen:14b',
+ lms: { id: 'lms-model', contextLength: 16384 },
+ bundled: { port: 8127, modelPath: 'C:/models/qwen3-8b.gguf', modelBytes: 5 * GB, slotSaved: true },
+ })
+
+ it('brings every evicted backend back and restores the KV slot', async () => {
+ await restoreChatBackendsAfterRender(fullHaul(), 0)
+ expect(freeMemory).toHaveBeenCalledTimes(1)
+ // Engine restart rides through the real engine client (start_bundled_engine).
+ const starts = callsTo('start_bundled_engine')
+ expect(starts).toHaveLength(1)
+ expect(starts[0][1]).toMatchObject({ modelPath: 'C:/models/qwen3-8b.gguf' })
+ const restoreIdx = callIndex('kv_slot_action', (a) => (a as { action?: string })?.action === 'restore')
+ expect(restoreIdx).toBeGreaterThanOrEqual(0)
+ expect(loadModel).toHaveBeenCalledWith('qwen:14b')
+ const lmsLoads = callsTo('lmstudio_load_model')
+ expect(lmsLoads).toHaveLength(1)
+ expect(lmsLoads[0][1]).toMatchObject({ model: 'lms-model', contextLength: 16384 })
+ })
+
+ it('NEGATIVE: an unsaved slot is not restored (engine still restarts)', async () => {
+ const haul = fullHaul()
+ haul.bundled = { ...haul.bundled!, slotSaved: false }
+ await restoreChatBackendsAfterRender(haul, 0)
+ expect(callsTo('start_bundled_engine')).toHaveLength(1)
+ const restoreIdx = callIndex('kv_slot_action', (a) => (a as { action?: string })?.action === 'restore')
+ expect(restoreIdx).toBe(-1)
+ })
+
+ it('NEGATIVE: an empty haul touches nothing', async () => {
+ await restoreChatBackendsAfterRender({ ollamaModel: null, lms: null, bundled: null }, 0)
+ expect(freeMemory).not.toHaveBeenCalled()
+ expect(backendCall).not.toHaveBeenCalled()
+ expect(loadModel).not.toHaveBeenCalled()
+ })
+
+ it('a render starting inside the grace window inherits the haul instead of a reload', async () => {
+ vi.useFakeTimers()
+ // The follow-up render finds the engine already stopped and no Ollama
+ // resident (everything is still evicted from render #1).
+ mockBackends({ engineRunning: false })
+ localFetch.mockResolvedValue({ ok: true, json: async () => ({ models: [] }) })
+
+ const pRestore = restoreChatBackendsAfterRender(fullHaul())
+ const pEvict = evictChatBackendsForRender() // arrives inside the grace window
+ await vi.advanceTimersByTimeAsync(5_000)
+ await pRestore
+ const second = await pEvict
+
+ // The restore skipped: nothing was reloaded just to be evicted again.
+ expect(callsTo('start_bundled_engine')).toHaveLength(0)
+ expect(loadModel).not.toHaveBeenCalled()
+ // The second render's haul carries the inherited backends.
+ expect(second.bundled?.modelPath).toBe('C:/models/qwen3-8b.gguf')
+ expect(second.ollamaModel).toBe('qwen:14b')
+ expect(second.lms?.id).toBe('lms-model')
+ })
+
+ it('with no follow-up render the grace window elapses and the reload happens', async () => {
+ vi.useFakeTimers()
+ const pRestore = restoreChatBackendsAfterRender(fullHaul())
+ await vi.advanceTimersByTimeAsync(5_000)
+ await pRestore
+ expect(callsTo('start_bundled_engine')).toHaveLength(1)
+ expect(loadModel).toHaveBeenCalledWith('qwen:14b')
+ })
+})
+
+describe('wiring: useCreate uses the hand-off helpers', () => {
+ const read = (rel: string) => fs.readFileSync(path.resolve(__dirname, rel), 'utf8')
+
+ it('evicts via the helper, restores in its finally, bare offload pair is gone', () => {
+ const src = read('../../hooks/useCreate.ts')
+ expect(src).toContain('evictChatBackendsForRender()')
+ expect(src).toContain('restoreChatBackendsAfterRender(renderEviction)')
+ // The exact uncaptured kill Z36 flagged must not come back.
+ expect(src).not.toContain("backendCall('offload_local_models'")
+ expect(src).not.toContain("backendCall('lmstudio_unload_model'")
+ })
+})
diff --git a/src/api/vram-handoff.ts b/src/api/vram-handoff.ts
index d9c4059f..0c0ecc1d 100644
--- a/src/api/vram-handoff.ts
+++ b/src/api/vram-handoff.ts
@@ -1731,3 +1731,200 @@ function readSettingNumber(key: 'imageGenTimeoutMinutes' | 'videoGenTimeoutMinut
return null
}
}
+
+// ..................................................................
+// Create-tab render juggling (Z36 finding 1, W3 run 2026-08-16)
+//
+// The Create/music/video lanes used to free VRAM with one bare
+// `offload_local_models` call: both llama processes died with no KV save and
+// nobody reloaded them, so the next chat turn paid a measured 62 s cold
+// start. These two functions give that path the same discipline the agent
+// hand-off above has: capture what is resident, save the built-in engine's
+// KV slot, evict, and after the render bring everything back warm.
+//
+// The eviction itself stays as eager as before. The render should own the
+// whole card; a resident chat model forces ComfyUI into heavy CPU offload
+// even when nothing OOMs, so unlike the agent path there is no fits-or-not
+// math here. One exception: exclusiveVramMode 'never' now really means
+// never, matching decideUnload's contract for the agent path.
+
+export interface RenderEviction {
+ /** Ollama model that was resident in VRAM and should come back. */
+ ollamaModel: string | null
+ /** LM Studio model (with its loaded context length) to reload. */
+ lms: LmsTextModel | null
+ /** Built-in llama-server to restart, and whether its KV slot was saved. */
+ bundled: (BundledTarget & { slotSaved: boolean }) | null
+}
+
+const EMPTY_EVICTION: RenderEviction = { ollamaModel: null, lms: null, bundled: null }
+
+function evictionEmpty(e: RenderEviction): boolean {
+ return !e.ollamaModel && !e.lms && !e.bundled
+}
+
+// Evict/restore pairs run serialised through one chain so they never overlap.
+// A finished render parks its haul in _pendingRestore for a short grace
+// window; a NEW eviction inside that window inherits the haul instead of
+// letting it load, so back-to-back renders skip the pointless reload cycle.
+let _renderJuggle: Promise<unknown> = Promise.resolve()
+let _renderEpoch = 0
+let _pendingRestore: RenderEviction | null = null
+export const RENDER_RESTORE_GRACE_MS = 2_000
+
+/** Test-only: reset the render-juggle chain state between unit tests. */
+export function __resetRenderJuggleForTests(): void {
+ _renderJuggle = Promise.resolve()
+ _renderEpoch = 0
+ _pendingRestore = null
+}
+
+function mergeEvictions(base: RenderEviction | null, add: RenderEviction): RenderEviction {
+ if (!base) return add
+ return {
+ ollamaModel: add.ollamaModel ?? base.ollamaModel,
+ lms: add.lms ?? base.lms,
+ bundled: add.bundled ?? base.bundled,
+ }
+}
+
+/**
+ * Free the GPU for a Create-tab render, remembering what was evicted so
+ * restoreChatBackendsAfterRender can bring it back. Never throws; a failed
+ * probe just means that backend is not in the haul.
+ */
+export function evictChatBackendsForRender(): Promise<RenderEviction> {
+ _renderEpoch++
+ const run = _renderJuggle.catch(() => {}).then(() => evictBody())
+ _renderJuggle = run.catch(() => {})
+ return run.catch(() => ({ ...EMPTY_EVICTION }))
+}
+
+async function evictBody(): Promise<RenderEviction> {
+ // A restore that has not run yet is inherited wholesale: whatever it wanted
+ // to bring back stays evicted and becomes THIS render's restore duty.
+ const inherited = _pendingRestore
+ _pendingRestore = null
+
+ if (getExclusiveVramMode() === 'never') {
+ // The user opted out of VRAM juggling; do not touch the resident chat
+ // backends. An inherited haul still needs restoring after this render.
+ return inherited ?? { ...EMPTY_EVICTION }
+ }
+
+ const result: RenderEviction = { ...EMPTY_EVICTION }
+
+ // Capture BEFORE the kill so the restore list is honest.
+ if (isOllamaLocal()) {
+ try {
+ const resident = await getResidentModels()
+ const target = pickResidentOllamaTarget(resident, getActiveAgentModel())
+ if (target) result.ollamaModel = target.name
+ } catch { /* nothing resident to remember */ }
+ }
+ try {
+ const lms = (await detectLmsTextModel(getActiveAgentModel())) ?? (await detectAnyLoadedLmsModel())
+ if (lms) result.lms = lms
+ } catch { /* LM Studio absent */ }
+ const bundled = await detectBundledEngine()
+ if (bundled) {
+ // GH #85 discipline for the Create path too: serialize the KV cache so
+ // the reload after the render does not re-process the whole history.
+ const saved = await backendCall<{ ok?: boolean }>('kv_slot_action', { port: bundled.port, action: 'save' }).catch(() => null)
+ if (saved?.ok !== true) log.warn('render_juggle.kv_save_failed', { port: bundled.port })
+ result.bundled = { ...bundled, slotSaved: saved?.ok === true }
+ }
+
+ // The actual eviction, exactly the pair of calls the Create tab always
+ // made: offload_local_models stops Ollama residents and both managed
+ // sidecars, lmstudio_unload_model clears LM Studio. Best effort, a failed
+ // call must never block a render.
+ await Promise.all([
+ backendCall('offload_local_models', { includeComfyui: false }).catch(() => {}),
+ backendCall('lmstudio_unload_model', { model: '--all' }).catch(() => {}),
+ ])
+
+ // Merge an inherited haul: it describes models that are STILL evicted from
+ // an earlier render whose restore never ran. Fresh captures win on
+ // conflict, they are the newer truth about the same backend.
+ const merged = inherited ? mergeEvictions(inherited, result) : result
+ log.info('render_juggle.evicted', {
+ ollama: merged.ollamaModel,
+ lms: merged.lms?.id ?? null,
+ bundled: merged.bundled?.modelPath ?? null,
+ })
+ return merged
+}
+
+/**
+ * Bring the evicted chat backends back after a render (success, failure or
+ * cancel). Waits a short grace window first so a follow-up render can take
+ * over the haul instead of paying reload-then-evict. Never throws.
+ */
+export function restoreChatBackendsAfterRender(
+ evicted: RenderEviction,
+ graceMs: number = RENDER_RESTORE_GRACE_MS,
+): Promise<void> {
+ // Snapshot the epoch AT CALL TIME, not when the body gets its turn on the
+ // chain: an eviction that lands in between must count as "newer render".
+ const myEpoch = _renderEpoch
+ const run = _renderJuggle.catch(() => {}).then(() => restoreBody(evicted, graceMs, myEpoch))
+ _renderJuggle = run.catch(() => {})
+ return run.catch(() => {})
+}
+
+async function restoreBody(evicted: RenderEviction, graceMs: number, myEpoch: number): Promise<void> {
+ if (evictionEmpty(evicted)) return
+ _pendingRestore = mergeEvictions(_pendingRestore, evicted)
+ if (_renderEpoch !== myEpoch) return // a newer render inherits the haul
+ if (graceMs > 0) await sleep(graceMs)
+ if (_renderEpoch !== myEpoch) return // a newer render inherits the haul
+ const todo = _pendingRestore
+ _pendingRestore = null
+ if (!todo || evictionEmpty(todo)) return
+
+ // Give the chat backends their VRAM back. freeMemory drops ComfyUI's
+ // cached checkpoint; without it the reloads below can OOM right after a
+ // big render.
+ try { await freeMemory() } catch { /* best effort */ }
+ if (todo.bundled) {
+ try {
+ await startBundledEngine(todo.bundled.modelPath)
+ if (todo.bundled.slotSaved) {
+ const restored = await backendCall<{ ok?: boolean }>('kv_slot_action', { port: todo.bundled.port, action: 'restore' }).catch(() => null)
+ if (restored?.ok !== true) {
+ // Non-fatal: the next turn re-processes the history, the pre-#85 cost.
+ log.warn('render_juggle.kv_restore_failed', { port: todo.bundled.port })
+ }
+ }
+ } catch (e) {
+ log.warn('render_juggle.bundled_reload_failed', { err: String(e instanceof Error ? e.message : e) })
+ }
+ }
+ if (todo.ollamaModel) {
+ try {
+ await loadModel(todo.ollamaModel)
+ } catch (e) {
+ // No ComfyUI-restart recovery here on purpose: on the Create tab the
+ // user's next step is usually another render, so stopping ComfyUI to
+ // rescue a chat model would be the wrong trade. Ollama lazy-loads on
+ // the next message anyway.
+ log.warn('render_juggle.ollama_reload_failed', { model: todo.ollamaModel, err: String(e instanceof Error ? e.message : e) })
+ }
+ }
+ if (todo.lms) {
+ try {
+ await backendCall('lmstudio_load_model', {
+ model: todo.lms.id,
+ ...(todo.lms.contextLength ? { contextLength: todo.lms.contextLength } : {}),
+ })
+ } catch (e) {
+ log.warn('render_juggle.lms_reload_failed', { model: todo.lms.id, err: String(e instanceof Error ? e.message : e) })
+ }
+ }
+ log.info('render_juggle.restored', {
+ ollama: todo.ollamaModel,
+ lms: todo.lms?.id ?? null,
+ bundled: todo.bundled?.modelPath ?? null,
+ })
+}
diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.ts
index 68a406da..5f2458f4 100644
--- a/src/hooks/useCreate.ts
+++ b/src/hooks/useCreate.ts
@@ -30,7 +30,12 @@ import {
type ComfyUIOutput,
type VideoBackend,
} from '../api/comfyui'
-import { comfyErrorHint } from '../api/vram-handoff'
+import {
+ comfyErrorHint,
+ evictChatBackendsForRender,
+ restoreChatBackendsAfterRender,
+ type RenderEviction,
+} from '../api/vram-handoff'
import {
comfyWS, CLIENT_ID,
LOADER_NODES, CLIP_LOADER_NODES, VAE_LOADER_NODES, SAMPLER_NODES, DECODE_NODES,
@@ -40,7 +45,6 @@ import { buildDynamicWorkflow, buildLocalOpWorkflow, checkVideoOutputCapability
import { getAllNodeInfo, clearNodeCache } from '../api/comfyui-nodes'
import { restartComfyForNewNodes } from '../api/comfy-restart'
import { installCustomNodes } from '../api/discover'
-import { backendCall } from '../api/backend'
import { checkPromptSafety, SAFETY_BLOCK_MESSAGE } from '../lib/render/safety'
import { resolveRunSeed } from '../lib/run-seed'
import {
@@ -782,16 +786,17 @@ export function useCreate() {
// 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
- // ComfyUI into heavy CPU offload — or a CUDA OOM on the 14B video lanes
- // (S2V / Animate). Free the chat backends first (they reload lazily on the
- // next message) but keep ComfyUI's own checkpoint cached across runs
- // (includeComfyui:false). Best-effort — never block a render on housekeeping.
+ // ComfyUI into heavy CPU offload, or a CUDA OOM on the 14B video lanes
+ // (S2V / Animate). Z36: this used to be a bare offload_local_models call
+ // that killed both llama processes with no KV save and no reload, costing
+ // the next chat turn a 62 s cold start. The hand-off helper captures what
+ // is resident, saves the built-in engine's KV slot, then evicts; the
+ // finally below brings everything back. exclusiveVramMode 'never' skips
+ // the eviction. Best-effort, never blocks a render.
+ let renderEviction: RenderEviction | null = null
try {
- await Promise.all([
- backendCall('offload_local_models', { includeComfyui: false }).catch(() => {}),
- backendCall('lmstudio_unload_model', { model: '--all' }).catch(() => {}),
- ])
- } catch { /* ignore — VRAM housekeeping is best-effort */ }
+ renderEviction = await evictChatBackendsForRender()
+ } catch { /* VRAM housekeeping is best-effort */ }
try {
let outputWidth = width
@@ -1379,6 +1384,11 @@ export function useCreate() {
useCreateStore.getState().setCurrentPromptId(null)
if (pollRef.current) { clearInterval(pollRef.current); pollRef.current = null }
abortRef.current = null
+ // Bring the evicted chat backends back (Z36). Fire and forget: the
+ // reload can take a minute and must not hold the Create UI or the
+ // 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)
}
}, [videoBackend, runCharacterTraining])