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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
pass reference images through to codex, grok and agy instead of rejecting them as "Flux only"
[._.]/ Adam Eivy77abe1ac53c6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d9a3f4c99e..06d9cc1952 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -8,6 +8,8 @@- Series Pipeline **Autonomous mode** now says which AI it will spend on. The Options popover names the provider and model the run resolves to, links to where per-stage pins and reasoning effort are configured, and offers a per-run provider/model override (never persisted — a one-off run can't silently re-point the whole series). The live progress line names the provider of an in-flight run too, including one the scheduler started.+- **Reference images now work on Codex, Grok and Agy, not just local FLUX.** Picking a reference image told you it was "Flux only", and it was: the server rejected reference uploads for every backend but local FLUX.2, and Agy refused an input image of any kind. All three cloud CLIs in fact expose a reference-image parameter — their tool schemas were probed directly rather than taken on the CLI's word — so each now receives them: Codex attaches every input image to `image_gen`'s `referenced_image_paths`, Grok routes them to `image_edit`'s `image` array (a reference-only render goes there too, since its `image_gen` has no image parameter at all), and Agy passes them as `generate_image`'s `ImagePaths`. The init image leads the list everywhere and still carries the strength → fidelity-phrase mapping. The Image Gen form offers as many reference slots as the selected backend actually accepts — Agy's tool takes at most 3 images total, so an init image there leaves room for 2 — and hides the per-reference strength slider on the cloud CLIs, which expose no numeric weight. Sprite forks, seeded reference renders and pipeline redraws no longer divert away from an Agy pin, and Agy alone still requires a prompt even with an input image, because its tool does.+## Fixed- **Universe Canon — "AI: differentiate cast" and per-character "AI: differentiate" now run.** Both threw `Stage pipeline-character-differentiate-cast not found` / `Stage pipeline-character-refine not found` on every install since they shipped: the prompt templates landed in `data.reference/prompts/stages/` but their `stage-config.json` entries were never authored, and `buildPrompt()` resolves the config entry first. Arc-verification **auto-resolve** (`pipeline-arc-resolve`) was dead the same way. All three entries now ship, migration 232 seeds them onto existing installs, and a new catalog-parity guard fails the build if a prompt template ever ships without its config entry again (or the reverse). The inverse gap on the Digital Twin side — ten stages whose config entry ships with no template, so each soul/twin AI pass silently runs its fallback — is tracked in #3644.diff --git a/client/src/components/imageGen/InitImagePicker.jsx b/client/src/components/imageGen/InitImagePicker.jsxindex 6cff809577..29363bfd13 100644--- a/client/src/components/imageGen/InitImagePicker.jsx+++ b/client/src/components/imageGen/InitImagePicker.jsx@@ -24,11 +24,13 @@ export default function InitImagePicker({backend = 'local',disabled = false,}) {- // i2i runs on both local (FLUX) and codex; the "Flux only" caveat applies only- // to the local backend (non-FLUX local models ignore the init image).+ // i2i runs on every backend the page offers it for. The "Flux only" caveat is+ // a LOCAL-runner constraint (non-FLUX mflux/diffusers models ignore the init+ // image) — the cloud CLIs each feed it to their own image tool, so the caveat+ // must not follow them.const subtitle = editOnly? '(required — this model edits an existing image)'- : backend === 'codex' ? '(image-to-image)' : '(image-to-image — Flux only)';+ : backend === 'local' ? '(image-to-image — Flux only)' : '(image-to-image)';return (<div><label className="block text-xs font-medium text-gray-400 mb-1">diff --git a/client/src/components/imageGen/InitImagePicker.test.jsx b/client/src/components/imageGen/InitImagePicker.test.jsxindex 5e33d03403..50e4d87495 100644--- a/client/src/components/imageGen/InitImagePicker.test.jsx+++ b/client/src/components/imageGen/InitImagePicker.test.jsx@@ -20,7 +20,10 @@ describe('InitImagePicker', () => {expect(screen.getByText(/image-to-image — Flux only/i)).toBeTruthy();});- it('drops the "Flux only" caveat on the codex backend', () => {+ // The caveat is a LOCAL-runner constraint (non-FLUX mflux/diffusers models+ // ignore the init image). Every cloud CLI feeds it to its own image tool, so+ // it must not follow them.+ it.each(['codex', 'grok', 'agy'])('drops the "Flux only" caveat on the %s backend', (backend) => {render(<InitImagePickerinitImage={EMPTY}@@ -28,7 +31,7 @@ describe('InitImagePicker', () => {onStrengthChange={vi.fn()}onPick={vi.fn()}onClear={vi.fn()}- backend="codex"+ backend={backend}/>,);expect(screen.getByText('(image-to-image)')).toBeTruthy();diff --git a/client/src/components/imageGen/ReferenceImagePicker.jsx b/client/src/components/imageGen/ReferenceImagePicker.jsxindex 9805d27dec..a6e941bb15 100644--- a/client/src/components/imageGen/ReferenceImagePicker.jsx+++ b/client/src/components/imageGen/ReferenceImagePicker.jsx@@ -1,16 +1,23 @@-// FLUX.2 multi-reference uploader — up to 4 fixed, positional slots, each-// carrying an uploaded File + a 0..1 strength weight. The caller owns the-// `referenceImages` array (`[{ file, previewUrl, strength }]`) and the slot-// mutations; this component only renders the grid of thumbnails / Add tiles /-// strength sliders.+// Multi-reference uploader — up to 4 fixed, positional slots, each carrying an+// uploaded File + a 0..1 strength weight. The caller owns the `referenceImages`+// array (`[{ file, previewUrl, strength }]`) and the slot mutations; this+// component only renders the grid of thumbnails / Add tiles / strength sliders.//-// References are conditioned via diffusers' Flux2KleinKVPipeline (K/V-cache-// reference-token attention). First-time use prompts the user to accept the-// FLUX.2-klein-9B-kv license on Hugging Face. Per-reference strengths are-// honored end-to-end: scripts/flux2_macos.py patches Flux2KVLayerCache.store ++// On the LOCAL backend, references are conditioned via diffusers'+// Flux2KleinKVPipeline (K/V-cache reference-token attention). First-time use+// prompts the user to accept the FLUX.2-klein-9B-kv license on Hugging Face.+// Per-reference strengths are honored end-to-end there:+// scripts/flux2_macos.py patches Flux2KVLayerCache.store +// _flux2_kv_causal_attention so each reference's V slice is scaled by its// strength (1.0 = full influence, 0.0 = ignored).//+// The cloud CLIs feed the same references to their own image tools (codex+// `referenced_image_paths`, grok `image_edit.image`, agy `ImagePaths`), which+// expose NO numeric per-reference weight — so `showStrength={false}` hides the+// sliders there rather than offering a control the backend ignores. The caller+// passes only the slots the active backend accepts (see `referenceSlotsFor`),+// so this renders one tile per element it is given.+//// `onPick(slotIndex, event)` receives the raw file-input change event so the// caller can run EXIF orientation normalization before storing the File.@@ -25,11 +32,13 @@ export default function ReferenceImagePicker({onStrengthChange,onBrowse,disabled = false,+ showStrength = true,+ caption = 'up to 4 images for FLUX.2 multi-reference edit',}) {return (<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>+ Reference images <span className="text-gray-500 font-normal">({caption})</span></label><div className="grid grid-cols-2 sm:grid-cols-4 gap-2">{referenceImages.map((slot, i) => {@@ -57,17 +66,21 @@ export default function ReferenceImagePicker({<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={disabled}- onChange={(e) => onStrengthChange(i, Number(e.target.value))}- className="w-full accent-port-accent"- />+ {showStrength && (+ <>+ <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={disabled}+ onChange={(e) => onStrengthChange(i, Number(e.target.value))}+ className="w-full accent-port-accent"+ />+ </>+ )}</>) : (<div className="flex flex-col gap-1">diff --git a/client/src/components/imageGen/ReferenceImagePicker.test.jsx b/client/src/components/imageGen/ReferenceImagePicker.test.jsxindex 63744345b5..2651b5dd88 100644--- a/client/src/components/imageGen/ReferenceImagePicker.test.jsx+++ b/client/src/components/imageGen/ReferenceImagePicker.test.jsx@@ -13,6 +13,28 @@ describe('ReferenceImagePicker', () => {expect(screen.getByText('Ref 4')).toBeTruthy();});+ it('renders one tile per slot it is given, so a capped backend shows no droppable slot', () => {+ render(<ReferenceImagePicker referenceImages={fourEmpty().slice(0, 2)} onPick={vi.fn()} onClear={vi.fn()} onStrengthChange={vi.fn()} />);+ expect(screen.getAllByText('Upload')).toHaveLength(2);+ expect(screen.queryByText('Ref 3')).toBeNull();+ });++ it('hides the strength slider on backends with no numeric per-reference weight', () => {+ const slots = fourEmpty();+ slots[0] = { file: null, previewUrl: 'blob:one', strength: 0.5 };+ const { container } = render(+ <ReferenceImagePicker referenceImages={slots} showStrength={false} onPick={vi.fn()} onClear={vi.fn()} onStrengthChange={vi.fn()} />,+ );+ // The thumbnail and its clear button stay — only the inert control goes.+ expect(screen.getByTitle('Remove reference 1')).toBeTruthy();+ expect(container.querySelector('input[type="range"]')).toBeNull();+ });++ it('renders the caller-supplied caption', () => {+ render(<ReferenceImagePicker referenceImages={fourEmpty()} caption="up to 2 more images Agy will use as visual references" onPick={vi.fn()} onClear={vi.fn()} onStrengthChange={vi.fn()} />);+ expect(screen.getByText('(up to 2 more images Agy will use as visual references)')).toBeTruthy();+ });+it('renders a per-slot Gallery button when onBrowse is set and fires it with the slot index', () => {const onBrowse = vi.fn();render(<ReferenceImagePicker referenceImages={fourEmpty()} onPick={vi.fn()} onClear={vi.fn()} onStrengthChange={vi.fn()} onBrowse={onBrowse} />);diff --git a/client/src/components/sprites/ForkSpriteModal.jsx b/client/src/components/sprites/ForkSpriteModal.jsxindex 93e24b7efd..75c87edeb8 100644--- a/client/src/components/sprites/ForkSpriteModal.jsx+++ b/client/src/components/sprites/ForkSpriteModal.jsx@@ -158,8 +158,9 @@ export default function ForkSpriteModal({ open, onClose, source, referencePath,</div>{!hasBackends && (<p className="text-xs text-port-warning">- No image-to-image backend configured — enable Codex or Grok, or set a local Python path, in- Settings → Image Gen. A fork redraws this reference, which text-to-image-only backends cannot do.+ No image-to-image backend configured — enable Codex, Grok or Agy, or set a local Python path,+ in Settings → Image Gen. A fork redraws this reference, so it needs a backend that takes an+ input image.</p>)}</div>diff --git a/client/src/components/sprites/ForkSpriteModal.test.jsx b/client/src/components/sprites/ForkSpriteModal.test.jsxindex 13df786eb4..5ed1e30767 100644--- a/client/src/components/sprites/ForkSpriteModal.test.jsx+++ b/client/src/components/sprites/ForkSpriteModal.test.jsx@@ -139,18 +139,36 @@ describe('ForkSpriteModal submit gating', () => {*/describe('ForkSpriteModal backend filtering', () => {const WITH_AGY = [...BACKENDS, { id: 'agy', label: 'Agy' }];+ const WITH_EXTERNAL = [...BACKENDS, { id: 'external', label: 'External' }];- it('omits a text-to-image-only backend from the picker', () => {+ // A fork always seeds from the source reference, so the picker lists only+ // backends that take an input image. Every configured generation backend now+ // does (agy included, via its tool's ImagePaths parameter) — external is the+ // one that doesn't.+ it('offers every input-image-capable backend, including agy', () => {renderModal({ backends: WITH_AGY });const options = [...screen.getByRole('combobox').options].map((o) => o.value);+ expect(options).toEqual(['codex', 'grok', 'agy']);+ });++ it('omits the external backend, which cannot take an input image', () => {+ renderModal({ backends: WITH_EXTERNAL });+ const options = [...screen.getByRole('combobox').options].map((o) => o.value);expect(options).toEqual(['codex', 'grok']);});- it('ignores a text-to-image-only page mode instead of adopting it', async () => {+ it('adopts an input-image-capable page mode', async () => {renderModal({ backends: WITH_AGY, mode: 'agy' });await userEvent.type(promptBox(), 'now with a red coat');+ await userEvent.click(forkButton());+ expect(forkSpriteRecord.mock.calls[0][1].mode).toBe('agy');+ });++ it('ignores an input-image-incapable page mode instead of adopting it', async () => {+ renderModal({ backends: WITH_EXTERNAL, mode: 'external' });+ await userEvent.type(promptBox(), 'now with a red coat');// An adopted mode satisfies the backend half of the submit gate, so a still- // disabled button with a written prompt is exactly "agy was not adopted".+ // disabled button with a written prompt is exactly "external was not adopted".expect(forkButton()).toBeDisabled();await userEvent.selectOptions(screen.getByRole('combobox'), 'grok');@@ -158,8 +176,8 @@ describe('ForkSpriteModal backend filtering', () => {expect(forkSpriteRecord.mock.calls[0][1].mode).toBe('grok');});- it('warns instead of offering a picker when every backend is text-to-image-only', () => {- renderModal({ backends: [{ id: 'agy', label: 'Agy' }], mode: 'agy' });+ it('warns instead of offering a picker when no backend takes an input image', () => {+ renderModal({ backends: [{ id: 'external', label: 'External' }], mode: 'external' });expect(screen.queryByRole('combobox')).not.toBeInTheDocument();expect(screen.getByText(/No image-to-image backend configured/)).toBeInTheDocument();});diff --git a/client/src/lib/imageGenBackends.test.js b/client/src/lib/imageGenBackends.test.jsindex d1ca2969b1..c60fce46ca 100644--- a/client/src/lib/imageGenBackends.test.js+++ b/client/src/lib/imageGenBackends.test.js@@ -2,23 +2,72 @@ import { describe, it, expect } from 'vitest';import {IMAGE_GEN_MODE,I2I_CAPABLE_MODES,+ MAX_INPUT_IMAGES,+ cloudPromptRequired,isI2iCapableMode,pickI2iMode,+ referenceSlotsFor,+ supportsReferenceStrength,deriveAvailableBackends,} from './imageGenBackends';describe('I2I_CAPABLE_MODES / isI2iCapableMode', () => {- it('treats local, codex, and grok as i2i-capable, but not Agy or external', () => {- expect(I2I_CAPABLE_MODES).toEqual([IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK]);+ it('treats every generation backend as i2i-capable, but not external', () => {+ expect(I2I_CAPABLE_MODES).toEqual([+ IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK, IMAGE_GEN_MODE.AGY,+ ]);expect(isI2iCapableMode(IMAGE_GEN_MODE.LOCAL)).toBe(true);expect(isI2iCapableMode(IMAGE_GEN_MODE.CODEX)).toBe(true);expect(isI2iCapableMode(IMAGE_GEN_MODE.GROK)).toBe(true);- expect(isI2iCapableMode(IMAGE_GEN_MODE.AGY)).toBe(false);+ expect(isI2iCapableMode(IMAGE_GEN_MODE.AGY)).toBe(true);expect(isI2iCapableMode(IMAGE_GEN_MODE.EXTERNAL)).toBe(false);expect(isI2iCapableMode(undefined)).toBe(false);});});+describe('input-image capability helpers', () => {+ it('caps agy at the 3 images its generate_image tool accepts', () => {+ expect(MAX_INPUT_IMAGES[IMAGE_GEN_MODE.AGY]).toBe(3);+ // The other two declare no maximum, so PortOS's own ceiling applies:+ // 1 init image + 4 reference slots.+ expect(MAX_INPUT_IMAGES[IMAGE_GEN_MODE.CODEX]).toBe(5);+ expect(MAX_INPUT_IMAGES[IMAGE_GEN_MODE.GROK]).toBe(5);+ });++ it('lets codex/grok render image-only but always demands a prompt for agy', () => {+ expect(cloudPromptRequired(IMAGE_GEN_MODE.CODEX, true)).toBe(false);+ expect(cloudPromptRequired(IMAGE_GEN_MODE.GROK, true)).toBe(false);+ expect(cloudPromptRequired(IMAGE_GEN_MODE.AGY, true)).toBe(true);+ for (const mode of [IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK, IMAGE_GEN_MODE.AGY]) {+ expect(cloudPromptRequired(mode, false)).toBe(true);+ }+ });++ it('leaves room for the init image when capping a cloud backend\'s reference slots', () => {+ // agy's tool takes 3 images TOTAL, so an init image leaves 2 ref slots.+ expect(referenceSlotsFor(IMAGE_GEN_MODE.AGY, { hasInitImage: false })).toBe(3);+ expect(referenceSlotsFor(IMAGE_GEN_MODE.AGY, { hasInitImage: true })).toBe(2);+ // codex/grok declare no cap, so the form's own 4 slots are the ceiling and+ // an init image doesn't eat into them.+ expect(referenceSlotsFor(IMAGE_GEN_MODE.CODEX, { hasInitImage: true })).toBe(4);+ expect(referenceSlotsFor(IMAGE_GEN_MODE.GROK, { hasInitImage: false })).toBe(4);+ });++ 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);+ expect(referenceSlotsFor(IMAGE_GEN_MODE.EXTERNAL, { localSupportsReferences: true })).toBe(0);+ expect(referenceSlotsFor(undefined)).toBe(0);+ });++ it('offers numeric per-reference strength only on the local runner', () => {+ expect(supportsReferenceStrength(IMAGE_GEN_MODE.LOCAL)).toBe(true);+ for (const mode of [IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK, IMAGE_GEN_MODE.AGY]) {+ expect(supportsReferenceStrength(mode)).toBe(false);+ }+ });+});+describe('pickI2iMode', () => {const backend = (id) => ({ id });diff --git a/client/src/lib/imageGenModes.js b/client/src/lib/imageGenModes.jsindex dbed54cb0f..6437f35411 100644--- a/client/src/lib/imageGenModes.js+++ b/client/src/lib/imageGenModes.js@@ -120,15 +120,20 @@ export const supportsCloudModelOverride = (mode) => MODEL_OVERRIDE_CAPABLE_MODES// MODE_LABELS already holds and grow a branch per backend.export const modeLabel = (mode) => MODE_LABELS[mode] || mode || '';-// Backends that support image-to-image (init image / reference editing). The-// external SD-API path does not. Single source of truth for i2i gating in the UI.-export const I2I_CAPABLE_MODES = Object.freeze([IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK]);+// Backends that support image-to-image (init image / reference conditioning).+// The external SD-API path does not. Client mirror of the server's+// EDIT_INCAPABLE_IMAGE_MODES complement (imageGen/modes.js), bound to it by+// server/lib/renderTargets.parity.test.js. Ordered best-first — pickI2iMode+// walks this list.+export const I2I_CAPABLE_MODES = Object.freeze([+ IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK, IMAGE_GEN_MODE.AGY,+]);// True when a mode can run image-to-image.export const isI2iCapableMode = (mode) => I2I_CAPABLE_MODES.includes(mode);// Pick the best available i2i backend from a list of `{ id }` backends,-// preferring local (its form exposes strength + LoRAs), else codex, else grok.+// preferring local (its form exposes strength + LoRAs), then codex, grok, agy.// Returns null when none is installed.export function pickI2iMode(backends) {for (const mode of I2I_CAPABLE_MODES) {@@ -136,3 +141,47 @@ export function pickI2iMode(backends) {}return null;}++// Client mirror of the `maxInputImages` field on the server's+// CLOUD_PROVIDER_SPECS (imageGen/cloudProviderConfig.js) — how many input+// images (init image + reference slots, combined) each cloud CLI's image tool+// accepts. The form uses this to cap the reference slots it offers, so a user+// never fills a slot the backend would silently drop. Local isn't listed:+// FLUX.2 takes the init image plus all 4 reference slots.+// Bound to the server values by server/lib/renderTargets.parity.test.js.+export const MAX_INPUT_IMAGES = Object.freeze({+ [IMAGE_GEN_MODE.AGY]: 3,+ [IMAGE_GEN_MODE.CODEX]: 5,+ [IMAGE_GEN_MODE.GROK]: 5,+});++// Client mirror of the server's cloudPromptRequired (imageGen/cloudProviderConfig.js).+// Codex and grok can render from an input image alone; agy's generate_image+// lists `Prompt` in its required parameters, so it always needs one. Bound to+// the server predicate by server/lib/renderTargets.parity.test.js.+export const cloudPromptRequired = (mode, hasInputImage) =>+ isCloudCliMode(mode) && (!hasInputImage || mode === IMAGE_GEN_MODE.AGY);++/**+ * How many reference slots the form should offer for `mode`.+ *+ * The client half of the server's input-image cap: a cloud CLI's tool caps the+ * COMBINED count, so an init image eats one of its slots — the same "init image+ * leads" rule `resolveInputImages` applies server-side, predicted here so the+ * form never offers a slot the backend would drop. 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.+ */+export function referenceSlotsFor(mode, { hasInitImage = false, maxSlots = 4, localSupportsReferences = false } = {}) {+ if (mode === IMAGE_GEN_MODE.LOCAL) return localSupportsReferences ? maxSlots : 0;+ if (!isCloudCliMode(mode)) return 0;+ return Math.min(maxSlots, MAX_INPUT_IMAGES[mode] - (hasInitImage ? 1 : 0));+}++// Backends that honor a NUMERIC per-reference strength. Only the local FLUX.2+// runner does (its K/V reference-attention scales each reference's V slice by+// its weight); the cloud CLIs expose no such knob, so their forms must not show+// a slider that does nothing. The single init image is the exception — its+// strength maps to a fidelity PHRASE in the cloud prompts (describeFidelity),+// so that slider stays meaningful everywhere.+export const supportsReferenceStrength = (mode) => mode === IMAGE_GEN_MODE.LOCAL;diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsxindex 44fc6453fd..a2ee3d796c 100644--- a/client/src/pages/ImageGen.jsx+++ b/client/src/pages/ImageGen.jsx@@ -37,7 +37,7 @@ import {AlertTriangle, X, Film,} from 'lucide-react';import { composeStyledPrompt } from '../lib/composeStyledPrompt';-import { isCloudCliMode, deriveAvailableBackends, AGY_IMAGEGEN_DEFAULT_MODEL, IMAGE_GEN_MODE, isI2iCapableMode, pickI2iMode, modeLabel } from '../lib/imageGenBackends';+import { isCloudCliMode, deriveAvailableBackends, AGY_IMAGEGEN_DEFAULT_MODEL, IMAGE_GEN_MODE, cloudPromptRequired, isI2iCapableMode, pickI2iMode, modeLabel, referenceSlotsFor, supportsReferenceStrength } from '../lib/imageGenBackends';import { clampImageDimensions, clampImageEdge } from '../lib/imageGenResolutions';import { DEFAULT_NEGATIVE_PROMPT } from '../lib/imageGenDefaults';import { resolveCleanersFromConfig } from '../lib/imageCleaners';@@ -55,9 +55,11 @@ import {getFlux2Status,} from '../services/api';-// 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.+// 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+// MAX_INPUT_IMAGES), so the form offers only that many slots there.const REFERENCE_SLOT_COUNT = 4;const EMPTY_REF_SLOT = { file: null, previewUrl: null, strength: 1.0 };@@ -405,7 +407,7 @@ export default function ImageGen() {// Deferred i2i mode nudge: once backends resolve, flip to an i2i-capable// backend so the URL-supplied init image actually takes effect (the picker +- // generate payload are local/codex only). Give up quietly if neither exists.+ // generate payload skip external). Give up quietly if none exists.useEffect(() => {if (!wantI2iModeRef.current) return;if (i2iCapable) { wantI2iModeRef.current = false; return; }@@ -629,11 +631,36 @@ export default function ImageGen() {// submit button + show a hint rather than letting the user hit a failed job.const isEditOnlyModel = currentModel?.editOnly === true;const editImageMissing = isLocalMode && isEditOnlyModel && initImage.source == null;- // Codex text-to-image (no init image) still needs a prompt — mirror the server- // rule (codex.js requires a prompt only when there's no init image) so the user- // sees a disabled button + hint instead of a failed job toast. Local runs- // unconditionally and external (A1111) accepts an empty prompt, so neither gates.- const cloudNeedsPrompt = isCloudMode && initImage.source == null && !prompt.trim();+ // The reference slots the active backend can actually consume, and the+ // populated subset of them. Slots past the cap stay in state (a backend+ // 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 referenceSlotCount = referenceSlotsFor(effectiveMode, {+ hasInitImage: initImage.source != null,+ maxSlots: REFERENCE_SLOT_COUNT,+ localSupportsReferences: isFlux2Model,+ });+ const activeReferenceImages = useMemo(+ () => referenceImages.slice(0, referenceSlotCount),+ [referenceImages, referenceSlotCount],+ );+ const populatedRefs = useMemo(+ () => activeReferenceImages.filter((s) => s.file != null),+ [activeReferenceImages],+ );+ // Cloud text-to-image still needs a prompt — mirror the server rule+ // (cloudPromptRequired: codex/grok can run image-only, agy always needs a+ // Prompt) so the user sees a disabled button + hint instead of a failed job+ // toast. Local runs unconditionally and external (A1111) accepts an empty+ // prompt, so neither gates.+ const hasCloudInputImage = initImage.source != null || populatedRefs.length > 0;+ const cloudNeedsPrompt = cloudPromptRequired(effectiveMode, hasCloudInputImage) && !prompt.trim();+ // Agy needs a prompt even WITH an input image (its tool requires one), so the+ // "text-to-image" framing would be wrong there.+ const cloudPromptHint = hasCloudInputImage+ ? `${cloudModeLabel} always needs a prompt, even with a reference image`+ : `${cloudModeLabel} text-to-image needs a prompt`;// mflux is the default runner for entries with no explicit `runner` field.// LoraPicker filters compatible weights itself; we pass the family (for the// "install one matching X" copy) and the fine-grained compat key (which@@ -760,15 +787,11 @@ export default function ImageGen() {mode: IMAGE_GEN_MODE.LOCAL,cleanC2PA, denoise,};- // i2i works on local (mflux/FLUX) and codex (gpt-image edit) — not external.+ // i2i works on local (mflux/FLUX) and every cloud CLI — not external.const hasInitImage = i2iCapable && initImage.source != null;- // 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)- : [];+ // `populatedRefs` is already packed (a gap — slots 1,3 filled, 2 empty —+ // collapses to a two-image submit) and already limited to what the backend+ // accepts, which is what the server's positional strength pairing expects.const hasReferenceImages = populatedRefs.length > 0;if (hasInitImage || hasReferenceImages) {const initFields = hasInitImage ? {@@ -1253,9 +1276,13 @@ export default function ImageGen() {/>)}- {isLocalMode && isFlux2Model && (+ {referenceSlotCount > 0 && (<ReferenceImagePicker- referenceImages={referenceImages}+ referenceImages={activeReferenceImages}+ showStrength={supportsReferenceStrength(effectiveMode)}+ caption={isLocalMode+ ? `up to ${referenceSlotCount} images for FLUX.2 multi-reference edit`+ : `up to ${referenceSlotCount} more image${referenceSlotCount === 1 ? '' : 's'} ${cloudModeLabel} will use as visual references`}onPick={handlePickReferenceImage}onClear={handleClearReferenceImage}onStrengthChange={handleReferenceStrengthChange}@@ -1268,7 +1295,7 @@ export default function ImageGen() {<buttontype="submit"disabled={notConnected || editImageMissing || cloudNeedsPrompt}- title={editImageMissing ? 'This image-edit model needs a source image — upload one below first' : cloudNeedsPrompt ? `${cloudModeLabel} text-to-image needs a prompt` : undefined}+ title={editImageMissing ? 'This image-edit model needs a source image — upload one below first' : cloudNeedsPrompt ? cloudPromptHint : undefined}className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg min-h-[40px]"><Sparkles className="w-4 h-4" /> {generating ? 'Queue' : 'Generate'}@@ -1278,7 +1305,7 @@ export default function ImageGen() {<span className="text-xs text-port-warning">Upload a source image to use this edit model</span>)}{cloudNeedsPrompt && (- <span className="text-xs text-port-warning">{cloudModeLabel} text-to-image needs a prompt</span>+ <span className="text-xs text-port-warning">{cloudPromptHint}</span>)}{isAsyncMode && (<label className="flex items-center gap-1.5 text-xs text-gray-400" title="Batch size: number of renders to queue per submit">diff --git a/server/lib/renderTargets.parity.test.js b/server/lib/renderTargets.parity.test.jsindex 70ca7f8efe..1614778bc5 100644--- a/server/lib/renderTargets.parity.test.js+++ b/server/lib/renderTargets.parity.test.js@@ -16,7 +16,10 @@import { describe, it, expect } from 'vitest';import { RENDER_TARGETS, RENDER_TARGET_BACKEND_AUTO } from './renderTargets.js';-import { EDIT_INCAPABLE_IMAGE_MODES } from '../services/imageGen/modes.js';+import {+ CLOUD_IMAGE_GEN_MODES, EDIT_INCAPABLE_IMAGE_MODES, IMAGE_GEN_MODES,+} from '../services/imageGen/modes.js';+import { cloudPromptRequired, maxInputImages } from '../services/imageGen/cloudProviderConfig.js';// Import the node-safe leaf, NOT imageGenBackends.js — that module imports// lucide-react, which is not installed in the server CI job (this exact import// broke main's CI when Phase 2 landed pointing at imageGenBackends).@@ -24,6 +27,8 @@ import {RENDER_TARGET_OPTIONS as CLIENT_OPTIONS,RENDER_TARGET_BACKEND_AUTO as CLIENT_AUTO,I2I_CAPABLE_MODES as CLIENT_I2I_CAPABLE,+ MAX_INPUT_IMAGES as CLIENT_MAX_INPUT_IMAGES,+ cloudPromptRequired as clientCloudPromptRequired,} from '../../client/src/lib/imageGenModes.js';// Targets the Settings UI deliberately does NOT list — a pin nobody's@@ -60,15 +65,44 @@ describe('render-target client mirror parity (#3231)', () => {* client list, every i2i picker would go back to offering a backend the server* 400s — the exact bug #3331 fixed, re-introduced silently.*- * Only one direction is asserted: the client list ALSO omits `external`, which is- * edit-capable server-side but isn't queueable and has no i2i UI, so an equality- * check would be wrong.+ * Both directions are asserted: the two sets are exact complements over the mode+ * alphabet, so a backend that gains or loses input-image support server-side has+ * to be reflected in the client list.*/describe('edit-capability client mirror parity (#3331)', () => {- it('no server edit-incapable backend appears in the client i2i-capable list', () => {- for (const mode of EDIT_INCAPABLE_IMAGE_MODES) {- expect(CLIENT_I2I_CAPABLE.includes(mode),- `"${mode}" is edit-incapable server-side but still listed in the client I2I_CAPABLE_MODES`).toBe(false);+ it('the client i2i-capable list is the exact complement of the server incapable list', () => {+ const expected = IMAGE_GEN_MODES.filter((m) => !EDIT_INCAPABLE_IMAGE_MODES.includes(m));+ expect([...CLIENT_I2I_CAPABLE].sort()).toEqual([...expected].sort());+ });+});++/**+ * The per-provider input-image capabilities live on `CLOUD_PROVIDER_SPECS`+ * (server/services/imageGen/cloudProviderConfig.js) and are mirrored into the+ * client so the Image Gen form can offer exactly the reference slots the backend+ * accepts and gate the Generate button on the same prompt rule the server+ * enforces. Drift in either direction is invisible to both suites on its own:+ * the client tests assert the client's own literals, and the server never loads+ * the client mirror. A raised/lowered cap would make the form offer a slot the+ * server silently drops; a changed prompt rule would enable a button on a render+ * `prepareParams` then 400s.+ */+describe('cloud input-image capability client mirror parity', () => {+ it('every cloud CLI mirrors its server maxInputImages', () => {+ for (const mode of CLOUD_IMAGE_GEN_MODES) {+ expect(CLIENT_MAX_INPUT_IMAGES[mode],+ `client MAX_INPUT_IMAGES["${mode}"] does not match the server spec's maxInputImages`)+ .toBe(maxInputImages(mode));+ }+ });++ it('the client prompt-required predicate agrees with the server for every mode', () => {+ for (const mode of IMAGE_GEN_MODES) {+ for (const hasInputImage of [false, true]) {+ expect(clientCloudPromptRequired(mode, hasInputImage),+ `client cloudPromptRequired("${mode}", ${hasInputImage}) disagrees with the server`)+ .toBe(cloudPromptRequired(mode, hasInputImage));+ }}});});diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex e141c44bfc..986925597f 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -19,7 +19,6 @@ import {import { optionalUploadFields } from '../lib/multipart.js';import * as imageGen from '../services/imageGen/index.js';import { local, IMAGE_GEN_MODE, IMAGE_GEN_MODES } from '../services/imageGen/index.js';-import { editIncapableModeError, isEditCapableMode } from '../services/imageGen/modes.js';import { resolveCloudProviderConfig } from '../services/imageGen/cloudProviderConfig.js';import setupRouter from './imageGenSetup.js';import { enqueueJob, attachSseClient as attachQueueSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';@@ -94,12 +93,14 @@ 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`;+ // Multi-reference image conditioning. 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.+ // pairs filled slots with their strengths positionally. Strengths are honored+ // numerically only by local FLUX.2; the cloud CLIs expose no per-reference+ // weight, so they receive the paths alone.referenceStrengths: z.array(z.number().min(0).max(1)).max(MAX_REFERENCE_IMAGES).optional(),// Per-render override of the cleaners. When omitted, the route inherits// from `settings.imageGen.{mode}.{cleanC2PA,denoise}`. Explicit booleans@@ -416,9 +417,6 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {// gated behind an explicit toggle each (not every Codex account has access// to the image_gen tool, and grok spends the user's Grok quota).if (!cloud.enabled) throw cloud.disabledError;- if (!isEditCapableMode(mode) && (params.initImagePath || params.referenceImagePaths?.length)) {- throw editIncapableModeError(mode);- }// `mode` inside jobParams is the queue's discriminator — laneForJob()// routes cloud jobs to the parallel cloud lane, and runJob's image branch// dispatches to the matching imageGen provider module when it sees it.diff --git a/server/routes/imageGen.multipart.test.js b/server/routes/imageGen.multipart.test.jsindex 8d7c2f2b84..9f4ed2c0fe 100644--- a/server/routes/imageGen.multipart.test.js+++ b/server/routes/imageGen.multipart.test.js@@ -297,10 +297,10 @@ describe('POST /api/image-gen/generate — multipart reference-image packing', (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.+ it('rejects refs on the external backend, which has no input-image wiring', async () => {+ // FLUX.2 model selected, but settings.imageGen.mode flips to the one+ // backend that can'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' },@@ -309,12 +309,30 @@ describe('POST /api/image-gen/generate — multipart reference-image packing', (]);expect(res.status).toBe(400);- expect(res.body.error || res.body).toMatch(/local/i);+ expect(res.body.error || res.body).toMatch(/text-to-image only/i);expect(enqueueJob).not.toHaveBeenCalled();const refDirContents = await readdir(refsSandbox).catch(() => []);expect(refDirContents.filter((f) => f.startsWith('ref-'))).toHaveLength(0);});+ it.each(['codex', 'grok', 'agy'])('stages refs for the %s backend and threads the paths into the job', async (mode) => {+ // The cloud CLIs each feed reference images to their own image tool, so a+ // ref upload is honored rather than 400'd — the "local FLUX.2 only" gate+ // that used to reject these was the bug.+ mockedSettings = { imageGen: { mode, [mode]: { enabled: true } } };+ const res = await postMultipart(app, '/api/image-gen/generate', [+ { name: 'prompt', value: 'a fox in this style' },+ { name: 'referenceImage1', filename: 'a.png', contentType: 'image/png', value: PNG_FIXTURE },+ { name: 'referenceImage2', filename: 'b.png', contentType: 'image/png', value: PNG_FIXTURE },+ ]);++ expect(res.status).toBe(200);+ const { params } = enqueueJob.mock.calls.at(-1)[0];+ expect(params.mode).toBe(mode);+ expect(params.referenceImagePaths).toHaveLength(2);+ for (const p of params.referenceImagePaths) expect(p.startsWith(refsSandbox)).toBe(true);+ });+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 thediff --git a/server/services/creative/tools/media.js b/server/services/creative/tools/media.jsindex b3f2cd3842..348dde64cf 100644--- a/server/services/creative/tools/media.js+++ b/server/services/creative/tools/media.js@@ -8,7 +8,7 @@ import { z } from 'zod';import { enqueueJob } from '../../mediaJobQueue/index.js';import { ASPECT_PRESETS, QUALITY_PRESETS, presetToRenderParams } from '../../../lib/creativeDirectorPresets.js';import { getSettings } from '../../settings.js';-import { IMAGE_GEN_MODE, resolveQueueImageMode, resolveQueueImageEditMode } from '../../imageGen/modes.js';+import { IMAGE_GEN_MODE, resolveQueueImageMode } from '../../imageGen/modes.js';import { renderTargetDefaults, resolveRenderTargetConfig } from '../../imageGen/cloudProviderConfig.js';import { RENDER_TARGET } from '../../../lib/renderTargets.js';import { VIDEO_GEN_MODE, VIDEO_GEN_MODES, resolveVideoMode, hasVideoPin } from '../../videoGen/modes.js';@@ -187,14 +187,11 @@ async function enforceRenderBackendPin(kind, params, project) {};}- const wantsEdit = !!params?.initImagePath || params?.referenceImagePaths?.length > 0;// Project pin (explicit, per-record) → creative-agent renderDefaults pin —// both usability-laddered so a disabled backend degrades instead of failing- // a nightly commission.- const requested = pin?.mode || targetDefaults.imageMode;- const mode = wantsEdit- ? resolveQueueImageEditMode(requested, settings)- : resolveQueueImageMode(requested, settings);+ // a nightly commission. One ladder covers text-to-image and edit/reference+ // renders alike: every queueable backend accepts input images.+ const mode = resolveQueueImageMode(pin?.mode || targetDefaults.imageMode, settings);// Mode is laddered above; this threads the creative-agent renderDefaults// imageModel into the cloud job params (#3231). The project's own// `pin.modelId` is deliberately NOT passed as the cloud model override —diff --git a/server/services/imageGen/agy.js b/server/services/imageGen/agy.jsindex 94e40bb891..0982244d28 100644--- a/server/services/imageGen/agy.js+++ b/server/services/imageGen/agy.js@@ -1,10 +1,14 @@/*** Image Gen — Antigravity (`agy`) CLI provider.*- * Agy is an opt-in, text-to-image-only cloud CLI backend. Each request runs- * in a throwaway scratch directory and directs the built-in `generate_image`- * tool to one PortOS-owned staging path. Only signature-verified image bytes- * are moved into the gallery.+ * Agy is an opt-in cloud CLI backend. Each request runs in a throwaway scratch+ * directory and directs the built-in `generate_image` tool to one PortOS-owned+ * staging path. Only signature-verified image bytes are moved into the gallery.+ *+ * `generate_image` takes input images through its `ImagePaths` parameter — up+ * to 3, usable to "edit, combine, or use as references" — so an init image and+ * the reference slots both reach it. Unlike codex/grok, `Prompt` is a REQUIRED+ * tool parameter, so an image-only agy render is rejected up front.*/import { spawn } from 'child_process';@@ -27,8 +31,11 @@ import { imageGenEvents } from '../imageGenEvents.js';import { buildNoImageReason } from './noImageReason.js';import { checkFabrication, noFabricationClause } from './fabricationGuard.js';import {- AGY_IMAGEGEN_IMAGE_MODEL, IMAGE_GEN_MODE, IMAGE_TOOL_NAMES, editIncapableModeError, nearestAgyAspectRatio,+ AGY_IMAGEGEN_IMAGE_MODEL, IMAGE_GEN_MODE, IMAGE_TOOL_NAMES, describeFidelity,+ nearestAgyAspectRatio, visualReferenceRole,} from './modes.js';+import { resolveInputImages } from './inputImages.js';+import { cloudPromptRequired } from './cloudProviderConfig.js';import { withSpawnCwdEnv } from '../../lib/spawnCwd.js';const AGY_TIMEOUT_MS = (() => {@@ -143,7 +150,33 @@ export const noImageReason = (stdoutTail = '') => buildNoImageReason(stdoutTail,describe: (said) => `Agy did not produce an image at the directed path. Agy said: "${said}"`,});-export function buildAgyPrompt({ prompt, negativePrompt, width, height, stagingPath }) {+/**+ * Directs agy's `generate_image` at whatever input images the render carries.+ *+ * `ImagePaths` is a real tool parameter — "Optional absolute paths to the images+ * to use in generation. You can pass in images here if you would like to edit,+ * combine, or use as references… you cannot pass in more than 3 images" (schema+ * probed 2026-08-09). The 3-image ceiling is enforced upstream by+ * resolveInputImages, which also fixes the order — hence `inputImagePaths` ++ * `hasInit` here rather than re-deriving "init leads" a second time.+ *+ * Naming the paths on their own line keeps them out of the tool's `Prompt`, for+ * the same reason the AspectRatio directive is separated: anything that lands+ * inside `Prompt` becomes part of what gets drawn.+ */+const agyImagePathsDirective = ({ inputImagePaths, hasInit, initImageStrength }) => {+ if (!inputImagePaths.length) return '';+ const refCount = hasInit ? inputImagePaths.length - 1 : inputImagePaths.length;+ const role = hasInit+ ? `The first is the source image to edit — ${describeFidelity(initImageStrength)}.${refCount ? ` The rest are ${visualReferenceRole(refCount)}.` : ''}`+ : `Use ${refCount === 1 ? 'it' : 'them'} as ${visualReferenceRole(refCount)}.`;+ return `\nPass these absolute paths to the tool's ImagePaths parameter, in this order: ${inputImagePaths.join(', ')}\n${role}`;+};++export function buildAgyPrompt({+ prompt, negativePrompt, width, height, stagingPath,+ inputImagePaths = [], hasInit = false, initImageStrength,+}) {const avoid = negativePrompt?.trim() ? `\nAvoid: ${negativePrompt.trim()}` : '';// `AspectRatio` is a real generate_image parameter and it defaults to '1:1'.// Naming the pixel dimensions alone is not enough — the agent has to be told@@ -159,8 +192,9 @@ export function buildAgyPrompt({ prompt, negativePrompt, width, height, stagingP// exposed this failure mode captioned itself "DIMENSIONS: 832 x 1216 (2:3)".const ratio = nearestAgyAspectRatio(width, height);const aspect = ratio ? `\nPass AspectRatio "${ratio}" to the tool.` : '';+ const images = agyImagePathsDirective({ inputImagePaths, hasInit, initImageStrength });return `Use your built-in ${AGY_TOOL} tool to generate exactly one image.-Image prompt: ${prompt.trim()}${avoid}${aspect}+Image prompt: ${prompt.trim()}${avoid}${aspect}${images}Save the generated image as a PNG file at exactly this path: ${stagingPath}${noFabricationClause(AGY_TOOL)}Do not create any other files, do not modify any code or workspace content, and do not run unrelated tools. When the file is written, you are done.`;@@ -174,13 +208,21 @@ export async function generateImage({height,negativePrompt,initImagePath,- referenceImagePaths,+ initImageStrength,+ referenceImagePaths = [],jobId: providedJobId = null,cleanC2PA = false,denoise = false,}) {- if (initImagePath || referenceImagePaths?.length) throw editIncapableModeError(IMAGE_GEN_MODE.AGY);- if (!prompt.trim()) {+ // Re-anchors every path to the approved image roots and caps at agy's+ // 3-image ImagePaths ceiling — see inputImages.js.+ const inputImages = resolveInputImages({+ mode: IMAGE_GEN_MODE.AGY, initImagePath, referenceImagePaths,+ });+ // Unlike codex/grok, agy always needs a prompt even with input images:+ // `Prompt` is in generate_image's `required` list, which the provider spec+ // records as `promptRequiredWithInputImage`.+ if (cloudPromptRequired(IMAGE_GEN_MODE.AGY, inputImages.paths.length > 0) && !prompt.trim()) {throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });}if (model && !MODEL_ID_RE.test(model)) {@@ -195,7 +237,10 @@ export async function generateImage({const stagingPath = join(scratchDir, 'output.png');await mkdir(scratchDir, { recursive: true });- const fullPrompt = buildAgyPrompt({ prompt, negativePrompt, width, height, stagingPath });+ const fullPrompt = buildAgyPrompt({+ prompt, negativePrompt, width, height, stagingPath,+ inputImagePaths: inputImages.paths, hasInit: Boolean(inputImages.initPath), initImageStrength,+ });const baseArgs = ensureAntigravityPrintArgs([], { model });const { args } = prepareAntigravityPrompt(baseArgs, fullPrompt);const bin = agyPath || DEFAULT_BIN;diff --git a/server/services/imageGen/agy.test.js b/server/services/imageGen/agy.test.jsindex ce92d6fb96..03d8a78f86 100644--- a/server/services/imageGen/agy.test.js+++ b/server/services/imageGen/agy.test.js@@ -103,11 +103,57 @@ describe('agy image provider', () => {await closeChild();});- it('rejects image-edit inputs before spawning', async () => {- await expect(agy.generateImage({+ // resolveImageInputPath requires the file to exist under PATHS.images.+ const stageGalleryImages = async (...names) => {+ await mkdir(FAKE_IMAGES_DIR, { recursive: true });+ for (const name of names) await writeFile(join(FAKE_IMAGES_DIR, name), 'fake');+ };++ it('directs an init image at the tool ImagePaths parameter with a fidelity phrase', async () => {+ await stageGalleryImages('source.png');+ await agy.generateImage({prompt: 'edit this',initImagePath: 'source.png',- })).rejects.toMatchObject({ code: 'AGY_IMAGE_EDIT_UNSUPPORTED', status: 400 });+ initImageStrength: 0.1,+ });+ expect(spawnCalls).toHaveLength(1);+ const { args } = spawnCalls[0];+ const prompt = args[args.indexOf('--print') + 1];+ expect(prompt).toContain('ImagePaths');+ expect(prompt).toContain(join(FAKE_IMAGES_DIR, 'source.png'));+ expect(prompt).toContain('the source image to edit');+ // Low strength → composition-preserving fidelity phrase.+ expect(prompt).toMatch(/preserve composition/i);+ await closeChild();+ });++ it('passes reference images through in order and caps at the tool 3-image limit', async () => {+ await stageGalleryImages('source.png', 'ref-a.png', 'ref-b.png', 'ref-c.png', 'ref-d.png');+ await agy.generateImage({+ prompt: 'a fox',+ initImagePath: 'source.png',+ referenceImagePaths: ['ref-a.png', 'ref-b.png', 'ref-c.png', 'ref-d.png'],+ });+ const { args } = spawnCalls[0];+ const prompt = args[args.indexOf('--print') + 1];+ const listed = prompt.slice(prompt.indexOf('ImagePaths parameter, in this order: ')).split('\n')[0];+ expect(listed).toContain(join(FAKE_IMAGES_DIR, 'source.png'));+ expect(listed).toContain(join(FAKE_IMAGES_DIR, 'ref-a.png'));+ expect(listed).toContain(join(FAKE_IMAGES_DIR, 'ref-b.png'));+ // generate_image accepts at most 3 — the trailing references drop out+ // rather than being sent and silently ignored.+ expect(listed).not.toContain('ref-c.png');+ expect(listed).not.toContain('ref-d.png');+ expect(prompt).toContain('visual references');+ await closeChild();+ });++ it('still requires a prompt even with input images (Prompt is a required tool param)', async () => {+ await stageGalleryImages('source.png');+ await expect(agy.generateImage({+ prompt: '',+ initImagePath: 'source.png',+ })).rejects.toMatchObject({ code: 'VALIDATION_ERROR', status: 400 });expect(spawnCalls).toHaveLength(0);});diff --git a/server/services/imageGen/cloudProviderConfig.js b/server/services/imageGen/cloudProviderConfig.jsindex fa170977df..7ce470d103 100644--- a/server/services/imageGen/cloudProviderConfig.js+++ b/server/services/imageGen/cloudProviderConfig.js@@ -24,7 +24,6 @@ import {CODEX_IMAGEGEN_DEFAULT_MODEL,IMAGE_GEN_MODE,QUEUEABLE_IMAGE_MODES,- isEditCapableMode,} from './modes.js';/**@@ -40,6 +39,16 @@ import {* saved default for one queue item. Grok is `false`: its* `image_gen` tool runs on a fixed xAI backend with no model* knob at all, so accepting an override there would be a lie.+ * - `maxInputImages` — how many input images (init image + reference images,+ * combined) the provider's image tool accepts. Probed from+ * the live tool schemas on 2026-08-09 — do NOT raise one on a+ * provider's word, re-probe the schema. Applied in exactly one+ * place: `resolveInputImages` (inputImages.js).+ * - `promptRequiredWithInputImage` — whether the provider still needs a text+ * prompt when the render already carries an input image.+ * `false` for the tools where the attached image is the whole+ * instruction; `true` where the tool schema lists the prompt+ * as required.** `modelId`/`params` both take `(config, override)` where `override` is the* per-render model id (or a falsy value when the render inherits the saved@@ -50,6 +59,10 @@ export const CLOUD_PROVIDER_SPECS = Object.freeze({label: 'Codex Imagegen',errorCode: 'CODEX_IMAGEGEN_DISABLED',supportsModelOverride: true,+ // `image_gen.referenced_image_paths` is a string[] with no declared+ // maximum, so PortOS's own ceiling applies: 1 init image + 4 ref slots.+ maxInputImages: 5,+ promptRequiredWithInputImage: false,modelId: (c, override) => override || c.model || CODEX_IMAGEGEN_DEFAULT_MODEL,params: (c, override) => ({codexPath: c.codexPath,@@ -62,6 +75,10 @@ export const CLOUD_PROVIDER_SPECS = Object.freeze({errorCode: 'GROK_IMAGEGEN_DISABLED',// Grok's image tools run on xAI's fixed image backend — no model knob.supportsModelOverride: false,+ // `image_edit.image` is a string[] with no declared maximum — same PortOS+ // ceiling as codex.+ maxInputImages: 5,+ promptRequiredWithInputImage: false,modelId: () => 'grok-imagegen',params: (g) => ({ grokPath: g.grokPath, aspectRatio: g.aspectRatio }),}),@@ -69,6 +86,11 @@ export const CLOUD_PROVIDER_SPECS = Object.freeze({label: 'Agy Imagegen',errorCode: 'AGY_IMAGEGEN_DISABLED',supportsModelOverride: true,+ // `generate_image.ImagePaths`: "you cannot pass in more than 3 images".+ maxInputImages: 3,+ // …and `Prompt` is in that tool's `required` list, so an image-only agy+ // render has nothing to send.+ promptRequiredWithInputImage: true,// The concrete cheap-tier pin (not the ANTIGRAVITY_CONFIGURED_DEFAULT// sentinel, which resolves to "no --model" and lets agy pick a possibly// reasoning-heavy session default) — see AGY_IMAGEGEN_DEFAULT_MODEL.@@ -130,6 +152,28 @@ export function resolveCloudProviderConfig(settings, mode, overrides = {}) {};}+/**+ * How many input images (init image + reference images, combined) `mode`'s+ * image tool accepts. `null` for a non-cloud mode: the local runner's ceiling+ * is the form's own slot count, and external takes none at all (it never+ * reaches here — `isEditCapableMode` rejects it first).+ */+export const maxInputImages = (mode) => CLOUD_PROVIDER_SPECS[mode]?.maxInputImages ?? null;++/**+ * Does a cloud-CLI render need a text prompt, given whether it carries an input+ * image? Text-to-image always does; with an input image it depends on whether+ * the provider's tool lists the prompt as required (`promptRequiredWithInputImage`).+ * Non-cloud modes return `false` — local and external both accept an empty+ * prompt. Rejecting up front keeps the failure a 400 instead of a queued job+ * that dies asynchronously.+ */+export const cloudPromptRequired = (mode, hasInputImage) => {+ const spec = CLOUD_PROVIDER_SPECS[mode];+ if (!spec) return false;+ return !hasInputImage || spec.promptRequiredWithInputImage === true;+};+/*** Can the queue-backed surfaces render in `mode` right now? Cloud CLIs need* their opt-in toggle; local is always usable (its own pythonPath/model@@ -138,14 +182,16 @@ export function resolveCloudProviderConfig(settings, mode, overrides = {}) {* The predicate behind the candidate walk in `resolveMode`* (pipeline/visualStageHelpers.js), so the mode ladder no longer grows a* pairwise `if` per backend.+ *+ * There is no edit/i2i variant: every queueable backend accepts an input image+ * (see EDIT_INCAPABLE_IMAGE_MODES, whose sole member — external — is not+ * queueable), so an i2i render walks this exact ladder. #3243 threaded an+ * `{ edit }` flag through here to route redraws away from Agy; that turned out+ * to be a misreading of Agy's tool schema, and the flag is gone rather than+ * left as a branch that can never be taken.*/-export function isModeUsable(settings, mode, { edit = false } = {}) {+export function isModeUsable(settings, mode) {if (!QUEUEABLE_IMAGE_MODES.includes(mode)) return false;- // An edit render (i2i / "use proof as base" / refine) can only go to a backend- // that accepts an input image at all — #3243. Without this the ladder happily- // returned Agy for a redraw, and the failure surfaced asynchronously in the- // queue as AGY_IMAGE_EDIT_UNSUPPORTED, long after the request 200'd.- if (edit && !isEditCapableMode(mode)) return false;const cloud = resolveCloudProviderConfig(settings, mode);return cloud ? cloud.enabled : true;}@@ -154,16 +200,13 @@ export function isModeUsable(settings, mode, { edit = false } = {}) {* First usable mode from an ordered candidate list, falling back to the* cloud providers (in `CLOUD_IMAGE_GEN_MODES` order) and finally local.*- * Pass `{ edit: true }` when the render carries an input image: edit-incapable- * backends are then skipped at every rung, so a record pinned to such a backend- * FALLS THROUGH to the next usable one rather than failing. Falling through is- * deliberate — a pin is a preference, and the surrounding pins already degrade- * this way when a pinned backend is disabled (the enforceRenderBackendPin- * contract). LOCAL is edit-capable, so the tail always resolves.+ * A record pinned to a DISABLED backend falls through to the next usable one+ * rather than failing — a pin is a preference (the enforceRenderBackendPin+ * contract). LOCAL is always usable, so the tail always resolves.*/-export function pickUsableMode(settings, candidates = [], { edit = false } = {}) {+export function pickUsableMode(settings, candidates = []) {const ordered = [...candidates, ...CLOUD_IMAGE_GEN_MODES, IMAGE_GEN_MODE.LOCAL];- return ordered.find((m) => m && isModeUsable(settings, m, { edit })) || IMAGE_GEN_MODE.LOCAL;+ return ordered.find((m) => m && isModeUsable(settings, m)) || IMAGE_GEN_MODE.LOCAL;}/**diff --git a/server/services/imageGen/cloudProviderConfig.test.js b/server/services/imageGen/cloudProviderConfig.test.jsindex 3edc9aaf7c..2795712751 100644--- a/server/services/imageGen/cloudProviderConfig.test.js+++ b/server/services/imageGen/cloudProviderConfig.test.js@@ -10,7 +10,6 @@ import {AGY_IMAGEGEN_DEFAULT_MODEL,CODEX_IMAGEGEN_DEFAULT_MODEL,IMAGE_GEN_MODE,- resolveQueueImageEditMode,resolveQueueImageMode,} from './modes.js';import { recordRenderPin } from '../../lib/renderTargets.js';@@ -169,17 +168,19 @@ describe('isModeUsable', () => {expect(isModeUsable(settingsWith({}), 'nonsense')).toBe(false);});- it('refuses an edit-incapable backend for an edit render, enabled or not (#3243)', () => {- // Agy's generate_image takes no input image, so an i2i render routed there- // throws AGY_IMAGE_EDIT_UNSUPPORTED — asynchronously, inside the queue, long- // after the request 200'd. Enabled-ness is irrelevant: it is a capability,- // not a toggle.- const s = settingsWith({ agy: { enabled: true }, codex: { enabled: true } });- expect(isModeUsable(s, IMAGE_GEN_MODE.AGY)).toBe(true);- expect(isModeUsable(s, IMAGE_GEN_MODE.AGY, { edit: true })).toBe(false);- // Edit-capable backends are unaffected by the flag.- expect(isModeUsable(s, IMAGE_GEN_MODE.CODEX, { edit: true })).toBe(true);- expect(isModeUsable(s, IMAGE_GEN_MODE.LOCAL, { edit: true })).toBe(true);+ it('allows every queueable backend for an edit render — all take input images', () => {+ // Each backend feeds an input image to its own tool: local `--image-path`,+ // codex `referenced_image_paths`, grok `image_edit.image`, agy+ // `ImagePaths`. The `edit` flag stays the single gate a future+ // input-image-less backend would need, so it is asserted as a no-op rather+ // than dropped.+ const s = settingsWith({ agy: { enabled: true }, codex: { enabled: true }, grok: { enabled: true } });+ for (const mode of [IMAGE_GEN_MODE.AGY, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK, IMAGE_GEN_MODE.LOCAL]) {+ expect(isModeUsable(s, mode, { edit: true })).toBe(isModeUsable(s, mode));+ }+ // Disabled-ness still gates, independently of the edit flag.+ const off = settingsWith({ agy: { enabled: false }, codex: { enabled: true } });+ expect(isModeUsable(off, IMAGE_GEN_MODE.AGY, { edit: true })).toBe(false);});});@@ -209,22 +210,21 @@ describe('pickUsableMode', () => {)).toBe(IMAGE_GEN_MODE.CODEX);});- it('falls a record pinned to an edit-incapable backend through to the next usable one (#3243)', () => {- // The bug: a series pinned to Agy rendered plain text-to-image fine, but- // every redraw ("use proof as base", a reference page, a refine pass)- // enqueued and then failed async. Falling through is the right answer, not- // an error — a pin is a preference, and the surrounding pins already degrade- // this way when a pinned backend is disabled.+ it('keeps a record pin on an edit render — every queueable backend takes input images', () => {+ // Agy used to fall through here (#3243) because its generate_image was+ // believed to take no input image. Its tool schema documents `ImagePaths`+ // ("edit, combine, or use as references"), so the pin is now honored and an+ // edit render lands where the user asked for it.const s = settingsWith({ agy: { enabled: true }, codex: { enabled: true } });expect(pickUsableMode(s, [IMAGE_GEN_MODE.AGY])).toBe(IMAGE_GEN_MODE.AGY);- expect(pickUsableMode(s, [IMAGE_GEN_MODE.AGY], { edit: true })).toBe(IMAGE_GEN_MODE.CODEX);+ expect(pickUsableMode(s, [IMAGE_GEN_MODE.AGY], { edit: true })).toBe(IMAGE_GEN_MODE.AGY);});- it('lands on local for an edit render when every cloud backend is edit-incapable or off (#3243)', () => {+ it('lands on local for an edit render when every cloud backend is off', () => {// LOCAL is edit-capable, so the auto tail always resolves — an edit render// can never fall off the end of the ladder.- const agyOnly = settingsWith({ codex: { enabled: false }, grok: { enabled: false }, agy: { enabled: true } });- expect(pickUsableMode(agyOnly, [IMAGE_GEN_MODE.AGY], { edit: true })).toBe(IMAGE_GEN_MODE.LOCAL);+ const allOff = settingsWith({ codex: { enabled: false }, grok: { enabled: false }, agy: { enabled: false } });+ expect(pickUsableMode(allOff, [IMAGE_GEN_MODE.AGY], { edit: true })).toBe(IMAGE_GEN_MODE.LOCAL);});it('falls back to local when nothing else is usable', () => {@@ -250,8 +250,8 @@ describe('queue mode resolution with Agy', () => {expect(resolveQueueImageMode(undefined, settings)).toBe(IMAGE_GEN_MODE.AGY);});- it('excludes Agy from image-edit fallback', () => {- expect(resolveQueueImageEditMode(IMAGE_GEN_MODE.AGY, settings)).toBe(IMAGE_GEN_MODE.CODEX);+ it('uses the same ladder for image-edit work — Agy takes input images too', () => {+ expect(resolveQueueImageMode(IMAGE_GEN_MODE.AGY, settings)).toBe(IMAGE_GEN_MODE.AGY);});});diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.jsindex 3413ab57c4..3cf1197c3a 100644--- a/server/services/imageGen/codex.js+++ b/server/services/imageGen/codex.js@@ -35,15 +35,20 @@ import { existsSync } from 'fs';import { join } from 'path';import { homedir } from 'os';import { randomUUID } from 'crypto';-import { atomicWrite, ensureDir, PATHS, resolveImageInputPath } from '../../lib/fileUtils.js';+import { atomicWrite, ensureDir, PATHS } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';import { autoCleanGeneratedImage } from '../../lib/imageClean.js';import { imageGenEvents } from '../imageGenEvents.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';import { killWithEscalation } from '../../lib/killWithEscalation.js';import { buildCodexStartupArgs, buildEffortArgs, CODEX_EFFORT_LEVELS } from '../../lib/providerModels.js';-import { IMAGE_GEN_MODE, CODEX_IMAGEGEN_DEFAULT_MODEL, CODEX_IMAGEGEN_DEFAULT_EFFORT, describeFidelity } from './modes.js';+import {+ IMAGE_GEN_MODE, CODEX_IMAGEGEN_DEFAULT_MODEL, CODEX_IMAGEGEN_DEFAULT_EFFORT,+ describeFidelity, visualReferenceRole,+} from './modes.js';import { buildNoImageReason } from './noImageReason.js';+import { resolveInputImages } from './inputImages.js';+import { cloudPromptRequired } from './cloudProviderConfig.js';// 20 minutes — built-in `image_gen` typically returns in 30–90s, but with the// parallel codex lane several renders share OpenAI throughput and a single@@ -132,14 +137,40 @@ export async function checkConnection({ codexPath } = {}) {const SESSION_ID_RE = /^session id:\s*([0-9a-f-]{36})/im;-// When `initImagePath` is set we attach the file via codex CLI's `-i <FILE>`-// flag and reshape the prompt so the `$imagegen` skill feeds the attachment-// to `image_gen` as an input image (gpt-image-2's image-edit mode).-// `initImageStrength` is mapped to a fidelity phrase via describeFidelity —-// codex CLI exposes no numeric denoise knob.+/**+ * The `$imagegen` directive describing however many images are attached.+ *+ * Codex's `image_gen` tool takes `referenced_image_paths` — an ARRAY of+ * references (probed 2026-08-09) — so an init image and the reference slots are+ * the same kind of thing to the tool; only the wording differs. The init image+ * leads and gets the fidelity phrase (`initImageStrength` mapped via+ * describeFidelity — codex CLI exposes no numeric denoise knob); the rest are+ * named as additional visual references so the model doesn't try to edit all of+ * them at once.+ */+export function buildCodexAttachmentPrefix({ initPath, referenceCount, initImageStrength }) {+ if (initPath) {+ // Single attachment keeps the wording it has always shipped with; naming a+ // position only makes sense once there is more than one to disambiguate.+ const subject = referenceCount > 0 ? 'the FIRST attached image' : 'the attached reference image';+ const refs = referenceCount > 0+ ? ` Use the other ${referenceCount === 1 ? 'attached image' : `${referenceCount} attached images`} as ${visualReferenceRole(referenceCount)}.`+ : '';+ return `Edit ${subject} — ${describeFidelity(initImageStrength)}.${refs} Render target:\n`;+ }+ if (referenceCount > 0) {+ const subject = referenceCount === 1 ? 'the attached image' : `all ${referenceCount} attached images`;+ return `Generate a new image conditioned on ${subject} — use ${referenceCount === 1 ? 'it' : 'them'} as ${visualReferenceRole(referenceCount)}. Render target:\n`;+ }+ return '';+}++// Input images are attached via codex CLI's `-i <FILE>` flag (variadic, so all+// of them ride one flag) and the prompt is reshaped so the `$imagegen` skill+// feeds the attachments to `image_gen` as references.export async function generateImage({codexPath, model, effort, prompt = '', width, height, negativePrompt,- initImagePath, initImageStrength,+ initImagePath, initImageStrength, referenceImagePaths = [],jobId: providedJobId = null,cleanC2PA = false,denoise = false,@@ -160,18 +191,16 @@ export async function generateImage({const requestedEffort = (typeof effort === 'string' && effort.trim()) ? effort.trim() : CODEX_IMAGEGEN_DEFAULT_EFFORT;const effectiveEffort = CODEX_EFFORT_LEVELS.includes(requestedEffort) ? requestedEffort : CODEX_IMAGEGEN_DEFAULT_EFFORT;- // Defense-in-depth: HTTP routes already resolve basenames to absolute paths,- // but re-anchor here so any future caller can't attach an arbitrary local- // file via the codex CLI's `-i` flag. Mirrors imageGen/local.js — accepts- // the gallery, the image-refs upload dir (where init uploads are staged), and- // shipped visual templates.- const validInitImagePath = (initImagePath && typeof initImagePath === 'string')- ? resolveImageInputPath(initImagePath)- : null;-- // An empty prompt is fine when editing an init image (the attached image is- // the instruction); a pure text-to-image codex render still needs a prompt.- if (!validInitImagePath && !prompt?.trim()) {+ // Re-anchors every path to the approved image roots and caps the list at what+ // codex's image_gen accepts — see inputImages.js.+ const inputImages = resolveInputImages({+ mode: IMAGE_GEN_MODE.CODEX, initImagePath, referenceImagePaths,+ });++ // An empty prompt is fine when an image is attached (the attachment is the+ // instruction); a pure text-to-image codex render still needs a prompt. The+ // per-provider rule lives on the provider spec — see cloudPromptRequired.+ if (cloudPromptRequired(IMAGE_GEN_MODE.CODEX, inputImages.paths.length > 0) && !prompt?.trim()) {throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });}@@ -188,9 +217,11 @@ export async function generateImage({const sizeHint = (width && height) ? ` (${width}x${height})` : '';const qualityHint = (width >= 1536 || height >= 1536) ? ' (high quality)' : '';const avoidHint = negativePrompt?.trim() ? `\nAvoid: ${negativePrompt.trim()}` : '';- const editPrefix = validInitImagePath- ? `Edit the attached reference image — ${describeFidelity(initImageStrength)}. Render target:\n`- : '';+ const editPrefix = buildCodexAttachmentPrefix({+ initPath: inputImages.initPath,+ referenceCount: inputImages.referencePaths.length,+ initImageStrength,+ });const fullPrompt = `$imagegen ${editPrefix}${prompt.trim()}${sizeHint}${qualityHint}${avoidHint}`;const bin = codexPath || DEFAULT_BIN;@@ -212,9 +243,10 @@ export async function generateImage({// to `low` — also before the variadic `-i`. A user who baked an effort pin// into their config is respected via hasEffortFlag inside buildEffortArgs....buildEffortArgs(effectiveEffort, { command: 'codex' }),- ...(validInitImagePath ? ['-i', validInitImagePath] : []),+ // `-i` is variadic, so every input image rides one flag.+ ...(inputImages.paths.length ? ['-i', ...inputImages.paths] : []),'-m', effectiveModel,- ...(validInitImagePath ? ['--'] : []),+ ...(inputImages.paths.length ? ['--'] : []),fullPrompt,];diff --git a/server/services/imageGen/codex.test.js b/server/services/imageGen/codex.test.jsindex 4f3e18b9e9..00b6dad035 100644--- a/server/services/imageGen/codex.test.js+++ b/server/services/imageGen/codex.test.js@@ -196,6 +196,46 @@ describe('codex provider — generateImage', () => {await flush();});+ it('attaches every reference image on the one variadic -i flag', async () => {+ await mkdir(FAKE_IMAGES_DIR, { recursive: true });+ for (const n of ['proof.png', 'ref-a.png', 'ref-b.png']) {+ await writeFile(join(FAKE_IMAGES_DIR, n), 'fake');+ }+ await codex.generateImage({+ prompt: 'cover art', initImagePath: 'proof.png', initImageStrength: 0.2,+ referenceImagePaths: ['ref-a.png', 'ref-b.png'],+ });+ const { args } = spawnCalls[0];+ const i = args.indexOf('-i');+ expect(args.slice(i + 1, i + 4)).toEqual([+ join(FAKE_IMAGES_DIR, 'proof.png'),+ join(FAKE_IMAGES_DIR, 'ref-a.png'),+ join(FAKE_IMAGES_DIR, 'ref-b.png'),+ ]);+ // The `--` terminator still bounds the variadic so the prompt lands as the+ // positional rather than being swallowed as a fourth image path.+ expect(args).toContain('--');+ expect(args[args.length - 1]).toMatch(/edit the FIRST attached image/i);+ expect(args[args.length - 1]).toMatch(/other 2 attached images as visual references/i);+ spawnCalls[0].child.exitCode = 1;+ spawnCalls[0].child.emit('close', 1, null);+ await flush();+ });++ it('describes a reference-only render as conditioning, not an edit', async () => {+ await mkdir(FAKE_IMAGES_DIR, { recursive: true });+ await writeFile(join(FAKE_IMAGES_DIR, 'ref-a.png'), 'fake');+ await codex.generateImage({ prompt: 'a fox', referenceImagePaths: ['ref-a.png'] });+ const { args } = spawnCalls[0];+ expect(args.slice(args.indexOf('-i') + 1, args.indexOf('-i') + 2))+ .toEqual([join(FAKE_IMAGES_DIR, 'ref-a.png')]);+ expect(args[args.length - 1]).toMatch(/conditioned on the attached image/i);+ expect(args[args.length - 1]).not.toMatch(/^\$imagegen Edit /);+ spawnCalls[0].child.exitCode = 1;+ spawnCalls[0].child.emit('close', 1, null);+ await flush();+ });+it('rejects when prompt is empty and there is no init image', async () => {await expect(codex.generateImage({ prompt: ' ' })).rejects.toThrow(/Prompt is required/);});diff --git a/server/services/imageGen/grok.js b/server/services/imageGen/grok.jsindex f49ff7c70b..f2203ac8f5 100644--- a/server/services/imageGen/grok.js+++ b/server/services/imageGen/grok.js@@ -37,7 +37,7 @@ import { copyFile, mkdir, open, rename, rm, stat, unlink } from 'fs/promises';import { isAbsolute, join, resolve as pathResolve, sep } from 'path';import { tmpdir } from 'os';import { randomUUID } from 'crypto';-import { atomicWrite, detectImageFormat, ensureDir, PATHS, resolveImageInputPath } from '../../lib/fileUtils.js';+import { atomicWrite, detectImageFormat, ensureDir, PATHS } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';import { autoCleanGeneratedImage } from '../../lib/imageClean.js';import { imageGenEvents } from '../imageGenEvents.js';@@ -48,7 +48,11 @@ import { checkFabrication, noFabricationClause } from './fabricationGuard.js';import sharp from 'sharp';import { bufferedSpawn, killProcessTree, prepareCliSpawn } from '../../lib/bufferedSpawn.js';import { ensureGrokHeadlessArgs, prepareGrokPromptFile } from '../../lib/grok.js';-import { IMAGE_GEN_MODE, describeFidelity, grokImageTool, nearestAspectRatio } from './modes.js';+import {+ IMAGE_GEN_MODE, describeFidelity, grokImageTool, nearestAspectRatio, visualReferenceRole,+} from './modes.js';+import { resolveInputImages } from './inputImages.js';+import { cloudPromptRequired } from './cloudProviderConfig.js';import { withSpawnCwdEnv } from '../../lib/spawnCwd.js';// 20 minutes — grok's image_gen typically returns in well under a minute, but@@ -157,39 +161,72 @@ export const noImageReason = (stdoutTail = '') => buildNoImageReason(stdoutTail,});// Build the single-turn agent prompt that triggers image_gen (or image_edit-// for i2i) and directs the output to a PortOS-chosen path. Grok is a general-// coding agent, so the prompt is explicit about the tool, the save path, and-// staying out of everything else.-export function buildGrokPrompt({ prompt, negativePrompt, aspectRatio, stagingPath, initImagePath, initImageStrength }) {- const avoid = negativePrompt?.trim() ? `\nAvoid: ${negativePrompt.trim()}` : '';- const ratio = aspectRatio ? `\nUse aspect_ratio "${aspectRatio}".` : '';- const task = initImagePath- ? `Use your built-in image_edit tool to transform the source image at ${initImagePath} — ${describeFidelity(initImageStrength)}.\nEdit instruction: ${prompt.trim()}${avoid}`- : `Use your built-in image_gen tool to generate exactly one image.\nImage prompt: ${prompt.trim()}${avoid}`;- return `${task}${ratio}\nSave the generated image as a PNG file at exactly this path: ${stagingPath}\n${noFabricationClause(grokImageTool(initImagePath))}\nDo not create any other files, do not modify any code, and do not run any other tools beyond what is needed to generate the image and write it to that path. When the file is written, you are done.`;+// whenever the render carries any input image) and directs the output to a+// PortOS-chosen path. Grok is a general coding agent, so the prompt is explicit+// about the tool, the save path, and staying out of everything else.+//+// grok's `image_gen` has NO image parameter at all, so reference images route+// to `image_edit` too — its `image` parameter is an ARRAY of references (probed+// 2026-08-09: "Reference image(s) to condition the edit on"), which is exactly+// how PortOS's reference slots are fed. The init image, when present, leads the+// array and is the one the fidelity phrase describes.+export function buildGrokPrompt({+ prompt, negativePrompt, aspectRatio, stagingPath,+ initImagePath, initImageStrength, referenceImagePaths = [],+}) {+ const refCount = referenceImagePaths.length;+ const refList = referenceImagePaths.join(', ');+ const refNoun = refCount === 1 ? 'this reference image' : `these ${refCount} reference images`;+ const inOrder = refCount > 1 ? ', in this order,' : '';+ const toolName = grokImageTool(Boolean(initImagePath || refCount));++ // One clause per line, assembled in the order grok reads them: what to call,+ // what to pass it, then what to draw.+ const lines = [];+ if (initImagePath) {+ lines.push(`Use your built-in image_edit tool to transform the source image at ${initImagePath} — ${describeFidelity(initImageStrength)}. Pass that source image FIRST in the tool's \`image\` array.`);+ if (refCount) {+ lines.push(`Also pass ${refNoun} to the tool's \`image\` array after it${inOrder} as ${visualReferenceRole(refCount)}: ${refList}`);+ }+ } else if (refCount) {+ lines.push(`Use your built-in image_edit tool to generate exactly one image conditioned on ${refNoun}.`);+ lines.push(`Pass ${refCount === 1 ? 'it' : 'them'} to the tool's \`image\` array${inOrder} as ${visualReferenceRole(refCount)}: ${refList}`);+ } else {+ lines.push('Use your built-in image_gen tool to generate exactly one image.');+ }+ // An edit reads as an instruction ON the source image; everything else is a+ // description OF the image to make.+ lines.push(`${initImagePath ? 'Edit instruction' : 'Image prompt'}: ${prompt.trim()}`);+ if (negativePrompt?.trim()) lines.push(`Avoid: ${negativePrompt.trim()}`);+ if (aspectRatio) lines.push(`Use aspect_ratio "${aspectRatio}".`);+ lines.push(`Save the generated image as a PNG file at exactly this path: ${stagingPath}`);+ lines.push(noFabricationClause(toolName));+ lines.push('Do not create any other files, do not modify any code, and do not run any other tools beyond what is needed to generate the image and write it to that path. When the file is written, you are done.');+ return lines.join('\n');}// `initImageStrength` maps to a fidelity phrase (grok's image_edit has no// numeric denoise knob, same constraint as codex).export async function generateImage({grokPath, aspectRatio, prompt = '', width, height, negativePrompt,- initImagePath, initImageStrength,+ initImagePath, initImageStrength, referenceImagePaths = [],jobId: providedJobId = null,cleanC2PA = false,denoise = false,}) {await ensureDir(PATHS.images);- // Defense-in-depth: re-anchor the init image to the allowed input roots so- // no caller can point grok's image_edit at an arbitrary local file. Mirrors- // imageGen/codex.js.- const validInitImagePath = (initImagePath && typeof initImagePath === 'string')- ? resolveImageInputPath(initImagePath)- : null;+ // Re-anchors every path to the allowed input roots (so no caller can point+ // grok's image_edit at an arbitrary local file) and caps the list — see+ // inputImages.js.+ const inputImages = resolveInputImages({+ mode: IMAGE_GEN_MODE.GROK, initImagePath, referenceImagePaths,+ });- // An empty prompt is fine when editing an init image; a pure text-to-image- // grok render still needs one.- if (!validInitImagePath && !prompt?.trim()) {+ // An empty prompt is fine when an input image is present; a pure+ // text-to-image grok render still needs one. The per-provider rule lives on+ // the provider spec — see cloudPromptRequired.+ if (cloudPromptRequired(IMAGE_GEN_MODE.GROK, inputImages.paths.length > 0) && !prompt?.trim()) {throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });}@@ -215,7 +252,8 @@ export async function generateImage({const fullPrompt = buildGrokPrompt({prompt, negativePrompt, aspectRatio: effectiveRatio, stagingPath,- initImagePath: validInitImagePath, initImageStrength,+ initImagePath: inputImages.initPath, initImageStrength,+ referenceImagePaths: inputImages.referencePaths,});const bin = grokPath || DEFAULT_BIN;@@ -245,7 +283,7 @@ export async function generateImage({// attaches to the per-job SSE stream (mirrors codex.js/local.js).runGrok(job, jobId, bin, args, {useStdin, fullPrompt, cleanupPromptFile, scratchDir, stagingPath, outputPath, filename, meta, cleanC2PA, denoise,- toolName: grokImageTool(validInitImagePath),+ toolName: grokImageTool(inputImages.paths.length > 0),}).catch((err) => {console.log(`❌ grok run failed [${jobId.slice(0, 8)}]: ${err?.message}`);});@@ -261,7 +299,7 @@ export async function generateImage({async function runGrok(job, jobId, bin, args, {useStdin, fullPrompt, cleanupPromptFile, scratchDir, stagingPath, outputPath, filename, meta, cleanC2PA = false, denoise = false,- toolName = grokImageTool(null),+ toolName = grokImageTool(false),}) {// A path-shaped grokPath (contains a separator) must resolve against the// PortOS working directory NOW — the child spawns with cwd set to thediff --git a/server/services/imageGen/grok.test.js b/server/services/imageGen/grok.test.jsindex 654323316e..ba3536803e 100644--- a/server/services/imageGen/grok.test.js+++ b/server/services/imageGen/grok.test.js@@ -159,6 +159,46 @@ describe('grok provider — generateImage', () => {await closeChild();});+ it('routes a reference-only render to image_edit — image_gen takes no input image', async () => {+ await mkdir(FAKE_IMAGES_DIR, { recursive: true });+ await writeFile(join(FAKE_IMAGES_DIR, 'ref-a.png'), 'fake');+ await writeFile(join(FAKE_IMAGES_DIR, 'ref-b.png'), 'fake');+ await grok.generateImage({ prompt: 'a fox', referenceImagePaths: ['ref-a.png', 'ref-b.png'] });+ const prompt = promptOf();+ expect(prompt).toContain('image_edit');+ expect(prompt).toContain('`image` array');+ expect(prompt).toContain(join(FAKE_IMAGES_DIR, 'ref-a.png'));+ expect(prompt).toContain(join(FAKE_IMAGES_DIR, 'ref-b.png'));+ // No source image, so no fidelity phrase — these are references, not an edit.+ expect(prompt).not.toMatch(/transform the source image/i);+ await closeChild();+ });++ it('puts the init image first and the references after it', async () => {+ await mkdir(FAKE_IMAGES_DIR, { recursive: true });+ await writeFile(join(FAKE_IMAGES_DIR, 'proof.png'), 'fake');+ await writeFile(join(FAKE_IMAGES_DIR, 'ref-a.png'), 'fake');+ await grok.generateImage({+ prompt: 'cover art', initImagePath: 'proof.png', initImageStrength: 0.2,+ referenceImagePaths: ['ref-a.png'],+ });+ const prompt = promptOf();+ expect(prompt).toMatch(/source image at .*proof\.png/);+ expect(prompt).toContain('FIRST in the tool');+ expect(prompt.indexOf(join(FAKE_IMAGES_DIR, 'proof.png')))+ .toBeLessThan(prompt.indexOf(join(FAKE_IMAGES_DIR, 'ref-a.png')));+ await closeChild();+ });++ it('drops a reference path that escapes the gallery (defense-in-depth)', async () => {+ await grok.generateImage({ prompt: 'a fox', referenceImagePaths: ['/etc/passwd'] });+ const prompt = promptOf();+ expect(prompt).not.toContain('/etc/passwd');+ // Nothing survived, so it falls back to plain text-to-image.+ expect(prompt).not.toContain('image_edit');+ await closeChild();+ });+it('drops an initImagePath that escapes the gallery (defense-in-depth)', async () => {await grok.generateImage({ prompt: 'cover art', initImagePath: '/etc/passwd', initImageStrength: 0.2 });const prompt = promptOf();diff --git a/server/services/imageGen/index.js b/server/services/imageGen/index.jsindex b1d3ea9d62..9a1bd33552 100644--- a/server/services/imageGen/index.js+++ b/server/services/imageGen/index.js@@ -20,7 +20,7 @@ import * as codex from './codex.js';import * as grok from './grok.js';import * as agy from './agy.js';import {- IMAGE_GEN_MODE, IMAGE_GEN_MODES, CLOUD_IMAGE_GEN_MODES, editIncapableModeError, isEditCapableMode,+ IMAGE_GEN_MODE, IMAGE_GEN_MODES, CLOUD_IMAGE_GEN_MODES, isEditCapableMode,} from './modes.js';import { resolveCloudProviderConfig } from './cloudProviderConfig.js';@@ -97,14 +97,19 @@ export async function generateImage(params) {// so providers never see the raw field.const cloudModel = normalized.cloudModel;delete normalized.cloudModel;- // i2i is supported by local (mflux/diffusers --image-path), codex- // (gpt-image-2 image-edit via codex CLI's -i flag), and grok (image_edit).- // External SD-API has no i2i wiring in this codebase, so drop the init- // image there rather than failing the whole render — the prompt still- // produces a useful txt2img.- if (mode === IMAGE_GEN_MODE.EXTERNAL && (normalized.initImagePath || normalized.initImageStrength != null)) {+ // Input images are supported by local (mflux/diffusers --image-path plus+ // FLUX.2 --reference-images), codex (image_gen.referenced_image_paths via the+ // CLI's -i flag), grok (image_edit.image) and agy (generate_image.ImagePaths).+ // External SD-API has no input-image wiring in this codebase, so drop them+ // there rather than failing the whole render — the prompt still produces a+ // useful txt2img. (The route/prepareParams path rejects instead, because it+ // has already staged uploads that would otherwise be orphaned; this branch+ // covers direct in-process callers.)+ if (!isEditCapableMode(mode)) {delete normalized.initImagePath;delete normalized.initImageStrength;+ delete normalized.referenceImagePaths;+ delete normalized.referenceImageStrengths;}// Cleaners are per-provider-mode. The route layer already resolves them so// the queue/route paths agree, but resolve here too for direct callers@@ -121,9 +126,6 @@ export async function generateImage(params) {const cloud = resolveCloudProviderConfig(s, mode, { model: cloudModel });if (cloud) {if (!cloud.enabled) throw cloud.disabledError;- if (!isEditCapableMode(mode) && (normalized.initImagePath || normalized.referenceImagePaths?.length)) {- throw editIncapableModeError(mode);- }return CLOUD_PROVIDERS[mode].generateImage({ ...cloud.providerParams, cleanC2PA, denoise, ...normalized });}if (mode === IMAGE_GEN_MODE.LOCAL) {diff --git a/server/services/imageGen/inputImages.js b/server/services/imageGen/inputImages.jsnew file mode 100644index 0000000000..d7e8ab393a--- /dev/null+++ b/server/services/imageGen/inputImages.js@@ -0,0 +1,59 @@+/**+ * Cloud-CLI input images — the one place that turns a render request's+ * `initImagePath` + `referenceImagePaths` into the ordered, re-anchored,+ * per-backend-capped list a CLI hands to its image tool.+ *+ * All three cloud CLIs take their input images as a single ordered array+ * (codex `referenced_image_paths`, grok `image_edit.image`, agy `ImagePaths`),+ * so they share one resolution rule: the init image, if any, leads — it is the+ * one the fidelity phrase describes — followed by the reference slots in submit+ * order. Only the per-backend ceiling differs, and that lives on the provider+ * spec (`maxInputImages` in cloudProviderConfig.js) with the rest of the+ * per-provider capability facts.+ *+ * Path re-anchoring is defense-in-depth, mirroring imageGen/local.js: the HTTP+ * routes already resolve basenames to absolute paths, but a CLI is handed these+ * as literal filesystem paths, so re-anchor here too and no caller can point one+ * at an arbitrary local file.+ */++import { resolveImageInputPath } from '../../lib/fileUtils.js';+import { maxInputImages } from './cloudProviderConfig.js';++const asPathList = (value) => (Array.isArray(value) ? value : [])+ .filter((p) => typeof p === 'string' && p.trim());++/**+ * @param {object} opts+ * @param {string} opts.mode - IMAGE_GEN_MODE key (picks the cap)+ * @param {string|null} opts.initImagePath - primary source image, if any+ * @param {string[]} opts.referenceImagePaths - additional reference images+ * @returns {{ paths: string[], initPath: string|null, referencePaths: string[] }}+ * `paths` is what the tool receives (init first). `initPath` is non-null only+ * when a valid init image survived, so callers can pick the edit-vs-reference+ * wording without re-deriving the ordering; `referencePaths` is the same list+ * minus that leading source image.+ */+export function resolveInputImages({ mode, initImagePath = null, referenceImagePaths = [] } = {}) {+ const rawInit = (typeof initImagePath === 'string' && initImagePath.trim()) ? initImagePath : null;+ // An unresolvable path drops out rather than failing the render — the caller+ // still gets a usable (possibly text-only) generation instead of a 500.+ const resolvedInit = rawInit ? resolveImageInputPath(rawInit) : null;+ const resolvedRefs = asPathList(referenceImagePaths)+ .map((p) => resolveImageInputPath(p))+ .filter(Boolean);++ const ordered = [...(resolvedInit ? [resolvedInit] : []), ...resolvedRefs];+ // A mode with no declared cap (a direct caller passing something odd) gets no+ // truncation rather than a silent truncation to zero.+ const limit = maxInputImages(mode) ?? ordered.length;+ const paths = ordered.slice(0, limit);+ if (ordered.length > paths.length) {+ console.log(`⚠️ ${mode} accepts at most ${limit} input images — dropping ${ordered.length - paths.length} reference(s)`);+ }+ return {+ paths,+ initPath: resolvedInit,+ referencePaths: resolvedInit ? paths.slice(1) : paths,+ };+}diff --git a/server/services/imageGen/inputImages.test.js b/server/services/imageGen/inputImages.test.jsnew file mode 100644index 0000000000..71f0d64cdd--- /dev/null+++ b/server/services/imageGen/inputImages.test.js@@ -0,0 +1,90 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { mkdir, rm, writeFile } from 'fs/promises';+import { join } from 'path';+import { tmpdir } from 'os';++const TEST_ROOT = join(tmpdir(), `portos-inputimages-test-${process.pid}-${Date.now()}`);+const FAKE_IMAGES_DIR = join(TEST_ROOT, 'data-images');+vi.mock('../../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../../lib/fileUtils.js');+ actual.PATHS.images = FAKE_IMAGES_DIR;+ return actual;+});++const { resolveInputImages } = await import('./inputImages.js');+const { IMAGE_GEN_MODE } = await import('./modes.js');+const { maxInputImages } = await import('./cloudProviderConfig.js');++const stage = async (...names) => {+ await mkdir(FAKE_IMAGES_DIR, { recursive: true });+ for (const name of names) await writeFile(join(FAKE_IMAGES_DIR, name), 'fake');+};+const abs = (name) => join(FAKE_IMAGES_DIR, name);++beforeEach(async () => {+ await rm(TEST_ROOT, { recursive: true, force: true }).catch(() => {});+ await mkdir(TEST_ROOT, { recursive: true });+});+afterEach(async () => {+ await rm(TEST_ROOT, { recursive: true, force: true }).catch(() => {});+});++describe('resolveInputImages', () => {+ it('orders the init image first and re-anchors every path to an approved root', async () => {+ await stage('init.png', 'ref-a.png', 'ref-b.png');+ const out = resolveInputImages({+ mode: IMAGE_GEN_MODE.CODEX,+ initImagePath: 'init.png',+ referenceImagePaths: ['ref-a.png', 'ref-b.png'],+ });+ expect(out.paths).toEqual([abs('init.png'), abs('ref-a.png'), abs('ref-b.png')]);+ expect(out.initPath).toBe(abs('init.png'));+ expect(out.referencePaths).toEqual([abs('ref-a.png'), abs('ref-b.png')]);+ });++ it('reports references without an init image as references, not a source image', async () => {+ await stage('ref-a.png');+ const out = resolveInputImages({+ mode: IMAGE_GEN_MODE.GROK,+ referenceImagePaths: ['ref-a.png'],+ });+ expect(out.initPath).toBeNull();+ expect(out.referencePaths).toEqual([abs('ref-a.png')]);+ });++ it('caps at the per-backend limit, dropping from the tail', async () => {+ await stage('init.png', 'a.png', 'b.png', 'c.png', 'd.png');+ const out = resolveInputImages({+ mode: IMAGE_GEN_MODE.AGY,+ initImagePath: 'init.png',+ referenceImagePaths: ['a.png', 'b.png', 'c.png', 'd.png'],+ });+ expect(maxInputImages(IMAGE_GEN_MODE.AGY)).toBe(3);+ expect(out.paths).toEqual([abs('init.png'), abs('a.png'), abs('b.png')]);+ });++ it('drops a path that escapes the approved roots instead of forwarding it', () => {+ const out = resolveInputImages({+ mode: IMAGE_GEN_MODE.CODEX,+ initImagePath: '/etc/passwd',+ referenceImagePaths: ['/etc/hosts'],+ });+ expect(out.paths).toEqual([]);+ expect(out.initPath).toBeNull();+ });++ it('returns an empty list for a render with no input images', () => {+ const out = resolveInputImages({ mode: IMAGE_GEN_MODE.CODEX });+ expect(out.paths).toEqual([]);+ expect(out.referencePaths).toEqual([]);+ });++ it('leaves an unknown mode uncapped rather than truncating it to nothing', async () => {+ await stage('a.png', 'b.png');+ const out = resolveInputImages({+ mode: 'not-a-backend',+ referenceImagePaths: ['a.png', 'b.png'],+ });+ expect(out.paths).toHaveLength(2);+ });+});diff --git a/server/services/imageGen/modes.js b/server/services/imageGen/modes.jsindex 989eb18e53..07ff369514 100644--- a/server/services/imageGen/modes.js+++ b/server/services/imageGen/modes.js@@ -41,15 +41,29 @@ export const CLOUD_IMAGE_GEN_MODES = Object.freeze([// source: the prompt builders name it, the fabrication guard names it when it// rejects a code-drawn stand-in, and the usage card labels its quota row with// it — six string literals before this existed. Grok is the one backend with-// two, picked by whether the render has a source image.+// two, picked by whether the render has any input image.export const IMAGE_TOOL_NAMES = Object.freeze({[IMAGE_GEN_MODE.AGY]: 'generate_image',[IMAGE_GEN_MODE.GROK]: 'image_gen',[IMAGE_GEN_MODE.CODEX]: 'image_gen',});-/** Grok's tool depends on the direction: i2i edits go to `image_edit`. */-export const grokImageTool = (initImagePath) => (initImagePath ? 'image_edit' : IMAGE_TOOL_NAMES[IMAGE_GEN_MODE.GROK]);+/**+ * Grok's tool depends on the direction: anything with an input image goes to+ * `image_edit`. Grok's `image_gen` schema has NO image parameter at all (probed+ * 2026-08-09), so a reference-only render must route to `image_edit` too — its+ * `image` parameter is an array of references, not a single source.+ */+export const grokImageTool = (hasInputImage) => (hasInputImage ? 'image_edit' : IMAGE_TOOL_NAMES[IMAGE_GEN_MODE.GROK]);++/**+ * The clause every cloud-CLI prompt uses to say what a reference image is FOR.+ * Shared (like describeFidelity) so the three prompt builders describe+ * reference conditioning identically and agree on singular/plural.+ */+export const visualReferenceRole = (count) => (count === 1+ ? 'a visual reference for style, characters, and subject matter'+ : 'visual references for style, characters, and subject matter');/*** Cloud image backends the user has enabled in Settings → Image Gen. Hoisted@@ -66,21 +80,31 @@ export const enabledCloudImageModes = (settings) =>// future backend is one edit here instead of a sweep of enum literals.export const QUEUEABLE_IMAGE_MODES = Object.freeze([IMAGE_GEN_MODE.LOCAL, ...CLOUD_IMAGE_GEN_MODES]);-// Backends that cannot take an input image at all (#3243). Agy's `generate_image`-// tool accepts prompt / image name / aspect ratio / reference paths and exposes-// no edit mode, so `agy.js` throws AGY_IMAGE_EDIT_UNSUPPORTED the moment an-// initImagePath or referenceImagePaths arrives.+// Backends that cannot take an input image at all (#3243). Every *queueable*+// backend now can: local (mflux/diffusers `--image-path` + FLUX.2 references),+// codex (`image_gen.referenced_image_paths`), grok (`image_edit.image`) and agy+// (`generate_image.ImagePaths`) all accept an init image and/or reference+// images — see MAX_INPUT_IMAGES above for the probed per-backend limits. Agy+// was listed here until its tool schema was probed directly and turned out to+// document ImagePaths as "images to use in generation… edit, combine, or use as+// references".//-// This is the SINGLE source for that fact. It was previously encoded implicitly,-// by `resolveQueueImageEditMode` simply never listing AGY — which is invisible to-// any other ladder, and is why the pipeline's `pickUsableMode` ladder could route-// an i2i redraw to Agy and fail asynchronously in the queue. A future-// edit-incapable backend belongs here and nowhere else.-export const EDIT_INCAPABLE_IMAGE_MODES = Object.freeze([IMAGE_GEN_MODE.AGY]);--/** Can `mode` accept an input image (i2i / edit)? */+// The external SD-API backend is the one that genuinely has no input-image+// wiring in this codebase, so it inherits the slot. This is the SINGLE source+// for the fact — a future edit-incapable backend belongs here and nowhere else.+export const EDIT_INCAPABLE_IMAGE_MODES = Object.freeze([IMAGE_GEN_MODE.EXTERNAL]);++/** Can `mode` accept an input image (i2i / edit / reference)? */export const isEditCapableMode = (mode) => !EDIT_INCAPABLE_IMAGE_MODES.includes(mode);+/**+ * Sentence-case backend name for user-facing messages ('Codex', 'Agy', …).+ * The client mirror is `modeLabel` in client/src/lib/imageGenModes.js; this is+ * the server half, shared so error messages don't grow a per-backend ternary+ * ladder each time a backend is added.+ */+export const modeLabel = (mode) => (mode ? mode[0].toUpperCase() + mode.slice(1) : 'This');+/*** The one 400 for "this backend was handed an input image and cannot take one".*@@ -89,14 +113,10 @@ export const isEditCapableMode = (mode) => !EDIT_INCAPABLE_IMAGE_MODES.includes(* needed a fifth (#3331), so it now lives beside the predicate that decides it.* Every caller gates on `isEditCapableMode`, so adding a backend to* EDIT_INCAPABLE_IMAGE_MODES still stays a one-line change.- *- * The `AGY_IMAGE_EDIT_UNSUPPORTED` code keeps the name it shipped under (it is- * the only edit-incapable backend today) so existing clients and docs still- * match; the message names whichever backend was actually asked for.*/export const editIncapableModeError = (mode) => new ServerError(- `${mode ? mode[0].toUpperCase() + mode.slice(1) : 'This'} Imagegen supports text-to-image only`,- { status: 400, code: 'AGY_IMAGE_EDIT_UNSUPPORTED' },+ `${modeLabel(mode)} image generation supports text-to-image only`,+ { status: 400, code: 'IMAGE_EDIT_UNSUPPORTED_MODE' },);// Cloud-CLI providers expose no numeric i2i denoise knob, so map the@@ -210,10 +230,14 @@ export const LOCAL_IMAGEGEN_DEFAULT_MODEL = 'dev';/*** Resolve the queue-capable image mode for a render request: the per-request* override (honored only when that backend is enabled/available), else the- * saved dispatcher default, else codex → grok → local. External never queues.- * Hoisted from the pipeline visual stages (#2896) so sprite renders and any- * future queued surface share one enable-gating ladder — see issue #2881 for- * the wider param-assembly consolidation.+ * saved dispatcher default, else codex → grok → agy → local. External never+ * queues. Hoisted from the pipeline visual stages (#2896) so sprite renders and+ * any future queued surface share one enable-gating ladder — see issue #2881+ * for the wider param-assembly consolidation.+ *+ * There is no separate edit-mode ladder: every queueable backend accepts input+ * images (see EDIT_INCAPABLE_IMAGE_MODES), so an i2i render resolves through+ * this exact same ladder.*/export function resolveQueueImageMode(requested, settings) {const codexEnabled = settings?.imageGen?.codex?.enabled === true;@@ -233,18 +257,3 @@ export function resolveQueueImageMode(requested, settings) {if (agyEnabled) return IMAGE_GEN_MODE.AGY;return IMAGE_GEN_MODE.LOCAL;}--export function resolveQueueImageEditMode(requested, settings) {- const codexEnabled = settings?.imageGen?.codex?.enabled === true;- const grokEnabled = settings?.imageGen?.grok?.enabled === true;- if (requested === IMAGE_GEN_MODE.CODEX && codexEnabled) return IMAGE_GEN_MODE.CODEX;- if (requested === IMAGE_GEN_MODE.GROK && grokEnabled) return IMAGE_GEN_MODE.GROK;- if (requested === IMAGE_GEN_MODE.LOCAL) return IMAGE_GEN_MODE.LOCAL;- const saved = settings?.imageGen?.mode;- if (saved === IMAGE_GEN_MODE.CODEX && codexEnabled) return IMAGE_GEN_MODE.CODEX;- if (saved === IMAGE_GEN_MODE.GROK && grokEnabled) return IMAGE_GEN_MODE.GROK;- if (saved === IMAGE_GEN_MODE.LOCAL) return IMAGE_GEN_MODE.LOCAL;- if (codexEnabled) return IMAGE_GEN_MODE.CODEX;- if (grokEnabled) return IMAGE_GEN_MODE.GROK;- return IMAGE_GEN_MODE.LOCAL;-}diff --git a/server/services/imageGen/prepareParams.js b/server/services/imageGen/prepareParams.jsindex 4317d97702..7744017f02 100644--- a/server/services/imageGen/prepareParams.js+++ b/server/services/imageGen/prepareParams.js@@ -3,10 +3,10 @@** Handles everything between Zod validation and the final dispatch branch:* - resolve effective backend mode + per-render cleaners- * - gate reference-image uploads to local FLUX.2 only+ * - gate reference-image uploads to backends that can consume them* - stage multer temp uploads into PATHS.images / PATHS.imageRefs* - resolve initImagePath from upload or gallery filename- * - enforce the Codex text-to-image prompt requirement+ * - enforce each cloud CLI's prompt requirement** Returns:* {@@ -27,9 +27,9 @@ import { join } from 'node:path';import { ServerError } from '../../lib/errorHandler.js';import { PATHS, ensureDir, resolveGalleryImage } from '../../lib/fileUtils.js';import { getSettings } from '../settings.js';-import { IMAGE_GEN_MODE, CLOUD_IMAGE_GEN_MODES, resolveImageCleaners } from './index.js';-import { editIncapableModeError, isEditCapableMode } from './modes.js';-import { resolveRenderTargetConfig } from './cloudProviderConfig.js';+import { IMAGE_GEN_MODE, resolveImageCleaners } from './index.js';+import { editIncapableModeError, isEditCapableMode, modeLabel } from './modes.js';+import { cloudPromptRequired, resolveRenderTargetConfig } from './cloudProviderConfig.js';import { RENDER_TARGET, recordRenderPin } from '../../lib/renderTargets.js';import { getProject as getMusicVideoProject } from '../musicVideo/projects.js';import { getImageModels, isFlux2 } from '../../lib/mediaModels.js';@@ -66,7 +66,7 @@ export async function prepareGenerateParams({ data, files, referenceImageFields// 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).+ // throw site (the local-FLUX.2 gate, the edit-incapable-backend gate).const cleanupReqFilesTemp = () => {if (!files) return;for (const f of Object.values(files)) {@@ -74,9 +74,8 @@ export async function prepareGenerateParams({ data, files, referenceImageFields}};- // 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+ // Resolve the effective backend BEFORE staging reference uploads — an+ // `external` 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.)@@ -118,29 +117,30 @@ export async function prepareGenerateParams({ data, files, referenceImageFieldsdata.denoise = cleaners.denoise;delete data.autoClean; // legacy field — already mapped into both flags above- // 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).+ // 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+ // 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 (referenceUploads.length) {- if (mode !== IMAGE_GEN_MODE.LOCAL) {+ if (!isEditCapableMode(mode)) {cleanupReqFilesTemp();- throw new ServerError(- 'Reference images are only supported for local FLUX.2 renders',- { status: 400, code: 'REFERENCE_IMAGES_LOCAL_ONLY' },- );+ throw editIncapableModeError(mode);}- 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 (mode === IMAGE_GEN_MODE.LOCAL) {+ 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 on the local backend',+ { status: 400, code: 'REFERENCE_IMAGES_FLUX2_ONLY' },+ );+ }}}@@ -192,14 +192,18 @@ export async function prepareGenerateParams({ data, files, referenceImageFieldsdata.referenceImageStrengths = referenceImageStrengths;}- // Empty prompt is allowed for i2i / local / external, but cloud-CLI- // text-to-image (no init image) still needs one — reject- // synchronously here so direct API callers get a 400 instead of a- // 200-then-async-job-failure. Mirrors the guards in codex.js/grok.js and- // the client's needs-prompt gate.- if (CLOUD_IMAGE_GEN_MODES.includes(mode) && !initImagePath && !data.prompt?.trim()) {- const label = mode === IMAGE_GEN_MODE.CODEX ? 'Codex' : mode === IMAGE_GEN_MODE.GROK ? 'Grok' : 'Agy';- throw new ServerError(`Prompt is required for ${label} text-to-image`, { status: 400, code: 'VALIDATION_ERROR' });+ // Empty prompt is allowed for i2i / local / external, but a cloud-CLI render+ // still needs one whenever its tool can't run image-only — text-to-image+ // everywhere, plus agy even with input images (`Prompt` is required by its+ // tool schema). Reject synchronously here so direct API callers get a 400+ // instead of a 200-then-async-job-failure. Mirrors the guards in+ // codex.js/grok.js/agy.js and the client's needs-prompt gate.+ const hasInputImage = Boolean(initImagePath) || referenceImagePaths.length > 0;+ if (cloudPromptRequired(mode, hasInputImage) && !data.prompt?.trim()) {+ // Naming "text-to-image" would be wrong for the agy-with-input-images case,+ // which is precisely the one that isn't.+ const what = hasInputImage ? 'an image render' : 'text-to-image';+ throw new ServerError(`Prompt is required for ${modeLabel(mode)} ${what}`, { status: 400, code: 'VALIDATION_ERROR' });}if (data.guidance == null && data.cfgScale != null) {diff --git a/server/services/pipeline/comicPages.js b/server/services/pipeline/comicPages.jsindex 10ef508934..0d9e4039a0 100644--- a/server/services/pipeline/comicPages.js+++ b/server/services/pipeline/comicPages.js@@ -256,7 +256,7 @@ export async function enqueueVisualComicPage(issueId, options = {}) {// Resolved AFTER the init image, so an i2i render skips edit-incapable// backends rather than resolving to one that rejects the job in the queue// (#3243).- const mode = resolveMode(options, settings, series, { edit: Boolean(initImagePath) });+ const mode = resolveMode(options, settings, series);// Build a free-text haystack from every panel's prose (description +// caption + sfx). Dialogue lines feed character matching via CAPS names@@ -480,7 +480,7 @@ export async function refineComicPageRender(issueId, options = {}) {// A refine render always redraws from `initImagePath`, so it is unconditionally// an edit — edit-incapable backends are skipped (#3243).- const mode = resolveMode(options, settings, series, { edit: true });+ const mode = resolveMode(options, settings, series);const initImageStrength = Number.isFinite(options.initImageStrength)? Math.min(Math.max(options.initImageStrength, 0), 1): REFINE_RENDER_DEFAULT_STRENGTH;diff --git a/server/services/pipeline/covers.js b/server/services/pipeline/covers.jsindex d2dd537d0c..b1356629d3 100644--- a/server/services/pipeline/covers.js+++ b/server/services/pipeline/covers.js@@ -155,7 +155,7 @@ async function enqueueComicCoverLike(issueId, target, options = {}) {: null;// Resolved AFTER the init image so a proof-as-base render skips edit-incapable// backends instead of failing asynchronously in the queue (#3243).- const mode = resolveMode(options, settings, series, { edit: Boolean(initImagePath) });+ const mode = resolveMode(options, settings, series);const initImageStrength = fromProof? (Number.isFinite(options.initImageStrength) ? options.initImageStrength : PROOF_AS_BASE_DEFAULT_STRENGTH): undefined;@@ -351,7 +351,7 @@ async function enqueueVolumeCoverLike(seriesId, seasonId, target, options = {})? resolveProofInitImage(record?.proofImage, `volume ${target}`): null;// Resolved AFTER the init image — see the issue-cover path above (#3243).- const mode = resolveMode(options, settings, series, { edit: Boolean(initImagePath) });+ const mode = resolveMode(options, settings, series);const initImageStrength = fromProof? (Number.isFinite(options.initImageStrength) ? options.initImageStrength : PROOF_AS_BASE_DEFAULT_STRENGTH): undefined;diff --git a/server/services/pipeline/visualStageHelpers.js b/server/services/pipeline/visualStageHelpers.jsindex 99f2c51a07..87b718b5fc 100644--- a/server/services/pipeline/visualStageHelpers.js+++ b/server/services/pipeline/visualStageHelpers.js@@ -76,19 +76,16 @@ const applyWorldStyle = (prompt, world, series = null) => {// The series' persisted per-record pin (#3231 Phase 3) sits between the// per-request override and the install-wide target pin: "this series renders// on codex" beats the surface default, loses to an explicit UI selection.-// `edit` marks a render that carries an input image (i2i: "use proof as base",-// a reference page, or a refine pass). Edit-incapable backends are skipped at-// every rung so the ladder falls through instead of resolving to one that will-// reject the job asynchronously (#3243). It DEFAULTS from `options.initImagePath`-// so a call site that already carries the image on `options` — enqueueVisualImage,-// the storyboard shot path — is covered without opting in; the sites that derive-// the init image AFTER resolving the mode pass `{ edit: true }` explicitly.-const resolveMode = (options, settings, series = null, { edit } = {}) => pickUsableMode(settings, [+// An i2i render ("use proof as base", a reference page, a refine pass) walks+// this same ladder — every queueable backend accepts an input image, so there+// is nothing for it to skip. #3243 added an `edit` flag here to route redraws+// away from Agy; Agy's tool does take input images, so the flag is gone.+const resolveMode = (options, settings, series = null) => pickUsableMode(settings, [options.mode,recordRenderPin(series).mode,renderTargetDefaults(settings, RENDER_TARGET.PIPELINE_VISUAL).imageMode,settings?.imageGen?.mode,-], { edit: edit ?? Boolean(options.initImagePath) });+]);/*** Resolve trained character LoRAs for a pipeline render. Local mode only —diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.jsindex 5702d9dbfc..484e754648 100644--- a/server/services/sprites/reference.js+++ b/server/services/sprites/reference.js@@ -32,8 +32,7 @@ import { ServerError } from '../../lib/errorHandler.js';import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';import { enqueueJob } from '../mediaJobQueue/index.js';import {- IMAGE_GEN_MODE, resolveQueueImageMode, resolveQueueImageEditMode,- LOCAL_IMAGEGEN_DEFAULT_MODEL, editIncapableModeError, isEditCapableMode,+ IMAGE_GEN_MODE, resolveQueueImageMode, LOCAL_IMAGEGEN_DEFAULT_MODEL,} from '../imageGen/modes.js';import { resolveImageCleaners } from '../imageGen/index.js';import { pickUsableMode, renderTargetDefaults, resolveRenderTargetConfig } from '../imageGen/cloudProviderConfig.js';@@ -395,7 +394,7 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {// disabled record pin swallowing the target pin; resolveQueueImageMode// keeps the historical gate for an explicit body.mode.const spritePin = recordRenderPin(record);- let mode = resolveQueueImageMode(+ const mode = resolveQueueImageMode(body.mode || pickUsableMode(settings, [spritePin.mode,renderTargetDefaults(settings, RENDER_TARGET.SPRITE_REFERENCE).imageMode,@@ -549,23 +548,10 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {// pipeline i2i renders on that platform. Cloud modes are unaffected.}- // An edit-incapable backend cannot run an i2i render at all (#3243/#3331), and- // every reference render but a from-scratch turnaround carries a seed. How that- // backend was chosen decides what happens:- // • an explicit request-level `body.mode` is a REQUEST — fail it here, with a- // message naming the backend, rather than silently rendering somewhere else- // (the picker that sent it would otherwise show one backend and get another,- // and #3231 persists the choice as the record's render pin);- // • a record/target/settings pin is a PREFERENCE — fall through to an- // edit-capable backend, exactly as pickUsableMode's contract degrades a pin- // whose backend is disabled.- // `mode === body.mode` is what distinguishes the two: resolveQueueImageMode- // drops an explicit-but-disabled body.mode to the ladder, and that ladder result- // is a preference again.- if (initImagePath && !isEditCapableMode(mode)) {- if (body.mode === mode) throw editIncapableModeError(mode);- mode = resolveQueueImageEditMode(undefined, settings);- }+ // No edit-capability fallback here: every queueable backend accepts an input+ // image (local `--image-path`, codex `referenced_image_paths`, grok+ // `image_edit.image`, agy `ImagePaths` — see EDIT_INCAPABLE_IMAGE_MODES), so+ // the seed a reference render carries can go wherever the ladder resolved.const { cleanC2PA, denoise } = resolveImageCleaners(undefined, settings, mode);// The model the provider will ACTUALLY run, for candidate provenance —// grok picks its model internally, so its sidecars record null. body.model@@ -778,12 +764,6 @@ export async function listSpriteThumbnails() {* behind. User-triggered only.*/export async function forkSprite(sourceId, body) {- // A fork is unconditionally image+text→image, so a backend that cannot take an- // input image can never run one (#3331). Refuse before `createCharacter` for the- // same reason the source is resolved first — a 400 must not leave an orphan- // record behind, and the doomed backend would be persisted as the new record's- // render pin (#3231 Phase 3) on the way past.- if (body.mode && !isEditCapableMode(body.mode)) throw editIncapableModeError(body.mode);await resolveSourceReference(sourceId); // fail fast before creating a record// The fork's chosen backend/model seeds the NEW record's render pin// (#3231 Phase 3) in the create itself, so re-rolls keep rendering wherediff --git a/server/services/sprites/reference.test.js b/server/services/sprites/reference.test.jsindex 0554e216a5..3281728597 100644--- a/server/services/sprites/reference.test.js+++ b/server/services/sprites/reference.test.js@@ -1130,24 +1130,26 @@ describe('listSpriteThumbnails', () => {});/**- * #3331 — a backend that cannot take an input image (agy) may still render a- * from-scratch turnaround, but nothing downstream of it. The distinction the- * service draws is not "which target" but "where did the mode come from":- * an explicit request-level pick fails loudly, a pin degrades quietly.+ * #3331 — the seeded reference paths (main, anchors, forks) are all i2i, so+ * they used to be closed to agy. Its `generate_image` tool takes input images+ * through `ImagePaths`, so every queueable backend can now run them: neither an+ * explicit request-level pick nor a record pin is diverted.*/-describe('edit-incapable backends on the seeded reference paths (#3331)', () => {- it('400s an explicitly requested edit-incapable mode on a seeded render', async () => {+describe('input-image backends on the seeded reference paths (#3331)', () => {+ it('runs an explicitly requested agy render on a seeded (i2i) target', async () => {const id = newId();await createCharacter(id);await lockTurnaround(id);enqueueJob.mockClear();// The main always derives from the locked sheet, so this render is i2i.- await expect(startReferenceGeneration(id, { target: 'main', mode: 'agy' }))- .rejects.toMatchObject({ code: 'AGY_IMAGE_EDIT_UNSUPPORTED', status: 400 });- expect(enqueueJob).not.toHaveBeenCalled();+ const { mode } = await startReferenceGeneration(id, { target: 'main', mode: 'agy' });+ expect(mode).toBe('agy');+ expect(enqueueJob.mock.calls.at(-1)[0].params.mode).toBe('agy');+ // The seed still rides along — the backend consumes it as its input image.+ expect(enqueueJob.mock.calls.at(-1)[0].params.initImagePath).toBeTruthy();});- it('still runs an explicitly requested edit-incapable mode for a from-scratch turnaround', async () => {+ it('runs an explicitly requested agy render for a from-scratch turnaround', async () => {const id = newId();await createCharacter(id);const result = await startReferenceGeneration(id, { target: 'turnaround', designPrompt: 'a wiry ranger', mode: 'agy' });@@ -1155,16 +1157,14 @@ describe('edit-incapable backends on the seeded reference paths (#3331)', () =>expect(enqueueJob.mock.calls.at(-1)[0].params.mode).toBe('agy');});- it('degrades a record PIN to an edit-capable backend rather than failing the render', async () => {+ it('honors a record PIN on a seeded render instead of diverting it', async () => {const id = newId();await createCharacter(id, { imageMode: 'agy' });await lockTurnaround(id);enqueueJob.mockClear();const { mode } = await startReferenceGeneration(id, { target: 'main' });- // A pin is a preference — the same way pickUsableMode degrades a pin whose- // backend was switched off, rather than 400ing a request the user didn't make.- expect(mode).toBe('codex');- expect(enqueueJob.mock.calls.at(-1)[0].params.mode).toBe('codex');+ expect(mode).toBe('agy');+ expect(enqueueJob.mock.calls.at(-1)[0].params.mode).toBe('agy');});});@@ -1192,20 +1192,19 @@ describe('forkSprite', () => {expect(call.params.initImagePath).toBe(join(TEST_ROOT, 'sprites', source, `reference/${source}-turnaround-v1.png`));});- it('400s a fork onto a text-to-image-only backend and creates no orphan record', async () => {+ it('forks onto agy, seeding the render from the source reference', async () => {const source = newId();await createCharacter(source, { name: 'Origin' });await lockMain(source);enqueueJob.mockClear();- const before = (await records.listRecords()).length;- // A fork ALWAYS seeds from the source reference, so agy can never run one —- // and the picker used to offer it, accept the request, and only diverge- // later (#3331). The refusal must land before createCharacter, or the doomed- // backend is persisted as the new record's render pin on the way past.- await expect(forkSprite(source, { name: 'Agy Fork', designPrompt: 'x', mode: 'agy' }))- .rejects.toMatchObject({ code: 'AGY_IMAGE_EDIT_UNSUPPORTED', status: 400 });- expect((await records.listRecords()).length).toBe(before);- expect(enqueueJob).not.toHaveBeenCalled();+ // A fork ALWAYS seeds from the source reference, which used to close agy+ // out of the fork picker entirely (#3331). Its ImagePaths parameter takes+ // that seed, so the fork runs and the chosen backend is persisted as the+ // new record's render pin.+ const { record } = await forkSprite(source, { name: 'Agy Fork', designPrompt: 'x', mode: 'agy' });+ expect(record.imageMode).toBe('agy');+ expect(enqueueJob.mock.calls.at(-1)[0].params.mode).toBe('agy');+ expect(enqueueJob.mock.calls.at(-1)[0].params.initImagePath).toBeTruthy();});it('400s forking a source with no locked main and creates no orphan record', async () => {