Skip to content

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

Preview the exact Image Gen prompt under the prompt box before Generate

Claude8b1fd55fa5fe
diff --git a/client/src/components/imageGen/ImageGenFormEditor.jsx b/client/src/components/imageGen/ImageGenFormEditor.jsx
index e381dc2112..eb26f5b12b 100644
--- a/client/src/components/imageGen/ImageGenFormEditor.jsx
+++ b/client/src/components/imageGen/ImageGenFormEditor.jsx
@@ -8,6 +8,7 @@ import MusicVideoFilingSelect from '../media/MusicVideoFilingSelect';
import { FormField } from '../ui/FormField';
import Banner from '../ui/Banner';
import AutoSizeTextarea from '../ui/AutoSizeTextarea';
+import SentPromptPanel from '../media/SentPromptPanel';
import HfTokenBanner from './HfTokenBanner';
import ImageGenControls from './ImageGenControls';
import InitImagePicker from './InitImagePicker';
@@ -24,6 +25,25 @@ const ERROR_HEADINGS = {
repo_not_found: 'Model repo not found',
};
+// What Generate will send (#11317): the server's preview, built by the same
+// code as the render. The box above keeps only the user's words.
+function ModelInputPreview({ preview, prompt }) {
+ if (preview?.error) return <p role="alert" className="text-xs text-port-warning">{preview.error}</p>;
+ const sent = preview?.preview;
+ if (!sent) return null;
+ return (
+ <div className="text-xs">
+ <SentPromptPanel
+ prompt={prompt}
+ sentPrompt={sent.sentPrompt}
+ sentNegativePrompt={sent.sentNegativePrompt}
+ additions={sent.promptAdditions || []}
+ asWrittenText="Sent to the model as written."
+ />
+ </div>
+ );
+}
+
export default function ImageGenFormEditor({ form, backend, generation }) {
const {
fields,
@@ -71,6 +91,7 @@ export default function ImageGenFormEditor({ form, backend, generation }) {
placeholder="Describe the image you want to generate..."
/>
</FormField>
+ <ModelInputPreview preview={generation.modelInputPreview} prompt={fields.prompt} />
<div
className="sticky top-0 z-10 -mx-3 flex flex-wrap items-center gap-2 border-y border-port-border bg-port-card/95 px-3 py-2 backdrop-blur sm:-mx-4 sm:px-4 lg:static lg:mx-0 lg:border-0 lg:bg-transparent lg:p-0 lg:backdrop-blur-none"
diff --git a/client/src/components/media/SentPromptPanel.jsx b/client/src/components/media/SentPromptPanel.jsx
index 992b9fbf26..d70cef5f4e 100644
--- a/client/src/components/media/SentPromptPanel.jsx
+++ b/client/src/components/media/SentPromptPanel.jsx
@@ -6,15 +6,19 @@ import { copyToClipboard } from '../../lib/clipboard';
* What a model actually received, beside the prompt the user wrote (#11317):
* one chip per block PortOS added (tap to read it), and a "Show full prompt"
* view of the exact final text with Copy. Renders nothing for a record made
- * before sent prompts were recorded.
+ * before sent prompts were recorded. The Image Gen form shows the same panel
+ * from the server's preview before the render (`asWrittenText` names the tense).
*/
-export default function SentPromptPanel({ prompt = '', sentPrompt = null, sentNegativePrompt = null, additions = [] }) {
+export default function SentPromptPanel({
+ prompt = '', sentPrompt = null, sentNegativePrompt = null, additions = [],
+ asWrittenText = 'Sent to the model exactly as written.',
+}) {
const [openChip, setOpenChip] = useState(null);
const [showFull, setShowFull] = useState(false);
if (typeof sentPrompt !== 'string') return null;
const asWritten = !additions.length && !sentNegativePrompt && sentPrompt.trim() === (prompt || '').trim();
- if (asWritten) return <p className="text-[11px] text-gray-500">Sent to the model exactly as written.</p>;
+ if (asWritten) return <p className="text-[11px] text-gray-500">{asWrittenText}</p>;
const fullText = sentNegativePrompt ? `${sentPrompt}\n\nNegative prompt: ${sentNegativePrompt}` : sentPrompt;
const opened = additions.find((addition) => addition.id === openChip);
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 368a418a7d..a050d1b770 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -46,6 +46,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useSseJobSlot` | Generic single-slot SSE job: captured target from preparation through completion, terminal-frame handling (`complete`/`error`/`canceled`), and `sse.closed`-without-terminal-frame recovery in one place. Returns `{ active, pending, jobId, percent, stage, context, start, attach, cancel }` (`attach(jobId, context)` adopts a job another request already started into the idle slot); reserves synchronously, exposes context during kickoff and ignores unmounted responses. Optional `readPercent` adapts other progress scales; `connected` distinguishes a live stream from reconnecting, and `onSettled(reason, context)` refreshes persisted state after completion, failure, cancellation or a terminal disconnect. Pass `startRequest`/`eventsUrl`/`cancelRequest` + per-feature toast copy. | Any "kick off a job → stream SSE → settle on terminal frame" hook. The reference-audio/YouTube/video-download/MIDI/music-video-render hooks all wrap this — don't re-roll the terminal-frame + lost-connection dance. |
| `useInstallStream` | BYO-runtime install-log stream lifecycle: `stage`/`log`/`complete`/`error` frame dispatch, capped + optionally-debounced log accumulation, "connection lost" handling, ref-stashed `onComplete`, auto-scroll. `method: 'GET'` uses EventSource; `method: 'POST'` reads one fetch stream for a non-idempotent install. | A streamed install/setup modal that shows live SSE log lines (FLUX.2, video runtimes, OpenCode). Don't re-roll the teardown/onComplete-ref dance. |
| `useModelDownloadStatus` | Image/video model cache-status + SSE pre-download. `useDownloadableAssets(descriptors, options)` shares readiness and independent integrity dismissals across asset roles. `start(id)` commands a pull; `startWhenIdle(id)` requests one — it waits for the cache verdict, skips an already-resident repo, and queues behind whatever owns the single EventSource lane (`queuedModelId` while it waits, falsy id to retract). | Surfacing "Available" vs "Download" badge inline in the gen form; `startWhenIdle` for a picker where choosing an option IS the request for its weights. |
+| `useModelInputPreview` | `useModelInputPreview(fetchPreview, body, { enabled })` — the server's preview of what a render would send to its model (#11317), refreshed 500 ms after the form stops changing; superseded responses dropped, a refusal returned as `error`. | Showing the exact prompt and its additions beside a render form before Generate. |
| `useAgyModels` | Live `agy models` probe (the AGENT models `--model` accepts) with `models`/`error`/`loading`/`refresh`; opt-in via an `enabled` flag so it never spawns for a disabled backend. | Any Agy model picker — the Settings default or the per-render override. Don't hardcode a model list: agy exits non-zero on an id outside this catalog. |
| `useSpritePendingRenders` | Sprite render map reconciled on scoped queue events, entry, reconnect and tab show; submitting sentinel, terminal-before-response recovery and 404-only release. | Queue-backed sprite reference/walk renders; persisted assets reconcile separately on `sprites:changed`. |
| `useSpriteRecordCrud` | Rename/delete state machine for one sprite record: `view`/`rename`/`confirm` mode, name draft, busy/inline-error, silent PATCH/DELETE. | A surface that renames or deletes a sprite record (the Library catalog card, the detail header) — share this so both stay in lock-step. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 56e5f951f1..ade1771b98 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -172,6 +172,7 @@ export * from './useSeriesRunLifecycle.js';
export * from './useSseProgress.js';
export * from './useStoryStepRuns.jsx';
export * from './useModelDownloadStatus.js';
+export * from './useModelInputPreview.js';
// === Media (annotations, completion, attachments) ===
export * from './useAvatarCapabilities.js';
diff --git a/client/src/hooks/useImageGenPageRuntime.js b/client/src/hooks/useImageGenPageRuntime.js
index b66430df8a..0695ab4601 100644
--- a/client/src/hooks/useImageGenPageRuntime.js
+++ b/client/src/hooks/useImageGenPageRuntime.js
@@ -18,6 +18,7 @@ import { useMediaJobSse, isMediaRunEnded } from './useMediaJobSse';
import { useModelDownloadStatus } from './useModelDownloadStatus';
import { useHfTokenStatus } from './useHfTokenStatus';
import { useAgyModels } from './useAgyModels';
+import { useModelInputPreview } from './useModelInputPreview';
import toast from '../components/ui/Toast';
import {
buildFormData,
@@ -29,6 +30,7 @@ import {
getImageGenStatus,
getRegenAvailability,
listMediaJobs,
+ previewImagePrompt,
regenerateGalleryImage,
} from '../services/api';
import { musicVideoFilingFields } from '../lib/musicVideoFiling';
@@ -260,7 +262,7 @@ export function useImageGenPageRuntime() {
? previous : [...(previous || []), { id, status: ack.status || 'queued' }]);
};
- const submitGenerationPayload = async () => {
+ const buildGenerationPayload = () => {
const composed = composeStyledPrompt(fields.prompt, fields.negativePrompt, derived.activeStylePresets);
const width = clampImageEdge(fields.width);
const height = clampImageEdge(fields.height);
@@ -301,17 +303,44 @@ export function useImageGenPageRuntime() {
Object.assign(payload, musicVideoFilingFields(searchParams), promptAdditionsField(derived.activeStylePresets));
const hasInitImage = derived.i2iCapable && images.initImage.source != null;
const hasReferenceImages = derived.populatedRefs.length > 0;
- if (hasInitImage || hasReferenceImages) {
- const initFields = hasInitImage ? {
- ...(images.initImage.source === 'upload'
- ? { initImage: images.initImage.file }
- : { initImageFile: images.initImage.name }),
- initImageStrength: images.initImageStrength,
- } : {};
- const referenceFields = hasReferenceImages ? {
- ...Object.fromEntries(derived.populatedRefs.map((slot, index) => [`referenceImage${index + 1}`, slot.file])),
- referenceStrengths: derived.populatedRefs.map((slot) => slot.strength),
- } : {};
+ const initFields = hasInitImage ? {
+ ...(images.initImage.source === 'upload'
+ ? { initImage: images.initImage.file }
+ : { initImageFile: images.initImage.name }),
+ initImageStrength: images.initImageStrength,
+ } : {};
+ const referenceFields = hasReferenceImages ? {
+ ...Object.fromEntries(derived.populatedRefs.map((slot, index) => [`referenceImage${index + 1}`, slot.file])),
+ referenceStrengths: derived.populatedRefs.map((slot) => slot.strength),
+ } : {};
+ return { payload, initFields, referenceFields, hasInputImages: hasInitImage || hasReferenceImages };
+ };
+
+ // The same request as Generate, with uploads named by count (#11317).
+ const previewBody = (() => {
+ if (!derived.isAsyncMode) {
+ const composed = composeStyledPrompt(fields.prompt, fields.negativePrompt, derived.activeStylePresets);
+ return {
+ prompt: composed.prompt, negativePrompt: composed.negativePrompt || undefined,
+ width: clampImageEdge(fields.width), height: clampImageEdge(fields.height), mode: IMAGE_GEN_MODE.EXTERNAL,
+ ...promptAdditionsField(derived.activeStylePresets),
+ };
+ }
+ const { payload, initFields, referenceFields } = buildGenerationPayload();
+ const { initImage, ...initRest } = initFields;
+ const { referenceStrengths, ...referenceUploads } = referenceFields;
+ const uploadedReferenceCount = Object.keys(referenceUploads).length;
+ return {
+ ...payload, ...initRest,
+ ...(initImage ? { uploadedInitImage: true } : {}),
+ ...(uploadedReferenceCount ? { uploadedReferenceCount, referenceStrengths } : {}),
+ };
+ })();
+ const modelInputPreview = useModelInputPreview(previewImagePrompt, previewBody, { enabled: !form.remix.pending });
+
+ const submitGenerationPayload = async () => {
+ const { payload, initFields, referenceFields, hasInputImages } = buildGenerationPayload();
+ if (hasInputImages) {
const formData = buildFormData({ ...payload, ...initFields, ...referenceFields });
const data = await generateImageMultipart(formData, { silent: true });
rememberQueuedJob(data);
@@ -530,6 +559,7 @@ export function useImageGenPageRuntime() {
refreshFlux2Status,
needsFlux2Token: derived.isFlux2Model && !!flux2Status && flux2Status.venvInstalled && !flux2Status.hfTokenPresent,
handleRegenerate,
+ modelInputPreview,
},
gallery: {
view: gallery.view,
diff --git a/client/src/hooks/useModelInputPreview.js b/client/src/hooks/useModelInputPreview.js
new file mode 100644
index 0000000000..f32028c421
--- /dev/null
+++ b/client/src/hooks/useModelInputPreview.js
@@ -0,0 +1,31 @@
+import { useEffect, useRef, useState } from 'react';
+
+const PREVIEW_DELAY_MS = 500;
+
+/**
+ * The server's preview of what a render would send to its model (#11317),
+ * refreshed a moment after the form stops changing. `body` must be plain JSON
+ * (uploads named by count); `fetchPreview(body, { silent })` is the route
+ * wrapper. A superseded response is dropped, and a refusal comes back as
+ * `error` so the form can show why the render would be refused.
+ */
+export function useModelInputPreview(fetchPreview, body, { enabled = true } = {}) {
+ const [state, setState] = useState({ preview: null, error: null });
+ const generation = useRef(0);
+ const key = enabled ? JSON.stringify(body) : null;
+
+ useEffect(() => {
+ if (key === null) return undefined;
+ const current = ++generation.current;
+ const timer = setTimeout(() => {
+ fetchPreview(JSON.parse(key), { silent: true })
+ .then((preview) => { if (current === generation.current) setState({ preview, error: null }); })
+ .catch((err) => { if (current === generation.current) setState({ preview: null, error: err?.message || 'Preview failed' }); });
+ }, PREVIEW_DELAY_MS);
+ return () => clearTimeout(timer);
+ }, [fetchPreview, key]);
+
+ return state;
+}
+
+export default useModelInputPreview;
diff --git a/client/src/hooks/useModelInputPreview.test.js b/client/src/hooks/useModelInputPreview.test.js
new file mode 100644
index 0000000000..9d5275e022
--- /dev/null
+++ b/client/src/hooks/useModelInputPreview.test.js
@@ -0,0 +1,35 @@
+import { describe, expect, it, vi, afterEach } from 'vitest';
+import { act, renderHook } from '@testing-library/react';
+import { useModelInputPreview } from './useModelInputPreview';
+
+afterEach(() => vi.useRealTimers());
+
+describe('useModelInputPreview', () => {
+ // Typing fires one request after the pause, and an older answer arriving
+ // late must never replace the preview of what the form says now.
+ it('asks once per pause and keeps only the newest answer', async () => {
+ vi.useFakeTimers();
+ const resolvers = [];
+ const fetchPreview = vi.fn(() => new Promise((resolve) => resolvers.push(resolve)));
+ const { result, rerender } = renderHook(({ body }) => useModelInputPreview(fetchPreview, body), { initialProps: { body: { prompt: 'a' } } });
+
+ rerender({ body: { prompt: 'a fox' } });
+ await act(async () => { vi.advanceTimersByTime(500); });
+ expect(fetchPreview).toHaveBeenCalledTimes(1);
+ expect(fetchPreview).toHaveBeenLastCalledWith({ prompt: 'a fox' }, { silent: true });
+
+ rerender({ body: { prompt: 'a red fox' } });
+ await act(async () => { vi.advanceTimersByTime(500); });
+ await act(async () => { resolvers[1]({ sentPrompt: 'a red fox' }); });
+ await act(async () => { resolvers[0]({ sentPrompt: 'a fox' }); });
+ expect(result.current.preview).toEqual({ sentPrompt: 'a red fox' });
+ });
+
+ it('reports a refusal as the error to show', async () => {
+ vi.useFakeTimers();
+ const fetchPreview = vi.fn(async () => { throw new Error('Codex Imagegen is disabled'); });
+ const { result } = renderHook(() => useModelInputPreview(fetchPreview, { prompt: 'a fox' }));
+ await act(async () => { vi.advanceTimersByTime(500); });
+ expect(result.current).toEqual({ preview: null, error: 'Codex Imagegen is disabled' });
+ });
+});
diff --git a/client/src/pages/ImageGen.promptPreview.test.jsx b/client/src/pages/ImageGen.promptPreview.test.jsx
new file mode 100644
index 0000000000..988971d974
--- /dev/null
+++ b/client/src/pages/ImageGen.promptPreview.test.jsx
@@ -0,0 +1,49 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, fireEvent, screen, waitFor } from '@testing-library/react';
+
+import {
+ loadImageGenPage,
+ renderImageGenPage,
+ resetImageGenMockState,
+ state,
+} from '../test/imageGenPageMocks.jsx';
+
+const InitPicker = ({ onPick }) => (
+ <button type="button" onClick={() => onPick({ target: { files: [new File(['x'], 'photo.jpg', { type: 'image/jpeg' })] } })}>pick-init</button>
+);
+
+await loadImageGenPage();
+
+// #11317: the form shows what Generate will send, from the server's preview.
+// The preview body is the Generate request with the upload named by count
+// (no bytes ride a JSON body), and the box keeps only the typed words.
+describe('ImageGen prompt preview', () => {
+ beforeEach(() => {
+ resetImageGenMockState();
+ state.settings = { imageGen: { mode: 'codex' } };
+ state.getImageGenStatus.mockResolvedValue({ connected: true, mode: 'codex' });
+ state.initImagePickerFactory = InitPicker;
+ state.previewImagePrompt.mockResolvedValue({
+ mode: 'codex',
+ sentPrompt: '$imagegen Edit the attached image: a red fox',
+ promptAdditions: [{ id: 'agent-instructions', label: 'Codex image tool instructions', text: '$imagegen Edit the attached image: [prompt]' }],
+ });
+ vi.stubGlobal('createImageBitmap', vi.fn(() => Promise.reject(new Error('no decoder'))));
+ });
+
+ it('previews the request with the upload counted and shows the additions as chips', async () => {
+ await renderImageGenPage('/media/image');
+ fireEvent.change(screen.getByLabelText('Prompt'), { target: { value: 'a red fox' } });
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'pick-init' })); });
+
+ await waitFor(() => expect(state.previewImagePrompt).toHaveBeenCalledWith(
+ expect.objectContaining({ prompt: 'a red fox', uploadedInitImage: true }),
+ { silent: true },
+ ), { timeout: 2000 });
+ const body = state.previewImagePrompt.mock.calls.at(-1)[0];
+ expect(body).not.toHaveProperty('initImage');
+
+ expect(await screen.findByRole('button', { name: '+ Codex image tool instructions' })).toBeTruthy();
+ expect(screen.getByLabelText('Prompt')).toHaveValue('a red fox');
+ });
+});
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index e7433533f1..5c0ed18ed6 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -163,6 +163,14 @@ export const generateImageMultipart = (formData, options = {}) => request('/imag
...options,
});
+// What an Image Gen render would send to its model, before it is sent (#11317).
+// Same body as /generate, with uploads named by count instead of attached.
+export const previewImagePrompt = (body, options = {}) => request('/image-gen/prompt-preview', {
+ method: 'POST',
+ body: JSON.stringify(body),
+ ...options,
+});
+
// Local Python-runtime setup probes (LocalSetupPanel). These use fetch() rather
// than request() because the caller distinguishes intentional AbortError (a
// superseded/unmounted probe) from a real failure — request()'s catch collapses
diff --git a/client/src/test/imageGenPageMocks.jsx b/client/src/test/imageGenPageMocks.jsx
index 45f57c08b7..5ad4e45657 100644
--- a/client/src/test/imageGenPageMocks.jsx
+++ b/client/src/test/imageGenPageMocks.jsx
@@ -109,6 +109,8 @@ export const state = {
getImageGenStatus: vi.fn(defaultStatus),
/** `generateImage`; a spy so a suite can assert payloads or reject. */
generateImage: vi.fn(async () => ({ jobId: 'job-1' })),
+ /** `previewImagePrompt` (#11317); a spy so a suite can assert the preview body and answer. */
+ previewImagePrompt: vi.fn(async () => ({ sentPrompt: '' })),
/** `getActiveImageJob`'s payload. */
activeJob: null,
/** Settings `getSettings` resolves to; reset restores DEFAULT_SETTINGS. */
@@ -155,6 +157,7 @@ export function resetImageGenMockState() {
state.peers = [];
state.getImageGenStatus.mockReset().mockImplementation(defaultStatus);
state.generateImage.mockReset().mockResolvedValue({ jobId: 'job-1' });
+ state.previewImagePrompt.mockReset().mockResolvedValue({ sentPrompt: '' });
// The real media-run hook opens this for a started/resumed render; a silent
// stream keeps the job open mid-render without leaking timers, and a test
// drives its frames through `lastEventSource()`.
@@ -181,6 +184,7 @@ vi.mock('../services/api', () => ({
getImageGenStatus: (...args) => state.getImageGenStatus(...args),
generateImage: (...args) => state.generateImage(...args),
generateImageMultipart: vi.fn(async () => ({})),
+ previewImagePrompt: (...args) => state.previewImagePrompt(...args),
listImageModels: (...args) => state.listImageModels(...args),
getGalleryImages: (...args) => state.getGalleryImages(...args),
listLorasFull: (...args) => state.listLorasFull(...args),
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index f8affe6c98..2cdbd8c58f 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -30,6 +30,7 @@ import { PATHS, ensureDir, resolveGalleryImage, unlinkGuarded, copyFileGuarded }
import { prepareGenerateParams, resolveLocalImageModel, selectLocalImageModelFromSettings } from '../services/imageGen/prepareParams.js';
import { applyImageClean, applyWatermarkRemoval, applyLightRegenVariant } from '../services/imageGen/variants.js';
import { applyFilmLookBake } from '../services/imageGen/filmLookBake.js';
+import { previewImagePrompt } from '../services/imageGen/promptPreview.js';
import { filmLookBakeSchema } from '../lib/filmLookValidation.js';
import { join, basename } from 'node:path';
import { STYLE_PRESETS } from '../lib/writersRoomStylePresets.js';
@@ -455,6 +456,18 @@ const queuedImageResponse = ({ jobId, position, status, mode, model, mediaProvid
mediaProviderPeerId,
});
+// What the render would send, before it is sent (#11317). Same preparation and
+// prompt builders as POST /generate; the form says which uploads it holds by
+// count rather than sending their bytes, and nothing is staged or queued.
+const promptPreviewSchema = generateSchema.safeExtend({
+ uploadedInitImage: z.boolean().optional(),
+ uploadedReferenceCount: z.number().int().min(0).max(MAX_REFERENCE_IMAGES).optional(),
+});
+
+router.post('/prompt-preview', asyncHandler(async (req, res) => {
+ res.json(await previewImagePrompt(validateRequest(promptPreviewSchema, req.body ?? {})));
+}));
+
router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {
const data = validateRequest(generateSchema, coerceFormFields(req.body));
const { data: params, mode, settings, uploadedTempPaths } = await prepareGenerateParams({
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index 7a79118c96..29a66ba147 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -893,6 +893,29 @@ describe('Image Gen Routes', () => {
expect(imageGen.generateImage).not.toHaveBeenCalled();
});
+ // #11317: the compose preview runs the same preparation and Codex builder as
+ // /generate, so the form shows the wrapper and chips before anything queues.
+ it('prompt-preview shows the exact Codex message and its additions without queueing', async () => {
+ getSettings.mockResolvedValueOnce({
+ imageGen: { mode: 'codex', codex: { enabled: true, codexPath: '/usr/local/bin/codex', model: 'gpt-5.4' } },
+ });
+ const style = { id: 'style-1', label: 'Universe style', text: 'muted earth tones' };
+
+ const response = await request(app)
+ .post('/api/image-gen/prompt-preview')
+ .send({ prompt: 'muted earth tones. a tavern at dusk', width: 1024, height: 1024, promptAdditions: [style], uploadedInitImage: true });
+
+ expect(response.status).toBe(200);
+ expect(response.body.mode).toBe('codex');
+ expect(response.body.sentPrompt).toMatch(/^\$imagegen .*muted earth tones\. a tavern at dusk/s);
+ expect(response.body.promptAdditions[0]).toEqual(style);
+ expect(response.body.promptAdditions[1]).toMatchObject({ id: 'agent-instructions', label: 'Codex image tool instructions' });
+ expect(response.body.promptAdditions[1].text).toContain('[prompt]');
+ expect(response.body.promptAdditions[1].text).not.toContain('a tavern at dusk');
+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
+ expect(mediaJobQueue.assertMediaQueueRoom).not.toHaveBeenCalled();
+ });
+
// Per-request codex override: even when the saved default is external,
// an explicit `mode: 'codex'` on the payload (e.g. the writers-room
// storyboard chip strip) flips into queue mode so renders serialize.
diff --git a/server/services/imageGen/agy.js b/server/services/imageGen/agy.js
index 548fabc992..c19a2db36f 100644
--- a/server/services/imageGen/agy.js
+++ b/server/services/imageGen/agy.js
@@ -260,6 +260,22 @@ async function resolveAgyDriverModel(model, shippedDefault) {
return { model, models };
}
+/**
+ * The exact message agy receives and the record of what PortOS added to the
+ * user's prompt (#11317). Shared by the render and the compose preview.
+ */
+export function agySentPrompt({ prompt = '', negativePrompt, width, height, stagingPath, inputImages, initImageStrength, promptAdditions = [] }) {
+ const buildWith = (text) => buildAgyPrompt({
+ prompt: text, negativePrompt, width, height, stagingPath, inputImages, initImageStrength,
+ });
+ const fullPrompt = buildWith(prompt);
+ return {
+ fullPrompt,
+ record: sentPromptRecord({ sentPrompt: fullPrompt, carried: carriedPromptAdditions({ promptAdditions }),
+ added: [agentInstructionsAddition('Antigravity image tool instructions', buildWith)] }),
+ };
+}
+
export async function generateImage({
promptAdditions = [],
agyPath,
@@ -302,10 +318,9 @@ export async function generateImage({
const scratchDir = join(tmpdir(), `portos-agy-${jobId}`);
const stagingPath = join(scratchDir, 'output.png');
- const buildWith = (text) => buildAgyPrompt({
- prompt: text, negativePrompt, width, height, stagingPath, inputImages, initImageStrength,
+ const { fullPrompt, record: sentRecord } = agySentPrompt({
+ prompt, negativePrompt, width, height, stagingPath, inputImages, initImageStrength, promptAdditions,
});
- const fullPrompt = buildWith(prompt);
// `driverModel` is what agy actually runs on — a retired shipped default is
// re-pointed here, so every record below reports the model that rendered
// rather than the one the caller asked for. See resolveAgyDriverModel.
@@ -327,8 +342,7 @@ export async function generateImage({
// provenance names the model that actually produced the pixels (#3231).
imageModel: AGY_IMAGEGEN_IMAGE_MODEL,
...(visualConditioning ? { visualConditioning } : {}),
- ...sentPromptRecord({ sentPrompt: fullPrompt, carried: carriedPromptAdditions({ promptAdditions }),
- added: [agentInstructionsAddition('Antigravity image tool instructions', buildWith)] }),
+ ...sentRecord,
createdAt: new Date().toISOString(),
};
// The scratch dir is the last fallible step before the job exists, so a
diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.js
index 244eb9998c..bb80857c2e 100644
--- a/server/services/imageGen/codex.js
+++ b/server/services/imageGen/codex.js
@@ -180,6 +180,38 @@ export function buildCodexAttachmentPrefix({ initPath, referenceCount, initImage
return '';
}
+/**
+ * The exact message `codex exec` receives and the record of what PortOS added
+ * to the user's prompt (#11317). Shared by the render and the compose preview.
+ */
+export function codexSentPrompt({ prompt = '', negativePrompt, width, height, inputImages, initImageStrength, promptAdditions = [] }) {
+ // Width/height/negative aren't first-class args for Codex's built-in
+ // image_gen tool — pass them as natural-language hints inside the prompt.
+ // Codex's imagegen skill is prompt-driven; the model decides resolution.
+ // gpt-image-2 supports up to 4K output; the "(high quality)" suffix
+ // pushes it off its 1024 default toward whatever native size best fits
+ // the requested aspect ratio.
+ // The ratio is named as well as the pixels: a bare "(1672x941)" left the
+ // model free to return a square close-up, so the frame is also conformed
+ // after harvest (aspectConform.js) — the hint just makes that crop rarer.
+ const ratioPhrase = (width && height) ? aspectRatioPhrase(Number(width), Number(height)) : '';
+ const sizeHint = (width && height) ? ` (${ratioPhrase ? `${ratioPhrase} frame, ` : ''}${width}x${height})` : '';
+ const qualityHint = (width >= 1536 || height >= 1536) ? ' (high quality)' : '';
+ const avoidHint = negativePrompt?.trim() ? `\nAvoid: ${negativePrompt.trim()}` : '';
+ const editPrefix = buildCodexAttachmentPrefix({
+ initPath: inputImages.initPath,
+ referenceCount: inputImages.referencePaths.length,
+ initImageStrength,
+ });
+ const buildWith = (text) => `$imagegen ${editPrefix}${text.trim()}${sizeHint}${qualityHint}${avoidHint}`;
+ const fullPrompt = buildWith(prompt);
+ return {
+ fullPrompt,
+ record: sentPromptRecord({ sentPrompt: fullPrompt, carried: carriedPromptAdditions({ promptAdditions }),
+ added: [agentInstructionsAddition('Codex image tool instructions', buildWith)] }),
+ };
+}
+
// 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.
@@ -236,26 +268,9 @@ export async function generateImage({
const filename = `${jobId}.png`;
const outputPath = join(PATHS.images, filename);
- // Width/height/negative aren't first-class args for Codex's built-in
- // image_gen tool — pass them as natural-language hints inside the prompt.
- // Codex's imagegen skill is prompt-driven; the model decides resolution.
- // gpt-image-2 supports up to 4K output; the "(high quality)" suffix
- // pushes it off its 1024 default toward whatever native size best fits
- // the requested aspect ratio.
- // The ratio is named as well as the pixels: a bare "(1672x941)" left the
- // model free to return a square close-up, so the frame is also conformed
- // after harvest (aspectConform.js) — the hint just makes that crop rarer.
- const ratioPhrase = (width && height) ? aspectRatioPhrase(Number(width), Number(height)) : '';
- const sizeHint = (width && height) ? ` (${ratioPhrase ? `${ratioPhrase} frame, ` : ''}${width}x${height})` : '';
- const qualityHint = (width >= 1536 || height >= 1536) ? ' (high quality)' : '';
- const avoidHint = negativePrompt?.trim() ? `\nAvoid: ${negativePrompt.trim()}` : '';
- const editPrefix = buildCodexAttachmentPrefix({
- initPath: inputImages.initPath,
- referenceCount: inputImages.referencePaths.length,
- initImageStrength,
+ const { fullPrompt, record: sentRecord } = codexSentPrompt({
+ prompt, negativePrompt, width, height, inputImages, initImageStrength, promptAdditions,
});
- const buildWith = (text) => `$imagegen ${editPrefix}${text.trim()}${sizeHint}${qualityHint}${avoidHint}`;
- const fullPrompt = buildWith(prompt);
const bin = codexPath || DEFAULT_BIN;
// `codex exec` treats `-i, --image <FILE>...` as VARIADIC, so it greedily
@@ -288,8 +303,7 @@ export async function generateImage({
width: width ? Number(width) : null, height: height ? Number(height) : null,
filename, mode: IMAGE_GEN_MODE.CODEX, model: effectiveModel,
...(visualConditioning ? { visualConditioning } : {}),
- ...sentPromptRecord({ sentPrompt: fullPrompt, carried: carriedPromptAdditions({ promptAdditions }),
- added: [agentInstructionsAddition('Codex image tool instructions', buildWith)] }),
+ ...sentRecord,
createdAt: new Date().toISOString(),
};
const job = { ...meta, clients: [], status: 'running', renderStartedAtMs };
diff --git a/server/services/imageGen/fal.js b/server/services/imageGen/fal.js
index 941fd28765..6f01078b7e 100644
--- a/server/services/imageGen/fal.js
+++ b/server/services/imageGen/fal.js
@@ -195,6 +195,29 @@ const firstImageUrl = (result) => {
return typeof url === 'string' && url.trim() ? url : null;
};
+/**
+ * The prompt text fal receives (the image-role prose plus the negative folded in
+ * as "Avoid:") and the record of what PortOS added (#11317). Shared by the
+ * render and the compose preview.
+ */
+export function falImageSentPrompt({ family, prompt = '', negativePrompt, inputImages, initImageStrength, promptAdditions = [] }) {
+ const fullPrompt = buildFalPrompt({
+ prompt,
+ hasInitImage: Boolean(inputImages.initPath),
+ initImageStrength,
+ referenceCount: inputImages.referencePaths.length,
+ });
+ return {
+ fullPrompt,
+ record: sentPromptRecord({
+ sentPrompt: buildFalImageRequest({ modelId: family.textEndpoint, prompt: fullPrompt, negativePrompt }).body.prompt,
+ carried: carriedPromptAdditions({ promptAdditions }),
+ added: [promptAddition('image-roles', 'How to read the attached images', fullPrompt.slice(prompt.trim().length)),
+ promptAddition('avoid', 'Negative prompt, sent as "Avoid:"', negativePrompt)],
+ }),
+ };
+}
+
export async function generateImage({
promptAdditions = [],
model, prompt = '', negativePrompt, width, height, seed,
@@ -242,12 +265,7 @@ export async function generateImage({
const jobId = providedJobId || randomUUID();
const filename = `${jobId}.png`;
const outputPath = join(PATHS.images, filename);
- const fullPrompt = buildFalPrompt({
- prompt,
- hasInitImage: Boolean(inputImages.initPath),
- initImageStrength,
- referenceCount: inputImages.referencePaths.length,
- });
+ const { fullPrompt, record: sentRecord } = falImageSentPrompt({ family, prompt, negativePrompt, inputImages, initImageStrength, promptAdditions });
const meta = {
id: jobId, prompt: prompt.trim(), negativePrompt: negativePrompt || '',
@@ -259,13 +277,7 @@ export async function generateImage({
modelFamily: family.id,
...(inputImages.paths.length ? { inputImageCount: inputImages.paths.length } : {}),
...(visualConditioning ? { visualConditioning } : {}),
- // The text runFal sends: the image-role prose plus the negative prompt folded in as "Avoid:".
- ...sentPromptRecord({
- sentPrompt: buildFalImageRequest({ modelId: family.textEndpoint, prompt: fullPrompt, negativePrompt }).body.prompt,
- carried: carriedPromptAdditions({ promptAdditions }),
- added: [promptAddition('image-roles', 'How to read the attached images', fullPrompt.slice(prompt.trim().length)),
- promptAddition('avoid', 'Negative prompt, sent as "Avoid:"', negativePrompt)],
- }),
+ ...sentRecord,
createdAt: new Date().toISOString(),
};
const job = { ...meta, clients: [], status: 'running', renderStartedAtMs };
diff --git a/server/services/imageGen/grok.js b/server/services/imageGen/grok.js
index 2a1ad32973..6bebcc5814 100644
--- a/server/services/imageGen/grok.js
+++ b/server/services/imageGen/grok.js
@@ -209,6 +209,33 @@ export function buildGrokPrompt({
return lines.join('\n');
}
+/**
+ * The exact message grok receives and the record of what PortOS added to the
+ * user's prompt (#11317). Shared by the render and the compose preview.
+ */
+export function grokSentPrompt({ prompt = '', negativePrompt, width, height, aspectRatio, stagingPath, inputImages, initImageStrength, promptAdditions = [] }) {
+ // Caller dimensions win (mapped to the closest supported ratio); the saved
+ // per-provider default applies when no dimensions were sent; otherwise the
+ // tool's own default. Validate the saved value against the known ratios so
+ // a hand-edited settings.json can't inject arbitrary prompt text.
+ const derived = deriveAspectRatio(width, height);
+ const configured = GROK_ASPECT_RATIOS.includes(aspectRatio) ? aspectRatio : null;
+ const effectiveRatio = derived || configured;
+
+ const buildWith = (text) => buildGrokPrompt({
+ prompt: text, negativePrompt, aspectRatio: effectiveRatio, stagingPath,
+ initImagePath: inputImages.initPath, initImageStrength,
+ referenceImagePaths: inputImages.referencePaths,
+ });
+ const fullPrompt = buildWith(prompt);
+ return {
+ fullPrompt,
+ effectiveRatio,
+ record: sentPromptRecord({ sentPrompt: fullPrompt, carried: carriedPromptAdditions({ promptAdditions }),
+ added: [agentInstructionsAddition('Grok image tool instructions', buildWith)] }),
+ };
+}
+
// `initImageStrength` maps to a fidelity phrase (grok's image_edit has no
// numeric denoise knob, same constraint as codex).
export async function generateImage({
@@ -250,20 +277,9 @@ export async function generateImage({
const scratchDir = join(tmpdir(), `portos-grok-${jobId}`);
const stagingPath = join(scratchDir, 'output.png');
- // Caller dimensions win (mapped to the closest supported ratio); the saved
- // per-provider default applies when no dimensions were sent; otherwise the
- // tool's own default. Validate the saved value against the known ratios so
- // a hand-edited settings.json can't inject arbitrary prompt text.
- const derived = deriveAspectRatio(width, height);
- const configured = GROK_ASPECT_RATIOS.includes(aspectRatio) ? aspectRatio : null;
- const effectiveRatio = derived || configured;
-
- const buildWith = (text) => buildGrokPrompt({
- prompt: text, negativePrompt, aspectRatio: effectiveRatio, stagingPath,
- initImagePath: inputImages.initPath, initImageStrength,
- referenceImagePaths: inputImages.referencePaths,
+ const { fullPrompt, effectiveRatio, record: sentRecord } = grokSentPrompt({
+ prompt, negativePrompt, width, height, aspectRatio, stagingPath, inputImages, initImageStrength, promptAdditions,
});
- const fullPrompt = buildWith(prompt);
const bin = grokPath || DEFAULT_BIN;
// No model arg — grok's image tools run on xAI's fixed image backend and
@@ -276,8 +292,7 @@ export async function generateImage({
width: width ? Number(width) : null, height: height ? Number(height) : null,
filename, mode: IMAGE_GEN_MODE.GROK,
...(visualConditioning ? { visualConditioning } : {}),
- ...sentPromptRecord({ sentPrompt: fullPrompt, carried: carriedPromptAdditions({ promptAdditions }),
- added: [agentInstructionsAddition('Grok image tool instructions', buildWith)] }),
+ ...sentRecord,
...(effectiveRatio ? { aspectRatio: effectiveRatio } : {}),
createdAt: new Date().toISOString(),
};
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index e84d7c7b63..093061913a 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -569,6 +569,21 @@ export function parseImageExecutionMarker(line) {
};
}
+/**
+ * What the local runner would receive for this prompt — the LoRA trigger weave
+ * included — as the compose preview's record (#11317). Same buildSidecarMeta
+ * the render calls.
+ */
+export async function localSentPrompt({ model, modelId, prompt = '', negativePrompt = '', loraFilenames = [], loraPaths = [], promptAdditions = [] }) {
+ const loraTriggerWords = await readTriggerWordsByFilename([...loraFilenames, ...loraPaths]);
+ const { meta } = buildSidecarMeta({
+ jobId: 'preview', model: model || { id: modelId }, prompt, negativePrompt, modelId,
+ loraFilenames, loraPaths, loraTriggerWords, promptAdditions,
+ resolveInputPath: resolveImageInputPath, loraExists: existsSync,
+ });
+ return sentPromptRecord({ sentPrompt: meta.sentPrompt, sentNegativePrompt: meta.sentNegativePrompt, carried: meta.promptAdditions || [] });
+}
+
export async function generateImage({ pythonPath, prompt = '', negativePrompt = '', modelId = LOCAL_IMAGEGEN_DEFAULT_MODEL, width = 1024, height = 1024, steps, guidance, seed, quantize = '8', loraFilenames = [], loraPaths = [], loraScales = [], initImagePath = null, initImageStrength = null, referenceImagePaths = [], referenceImageStrengths = [], visualConditioning = null, jobId: providedJobId = null, cleanC2PA = false, denoise = false, regenOf = null, upscaleTo = null, outputTarget = null, promptAdditions = [] }) {
// The ingestion instant `renderTimingFields` measures from — the queue calls
// generateImage the moment it picks this job up. See lib/renderTiming.js.
diff --git a/server/services/imageGen/prepareParams.js b/server/services/imageGen/prepareParams.js
index 06207170b8..d75e94257a 100644
--- a/server/services/imageGen/prepareParams.js
+++ b/server/services/imageGen/prepareParams.js
@@ -127,7 +127,11 @@ export function selectLocalImageModelFromSettings(settings, modelId, allModels =
* @param {string[]} opts.referenceImageFields - field names for multi-ref slots
* @returns {Promise<{ data, mode, settings, uploadedTempPaths }>}
*/
-export async function prepareGenerateParams({ data, files, referenceImageFields }) {
+// A compose-time preview (#11317) names uploads it never stages: each stands in
+// as this label, so the preview shows where the image goes without copying it.
+export const previewUploadLabel = (index) => `(uploaded image ${index + 1})`;
+
+export async function prepareGenerateParams({ data, files, referenceImageFields, preview = false }) {
let initImagePath = null;
const uploadedTempPaths = [];
const initUpload = files?.initImage;
@@ -272,7 +276,7 @@ export async function prepareGenerateParams({ data, files, referenceImageFields
// A full media queue (#8326) is refused before anything is staged too — the
// route's enqueue would refuse the same render, after these copies landed.
// Lazy: only a queue-bound render needs the queue loaded.
- if (data.mediaProviderPeerId || QUEUEABLE_IMAGE_MODES.includes(mode)) {
+ if (!preview && (data.mediaProviderPeerId || QUEUEABLE_IMAGE_MODES.includes(mode))) {
await import('../mediaJobQueue/index.js')
.then(({ assertMediaQueueRoom }) => assertMediaQueueRoom(1))
.catch((err) => {
@@ -326,8 +330,11 @@ export async function prepareGenerateParams({ data, files, referenceImageFields
);
}
- if (initUpload || referenceUploads.length) await ensureDir(PATHS.imageRefs);
- if (initUpload) {
+ let uploadIndex = 0;
+ if (!preview && (initUpload || referenceUploads.length)) await ensureDir(PATHS.imageRefs);
+ if (initUpload && preview) {
+ initImagePath = previewUploadLabel(uploadIndex++);
+ } else if (initUpload) {
// Trust the validated mimetype from the fileFilter — picking the ext
// off the original filename can mismatch the bytes (e.g. HEIC saved
// as .jpg). MIME_TO_EXT only contains formats the fileFilter accepts.
@@ -373,6 +380,11 @@ export async function prepareGenerateParams({ data, files, referenceImageFields
// are filtered out above so the runner sees `referenceImagePaths: [p1, ...]`
// and aligns strengths by index.
for (const { upload, strength } of referenceUploads) {
+ if (preview) {
+ referenceImagePaths.push(previewUploadLabel(uploadIndex++));
+ referenceImageStrengths.push(typeof strength === 'number' ? strength : 1.0);
+ continue;
+ }
const ext = MIME_TO_EXT[(upload.mimetype || '').toLowerCase()] || '.png';
const refFilename = `ref-${randomUUID()}${ext}`;
const refPath = join(PATHS.imageRefs, refFilename);
diff --git a/server/services/imageGen/promptPreview.js b/server/services/imageGen/promptPreview.js
new file mode 100644
index 0000000000..af0513b972
--- /dev/null
+++ b/server/services/imageGen/promptPreview.js
@@ -0,0 +1,84 @@
+/**
+ * Compose-time preview of what an Image Gen render sends to its model (#11317):
+ * the same request preparation and the same per-backend prompt builders the
+ * render runs, without staging uploads or queueing anything. Uploads the form
+ * holds are named by `previewUploadLabel` in place of their staged path, and
+ * the grok/agy output path names the job folder it will get.
+ */
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { IMAGE_GEN_MODE } from '../../lib/generationModes.js';
+import { carriedPromptAdditions, sentPromptRecord } from '../../lib/modelInput.js';
+import { FAL_IMAGE_DEFAULT_MODEL, falImageFamily } from '../../lib/falImageModels.js';
+import { maxInputImages, resolveCloudProviderConfig } from './cloudProviderConfig.js';
+import { resolveInputImages } from './inputImages.js';
+import { prepareGenerateParams, previewUploadLabel, resolveLocalImageModel } from './prepareParams.js';
+import { codexSentPrompt } from './codex.js';
+import { grokSentPrompt } from './grok.js';
+import { agySentPrompt } from './agy.js';
+import { falImageSentPrompt } from './fal.js';
+import { localSentPrompt } from './local.js';
+
+const isUploadLabel = (path) => typeof path === 'string' && path.startsWith('(uploaded image ');
+
+// The input images in the order the render attaches them: gallery images
+// resolved as the backend resolves them, the form's uploads by label.
+function previewInputImages(mode, params, modelId) {
+ const init = params.initImagePath || null;
+ const refs = params.referenceImagePaths || [];
+ const named = resolveInputImages({
+ mode, modelId,
+ initImagePath: isUploadLabel(init) ? null : init,
+ referenceImagePaths: refs.filter((path) => !isUploadLabel(path)),
+ });
+ const initPath = isUploadLabel(init) ? init : named.initPath;
+ const ordered = [...(initPath ? [initPath] : []), ...named.referencePaths, ...refs.filter(isUploadLabel)];
+ const paths = ordered.slice(0, maxInputImages(mode, modelId) ?? ordered.length);
+ return { paths, initPath, referencePaths: initPath ? paths.slice(1) : paths };
+}
+
+const jobOutputPath = (prefix) => join(tmpdir(), `${prefix}-<job>`, 'output.png');
+
+export async function previewImagePrompt({ uploadedInitImage = false, uploadedReferenceCount = 0, ...body }) {
+ const referenceImageFields = Array.from({ length: uploadedReferenceCount }, (_, index) => `referenceImage${index + 1}`);
+ const files = {
+ ...(uploadedInitImage ? { initImage: {} } : {}),
+ ...Object.fromEntries(referenceImageFields.map((field) => [field, {}])),
+ };
+ const { data: params, mode, settings } = await prepareGenerateParams({ data: body, files, referenceImageFields, preview: true });
+ const carried = carriedPromptAdditions(params);
+ const common = {
+ prompt: params.prompt || '', negativePrompt: params.negativePrompt || '',
+ width: params.width, height: params.height, initImageStrength: params.initImageStrength,
+ promptAdditions: carried,
+ };
+ const cloud = params.mediaProviderPeerId ? null : resolveCloudProviderConfig(settings, mode, { model: params.cloudModel });
+
+ if (mode === IMAGE_GEN_MODE.CODEX) {
+ return { mode, ...codexSentPrompt({ ...common, inputImages: previewInputImages(mode, params) }).record };
+ }
+ if (mode === IMAGE_GEN_MODE.GROK) {
+ return { mode, ...grokSentPrompt({
+ ...common, aspectRatio: cloud?.providerParams.aspectRatio, stagingPath: jobOutputPath('portos-grok'),
+ inputImages: previewInputImages(mode, params),
+ }).record };
+ }
+ if (mode === IMAGE_GEN_MODE.AGY) {
+ return { mode, ...agySentPrompt({ ...common, stagingPath: jobOutputPath('portos-agy'), inputImages: previewInputImages(mode, params) }).record };
+ }
+ if (mode === IMAGE_GEN_MODE.FAL) {
+ const family = falImageFamily(cloud?.providerParams.model || FAL_IMAGE_DEFAULT_MODEL) || falImageFamily(FAL_IMAGE_DEFAULT_MODEL);
+ return { mode, ...falImageSentPrompt({ ...common, family, inputImages: previewInputImages(mode, params, family.textEndpoint) }).record };
+ }
+ if (mode === IMAGE_GEN_MODE.LOCAL && !params.mediaProviderPeerId) {
+ const { selectedModel } = resolveLocalImageModel(settings, params);
+ return { mode, ...await localSentPrompt({ ...params, ...common, model: selectedModel, modelId: selectedModel?.id || params.modelId }) };
+ }
+ // The SD-API backend and a federated provider receive the prompt and negative
+ // as written; a provider machine's own backend may add its own lines there.
+ return {
+ mode,
+ ...(params.mediaProviderPeerId ? { remote: true } : {}),
+ ...sentPromptRecord({ sentPrompt: common.prompt, sentNegativePrompt: common.negativePrompt, carried }),
+ };
+}
diff --git a/server/services/imageGen/renderTargets.guard.test.js b/server/services/imageGen/renderTargets.guard.test.js
index 319aa4989e..e468d7f418 100644
--- a/server/services/imageGen/renderTargets.guard.test.js
+++ b/server/services/imageGen/renderTargets.guard.test.js
@@ -31,11 +31,15 @@ const SERVER_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
// rejected BEFORE uploads are staged to PATHS.imageRefs. Rejecting later, in
// the route, strands those staged copies — the route's res.on('close') sweep
// covers only multer temps.
+// - services/imageGen/promptPreview.js — the compose preview of routes/imageGen.js's
+// POST /generate (#11317). It reads the mode prepareGenerateParams already
+// resolved and resolves the same provider knobs the route dispatches with.
const ALLOWED = new Set([
'services/imageGen/cloudProviderConfig.js',
'routes/imageGen.js',
'services/imageGen/index.js',
'services/imageGen/prepareParams.js',
+ 'services/imageGen/promptPreview.js',
]);
describe('render-target resolver guard (#3231)', () => {