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): the wait before a run says what it is and counts its seconds

purple314f8e496685
diff --git a/src/api/__tests__/create-render-handoff.test.ts b/src/api/__tests__/create-render-handoff.test.ts
index 6d44b6e3..1b3d29df 100644
--- a/src/api/__tests__/create-render-handoff.test.ts
+++ b/src/api/__tests__/create-render-handoff.test.ts
@@ -285,12 +285,72 @@ describe('holdRenderRestore: a run of several renders restores once, at its end'
})
})
+// The box, 03.10.2026: 25 to 30 s under "Preparing workflow..." before a run.
+// Timed in the test build, the eviction itself took under a second; the rest
+// was the previous render's restore reading the chat model back in, which an
+// eviction has to wait for. The caller is told which of the two it is.
+describe('the eviction says what the wait is spent on', () => {
+ const LMS = { id: 'qwen/qwen2.5-vl-7b', contextLength: 4096 }
+
+ it('nothing in the way: it frees, and says so', async () => {
+ const phases: string[] = []
+ await evictChatBackendsForRender((p) => phases.push(p))
+ expect(phases).toEqual(['freeing'])
+ })
+
+ it('a restore that is reading the chat model back in: waits for it first', async () => {
+ let finishLoad: () => void = () => {}
+ const loading = new Promise<void>((resolve) => { finishLoad = resolve })
+ const base = backendCall.getMockImplementation()!
+ backendCall.mockImplementation(async (cmd: unknown, args?: unknown) => {
+ if (cmd === 'lmstudio_load_model') { await loading; return { ok: true } }
+ return base(cmd, args)
+ })
+ const restored = restoreChatBackendsAfterRender({ ollamaModel: null, lms: LMS, bundled: null } as RenderEviction, 0)
+ await vi.waitFor(() => expect(callsTo('lmstudio_load_model')).toHaveLength(1))
+
+ const phases: string[] = []
+ const next = evictChatBackendsForRender((p) => phases.push(p))
+ // Told at once, while the load is still running, and nothing is freed yet.
+ expect(phases).toEqual(['waiting-for-chat-model'])
+ expect(callsTo('offload_local_models')).toHaveLength(0)
+
+ finishLoad()
+ await restored
+ await next
+ expect(phases).toEqual(['waiting-for-chat-model', 'freeing'])
+ expect(callsTo('offload_local_models')).toHaveLength(1)
+ })
+
+ it('a restore still inside its grace window is not a wait for the chat model', async () => {
+ vi.useFakeTimers()
+ const restored = restoreChatBackendsAfterRender({ ollamaModel: null, lms: LMS, bundled: null } as RenderEviction)
+ const phases: string[] = []
+ const next = evictChatBackendsForRender((p) => phases.push(p))
+ expect(phases).toEqual([])
+ await vi.advanceTimersByTimeAsync(5_000)
+ await restored
+ await next
+ expect(phases).toEqual(['freeing'])
+ // The newer render inherited the haul: the chat model was never reloaded.
+ expect(callsTo('lmstudio_load_model')).toHaveLength(0)
+ })
+
+ it('the next eviction after a finished restore does not claim to wait', async () => {
+ await restoreChatBackendsAfterRender({ ollamaModel: null, lms: LMS, bundled: null } as RenderEviction, 0)
+ const phases: string[] = []
+ await evictChatBackendsForRender((p) => phases.push(p))
+ expect(phases).toEqual(['freeing'])
+ })
+})
+
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('renderEviction = await evictChatBackendsForRender((phase) => handoff.setLabel(HANDOFF_LINE[phase]))')
expect(src).toContain('restoreChatBackendsAfterRender(renderEviction)')
// The exact uncaptured kill Z36 flagged must not come back.
expect(src).not.toContain("backendCall('offload_local_models'")
diff --git a/src/api/vram-handoff.ts b/src/api/vram-handoff.ts
index 9b3edc22..a70cd6f3 100644
--- a/src/api/vram-handoff.ts
+++ b/src/api/vram-handoff.ts
@@ -2207,14 +2207,31 @@ let _renderJuggle: Promise<unknown> = Promise.resolve()
let _renderEpoch = 0
let _pendingRestore: RenderEviction | null = null
let _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 _restoreInFlight = false
export const RENDER_RESTORE_GRACE_MS = 2_000
+/**
+ * What the eviction is doing, for the waiting line of the run.
+ *
+ * Measured on the Windows box, 03.10.2026 (RTX 3060, LM Studio as the chat
+ * backend, a 6 GB chat model): the eviction itself is quick, 0.3 s for
+ * offload_local_models and 0.5 s for the LM Studio unload. The 25 to 30 s the
+ * stage stood on "Preparing workflow..." were the step before it: the previous
+ * render's restore was still reading the chat model back in, and an eviction
+ * waits its turn on the same chain, so the model is loaded completely and then
+ * unloaded again. The line now says which of the two is going on.
+ */
+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
_restoreHolds = 0
+ _restoreInFlight = false
}
function mergeEvictions(base: RenderEviction | null, add: RenderEviction): RenderEviction {
@@ -2229,11 +2246,16 @@ function mergeEvictions(base: RenderEviction | null, add: RenderEviction): Rende
/**
* 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.
+ * probe just means that backend is not in the haul. `onPhase` is told what
+ * the wait is spent on (RenderEvictionPhase).
*/
-export function evictChatBackendsForRender(): Promise<RenderEviction> {
+export function evictChatBackendsForRender(onPhase?: (phase: RenderEvictionPhase) => void): Promise<RenderEviction> {
_renderEpoch++
- const run = _renderJuggle.catch(() => {}).then(() => evictBody())
+ if (_restoreInFlight) onPhase?.('waiting-for-chat-model')
+ const run = _renderJuggle.catch(() => {}).then(() => {
+ onPhase?.('freeing')
+ return evictBody()
+ })
_renderJuggle = run.catch(() => {})
return run.catch(() => ({ ...EMPTY_EVICTION }))
}
@@ -2375,41 +2397,46 @@ async function restoreBody(evicted: RenderEviction, graceMs: number, myEpoch: nu
// the 14B lanes), and `exclusiveVramMode: 'never'` already turns the whole
// juggle off. Trading a render's load time against a chat model's is David's
// call, not a fixer's.
- 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 })
+ _restoreInFlight = true
+ try {
+ 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) })
}
- } 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.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) })
+ 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) })
+ }
}
+ } finally {
+ _restoreInFlight = false
}
log.info('render_juggle.restored', {
ollama: todo.ollamaModel,
diff --git a/src/hooks/__tests__/useCreate-handoff-line.test.ts b/src/hooks/__tests__/useCreate-handoff-line.test.ts
new file mode 100644
index 00000000..6cd206ac
--- /dev/null
+++ b/src/hooks/__tests__/useCreate-handoff-line.test.ts
@@ -0,0 +1,98 @@
+// @vitest-environment jsdom
+/**
+ * The box, 03.10.2026: before a run the stage stood 25 to 30 s on "Preparing
+ * workflow..." with no counter. That time is the hand-over of the graphics
+ * card (api/vram-handoff), most of it waiting for the chat model the previous
+ * render brought back. The stage says so and counts the seconds, through the
+ * real generate path of useCreate.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { renderHook } from '@testing-library/react'
+
+const seen = vi.hoisted(() => ({ lines: [] as string[], atBuild: '' }))
+
+vi.mock('../../api/mlx-image', () => ({
+ isMlxImageHost: () => false,
+ isMlxImageModel: () => false,
+ mlxStatus: vi.fn(async () => ({ installed: false })),
+ listMlxImageModels: vi.fn(async () => []),
+ buildMlxImageModels: vi.fn(() => []),
+ mergeImageModels: vi.fn((a: unknown[]) => a),
+ mlxModelIdFor: vi.fn(() => ''),
+ generateMlxImageDataUrl: vi.fn(),
+}))
+vi.mock('../../api/comfyui', async (orig) => ({
+ ...((await orig()) as Record<string, unknown>),
+ checkComfyConnection: vi.fn(async () => true),
+ submitWorkflow: vi.fn(async () => { throw new Error('stop here') }),
+}))
+vi.mock('../../api/comfyui-ws', () => ({
+ CLIENT_ID: 'lu-test',
+ comfyWS: { connect: vi.fn(async () => { throw new Error('no socket') }), mark: () => 0 },
+}))
+vi.mock('../../api/vram-handoff', async (orig) => ({
+ ...((await orig()) as Record<string, unknown>),
+ evictChatBackendsForRender: vi.fn(async (onPhase?: (phase: string) => void) => {
+ const { useCreateStore } = await import('../../stores/createStore')
+ const line = () => useCreateStore.getState().progressText
+ seen.lines.push(line())
+ onPhase?.('waiting-for-chat-model')
+ seen.lines.push(line())
+ await new Promise((r) => setTimeout(r, 2100))
+ seen.lines.push(line())
+ onPhase?.('freeing')
+ seen.lines.push(line())
+ return null
+ }),
+ restoreChatBackendsAfterRender: vi.fn(),
+}))
+vi.mock('../../api/dynamic-workflow', async (orig) => ({
+ ...((await orig()) as Record<string, unknown>),
+ buildDynamicWorkflow: vi.fn(async () => {
+ const { useCreateStore } = await import('../../stores/createStore')
+ seen.atBuild = useCreateStore.getState().progressText
+ return { '1': { class_type: 'SaveImage', inputs: {} } }
+ }),
+}))
+
+import { useCreate } from '../useCreate'
+import { useCreateStore } from '../../stores/createStore'
+
+const MODEL = 'sd_turbo.safetensors'
+
+beforeEach(() => {
+ seen.lines.length = 0
+ seen.atBuild = ''
+ useCreateStore.setState({
+ backend: 'local', isGenerating: false, error: null, gallery: [], promptHistory: [],
+ improvePrompt: false, cloudOp: null, utilityOp: null, removebg: false, source: null, mask: null, references: [],
+ selectedLoras: [], hiresFixEnabled: false, transparentBackground: false, seed: 42,
+ imageModel: MODEL, imageModelList: [{ name: MODEL, type: 'sd15' }],
+ } as never)
+ const s = useCreateStore.getState()
+ s.setIntent('image')
+ s.setPrompt('a lighthouse at dusk')
+})
+
+describe('the wait before a local run', () => {
+ it('names the hand-over of the graphics card and counts its seconds', async () => {
+ const { result } = renderHook(() => useCreate())
+ await result.current.generate()
+ expect(seen.lines).toEqual([
+ 'Freeing graphics memory... 0s',
+ 'Waiting for the chat model to finish loading... 0s',
+ 'Waiting for the chat model to finish loading... 2s',
+ 'Freeing graphics memory... 2s',
+ ])
+ }, 15_000)
+
+ it('stops counting when the hand-over is done: the next line is not painted over', async () => {
+ const { result } = renderHook(() => useCreate())
+ await result.current.generate()
+ expect(seen.atBuild).toBe('Building workflow...')
+ const after = useCreateStore.getState().progressText
+ await new Promise((r) => setTimeout(r, 1200))
+ expect(useCreateStore.getState().progressText).toBe(after)
+ expect(after).not.toMatch(/Freeing|Waiting for the chat model/)
+ }, 15_000)
+})
diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.ts
index 13c766bf..a2f48cf4 100644
--- a/src/hooks/useCreate.ts
+++ b/src/hooks/useCreate.ts
@@ -40,6 +40,7 @@ import {
evictChatBackendsForRender,
restoreChatBackendsAfterRender,
type RenderEviction,
+ type RenderEvictionPhase,
} from '../api/vram-handoff'
import { cpuCauseSuffix } from '../lib/render-budget'
import { backendCall } from '../api/backend'
@@ -87,6 +88,13 @@ import {
buildMlxVideoModels, mlxVideoModelIdFor, readVideoAsBlobUrl,
} from '../api/mlx-video'
+/** What the stage says while the graphics card is handed to the render
+ * (api/vram-handoff, RenderEvictionPhase). */
+const HANDOFF_LINE: Record<RenderEvictionPhase, string> = {
+ 'waiting-for-chat-model': 'Waiting for the chat model to finish loading...',
+ freeing: 'Freeing graphics memory...',
+}
+
/**
* The `[event, payload]` pairs of a `/history` status entry.
*
@@ -951,7 +959,6 @@ export function useCreate() {
return
}
- setProgress(0, 'Preparing workflow...')
abortRef.current = new AbortController()
// Make VRAM room for the render. On a single local GPU a resident chat LLM
@@ -963,10 +970,20 @@ export function useCreate() {
// 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.
+ //
+ // 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 is
+ // handed over, and most of the time goes into waiting for the previous
+ // render's restore to finish reading the chat model back in. The line
+ // says which it is and counts like every other waiting line.
let renderEviction: RenderEviction | null = null
+ const handoff = elapsedLine((text) => setProgress(0, text), HANDOFF_LINE.freeing)
try {
- renderEviction = await evictChatBackendsForRender()
- } catch { /* VRAM housekeeping is best-effort */ }
+ renderEviction = await evictChatBackendsForRender((phase) => handoff.setLabel(HANDOFF_LINE[phase]))
+ } catch { /* VRAM housekeeping is best-effort */ } finally {
+ handoff.stop()
+ }
+ setProgress(0, 'Preparing workflow...')
try {
// The Qwen prompt enhancer writes now: the chat model has left the card,