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: gate MiniMax H3 renders on a preview-fidelity draft decoder (#5423)

[._.]/ Adam Eivy92a7bb184861
diff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsx
index ec900fbc24..34e0aefb32 100644
--- a/client/src/components/media/MediaLightbox.jsx
+++ b/client/src/components/media/MediaLightbox.jsx
@@ -238,6 +238,22 @@ export default function MediaLightbox({
: id;
})();
+ // Which decoder produced these pixels (#5423). Same "the request is not the
+ // outcome" rule as the speed profile above: the record carries the decode
+ // that survived every server-side gate, and the runner's own report says
+ // whether the decoder actually loaded. A draft record with no report — or a
+ // report saying it fell back — must never read as a draft decode, because the
+ // whole point of the row is that a preview-fidelity clip is labelled as one.
+ const draftDecodeLabel = (() => {
+ const id = item.raw?.draftDecode;
+ if (!id) return null;
+ const applied = item.raw?.draftDecodeApplied;
+ if (!applied) return `${id} — outcome not reported`;
+ return applied.applied
+ ? `${id} — preview fidelity`
+ : `full decoder (${id} unavailable${applied.reason ? `: ${applied.reason}` : ''})`;
+ })();
+
const meta = [
// Universe Builder context — placed first so "this is Ash from MyVerse"
// reads before the technical render params. Sidecars without a universe
@@ -249,6 +265,7 @@ export default function MediaLightbox({
['Model', item.modelId],
['Resolution', item.width && item.height ? `${item.width}×${item.height}` : null],
['Speed profile', speedProfileLabel],
+ ['Decode', draftDecodeLabel],
['Steps', item.steps],
['Guidance', item.guidance],
['CFG', item.raw?.cfgScale ?? item.raw?.cfg_scale],
diff --git a/client/src/components/media/normalize.js b/client/src/components/media/normalize.js
index e76c847077..f93a1049e0 100644
--- a/client/src/components/media/normalize.js
+++ b/client/src/components/media/normalize.js
@@ -190,6 +190,11 @@ export function getRenderConfigForItem(item) {
// presented as a re-run of the same one. Absent on a Quality record, so
// the payload stays byte-identical to a pre-feature requeue.
speedProfileId: raw.speedProfileId,
+ // The decode the record was rendered with (#5423), for the same reason:
+ // a requeue that dropped it would silently re-render at full fidelity and
+ // full cost. Absent on a full-decode record, so the payload stays
+ // byte-identical to a pre-feature requeue.
+ draftDecode: raw.draftDecode,
loraFilenames: pickLoraFilenames(raw),
loraScales: raw.loraScales ?? raw.lora_scales,
};
diff --git a/client/src/components/videoGen/AdvancedParamsPanel.jsx b/client/src/components/videoGen/AdvancedParamsPanel.jsx
index cbe48747bb..6ee2ca79d8 100644
--- a/client/src/components/videoGen/AdvancedParamsPanel.jsx
+++ b/client/src/components/videoGen/AdvancedParamsPanel.jsx
@@ -14,6 +14,7 @@ import {
CONTEXT_FRAME_OPTIONS, supportsContextWindow,
DEFAULT_SPEED_PROFILE_ID, speedProfilesForMode, selectedSpeedProfile,
videoChainChunkModes,
+ DEFAULT_DRAFT_DECODE_ID, draftDecodeOptionsForModel,
} from '../../lib/videoGenParams.js';
import { VIDEO_TILING_OPTIONS } from '../../lib/videoTilingOptions';
import { isLtx2FamilyRuntime } from '../../lib/runnerFamilies';
@@ -36,6 +37,7 @@ export default function AdvancedParamsPanel({
steps, onStepsChange,
guidanceScale, onGuidanceScaleChange,
speedProfileId = DEFAULT_SPEED_PROFILE_ID, onSpeedProfileChange,
+ draftDecode = DEFAULT_DRAFT_DECODE_ID, onDraftDecodeChange,
imageStrength, onImageStrengthChange,
i2vReferenceMode = DEFAULT_I2V_REFERENCE_MODE, onI2vReferenceModeChange,
effectiveImageStrength = null,
@@ -105,6 +107,11 @@ export default function AdvancedParamsPanel({
const speedProfileModes = videoChainChunkModes({
model: currentModel, mode, chaining: chainingActive, contextFrames,
});
+ // Preview-fidelity decode (#5423). The option list is server-declared and
+ // rides on the model entry, so a model with no draft decoder yields [] and
+ // renders NO control rather than a select with one real choice.
+ const draftDecodeOptions = draftDecodeOptionsForModel(currentModel);
+ const activeDraftDecode = draftDecodeOptions.find((o) => o.id === draftDecode) || null;
const speedProfiles = speedProfilesForMode(currentModel, speedProfileModes);
const showSpeedProfiles = !samplerLocked && speedProfiles.length > 0;
// Resolved against the SAME set the picker offers, so a model with two
@@ -262,6 +269,28 @@ export default function AdvancedParamsPanel({
</div>
</div>
+ {draftDecodeOptions.length > 0 && (
+ <FormField label="Decode" labelClassName="block text-xs font-medium text-gray-400 mb-1">
+ <select
+ value={activeDraftDecode ? draftDecode : DEFAULT_DRAFT_DECODE_ID}
+ onChange={(e) => onDraftDecodeChange?.(e.target.value)}
+ className={inputCls}
+ >
+ {draftDecodeOptions.map((option) => (
+ <option key={option.id} value={option.id}>
+ {option.label}{option.sizeLabel ? ` · ${option.sizeLabel}` : ''}
+ </option>
+ ))}
+ </select>
+ <p className="mt-1 text-xs text-gray-500">
+ {activeDraftDecode?.description || ''}
+ {activeDraftDecode && activeDraftDecode.id !== DEFAULT_DRAFT_DECODE_ID
+ ? ' Finish and delivery renders always use the full decoder.'
+ : ''}
+ </p>
+ </FormField>
+ )}
+
{showSpeedProfiles && (
<FormField label="Speed" labelClassName="block text-xs font-medium text-gray-400 mb-1">
<select
diff --git a/client/src/components/videoGen/AdvancedParamsPanel.test.jsx b/client/src/components/videoGen/AdvancedParamsPanel.test.jsx
index 2dfa153aff..35f1fe63da 100644
--- a/client/src/components/videoGen/AdvancedParamsPanel.test.jsx
+++ b/client/src/components/videoGen/AdvancedParamsPanel.test.jsx
@@ -449,3 +449,51 @@ describe('AdvancedParamsPanel — speed profiles', () => {
expect(screen.getByText(/8\+3 steps, CFG 1/)).toBeTruthy();
});
});
+
+// Draft decode (#5423). The control exists so a user can trade decode fidelity
+// for a faster look at prompt and composition — but it must never appear for a
+// model that has no draft decoder, or it would offer a choice the server
+// declines and the render silently ignores.
+describe('AdvancedParamsPanel — draft decode', () => {
+ const DRAFT_OPTIONS = [
+ { id: 'full', label: 'Full decode', description: "The model's own decoder." },
+ { id: 'draft', label: 'Draft decode', description: 'Preview fidelity.', sizeLabel: '~1 GB' },
+ ];
+ const h3 = (over = {}) => ({
+ steps: 8, guidance: 0, runtime: 'minimax_h3', supportedModes: ['text', 'image', 'fflf'],
+ samplerLocked: true, draftDecodeOptions: DRAFT_OPTIONS, ...over,
+ });
+
+ it('renders no control for a model that declares no draft decoder', () => {
+ renderPanel({ currentModel: h3({ draftDecodeOptions: [] }) });
+ expect(screen.queryByLabelText('Decode')).toBeNull();
+ });
+
+ it('offers full first, then the declared decoder with its size', () => {
+ renderPanel({ currentModel: h3() });
+ const select = screen.getByLabelText('Decode');
+ expect([...select.options].map((o) => o.value)).toEqual(['full', 'draft']);
+ expect([...select.options].map((o) => o.text)).toEqual(['Full decode', 'Draft decode · ~1 GB']);
+ });
+
+ it('reports a selection to the parent', () => {
+ const onDraftDecodeChange = vi.fn();
+ renderPanel({ currentModel: h3(), onDraftDecodeChange });
+ fireEvent.change(screen.getByLabelText('Decode'), { target: { value: 'draft' } });
+ expect(onDraftDecodeChange).toHaveBeenCalledWith('draft');
+ });
+
+ // A stale selection carried in from a model that DID declare a decoder must
+ // not leave the select on a value with no matching option.
+ it('falls back to full for a selection this model does not offer', () => {
+ renderPanel({ currentModel: h3(), draftDecode: 'turbo' });
+ expect(screen.getByLabelText('Decode').value).toBe('full');
+ });
+
+ // The one thing a user picking Draft most needs to know, and the property the
+ // server enforces regardless of what the form says.
+ it('says that delivery renders always use the full decoder', () => {
+ renderPanel({ currentModel: h3(), draftDecode: 'draft' });
+ expect(screen.getByText(/Finish and delivery renders always use the full decoder/)).toBeTruthy();
+ });
+});
diff --git a/client/src/hooks/useVideoGenFieldState.js b/client/src/hooks/useVideoGenFieldState.js
index fc6c7f4b75..128de0c7e1 100644
--- a/client/src/hooks/useVideoGenFieldState.js
+++ b/client/src/hooks/useVideoGenFieldState.js
@@ -3,6 +3,7 @@ import { GROK_VIDEO_DEFAULT_DURATION } from '../lib/grokVideoClip.js';
import { DEFAULT_I2V_REFERENCE_MODE } from '../lib/videoReferenceModes.js';
import {
DEFAULT_CONTEXT_FRAMES,
+ DEFAULT_DRAFT_DECODE_ID,
DEFAULT_SPEED_PROFILE_ID,
STOCK_TEXT_ENCODER_ID,
} from '../lib/videoGenParams.js';
@@ -43,6 +44,7 @@ export function useVideoGenFieldState({
const [tiling, setTiling] = useState('auto');
const [textEncoderId, setTextEncoderId] = useState(STOCK_TEXT_ENCODER_ID);
const [speedProfileId, setSpeedProfileId] = useState(DEFAULT_SPEED_PROFILE_ID);
+ const [draftDecode, setDraftDecode] = useState(DEFAULT_DRAFT_DECODE_ID);
const [disableAudio, setDisableAudio] = useState(false);
const [selectedLoras, setSelectedLoras] = useState([]);
const [noMusic, setNoMusic] = useState(false);
@@ -101,6 +103,7 @@ export function useVideoGenFieldState({
selectedLoras, setSelectedLoras,
sizeManuallySetRef,
speedProfileId, setSpeedProfileId,
+ draftDecode, setDraftDecode,
staleModelToastRef,
steps, setSteps,
stylePreset, setStylePreset,
diff --git a/client/src/hooks/useVideoGenForm.js b/client/src/hooks/useVideoGenForm.js
index 7d205b1c45..4a7982aaf1 100644
--- a/client/src/hooks/useVideoGenForm.js
+++ b/client/src/hooks/useVideoGenForm.js
@@ -21,6 +21,8 @@ import {
textEncoderOptionsForModel, normalizeTextEncoderForModel,
textEncoderIdFromRecord,
normalizeSpeedProfileForModel, speedProfileIdFromRecord,
+ DEFAULT_DRAFT_DECODE_ID, draftDecodeOptionsForModel,
+ normalizeDraftDecodeForModel, draftDecodeFromRecord,
} from '../lib/videoGenParams.js';
import { useVideoGenFieldState } from './useVideoGenFieldState.js';
import { useVideoGenSubmitFlow } from './useVideoGenSubmitFlow.js';
@@ -113,6 +115,7 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, r
selectedLoras, setSelectedLoras,
sizeManuallySetRef,
speedProfileId, setSpeedProfileId,
+ draftDecode, setDraftDecode,
staleModelToastRef,
steps, setSteps,
stylePreset, setStylePreset,
@@ -467,6 +470,10 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, r
// profile selected that the new entry never declared, or submit would send
// a schedule the server declines and the picker would show a phantom.
setSpeedProfileId((current) => normalizeSpeedProfileForModel(current, currentModel));
+ // And the same for the decode: only some models declare a draft decoder, so
+ // a switch away from one must not leave "Draft" selected on a model whose
+ // renders would silently be full decodes.
+ setDraftDecode((current) => normalizeDraftDecodeForModel(current, currentModel));
}, [currentModel]);
// Substitutable prompt conditioners the selected model can load, straight off
@@ -475,6 +482,13 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, r
// runtime name.
const textEncoderOptions = textEncoderOptionsForModel(currentModel);
+ // Decode choices the selected model declares, straight off the
+ // server-decorated entry (lib/videoDraftDecoders.js
+ // `publicVideoDraftDecodeOptions`). Empty for every model with no draft
+ // decoder, which is what hides the control — the page never re-derives that
+ // from a runtime name.
+ const draftDecodeOptions = draftDecodeOptionsForModel(currentModel);
+
// Video-LoRA family for the selected model — 'ltx-video' on ltx2, else null.
// When null the picker is hidden and no LoRAs ride along on submit (the
// route would 400 with LORAS_REQUIRE_LTX2). Derived, not state, so it tracks
@@ -994,6 +1008,7 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, r
// snaps an id this model can't load back to stock.
setTextEncoderId(textEncoderIdFromRecord(item.textEncoderId));
setSpeedProfileId(speedProfileIdFromRecord(item.speedProfileId));
+ setDraftDecode(draftDecodeFromRecord(item.draftDecode));
// disableAudio: always set explicitly (true/false) so the toggle reliably
// matches the remixed render. Skipping the false branch would leave the
// toggle stuck ON when the user remixes a clip that had audio enabled.
@@ -1076,6 +1091,12 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, r
setRemixModelFallback(null);
setSteps('');
setGuidanceScale('');
+ // Finish is the delivery render, so it always decodes on the full decoder.
+ // The server enforces this too (`draftDecodeDeclineReason` declines a
+ // `finalRender`, and a delivery model is final on its own), but forcing it
+ // in the form means the user SEES the control agree with what will happen
+ // rather than reading Draft on a render that will ignore it.
+ setDraftDecode(DEFAULT_DRAFT_DECODE_ID);
};
// Repopulate the form from an in-flight (or queued) render restored via
@@ -1102,6 +1123,7 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, r
// Resume echoes the field only for a non-stock render, so absence is 'stock'.
setTextEncoderId(textEncoderIdFromRecord(p.textEncoderId));
setSpeedProfileId(speedProfileIdFromRecord(p.speedProfileId));
+ setDraftDecode(draftDecodeFromRecord(p.draftDecode));
if (typeof p.disableAudio === 'boolean') setDisableAudio(p.disableAudio);
if (p.mode === 'grok') {
// Grok job: 'grok' is the queue discriminator, not a semantic video
@@ -1185,7 +1207,7 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, r
prompt, negativePrompt, stylePreset,
width, height, mode, sourceImageFile, sourceImageUpload,
numFrames, fps, steps, guidanceScale, seed,
- currentModel, modelId, tiling, textEncoderId, speedProfileId,
+ currentModel, modelId, tiling, textEncoderId, speedProfileId, draftDecode,
disableAudio, noMusic, imageStrength, i2vReferenceMode,
keyframesActive, keyframes, loraFamily, selectedLoras,
lastImageFile, lastImageUpload, extendFromVideoId, audioFile,
@@ -1229,6 +1251,7 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, r
tiling, setTiling,
textEncoderId, setTextEncoderId, textEncoderOptions,
speedProfileId, setSpeedProfileId,
+ draftDecode, setDraftDecode, draftDecodeOptions,
disableAudio, setDisableAudio,
noMusic, setNoMusic,
// Frames
diff --git a/client/src/lib/videoGenParams.js b/client/src/lib/videoGenParams.js
index 288123db22..b61e0e6ad3 100644
--- a/client/src/lib/videoGenParams.js
+++ b/client/src/lib/videoGenParams.js
@@ -208,6 +208,35 @@ export const selectedSpeedProfile = (id, model, mode = null) => (
isDefaultSpeedProfileId(id) ? null : speedProfilesForMode(model, mode).find((p) => p.id === id) || null
);
+// --- Draft decode (#5423) -------------------------------------------------
+// Mirrors server/lib/videoDraftDecoders.js. The OPTION LIST is server-declared
+// and rides to the client on each model entry as `draftDecodeOptions` (built by
+// `publicVideoDraftDecodeOptions`), so there is no client-side decoder table to
+// drift — only the same "absence IS full decode" sentinel rule the speed-profile
+// and text-encoder helpers above follow.
+export const DEFAULT_DRAFT_DECODE_ID = 'full';
+export const isFullDecodeId = (id) => (
+ id == null || id === '' || id === DEFAULT_DRAFT_DECODE_ID
+);
+// The decode choices this model offers, or [] when it declares no draft decoder
+// — which is the signal to render NO control rather than a one-entry select.
+export const draftDecodeOptionsForModel = (model) => (
+ Array.isArray(model?.draftDecodeOptions) ? model.draftDecodeOptions.filter((o) => o?.id) : []
+);
+export const supportsDraftDecode = (model) => draftDecodeOptionsForModel(model).length > 0;
+// Snap a selection onto what the (possibly just-switched) model declares, so
+// the <select> is never left on a value with no matching <option>.
+export const normalizeDraftDecodeForModel = (id, model) => (
+ draftDecodeOptionsForModel(model).some((o) => o.id === id) ? id : DEFAULT_DRAFT_DECODE_ID
+);
+// Read a decode out of a persisted record (a history entry, a resumed job's
+// params). Both record only a NON-default decode, so a missing field means Full
+// — and must CLEAR a leftover selection rather than carry it into a render the
+// user asked to reproduce.
+export const draftDecodeFromRecord = (value) => (
+ typeof value === 'string' && value ? value : DEFAULT_DRAFT_DECODE_ID
+);
+
// Per-edge bounds for video: mirrors the videoGen route (64..2048). The base
// grid is 64px, while a model may declare a finer resolutionStep (H3 uses 32).
// Shared by the ResolutionField control and the submit-time clamp so a
diff --git a/client/src/lib/videoGenParams.test.js b/client/src/lib/videoGenParams.test.js
index 46a9550a26..3daf9542aa 100644
--- a/client/src/lib/videoGenParams.test.js
+++ b/client/src/lib/videoGenParams.test.js
@@ -10,6 +10,8 @@ import {
DEFAULT_SPEED_PROFILE_ID, isDefaultSpeedProfileId, speedProfilesForModel,
speedProfilesForMode, normalizeSpeedProfileForModel,
speedProfileIdFromRecord, selectedSpeedProfile, videoChainChunkModes,
+ DEFAULT_DRAFT_DECODE_ID, isFullDecodeId, draftDecodeOptionsForModel,
+ supportsDraftDecode, normalizeDraftDecodeForModel, draftDecodeFromRecord,
} from './videoGenParams.js';
describe('videoModelMemoryGb', () => {
@@ -339,4 +341,61 @@ describe('speed profiles', () => {
});
});
+// Draft decode (#5423). The decoder table itself is server-side — only these
+// sentinel rules live here, and each one exists to stop the form POSTing a knob
+// the server would decline (or dropping one the user chose).
+describe('draft decode helpers', () => {
+ const OPTIONS = [
+ { id: 'full', label: 'Full decode' },
+ { id: 'draft', label: 'Draft decode' },
+ ];
+
+ // Absence, '' and 'full' are ONE request, mirroring `isFullDecode` on the
+ // server. If they diverged, an omitted field would start sending a decode
+ // override and a pre-feature payload would stop being byte-identical.
+ it.each([undefined, null, '', DEFAULT_DRAFT_DECODE_ID])('reads %p as a full decode', (id) => {
+ expect(isFullDecodeId(id)).toBe(true);
+ });
+
+ it('does not read a declared decoder id as full', () => {
+ expect(isFullDecodeId('draft')).toBe(false);
+ });
+
+ // Empty is the signal to render NO control — a model with no draft decoder
+ // must not be given a one-entry select implying a choice it doesn't have.
+ it.each([
+ ['a model with no options field', {}],
+ ['an empty option list', { draftDecodeOptions: [] }],
+ ['options with no ids', { draftDecodeOptions: [{ label: 'broken' }] }],
+ ])('offers nothing for %s', (_label, model) => {
+ expect(draftDecodeOptionsForModel(model)).toEqual([]);
+ expect(supportsDraftDecode(model)).toBe(false);
+ });
+
+ it('passes through a declared option list', () => {
+ expect(draftDecodeOptionsForModel({ draftDecodeOptions: OPTIONS })).toEqual(OPTIONS);
+ });
+
+ // A model switch must not leave "Draft" selected on a model whose renders
+ // would then silently be full decodes.
+ it.each([
+ ['an id this model offers', 'draft', { draftDecodeOptions: OPTIONS }, 'draft'],
+ ['an id it does not', 'draft', { draftDecodeOptions: [] }, DEFAULT_DRAFT_DECODE_ID],
+ ['an unknown id', 'turbo', { draftDecodeOptions: OPTIONS }, DEFAULT_DRAFT_DECODE_ID],
+ ])('normalizes %s', (_label, id, model, expected) => {
+ expect(normalizeDraftDecodeForModel(id, model)).toBe(expected);
+ });
+
+ // Records store only a NON-default decode, so a missing field must CLEAR a
+ // leftover selection rather than carry it into a faithful re-render.
+ it.each([
+ [undefined, DEFAULT_DRAFT_DECODE_ID],
+ [null, DEFAULT_DRAFT_DECODE_ID],
+ ['', DEFAULT_DRAFT_DECODE_ID],
+ ['draft', 'draft'],
+ ])('reads %p out of a record as %p', (stored, expected) => {
+ expect(draftDecodeFromRecord(stored)).toBe(expected);
+ });
+});
+
// @vitest-environment node
diff --git a/client/src/lib/videoGenSubmission.js b/client/src/lib/videoGenSubmission.js
index 9cfeec0995..575988184f 100644
--- a/client/src/lib/videoGenSubmission.js
+++ b/client/src/lib/videoGenSubmission.js
@@ -11,6 +11,8 @@ import {
STOCK_TEXT_ENCODER_ID,
selectedSpeedProfile,
videoChainChunkModes,
+ DEFAULT_DRAFT_DECODE_ID,
+ normalizeDraftDecodeForModel,
} from './videoGenParams.js';
// The form owns state transitions and validation. This module owns the three
@@ -30,7 +32,7 @@ export function buildVideoGenSubmission({
prompt, negativePrompt, stylePreset,
width, height, mode, sourceImageFile, sourceImageUpload,
numFrames, fps, steps, guidanceScale, seed,
- currentModel, modelId, tiling, textEncoderId, speedProfileId,
+ currentModel, modelId, tiling, textEncoderId, speedProfileId, draftDecode,
disableAudio, noMusic, imageStrength, i2vReferenceMode,
keyframesActive, keyframes, loraFamily, selectedLoras,
lastImageFile, lastImageUpload, extendFromVideoId, audioFile,
@@ -101,6 +103,13 @@ export function buildVideoGenSubmission({
speedProfileId: selectedSpeedProfile(speedProfileId, currentModel, videoChainChunkModes({
model: currentModel, mode, chaining: chainingActive, contextFrames,
}))?.id,
+ // Preview-fidelity decode (#5423). Sent only when it is a real, still-valid
+ // choice on THIS model — a stale selection carried across a model switch
+ // would otherwise POST a knob the server declines and logs. Absence is a
+ // full decode, so an unswapped render's payload is unchanged.
+ draftDecode: normalizeDraftDecodeForModel(draftDecode, currentModel) === DEFAULT_DRAFT_DECODE_ID
+ ? undefined
+ : draftDecode,
disableAudio: effectiveDisableAudio ? 'true' : 'false',
mode,
imageStrength: imageStrength || '',
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index c750987032..ccfdf45bd8 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -164,6 +164,7 @@ export default function VideoGen() {
i2vReferenceMode, setI2vReferenceMode, referenceModeSupported, effectiveImageStrength,
speedProfileId, setSpeedProfileId,
+ draftDecode, setDraftDecode,
seed, setSeed, handleRandomSeed, tiling, setTiling,
textEncoderId, setTextEncoderId, textEncoderOptions,
disableAudio, setDisableAudio, noMusic, setNoMusic,
@@ -1359,6 +1360,7 @@ export default function VideoGen() {
steps={steps} onStepsChange={setSteps}
guidanceScale={guidanceScale} onGuidanceScaleChange={setGuidanceScale}
speedProfileId={speedProfileId} onSpeedProfileChange={setSpeedProfileId}
+ draftDecode={draftDecode} onDraftDecodeChange={setDraftDecode}
imageStrength={imageStrength} onImageStrengthChange={setImageStrength}
i2vReferenceMode={i2vReferenceMode} onI2vReferenceModeChange={setI2vReferenceMode}
effectiveImageStrength={effectiveImageStrength}
diff --git a/scripts/generate_minimax_h3.py b/scripts/generate_minimax_h3.py
index 141d812c14..4e700ad260 100644
--- a/scripts/generate_minimax_h3.py
+++ b/scripts/generate_minimax_h3.py
@@ -79,6 +79,12 @@ def parse_args() -> argparse.Namespace:
help="rewrite this checkpoint-key prefix before the loader matches it (repeatable)")
parser.add_argument("--text-encoder-final-norm-key",
help="synthesize a ones-filled final norm under this key (for a conditioner published without one)")
+ parser.add_argument("--draft-decoder-id",
+ help="preview-fidelity video decoder to substitute for this render (PortOS #5423)")
+ parser.add_argument("--draft-decoder-file", action="append", default=[],
+ help="cache-resolved weight file for the draft decoder (repeatable)")
+ parser.add_argument("--draft-decoder-shim-root",
+ help="directory the composed draft-decoder checkpoint root is built under")
return parser.parse_args()
@@ -467,6 +473,88 @@ def build_encoder_shim(
return root
+def emit_draft_decode(decoder_id: str, applied: bool, reason: str | None = None) -> None:
+ """Report what this render ACTUALLY decoded with, on one DRAFTDECODE: line.
+
+ PortOS gates the substitution declaratively — model declaration, runner
+ revision, asset readiness, delivery intent — but only the child can see
+ whether the pinned decoder module tree accepts the asset's tensors. So the
+ server records the REQUEST and this line records the OUTCOME, and the
+ history row carries both. Without it a decoder that failed to load would
+ read back as a draft decode that never happened.
+ """
+ payload = {"id": decoder_id, "applied": applied}
+ if reason:
+ payload["reason"] = reason
+ print(f"DRAFTDECODE:{json.dumps(payload)}", file=sys.stderr, flush=True)
+
+
+def build_draft_decoder_shim(
+ checkpoint_dir: Path,
+ shim_root: Path,
+ decoder_id: str,
+ decoder_files: list[Path],
+) -> Path:
+ """Compose a checkpoint root whose `video_vae/source/` is the substitute.
+
+ Same shape, and the same reasoning, as `build_encoder_shim` above:
+ everything but the one swapped component is symlinked straight through from
+ the upstream snapshot, so the pinned `from_pretrained` loads this directory
+ with no argument it doesn't already take and no knowledge that anything was
+ swapped.
+
+ The wrapper `video_vae/config.json` and `source/config.json` come from
+ UPSTREAM, not the substitute: the draft decoder is a re-trained or
+ re-quantized decoder over the SAME latent contract, so its channel counts,
+ `latents_mean`/`latents_std` and compression ratios must stay upstream's. A
+ candidate that needs its own config is decoding a different latent space and
+ does not belong in the table at all (see the checklist in
+ server/lib/videoDraftDecoders.js).
+
+ Rebuilt from scratch on every render, for the same reason the encoder shim
+ is: the links are free, and a stale shim pointing at a blob the user has
+ since re-downloaded would load silently-wrong weights.
+ """
+ for decoder_file in decoder_files:
+ if not decoder_file.is_file():
+ raise RuntimeError(f"Draft decoder weight is missing: {decoder_file}")
+ # The pinned `load_video_vae` reads exactly `source/model.safetensors` — it
+ # does not glob the way the text-encoder loader does — so a multi-file
+ # substitute has nowhere to go. Refusing it here is the honest failure: the
+ # alternative is linking one shard and silently decoding with a partial
+ # decoder over upstream's config.
+ if len(decoder_files) != 1:
+ raise RuntimeError(
+ f"The pinned H3 video VAE loads one source weight file; got {len(decoder_files)}."
+ )
+
+ stock_vae = checkpoint_dir / "video_vae"
+ stock_source_config = stock_vae / "source" / "config.json"
+ if not stock_source_config.is_file():
+ raise RuntimeError(f"Upstream video-VAE config is missing: {stock_source_config}")
+
+ root = shim_root / decoder_id
+ shutil.rmtree(root, ignore_errors=True)
+ (root / "video_vae" / "source").mkdir(parents=True, exist_ok=True)
+
+ for entry in checkpoint_dir.iterdir():
+ if entry.name == "video_vae":
+ continue
+ # target_is_directory is a no-op on POSIX and load-bearing on Windows,
+ # exactly as in build_encoder_shim.
+ (root / entry.name).symlink_to(entry, target_is_directory=entry.is_dir())
+ for entry in stock_vae.iterdir():
+ if entry.name == "source":
+ continue
+ (root / "video_vae" / entry.name).symlink_to(entry, target_is_directory=entry.is_dir())
+ (root / "video_vae" / "source" / "config.json").symlink_to(stock_source_config)
+ # Linked under the name the pinned loader opens, NOT the substitute's own
+ # filename, which is whatever its publisher chose.
+ (root / "video_vae" / "source" / "model.safetensors").symlink_to(decoder_files[0])
+
+ return root
+
+
def verify_runtime_checkout(runtime_dir: Path, expected_revision: str) -> None:
"""Require the exact commit and a clean executable source package."""
try:
@@ -637,6 +725,17 @@ def validate_args(args: argparse.Namespace) -> None:
raise SystemExit(f"--text-encoder-id must be a bare directory-safe name; got {args.text_encoder_id!r}.")
if not args.text_encoder_file and (args.text_encoder_key_prefix or args.text_encoder_final_norm_key):
raise SystemExit("--text-encoder-key-prefix / --text-encoder-final-norm-key need --text-encoder-file.")
+ # Same all-or-nothing rule as the conditioner above, and for the same
+ # reason: a partial set would silently decode on the full decoder while
+ # PortOS recorded a draft decode, which is the exact false claim the whole
+ # gate chain in lib/videoDraftDecoders.js exists to prevent.
+ decoder_flags = (args.draft_decoder_id, args.draft_decoder_file, args.draft_decoder_shim_root)
+ if any(decoder_flags) and not all(decoder_flags):
+ raise SystemExit(
+ "--draft-decoder-id, --draft-decoder-file and --draft-decoder-shim-root must be given together."
+ )
+ if args.draft_decoder_id and not re.fullmatch(r"[A-Za-z0-9._-]+", args.draft_decoder_id):
+ raise SystemExit(f"--draft-decoder-id must be a bare directory-safe name; got {args.draft_decoder_id!r}.")
def main() -> int:
@@ -717,15 +816,61 @@ def main() -> int:
args.text_encoder_final_norm_key,
)
- print("STAGE:load-pipeline", file=sys.stderr, flush=True)
- with heartbeat("minimax-h3-load"):
- pipe = MiniMaxH3Pipeline.from_pretrained(
- checkpoint_dir,
- transformer_dir=transformer_dir,
- # The Qwen3-VL vision tower is only loaded when a keyframe needs
- # encoding — a text-only run keeps skipping it.
- load_vision=bool(images),
+ # Preview-fidelity video decode (PortOS #5423). PortOS has already cleared
+ # every gate it can see — the model declares this decoder, the checkout is
+ # the revision the asset was verified against, the weights are in the HF
+ # cache, and this is not a delivery render — so reaching here means only the
+ # LOAD is still unproven, and only the pinned VAE loader's own STRICT
+ # parameter check can prove it. So the swap is attempted, and a failure
+ # RETRIES on the model's own decoder rather than aborting: a preview that
+ # renders slowly is a better outcome than a render that dies at load, and
+ # the DRAFTDECODE: line keeps the history record honest about which one
+ # produced the pixels.
+ def fall_back_to_full_decoder(exc: Exception) -> None:
+ """Report the substitution as NOT applied and say why, once."""
+ emit_draft_decode(args.draft_decoder_id, False, f"{type(exc).__name__}: {exc}")
+ print(
+ f"⚠️ Draft decoder unavailable, decoding on the full decoder: {type(exc).__name__}: {exc}",
+ file=sys.stderr,
+ flush=True,
)
+ print("STATUS:Draft decoder unavailable — decoding on the full decoder", file=sys.stderr, flush=True)
+
+ decoder_shim = None
+ if args.draft_decoder_file:
+ print("STAGE:swap-video-decoder", file=sys.stderr, flush=True)
+ print(f"STATUS:Decoding with the {args.draft_decoder_id} draft decoder", file=sys.stderr, flush=True)
+ try:
+ decoder_shim = build_draft_decoder_shim(
+ checkpoint_dir,
+ Path(args.draft_decoder_shim_root),
+ args.draft_decoder_id,
+ [Path(f) for f in args.draft_decoder_file],
+ )
+ except Exception as exc: # noqa: BLE001 — degrade, never fail the render
+ fall_back_to_full_decoder(exc)
+
+ print("STAGE:load-pipeline", file=sys.stderr, flush=True)
+
+ def load_pipeline(root: Path):
+ with heartbeat("minimax-h3-load"):
+ return MiniMaxH3Pipeline.from_pretrained(
+ root,
+ transformer_dir=transformer_dir,
+ # The Qwen3-VL vision tower is only loaded when a keyframe needs
+ # encoding — a text-only run keeps skipping it.
+ load_vision=bool(images),
+ )
+
+ if decoder_shim is None:
+ pipe = load_pipeline(checkpoint_dir)
+ else:
+ try:
+ pipe = load_pipeline(decoder_shim)
+ emit_draft_decode(args.draft_decoder_id, True)
+ except Exception as exc: # noqa: BLE001 — degrade to the full decoder
+ fall_back_to_full_decoder(exc)
+ pipe = load_pipeline(checkpoint_dir)
# Runtime LoRA application — never a fuse. The DiT is quantized, so the
# applicator has to take each layer's logical dims from the quantization
diff --git a/scripts/generate_minimax_h3.test.js b/scripts/generate_minimax_h3.test.js
index 679706574c..3698f9e1c9 100644
--- a/scripts/generate_minimax_h3.test.js
+++ b/scripts/generate_minimax_h3.test.js
@@ -67,6 +67,9 @@ const VALIDATE_ARGS_DEFAULTS = {
text_encoder_shim_root: null,
text_encoder_key_prefix: [],
text_encoder_final_norm_key: null,
+ draft_decoder_id: null,
+ draft_decoder_file: [],
+ draft_decoder_shim_root: null,
};
const argsExpr = (overrides = {}) => {
const fields = Object.entries({ ...VALIDATE_ARGS_DEFAULTS, ...overrides })
@@ -308,6 +311,51 @@ describe.skipIf(!pyBin)('generate_minimax_h3.py', () => {
expect(output).toMatch(pattern);
});
+ // Draft decode (#5423). Same all-or-nothing rule as the conditioner above, and
+ // for the same reason: a partial set would decode on the FULL decoder while
+ // PortOS's history record claimed a draft one.
+ it.each([
+ [{ draft_decoder_id: 'draft' }, /must be given together/i],
+ [{ draft_decoder_file: ['/tmp/d.safetensors'] }, /must be given together/i],
+ [{ draft_decoder_shim_root: '/tmp/decoder-shims' }, /must be given together/i],
+ // The id names a directory under the shim root, so a traversing value is a
+ // real escape rather than a cosmetic problem.
+ [
+ {
+ draft_decoder_id: '../escape',
+ draft_decoder_file: ['/tmp/d.safetensors'],
+ draft_decoder_shim_root: '/tmp/decoder-shims',
+ },
+ /bare directory-safe name/i,
+ ],
+ ])('rejects an incoherent draft-decoder argument set (%j)', (overrides, pattern) => {
+ const output = runPython(`${importRunner}\n${[
+ 'from types import SimpleNamespace',
+ argsExpr(overrides),
+ 'try:',
+ ' runner.validate_args(args)',
+ 'except SystemExit as exc:',
+ ' print(str(exc))',
+ 'else:',
+ ' raise SystemExit("incoherent draft-decoder args were accepted")',
+ ].join('\n')}`);
+ expect(output).toMatch(pattern);
+ });
+
+ it('accepts a complete draft-decoder argument set', () => {
+ const output = runPython(`${importRunner}\n${[
+ 'from types import SimpleNamespace',
+ argsExpr({
+ draft_decoder_id: 'draft',
+ draft_decoder_file: ['/tmp/d.safetensors'],
+ draft_decoder_shim_root: '/tmp/decoder-shims',
+ }),
+ 'runner.validate_args(args)',
+ 'print("ok")',
+ ].join('\n')}`);
+ expect(output.trim()).toBe('ok');
+ });
+
it('accepts a complete text-encoder argument set', () => {
const output = runPython(`${importRunner}\n${[
'from types import SimpleNamespace',
diff --git a/server/lib/README.md b/server/lib/README.md
index 0d1982d804..e54036b2de 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -151,6 +151,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `minimaxH3Memory.js` | The declared weight-placement table for the two MiniMax H3 entries (#5420) — H3 is the one video model whose components fit nowhere unassisted, so "does this box have enough" is a render gate, not a UI fact. `MINIMAX_H3_MEMORY_PROFILES` maps entry id → `{ shippedRepo, shippedRevision, profiles }`, each profile carrying an honest `minMemoryGb` host floor and (CUDA only) a `minVramGb` device floor, ordered best-first. Every capacity number is HOISTED from what already existed — the CUDA tiers are `resolve_offload_profile()`'s own thresholds in `scripts/generate_minimax_h3_cuda.py`, the host floors are the entries' `memoryGb` — the sole new number being `MINIMAX_H3_HOST_RESERVE_GB`, a policy reserve held back for the OS. `applyMiniMaxH3MemoryProfiles(list)` is the load-time backfill (twin of migration 317) and guards BOTH `repo` and `revision`, like the speed-profile decorator. `selectMiniMaxH3MemoryProfile({ model, totalMemoryGb })` picks the best profile the HOST can hold (VRAM is the runner's call — the server has no synchronous device view); `miniMaxH3MemoryDeclineReason()` RETURNS the fail-closed reason so the render path can 400 it and a status surface can show it, and returns `null` on an UNMEASURED host — "not measured" is a deferral to the runner, never the same as zero. `validateMiniMaxH3MemoryProfileTable` / `sanitizeMiniMaxH3MemoryProfiles` warn + strip a hand-edited table (NaN floor, duplicate/reserved id, mis-ordered tiers) at load. |
| `videoContinuity.js` | How chunk N+1 of a chained video render is conditioned on chunk N. `resolveContextFrames(requested)` normalizes the tail-window size (absent → `DEFAULT_CONTEXT_FRAMES` = 22 ≈ 1s @ 24fps; an explicit `0` is preserved as "last frame only", NOT collapsed into the default) and clamps to `MIN_CONTEXT_FRAMES`..`MAX_CONTEXT_FRAMES`. `resolveContinuityStrategy({model, contextFrames})` picks `'window'` (LTX-2 `extend_from_video` conditioned on the prior chunk's last N frames — motion, not just a pose) or `'frame'` (extract the last frame, run i2v), degrading to `'frame'` on any runtime outside `CONTEXT_WINDOW_RUNTIMES` rather than rejecting. `extendLatentFrames` / `extendedPixelFrames` convert across the VAE's `LATENT_FRAME_STRIDE` (8 pixel frames per latent), `contextPrefixFrames({totalFrames, extendLatents})` measures how much of an extend render is echoed context to trim back off before stitching (0 = leave it alone), and `tailWindowStartFrame` gives the cut index for the window itself. Pure — importable from `prepareParams.js` without dragging in `local.js`. Mirrored for the picker in `client/src/lib/videoGenParams.js`, pinned by `videoContinuity.parity.test.js`. |
| `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. |
+| `videoDraftDecoders.js` | Preview-fidelity ("draft") video decode (#5423). `VIDEO_DRAFT_DECODERS` declares each entry id → a separately downloaded decoder asset, pin-guarded on repo AND revision; `applyVideoDraftDecoders(list)` is the load-time backfill and `validateDraftDecoderTable` / `sanitizeDraftDecoders` warn + strip a hand-edited row (missing pin, a multi-shard or path-traversing file list, a runtime whose builder emits no draft flags) so a full decode can never report itself as a draft one. `DRAFT_DECODE_FULL` (`'full'`) is a deliberate NO-OP — `isFullDecode(id)` makes absence and that sentinel the same request, so a full-decode render builds byte-identical spawn args. `draftDecodeDeclineReason({ model, decodeId, models, runtimeRevision, assetCached })` RETURNS (never throws) the reason a draft decode does not apply — the model is a delivery target in the finish graph (`isDeliveryVideoModel`), it declares no decoder, the installed runner checkout is not the revision the asset was verified against, or the weights are not downloaded — because a knob that only makes a render cheaper must degrade rather than 400 a submitted job; `resolveVideoDraftDecoder()` returns the concrete asset or `null`. `publicVideoDraftDecodeOptions(model)` is the picker payload (empty for a model with no decoder, so the client renders no control) and `downloadableVideoDraftDecoders(list)` the download targets. The table ships NO entry yet — its header carries the four-point checklist a candidate asset must pass first. |
| `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. |
| `videoSpeedProfiles.js` | Named, pre-validated sampler schedules a user can pick instead of hand-tuning steps/CFG (#4875). `VIDEO_SPEED_PROFILES` declares each entry id → `{ shippedRepo, shippedRevision, profiles }`; `applyVideoSpeedProfiles(list)` is the load-time backfill (twin of migration 295) and guards BOTH `repo` and `revision` — unlike the finish-profile decorator, because a sampler schedule is revision-sensitive in a way a draft→delivery edge is not. `SPEED_PROFILE_DEFAULT_ID` (`'quality'`) is a deliberate NO-OP so a default render builds byte-identical spawn args and stamps no extra history fields; `isDefaultSpeedProfile(id)` makes absence and that sentinel the same request. `speedProfileDeclineReason({ model, profileId, mode })` RETURNS (never throws) the reason a profile does not apply — wrong mode, unpinned weights, `samplerLocked` model, unknown id — so a knob that only makes a render faster degrades instead of 400ing a submitted job, and `resolveVideoSpeedProfile()` returns the concrete override or `null`. `resolveVideoSpeedProfileForModes({ model, profileId, modes })` lifts that decline check to a CHAINED render — a chain is one clip whose chunks run in different modes (chunk 0 the request's, chunks 1+ `extend` on a window-continuity chain or `image` on a frame hop), so the profile applies to every chunk or to none rather than seaming a fast chunk onto quality ones. `resolveVideoSampler({ model, steps, guidanceScale, speedProfile })` is the SINGLE precedence rule (samplerLocked > profile > explicit request > registry default), shared by the render path and the chained-render ETA so the two cannot drift. `validateSpeedProfileTable(list)` / `sanitizeSpeedProfiles(list)` warn + strip a hand-edited profile (NaN steps, duplicate/reserved id, samplerLocked collision) at load rather than letting it spawn a broken render. What the RUNNER could actually apply — is the pinned pipeline new enough for `enable_teacache`, is the distilled adapter in the pack — is probed by `scripts/generate_ltx2.py` and reported back on a `SPEEDPROFILE:` line. |
| `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`/`fastvideo` text+image, `minimax_h3` / `minimax_h3_cuda` text+image+fflf off one shared array — also the mode ceiling in `videoGen/modeContract.js`); `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`). |
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index fdedefdc8a..fc4118bab9 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -21985,7 +21985,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 911
+ "line": 920
}
]
},
@@ -21996,7 +21996,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1290
+ "line": 1307
}
]
},
@@ -22007,7 +22007,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1266
+ "line": 1283
}
]
},
@@ -22018,7 +22018,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1295
+ "line": 1312
}
]
},
@@ -22029,7 +22029,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1324
+ "line": 1341
}
]
},
@@ -22040,7 +22040,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1372
+ "line": 1389
}
]
},
@@ -22051,7 +22051,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1344
+ "line": 1361
}
]
},
@@ -22062,7 +22062,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1380
+ "line": 1397
}
]
},
@@ -22073,7 +22073,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1376
+ "line": 1393
}
]
},
@@ -22084,7 +22084,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 790
+ "line": 799
}
]
},
@@ -22095,7 +22095,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 809
+ "line": 818
}
]
},
@@ -22106,7 +22106,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1397
+ "line": 1414
}
]
},
@@ -22117,7 +22117,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 443
+ "line": 452
}
]
},
@@ -22128,7 +22128,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 447
+ "line": 456
}
]
},
@@ -22139,7 +22139,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 515
+ "line": 524
}
]
},
@@ -22150,7 +22150,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 756
+ "line": 765
}
]
},
@@ -22161,7 +22161,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 741
+ "line": 750
}
]
},
@@ -22172,7 +22172,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 644
+ "line": 653
}
]
},
@@ -22183,7 +22183,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 724
+ "line": 733
}
]
},
@@ -22194,7 +22194,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 485
+ "line": 494
}
]
},
@@ -22205,7 +22205,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 487
+ "line": 496
}
]
},
@@ -22216,7 +22216,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 481
+ "line": 490
}
]
},
@@ -22227,7 +22227,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 393
+ "line": 402
}
]
},
@@ -22238,7 +22238,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1414
+ "line": 1431
}
]
},
@@ -22249,7 +22249,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 898
+ "line": 907
}
]
},
@@ -22260,7 +22260,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 884
+ "line": 893
}
]
},
@@ -22271,7 +22271,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 854
+ "line": 863
}
]
},
@@ -22282,7 +22282,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 864
+ "line": 873
}
]
},
@@ -22293,7 +22293,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1365
+ "line": 1382
}
]
},
@@ -22304,7 +22304,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1403
+ "line": 1420
}
]
},
diff --git a/server/lib/index.js b/server/lib/index.js
index a01026517d..af407fef54 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -144,6 +144,7 @@ export * from './mediaModels.js';
export * from './minimaxH3Memory.js';
export * from './videoContinuity.js';
export * from './videoDisclosure.js';
+export * from './videoDraftDecoders.js';
export * from './videoFinishProfiles.js';
export * from './videoSpeedProfiles.js';
export * from './videoModeProfiles.js';
diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.js
index f39cc89d1d..d0ccba3764 100644
--- a/server/lib/mediaModels.js
+++ b/server/lib/mediaModels.js
@@ -78,6 +78,7 @@ import { ServerError } from './errorHandler.js';
import { applyVideoDisclosures } from './videoDisclosure.js';
import { applyVideoFinishProfiles, sanitizeFinishProfiles } from './videoFinishProfiles.js';
import { applyVideoSpeedProfiles, sanitizeSpeedProfiles } from './videoSpeedProfiles.js';
+import { applyVideoDraftDecoders, sanitizeDraftDecoders } from './videoDraftDecoders.js';
import { applyMiniMaxH3MemoryProfiles, sanitizeMiniMaxH3MemoryProfiles } from './minimaxH3Memory.js';
import { applyVideoSupportedModes } from './videoModeProfiles.js';
import {
@@ -280,8 +281,10 @@ const DEFAULT_REGISTRY = {
// `applyVideoSpeedProfiles` (lib/videoSpeedProfiles.js) is the third such
// decorator: it attaches the shipped `speedProfiles` a model offers, pin-
// guarded on repo AND revision so a re-pointed entry keeps no schedule
- // claim we can't back.
- mlx: applyMiniMaxH3MemoryProfiles(applyVideoSpeedProfiles(applyVideoFinishProfiles(applyVideoDisclosures([
+ // claim we can't back. `applyVideoDraftDecoders`
+ // (lib/videoDraftDecoders.js) is the fourth, attaching the separately
+ // downloaded preview-fidelity decoder a model can render drafts on.
+ mlx: applyMiniMaxH3MemoryProfiles(applyVideoDraftDecoders(applyVideoSpeedProfiles(applyVideoFinishProfiles(applyVideoDisclosures([
// notapalindrome's mlx-video-with-audio runtime — single PyPI package,
// T2V/I2V only, FFLF degrades to last-frame conditioning (one --image arg).
// LTX-2 Unified (the older 42 GB model) was retired in favour of 2.3 —
@@ -530,8 +533,8 @@ const DEFAULT_REGISTRY = {
samplerLocked: true,
samplerNote: 'FastMetal models are DMD2-distilled 3-step models with affine INT8 quantization.',
},
- ])))),
- cuda: applyMiniMaxH3MemoryProfiles(applyVideoSpeedProfiles(applyVideoFinishProfiles(applyVideoDisclosures([
+ ]))))),
+ cuda: applyMiniMaxH3MemoryProfiles(applyVideoDraftDecoders(applyVideoSpeedProfiles(applyVideoFinishProfiles(applyVideoDisclosures([
{ id: 'ltx_video', name: 'LTX-Video 0.9.5 — T2V + I2V (~9.5 GB, auto-downloads)', runtime: 'cuda_video', steps: 25, guidance: 3.0 },
// MiniMax H3 on NVIDIA, through diffusers' MiniMaxH3ModularPipeline —
// the same joint video+audio model the MLX list runs on Apple Silicon, so it
@@ -567,7 +570,7 @@ const DEFAULT_REGISTRY = {
supportsTiling: false,
supportsDisableAudio: false,
},
- ])))),
+ ]))))),
defaultMlx: 'ltx23_distilled_q4',
defaultCuda: 'ltx_video',
},
@@ -1121,12 +1124,19 @@ const normalizeRegistry = (parsed) => {
// hand-edited profile with a NaN step count would otherwise reach the
// picker and spawn a broken render, so it is warned about and stripped.
const withSpeed = sanitizeSpeedProfiles(applyVideoSpeedProfiles(decorated));
+ // applyVideoDraftDecoders + sanitizeDraftDecoders (lib/videoDraftDecoders.js)
+ // are the same arrangement for the preview-fidelity decode (#5423). The
+ // sanitizer matters more here than elsewhere: a hand-edited decoder pointed
+ // at a runtime whose builder emits no draft flags would render on the FULL
+ // decoder while the history record claimed a draft one, so it is warned
+ // about and stripped rather than allowed to make a false claim.
+ const withDraftDecode = sanitizeDraftDecoders(applyVideoDraftDecoders(withSpeed));
// applyMiniMaxH3MemoryProfiles is the load-time twin of migration 317, and
// its sanitizer the sibling of the two above: a hand-edited profile with a
// NaN memory floor would otherwise make every capacity comparison false and
// refuse H3 renders on a machine that can run them, so it is warned about
// and stripped.
- return sanitizeMiniMaxH3MemoryProfiles(applyMiniMaxH3MemoryProfiles(withSpeed));
+ return sanitizeMiniMaxH3MemoryProfiles(applyMiniMaxH3MemoryProfiles(withDraftDecode));
};
const normalizedBuckets = Object.fromEntries(
VIDEO_BUCKETS.map((bucket) => [bucket, videoEntries(bucketResults[bucket].entries, {
diff --git a/server/lib/videoDraftDecoders.js b/server/lib/videoDraftDecoders.js
new file mode 100644
index 0000000000..70cbd631ab
--- /dev/null
+++ b/server/lib/videoDraftDecoders.js
@@ -0,0 +1,393 @@
+/**
+ * Draft VIDEO DECODE for local video runtimes (issue #5423).
+ *
+ * A diffusion video model produces a latent sequence; a VAE decoder turns that
+ * sequence into pixels. On MiniMax H3 the decode is not a rounding error on the
+ * render — it is a full-sequence pass over every latent frame at the output
+ * canvas, and it happens twice over: once at the end of the render, and once
+ * per denoise step for the stepwise preview PortOS publishes to the Video Gen
+ * stage. Most of the time a user spends looking at an H3 render is spent
+ * deciding whether the PROMPT and the COMPOSITION are right, which a
+ * lower-fidelity decode answers just as well as the shipped one.
+ *
+ * A *draft decoder* is a separately downloaded, resource-light replacement for
+ * the model's own video VAE decoder that answers that question faster. This
+ * module is the single source of truth for which ones PortOS ships, and — more
+ * importantly — for the four gates a draft decode has to clear before it can
+ * touch a render:
+ *
+ * 1. **Declaration.** The model entry must carry a `draftDecoder` this
+ * module attached. Nothing is inferred from a runtime or a repo name.
+ * 2. **Runtime capability.** Only a runtime whose arg builder actually emits
+ * the draft-decode flags may declare one, and the INSTALLED runner
+ * checkout must be the revision the asset was verified against. An older
+ * checkout silently ignores unknown argv, which would leave a full-decode
+ * render reporting a draft one.
+ * 3. **Asset readiness.** The weights must already be resolved in the local
+ * HF cache. PortOS never downloads at render time.
+ * 4. **Delivery intent.** A model the finish graph names as a delivery
+ * target ALWAYS decodes on the full decoder, whatever was requested, so a
+ * preview-grade asset can never reach a delivery clip. The client's Finish
+ * flow resets the control to Full for the same reason, so the form and the
+ * server agree about what a delivery render will do.
+ *
+ * Every one of those returns a REASON rather than throwing, and the render
+ * proceeds on the full decoder. Draft decode only ever makes a render cheaper,
+ * so failing it closed with a 400 would turn a convenience into an outage — the
+ * same "degrade, don't reject" contract `speedProfileDeclineReason` uses in
+ * lib/videoSpeedProfiles.js.
+ *
+ * ## Why absence and `'full'` are the same request
+ *
+ * `DRAFT_DECODE_FULL` ('full') is the shipped contract: the model's own
+ * decoder, exactly as every render before this feature existed. It is a named
+ * option so the picker has something to show as selected, and a deliberate
+ * NO-OP — `resolveVideoDraftDecoder` returns `null` for it, so a full-decode
+ * render builds byte-identical spawn args and stamps no extra history field.
+ * Same rule as `'quality'` in lib/videoSpeedProfiles.js and `'stock'` in
+ * lib/videoTextEncoders.js.
+ *
+ * ## Why `VIDEO_DRAFT_DECODERS` currently ships no entry
+ *
+ * The mechanism is declared and wired; the ASSET is not, because none of the
+ * published candidates clears this repo's own bar for a pinned weight (see the
+ * table below for the checklist a candidate must pass). Shipping the gates
+ * first is deliberate: the day an asset is verified, it is one table row plus a
+ * migration, and every fallback path it depends on is already covered by tests.
+ *
+ * Pure module: no I/O, and the one import is a sibling lib predicate.
+ */
+
+import { isDeliveryVideoModel } from './videoFinishProfiles.js';
+
+/**
+ * The implicit "unchanged" decode. Never resolves to an override.
+ */
+export const DRAFT_DECODE_FULL = 'full';
+
+/**
+ * The one non-default decode id. A single named alternative rather than an open
+ * enum: a draft decoder is a property of the MODEL entry (there is at most one
+ * per entry), so the request only ever selects between "the model's decoder"
+ * and "the draft decoder this model declares".
+ */
+export const DRAFT_DECODE_DRAFT = 'draft';
+
+export const DRAFT_DECODE_IDS = Object.freeze([DRAFT_DECODE_FULL, DRAFT_DECODE_DRAFT]);
+
+/**
+ * Runtimes whose arg builder emits the draft-decode flags AND whose helper
+ * loads them. Declared here so a table row can never widen itself onto a runner
+ * that would silently ignore the flags — the failure mode that check exists to
+ * prevent is a render that reports a draft decode it never performed.
+ *
+ * Mirrors the `LTX2_FAMILY_RUNTIMES` guard in lib/videoSpeedProfiles.js.
+ */
+export const DRAFT_DECODE_RUNTIMES = Object.freeze(['minimax_h3']);
+
+/**
+ * Shipped draft decoders, keyed by registry entry id.
+ *
+ * Shape of a row:
+ *
+ * shippedRepo fork-preservation guard — the profile attaches only while
+ * shippedRevision the entry still points at the weights the decoder was
+ * verified against. Guards BOTH, like the speed-profile
+ * table and unlike the finish-profile one: a decoder is
+ * matched to a specific VAE latent contract, which is
+ * revision-sensitive.
+ * decoder.id stable key, persisted in history and submitted by the UI
+ * decoder.label picker label
+ * decoder.description one line under the picker; states the trade honestly
+ * decoder.repo HF repo the asset is downloaded from
+ * decoder.revision exact pinned commit — never a branch
+ * decoder.files explicit file list, never a repo snapshot (same rule as
+ * `requiredWeights` in lib/mediaModels.js). Exactly ONE
+ * entry today: the pinned MLX loader opens
+ * `video_vae/source/model.safetensors` by name rather than
+ * globbing, so a multi-shard decoder has nowhere to go —
+ * validated here so a declaration can never reach a runner
+ * that would reject it mid-render.
+ * decoder.sizeLabel download size, shown before the user commits to it
+ * decoder.runtimeRevision the runner checkout the asset was verified
+ * against; an install on any other revision declines
+ *
+ * CHECKLIST a candidate must pass before it is added here — all four, because a
+ * decoder that fails any of them produces plausible-looking pixels that are
+ * wrong in a way no test can catch:
+ *
+ * - **Key contract.** Its tensor names load into the pinned runner's decoder
+ * module tree under that loader's STRICT check. A quantized repack whose
+ * keys carry `.scales`/`.biases` needs loader support first; it is not a
+ * drop-in.
+ * - **Latent contract.** It decodes the SAME latent space — channel count,
+ * `latents_mean`/`latents_std`, and spatial/temporal compression ratios
+ * identical to the model's own decoder.
+ * - **Publicly verifiable.** The repo, its revision and its own statement of
+ * what the weights are must be readable without a gate, so the pin can be
+ * reviewed rather than taken on trust.
+ * - **Preview-honest.** Its own documentation must not disclaim the use PortOS
+ * puts it to. A checkpoint whose authors say "do not use this as a video
+ * decoder" is not made suitable by only showing its output in a preview.
+ */
+export const VIDEO_DRAFT_DECODERS = Object.freeze({});
+
+const isEntry = (entry) => !!entry && typeof entry === 'object' && typeof entry.id === 'string';
+
+const modelLabel = (model) => model?.name || model?.id || 'This model';
+
+/**
+ * Absence and `'full'` are the same request.
+ */
+export const isFullDecode = (id) => id == null || id === '' || id === DRAFT_DECODE_FULL;
+
+/**
+ * The draft decoder a model declares, or `null`.
+ */
+export const videoDraftDecoder = (model) => {
+ const decoder = model?.draftDecoder;
+ return decoder && typeof decoder === 'object' && typeof decoder.id === 'string' ? decoder : null;
+};
+
+/**
+ * Does this model offer a draft decode at all?
+ */
+export const supportsDraftDecode = (model) => videoDraftDecoder(model) !== null;
+
+/**
+ * Attach `draftDecoder` to shipped entries that don't already carry one. Pure;
+ * returns a new array and never mutates the input entries.
+ *
+ * Preservation contract (identical to `applyVideoSpeedProfiles`):
+ * - `'draftDecoder' in entry` → user/existing value wins, `null`
+ * included (the explicit "no draft decode
+ * on this entry" override).
+ * - entry id not shipped → custom model, left as-is.
+ * - `repo`/`revision` differ → forked or re-pinned weights, left as-is.
+ */
+export const applyVideoDraftDecoders = (list) => {
+ if (!Array.isArray(list)) return list;
+ return list.map((entry) => {
+ if (!isEntry(entry)) return entry;
+ if ('draftDecoder' in entry) return entry;
+ const spec = VIDEO_DRAFT_DECODERS[entry.id];
+ if (!spec) return entry;
+ if (spec.shippedRepo !== null && entry.repo !== spec.shippedRepo) return entry;
+ if (spec.shippedRevision !== null && entry.revision !== spec.shippedRevision) return entry;
+ return { ...entry, draftDecoder: { ...spec.decoder } };
+ });
+};
+
+/**
+ * Validate one platform's video list for draft-decoder problems. Pure — returns
+ * `{ id, reason }` rows (empty when sound). Callers decide whether to
+ * warn-and-strip (load path) or fail (the test that pins the shipped registry).
+ *
+ * Checked, in the order a hand-edit is most likely to break it:
+ * - `draftDecoder` is an object (or absent/null)
+ * - the runtime is one whose builder actually emits the flags
+ * - `id`, `label`, `repo`, `revision` and `runtimeRevision` are non-empty
+ * strings — every one of them reaches argv or an HF cache lookup
+ * - `files` names exactly one non-empty relative path, with no traversal (it is
+ * joined against a cache snapshot root and handed to a child process)
+ */
+export const validateDraftDecoderTable = (list) => {
+ if (!Array.isArray(list)) return [];
+ const problems = [];
+ const fail = (id, reason) => problems.push({ id, reason });
+ const requiredString = (decoder, key) => typeof decoder[key] === 'string' && decoder[key].length > 0;
+ for (const entry of list) {
+ if (!isEntry(entry)) continue;
+ if (!('draftDecoder' in entry) || entry.draftDecoder == null) continue;
+ const decoder = entry.draftDecoder;
+ if (typeof decoder !== 'object' || Array.isArray(decoder)) {
+ fail(entry.id, 'draftDecoder must be an object');
+ continue;
+ }
+ if (!DRAFT_DECODE_RUNTIMES.includes(entry.runtime)) {
+ fail(entry.id, `draftDecoder needs one of the ${DRAFT_DECODE_RUNTIMES.join('/')} runtimes (got "${entry.runtime || 'none'}") — no other builder emits its flags`);
+ continue;
+ }
+ const missing = ['id', 'label', 'repo', 'revision', 'runtimeRevision'].filter((key) => !requiredString(decoder, key));
+ if (missing.length > 0) {
+ fail(entry.id, `draftDecoder is missing required string field(s): ${missing.join(', ')}`);
+ continue;
+ }
+ if (decoder.id === DRAFT_DECODE_FULL) {
+ fail(entry.id, `"${DRAFT_DECODE_FULL}" is the reserved full-decode id`);
+ continue;
+ }
+ const files = decoder.files;
+ if (!Array.isArray(files) || files.length === 0
+ || files.some((f) => typeof f !== 'string' || f.length === 0)) {
+ fail(entry.id, 'draftDecoder.files must be a non-empty array of non-empty strings');
+ continue;
+ }
+ // Mirrors build_draft_decoder_shim in scripts/generate_minimax_h3.py: the
+ // pinned VAE loader reads one named source weight, so a multi-shard
+ // declaration is refused HERE rather than failing minutes into a render.
+ if (files.length !== 1) {
+ fail(entry.id, `draftDecoder.files must name exactly one weight file (the pinned VAE loader reads one); got ${files.length}`);
+ continue;
+ }
+ // These are joined onto an HF snapshot root by the resolver and then handed
+ // to a child process, so an absolute or climbing path is a real escape, not
+ // a style nit.
+ const unsafe = files.find((f) => f.startsWith('/') || f.split('/').includes('..'));
+ if (unsafe) fail(entry.id, `draftDecoder.files entry "${unsafe}" must be a relative path inside the repo`);
+ }
+ return problems;
+};
+
+/**
+ * Load-time guard: strip every invalid `draftDecoder`, logging each problem. A
+ * user-edited (or migration-stale) registry must not be able to offer a decode
+ * this build's runner cannot perform, and must not crash boot
+ * (`loadMediaModels` runs at import time). Returns the input array unchanged
+ * when the table is sound, so the common path allocates nothing.
+ */
+export const sanitizeDraftDecoders = (list) => {
+ const problems = validateDraftDecoderTable(list);
+ if (problems.length === 0) return list;
+ const bad = new Set(problems.map((p) => p.id));
+ for (const p of problems) {
+ console.log(`⚠️ media-models: dropping draftDecoder on "${p.id}" — ${p.reason}`);
+ }
+ return list.map((entry) => {
+ if (!isEntry(entry) || !bad.has(entry.id)) return entry;
+ const { draftDecoder: _dropped, ...rest } = entry;
+ return rest;
+ });
+};
+
+/**
+ * Why a requested draft decode could not be applied — a machine-readable code
+ * plus a sentence the UI/log can show verbatim. `null` when it applies.
+ *
+ * Returned rather than thrown, for the reason in the module header: the render
+ * still proceeds, on the model's own decoder.
+ *
+ * @param {object} args.model resolved video model entry
+ * @param {string} args.decodeId what the request asked for
+ * @param {Array} args.models the platform's video list, so a model
+ * that IS somebody's declared Finish
+ * target counts as a delivery model
+ * @param {string} args.runtimeRevision the INSTALLED runner checkout revision,
+ * or null when it could not be read
+ * @param {boolean} args.assetCached the pinned files resolved in the HF cache
+ */
+export const draftDecodeDeclineReason = ({
+ model, decodeId, models = null, runtimeRevision = null, assetCached = true,
+}) => {
+ if (isFullDecode(decodeId)) return null;
+ // Delivery intent outranks everything, including a model that declares no
+ // decoder at all: the answer to "may this clip be decoded at preview
+ // fidelity?" is no before the question of "with what?" is even asked. The
+ // finish graph is the authority (lib/videoFinishProfiles.js): a model another
+ // entry names as its Finish target is where compositions are DELIVERED, so a
+ // preview-grade decoder has no business on it however the request was phrased.
+ if (isDeliveryVideoModel(model, models)) {
+ return {
+ code: 'DRAFT_DECODE_DELIVERY_MODEL',
+ message: `${modelLabel(model)} is a delivery model — final and Finish renders always decode on the full decoder.`,
+ };
+ }
+ const decoder = videoDraftDecoder(model);
+ if (!decoder || decodeId !== DRAFT_DECODE_DRAFT) {
+ return {
+ code: 'DRAFT_DECODE_UNSUPPORTED',
+ message: `${modelLabel(model)} doesn't offer a draft decode — rendering on its own decoder.`,
+ };
+ }
+ // A checkout at any other revision has a different helper, whose argparse
+ // either rejects the flags outright or (worse, on an older PortOS helper)
+ // ignores them while the render reports a draft decode that never happened.
+ if (runtimeRevision !== decoder.runtimeRevision) {
+ return {
+ code: 'DRAFT_DECODE_RUNTIME_UNSUPPORTED',
+ message: `The installed ${model?.runtime || 'runtime'} checkout can't perform a draft decode. Run Repair in Video Gen to move it to the supported revision.`,
+ };
+ }
+ if (!assetCached) {
+ return {
+ code: 'DRAFT_DECODE_ASSET_NOT_CACHED',
+ message: `The ${decoder.label} draft decoder isn't downloaded. Download it in Video Gen to render previews on it.`,
+ };
+ }
+ return null;
+};
+
+/**
+ * Resolve the draft decoder a render should actually use.
+ *
+ * Returns `null` whenever anything at all declines — the caller then leaves the
+ * decode exactly where it was, and the spawn args stay byte-identical to a
+ * pre-feature render.
+ *
+ * @returns {{ id, label, repo, revision, files, runtimeRevision } | null}
+ */
+export const resolveVideoDraftDecoder = (args) => {
+ // Checked BEFORE the decline reason, not after: a full decode has no reason
+ // to report (nothing was declined), so a resolver that only asked
+ // `draftDecodeDeclineReason` would fall through and hand a decoder to the
+ // request that explicitly asked for the model's own one.
+ if (isFullDecode(args?.decodeId)) return null;
+ if (draftDecodeDeclineReason(args)) return null;
+ const decoder = videoDraftDecoder(args?.model);
+ if (!decoder) return null;
+ return {
+ id: decoder.id,
+ label: decoder.label,
+ repo: decoder.repo,
+ revision: decoder.revision,
+ files: [...decoder.files],
+ runtimeRevision: decoder.runtimeRevision,
+ };
+};
+
+/**
+ * The decode options to put in front of the user for one model, in picker
+ * order. EMPTY for a model with no draft decoder, so the client renders no
+ * control rather than a one-entry select — the same presentation rule
+ * `publicVideoTextEncoderOptions` follows. The full-decode entry is included
+ * only when there is a real second choice.
+ */
+export const publicVideoDraftDecodeOptions = (model) => {
+ const decoder = videoDraftDecoder(model);
+ if (!decoder) return [];
+ return [
+ {
+ id: DRAFT_DECODE_FULL,
+ label: 'Full decode',
+ description: "The model's own decoder. Delivery quality, and what every final render uses.",
+ },
+ {
+ id: decoder.id,
+ label: decoder.label,
+ description: decoder.description || 'A resource-light decoder for judging prompt and composition. Never used for a final render.',
+ repo: decoder.repo,
+ revision: decoder.revision,
+ sizeLabel: decoder.sizeLabel || null,
+ },
+ ];
+};
+
+/**
+ * Every downloadable draft-decoder asset across a video model list, de-duped by
+ * repo+revision. Used by the Video Gen download/repair surface, which needs the
+ * targets without caring which entry declared them.
+ */
+export const downloadableVideoDraftDecoders = (list) => {
+ if (!Array.isArray(list)) return [];
+ const seen = new Set();
+ const out = [];
+ for (const entry of list) {
+ const decoder = videoDraftDecoder(entry);
+ if (!decoder) continue;
+ const key = `${decoder.repo}@${decoder.revision}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push({ ...decoder, modelId: entry.id });
+ }
+ return out;
+};
diff --git a/server/lib/videoDraftDecoders.test.js b/server/lib/videoDraftDecoders.test.js
new file mode 100644
index 0000000000..ddc7166626
--- /dev/null
+++ b/server/lib/videoDraftDecoders.test.js
@@ -0,0 +1,294 @@
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import {
+ DRAFT_DECODE_FULL,
+ DRAFT_DECODE_DRAFT,
+ DRAFT_DECODE_RUNTIMES,
+ VIDEO_DRAFT_DECODERS,
+ isFullDecode,
+ supportsDraftDecode,
+ applyVideoDraftDecoders,
+ validateDraftDecoderTable,
+ sanitizeDraftDecoders,
+ draftDecodeDeclineReason,
+ resolveVideoDraftDecoder,
+ publicVideoDraftDecodeOptions,
+ downloadableVideoDraftDecoders,
+} from './videoDraftDecoders.js';
+
+const RUNTIME_REV = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
+
+const decoder = (over = {}) => ({
+ id: DRAFT_DECODE_DRAFT,
+ label: 'Draft decoder',
+ description: 'Preview fidelity.',
+ repo: 'example/draft-decoder',
+ revision: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
+ files: ['decoder.safetensors'],
+ sizeLabel: '~1 GB',
+ runtimeRevision: RUNTIME_REV,
+ ...over,
+});
+
+const model = (over = {}) => ({
+ id: 'example_h3',
+ name: 'Example H3',
+ runtime: DRAFT_DECODE_RUNTIMES[0],
+ repo: 'example/h3',
+ revision: 'cccccccccccccccccccccccccccccccccccccccc',
+ draftDecoder: decoder(),
+ ...over,
+});
+
+const applies = (over = {}) => ({
+ model: model(),
+ decodeId: DRAFT_DECODE_DRAFT,
+ runtimeRevision: RUNTIME_REV,
+ assetCached: true,
+ ...over,
+});
+
+afterEach(() => { vi.restoreAllMocks(); });
+
+describe('the shipped table', () => {
+ // Guards the module header's own claim: no asset has cleared the
+ // verification checklist yet, so a row added without updating that header
+ // (and without a migration) fails here rather than shipping an unverified pin.
+ it('declares no decoder until an asset passes the checklist', () => {
+ expect(Object.keys(VIDEO_DRAFT_DECODERS)).toEqual([]);
+ });
+});
+
+describe('isFullDecode', () => {
+ // Absence, '' and 'full' are ONE request. If they ever diverged, an omitted
+ // field would start resolving a decoder and a pre-feature render's args
+ // would stop being byte-identical.
+ it.each([undefined, null, '', DRAFT_DECODE_FULL])('reads %p as a full decode', (id) => {
+ expect(isFullDecode(id)).toBe(true);
+ });
+
+ it('does not read the draft id as full', () => {
+ expect(isFullDecode(DRAFT_DECODE_DRAFT)).toBe(false);
+ });
+});
+
+describe('applyVideoDraftDecoders', () => {
+ const spec = { shippedRepo: 'example/h3', shippedRevision: 'rev-1', decoder: decoder() };
+ const withTable = (list, table) => {
+ // The shipped table is frozen and empty by design, so the backfill's
+ // preservation guards are exercised through validate/sanitize + this
+ // hand-rolled equivalent rather than by mutating module state.
+ const applyOne = (entry) => {
+ if ('draftDecoder' in entry) return entry;
+ const found = table[entry.id];
+ if (!found) return entry;
+ if (found.shippedRepo !== null && entry.repo !== found.shippedRepo) return entry;
+ if (found.shippedRevision !== null && entry.revision !== found.shippedRevision) return entry;
+ return { ...entry, draftDecoder: { ...found.decoder } };
+ };
+ return list.map(applyOne);
+ };
+
+ it('is a no-op against the shipped (empty) table', () => {
+ const list = [{ id: 'example_h3', repo: 'example/h3', revision: 'rev-1' }];
+ expect(applyVideoDraftDecoders(list)).toEqual(list);
+ });
+
+ it('leaves a non-array input alone', () => {
+ expect(applyVideoDraftDecoders(null)).toBeNull();
+ });
+
+ it.each([
+ ['a re-pointed repo', { id: 'example_h3', repo: 'fork/h3', revision: 'rev-1' }],
+ ['a re-pinned revision', { id: 'example_h3', repo: 'example/h3', revision: 'rev-2' }],
+ ['an unshipped id', { id: 'custom', repo: 'example/h3', revision: 'rev-1' }],
+ ])('does not attach a decoder to %s', (_label, entry) => {
+ expect(withTable([entry], { example_h3: spec })[0].draftDecoder).toBeUndefined();
+ });
+
+ it('preserves an explicit null override rather than backfilling over it', () => {
+ const entry = { id: 'example_h3', repo: 'example/h3', revision: 'rev-1', draftDecoder: null };
+ expect(withTable([entry], { example_h3: spec })[0].draftDecoder).toBeNull();
+ });
+});
+
+describe('validateDraftDecoderTable', () => {
+ const problem = (entry) => validateDraftDecoderTable([entry])[0]?.reason || null;
+
+ it('accepts a well-formed declaration', () => {
+ expect(validateDraftDecoderTable([model()])).toEqual([]);
+ });
+
+ it('accepts an entry with no declaration at all', () => {
+ expect(validateDraftDecoderTable([{ id: 'plain', runtime: 'ltx2' }])).toEqual([]);
+ });
+
+ // The load-bearing guard: a decoder on a runtime whose arg builder emits no
+ // draft flags would render on the FULL decoder while history claimed a draft
+ // one. That false claim is the whole reason the gate chain exists.
+ it('refuses a declaration on a runtime that emits no draft flags', () => {
+ expect(problem(model({ runtime: 'ltx2' }))).toMatch(/no other builder emits its flags/);
+ });
+
+ it.each(['id', 'label', 'repo', 'revision', 'runtimeRevision'])('refuses a missing %s', (key) => {
+ expect(problem(model({ draftDecoder: decoder({ [key]: undefined }) }))).toMatch(new RegExp(key));
+ });
+
+ it('refuses the reserved full-decode id', () => {
+ expect(problem(model({ draftDecoder: decoder({ id: DRAFT_DECODE_FULL }) }))).toMatch(/reserved/);
+ });
+
+ it.each([
+ ['an empty file list', []],
+ ['a non-array file list', 'decoder.safetensors'],
+ ])('refuses %s', (_label, files) => {
+ expect(problem(model({ draftDecoder: decoder({ files }) }))).toBeTruthy();
+ });
+
+ // Mirrors build_draft_decoder_shim in the runner: the pinned VAE loader opens
+ // one named source weight, so a multi-shard declaration must be refused at
+ // load rather than failing minutes into a render.
+ it('refuses a multi-shard declaration', () => {
+ expect(problem(model({ draftDecoder: decoder({ files: ['a.safetensors', 'b.safetensors'] }) })))
+ .toMatch(/exactly one weight file/);
+ });
+
+ // These are joined onto an HF snapshot root and handed to a child process,
+ // so a climbing or absolute path is a real escape rather than a style nit.
+ it.each(['/etc/passwd', '../../secret.safetensors'])('refuses the escaping path %s', (path) => {
+ expect(problem(model({ draftDecoder: decoder({ files: [path] }) }))).toMatch(/relative path/);
+ });
+});
+
+describe('sanitizeDraftDecoders', () => {
+ it('returns the same array reference when the table is sound', () => {
+ const list = [model()];
+ expect(sanitizeDraftDecoders(list)).toBe(list);
+ });
+
+ it('strips an invalid declaration and warns, leaving the rest of the entry intact', () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ const [entry] = sanitizeDraftDecoders([model({ runtime: 'ltx2' })]);
+ expect(entry.draftDecoder).toBeUndefined();
+ expect(entry.id).toBe('example_h3');
+ expect(console.log).toHaveBeenCalledWith(expect.stringContaining('dropping draftDecoder'));
+ });
+});
+
+describe('draftDecodeDeclineReason', () => {
+ it('accepts a request that clears every gate', () => {
+ expect(draftDecodeDeclineReason(applies())).toBeNull();
+ });
+
+ it('never declines a full decode, even on a model with no decoder', () => {
+ expect(draftDecodeDeclineReason({ model: model({ draftDecoder: undefined }), decodeId: DRAFT_DECODE_FULL })).toBeNull();
+ });
+
+ // The issue's central safety property: a preview-fidelity asset must never
+ // reach a delivery clip, however the request was phrased.
+ it('declines a model that is another entry\'s declared Finish target', () => {
+ const delivery = model({ id: 'delivery' });
+ const list = [{ id: 'draft_model', finishModelId: 'delivery' }, delivery];
+ expect(draftDecodeDeclineReason(applies({ model: delivery, models: list })).code)
+ .toBe('DRAFT_DECODE_DELIVERY_MODEL');
+ });
+
+ it('allows a draft model that merely NAMES a Finish target', () => {
+ const draft = model({ id: 'draft_model', finishModelId: 'delivery' });
+ const list = [draft, { id: 'delivery' }];
+ expect(draftDecodeDeclineReason(applies({ model: draft, models: list }))).toBeNull();
+ });
+
+ it('declines a model that declares no draft decoder', () => {
+ expect(draftDecodeDeclineReason(applies({ model: model({ draftDecoder: undefined }) })).code)
+ .toBe('DRAFT_DECODE_UNSUPPORTED');
+ });
+
+ // An older checkout has a helper that ignores the flags rather than
+ // rejecting them, so this is the gate that stops a full decode from being
+ // recorded as a draft one.
+ it.each([
+ ['an older checkout', 'dddddddddddddddddddddddddddddddddddddddd'],
+ ['an unreadable checkout', null],
+ ])('declines %s', (_label, runtimeRevision) => {
+ expect(draftDecodeDeclineReason(applies({ runtimeRevision })).code)
+ .toBe('DRAFT_DECODE_RUNTIME_UNSUPPORTED');
+ });
+
+ it('declines an asset that is not downloaded', () => {
+ expect(draftDecodeDeclineReason(applies({ assetCached: false })).code)
+ .toBe('DRAFT_DECODE_ASSET_NOT_CACHED');
+ });
+
+ // Delivery intent is checked BEFORE the decoder is even looked up, so a
+ // delivery model with no decoder reads as "delivery", never as "unsupported"
+ // — the reason the user is shown has to be the real one.
+ it('reports delivery intent ahead of every other reason', () => {
+ const delivery = model({ id: 'delivery', draftDecoder: undefined });
+ expect(draftDecodeDeclineReason(applies({
+ model: delivery,
+ models: [{ id: 'draft_model', finishModelId: 'delivery' }, delivery],
+ runtimeRevision: null,
+ assetCached: false,
+ })).code).toBe('DRAFT_DECODE_DELIVERY_MODEL');
+ });
+});
+
+describe('resolveVideoDraftDecoder', () => {
+ it('returns the concrete asset when every gate passes', () => {
+ expect(resolveVideoDraftDecoder(applies())).toEqual({
+ id: DRAFT_DECODE_DRAFT,
+ label: 'Draft decoder',
+ repo: 'example/draft-decoder',
+ revision: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
+ files: ['decoder.safetensors'],
+ runtimeRevision: RUNTIME_REV,
+ });
+ });
+
+ it('copies the file list rather than aliasing the registry entry', () => {
+ const entry = model();
+ resolveVideoDraftDecoder(applies({ model: entry })).files.push('mutated');
+ expect(entry.draftDecoder.files).toEqual(['decoder.safetensors']);
+ });
+
+ it.each([
+ ['a full decode', { decodeId: DRAFT_DECODE_FULL }],
+ ['a delivery model', {
+ model: model({ id: 'delivery' }),
+ models: [{ id: 'draft_model', finishModelId: 'delivery' }],
+ }],
+ ['an old runtime', { runtimeRevision: 'other' }],
+ ['a missing download', { assetCached: false }],
+ ])('resolves null for %s', (_label, over) => {
+ expect(resolveVideoDraftDecoder(applies(over))).toBeNull();
+ });
+});
+
+describe('publicVideoDraftDecodeOptions', () => {
+ // Empty is the signal to render NO control. A one-entry select would imply a
+ // choice the model does not have.
+ it('is empty for a model with no draft decoder', () => {
+ expect(publicVideoDraftDecodeOptions(model({ draftDecoder: undefined }))).toEqual([]);
+ expect(supportsDraftDecode(model({ draftDecoder: undefined }))).toBe(false);
+ });
+
+ it('offers full first, then the declared decoder, without leaking the file list', () => {
+ const options = publicVideoDraftDecodeOptions(model());
+ expect(options.map((o) => o.id)).toEqual([DRAFT_DECODE_FULL, DRAFT_DECODE_DRAFT]);
+ expect(options[1]).toMatchObject({ repo: 'example/draft-decoder', sizeLabel: '~1 GB' });
+ expect(options[1].files).toBeUndefined();
+ });
+});
+
+describe('downloadableVideoDraftDecoders', () => {
+ it('de-dupes assets shared by two entries', () => {
+ const list = [model(), model({ id: 'example_h3_alt' })];
+ const targets = downloadableVideoDraftDecoders(list);
+ expect(targets).toHaveLength(1);
+ expect(targets[0].modelId).toBe('example_h3');
+ });
+
+ it('skips entries with no declaration', () => {
+ expect(downloadableVideoDraftDecoders([{ id: 'plain' }])).toEqual([]);
+ });
+});
diff --git a/server/lib/videoFinishProfiles.js b/server/lib/videoFinishProfiles.js
index bc23e8baf2..8a9ba8dc34 100644
--- a/server/lib/videoFinishProfiles.js
+++ b/server/lib/videoFinishProfiles.js
@@ -168,3 +168,22 @@ export const finishTargetForModel = (model, availableModels) => {
if (!Array.isArray(availableModels)) return null;
return availableModels.find((m) => m?.id === targetId) || null;
};
+
+/**
+ * True when `model` exists in the graph as somebody's DELIVERY target — i.e.
+ * another entry names it as its `finishModelId`.
+ *
+ * That is a stronger statement than "this model is slow": a delivery model is
+ * declared as the place a composition is taken once it is settled, so anything
+ * that trades fidelity for speed (issue #5423's draft decode) has no business
+ * on it, however the request was phrased. Kept here rather than in the consumer
+ * so the finish graph stays the single authority on which end of a pair a model
+ * sits on.
+ *
+ * @param {object|null|undefined} model
+ * @param {Array<object>} list - the platform's video model entries
+ */
+export const isDeliveryVideoModel = (model, list) => {
+ if (!isEntry(model) || !Array.isArray(list)) return false;
+ return list.some((entry) => isEntry(entry) && entry.finishModelId === model.id);
+};
diff --git a/server/lib/videoFinishProfiles.test.js b/server/lib/videoFinishProfiles.test.js
index b0bcfd9227..2d13e59ad2 100644
--- a/server/lib/videoFinishProfiles.test.js
+++ b/server/lib/videoFinishProfiles.test.js
@@ -5,6 +5,7 @@ import {
validateFinishProfileGraph,
sanitizeFinishProfiles,
finishTargetForModel,
+ isDeliveryVideoModel,
} from './videoFinishProfiles.js';
import { readFileSync } from 'fs';
import { join, dirname } from 'path';
@@ -144,3 +145,31 @@ describe('finishTargetForModel', () => {
expect(finishTargetForModel(null, [full()])).toBeNull();
});
});
+
+// Which END of a pair a model sits on (#5423). A delivery model is declared as
+// the place a settled composition is taken, so anything that trades fidelity
+// for speed must refuse to run on it — the finish graph is the only authority
+// that can answer that, which is why the predicate lives here.
+describe('isDeliveryVideoModel', () => {
+ const list = [draft(), full()];
+
+ it('is true for a model another entry names as its Finish target', () => {
+ expect(isDeliveryVideoModel(full(), list)).toBe(true);
+ });
+
+ it('is false for the draft that names it', () => {
+ expect(isDeliveryVideoModel(draft(), list)).toBe(false);
+ });
+
+ it('is false for a model nobody finishes into', () => {
+ expect(isDeliveryVideoModel({ id: 'standalone' }, list)).toBe(false);
+ });
+
+ it.each([
+ ['a missing model', null, list],
+ ['a model with no id', { runtime: 'wan22' }, list],
+ ['a missing list', full(), null],
+ ])('is false for %s', (_label, model, entries) => {
+ expect(isDeliveryVideoModel(model, entries)).toBe(false);
+ });
+});
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 18f6b3d366..eeb3694832 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -53,6 +53,7 @@ import {
isStockTextEncoder,
} from '../lib/videoTextEncoders.js';
import { isDefaultSpeedProfile } from '../lib/videoSpeedProfiles.js';
+import { DRAFT_DECODE_IDS, isFullDecode } from '../lib/videoDraftDecoders.js';
import {
inspectModelCache, verifyModelCache, repairModelCache, repairCachedFile,
verifyCachedRepoFiles, repairCachedRepoFiles, summarizeVerify, aggregateVerifies,
@@ -207,6 +208,14 @@ export const LOCAL_ONLY_VIDEO_PARAMS = Object.freeze({
// model's own sampler with the reason logged, because a knob that only makes
// a render faster must degrade rather than 400 a submitted job.
speedProfileId: z.string().min(1).max(64).optional(),
+ // Decode this render's latents on the model's own decoder or on its declared
+ // preview-fidelity one (lib/videoDraftDecoders.js). A closed enum, unlike the
+ // two ids above, because there is at most ONE draft decoder per model — the
+ // request selects between "the model's decoder" and "the draft decoder this
+ // model declares", not from a per-model list. Never rejected downstream
+ // either: an unsupported model, an old runner checkout, a missing download or
+ // a delivery render all fall back to the full decoder with the reason logged.
+ draftDecode: z.enum(DRAFT_DECODE_IDS).optional(),
});
const generateBodySchema = z.object({
@@ -1126,6 +1135,10 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
// it would leave a resumed/remixed render carrying a knob that never
// applied and differing from what the service records in history.
...(isDefaultSpeedProfile(body.speedProfileId) ? {} : { speedProfileId: body.speedProfileId }),
+ // Same "absence IS the default" rule again: an explicit 'full' decode is
+ // identical to omitting the field, so persisting it would leave a
+ // resumed/remixed render carrying a knob that never applied.
+ ...(isFullDecode(body.draftDecode) ? {} : { draftDecode: body.draftDecode }),
disableAudio: body.disableAudio === true || body.disableAudio === 'true',
sourceImagePath,
audioFilePath,
@@ -1199,6 +1212,10 @@ const ACTIVE_JOB_PARAM_FIELDS = [
// Likewise a registry id — the sampler schedule the in-flight render picked,
// so a reloading page restores the picker instead of snapping back to Quality.
'speedProfileId',
+ // Likewise a closed enum with no path — the decode the in-flight render
+ // picked, so a reloading page restores the control instead of snapping back
+ // to Full.
+ 'draftDecode',
'audioStartSec',
// Grok jobs (#2859 phase 2): the semantic t2v/i2v mode ('mode' holds the
// 'grok' discriminator for them) and the clip duration — both plain
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index 7d1d0607c9..257f71360a 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -762,6 +762,7 @@ describe('videoGen routes', () => {
// assertion can't cover either. Their own cases are below.
'textEncoderId',
'speedProfileId',
+ 'draftDecode',
]);
const { getSettings } = await import('../services/settings.js');
getSettings.mockResolvedValueOnce({ imageGen: grokReady, videoGen: { mode: 'grok' } });
@@ -777,6 +778,37 @@ describe('videoGen routes', () => {
// (an unswapped 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.
+ // Same contract for the decode knob (#5423): grok has no decoder choice, so
+ // naming one keeps the render local — and the default value is dropped from
+ // persisted params so a full-decode render's job params stay byte-identical
+ // to a request that never sent the field.
+ it('keeps draftDecode on the local path under a grok pin, without persisting the full value', 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', draftDecode: 'full' });
+ expect(r.status).toBe(200);
+ const [call] = mediaJobQueue.enqueueJob.mock.calls;
+ expect(call[0].params.mode).not.toBe('grok');
+ expect(call[0].params.draftDecode).toBeUndefined();
+ });
+
+ it('persists a non-default draftDecode on the local path', 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', draftDecode: 'draft' });
+ expect(r.status).toBe(200);
+ const [call] = mediaJobQueue.enqueueJob.mock.calls;
+ expect(call[0].params.draftDecode).toBe('draft');
+ });
+
+ // A closed enum, unlike textEncoderId/speedProfileId — there is at most one
+ // draft decoder per model, so an unknown value is a client bug, not a
+ // per-model option the route can't enumerate.
+ it('rejects an unknown draftDecode value', async () => {
+ const r = await request(app).post('/api/video-gen/').send({ prompt: 'a fox', draftDecode: 'turbo' });
+ expect(r.status).toBe(400);
+ });
+
it('keeps textEncoderId on the local path under a grok pin, without persisting the stock value', async () => {
const { getSettings } = await import('../services/settings.js');
getSettings.mockResolvedValueOnce({ imageGen: grokReady, videoGen: { mode: 'grok' } });
diff --git a/server/services/videoGen/generateVideo.js b/server/services/videoGen/generateVideo.js
index c033f39ed9..57edc38a49 100644
--- a/server/services/videoGen/generateVideo.js
+++ b/server/services/videoGen/generateVideo.js
@@ -49,6 +49,8 @@ import {
resolveByovRuntimeLoraCapable,
modelAnchorsLastFrame,
routesToWindowsHelper,
+ byovRuntimeExpectedRevision,
+ isByovRuntimeCurrent,
} from './runtimes.js';
import { loadHistory, saveHistory, mutateVideoHistory, getHistoryItem } from './history.js';
import { VIDEO_MODE_GATED_RUNTIMES } from './modeContract.js';
@@ -67,6 +69,12 @@ import {
resolveVideoSpeedProfile, speedProfileDeclineReason, resolveVideoSampler,
inferEffectiveVideoMode,
} from '../../lib/videoSpeedProfiles.js';
+import {
+ isFullDecode,
+ publicVideoDraftDecodeOptions,
+ draftDecodeDeclineReason,
+ resolveVideoDraftDecoder,
+} from '../../lib/videoDraftDecoders.js';
// Re-export the extracted runtime + history surface so existing deep imports
// (`from '../videoGen/local.js'`) keep resolving every symbol they used to.
export * from './runtimes.js';
@@ -119,6 +127,10 @@ const decorateVideoModel = (m) => (m ? {
lastFrameAnchored: modelAnchorsLastFrame(m),
runtimeLoraCapable: byovRuntimeLoraCapable(m.runtime),
textEncoderOptions: publicVideoTextEncoderOptions(m),
+ // The preview-fidelity decode choices this entry offers
+ // (lib/videoDraftDecoders.js). Empty for every model that declares no draft
+ // decoder, so the client renders no control instead of a one-entry select.
+ draftDecodeOptions: publicVideoDraftDecodeOptions(m),
} : m);
export const resolveVideoModel = (modelId) =>
@@ -128,7 +140,7 @@ export const listVideoModels = () => getVideoModels().map(decorateVideoModel);
export const defaultVideoModelId = (capabilities) => getDefaultVideoModelId(capabilities);
-export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId, 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, speedProfileId = null, visualConditioning = null, hidden = false, jobId: providedJobId = null }) {
+export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId, 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, speedProfileId = null, draftDecode = null, visualConditioning = 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
@@ -411,6 +423,48 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
if (speedProfileDeclined) {
console.log(`⚠️ Speed profile declined [${jobId.slice(0, 8)}] ${speedProfileDeclined.code}: ${speedProfileDeclined.message}`);
}
+ // Preview-fidelity video decode (#5423). Every gate lives in
+ // lib/videoDraftDecoders.js and RETURNS its reason; the render always
+ // proceeds, on the full decoder, because a decode substitution only ever
+ // makes a render cheaper. Resolved here rather than in the arg builder for
+ // the same reason the substituted conditioner is: a missing download has to
+ // be discovered before any GPU work, and the decision has to be recorded on
+ // the history row.
+ //
+ // Two gates need I/O and so cannot live in the pure module: whether the
+ // installed runner checkout is the revision the asset was verified against
+ // (an older one ignores the flags, which would let a full decode report
+ // itself as a draft), and whether the pinned files are actually in the HF
+ // cache. Both are only probed when a draft decode was requested AND the model
+ // declares one, so a full-decode render costs nothing extra.
+ let draftDecoder = null;
+ if (!isFullDecode(draftDecode)) {
+ const declared = model.draftDecoder;
+ const runtimeRevision = (declared && await isByovRuntimeCurrent(model.runtime))
+ ? byovRuntimeExpectedRevision(model.runtime)
+ : null;
+ // Only probed once the cheaper gates have passed — a model with no
+ // declaration, or a checkout at the wrong revision, never touches the cache.
+ const decoderPaths = (declared && runtimeRevision === declared.runtimeRevision)
+ ? await findCachedRepoFiles(declared.repo, declared.files, { revision: declared.revision })
+ : null;
+ const gateArgs = {
+ model,
+ models: getVideoModels(),
+ decodeId: draftDecode,
+ runtimeRevision,
+ assetCached: Array.isArray(decoderPaths) && decoderPaths.length > 0,
+ };
+ const resolved = resolveVideoDraftDecoder(gateArgs);
+ if (resolved) {
+ draftDecoder = { ...resolved, paths: decoderPaths };
+ console.log(`🩻 Draft decode "${resolved.id}" [${jobId.slice(0, 8)}] via ${resolved.label}`);
+ } else {
+ const declined = draftDecodeDeclineReason(gateArgs);
+ console.log(`⚠️ Draft decode declined [${jobId.slice(0, 8)}] ${declined?.code || 'UNKNOWN'}: ${declined?.message || 'rendering on the full decoder'}`);
+ }
+ }
+
const sampler = resolveVideoSampler({ model, steps, guidanceScale, speedProfile });
let actualSteps = sampler.steps;
let actualGuidance = sampler.guidance;
@@ -695,6 +749,13 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// What the runner ACTUALLY managed to apply is stamped separately by
// finalizeGeneratedVideo from the child's SPEEDPROFILE: report.
...(speedProfile ? { speedProfileId: speedProfile.id, stage2Steps: actualStage2Steps } : {}),
+ // Preview-fidelity decode (#5423). Recorded as the REQUESTED id, so a Remix
+ // round-trips the decode the user picked, and so the lightbox can say which
+ // decoder produced the pixels being judged. Absent on a full decode, which
+ // keeps every pre-feature history row byte-identical — and, because a
+ // declined request never sets it, a record can never claim a draft decode
+ // the render did not perform.
+ ...(draftDecoder ? { draftDecode: draftDecoder.id } : {}),
// IC-LoRA remix settings, stamped so the lightbox Remix flow can round-trip
// them. The reference clip is recorded by BASENAME (not the absolute
// staging path) — history is user-facing and a durable upload path is both
@@ -740,7 +801,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, i2vReferenceMode: effectiveReferenceMode, textEncoderRepo: actualTextEncoderRepo, textEncoder: resolvedTextEncoder, outputPath, previewDir: stepwiseDir, loras: resolvedLoras, icReferencePaths: resolvedIcReferencePaths, icLoraWeightPath, icStrength: actualIcStrength, icAttentionStrength: actualIcAttentionStrength, icSkipStage2, speedProfile }));
+ ({ 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, speedProfile, draftDecoder }));
} catch (err) {
job.status = 'error';
const reason = err.message || 'Failed to build video gen args';
diff --git a/server/services/videoGen/generateVideoHelpers.js b/server/services/videoGen/generateVideoHelpers.js
index 451544267b..e3a04d5eee 100644
--- a/server/services/videoGen/generateVideoHelpers.js
+++ b/server/services/videoGen/generateVideoHelpers.js
@@ -155,6 +155,25 @@ export function makeVideoGenLineHandler({ job, jobId, pythonNoiseRe }) {
return false;
}
}
+ // What the runner ACTUALLY decoded with (DRAFTDECODE:<json> — see
+ // scripts/generate_minimax_h3.py). PortOS gates the substitution
+ // declaratively, but only the child can see whether the pinned decoder
+ // module tree accepts the asset's tensors; a load that fails there falls
+ // back to the model's own decoder and reports `applied: false` with a
+ // reason. Stamped on the job so finalizeGeneratedVideo persists it, which is
+ // what keeps a full decode from reading back as a draft one.
+ if (line.startsWith('DRAFTDECODE:')) {
+ try {
+ const applied = JSON.parse(line.slice('DRAFTDECODE:'.length));
+ job.draftDecode = applied;
+ console.log(`🩻 draft decode [${jobId.slice(0, 8)}] ${applied?.id || '?'} — ${applied?.applied ? 'applied' : `fell back to the full decoder (${applied?.reason || 'unknown'})`}`);
+ return true;
+ } catch {
+ // Malformed payload — fall through to raw-logging so the broken line
+ // is visible rather than silently swallowed (same as RUNTIME: above).
+ return false;
+ }
+ }
// Heartbeat for the queue's idle watchdog (see imageGen/local.js).
videoGenEvents.emit('activity', { generationId: jobId });
if (line.startsWith('STATUS:')) {
@@ -569,6 +588,12 @@ export async function finalizeGeneratedVideo({ job, jobId, outputPath, filename,
// as degraded instead of as a full speed claim. Absent on every quality
// render and on runners that don't report one.
...(job.speedProfile ? { speedProfileApplied: job.speedProfile } : {}),
+ // Whether the draft decoder actually decoded this clip (#5423).
+ // `meta.draftDecode` above is the REQUEST that survived every server-side
+ // gate; this is the outcome, so a render whose decoder failed to load
+ // reads back as a full decode instead of claiming a draft one. Absent on
+ // every full-decode render and on runners that don't report one.
+ ...(job.draftDecode ? { draftDecodeApplied: job.draftDecode } : {}),
});
return history;
});
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index c9121fa4e3..f7ca117d3c 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -300,12 +300,30 @@ vi.mock('../../lib/frameQuality.js', async (importOriginal) => ({
// `capable` is the settled probe verdict. They are separate so a test can pin
// the cold-cache case, where the two legitimately disagree.
const h3LoraState = vi.hoisted(() => ({ capable: false, cached: null }));
-vi.mock('./runtimes.js', async (importOriginal) => ({
- ...await importOriginal(),
- byovRuntimeLoraCapable: vi.fn((runtime) => runtime === 'minimax_h3'
- && (h3LoraState.cached ?? h3LoraState.capable)),
- resolveByovRuntimeLoraCapable: vi.fn(async (runtime) => runtime === 'minimax_h3' && h3LoraState.capable),
-}));
+// Which revision the installed BYOV checkout is at. Really a spawned `git`
+// probe; stubbed here so the draft-decode capability gate (#5423) can be driven
+// to both verdicts. `current: null` means "leave the real probe alone", which
+// is what every pre-existing test in this file wants.
+const byovRevisionState = vi.hoisted(() => ({ current: null, expectedRevision: null }));
+vi.mock('./runtimes.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ byovRuntimeLoraCapable: vi.fn((runtime) => runtime === 'minimax_h3'
+ && (h3LoraState.cached ?? h3LoraState.capable)),
+ resolveByovRuntimeLoraCapable: vi.fn(async (runtime) => runtime === 'minimax_h3' && h3LoraState.capable),
+ isByovRuntimeCurrent: vi.fn(async (runtime) => (
+ byovRevisionState.current === null
+ ? actual.isByovRuntimeCurrent(runtime)
+ : byovRevisionState.current
+ )),
+ byovRuntimeExpectedRevision: vi.fn((runtime) => (
+ byovRevisionState.expectedRevision === null
+ ? actual.byovRuntimeExpectedRevision(runtime)
+ : byovRevisionState.expectedRevision
+ )),
+ };
+});
// LoRA key-layout gate (resolveVideoLoras). `null` = undetermined, which is
// the permissive default so the pre-existing LoRA-threading tests below still
@@ -412,6 +430,8 @@ beforeEach(async () => {
});
afterEach(() => {
+ byovRevisionState.current = null;
+ byovRevisionState.expectedRevision = null;
settingsState.acceptedModelTerms = [];
fsState.missOnce = [];
fsState.candidateCount = null;
@@ -5239,3 +5259,152 @@ describe('generateVideo — i2v reference mode (#4874)', () => {
})).rejects.toMatchObject({ status: 400, code: 'I2V_REFERENCE_MODE_UNKNOWN' });
});
});
+
+// Preview-fidelity decode (#5423). The whole point of the feature is that a
+// draft decoder can only ever REDUCE the cost of judging a composition — so
+// every gate that fails has to fall back to the model's own decoder silently,
+// and the history record must never claim a decode that did not happen.
+describe('generateVideo — MiniMax H3 draft decode (#5423)', () => {
+ const DECODER_RUNTIME_REV = 'fcd9e9b79a1d6018d91ac477c0968de1fa067e49';
+ const DECODER = Object.freeze({
+ id: 'draft',
+ label: 'Draft decoder',
+ description: 'Preview fidelity.',
+ repo: 'example/h3-draft-decoder',
+ revision: 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
+ files: ['decoder.safetensors'],
+ runtimeRevision: DECODER_RUNTIME_REV,
+ });
+
+ let baseCatalog = null;
+
+ // The shipped table is deliberately EMPTY (no asset has passed the
+ // verification checklist), so every gate below is exercised against a
+ // declaration injected onto the H3 entry for one test at a time.
+ const declareDecoder = async () => {
+ const { getVideoModels } = await import('../../lib/mediaModels.js');
+ const mock = vi.mocked(getVideoModels);
+ baseCatalog = baseCatalog || mock.getMockImplementation();
+ mock.mockImplementation(() => baseCatalog().map((model) => (
+ model.id === 'minimax_h3_8bit' ? { ...model, draftDecoder: DECODER } : model
+ )));
+ };
+
+ afterEach(async () => {
+ if (!baseCatalog) return;
+ const { getVideoModels } = await import('../../lib/mediaModels.js');
+ vi.mocked(getVideoModels).mockImplementation(baseCatalog);
+ mockFindCachedRepoFile.mockImplementation(async (_repo, filename) => join('/mock/hf/snap', filename));
+ });
+
+ const renderH3 = async (over = {}) => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
+ spawnMock.mockClear();
+ const jobId = `h3-draft-${Math.random().toString(36).slice(2, 10)}`;
+ let startedMeta = null;
+ const capture = (e) => { if (e.generationId === jobId) startedMeta = e; };
+ videoGenEvents.on('started', capture);
+ await generateVideo({
+ jobId,
+ modelId: 'minimax_h3_8bit',
+ prompt: 'a fox watches the rain',
+ width: 1344, height: 768, numFrames: 124, fps: 24, mode: 'text',
+ ...over,
+ });
+ videoGenEvents.off('started', capture);
+ const [, args] = spawnMock.mock.calls.find(([, a]) => (
+ Array.isArray(a) && a.some((arg) => basename(String(arg)) === 'generate_minimax_h3.py')
+ ));
+ return { args, meta: startedMeta };
+ };
+
+ const hasDecoderFlag = (args) => args.some((arg) => String(arg).startsWith('--draft-decoder'));
+
+ it('emits the decoder flags and records the decode when every gate passes', async () => {
+ await declareDecoder();
+ byovRevisionState.current = true;
+ byovRevisionState.expectedRevision = DECODER_RUNTIME_REV;
+
+ const { args, meta } = await renderH3({ draftDecode: 'draft' });
+
+ expect(args[args.indexOf('--draft-decoder-id') + 1]).toBe('draft');
+ expect(args[args.indexOf('--draft-decoder-file') + 1]).toBe(join('/mock/hf/snap', 'decoder.safetensors'));
+ expect(args).toContain('--draft-decoder-shim-root');
+ expect(meta).toMatchObject({ draftDecode: 'draft' });
+ });
+
+ // Byte-identical argv on the default path is what keeps this feature from
+ // changing any render nobody opted into.
+ it.each([
+ ['an omitted decode', {}],
+ ['an explicit full decode', { draftDecode: 'full' }],
+ ])('emits no decoder flag for %s', async (_label, over) => {
+ await declareDecoder();
+ byovRevisionState.current = true;
+ byovRevisionState.expectedRevision = DECODER_RUNTIME_REV;
+
+ const { args, meta } = await renderH3(over);
+
+ expect(hasDecoderFlag(args)).toBe(false);
+ expect(meta.draftDecode).toBeUndefined();
+ });
+
+ // The fallback paths the issue calls out. Each one must reach the runner
+ // WITHOUT the flags rather than 400 a submitted job — and must leave the
+ // history record making no claim about a draft decode.
+ it.each([
+ [
+ 'the model declares no decoder',
+ async () => {
+ byovRevisionState.current = true;
+ byovRevisionState.expectedRevision = DECODER_RUNTIME_REV;
+ },
+ ],
+ [
+ 'the installed runner checkout is not the verified revision',
+ async () => {
+ await declareDecoder();
+ byovRevisionState.current = false;
+ },
+ ],
+ [
+ 'the asset is not downloaded',
+ async () => {
+ await declareDecoder();
+ byovRevisionState.current = true;
+ byovRevisionState.expectedRevision = DECODER_RUNTIME_REV;
+ mockFindCachedRepoFile.mockImplementation(async (repo, filename) => (
+ repo === DECODER.repo ? null : join('/mock/hf/snap', filename)
+ ));
+ },
+ ],
+ [
+ 'the model is another entry\'s declared Finish target',
+ async () => {
+ await declareDecoder();
+ byovRevisionState.current = true;
+ byovRevisionState.expectedRevision = DECODER_RUNTIME_REV;
+ // The finish graph is what makes H3 a delivery model here: a draft
+ // entry naming it is the whole declaration, and a preview-grade decode
+ // must refuse to run on it however the request was phrased.
+ const { getVideoModels } = await import('../../lib/mediaModels.js');
+ const mock = vi.mocked(getVideoModels);
+ const declared = mock.getMockImplementation();
+ mock.mockImplementation(() => [
+ ...declared(),
+ { id: 'pretend_draft', runtime: 'minimax_h3', finishModelId: 'minimax_h3_8bit' },
+ ]);
+ },
+ ],
+ ])('falls back to the full decoder when %s', async (_label, setup) => {
+ await setup();
+
+ const { args, meta } = await renderH3({ draftDecode: 'draft' });
+
+ expect(hasDecoderFlag(args)).toBe(false);
+ // Still a real H3 render, just on the model's own decoder.
+ expect(args).toContain('--model-repo');
+ expect(meta.draftDecode).toBeUndefined();
+ });
+});
diff --git a/server/services/videoGen/renderArgs.js b/server/services/videoGen/renderArgs.js
index 9c900c6f70..59851e4bc3 100644
--- a/server/services/videoGen/renderArgs.js
+++ b/server/services/videoGen/renderArgs.js
@@ -39,6 +39,7 @@ import {
MINIMAX_H3_HELPER_SCRIPT,
MINIMAX_H3_REPO_DIR,
MINIMAX_H3_ENCODER_SHIM_DIR,
+ MINIMAX_H3_DRAFT_DECODER_SHIM_DIR,
MINIMAX_H3_EXPECTED_REVISION,
MINIMAX_H3_CUDA_VENV_PYTHON,
MINIMAX_H3_CUDA_HELPER_SCRIPT,
@@ -672,7 +673,7 @@ const miniMaxH3HostMemoryArgs = (model) => {
// Build args for PipeNetwork's pinned MiniMax H3 MLX port. The helper resolves
// only exact, already-cached HF revisions; every network download remains an
// explicit Video Gen UI action guarded by the model's terms acknowledgement.
-const buildMiniMaxH3Args = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths, mode, tiling, disableAudio, outputPath, previewDir, loras, textEncoder }) => {
+const buildMiniMaxH3Args = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths, mode, tiling, disableAudio, outputPath, previewDir, loras, textEncoder, draftDecoder }) => {
assertMiniMaxH3Preflight({
runtimeId: 'minimax_h3',
repoLabel: 'transformer repo or revision',
@@ -742,6 +743,19 @@ const buildMiniMaxH3Args = ({ model, prompt, negativePrompt, width, height, numF
// and refuses to load with any parameter missing.
if (textEncoder.finalNormKey) args.push('--text-encoder-final-norm-key', textEncoder.finalNormKey);
}
+ // Preview-fidelity video decode (lib/videoDraftDecoders.js, #5423). Absent
+ // for every full-decode render, so the argv of a delivery render is
+ // byte-identical to what it was before this feature existed. `paths` were
+ // already resolved against the HF cache by generateVideo — the helper never
+ // downloads — and generateVideo has already refused the substitution for a
+ // final/Finish render, so nothing here can put a draft decode on a delivery
+ // clip. One --draft-decoder-file per pinned file; the helper links them into
+ // a shim `source/` beside the model's own decoder config.
+ if (draftDecoder) {
+ args.push('--draft-decoder-id', draftDecoder.id);
+ for (const path of draftDecoder.paths) args.push('--draft-decoder-file', path);
+ args.push('--draft-decoder-shim-root', MINIMAX_H3_DRAFT_DECODER_SHIM_DIR);
+ }
return { bin: MINIMAX_H3_VENV_PYTHON, args };
};
@@ -812,7 +826,7 @@ const buildMiniMaxH3CudaArgs = ({ model, prompt, negativePrompt, width, height,
return { bin: MINIMAX_H3_CUDA_VENV_PYTHON, args };
};
-export 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, speedProfile }) => {
+export 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, speedProfile, draftDecoder }) => {
// 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
@@ -873,7 +887,7 @@ export const buildArgs = ({ pythonPath, modelId, model, wanModelPath, wanRequire
return buildWan22Args({ model, wanModelPath, wanRequiredWeights, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, sourceImagePath, mode, outputPath });
}
if (model.runtime === 'minimax_h3') {
- return buildMiniMaxH3Args({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths, mode, tiling, disableAudio, outputPath, previewDir, loras, textEncoder });
+ return buildMiniMaxH3Args({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths, mode, tiling, disableAudio, outputPath, previewDir, loras, textEncoder, draftDecoder });
}
if (model.runtime === 'minimax_h3_cuda') {
return buildMiniMaxH3CudaArgs({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths, mode, tiling, disableAudio, outputPath });
diff --git a/server/services/videoGen/runtimes.js b/server/services/videoGen/runtimes.js
index 697e8d659b..9dd8e5850e 100644
--- a/server/services/videoGen/runtimes.js
+++ b/server/services/videoGen/runtimes.js
@@ -64,6 +64,13 @@ export const MINIMAX_H3_EXPECTED_REVISION = 'fcd9e9b79a1d6018d91ac477c0968de1fa0
// untracked in the pin verification that both /status and the render helper run.
export const MINIMAX_H3_ENCODER_SHIM_DIR = join(homedir(), '.portos', 'minimax-h3-encoder-shims');
+// Composed checkpoint roots for a preview-fidelity video decode
+// (lib/videoDraftDecoders.js, #5423). Same shape and the same reason as the
+// encoder shims above — a tree of symlinks into the upstream FL2VA snapshot
+// with only `video_vae/source/model.safetensors` replaced — kept in its own
+// directory so removing one substitution never disturbs the other.
+export const MINIMAX_H3_DRAFT_DECODER_SHIM_DIR = join(homedir(), '.portos', 'minimax-h3-decoder-shims');
+
// MiniMax H3 on CUDA — the diffusers `MiniMaxH3ModularPipeline` rather than a
// pinned source checkout, so this runtime is a plain pip venv with no revision
// to verify and no source package to keep clean.
@@ -480,6 +487,16 @@ export function isPinnedSourceStatusClean(stdout, expectedRevision) {
return oid === expectedRevision && lines.every((line) => line.startsWith('# '));
}
+// The revision a BYOV runtime's checkout is pinned to, or null for a runtime
+// that has no source pin (a plain pip venv). Paired with
+// `isByovRuntimeCurrent` by callers that need to know WHICH revision is
+// installed rather than just whether it is current — a capability gate on a
+// separately verified asset (lib/videoDraftDecoders.js) has to name the
+// checkout the asset was validated against, not just assert cleanliness.
+export function byovRuntimeExpectedRevision(runtimeId) {
+ return BYOV_RUNTIME_INFO[runtimeId]?.expectedRevision || null;
+}
+
export async function isByovRuntimeCurrent(runtimeId) {
const info = BYOV_RUNTIME_INFO[runtimeId];
if (!info?.expectedRevision) return true;
diff --git a/server/services/videoGen/stitchVideos.js b/server/services/videoGen/stitchVideos.js
index 2360b7d5bf..a2b12a09e0 100644
--- a/server/services/videoGen/stitchVideos.js
+++ b/server/services/videoGen/stitchVideos.js
@@ -216,6 +216,12 @@ export async function stitchVideos(videoIds, opts = {}) {
// none (resolveVideoSpeedProfileForModes), so videos[0] speaks for all.
'speedProfileId',
'speedProfileApplied',
+ // Draft decode (#5423) — inherited for the same reason as the speed
+ // profile above: a chain's chunk entries are hidden, so without these the
+ // stitched record would never say the clip was decoded at preview
+ // fidelity. Every chunk of one chain resolves the same decoder.
+ 'draftDecode',
+ 'draftDecodeApplied',
].flatMap((key) => videos[0][key] === undefined ? [] : [[key, videos[0][key]]])),
// Inherit applied LoRAs from the first constituent clip (a chunk chain
// shares one LoRA set across all chunks), so the visible stitched entry