Skip to content

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

feat: make an i2v reference image state what it promises — Anchor or Inspire (#4874)

[._.]/ Adam Eivya8b7114890dc
diff --git a/client/src/components/media/MediaJobsQueue.jsx b/client/src/components/media/MediaJobsQueue.jsx
index 3c903d687d..f2a3611dc2 100644
--- a/client/src/components/media/MediaJobsQueue.jsx
+++ b/client/src/components/media/MediaJobsQueue.jsx
@@ -9,6 +9,7 @@ import { listLoraTrainingCheckpoints } from '../../services/apiLoraTraining.js';
import { isCloudCliMode, IMAGE_GEN_MODE, CODEX_IMAGEGEN_DEFAULT_EFFORT, supportsCloudModelOverride, modeLabel } from '../../lib/imageGenBackends';
import { ANTIGRAVITY_CONFIGURED_DEFAULT, CODEX_EFFORT_LEVELS, isConfiguredDefaultModel } from '../../utils/providers';
import { lossSparklineGeometry } from '../../lib/lossSparkline';
+import { isDefaultI2vReferenceMode, normalizeI2vReferenceMode, resolveI2vReferenceStrength } from '../../lib/videoReferenceModes';
import { useAutoRefetch } from '../../hooks/useAutoRefetch';
import { useConfirmDelete } from '../../hooks/useConfirmDelete';
import useMounted from '../../hooks/useMounted';
@@ -699,6 +700,10 @@ function VideoRetryForm({ job, onSubmit, onCancel }) {
const [steps, setSteps] = useState(p.steps ?? '');
const [guidanceScale, setGuidanceScale] = useState(p.guidanceScale ?? '');
const [imageStrength, setImageStrength] = useState(p.imageStrength ?? '');
+ // The conditioning promise rides the retry the same way the strength does — a
+ // retry that silently dropped it would re-render an anchored clip under the
+ // original job's Inspire label. Absent means the default.
+ const [i2vReferenceMode, setI2vReferenceMode] = useState(normalizeI2vReferenceMode(p.i2vReferenceMode));
const [tiling, setTiling] = useState(p.tiling || 'auto');
const [disableAudio, setDisableAudio] = useState(p.disableAudio === true);
const [textEncoderId, setTextEncoderId] = useState(p.textEncoderId || STOCK_TEXT_ENCODER_ID);
@@ -771,6 +776,11 @@ function VideoRetryForm({ job, onSubmit, onCancel }) {
setNumericOverride('steps', steps, p.steps, true);
setNumericOverride('guidanceScale', guidanceScale, p.guidanceScale, true);
setNumericOverride('imageStrength', imageStrength, p.imageStrength, true);
+ if (i2vReferenceMode !== normalizeI2vReferenceMode(p.i2vReferenceMode)) {
+ // `null` clears the persisted value, mirroring the numeric knobs above — an
+ // explicit 'anchor' would leave the retry carrying a knob that changed nothing.
+ overrides.i2vReferenceMode = isDefaultI2vReferenceMode(i2vReferenceMode) ? null : i2vReferenceMode;
+ }
if (tiling !== (p.tiling || 'auto')) overrides.tiling = tiling;
if (disableAudio !== (p.disableAudio === true)) overrides.disableAudio = disableAudio;
// A model switch can normalize an inherited encoder to stock locally;
@@ -826,6 +836,8 @@ function VideoRetryForm({ job, onSubmit, onCancel }) {
fps={displayedFps} onFpsChange={setFps} seed={seed} onSeedChange={setSeed} onRandomSeed={() => setSeed(Math.floor(Math.random() * 2147483647))}
steps={steps} onStepsChange={setSteps} guidanceScale={guidanceScale} onGuidanceScaleChange={setGuidanceScale}
imageStrength={imageStrength} onImageStrengthChange={setImageStrength} tiling={tiling} onTilingChange={setTiling}
+ i2vReferenceMode={i2vReferenceMode} onI2vReferenceModeChange={setI2vReferenceMode}
+ effectiveImageStrength={resolveI2vReferenceStrength(i2vReferenceMode, imageStrength)}
disableAudio={disableAudio} onDisableAudioChange={setDisableAudio}
idPrefix={`retry-video-${job.id}`}
/>
diff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsx
index 9026909aa7..011f0f8f97 100644
--- a/client/src/components/media/MediaLightbox.jsx
+++ b/client/src/components/media/MediaLightbox.jsx
@@ -12,6 +12,7 @@ import MediaImage from '../MediaImage';
import { useScrollLock } from '../../hooks/useScrollLock';
import { useSwipeNav } from '../../hooks/useSwipeNav';
import { isEditableTarget } from '../../lib/a11yKeyboard';
+import { i2vReferenceModeLabel } from '../../lib/videoReferenceModes';
import useFocusTrap from '../../hooks/useFocusTrap.js';
import { copyToClipboard } from '../../lib/clipboard';
import { IMAGE_GEN_MODE } from '../../lib/imageGenBackends';
@@ -228,6 +229,12 @@ export default function MediaLightbox({
['Cleaned', cleanedLabel],
['Frames', item.numFrames],
['FPS', item.fps],
+ // What the conditioning image promised (#4874). Recorded on the render only
+ // when it wasn't the default, so this row appears exactly on the clips whose
+ // opening frame was generated rather than reproduced — the one fact the
+ // Image Strength number alone never told anyone.
+ ['Reference', item.raw?.i2vReferenceMode ? i2vReferenceModeLabel(item.raw.i2vReferenceMode) : null],
+ ['Image strength', item.raw?.imageStrength],
['Created', item.createdAt && formatDateTime(item.createdAt)],
].filter(([, v]) => v != null && v !== '');
diff --git a/client/src/components/media/MediaLightbox.test.jsx b/client/src/components/media/MediaLightbox.test.jsx
index 3f0a792fb2..f0516e525d 100644
--- a/client/src/components/media/MediaLightbox.test.jsx
+++ b/client/src/components/media/MediaLightbox.test.jsx
@@ -192,3 +192,39 @@ describe('MediaLightbox route-changing actions', () => {
expect(calls).toEqual(['close', 'send']);
});
});
+
+// The conditioning promise (#4874) is provenance: a clip whose opening frame was
+// GENERATED rather than reproduced has to say so where the render is inspected.
+// The Image Strength number alone never carried that distinction.
+describe('MediaLightbox — i2v reference provenance (#4874)', () => {
+ // jsdom has no HTMLMediaElement.play; the lightbox calls it on mount for a
+ // video item, so stub it here the way the playback suite above does.
+ beforeEach(() => { HTMLMediaElement.prototype.play = vi.fn(() => Promise.resolve()); });
+ afterEach(() => { delete HTMLMediaElement.prototype.play; });
+
+ const videoItem = (raw) => ({
+ kind: 'video',
+ key: 'video:ref-1',
+ id: 'ref-1',
+ filename: 'ref-1.mp4',
+ downloadUrl: '/data/videos/ref-1.mp4',
+ prompt: 'a fox in the rain',
+ modelId: 'ltx25_mlx_q8',
+ numFrames: 121,
+ fps: 24,
+ createdAt: '2026-08-23T10:00:00.000Z',
+ raw,
+ });
+
+ it('names the promise and the strength that delivered it', () => {
+ render(<MediaLightbox item={videoItem({ i2vReferenceMode: 'inspire', imageStrength: 0.35 })} onClose={() => {}} />);
+ expect(screen.getByText('Reference')).toBeTruthy();
+ expect(screen.getByText('Inspire')).toBeTruthy();
+ expect(screen.getByText('Image strength')).toBeTruthy();
+ });
+
+ it('shows no Reference row for an anchored render, so the row means something', () => {
+ render(<MediaLightbox item={videoItem({})} onClose={() => {}} />);
+ expect(screen.queryByText('Reference')).toBeNull();
+ });
+});
diff --git a/client/src/components/videoGen/AdvancedParamsPanel.jsx b/client/src/components/videoGen/AdvancedParamsPanel.jsx
index dfa5e35d30..f544bea41a 100644
--- a/client/src/components/videoGen/AdvancedParamsPanel.jsx
+++ b/client/src/components/videoGen/AdvancedParamsPanel.jsx
@@ -15,6 +15,10 @@ import {
} from '../../lib/videoGenParams.js';
import { VIDEO_TILING_OPTIONS } from '../../lib/videoTilingOptions';
import { isLtx2FamilyRuntime } from '../../lib/runnerFamilies';
+import {
+ I2V_REFERENCE_MODE_OPTIONS, DEFAULT_I2V_REFERENCE_MODE,
+ normalizeI2vReferenceMode, runtimeSupportsI2vReferenceMode,
+} from '../../lib/videoReferenceModes';
const inputCls = 'w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50';
@@ -30,6 +34,8 @@ export default function AdvancedParamsPanel({
steps, onStepsChange,
guidanceScale, onGuidanceScaleChange,
imageStrength, onImageStrengthChange,
+ i2vReferenceMode = DEFAULT_I2V_REFERENCE_MODE, onI2vReferenceModeChange,
+ effectiveImageStrength = null,
tiling, onTilingChange,
disableAudio, onDisableAudioChange,
noMusic, onNoMusicChange,
@@ -48,6 +54,18 @@ export default function AdvancedParamsPanel({
// ltx2 extend conditions on the source's latent rather than a single frame,
// so image strength is meaningless for it.
const showImageStrength = mode === 'image' || (mode === 'extend' && !isLtx2FamilyRuntime(currentModel?.runtime));
+ // The reference-mode promise (#4874) is an image-mode question only, and only
+ // a runtime that carries per-image conditioning strength can keep anything but
+ // the default. Rendering it read-only elsewhere would imply a choice that does
+ // not exist, so the picker appears in image mode and explains itself when the
+ // selected model cannot honor the loose option.
+ const showReferenceMode = mode === 'image' && typeof onI2vReferenceModeChange === 'function';
+ const referenceMode = normalizeI2vReferenceMode(i2vReferenceMode);
+ const referenceOptions = I2V_REFERENCE_MODE_OPTIONS.filter(
+ (o) => runtimeSupportsI2vReferenceMode(currentModel?.runtime, o.value),
+ );
+ const referencePromise = I2V_REFERENCE_MODE_OPTIONS.find((o) => o.value === referenceMode);
+ const referenceModeLocked = referenceOptions.length < 2;
const frameOptions = frameOptionsForModel(currentModel, numFrames);
const fpsOptions = fpsOptionsForModel(currentModel);
const samplerLocked = currentModel?.samplerLocked === true;
@@ -229,16 +247,37 @@ export default function AdvancedParamsPanel({
</p>
)}
+ {showReferenceMode && (
+ <div className="col-span-2 sm:col-span-3">
+ <label htmlFor={fieldId('video-reference-mode')} className="block text-xs font-medium text-gray-400 mb-1">Reference mode</label>
+ <select
+ id={fieldId('video-reference-mode')}
+ value={referenceMode}
+ disabled={referenceModeLocked}
+ onChange={(e) => onI2vReferenceModeChange(e.target.value)}
+ className={inputCls}
+ >
+ {referenceOptions.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
+ </select>
+ <p className="text-[10px] text-gray-500 leading-snug mt-1">{referencePromise?.promise}</p>
+ {referenceModeLocked && (
+ <p className="text-[10px] text-gray-500 leading-snug mt-1">
+ {currentModel?.name || 'This model'} can only anchor a reference. Pick an LTX-2.5 model to loosen it.
+ </p>
+ )}
+ </div>
+ )}
+
{showImageStrength && (
<div className="col-span-2 sm:col-span-3">
<div className="flex items-center justify-between gap-3 mb-1">
<label htmlFor={fieldId('video-image-strength')} className="block text-xs font-medium text-gray-400">Image Strength</label>
- <span className="text-[11px] text-gray-500">{imageStrength || '1.0'}</span>
+ <span className="text-[11px] text-gray-500">{imageStrength || (effectiveImageStrength != null ? String(effectiveImageStrength) : '1.0')}</span>
</div>
<input
id={fieldId('video-image-strength')}
type="range" min={0} max={1} step={0.05}
- value={imageStrength || 1}
+ value={imageStrength || effectiveImageStrength || 1}
onChange={(e) => onImageStrengthChange(e.target.value)}
className="w-full accent-port-accent"
title="Higher values preserve the source frame more strongly"
diff --git a/client/src/components/videoGen/AdvancedParamsPanel.test.jsx b/client/src/components/videoGen/AdvancedParamsPanel.test.jsx
index 6143462d11..37268ec318 100644
--- a/client/src/components/videoGen/AdvancedParamsPanel.test.jsx
+++ b/client/src/components/videoGen/AdvancedParamsPanel.test.jsx
@@ -190,3 +190,61 @@ describe('AdvancedParamsPanel', () => {
});
});
});
+
+// What the source image PROMISES (#4874). The panel is the surface that states
+// the promise, so a wrong option list here is a lie the user acts on.
+describe('AdvancedParamsPanel — i2v reference mode (#4874)', () => {
+ const LTX25 = { runtime: 'ltx25', name: 'LTX-2.5 MLX Q8', supportedModes: MLX_MODES };
+ const withReference = (props = {}) => renderPanel({
+ mode: 'image',
+ currentModel: LTX25,
+ i2vReferenceMode: 'anchor',
+ onI2vReferenceModeChange: vi.fn(),
+ ...props,
+ });
+
+ it('offers both promises on a runtime that can keep them, and prints the active one', () => {
+ withReference();
+ const select = screen.getByLabelText('Reference mode');
+ expect([...select.options].map((o) => o.value)).toEqual(['anchor', 'inspire']);
+ expect(select.disabled).toBe(false);
+ expect(screen.getByText(/reference is frame one/i)).toBeTruthy();
+ });
+
+ it('states the Inspire promise when Inspire is selected', () => {
+ withReference({ i2vReferenceMode: 'inspire' });
+ expect(screen.getByText(/without reproducing it/i)).toBeTruthy();
+ });
+
+ it('offers only Anchor — locked, and explains why — on a runtime that pins frame one', () => {
+ withReference({ currentModel: { runtime: 'ltx2', name: 'LTX-2 Unified', supportedModes: MLX_MODES } });
+ const select = screen.getByLabelText('Reference mode');
+ expect([...select.options].map((o) => o.value)).toEqual(['anchor']);
+ expect(select.disabled).toBe(true);
+ expect(screen.getByText(/Pick an LTX-2\.5 model to loosen it/i)).toBeTruthy();
+ });
+
+ it.each(['text', 'fflf', 'extend', 'a2v'])('hides the picker in %s mode', (mode) => {
+ withReference({ mode });
+ expect(screen.queryByLabelText('Reference mode')).toBeNull();
+ });
+
+ it('hides the picker when no handler is wired, rather than rendering a dead control', () => {
+ renderPanel({ mode: 'image', currentModel: LTX25 });
+ expect(screen.queryByLabelText('Reference mode')).toBeNull();
+ });
+
+ it('reports the change up', () => {
+ const onI2vReferenceModeChange = vi.fn();
+ withReference({ onI2vReferenceModeChange });
+ fireEvent.change(screen.getByLabelText('Reference mode'), { target: { value: 'inspire' } });
+ expect(onI2vReferenceModeChange).toHaveBeenCalledWith('inspire');
+ });
+
+ it('shows the strength the render will ACTUALLY use, not the pipeline default', () => {
+ // An untouched slider under Inspire resolves to the contract's low default;
+ // printing "1.0" there would describe an anchored render.
+ withReference({ i2vReferenceMode: 'inspire', imageStrength: '', effectiveImageStrength: 0.35 });
+ expect(screen.getByText('0.35')).toBeTruthy();
+ });
+});
diff --git a/client/src/hooks/useVideoGenForm.js b/client/src/hooks/useVideoGenForm.js
index 130d865a77..c714b03340 100644
--- a/client/src/hooks/useVideoGenForm.js
+++ b/client/src/hooks/useVideoGenForm.js
@@ -5,6 +5,10 @@ import { extractLastFrame } from '../services/api';
import { trackAudioUrl } from '../services/apiTracks.js';
import { composeStyledPrompt } from '../lib/composeStyledPrompt';
import { videoLoraFamily, isVideoLoraFamily, loraFamilyOf, VIDEO_LORA_FAMILIES, isLtx2FamilyRuntime } from '../lib/runnerFamilies';
+import {
+ DEFAULT_I2V_REFERENCE_MODE, isDefaultI2vReferenceMode, normalizeI2vReferenceMode,
+ runtimeSupportsI2vReferenceMode, resolveI2vReferenceStrength,
+} from '../lib/videoReferenceModes';
import { randomSeed } from '../lib/genUtils';
import {
resolutionOptionsForModel, defaultResolutionForModel, snapAspectToImage,
@@ -117,6 +121,12 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, r
const [steps, setSteps] = useState('');
const [guidanceScale, setGuidanceScale] = useState('');
const [imageStrength, setImageStrength] = useState('');
+ // What the source image PROMISES (#4874): Anchor reproduces it as frame one,
+ // Inspire uses it for subject/style guidance and generates frame one. The
+ // effect below snaps this back to the default whenever the selected model or
+ // mode can't keep the promise, so the form can never submit a mode the server
+ // would reject — or, worse, display a promise the render would not honor.
+ const [i2vReferenceMode, setI2vReferenceMode] = useState(DEFAULT_I2V_REFERENCE_MODE);
const [seed, setSeed] = useState('');
const [tiling, setTiling] = useState('auto');
// Which prompt conditioner reads the prompt. Only MiniMax H3 offers a choice
@@ -586,6 +596,21 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, r
// (server/services/videoGen/runtimes.js), so this can't drift from the
// resize/forwarding decision the render path makes off the same flag.
const lastFrameIsAdvisory = !currentModel?.lastFrameAnchored;
+ // A loose reference needs a runtime that carries per-image conditioning
+ // strength (LTX-2.5 today) AND an image-mode render to loosen. Both are read
+ // from the shared contract the server gates on, so the picker can never offer
+ // an option the POST would 400 on.
+ const referenceModeSupported = runtimeSupportsI2vReferenceMode(currentModel?.runtime, 'inspire');
+ const referenceModeApplies = mode === 'image';
+ // The strength the render will actually use, for the slider readout — an
+ // untouched slider under Inspire still resolves to the contract's low default
+ // rather than the pipeline's 1.0, and the panel must say so.
+ const effectiveImageStrength = resolveI2vReferenceStrength(i2vReferenceMode, imageStrength);
+ useEffect(() => {
+ if (isDefaultI2vReferenceMode(i2vReferenceMode)) return;
+ if (referenceModeApplies && referenceModeSupported) return;
+ setI2vReferenceMode(DEFAULT_I2V_REFERENCE_MODE);
+ }, [i2vReferenceMode, referenceModeApplies, referenceModeSupported]);
// IC-LoRA remix mode is on. `icSpec` is the registry entry (reference count +
// the resolution-divisibility rule its encoder imposes); null outside the
// family, so every consumer gates on `icModeActive` first.
@@ -996,6 +1021,15 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, r
// store a boolean here — silently ignore unknown values so the <select>
// stays valid and the next POST doesn't 400.
if (typeof item.tiling === 'string' && VIDEO_TILING_ENUM_SET.has(item.tiling)) setTiling(item.tiling);
+ // ALWAYS set explicitly, like steps/guidanceScale above: history stamps these
+ // only when they applied, so a missing field means "the defaults" and has to
+ // clear a leftover value rather than steer a render the user asked to
+ // reproduce faithfully. Remix resets to text mode below, which snaps the
+ // reference mode back to Anchor — restoring it is still what keeps the value
+ // correct the moment the user switches back to image mode with the record's
+ // own source.
+ setImageStrength(item.imageStrength != null && item.imageStrength !== '' ? String(item.imageStrength) : '');
+ setI2vReferenceMode(normalizeI2vReferenceMode(item.i2vReferenceMode));
// ALWAYS set explicitly (like steps/guidanceScale above): history records the
// conditioner only when it wasn't the stock one, so a missing field means
// 'stock' and must clear a leftover override rather than silently reusing it
@@ -1101,6 +1135,12 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, r
if (p.guidanceScale != null) setGuidanceScale(String(p.guidanceScale));
if (p.seed != null) setSeed(String(p.seed));
if (p.tiling) setTiling(p.tiling);
+ // Conditioning promise + strength. Both are echoed only when they applied, so
+ // absence means "the defaults" and must CLEAR whatever the form last held —
+ // a resumed page that kept a stale Inspire pick would describe the running
+ // render's frame one wrongly.
+ setImageStrength(p.imageStrength != null && p.imageStrength !== '' ? String(p.imageStrength) : '');
+ setI2vReferenceMode(normalizeI2vReferenceMode(p.i2vReferenceMode));
// Resume echoes the field only for a non-stock render, so absence is 'stock'.
setTextEncoderId(textEncoderIdFromRecord(p.textEncoderId));
if (typeof p.disableAudio === 'boolean') setDisableAudio(p.disableAudio);
@@ -1336,6 +1376,10 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, r
disableAudio: effectiveDisableAudio ? 'true' : 'false',
mode,
imageStrength: imageStrength || '',
+ // Dropped entirely on the default so an anchored render posts exactly the
+ // body it did before this knob existed. The snap-back effect guarantees a
+ // non-default value here is one the selected model + mode can honor.
+ i2vReferenceMode: isDefaultI2vReferenceMode(i2vReferenceMode) ? '' : i2vReferenceMode,
// ltx2-extend bypasses the last-frame i2v path: we send the source
// video's history id directly so the server resolves it to a disk
// path and routes through ExtendPipeline. Legacy extend (mlx_video)
@@ -1420,6 +1464,8 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, r
steps, setSteps,
guidanceScale, setGuidanceScale,
imageStrength, setImageStrength,
+ i2vReferenceMode, setI2vReferenceMode,
+ referenceModeSupported, effectiveImageStrength,
seed, setSeed, handleRandomSeed,
tiling, setTiling,
textEncoderId, setTextEncoderId, textEncoderOptions,
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index bd9e74ba8b..d56d08aeb5 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -75,6 +75,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `videoFinish.js` | Finish-a-draft gate (#3696). `isReproducibleTextToVideo(record)` is true only for a single text-to-video render whose history record already carries everything a re-render needs — `renderInputsVersion` (the positive marker that its conditioning inventory is trustworthy, so legacy records degrade to not-finishable rather than reading as unconditioned), an empty `conditioning` array, a resolved seed, a real prompt, and no stitched/chained/upscaled provenance. `finishTargetForRecord(record, models)` additionally resolves the draft model's server-declared `finishModelId` against the models this install can actually run, returning the delivery model entry or `null`. Mirrors `finishTargetForModel` in `server/lib/videoFinishProfiles.js`; the pair table itself stays server-side. |
| `videoGenParams.js` | Pure VideoGen param helpers: `FRAME_OPTIONS`/`FPS_OPTIONS`/`VIDEO_EDGE_BOUNDS`/`MAX_CHUNKS`/`CHUNK_OPTIONS`/`DEFAULT_CONTEXT_FRAMES`/`CONTEXT_FRAME_OPTIONS` constants, model-aware frame/fps/resolution-grid normalization, separate mute vs prompt-audio capability checks, `supportsContextWindow(model)` (does this runtime have an extend pipeline to feed a continuation window to — display mirror of `server/lib/videoContinuity.js`, pinned by `server/lib/videoContinuity.parity.test.js`), `videoModelMemoryGb()` (model memory footprint), `computeFflfSafeFrames()` (FFLF/ltx2 pixel-budget back-solve, mirrors `server/services/videoGen/local.js`), and `isModelAllowedForMode()` (a2v + IC-remix → ltx2 gate). Also mirrors the IC-LoRA remix registry (`IC_LORA_MODES`/`IC_LORA_MODE_VALUES`/`isIcLoraMode()`/`icLoraSpecForMode()`/`icResolutionIssue()`) from `server/lib/icLoraWeights.js` so the form validates a reference render pre-submit — pinned by `server/lib/icLoraWeights.parity.test.js`. |
| `videoGenResolutions.js` | Shared resolution presets/default for video generation, model-specific preset/default resolvers (for native canvases such as MiniMax H3), and `snapAspectToImage()` to pick the closest-aspect preset for an I2V source. |
+| `videoReferenceModes.js` | Mirror of `server/lib/videoReferenceModes.js` (parity enforced by `server/lib/videoReferenceModes.mirror.test.js`) — the i2v reference-mode contract: `I2V_REFERENCE_MODES`, `I2V_REFERENCE_MODE_OPTIONS` (label + the promise sentence `AdvancedParamsPanel` and the source-frame note print), `runtimeSupportsI2vReferenceMode` (gates which options the picker offers), `resolveI2vReferenceStrength` (the effective strength the panel displays), and `i2vReferenceModeViolation` for pre-submit feedback. |
| `videoStagePreview.js` | VideoGen main-stage preview resolver (#4588). `resolveVideoStagePreview({ generating, currentImage, width, height, result, extendSource, sourceImageFile/Url, lastImageFile/Url, keyframes })` → `{ kind: 'live'|'loop'|'still'|'result'|'empty', src, poster, label, aspectRatio }` — what the stage should show at each moment of a render, with mid-render vs idle precedence. Plus `videoStageAspectRatio()` (a NUMBER for an inline `aspect-ratio` style — a computed Tailwind `aspect-[w/h]` class never reaches the JIT build; `null` means unknown geometry, not 16:9), `videoPreviewFrameSrc()` (the runners' `currentImage` is polymorphic — raw base64 from imageGen, a served URL from loraTraining — so classify before prefixing), and `videoStageSignature()` for the hold/return guard in `components/videoGen/LiveVideoStage.jsx`. |
| `videoTilingOptions.js` | `VIDEO_TILING_OPTIONS` (the `<select>` rows) + `VIDEO_TILING_ENUM_SET` (the value-only Set). Single source consumed by `VideoGen.jsx` and the Remix URL builder in `useMediaPreviewActions`. Mirrors the server's `z.enum` in `server/routes/videoGen.js`. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 27b52db640..8d356d23c1 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -54,6 +54,7 @@ export * from './slashdoCatalog.js';
export * from './videoFinish.js';
export * from './videoGenParams.js';
export * from './videoGenResolutions.js';
+export * from './videoReferenceModes.js';
export * from './videoStagePreview.js';
export * from './videoTilingOptions.js';
export * from './wrImageDefaults.js';
diff --git a/client/src/lib/videoReferenceModes.js b/client/src/lib/videoReferenceModes.js
new file mode 100644
index 0000000000..98a9e7c3b4
--- /dev/null
+++ b/client/src/lib/videoReferenceModes.js
@@ -0,0 +1,141 @@
+/**
+ * Mirror of server/lib/videoReferenceModes.js — keep the LOGIC byte-for-byte in
+ * sync (server/lib/videoReferenceModes.mirror.test.js is the contract; it
+ * strips comments, so this commentary may diverge but nothing else may).
+ *
+ * Vites fs.allow does not cross the server/ boundary, so the client carries its
+ * own copy of the i2v reference-mode table. The page uses it to decide which
+ * options to offer, what promise to print next to the source-image picker, and
+ * what the effective conditioning strength will be — a drifted copy would
+ * promise the user a render the server refuses, or worse, one it silently
+ * downgrades.
+ */
+
+// Ordered — the UI renders the picker in this order and `anchor` is first
+// because it is the default.
+export const I2V_REFERENCE_MODES = Object.freeze(['anchor', 'inspire']);
+
+export const DEFAULT_I2V_REFERENCE_MODE = 'anchor';
+
+// The promise each mode makes, in the words the UI shows the user. Kept beside
+// the rule table rather than in the component so the server's rejection message
+// and the panel's helper text can't describe two different contracts.
+export const I2V_REFERENCE_MODE_OPTIONS = Object.freeze([
+ Object.freeze({
+ value: 'anchor',
+ label: 'Anchor',
+ promise: 'The reference is frame one — the clip animates outward from those exact pixels.',
+ }),
+ Object.freeze({
+ value: 'inspire',
+ label: 'Inspire',
+ promise: 'The reference guides subject and style. Frame one is generated, so it resembles the image without reproducing it.',
+ }),
+]);
+
+// Runtimes that can honor each mode. `null` means "every runtime" — `anchor` is
+// what an i2v pipeline does by construction. `inspire` needs per-image
+// conditioning strength, which today only the LTX-2.5 pin exposes
+// (ImageConditioningInput on generate_and_save); the 2.3 pin shares the family
+// predicate but not that API, so it is NOT listed.
+export const I2V_REFERENCE_MODE_RUNTIMES = Object.freeze({
+ anchor: null,
+ inspire: Object.freeze(['ltx25']),
+});
+
+// Conditioning strength applied to a loose reference when the user leaves the
+// Image Strength slider untouched. Low enough that the first frame is visibly
+// re-generated rather than reproduced — which is exactly the promise `inspire`
+// makes. An explicit slider value always wins.
+export const INSPIRE_DEFAULT_IMAGE_STRENGTH = 0.35;
+
+/**
+ * `''` / `null` / `undefined` all mean "not set" and resolve to the default.
+ * Anything else is returned VERBATIM so an unknown value reaches the gate below
+ * and is rejected there — collapsing garbage into `anchor` would turn a typo
+ * into a silently different render (AGENTS: sentinel + validate, never let
+ * invalid share a value with valid).
+ */
+export const normalizeI2vReferenceMode = (value) => (
+ value == null || value === '' ? DEFAULT_I2V_REFERENCE_MODE : value
+);
+
+export const isDefaultI2vReferenceMode = (value) => (
+ normalizeI2vReferenceMode(value) === DEFAULT_I2V_REFERENCE_MODE
+);
+
+export const isKnownI2vReferenceMode = (value) => (
+ I2V_REFERENCE_MODES.includes(normalizeI2vReferenceMode(value))
+);
+
+/** Can `runtime` deliver what `value` promises? Unknown modes are never supported. */
+export const runtimeSupportsI2vReferenceMode = (runtime, value) => {
+ const mode = normalizeI2vReferenceMode(value);
+ if (!I2V_REFERENCE_MODES.includes(mode)) return false;
+ const allowed = I2V_REFERENCE_MODE_RUNTIMES[mode];
+ return allowed === null || allowed.includes(runtime);
+};
+
+export const i2vReferenceModeLabel = (value) => (
+ I2V_REFERENCE_MODE_OPTIONS.find((o) => o.value === normalizeI2vReferenceMode(value))?.label
+ || normalizeI2vReferenceMode(value)
+);
+
+/**
+ * The effective first-frame conditioning strength for a render, or `null` for
+ * "let the pipeline apply its own default".
+ *
+ * An explicit slider value is honored on BOTH modes — a user who wants a firmer
+ * loose reference (or a softer anchor) gets it. Only the *unset* case differs:
+ * `inspire` substitutes its own low default, because "no value" there still has
+ * to mean "don't reproduce frame one", while `anchor` keeps deferring to the
+ * pipeline exactly as it did before this field existed.
+ */
+export const resolveI2vReferenceStrength = (referenceMode, imageStrength) => {
+ if (imageStrength != null && imageStrength !== '') {
+ const explicit = Number(imageStrength);
+ if (Number.isFinite(explicit)) return explicit;
+ }
+ return normalizeI2vReferenceMode(referenceMode) === 'inspire'
+ ? INSPIRE_DEFAULT_IMAGE_STRENGTH
+ : null;
+};
+
+/**
+ * The one reference-mode rule, as a pure `{ code, message } | null`.
+ *
+ * `anchor` is always legal, so a request that never touched this field can
+ * never be rejected by it. Everything else has to clear three gates: the value
+ * is known, the render is actually image-to-video with a source image, and the
+ * model's runtime can honor the promise.
+ *
+ * @param {object} opts
+ * @param {object} [opts.model] - registry entry (`name`, `runtime`)
+ * @param {string} [opts.mode] - RESOLVED semantic mode ('image', 'text', 'fflf', …)
+ * @param {string} [opts.referenceMode]- requested reference mode
+ * @param {boolean} [opts.hasFirstImage] - a first-frame conditioning image is present
+ */
+export const i2vReferenceModeViolation = ({ model, mode, referenceMode, hasFirstImage = true } = {}) => {
+ const requested = normalizeI2vReferenceMode(referenceMode);
+ if (requested === DEFAULT_I2V_REFERENCE_MODE) return null;
+ if (!I2V_REFERENCE_MODES.includes(requested)) {
+ return {
+ code: 'I2V_REFERENCE_MODE_UNKNOWN',
+ message: `Unknown reference mode "${requested}" — expected one of ${I2V_REFERENCE_MODES.join(', ')}.`,
+ };
+ }
+ const label = i2vReferenceModeLabel(requested);
+ if (mode !== 'image' || !hasFirstImage) {
+ return {
+ code: 'I2V_REFERENCE_MODE_REQUIRES_IMAGE',
+ message: `${label} reference mode applies to image-to-video only — switch to image mode with a source image, or use ${i2vReferenceModeLabel(DEFAULT_I2V_REFERENCE_MODE)}.`,
+ };
+ }
+ if (!runtimeSupportsI2vReferenceMode(model?.runtime, requested)) {
+ return {
+ code: 'I2V_REFERENCE_MODE_UNSUPPORTED',
+ message: `${model?.name || 'This model'} cannot honor the ${label} reference mode — its runtime ("${model?.runtime || 'mlx_video'}") pins the reference as frame one. Choose an LTX-2.5 model, or switch to ${i2vReferenceModeLabel(DEFAULT_I2V_REFERENCE_MODE)}.`,
+ };
+ }
+ return null;
+};
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index badca2179b..a1c3bfb8ad 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -161,6 +161,7 @@ export default function VideoGen() {
chunkPrompts, setChunkPromptAt, chainingActive,
contextFrames, setContextFrames,
steps, setSteps, guidanceScale, setGuidanceScale, imageStrength, setImageStrength,
+ i2vReferenceMode, setI2vReferenceMode, referenceModeSupported, effectiveImageStrength,
seed, setSeed, handleRandomSeed, tiling, setTiling,
textEncoderId, setTextEncoderId, textEncoderOptions,
disableAudio, setDisableAudio, noMusic, setNoMusic,
@@ -1075,6 +1076,14 @@ export default function VideoGen() {
onUpload={uploadSourceImage}
onClear={clearSourceImage}
alt="Source"
+ advisoryNote={mode === 'image' && i2vReferenceMode === 'inspire' ? {
+ text: 'Inspire — frame one is generated from this, not copied.',
+ title: 'Inspire conditions the opening frame loosely, so the clip carries this image\u2019s subject and style without reproducing its exact pixels. Switch Reference mode to Anchor under Advanced to make it frame one.',
+ } : null}
+ hint={mode === 'image' && !referenceModeSupported ? {
+ text: 'This model anchors the reference — it becomes frame one exactly.',
+ title: 'Only LTX-2.5 carries a per-image conditioning strength, which is what a loose (Inspire) reference needs. Every other runtime pins the supplied image as frame one.',
+ } : null}
/>
{mode === 'fflf' && (
<FramePanel
@@ -1342,6 +1351,8 @@ export default function VideoGen() {
steps={steps} onStepsChange={setSteps}
guidanceScale={guidanceScale} onGuidanceScaleChange={setGuidanceScale}
imageStrength={imageStrength} onImageStrengthChange={setImageStrength}
+ i2vReferenceMode={i2vReferenceMode} onI2vReferenceModeChange={setI2vReferenceMode}
+ effectiveImageStrength={effectiveImageStrength}
tiling={tiling} onTilingChange={setTiling}
disableAudio={disableAudio} onDisableAudioChange={setDisableAudio}
noMusic={noMusic} onNoMusicChange={setNoMusic}
diff --git a/scripts/generate_ltx2.py b/scripts/generate_ltx2.py
index 00d4afd18d..24cbea81f1 100644
--- a/scripts/generate_ltx2.py
+++ b/scripts/generate_ltx2.py
@@ -464,6 +464,13 @@ def parse_args() -> argparse.Namespace:
p.add_argument("--cfg-scale", type=float, default=None)
p.add_argument("--image-strength", type=float, default=None,
help="First-frame conditioning strength for image mode (0.0-1.0).")
+ p.add_argument("--i2v-reference-mode", choices=["anchor", "inspire"], default="anchor",
+ help="What --image PROMISES in image mode. 'anchor' (default) pins it as "
+ "frame one, reproducing those pixels; 'inspire' conditions loosely so "
+ "the reference guides subject/style while frame one is generated. "
+ "'inspire' needs a pin whose generate_and_save accepts "
+ "images=[ImageConditioningInput(...)]; the run FAILS rather than "
+ "silently anchoring when it does not.")
p.add_argument("--dev-transformer", default=None,
help="Filename of the non-distilled (dev) transformer inside the model repo. "
"Required for fflf mode — KeyframeInterpolationPipeline rejects pure-distilled "
@@ -565,6 +572,22 @@ def parse_text_encoder_config_overrides(raw: str | None) -> dict:
return parsed
+def validate_reference_mode_args(args: argparse.Namespace) -> None:
+ """Reject a loose reference on a mode that cannot express one, before any load.
+
+ A loose ("inspire") reference is an image-mode promise. Every other mode pins
+ its conditioning by construction — fflf keyframes, extend latents, a2v audio,
+ an IC reference clip — so the flag has nothing to loosen there, and accepting
+ it would render an anchored clip under a loose-reference label. PortOS gates
+ this server-side too; this covers a direct CLI caller.
+ """
+ if args.i2v_reference_mode != "anchor" and args.mode != "image":
+ raise SystemExit(
+ f"--i2v-reference-mode {args.i2v_reference_mode} applies to --mode image only; "
+ f"got --mode {args.mode}."
+ )
+
+
def validate_text_encoder_args(args: argparse.Namespace) -> None:
"""Reject a partial substitution set before any weights load.
@@ -935,12 +958,31 @@ def _apply_legacy_image_strength(image_strength: float) -> bool:
return True
+# Conditioning strength applied to a loose ("inspire") reference when the caller
+# passes no --image-strength. PortOS resolves the same default server-side and
+# always sends an explicit value (see lib/videoReferenceModes.js —
+# INSPIRE_DEFAULT_IMAGE_STRENGTH is authoritative), so this only covers a direct
+# CLI invocation of this script.
+INSPIRE_DEFAULT_IMAGE_STRENGTH = 0.35
+
+
def _image_conditioning_kwargs(generate_and_save, image: str | None,
- image_strength: float | None) -> dict:
+ image_strength: float | None,
+ reference_mode: str = "anchor") -> dict:
"""I2V image kwarg(s) for generate_and_save, honoring --image-strength on both pins.
- Returns {} when there's no source image. With no strength override we pass a
- bare `image=` on every pin — unchanged behavior. With a strength override:
+ `reference_mode` is what the image PROMISES (#4874). "anchor" is the historical
+ behavior: the reference is frame one. "inspire" conditions the same frame-0 slot
+ at a deliberately low strength so the reference steers subject/style while the
+ opening frame is re-generated — the only loose-reference mechanism the MLX
+ pipelines expose. Because that mechanism IS the per-image strength field, a pin
+ without it cannot honor "inspire" at all; this raises there instead of falling
+ back to a bare `image=`, which would anchor the render the user asked NOT to be
+ anchored. "anchor" keeps its existing graceful degradation.
+
+ Returns {} when there's no source image. With no strength override and an
+ anchored reference we pass a bare `image=` on every pin — unchanged behavior.
+ With a strength override (or any loose reference, which always resolves one):
- v0.14.x carries per-image strength as a first-class field on
ImageConditioningInput passed through `images=[...]` (passing
@@ -957,21 +999,29 @@ def _image_conditioning_kwargs(generate_and_save, image: str | None,
"""
if not image:
return {}
- if image_strength is None:
+ loose = reference_mode == "inspire"
+ if image_strength is None and not loose:
return {"image": image}
- if image_strength < 0.0 or image_strength > 1.0:
+ if image_strength is not None and (image_strength < 0.0 or image_strength > 1.0):
raise SystemExit("--image-strength must be between 0.0 and 1.0")
+ strength = INSPIRE_DEFAULT_IMAGE_STRENGTH if image_strength is None else image_strength
ImageConditioningInput = _import_image_conditioning_input()
if ImageConditioningInput is not None and \
"images" in inspect.signature(generate_and_save).parameters:
- emit_status(f"Using image strength {image_strength:g}")
+ emit_status(f"Using {reference_mode} reference at image strength {strength:g}")
return {"images": [ImageConditioningInput(
- path=image, frame_idx=0, strength=image_strength,
+ path=image, frame_idx=0, strength=strength,
)]}
- if _apply_legacy_image_strength(image_strength):
- emit_status(f"Using image strength {image_strength:g}")
+ if loose:
+ raise SystemExit(
+ "--i2v-reference-mode inspire needs per-image conditioning strength "
+ "(ImageConditioningInput), which this ltx-2-mlx pin does not expose. "
+ "Re-run with --i2v-reference-mode anchor, or select an LTX-2.5 model."
+ )
+ if _apply_legacy_image_strength(strength):
+ emit_status(f"Using image strength {strength:g}")
else:
emit_status(
"--image-strength not supported at this ltx-2-mlx pin "
@@ -1059,7 +1109,8 @@ def run_two_stage(args: argparse.Namespace, image: str | None = None) -> str:
stage1_steps=args.steps if args.steps is not None else 30,
stage2_steps=args.stage2_steps,
cfg_scale=args.cfg_scale if args.cfg_scale is not None else 3.0,
- **_image_conditioning_kwargs(pipe.generate_and_save, image, args.image_strength),
+ **_image_conditioning_kwargs(pipe.generate_and_save, image, args.image_strength,
+ args.i2v_reference_mode),
**_rate_kwargs(pipe.generate_and_save, args.fps),
))
@@ -1098,7 +1149,7 @@ def run_image(args: argparse.Namespace) -> str:
emit_stage(1, 1, 1, "Loaded")
emit_status("Generating I2V…")
image_kwargs = _image_conditioning_kwargs(
- pipe.generate_and_save, args.image, args.image_strength
+ pipe.generate_and_save, args.image, args.image_strength, args.i2v_reference_mode
)
return _run_with_ltx_stepwise_preview(pipe, args, lambda: pipe.generate_and_save(
**_one_stage_kwargs(args, **image_kwargs),
@@ -1438,6 +1489,7 @@ def maybe_strip_audio(output_path: str) -> None:
def main() -> NoReturn:
args = parse_args()
validate_text_encoder_args(args)
+ validate_reference_mode_args(args)
# One-line runtime fingerprint at startup — captured by PortOS onto the
# render record so garbled output can be tied to a specific ltx/mlx stack.
emit_runtime_fingerprint("ltx2", ["ltx_pipelines_mlx", "ltx_core_mlx", "mlx", "mlx_metal"])
diff --git a/scripts/generate_ltx2.test.js b/scripts/generate_ltx2.test.js
index e9f926423c..8e1813375b 100644
--- a/scripts/generate_ltx2.test.js
+++ b/scripts/generate_ltx2.test.js
@@ -469,6 +469,97 @@ describe.skipIf(!pyBin)('generate_ltx2.py', () => {
expect(output.trim()).toBe(expected);
});
+ // The reference-mode promise (#4874). "inspire" is only expressible where the
+ // pin carries a per-image conditioning strength; everywhere else the helper has
+ // to FAIL, because falling back to a bare `image=` would anchor the very frame
+ // the user asked not to be anchored.
+ describe('i2v reference mode', () => {
+ // A fake generate_and_save whose signature decides which pin the helper sees:
+ // `images=` present is the v0.14.x API, absent is a pre-rename pin.
+ const condKwargs = ({ hasImagesParam, referenceMode, imageStrength }) => runPython(`${importRunner}\n${[
+ 'import sys, types',
+ hasImagesParam
+ ? 'def gen(prompt=None, images=None, image=None): pass'
+ : 'def gen(prompt=None, image=None): pass',
+ // Stand in for the ltx wheel: the helper only needs a constructor whose
+ // instances it can hand back, and repr is what we assert against.
+ 'class ICI:',
+ ' def __init__(self, path, frame_idx, strength):',
+ ' self.path, self.frame_idx, self.strength = path, frame_idx, strength',
+ ' def __repr__(self):',
+ ' return f"ICI({self.path},{self.frame_idx},{self.strength})"',
+ hasImagesParam
+ ? 'runner._import_image_conditioning_input = lambda: ICI'
+ : 'runner._import_image_conditioning_input = lambda: None',
+ // The legacy monkey-patch needs the real ltx modules; report "absent" so
+ // the anchored fallback path is exercised without them.
+ 'runner._apply_legacy_image_strength = lambda strength: False',
+ 'try:',
+ ` print(repr(runner._image_conditioning_kwargs(gen, "/tmp/ref.png", ${imageStrength === null ? 'None' : imageStrength}, "${referenceMode}")))`,
+ 'except SystemExit as exc:',
+ ' print("SystemExit:", str(exc))',
+ ].join('\n')}`);
+
+ it('leaves an unset anchored reference exactly as it was before the flag existed', () => {
+ const out = condKwargs({ hasImagesParam: true, referenceMode: 'anchor', imageStrength: null });
+ expect(out.trim()).toBe("{'image': '/tmp/ref.png'}");
+ });
+
+ it('resolves the loose default when no strength was given', () => {
+ const out = condKwargs({ hasImagesParam: true, referenceMode: 'inspire', imageStrength: null });
+ expect(out).toMatch(/ICI\(\/tmp\/ref\.png,0,0\.35\)/);
+ });
+
+ it('honors an explicit strength under a loose reference', () => {
+ const out = condKwargs({ hasImagesParam: true, referenceMode: 'inspire', imageStrength: 0.8 });
+ expect(out).toMatch(/ICI\(\/tmp\/ref\.png,0,0\.8\)/);
+ });
+
+ it('FAILS rather than anchoring when the pin has no per-image strength', () => {
+ const out = condKwargs({ hasImagesParam: false, referenceMode: 'inspire', imageStrength: 0.5 });
+ expect(out).toMatch(/SystemExit:/);
+ expect(out).toMatch(/does not expose/i);
+ });
+
+ it('still degrades gracefully for an anchored reference on the same old pin', () => {
+ const out = condKwargs({ hasImagesParam: false, referenceMode: 'anchor', imageStrength: 0.5 });
+ expect(out.trim()).toContain("{'image': '/tmp/ref.png'}");
+ });
+
+ it.each(['text', 'fflf', 'extend', 'a2v', 'ic'])('rejects a loose reference in %s mode', (mode) => {
+ const out = runPython(`${importRunner}\n${[
+ 'from types import SimpleNamespace',
+ `args = SimpleNamespace(i2v_reference_mode="inspire", mode="${mode}")`,
+ 'try:',
+ ' runner.validate_reference_mode_args(args)',
+ 'except SystemExit as exc:',
+ ' print(str(exc))',
+ 'else:',
+ ' raise SystemExit("a loose reference was accepted outside image mode")',
+ ].join('\n')}`);
+ expect(out).toMatch(/applies to --mode image only/);
+ });
+
+ it('accepts a loose reference in image mode, and anchor anywhere', () => {
+ const out = runPython(`${importRunner}\n${[
+ 'from types import SimpleNamespace',
+ 'runner.validate_reference_mode_args(SimpleNamespace(i2v_reference_mode="inspire", mode="image"))',
+ 'runner.validate_reference_mode_args(SimpleNamespace(i2v_reference_mode="anchor", mode="a2v"))',
+ 'print("ok")',
+ ].join('\n')}`);
+ expect(out.trim()).toBe('ok');
+ });
+
+ it('defaults the flag to anchor and rejects an unknown value at the parser', () => {
+ const parsed = runPython(`${importRunner}\n${[
+ 'import sys',
+ 'sys.argv = ["generate_ltx2.py", "--mode", "image", "--prompt", "p", "--output", "/tmp/o.mp4", "--model", "m"]',
+ 'print(runner.parse_args().i2v_reference_mode)',
+ ].join('\n')}`);
+ expect(parsed.trim()).toBe('anchor');
+ });
+ });
+
it('parses the optional bounded preview directory', () => {
const output = runPython(`${importRunner}\n${[
'import sys',
diff --git a/server/lib/README.md b/server/lib/README.md
index c83a54f4c2..c42fa1da0b 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -130,6 +130,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `videoDisclosure.js` | Video Gen provenance/licensing + backend policy-scope facts (#3674). `VIDEO_MODEL_DISCLOSURES` maps each shipped video model id to `{ shippedRepo, disclosure }` (model card URL, weights license, runtime license, pinned-snapshot download size in decimal GB, review date) — every value checked against a primary upstream source, and any fact that could not be established is OMITTED so the UI renders "Unknown" instead of guessing. `applyVideoDisclosures(list)` is the load-time backfill (twin of migration 237) with the same preservation guards: an existing `disclosure` key wins, a custom id is skipped, and a `repo` pointed at a fork keeps Unknown. `VIDEO_BACKEND_DISCLOSURES` / `videoBackendDisclosure(id)` state where inference runs (`execution: local or hosted`) and whose policy applies — execution facts only, never a restrictiveness ranking. `APACHE_2` / `GEMMA_TERMS` are the shared license descriptors `videoTextEncoders.js` reuses, so a license-text correction reaches both tables from one edit. |
| `videoFinishProfiles.js` | Draft → delivery ("Finish") relationships between video models (#3696). `VIDEO_FINISH_PROFILES` declares each fast draft entry id → `{ shippedRepo, finishModelId }`, only for pairs that share a runtime, base repo and supported modes (the same weights at a different step budget), so re-rendering the draft's seed reproduces its composition instead of re-rolling it. `applyVideoFinishProfiles(list)` is the load-time backfill (twin of migration 238) with the usual preservation guards (existing key wins, custom id skipped, forked `repo` skipped); `validateFinishProfileGraph(list)` returns the graph problems (missing / self-referencing / chained target, runtime / repo / supportedModes mismatch) and `sanitizeFinishProfiles(list)` warns + strips them at load so a typo can never surface a Finish button targeting nothing. `finishTargetForModel(model, availableModels)` resolves the delivery entry scoped to what this install can run. |
| `videoModeProfiles.js` | The shipped `supportedModes` fact per video runtime (#3737), so "which modes does this model support?" has one answer on the registry entry instead of 25+ `runtime === '…'` comparisons. `VIDEO_RUNTIME_MODES` maps each runtime to the base semantic modes its helper's argv can actually render (`mlx_video`/`ltx2` text+image+fflf+extend, `wan22` text+image, `minimax_h3` / `minimax_h3_cuda` text+image+fflf off one shared array — also the mode ceiling in `videoGen/modeContract.js` — `hunyuan` text only, replacing the legacy unread `mode: 't2v'` field); `VIDEO_BASE_MODES` is the fallback for an unknown (user-added or peer-synced) runtime, deliberately the full base set so a custom model doesn't vanish from every picker. `resolveVideoSupportedModes(entry)` (declared non-empty list always wins) and `applyVideoSupportedModes(list)` — the read-time decoration `mediaModels.js#getVideoModels` applies, so the derived list never lands in `data/media-models.json` where it would read back as a *declared* list no later correction could reach. a2v and the IC-LoRA remix ids are NOT enumerated here: they're ltx2 pipeline capabilities, gated by runtime (`A2V_REQUIRES_LTX2` / `IC_LORA_REQUIRES_LTX2`). |
+| `videoReferenceModes.js` | The i2v reference-mode contract (#4874) — what a supplied conditioning image PROMISES. `I2V_REFERENCE_MODES` (`anchor` \| `inspire`) + `I2V_REFERENCE_MODE_OPTIONS` (the label + the promise sentence the UI prints), `I2V_REFERENCE_MODE_RUNTIMES` (only `ltx25` can honor `inspire` — it needs per-image conditioning strength), `INSPIRE_DEFAULT_IMAGE_STRENGTH`, plus `normalizeI2vReferenceMode` / `isDefaultI2vReferenceMode` / `isKnownI2vReferenceMode` / `runtimeSupportsI2vReferenceMode` / `i2vReferenceModeLabel` / `resolveI2vReferenceStrength` and the one rule `i2vReferenceModeViolation({ model, mode, referenceMode, hasFirstImage })` → `{ code, message }` or null. Pure (no `ServerError`) because it is MIRRORED to `client/src/lib/videoReferenceModes.js`; `videoGen/modeContract.js#videoReferenceModeError` wraps it for the route + render boundaries. |
| `videoTextEncoders.js` | Swappable prompt conditioners for local video runtimes. MiniMax H3 reads the *unnormalized* hidden state after Qwen3-VL language layer 49 (layers 50-63, the final norm and `lm_head` are never evaluated), so any checkpoint carrying the same embedding + layers 0-49 + vision tower is a drop-in conditioner — swapping it changes how the model reads a prompt without touching the diffusion weights. `TEXT_ENCODERS_BY_RUNTIME` declares the shipped options per runtime (pinned repo/revision plus an explicit `files` LIST — one repackaged safetensors, or just the shards of an upstream checkpoint that carry parameters the loader actually builds; in code rather than the media-models registry so a stale `data/media-models.json` can't name a file the runner can't map); `videoTextEncoderOptions(model)` returns the TRUE list stock-first (it deliberately does NOT collapse a one-entry runtime to `[]` — that is a presentation rule, and folding it in here would change what the server believes a model supports and empty the "offers …" list in the error; `TextEncoderPicker` owns the hide-when-there-is-no-real-choice check), `isStockTextEncoder(id)` makes absence and the `stock` sentinel the same request, `resolveVideoTextEncoder(model, id)` returns `null` for the stock choice or throws `VIDEO_TEXT_ENCODER_UNSUPPORTED` (with the non-throwing `supportsVideoTextEncoder` + `videoTextEncoderUnsupportedError` split out so the request path can reject before staging uploads), and `downloadableVideoTextEncoders()` (deduped by id — the table is keyed by RUNTIME, so one conditioner can be offered by two) / `downloadableVideoTextEncoder(id)` feed the `/api/video-gen/text-encoders/:id/(download\|repair)` lane. Two loader-mechanics fields exist because a ComfyUI-packaged conditioner is namespaced differently from the HF checkpoint the MLX port matches: `keyPrefixMap` (`model.` → `model.language_model.`, `visual.` → `model.visual.`) is applied to every checkpoint key by `scripts/generate_minimax_h3.py` BEFORE the pinned loader sees it — no fork of the pinned runtime — and `finalNormKey` names where the runner synthesizes a ones-filled `norm.weight` for a checkpoint published without one (correct upstream, since H3 reads the state *before* the norm, but the pinned loader refuses to load with any parameter missing). Both are absent for an UPSTREAM Qwen3-VL-32B checkpoint, which already uses the loader namespace and ships its own norm. A candidate must BE Qwen3-VL-32B (the shim reuses upstream's config/tokenizer/processor) — a different Qwen generation is not a substitute however close its conditioning width looks; see docs/features/video-text-encoders.md. `publicTextEncoderOption(entry)` is the client projection and deliberately drops both, so the UI can't reimplement the remap. The `ltx25` table (#4320) uses a third mechanic, `configOverrides`, because an LTX-2.5 pack's OWN Gemma 4 tower wins over `--gemma` inside the pinned fork: the substitution is a standalone shim directory whose generated `config.json` is the substitute's own with these keys merged over it (only ever the `model_type` label a unified checkpoint gets wrong — never `text_config`/`quantization`), and a candidate must BE Gemma 4 12B at 48 layers / hidden 3840 / vocab 262144 / `k_eq_v`. `verified` gates a substitute out of BOTH lanes (picker AND download) until it has been A/B-rendered against its runtime's stock conditioner — required on every non-built-in entry and fail-closed on absence, so a new entry is unreachable until someone states a verdict; both ltx25 substitutes are `verified: false` today. `declaredVideoTextEncoders()` is the UNFILTERED table for shape/invariant checks only — never the render or download path, and `videoTextEncoderRuntimes()` enumerates the table's runtime keys so parity/shape tests cover every runtime rather than the one that happened to exist when they were written. |
| `providerModels.js` | Provider model resolution sentinels + helpers (`CODEX_CONFIGURED_DEFAULT` / `ANTIGRAVITY_CONFIGURED_DEFAULT` / `GROK_CONFIGURED_DEFAULT` / `KIMI_CONFIGURED_DEFAULT`, `resolveCliModel`, `filterSelectableModels`, Bedrock/OpenCode model mappers, model-flag scan helpers incl. `stripBrokenModelFlags`, `isCodexProvider`, `isKimiProvider`, `isAntigravityProvider`, `isCursorProvider`) plus reasoning-effort helpers for the claude/codex/agy/cursor CLIs (`CLAUDE_EFFORT_LEVELS` / `CODEX_EFFORT_LEVELS` / `ANTIGRAVITY_EFFORT_LEVELS` / `CURSOR_EFFORT_LEVELS` / `EFFORT_LEVELS`, `effortLevelsForProvider`, `resolveCliEffort` — clamps an out-of-range effort to the nearest level the target CLI accepts rather than dropping it, so a value saved against a wider ladder survives a provider switch — `hasEffortFlag`, `buildEffortArgs` — the one emitter of `--effort <level>` / `-c model_reasoning_effort=<level>`, and deliberately silent for cursor — and `foldCursorEffortIntoModel`, which carries a cursor level inside `--model` as Cursor’s own variant syntax (`gpt-5[effort=max]`) because `cursor-agent` has no `--effort` flag) plus codex startup-arg helpers (`CODEX_EFFORT_KEY`, `CODEX_UPDATE_CHECK_KEY`, `hasCodexUpdateCheckConfig`, `buildCodexStartupArgs` — the one emitter of `-c check_for_update_on_startup=false`, spread by every codex spawn builder to disable the blocking startup update modal) plus `PORTOS_CLI_CONFIG_KEYS` / `isPortosSuppliedConfigKey` — the exhaustive list of `-c <key>=<value>` config keys PortOS injects, read by the `cli-config-invalid` error analyzer to tell a rejected PortOS override apart from a bad line in the user's own CLI config file. |
| `providerVendors.js` | `PROVIDER_VENDORS` — one row per coding-agent CLI/TUI vendor (claude/codex/antigravity/opencode/grok/kimi/cursor, plus a deliberately-incomplete legacy `gemini-cli` row), consumed by every dispatch site that used to hand-roll its own vendor if-chain across ~8 branches in 5 files (#3618): `applyCommandDefaults`/`prepareCliPrompt` (re-exported from `tuiHandshake.js`/`cliProviderArgs.js`), `buildVendorCliArgs`/`buildVendorSpawnConfig` (consumed by `cliProviderArgs.js#buildCliArgs` / `agentCliSpawning.js#buildCliSpawnConfig`), `inferTuiCommand` (re-exported from `tuiHandshake.js`), and `injectTuiModelAndEffort` — the shared antigravity-validates-the-pair-vs-everyone-else `--model`/`--effort` injection used by both `tuiHandshake.js#buildTuiInvocation` and `agentTuiSpawning.js#buildTuiSpawnConfig`, replacing a second copy of that split that had already drifted once before this file existed. Doesn't rewrite any vendor's argv-building logic — that stays in `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`/`codex.js`. Dependency-light on purpose, mirroring those files. |
diff --git a/server/lib/index.js b/server/lib/index.js
index a8d756b36d..e8e839b6a1 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -134,6 +134,7 @@ export * from './videoContinuity.js';
export * from './videoDisclosure.js';
export * from './videoFinishProfiles.js';
export * from './videoModeProfiles.js';
+export * from './videoReferenceModes.js';
export * from './videoTextEncoders.js';
export * from './promptPartials.js';
export * from './promptRunner.js';
diff --git a/server/lib/videoReferenceModes.js b/server/lib/videoReferenceModes.js
new file mode 100644
index 0000000000..e46190ec3c
--- /dev/null
+++ b/server/lib/videoReferenceModes.js
@@ -0,0 +1,158 @@
+/**
+ * i2v reference-mode contract (#4874) — what a supplied conditioning image
+ * PROMISES about the render.
+ *
+ * PortOS already had an "image strength" slider, but a bare scalar says nothing
+ * about the *semantic* the user is buying. Two very different promises hid
+ * behind the same dial:
+ *
+ * - `anchor` — the reference IS frame one. The clip animates outward from
+ * those exact pixels. This is the historical behavior and stays
+ * the default, so a render that predates this field is
+ * byte-identical to one that omits it.
+ * - `inspire` — the reference steers subject and style, and frame one is
+ * GENERATED. It will resemble the image without reproducing it.
+ *
+ * Only a runtime that can carry a per-image conditioning strength can honor
+ * `inspire`; on everything else the pipeline pins frame 0 unconditionally, so
+ * accepting the request would silently deliver `anchor` while the UI promised
+ * otherwise. That is the whole failure this table exists to prevent — every
+ * boundary rejects instead (`i2vReferenceModeViolation` below), and the LTX
+ * helper fails loudly rather than downgrading mid-render.
+ *
+ * PURE and MIRRORED to `client/src/lib/videoReferenceModes.js` (byte-for-byte;
+ * `videoReferenceModes.mirror.test.js` is the contract) — so it must not import
+ * `ServerError` or anything else server-side. Callers translate the returned
+ * `{ code, message }` into whatever their layer throws:
+ * `videoReferenceModeError()` in services/videoGen/modeContract.js does that
+ * for the route + render boundaries.
+ */
+
+// Ordered — the UI renders the picker in this order and `anchor` is first
+// because it is the default.
+export const I2V_REFERENCE_MODES = Object.freeze(['anchor', 'inspire']);
+
+export const DEFAULT_I2V_REFERENCE_MODE = 'anchor';
+
+// The promise each mode makes, in the words the UI shows the user. Kept beside
+// the rule table rather than in the component so the server's rejection message
+// and the panel's helper text can't describe two different contracts.
+export const I2V_REFERENCE_MODE_OPTIONS = Object.freeze([
+ Object.freeze({
+ value: 'anchor',
+ label: 'Anchor',
+ promise: 'The reference is frame one — the clip animates outward from those exact pixels.',
+ }),
+ Object.freeze({
+ value: 'inspire',
+ label: 'Inspire',
+ promise: 'The reference guides subject and style. Frame one is generated, so it resembles the image without reproducing it.',
+ }),
+]);
+
+// Runtimes that can honor each mode. `null` means "every runtime" — `anchor` is
+// what an i2v pipeline does by construction. `inspire` needs per-image
+// conditioning strength, which today only the LTX-2.5 pin exposes
+// (ImageConditioningInput on generate_and_save); the 2.3 pin shares the family
+// predicate but not that API, so it is NOT listed.
+export const I2V_REFERENCE_MODE_RUNTIMES = Object.freeze({
+ anchor: null,
+ inspire: Object.freeze(['ltx25']),
+});
+
+// Conditioning strength applied to a loose reference when the user leaves the
+// Image Strength slider untouched. Low enough that the first frame is visibly
+// re-generated rather than reproduced — which is exactly the promise `inspire`
+// makes. An explicit slider value always wins.
+export const INSPIRE_DEFAULT_IMAGE_STRENGTH = 0.35;
+
+/**
+ * `''` / `null` / `undefined` all mean "not set" and resolve to the default.
+ * Anything else is returned VERBATIM so an unknown value reaches the gate below
+ * and is rejected there — collapsing garbage into `anchor` would turn a typo
+ * into a silently different render (AGENTS: sentinel + validate, never let
+ * invalid share a value with valid).
+ */
+export const normalizeI2vReferenceMode = (value) => (
+ value == null || value === '' ? DEFAULT_I2V_REFERENCE_MODE : value
+);
+
+export const isDefaultI2vReferenceMode = (value) => (
+ normalizeI2vReferenceMode(value) === DEFAULT_I2V_REFERENCE_MODE
+);
+
+export const isKnownI2vReferenceMode = (value) => (
+ I2V_REFERENCE_MODES.includes(normalizeI2vReferenceMode(value))
+);
+
+/** Can `runtime` deliver what `value` promises? Unknown modes are never supported. */
+export const runtimeSupportsI2vReferenceMode = (runtime, value) => {
+ const mode = normalizeI2vReferenceMode(value);
+ if (!I2V_REFERENCE_MODES.includes(mode)) return false;
+ const allowed = I2V_REFERENCE_MODE_RUNTIMES[mode];
+ return allowed === null || allowed.includes(runtime);
+};
+
+export const i2vReferenceModeLabel = (value) => (
+ I2V_REFERENCE_MODE_OPTIONS.find((o) => o.value === normalizeI2vReferenceMode(value))?.label
+ || normalizeI2vReferenceMode(value)
+);
+
+/**
+ * The effective first-frame conditioning strength for a render, or `null` for
+ * "let the pipeline apply its own default".
+ *
+ * An explicit slider value is honored on BOTH modes — a user who wants a firmer
+ * loose reference (or a softer anchor) gets it. Only the *unset* case differs:
+ * `inspire` substitutes its own low default, because "no value" there still has
+ * to mean "don't reproduce frame one", while `anchor` keeps deferring to the
+ * pipeline exactly as it did before this field existed.
+ */
+export const resolveI2vReferenceStrength = (referenceMode, imageStrength) => {
+ if (imageStrength != null && imageStrength !== '') {
+ const explicit = Number(imageStrength);
+ if (Number.isFinite(explicit)) return explicit;
+ }
+ return normalizeI2vReferenceMode(referenceMode) === 'inspire'
+ ? INSPIRE_DEFAULT_IMAGE_STRENGTH
+ : null;
+};
+
+/**
+ * The one reference-mode rule, as a pure `{ code, message } | null`.
+ *
+ * `anchor` is always legal, so a request that never touched this field can
+ * never be rejected by it. Everything else has to clear three gates: the value
+ * is known, the render is actually image-to-video with a source image, and the
+ * model's runtime can honor the promise.
+ *
+ * @param {object} opts
+ * @param {object} [opts.model] - registry entry (`name`, `runtime`)
+ * @param {string} [opts.mode] - RESOLVED semantic mode ('image', 'text', 'fflf', …)
+ * @param {string} [opts.referenceMode]- requested reference mode
+ * @param {boolean} [opts.hasFirstImage] - a first-frame conditioning image is present
+ */
+export const i2vReferenceModeViolation = ({ model, mode, referenceMode, hasFirstImage = true } = {}) => {
+ const requested = normalizeI2vReferenceMode(referenceMode);
+ if (requested === DEFAULT_I2V_REFERENCE_MODE) return null;
+ if (!I2V_REFERENCE_MODES.includes(requested)) {
+ return {
+ code: 'I2V_REFERENCE_MODE_UNKNOWN',
+ message: `Unknown reference mode "${requested}" — expected one of ${I2V_REFERENCE_MODES.join(', ')}.`,
+ };
+ }
+ const label = i2vReferenceModeLabel(requested);
+ if (mode !== 'image' || !hasFirstImage) {
+ return {
+ code: 'I2V_REFERENCE_MODE_REQUIRES_IMAGE',
+ message: `${label} reference mode applies to image-to-video only — switch to image mode with a source image, or use ${i2vReferenceModeLabel(DEFAULT_I2V_REFERENCE_MODE)}.`,
+ };
+ }
+ if (!runtimeSupportsI2vReferenceMode(model?.runtime, requested)) {
+ return {
+ code: 'I2V_REFERENCE_MODE_UNSUPPORTED',
+ message: `${model?.name || 'This model'} cannot honor the ${label} reference mode — its runtime ("${model?.runtime || 'mlx_video'}") pins the reference as frame one. Choose an LTX-2.5 model, or switch to ${i2vReferenceModeLabel(DEFAULT_I2V_REFERENCE_MODE)}.`,
+ };
+ }
+ return null;
+};
diff --git a/server/lib/videoReferenceModes.mirror.test.js b/server/lib/videoReferenceModes.mirror.test.js
new file mode 100644
index 0000000000..a5aaa04a1f
--- /dev/null
+++ b/server/lib/videoReferenceModes.mirror.test.js
@@ -0,0 +1,63 @@
+/**
+ * Mirror parity test for server/lib/videoReferenceModes.js ↔
+ * client/src/lib/videoReferenceModes.js
+ *
+ * The server decides whether a reference mode is honorable; the client only
+ * previews that decision (which options to offer, what promise to print, what
+ * conditioning strength will actually apply). A drifted client offers Inspire
+ * on a runtime that pins frame one — the exact silent downgrade this contract
+ * exists to prevent.
+ *
+ * Comparison strips comments, so the intentionally divergent header commentary
+ * does not fail the test — only logic does.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'fs';
+import { resolve, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { compareDeclaration } from './mirrorParity.js';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+
+const SERVER_PATH = resolve(__dirname, 'videoReferenceModes.js');
+const CLIENT_PATH = resolve(__dirname, '../../client/src/lib/videoReferenceModes.js');
+
+const MIRRORED_NAMES = [
+ 'I2V_REFERENCE_MODES',
+ 'DEFAULT_I2V_REFERENCE_MODE',
+ 'I2V_REFERENCE_MODE_OPTIONS',
+ 'I2V_REFERENCE_MODE_RUNTIMES',
+ 'INSPIRE_DEFAULT_IMAGE_STRENGTH',
+ 'normalizeI2vReferenceMode',
+ 'isDefaultI2vReferenceMode',
+ 'isKnownI2vReferenceMode',
+ 'runtimeSupportsI2vReferenceMode',
+ 'i2vReferenceModeLabel',
+ 'resolveI2vReferenceStrength',
+ 'i2vReferenceModeViolation',
+];
+
+describe('videoReferenceModes server↔client mirror parity', () => {
+ const serverSrc = readFileSync(SERVER_PATH, 'utf8');
+ const clientSrc = readFileSync(CLIENT_PATH, 'utf8');
+
+ it('both files are non-empty', () => {
+ expect(serverSrc.length).toBeGreaterThan(100);
+ expect(clientSrc.length).toBeGreaterThan(100);
+ });
+
+ for (const name of MIRRORED_NAMES) {
+ it(`${name} is present and identical on both sides (code only)`, () => {
+ const { serverDecl, clientDecl, serverNorm, clientNorm } =
+ compareDeclaration(serverSrc, clientSrc, name);
+
+ expect(serverDecl, `server/lib/videoReferenceModes.js is missing: ${name}`).not.toBeNull();
+ expect(clientDecl, `client/src/lib/videoReferenceModes.js is missing: ${name}`).not.toBeNull();
+ expect(
+ clientNorm,
+ `"${name}" diverged — the server copy is authoritative; port the change verbatim`,
+ ).toBe(serverNorm);
+ });
+ }
+});
diff --git a/server/lib/videoReferenceModes.test.js b/server/lib/videoReferenceModes.test.js
new file mode 100644
index 0000000000..9c286be0c6
--- /dev/null
+++ b/server/lib/videoReferenceModes.test.js
@@ -0,0 +1,133 @@
+/**
+ * The i2v reference-mode contract (#4874).
+ *
+ * These assert the RULE, not the plumbing: which promises are legal, which
+ * runtime can keep them, and what strength actually applies. Every boundary
+ * (route, retry, render, client picker) resolves through this one table, so a
+ * hole here is a hole everywhere.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ I2V_REFERENCE_MODES,
+ DEFAULT_I2V_REFERENCE_MODE,
+ INSPIRE_DEFAULT_IMAGE_STRENGTH,
+ normalizeI2vReferenceMode,
+ isDefaultI2vReferenceMode,
+ isKnownI2vReferenceMode,
+ runtimeSupportsI2vReferenceMode,
+ i2vReferenceModeLabel,
+ resolveI2vReferenceStrength,
+ i2vReferenceModeViolation,
+} from './videoReferenceModes.js';
+
+const ltx25 = { name: 'LTX-2.5', runtime: 'ltx25' };
+const ltx2 = { name: 'LTX-2.3', runtime: 'ltx2' };
+const wan = { name: 'Wan 2.2', runtime: 'wan22' };
+
+describe('normalizeI2vReferenceMode', () => {
+ it('treats null/undefined/empty as unset → the default', () => {
+ expect(normalizeI2vReferenceMode(null)).toBe(DEFAULT_I2V_REFERENCE_MODE);
+ expect(normalizeI2vReferenceMode(undefined)).toBe(DEFAULT_I2V_REFERENCE_MODE);
+ expect(normalizeI2vReferenceMode('')).toBe(DEFAULT_I2V_REFERENCE_MODE);
+ });
+ it('returns an unknown value VERBATIM so the gate can reject it', () => {
+ // Collapsing garbage into 'anchor' would turn a typo into a silently
+ // different render — the whole point of the sentinel-vs-invalid split.
+ expect(normalizeI2vReferenceMode('inspiration')).toBe('inspiration');
+ expect(isKnownI2vReferenceMode('inspiration')).toBe(false);
+ });
+ it('recognizes every shipped mode', () => {
+ for (const m of I2V_REFERENCE_MODES) expect(isKnownI2vReferenceMode(m)).toBe(true);
+ });
+ it('isDefaultI2vReferenceMode is true only for anchor/unset', () => {
+ expect(isDefaultI2vReferenceMode('')).toBe(true);
+ expect(isDefaultI2vReferenceMode('anchor')).toBe(true);
+ expect(isDefaultI2vReferenceMode('inspire')).toBe(false);
+ });
+});
+
+describe('runtimeSupportsI2vReferenceMode', () => {
+ it('anchors on every runtime, including an unknown one', () => {
+ for (const runtime of ['ltx25', 'ltx2', 'wan22', 'mlx_video', 'minimax_h3', undefined]) {
+ expect(runtimeSupportsI2vReferenceMode(runtime, 'anchor')).toBe(true);
+ }
+ });
+ it('inspires ONLY on ltx25 — the 2.3 pin shares the family but not the API', () => {
+ expect(runtimeSupportsI2vReferenceMode('ltx25', 'inspire')).toBe(true);
+ expect(runtimeSupportsI2vReferenceMode('ltx2', 'inspire')).toBe(false);
+ expect(runtimeSupportsI2vReferenceMode('wan22', 'inspire')).toBe(false);
+ expect(runtimeSupportsI2vReferenceMode(undefined, 'inspire')).toBe(false);
+ });
+ it('never supports an unknown mode', () => {
+ expect(runtimeSupportsI2vReferenceMode('ltx25', 'inspiration')).toBe(false);
+ });
+});
+
+describe('resolveI2vReferenceStrength', () => {
+ it('defers to the pipeline for an unset anchored reference', () => {
+ expect(resolveI2vReferenceStrength('anchor', '')).toBeNull();
+ expect(resolveI2vReferenceStrength(null, null)).toBeNull();
+ });
+ it('substitutes the loose default for an unset inspired reference', () => {
+ expect(resolveI2vReferenceStrength('inspire', '')).toBe(INSPIRE_DEFAULT_IMAGE_STRENGTH);
+ expect(resolveI2vReferenceStrength('inspire', null)).toBe(INSPIRE_DEFAULT_IMAGE_STRENGTH);
+ });
+ it('honors an explicit strength on BOTH modes', () => {
+ expect(resolveI2vReferenceStrength('inspire', '0.8')).toBe(0.8);
+ expect(resolveI2vReferenceStrength('anchor', 0.6)).toBe(0.6);
+ });
+ it('keeps an explicit 0 rather than treating it as unset', () => {
+ expect(resolveI2vReferenceStrength('anchor', 0)).toBe(0);
+ expect(resolveI2vReferenceStrength('inspire', '0')).toBe(0);
+ });
+ it('falls back rather than emitting NaN for a non-numeric strength', () => {
+ expect(resolveI2vReferenceStrength('anchor', 'loose')).toBeNull();
+ expect(resolveI2vReferenceStrength('inspire', 'loose')).toBe(INSPIRE_DEFAULT_IMAGE_STRENGTH);
+ });
+});
+
+describe('i2vReferenceModeViolation', () => {
+ it('never rejects a request that left the field alone', () => {
+ for (const referenceMode of [undefined, null, '', 'anchor']) {
+ expect(i2vReferenceModeViolation({
+ model: wan, mode: 'text', referenceMode, hasFirstImage: false,
+ })).toBeNull();
+ }
+ });
+ it('accepts inspire on ltx25 image-to-video', () => {
+ expect(i2vReferenceModeViolation({
+ model: ltx25, mode: 'image', referenceMode: 'inspire', hasFirstImage: true,
+ })).toBeNull();
+ });
+ it('rejects an unknown mode', () => {
+ expect(i2vReferenceModeViolation({
+ model: ltx25, mode: 'image', referenceMode: 'inspiration', hasFirstImage: true,
+ })).toMatchObject({ code: 'I2V_REFERENCE_MODE_UNKNOWN' });
+ });
+ it('rejects inspire outside image mode', () => {
+ for (const mode of ['text', 'fflf', 'extend', 'a2v', 'ic-control']) {
+ expect(i2vReferenceModeViolation({
+ model: ltx25, mode, referenceMode: 'inspire', hasFirstImage: true,
+ })).toMatchObject({ code: 'I2V_REFERENCE_MODE_REQUIRES_IMAGE' });
+ }
+ });
+ it('rejects inspire when the image never resolved', () => {
+ expect(i2vReferenceModeViolation({
+ model: ltx25, mode: 'image', referenceMode: 'inspire', hasFirstImage: false,
+ })).toMatchObject({ code: 'I2V_REFERENCE_MODE_REQUIRES_IMAGE' });
+ });
+ it('rejects inspire on a runtime that pins frame one', () => {
+ for (const model of [ltx2, wan, { name: 'Legacy', runtime: undefined }]) {
+ const v = i2vReferenceModeViolation({
+ model, mode: 'image', referenceMode: 'inspire', hasFirstImage: true,
+ });
+ expect(v).toMatchObject({ code: 'I2V_REFERENCE_MODE_UNSUPPORTED' });
+ // The message has to name the way out, not just the refusal.
+ expect(v.message).toContain('LTX-2.5');
+ }
+ });
+ it('names the mode in user-facing words', () => {
+ expect(i2vReferenceModeLabel('inspire')).toBe('Inspire');
+ expect(i2vReferenceModeLabel('')).toBe('Anchor');
+ });
+});
diff --git a/server/routes/mediaJobs.js b/server/routes/mediaJobs.js
index b3a97f933f..037a3ccd8b 100644
--- a/server/routes/mediaJobs.js
+++ b/server/routes/mediaJobs.js
@@ -16,6 +16,7 @@ import { CODEX_EFFORT_LEVELS } from '../lib/providerModels.js';
import { sanitizeJob } from '../services/mediaJobQueue/sanitizeJob.js';
import { isRemoteMediaJob } from '../services/mediaJobQueue/remoteMediaJob.js';
import { validateVideoRetryParams } from '../services/videoGen/prepareParams.js';
+import { I2V_REFERENCE_MODES } from '../lib/videoReferenceModes.js';
const router = Router();
@@ -216,6 +217,10 @@ const RETRY_OVERRIDE_SCHEMA = z.object({
tiling: z.enum(['auto', 'none', 'spatial', 'temporal']).optional(),
disableAudio: z.boolean().optional(),
imageStrength: z.number().min(0).max(1).nullable().optional(),
+ // What the conditioning image promises (#4874). `null` clears it back to the
+ // default, like the numeric knobs above — the schema STRIPS unknown keys, so
+ // an override missing from here is silently dropped rather than rejected.
+ i2vReferenceMode: z.enum(I2V_REFERENCE_MODES).nullable().optional(),
textEncoderId: z.string().max(64).optional().transform(emptyToUndef),
chunks: z.number().int().min(1).max(8).optional(),
chunkPrompts: z.array(z.string().max(8000)).max(8).optional(),
@@ -283,7 +288,7 @@ router.post('/:id/retry', asyncHandler(async (req, res) => {
const bounds = VIDEO_RETRY_BOUNDS_SCHEMA.safeParse(rawOverrides);
if (!bounds.success) throw new ServerError('Video retry settings are outside the supported range', { status: 400, code: 'VALIDATION_ERROR' });
}
- for (const key of ['seed', 'steps', 'guidanceScale', 'imageStrength']) {
+ for (const key of ['seed', 'steps', 'guidanceScale', 'imageStrength', 'i2vReferenceMode']) {
if (rawOverrides[key] === null) delete params[key];
}
if (rawOverrides.chunks === 1) delete params.chunkPrompts;
diff --git a/server/routes/mediaJobs.test.js b/server/routes/mediaJobs.test.js
index 0c9018a8cb..0994b363f1 100644
--- a/server/routes/mediaJobs.test.js
+++ b/server/routes/mediaJobs.test.js
@@ -452,3 +452,56 @@ describe('mediaJobs routes', () => {
expect(r.body.code).toBe('NOT_FOUND');
});
});
+
+// The conditioning promise (#4874) rides a retry the same way the strength
+// does. RETRY_OVERRIDE_SCHEMA STRIPS unknown keys, so a missing entry there
+// would silently re-render an anchored clip under the original job's Inspire
+// label instead of failing loudly — which is why this is asserted, not assumed.
+describe('POST /:id/retry — i2v reference mode overrides (#4874)', () => {
+ const seed = (i2vReferenceMode) => {
+ jobStore.set('j-ref-mode', {
+ id: 'j-ref-mode', kind: 'video', owner: null, status: 'failed',
+ params: {
+ prompt: 'a fox', modelId: 'ltx25_mlx_q8', mode: 'image',
+ sourceImagePath: '/mock/uploads/frame.png',
+ ...(i2vReferenceMode ? { i2vReferenceMode } : {}),
+ },
+ });
+ };
+
+ beforeEach(() => {
+ jobStore.clear();
+ vi.clearAllMocks();
+ });
+
+ it('carries an inspire override into the retried params', async () => {
+ seed(null);
+ const r = await request(makeApp()).post('/api/media-jobs/j-ref-mode/retry')
+ .send({ params: { i2vReferenceMode: 'inspire' } });
+ expect(r.status).toBe(200);
+ expect(stubs.enqueueJob.mock.calls[0][0].params.i2vReferenceMode).toBe('inspire');
+ });
+
+ it('drops the key entirely on a null clear rather than persisting a default', async () => {
+ seed('inspire');
+ const r = await request(makeApp()).post('/api/media-jobs/j-ref-mode/retry')
+ .send({ params: { i2vReferenceMode: null } });
+ expect(r.status).toBe(200);
+ expect(stubs.enqueueJob.mock.calls[0][0].params).not.toHaveProperty('i2vReferenceMode');
+ });
+
+ it('inherits the original promise when the retry overrides nothing', async () => {
+ seed('inspire');
+ const r = await request(makeApp()).post('/api/media-jobs/j-ref-mode/retry').send({});
+ expect(r.status).toBe(200);
+ expect(stubs.enqueueJob.mock.calls[0][0].params.i2vReferenceMode).toBe('inspire');
+ });
+
+ it('rejects an unknown reference mode instead of stripping it', async () => {
+ seed(null);
+ const r = await request(makeApp()).post('/api/media-jobs/j-ref-mode/retry')
+ .send({ params: { i2vReferenceMode: 'inspiration' } });
+ expect(r.status).toBe(400);
+ expect(stubs.enqueueJob).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index e13c3cafcc..c7ee0e1758 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -18,6 +18,7 @@ import {
} from '../lib/validation.js';
import { grokVideoDurationSchema } from '../lib/sharedSchemas.js';
import { MIN_CONTEXT_FRAMES, MAX_CONTEXT_FRAMES } from '../lib/videoContinuity.js';
+import { I2V_REFERENCE_MODES, isDefaultI2vReferenceMode } from '../lib/videoReferenceModes.js';
import {
VIDEO_BACKEND_DISCLOSURES, acceptedVideoModelTerms,
videoModelTermsGateId,
@@ -170,6 +171,16 @@ export const LOCAL_ONLY_VIDEO_PARAMS = Object.freeze({
guidanceScale: optionalNum(0, 30, 'guidanceScale'),
seed: optionalNum(0, Number.MAX_SAFE_INTEGER, 'seed'),
imageStrength: optionalNum(0, 1, 'imageStrength'),
+ // What the conditioning image PROMISES (#4874) — 'anchor' (default) pins it as
+ // frame one, 'inspire' conditions loosely for subject/style. Local-only by
+ // construction: grok's image_to_video always anchors, so a request that names a
+ // mode is not grok-deliverable and must stay on the local lane rather than be
+ // rerouted into a render that silently ignores it. Preprocessed like the numeric
+ // knobs because a multipart body sends an unset select as ''.
+ i2vReferenceMode: z.preprocess(
+ (v) => (v == null || v === '' ? undefined : v),
+ z.enum(I2V_REFERENCE_MODES).optional(),
+ ),
tiling: z.enum(['auto', 'none', 'spatial', 'temporal']).optional(),
// Which prompt conditioner reads the prompt (lib/videoTextEncoders.js).
// Validated loosely here and resolved against the MODEL's own option list in
@@ -1036,6 +1047,14 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
['LoRA weights', body.loraFilenames?.length],
['chained chunks', body.chunks > 1],
['the Grok backend', body.backend === 'grok'],
+ // A loose reference (#4874) is a per-runtime CAPABILITY, and this side
+ // cannot see which runtime the peer will pick — nor can an older peer even
+ // parse the field, which its wire schema would strip on the way in. Sending
+ // it would hand back an anchored clip under an Inspire label, which is the
+ // one outcome the contract exists to make impossible. Refuse instead: the
+ // user renders locally, or switches to Anchor and gets exactly what a peer
+ // can actually deliver.
+ ['a loose reference mode', !isDefaultI2vReferenceMode(body.i2vReferenceMode)],
// A director-board render is image-to-video by construction (its scene
// reference frame conditions the shot), and its project/scene ids are
// validated inside prepareVideoGenParams, which this branch bypasses.
@@ -1187,6 +1206,11 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
extendFromVideoPath,
mode,
imageStrength: body.imageStrength,
+ // Persisted only when it is NOT the default, exactly like textEncoderId above:
+ // storing an explicit 'anchor' would make a resumed/remixed render carry a knob
+ // that changed nothing, and would differ from what the service records in
+ // history for the same render.
+ ...(isDefaultI2vReferenceMode(body.i2vReferenceMode) ? {} : { i2vReferenceMode: body.i2vReferenceMode }),
chunks: effectiveChunks,
// Undefined when the request doesn't chain (or every beat was blank) — the
// key is simply absent from job.params then, so a resumed form restores no
@@ -1231,6 +1255,9 @@ const ACTIVE_JOB_PARAM_FIELDS = [
'width', 'height', 'numFrames', 'fps',
'steps', 'guidanceScale', 'seed',
'tiling', 'disableAudio', 'mode', 'chunks', 'chunkPrompts', 'contextFrames', 'imageStrength',
+ // Plain enum, no path — safe to echo so a reloading page restores the promise the
+ // in-flight render is actually keeping.
+ 'i2vReferenceMode',
// A registry id, not a path — safe to echo so a reloading page restores the
// conditioner the in-flight render is actually using.
'textEncoderId',
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index 500d6f9179..b8bb1a182b 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -710,6 +710,11 @@ describe('videoGen routes', () => {
'guidanceScale',
'seed',
'imageStrength',
+ // Not in the it.each table above: a non-default value is only legal on
+ // an image-mode request with a source image, so the generic
+ // prompt-only round-trip would 400 rather than assert anything. Its
+ // own case is below.
+ 'i2vReferenceMode',
'tiling',
// Not in the it.each table above: the route deliberately DROPS the
// stock value from persisted params, so the generic round-trip
@@ -740,6 +745,21 @@ describe('videoGen routes', () => {
expect(call[0].params.textEncoderId).toBeUndefined();
});
+ // grok's image_to_video always anchors, so naming a reference mode must keep
+ // the render local — including the default, which the route then drops from
+ // persisted params so an anchored render's job params stay byte-identical to
+ // a request that never sent the field. Both halves matter: keeping it local
+ // without dropping it would persist a knob that never applied.
+ it('keeps i2vReferenceMode on the local path under a grok pin, without persisting the default', async () => {
+ const { getSettings } = await import('../services/settings.js');
+ getSettings.mockResolvedValueOnce({ imageGen: grokReady, videoGen: { mode: 'grok' } });
+ const r = await request(app).post('/api/video-gen/').send({ prompt: 'a fox', i2vReferenceMode: 'anchor' });
+ expect(r.status).toBe(200);
+ const [call] = mediaJobQueue.enqueueJob.mock.calls;
+ expect(call[0].params.mode).not.toBe('grok');
+ expect(call[0].params.i2vReferenceMode).toBeUndefined();
+ });
+
it('a grok pin degrades to local when the request carries local-only machinery', async () => {
const { getSettings } = await import('../services/settings.js');
getSettings.mockResolvedValueOnce({
@@ -2403,6 +2423,43 @@ describe('videoGen routes', () => {
expect(prepareRemoteMediaJob).not.toHaveBeenCalled();
});
+ // A loose reference (#4874) is a per-runtime capability this side cannot
+ // verify on the peer — and an older peer's wire schema strips the field
+ // outright. Shipping it would return an anchored clip under an Inspire
+ // label, so the request is refused rather than silently downgraded.
+ it('refuses a federated render that asks for a loose reference mode', async () => {
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'a slow pan across a harbour',
+ modelId: 'ltx2',
+ mode: 'image',
+ sourceImageFile: 'frame.png',
+ i2vReferenceMode: 'inspire',
+ mediaProviderPeerId: federatedPeerId,
+ });
+
+ expect(r.status).toBe(400);
+ expect(r.body.code).toBe('MEDIA_PROVIDER_INPUT_UNSUPPORTED');
+ expect(r.body.error).toMatch(/loose reference mode/);
+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
+ expect(prepareRemoteMediaJob).not.toHaveBeenCalled();
+ });
+
+ // The default is not a capability claim, so it must NOT block a federated
+ // render — an over-broad guard here would refuse every ordinary i2v submit.
+ it('still routes a federated i2v render that leaves the reference mode at the default', async () => {
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'a slow pan across a harbour',
+ modelId: 'ltx2',
+ mode: 'image',
+ sourceImageFile: 'frame.png',
+ i2vReferenceMode: 'anchor',
+ mediaProviderPeerId: federatedPeerId,
+ });
+
+ expect(r.status).toBe(200);
+ expect(prepareRemoteMediaJob).toHaveBeenCalled();
+ });
+
it('refuses a federated chained render rather than shipping one unchained clip', async () => {
const r = await request(app).post('/api/video-gen/').send({
prompt: 'a slow pan across a harbour',
diff --git a/server/services/mediaJobQueue/sanitizeJob.js b/server/services/mediaJobQueue/sanitizeJob.js
index 191a05eade..d0bdd7f20c 100644
--- a/server/services/mediaJobQueue/sanitizeJob.js
+++ b/server/services/mediaJobQueue/sanitizeJob.js
@@ -7,6 +7,7 @@ const PARAM_ALLOWLIST = new Set([
'prompt', 'negativePrompt', 'modelId', 'model', 'effort',
'width', 'height', 'numFrames', 'fps', 'steps', 'guidanceScale',
'seed', 'tiling', 'disableAudio', 'mode', 'imageStrength',
+ 'i2vReferenceMode',
'textEncoderId', 'chunks', 'chunkPrompts', 'contextFrames', 'loras',
'cfgScale', 'guidance', 'quantize',
'runId', 'runtime', 'datasetId', 'characterId', 'characterName',
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index 28d2ce05a5..74d541b113 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -24,6 +24,10 @@ import { createLineReader } from '../../lib/streamLines.js';
import { claimHeavyLocalJob } from '../../lib/heavyJobClaim.js';
import { prepareLocalMemory, gpuBlockersMessage } from '../../lib/localMemory.js';
import { ServerError } from '../../lib/errorHandler.js';
+import {
+ isDefaultI2vReferenceMode, normalizeI2vReferenceMode, resolveI2vReferenceStrength,
+} from '../../lib/videoReferenceModes.js';
+import { videoReferenceModeError } from './modeContract.js';
import { videoLoraLayoutIssue } from '../../lib/safetensors.js';
import { videoGenEvents } from './events.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';
@@ -492,7 +496,7 @@ export const ltx25TextEncoderArgs = (textEncoder) => {
return args;
};
-const buildLtx2Args = ({ model, ltxModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, disableAudio, outputPath, previewDir, textEncoderRepo, textEncoder, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 }) => {
+const buildLtx2Args = ({ model, ltxModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, i2vReferenceMode, disableAudio, outputPath, previewDir, textEncoderRepo, textEncoder, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 }) => {
assertByovRuntimeInstalled(model.runtime);
// Map PortOS UI modes to the helper's subcommand. Native extend on ltx2
// routes to ExtendPipeline.extend_from_video — conditions on the entire
@@ -622,6 +626,14 @@ const buildLtx2Args = ({ model, ltxModelPath, prompt, negativePrompt, width, hei
if (stage2Steps != null) args.push('--stage2-steps', String(stage2Steps));
if (negativePrompt) args.push('--negative-prompt', negativePrompt);
if (imageStrength != null) args.push('--image-strength', String(imageStrength));
+ // The reference-mode promise (#4874). Emitted only when it is NOT the default so
+ // an anchored render's argv stays byte-identical to what it was before the flag
+ // existed. buildArgs already rejected a mode this model cannot honor; the helper
+ // re-checks against the LIVE pipeline API and fails rather than anchoring
+ // silently, which is the failure the flag exists to make impossible.
+ if (!isDefaultI2vReferenceMode(i2vReferenceMode)) {
+ args.push('--i2v-reference-mode', normalizeI2vReferenceMode(i2vReferenceMode));
+ }
if (disableAudio) args.push('--no-audio');
if (helperMode === 'image' && sourceImagePath) args.push('--image', sourceImagePath);
if (helperMode === 'fflf') {
@@ -924,12 +936,25 @@ const buildHunyuanArgs = ({ model, prompt, negativePrompt, width, height, numFra
return { bin: HUNYUAN_VENV_PYTHON, args };
};
-const buildArgs = ({ pythonPath, modelId, model, wanModelPath, wanRequiredWeights, ltxModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, textEncoderRepo, textEncoder, outputPath, previewDir, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 }) => {
+const buildArgs = ({ pythonPath, modelId, model, wanModelPath, wanRequiredWeights, ltxModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, i2vReferenceMode, textEncoderRepo, textEncoder, outputPath, previewDir, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 }) => {
+ // Reference-mode promise (#4874) — checked HERE rather than inside
+ // buildLtx2Args because every runtime reaches this function and only one can
+ // honor a loose reference. A wan22/mlx_video/H3 render that fell through to its
+ // own branch would pin frame one while the request asked for guidance, which is
+ // exactly the silent downgrade the contract forbids. The route rejects this too;
+ // internal producers, persisted-queue replays and retries all land here instead.
+ const referenceModeError = videoReferenceModeError({
+ model,
+ mode: mode || (sourceImagePath ? 'image' : 'text'),
+ referenceMode: i2vReferenceMode,
+ hasFirstImage: Boolean(sourceImagePath),
+ });
+ if (referenceModeError) throw referenceModeError;
// Route to the dgrauet/ltx-2-mlx helper when the model declares the new
// runtime. Existing notapalindrome models default to runtime: 'mlx_video'
// (or undefined in legacy registries — see backfillRuntime in mediaModels.js).
if (isLtx2FamilyRuntime(model.runtime)) {
- return buildLtx2Args({ model, ltxModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, disableAudio, outputPath, previewDir, textEncoderRepo, textEncoder, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 });
+ return buildLtx2Args({ model, ltxModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, i2vReferenceMode, disableAudio, outputPath, previewDir, textEncoderRepo, textEncoder, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 });
}
// IC-LoRA remix modes are an LTX-2 primitive (ICLoraPipeline) — no other
// runtime has an equivalent. The route guards this too, but a non-route
@@ -1081,7 +1106,7 @@ const resolveVideoDimensions = (model, width, height) => ({
height: height ?? configuredVideoDimension(model?.defaultHeight, 512),
});
-export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId = defaultVideoModelId(), width = null, height = null, numFrames = null, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, uploadedTempPaths = [], lastImagePath = null, keyframes = null, extendFromVideoPath = null, audioFilePath = null, audioStartSec = null, mode = null, imageStrength = null, loras = null, icReferencePaths = null, icStrength = null, icAttentionStrength = null, icSkipStage2 = false, textEncoderId = null, hidden = false, jobId: providedJobId = null }) {
+export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId = defaultVideoModelId(), width = null, height = null, numFrames = null, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, uploadedTempPaths = [], lastImagePath = null, keyframes = null, extendFromVideoPath = null, audioFilePath = null, audioStartSec = null, mode = null, imageStrength = null, i2vReferenceMode = null, loras = null, icReferencePaths = null, icStrength = null, icAttentionStrength = null, icSkipStage2 = false, textEncoderId = null, hidden = false, jobId: providedJobId = null }) {
uploadedTempPaths = Array.isArray(uploadedTempPaths) ? uploadedTempPaths : [];
if (!prompt?.trim()) throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
// Single-flight is now enforced by the mediaJobQueue worker upstream — only
@@ -1319,8 +1344,13 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
actualStage2Steps = t2vTwoStage.stage2Steps;
console.log(`🎬 PORTOS_T2V_TWO_STAGE on — T2V Standard via fast two-stage (${actualSteps}/${actualStage2Steps} steps, cfg ${actualGuidance}) [${jobId.slice(0, 8)}]`);
}
- // Caller may pass null/'' to use mlx_video's default (1.0 = preserve source).
- const actualImageStrength = imageStrength != null && imageStrength !== '' ? Number(imageStrength) : null;
+ // Caller may pass null/'' to use the runtime's own default (1.0 = preserve
+ // source). An unset strength under the "inspire" promise is the one exception:
+ // "no value" there still has to mean "do not reproduce frame one", so the
+ // contract substitutes its low default rather than deferring to a pipeline that
+ // would anchor. An explicit slider value always wins on both modes.
+ const effectiveReferenceMode = normalizeI2vReferenceMode(i2vReferenceMode);
+ const actualImageStrength = resolveI2vReferenceStrength(effectiveReferenceMode, imageStrength);
// IC-LoRA dials. `icStrength` weights the reference-video conditioning
// channel (default 1.0 matches the pipeline); `icAttentionStrength` stays
// null when unset so the pipeline applies its own default rather than us
@@ -1536,6 +1566,13 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// from `keyframes` even when caller omitted `mode`, so without this the
// history entry would say 'text' for a multi-keyframe render.
mode: mode || (hasMultiKeyframes ? 'fflf' : sourceImagePath ? 'image' : 'text'),
+ // What the conditioning image promised, and the strength that delivered it
+ // (#4874). Both are recorded only when they actually applied, so every text
+ // render and every pre-feature row stays byte-identical — and a Remix of an
+ // anchored render can't resurrect a mode the user never chose. The mode is the
+ // EFFECTIVE one, so a record never claims a promise the render did not make.
+ ...(isDefaultI2vReferenceMode(effectiveReferenceMode) ? {} : { i2vReferenceMode: effectiveReferenceMode }),
+ ...(actualImageStrength != null ? { imageStrength: actualImageStrength } : {}),
// Durable re-render provenance (#3696). `seed` above is ALWAYS the resolved
// seed (a caller-omitted seed was rolled into `actualSeed` before the child
// ever ran), so a random-seed render records the seed it actually used and
@@ -1602,7 +1639,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// logic of the spawn-error handler so failure modes converge.
let bin, args;
try {
- ({ bin, args } = buildArgs({ pythonPath, modelId, model: loraCapableModel, wanModelPath, wanRequiredWeights, ltxModelPath, prompt: renderPrompt, negativePrompt, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, steps: actualSteps, stage2Steps: actualStage2Steps, guidance: actualGuidance, seed: actualSeed, tiling, disableAudio, sourceImagePath: resolvedSourceImage, lastImagePath: resolvedLastImage, keyframes: resolvedKeyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength: actualImageStrength, textEncoderRepo: actualTextEncoderRepo, textEncoder: resolvedTextEncoder, outputPath, previewDir: stepwiseDir, loras: resolvedLoras, icReferencePaths: resolvedIcReferencePaths, icLoraWeightPath, icStrength: actualIcStrength, icAttentionStrength: actualIcAttentionStrength, icSkipStage2 }));
+ ({ bin, args } = buildArgs({ pythonPath, modelId, model: loraCapableModel, wanModelPath, wanRequiredWeights, ltxModelPath, prompt: renderPrompt, negativePrompt, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, steps: actualSteps, stage2Steps: actualStage2Steps, guidance: actualGuidance, seed: actualSeed, tiling, disableAudio, sourceImagePath: resolvedSourceImage, lastImagePath: resolvedLastImage, keyframes: resolvedKeyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength: actualImageStrength, i2vReferenceMode: effectiveReferenceMode, textEncoderRepo: actualTextEncoderRepo, textEncoder: resolvedTextEncoder, outputPath, previewDir: stepwiseDir, loras: resolvedLoras, icReferencePaths: resolvedIcReferencePaths, icLoraWeightPath, icStrength: actualIcStrength, icAttentionStrength: actualIcAttentionStrength, icSkipStage2 }));
} catch (err) {
job.status = 'error';
const reason = err.message || 'Failed to build video gen args';
@@ -2526,6 +2563,13 @@ export async function generateChainedVideo({ chunks, chunkPrompts, contextFrames
// chunks fall through to the image-chain path, conditioning on the
// prior chunk's tail frame.
keyframes: i === 0 ? rest.keyframes : null,
+ // The reference-mode promise (#4874) belongs to the first chunk alone. Every
+ // continuation conditions on the PRIOR chunk's tail — a still or a window
+ // clip the chain produced, not something the user offered as inspiration —
+ // and loosening that hop would break the seam it exists to hold. A window hop
+ // isn't image mode at all, so carrying the mode forward would also fail the
+ // gate outright.
+ i2vReferenceMode: i === 0 ? rest.i2vReferenceMode : null,
}).catch((err) => {
detach();
reject(err);
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index c92360cfbd..e2417f7fb5 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -9,6 +9,8 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { basename, join } from 'path';
import { tmpdir, totalmem } from 'os';
import { randomUUID } from 'crypto';
+// Pure table, no mocking involved — a static import survives vi.resetModules().
+import { INSPIRE_DEFAULT_IMAGE_STRENGTH } from '../../lib/videoReferenceModes.js';
const { heavyClaimRelease, heavyClaimHandoff, mockPrepareLocalMemory } = vi.hoisted(() => ({
heavyClaimRelease: vi.fn(async () => {}),
@@ -4991,3 +4993,85 @@ describe('updateHistoryItemPrompt — trigger-weave provenance (#4665)', () => {
expect(item).toEqual({ id: 'plain-1', prompt: 'a beach', seed: 42 });
});
});
+
+// The reference-mode promise (#4874) at the RENDER boundary. The route gates it
+// too, but persisted-queue replays, retries and internal producers all reach
+// generateVideo directly — a hole here means a clip anchored under an Inspire
+// label, which is precisely the lie the contract exists to prevent.
+describe('generateVideo — i2v reference mode (#4874)', () => {
+ const renderWithReference = async ({ jobId, modelId = 'ltx25_mlx_q8', i2vReferenceMode, imageStrength, mode = 'image' }) => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
+ spawnMock.mockClear();
+ let startedMeta = null;
+ const onStarted = (e) => { if (e.generationId === jobId) startedMeta = e; };
+ videoGenEvents.on('started', onStarted);
+ await generateVideo({
+ jobId,
+ pythonPath: '/usr/bin/python3',
+ modelId,
+ prompt: 'a fox in the rain',
+ width: 512, height: 512, numFrames: 25, fps: 24,
+ mode,
+ sourceImagePath: mode === 'image' ? '/mock/uploads/start.png' : null,
+ i2vReferenceMode,
+ imageStrength,
+ });
+ videoGenEvents.off('started', onStarted);
+ const call = spawnMock.mock.calls.find(([, args]) => Array.isArray(args) && args.includes('--mode'));
+ return { args: call?.[1] || [], startedMeta };
+ };
+
+ const valueAfter = (args, flag) => args[args.indexOf(flag) + 1];
+
+ it('emits no reference-mode argv for a default (anchored) render', async () => {
+ // An anchored render's argv must stay byte-identical to what it was before
+ // the flag existed, so an older helper pin can still run it.
+ const { args, startedMeta } = await renderWithReference({ jobId: 'ref-anchor-default' });
+ expect(args).not.toContain('--i2v-reference-mode');
+ expect(args).not.toContain('--image-strength');
+ expect(startedMeta.i2vReferenceMode).toBeUndefined();
+ expect(startedMeta.imageStrength).toBeUndefined();
+ });
+
+ it('emits the flag AND a resolved strength for a loose reference on LTX-2.5', async () => {
+ const { args, startedMeta } = await renderWithReference({
+ jobId: 'ref-inspire', i2vReferenceMode: 'inspire',
+ });
+ expect(valueAfter(args, '--i2v-reference-mode')).toBe('inspire');
+ // "Unset" under Inspire cannot mean "let the pipeline decide" — that would
+ // anchor. The contract's low default is substituted instead.
+ expect(Number(valueAfter(args, '--image-strength'))).toBe(INSPIRE_DEFAULT_IMAGE_STRENGTH);
+ // History provenance, so Remix and the gallery can describe the promise.
+ expect(startedMeta.i2vReferenceMode).toBe('inspire');
+ expect(startedMeta.imageStrength).toBe(INSPIRE_DEFAULT_IMAGE_STRENGTH);
+ });
+
+ it('honors an explicit strength under a loose reference', async () => {
+ const { args, startedMeta } = await renderWithReference({
+ jobId: 'ref-inspire-explicit', i2vReferenceMode: 'inspire', imageStrength: 0.8,
+ });
+ expect(Number(valueAfter(args, '--image-strength'))).toBe(0.8);
+ expect(startedMeta.imageStrength).toBe(0.8);
+ });
+
+ it('rejects a loose reference on the 2.3 pin rather than silently anchoring', async () => {
+ // ltx2 and ltx25 share the family predicate but not the per-image
+ // conditioning API — waving this through would deliver an anchored clip.
+ await expect(renderWithReference({
+ jobId: 'ref-inspire-ltx2', modelId: 'ltx2_unified', i2vReferenceMode: 'inspire',
+ })).rejects.toMatchObject({ status: 400, code: 'I2V_REFERENCE_MODE_UNSUPPORTED' });
+ });
+
+ it('rejects a loose reference outside image mode', async () => {
+ await expect(renderWithReference({
+ jobId: 'ref-inspire-text', i2vReferenceMode: 'inspire', mode: 'text',
+ })).rejects.toMatchObject({ status: 400, code: 'I2V_REFERENCE_MODE_REQUIRES_IMAGE' });
+ });
+
+ it('rejects an unknown reference mode instead of collapsing it to anchor', async () => {
+ await expect(renderWithReference({
+ jobId: 'ref-bogus', i2vReferenceMode: 'inspiration',
+ })).rejects.toMatchObject({ status: 400, code: 'I2V_REFERENCE_MODE_UNKNOWN' });
+ });
+});
diff --git a/server/services/videoGen/modeContract.js b/server/services/videoGen/modeContract.js
index 3f548c4422..5212a4c1cc 100644
--- a/server/services/videoGen/modeContract.js
+++ b/server/services/videoGen/modeContract.js
@@ -36,6 +36,7 @@
import { ServerError } from '../../lib/errorHandler.js';
import { VIDEO_RUNTIME_MODES, resolveVideoSupportedModes } from '../../lib/videoModeProfiles.js';
+import { i2vReferenceModeViolation } from '../../lib/videoReferenceModes.js';
// H3's fl2va path conditions on up to two keyframes anchored at the first and
// last latent frame — so text, image (first only) and FFLF (first + last) all
@@ -219,3 +220,24 @@ export const videoChainUnsupportedError = (model) => {
},
);
};
+
+/**
+ * The i2v reference-mode gate (#4874) — is the promise this request makes about
+ * its conditioning image one the selected model can actually keep?
+ *
+ * Deliberately a SEPARATE rule from `videoModeContractError` above: that one is
+ * per-runtime mode/source pairing (which is why it returns null for a runtime
+ * with no row), while this axis is orthogonal and applies to EVERY runtime —
+ * `anchor` is the universal default, and any other value has to be earned. The
+ * rule itself is stated once, purely, in `lib/videoReferenceModes.js` so the
+ * client can preview the same verdict; this only wraps the verdict in the
+ * ServerError the route and the render boundary throw.
+ *
+ * @param {object} opts - see `i2vReferenceModeViolation`
+ * @returns {ServerError|null}
+ */
+export const videoReferenceModeError = (opts) => {
+ const violation = i2vReferenceModeViolation(opts);
+ if (!violation) return null;
+ return new ServerError(violation.message, { status: 400, code: violation.code });
+};
diff --git a/server/services/videoGen/prepareParams.js b/server/services/videoGen/prepareParams.js
index 2fa69ce14f..250030b6b8 100644
--- a/server/services/videoGen/prepareParams.js
+++ b/server/services/videoGen/prepareParams.js
@@ -56,7 +56,7 @@ import {
} from './local.js';
// Straight from the leaf, not through local.js: the suites that exercise this
// module mock local.js wholesale, and a mocked rule table would assert nothing.
-import { videoModeContractError, videoChainUnsupportedError } from './modeContract.js';
+import { videoModeContractError, videoChainUnsupportedError, videoReferenceModeError } from './modeContract.js';
import { resolveByovRuntimeLoraCapable, videoLoraUnsupportedError } from './runtimes.js';
// Retries reuse persisted worker parameters instead of passing through the
@@ -84,6 +84,17 @@ export async function validateVideoRetryParams(params = {}) {
icReferences: params.icReferencePaths,
});
if (modeError) throw modeError;
+ // Reference-mode promise (#4874). A retry replays persisted params without
+ // passing the route schema, so an entry written by a newer/edited install (or
+ // a model swapped to a runtime that can't honor the mode) has to be caught
+ // here rather than reaching the render as a silent downgrade to anchor.
+ const referenceModeError = videoReferenceModeError({
+ model,
+ mode,
+ referenceMode: params.i2vReferenceMode,
+ hasFirstImage: Boolean(params.sourceImagePath),
+ });
+ if (referenceModeError) throw referenceModeError;
if (Number(params.chunks || 1) > 1) {
const chainError = videoChainUnsupportedError(model);
if (chainError) throw chainError;
@@ -513,6 +524,21 @@ async function resolvePreparedParams({
await cleanupStaged();
throw modeContractError;
}
+ // What the conditioning image PROMISES (#4874) — the orthogonal axis to the
+ // mode/source pairing above, and the same "reject rather than silently deliver
+ // something else" rule. Runs on the DECLARED shape for the same reason the
+ // mode contract does: rejecting before durable staging keeps cleanup cheap, and
+ // the resolved pass below re-checks once a gallery pick has become a real path.
+ const declaredReferenceModeError = videoReferenceModeError({
+ model: effectiveModel,
+ mode: declaredMode,
+ referenceMode: body.i2vReferenceMode,
+ hasFirstImage: hasDeclaredFirstImage,
+ });
+ if (declaredReferenceModeError) {
+ await cleanupStaged();
+ throw declaredReferenceModeError;
+ }
// MiniMax H3 is fixed-24fps, joint A/V and CFG-distilled on both its runtimes
// (MLX and CUDA). These are the model's non-mode controls; the mode gate
// above already ran. Fail before queue persistence so a direct API caller
@@ -590,6 +616,19 @@ async function resolvePreparedParams({
await cleanupStaged();
throw resolvedModeError;
}
+ // Same re-check for the reference-mode promise: a declared gallery pick that
+ // failed to resolve leaves an i2v request with no image, and "Inspire" over
+ // nothing is not a promise anything can keep.
+ const resolvedReferenceModeError = videoReferenceModeError({
+ model: effectiveModel,
+ mode: declaredMode,
+ referenceMode: body.i2vReferenceMode,
+ hasFirstImage: Boolean(sourceImagePath),
+ });
+ if (resolvedReferenceModeError) {
+ await cleanupStaged();
+ throw resolvedReferenceModeError;
+ }
// Music Video director-board renders are always i2v FROM the scene's reference
// frame (#1760 Phase 1). resolveGalleryImage returns null for a missing/invalid
// gallery file (mustExist defaults true), and an unresolved source would
diff --git a/server/services/videoGen/prepareParams.test.js b/server/services/videoGen/prepareParams.test.js
index defa3fb8bf..ff14189e8a 100644
--- a/server/services/videoGen/prepareParams.test.js
+++ b/server/services/videoGen/prepareParams.test.js
@@ -57,7 +57,7 @@ import { prepareVideoGenParams, withStagedRollback, cleanupMultipartTemp } from
// Field names the route owns Zod schemas for; the service only needs the keys
// to decide grok eligibility. Mirrors LOCAL_ONLY_VIDEO_PARAMS in the route.
-const LOCAL_ONLY_KEYS = ['numFrames', 'fps', 'steps', 'guidanceScale', 'seed', 'imageStrength', 'tiling'];
+const LOCAL_ONLY_KEYS = ['numFrames', 'fps', 'steps', 'guidanceScale', 'seed', 'imageStrength', 'i2vReferenceMode', 'tiling'];
const upload = (fieldname, name = 'frame.png') => ({
fieldname,
@@ -490,3 +490,53 @@ describe('prepareVideoGenParams — MiniMax H3 contract', () => {
expect(prepared.effectiveModelId).toBe(H3_MODEL.id);
});
});
+
+// The reference-mode promise (#4874) at the REQUEST boundary — rejected before
+// any durable upload is staged, so a doomed job never reaches the persisted
+// queue and the cleanup stays cheap.
+describe('prepareVideoGenParams — i2v reference mode (#4874)', () => {
+ const LTX25 = { id: 'ltx25_mlx_q8', name: 'LTX-2.5 MLX Q8', runtime: 'ltx25' };
+ const LTX2 = { id: 'ltx2_unified', name: 'LTX-2 Unified', runtime: 'ltx2' };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ listVideoModels.mockReturnValue([LTX2, LTX25]);
+ loadHistory.mockResolvedValue([]);
+ });
+
+ it('accepts a loose reference on an LTX-2.5 image render', async () => {
+ const prepared = await prepare(
+ { modelId: 'ltx25_mlx_q8', mode: 'image', i2vReferenceMode: 'inspire' },
+ { sourceImage: upload('sourceImage') },
+ );
+ expect(prepared.mode).toBe('image');
+ expect(unlinkedDurablePaths()).toEqual([]);
+ });
+
+ it.each([undefined, '', 'anchor'])('never rejects a request that left the field at %s', async (i2vReferenceMode) => {
+ await expect(prepare({ modelId: 'ltx2_unified', i2vReferenceMode })).resolves.toBeTruthy();
+ });
+
+ it('rejects a loose reference on a runtime that pins frame one, before staging', async () => {
+ await expect(prepare(
+ { modelId: 'ltx2_unified', mode: 'image', i2vReferenceMode: 'inspire' },
+ { sourceImage: upload('sourceImage') },
+ )).rejects.toMatchObject({ status: 400, code: 'I2V_REFERENCE_MODE_UNSUPPORTED' });
+ // Nothing durable was written, so nothing had to be rolled back.
+ expect(unlinkedDurablePaths()).toEqual([]);
+ });
+
+ it('rejects a loose reference on a text render', async () => {
+ await expect(prepare({ modelId: 'ltx25_mlx_q8', i2vReferenceMode: 'inspire' }))
+ .rejects.toMatchObject({ status: 400, code: 'I2V_REFERENCE_MODE_REQUIRES_IMAGE' });
+ });
+
+ it('rejects a loose reference whose gallery pick failed to resolve', async () => {
+ // The declared pass sees a filename and lets it through; the resolved pass
+ // is what catches an i2v request that has quietly become text-to-video.
+ vi.mocked(resolveGalleryImage).mockReturnValueOnce(null);
+ await expect(prepare({
+ modelId: 'ltx25_mlx_q8', mode: 'image', sourceImageFile: 'missing.png', i2vReferenceMode: 'inspire',
+ })).rejects.toMatchObject({ status: 400, code: 'I2V_REFERENCE_MODE_REQUIRES_IMAGE' });
+ });
+});