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([multi-reference-image-editing-for-flux-2-ui]): FLUX.2 multi-reference image editing — UI + server contract (#298)

[._.]/ Adam Eivy2988bd2e9a69
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 8c0727221a..071edc4542 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -23,6 +23,7 @@
### Media Gen
- **Removed duplicate Universe Builder tab.** The MediaGen tab strip no longer shows a Universe Builder entry — the Create sidebar already links straight to `/universe-builder`. Legacy `/media/universe-builder/*` URLs redirect to the top-level routes so bookmarks keep working.
+- **Image Gen — multi-reference editing for FLUX.2 (UI + server contract).** A 4-slot reference-image picker appears under the Init Image block whenever a FLUX.2 model is selected. Each slot accepts a PNG/JPG/WebP upload with a 0..1 strength slider; populated slots are packed in submit order and posted as `referenceImage1`…`referenceImage4` multipart fields with a parallel `referenceStrengths` array. New `optionalUploadFields` helper in `server/lib/multipart.js`; the Image Gen route extends `generateSchema` with `referenceStrengths` (max 4 entries, 0..1 each), copies each upload into a sibling `data/image-refs/` directory (NOT the gallery) so refs never surface in the flat `.png` listing, and threads the paths + strengths through `local.js` → `buildArgs` → the FLUX.2 Python runner via `--reference-images`/`--reference-strengths`. The UI shows an "Experimental — no-op today" banner above the slot grid: the Python runner currently ignores these flags pending the `FLUX.2-klein-9B-kv` model swap (see PLAN.md `[flux2-multi-reference-python-runner]`), but accepts them as no-op argparse stubs so single-init renders still work. The route resolves the effective backend (`local` / `external` / `codex`) BEFORE staging any uploads and rejects refs with `REFERENCE_IMAGES_LOCAL_ONLY` for non-local backends + `REFERENCE_IMAGES_FLUX2_ONLY` for non-FLUX.2 models — both gates also unlink the multer-staged temp files before throwing, so a rejected request doesn't leak under `os.tmpdir()`.
### Sharing
diff --git a/DONE.md b/DONE.md
index 47d5c5e91c..647a0e80d3 100644
--- a/DONE.md
+++ b/DONE.md
@@ -20,6 +20,7 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./
- **[extract-upsertbyidprepend-helper-universe-builder] Extract `upsertByIdPrepend(list, item)` helper.** New `client/src/lib/upsertByIdPrepend.js` collapses the "filter-by-id then prepend" worlds-list upsert into one helper. The PLAN line called out 3 sites; the actual count was 7 — all collapsed to `setWorlds((prev) => upsertByIdPrepend(prev, entity))`: 1 in `client/src/hooks/useUniverseAction.js` (LLM-action result merge) + 6 in `client/src/pages/UniverseBuilder.jsx` (`handleCreate`, `handleSave`, expand auto-save, refine auto-save, `handleMoveCategoryToTrunk`, `handleGenerateInCategory`). 4 new vitest cases in `upsertByIdPrepend.test.js` (new-id prepend, id replacement, empty-list, no input mutation).
- **[universe-builder-redesign-trunks-sub-buckets] Universe Builder redesign — trunks + sub-buckets layout (Phases A–D + Phase C follow-ups).** Multi-phase rewrite landing across 2026-05-15 → 2026-05-17. Phase A added a `kind: 'characters'|'settings'|'objects'|'other'` field to every category bucket + a migration to backfill the built-in defaults; Phase B taught `buildExpansionPrompt()` + `isExpansionShape()` to emit and accept rich canon arrays alongside categories, with client-side `handleExpand` merging canon entries into `universe.{characters,settings,objects}` (dedupe by name, respect locks); Phase C rewrote the page as a tabbed-trunk layout (Bible / Cast / Places / Objects / Other / Composites / Render) with URL state, a unified `EntryCard` rendering both canon entries and category variations, and per-trunk / per-bucket / all-canon batch-render targeting; Phase D shipped `POST /:id/promote-variation` to LLM-expand a variation into a full canon entry (atomic canon append + variation removal in one `updateUniverse` patch, duplicate-name 409 before the LLM call, trunk picker for `kind: 'other'` buckets). Phase C follow-ups closed today: (1) `updateUniverse(id, mutator)` now accepts an async `mutator(latest) => patch` callback that runs INSIDE `queueUniverseWrite` — `autoSortOtherBuckets` and `promoteVariationToCanon` route their read-modify-write through this so a slow LLM call can't admit a concurrent edit between read and persist; promote's variation removal also re-locates by label inside the queue rather than relying on the stale pre-LLM index, and the duplicate-name 409 is re-checked against the latest canon (returns `UNIVERSE_PROMOTE_CATEGORY_GONE` / `UNIVERSE_PROMOTE_VARIATION_GONE` when the bucket/variation disappears mid-flight); (2) `handleAutoSort` / `handlePromoteVariation` / `handleGenerateInCategory` now flush a dirty draft via `handleSave()` before kicking off — `UniverseBuilder.jsx` tracks a `savedDraftSnapshotRef` baseline (compared via `draftSnapshotForDirty`) that updates on universe-load, manual save, expand auto-save, refine auto-save, generate auto-save, and after each LLM mutator's `onFreshResult` merge. `useUniverseAction` gained a `preflight` option that runs AFTER the ref/savedId guard so double-clicks short-circuit before flushing. 5 new server tests (`updateUniverse` mutator overload — happy path, null-skip, throw-propagation, non-object validation, queue-ordering against a parallel literal-patch write) + 4 new client tests (`useUniverseAction` preflight — returns-false abort, throw-as-false, returns-true continue, post-ref-guard ordering).
- **[canoncard-from-series-name-full-provenance-label] CanonCard "from series: <name>" full provenance label.** The provenance chip now reads `seriesNameMap?.[entry.sourceSeriesId]` to render `from <Series Name>` with `Introduced by series "<name>" (<id>)` in the tooltip; missing-name fallback preserves the existing `from series` label + id-only tooltip. Chip rendering extracted into a `SourceSeriesChip` helper alongside `ChipPicker` / `ReadonlyChip` in `client/src/components/pipeline/CanonCard.jsx`. Map plumbed from both parents: `UniverseCanonSection.jsx` passes `usage?.seriesNameMap` (no new fetch — reuses the canon-usage call it already makes), and `NounsStage.jsx` fetches `getUniverseCanonUsage(series.universeId)` once on universe load. Server-side `getUniverseCanonUsage` (`server/services/canonUsage.js`) gains a top-level `seriesNameMap: { [seriesId]: name }` field built from every `linkedSeries` (not just ones with prose-match rows) so an entry whose `sourceSeriesId` points at a series with no matching prose still resolves to a name. Coverage: 4 new vitest cases in `CanonCard.test.jsx` (chip omitted with no `sourceSeriesId`; generic fallback when map missing; resolved name + dual-tooltip when present; fallback when id not in map) and 2 new `canonUsage.test.js` cases (linked-with-no-prose-match included; empty map when no series link). NounsStage's per-render fetch is acknowledged as quadratic-cost relative to need; deferred to `[nounsstage-cheaper-seriesnamemap-fetch]` for a thin-endpoint follow-up.
+- **[multi-reference-image-editing-for-flux-2-ui] Multi-reference image editing for FLUX.2 — UI + server contract.** New 4-slot reference-image picker on the Image Gen page, gated on FLUX.2 models (`isFlux2Model`). Each populated slot uploads as `referenceImage1`…`referenceImage4` over multipart with a parallel `referenceStrengths` array (0..1 per slot). Server-side: `optionalUploadFields` helper added to `server/lib/multipart.js`; `generateSchema` in `server/routes/imageGen.js` accepts the new `referenceStrengths` array (max 4, 0..1 per entry); the route resolves the effective backend (`local` / `external` / `codex`) BEFORE staging any uploads and rejects with `REFERENCE_IMAGES_LOCAL_ONLY` for non-local backends + `REFERENCE_IMAGES_FLUX2_ONLY` for non-FLUX.2 models (no orphan files written; both pre-stage rejects also unlink the multer-staged `os.tmpdir()` files). It then packs filled slots in submit order, copies each into a sibling `data/image-refs/ref-<uuid>.<ext>` directory (kept out of `data/images/` so the gallery's flat `.png` enumeration never surfaces them), and threads `referenceImagePaths`/`referenceImageStrengths` arrays through `server/services/imageGen/local.js` to `buildArgs`, which emits `--reference-images <p1> <p2> ...` + `--reference-strengths <s1> ...` to the FLUX.2 Python runner. Defense-in-depth: a new `resolveImageRef` helper in `fileUtils.js` mirrors `resolveGalleryImage` but anchors at `PATHS.imageRefs`; paths and strengths are paired BEFORE filtering so a rejected entry can't shift strengths onto the wrong surviving image; the `clampStrength01` helper falls back to a finite default for NaN/non-finite inputs so a corrupt sidecar replay can't serialize `NaN` into metadata or the CLI flag; sidecar metadata records `referenceImageFilenames`/`referenceImageStrengths` for replay. The UI shows an "Experimental — no-op today" banner above the slot grid: the Python runner ignores the new flags but accepts them via no-op `--reference-images`/`--reference-strengths` argparse stubs in `scripts/flux2_macos.py` — without those the route would break every existing single-init FLUX.2 render with "unrecognized arguments." Full multi-reference diffusers wiring + the `FLUX.2-klein-9B-kv` model swap is captured as `[flux2-multi-reference-python-runner]` in PLAN.md (gated on HF license acceptance). 12 new tests: 3 in `local.test.js` (buildArgs multi-ref branches), 3 in `imageGen.test.js` (schema validation), 6 in `imageGen.multipart.test.js` (real-multipart route packing — verifies `referenceImagePaths`/`referenceImageStrengths` land in submit order, gaps in slot numbering collapse to a packed array via post-filter index pairing, missing strengths default to 1.0, ref files land in `PATHS.imageRefs` not `PATHS.images`, a non-FLUX.2 modelId with refs gets a 400 before any file is staged, refs on a non-local backend get a 400, AND rejected non-FLUX.2 uploads don't leak `upload-*` files under `os.tmpdir()`).
- **[extract-useuniverseaction-hook] Extract `useUniverseAction` hook from `UniverseBuilder.jsx`.** New `client/src/hooks/useUniverseAction.js` consolidates the scaffolding shared by `handlePromoteVariation` + `handleAutoSort`: `selectedId` guard, per-action ref re-entrancy, `capturedId` snapshot, loading-toast lifecycle (`silent: true` + `.catch` → dismiss + error), mountedRef-gated busy reset, always-update `setWorlds`, and the `mountedRef.current && capturedId === selectedId` stale-write guard. Each caller now passes only what varies — its `ref`/`setBusy`/`loadingMessage`/`errorPrefix`/`notSavedMessage`, the API call (receives `capturedId`), and an `onFreshResult(result)` callback that does the selective `setDraft` and returns the success-toast string. `handleGenerateInCategory` is intentionally NOT a consumer (the PLAN line's "to a lesser extent" — eager local merge first + best-effort save is a different shape; forcing it through would warp it); the hook header documents this. 9 new vitest cases in `useUniverseAction.test.jsx` (selectedId guard, re-entrancy, happy path, stale-write, action-rejects, no-loading-toast variant, falsy-universe result, suppressed-toast onFreshResult, unmount mid-flight). PLAN.md description gated this on "extract when a 4th handler lands"; promoted now with 3 — the hook itself is small and the scaffold is the most-bug-prone piece of these handlers.
- **[extract-builduniversestylecontext-helper] Extract `buildUniverseStyleContext(universe, options)` helper.** New helper in `server/services/universeBuilder.js` (next to `joinInfluenceList`) renders the shared "Universe context" prompt block (LOGLINE / optional PREMISE / STYLE NOTES / optional EMBRACE INFLUENCES). Three call sites collapsed: `buildAutoSortPrompt` (`universeBuilderAutoSort.js`, `escape: true`), `buildPromotePrompt` (`universeBuilderPromote.js`, default opts + headerSuffix), and `buildCategoryGeneratePrompt` (`universeBuilderExpand.js`, `includePremise: true` + `includeEmbrace: false` since it has its own influences section). Toggles cover the actual variance: `includePremise`, `includeEmbrace`, `escape` (newline/control-char stripping for defense-in-depth), `headerSuffix` (per-call header framing). 9 new unit tests in `universeBuilder.test.js` assert byte-exact outputs for each call shape. Pipeline call sites at `visualStages.js` and `seriesTitleLogo.js` were inspected but are out of scope — they only use `joinInfluenceList` for render-style composition and template variables, not the LOGLINE/STYLE NOTES/EMBRACE block. `buildExpansionPrompt`'s "Current universe state" block also stays separate — its `[LOCKED]` flags + `LOCKABLE_FIELD_LABELS` make it too distinct to fold without compromising the helper.
- **[extract-descriptorforcanonentry-kind-entry-into] Extract `descriptorForCanonEntry(kind, entry)` into `server/lib/canonPrompt.js` (mirror in client).** New `server/lib/canonPrompt.js` + `client/src/lib/canonPrompt.js` mirror is the single source of truth for per-kind canon descriptor fields. Exports `shortCanonDescriptorFragments` (UI summary scope: physicalDescription || description for chars; description + Palette + recurringDetails for settings; description || significance for objects), `richCanonDescriptorFragments` (adds role, era, weather, significance-as-additive — the render-prompt scope), `descriptorForCanonEntry` (flattened short string matching legacy `KINDS[].descFor`), and `hasCanonDescriptorContent` (rich-field union for "is there anything to render?" gates). Migrated four call sites: `synthesizeCanonPrompt` (`server/services/universeBuilder.js`), `KINDS[].descFor` (`client/src/components/universe/UniverseCanonSection.jsx`), `canonEntryHasContent` (`client/src/pages/UniverseBuilder.jsx`), and `settingFrags` in `server/lib/scenePrompt.js` + client mirror. Tests: 29 new in `server/lib/canonPrompt.test.js`. Minor cosmetic uniformity in canon render prompts: lowercase `palette:`/`era:`/`weather:`/`significance:` prefixes are now capitalized (`Palette:` etc.) to match the UI descriptor format — case-only diff, no functional impact on diffusion models.
diff --git a/PLAN.md b/PLAN.md
index 08dfcf1344..826c26675b 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -93,7 +93,7 @@ _Nothing currently parked — pick the next item from the Backlog._
### Image / Video Gen UI
-- [ ] [multi-reference-image-editing-for-flux-2-ui] **Multi-reference image editing for FLUX.2.** UI accepting 2+ reference images + edit prompt. Swap registry's 9B entry to `FLUX.2-klein-9B-kv` for 2.5× speedup on multi-reference workflows. Gated repo — request access.
+- [ ] [flux2-multi-reference-python-runner] **FLUX.2 multi-reference Python runner.** The UI + server contract for multi-reference editing shipped 2026-05-17 (slug `multi-reference-image-editing-for-flux-2-ui`); the Python runner (`scripts/flux2_macos.py`) currently ignores the `--reference-images`/`--reference-strengths` args that `local.js` now passes. Wire diffusers' multi-reference API in the runner and swap `server/lib/mediaModels.js#flux2-klein-9b` `tokenizerRepo` to `FLUX.2-klein-9B-kv` (gated repo — requires the user to accept the license on HF). Validate end-to-end with 2–4 uploaded refs.
- [ ] [world-builder-phase-2-external-sd-api-per-bucket] **World Builder Phase 2 — external SD-API + per-bucket model overrides.** Wire Together / Replicate / Fal into world-builder batch path so high-end renders are practical; let each bucket pick its own model.
- [ ] [unify-videogen-resolutions-with-shared-image-gen] **Unify VideoGen `RESOLUTIONS` with shared image-gen list.** Move to `client/src/lib/videoGenResolutions.js` (or extend imageGenResolutions with `media: 'image'|'video'`) so dropdown + custom-fallback live in one place.
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index 90bacc7906..6b0e729208 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -44,6 +44,12 @@ import { safeParseJSON } from '../lib/genUtils';
const DEFAULT_NEGATIVE = 'blurry, low quality, distorted, deformed, ugly, watermark, text, signature';
+// Multi-reference editing (FLUX.2 only) — 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.
+const REFERENCE_SLOT_COUNT = 4;
+const EMPTY_REF_SLOT = { file: null, previewUrl: null, strength: 1.0 };
+
// Append LoRA trigger words to a prompt comma-separated, skipping any
// already present. Compares against comma-separated prompt segments rather
// than raw substrings so a short trigger like "cat" doesn't false-match
@@ -135,6 +141,9 @@ export default function ImageGen() {
// the whole object so previewUrl can never out-live its file/name.
const [initImage, setInitImage] = useState({ source: null, file: null, name: null, previewUrl: null });
const [initImageStrength, setInitImageStrength] = useState(0.4);
+ // Form posts populated slots as `referenceImage1` … `referenceImage4`
+ // multipart fields with a parallel `referenceStrengths` array.
+ const [referenceImages, setReferenceImages] = useState(() => Array.from({ length: REFERENCE_SLOT_COUNT }, () => ({ ...EMPTY_REF_SLOT })));
// Batch size: how many renders this submit kicks off. Only meaningful for
// async modes (local + codex); external is synchronous and runs N=1.
@@ -368,10 +377,54 @@ export default function ImageGen() {
if (initImage.previewUrl?.startsWith('blob:')) URL.revokeObjectURL(initImage.previewUrl);
setInitImage({ source: null, file: null, name: null, previewUrl: null });
};
- // Object URL cleanup on unmount.
+
+ const handlePickReferenceImage = async (slotIndex, e) => {
+ const raw = e.target.files?.[0];
+ if (!raw) return;
+ const file = await normalizeImageOrientation(raw);
+ setReferenceImages((prev) => {
+ const next = [...prev];
+ const prior = next[slotIndex];
+ if (prior?.previewUrl?.startsWith('blob:')) URL.revokeObjectURL(prior.previewUrl);
+ next[slotIndex] = { file, previewUrl: URL.createObjectURL(file), strength: prior?.strength ?? 1.0 };
+ return next;
+ });
+ };
+ const handleClearReferenceImage = (slotIndex) => {
+ setReferenceImages((prev) => {
+ const next = [...prev];
+ const prior = next[slotIndex];
+ if (prior?.previewUrl?.startsWith('blob:')) URL.revokeObjectURL(prior.previewUrl);
+ next[slotIndex] = { ...EMPTY_REF_SLOT };
+ return next;
+ });
+ };
+ const handleReferenceStrengthChange = (slotIndex, strength) => {
+ setReferenceImages((prev) => {
+ const next = [...prev];
+ next[slotIndex] = { ...next[slotIndex], strength };
+ return next;
+ });
+ };
+
+ // Object URL cleanup on unmount — both the single init image and any
+ // populated reference slots. Mirror the live URLs into a ref so the
+ // empty-deps unmount cleanup walks the LATEST set, not the initial empty
+ // closure snapshot (per-action handlers already revoke when a slot is
+ // replaced/cleared; this catches the one held at unmount).
+ const previewUrlsRef = useRef({ init: null, refs: [] });
+ useEffect(() => {
+ previewUrlsRef.current = {
+ init: initImage.previewUrl,
+ refs: referenceImages.map((s) => s.previewUrl),
+ };
+ });
useEffect(() => () => {
- if (initImage.previewUrl?.startsWith('blob:')) URL.revokeObjectURL(initImage.previewUrl);
- // eslint-disable-next-line react-hooks/exhaustive-deps
+ const { init, refs } = previewUrlsRef.current;
+ if (init?.startsWith('blob:')) URL.revokeObjectURL(init);
+ for (const url of refs) {
+ if (url?.startsWith('blob:')) URL.revokeObjectURL(url);
+ }
}, []);
// When the user closes the Settings drawer, settings may have changed
@@ -512,12 +565,24 @@ export default function ImageGen() {
mode: 'local',
};
const hasInitImage = isLocalMode && initImage.source != null;
- if (hasInitImage) {
- const fd = buildFormData({
- ...payload,
+ // Multi-reference editing is FLUX.2-only; gate the slot read so it can't
+ // accidentally fire on mflux or codex, and pack the populated slots so a
+ // gap (e.g. slots 1,3 filled, 2 empty) collapses to a packed two-image
+ // submit that aligns with the server's positional pairing.
+ const populatedRefs = (isLocalMode && isFlux2Model)
+ ? referenceImages.filter((s) => s.file != null)
+ : [];
+ const hasReferenceImages = populatedRefs.length > 0;
+ if (hasInitImage || hasReferenceImages) {
+ const initFields = hasInitImage ? {
...(initImage.source === 'upload' ? { initImage: initImage.file } : { initImageFile: initImage.name }),
initImageStrength,
- });
+ } : {};
+ const refFields = hasReferenceImages ? {
+ ...Object.fromEntries(populatedRefs.map((slot, i) => [`referenceImage${i + 1}`, slot.file])),
+ referenceStrengths: populatedRefs.map((s) => s.strength),
+ } : {};
+ const fd = buildFormData({ ...payload, ...initFields, ...refFields });
const res = await fetch('/api/image-gen/generate', { method: 'POST', body: fd });
if (!res.ok) {
const body = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));
@@ -941,6 +1006,86 @@ export default function ImageGen() {
</div>
)}
+ {isLocalMode && isFlux2Model && (
+ <div>
+ <label className="block text-xs font-medium text-gray-400 mb-1">
+ Reference images <span className="text-gray-500 font-normal">(up to 4 images for FLUX.2 multi-reference edit)</span>
+ </label>
+ {/*
+ Experimental: the server contract (upload slots, packing, sidecar
+ metadata, CLI flag emission) is wired end-to-end, but the bundled
+ FLUX.2 Python runner currently accepts `--reference-images` /
+ `--reference-strengths` as no-op argparse stubs — the references
+ are NOT yet conditioned into the diffusion graph. Full multi-ref
+ inference is tracked as `[flux2-multi-reference-python-runner]`
+ in PLAN.md (gated on the FLUX.2-klein-9B-kv HF license).
+ */}
+ <div className="mb-2 px-2 py-1.5 text-[11px] text-port-warning/90 bg-port-warning/10 border border-port-warning/30 rounded">
+ <strong className="font-semibold">Experimental — no-op today:</strong> Uploads + strengths are
+ staged and forwarded to the runner, but the FLUX.2 Python script ignores them. Final inference wiring
+ is pending the multi-reference runner upgrade.
+ </div>
+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
+ {referenceImages.map((slot, i) => {
+ const slotId = `ref-image-${i}`;
+ const strengthId = `ref-strength-${i}`;
+ return (
+ <div key={i} className="flex flex-col gap-1 p-2 rounded-lg border border-port-border bg-port-bg/30">
+ <div className="text-[10px] uppercase tracking-wide text-gray-500">Ref {i + 1}</div>
+ {slot.previewUrl ? (
+ <>
+ <div className="relative">
+ <img
+ src={slot.previewUrl}
+ alt={`Reference ${i + 1}`}
+ className="w-full h-16 object-cover rounded border border-port-border bg-port-bg"
+ />
+ <button
+ type="button"
+ onClick={() => handleClearReferenceImage(i)}
+ disabled={statusLoading}
+ className="absolute -top-1.5 -right-1.5 w-5 h-5 rounded-full bg-port-card border border-port-border text-gray-300 hover:text-white hover:bg-port-error/40 flex items-center justify-center disabled:opacity-50"
+ title={`Remove reference ${i + 1}`}
+ >
+ <X className="w-3 h-3" />
+ </button>
+ </div>
+ <label htmlFor={strengthId} className="block text-[10px] text-gray-500">
+ Strength {slot.strength.toFixed(2)}
+ </label>
+ <input
+ id={strengthId}
+ type="range" min={0} max={1} step={0.05}
+ value={slot.strength}
+ disabled={statusLoading}
+ onChange={(e) => handleReferenceStrengthChange(i, Number(e.target.value))}
+ className="w-full accent-port-accent"
+ />
+ </>
+ ) : (
+ <label
+ htmlFor={slotId}
+ className="flex flex-col items-center justify-center gap-1 h-[88px] border border-dashed border-port-border rounded text-[10px] text-gray-500 hover:text-white hover:border-port-accent cursor-pointer transition-colors"
+ >
+ <ImageIcon className="w-4 h-4" />
+ Add
+ <input
+ id={slotId}
+ type="file"
+ accept="image/png,image/jpeg,image/webp"
+ className="hidden"
+ onChange={(e) => handlePickReferenceImage(i, e)}
+ disabled={statusLoading}
+ />
+ </label>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ )}
+
<div className="flex items-center gap-2 pt-1 flex-wrap">
<button
type="submit"
diff --git a/scripts/flux2_macos.py b/scripts/flux2_macos.py
index 264e4d2c3a..eacead4ea9 100755
--- a/scripts/flux2_macos.py
+++ b/scripts/flux2_macos.py
@@ -212,6 +212,14 @@ def parse_args() -> argparse.Namespace:
p.add_argument("--device", default="auto", choices=["auto", "mps", "cuda", "cpu"])
p.add_argument("--lora-paths", nargs="*", default=[], help="absolute paths to LoRA .safetensors files")
p.add_argument("--lora-scales", nargs="*", default=[], help="scale per LoRA, parallel to --lora-paths")
+ # Multi-reference editing — accepted but currently ignored. The Node side
+ # already plumbs these end-to-end so the UI + server contract is shippable;
+ # the diffusers multi-reference pipeline wiring lands with the
+ # FLUX.2-klein-9B-kv model swap (see PLAN.md `flux2-multi-reference-python-runner`).
+ # Without these stubs argparse would reject the args with "unrecognized
+ # arguments" and break every single-init FLUX.2 render once the route is live.
+ p.add_argument("--reference-images", nargs="*", default=[], help="(reserved) absolute paths to reference images")
+ p.add_argument("--reference-strengths", nargs="*", default=[], help="(reserved) 0..1 strength per reference image, parallel to --reference-images")
return p.parse_args()
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index c48ac31e13..e94ba49952 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -63,6 +63,11 @@ export const PATHS = {
missions: join(__lib_dirname, '../../data/cos/missions'),
tools: join(__lib_dirname, '../../data/tools'),
images: join(__lib_dirname, '../../data/images'),
+ // Uploaded multi-reference inputs for FLUX.2 multi-ref edits. Sibling of
+ // `images/` rather than a subdir so the gallery's flat `.png` enumeration
+ // never surfaces them, and so a future per-render cleanup pass can drop
+ // the whole dir without touching the gallery.
+ imageRefs: join(__lib_dirname, '../../data/image-refs'),
loras: join(__lib_dirname, '../../data/loras'),
videos: join(__lib_dirname, '../../data/videos'),
videoThumbnails: join(__lib_dirname, '../../data/video-thumbnails'),
@@ -641,6 +646,34 @@ export function resolveGalleryImage(name, { mustExist = true } = {}) {
}
}
+/**
+ * Resolve a user-supplied reference-image filename to an absolute path under
+ * `PATHS.imageRefs`. Multi-reference uploads land in a sibling dir to keep
+ * them out of the gallery enumeration; this helper enforces the same
+ * defense-in-depth checks as `resolveGalleryImage` but anchored at the refs
+ * root.
+ *
+ * @param {string} name - Filename to resolve (basenamed internally)
+ * @param {object} [opts]
+ * @param {boolean} [opts.mustExist=true] - Require the resolved path to be an existing regular file
+ * @returns {string|null} Absolute path inside PATHS.imageRefs, or null
+ */
+export function resolveImageRef(name, { mustExist = true } = {}) {
+ if (typeof name !== 'string' || !name) return null;
+ const safe = basename(name);
+ if (!safe || safe === '.' || safe === '..') return null;
+ const refsRoot = resolvePath(PATHS.imageRefs) + PATH_SEP;
+ const localPath = resolvePath(join(PATHS.imageRefs, safe));
+ if (!localPath.startsWith(refsRoot)) return null;
+ if (!mustExist) return localPath;
+ try {
+ const stat = statSync(localPath, { throwIfNoEntry: false });
+ return stat?.isFile() ? localPath : null;
+ } catch {
+ return null;
+ }
+}
+
/**
* List a directory, keep entries whose extension matches `extensions`, stat
* each, and project the survivors through `mapEntry(name, fullPath, stat)`.
diff --git a/server/lib/multipart.js b/server/lib/multipart.js
index 5216536dce..9da28da838 100644
--- a/server/lib/multipart.js
+++ b/server/lib/multipart.js
@@ -85,6 +85,18 @@ export function optionalUpload(fieldName, opts) {
};
}
+// Multi-field version of optionalUpload — same JSON-body passthrough, but
+// accepts the uploadFields field-name list. Files land on req.files keyed by
+// field name; non-multipart JSON requests skip the parser entirely.
+export function optionalUploadFields(fieldNames, opts) {
+ const uploader = uploadFields(fieldNames, opts);
+ return (req, res, next) => {
+ const ct = req.headers['content-type'] || '';
+ if (!ct.toLowerCase().startsWith('multipart/form-data')) return next();
+ return uploader(req, res, next);
+ };
+}
+
function streamMultipart(req, boundary, acceptedNames, maxSize, fileFilter, next) {
const PART_DELIM = Buffer.from('\r\n--' + boundary);
const FIRST_DELIM = Buffer.from('--' + boundary);
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 5e999d8362..e8f8b74961 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -17,7 +17,7 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import {
validateRequest, imageEdgeSchema, refineImagePixelCap, PIXEL_CAP_MESSAGE,
} from '../lib/validation.js';
-import { optionalUpload } from '../lib/multipart.js';
+import { optionalUploadFields } from '../lib/multipart.js';
import * as imageGen from '../services/imageGen/index.js';
import { local, IMAGE_GEN_MODES } from '../services/imageGen/index.js';
import { enqueueJob, attachSseClient as attachQueueSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';
@@ -66,6 +66,13 @@ const generateSchema = z.object({
// upload. Strength: 0.0 = ignore source, 1.0 = max influence.
initImageFile: z.string().max(256).regex(/^[^/\\]+\.(png|jpg|jpeg|webp)$/i, 'init image must be a basename ending in png/jpg/jpeg/webp').optional(),
initImageStrength: z.number().min(0).max(1).optional(),
+ // Multi-reference image editing (FLUX.2). Up to 4 reference images are
+ // uploaded as separate multipart fields `referenceImage1` … `referenceImage4`;
+ // `referenceStrengths` is a parallel array of weights (0.0 = ignore the
+ // reference, 1.0 = full influence). The schema only constrains the strengths
+ // array — file presence is enforced at the upload layer, and the route
+ // pairs filled slots with their strengths positionally.
+ referenceStrengths: z.array(z.number().min(0).max(1)).max(4).optional(),
}).refine(refineImagePixelCap, { message: PIXEL_CAP_MESSAGE, path: ['width'] });
// JSON callers (SDAPI bridge, avatar route, the Imagine page's old payload
@@ -77,18 +84,30 @@ const generateSchema = z.object({
const ACCEPTED_INIT_IMAGE_MIME = new Set(['image/png', 'image/jpeg', 'image/webp']);
const MIME_TO_EXT = { 'image/png': '.png', 'image/jpeg': '.jpg', 'image/webp': '.webp' };
-const initImageUpload = optionalUpload('initImage', {
+// Multi-reference editing accepts up to 4 references on dedicated field names.
+// The legacy single `initImage` upload (mflux i2i) stays on its own slot so a
+// FLUX.2 multi-ref upload and an mflux i2i upload don't collide.
+const REFERENCE_IMAGE_FIELDS = ['referenceImage1', 'referenceImage2', 'referenceImage3', 'referenceImage4'];
+const IMAGE_UPLOAD_FIELDS = ['initImage', ...REFERENCE_IMAGE_FIELDS];
+
+const imageGenUploads = optionalUploadFields(IMAGE_UPLOAD_FIELDS, {
limits: { fileSize: 20 * 1024 * 1024 },
fileFilter: (_req, file, cb) => cb(null, ACCEPTED_INIT_IMAGE_MIME.has((file.mimetype || '').toLowerCase())),
});
// Numerics arrive as strings from FormData — coerce before Zod validation.
+// `referenceStrengths` is a repeated key (one per slot), which arrives as a
+// string OR an array of strings; coerce element-wise so Zod sees numbers.
function coerceFormFields(body) {
const numericFields = ['width', 'height', 'steps', 'cfgScale', 'guidance', 'seed', 'initImageStrength'];
for (const f of numericFields) {
if (typeof body[f] === 'string' && body[f] !== '') body[f] = Number(body[f]);
}
if (typeof body.quantize === 'string' && /^\d+$/.test(body.quantize)) body.quantize = Number(body.quantize);
+ if (body.referenceStrengths != null) {
+ const raw = Array.isArray(body.referenceStrengths) ? body.referenceStrengths : [body.referenceStrengths];
+ body.referenceStrengths = raw.map((v) => (typeof v === 'string' && v !== '' ? Number(v) : v));
+ }
return body;
}
@@ -128,22 +147,83 @@ const queuedImageResponse = ({ jobId, position, status, mode, model }) => ({
position,
});
-router.post('/generate', initImageUpload, asyncHandler(async (req, res) => {
+router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {
const data = validateRequest(generateSchema, coerceFormFields(req.body));
// Resolve init image source: uploaded file > gallery filename. The local
// service double-checks that the path stays under PATHS.images.
let initImagePath = null;
- let uploadedInitTempPath = null;
- if (req.file) {
- await ensureDir(PATHS.images);
+ const uploadedTempPaths = [];
+ const initUpload = req.files?.initImage;
+ const referenceImagePaths = [];
+ const referenceImageStrengths = [];
+ // Pair strengths by PACK position (post-filter), not slot position — the
+ // client renumbers populated slots into `referenceImage1..N` and sends a
+ // parallel `referenceStrengths` array sized N. A curl user could leave a
+ // gap (`referenceImage2` + `referenceImage4` only); the strength at index 0
+ // still pairs with the first surviving upload in slot order.
+ const referenceUploads = REFERENCE_IMAGE_FIELDS
+ .map((field) => req.files?.[field])
+ .filter(Boolean)
+ .map((upload, packedIndex) => ({ upload, strength: data.referenceStrengths?.[packedIndex] }));
+
+ // Best-effort cleanup of every multer-staged file currently on `req.files`.
+ // The multipart parser writes uploads to `os.tmpdir()` as they stream in,
+ // so a 400 thrown from validation BEFORE we've registered the `res.on('close')`
+ // sweep would otherwise leak those temp files. Call this from any pre-stage
+ // throw site (FLUX.2-only gate, non-local-backend gate).
+ const cleanupReqFilesTemp = () => {
+ if (!req.files) return;
+ for (const f of Object.values(req.files)) {
+ if (f?.path) unlink(f.path).catch(() => {});
+ }
+ };
+
+ // Resolve the effective backend BEFORE staging reference uploads — only the
+ // local FLUX.2 runner consumes `referenceImagePaths`; an `external` or `codex`
+ // request that uploaded refs would otherwise stage files under
+ // `PATHS.imageRefs` and write sidecar metadata claiming references were used,
+ // while the actual generation silently ignored them. (Reading settings here
+ // is cheap — it's already read again below for the per-mode dispatch.)
+ const settings = await getSettings();
+ const mode = data.mode || settings.imageGen?.mode || 'external';
+
+ // Multi-reference is a FLUX.2-only, local-backend-only feature — local.js's
+ // buildArgs only emits --reference-images/--reference-strengths inside the
+ // isFlux2 branch, and codex/external backends don't read these fields at all.
+ // Reject up-front rather than copying the uploads to PATHS.imageRefs and
+ // silently dropping them downstream (which would orphan files on disk and
+ // produce metadata sidecars that lie about how the render was conditioned).
+ if (referenceUploads.length) {
+ if (mode !== 'local') {
+ cleanupReqFilesTemp();
+ throw new ServerError(
+ 'Reference images are only supported for local FLUX.2 renders',
+ { status: 400, code: 'REFERENCE_IMAGES_LOCAL_ONLY' },
+ );
+ }
+ const candidate = getImageModels().find((m) => m.id === data.modelId)
+ ?? getImageModels().find((m) => m.id === 'dev')
+ ?? getImageModels()[0];
+ if (!isFlux2(candidate)) {
+ cleanupReqFilesTemp();
+ throw new ServerError(
+ 'Reference images are only supported for FLUX.2 models',
+ { status: 400, code: 'REFERENCE_IMAGES_FLUX2_ONLY' },
+ );
+ }
+ }
+
+ if (initUpload) await ensureDir(PATHS.images);
+ if (referenceUploads.length) await ensureDir(PATHS.imageRefs);
+ if (initUpload) {
// Trust the validated mimetype from the fileFilter — picking the ext
// off the original filename can mismatch the bytes (e.g. HEIC saved
// as .jpg). MIME_TO_EXT only contains formats the fileFilter accepts.
- const ext = MIME_TO_EXT[(req.file.mimetype || '').toLowerCase()] || '.png';
+ const ext = MIME_TO_EXT[(initUpload.mimetype || '').toLowerCase()] || '.png';
const initFilename = `init-${randomUUID()}${ext}`;
initImagePath = join(PATHS.images, initFilename);
- await copyFile(req.file.path, initImagePath);
- uploadedInitTempPath = req.file.path;
+ await copyFile(initUpload.path, initImagePath);
+ uploadedTempPaths.push(initUpload.path);
} else if (data.initImageFile) {
const resolved = resolveGalleryImage(data.initImageFile);
if (!resolved) {
@@ -151,25 +231,47 @@ router.post('/generate', initImageUpload, asyncHandler(async (req, res) => {
}
initImagePath = resolved;
}
- // Strip the route-only `initImageFile` field — providers expect `initImagePath`.
+ // Multi-reference editing (FLUX.2). Walk packed slot entries in submit
+ // order — each contributes a path + its parallel strength. Empty slots
+ // are filtered out above so the runner sees `referenceImagePaths: [p1, ...]`
+ // and aligns strengths by index.
+ for (const { upload, strength } of referenceUploads) {
+ const ext = MIME_TO_EXT[(upload.mimetype || '').toLowerCase()] || '.png';
+ const refFilename = `ref-${randomUUID()}${ext}`;
+ const refPath = join(PATHS.imageRefs, refFilename);
+ await copyFile(upload.path, refPath);
+ uploadedTempPaths.push(upload.path);
+ referenceImagePaths.push(refPath);
+ // Default to 1.0 when the client didn't send a parallel strength entry,
+ // matching the "full influence" intent of an uploaded reference.
+ referenceImageStrengths.push(typeof strength === 'number' ? strength : 1.0);
+ }
+ // Strip the route-only fields — providers expect normalized `…Path(s)`.
delete data.initImageFile;
+ delete data.referenceStrengths;
if (initImagePath) data.initImagePath = initImagePath;
+ if (referenceImagePaths.length) {
+ data.referenceImagePaths = referenceImagePaths;
+ data.referenceImageStrengths = referenceImageStrengths;
+ }
if (data.guidance == null && data.cfgScale != null) {
data.guidance = data.cfgScale;
}
// Multer's tmp upload is no longer needed once we've copied it into
- // PATHS.images. Use res.on('close') so the temp file is cleaned up whether
+ // PATHS.images. Use res.on('close') so the temp files are cleaned up whether
// generateImage resolves, throws (handled by errorHandler middleware), or
// the client drops the connection mid-flight.
- if (uploadedInitTempPath) {
- res.on('close', () => { unlink(uploadedInitTempPath).catch(() => {}); });
+ if (uploadedTempPaths.length) {
+ res.on('close', () => {
+ for (const p of uploadedTempPaths) unlink(p).catch(() => {});
+ });
}
// Local + codex both go through mediaJobQueue (separate lanes — codex
// doesn't share MLX). External SD-API stays synchronous: it's a remote
- // call with no local single-flight constraint to absorb.
- const settings = await getSettings();
- const mode = data.mode || settings.imageGen?.mode || 'external';
+ // call with no local single-flight constraint to absorb. `settings` and
+ // `mode` were already resolved above (so the FLUX.2 + local-backend gate
+ // could fire before staging any uploads).
if (mode === 'codex') {
// Reject up-front rather than enqueueing a doomed job — codex is gated
// behind an explicit toggle since not every Codex account has access to
diff --git a/server/routes/imageGen.multipart.test.js b/server/routes/imageGen.multipart.test.js
new file mode 100644
index 0000000000..a352cad005
--- /dev/null
+++ b/server/routes/imageGen.multipart.test.js
@@ -0,0 +1,279 @@
+import { describe, it, expect, beforeEach, beforeAll, afterAll, vi } from 'vitest';
+import express from 'express';
+import { createServer } from 'http';
+import { mkdtemp, rm, readdir, readFile, unlink } from 'fs/promises';
+import { join, parse as parsePath } from 'path';
+import { tmpdir } from 'os';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+// Sandbox PATHS.images + PATHS.imageRefs so the route can copyFile() to real
+// directories without touching the repo's data/. Installed BEFORE the route
+// module imports fileUtils.js — hence the dynamic import below.
+let imagesSandbox;
+let refsSandbox;
+
+vi.mock('../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../lib/fileUtils.js');
+ return {
+ ...actual,
+ get PATHS() {
+ return { ...actual.PATHS, images: imagesSandbox, imageRefs: refsSandbox };
+ },
+ };
+});
+
+vi.mock('../services/imageGen/index.js', async () => {
+ const actual = await vi.importActual('../services/imageGen/index.js');
+ return {
+ ...actual,
+ checkConnection: vi.fn(),
+ generateImage: vi.fn(),
+ generateAvatar: vi.fn(),
+ attachSseClient: vi.fn(() => false),
+ cancel: vi.fn(() => false),
+ };
+});
+
+// Local-mode test: route enqueues into the queue rather than running the
+// renderer; assert the params landing in enqueueJob carry the packed reference
+// arrays in submit order.
+// `getSettings` is mocked per-test so we can flip the effective backend
+// (`local` vs. `external` vs. `codex`) and exercise the route's mode-aware
+// reference-image gate. Default: `mode: 'local'` with a fake pythonPath.
+let mockedSettings = { imageGen: { mode: 'local', local: { pythonPath: '/usr/bin/python3' } } };
+vi.mock('../services/settings.js', () => ({
+ getSettings: vi.fn(async () => mockedSettings),
+}));
+
+vi.mock('../services/mediaJobQueue/index.js', () => ({
+ enqueueJob: vi.fn(() => ({ jobId: 'multipart-job', position: 1, status: 'queued' })),
+ attachSseClient: vi.fn(() => false),
+ cancelJob: vi.fn(),
+ listJobs: vi.fn(() => []),
+}));
+
+let imageGenRoutes;
+let enqueueJob;
+
+// Minimal valid PNG (8×8 white) — the route trusts the validated mimetype,
+// not the pixel data, so any PNG-shaped bytes work for verifying the copy
+// + pack path.
+const PNG_FIXTURE = Buffer.from(
+ '89504e470d0a1a0a0000000d49484452000000080000000808060000' +
+ '00c40fbe8b0000001c4944415478da636060606060606060606060606060' +
+ '0000000600014cbc20a30000000049454e44ae426082',
+ 'hex',
+);
+
+beforeAll(async () => {
+ imagesSandbox = await mkdtemp(join(tmpdir(), 'portos-imagegen-multipart-images-'));
+ refsSandbox = await mkdtemp(join(tmpdir(), 'portos-imagegen-multipart-refs-'));
+ ({ default: imageGenRoutes } = await import('./imageGen.js'));
+ ({ enqueueJob } = await import('../services/mediaJobQueue/index.js'));
+});
+
+afterAll(async () => {
+ await rm(imagesSandbox, { recursive: true, force: true });
+ await rm(refsSandbox, { recursive: true, force: true });
+});
+
+// Build a multipart/form-data body buffer. Each part is { name, filename?,
+// contentType?, value: string|Buffer }. Returns the body + the Content-Type
+// header (boundary baked in).
+const BOUNDARY = '----PortOSMultipartTestBoundary';
+const CRLF = '\r\n';
+function buildMultipart(parts) {
+ const sections = parts.map((p) => {
+ let header = `--${BOUNDARY}${CRLF}Content-Disposition: form-data; name="${p.name}"`;
+ if (p.filename) header += `; filename="${p.filename}"`;
+ header += CRLF;
+ if (p.contentType) header += `Content-Type: ${p.contentType}${CRLF}`;
+ header += CRLF;
+ const value = Buffer.isBuffer(p.value) ? p.value : Buffer.from(String(p.value));
+ return Buffer.concat([Buffer.from(header), value, Buffer.from(CRLF)]);
+ });
+ return {
+ body: Buffer.concat([...sections, Buffer.from(`--${BOUNDARY}--${CRLF}`)]),
+ contentType: `multipart/form-data; boundary=${BOUNDARY}`,
+ };
+}
+
+async function postMultipart(app, path, parts) {
+ const { body, contentType } = buildMultipart(parts);
+ const server = createServer(app);
+ await new Promise((resolve, reject) => {
+ server.listen(0, '127.0.0.1', resolve);
+ server.on('error', reject);
+ });
+ try {
+ const { port } = server.address();
+ const res = await fetch(`http://127.0.0.1:${port}${path}`, {
+ method: 'POST',
+ body,
+ headers: { 'content-type': contentType },
+ });
+ const text = await res.text();
+ const ct = res.headers.get('content-type') || '';
+ return {
+ status: res.status,
+ body: text && ct.includes('application/json') ? JSON.parse(text) : text,
+ };
+ } finally {
+ await new Promise((resolve) => server.close(resolve));
+ }
+}
+
+describe('POST /api/image-gen/generate — multipart reference-image packing', () => {
+ let app;
+
+ beforeEach(async () => {
+ app = express();
+ app.use(express.json());
+ app.use('/api/image-gen', imageGenRoutes);
+ app.use(errorMiddleware);
+ vi.clearAllMocks();
+ // Reset the mode-mock to the default `local` so a previous test that
+ // flipped it to `external`/`codex` doesn't bleed into the next one.
+ mockedSettings = { imageGen: { mode: 'local', local: { pythonPath: '/usr/bin/python3' } } };
+ // Empty both sandbox dirs so each test's file-presence assertions reflect
+ // ONLY that test's uploads — leftover ref-* files from prior tests would
+ // make the "gate rejects before copy" test see stale data.
+ for (const dir of [imagesSandbox, refsSandbox]) {
+ const existing = await readdir(dir).catch(() => []);
+ await Promise.all(existing.map((f) => unlink(join(dir, f)).catch(() => {})));
+ }
+ });
+
+ it('packs populated reference slots into referenceImagePaths in submit order with parallel strengths', async () => {
+ const res = await postMultipart(app, '/api/image-gen/generate', [
+ { name: 'prompt', value: 'multi-ref test' },
+ { name: 'modelId', value: 'flux2-klein-4b' },
+ { name: 'referenceImage1', filename: 'a.png', contentType: 'image/png', value: PNG_FIXTURE },
+ { name: 'referenceImage2', filename: 'b.png', contentType: 'image/png', value: PNG_FIXTURE },
+ { name: 'referenceStrengths', value: '0.8' },
+ { name: 'referenceStrengths', value: '0.3' },
+ ]);
+
+ expect(res.status).toBe(200);
+ expect(res.body.status).toBe('queued');
+ expect(enqueueJob).toHaveBeenCalledTimes(1);
+ const params = enqueueJob.mock.calls[0][0].params;
+ // Both refs landed in PATHS.imageRefs (sandboxed) with submit-order positions.
+ // Compare via path utilities rather than building a regex from the sandbox
+ // path — temp paths on Windows (backslashes) and any sandbox path containing
+ // regex metacharacters (`.`, `(`, `[`) would otherwise be interpreted by
+ // the regex engine instead of matched literally.
+ expect(params.referenceImagePaths).toHaveLength(2);
+ for (const refPath of params.referenceImagePaths) {
+ const { dir, name, ext } = parsePath(refPath);
+ expect(dir).toBe(refsSandbox);
+ expect(name.startsWith('ref-')).toBe(true);
+ expect(ext).toBe('.png');
+ }
+ expect(params.referenceImageStrengths).toEqual([0.8, 0.3]);
+ // Files were actually copied (gallery enumeration would never see them
+ // because they're outside PATHS.images).
+ const refDirContents = await readdir(refsSandbox);
+ expect(refDirContents.filter((f) => f.startsWith('ref-'))).toHaveLength(2);
+ // Sanity: the copies carry the PNG fixture bytes (route trusts mimetype but
+ // writes the raw upload through, so the bytes round-trip).
+ const firstRefBytes = await readFile(params.referenceImagePaths[0]);
+ expect(firstRefBytes.equals(PNG_FIXTURE)).toBe(true);
+ // References must NOT land in PATHS.images — that would surface them in
+ // the gallery's flat .png enumeration.
+ const imagesDirContents = await readdir(imagesSandbox);
+ expect(imagesDirContents.filter((f) => f.startsWith('ref-'))).toHaveLength(0);
+ });
+
+ it('packs only the filled slots (gaps in the slot numbering collapse to a packed array)', async () => {
+ const res = await postMultipart(app, '/api/image-gen/generate', [
+ { name: 'prompt', value: 'sparse multi-ref' },
+ { name: 'modelId', value: 'flux2-klein-4b' },
+ // Slot 1 empty, slots 2 + 4 filled, slot 3 empty.
+ { name: 'referenceImage2', filename: 'b.png', contentType: 'image/png', value: PNG_FIXTURE },
+ { name: 'referenceImage4', filename: 'd.png', contentType: 'image/png', value: PNG_FIXTURE },
+ // Two strengths to match the two filled slots, in slot order.
+ { name: 'referenceStrengths', value: '0.6' },
+ { name: 'referenceStrengths', value: '0.9' },
+ ]);
+
+ expect(res.status).toBe(200);
+ const params = enqueueJob.mock.calls[0][0].params;
+ expect(params.referenceImagePaths).toHaveLength(2);
+ expect(params.referenceImageStrengths).toEqual([0.6, 0.9]);
+ });
+
+ it('defaults missing strengths to 1.0 (full influence)', async () => {
+ const res = await postMultipart(app, '/api/image-gen/generate', [
+ { name: 'prompt', value: 'no-strengths multi-ref' },
+ { name: 'modelId', value: 'flux2-klein-4b' },
+ { name: 'referenceImage1', filename: 'a.png', contentType: 'image/png', value: PNG_FIXTURE },
+ // No referenceStrengths sent.
+ ]);
+
+ expect(res.status).toBe(200);
+ const params = enqueueJob.mock.calls[0][0].params;
+ expect(params.referenceImagePaths).toHaveLength(1);
+ expect(params.referenceImageStrengths).toEqual([1.0]);
+ });
+
+ it('rejects refs uploaded for a non-FLUX.2 model before any file is copied', async () => {
+ const res = await postMultipart(app, '/api/image-gen/generate', [
+ { name: 'prompt', value: 'wrong-model ref' },
+ // `dev` is the default mflux Flux.1 model — NOT FLUX.2.
+ { name: 'modelId', value: 'dev' },
+ { name: 'referenceImage1', filename: 'a.png', contentType: 'image/png', value: PNG_FIXTURE },
+ ]);
+
+ expect(res.status).toBe(400);
+ expect(res.body.error || res.body).toMatch(/FLUX\.2/i);
+ expect(enqueueJob).not.toHaveBeenCalled();
+ // The upload was never persisted to PATHS.imageRefs (no orphan files left
+ // behind by a request the route already knows it can't honor).
+ const refDirContents = await readdir(refsSandbox).catch(() => []);
+ expect(refDirContents.filter((f) => f.startsWith('ref-'))).toHaveLength(0);
+ });
+
+ it('rejects refs when the effective backend is not local (codex/external) — even with a FLUX.2 modelId', async () => {
+ // FLUX.2 model selected, but settings.imageGen.mode flips to a backend
+ // that doesn't consume `referenceImagePaths`. The gate must fire BEFORE
+ // any file is staged into PATHS.imageRefs.
+ mockedSettings = { imageGen: { mode: 'external' } };
+ const res = await postMultipart(app, '/api/image-gen/generate', [
+ { name: 'prompt', value: 'flux2 ref on wrong backend' },
+ { name: 'modelId', value: 'flux2-klein-4b' },
+ { name: 'referenceImage1', filename: 'a.png', contentType: 'image/png', value: PNG_FIXTURE },
+ ]);
+
+ expect(res.status).toBe(400);
+ expect(res.body.error || res.body).toMatch(/local/i);
+ expect(enqueueJob).not.toHaveBeenCalled();
+ const refDirContents = await readdir(refsSandbox).catch(() => []);
+ expect(refDirContents.filter((f) => f.startsWith('ref-'))).toHaveLength(0);
+ });
+
+ it('rejecting a non-FLUX.2 ref upload deletes the multer-staged tmp file (no os.tmpdir leak)', async () => {
+ // Snapshot the tmpdir's `upload-*` entries before and after the request.
+ // The multipart parser writes uploads as `upload-<uuid><ext>`, so the
+ // post-cleanup diff must be empty for the rejected request.
+ const tmpRoot = tmpdir();
+ const before = new Set((await readdir(tmpRoot).catch(() => []))
+ .filter((f) => f.startsWith('upload-')));
+
+ const res = await postMultipart(app, '/api/image-gen/generate', [
+ { name: 'prompt', value: 'wrong-model ref tmp-cleanup' },
+ { name: 'modelId', value: 'dev' },
+ { name: 'referenceImage1', filename: 'a.png', contentType: 'image/png', value: PNG_FIXTURE },
+ ]);
+ expect(res.status).toBe(400);
+
+ // unlink() is fire-and-forget — give it a microtask tick to settle so the
+ // post-snapshot reflects the cleanup.
+ await new Promise((r) => setTimeout(r, 50));
+ const after = new Set((await readdir(tmpRoot).catch(() => []))
+ .filter((f) => f.startsWith('upload-')));
+ // Any `upload-*` entry that's new vs. the pre-request snapshot is a leak.
+ const leaked = [...after].filter((f) => !before.has(f));
+ expect(leaked).toEqual([]);
+ });
+});
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index e18fd537bc..1010ab05bf 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -137,6 +137,32 @@ describe('Image Gen Routes', () => {
);
});
+ // referenceStrengths is the multi-reference companion to the
+ // multipart referenceImage1..4 uploads. The schema accepts the array on a
+ // JSON body too so a future internal caller (no files attached) doesn't
+ // 400 just by listing weights.
+ it('accepts a referenceStrengths array (0..1, max 4 entries)', async () => {
+ imageGen.generateImage.mockResolvedValue({ generationId: 'gen-ref', filename: 'r.png', path: '/data/images/r.png' });
+ const response = await request(app)
+ .post('/api/image-gen/generate')
+ .send({ prompt: 'multi-ref', referenceStrengths: [0.8, 0.4] });
+ expect(response.status).toBe(200);
+ });
+
+ it('rejects a referenceStrengths entry outside 0..1', async () => {
+ const response = await request(app)
+ .post('/api/image-gen/generate')
+ .send({ prompt: 'multi-ref', referenceStrengths: [0.5, 1.7] });
+ expect(response.status).toBe(400);
+ });
+
+ it('rejects more than 4 referenceStrengths entries', async () => {
+ const response = await request(app)
+ .post('/api/image-gen/generate')
+ .send({ prompt: 'multi-ref', referenceStrengths: [0.1, 0.2, 0.3, 0.4, 0.5] });
+ expect(response.status).toBe(400);
+ });
+
// Local mode goes through the mediaJobQueue rather than calling
// generateImage synchronously; the route returns immediately with
// { jobId, status: 'queued', position } so the UI can attach SSE.
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index f31a61794d..6959f4ce90 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -18,7 +18,7 @@ import { existsSync, watch as fsWatch } from 'fs';
import { join, dirname, resolve as resolvePath, sep as PATH_SEP, basename } from 'path';
import { tmpdir } from 'os';
import { randomUUID } from 'crypto';
-import { assertSafeFilename, ensureDir, listDirectoryByExtension, PATHS, safeJSONParse, resolveGalleryImage } from '../../lib/fileUtils.js';
+import { assertSafeFilename, ensureDir, listDirectoryByExtension, PATHS, safeJSONParse, resolveGalleryImage, resolveImageRef } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { imageGenEvents } from '../imageGenEvents.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';
@@ -65,7 +65,7 @@ export const cancel = () => {
return true;
};
-export const buildArgs = ({ pythonPath, model, prompt, negativePrompt, width, height, steps, guidance, seed, quantize, outputPath, loraPaths = [], loraScales = [], stepwiseDir, initImagePath, initImageStrength }) => {
+export const buildArgs = ({ pythonPath, model, prompt, negativePrompt, width, height, steps, guidance, seed, quantize, outputPath, loraPaths = [], loraScales = [], stepwiseDir, initImagePath, initImageStrength, referenceImagePaths = [], referenceImageStrengths = [] }) => {
const modelId = model?.id;
if (isZImage(model) || isErnie(model)) {
if (!model.repo) {
@@ -163,6 +163,19 @@ export const buildArgs = ({ pythonPath, model, prompt, negativePrompt, width, he
if (negativePrompt) args.push('--negative-prompt', negativePrompt);
if (initImagePath) args.push('--image-path', initImagePath);
if (initImagePath && initImageStrength != null) args.push('--image-strength', String(initImageStrength));
+ // Multi-reference editing for FLUX.2. The Python runner currently ignores
+ // these flags — they're plumbed end-to-end so the UI + server contract is
+ // in place, but the actual multi-reference diffusers wiring is gated on
+ // the FLUX.2-klein-9B-kv model swap (see PLAN.md) since the user-facing
+ // model that supports this hasn't been validated yet. Adding them here
+ // (rather than waiting) keeps the wiring testable + avoids a second PR
+ // that touches the same lines.
+ if (referenceImagePaths?.length) {
+ args.push('--reference-images', ...referenceImagePaths);
+ if (referenceImageStrengths?.length) {
+ args.push('--reference-strengths', ...referenceImageStrengths.map(String));
+ }
+ }
if (stepwiseDir) args.push('--stepwise-image-output-dir', stepwiseDir);
if (loraPaths?.length) args.push('--lora-paths', ...loraPaths);
if (loraScales?.length) args.push('--lora-scales', ...loraScales.map(String));
@@ -199,7 +212,7 @@ export const buildArgs = ({ pythonPath, model, prompt, negativePrompt, width, he
return { bin, args };
};
-export async function generateImage({ pythonPath, prompt, negativePrompt = '', modelId = 'dev', width = 1024, height = 1024, steps, guidance, seed, quantize = '8', loraFilenames = [], loraPaths = [], loraScales = [], initImagePath = null, initImageStrength = null, jobId: providedJobId = null }) {
+export async function generateImage({ pythonPath, prompt, negativePrompt = '', modelId = 'dev', width = 1024, height = 1024, steps, guidance, seed, quantize = '8', loraFilenames = [], loraPaths = [], loraScales = [], initImagePath = null, initImageStrength = null, referenceImagePaths = [], referenceImageStrengths = [], jobId: providedJobId = null }) {
if (!prompt?.trim()) throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
// Single-flight is enforced by the mediaJobQueue worker upstream. Direct
// callers that bypass the queue must not run two concurrent renders — the
@@ -273,10 +286,37 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', m
const validInitImagePath = (initImagePath && typeof initImagePath === 'string')
? resolveGalleryImage(initImagePath)
: null;
+ // Clamp 0..1 with a finite-fallback — Math.max/min preserve NaN, so a
+ // corrupt sidecar value like Number('bad') would slip through and end up
+ // serialized into metadata / the CLI flag. `null` here means "no strength
+ // sent" (init-image), which the args builder already gates on; for refs
+ // (below) we fall back to 1.0 (full influence).
+ const clampStrength01 = (raw, fallback) => {
+ const n = Number(raw);
+ if (!Number.isFinite(n)) return fallback;
+ return Math.max(0, Math.min(1, n));
+ };
const validInitImageStrength = validInitImagePath && initImageStrength != null
- ? Math.max(0, Math.min(1, Number(initImageStrength)))
+ ? clampStrength01(initImageStrength, null)
: null;
- const meta = { id: jobId, prompt, negativePrompt, modelId, seed: actualSeed, width: Number(width), height: Number(height), steps: actualSteps, guidance: actualGuidance, quantize, filename, loraFilenames: validLoraFilenames, loraPaths: validLoras, loraScales, initImageFilename: validInitImagePath ? basename(validInitImagePath) : null, initImageStrength: validInitImageStrength, createdAt: new Date().toISOString() };
+ // Multi-reference: re-anchor each path through resolveImageRef so a sidecar
+ // replay can't sneak a path outside PATHS.imageRefs into the runner. Pair
+ // each path with its strength BEFORE filtering so a rejected entry doesn't
+ // shift the strength array — otherwise the surviving path would inherit the
+ // wrong slot's strength.
+ const rawRefPaths = Array.isArray(referenceImagePaths) ? referenceImagePaths : [];
+ const validReferences = rawRefPaths
+ .map((p, i) => {
+ const resolved = typeof p === 'string' ? resolveImageRef(p) : null;
+ if (!resolved) return null;
+ const rawStrength = referenceImageStrengths?.[i];
+ const strength = rawStrength != null ? clampStrength01(rawStrength, 1.0) : 1.0;
+ return { path: resolved, strength };
+ })
+ .filter(Boolean);
+ const validReferenceImagePaths = validReferences.map((r) => r.path);
+ const validReferenceImageStrengths = validReferences.map((r) => r.strength);
+ const meta = { id: jobId, prompt, negativePrompt, modelId, seed: actualSeed, width: Number(width), height: Number(height), steps: actualSteps, guidance: actualGuidance, quantize, filename, loraFilenames: validLoraFilenames, loraPaths: validLoras, loraScales, initImageFilename: validInitImagePath ? basename(validInitImagePath) : null, initImageStrength: validInitImageStrength, referenceImageFilenames: validReferenceImagePaths.map((p) => basename(p)), referenceImageStrengths: validReferenceImageStrengths, createdAt: new Date().toISOString() };
const job = { ...meta, clients: [], status: 'running' };
jobs.set(jobId, job);
@@ -284,7 +324,7 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', m
// per inference step here; we watch and stream the latest as `currentImage`.
const stepwiseDir = await mkdtemp(join(tmpdir(), 'portos-stepwise-'));
- const { bin, args } = buildArgs({ pythonPath, model, prompt, negativePrompt, width: Number(width), height: Number(height), steps: actualSteps, guidance: actualGuidance, seed: actualSeed, quantize, outputPath, loraPaths: validLoras, loraScales, stepwiseDir, initImagePath: validInitImagePath, initImageStrength: validInitImageStrength });
+ const { bin, args } = buildArgs({ pythonPath, model, prompt, negativePrompt, width: Number(width), height: Number(height), steps: actualSteps, guidance: actualGuidance, seed: actualSeed, quantize, outputPath, loraPaths: validLoras, loraScales, stepwiseDir, initImagePath: validInitImagePath, initImageStrength: validInitImageStrength, referenceImagePaths: validReferenceImagePaths, referenceImageStrengths: validReferenceImageStrengths });
console.log(`🎨 Generating image [${jobId.slice(0, 8)}] local: ${modelId} ${width}x${height} steps=${actualSteps}`);
imageGenEvents.emit('started', { generationId: jobId, totalSteps: actualSteps });
diff --git a/server/services/imageGen/local.test.js b/server/services/imageGen/local.test.js
index 376217db37..bc3ab674d6 100644
--- a/server/services/imageGen/local.test.js
+++ b/server/services/imageGen/local.test.js
@@ -181,6 +181,65 @@ describe('imageGen local.buildArgs flux2 dispatch', () => {
expect(args[args.indexOf('--image-strength') + 1]).toBe('0.7');
});
+ it('emits --reference-images + --reference-strengths for flux2 multi-ref edits', () => {
+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');
+ const { args } = buildArgs({
+ ...baseInput,
+ referenceImagePaths: ['/safe/path/ref-a.png', '/safe/path/ref-b.jpg'],
+ referenceImageStrengths: [0.85, 0.5],
+ model: {
+ id: 'flux2-klein-9b',
+ runner: 'flux2',
+ quantization: 'sdnq',
+ repo: 'Disty0/FLUX.2-klein-9B-SDNQ-4bit-dynamic-svd-r32',
+ tokenizerRepo: 'black-forest-labs/FLUX.2-klein-9B',
+ },
+ });
+ const refIdx = args.indexOf('--reference-images');
+ expect(refIdx).toBeGreaterThan(-1);
+ // Both paths land immediately after the flag, in submit order.
+ expect(args[refIdx + 1]).toBe('/safe/path/ref-a.png');
+ expect(args[refIdx + 2]).toBe('/safe/path/ref-b.jpg');
+ const strIdx = args.indexOf('--reference-strengths');
+ expect(strIdx).toBeGreaterThan(-1);
+ expect(args[strIdx + 1]).toBe('0.85');
+ expect(args[strIdx + 2]).toBe('0.5');
+ });
+
+ it('omits --reference-images entirely when no reference paths are supplied', () => {
+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');
+ const { args } = buildArgs({
+ ...baseInput,
+ model: {
+ id: 'flux2-klein-4b',
+ runner: 'flux2',
+ quantization: 'sdnq',
+ repo: 'Disty0/FLUX.2-klein-4B-SDNQ-4bit-dynamic',
+ tokenizerRepo: 'black-forest-labs/FLUX.2-klein-4B',
+ },
+ });
+ expect(args).not.toContain('--reference-images');
+ expect(args).not.toContain('--reference-strengths');
+ });
+
+ it('skips --reference-strengths when paths are supplied without strengths', () => {
+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');
+ const { args } = buildArgs({
+ ...baseInput,
+ referenceImagePaths: ['/safe/path/ref-only.png'],
+ referenceImageStrengths: [],
+ model: {
+ id: 'flux2-klein-4b',
+ runner: 'flux2',
+ quantization: 'sdnq',
+ repo: 'Disty0/FLUX.2-klein-4B-SDNQ-4bit-dynamic',
+ tokenizerRepo: 'black-forest-labs/FLUX.2-klein-4B',
+ },
+ });
+ expect(args).toContain('--reference-images');
+ expect(args).not.toContain('--reference-strengths');
+ });
+
it('falls back to mflux dispatch for non-flux2 models on macOS', () => {
// No flux2 mock needed — the branch shouldn't be taken at all.
mockResolveFlux2Python.mockReturnValue(null);