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(create): the chat model comes back when it is needed, not two seconds after every render
purple0653be396e33
diff --git a/src/api/__tests__/create-render-handoff.test.ts b/src/api/__tests__/create-render-handoff.test.tsindex 1b3d29df..42f928c3 100644--- a/src/api/__tests__/create-render-handoff.test.ts+++ b/src/api/__tests__/create-render-handoff.test.ts@@ -6,7 +6,8 @@* 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.+ * and the takeover of a parked haul by back-to-back renders. Since 3.0.5 the+ * restore waits for a need while Create is open (last describe blocks).** Run: npx vitest run src/api/__tests__/create-render-handoff.test.ts*/@@ -57,10 +58,15 @@ vi.mock('../comfyui-ws', () => ({import {evictChatBackendsForRender,restoreChatBackendsAfterRender,+ restoreChatBackendsNow,+ setRenderSurfaceOpen,holdRenderRestore,__resetRenderJuggleForTests,+ RENDER_RESTORE_GRACE_MS,+ RENDER_RESTORE_IDLE_MS,type RenderEviction,} from '../vram-handoff'+import { chatBackendsBack } from '../../lib/chat-backends-gate'import { useSettingsStore } from '../../stores/settingsStore'const GB = 1024 * 1024 * 1024@@ -344,6 +350,138 @@ describe('the eviction says what the wait is spent on', () => {})})+// The box, 04.10.2026 (LM Studio, a 6 GB chat model, about 7 s to load): the+// chat model was read back in 2 s after every render. A second render started+// shortly after waited up to 30 s for that load to finish and then unloaded+// the model again. While Create is open the haul now stays parked until the+// chat model is needed.+describe('while Create is open the chat model comes back when it is needed', () => {+ const LMS = { id: 'qwen/qwen2.5-vl-7b', contextLength: 8192 }+ const haul = (): RenderEviction => ({+ ollamaModel: 'qwen:14b',+ lms: LMS,+ bundled: { port: 8127, modelPath: 'C:/models/qwen3-8b.gguf', modelBytes: 5 * GB, slotSaved: true },+ })+ const nothingLoaded = () => {+ expect(freeMemory).not.toHaveBeenCalled()+ expect(loadModel).not.toHaveBeenCalled()+ expect(callsTo('lmstudio_load_model')).toHaveLength(0)+ expect(callsTo('start_bundled_engine')).toHaveLength(0)+ }+ const allLoaded = () => {+ expect(freeMemory).toHaveBeenCalledTimes(1)+ expect(loadModel).toHaveBeenCalledTimes(1)+ expect(loadModel).toHaveBeenCalledWith('qwen:14b')+ expect(callsTo('lmstudio_load_model')).toHaveLength(1)+ expect(callsTo('lmstudio_load_model')[0][1]).toMatchObject({ model: LMS.id, contextLength: 8192 })+ expect(callsTo('start_bundled_engine')).toHaveLength(1)+ expect(callIndex('kv_slot_action', (a) => (a as { action?: string })?.action === 'restore')).toBeGreaterThanOrEqual(0)+ }+ /** Everything is still evicted from the render before. */+ const stillEvicted = () => {+ mockBackends({ engineRunning: false })+ localFetch.mockResolvedValue({ ok: true, json: async () => ({ models: [] }) })+ }++ beforeEach(() => {+ vi.useFakeTimers()+ setRenderSurfaceOpen(true)+ })++ it('two renders in a row: nothing is loaded in between, and the second does not wait', async () => {+ await restoreChatBackendsAfterRender(haul())+ // The user looks at the picture and writes the next prompt: far longer+ // than the old 2 s, long enough for the old reload to be in full swing.+ await vi.advanceTimersByTimeAsync(45_000)+ nothingLoaded()++ stillEvicted()+ const phases: string[] = []+ const second = await evictChatBackendsForRender((p) => phases.push(p))+ expect(phases).toEqual(['freeing'])+ nothingLoaded()+ // The second render carries the duty to bring the first one's haul back.+ expect(second.lms).toEqual(LMS)+ expect(second.ollamaModel).toBe('qwen:14b')+ expect(second.bundled?.modelPath).toBe('C:/models/qwen3-8b.gguf')++ // And nothing fires behind its back while it renders.+ await vi.advanceTimersByTimeAsync(RENDER_RESTORE_IDLE_MS * 2)+ nothingLoaded()+ })++ it('a chat request after the render brings everything back before it is sent', async () => {+ await restoreChatBackendsAfterRender(haul())+ await vi.advanceTimersByTimeAsync(10_000)+ nothingLoaded()+ await chatBackendsBack()+ allLoaded()+ // Once. The next message has nothing to wait for, and the idle time+ // brings nothing back a second time.+ await chatBackendsBack()+ await vi.advanceTimersByTimeAsync(RENDER_RESTORE_IDLE_MS * 2)+ allLoaded()+ })++ it('leaving Create brings everything back', async () => {+ await restoreChatBackendsAfterRender(haul())+ await vi.advanceTimersByTimeAsync(10_000)+ nothingLoaded()+ setRenderSurfaceOpen(false)+ await restoreChatBackendsNow()+ allLoaded()+ })++ it('nobody asks: after the idle time everything comes back by itself', async () => {+ expect(RENDER_RESTORE_IDLE_MS).toBeGreaterThanOrEqual(120_000)+ await restoreChatBackendsAfterRender(haul())+ await vi.advanceTimersByTimeAsync(RENDER_RESTORE_IDLE_MS - 1_000)+ nothingLoaded()+ await vi.advanceTimersByTimeAsync(2_000)+ await restoreChatBackendsNow()+ allLoaded()+ })++ it('a render that ends after Create was left restores after the short grace window', async () => {+ setRenderSurfaceOpen(false)+ await restoreChatBackendsNow()+ await restoreChatBackendsAfterRender(haul())+ nothingLoaded()+ await vi.advanceTimersByTimeAsync(RENDER_RESTORE_GRACE_MS + 500)+ await restoreChatBackendsNow()+ allLoaded()+ })++ it('a chat request with nothing parked waits for nothing and touches nothing', async () => {+ await chatBackendsBack()+ expect(backendCall).not.toHaveBeenCalled()+ nothingLoaded()+ })++ it('a chat request between two pictures of a batch does not take the card from the batch', async () => {+ const release = holdRenderRestore()+ await evictChatBackendsForRender()+ backendCall.mockClear()+ await restoreChatBackendsAfterRender(haul())+ await chatBackendsBack()+ nothingLoaded()+ release()+ await chatBackendsBack()+ allLoaded()+ })++ it('a render that fails or is cancelled parks its haul the same way: a chat request gets the model', async () => {+ stillEvicted()+ const taken = await evictChatBackendsForRender()+ expect(taken.ollamaModel).toBeNull()+ // useCreate's finally hands back what the run held, here the haul of the+ // render before it.+ await restoreChatBackendsAfterRender(haul())+ await chatBackendsBack()+ expect(loadModel).toHaveBeenCalledWith('qwen:14b')+ })+})+describe('wiring: useCreate uses the hand-off helpers', () => {const read = (rel: string) => fs.readFileSync(path.resolve(__dirname, rel), 'utf8')@@ -356,4 +494,14 @@ describe('wiring: useCreate uses the hand-off helpers', () => {expect(src).not.toContain("backendCall('offload_local_models'")expect(src).not.toContain("backendCall('lmstudio_unload_model'")})++ it('Create says when it is on screen, and the local providers ask for the chat model before they send', () => {+ const create = read('../../components/create/experimental/CreateExperimental.tsx')+ expect(create).toContain('setRenderSurfaceOpen(true)')+ expect(create).toContain('return () => setRenderSurfaceOpen(false)')+ const ollama = read('../providers/ollama-provider.ts')+ expect(ollama.split('await chatBackendsBack()').length - 1).toBe(2)+ const openai = read('../providers/openai-provider.ts')+ expect(openai.split('if (this.isLanBackend) await chatBackendsBack()').length - 1).toBe(2)+ })})diff --git a/src/api/providers/__tests__/a-chat-request-waits-for-the-chat-model.test.ts b/src/api/providers/__tests__/a-chat-request-waits-for-the-chat-model.test.tsnew file mode 100644index 00000000..1896bd50--- /dev/null+++ b/src/api/providers/__tests__/a-chat-request-waits-for-the-chat-model.test.ts@@ -0,0 +1,127 @@+/**+ * A Create render moves the local chat model off the graphics card and, since+ * 3.0.5, leaves it out until it is needed (api/vram-handoff). The need is a+ * chat request: the local providers wait for the parked restore before they+ * send, so nobody chats into an unloaded LM Studio or a stopped engine. A+ * hosted endpoint has no model on this machine and waits for nothing.+ *+ * Run: npx vitest run src/api/providers/__tests__/a-chat-request-waits-for-the-chat-model.test.ts+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import type { ProviderConfig, ChatStreamChunk } from '../types'++const order: string[] = []+const streamBody = 'data: {"choices":[{"delta":{"content":"hi"}}]}\n\ndata: [DONE]\n\n'+const ollamaBody = '{"message":{"role":"assistant","content":"hi"},"done":true}\n'++async function load() {+ vi.resetModules()+ const respond = async (url: string, init?: { body?: string }) => {+ // Only the chat request itself counts; a local provider may read the+ // model's context window first, which loads nothing.+ if (/\/chat\/completions|\/api\/chat/.test(String(url))) order.push('request')+ const body = typeof init?.body === 'string' ? JSON.parse(init.body) as { stream?: boolean } : {}+ if (String(url).includes('/api/chat')) {+ return new Response(body.stream ? ollamaBody : JSON.stringify({ message: { role: 'assistant', content: 'ok' } }), { status: 200 })+ }+ if (body.stream) return new Response(streamBody, { status: 200 })+ return new Response(JSON.stringify({ choices: [{ message: { content: 'ok' } }] }), { status: 200 })+ }+ vi.doMock('../../backend', () => ({+ localFetch: vi.fn(respond),+ localFetchStream: vi.fn(respond),+ backendCall: vi.fn(),+ ollamaUrl: (path: string) => `/api${path}`,+ isPrivateOrLanHost: (host: string) => host === 'localhost' || host === '127.0.0.1',+ isDirectFetchAllowed: () => true,+ hostnameOf: (url: string) => new URL(url).hostname,+ ensureProxyAllowsHost: vi.fn(),+ isTauri: () => false,+ }))+ vi.doMock('../../builtin-ensure', () => ({+ ensureBuiltinEngineAlive: vi.fn(),+ explainDeadEngine: (e: unknown) => e,+ explainEngineTransportMessage: (m: string) => m,+ isManagedBuiltinSlot: () => false,+ }))+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (url, init) => respond(String(url), { body: typeof init?.body === 'string' ? init.body : undefined }))+ const gate = await import('../../../lib/chat-backends-gate')+ const { OpenAIProvider } = await import('../openai-provider')+ const { OllamaProvider } = await import('../ollama-provider')+ return { gate, OpenAIProvider, OllamaProvider }+}++const LM_STUDIO: ProviderConfig = { id: 'openai', name: 'LM Studio', apiKey: '', enabled: true, baseUrl: 'http://127.0.0.1:1234/v1', isLocal: true }+const HOSTED: ProviderConfig = { id: 'openai', name: 'Hosted', apiKey: 'k', enabled: true, baseUrl: 'https://api.example.com/v1', isLocal: false }+const OLLAMA: ProviderConfig = { id: 'ollama', name: 'Ollama', apiKey: '', enabled: true, baseUrl: 'http://localhost:11434', isLocal: true }+const USER = [{ role: 'user' as const, content: 'hi' }]++async function drain(gen: AsyncGenerator<ChatStreamChunk>) {+ for await (const _ of gen) { /* the request fires on the first next() */ }+}+/** A restore that takes a moment, like a model load. */+const parkedRestore = () => vi.fn(async () => {+ order.push('restore started')+ await new Promise((r) => setTimeout(r, 20))+ order.push('restore done')+})++beforeEach(() => { order.length = 0 })+afterEach(() => {+ vi.doUnmock('../../backend')+ vi.doUnmock('../../builtin-ensure')+ vi.restoreAllMocks()+ vi.resetModules()+})++describe('a chat request while a render has the chat model parked', () => {+ it('LM Studio and the built-in engine (OpenAI compatible, local): the stream waits for the restore', async () => {+ const { gate, OpenAIProvider } = await load()+ const restore = parkedRestore()+ gate.setChatBackendsRestore(restore)+ await drain(new OpenAIProvider(LM_STUDIO).chatStream('m', USER))+ expect(restore).toHaveBeenCalledTimes(1)+ expect(order.slice(0, 3)).toEqual(['restore started', 'restore done', 'request'])+ })++ it('the same for a tool turn', async () => {+ const { gate, OpenAIProvider } = await load()+ gate.setChatBackendsRestore(parkedRestore())+ await new OpenAIProvider(LM_STUDIO).chatWithTools('m', USER, [])+ expect(order.slice(0, 3)).toEqual(['restore started', 'restore done', 'request'])+ })++ it('Ollama: stream and tool turn wait for the restore', async () => {+ const { gate, OllamaProvider } = await load()+ const restore = parkedRestore()+ gate.setChatBackendsRestore(restore)+ await drain(new OllamaProvider(OLLAMA).chatStream('qwen:14b', USER))+ expect(order.slice(0, 3)).toEqual(['restore started', 'restore done', 'request'])+ order.length = 0+ await new OllamaProvider(OLLAMA).chatWithTools('qwen:14b', USER, [])+ expect(order.slice(0, 3)).toEqual(['restore started', 'restore done', 'request'])+ })++ it('a hosted endpoint has no model on this machine: it sends at once', async () => {+ const { gate, OpenAIProvider } = await load()+ const restore = parkedRestore()+ gate.setChatBackendsRestore(restore)+ await drain(new OpenAIProvider(HOSTED).chatStream('m', USER))+ expect(restore).not.toHaveBeenCalled()+ expect(order).toContain('request')+ })++ it('nothing parked: nothing to wait for', async () => {+ const { gate, OpenAIProvider } = await load()+ gate.setChatBackendsRestore(null)+ await drain(new OpenAIProvider(LM_STUDIO).chatStream('m', USER))+ expect(order[0]).toBe('request')+ })++ it('a restore that fails does not stop the message', async () => {+ const { gate, OpenAIProvider } = await load()+ gate.setChatBackendsRestore(async () => { throw new Error('LM Studio is not running') })+ await drain(new OpenAIProvider(LM_STUDIO).chatStream('m', USER))+ expect(order).toContain('request')+ })+})diff --git a/src/api/providers/ollama-provider.ts b/src/api/providers/ollama-provider.tsindex 7985cc29..296e0c43 100644--- a/src/api/providers/ollama-provider.ts+++ b/src/api/providers/ollama-provider.ts@@ -1,3 +1,4 @@+import { chatBackendsBack } from '../../lib/chat-backends-gate'import { resolveMessageAttachments } from '../../lib/chat-attachments'/*** Ollama Provider, wraps existing ollama.ts into the ProviderClient interface.@@ -120,6 +121,8 @@ export class OllamaProvider implements ProviderClient {// llama.cpp does, and a strict one raises instead of improvising. See// providers/normalize-system.ts for the whole contract.messages = await resolveMessageAttachments(messages)+ // A Create render may have moved the chat model out (vram-handoff).+ await chatBackendsBack()const ollamaMessages = applyTemplateContract(messages, {toolRole: 'text',alternate: true,@@ -292,6 +295,8 @@ export class OllamaProvider implements ProviderClient {// only sends one after Ollama itself reported the `tools` capability for// this model (/api/show, see lib/tool-support.ts).messages = await resolveMessageAttachments(messages)+ // A Create render may have moved the chat model out (vram-handoff).+ await chatBackendsBack()const ollamaMessages = applyTemplateContract(messages, {toolRole: tools.length > 0 ? 'native' : 'text',alternate: tools.length === 0,diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.tsindex a2827ae4..aabab14a 100644--- a/src/api/providers/openai-provider.ts+++ b/src/api/providers/openai-provider.ts@@ -25,6 +25,7 @@ import { repairJson } from '../../lib/tool-call-repair'import { signalCreditsExhausted } from '../../lib/credits-exhausted'import { parseRetryAfter } from '../../lib/http-status'import { localFetch, localFetchStream, isPrivateOrLanHost, isDirectFetchAllowed, hostnameOf, ensureProxyAllowsHost, backendCall } from '../backend'+import { chatBackendsBack } from '../../lib/chat-backends-gate'import { ensureBuiltinEngineAlive, explainDeadEngine, explainEngineTransportMessage, isManagedBuiltinSlot } from '../builtin-ensure'import { isLocalTransportFailure, localBackendUnreachableMessage, remoteBackendUnreachableMessage } from '../../lib/local-backend-transport'import { applyTemplateContract } from './normalize-system'@@ -855,6 +856,8 @@ export class OpenAIProvider implements ProviderClient {// child to free VRAM ("reloads lazily on the next message"), this is that// lazy reload. Restart-before-send instead of letting the fetch hit a dead// 127.0.0.1:8127 and look like a crashed backend.+ // A Create render may have moved this backend's model out (vram-handoff).+ if (this.isLanBackend) await chatBackendsBack()if (this.config.managed === true) await ensureBuiltinEngineAlive(model)if (this.useLocalProxy) await ensureProxyAllowsHost(this.baseUrl)@@ -1065,6 +1068,8 @@ export class OpenAIProvider implements ProviderClient {// Same self-heal as chatStream: agent/tool turns after a Create render// must revive the offloaded built-in engine before hitting its port.+ // A Create render may have moved this backend's model out (vram-handoff).+ if (this.isLanBackend) await chatBackendsBack()if (this.config.managed === true) await ensureBuiltinEngineAlive(model)if (this.useLocalProxy) await ensureProxyAllowsHost(this.baseUrl)diff --git a/src/api/vram-handoff.ts b/src/api/vram-handoff.tsindex a70cd6f3..333aa820 100644--- a/src/api/vram-handoff.ts+++ b/src/api/vram-handoff.ts@@ -44,6 +44,7 @@* of call #2 and re-trigger the exact OOM we are avoiding.*/+import { setChatBackendsRestore } from '../lib/chat-backends-gate'import { backendCall, ollamaUrl, localFetch, isOllamaLocal, isWindows } from './backend'import type { ComfyApiGraph } from '../types/comfy-graph'import { asNumber, asRecordArray, asString, prop } from '../types/json-guards'@@ -2200,17 +2201,38 @@ function evictionEmpty(e: RenderEviction): boolean {}// 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.+// A finished render parks its haul in _pendingRestore and the chat backends+// stay out until somebody needs them (see restoreChatBackendsAfterRender); a+// NEW eviction inherits the parked haul instead of letting it load, so+// back-to-back renders skip the pointless reload cycle.let _renderJuggle: Promise<unknown> = Promise.resolve()-let _renderEpoch = 0let _pendingRestore: RenderEviction | null = nulllet _restoreHolds = 0-/** True while a restore is past its grace window and is reloading the chat- * backends. An eviction that arrives now has to wait for that reload. */+let _restoreTimer: ReturnType<typeof setTimeout> | null = null+/** True while the Create view is on screen: the next thing the user does is+ * most likely another render. */+let _renderSurfaceOpen = false+/** True while a restore is reloading the chat backends. An eviction that+ * arrives now has to wait for that reload. */let _restoreInFlight = false+/** How long a parked haul waits when no render surface is open (a render that+ * finished after the user left Create, the trainer). */export const RENDER_RESTORE_GRACE_MS = 2_000+/** How long it waits while Create is open and nobody asks for the chat model.+ * After that the machine is put back the way it was found. */+export const RENDER_RESTORE_IDLE_MS = 180_000++function park(haul: RenderEviction | null): void {+ _pendingRestore = haul+ // A chat request that arrives while the haul is parked brings it back first+ // (lib/chat-backends-gate, asked by the local providers).+ setChatBackendsRestore(haul ? restoreChatBackendsNow : null)+}++function clearRestoreTimer(): void {+ if (_restoreTimer) clearTimeout(_restoreTimer)+ _restoreTimer = null+}/*** What the eviction is doing, for the waiting line of the run.@@ -2228,9 +2250,10 @@ export type RenderEvictionPhase = 'waiting-for-chat-model' | 'freeing'/** Test-only: reset the render-juggle chain state between unit tests. */export function __resetRenderJuggleForTests(): void {_renderJuggle = Promise.resolve()- _renderEpoch = 0- _pendingRestore = null+ clearRestoreTimer()+ park(null)_restoreHolds = 0+ _renderSurfaceOpen = false_restoreInFlight = false}@@ -2250,7 +2273,9 @@ function mergeEvictions(base: RenderEviction | null, add: RenderEviction): Rende* the wait is spent on (RenderEvictionPhase).*/export function evictChatBackendsForRender(onPhase?: (phase: RenderEvictionPhase) => void): Promise<RenderEviction> {- _renderEpoch+++ // A restore that is only planned is called off here and now: this render+ // inherits its haul (evictBody) instead of waiting for a reload.+ clearRestoreTimer()if (_restoreInFlight) onPhase?.('waiting-for-chat-model')const run = _renderJuggle.catch(() => {}).then(() => {onPhase?.('freeing')@@ -2264,7 +2289,7 @@ 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+ park(null)if (getExclusiveVramMode() === 'never') {// The user opted out of VRAM juggling; do not touch the resident chat@@ -2326,29 +2351,63 @@ async function evictBody(): Promise<RenderEviction> {}/**- * 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.+ * A render is over (success, failure or cancel): park what it evicted. The+ * chat backends do NOT come straight back. The box, 04.10.2026 (LM Studio,+ * a 6 GB chat model): the reload started 2 s after every render, and a second+ * render started shortly after it waited up to 30 s for a model to finish+ * loading that it then unloaded again. They come back when they are needed:+ *+ * - a chat request to a local backend (restoreChatBackendsNow through+ * lib/chat-backends-gate), which covers the chat, the agents and+ * "Improve my prompt" written by the chat model,+ * - Create is left (setRenderSurfaceOpen),+ * - or nobody asked for RENDER_RESTORE_IDLE_MS.+ *+ * With no render surface open the wait is the short grace window, as before.+ * A new render calls a planned restore off and inherits the haul. `delayMs`+ * of 0 restores at once. Never throws.+ */+export function restoreChatBackendsAfterRender(evicted: RenderEviction, delayMs?: number): Promise<void> {+ const run = _renderJuggle.catch(() => {}).then(() => {+ if (!evictionEmpty(evicted)) park(mergeEvictions(_pendingRestore, evicted))+ if (!_pendingRestore) return+ if (_restoreHolds > 0) return // the run restores once, at its end+ const wait = delayMs ?? (_renderSurfaceOpen ? RENDER_RESTORE_IDLE_MS : RENDER_RESTORE_GRACE_MS)+ if (wait <= 0) return restoreParked()+ clearRestoreTimer()+ _restoreTimer = setTimeout(() => { void restoreChatBackendsNow() }, wait)+ })+ _renderJuggle = run.catch(() => {})+ return run.catch(() => {})+}++/**+ * Bring the parked chat backends back now, because somebody needs them.+ * Resolves when they are loaded. Nothing parked, or a batch holding the+ * restore: resolves at once and touches nothing. 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))+export function restoreChatBackendsNow(): Promise<void> {+ const run = _renderJuggle.catch(() => {}).then(() => (_restoreHolds > 0 ? undefined : restoreParked()))_renderJuggle = run.catch(() => {})return run.catch(() => {})}+/**+ * Create came on screen or left it. While it is open a finished render keeps+ * the card for the next one; leaving it brings the chat backends back.+ */+export function setRenderSurfaceOpen(open: boolean): void {+ _renderSurfaceOpen = open+ if (!open) void restoreChatBackendsNow()+}+/*** A run of several renders in a row (batch edit) holds the restore: each* render still parks its haul, but nothing is freed or reloaded until the- * returned release is called. Then the chat backends come back once, after- * the usual grace window. Without the hold a picture that took longer than- * that window to start paid `/free` plus a chat model reload, and ComfyUI- * read the image model back in before every picture.+ * returned release is called. Then the haul waits like the one of a single+ * render. Without the hold a picture of the batch could meet a restore that+ * the idle time or a chat request had started, and ComfyUI read the image+ * model back in before the next picture.*/export function holdRenderRestore(): () => void {_restoreHolds++@@ -2361,15 +2420,10 @@ export function holdRenderRestore(): () => void {}}-async function restoreBody(evicted: RenderEviction, graceMs: number, myEpoch: number): Promise<void> {- if (!evictionEmpty(evicted)) _pendingRestore = mergeEvictions(_pendingRestore, evicted)- if (!_pendingRestore) return- if (_restoreHolds > 0) return // the run restores once, at its end- 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+async function restoreParked(): Promise<void> {+ clearRestoreTimer()const todo = _pendingRestore- _pendingRestore = null+ park(null)if (!todo || evictionEmpty(todo)) return// Give the chat backends their VRAM back. freeMemory drops ComfyUI'sdiff --git a/src/components/create/experimental/CreateExperimental.tsx b/src/components/create/experimental/CreateExperimental.tsxindex 98c81e11..629dce48 100644--- a/src/components/create/experimental/CreateExperimental.tsx+++ b/src/components/create/experimental/CreateExperimental.tsx@@ -9,6 +9,7 @@ import { comfyIdleNotice, shouldWatchComfyIdle, IDLE_WATCH_INTERVAL_MS, IDLE_STAimport type { ComfyGuardStatus } from '../../../lib/comfy-restart-guard'import { anyInstallRunning, subscribeInstallRuns } from '../../../lib/model-install-runs'import { useComfyInstallStore } from '../../../stores/comfyInstallStore'+import { setRenderSurfaceOpen } from '../../../api/vram-handoff'import { useWorkflowStore } from '../../../stores/workflowStore'import { CreateExpProvider, useCreateExp } from './CreateContext'import { IntentBar } from './IntentBar'@@ -169,6 +170,12 @@ function CreateExperimentalInner() {const setupRunning = useSyncExternalStore(subscribeInstallRuns, anyInstallRunning)const comfyUpdating = useComfyInstallStore((s) => s.phase !== 'idle' && s.phase !== 'error')const luIsRestartingComfy = setupRunning || comfyUpdating || corsFixing+ // While this view is open a finished render keeps the graphics card for the+ // next one; leaving it brings the chat model back (api/vram-handoff).+ useEffect(() => {+ setRenderSurfaceOpen(true)+ return () => setRenderSurfaceOpen(false)+ }, [])const [idleNotice, setIdleNotice] = useState('')const idleTimerRef = useRef<(() => void) | null>(null)useEffect(() => {diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.tsindex 6bfad52d..48c7910f 100644--- a/src/hooks/useCreate.ts+++ b/src/hooks/useCreate.ts@@ -969,8 +969,10 @@ export function useCreate() {// 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.+ // finally below hands the haul back, and the chat backends return when a+ // chat needs them, Create is left, or nobody asked for a while (see+ // restoreChatBackendsAfterRender). exclusiveVramMode 'never' skips the+ // eviction. Best-effort, never blocks a render.//// The box, 03.10.2026: this wait stood for 25 to 30 s under "Preparing// workflow..." with no counter. No workflow is prepared in it: the card isdiff --git a/src/lib/chat-backends-gate.ts b/src/lib/chat-backends-gate.tsnew file mode 100644index 00000000..7dd46c5d--- /dev/null+++ b/src/lib/chat-backends-gate.ts@@ -0,0 +1,29 @@+/**+ * The way a chat request asks for the chat backends a render moved out.+ *+ * A Create render takes the local chat model off the graphics card+ * (api/vram-handoff) and no longer loads it straight back, because the next+ * thing on the Create view is usually another render. The model comes back+ * when a chat needs it. The providers cannot import the hand-off module+ * (it sits on top of half the api layer), so the hand-off leaves its restore+ * here while a haul is parked, and a local provider waits for it before it+ * sends. Nothing parked: nothing to wait for.+ *+ * Why not let the backends load lazily: Ollama would, but the built-in engine+ * comes back without its saved KV slot and LM Studio without the context+ * length it was loaded with, or not at all with its own load on demand+ * switched off. The restore knows all three.+ */+let restore: (() => Promise<void>) | null = null++/** Set by the hand-off while a haul is parked, null once it is back or taken over. */+export function setChatBackendsRestore(fn: (() => Promise<void>) | null): void {+ restore = fn+}++/** Resolves when the chat backends a render moved out are loaded again. */+export async function chatBackendsBack(): Promise<void> {+ const run = restore+ if (!run) return+ try { await run() } catch { /* the request goes out either way */ }+}