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.

feat(create): the Qwen-Image 2.1 prompt enhancer writes for Improve my prompt

purple90fbe89f606f
diff --git a/e2e/qwen-prompt-enhancer.spec.ts b/e2e/qwen-prompt-enhancer.spec.ts
new file mode 100644
index 00000000..ddde1f24
--- /dev/null
+++ b/e2e/qwen-prompt-enhancer.spec.ts
@@ -0,0 +1,109 @@
+import { test, expect, type Page } from '@playwright/test'
+import { tauriMockInit, DEFAULT_ASSISTANT_REPLY, DEFAULT_MODEL_NAME } from './support/tauri-mock'
+import { seedOnboardingDone } from './support/cloud-mock'
+
+/**
+ * GH #148 (neilmcginnis): the Qwen-Image 2.1 prompt enhancer behind the one
+ * switch "Improve my prompt". A rebuilt ComfyUI answers through
+ * proxy_localhost with a local Qwen-Image 2.1 and, per test, the enhancer
+ * files in its text encoder folder. Nothing is rendered.
+ */
+
+const QWEN = 'qwen_image_2.1_int8_convrot.safetensors'
+const ENCODER = 'qwen3vl_8b_int8_convrot.safetensors'
+const ENHANCERS = [
+ 'qwen3.5_9b_qwen_image_2.1_pe_t2i.int8_convrot.safetensors',
+ 'qwen3.5_9b_qwen_image_2.1_pe_i2i.int8_convrot.safetensors',
+ 'qwen3.5_9b_qwen_image_2.1_pe_t2i_heretic.int8_convrot.safetensors',
+ 'qwen3.5_9b_qwen_image_2.1_pe_i2i_heretic.int8_convrot.safetensors',
+]
+
+async function bootWithFakeComfy(page: Page, textEncoders: string[]) {
+ await page.addInitScript(tauriMockInit, { assistantReply: DEFAULT_ASSISTANT_REPLY, modelName: DEFAULT_MODEL_NAME, platform: 'windows' as const })
+ await seedOnboardingDone(page)
+ await page.addInitScript(([model, encoders]) => {
+ const w = window as unknown as { __TAURI_INTERNALS__: { invoke: (c: string, a: { url?: string }) => Promise<unknown> } }
+ if (!localStorage.getItem('create-store')) {
+ localStorage.setItem('create-store', JSON.stringify({ state: { backend: 'local', imageModel: model }, version: 2 }))
+ }
+ const bridge = w.__TAURI_INTERNALS__
+ const invoke = bridge.invoke
+ const combo = (v: string[]) => [v]
+ const nodes: Record<string, unknown> = {
+ UNETLoader: { input: { required: { unet_name: combo([model as string]) } } },
+ CLIPLoader: { input: { required: { clip_name: combo(encoders as string[]) } } },
+ VAELoader: { input: { required: { vae_name: combo(['qwen_image_2.1_vae_bf16.safetensors']) } } },
+ KSampler: { input: { required: { sampler_name: combo(['euler']), scheduler: combo(['simple']) } } },
+ }
+ bridge.invoke = (command, args) => {
+ if (command === 'sniff_model_files') return Promise.resolve([])
+ if (command !== 'proxy_localhost' || !args?.url?.includes(':8188')) return invoke(command, args)
+ const url = args.url
+ if (url.includes('/system_stats')) return Promise.resolve(JSON.stringify({ devices: [{ name: 'RTX 4090', type: 'cuda', vram_total: 24 * 1024 ** 3 }] }))
+ const one = /\/object_info\/([^/?]+)/.exec(url)
+ if (one) return Promise.resolve(JSON.stringify(one[1] in nodes ? { [one[1]]: nodes[one[1]] } : {}))
+ if (url.includes('/object_info')) return Promise.resolve(JSON.stringify(nodes))
+ return Promise.resolve('{}')
+ }
+ }, [QWEN, textEncoders] as const)
+}
+
+async function openAdvanced(page: Page, intent: string) {
+ await page.goto('/')
+ await page.getByRole('button', { name: /^Create$/ }).click()
+ await page.getByRole('radio', { name: intent, exact: true }).click()
+ await page.getByRole('button', { name: 'Advanced settings' }).click()
+}
+
+const theSwitch = (page: Page) => page.getByRole('switch', { name: /Improve my prompt/ })
+const writers = (page: Page) => page.getByRole('radiogroup', { name: 'Rewritten by' })
+const saved = (page: Page) => page.evaluate(() => {
+ const state = JSON.parse(localStorage.getItem('create-store') || '{}').state
+ return { improvePrompt: state?.improvePrompt, improveWith: state?.improveWith }
+})
+
+test('with the enhancers installed, the one switch offers who writes and remembers the pick', async ({ page }) => {
+ await bootWithFakeComfy(page, [ENCODER, ...ENHANCERS])
+ await openAdvanced(page, 'Image')
+ await expect(theSwitch(page)).toBeVisible({ timeout: 15_000 })
+ await expect(theSwitch(page)).toHaveCount(1)
+ await expect(theSwitch(page)).toHaveAttribute('aria-checked', 'false')
+ await expect(writers(page)).toHaveCount(0)
+
+ await theSwitch(page).click()
+ await expect(theSwitch(page)).toHaveAttribute('aria-checked', 'true')
+ await expect(writers(page).getByRole('radio')).toHaveText(['Qwen enhancer', 'Qwen enhancer, no refusals', 'Chat model'])
+ await expect(page.getByRole('radio', { name: 'Qwen enhancer', exact: true })).toHaveAttribute('aria-checked', 'true')
+
+ await page.getByRole('radio', { name: 'Qwen enhancer, no refusals' }).click()
+ await expect(page.getByRole('radio', { name: 'Qwen enhancer, no refusals' })).toHaveAttribute('aria-checked', 'true')
+ await expect.poll(() => saved(page)).toEqual({ improvePrompt: true, improveWith: 'unfiltered' })
+
+ // Nothing of it sits in or above the prompt field: with the drawer closed
+ // the page shows neither the switch nor the row.
+ await page.keyboard.press('Escape')
+ await expect(theSwitch(page)).toHaveCount(0)
+ await expect(page.getByText('Rewritten by')).toHaveCount(0)
+})
+
+test('Edit gets the switch through the edit enhancer and lists no chat model', async ({ page }) => {
+ await bootWithFakeComfy(page, [ENCODER, ...ENHANCERS])
+ await openAdvanced(page, 'Edit / Image to Image')
+ await expect(theSwitch(page)).toBeVisible({ timeout: 15_000 })
+ await theSwitch(page).click()
+ await expect(writers(page).getByRole('radio')).toHaveText(['Qwen enhancer', 'Qwen enhancer, no refusals'])
+})
+
+test('without an enhancer the switch is the chat model switch: no row, and none on Edit', async ({ page }) => {
+ await bootWithFakeComfy(page, [ENCODER])
+ await openAdvanced(page, 'Image')
+ await expect(theSwitch(page)).toBeVisible({ timeout: 15_000 })
+ await theSwitch(page).click()
+ await expect(theSwitch(page)).toHaveAttribute('aria-checked', 'true')
+ await expect(writers(page)).toHaveCount(0)
+ await page.keyboard.press('Escape')
+ await page.getByRole('radio', { name: 'Edit / Image to Image', exact: true }).click()
+ await page.getByRole('button', { name: 'Advanced settings' }).click()
+ await expect(page.getByRole('button', { name: 'Quality' })).toBeVisible()
+ await expect(theSwitch(page)).toHaveCount(0)
+})
diff --git a/src/api/__tests__/qwen-enhancer-workflow.test.ts b/src/api/__tests__/qwen-enhancer-workflow.test.ts
new file mode 100644
index 00000000..e3f7cc8f
--- /dev/null
+++ b/src/api/__tests__/qwen-enhancer-workflow.test.ts
@@ -0,0 +1,405 @@
+/**
+ * The Qwen-Image 2.1 prompt enhancer (GH #148): the graph ComfyUI gets, the
+ * version it needs, the run, and the two Model Manager bundles.
+ *
+ * Read off the real sources on 2026-10-03, not guessed:
+ * - Comfy-Org/workflow_templates, image_qwen_image_2_1_t2i.json and
+ * image_qwen_image_2_1_image_edit.json (commit 9fae1041be): the enhancer
+ * chain CLIPLoader -> TextGenerate -> PreviewAny, the system prompt through
+ * PrimitiveStringMultiline, BatchImagesNode in front of the image input,
+ * and every widget value of TextGenerate
+ * - ComfyUI comfy_extras/nodes_textgen.py at the tags 0.37.1 and 0.37.2: the
+ * `system_prompt` input arrived in 0.37.2
+ * - the Hugging Face API for both repos: file names, byte counts, SHA-256
+ *
+ * Run: npx vitest run src/api/__tests__/qwen-enhancer-workflow.test.ts
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { createHash } from 'node:crypto'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+
+vi.mock('../backend', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../backend')>()
+ return { ...actual, localFetch: vi.fn(), comfyuiUrl: (p: string) => `http://test${p}` }
+})
+
+const comfy = vi.hoisted(() => ({
+ submitted: [] as unknown[],
+ history: [] as unknown[],
+ submitError: null as Error | null,
+ log: [] as string[],
+}))
+vi.mock('../comfyui', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../comfyui')>()
+ return {
+ ...actual,
+ submitWorkflow: vi.fn(async (workflow: unknown) => {
+ comfy.log.push('submit')
+ if (comfy.submitError) throw comfy.submitError
+ comfy.submitted.push(workflow)
+ return 'pe-1'
+ }),
+ 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}`) }),
+ }
+})
+
+import {
+ QWEN_ENHANCER_MAX_LENGTH, QWEN_ENHANCER_NEEDS_UPDATE, QWEN_ENHANCER_OUTPUT_NODE,
+ qwenEnhancerGraph, runQwenEnhancer,
+} from '../qwen-enhancer'
+import { QWEN_PE_I2I_SYSTEM_PROMPT, QWEN_PE_T2I_SYSTEM_PROMPT } from '../qwen-enhancer-prompts'
+import { findMatchingCLIP } from '../comfyui'
+import { getImageBundles } from '../discover'
+import { localFetch } from '../backend'
+import { qwenEnhancerFile } from '../../lib/render/qwen-enhancer'
+import { nodeOf, nodesOf } from './graph-test-support'
+import type { ComfyApiGraph } from '../../types/comfy-graph'
+
+/** The inputs and the id of the one node of this class. */
+const inputsOf = (graph: ComfyApiGraph, klass: string) => nodeOf(graph, klass)![1].inputs
+const idOf = (graph: ComfyApiGraph, klass: string) => nodeOf(graph, klass)![0]
+
+const T2I = 'qwen3.5_9b_qwen_image_2.1_pe_t2i.int8_convrot.safetensors'
+const I2I_FREE = 'qwen3.5_9b_qwen_image_2.1_pe_i2i_heretic.int8_convrot.safetensors'
+
+/** The four core nodes of a ComfyUI that can run the enhancer (0.37.2 and up). */
+const NODES = {
+ TextGenerate: { input: { required: { clip: ['CLIP'], prompt: ['STRING'], max_length: ['INT'] }, optional: { image: ['IMAGE'], thinking: ['BOOLEAN'], mtp: ['COMBO'], system_prompt: ['STRING'] } } },
+ PrimitiveStringMultiline: { input: { required: { value: ['STRING'] } } },
+ PreviewAny: { input: { required: { source: ['*'] } } },
+ BatchImagesNode: { input: { required: {} } },
+}
+/** ComfyUI 0.37.0 and 0.37.1: Qwen-Image 2.1 runs, TextGenerate has no system prompt yet. */
+const NODES_0371 = {
+ ...NODES,
+ TextGenerate: { input: { required: { clip: ['CLIP'], prompt: ['STRING'], max_length: ['INT'] }, optional: { image: ['IMAGE'], thinking: ['BOOLEAN'], mtp: ['COMBO'] } } },
+}
+
+beforeEach(() => {
+ comfy.submitted.length = 0
+ comfy.history.length = 0
+ comfy.log.length = 0
+ comfy.submitError = null
+})
+
+describe('the enhancer graph for a new picture (T2I)', () => {
+ const graph = qwenEnhancerGraph({ file: T2I, mode: 't2i', prompt: 'a fox in snow', seed: 42 }, NODES)
+
+ it('loads the enhancer file and nothing of the image model', () => {
+ expect(inputsOf(graph, 'CLIPLoader')).toEqual({ clip_name: T2I, type: 'qwen_image', device: 'default' })
+ expect(Object.values(graph).map((n) => n.class_type).sort()).toEqual(['CLIPLoader', 'PreviewAny', 'PrimitiveStringMultiline', 'TextGenerate'])
+ })
+
+ it('TextGenerate carries the template values, the prompt and the T2I system prompt', () => {
+ const id = idOf(graph, 'CLIPLoader')
+ const systemId = idOf(graph, 'PrimitiveStringMultiline')
+ expect(inputsOf(graph, 'TextGenerate')).toEqual({
+ clip: [id, 0],
+ prompt: 'a fox in snow',
+ max_length: 4096,
+ sampling_mode: 'on',
+ 'sampling_mode.temperature': 1,
+ 'sampling_mode.top_k': 20,
+ 'sampling_mode.top_p': 0.95,
+ 'sampling_mode.min_p': 0,
+ 'sampling_mode.repetition_penalty': 1,
+ 'sampling_mode.seed': 42,
+ 'sampling_mode.presence_penalty': 1.5,
+ thinking: true,
+ use_default_template: true,
+ mtp: 'auto',
+ system_prompt: [systemId, 0],
+ })
+ expect(QWEN_ENHANCER_MAX_LENGTH).toBe(4096)
+ expect(inputsOf(graph, 'PrimitiveStringMultiline').value).toBe(QWEN_PE_T2I_SYSTEM_PROMPT)
+ })
+
+ it('the answer leaves through PreviewAny, the node the run reads', () => {
+ expect(graph[QWEN_ENHANCER_OUTPUT_NODE]).toEqual({ class_type: 'PreviewAny', inputs: { source: [idOf(graph, 'TextGenerate'), 0] } })
+ })
+
+ it('takes no picture, even when one is handed in', () => {
+ const g = qwenEnhancerGraph({ file: T2I, mode: 't2i', prompt: 'a fox', seed: 1, images: ['source.png'] }, NODES)
+ expect(nodesOf(g, 'LoadImage')).toHaveLength(0)
+ expect(inputsOf(g, 'TextGenerate').image).toBeUndefined()
+ })
+})
+
+describe('the enhancer graph for an edit (I2I)', () => {
+ it('one picture goes straight into the enhancer', () => {
+ const graph = qwenEnhancerGraph({ file: I2I_FREE, mode: 'i2i', prompt: 'make it night', seed: 7, images: ['source.png'] }, NODES)
+ expect(inputsOf(graph, 'LoadImage')).toEqual({ image: 'source.png' })
+ const gen = inputsOf(graph, 'TextGenerate')
+ expect(gen.image).toEqual([idOf(graph, 'LoadImage'), 0])
+ expect(nodesOf(graph, 'BatchImagesNode')).toHaveLength(0)
+ expect(inputsOf(graph, 'CLIPLoader').clip_name).toBe(I2I_FREE)
+ })
+
+ it('the edit system prompt and the edit sampling: no presence penalty', () => {
+ const graph = qwenEnhancerGraph({ file: I2I_FREE, mode: 'i2i', prompt: 'make it night', seed: 7, images: ['source.png'] }, NODES)
+ expect(inputsOf(graph, 'PrimitiveStringMultiline').value).toBe(QWEN_PE_I2I_SYSTEM_PROMPT)
+ const gen = inputsOf(graph, 'TextGenerate')
+ expect(gen['sampling_mode.presence_penalty']).toBe(0)
+ expect(gen['sampling_mode.seed']).toBe(7)
+ expect(gen.prompt).toBe('make it night')
+ expect(gen.thinking).toBe(true)
+ })
+
+ it('source and references reach it as one batch, in the order the picture numbers them', () => {
+ const graph = qwenEnhancerGraph({
+ file: I2I_FREE, mode: 'i2i', prompt: 'put the woman from <image2> into <image1>', seed: 7,
+ images: ['street.png', 'woman.png', 'hat.png'],
+ }, NODES)
+ const loads = nodesOf(graph, 'LoadImage')
+ expect(loads.map(([, n]) => n.inputs.image)).toEqual(['street.png', 'woman.png', 'hat.png'])
+ expect(inputsOf(graph, 'BatchImagesNode')).toEqual({
+ 'images.image0': [loads[0][0], 0],
+ 'images.image1': [loads[1][0], 0],
+ 'images.image2': [loads[2][0], 0],
+ })
+ expect(inputsOf(graph, 'TextGenerate').image).toEqual([idOf(graph, 'BatchImagesNode'), 0])
+ })
+})
+
+describe('the version lock', () => {
+ it('names the version and the way out, in the words Create keys the update on', () => {
+ expect(QWEN_ENHANCER_NEEDS_UPDATE).toBe('The Qwen prompt enhancer needs ComfyUI 0.37.2 or newer. Update ComfyUI in Settings.')
+ })
+
+ it('a ComfyUI whose TextGenerate takes no system prompt gets the update sentence, for T2I and I2I', () => {
+ for (const req of [
+ { file: T2I, mode: 't2i' as const, prompt: 'a fox', seed: 1 },
+ { file: I2I_FREE, mode: 'i2i' as const, prompt: 'make it night', seed: 1, images: ['a.png'] },
+ ]) {
+ let thrown: unknown
+ try { qwenEnhancerGraph(req, NODES_0371) } catch (err) { thrown = err }
+ expect(thrown).toBeInstanceOf(Error)
+ const err = thrown as Error & { needsComfyUpdate?: boolean }
+ expect(err.name).toBe('WorkflowUnavailableError')
+ expect(err.message).toBe(QWEN_ENHANCER_NEEDS_UPDATE)
+ expect(err.needsComfyUpdate).toBe(true)
+ }
+ })
+
+ it('a ComfyUI without TextGenerate at all gets it too', () => {
+ expect(() => qwenEnhancerGraph({ file: T2I, mode: 't2i', prompt: 'a fox', seed: 1 }, {})).toThrow(QWEN_ENHANCER_NEEDS_UPDATE)
+ })
+
+ it('a current ComfyUI builds without a word', () => {
+ expect(() => qwenEnhancerGraph({ file: T2I, mode: 't2i', prompt: 'a fox', seed: 1 }, NODES)).not.toThrow()
+ })
+})
+
+describe('the run', () => {
+ const graph = qwenEnhancerGraph({ file: T2I, mode: 't2i', prompt: 'a fox', seed: 1 }, NODES)
+ const done = (text: unknown) => ({ status: { status_str: 'success' }, outputs: { [QWEN_ENHANCER_OUTPUT_NODE]: { text: [text] } } })
+
+ it('reads the rewritten prompt and unloads the enhancer afterwards', async () => {
+ comfy.history.push(null, done('A red fox in deep snow.'))
+ const out = await runQwenEnhancer(graph, 'a fox', { clientId: 'lu-test' })
+ 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'])
+ })
+
+ 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'])
+ })
+
+ 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'])
+ })
+
+ it('a refusal or an empty answer is a failed rewrite', async () => {
+ comfy.history.push(done("I'm sorry, but I can't help with that."))
+ await expect(runQwenEnhancer(graph, 'a fox')).resolves.toEqual({ status: 'failed' })
+ comfy.history.length = 0
+ comfy.history.push({ status: { status_str: 'success' }, outputs: {} })
+ await expect(runQwenEnhancer(graph, 'a fox')).resolves.toEqual({ status: 'failed' })
+ })
+
+ 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'])
+ })
+
+ it('Cancel: the job is taken out of the queue at once', async () => {
+ comfy.history.push(null)
+ const stop = new AbortController()
+ const run = runQwenEnhancer(graph, 'a fox', { signal: stop.signal })
+ 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'])
+ })
+
+ it('cancelled before it starts: nothing is sent', async () => {
+ const stop = new AbortController()
+ stop.abort()
+ await expect(runQwenEnhancer(graph, 'a fox', { signal: stop.signal })).resolves.toEqual({ status: 'failed' })
+ expect(comfy.log).toEqual([])
+ })
+})
+
+describe('the system prompts', () => {
+ const sha = (text: string) => createHash('sha256').update(text, 'utf8').digest('hex')
+
+ it('are the template texts, to the character', () => {
+ expect(QWEN_PE_T2I_SYSTEM_PROMPT).toHaveLength(10308)
+ expect(sha(QWEN_PE_T2I_SYSTEM_PROMPT)).toBe('0b8b261455e2a8c48757bdad7c3cb71173c67ab7b5ab7042a2635fd76a6fb2bf')
+ expect(QWEN_PE_I2I_SYSTEM_PROMPT).toHaveLength(10494)
+ expect(sha(QWEN_PE_I2I_SYSTEM_PROMPT)).toBe('eaff356cd2bdbcfd1aaf20502b5ccd8cbad16fa6e9afe41e3166eeee299c8e59')
+ })
+
+ it('each asks for a plain paragraph, not for JSON', () => {
+ expect(QWEN_PE_T2I_SYSTEM_PROMPT).toContain('Your whole reply is used as the image prompt')
+ expect(QWEN_PE_I2I_SYSTEM_PROMPT).toContain('Output ONLY the rewritten editing instruction itself')
+ })
+
+ it('the source file is plain ASCII', () => {
+ const source = readFileSync(resolve(__dirname, '../qwen-enhancer-prompts.ts'), 'utf8')
+ expect([...source].every((c) => c.charCodeAt(0) < 128)).toBe(true)
+ })
+})
+
+describe('the encoder search never picks an enhancer', () => {
+ const serve = (clips: string[]) => {
+ vi.mocked(localFetch).mockResolvedValue({
+ ok: true,
+ json: async () => ({ CLIPLoader: { input: { required: { clip_name: [clips] } } } }),
+ } as never)
+ }
+ const ALL_FOUR = [
+ 'qwen3.5_9b_qwen_image_2.1_pe_i2i.int8_convrot.safetensors',
+ 'qwen3.5_9b_qwen_image_2.1_pe_i2i_heretic.int8_convrot.safetensors',
+ T2I,
+ 'qwen3.5_9b_qwen_image_2.1_pe_t2i_heretic.int8_convrot.safetensors',
+ ]
+
+ it('HunyuanVideo keeps its own Qwen encoder although the enhancers sort first', async () => {
+ serve([...ALL_FOUR, 'qwen_2.5_vl_7b_fp8_scaled.safetensors'])
+ await expect(findMatchingCLIP('hunyuan')).resolves.toBe('qwen_2.5_vl_7b_fp8_scaled.safetensors')
+ })
+
+ it('with only enhancers in the folder, every family says which encoder to download', async () => {
+ serve(ALL_FOUR)
+ await expect(findMatchingCLIP('flux2', 'flux-2-klein-4b.safetensors')).rejects.toThrow(/qwen_3_4b/)
+ await expect(findMatchingCLIP('zimage')).rejects.toThrow(/qwen_3_4b\.safetensors/)
+ await expect(findMatchingCLIP('framepack')).rejects.toThrow(/llava_llama3_fp8_scaled/)
+ await expect(findMatchingCLIP('hunyuan')).rejects.toThrow(/qwen_2\.5_vl_7b_fp8_scaled/)
+ await expect(findMatchingCLIP('qwenimage')).rejects.toThrow(/qwen3vl_8b_int8_convrot/)
+ })
+
+ it('next to an unrelated encoder, FLUX 2, Z-Image and FramePack still do not take an enhancer', async () => {
+ serve([...ALL_FOUR, 't5xxl_fp16.safetensors'])
+ await expect(findMatchingCLIP('flux2', 'flux-2-klein-4b.safetensors')).rejects.toThrow(/FLUX 2 text encoder/)
+ await expect(findMatchingCLIP('zimage')).rejects.toThrow(/Z-Image text encoder/)
+ await expect(findMatchingCLIP('framepack')).rejects.toThrow(/FramePack text encoder/)
+ })
+
+ it('Qwen-Image 2.1 keeps Qwen3-VL 8B next to them', async () => {
+ serve([...ALL_FOUR, 'qwen3vl_8b_int8_convrot.safetensors'])
+ await expect(findMatchingCLIP('qwenimage')).resolves.toBe('qwen3vl_8b_int8_convrot.safetensors')
+ })
+})
+
+describe('the two Model Manager bundles', () => {
+ const bundles = getImageBundles().filter((b) => b.tags.includes('Prompt Enhancer'))
+ const official = bundles.find((b) => b.name === 'Qwen-Image 2.1 Prompt Enhancer (Official)')
+ const free = bundles.find((b) => b.name === 'Qwen-Image 2.1 Prompt Enhancer (No Refusals)')
+
+ /** file name -> [repo path, SHA-256], as the Hugging Face API states them. */
+ const FILES: Record<string, [string, string]> = {
+ 'qwen3.5_9b_qwen_image_2.1_pe_t2i.int8_convrot.safetensors': [
+ 'Comfy-Org/Qwen-Image-2.1/resolve/main/text_encoders/', '9182abae56fe05459840a86d22abd21f972061c92fce032630af680c8c5178d3'],
+ 'qwen3.5_9b_qwen_image_2.1_pe_i2i.int8_convrot.safetensors': [
+ 'Comfy-Org/Qwen-Image-2.1/resolve/main/text_encoders/', '32707d01b427e488af252b95c551989aad59f9fec611a694f5db6bde7f0f1f6c'],
+ 'qwen3.5_9b_qwen_image_2.1_pe_t2i_heretic.int8_convrot.safetensors': [
+ 'Adahm/PE-Heretic-INT8-ConvRot-for-Qwen-Image-2.1/resolve/main/', '91b9ba42539fb662775181eabce845befe2c1441658a736fadf0033dd799d8f3'],
+ 'qwen3.5_9b_qwen_image_2.1_pe_i2i_heretic.int8_convrot.safetensors': [
+ 'Adahm/PE-Heretic-INT8-ConvRot-for-Qwen-Image-2.1/resolve/main/', '979b9063dd16645f0191c9ff55aa5059105bfe84096d96a817a85deed22231f0'],
+ }
+ const BYTES = 9_471_072_252
+
+ it('there are exactly two: the official one and the one without refusals', () => {
+ expect(bundles.map((b) => b.name)).toEqual([
+ 'Qwen-Image 2.1 Prompt Enhancer (Official)',
+ 'Qwen-Image 2.1 Prompt Enhancer (No Refusals)',
+ ])
+ expect(official!.uncensored).toBe(false)
+ expect(free!.uncensored).toBe(true)
+ })
+
+ it('each is one click for both tasks: a file for new pictures and one for edits', () => {
+ for (const b of bundles) {
+ expect(b.files.map((f) => qwenEnhancerFile(f.filename!)?.mode).sort(), b.name).toEqual(['i2i', 't2i'])
+ }
+ expect(official!.files.every((f) => qwenEnhancerFile(f.filename!)?.variant === 'official')).toBe(true)
+ expect(free!.files.every((f) => qwenEnhancerFile(f.filename!)?.variant === 'unfiltered')).toBe(true)
+ })
+
+ it('every file is complete: address, folder, exact size and SHA-256', () => {
+ const seen: string[] = []
+ for (const b of bundles) {
+ for (const f of b.files) {
+ const [path, sha256] = FILES[f.filename!]
+ expect(f.downloadUrl, f.filename).toBe(`https://huggingface.co/${path}${f.filename}`)
+ expect(f.subfolder, f.filename).toBe('text_encoders')
+ expect(f.sizeBytes, f.filename).toBe(BYTES)
+ expect(f.sha256, f.filename).toBe(sha256)
+ expect(f.sha256).toMatch(/^[0-9a-f]{64}$/)
+ // sizeGB is gibibytes: the install check multiplies it by 1_073_741_824.
+ expect(Math.abs(f.sizeGB! - BYTES / 1_073_741_824), f.filename).toBeLessThan(0.01)
+ seen.push(f.filename!)
+ }
+ expect(Math.abs(b.totalSizeGB - b.files.reduce((sum, f) => sum + f.sizeGB!, 0)), b.name).toBeLessThan(0.05)
+ }
+ expect(seen.sort()).toEqual(Object.keys(FILES).sort())
+ })
+
+ it('each carries a tier, a VRAM figure and the family it belongs to', () => {
+ for (const b of bundles) {
+ expect(b.tier, b.name).toBe('best')
+ expect(b.workflow, b.name).toBe('qwenimage')
+ expect(b.vramRequired, b.name).toBe('16 GB')
+ expect(b.tags, b.name).toContain('Addon')
+ expect(b.customNodes, b.name).toBeUndefined()
+ }
+ })
+
+ it('says what it does, where to switch it on, and the licence', () => {
+ for (const b of bundles) {
+ expect(b.description, b.name).toMatch(/Add-on for Qwen-Image 2\.1/)
+ expect(b.description, b.name).toMatch(/short prompt/)
+ expect(b.description, b.name).toMatch(/looks at your pictures when you edit/)
+ expect(b.description, b.name).toMatch(/runs before the image model and makes room for it/)
+ expect(b.description, b.name).toMatch(/Improve my prompt in the advanced settings/)
+ expect(b.description, b.name).toContain('Qwen Research License, non-commercial use: https://huggingface.co/')
+ }
+ })
+
+ it('the official one says it can soften an instruction, the other that it does not', () => {
+ expect(official!.description).toMatch(/can soften or refuse an instruction/)
+ expect(free!.description).toMatch(/refusals taken out/)
+ expect(free!.description).toMatch(/stay what you wrote/)
+ })
+
+ it('they stand after the model itself, so the family still finds its model first', () => {
+ const all = getImageBundles()
+ const first = all.find((b) => b.workflow === 'qwenimage')!
+ expect(first.name).toBe('Qwen-Image 2.1 (Generate and Edit)')
+ const at = (name: string) => all.findIndex((b) => b.name === name)
+ expect(at(official!.name)).toBeGreaterThan(at(first.name))
+ expect(at(free!.name)).toBeGreaterThan(at(first.name))
+ expect(all[0].tags).not.toContain('Prompt Enhancer')
+ })
+})
diff --git a/src/api/__tests__/qwen-image-21-workflow.test.ts b/src/api/__tests__/qwen-image-21-workflow.test.ts
index 766fbdcd..51aa4693 100644
--- a/src/api/__tests__/qwen-image-21-workflow.test.ts
+++ b/src/api/__tests__/qwen-image-21-workflow.test.ts
@@ -374,7 +374,10 @@ describe('Qwen-Image 2.1 bundle', () => {
const bundle = getImageBundles().find(b => b.workflow === 'qwenimage')
it('exists exactly once', () => {
- expect(getImageBundles().filter(b => b.workflow === 'qwenimage')).toHaveLength(1)
+ // The two prompt enhancer add-ons share the family and carry no model file.
+ const withModel = getImageBundles().filter(b => b.workflow === 'qwenimage' && b.files.some(f => f.subfolder === 'diffusion_models'))
+ expect(withModel).toHaveLength(1)
+ expect(withModel[0].name).toBe(bundle!.name)
expect(bundle).toBeDefined()
})
diff --git a/src/api/comfyui.ts b/src/api/comfyui.ts
index e60c524d..932d2fd2 100644
--- a/src/api/comfyui.ts
+++ b/src/api/comfyui.ts
@@ -17,6 +17,7 @@ import { isRecord, asString, asRecordArray } from '../types/json-guards'
// Bundle-Daten gehören weder hierher noch nach discover.ts — sie liegen
// jetzt in model-bundles.ts, das beide Seiten statisch lesen.
import { getImageBundles, getVideoBundles } from './model-bundles'
+import { isQwenEnhancerFile } from '../lib/render/qwen-enhancer'
import { COMPONENT_REGISTRY, type ComponentSpec } from './component-registry'
// ─── Control-plane fetch timeouts ───
@@ -1818,7 +1819,11 @@ export async function findMiniMaxAudioVAE(): Promise<string> {
* want.
*/
export async function findMatchingCLIP(modelType: ModelType, activeModelName?: string): Promise<string> {
- const clips = await getCLIPModels()
+ // The Qwen-Image 2.1 prompt enhancers sit in the same folder and carry
+ // "qwen" in their names, but they are text models, not encoders. Without
+ // this they answer the loose "qwen" searches below (HunyuanVideo, FramePack,
+ // FLUX 2) before the real encoder does.
+ const clips = (await getCLIPModels()).filter((c) => !isQwenEnhancerFile(c))
if (clips.length === 0) throw nothingInstalled('text encoder', [COMPONENT_REGISTRY[modelType]?.clip])
const lower = (s: string) => s.toLowerCase()
const modelLc = activeModelName ? lower(activeModelName) : ''
diff --git a/src/api/model-bundles.ts b/src/api/model-bundles.ts
index fb1691b6..711f8723 100644
--- a/src/api/model-bundles.ts
+++ b/src/api/model-bundles.ts
@@ -393,6 +393,81 @@ export function getImageBundles(): ModelBundle[] {
},
],
},
+ // The Qwen-Image 2.1 prompt enhancers (GH #148). Add-ons to the bundle
+ // above, not models of their own: a 9B text model that turns a short
+ // prompt or edit instruction into the long prompt Qwen-Image 2.1 works
+ // best with. One file writes prompts for new pictures (t2i), the other
+ // rewrites edit instructions and reads the pictures (i2i). ComfyUI runs
+ // them with its own TextGenerate node, no node pack; "Improve my prompt"
+ // uses them when they are installed (api/qwen-enhancer.ts), and that needs
+ // ComfyUI 0.37.2 or newer. Byte counts and SHA-256 are the Hugging Face
+ // LFS values read on 2026-10-03; all four addresses answer without a
+ // token. sizeGB is gibibytes, as everywhere in this file. The VRAM figure
+ // is the one the enhancer's node pack author measured for running it
+ // inside ComfyUI ("16 GB recommended"). The tier is the family's, as for
+ // every add-on (local-model-tier.test.ts).
+ {
+ name: 'Qwen-Image 2.1 Prompt Enhancer (Official)',
+ description: 'Add-on for Qwen-Image 2.1. Turns a short prompt or edit instruction into the long, detailed prompt the model works best with, and looks at your pictures when you edit. It runs before the image model and makes room for it afterwards. Made to play it safe: it can soften or refuse an instruction. Turn it on with Improve my prompt in the advanced settings. Qwen Research License, non-commercial use: https://huggingface.co/Qwen/Qwen-Image-2.1-PE-T2I/blob/main/LICENSE',
+ tags: ['Qwen Image 2.1', 'Prompt Enhancer', 'Addon'],
+ uncensored: false,
+ totalSizeGB: 17.64,
+ vramRequired: '16 GB',
+ workflow: 'qwenimage',
+ tier: 'best',
+ url: 'https://huggingface.co/Comfy-Org/Qwen-Image-2.1',
+ files: [
+ {
+ name: 'Qwen Prompt Enhancer, Image (INT8)',
+ description: 'Writes the prompt for a new picture.',
+ pulls: '', tags: ['Prompt Enhancer', '9.47 GB'], updated: 'New',
+ downloadUrl: 'https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/text_encoders/qwen3.5_9b_qwen_image_2.1_pe_t2i.int8_convrot.safetensors',
+ filename: 'qwen3.5_9b_qwen_image_2.1_pe_t2i.int8_convrot.safetensors', subfolder: 'text_encoders', sizeGB: 8.82,
+ sizeBytes: 9471072252,
+ sha256: '9182abae56fe05459840a86d22abd21f972061c92fce032630af680c8c5178d3',
+ },
+ {
+ name: 'Qwen Prompt Enhancer, Edit (INT8)',
+ description: 'Rewrites an edit instruction and reads your pictures.',
+ pulls: '', tags: ['Prompt Enhancer', '9.47 GB'], updated: 'New',
+ downloadUrl: 'https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/text_encoders/qwen3.5_9b_qwen_image_2.1_pe_i2i.int8_convrot.safetensors',
+ filename: 'qwen3.5_9b_qwen_image_2.1_pe_i2i.int8_convrot.safetensors', subfolder: 'text_encoders', sizeGB: 8.82,
+ sizeBytes: 9471072252,
+ sha256: '32707d01b427e488af252b95c551989aad59f9fec611a694f5db6bde7f0f1f6c',
+ },
+ ],
+ },
+ {
+ name: 'Qwen-Image 2.1 Prompt Enhancer (No Refusals)',
+ description: 'Add-on for Qwen-Image 2.1. The same prompt enhancer with its refusals taken out by the community (Heretic), so your prompt and your edit instruction stay what you wrote. Turns a short prompt into a long, detailed one and looks at your pictures when you edit. It runs before the image model and makes room for it afterwards. Turn it on with Improve my prompt in the advanced settings. Qwen Research License, non-commercial use: https://huggingface.co/Adahm/PE-Heretic-INT8-ConvRot-for-Qwen-Image-2.1/blob/main/LICENSE',
+ tags: ['Qwen Image 2.1', 'Prompt Enhancer', 'Addon'],
+ uncensored: true,
+ totalSizeGB: 17.64,
+ vramRequired: '16 GB',
+ workflow: 'qwenimage',
+ tier: 'best',
+ url: 'https://huggingface.co/Adahm/PE-Heretic-INT8-ConvRot-for-Qwen-Image-2.1',
+ files: [
+ {
+ name: 'Qwen Prompt Enhancer, Image, No Refusals (INT8)',
+ description: 'Writes the prompt for a new picture. From pottokao/Qwen-Image-2.1-PE-T2I-Heretic.',
+ pulls: '', tags: ['Prompt Enhancer', '9.47 GB'], updated: 'New',
+ downloadUrl: 'https://huggingface.co/Adahm/PE-Heretic-INT8-ConvRot-for-Qwen-Image-2.1/resolve/main/qwen3.5_9b_qwen_image_2.1_pe_t2i_heretic.int8_convrot.safetensors',
+ filename: 'qwen3.5_9b_qwen_image_2.1_pe_t2i_heretic.int8_convrot.safetensors', subfolder: 'text_encoders', sizeGB: 8.82,
+ sizeBytes: 9471072252,
+ sha256: '91b9ba42539fb662775181eabce845befe2c1441658a736fadf0033dd799d8f3',
+ },
+ {
+ name: 'Qwen Prompt Enhancer, Edit, No Refusals (INT8)',
+ description: 'Rewrites an edit instruction and reads your pictures. From darrellbest/Qwen-Image-2.1-PE-I2I-Heretic.',
+ pulls: '', tags: ['Prompt Enhancer', '9.47 GB'], updated: 'New',
+ downloadUrl: 'https://huggingface.co/Adahm/PE-Heretic-INT8-ConvRot-for-Qwen-Image-2.1/resolve/main/qwen3.5_9b_qwen_image_2.1_pe_i2i_heretic.int8_convrot.safetensors',
+ filename: 'qwen3.5_9b_qwen_image_2.1_pe_i2i_heretic.int8_convrot.safetensors', subfolder: 'text_encoders', sizeGB: 8.82,
+ sizeBytes: 9471072252,
+ sha256: '979b9063dd16645f0191c9ff55aa5059105bfe84096d96a817a85deed22231f0',
+ },
+ ],
+ },
{
name: 'DreamShaper XL Turbo V2 (Anime/Stylized)',
description: 'Fast anime and stylized art. Turbo mode for 4 step generation. Great for creative work.',
diff --git a/src/api/qwen-enhancer-prompts.ts b/src/api/qwen-enhancer-prompts.ts
new file mode 100644
index 00000000..948c868f
--- /dev/null
+++ b/src/api/qwen-enhancer-prompts.ts
@@ -0,0 +1,18 @@
+// The two system prompts the Qwen-Image 2.1 prompt enhancer is run with.
+//
+// Copied character for character from the official Comfy-Org templates
+// (Comfy-Org/workflow_templates, MIT, commit 9fae1041be of 2026-09-30):
+// templates/image_qwen_image_2_1_t2i.json subgraph node 475
+// templates/image_qwen_image_2_1_image_edit.json subgraph node 479
+// Both come from Qwen's own system prompts (system_prompt.txt in
+// Qwen/Qwen-Image-2.1-PE-T2I and -PE-I2I). Comfy-Org changed the answer format
+// from a JSON object to one plain paragraph, so the answer is the prompt, and
+// ships a shorter edition of the edit text (10.7 KB instead of 18.3 KB).
+//
+// Every character outside ASCII is written as a \u escape. The text is not
+// ours to reword, and this way the file carries no literal dash.
+// qwen-enhancer-prompts.test.ts pins both texts by length and SHA-256.
+
+export const QWEN_PE_T2I_SYSTEM_PROMPT = "# Image Prompt Rewriting Expert\n\nYou turn a user's image request into one long English paragraph that describes the\nfinished image as if you were looking at it, plus the aspect ratio it should be\nrendered at. You are not talking to the user and not talking to a renderer: you are\nan observer reporting what is in the frame.\n\nWork through the eight steps below in order. Each step commits one decision; later\nsteps never revise an earlier one.\n\n## Step 1 \u2014 Read the brief and split it in two\n\nList what the user has fixed and what they have left open.\n\nFixed, and it must survive into your description unchanged: every string of text\nthey want shown, every named object, every count, every stated colour, every stated\nposition, and the aspect ratio if they gave one. Copy their text strings character\nfor character, in their own script, including punctuation and spacing.\n\nA third thing they may give you is an instruction about the job rather than about the\npicture \u2014 \"use double quotes\", \"no hard-edged blocks\", \"4K, no noise\", \"make sure the\ntext is sharp\". That is not content. Obey it silently where it applies and never echo\nit: the description states what is in the frame, never what must be done.\n\nOpen, and you must decide it: everything they did not mention. A three-word request\nand a three-hundred-word request both become a description of the same size, so a\nshort brief means you are inventing most of the frame, not writing less.\n\n## Step 2 \u2014 Fix the frame\n\nDecide the orientation from the subject, then pick the ratio.\n\nIf the user states a ratio, use it. Otherwise: `3:2` for anything horizontal and\n`2:3` for anything vertical \u2014 these are the two defaults and cover most images.\nUse `1:1` for a square badge, icon, album cover or single centred emblem, `16:9`\nfor a wide cinematic or presentation frame, `1:2` or `9:16` for a phone screen or a\ntall standing banner. `3:4`, `2:1`, `21:9`, `4:3`, `9:21`, `4:5`, `3:1`, `5:4`,\n`1:3` exist but only when the subject or the user really calls for them.\n\nThe ratio lives only in the `wh_ratio` field. Never write a ratio, a resolution, or\na pixel count into the description itself.\n\n## Step 3 \u2014 Write the opening sentence\n\nOne sentence, around twenty words. Name the medium, the style, the subject, and the\nbackground or palette; usually name the orientation too:\n\n`The image is a \u27e8vertical / wide / square / tall\u27e9 \u27e8style\u27e9 \u27e8photograph \u00b7 poster \u00b7 illustration \u00b7 scene \u00b7 portrait \u00b7 infographic \u00b7 close-up \u00b7 graphic \u00b7 page \u00b7 card \u00b7 sheet \u00b7 logo\u27e9 of \u27e8subject\u27e9, \u27e8the background and its palette\u27e9.`\n\n`This is a \u2026` or a bare `A vertical realistic photograph of \u2026` work equally well. The\nmedium noun is the one part that is never omitted.\n\nThe style word goes here \u2014 realistic, photorealistic, minimalist, flat-vector,\ncinematic, watercolour, isometric, editorial, hand-drawn, 3D-rendered, retro. Name\nit once here; you may echo it in the closing sentence.\n\n## Step 4 \u2014 Inventory before you write\n\nBefore any more prose, settle two lists.\n\nEvery element that will appear, each with a place in the frame: upper-left,\nacross the top, on the far right, in the lower-third, in the centre, in front of,\nbehind, tucked into the corner. You will need eight to fourteen such positional\nphrases, about ten typically, and they must reach the corners, the edges and the\ncentre \u2014 not cluster in the middle.\n\nEvery piece of text that will be legible in the image, in reading order.\n\n## Step 5 \u2014 Walk the frame\n\nNow describe it in order. Which order depends on how the frame is filled.\n\n**If the frame is divided into regions** \u2014 a poster, a page, an interface, a layout, a\nwide scene with several things in it \u2014 walk the regions:\n\n1. The background and the surface it sits on \u2014 this comes immediately after the\n opening sentence, not at the end.\n2. The top band: headline, header bar, sky, ceiling, whatever occupies the top edge.\n3. Down and across the body of the frame: left side, then centre, then right side.\n Give each region one or two sentences.\n4. The bottom band: footer, foreground, ground plane, base row.\n\n**If one subject fills the frame** \u2014 a portrait, a close-up, a single object \u2014 walk\nthe subject instead: the background and how far it falls off, then the subject's pose\nand where it is placed in the frame, then head and face, then body and each garment or\nsurface, then what is held or touching it, then whatever little is left at the edges.\nKeep using positional phrases inside the subject \u2014 in the upper-left of the frame,\nbehind the left shoulder, along the lower edge \u2014 so the frame stays locatable.\n\nRoughly a third of your sentences should open on the positional phrase itself \u2014\n\"On the right side of the frame, \u2026\", \"In the upper-left corner, \u2026\", \"Across the\nlower third, \u2026\" \u2014 so the reader always knows where they are looking.\n\nKeep it to one paragraph. Break to a new paragraph only when the image is genuinely\nbuilt from stacked regions \u2014 panels, cards, sections, slides \u2014 and then one\nparagraph per region, each opening on where that region sits.\n\n## Step 6 \u2014 Set every piece of text\n\nSkip this step if nothing in the image is meant to be read \u2014 a third of images have\nno legible text at all, and inventing signage for them is a mistake.\n\nOtherwise, for each string from your Step 4 list, in reading order, name where it sits,\nwhat it looks like, and what it says: `a bold black headline across the top reads \"\u2026\"`.\n\nPut the string in straight double quotes, in its own script \u2014 Chinese, Russian,\nKorean, Japanese and Arabic text stays in Chinese, Russian, Korean, Japanese and\nArabic. Give its weight, colour, case and relative size. Describe a line break as a\nsecond line rather than putting a real newline inside the string. If a mark is not meant\nto be read \u2014 distant signage, a label behind glass, dense body copy \u2014 call it\nblurred, indistinct, or too small to read rather than inventing letters. If the image contains a chart\nor a table, its axes, tick labels, legend entries, series and cell values are text\ntoo: write them out.\n\n## Step 7 \u2014 Give the lighting its own sentence\n\nEvery image has light in it, and the description always accounts for it: the source,\nits direction, its quality, and the shadows and highlights it leaves. Soft diffused\ndaylight from a window on the left, hard overhead studio light, warm low sun, flat\neven ambient light for a diagram.\n\nOnce the contents are placed, give it a sentence of its own \u2014 `The lighting is \u2026` \u2014\nor, if the light is what makes a particular surface look the way it does, fold it into\nthat surface's sentence. Either way it is stated explicitly, not left implied.\n\n## Step 8 \u2014 Close with the whole frame\n\nEnd on a single sentence that steps back:\n\n`The overall composition \u27e8is / uses / feels\u27e9 \u2026`\n\n`The composition is \u2026`, `The overall design \u2026`, `The overall mood \u2026`, `The overall\npalette \u2026` and `The image has \u2026` are the same move. Cover balance and symmetry, the\npalette, the style, and the mood in that one sentence. Write exactly one such\nsentence \u2014 do not follow it with a second summary.\n\n## Throughout\n\n**Size.** The description runs about twenty sentences and four to five hundred words,\nroughly twenty-five words a sentence. That is the same size whether the brief was three\nwords or three hundred: a dense frame with many regions and a lot of text runs longer, a\nsingle quiet subject runs shorter, but a thin brief never buys a thin description.\n\n**Observe, don't instruct.** Present tense, third person, declarative. No \"you\", no\n\"create\", no \"make sure\", no \"the AI should\". No quality boosters \u2014 no \"masterpiece\",\n\"8K\", \"highly detailed\", \"award-winning\".\n\n**Hedge what you cannot be certain of.** An observer describing a picture says\n\"appears to be\", \"likely\", \"suggesting\", and offers a pair \u2014 \"a notebook\nor a tablet\", \"wood or dark laminate\" \u2014 when the thing is genuinely ambiguous. Do\nthis often; it is the natural register here. Be flatly definite only about what the\nuser fixed.\n\n**Name colours with a modifier, almost never bare.** Deep navy, muted olive, pale\ncream, warm terracotta, soft dusty rose, blue-grey, off-white, charcoal, brownish-\ngreen. Hex codes only if the user gave them.\n\n**Give the material, not just the noun.** Brushed metal, matte plastic, glossy\nceramic, coarse linen, weathered wood, frosted glass, grain, scuffs, condensation,\nvisible brush strokes, paper fibre.\n\n**Enumerate; never summarise.** \"Several items\" and \"various decorations\" are not\ndescriptions. Say what each thing is. Write small counts as words \u2014 three, five,\ntwelve \u2014 and if something is partly hidden, say so and describe the visible part.\n\n**People get their observable surface.** Build, posture, where they are looking,\nexpression, hair, skin tone, and each garment with its colour and material. Age is a\nlife stage or a decade \u2014 a child, a teenager, a young adult, middle-aged, elderly,\nin her thirties \u2014 never a number of years. If a face is turned away or cropped, say\nthat instead of describing it.\n\n**Objects by class, not by brand.** A silver laptop, a mirrorless camera, a compact\nhatchback \u2014 unless the user named the brand. Photographic and design vocabulary is\nwelcome: shallow depth of field, bokeh, backlit, close-up, negative space,\ngrid, drop shadow.\n\n**Everything holds together physically.** Shadows fall away from the light, reflections\nmatch what is in front of the surface, scale is consistent between neighbouring\nobjects, and a surface reacts to what sits on it. If the user asked for something\nimpossible, describe it as the image shows it and let the rest of the scene stay\ncoherent around it.\n\n## Language\n\nThe description is always in English, whatever language the request arrives in. The\nonly exception is text shown inside the image, which stays in its own script.\n\n## Output format\n\n- Return the description and nothing else: one continuous paragraph of English, in a single line\nstarting on the very first character of your reply.\n- No JSON, no braces, no key names, no labels, no headings, no markdown, no code fences, and no quotation marks around the paragraph.\n- No preamble, no acknowledgement, no explanation, no summary, no notes, no closing remarks, no questions.\n- No ratio, no resolution, no pixel count, no timestamps.\n\nYour whole reply is used as the image prompt, so every extra word you add becomes part of the image.\n"
+
+export const QWEN_PE_I2I_SYSTEM_PROMPT = "# Edit Prompt Enhancer \u2014 General (v2, \u7cbe\u7b80\u7248)\n\n**FIRST \u2014 there are TWO separate language decisions. Do NOT conflate them.**\n\n**(A) Language of the rewritten prompt's DESCRIPTIVE prose \u2014 every word OUTSIDE double quotes (the description you write for the diffusion model, NOT the text painted into the image). This decision is final and non-negotiable:**\n- User instruction is in Chinese \u2192 write the description in Chinese.\n- User instruction is in English \u2192 write the description in English.\n- User instruction is in ANY other language (Japanese, Korean, French, Spanish, Thai, etc.) \u2192 write the description in English.\n\n**(B) Language of the TEXT THAT WILL BE RENDERED INTO THE OUTPUT IMAGE \u2014 the content INSIDE double quotes. Decide it in this strict priority order:**\n1. If the user's instruction gives the exact text to write, OR names a target language for the text (e.g. \"\u6539\u6210'\u590f\u65e5\u7279\u60e0'\", \"\u628a\u6807\u9898\u5199\u6210\u82f1\u6587\", \"add a Japanese title\", \"write the caption in Thai\") \u2192 render exactly that text / in exactly that specified language.\n2. Otherwise, if the input image already contains text \u2192 render in the DOMINANT language of the image's existing text \u2014 even when the instruction is written in a different language.\n3. Otherwise (the image contains no text AND the instruction names no target language) \u2192 render in the language of the user's instruction itself \u2014 including Japanese, Korean, Thai, Arabic, French, etc. Do NOT force it to English.\nWorked example: image is mostly Thai, instruction is in English asking to add/redesign a title without giving the exact words or a language \u2192 the rendered (quoted) text must be **Thai** (the image's dominant language), while the surrounding description (A) is still written in English.\n\nTwo reinforcements on decision (B): all rendered (quoted) text must be **monolingual** \u2014 do not mix Chinese and English inside the quotes and do not emit a bilingual pair unless the user explicitly asks for one. And **genre never overrides input language**: a \"spec sheet / cinematic data-document / storyboard / technical parameter\" look is achieved through layout and typography, NOT by switching rendered labels to English \u2014 every header, label, and caption stays in the decided language (standardized units and user-given proper nouns may remain Latin).\n\nYou are an expert at clarifying image editing instructions. Given a user's vague or ambiguous edit instruction and the input image(s), rewrite it into a precise, unambiguous, actionable editing directive. An input image is ALWAYS present \u2014 this is always an image-editing task, never text-to-image from nothing.\n\n## Core Objective\n\nRewrite the instruction so a downstream image-editing model can execute it without guessing \u2014 anchored on what the input image(s) actually show, faithful to the user's intent, inventing nothing.\n\n**How much you build is intent-branched.** When the user wants *this picture changed* (a local object/attribute/background edit, a text or UI edit, a quality or style change, a viewpoint/canvas transform), clarify and constrain: say exactly what changes, and let everything else stand. When the user wants *a new picture of this subject* (placing a subject in a new scene, compositing across images, a photo-shoot or poster or infographic built from a reference), construct actively: design the scene, lighting, composition and layout to a professional standard. Scale the elaboration to what was asked \u2014 a plain placement stays restrained, a styled shoot or a publication-grade poster is built out fully.\n\n## The Governing Principle \u2014 Attribute Disentanglement at Full Strength\n\n**Edit exactly the attribute(s) the user named, push each to a strong and unmistakable degree, and hold everything else at input fidelity.**\n\nBoth halves matter, and the two failure modes are symmetric:\n\n- **Leakage** \u2014 touching what the user did not name (a sharpen that re-grades color, an upscale that reframes, a style change that drifts a face, an outfit swap that drops an accessory, a background change that \"helpfully\" cleans up something unmentioned).\n- **Under-editing** \u2014 an output a viewer could mistake for the unedited input, because the requested change was applied faintly.\n\nPreservation locks **content, never edit strength**. Recognizability is bought by naming what stays fixed, not by holding the effect back.\n\n## What to Anchor, What to Decide\n\n**Anchor on the image.** Every spatial, tonal and contextual claim comes from what is visibly there. If you are unsure a detail exists, leave it out \u2014 a preserved element described at a higher level of abstraction is always safer than an invented specific.\n\n**Say what stays, without repainting it.** Name the untargeted content by type, position and role rather than describing its appearance, and prefer one blanket preservation clause over walking the frame. A preservation description reads to the model as a generation instruction: the more concretely you describe something you meant to keep, the more likely it drifts. Describe appearance concretely only for what you are actually changing, or when it is the only way to disambiguate between similar objects.\n\n**Identity is the hardest invariant.** A person's facial identity and the personal accessories that make them recognizable; a product's exact design, markings and count; and the input's rendering medium (photograph, anime, illustration, sketch, 3D render, painting) all survive every edit unless the user explicitly targets them. When identity comes from a reference image, point at that image rather than describing features in words \u2014 verbal descriptions make the model regenerate and degrade the likeness.\n\n**Resolve ambiguity, then commit.** Turn vague intent, imprecise spatial reference and unparameterized style words into something concrete and observable. Translate abstract quality language into the visual properties it implies. Where the instruction offers alternatives or contradicts itself, pick the most reasonable reading and state it as a decision. Keep the user's own action verb, spatial relations and described state intact, and treat anything they asked to preserve as absolute. Preserve creative or physically impossible intent rather than correcting it.\n\n**Only what was asked.** Do not add operations the user did not request, and do not clean up unmentioned defects, overlays or clutter however prominent they look. When an edit removes, moves or reveals something, say enough about the newly exposed region that the result stays physically coherent.\n\n**Text in the image is literal.** Whenever readable text will appear in the output, commit to the exact characters \u2014 every element, quoted, nothing summarized or abbreviated away. Text you cannot commit to should not be added at all. Match the typography and language the input establishes unless the user asks otherwise. When the operation extends the canvas outward, name it as outpainting explicitly.\n\n**Write it as an instruction.** Lead with the operation, not a description of the finished picture, and write from the perspective of someone holding only the input image(s).\n\n## Thinking Process\n\nBefore emitting the final prompt, reason through: what the image(s) actually contain (including a complete reading of any text present); what the user is asking for and which attributes that names; what must therefore stay fixed; and finally the composed directive. Close with a check that every visible element is either the target of the edit or covered by what stays fixed, that the requested change is unmistakable, that nothing outside the target was touched, and that every quoted string obeys language decision (B).\n\n## Image Reference Rules\n\nFor Multi-Image Input (N >= 2), the rewritten instruction MUST use `<image1>`, `<image2>`, ... to refer to each input image. Do not use natural language references like \"\u56fe1\", \"\u7b2c\u4e00\u5f20\u56fe\", \"the first image\", or \"image A\". This tagging format is mandatory and non-negotiable. For single-image input (N = 1), do NOT use tags \u2014 refer to the image naturally (\"\u56fe\u50cf\", \"\u56fe\u7247\u4e2d\", \"the image\").\n\nState each image's role explicitly \u2014 which one is the canvas whose composition and untargeted content survive, and which supply material to transfer \u2014 and say what is taken from each. For scene generation with no canvas (\u5408\u5f71/\u5408\u7167 and the like), all images serve as identity sources. Describe every referenced image individually; never compress several into a range or a group to avoid describing them one by one.\n\n## Output Format\nOutput ONLY the rewritten editing instruction itself: one single continuous paragraph of plain text.\n\nFormatting rules:\n- The entire rewritten prompt must be a single continuous paragraph with NO line breaks or newline characters.\n- The response must contain nothing except the instruction itself: no object or array wrapper, no field names or key-value pairs, no headings, labels, or prefaces, no greetings, explanations, or commentary, no markdown, and no code fences. Begin with the first word of the instruction and end with its last word.\n- Do not wrap the whole instruction in quotes: double quotes are reserved for text that will be RENDERED in the image (next rule).\n- All text that should appear as visible, readable content in the output image must be enclosed in double quotes (\"\"). Descriptive or structural language that does not appear as rendered text should NOT be quoted.\n- **Never include any resolution or aspect ratio information** (e.g., \"2:3\", \"16:9\", \"1920x1080\", \"2K\", \"4K\"). Output size is decided downstream, not by you.\n- Write it out in full \u2014 no ellipsis, no truncation.\n- State requirements affirmatively (\"\u4fdd\u6301\u80cc\u666f\u4e0e\u8f93\u5165\u56fe\u5b8c\u5168\u4e00\u81f4\") rather than as prohibitions (\"\u7981\u6b62\u6539\u53d8\u80cc\u666f\"). Standard preservation phrasing \"\u4fdd\u6301/\u4fdd\u7559[X]\u4e0d\u53d8\" is fine.\n- Be precise and decisive: no hedging, no unresolved alternatives, no vague degree words left unresolved.\n- The descriptive prose (outside double quotes) follows language decision (A); the text rendered inside the image (inside double quotes) follows language decision (B). Retain proper nouns and domain-specific terms in their original language, placed in English double quotes.\n- **Language-purge self-check (do this last)**: re-scan every double-quoted string \u2014 the text that will be RENDERED in the image \u2014 and enforce language decision (B). No quoted string may mix Chinese and English, form a bilingual pair, or carry a parenthetical translation gloss unless the user explicitly asked. Standardized units and user-given proper nouns may remain Latin.\n\nThe user's edit instruction to rewrite is:"
diff --git a/src/api/qwen-enhancer.ts b/src/api/qwen-enhancer.ts
new file mode 100644
index 00000000..eed97a9f
--- /dev/null
+++ b/src/api/qwen-enhancer.ts
@@ -0,0 +1,198 @@
+// The Qwen-Image 2.1 prompt enhancer: the graph and the run (GH #148).
+//
+// The enhancer is a 9B text model that ComfyUI runs with its own core nodes,
+// no node pack needed. The graph is the enhancer half of the two official
+// Comfy-Org templates (image_qwen_image_2_1_t2i.json and
+// image_qwen_image_2_1_image_edit.json, read 2026-10-03):
+//
+// CLIPLoader (the enhancer file) -> TextGenerate <- PrimitiveStringMultiline
+// LoadImage(s) -> BatchImagesNode -^ (the system prompt)
+// TextGenerate -> PreviewAny
+//
+// It runs as its own short ComfyUI job BEFORE the picture, not inside the
+// picture's graph, for three reasons: the rewritten prompt can be read, checked
+// and shown before anything is rendered, a failed rewrite falls back to the
+// user's own prompt instead of failing the picture, and the enhancer is out of
+// the card's memory before the image model loads (freeMemory below).
+
+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 { WorkflowUnavailableError } from './dynamic-workflow'
+import { enhancedOutcome, 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'
+
+/** The sentence an older ComfyUI gets. TextGenerate takes a system prompt
+ * since ComfyUI 0.37.2 (comfy_extras/nodes_textgen.py, read off the tags
+ * 0.37.1 and 0.37.2 on 2026-10-03); without that input the enhancer would run
+ * on the wrong instructions. "Update ComfyUI" is what Create keys the one
+ * click update on. */
+export const QWEN_ENHANCER_NEEDS_UPDATE = 'The Qwen prompt enhancer needs ComfyUI 0.37.2 or newer. Update ComfyUI in Settings.'
+
+/** Room for the reasoning plus the rewritten prompt, the value of the official
+ * templates. Qwen's own 16256 and 24000 can run for many minutes. */
+export 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
+
+const POLL_MS = 1500
+
+/** The node whose text is the answer. */
+export const QWEN_ENHANCER_OUTPUT_NODE = '9'
+
+export interface QwenEnhancerRequest {
+ /** The enhancer file as ComfyUI lists it. */
+ file: string
+ mode: QwenEnhancerMode
+ prompt: string
+ /** Edit only: the source first, then the references, as ComfyUI input names.
+ * The order is the order the picture's own graph numbers them in. */
+ images?: string[]
+ seed: number
+}
+
+/** Sampling as the official templates set it, which follow Qwen's release:
+ * temperature 1.0, top_p 0.95, top_k 20, min_p 0, repetition_penalty 1.0, and
+ * presence_penalty 1.5 for a new picture, 0 for an edit. The dotted names are
+ * how ComfyUI spells the fields of a DynamicCombo in the API format. */
+function sampling(mode: QwenEnhancerMode, seed: number): ComfyNodeInputs {
+ return {
+ sampling_mode: 'on',
+ 'sampling_mode.temperature': 1,
+ 'sampling_mode.top_k': 20,
+ 'sampling_mode.top_p': 0.95,
+ 'sampling_mode.min_p': 0,
+ 'sampling_mode.repetition_penalty': 1,
+ 'sampling_mode.seed': seed,
+ 'sampling_mode.presence_penalty': mode === 't2i' ? 1.5 : 0,
+ }
+}
+
+/** The enhancer graph. Pure: `nodes` is the set of node classes ComfyUI has,
+ * with their inputs. Throws the update sentence on a ComfyUI that cannot run it. */
+export function qwenEnhancerGraph(
+ req: QwenEnhancerRequest,
+ nodes: Record<string, { input?: { required?: Record<string, unknown>; optional?: Record<string, unknown> } }>,
+): ComfyApiGraph {
+ const images = req.mode === 'i2i' ? (req.images ?? []).filter(Boolean) : []
+ const textGenerate = nodes.TextGenerate
+ const takesSystemPrompt = !!textGenerate?.input?.optional && 'system_prompt' in textGenerate.input.optional
+ const ready = takesSystemPrompt && !!nodes.PrimitiveStringMultiline && !!nodes.PreviewAny
+ && (images.length < 2 || !!nodes.BatchImagesNode)
+ if (!ready) {
+ throw new WorkflowUnavailableError(QWEN_ENHANCER_NEEDS_UPDATE, 'unet_qwenimage', undefined, { needsComfyUpdate: true })
+ }
+
+ const graph: ComfyApiGraph = {
+ // ComfyUI recognizes the enhancer by its weights, the type only has to be
+ // one the loader knows. The edit template and the loader docs use this one.
+ '1': { class_type: 'CLIPLoader', inputs: { clip_name: req.file, type: 'qwen_image', device: 'default' } },
+ '2': {
+ class_type: 'PrimitiveStringMultiline',
+ inputs: { value: req.mode === 't2i' ? QWEN_PE_T2I_SYSTEM_PROMPT : QWEN_PE_I2I_SYSTEM_PROMPT },
+ },
+ }
+ const generate: ComfyNodeInputs = {
+ clip: ['1', 0],
+ prompt: req.prompt,
+ max_length: QWEN_ENHANCER_MAX_LENGTH,
+ ...sampling(req.mode, req.seed),
+ // The enhancer was trained to reason first and writes worse prompts without it.
+ thinking: true,
+ use_default_template: true,
+ mtp: 'auto',
+ system_prompt: ['2', 0],
+ }
+ if (images.length > 0) {
+ let n = 10
+ const loaded: Array<[string, number]> = images.map((image) => {
+ const id = String(n++)
+ graph[id] = { class_type: 'LoadImage', inputs: { image } }
+ return [id, 0]
+ })
+ if (loaded.length === 1) {
+ generate.image = loaded[0]
+ } else {
+ // Several pictures reach the enhancer as one batch, as in the template.
+ const batch: ComfyNodeInputs = {}
+ loaded.forEach((ref, i) => { batch[`images.image${i}`] = ref })
+ graph['3'] = { class_type: 'BatchImagesNode', inputs: batch }
+ generate.image = ['3', 0]
+ }
+ }
+ graph['4'] = { class_type: 'TextGenerate', inputs: generate }
+ graph[QWEN_ENHANCER_OUTPUT_NODE] = { class_type: 'PreviewAny', inputs: { source: ['4', 0] } }
+ return graph
+}
+
+/** The graph for this ComfyUI. */
+export async function buildQwenEnhancerWorkflow(req: QwenEnhancerRequest): Promise<ComfyApiGraph> {
+ return qwenEnhancerGraph(req, await getAllNodeInfo())
+}
+
+/** PreviewAny answers with `{ text: [value] }`. */
+function answerText(outputs: unknown): string | null {
+ const node = isRecord(outputs) ? outputs[QWEN_ENHANCER_OUTPUT_NODE] : undefined
+ const text = isRecord(node) ? node.text : undefined
+ const first: unknown = Array.isArray(text) ? text[0] : undefined
+ return typeof first === 'string' ? first : null
+}
+
+const wait = (ms: number, signal?: AbortSignal) => new Promise<void>((resolve) => {
+ const timer = setTimeout(done, ms)
+ function done() {
+ clearTimeout(timer)
+ signal?.removeEventListener('abort', done)
+ resolve()
+ }
+ signal?.addEventListener('abort', done)
+})
+
+/**
+ * Run the enhancer graph and read the rewritten prompt. Never throws: a
+ * rejected graph, a ComfyUI error, the time limit or Cancel all answer
+ * `failed`, and the run goes on with the user's own prompt (Cancel is the
+ * caller's to notice on its signal).
+ *
+ * Afterwards the enhancer is unloaded, whatever happened: it and Qwen-Image
+ * 2.1 run one after the other on the same card, and 9 GB of text model must
+ * not sit there while the encoder and the image model load.
+ */
+export async function runQwenEnhancer(
+ workflow: ComfyApiGraph,
+ original: string,
+ opts: { clientId?: string; signal?: AbortSignal; timeoutMs?: number } = {},
+): Promise<ImproveOutcome> {
+ const { signal } = opts
+ if (signal?.aborted) return { status: 'failed' }
+ let promptId: string | null = null
+ try {
+ promptId = await submitWorkflow(workflow, opts.clientId)
+ const deadline = Date.now() + (opts.timeoutMs ?? QWEN_ENHANCER_TIMEOUT_MS)
+ for (;;) {
+ if (signal?.aborted || Date.now() > deadline) break
+ const entry = await getHistory(promptId)
+ const status = entry?.status?.status_str
+ if (status === 'success') {
+ promptId = null
+ return enhancedOutcome(answerText(entry?.outputs), original)
+ }
+ if (status === 'error') {
+ promptId = null
+ return { status: 'failed' }
+ }
+ await wait(POLL_MS, signal)
+ }
+ return { status: 'failed' }
+ } catch {
+ return { status: 'failed' }
+ } finally {
+ // 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/components/create/experimental/ImproveToggle.tsx b/src/components/create/experimental/ImproveToggle.tsx
index 6a9be734..e0b06e39 100644
--- a/src/components/create/experimental/ImproveToggle.tsx
+++ b/src/components/create/experimental/ImproveToggle.tsx
@@ -2,21 +2,50 @@ import { Wand2 } from 'lucide-react'
import { useCreateStore } from '../../../stores/createStore'
import { improveKindForIntent } from '../../../lib/render/improve-prompt'
import { useImproveAvailability } from '../../../lib/render/improve-prompt-run'
+import { QWEN_ENHANCER_HINT, activeWriter, improveWriters } from '../../../lib/render/qwen-enhancer'
+import { isMlxImageHost } from '../../../api/mlx-image'
+import { classifyModel } from '../../../api/comfyui'
import { Tooltip } from '../ui/Tooltip'
import { cn } from '../ui/cn'
// "Improve my prompt": a switch in the advanced settings. It never sits in or
// above the prompt field. Off by default and remembered. Shown only on the
// tools that write a prompt for an image, a clip or a track.
+//
+// On a local Qwen-Image 2.1 with a prompt enhancer installed the enhancer
+// writes instead of the chat model, for a new picture and for an edit, and a
+// row under the switch lets the user pick who writes. Same switch, same place.
export function ImproveToggle() {
- const kind = improveKindForIntent(useCreateStore((s) => s.intent()))
+ const intent = useCreateStore((s) => s.intent())
+ const kind = improveKindForIntent(intent)
const on = useCreateStore((s) => s.improvePrompt)
const setOn = useCreateStore((s) => s.setImprovePrompt)
- const { available, hint } = useImproveAvailability()
- if (!kind) return null
+ const choice = useCreateStore((s) => s.improveWith)
+ const setChoice = useCreateStore((s) => s.setImproveWith)
+ const backend = useCreateStore((s) => s.backend)
+ const imageModel = useCreateStore((s) => s.imageModel)
+ const imageModelList = useCreateStore((s) => s.imageModelList)
+ const textEncoders = useCreateStore((s) => s.textEncoderList)
+ const chat = useImproveAvailability()
+
+ // The model the run really uses: the first of the list when the stored pick
+ // is not in it, the same rule the run applies.
+ const model = imageModelList.find((m) => m.name === imageModel) ?? imageModelList[0]
+ const situation = {
+ local: backend === 'local' && !isMlxImageHost(),
+ intent,
+ modelType: model ? model.type : classifyModel(imageModel),
+ textEncoders,
+ }
+ const writers = improveWriters(situation)
+ const writer = activeWriter(situation, choice)
+ const byEnhancer = writer !== null && writer !== 'chat'
+
+ if (!kind && !byEnhancer) return null
+ const { available, hint } = byEnhancer ? { available: true, hint: QWEN_ENHANCER_HINT } : chat
const active = on && available
return (
- <div className="py-3">
+ <div className="space-y-2 py-3">
<Tooltip content={hint} side="bottom" className="flex w-full">
<button
type="button"
@@ -38,6 +67,26 @@ export function ImproveToggle() {
<span className={cn('t-mono text-xs', active ? 'text-emerald-400' : 'text-gray-600')}>{active ? 'on' : 'off'}</span>
</button>
</Tooltip>
+ {on && writers.length > 1 && (
+ <div role="radiogroup" aria-label="Rewritten by" className="flex flex-wrap items-center gap-1.5">
+ <span className="w-full t-label text-gray-500">Rewritten by</span>
+ {writers.map((w) => (
+ <button
+ key={w.id}
+ type="button"
+ role="radio"
+ aria-checked={w.id === writer}
+ onClick={() => setChoice(w.id)}
+ className={cn(
+ 'rounded-md border px-2 py-1 t-control transition-colors',
+ w.id === writer ? 'border-white/20 bg-white/[0.07] text-gray-200' : 'border-white/[0.07] text-gray-500 hover:text-gray-300',
+ )}
+ >
+ {w.label}
+ </button>
+ ))}
+ </div>
+ )}
</div>
)
}
diff --git a/src/components/create/experimental/__tests__/qwen-enhancer-oberflaeche.test.tsx b/src/components/create/experimental/__tests__/qwen-enhancer-oberflaeche.test.tsx
new file mode 100644
index 00000000..ffc89c5a
--- /dev/null
+++ b/src/components/create/experimental/__tests__/qwen-enhancer-oberflaeche.test.tsx
@@ -0,0 +1,179 @@
+// @vitest-environment jsdom
+/**
+ * "Improve my prompt" with the Qwen-Image 2.1 prompt enhancer (GH #148): ONE
+ * switch in the advanced settings. With a local Qwen-Image 2.1 and an enhancer
+ * installed it also stands on Edit, a row under it picks who writes, and
+ * without an enhancer everything is as before: the chat model writes.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+
+vi.mock('../../../../api/mlx-image', () => ({ isMlxImageHost: () => false }))
+vi.mock('../../../../api/comfyui', () => ({
+ classifyModel: (name: string) => (name.includes('qwen_image_2.1') ? 'qwenimage' : 'sdxl'),
+ isI2VModel: () => false,
+ isT2VCapable: () => true,
+ isVideoModelType: () => false,
+}))
+vi.mock('../CreateContext', () => ({
+ useCreateExp: () => ({
+ samplerList: [], schedulerList: [], loraList: [], vaeList: [], refreshModelLists: vi.fn(),
+ }),
+}))
+vi.mock('../../../../api/providers', () => ({
+ getProviderIdFromModel: (m: string) => (m.startsWith('lu-cloud::') ? 'lu-cloud' : 'ollama'),
+ getProviderForModel: vi.fn(),
+}))
+
+import { AdvancedDrawer } from '../AdvancedDrawer'
+import { ImproveToggle } from '../ImproveToggle'
+import { useCreateStore } from '../../../../stores/createStore'
+import { useModelStore } from '../../../../stores/modelStore'
+
+const QWEN = 'qwen_image_2.1_int8_convrot.safetensors'
+const T2I = 'qwen3.5_9b_qwen_image_2.1_pe_t2i.int8_convrot.safetensors'
+const I2I = 'qwen3.5_9b_qwen_image_2.1_pe_i2i.int8_convrot.safetensors'
+const T2I_FREE = 'qwen3.5_9b_qwen_image_2.1_pe_t2i_heretic.int8_convrot.safetensors'
+const I2I_FREE = 'qwen3.5_9b_qwen_image_2.1_pe_i2i_heretic.int8_convrot.safetensors'
+
+const local = (textEncoders: string[], model: { name: string; type: string } = { name: QWEN, type: 'qwenimage' }) => {
+ useCreateStore.setState({
+ backend: 'local', isGenerating: false, improvePrompt: false, improveWith: 'auto', cloudStudioOptions: {},
+ imageModel: model.name, imageModelList: [model], textEncoderList: textEncoders,
+ } as never)
+}
+const theSwitch = () => screen.queryByRole('switch', { name: /improve my prompt/i })
+const writers = () => screen.queryAllByRole('radio').map((r) => `${r.textContent}${r.getAttribute('aria-checked') === 'true' ? '*' : ''}`)
+
+beforeEach(() => {
+ useModelStore.setState({ activeModel: 'qwen3:8b' })
+ local([T2I, I2I, T2I_FREE, I2I_FREE])
+})
+afterEach(() => { cleanup() })
+
+describe('one switch, also on Edit when the enhancer is there', () => {
+ it('Edit shows the switch on a local Qwen-Image 2.1 with an edit enhancer', () => {
+ useCreateStore.getState().setIntent('edit')
+ render(<ImproveToggle />)
+ expect(theSwitch()).toBeTruthy()
+ expect(screen.getAllByRole('switch')).toHaveLength(1)
+ })
+
+ it('Edit stays without it when no edit enhancer is installed, or on another model, or in the cloud', () => {
+ useCreateStore.getState().setIntent('edit')
+ local([T2I, T2I_FREE])
+ const a = render(<ImproveToggle />)
+ expect(theSwitch()).toBeNull()
+ a.unmount()
+ local([T2I, I2I], { name: 'flux2-klein.safetensors', type: 'flux2' })
+ const b = render(<ImproveToggle />)
+ expect(theSwitch()).toBeNull()
+ b.unmount()
+ local([T2I, I2I])
+ useCreateStore.setState({ backend: 'cloud' })
+ render(<ImproveToggle />)
+ expect(theSwitch()).toBeNull()
+ })
+
+ it('the enhancer needs no chat model: the switch works without one', async () => {
+ useModelStore.setState({ activeModel: null })
+ useCreateStore.getState().setIntent('image')
+ render(<ImproveToggle />)
+ const sw = theSwitch() as HTMLButtonElement
+ expect(sw.disabled).toBe(false)
+ fireEvent.click(sw)
+ expect(useCreateStore.getState().improvePrompt).toBe(true)
+ fireEvent.mouseEnter(sw.parentElement as HTMLElement)
+ await waitFor(() => expect(screen.getByRole('tooltip').textContent).toMatch(/Qwen prompt enhancer rewrites your prompt/i))
+ })
+})
+
+describe('who writes', () => {
+ it('off: no row. On: the installed enhancers and the chat model, the official one marked', () => {
+ useCreateStore.getState().setIntent('image')
+ render(<ImproveToggle />)
+ expect(screen.queryByRole('radiogroup')).toBeNull()
+ fireEvent.click(theSwitch()!)
+ expect(screen.getByRole('radiogroup', { name: 'Rewritten by' })).toBeTruthy()
+ expect(writers()).toEqual(['Qwen enhancer*', 'Qwen enhancer, no refusals', 'Chat model'])
+ })
+
+ it('a click picks the one without refusals and it is remembered in the store', () => {
+ useCreateStore.getState().setIntent('image')
+ useCreateStore.setState({ improvePrompt: true })
+ render(<ImproveToggle />)
+ fireEvent.click(screen.getByRole('radio', { name: 'Qwen enhancer, no refusals' }))
+ expect(useCreateStore.getState().improveWith).toBe('unfiltered')
+ expect(writers()).toEqual(['Qwen enhancer', 'Qwen enhancer, no refusals*', 'Chat model'])
+ })
+
+ it('picking the chat model brings the chat tooltip back', async () => {
+ useCreateStore.getState().setIntent('image')
+ useCreateStore.setState({ improvePrompt: true })
+ render(<ImproveToggle />)
+ fireEvent.click(screen.getByRole('radio', { name: 'Chat model' }))
+ expect(useCreateStore.getState().improveWith).toBe('chat')
+ fireEvent.mouseEnter(theSwitch()!.parentElement as HTMLElement)
+ await waitFor(() => expect(screen.getByRole('tooltip').textContent).toMatch(/your chat model rewrites your prompt/i))
+ })
+
+ it('Edit lists the enhancers only, a chat model cannot see the picture', () => {
+ useCreateStore.getState().setIntent('edit')
+ useCreateStore.setState({ improvePrompt: true, improveWith: 'chat' })
+ render(<ImproveToggle />)
+ expect(writers()).toEqual(['Qwen enhancer*', 'Qwen enhancer, no refusals'])
+ })
+
+ it('a single enhancer on Edit leaves nothing to choose: no row', () => {
+ local([I2I_FREE])
+ useCreateStore.getState().setIntent('edit')
+ useCreateStore.setState({ improvePrompt: true })
+ render(<ImproveToggle />)
+ expect(theSwitch()!.getAttribute('aria-checked')).toBe('true')
+ expect(screen.queryByRole('radiogroup')).toBeNull()
+ })
+})
+
+describe('without an enhancer everything is as before', () => {
+ it('no row, the chat model writes, and without a chat model the switch is locked', async () => {
+ local(['qwen3vl_8b_int8_convrot.safetensors'])
+ useCreateStore.getState().setIntent('image')
+ useCreateStore.setState({ improvePrompt: true })
+ const a = render(<ImproveToggle />)
+ expect(theSwitch()!.getAttribute('aria-checked')).toBe('true')
+ expect(screen.queryByRole('radiogroup')).toBeNull()
+ fireEvent.mouseEnter(theSwitch()!.parentElement as HTMLElement)
+ await waitFor(() => expect(screen.getByRole('tooltip').textContent).toMatch(/your chat model rewrites your prompt/i))
+ a.unmount()
+ useModelStore.setState({ activeModel: null })
+ render(<ImproveToggle />)
+ expect((theSwitch() as HTMLButtonElement).disabled).toBe(true)
+ })
+
+ it('another local model with the enhancers on disk: no row', () => {
+ local([T2I, I2I, T2I_FREE, I2I_FREE], { name: 'juggernaut.safetensors', type: 'sdxl' })
+ useCreateStore.getState().setIntent('image')
+ useCreateStore.setState({ improvePrompt: true })
+ render(<ImproveToggle />)
+ expect(theSwitch()).toBeTruthy()
+ expect(screen.queryByRole('radiogroup')).toBeNull()
+ })
+})
+
+describe('where it stands', () => {
+ it('switch and row are in the advanced settings drawer, on Edit too', () => {
+ useCreateStore.getState().setIntent('edit')
+ useCreateStore.setState({ improvePrompt: true })
+ render(<AdvancedDrawer open onClose={() => {}} />)
+ expect(screen.getByText('Improve my prompt')).toBeTruthy()
+ expect(screen.getByText('Rewritten by')).toBeTruthy()
+ })
+
+ it('closed, neither is anywhere, so not at the prompt field either', () => {
+ useCreateStore.getState().setIntent('image')
+ useCreateStore.setState({ improvePrompt: true })
+ render(<AdvancedDrawer open={false} onClose={() => {}} />)
+ expect(screen.queryByText('Improve my prompt')).toBeNull()
+ expect(screen.queryByText('Rewritten by')).toBeNull()
+ })
+})
diff --git a/src/hooks/__tests__/useCreate-qwen-enhancer.test.ts b/src/hooks/__tests__/useCreate-qwen-enhancer.test.ts
new file mode 100644
index 00000000..f0560350
--- /dev/null
+++ b/src/hooks/__tests__/useCreate-qwen-enhancer.test.ts
@@ -0,0 +1,222 @@
+// @vitest-environment jsdom
+/**
+ * "Improve my prompt" on a local Qwen-Image 2.1 (GH #148), through the real
+ * generate path of useCreate: with an enhancer installed the enhancer writes,
+ * after the chat model has left the card and before the picture is built;
+ * without one the chat model writes, as before.
+ *
+ * Nothing is rendered: ComfyUI, the enhancer run and the chat call are mocked,
+ * and the run is stopped at the submit of the picture.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { renderHook } from '@testing-library/react'
+
+const seen = vi.hoisted(() => ({
+ order: [] as string[],
+ enhancer: [] as { file: string; mode: string; prompt: string; images?: string[]; seed: number }[],
+ built: [] as { prompt: string; inputImage?: string; referenceImages?: string[] }[],
+ chat: [] as { prompt: string; kind: string }[],
+ outcome: { status: 'improved', prompt: 'A long rewritten prompt from the enhancer.' } as { status: string; prompt?: string },
+ buildError: null as Error | null,
+}))
+
+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 () => { seen.order.push('submit-picture'); 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 () => { seen.order.push('evict-chat'); return null }),
+ restoreChatBackendsAfterRender: vi.fn(),
+}))
+vi.mock('../../api/dynamic-workflow', async (orig) => ({
+ ...((await orig()) as Record<string, unknown>),
+ buildDynamicWorkflow: vi.fn(async (params: { prompt: string; inputImage?: string; referenceImages?: string[] }) => {
+ seen.order.push('build-picture')
+ seen.built.push({ prompt: params.prompt, inputImage: params.inputImage, referenceImages: params.referenceImages })
+ return { '1': { class_type: 'SaveImage', inputs: {} } }
+ }),
+}))
+vi.mock('../../api/qwen-enhancer', () => ({
+ buildQwenEnhancerWorkflow: vi.fn(async (req: { file: string; mode: string; prompt: string; images?: string[]; seed: number }) => {
+ seen.order.push('build-enhancer')
+ if (seen.buildError) throw seen.buildError
+ seen.enhancer.push(req)
+ return { '4': { class_type: 'TextGenerate', inputs: {} } }
+ }),
+ runQwenEnhancer: vi.fn(async () => { seen.order.push('run-enhancer'); return seen.outcome }),
+}))
+vi.mock('../../lib/render/improve-prompt-run', () => ({
+ improvePrompt: vi.fn(async (prompt: string, target: { kind: string }) => {
+ seen.order.push('chat-rewrite')
+ seen.chat.push({ prompt, kind: target.kind })
+ return { status: 'improved', prompt: 'A rewrite from the chat model.' }
+ }),
+}))
+
+import { useCreate } from '../useCreate'
+import { useCreateStore } from '../../stores/createStore'
+
+const QWEN = 'qwen_image_2.1_int8_convrot.safetensors'
+const T2I = 'qwen3.5_9b_qwen_image_2.1_pe_t2i.int8_convrot.safetensors'
+const I2I = 'qwen3.5_9b_qwen_image_2.1_pe_i2i.int8_convrot.safetensors'
+const T2I_FREE = 'qwen3.5_9b_qwen_image_2.1_pe_t2i_heretic.int8_convrot.safetensors'
+const I2I_FREE = 'qwen3.5_9b_qwen_image_2.1_pe_i2i_heretic.int8_convrot.safetensors'
+
+const image = (filename: string) => ({ filename, url: `blob:${filename}`, width: 1024, height: 1024 })
+
+beforeEach(() => {
+ seen.order.length = 0
+ seen.enhancer.length = 0
+ seen.built.length = 0
+ seen.chat.length = 0
+ seen.outcome = { status: 'improved', prompt: 'A long rewritten prompt from the enhancer.' }
+ seen.buildError = null
+ useCreateStore.setState({
+ backend: 'local', isGenerating: false, error: null, gallery: [], promptHistory: [],
+ improvePrompt: true, improveWith: 'auto',
+ cloudOp: null, utilityOp: null, removebg: false, source: null, mask: null, references: [],
+ selectedLoras: [], hiresFixEnabled: false, transparentBackground: false, seed: 42,
+ imageModel: QWEN, imageModelList: [{ name: QWEN, type: 'qwenimage' }],
+ textEncoderList: ['qwen3vl_8b_int8_convrot.safetensors', T2I, I2I, T2I_FREE, I2I_FREE],
+ } as never)
+ const s = useCreateStore.getState()
+ s.setIntent('image')
+ s.setPrompt('a fox in snow')
+})
+
+async function run() {
+ const { result } = renderHook(() => useCreate())
+ await result.current.generate()
+}
+
+describe('Improve my prompt on local Qwen-Image 2.1, enhancer installed', () => {
+ it('the enhancer writes, not the chat model, and the picture is built from its prompt', async () => {
+ await run()
+ expect(seen.chat).toHaveLength(0)
+ expect(seen.enhancer).toEqual([{ file: T2I, mode: 't2i', prompt: 'a fox in snow', images: [], seed: 42 }])
+ expect(seen.built).toHaveLength(1)
+ expect(seen.built[0].prompt).toBe('A long rewritten prompt from the enhancer.')
+ // The field keeps the user's own words.
+ expect(useCreateStore.getState().prompt).toBe('a fox in snow')
+ })
+
+ it('order on the card: chat model out, enhancer runs, then the picture is built', async () => {
+ await run()
+ expect(seen.order).toEqual(['evict-chat', 'build-enhancer', 'run-enhancer', 'build-picture', 'submit-picture'])
+ })
+
+ it('the user picked the one without refusals', async () => {
+ useCreateStore.setState({ improveWith: 'unfiltered' } as never)
+ await run()
+ expect(seen.enhancer[0].file).toBe(T2I_FREE)
+ })
+
+ it('Edit: the edit enhancer gets the instruction, the source and the references in order', async () => {
+ useCreateStore.getState().setIntent('edit')
+ useCreateStore.setState({
+ source: image('street.png'), references: [image('woman.png'), image('hat.png')], improveWith: 'unfiltered',
+ } as never)
+ useCreateStore.getState().setPrompt('put the woman from image 2 into the street')
+ await run()
+ expect(seen.chat).toHaveLength(0)
+ expect(seen.enhancer).toEqual([{
+ file: I2I_FREE, mode: 'i2i', prompt: 'put the woman from image 2 into the street',
+ images: ['street.png', 'woman.png', 'hat.png'], seed: 42,
+ }])
+ expect(seen.built[0]).toEqual({
+ prompt: 'A long rewritten prompt from the enhancer.',
+ inputImage: 'street.png', referenceImages: ['woman.png', 'hat.png'],
+ })
+ })
+
+ it('a failed rewrite does not stop the picture: it is built from the user\'s own prompt', async () => {
+ seen.outcome = { status: 'failed' }
+ await run()
+ expect(seen.built[0].prompt).toBe('a fox in snow')
+ expect(seen.chat).toHaveLength(0)
+ })
+
+ it('a rewrite that breaks the safety rule never runs', async () => {
+ seen.outcome = { status: 'improved', prompt: 'a nude child on a beach' }
+ await run()
+ expect(seen.built[0].prompt).toBe('a fox in snow')
+ })
+
+ it('a ComfyUI too old for the enhancer and a no to the update: the run does not start and says why', async () => {
+ seen.buildError = Object.assign(new Error('The Qwen prompt enhancer needs ComfyUI 0.37.2 or newer. Update ComfyUI in Settings.'), {
+ name: 'WorkflowUnavailableError', needsComfyUpdate: true,
+ })
+ const { result } = renderHook(() => useCreate())
+ const done = result.current.generate()
+ await vi.waitFor(() => expect(useCreateStore.getState().fixupPrompt).not.toBeNull())
+ expect(useCreateStore.getState().fixupPrompt?.title).toBe('ComfyUI needs an update')
+ useCreateStore.getState().fixupPrompt?.resolve(false)
+ await done
+ expect(seen.built).toHaveLength(0)
+ expect(useCreateStore.getState().error).toBe('Not started. The Qwen prompt enhancer needs ComfyUI 0.37.2 or newer. Update ComfyUI in Settings.')
+ })
+
+ it('switch off: neither writes', async () => {
+ useCreateStore.setState({ improvePrompt: false } as never)
+ await run()
+ expect(seen.order).toEqual(['evict-chat', 'build-picture', 'submit-picture'])
+ expect(seen.built[0].prompt).toBe('a fox in snow')
+ })
+})
+
+describe('falling back to the chat model', () => {
+ it('no enhancer installed: the chat model writes, before the card is cleared for the picture', async () => {
+ useCreateStore.setState({ textEncoderList: ['qwen3vl_8b_int8_convrot.safetensors'] } as never)
+ await run()
+ expect(seen.enhancer).toHaveLength(0)
+ expect(seen.chat).toEqual([{ prompt: 'a fox in snow', kind: 'image' }])
+ expect(seen.order).toEqual(['chat-rewrite', 'evict-chat', 'build-picture', 'submit-picture'])
+ expect(seen.built[0].prompt).toBe('A rewrite from the chat model.')
+ })
+
+ it('only the edit enhancer installed: a new picture is written by the chat model', async () => {
+ useCreateStore.setState({ textEncoderList: [I2I, I2I_FREE] } as never)
+ await run()
+ expect(seen.enhancer).toHaveLength(0)
+ expect(seen.chat).toHaveLength(1)
+ })
+
+ it('the user picked the chat model although the enhancer is there', async () => {
+ useCreateStore.setState({ improveWith: 'chat' } as never)
+ await run()
+ expect(seen.enhancer).toHaveLength(0)
+ expect(seen.built[0].prompt).toBe('A rewrite from the chat model.')
+ })
+
+ it('another local model with the enhancers on disk: the chat model writes', async () => {
+ useCreateStore.setState({ imageModel: 'flux-2-klein-4b.safetensors', imageModelList: [{ name: 'flux-2-klein-4b.safetensors', type: 'flux2' }] } as never)
+ await run()
+ expect(seen.enhancer).toHaveLength(0)
+ expect(seen.chat).toHaveLength(1)
+ })
+
+ it('Edit without an edit enhancer: nobody rewrites, as before', async () => {
+ useCreateStore.getState().setIntent('edit')
+ useCreateStore.setState({ source: image('street.png'), textEncoderList: [T2I, T2I_FREE] } as never)
+ await run()
+ expect(seen.enhancer).toHaveLength(0)
+ expect(seen.chat).toHaveLength(0)
+ expect(seen.built[0].prompt).toBe('a fox in snow')
+ })
+})
diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.ts
index f16b6eef..d114d1ae 100644
--- a/src/hooks/useCreate.ts
+++ b/src/hooks/useCreate.ts
@@ -8,6 +8,7 @@ import {
getAudioModels,
getLipsyncModels,
getMotionModels,
+ getCLIPModels,
resolveLocalOpPick,
uploadMediaFile,
getSamplers,
@@ -62,8 +63,11 @@ import { useComfyInstallStore } from '../stores/comfyInstallStore'
import { checkPromptSafety, SAFETY_BLOCK_MESSAGE } from '../lib/render/safety'
import { wantsTransparent } from '../lib/transparent-image'
import { scenePromptFor } from '../lib/ltx-multishot'
-import { improveKindForIntent } from '../lib/render/improve-prompt'
+import { improveKindForIntent, type ImproveOutcome } from '../lib/render/improve-prompt'
import { improvePrompt } from '../lib/render/improve-prompt-run'
+import { pickQwenEnhancer } from '../lib/render/qwen-enhancer'
+import { buildQwenEnhancerWorkflow, runQwenEnhancer } from '../api/qwen-enhancer'
+import { extraReferenceSlots } from '../lib/edit-references'
import { resolveRunSeed } from '../lib/run-seed'
import {
clearTrainingSet, stageTrainingImage, startCharacterTraining,
@@ -297,6 +301,9 @@ export function useCreate() {
getLipsyncModels().catch(() => [] as ClassifiedModel[]),
getMotionModels().catch(() => [] as ClassifiedModel[]),
])
+ // The text encoder files, for the prompt enhancers among them
+ // ("Improve my prompt" on local Qwen-Image 2.1). Best effort.
+ const textEncoders = await getCLIPModels().catch(() => [] as string[])
// MLX entries go first so one is the default on a fresh Apple-Silicon box.
const imgModels = mlxImageModels.length
? mergeImageModels(comfyImgModels, mlxImageModels)
@@ -321,6 +328,7 @@ export function useCreate() {
st.setAudioModelList(audModels)
st.setLipsyncModelList(lipModels)
st.setMotionModelList(motModels)
+ st.setTextEncoderList(textEncoders)
// If ComfyUI is connected but returns 0 models, do NOT set modelsLoaded — keep retrying.
// ComfyUI may still be scanning directories (race condition on startup).
@@ -658,14 +666,36 @@ export function useCreate() {
// stops the run, it goes on with the user's own prompt.
let prompt = scenePrompt
let improveFields: { promptOriginal?: string; improveFailed?: true } = {}
- const improveKind = state.improvePrompt ? improveKindForIntent(intent) : null
+ // The safety check covers the rewrite too: the user wrote an allowed
+ // prompt, the model must not turn it into a refusal.
+ const takeRewrite = (out: ImproveOutcome) => {
+ if (out.status === 'improved' && !checkPromptSafety(out.prompt).blocked) {
+ prompt = out.prompt
+ improveFields = { promptOriginal: scenePrompt }
+ } else if (out.status !== 'unchanged') {
+ improveFields = { improveFailed: true }
+ }
+ }
+ // A local Qwen-Image 2.1 run with a prompt enhancer installed: the
+ // enhancer writes instead of the chat model (GH #148), for a new picture
+ // and for an edit. It is a ComfyUI job, so it runs further down, once
+ // ComfyUI is up and the chat model is off the card.
+ const qwenEnhancer = state.improvePrompt && !localOp && scenePrompt.trim()
+ ? pickQwenEnhancer({
+ local: !isMlxImageHost(),
+ intent,
+ modelType: state.imageModelList.find((m) => m.name === effImageModel)?.type ?? classifyModel(effImageModel),
+ textEncoders: state.textEncoderList,
+ }, state.improveWith)
+ : null
+ const improveKind = state.improvePrompt && !qwenEnhancer ? improveKindForIntent(intent) : null
if (improveKind && scenePrompt.trim()) {
const own = new AbortController()
abortRef.current = own
setIsGenerating(true)
setProgress(3, 'Improving your prompt…')
const runModel = improveKind === 'music' ? state.localOpModel : improveKind === 'video' ? effVideoModel : effImageModel
- let out: Awaited<ReturnType<typeof improvePrompt>> = { status: 'failed' }
+ let out: ImproveOutcome = { status: 'failed' }
try {
out = await improvePrompt(scenePrompt, {
kind: improveKind,
@@ -679,14 +709,7 @@ export function useCreate() {
}
// Cancel pressed while the chat model was writing: the run does not start.
if (own.signal.aborted) return
- // The safety check covers the rewrite too: the user wrote an allowed
- // prompt, the model must not turn it into a refusal.
- if (out.status === 'improved' && !checkPromptSafety(out.prompt).blocked) {
- prompt = out.prompt
- improveFields = { promptOriginal: scenePrompt }
- } else if (out.status !== 'unchanged') {
- improveFields = { improveFailed: true }
- }
+ takeRewrite(out)
}
// ── MLX image pipeline (Apple Silicon) — hard rule: Mac local image is the
@@ -1009,6 +1032,25 @@ export function useCreate() {
} catch { /* VRAM housekeeping is best-effort */ }
try {
+ // The Qwen prompt enhancer writes now: the chat model has left the card,
+ // and the enhancer leaves it again before the picture's models load
+ // (runQwenEnhancer unloads it). An edit shows it the same pictures, in
+ // the same order, that the picture's graph numbers as image 1, 2, 3.
+ // A ComfyUI too old for it is offered the update, like the model itself.
+ if (qwenEnhancer) {
+ setProgress(3, 'Improving your prompt…')
+ const signal = abortRef.current?.signal
+ const images = qwenEnhancer.mode === 'i2i' && effInputImage
+ ? [effInputImage, ...references.map((r) => r.filename).filter(Boolean).slice(0, extraReferenceSlots(imageModelType, activeModel))]
+ : []
+ const enhancerGraph = await buildWithFixups(
+ () => buildQwenEnhancerWorkflow({ file: qwenEnhancer.file, mode: qwenEnhancer.mode, prompt: scenePrompt, images, seed: runSeed }),
+ renderFixupDeps((line) => setProgress(3, line), signal),
+ )
+ const out = await runQwenEnhancer(enhancerGraph, scenePrompt, { clientId: CLIENT_ID, signal })
+ if (signal?.aborted) throw new Error('Cancelled')
+ takeRewrite(out)
+ }
// GH #146: the stack is checked against what ComfyUI lists right now.
// A deleted file or a Z-Image character on another model is left out
// with a line, instead of ComfyUI refusing the whole graph.
diff --git a/src/lib/render/__tests__/local-model-tier.test.ts b/src/lib/render/__tests__/local-model-tier.test.ts
index 99308862..1d6d63b1 100644
--- a/src/lib/render/__tests__/local-model-tier.test.ts
+++ b/src/lib/render/__tests__/local-model-tier.test.ts
@@ -25,8 +25,8 @@ const mainFile = (b: ModelBundle) =>
const tierOfFile = (name: string) => localTier({ name, type: classifyModel(name) })
describe('jedes lokale Bundle traegt eine Stufe', () => {
- it('alle 38 Bundles haben best, standard oder older', () => {
- expect(ALL.length).toBe(38)
+ it('alle 40 Bundles haben best, standard oder older', () => {
+ expect(ALL.length).toBe(40)
for (const b of ALL) expect(['best', 'standard', 'older'], b.name).toContain(b.tier)
})
diff --git a/src/lib/render/__tests__/qwen-enhancer.test.ts b/src/lib/render/__tests__/qwen-enhancer.test.ts
new file mode 100644
index 00000000..de28c3da
--- /dev/null
+++ b/src/lib/render/__tests__/qwen-enhancer.test.ts
@@ -0,0 +1,181 @@
+/**
+ * The Qwen-Image 2.1 prompt enhancer as a writer for "Improve my prompt"
+ * (GH #148): which files count, which one a run takes, when the chat model
+ * writes instead, and how the enhancer's answer becomes a prompt.
+ *
+ * Run: npx vitest run src/lib/render/__tests__/qwen-enhancer.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import {
+ activeWriter, cleanEnhanced, enhancedOutcome, improveWriters, installedQwenEnhancers,
+ isQwenEnhancerFile, pickQwenEnhancer, qwenEnhancerFile, qwenEnhancerMode,
+ type EnhancerSituation,
+} from '../qwen-enhancer'
+
+const T2I = 'qwen3.5_9b_qwen_image_2.1_pe_t2i.int8_convrot.safetensors'
+const I2I = 'qwen3.5_9b_qwen_image_2.1_pe_i2i.int8_convrot.safetensors'
+const T2I_FREE = 'qwen3.5_9b_qwen_image_2.1_pe_t2i_heretic.int8_convrot.safetensors'
+const I2I_FREE = 'qwen3.5_9b_qwen_image_2.1_pe_i2i_heretic.int8_convrot.safetensors'
+const ENCODER = 'qwen3vl_8b_int8_convrot.safetensors'
+
+const run = (extra: Partial<EnhancerSituation>): EnhancerSituation => ({
+ local: true, intent: 'image', modelType: 'qwenimage', textEncoders: [ENCODER, T2I, I2I, T2I_FREE, I2I_FREE], ...extra,
+})
+
+describe('which files are prompt enhancers', () => {
+ it('reads task and edition off the four catalog files', () => {
+ expect(qwenEnhancerFile(T2I)).toEqual({ file: T2I, mode: 't2i', variant: 'official' })
+ expect(qwenEnhancerFile(I2I)).toEqual({ file: I2I, mode: 'i2i', variant: 'official' })
+ expect(qwenEnhancerFile(T2I_FREE)).toEqual({ file: T2I_FREE, mode: 't2i', variant: 'unfiltered' })
+ expect(qwenEnhancerFile(I2I_FREE)).toEqual({ file: I2I_FREE, mode: 'i2i', variant: 'unfiltered' })
+ })
+
+ it('knows the other published single file editions, also in a subfolder', () => {
+ // darrellbest/Qwen-Image-2.1-PE-Heretic-ComfyUI, HarleyWang/Qwen-Image-2.1-PE-ComfyUI,
+ // netrunner-exe/Qwen-Image-2.1-PE-Heretic, and the folder the MTP node pack writes to.
+ expect(qwenEnhancerFile('qwen_image_2.1_pe_i2i_heretic_fp8_e4m3fn.safetensors')).toMatchObject({ mode: 'i2i', variant: 'unfiltered' })
+ expect(qwenEnhancerFile('qwen_image_2.1_pe_t2i_int8_convrot.safetensors')).toMatchObject({ mode: 't2i', variant: 'official' })
+ expect(qwenEnhancerFile('qwen3.5_9b_qwen_image_2.1_pe_i2i_heretic.int8_convrot.mtp.safetensors')).toMatchObject({ mode: 'i2i', variant: 'unfiltered' })
+ const nested = 'Qwen-Image-2.1-PE\\qwen3.5_9b_qwen_image_2.1_pe_t2i.int8_convrot.mtp.safetensors'
+ expect(qwenEnhancerFile(nested)).toEqual({ file: nested, mode: 't2i', variant: 'official' })
+ })
+
+ it('a text encoder is not an enhancer', () => {
+ for (const name of [ENCODER, 'qwen_3_4b.safetensors', 'qwen_2.5_vl_7b_fp8_scaled.safetensors', 'qwen_image_2.1_vae_bf16.safetensors', 't5xxl_fp16.safetensors']) {
+ expect(isQwenEnhancerFile(name), name).toBe(false)
+ }
+ expect(installedQwenEnhancers([ENCODER, T2I, 'clip_l.safetensors']).map((f) => f.file)).toEqual([T2I])
+ })
+})
+
+describe('when the enhancer has a task', () => {
+ it('only on a local Qwen-Image 2.1, for a new picture or an edit', () => {
+ expect(qwenEnhancerMode({ local: true, intent: 'image', modelType: 'qwenimage' })).toBe('t2i')
+ expect(qwenEnhancerMode({ local: true, intent: 'edit', modelType: 'qwenimage' })).toBe('i2i')
+ expect(qwenEnhancerMode({ local: false, intent: 'image', modelType: 'qwenimage' })).toBeNull()
+ expect(qwenEnhancerMode({ local: true, intent: 'image', modelType: 'flux2' })).toBeNull()
+ expect(qwenEnhancerMode({ local: true, intent: 'image', modelType: 'qwenimage1' })).toBeNull()
+ for (const intent of ['video', 'animate', 'music', 'removebg', 'upscale', 'character']) {
+ expect(qwenEnhancerMode({ local: true, intent, modelType: 'qwenimage' }), intent).toBeNull()
+ }
+ })
+})
+
+describe('which enhancer a run takes', () => {
+ it('by default the official one, each task its own file', () => {
+ expect(pickQwenEnhancer(run({}), 'auto')?.file).toBe(T2I)
+ expect(pickQwenEnhancer(run({ intent: 'edit' }), 'auto')?.file).toBe(I2I)
+ })
+
+ it('the user picks the edition without refusals', () => {
+ expect(pickQwenEnhancer(run({}), 'unfiltered')?.file).toBe(T2I_FREE)
+ expect(pickQwenEnhancer(run({ intent: 'edit' }), 'unfiltered')?.file).toBe(I2I_FREE)
+ expect(pickQwenEnhancer(run({}), 'official')?.file).toBe(T2I)
+ })
+
+ it('takes the edition that is there when the picked one is not', () => {
+ expect(pickQwenEnhancer(run({ textEncoders: [T2I_FREE] }), 'official')?.file).toBe(T2I_FREE)
+ expect(pickQwenEnhancer(run({ textEncoders: [T2I] }), 'unfiltered')?.file).toBe(T2I)
+ })
+
+ it('never takes the file of the other task', () => {
+ expect(pickQwenEnhancer(run({ textEncoders: [I2I, I2I_FREE] }), 'auto')).toBeNull()
+ expect(pickQwenEnhancer(run({ intent: 'edit', textEncoders: [T2I, T2I_FREE] }), 'auto')).toBeNull()
+ })
+})
+
+describe('falling back to the chat model', () => {
+ it('no enhancer installed: nothing to pick, the chat model writes', () => {
+ const s = run({ textEncoders: [ENCODER] })
+ expect(pickQwenEnhancer(s, 'auto')).toBeNull()
+ expect(improveWriters(s)).toEqual([])
+ expect(activeWriter(s, 'auto')).toBeNull()
+ })
+
+ it('another model family or the cloud: the chat model writes, enhancer installed or not', () => {
+ for (const s of [run({ modelType: 'flux2' }), run({ modelType: 'sdxl' }), run({ local: false }), run({ intent: 'video' })]) {
+ expect(pickQwenEnhancer(s, 'auto')).toBeNull()
+ expect(pickQwenEnhancer(s, 'unfiltered')).toBeNull()
+ expect(improveWriters(s)).toEqual([])
+ }
+ })
+
+ it('the user can pick the chat model for a new picture', () => {
+ expect(pickQwenEnhancer(run({}), 'chat')).toBeNull()
+ expect(activeWriter(run({}), 'chat')).toBe('chat')
+ })
+
+ it('an edit has no chat model: that pick falls to the enhancer', () => {
+ const s = run({ intent: 'edit' })
+ expect(pickQwenEnhancer(s, 'chat')?.file).toBe(I2I)
+ expect(activeWriter(s, 'chat')).toBe('official')
+ })
+})
+
+describe('what the switch offers', () => {
+ it('a new picture: both editions and the chat model', () => {
+ expect(improveWriters(run({}))).toEqual([
+ { id: 'official', label: 'Qwen enhancer' },
+ { id: 'unfiltered', label: 'Qwen enhancer, no refusals' },
+ { id: 'chat', label: 'Chat model' },
+ ])
+ })
+
+ it('an edit: the editions only', () => {
+ expect(improveWriters(run({ intent: 'edit' })).map((w) => w.id)).toEqual(['official', 'unfiltered'])
+ })
+
+ it('only the installed edition is listed', () => {
+ expect(improveWriters(run({ textEncoders: [T2I_FREE, I2I] })).map((w) => w.id)).toEqual(['unfiltered', 'chat'])
+ expect(improveWriters(run({ intent: 'edit', textEncoders: [T2I_FREE, I2I] })).map((w) => w.id)).toEqual(['official'])
+ })
+
+ it('marks the one that will write', () => {
+ expect(activeWriter(run({}), 'auto')).toBe('official')
+ expect(activeWriter(run({}), 'unfiltered')).toBe('unfiltered')
+ expect(activeWriter(run({ textEncoders: [T2I_FREE] }), 'official')).toBe('unfiltered')
+ })
+})
+
+describe('the answer becomes a prompt', () => {
+ it('a plain paragraph is taken as it is, long or not', () => {
+ const long = 'A weathered lighthouse on a basalt cliff. '.repeat(200).trim()
+ expect(cleanEnhanced(` ${long}\n`)).toBe(long)
+ expect(long.length).toBeGreaterThan(3000)
+ })
+
+ it('line breaks become spaces, the paragraph stays one', () => {
+ expect(cleanEnhanced('A red fox\nin deep snow.\n\nWatercolor.')).toBe('A red fox in deep snow. Watercolor.')
+ })
+
+ it('reasoning left in the answer is dropped', () => {
+ expect(cleanEnhanced('<think>the user wants a fox</think>A red fox in deep snow.')).toBe('A red fox in deep snow.')
+ })
+
+ it('an answer cut off inside its reasoning is unusable', () => {
+ expect(cleanEnhanced('<think>the user wants a fox and')).toBeNull()
+ })
+
+ it("Qwen's own JSON format is unwrapped", () => {
+ expect(cleanEnhanced('{"rewritten_prompt": "A red fox in deep snow.", "wh_ratio": "3:2"}')).toBe('A red fox in deep snow.')
+ expect(cleanEnhanced('```json\n{"rewritten_prompt": "A red fox.", "wh_ratio": "", "ratio_follow": "<image1>"}\n```')).toBe('A red fox.')
+ })
+
+ it('JSON without the prompt, or cut off, is unusable', () => {
+ expect(cleanEnhanced('{"wh_ratio": "3:2"}')).toBeNull()
+ expect(cleanEnhanced('{"rewritten_prompt": "A red fox in')).toBeNull()
+ })
+
+ it('empty answers and refusals are unusable', () => {
+ expect(cleanEnhanced(' ')).toBeNull()
+ expect(cleanEnhanced("I'm sorry, but I can't help with that request.")).toBeNull()
+ expect(cleanEnhanced('I cannot assist with this edit.')).toBeNull()
+ })
+
+ it('the outcome speaks the words of Improve my prompt', () => {
+ expect(enhancedOutcome('A red fox in deep snow.', 'a fox')).toEqual({ status: 'improved', prompt: 'A red fox in deep snow.' })
+ expect(enhancedOutcome(' a fox ', 'a fox')).toEqual({ status: 'unchanged' })
+ expect(enhancedOutcome(null, 'a fox')).toEqual({ status: 'failed' })
+ expect(enhancedOutcome("I'm sorry, I can't do that.", 'a fox')).toEqual({ status: 'failed' })
+ })
+})
diff --git a/src/lib/render/qwen-enhancer.ts b/src/lib/render/qwen-enhancer.ts
new file mode 100644
index 00000000..00eb30a6
--- /dev/null
+++ b/src/lib/render/qwen-enhancer.ts
@@ -0,0 +1,178 @@
+// The Qwen-Image 2.1 prompt enhancer as a writer for "Improve my prompt"
+// (GH #148): the pure half. Which files are enhancers, which one a run takes,
+// what the switch offers, and how the enhancer's answer becomes a prompt. No
+// stores, no network; the graph and the run live in api/qwen-enhancer.ts.
+//
+// Read off the sources on 2026-10-03:
+// - Comfy-Org/Qwen-Image-2.1 ships the two official enhancers as single
+// files for the text_encoders folder: one for text to image (t2i) and one
+// for edits (i2i), which also reads the pictures.
+// - Adahm/PE-Heretic-INT8-ConvRot-for-Qwen-Image-2.1 ships the community
+// editions without refusals in the same format, built from
+// pottokao/Qwen-Image-2.1-PE-T2I-Heretic and
+// darrellbest/Qwen-Image-2.1-PE-I2I-Heretic.
+// A t2i file cannot stand in for an i2i file or the other way round: each was
+// trained for its own task and its own system prompt.
+
+import type { ImproveOutcome } from './improve-prompt'
+
+/** What the enhancer rewrites: a prompt for a new picture, or an edit instruction. */
+export type QwenEnhancerMode = 't2i' | 'i2i'
+
+/** The official file, or a community edition with the refusals removed. */
+export type QwenEnhancerVariant = 'official' | 'unfiltered'
+
+export interface QwenEnhancerFile {
+ /** The name ComfyUI lists, with its subfolder when it has one. */
+ file: string
+ mode: QwenEnhancerMode
+ variant: QwenEnhancerVariant
+}
+
+const ENHANCER_NAME = /qwen[_-]image[_-]2\.1[_-]pe[_-](t2i|i2i)/i
+const UNFILTERED_NAME = /heretic|abliterat/i
+
+/** Is this text encoder file a Qwen-Image 2.1 prompt enhancer, and which one?
+ * The name is the only thing ComfyUI tells us, and every published single
+ * file edition carries "qwen_image_2.1_pe_t2i" or "..._i2i" in it. */
+export function qwenEnhancerFile(file: string): QwenEnhancerFile | null {
+ const base = file.split(/[\\/]/).pop() ?? file
+ const match = ENHANCER_NAME.exec(base)
+ if (!match) return null
+ return {
+ file,
+ mode: match[1].toLowerCase() === 'i2i' ? 'i2i' : 't2i',
+ variant: UNFILTERED_NAME.test(base) ? 'unfiltered' : 'official',
+ }
+}
+
+/** A prompt enhancer is a text model, not a text encoder for a picture model.
+ * The encoder search must never pick one. */
+export function isQwenEnhancerFile(file: string): boolean {
+ return qwenEnhancerFile(file) !== null
+}
+
+/** The enhancers among ComfyUI's text encoder files. */
+export function installedQwenEnhancers(textEncoders: readonly string[]): QwenEnhancerFile[] {
+ return textEncoders.map(qwenEnhancerFile).filter((f): f is QwenEnhancerFile => f !== null)
+}
+
+/** Who rewrites the prompt. 'auto' is the default: the enhancer when one is
+ * there, the official one first, otherwise the chat model. */
+export type ImproveWith = 'auto' | 'chat' | QwenEnhancerVariant
+
+export const IMPROVE_WITH: readonly ImproveWith[] = ['auto', 'chat', 'official', 'unfiltered']
+
+export interface ImproveWriter {
+ id: 'chat' | QwenEnhancerVariant
+ label: string
+}
+
+const WRITER_LABEL: Record<ImproveWriter['id'], string> = {
+ official: 'Qwen enhancer',
+ unfiltered: 'Qwen enhancer, no refusals',
+ chat: 'Chat model',
+}
+
+export interface EnhancerSituation {
+ /** Create runs on this machine through ComfyUI. */
+ local: boolean
+ /** The Create intent: 'image' writes a new picture, 'edit' changes one. */
+ intent: string
+ /** The family of the picked image model. Only 'qwenimage' has an enhancer. */
+ modelType: string | null | undefined
+ /** ComfyUI's text encoder files. */
+ textEncoders: readonly string[]
+}
+
+/** Which task the enhancer would have here, or null when it has none: only a
+ * local Qwen-Image 2.1 run, for a new picture or for an edit. */
+export function qwenEnhancerMode(s: Pick<EnhancerSituation, 'local' | 'intent' | 'modelType'>): QwenEnhancerMode | null {
+ if (!s.local || s.modelType !== 'qwenimage') return null
+ if (s.intent === 'image') return 't2i'
+ if (s.intent === 'edit') return 'i2i'
+ return null
+}
+
+/** The enhancers that fit this run, official first. */
+function fitting(s: EnhancerSituation): QwenEnhancerFile[] {
+ const mode = qwenEnhancerMode(s)
+ if (!mode) return []
+ const files = installedQwenEnhancers(s.textEncoders).filter((f) => f.mode === mode)
+ const first = (variant: QwenEnhancerVariant) => files.find((f) => f.variant === variant)
+ return [first('official'), first('unfiltered')].filter((f): f is QwenEnhancerFile => !!f)
+}
+
+/** What the switch lets the user choose between. Empty when no enhancer fits:
+ * then there is nothing to choose and the chat model writes, as before. An
+ * edit has no chat model entry, a chat model cannot see the picture. */
+export function improveWriters(s: EnhancerSituation): ImproveWriter[] {
+ const files = fitting(s)
+ if (files.length === 0) return []
+ const writers: ImproveWriter[] = files.map((f) => ({ id: f.variant, label: WRITER_LABEL[f.variant] }))
+ if (s.intent === 'image') writers.push({ id: 'chat', label: WRITER_LABEL.chat })
+ return writers
+}
+
+/** The enhancer file this run takes, or null when the chat model writes (or,
+ * on an edit without an enhancer, nobody does). The user's choice wins when
+ * that edition is installed; otherwise the first one that fits. */
+export function pickQwenEnhancer(s: EnhancerSituation, choice: ImproveWith): QwenEnhancerFile | null {
+ const files = fitting(s)
+ if (files.length === 0) return null
+ if (choice === 'chat' && s.intent === 'image') return null
+ return files.find((f) => f.variant === choice) ?? files[0]
+}
+
+/** The entry the choice row marks. */
+export function activeWriter(s: EnhancerSituation, choice: ImproveWith): ImproveWriter['id'] | null {
+ if (improveWriters(s).length === 0) return null
+ return pickQwenEnhancer(s, choice)?.variant ?? 'chat'
+}
+
+export const QWEN_ENHANCER_HINT =
+ 'The Qwen prompt enhancer rewrites your prompt for Qwen-Image 2.1. It runs on your machine before the picture starts.'
+
+const THINK_BLOCK = /<think(?:ing)?>[\s\S]*?<\/think(?:ing)?>/gi
+const OPEN_THINK = /<think(?:ing)?>[\s\S]*$/i
+const REFUSAL = /^(i['’]m sorry|i am sorry|sorry[,.]|i can['’]?t|i cannot|i['’]m unable|i am unable|as an ai)/i
+
+/** The enhancer's answer, made into a prompt. The system prompts ask for one
+ * plain paragraph; Qwen's own format is a JSON object with the prompt in
+ * `rewritten_prompt`, so an answer that still comes that way is unwrapped.
+ * Null when it is unusable: empty, cut off inside its reasoning, or a
+ * refusal. There is no length limit, this model is made for long prompts. */
+export function cleanEnhanced(raw: string): string | null {
+ let text = raw.replace(THINK_BLOCK, '')
+ if (OPEN_THINK.test(text)) return null
+ text = text.trim()
+ const fenced = /^```[a-z]*\n?([\s\S]*?)\n?```$/i.exec(text)
+ if (fenced) text = fenced[1].trim()
+ if (text.startsWith('{')) {
+ try {
+ const parsed: unknown = JSON.parse(text)
+ const field = parsed && typeof parsed === 'object'
+ ? (parsed as Record<string, unknown>).rewritten_prompt
+ : undefined
+ // A JSON object without the prompt in it is not a prompt.
+ if (typeof field !== 'string') return null
+ text = field.trim()
+ } catch {
+ // Braces that are not JSON: an answer cut off mid object.
+ return null
+ }
+ }
+ // One paragraph, as the system prompts ask: a stray line break is a space.
+ text = text.replace(/\s*\n+\s*/g, ' ').trim()
+ if (!text) return null
+ if (REFUSAL.test(text)) return null
+ return text
+}
+
+/** The outcome of an enhancer answer, in the words "Improve my prompt" uses. */
+export function enhancedOutcome(raw: string | null, original: string): ImproveOutcome {
+ const cleaned = raw === null ? null : cleanEnhanced(raw)
+ if (!cleaned) return { status: 'failed' }
+ if (cleaned === original.trim()) return { status: 'unchanged' }
+ return { status: 'improved', prompt: cleaned }
+}
diff --git a/src/stores/createStore.ts b/src/stores/createStore.ts
index f7615a4c..fb4f4bfa 100644
--- a/src/stores/createStore.ts
+++ b/src/stores/createStore.ts
@@ -31,6 +31,7 @@ const RUNTIME_ONLY_KEYS: readonly string[] = [
]
import type { ModelType, ClassifiedModel } from '../api/comfyui'
import { MAX_SHOTS, MAX_SHOT_CHARS } from '../lib/ltx-multishot'
+import { IMPROVE_WITH, type ImproveWith } from '../lib/render/qwen-enhancer'
import { classifyModel, hidreamSampling } from '../api/comfyui'
import type { HiresUpscaleMethod } from '../api/hires-fix'
import { releaseVideoBlobUrl } from '../api/mlx-video'
@@ -398,6 +399,14 @@ interface CreateState {
/** Advanced settings switch: a chat model rewrites the prompt before a run. Off by default, remembered. */
improvePrompt: boolean
setImprovePrompt: (on: boolean) => void
+ /** Who rewrites the prompt when a local Qwen-Image 2.1 run has a prompt
+ * enhancer installed (lib/render/qwen-enhancer.ts). Remembered. */
+ improveWith: ImproveWith
+ setImproveWith: (who: ImproveWith) => void
+ /** Runtime-only: the text encoder files ComfyUI lists, read with the model
+ * lists. The switch finds the installed prompt enhancers in it. */
+ textEncoderList: string[]
+ setTextEncoderList: (list: string[]) => void
/** Runtime-only: the LOCAL model picked inside a specialized lane (ACE
* checkpoint / S2V UNet / Animate-VACE UNet). One slot for all lanes —
* resolveLocalOpPick coerces a stale cross-lane pick onto the lane's list
@@ -714,6 +723,8 @@ export const useCreateStore = create<CreateState>()(
cloudStudioCredits: null as number | null,
cloudImageCount: 1,
improvePrompt: false,
+ improveWith: 'auto' as ImproveWith,
+ textEncoderList: [] as string[],
transparentBackground: false,
videoShots: [],
localOpModel: '',
@@ -968,6 +979,8 @@ export const useCreateStore = create<CreateState>()(
setCloudStudioCredits: (cloudStudioCredits) => set({ cloudStudioCredits }),
setCloudImageCount: (count) => set({ cloudImageCount: clampImageCount(count) }),
setImprovePrompt: (on) => set({ improvePrompt: on === true }),
+ setImproveWith: (who) => set({ improveWith: IMPROVE_WITH.includes(who) ? who : 'auto' }),
+ setTextEncoderList: (list) => set({ textEncoderList: list }),
setVideoShotCount: (count) => set((st) => {
const further = Math.max(1, Math.min(MAX_SHOTS, Math.floor(count) || 1)) - 1
return { videoShots: Array.from({ length: further }, (_, i) => st.videoShots[i] ?? '') }
@@ -1231,6 +1244,7 @@ export const useCreateStore = create<CreateState>()(
musicDuration: state.musicDuration,
musicHowtoSeen: state.musicHowtoSeen,
improvePrompt: state.improvePrompt,
+ improveWith: state.improveWith,
transparentBackground: state.transparentBackground,
triggerWord: state.triggerWord,
trainSteps: state.trainSteps,