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(render): the checkpoint load stops spending the render's budget
purplebb6ef6b45c6e
diff --git a/src/api/__tests__/render-load-phase.test.ts b/src/api/__tests__/render-load-phase.test.tsnew file mode 100644index 00000000..3171e5a2--- /dev/null+++ b/src/api/__tests__/render-load-phase.test.ts@@ -0,0 +1,300 @@+/**+ * Z36 finding 4 (W3 run 2026-08-16): a forced z_image_bf16 render in the CHAT+ * tool was abandoned after 352.6 s, while the Create tab renders the same job.+ * The first load of the big bf16 checkpoint on a 3060 outlasted the 5 minute+ * warm-up budget, which cannot tell a slow load from a wedged one. The image+ * budget itself defaults to 20 minutes, so the flat deadline was never the one+ * that fired; it is fixed here too because a shorter user budget hits it next.+ *+ * These tests drive the REAL poll loop on a virtual clock and replay that+ * timeline. The pure budget maths lives in render-budget.test.ts; this file+ * proves the loop behaves.+ *+ * Run: npx vitest run src/api/__tests__/render-load-phase.test.ts+ */+import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'++const h = vi.hoisted(() => {+ const handlers: ((ev: unknown) => void)[] = []+ return {+ handlers,+ wsConnected: { value: true },+ getImageModels: vi.fn(),+ getSystemVRAM: vi.fn(),+ submitWorkflow: vi.fn(),+ getHistory: vi.fn(),+ isPromptQueued: vi.fn(),+ abandonPrompt: vi.fn(),+ sweepOrphanedLuJobs: vi.fn(),+ freeMemory: vi.fn(),+ cancelGeneration: vi.fn(),+ clearComfyQueue: vi.fn(),+ buildDynamicWorkflow: vi.fn(),+ backendCall: vi.fn(),+ listRunningModels: vi.fn(),+ loadModel: vi.fn(),+ unloadModel: vi.fn(),+ getActiveAgentModel: vi.fn(),+ }+})++vi.mock('../backend', () => ({+ backendCall: (...a: unknown[]) => h.backendCall(...a),+ localFetch: async () => ({ ok: true, status: 200, json: async () => ({}), text: async () => '' }),+ ollamaUrl: (p: string) => `http://localhost:11434/api${p}`,+ comfyuiUrl: (p: string) => `http://localhost:8188${p}`,+ isOllamaLocal: () => true,+}))++vi.mock('../ollama', () => ({+ listRunningModels: (...a: unknown[]) => h.listRunningModels(...a),+ loadModel: (...a: unknown[]) => h.loadModel(...a),+ unloadModel: (...a: unknown[]) => h.unloadModel(...a),+}))++vi.mock('../comfyui', async () => {+ const actual = await vi.importActual<typeof import('../comfyui')>('../comfyui')+ return {+ ...actual,+ getImageModels: (...a: unknown[]) => h.getImageModels(...a),+ getSystemVRAM: (...a: unknown[]) => h.getSystemVRAM(...a),+ submitWorkflow: (...a: unknown[]) => h.submitWorkflow(...a),+ getHistory: (...a: unknown[]) => h.getHistory(...a),+ isPromptQueued: (...a: unknown[]) => h.isPromptQueued(...a),+ abandonPrompt: (...a: unknown[]) => h.abandonPrompt(...a),+ sweepOrphanedLuJobs: (...a: unknown[]) => h.sweepOrphanedLuJobs(...a),+ freeMemory: (...a: unknown[]) => h.freeMemory(...a),+ cancelGeneration: (...a: unknown[]) => h.cancelGeneration(...a),+ clearComfyQueue: (...a: unknown[]) => h.clearComfyQueue(...a),+ }+})++vi.mock('../dynamic-workflow', () => ({+ buildDynamicWorkflow: (...a: unknown[]) => h.buildDynamicWorkflow(...a),+}))++vi.mock('../agent-context', () => ({+ getActiveAgentModel: () => h.getActiveAgentModel(),+}))++// A LIVE websocket, unlike the sibling suite: the load phase can only be told+// apart from the sampling phase by ComfyUI's own progress events.+vi.mock('../comfyui-ws', () => ({+ comfyWS: {+ on: (cb: (ev: unknown) => void) => {+ h.handlers.push(cb)+ return () => { const i = h.handlers.indexOf(cb); if (i >= 0) h.handlers.splice(i, 1) }+ },+ connect: () => Promise.resolve(),+ get connected() { return h.wsConnected.value },+ },+ CLIENT_ID: 'lu-test-client',+}))++import { vramHandoffGenerate, __resetGenerationStateForTests } from '../vram-handoff'+import { SWAP_WARMUP_BUDGET_MS, SWAP_WARMUP_ALIVE_BUDGET_MS } from '../../lib/render-budget'+import { useSettingsStore } from '../../stores/settingsStore'+import { DEFAULT_SETTINGS } from '../../lib/constants'++const PROMPT_ID = 'z-image-run'++/** The witness numbers: the checkpoint load outlasts the warm-up budget and+ * the whole job lands at 352.6 s. */+const SAMPLING_STARTS_AT = 320_000+const COMPLETED_AT = 352_600++/** Shrink the image budget so the flat-deadline half is reachable in a test.+ * The shipped default is 20 minutes, which the witness never came near. */+function useImageBudgetMinutes(mins: number): number {+ useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS, imageGenTimeoutMinutes: mins } })+ return mins * 60_000+}++let lastEmitted = 0++/**+ * Emit one sampler tick. ComfyUI goes quiet once the pass is done, so a value+ * that has already been sent is not repeated, and a dead socket delivers+ * nothing at all.+ */+function emitProgress(value: number, max: number, promptId = PROMPT_ID) {+ if (!h.wsConnected.value || value <= lastEmitted) return+ lastEmitted = value+ for (const cb of [...h.handlers]) cb({ type: 'progress', data: { prompt_id: promptId, value, max } })+}++const completedHistory = () => ({+ status: { completed: true },+ outputs: { '9': { images: [{ filename: 'z-image.png', subfolder: '', type: 'output' }] } },+})++/**+ * The FIRST generation in this module pays a one-time lazy init (the node-type+ * catalogue behind fetchCaps). It never reaches the poll loop on a virtual+ * clock, so pay it once on the real one before any case runs.+ */+beforeAll(async () => {+ h.getActiveAgentModel.mockReturnValue({ name: 'gpt-4o', providerId: 'openai', remote: false })+ h.getImageModels.mockResolvedValue([{ name: 'z_image_bf16.safetensors', type: 'sdxl', source: 'checkpoint' }])+ h.buildDynamicWorkflow.mockResolvedValue({ '9': { class_type: 'SaveImage' } })+ h.submitWorkflow.mockResolvedValue('warmup')+ h.getHistory.mockResolvedValue(completedHistory())+ h.getSystemVRAM.mockResolvedValue(null)+ h.listRunningModels.mockResolvedValue([])+ for (const fn of [h.freeMemory, h.loadModel, h.unloadModel, h.cancelGeneration, h.clearComfyQueue, h.abandonPrompt, h.sweepOrphanedLuJobs]) {+ fn.mockResolvedValue(undefined)+ }+ h.isPromptQueued.mockResolvedValue(false)+ h.backendCall.mockImplementation(async (cmd: string) => (cmd === 'comfyui_status' ? { running: true } : {}))+ await vramHandoffGenerate('image', { prompt: 'warm up the module' })+}, 30_000)++beforeEach(() => {+ vi.useFakeTimers()+ h.handlers.length = 0+ h.wsConnected.value = true+ for (const fn of Object.values(h)) {+ if (typeof fn === 'function' && 'mockReset' in fn) (fn as ReturnType<typeof vi.fn>).mockReset()+ }+ __resetGenerationStateForTests()+ h.getActiveAgentModel.mockReturnValue({ name: 'gpt-4o', providerId: 'openai', remote: false })+ h.getImageModels.mockResolvedValue([{ name: 'z_image_bf16.safetensors', type: 'sdxl', source: 'checkpoint' }])+ h.buildDynamicWorkflow.mockResolvedValue({ '9': { class_type: 'SaveImage' } })+ h.submitWorkflow.mockResolvedValue(PROMPT_ID)+ h.getSystemVRAM.mockResolvedValue(null)+ h.listRunningModels.mockResolvedValue([])+ h.freeMemory.mockResolvedValue(undefined)+ h.loadModel.mockResolvedValue(undefined)+ h.unloadModel.mockResolvedValue(undefined)+ h.cancelGeneration.mockResolvedValue(undefined)+ h.clearComfyQueue.mockResolvedValue(undefined)+ h.abandonPrompt.mockResolvedValue(undefined)+ h.sweepOrphanedLuJobs.mockResolvedValue(undefined)+ h.isPromptQueued.mockResolvedValue(false)+ h.backendCall.mockImplementation(async (cmd: string) => (cmd === 'comfyui_status' ? { running: true } : {}))+ useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS } })+})++afterEach(() => { vi.useRealTimers() })++/**+ * Replay a render on the virtual clock. `script` is asked on every poll what+ * ComfyUI would say at that moment, and may emit progress events.+ */+let lastElapsed = 0++async function runRender(script: (elapsed: number) => unknown, forMs: number): Promise<string> {+ const t0 = Date.now()+ lastElapsed = 0+ lastEmitted = 0+ h.getHistory.mockImplementation(async () => {+ lastElapsed = Date.now() - t0+ return script(lastElapsed)+ })+ let settled: string | null = null+ void vramHandoffGenerate('image', { prompt: 'a lighthouse' }).then((r) => { settled = r })+ // Step the virtual clock in minutes and stop as soon as the loop is done, so+ // a case that ends early does not pay for the rest of the window.+ for (let spent = 0; spent < forMs && settled === null; spent += 60_000) {+ await vi.advanceTimersByTimeAsync(Math.min(60_000, forMs - spent))+ }+ if (settled === null) throw new Error(`render did not finish inside ${forMs} ms of virtual time (last poll at ${lastElapsed} ms, ${h.getHistory.mock.calls.length} polls)`)+ return settled+}++/** Virtual ms from the start of the render to where the loop finished. */+function finishedAfter(): number { return lastElapsed }++describe('Z36 finding 4: the first checkpoint load stops eating the render budget', () => {+ // Each case steps a virtual clock through hundreds of one-second polls.++ it('the reported render survives: the load outlasts the warm-up budget', async () => {+ // Exactly the witness: nothing progresses for 320 s while the bf16+ // checkpoint loads, ComfyUI still has our prompt, sampling then finishes+ // the job at 352.6 s. Before the fix the warm-up guard killed it at 300 s.+ h.isPromptQueued.mockResolvedValue(true)+ const out = await runRender((elapsed) => {+ if (elapsed >= SAMPLING_STARTS_AT) {+ // Z-Image Turbo: eight quick steps once the checkpoint is finally in+ emitProgress(Math.min(8, Math.floor((elapsed - SAMPLING_STARTS_AT) / 4_000) + 1), 8)+ }+ return elapsed >= COMPLETED_AT ? completedHistory() : undefined+ }, 15 * 60_000)++ expect(out).toContain('Image generated: z-image.png')+ expect(h.isPromptQueued).toHaveBeenCalledWith(PROMPT_ID)+ expect(h.abandonPrompt).not.toHaveBeenCalled()+ }, 30_000)++ it('NEGATIVE CONTROL: a load nobody vouches for still dies on the plain budget', async () => {+ h.isPromptQueued.mockResolvedValue(false)+ const out = await runRender(() => undefined, 20 * 60_000)++ expect(out).toContain('still loading into VRAM')+ expect(h.abandonPrompt).toHaveBeenCalledWith(PROMPT_ID)+ expect(finishedAfter()).toBeLessThan(SWAP_WARMUP_ALIVE_BUDGET_MS)+ expect(finishedAfter()).toBeGreaterThanOrEqual(SWAP_WARMUP_BUDGET_MS)+ }, 30_000)++ it('NEGATIVE CONTROL: R17c, wedged but queued, still dies on the doubled budget', async () => {+ h.isPromptQueued.mockResolvedValue(true)+ const out = await runRender(() => undefined, 25 * 60_000)++ expect(out).toContain('still loading into VRAM')+ expect(h.abandonPrompt).toHaveBeenCalledWith(PROMPT_ID)+ expect(finishedAfter()).toBeGreaterThanOrEqual(SWAP_WARMUP_ALIVE_BUDGET_MS)+ }, 30_000)++ it('a short user budget spends its minutes on the render, not on the load', async () => {+ const budget = useImageBudgetMinutes(5)+ h.isPromptQueued.mockResolvedValue(true)+ // load until 4 min, then a 3 minute sampling pass: 7 min in total, more+ // than the 5 minute budget, but the render itself fits inside it+ const LOAD = 240_000+ const out = await runRender((elapsed) => {+ if (elapsed >= LOAD) emitProgress(Math.min(12, Math.floor((elapsed - LOAD) / 15_000) + 1), 12)+ return elapsed >= LOAD + 180_000 ? completedHistory() : undefined+ }, 20 * 60_000)++ expect(budget).toBe(5 * 60_000)+ expect(out).toContain('Image generated: z-image.png')+ expect(h.abandonPrompt).not.toHaveBeenCalled()+ expect(finishedAfter()).toBeGreaterThan(budget)+ }, 30_000)++ it('a render still sampling at the deadline is adopted, not thrown away', async () => {+ const budget = useImageBudgetMinutes(5)+ // sampling from the first seconds at a pace that lands just past the budget+ const out = await runRender((elapsed) => {+ emitProgress(Math.min(20, Math.floor(elapsed / 15_000) + 1), 20)+ return elapsed >= budget + 20_000 ? completedHistory() : undefined+ }, 20 * 60_000)++ expect(out).toContain('Image generated: z-image.png')+ expect(h.abandonPrompt).not.toHaveBeenCalled()+ }, 30_000)++ it('NEGATIVE CONTROL: R32, a hopeless sampling pace, still dies after three steps', async () => {+ const budget = useImageBudgetMinutes(5)+ // 30 steps at 80 s each, sampling from the very first second+ const out = await runRender((elapsed) => {+ emitProgress(Math.max(1, Math.floor(elapsed / 80_000) + 1), 30)+ return undefined+ }, 20 * 60_000)++ expect(out).toContain('stopped early')+ expect(h.abandonPrompt).toHaveBeenCalledWith(PROMPT_ID)+ // the verdict lands long before the budget, exactly as before the fix+ expect(finishedAfter()).toBeLessThan(budget)+ }, 30_000)++ it('NEGATIVE CONTROL: without a WS nothing is granted, the flat budget stands', async () => {+ const budget = useImageBudgetMinutes(5)+ h.wsConnected.value = false+ const out = await runRender((elapsed) => (elapsed >= COMPLETED_AT ? completedHistory() : undefined), 20 * 60_000)++ expect(out).toContain('hit the 5 minute budget')+ expect(h.abandonPrompt).toHaveBeenCalledWith(PROMPT_ID)+ expect(finishedAfter()).toBeLessThan(budget + 60_000)+ }, 30_000)+})diff --git a/src/api/vram-handoff.ts b/src/api/vram-handoff.tsindex 0c0ecc1d..0039bb82 100644--- a/src/api/vram-handoff.ts+++ b/src/api/vram-handoff.ts@@ -69,12 +69,13 @@ import {buildTxt2VidWorkflow,snapToVideoGrid,MODEL_TYPE_DEFAULTS,+ isPromptQueued,type VideoBackend,} from './comfyui'import type { ModelCapabilities } from './comfyui-nodes'import { getActiveAgentModel } from './agent-context'import { comfyWS, CLIENT_ID } from './comfyui-ws'-import { PaceTracker, overBudget, renderBudgetNotice, renderTimeoutNotice, warmupExceeded, swapWarmupNotice } from '../lib/render-budget'+import { PaceTracker, overBudget, renderBudgetNotice, renderTimeoutNotice, warmupExceeded, swapWarmupNotice, loadPhaseGraceMs, finishGraceMs, warmupBudgetMs, SWAP_WARMUP_BUDGET_MS } from '../lib/render-budget'import { log } from '../lib/logger'/**@@ -1325,7 +1326,6 @@ async function generateVideo(* message VERBATIM (Bug-G / honest-UX: an OOM reads as an OOM).*/async function pollAndExtract(promptId: string, prompt: string, kindLabel: string, timeoutMs: number): Promise<string> {- const deadline = Date.now() + timeoutMs// G19-1 render budget: read the pace off ComfyUI's own progress events and// give up EARLY, with the job cancelled, once the projection says the render// cannot land inside the budget (R32: a 30 to 60 minute Wan job burned the@@ -1337,19 +1337,61 @@ async function pollAndExtract(promptId: string, prompt: string, kindLabel: strin// (R17c: 19 minutes of "loading model into VRAM"). Track whether ANY prompt// progressed; if the WS is alive and nothing on the GPU has moved for the// whole warm-up budget, the load is wedged and the job gets abandoned.+ //+ // Z36 finding 4 (W3 run 2026-08-16): a forced z_image_bf16 render in the chat+ // tool was abandoned after 352.6 s while the Create tab renders the same job.+ // The first load of the big bf16 checkpoint on a 3060 outlasted the warm-up+ // budget, and neither guard here could tell a slow load from a wedged one.+ // Two things change. The warm-up guard asks ComfyUI whether the prompt is+ // still queued before calling the load wedged, the same life signal the+ // Create watchdog uses. And the flat deadline is recomputed every tick with+ // the measured load phase added, so the render budget is spent on the render.+ // The pace verdict keeps the RAW budget, so a hopeless render (R32) still+ // dies after three sampler steps.const startedAt = Date.now()let sawAnyProgress = false+ let firstOwnProgressAt: number | null = null+ let finishGraceUsed = 0+ // Z36 finding 4, second half: before calling a long load wedged, ask ComfyUI+ // whether our prompt is still in its queue. That is the same life signal the+ // Create watchdog uses (useCreate: isPromptQueued refreshes lastActivity), and+ // it is the reason the Create tab finishes a render the agent path abandoned.+ // Asked only once the plain warm-up budget is spent, and at most every 30 s,+ // so a healthy render never pays for the extra request.+ let promptAlive = false+ let aliveCheckedAt = 0const offProgress = comfyWS.on((ev) => {if (ev.type === 'progress') {sawAnyProgress = trueif (ev.data.prompt_id === promptId) {- pace.tick(ev.data.value, ev.data.max, Date.now())+ const at = Date.now()+ if (firstOwnProgressAt === null) firstOwnProgressAt = at+ pace.tick(ev.data.value, ev.data.max, at)}}})void comfyWS.connect().catch(() => { /* degrade to the flat deadline */ })try {- while (Date.now() < deadline) {+ for (;;) {+ const deadline = startedAt + timeoutMs+ + loadPhaseGraceMs(comfyWS.connected, startedAt, firstOwnProgressAt, Date.now(), warmupBudgetMs(promptAlive))+ + finishGraceUsed+ if (Date.now() >= deadline) {+ // Adopt a render that is seconds from done instead of throwing away the+ // load and the sampling it already paid for. Granted at most once.+ const grace = finishGraceUsed === 0 ? finishGraceMs(pace.projectedRemainingMs()) : 0+ if (grace > 0) {+ finishGraceUsed = grace+ log.info('vram_handoff.render_finish_grace', { promptId, graceMs: grace })+ continue+ }+ // Deadline reached: the wait ends AND the job ends. The old return here+ // walked away and left the render burning the GPU with no owner.+ const elapsedMs = Date.now() - startedAt+ log.warn('vram_handoff.render_timeout_abort', { promptId, budgetMs: timeoutMs, elapsedMs })+ await abandonPrompt(promptId)+ return renderTimeoutNotice(kindLabel, timeoutMs, elapsedMs)+ }// User hit the in-chat cancel button — ComfyUI was already sent /interrupt// + queue-clear by requestGenerationCancel(); stop polling so runHandoff's// finally can restore the text model into VRAM instead of waiting out the@@ -1391,17 +1433,16 @@ async function pollAndExtract(promptId: string, prompt: string, kindLabel: strinreturn renderBudgetNotice(kindLabel, projected!, timeoutMs)}const warmupElapsed = Date.now() - startedAt- if (warmupExceeded(sawAnyProgress, comfyWS.connected, warmupElapsed)) {- log.warn('vram_handoff.swap_warmup_abort', { promptId, elapsedMs: warmupElapsed })+ if (!sawAnyProgress && warmupElapsed > SWAP_WARMUP_BUDGET_MS && Date.now() - aliveCheckedAt > 30_000) {+ aliveCheckedAt = Date.now()+ promptAlive = await isPromptQueued(promptId)+ }+ if (warmupExceeded(sawAnyProgress, comfyWS.connected, warmupElapsed, warmupBudgetMs(promptAlive))) {+ log.warn('vram_handoff.swap_warmup_abort', { promptId, elapsedMs: warmupElapsed, promptAlive })await abandonPrompt(promptId)return swapWarmupNotice(kindLabel, warmupElapsed)}}- // Deadline reached: the wait ends AND the job ends. The old return here- // walked away and left the render burning the GPU with no owner.- log.warn('vram_handoff.render_timeout_abort', { promptId, budgetMs: timeoutMs })- await abandonPrompt(promptId)- return renderTimeoutNotice(kindLabel, timeoutMs)} finally {offProgress()}diff --git a/src/lib/__tests__/render-budget.test.ts b/src/lib/__tests__/render-budget.test.tsindex 1b0587c2..b4c9a3ef 100644--- a/src/lib/__tests__/render-budget.test.ts+++ b/src/lib/__tests__/render-budget.test.ts@@ -19,9 +19,15 @@ import {renderTimeoutNotice,warmupExceeded,swapWarmupNotice,+ loadPhaseGraceMs,+ finishGraceMs,MIN_STEPS_FOR_VERDICT,HOPELESS_FACTOR,SWAP_WARMUP_BUDGET_MS,+ SWAP_WARMUP_ALIVE_BUDGET_MS,+ warmupBudgetMs,+ LOAD_PHASE_GRACE_CAP_MS,+ FINISH_GRACE_CAP_MS,} from '../render-budget'const here = dirname(fileURLToPath(import.meta.url))@@ -117,12 +123,151 @@ describe('the warm-up budget (G24, R17c witness)', () => {})})+describe('the load phase does not eat the render budget (Z36 finding 4)', () => {+ const IMAGE_BUDGET = 5 * 60_000+ // The Z36 witness, W3 run 2026-08-16: a forced z_image_bf16 render in the+ // chat tool. The big bf16 checkpoint loads first, sampling only starts after+ // it, and the whole thing lands at 352.6 s against a 5 minute budget.+ const LOAD_MS = 300_000+ const TOTAL_MS = 352_600++ const deadlineAt = (firstOwnProgressAt: number | null, now: number, wsConnected = true) =>+ IMAGE_BUDGET + loadPhaseGraceMs(wsConnected, 0, firstOwnProgressAt, now)++ it('the Z36 render survives: at 352.6 s the deadline has not been reached', () => {+ // sampling started at 300 s, so the budget only starts counting there+ expect(TOTAL_MS).toBeLessThan(deadlineAt(LOAD_MS, TOTAL_MS))+ })++ it('the same render dies without the grace, which is exactly what was reported', () => {+ expect(TOTAL_MS).toBeGreaterThan(IMAGE_BUDGET)+ })++ it('the grace freezes at the measured load once sampling has started', () => {+ expect(loadPhaseGraceMs(true, 0, LOAD_MS, TOTAL_MS)).toBe(LOAD_MS)+ // and it does not keep growing with the clock afterwards+ expect(loadPhaseGraceMs(true, 0, LOAD_MS, TOTAL_MS + 600_000)).toBe(LOAD_MS)+ })++ it('while the checkpoint is still loading the grace grows with the clock', () => {+ expect(loadPhaseGraceMs(true, 0, null, 60_000)).toBe(60_000)+ expect(loadPhaseGraceMs(true, 0, null, 120_000)).toBe(120_000)+ })++ it('the whole wait stays bounded: the grace never exceeds its cap', () => {+ expect(loadPhaseGraceMs(true, 0, null, 60 * 60_000)).toBe(LOAD_PHASE_GRACE_CAP_MS)+ expect(loadPhaseGraceMs(true, 0, 60 * 60_000, 60 * 60_000)).toBe(LOAD_PHASE_GRACE_CAP_MS)+ // and the cap the poll loop really passes is the warm-up budget in force+ expect(loadPhaseGraceMs(true, 0, null, 60 * 60_000, warmupBudgetMs(false))).toBe(SWAP_WARMUP_BUDGET_MS)+ })++ it('the cap matches the warm-up ceiling, so a wedged load trips G24 first', () => {+ // The two guards cannot disagree about how long a load may take: the+ // warm-up verdict lands first, with the message that names the real cause.+ expect(LOAD_PHASE_GRACE_CAP_MS).toBe(SWAP_WARMUP_ALIVE_BUDGET_MS)+ expect(warmupExceeded(false, true, SWAP_WARMUP_ALIVE_BUDGET_MS + 1, SWAP_WARMUP_ALIVE_BUDGET_MS)).toBe(true)+ })++ it('NEGATIVE CONTROL: without a WS there is no grace, the old flat deadline stands', () => {+ expect(loadPhaseGraceMs(false, 0, null, 120_000)).toBe(0)+ expect(loadPhaseGraceMs(false, 0, LOAD_MS, TOTAL_MS)).toBe(0)+ expect(deadlineAt(LOAD_MS, TOTAL_MS, false)).toBe(IMAGE_BUDGET)+ })++ it('NEGATIVE CONTROL: a render that starts sampling at once gets no free time', () => {+ expect(loadPhaseGraceMs(true, 0, 0, 10_000)).toBe(0)+ expect(deadlineAt(0, 10_000)).toBe(IMAGE_BUDGET)+ })++ it('NEGATIVE CONTROL: R32 is untouched, the pace verdict still uses the raw budget', () => {+ // 30 steps at 80 s each after a 4 minute load: the projection is hopeless+ // against the 5 minute budget and must stay hopeless.+ const t = new PaceTracker()+ t.tick(1, 30, 240_000)+ t.tick(2, 30, 320_000)+ t.tick(3, 30, 400_000)+ t.tick(4, 30, 480_000)+ expect(overBudget(t.projectedTotalMs(), IMAGE_BUDGET)).toBe(true)+ })+})++describe('a render seconds from done is adopted, not thrown away (Z36 finding 4)', () => {+ const paceAt = (value: number, max: number, stepMs: number) => {+ const t = new PaceTracker()+ for (let i = 0; i <= 4; i++) t.tick(value - 4 + i, max, (value - 4 + i) * stepMs)+ return t+ }++ it('20 steps of 25 done at 1 s each: the rest fits, the job gets the grace', () => {+ const t = paceAt(20, 25, 1000)+ expect(t.projectedRemainingMs()).toBeCloseTo(5000, -2)+ expect(finishGraceMs(t.projectedRemainingMs())).toBe(FINISH_GRACE_CAP_MS)+ })++ it('the grace is bounded and granted from one measurement only', () => {+ expect(finishGraceMs(FINISH_GRACE_CAP_MS)).toBe(FINISH_GRACE_CAP_MS)+ expect(finishGraceMs(0)).toBe(FINISH_GRACE_CAP_MS)+ })++ it('NEGATIVE CONTROL: half an hour of work left buys nothing', () => {+ expect(finishGraceMs(30 * 60_000)).toBe(0)+ expect(finishGraceMs(FINISH_GRACE_CAP_MS + 1)).toBe(0)+ })++ it('NEGATIVE CONTROL: no measured pace, no grace', () => {+ expect(finishGraceMs(null)).toBe(0)+ expect(finishGraceMs(Number.NaN)).toBe(0)+ expect(new PaceTracker().projectedRemainingMs()).toBe(null)+ const barely = new PaceTracker()+ barely.tick(1, 30, 0)+ barely.tick(2, 30, 1000)+ expect(barely.projectedRemainingMs()).toBe(null)+ })++ it('the timeout notice names the real elapsed time when the load stretched it', () => {+ const n = renderTimeoutNotice('Image', 5 * 60_000, 9 * 60_000)+ expect(n).toContain('5 minute budget')+ expect(n).toContain('about 9 minutes')+ expect(n).toContain('loading')+ // NEGATIVE CONTROL: no stretch, no extra sentence+ expect(renderTimeoutNotice('Image', 5 * 60_000, 4 * 60_000)).not.toContain('about')+ expect(renderTimeoutNotice('Image', 5 * 60_000)).not.toContain('about')+ })+})++describe('a confirmed-alive load is not a wedged load (Z36 finding 4)', () => {+ it('the plain budget still ends a load nothing can vouch for', () => {+ expect(warmupBudgetMs(false)).toBe(SWAP_WARMUP_BUDGET_MS)+ expect(warmupExceeded(false, true, SWAP_WARMUP_BUDGET_MS + 1, warmupBudgetMs(false))).toBe(true)+ })++ it('a prompt ComfyUI still has in its queue buys the doubled budget', () => {+ expect(warmupBudgetMs(true)).toBe(SWAP_WARMUP_ALIVE_BUDGET_MS)+ expect(SWAP_WARMUP_ALIVE_BUDGET_MS).toBe(2 * SWAP_WARMUP_BUDGET_MS)+ // the Z36 load, past the plain budget, survives on the life signal+ expect(warmupExceeded(false, true, SWAP_WARMUP_BUDGET_MS + 1, warmupBudgetMs(true))).toBe(false)+ })++ it('NEGATIVE CONTROL: R17c still dies, 19 wedged minutes beat both budgets', () => {+ const R17C = 19 * 60_000+ expect(warmupExceeded(false, true, R17C, warmupBudgetMs(false))).toBe(true)+ expect(warmupExceeded(false, true, R17C, warmupBudgetMs(true))).toBe(true)+ })++ it('NEGATIVE CONTROL: the life signal never overrides the WS and progress gates', () => {+ // no WS, we are blind by design+ expect(warmupExceeded(false, false, 60 * 60_000, warmupBudgetMs(true))).toBe(false)+ // something on the GPU moved, so the load is not wedged and nothing dies+ expect(warmupExceeded(true, true, 60 * 60_000, warmupBudgetMs(true))).toBe(false)+ })+})+describe('wiring in the poll loop', () => {const handoff = read('../../api/vram-handoff.ts')it('the poll loop feeds progress events into the tracker and checks the budget', () => {expect(handoff).toContain("if (ev.type === 'progress') {")- expect(handoff).toContain('pace.tick(ev.data.value, ev.data.max, Date.now())')+ expect(handoff).toContain('pace.tick(ev.data.value, ev.data.max, at)')expect(handoff).toContain('if (overBudget(projected, timeoutMs))')})@@ -134,7 +279,7 @@ describe('wiring in the poll loop', () => {it('G24: the loop tracks warm-up with ANY-prompt progress and the live WS state', () => {expect(handoff).toContain('sawAnyProgress = true')- expect(handoff).toContain('warmupExceeded(sawAnyProgress, comfyWS.connected, warmupElapsed)')+ expect(handoff).toContain('warmupExceeded(sawAnyProgress, comfyWS.connected, warmupElapsed, warmupBudgetMs(promptAlive))')// own-prompt ticks still feed the pace tracker underneath the any-progress flagexpect(handoff).toContain("if (ev.data.prompt_id === promptId) {")})@@ -143,6 +288,31 @@ describe('wiring in the poll loop', () => {expect(handoff).toContain('offProgress()')})+ it('Z36 finding 4: the deadline is recomputed per tick and carries the load phase', () => {+ // the old fixed wall clock is gone from the poll loop (other helpers keep+ // their own plain deadlines, this pin must not reach into them)+ const loop = handoff.slice(handoff.indexOf('async function pollAndExtract'))+ expect(loop).not.toContain('const deadline = Date.now() + timeoutMs')+ expect(handoff).toContain('loadPhaseGraceMs(comfyWS.connected, startedAt, firstOwnProgressAt, Date.now(),')+ expect(handoff).toContain('if (firstOwnProgressAt === null) firstOwnProgressAt = at')+ // the pace verdict keeps the RAW budget, so R32 dies as early as before+ expect(handoff).toContain('if (overBudget(projected, timeoutMs))')+ })++ it('Z36 finding 4: the loop asks ComfyUI whether a long load is still alive', () => {+ expect(handoff).toContain('promptAlive = await isPromptQueued(promptId)')+ // the question is only asked once the plain budget is spent, and throttled+ expect(handoff).toContain('warmupElapsed > SWAP_WARMUP_BUDGET_MS && Date.now() - aliveCheckedAt > 30_000')+ // and the same budget bounds the flat deadline's load grace+ expect(handoff).toContain('warmupBudgetMs(promptAlive))')+ })++ it('Z36 finding 4: a nearly finished render is adopted once, then the job ends', () => {+ expect(handoff).toContain('finishGraceUsed === 0 ? finishGraceMs(pace.projectedRemainingMs()) : 0')+ expect(handoff).toContain('finishGraceUsed = grace')+ expect(handoff).toContain('renderTimeoutNotice(kindLabel, timeoutMs, elapsedMs)')+ })+it('abandonPrompt kills only OUR job: pending delete first, interrupt only if ours runs', () => {const comfy = read('../../api/comfyui.ts')const fn = comfy.slice(comfy.indexOf('export async function abandonPrompt'))diff --git a/src/lib/render-budget.ts b/src/lib/render-budget.tsindex 5b22d01d..95237105 100644--- a/src/lib/render-budget.ts+++ b/src/lib/render-budget.ts@@ -54,6 +54,20 @@ export class PaceTracker {if (steps < MIN_STEPS_FOR_VERDICT) return nullreturn ((s.at - s.t0) / steps) * s.max}++ /**+ * Projected ms of sampling still to come, or null before enough steps. On a+ * multi-pass job this only sees the CURRENT pass, so it under-estimates. It+ * is only ever used to grant a small, capped grace, and under-estimating+ * there simply means no grace is granted.+ */+ projectedRemainingMs(): number | null {+ const s = this.s+ const total = this.projectedTotalMs()+ if (!s || total === null || s.max <= 0) return null+ const done = Math.min(1, Math.max(0, s.value / s.max))+ return total * (1 - done)+ }}export function overBudget(projectedTotalMs: number | null, budgetMs: number): boolean {@@ -87,12 +101,94 @@ export function warmupExceeded(return wsConnected && !sawAnyProgress && elapsedMs > budgetMs}+/**+ * Warm-up budget once ComfyUI CONFIRMS our prompt is still queued or running+ * (Z36 finding 4). The flat 5 minutes cannot tell a wedged load from the first+ * load of a big bf16 checkpoint on a small card, and it cut off a render the+ * Create tab completes: the Create watchdog counts a still-queued prompt as a+ * life signal (useCreate isPromptQueued), the agent path counted nothing.+ * Doubling the budget on that same signal buys the honest load its time while+ * still ending the R17c case, which sat wedged for 19 minutes.+ */+export const SWAP_WARMUP_ALIVE_BUDGET_MS = 10 * 60_000++/** The warm-up budget in force, given what ComfyUI says about our prompt. */+export function warmupBudgetMs(promptConfirmedAlive: boolean): number {+ return promptConfirmedAlive ? SWAP_WARMUP_ALIVE_BUDGET_MS : SWAP_WARMUP_BUDGET_MS+}+/** Tool result for a warm-up abort. Says what was observed, not a guess. */export function swapWarmupNotice(kindLabel: string, elapsedMs: number): string {const m = Math.max(1, Math.round(elapsedMs / 60_000))return `${kindLabel} generation stopped: after ${m} minute${m === 1 ? '' : 's'} the model was still loading into VRAM and sampling never started. The job was cancelled so the GPU is free again. Free some VRAM (close other GPU apps, or set VRAM hand-off to "always" in Settings so the chat model is evicted first), or pick a smaller model.`}+/**+ * Cap on how far the FIRST load of the checkpoint may push the flat deadline+ * out (Z36 finding 4, W3 run 2026-08-16: a forced z_image_bf16 render in the+ * chat tool was abandoned after 352.6 s because loading the big bf16 checkpoint+ * on a 3060 outlasted the warm-up budget, while the Create tab renders the same+ * job, because its watchdog bounds the SILENT gap instead of the wall clock).+ * The warm-up guard below is the one that ended that render; this cap covers+ * the same phase for the flat deadline, which a slower card or a shorter user+ * budget would hit next. The load phase already has+ * its own guard in warmupExceeded, so this only has to cover a load that is+ * slow but healthy, and it keeps the whole wait bounded at budget + cap. The+ * cap is the warm-up ceiling, so the two guards cannot disagree about how long+ * a load may take: the warm-up guard always reaches its verdict first, with the+ * message that names the real cause.+ */+export const LOAD_PHASE_GRACE_CAP_MS = SWAP_WARMUP_ALIVE_BUDGET_MS++/**+ * Ms the flat deadline may move out because the checkpoint had to be loaded+ * before sampling could start. The load phase runs from submit to the first+ * sampler progress event for OUR prompt; while that tick is still missing the+ * grace grows with the clock, and once it arrives the grace freezes at the+ * measured load time.+ *+ * Without a live WS we cannot tell loading from sampling, so there is no grace+ * at all and the flat deadline applies exactly as it did before this existed.+ *+ * This moves the FLAT deadline only. The pace verdict keeps measuring the+ * sampling pass against the raw budget, so a hopeless render (R32) still dies+ * after three steps.+ */+export function loadPhaseGraceMs(+ wsConnected: boolean,+ startedAt: number,+ firstOwnProgressAt: number | null,+ now: number,+ cap: number = LOAD_PHASE_GRACE_CAP_MS,+): number {+ if (!wsConnected) return 0+ const loadEndedAt = firstOwnProgressAt ?? now+ const loadMs = loadEndedAt - startedAt+ if (!Number.isFinite(loadMs) || loadMs <= 0) return 0+ return Math.min(loadMs, cap)+}++/** One bounded extension for a render that is seconds away from done. */+export const FINISH_GRACE_CAP_MS = 60_000++/**+ * Ms of extra time a render past its deadline has earned by being nearly+ * finished (Z36 finding 4, second half: at the deadline the app threw away a+ * job that had already paid for the whole checkpoint load and almost all of the+ * sampling). A measured pace that says the rest of the pass fits inside the cap+ * buys the whole cap once, which also covers the VAE decode and save tail. No+ * measurement, or too much work left, buys nothing and the job is cancelled as+ * before.+ */+export function finishGraceMs(+ projectedRemainingMs: number | null,+ cap: number = FINISH_GRACE_CAP_MS,+): number {+ if (projectedRemainingMs === null) return 0+ if (!Number.isFinite(projectedRemainingMs) || projectedRemainingMs < 0) return 0+ return projectedRemainingMs <= cap ? cap : 0+}+const advice = 'Try fewer frames, a smaller resolution or fewer steps, or pick a lighter model. The generation timeout is adjustable in Settings.'/** Tool result for a pace-based early stop. Honest about what was measured. */@@ -102,8 +198,16 @@ export function renderBudgetNotice(kindLabel: string, projectedMs: number, budgereturn `${kindLabel} generation stopped early: at the measured pace this render needs about ${p} minutes, more than the ${b} minute budget. The job was cancelled so the GPU is free again. ${advice}`}-/** Tool result for the flat deadline. The job is abandoned, not orphaned. */-export function renderTimeoutNotice(kindLabel: string, budgetMs: number): string {+/**+ * Tool result for the flat deadline. The job is abandoned, not orphaned. When+ * the wait outlasted the budget because the checkpoint had to load first, say+ * so instead of reporting a budget the run visibly overran.+ */+export function renderTimeoutNotice(kindLabel: string, budgetMs: number, elapsedMs?: number): string {const b = Math.max(1, Math.round(budgetMs / 60_000))- return `${kindLabel} generation hit the ${b} minute budget and was cancelled so the GPU is free again. ${advice}`+ const e = typeof elapsedMs === 'number' && Number.isFinite(elapsedMs) ? Math.max(1, Math.round(elapsedMs / 60_000)) : null+ const spent = e !== null && e > b+ ? ` It ran for about ${e} minutes: the ${b} minute budget plus the time the model spent loading.`+ : ''+ return `${kindLabel} generation hit the ${b} minute budget and was cancelled so the GPU is free again.${spent} ${advice}`}