Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: support Qwen Image 2.1 reference image uploads

[._.]/ Adam Eivyd32d7e45fc57
diff --git a/client/src/lib/imageGenBackends.test.js b/client/src/lib/imageGenBackends.test.js
index 38071454b9..6b55bb9a30 100644
--- a/client/src/lib/imageGenBackends.test.js
+++ b/client/src/lib/imageGenBackends.test.js
@@ -67,6 +67,12 @@ describe('input-image capability helpers', () => {
expect(referenceSlotsFor(IMAGE_GEN_MODE.GROK, { hasInitImage: false })).toBe(4);
});
+ it('reserves the init slot within Qwen’s ten inputs', () => {
+ const options = { localSupportsReferences: true, localInputCap: 10, maxSlots: 10 };
+ expect(referenceSlotsFor(IMAGE_GEN_MODE.LOCAL, options)).toBe(10);
+ expect(referenceSlotsFor(IMAGE_GEN_MODE.LOCAL, { ...options, hasInitImage: true })).toBe(9);
+ });
+
it('offers local reference slots only when the model supports them, and none for external', () => {
expect(referenceSlotsFor(IMAGE_GEN_MODE.LOCAL, { localSupportsReferences: true })).toBe(4);
expect(referenceSlotsFor(IMAGE_GEN_MODE.LOCAL, { localSupportsReferences: false })).toBe(0);
diff --git a/client/src/lib/imageGenModes.js b/client/src/lib/imageGenModes.js
index 3264a802ec..5d4c949178 100644
--- a/client/src/lib/imageGenModes.js
+++ b/client/src/lib/imageGenModes.js
@@ -321,11 +321,14 @@ export function pickI2iMode(backends) {
* leads" rule `resolveInputImages` applies server-side, predicted here so the
* form never offers a slot the backend would drop. A backend that declares no
* cap gets the form's full slot count. Local FLUX.2 takes all of them (its
- * references ride a separate runner flag from the init image); a non-FLUX.2
- * local model and external take none.
+ * references ride a separate runner flag from the init image). Qwen 2.1 shares
+ * its ten-input cap with the init image. Unsupported models take none.
*/
-export function referenceSlotsFor(mode, { hasInitImage = false, maxSlots = 4, localSupportsReferences = false } = {}) {
- if (mode === IMAGE_GEN_MODE.LOCAL) return localSupportsReferences ? maxSlots : 0;
+export function referenceSlotsFor(mode, { hasInitImage = false, maxSlots = 4, localSupportsReferences = false, localInputCap = null } = {}) {
+ if (mode === IMAGE_GEN_MODE.LOCAL) {
+ if (!localSupportsReferences) return 0;
+ return Math.min(maxSlots, (localInputCap ?? Infinity) - (hasInitImage ? 1 : 0));
+ }
if (!isCloudCliMode(mode)) return 0;
const cap = maxInputImages(mode) ?? Infinity;
return Math.min(maxSlots, cap - (hasInitImage ? 1 : 0));
diff --git a/client/src/pages/ImageGen.defaultLocalModel.test.jsx b/client/src/pages/ImageGen.defaultLocalModel.test.jsx
index 93b4ec70ae..831a5d0625 100644
--- a/client/src/pages/ImageGen.defaultLocalModel.test.jsx
+++ b/client/src/pages/ImageGen.defaultLocalModel.test.jsx
@@ -33,6 +33,16 @@ describe('ImageGen default local model', () => {
window.matchMedia = vi.fn(() => ({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() }));
});
+ it('offers ten Qwen reference slots without strength controls', async () => {
+ state.models = [imageGenModel('qwen-image-2.1', { runner: 'qwen', pipelineClass: 'QwenImage21Pipeline' })];
+ state.getSettings.mockResolvedValue(settingsWith({ modelId: 'qwen-image-2.1' }));
+ state.referenceImagePickerFactory = ({ referenceImages, showStrength }) => (
+ <div data-testid="qwen-refs">{referenceImages.length}:{String(showStrength)}</div>
+ );
+ await renderImageGenPage();
+ await waitFor(() => expect(screen.getByTestId('qwen-refs').textContent).toBe('10:false'));
+ });
+
it('opens on the model pinned in settings, not the first catalog entry', async () => {
state.getSettings.mockResolvedValue(settingsWith({ modelId: 'flux2-klein-4b' }));
await renderImageGenPage();
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index 8653f56f42..a8d32f837b 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -66,12 +66,10 @@ import {
getFlux2Status,
} from '../services/api';
-// Multi-reference conditioning — 4 fixed slots, each carrying an uploaded File
-// + a 0..1 strength weight. Slots are positional so the blob-URL revoke pairs
-// with the slot the user cleared. Local consumes all 4 (FLUX.2 only); a cloud
-// CLI takes however many its image tool accepts alongside the init image (see
-// referenceSlotsFor), so the form offers only that many slots there.
-const REFERENCE_SLOT_COUNT = 4;
+// Positional slots preserve uploads across model switches. Qwen 2.1 takes up
+// to ten inputs total; other backends retain their existing four-slot form.
+// referenceSlotsFor reserves room for the init image where the cap is shared.
+const REFERENCE_SLOT_COUNT = 10;
const EMPTY_REF_SLOT = { file: null, previewUrl: null, strength: 1.0 };
// Revoke an object URL only when it's a blob: URL we created — gallery `/data/...`
@@ -756,10 +754,12 @@ export default function ImageGen() {
// switch shouldn't destroy an upload the user can get back by switching
// again) but are neither rendered nor submitted — every consumer reads these
// two derived views rather than re-slicing `referenceImages`.
+ const isQwen21Model = currentModel?.pipelineClass === 'QwenImage21Pipeline';
const referenceSlotCount = referenceSlotsFor(effectiveMode, {
hasInitImage: initImage.source != null,
- maxSlots: REFERENCE_SLOT_COUNT,
- localSupportsReferences: isFlux2Model,
+ maxSlots: isLocalMode && isQwen21Model ? REFERENCE_SLOT_COUNT : 4,
+ localSupportsReferences: isFlux2Model || isQwen21Model,
+ localInputCap: isQwen21Model ? 10 : null,
});
// The exact prompt a render would be submitted with right now — the same
// composition submitGenerationPayload performs. The LoRA picker's #4665
@@ -1616,9 +1616,9 @@ export default function ImageGen() {
{referenceSlotCount > 0 && (
<ReferenceImagePicker
referenceImages={activeReferenceImages}
- showStrength={supportsReferenceStrength(effectiveMode)}
+ showStrength={supportsReferenceStrength(effectiveMode) && isFlux2Model}
caption={isLocalMode
- ? `up to ${referenceSlotCount} images for FLUX.2 multi-reference edit`
+ ? `up to ${referenceSlotCount} images for ${isQwen21Model ? 'Qwen Image 2.1' : 'FLUX.2'} multi-reference edit`
: `up to ${referenceSlotCount} more image${referenceSlotCount === 1 ? '' : 's'} ${cloudModeLabel} will use as visual references`}
onPick={handlePickReferenceImage}
onClear={handleClearReferenceImage}
diff --git a/scripts/z_image_turbo.py b/scripts/z_image_turbo.py
index d7c565282a..36b2b7907e 100644
--- a/scripts/z_image_turbo.py
+++ b/scripts/z_image_turbo.py
@@ -203,6 +203,7 @@ def parse_args() -> argparse.Namespace:
p.add_argument("--seed", type=int, default=None)
p.add_argument("--output", required=True)
p.add_argument("--metadata", action="store_true", help="write <output>.metadata.json sidecar")
+ p.add_argument("--reference-images", nargs="+", default=[], help="Qwen 2.1 reference images (10 inputs total)")
p.add_argument("--image-path", default=None, help="optional init image for i2i")
p.add_argument("--image-strength", type=float, default=None, help="0..1 i2i denoise strength")
p.add_argument("--stepwise-image-output-dir", default=None)
@@ -221,6 +222,12 @@ def parse_args() -> argparse.Namespace:
def main() -> None:
args = parse_args()
+ input_count = len(args.reference_images) + bool(args.image_path)
+ if args.reference_images and args.pipeline_class != "QwenImage21Pipeline":
+ raise ValueError("Reference images require QwenImage21Pipeline")
+ if args.pipeline_class == "QwenImage21Pipeline" and input_count > 10:
+ raise ValueError("Qwen Image 2.1 accepts at most 10 input images")
+
device = pick_device(args.device)
dtype = torch.bfloat16 if device in ("mps", "cuda") else torch.float32
@@ -261,6 +268,13 @@ def main() -> None:
)
init_image = None
+ if args.reference_images:
+ images = [init_image] if init_image is not None else []
+ for path in args.reference_images:
+ with Image.open(path) as source:
+ images.append(source.convert("RGBA"))
+ init_image = images
+
apply_memory_optimizations(pipe, width=args.width, height=args.height)
apply_loras(pipe, args.lora_paths or [], args.lora_scales or [])
diff --git a/scripts/z_image_turbo_test.py b/scripts/z_image_turbo_test.py
index 05c46d194c..923713c37c 100644
--- a/scripts/z_image_turbo_test.py
+++ b/scripts/z_image_turbo_test.py
@@ -46,8 +46,8 @@ class RunnerContract(unittest.TestCase):
)
with patch.dict(sys.modules, {'torch': torch}):
runner = importlib.import_module('z_image_turbo')
- for editing in (False, True):
- with self.subTest(editing=editing), tempfile.TemporaryDirectory() as directory:
+ for editing, references in ((False, 0), (True, 0), (False, 10), (True, 9)):
+ with self.subTest(editing=editing, references=references), tempfile.TemporaryDirectory() as directory:
source = Path(directory) / 'source.png'
output = Path(directory) / 'output.png'
Image.new('RGBA', (48, 64), (1, 2, 3, 50)).save(source)
@@ -56,6 +56,8 @@ class RunnerContract(unittest.TestCase):
'--steps', '40', '--guidance', '1', '--seed', '42', '--output', str(output)]
if editing:
argv += ['--image-path', str(source), '--image-strength', '0.5']
+ if references:
+ argv += ['--reference-images'] + [str(source)] * references
pipe = Qwen21Pipeline()
with patch.object(sys, 'argv', argv), patch.multiple(
runner, pick_device=lambda _: 'cpu',
@@ -71,7 +73,12 @@ class RunnerContract(unittest.TestCase):
runner.main()
self.assertEqual(pipe.received['steps'], 40)
self.assertEqual(pipe.received['cfg'], 1)
- if editing:
+ if references:
+ self.assertEqual(len(pipe.received['image']), 10)
+ for image in pipe.received['image']:
+ self.assertEqual(image.size, (48, 64))
+ self.assertEqual(image.getpixel((0, 0))[3], 50)
+ elif editing:
self.assertEqual(pipe.received['image'].size, (48, 64))
self.assertEqual(pipe.received['image'].getpixel((0, 0))[3], 50)
else:
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 8224b3a1a6..7345ee4658 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -84,7 +84,7 @@ async function enqueueLoggedImage(req, job) {
// number of `referenceImageN` upload field names below.
const MAX_PROMPT_LENGTH = 8000;
const MAX_LORAS = 8;
-const MAX_REFERENCE_IMAGES = 4;
+const MAX_REFERENCE_IMAGES = 10;
const MAX_IMAGE_UPLOAD_BYTES = 20 * 1024 * 1024;
const updatePromptSchema = z.object({ prompt: z.string().max(MAX_PROMPT_LENGTH) });
const galleryImageFilenameSchema = (label) => z.string().max(256)
diff --git a/server/routes/imageGen.multipart.test.js b/server/routes/imageGen.multipart.test.js
index 325333f2aa..48c660a7cc 100644
--- a/server/routes/imageGen.multipart.test.js
+++ b/server/routes/imageGen.multipart.test.js
@@ -483,6 +483,26 @@ describe('POST /api/image-gen/generate — multipart reference-image packing', (
expect(refDirContents.filter((f) => f.startsWith('ref-'))).toHaveLength(0);
});
+ it.each([false, true])('packs ten Qwen inputs and rejects an eleventh (init: %s)', async (withInit) => {
+ const fields = [
+ { name: 'prompt', value: 'Combine the references' },
+ { name: 'modelId', value: 'qwen-image-2.1' },
+ ...Array.from({ length: withInit ? 9 : 10 }, (_, i) => ({
+ name: `referenceImage${i + 1}`, filename: `ref-${i}.png`, contentType: 'image/png', value: PNG_FIXTURE,
+ })),
+ ...(withInit ? [{ name: 'initImage', filename: 'init.png', contentType: 'image/png', value: PNG_FIXTURE }] : []),
+ ];
+ const res = await postMultipart(app, '/api/image-gen/generate', fields);
+ expect(res.status).toBe(200);
+ expect(enqueueJob.mock.calls.at(-1)[0].params.referenceImagePaths).toHaveLength(withInit ? 9 : 10);
+ enqueueJob.mockClear();
+ fields.push({ name: withInit ? 'referenceImage10' : 'initImage', filename: 'extra.png', contentType: 'image/png', value: PNG_FIXTURE });
+ const rejected = await postMultipart(app, '/api/image-gen/generate', fields);
+ expect(rejected.status).toBe(400);
+ expect(rejected.body.code).toBe('TOO_MANY_INPUT_IMAGES');
+ expect(enqueueJob).not.toHaveBeenCalled();
+ });
+
it('accepts exactly the backend cap — 3 references on agy with no init image', async () => {
// The boundary the gate above must NOT reject.
mockedSettings = { imageGen: { mode: 'agy', agy: { enabled: true } } };
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 047cdb0526..5d4e7c65e5 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -116,6 +116,12 @@ export const buildArgs = ({ pythonPath, model, prompt, negativePrompt, width, he
'--seed', String(seed),
'--output', outputPath,
];
+ if (model.pipelineClass === 'QwenImage21Pipeline') {
+ if (referenceImagePaths.length + (initImagePath ? 1 : 0) > 10) {
+ throw new ServerError('Qwen Image 2.1 accepts at most 10 input images', { status: 400, code: 'TOO_MANY_INPUT_IMAGES' });
+ }
+ if (referenceImagePaths.length) args.push('--reference-images', ...referenceImagePaths);
+ }
if (negativePrompt) args.push('--negative-prompt', negativePrompt);
if (initImagePath) args.push('--image-path', initImagePath);
if (initImagePath && initImageStrength != null) args.push('--image-strength', String(initImageStrength));
diff --git a/server/services/imageGen/local.test.js b/server/services/imageGen/local.test.js
index 4097b83260..59e9d30834 100644
--- a/server/services/imageGen/local.test.js
+++ b/server/services/imageGen/local.test.js
@@ -115,6 +115,15 @@ describe('imageGen local.buildArgs flux2 dispatch', () => {
initImageStrength: null,
};
+ it('passes Qwen references in order and enforces the combined ten-image cap', () => {
+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');
+ const input = { ...baseInput, model: { id: 'qwen-image-2.1', runner: 'qwen', repo: 'Qwen/Qwen-Image-2.1', pipelineClass: 'QwenImage21Pipeline' },
+ referenceImagePaths: Array.from({ length: 10 }, (_, i) => `/tmp/ref-${i}.png`) };
+ const { args } = buildArgs(input);
+ expect(args.slice(args.indexOf('--reference-images') + 1, args.indexOf('--reference-images') + 11)).toEqual(input.referenceImagePaths);
+ expect(() => buildArgs({ ...input, initImagePath: '/tmp/init.png' })).toThrow('at most 10');
+ });
+
it('routes SDNQ flux2 models to the flux2 venv + flux2_macos.py', () => {
mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');
const { bin, args } = buildArgs({
diff --git a/server/services/imageGen/prepareParams.js b/server/services/imageGen/prepareParams.js
index 18daa95364..92e7b3ff83 100644
--- a/server/services/imageGen/prepareParams.js
+++ b/server/services/imageGen/prepareParams.js
@@ -208,10 +208,12 @@ export async function prepareGenerateParams({ data, files, referenceImageFields
const referenceImageCount = namedReferenceFiles.length + referenceUploads.length;
const inputImageCount = (initUpload || data.initImageFile ? 1 : 0) + referenceImageCount;
- if (referenceImageCount > referenceImageFields.length) {
+ const localModel = mode === IMAGE_GEN_MODE.LOCAL ? selectLocalImageModelFromSettings(settings, data.modelId) : null;
+ const referenceCap = localModel?.pipelineClass === 'QwenImage21Pipeline' ? 10 : 4;
+ if (referenceImageCount > referenceCap) {
cleanupReqFilesTemp();
throw new ServerError(
- `Image generation accepts at most ${referenceImageFields.length} reference images; received ${referenceImageCount}`,
+ `Image generation accepts at most ${referenceCap} reference images; received ${referenceImageCount}`,
{ status: 400, code: 'TOO_MANY_REFERENCE_IMAGES' },
);
}
@@ -244,18 +246,18 @@ export async function prepareGenerateParams({ data, files, referenceImageFields
// Reference images reach every backend that can consume them: local via
// local.js's buildArgs (--reference-images/--reference-strengths, emitted
- // only inside the isFlux2 branch) and each cloud CLI via its own tool's
+ // for FLUX.2, and --reference-images for Qwen 2.1) and each cloud CLI via its tool's
// reference array (codex `referenced_image_paths`, grok `image_edit.image`,
// agy `ImagePaths`). The two that CAN'T are rejected up-front rather than
// copying the uploads to PATHS.imageRefs and silently dropping them
// downstream — that would orphan files on disk and produce metadata sidecars
// that lie about how the render was conditioned.
if (referenceImageCount && mode === IMAGE_GEN_MODE.LOCAL) {
- const candidate = selectLocalImageModelFromSettings(settings, data.modelId);
- if (!isFlux2(candidate)) {
+ const candidate = localModel;
+ if (!isFlux2(candidate) && candidate?.pipelineClass !== 'QwenImage21Pipeline') {
cleanupReqFilesTemp();
throw new ServerError(
- 'Reference images are only supported for FLUX.2 models on the local backend',
+ 'Reference images are only supported for FLUX.2 and Qwen Image 2.1 models on the local backend',
{ status: 400, code: 'REFERENCE_IMAGES_FLUX2_ONLY' },
);
}
@@ -269,7 +271,7 @@ export async function prepareGenerateParams({ data, files, referenceImageFields
// so this only fires for direct API callers — but a silent drop is exactly
// the failure the sidecar-honesty rule exists to prevent. `resolveInputImages`
// keeps its own cap as the backstop for in-process callers that skip the route.
- const inputImageCap = maxInputImages(mode);
+ const inputImageCap = localModel?.pipelineClass === 'QwenImage21Pipeline' ? 10 : maxInputImages(mode);
if (inputImageCap != null && inputImageCount > inputImageCap) {
cleanupReqFilesTemp();
throw new ServerError(