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): Qwen prompt enhancer frees the card first, shows its tokens, ends a silent job (B41)
purple311026c1f3d7
diff --git a/src/api/__tests__/qwen-enhancer-progress.test.ts b/src/api/__tests__/qwen-enhancer-progress.test.tsnew file mode 100644index 00000000..ade9f62f--- /dev/null+++ b/src/api/__tests__/qwen-enhancer-progress.test.ts@@ -0,0 +1,121 @@+/**+ * B41 (3.0.9): Discord mneme1761, 29.10.2026. "Improve my prompt" with the+ * local Qwen enhancer on Qwen-Image 2.1 Edit stood on "Improving your+ * prompt…" for more than 530 s, without it the edit took 40 s.+ *+ * Three things the run did not do:+ * - free the card BEFORE the enhancer: the edit model of the previous run+ * stayed warm in ComfyUI (vram-handoff keeps it on purpose), and the 9 GB+ * enhancer loaded next to it;+ * - say anything but the seconds, although ComfyUI reports every token;+ * - end a job that went silent before the 15 minute limit.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import type { ComfyWSEvent } from '../comfyui-ws'++const comfy = vi.hoisted(() => ({+ log: [] as string[],+ history: [] as unknown[],+ listeners: new Set<(ev: ComfyWSEvent) => void>(),+ connected: true,+}))+vi.mock('../comfyui', async (importOriginal) => ({+ ...(await importOriginal<typeof import('../comfyui')>()),+ submitWorkflow: vi.fn(async () => { comfy.log.push('submit'); return 'pe-7' }),+ getHistory: vi.fn(async () => (comfy.history.length > 1 ? comfy.history.shift() : comfy.history[0]) ?? null),+ freeMemory: vi.fn(async () => { comfy.log.push('free') }),+ abandonPrompt: vi.fn(async (id: string) => { comfy.log.push(`abandon:${id}`) }),+}))+vi.mock('../comfyui-ws', () => ({+ comfyWS: {+ get connected() { return comfy.connected },+ connect: vi.fn(async () => {}),+ mark: () => 0,+ on: (l: (ev: ComfyWSEvent) => void) => { comfy.listeners.add(l); return () => comfy.listeners.delete(l) },+ },+}))++import { runQwenEnhancer, QWEN_ENHANCER_TIMEOUT_MS, type EnhancerProgress } from '../qwen-enhancer'+import { enhancerLine } from '../../lib/render/qwen-enhancer'++const send = (ev: ComfyWSEvent) => { for (const l of comfy.listeners) l(ev) }+const graph = { '1': { class_type: 'CLIPLoader', inputs: {} } }+const done = { status: { status_str: 'success' }, outputs: { '9': { text: ['A red fox in deep snow, soft morning light.'] } } }++beforeEach(() => {+ vi.useFakeTimers()+ comfy.log.length = 0+ comfy.history.length = 0+ comfy.listeners.clear()+ comfy.connected = true+})+afterEach(() => { vi.useRealTimers() })++describe('the card is handed over before the enhancer', () => {+ it('frees ComfyUI first, then submits, then frees again', async () => {+ comfy.history.push(done)+ const out = await runQwenEnhancer(graph, 'a fox')+ expect(out.status).toBe('improved')+ expect(comfy.log).toEqual(['free', 'submit', 'free'])+ })+})++describe('the line says where the enhancer is', () => {+ it('loading, reading, then tokens and their rate, from the job\'s own events only', async () => {+ comfy.history.push(null)+ const seen: EnhancerProgress[] = []+ const run = runQwenEnhancer(graph, 'a fox', { onProgress: (p) => seen.push(p) })+ await vi.advanceTimersByTimeAsync(0)+ send({ type: 'executing', data: { node: '1', prompt_id: 'pe-7' } })+ send({ type: 'executing', data: { node: '4', prompt_id: 'pe-7' } })+ send({ type: 'progress', data: { value: 1, max: 4096, prompt_id: 'pe-7' } })+ // Someone else's job says nothing here.+ send({ type: 'progress', data: { value: 999, max: 4096, prompt_id: 'other' } })+ await vi.advanceTimersByTimeAsync(10_000)+ send({ type: 'progress', data: { value: 11, max: 4096, prompt_id: 'pe-7' } })+ comfy.history.length = 0+ comfy.history.push(done)+ await vi.advanceTimersByTimeAsync(2_000)+ await run+ expect(seen.map((p) => p.phase)).toEqual(['queued', 'loading', 'reading', 'writing', 'writing'])+ expect(seen[3]).toEqual({ phase: 'writing', tokens: 1, max: 4096, tokensPerSecond: null })+ expect(seen[4]).toEqual({ phase: 'writing', tokens: 11, max: 4096, tokensPerSecond: 1 })+ })++ it('the words: phase, tokens, rate, and the limit when it crawls', () => {+ expect(enhancerLine({ phase: 'loading' }, 'i2i', 8)).toBe('Improving your prompt: loading the prompt enhancer…')+ expect(enhancerLine({ phase: 'reading' }, 'i2i', 8)).toContain('reads your prompt and pictures')+ expect(enhancerLine({ phase: 'writing', tokens: 320, max: 4096, tokensPerSecond: 14.2 }, 't2i', 8))+ .toBe('Improving your prompt: 320 of up to 4096 tokens, 14 tokens/s…')+ const slow = enhancerLine({ phase: 'writing', tokens: 40, max: 4096, tokensPerSecond: 0.84 }, 'i2i', 8)+ expect(slow).toContain('0.8 tokens/s')+ expect(slow).toContain('gives up after 8 min and uses your own prompt')+ })+})++describe('a job that hangs ends', () => {+ it('silence after the job has spoken ends it at the stall limit, long before the time limit', async () => {+ comfy.history.push(null)+ const run = runQwenEnhancer(graph, 'a fox', { stallMs: 60_000 })+ await vi.advanceTimersByTimeAsync(0)+ send({ type: 'executing', data: { node: '4', prompt_id: 'pe-7' } })+ await vi.advanceTimersByTimeAsync(65_000)+ await expect(run).resolves.toEqual({ status: 'failed' })+ expect(comfy.log).toEqual(['free', 'submit', 'abandon:pe-7', 'free'])+ })++ it('without the progress stream only the time limit counts', async () => {+ comfy.connected = false+ comfy.history.push(null)+ let settled = false+ const run = runQwenEnhancer(graph, 'a fox', { stallMs: 60_000 }).then((r) => { settled = true; return r })+ await vi.advanceTimersByTimeAsync(5 * 60_000)+ expect(settled).toBe(false)+ await vi.advanceTimersByTimeAsync(QWEN_ENHANCER_TIMEOUT_MS)+ await expect(run).resolves.toEqual({ status: 'failed' })+ })++ it('the time limit is eight minutes, not fifteen', () => {+ expect(QWEN_ENHANCER_TIMEOUT_MS).toBe(8 * 60_000)+ })+})diff --git a/src/api/__tests__/qwen-enhancer-workflow.test.ts b/src/api/__tests__/qwen-enhancer-workflow.test.tsindex 2f4eaa66..cb80b1c3 100644--- a/src/api/__tests__/qwen-enhancer-workflow.test.ts+++ b/src/api/__tests__/qwen-enhancer-workflow.test.ts@@ -203,19 +203,19 @@ describe('the run', () => {expect(out).toEqual({ status: 'improved', prompt: 'A red fox in deep snow.' })expect(comfy.submitted).toEqual([graph])// The enhancer is out of the card before the caller builds the picture.- expect(comfy.log).toEqual(['submit', 'free'])+ expect(comfy.log).toEqual(['free', 'submit', 'free'])})it('a ComfyUI error is a failed rewrite, never a thrown one, and the card is freed', async () => {comfy.history.push({ status: { status_str: 'error', messages: [['execution_error', { exception_message: 'CUDA out of memory' }]] } })await expect(runQwenEnhancer(graph, 'a fox')).resolves.toEqual({ status: 'failed' })- expect(comfy.log).toEqual(['submit', 'free'])+ expect(comfy.log).toEqual(['free', 'submit', 'free'])})it('a rejected graph (file gone since the list was read) is a failed rewrite', async () => {comfy.submitError = new Error('ComfyUI rejected workflow: Value not in list')await expect(runQwenEnhancer(graph, 'a fox')).resolves.toEqual({ status: 'failed' })- expect(comfy.log).toEqual(['submit', 'free'])+ expect(comfy.log).toEqual(['free', 'submit', 'free'])})it('a refusal or an empty answer is a failed rewrite', async () => {@@ -229,7 +229,7 @@ describe('the run', () => {it('out of time: the job is taken out of the queue, then the card is freed', async () => {comfy.history.push(null)await expect(runQwenEnhancer(graph, 'a fox', { timeoutMs: -1 })).resolves.toEqual({ status: 'failed' })- expect(comfy.log).toEqual(['submit', 'abandon:pe-1', 'free'])+ expect(comfy.log).toEqual(['free', 'submit', 'abandon:pe-1', 'free'])})it('Cancel: the job is taken out of the queue at once', async () => {@@ -239,7 +239,7 @@ describe('the run', () => {await new Promise((r) => setTimeout(r, 10))stop.abort()await expect(run).resolves.toEqual({ status: 'failed' })- expect(comfy.log).toEqual(['submit', 'abandon:pe-1', 'free'])+ expect(comfy.log).toEqual(['free', 'submit', 'abandon:pe-1', 'free'])})it('cancelled before it starts: nothing is sent', async () => {diff --git a/src/api/qwen-enhancer.ts b/src/api/qwen-enhancer.tsindex eed97a9f..ff212892 100644--- a/src/api/qwen-enhancer.ts+++ b/src/api/qwen-enhancer.ts@@ -19,8 +19,9 @@ import type { ComfyApiGraph, ComfyNodeInputs } from '../types/comfy-graph'import { isRecord } from '../types/json-guards'import { getAllNodeInfo } from './comfyui-nodes'import { submitWorkflow, getHistory, freeMemory, abandonPrompt } from './comfyui'+import { comfyWS, type ComfyWSEvent } from './comfyui-ws'import { WorkflowUnavailableError } from './dynamic-workflow'-import { enhancedOutcome, type QwenEnhancerMode } from '../lib/render/qwen-enhancer'+import { enhancedOutcome, type EnhancerPhase, type QwenEnhancerMode } from '../lib/render/qwen-enhancer'import type { ImproveOutcome } from '../lib/render/improve-prompt'import { QWEN_PE_I2I_SYSTEM_PROMPT, QWEN_PE_T2I_SYSTEM_PROMPT } from './qwen-enhancer-prompts'@@ -36,13 +37,32 @@ export const QWEN_ENHANCER_NEEDS_UPDATE = 'The Qwen prompt enhancer needs ComfyUexport const QWEN_ENHANCER_MAX_LENGTH = 4096/** How long the rewrite may take, loading the 9 GB file included. After this- * the job is taken out of the queue and the run goes on with the user's prompt. */-export const QWEN_ENHANCER_TIMEOUT_MS = 15 * 60_000+ * the job is taken out of the queue and the run goes on with the user's prompt.+ * B41 (3.0.9): was 15 minutes, and a user gave up after 530 s of a line that+ * only counted. The box needs 70 s for a new picture and 175 s for an edit+ * on a 12 GB card; eight minutes leaves a slower card room and no more. */+export const QWEN_ENHANCER_TIMEOUT_MS = 8 * 60_000++/** How long the enhancer may go without a word from ComfyUI once it has+ * started reporting: no token, no node. A stuck job ends here instead of at+ * the time limit. Only counted while the progress stream is connected. */+export const QWEN_ENHANCER_STALL_MS = 3 * 60_000const POLL_MS = 1500/** The node whose text is the answer. */export const QWEN_ENHANCER_OUTPUT_NODE = '9'+/** The loader and the writer, by id, so their progress can be told apart. */+const LOADER_NODE = '1'+const WRITER_NODE = '4'++/**+ * Where the enhancer is, from ComfyUI's progress stream (B41). TextGenerate+ * counts its tokens through ComfyUI's ProgressBar, one `progress` event per+ * token with `max` = max_length (comfy/text_encoders/llama.py `generate`), so+ * the line can say how far it is instead of only counting seconds.+ */+export type EnhancerProgress = EnhancerPhaseexport interface QwenEnhancerRequest {/** The enhancer file as ComfyUI lists it. */@@ -165,16 +185,50 @@ const wait = (ms: number, signal?: AbortSignal) => new Promise<void>((resolve) =export async function runQwenEnhancer(workflow: ComfyApiGraph,original: string,- opts: { clientId?: string; signal?: AbortSignal; timeoutMs?: number } = {},+ opts: { clientId?: string; signal?: AbortSignal; timeoutMs?: number; stallMs?: number; onProgress?: (p: EnhancerProgress) => void } = {},): Promise<ImproveOutcome> {const { signal } = optsif (signal?.aborted) return { status: 'failed' }let promptId: string | null = null+ // B41: the card is handed over BEFORE the enhancer too. LU keeps the last+ // picture's model warm in ComfyUI on purpose (vram-handoff), so after an+ // edit without the rewrite, Qwen-Image 2.1 Edit still sat on the card when+ // the 9 GB enhancer loaded next to it, which then wrote its tokens partly+ // from system memory. ComfyUI frees the card between jobs, so this lands+ // before the enhancer's job starts. The picture after it loads again+ // anyway: the enhancer's own free below drops everything.+ await freeMemory()+ // Ask for the stream; a run without it still ends, by /history below.+ void comfyWS.connect().catch(() => {})+ const since = comfyWS.mark()+ let lastSign = 0+ let firstTokenAt = 0+ let firstTokenCount = 0+ const report = (p: EnhancerProgress) => { try { opts.onProgress?.(p) } catch { /* the line is the caller's */ } }+ const onEvent = (ev: ComfyWSEvent) => {+ if (!promptId || !('prompt_id' in ev.data) || ev.data.prompt_id !== promptId) return+ lastSign = Date.now()+ if (ev.type === 'executing' && ev.data.node === LOADER_NODE) report({ phase: 'loading' })+ else if (ev.type === 'executing' && ev.data.node === WRITER_NODE) report({ phase: 'reading' })+ else if (ev.type === 'progress') {+ const { value, max } = ev.data+ if (!firstTokenAt) { firstTokenAt = Date.now(); firstTokenCount = value }+ const secs = (Date.now() - firstTokenAt) / 1000+ const rate = secs >= 2 && value > firstTokenCount ? (value - firstTokenCount) / secs : null+ report({ phase: 'writing', tokens: value, max, tokensPerSecond: rate })+ }+ }+ let off: (() => void) | null = nulltry {+ report({ phase: 'queued' })promptId = await submitWorkflow(workflow, opts.clientId)+ off = comfyWS.on(onEvent, since)const deadline = Date.now() + (opts.timeoutMs ?? QWEN_ENHANCER_TIMEOUT_MS)+ const stallMs = opts.stallMs ?? QWEN_ENHANCER_STALL_MSfor (;;) {if (signal?.aborted || Date.now() > deadline) break+ // Silence only counts once the stream has spoken for this job.+ if (lastSign && comfyWS.connected && Date.now() - lastSign > stallMs) breakconst entry = await getHistory(promptId)const status = entry?.status?.status_strif (status === 'success') {@@ -191,6 +245,7 @@ export async function runQwenEnhancer(} catch {return { status: 'failed' }} finally {+ off?.()// Cancelled or out of time: our job must not keep the card busy.if (promptId) await abandonPrompt(promptId).catch(() => {})await freeMemory()diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.tsindex 733b118f..a45688f2 100644--- a/src/hooks/useCreate.ts+++ b/src/hooks/useCreate.ts@@ -80,8 +80,8 @@ import { improveKindForIntent, IMPROVING_PROMPT, type ImproveOutcome } from '../import { elapsedLine } from '../lib/elapsed-line'import { improvePrompt } from '../lib/render/improve-prompt-run'import { currentChatModelList, currentHelperModel } from '../lib/cloud-helper-model'-import { enhancerNames, pickQwenEnhancer, rewrittenByName, type ImproveWriter } from '../lib/render/qwen-enhancer'-import { buildQwenEnhancerWorkflow, runQwenEnhancer } from '../api/qwen-enhancer'+import { enhancerLine, enhancerNames, pickQwenEnhancer, rewrittenByName, type ImproveWriter } from '../lib/render/qwen-enhancer'+import { buildQwenEnhancerWorkflow, runQwenEnhancer, QWEN_ENHANCER_TIMEOUT_MS } from '../api/qwen-enhancer'import { enhancePromptOnMac } from '../api/mlx-enhancer'import { extraReferenceSlots, referenceSide } from '../lib/edit-references'import { canonicalImageRefs } from '../lib/image-ref-names'@@ -1779,7 +1779,14 @@ export function useCreate() {// The rewrite is the long wait (70 to 175 s on a 12 GB card), so the// line counts from here; the build above has its own status lines.const improving = elapsedLine((text) => setProgress(3, text), IMPROVING_PROMPT)- const out = await runQwenEnhancer(enhancerGraph, scenePrompt, { clientId: CLIENT_ID, signal }).finally(improving.stop)+ // B41: the line says which part runs and, while it writes, how many+ // tokens it has and how fast, from ComfyUI's own progress stream.+ const limitMinutes = Math.round(QWEN_ENHANCER_TIMEOUT_MS / 60_000)+ const out = await runQwenEnhancer(enhancerGraph, scenePrompt, {+ clientId: CLIENT_ID,+ signal,+ onProgress: (p) => improving.setLabel(enhancerLine(p, qwenEnhancer.mode, limitMinutes)),+ }).finally(improving.stop)if (signal?.aborted) throw new Error('Cancelled')takeRewrite(out, qwenEnhancer.variant)}diff --git a/src/lib/render/qwen-enhancer.ts b/src/lib/render/qwen-enhancer.tsindex 58baf1ed..29293411 100644--- a/src/lib/render/qwen-enhancer.ts+++ b/src/lib/render/qwen-enhancer.ts@@ -227,3 +227,39 @@ export function enhancerNames(if (!where.onMac) return textEncodersreturn where.mlxModel ? macEnhancers : []}++/** What the Qwen enhancer's progress looks like here; the run reports it+ * (api/qwen-enhancer.ts `EnhancerProgress`). */+export type EnhancerPhase =+ | { phase: 'queued' }+ | { phase: 'loading' }+ | { phase: 'reading' }+ | { phase: 'writing'; tokens: number; max: number; tokensPerSecond: number | null }++/**+ * The waiting line while the enhancer works (B41, 3.0.9). A user waited 530 s+ * on "Improving your prompt…" with nothing but the seconds moving. Now the+ * line says which part is running, and while it writes, how many tokens it+ * has and how fast it goes: a card that writes one token a second shows it+ * at once, instead of after minutes. `max` is the limit, not a goal: the+ * enhancer stops at its own end, usually long before.+ */+export function enhancerLine(p: EnhancerPhase, mode: QwenEnhancerMode, limitMinutes: number): string {+ switch (p.phase) {+ case 'queued':+ return 'Improving your prompt: waiting for ComfyUI…'+ case 'loading':+ return 'Improving your prompt: loading the prompt enhancer…'+ case 'reading':+ return mode === 'i2i'+ ? 'Improving your prompt: the enhancer reads your prompt and pictures…'+ : 'Improving your prompt: the enhancer reads your prompt…'+ case 'writing': {+ const rate = p.tokensPerSecond === null ? '' : `, ${p.tokensPerSecond >= 10 ? Math.round(p.tokensPerSecond) : Math.round(p.tokensPerSecond * 10) / 10} tokens/s`+ const slow = p.tokensPerSecond !== null && p.tokensPerSecond < 3+ ? ` Slow: the enhancer does not fit on the graphics card next to everything else. LU gives up after ${limitMinutes} min and uses your own prompt.`+ : ''+ return `Improving your prompt: ${p.tokens} of up to ${p.max} tokens${rate}…${slow}`+ }+ }+}