Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add a capability-gated LTX-2.5 speed profile with honest fallback (#4875)
[._.]/ Adam Eivy2b0bb93050c9
diff --git a/client/src/components/media/MediaJobsQueue.jsx b/client/src/components/media/MediaJobsQueue.jsxindex 2f2bed3371..7b43d6c593 100644--- a/client/src/components/media/MediaJobsQueue.jsx+++ b/client/src/components/media/MediaJobsQueue.jsx@@ -26,6 +26,7 @@ import { resolutionOptionsForModel } from '../../lib/videoGenResolutions';import {videoEdgeBoundsForModel, textEncoderOptionsForModel, STOCK_TEXT_ENCODER_ID,normalizeTextEncoderForModel,+ DEFAULT_SPEED_PROFILE_ID, normalizeSpeedProfileForModel, speedProfileIdFromRecord,} from '../../lib/videoGenParams';import { loraFamilyOf, videoLoraFamily } from '../../lib/runnerFamilies';import LoraPicker from '../imageGen/LoraPicker';@@ -710,6 +711,10 @@ function VideoRetryForm({ job, onSubmit, onCancel }) {const [tiling, setTiling] = useState(p.tiling || 'auto');const [disableAudio, setDisableAudio] = useState(p.disableAudio === true);const [textEncoderId, setTextEncoderId] = useState(p.textEncoderId || STOCK_TEXT_ENCODER_ID);+ // The failed job's sampler schedule (#4875). Seeded from its params so the+ // picker reports what the render actually used rather than always reading+ // "Quality", and so an unchanged retry re-submits the same schedule.+ const [speedProfileId, setSpeedProfileId] = useState(speedProfileIdFromRecord(p.speedProfileId));const [availableLoras, setAvailableLoras] = useState([]);const [selectedLoras, setSelectedLoras] = useState(Array.isArray(p.loras) ? p.loras : []);@@ -743,6 +748,15 @@ function VideoRetryForm({ job, onSubmit, onCancel }) {const videoLoras = loraFamily ? availableLoras.filter((lora) => loraFamilyOf(lora) === loraFamily) : [];const encoderOptions = textEncoderOptionsForModel(currentModel);const originalEncoder = normalizeTextEncoderForModel(p.textEncoderId || STOCK_TEXT_ENCODER_ID, currentModel);+ const originalSpeedProfileForModel = normalizeSpeedProfileForModel(speedProfileIdFromRecord(p.speedProfileId), currentModel);+ // Models arrive asynchronously, so the recorded profile can only be validated+ // once the entry resolves. Until then state holds the raw recorded id; this+ // snaps it to what the model actually declares, so an untouched form can't+ // re-submit a schedule the registry no longer offers.+ useEffect(() => {+ if (!currentModel) return;+ setSpeedProfileId((current) => normalizeSpeedProfileForModel(current, currentModel));+ }, [currentModel]);// Multi-keyframe inputs are not exposed in the sanitized queue projection,// but FFLF is their persisted semantic mode. IC/a2v conditioning also pins// a single render, so keep the shared chaining controls consistent with the@@ -753,6 +767,7 @@ function VideoRetryForm({ job, onSubmit, onCancel }) {const nextModel = models.find((model) => model.id === nextModelId) || null;setModelId(nextModelId);setTextEncoderId(normalizeTextEncoderForModel(textEncoderId, nextModel));+ setSpeedProfileId(normalizeSpeedProfileForModel(speedProfileId, nextModel));if (videoLoraFamily(nextModel) !== loraFamily) setSelectedLoras([]);};const setChunkPromptAt = (index, value) => setChunkPrompts((prev) => {@@ -803,6 +818,14 @@ function VideoRetryForm({ job, onSubmit, onCancel }) {// submit that reset explicitly so the retry does not retain the old,// incompatible encoder from the failed job.if (modelId !== p.modelId || textEncoderId !== originalEncoder) overrides.textEncoderId = textEncoderId;+ // Same model-switch clause its sibling above carries: switching to a model+ // that declares no profiles snaps BOTH the local value and+ // its baseline to the default, so they compare equal and no+ // override would be sent — leaving the old job's `speedProfileId` in the+ // inherited params for the queue to echo as a profile the render never used.+ if (modelId !== p.modelId || speedProfileId !== originalSpeedProfileForModel) {+ overrides.speedProfileId = speedProfileId === DEFAULT_SPEED_PROFILE_ID ? null : speedProfileId;+ }if (JSON.stringify(selectedLoras) !== JSON.stringify(p.loras || [])) overrides.loras = selectedLoras;onSubmit(Object.keys(overrides).length ? overrides : null);};@@ -851,6 +874,7 @@ function VideoRetryForm({ job, onSubmit, onCancel }) {contextFrames={contextFrames} onContextFramesChange={setContextFrames}fps={displayedFps} onFpsChange={setFps} seed={seed} onSeedChange={setSeed} onRandomSeed={() => setSeed(Math.floor(Math.random() * 2147483647))}steps={steps} onStepsChange={setSteps} guidanceScale={guidanceScale} onGuidanceScaleChange={setGuidanceScale}+ speedProfileId={speedProfileId} onSpeedProfileChange={setSpeedProfileId}imageStrength={imageStrength} onImageStrengthChange={setImageStrength} tiling={tiling} onTilingChange={setTiling}i2vReferenceMode={i2vReferenceMode} onI2vReferenceModeChange={setI2vReferenceMode}effectiveImageStrength={resolveI2vReferenceStrength(i2vReferenceMode, imageStrength)}diff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsxindex 011f0f8f97..c867d02a9e 100644--- a/client/src/components/media/MediaLightbox.jsx+++ b/client/src/components/media/MediaLightbox.jsx@@ -207,6 +207,27 @@ export default function MediaLightbox({const entryKindLabel = ({ canon: 'Canon entry', variation: 'Category variation', sheet: 'Composite sheet' })[item.entryKind] || item.entryKind;const cleanedLabel = describeCleanedLineage(item);+ // Speed profile (#4875). The REQUESTED schedule, annotated with whatever the+ // runner could not actually apply. Without this the degraded case exists only+ // as a transient STATUS line during the render, so a user who wasn't watching+ // would never learn their "faster" render ran without TeaCache or without the+ // distilled adapter — which is precisely the misleading speed claim the+ // feature is built to avoid. Absent on every Quality render.+ const speedProfileLabel = (() => {+ const id = item.raw?.speedProfileId;+ if (!id) return null;+ const applied = item.raw?.speedProfileApplied;+ // No report at all: the request named a profile but the runner never said+ // what it managed to apply. Say exactly that rather than let a bare id read+ // as a clean full run — the whole point is that an unverified speed-up is+ // never presented as a verified one.+ if (!applied) return `${id} — outcome not reported`;+ const degraded = applied.degraded;+ return Array.isArray(degraded) && degraded.length+ ? `${id} — reduced: ${degraded.join(', ')} unavailable`+ : id;+ })();+const meta = [// Universe Builder context — placed first so "this is Ash from MyVerse"// reads before the technical render params. Sidecars without a universe@@ -217,6 +238,7 @@ export default function MediaLightbox({['Category', item.entryCategory],['Model', item.modelId],['Resolution', item.width && item.height ? `${item.width}×${item.height}` : null],+ ['Speed profile', speedProfileLabel],['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.jsindex e42134b93e..e76c847077 100644--- a/client/src/components/media/normalize.js+++ b/client/src/components/media/normalize.js@@ -184,6 +184,12 @@ export function getRenderConfigForItem(item) {tiling: raw.tiling,disableAudio: raw.disableAudio ?? raw.disable_audio,textEncoderId: raw.textEncoderId,+ // The named sampler schedule (#4875), when the record was rendered with+ // one. Without it a requeue would carry the profile's steps/CFG but none+ // of its levers (stage-2 budget, TeaCache) — a slower, different render+ // 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,loraFilenames: pickLoraFilenames(raw),loraScales: raw.loraScales ?? raw.lora_scales,};diff --git a/client/src/components/media/normalize.test.js b/client/src/components/media/normalize.test.jsindex 7bc62d5cb6..2e3c55413b 100644--- a/client/src/components/media/normalize.test.js+++ b/client/src/components/media/normalize.test.js@@ -274,6 +274,18 @@ describe('getRenderConfigForItem - video', () => {expect(cfg.loraScales).toEqual([0.5]);});+ // #4875 — a requeue must carry the named schedule, not just the steps/CFG it+ // resolved to, or it silently re-renders without the profile's other levers.+ it('carries a speed profile through a requeue, and omits it on a Quality record', () => {+ const withProfile = normalizeVideo({+ id: 'v4', filename: 'd.mp4', prompt: '', modelId: 'ltx25_mlx_q8',+ steps: 8, guidanceScale: 1, speedProfileId: 'fast',+ });+ expect(getRenderConfigForItem(withProfile).speedProfileId).toBe('fast');+ const quality = normalizeVideo({ id: 'v5', filename: 'e.mp4', prompt: '', modelId: 'ltx25_mlx_q8', steps: 8 });+ expect(getRenderConfigForItem(quality).speedProfileId).toBeUndefined();+ });+it('preserves a deliberate guidanceScale of 0', () => {// 0 is a valid setting for some video models — must not be coerced via// truthy fallback.diff --git a/client/src/components/videoGen/AdvancedParamsPanel.jsx b/client/src/components/videoGen/AdvancedParamsPanel.jsxindex db6673ea18..cbe48747bb 100644--- a/client/src/components/videoGen/AdvancedParamsPanel.jsx+++ b/client/src/components/videoGen/AdvancedParamsPanel.jsx@@ -12,6 +12,8 @@ import {frameOptionsForModel, fpsOptionsForModel, CHUNK_OPTIONS,isModelAllowedForMode, supportsVideoAudioControls, supportsVideoAudioPromptControls,CONTEXT_FRAME_OPTIONS, supportsContextWindow,+ DEFAULT_SPEED_PROFILE_ID, speedProfilesForMode, selectedSpeedProfile,+ videoChainChunkModes,} from '../../lib/videoGenParams.js';import { VIDEO_TILING_OPTIONS } from '../../lib/videoTilingOptions';import { isLtx2FamilyRuntime } from '../../lib/runnerFamilies';@@ -33,6 +35,7 @@ export default function AdvancedParamsPanel({seed, onSeedChange, onRandomSeed,steps, onStepsChange,guidanceScale, onGuidanceScaleChange,+ speedProfileId = DEFAULT_SPEED_PROFILE_ID, onSpeedProfileChange,imageStrength, onImageStrengthChange,i2vReferenceMode = DEFAULT_I2V_REFERENCE_MODE, onI2vReferenceModeChange,effectiveImageStrength = null,@@ -88,6 +91,36 @@ export default function AdvancedParamsPanel({const frameOptions = frameOptionsForModel(currentModel, numFrames);const fpsOptions = fpsOptionsForModel(currentModel);const samplerLocked = currentModel?.samplerLocked === true;+ // Speed profiles (#4875). Only the profiles VALIDATED for what this request+ // will actually run are offered: a profile the server would decline is a dead+ // affordance that promises a speed-up the render then doesn't take. With none+ // applicable the picker is hidden entirely rather than shown holding only+ // "Quality".+ //+ // A CHAINED render is one clip whose chunks run in DIFFERENT modes, and the+ // server applies a profile to it only when every chunk accepts one — so the+ // gate takes the whole chunk-mode list. Without that, picking Fast with+ // Chunks = 4 would grey out Steps/CFG and then quietly run the entire chain+ // at the model default.+ const speedProfileModes = videoChainChunkModes({+ model: currentModel, mode, chaining: chainingActive, contextFrames,+ });+ const speedProfiles = speedProfilesForMode(currentModel, speedProfileModes);+ const showSpeedProfiles = !samplerLocked && speedProfiles.length > 0;+ // Resolved against the SAME set the picker offers, so a model with two+ // profiles can't lock Steps/CFG to one this request declines.+ const activeSpeedProfile = showSpeedProfiles+ ? selectedSpeedProfile(speedProfileId, currentModel, speedProfileModes)+ : null;+ // A profile drives steps AND CFG together, exactly as a samplerLocked model+ // does — leaving either editable would let the user half-override a+ // validated schedule and get neither its speed nor its quality.+ const samplerDriven = samplerLocked || !!activeSpeedProfile;+ const samplerDrivenTitle = samplerLocked+ ? 'This validated Lightning profile locks its sampler settings.'+ : activeSpeedProfile+ ? `The ${activeSpeedProfile.name} speed profile sets its own validated schedule. Switch to Quality to edit these.`+ : undefined;return (<div className="border-t border-port-border pt-3 space-y-3">@@ -229,17 +262,34 @@ export default function AdvancedParamsPanel({</div></div>+ {showSpeedProfiles && (+ <FormField label="Speed" labelClassName="block text-xs font-medium text-gray-400 mb-1">+ <select+ value={activeSpeedProfile ? speedProfileId : DEFAULT_SPEED_PROFILE_ID}+ onChange={(e) => onSpeedProfileChange(e.target.value)}+ className={inputCls}+ >+ <option value={DEFAULT_SPEED_PROFILE_ID}>Quality · default</option>+ {speedProfiles.map((p) => (+ <option key={p.id} value={p.id}>+ {p.name}{p.speedupLabel ? ` · ${p.speedupLabel}` : ''}+ </option>+ ))}+ </select>+ </FormField>+ )}+<FormFieldlabel={<>Steps {currentModel?.steps && `(default: ${currentModel.steps})`}</>}labelClassName="block text-xs font-medium text-gray-400 mb-1"><inputtype="number" min={1} max={150}- value={steps}+ value={activeSpeedProfile ? '' : steps}onChange={(e) => onStepsChange(e.target.value)}- disabled={samplerLocked}- title={samplerLocked ? 'This validated Lightning profile locks its sampler settings.' : undefined}- placeholder={String(currentModel?.steps || 25)}+ disabled={samplerDriven}+ title={samplerDrivenTitle}+ placeholder={String(activeSpeedProfile?.steps ?? currentModel?.steps ?? 25)}className={inputCls}/></FormField>@@ -250,11 +300,11 @@ export default function AdvancedParamsPanel({><inputtype="number" min={0} max={20} step={0.5}- value={guidanceScale}+ value={activeSpeedProfile ? '' : guidanceScale}onChange={(e) => onGuidanceScaleChange(e.target.value)}- disabled={samplerLocked}- title={samplerLocked ? 'This validated Lightning profile locks its sampler settings.' : undefined}- placeholder={String(currentModel?.guidance ?? 3.0)}+ disabled={samplerDriven}+ title={samplerDrivenTitle}+ placeholder={String(activeSpeedProfile?.guidance ?? currentModel?.guidance ?? 3.0)}className={inputCls}/></FormField>@@ -287,6 +337,15 @@ export default function AdvancedParamsPanel({</div>)}+ {activeSpeedProfile && (+ <p className="col-span-2 sm:col-span-3 text-[10px] text-port-accent leading-snug">+ {activeSpeedProfile.description}+ {' '}Steps and CFG follow the profile ({activeSpeedProfile.steps}+ {activeSpeedProfile.stage2Steps != null ? `+${activeSpeedProfile.stage2Steps}` : ''} steps, CFG {activeSpeedProfile.guidance}).+ {' '}If a lever it needs is missing on this machine, the render still runs and says so rather than claiming the speed-up.+ </p>+ )}+{showImageStrength && (<div className="col-span-2 sm:col-span-3"><div className="flex items-center justify-between gap-3 mb-1">diff --git a/client/src/components/videoGen/AdvancedParamsPanel.test.jsx b/client/src/components/videoGen/AdvancedParamsPanel.test.jsxindex 25456ec0be..2dfa153aff 100644--- a/client/src/components/videoGen/AdvancedParamsPanel.test.jsx+++ b/client/src/components/videoGen/AdvancedParamsPanel.test.jsx@@ -323,3 +323,129 @@ describe('AdvancedParamsPanel — reference mode before the model catalog loads'expect(screen.getByText(/can only anchor a reference/i)).toBeTruthy();});});++// Speed profiles (#4875). The picker exists so a validated fast schedule is+// reachable without hand-tuning steps/CFG — and so it is NEVER offered where+// the server would decline it, which would be a dead speed affordance.+describe('AdvancedParamsPanel — speed profiles', () => {+ const FAST = {+ id: 'fast',+ name: 'Fast',+ description: 'Validated 8+3-step two-stage schedule at CFG 1.0.',+ speedupLabel: '~2× faster',+ steps: 8,+ stage2Steps: 3,+ guidance: 1.0,+ modes: ['text', 'image'],+ };+ const ltx25 = (extra = {}) => ({+ steps: 8, guidance: 3.0, runtime: 'ltx25',+ supportedModes: ['text', 'image', 'fflf', 'extend'],+ speedProfiles: [FAST],+ ...extra,+ });++ it('is hidden on a model that declares no profiles', () => {+ renderPanel();+ expect(screen.queryByLabelText('Speed')).toBeNull();+ });++ it('offers Quality plus each profile validated for the current mode', () => {+ renderPanel({ currentModel: ltx25() });+ const select = screen.getByLabelText('Speed');+ expect([...select.options].map((o) => o.value)).toEqual(['quality', 'fast']);+ expect([...select.options].map((o) => o.text)).toEqual(['Quality · default', 'Fast · ~2× faster']);+ });++ // The whole reason the picker filters by mode: on fflf/extend the server+ // declines the profile, so offering it would promise a speed-up the render+ // silently doesn't take.+ it.each(['fflf', 'extend'])('is hidden on %s, where the profile is not validated', (mode) => {+ renderPanel({ currentModel: ltx25(), mode });+ expect(screen.queryByLabelText('Speed')).toBeNull();+ });++ it('is hidden on a samplerLocked model, whose own schedule is the authority', () => {+ renderPanel({ currentModel: ltx25({ samplerLocked: true }) });+ expect(screen.queryByLabelText('Speed')).toBeNull();+ });++ // A chained render is ONE clip: the server applies a profile only when every+ // chunk's mode accepts it. Chunks 1+ re-enter as `extend` on a+ // window-continuity chain, so offering Fast there would grey out Steps/CFG+ // and then quietly render the whole chain at the model default.+ it('hides the picker on a window-continuity chain, where the server declines', () => {+ renderPanel({ currentModel: ltx25(), chainingActive: true, chunks: 4, contextFrames: 22 });+ expect(screen.queryByLabelText('Speed')).toBeNull();+ });++ it('keeps the picker on a frame-hop chain, where every chunk qualifies', () => {+ // contextFrames 0 → frame hop → chunks 1+ are `image`, which Fast supports.+ renderPanel({ currentModel: ltx25(), chainingActive: true, chunks: 4, contextFrames: 0 });+ expect([...screen.getByLabelText('Speed').options].map((o) => o.value)).toEqual(['quality', 'fast']);+ });++ it('keeps the picker for a single-chunk render whatever the continuity setting', () => {+ renderPanel({ currentModel: ltx25(), chainingActive: false, chunks: 1, contextFrames: 22 });+ expect(screen.getByLabelText('Speed')).toBeTruthy();+ });++ it('leaves Steps and CFG editable when a chain declines the selected profile', () => {+ renderPanel({+ currentModel: ltx25(), chainingActive: true, chunks: 4, contextFrames: 22, speedProfileId: 'fast',+ });+ expect(screen.getByLabelText(/Steps/).disabled).toBe(false);+ expect(screen.getByLabelText(/CFG Scale/).disabled).toBe(false);+ });++ it('propagates a selection to the page handler', () => {+ const onSpeedProfileChange = vi.fn();+ renderPanel({ currentModel: ltx25(), onSpeedProfileChange });+ fireEvent.change(screen.getByLabelText('Speed'), { target: { value: 'fast' } });+ expect(onSpeedProfileChange).toHaveBeenCalledWith('fast');+ });++ it('falls back to Quality when the selection is not offered by this model', () => {+ // A model switch can leave a stale id in state before the reconcile effect+ // runs; the <select> must not sit on a value with no matching <option>.+ renderPanel({ currentModel: ltx25(), speedProfileId: 'turbo' });+ expect(screen.getByLabelText('Speed').value).toBe('quality');+ });++ // With two profiles the picker is shown (one is valid here), so resolving+ // the selection against the UNFILTERED list would lock Steps/CFG to the+ // profile this mode declines — promising a schedule the render won't use.+ it('ignores a selected profile that this mode does not support', () => {+ const twoProfiles = ltx25({+ speedProfiles: [FAST, { id: 'blitz', name: 'Blitz', steps: 4, guidance: 1.0, modes: ['fflf'] }],+ });+ renderPanel({ currentModel: twoProfiles, mode: 'text', speedProfileId: 'blitz' });+ // 'blitz' isn't offered for text, so the picker falls back to Quality...+ expect([...screen.getByLabelText('Speed').options].map((o) => o.value)).toEqual(['quality', 'fast']);+ expect(screen.getByLabelText('Speed').value).toBe('quality');+ // ...and the dials stay the user's to set.+ expect(screen.getByLabelText(/Steps/).disabled).toBe(false);+ expect(screen.getByLabelText(/CFG Scale/).disabled).toBe(false);+ });++ it('leaves Steps and CFG editable on Quality', () => {+ renderPanel({ currentModel: ltx25(), speedProfileId: 'quality' });+ expect(screen.getByLabelText(/Steps/).disabled).toBe(false);+ expect(screen.getByLabelText(/CFG Scale/).disabled).toBe(false);+ });++ it('locks Steps and CFG to the profile while one is active', () => {+ renderPanel({ currentModel: ltx25(), speedProfileId: 'fast', steps: '30', guidanceScale: '7' });+ const steps = screen.getByLabelText(/Steps/);+ const cfg = screen.getByLabelText(/CFG Scale/);+ expect(steps.disabled).toBe(true);+ expect(cfg.disabled).toBe(true);+ // The profile's own numbers show as placeholders — a stale typed value+ // must not read as if it were what the render will use.+ expect(steps.value).toBe('');+ expect(cfg.value).toBe('');+ expect(steps.placeholder).toBe('8');+ expect(cfg.placeholder).toBe('1');+ expect(screen.getByText(/8\+3 steps, CFG 1/)).toBeTruthy();+ });+});diff --git a/client/src/hooks/useVideoGenForm.js b/client/src/hooks/useVideoGenForm.jsindex dec8d26d24..4969bfe4bf 100644--- a/client/src/hooks/useVideoGenForm.js+++ b/client/src/hooks/useVideoGenForm.js@@ -24,6 +24,8 @@ import {icLoraSpecForMode, icResolutionIssue,STOCK_TEXT_ENCODER_ID, textEncoderOptionsForModel, normalizeTextEncoderForModel,textEncoderIdFromRecord,+ DEFAULT_SPEED_PROFILE_ID, normalizeSpeedProfileForModel, speedProfileIdFromRecord,+ selectedSpeedProfile, videoChainChunkModes,} from '../lib/videoGenParams.js';// A Remix is an editing starting point. A fixed sampler profile (for example,@@ -134,6 +136,10 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, r// the list is empty and this stays on the stock sentinel, which the submit// builder drops from the payload entirely.const [textEncoderId, setTextEncoderId] = useState(STOCK_TEXT_ENCODER_ID);+ // Named sampler schedule (#4875). Defaults to Quality, the shipped contract —+ // it is a real selectable value rather than '' so the <select> always has a+ // matching <option>, and the submit builder drops it as "unchanged".+ const [speedProfileId, setSpeedProfileId] = useState(DEFAULT_SPEED_PROFILE_ID);const [disableAudio, setDisableAudio] = useState(false);// Video LoRAs (ltx2 runtime only) — `{ filename, name, scale }` entries the// LoraPicker owns; `availableLoras` is the full installed library filtered@@ -524,6 +530,10 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, rsetNumFrames((current) => normalizeFramesForModel(current, currentModel));setFps((current) => normalizeFpsForModel(current, currentModel));setTextEncoderId((current) => normalizeTextEncoderForModel(current, currentModel));+ // Same reconcile for the speed profile: a model switch must not leave a+ // 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));}, [currentModel]);// Substitutable prompt conditioners the selected model can load, straight off@@ -1047,6 +1057,7 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, r// on a render the user asked to reproduce faithfully. The currentModel effect// snaps an id this model can't load back to stock.setTextEncoderId(textEncoderIdFromRecord(item.textEncoderId));+ setSpeedProfileId(speedProfileIdFromRecord(item.speedProfileId));// 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.@@ -1154,6 +1165,7 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, rsetI2vReferenceMode(normalizeI2vReferenceMode(p.i2vReferenceMode));// Resume echoes the field only for a non-stock render, so absence is 'stock'.setTextEncoderId(textEncoderIdFromRecord(p.textEncoderId));+ setSpeedProfileId(speedProfileIdFromRecord(p.speedProfileId));if (typeof p.disableAudio === 'boolean') setDisableAudio(p.disableAudio);if (p.mode === 'grok') {// Grok job: 'grok' is the queue discriminator, not a semantic video@@ -1383,6 +1395,19 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, rtextEncoderId: normalizeTextEncoderForModel(textEncoderId, currentModel) === STOCK_TEXT_ENCODER_ID? undefined: textEncoderId,+ // Dropped for Quality on the same rule as the conditioner above, so a+ // default render posts the body it did before this knob existed.+ //+ // Gated on the SAME mode/chain-filtered set the picker uses, not merely+ // on what the model declares: selecting Fast in text mode and then+ // switching to fflf (or raising Chunks with window continuity) hides the+ // picker and unlocks Steps/CFG, and posting the profile anyway would+ // persist a knob that never applied — echoed back on reload and seeded+ // into a Retry as a schedule the render never used. Exactly what the+ // sibling textEncoderId rule exists to prevent.+ speedProfileId: selectedSpeedProfile(speedProfileId, currentModel, videoChainChunkModes({+ model: currentModel, mode, chaining: chainingActive, contextFrames,+ }))?.id,disableAudio: effectiveDisableAudio ? 'true' : 'false',mode,imageStrength: imageStrength || '',@@ -1479,6 +1504,7 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, rseed, setSeed, handleRandomSeed,tiling, setTiling,textEncoderId, setTextEncoderId, textEncoderOptions,+ speedProfileId, setSpeedProfileId,disableAudio, setDisableAudio,noMusic, setNoMusic,// Framesdiff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex d56d08aeb5..53c6c135b5 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -73,7 +73,7 @@ grep -i "what you want to do" client/src/lib/README.md| `importerDeepLink.js` | The Importer deep-link contract both ways: `buildImporterLink({ universeId, seriesId, seriesName })` builds the `/importer?…` URL a Series Pipeline page navigates to; `resolveImporterDeepLink(...)` reads those params back into the universe + series names the importer matches on. || `muscriptorModels.js` | `MUSCRIPTOR_MODELS` (audio → MIDI size tiers `small`/`medium`/`large`) + `DEFAULT_MUSCRIPTOR_MODEL`. Single source consumed by the transcribe `<select>`s in `MusicVideo.jsx` and `ReferenceAnalysis.jsx`. Mirrors the server's `MUSCRIPTOR_MODELS` in `server/services/audioMidiTranscription.js`. || `videoFinish.js` | Finish-a-draft gate (#3696). `isReproducibleTextToVideo(record)` is true only for a single text-to-video render whose history record already carries everything a re-render needs — `renderInputsVersion` (the positive marker that its conditioning inventory is trustworthy, so legacy records degrade to not-finishable rather than reading as unconditioned), an empty `conditioning` array, a resolved seed, a real prompt, and no stitched/chained/upscaled provenance. `finishTargetForRecord(record, models)` additionally resolves the draft model's server-declared `finishModelId` against the models this install can actually run, returning the delivery model entry or `null`. Mirrors `finishTargetForModel` in `server/lib/videoFinishProfiles.js`; the pair table itself stays server-side. |-| `videoGenParams.js` | Pure VideoGen param helpers: `FRAME_OPTIONS`/`FPS_OPTIONS`/`VIDEO_EDGE_BOUNDS`/`MAX_CHUNKS`/`CHUNK_OPTIONS`/`DEFAULT_CONTEXT_FRAMES`/`CONTEXT_FRAME_OPTIONS` constants, model-aware frame/fps/resolution-grid normalization, separate mute vs prompt-audio capability checks, `supportsContextWindow(model)` (does this runtime have an extend pipeline to feed a continuation window to — display mirror of `server/lib/videoContinuity.js`, pinned by `server/lib/videoContinuity.parity.test.js`), `videoModelMemoryGb()` (model memory footprint), `computeFflfSafeFrames()` (FFLF/ltx2 pixel-budget back-solve, mirrors `server/services/videoGen/local.js`), and `isModelAllowedForMode()` (a2v + IC-remix → ltx2 gate). Also mirrors the IC-LoRA remix registry (`IC_LORA_MODES`/`IC_LORA_MODE_VALUES`/`isIcLoraMode()`/`icLoraSpecForMode()`/`icResolutionIssue()`) from `server/lib/icLoraWeights.js` so the form validates a reference render pre-submit — pinned by `server/lib/icLoraWeights.parity.test.js`. |+| `videoGenParams.js` | Pure VideoGen param helpers: `FRAME_OPTIONS`/`FPS_OPTIONS`/`VIDEO_EDGE_BOUNDS`/`MAX_CHUNKS`/`CHUNK_OPTIONS`/`DEFAULT_CONTEXT_FRAMES`/`CONTEXT_FRAME_OPTIONS` constants, model-aware frame/fps/resolution-grid normalization, separate mute vs prompt-audio capability checks, `supportsContextWindow(model)` (does this runtime have an extend pipeline to feed a continuation window to — display mirror of `server/lib/videoContinuity.js`, pinned by `server/lib/videoContinuity.parity.test.js`), `videoModelMemoryGb()` (model memory footprint), `computeFflfSafeFrames()` (FFLF/ltx2 pixel-budget back-solve, mirrors `server/services/videoGen/local.js`), and `isModelAllowedForMode()` (a2v + IC-remix → ltx2 gate). Speed profiles (#4875) mirror the conditioner shape: `DEFAULT_SPEED_PROFILE_ID` (must equal `SPEED_PROFILE_DEFAULT_ID` in `server/lib/videoSpeedProfiles.js` — absence and `'quality'` are the same request), `isDefaultSpeedProfileId()` mirrors the server's absence-is-the-default rule, `speedProfilesForModel()` reads the server-decorated `speedProfiles` off the entry, `speedProfilesForMode(model, mode)` applies the SAME mode gate the server's `speedProfileDeclineReason` does (so a profile the server would decline is never offered, nor allowed to lock the dials), `normalizeSpeedProfileForModel()` snaps a selection onto what a just-switched model declares (mode-independent, so switching to fflf hides the picker without rewriting the choice), `speedProfileIdFromRecord()` reads one back out of a history entry / resumed job, `selectedSpeedProfile(id, model, mode)` resolves the profile actually driving the render — what the picker shows and what disables Steps+CFG — and `videoChainChunkModes({ model, mode, chaining, contextFrames, hasSourceImage })` derives the modes a CHAINED request’s chunks will run in (chunk 0 the request’s, chunks 1+ `extend` on a window-continuity chain or `image` on a frame hop), mirroring `generateChainedVideo`’s dispatch and `resolveContinuityStrategy`; `resolveContextFramesForDisplay()` is the absent/invalid→`DEFAULT_CONTEXT_FRAMES` half of `resolveContextFrames` that gate depends on. All pinned by `server/lib/videoSpeedProfiles.parity.test.js`. Also mirrors the IC-LoRA remix registry (`IC_LORA_MODES`/`IC_LORA_MODE_VALUES`/`isIcLoraMode()`/`icLoraSpecForMode()`/`icResolutionIssue()`) from `server/lib/icLoraWeights.js` so the form validates a reference render pre-submit — pinned by `server/lib/icLoraWeights.parity.test.js`. || `videoGenResolutions.js` | Shared resolution presets/default for video generation, model-specific preset/default resolvers (for native canvases such as MiniMax H3), and `snapAspectToImage()` to pick the closest-aspect preset for an I2V source. || `videoReferenceModes.js` | Mirror of `server/lib/videoReferenceModes.js` (parity enforced by `server/lib/videoReferenceModes.mirror.test.js`) — the i2v reference-mode contract: `I2V_REFERENCE_MODES`, `I2V_REFERENCE_MODE_OPTIONS` (label + the promise sentence `AdvancedParamsPanel` and the source-frame note print), `runtimeSupportsI2vReferenceMode` (gates which options the picker offers), `resolveI2vReferenceStrength` (the effective strength the panel displays), and `i2vReferenceModeViolation` for pre-submit feedback. || `videoStagePreview.js` | VideoGen main-stage preview resolver (#4588). `resolveVideoStagePreview({ generating, currentImage, width, height, result, extendSource, sourceImageFile/Url, lastImageFile/Url, keyframes })` → `{ kind: 'live'|'loop'|'still'|'result'|'empty', src, poster, label, aspectRatio }` — what the stage should show at each moment of a render, with mid-render vs idle precedence. Plus `videoStageAspectRatio()` (a NUMBER for an inline `aspect-ratio` style — a computed Tailwind `aspect-[w/h]` class never reaches the JIT build; `null` means unknown geometry, not 16:9), `videoPreviewFrameSrc()` (the runners' `currentImage` is polymorphic — raw base64 from imageGen, a served URL from loraTraining — so classify before prefixing), and `videoStageSignature()` for the hold/return guard in `components/videoGen/LiveVideoStage.jsx`. |diff --git a/client/src/lib/videoGenParams.js b/client/src/lib/videoGenParams.jsindex a1e59b435f..7400967dc9 100644--- a/client/src/lib/videoGenParams.js+++ b/client/src/lib/videoGenParams.js@@ -109,6 +109,105 @@ export const textEncoderIdFromRecord = (value) => (typeof value === 'string' && value ? value : STOCK_TEXT_ENCODER_ID);+// Speed profiles (#4875) follow the SAME shape as the conditioner picker above,+// and for the same reason: the option list is decorated onto each model entry+// by the server (`applyVideoSpeedProfiles` in server/lib/videoSpeedProfiles.js),+// so the picker offers exactly what this install's registry declares and a+// stale client can't submit a schedule that no longer exists. Only the "no+// override" sentinel is duplicated here, and it must stay equal to+// `SPEED_PROFILE_DEFAULT_ID` on the server: the submit builder drops the field+// when it holds this value, and the server treats absence and this id+// identically.+export const DEFAULT_SPEED_PROFILE_ID = 'quality';+// Absence, the empty string and the default id are one request — mirrors+// `isDefaultSpeedProfile` on the server.+export const isDefaultSpeedProfileId = (id) => (+ id == null || id === '' || id === DEFAULT_SPEED_PROFILE_ID+);+// Every profile the model DECLARES, mode-independent. Used to validate a+// stored selection; the picker wants the mode-filtered view below.+export const speedProfilesForModel = (model) => (+ Array.isArray(model?.speedProfiles) ? model.speedProfiles.filter((p) => p?.id) : []+);+// The profiles that actually apply to THIS mode — what the picker offers, and+// the set a selection must be in to drive the sampler. The mode filter lives+// here rather than at each call site because both consumers need the same+// answer: a profile the server would decline must neither appear in the picker+// nor lock Steps/CFG. Mirrors the server's gate (`speedProfileDeclineReason`),+// pinned by server/lib/videoSpeedProfiles.parity.test.js. An absent mode is the+// default text render. A profile declaring no `modes` falls back to the+// two-stage set — NOT to "unrestricted": the server's decline check applies+// exactly that fallback, and reading a missing field as permissive here would+// offer a profile on fflf that the server then declines. (Such a profile can't+// reach a shipped registry — `validateSpeedProfileTable` strips it — so this is+// belt-and-braces against a hand-edited one, and must not diverge.)+export const DEFAULT_SPEED_PROFILE_MODES = ['text', 'image'];+// Accepts a single mode OR the list of modes a request will actually run in —+// a chained render is one clip whose chunks differ (see videoChainChunkModes),+// and the server applies a profile to such a request only when EVERY chunk+// accepts it. Matching that here is what stops the picker from offering a+// speed-up the chain then declines wholesale.+export const speedProfilesForMode = (model, mode) => {+ const wanted = (Array.isArray(mode) ? mode : [mode]).map((m) => m || 'text');+ const modes = wanted.length > 0 ? wanted : ['text'];+ return speedProfilesForModel(model).filter((p) => {+ const declared = Array.isArray(p.modes) ? p.modes : DEFAULT_SPEED_PROFILE_MODES;+ return modes.every((m) => declared.includes(m));+ });+};++// The modes a request's chunks will run in, mirroring generateChainedVideo's+// own dispatch: chunk 0 keeps the request's mode, and chunks 1+ re-enter as+// `extend` on a window-continuity chain or `image` on a frame hop. The+// window/frame rule mirrors resolveContinuityStrategy in+// server/lib/videoContinuity.js — the same predicate supportsContextWindow+// already mirrors for the Continuity control above.+// `hasSourceImage` mirrors the server's own inference for an ABSENT mode+// (`rest.mode || (rest.sourceImagePath ? 'image' : 'text')`). The panel always+// passes `mode`, so it never fires there — but keeping the fallback identical+// means the two cannot disagree for a caller that omits it, which matters the+// moment a profile ships supporting 'text' but not 'image'.+export const videoChainChunkModes = ({ model, mode, chaining, contextFrames, hasSourceImage = false }) => {+ const first = mode || (hasSourceImage ? 'image' : 'text');+ if (!chaining) return [first];+ // resolveContextFrames (server/lib/videoContinuity.js) reads absent / '' /+ // non-finite as DEFAULT_CONTEXT_FRAMES, NOT as zero — so a request that omits+ // the field chains with a window. Reading it as a frame hop here would show+ // the Fast picker and grey out Steps/CFG for a chain the server then declines+ // wholesale, which is the precise failure this gate exists to prevent.+ const windowHop = resolveContextFramesForDisplay(contextFrames) > 0 && supportsContextWindow(model);+ return [first, windowHop ? 'extend' : 'image'];+};++// Display-side mirror of resolveContextFrames. Only the absent/invalid→default+// rule matters for the gate above; the clamp is the server's business.+export const resolveContextFramesForDisplay = (requested) => {+ if (requested == null || requested === '') return DEFAULT_CONTEXT_FRAMES;+ const n = Number(requested);+ return Number.isFinite(n) ? n : DEFAULT_CONTEXT_FRAMES;+};+// Snap a selection onto what the (possibly just-switched) model declares, so+// the <select> is never left on a value with no matching <option>. Deliberately+// NOT mode-filtered: switching to fflf hides the picker, it must not silently+// rewrite the choice the user makes again when they switch back.+export const normalizeSpeedProfileForModel = (id, model) => (+ speedProfilesForModel(model).some((p) => p.id === id) ? id : DEFAULT_SPEED_PROFILE_ID+);+// Read a profile out of a persisted record (a history entry, a resumed job's+// params). Both record only a NON-default profile, so a missing field means+// Quality — and must CLEAR a leftover selection rather than carry it into a+// render the user asked to reproduce.+export const speedProfileIdFromRecord = (value) => (+ typeof value === 'string' && value ? value : DEFAULT_SPEED_PROFILE_ID+);+// The profile actually driving THIS render, or null for Quality / an unknown id+// / one this mode doesn't support. The picker disables Steps and CFG on exactly+// this — a profile owns both dials together, the same way a `samplerLocked`+// model does — so it must agree with what the server will resolve.+export const selectedSpeedProfile = (id, model, mode = null) => (+ isDefaultSpeedProfileId(id) ? null : speedProfilesForMode(model, mode).find((p) => p.id === id) || null+);+// 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 adiff --git a/client/src/lib/videoGenParams.test.js b/client/src/lib/videoGenParams.test.jsindex cf257a4c93..46a9550a26 100644--- a/client/src/lib/videoGenParams.test.js+++ b/client/src/lib/videoGenParams.test.js@@ -7,6 +7,9 @@ import {supportsVideoAudioControls, supportsVideoAudioPromptControls,IC_LORA_MODES, IC_LORA_MODE_VALUES, isIcLoraMode, icLoraSpecForMode,icResolutionIssue,+ DEFAULT_SPEED_PROFILE_ID, isDefaultSpeedProfileId, speedProfilesForModel,+ speedProfilesForMode, normalizeSpeedProfileForModel,+ speedProfileIdFromRecord, selectedSpeedProfile, videoChainChunkModes,} from './videoGenParams.js';describe('videoModelMemoryGb', () => {@@ -186,4 +189,154 @@ describe('IC-LoRA remix modes (#3100)', () => {expect(icLoraSpecForMode('ic-colorize').uploadLabel).toMatch(/B&W/);});});++// Speed profiles (#4875) — the client-side half of the sentinel + option list.+// Cross-package agreement with the server is pinned separately by+// server/lib/videoSpeedProfiles.parity.test.js.+describe('speed profiles', () => {+ const FAST = { id: 'fast', name: 'Fast', steps: 8, guidance: 1.0, modes: ['text', 'image'] };+ const model = { runtime: 'ltx25', speedProfiles: [FAST] };++ it('reads the server-decorated list and tolerates a model without one', () => {+ expect(speedProfilesForModel(model)).toEqual([FAST]);+ expect(speedProfilesForModel({})).toEqual([]);+ expect(speedProfilesForModel(null)).toEqual([]);+ // A malformed entry must not reach the <option> map as a keyless row.+ expect(speedProfilesForModel({ speedProfiles: [FAST, {}, null] })).toEqual([FAST]);+ });++ it('snaps an unknown or stale selection back to the default', () => {+ expect(normalizeSpeedProfileForModel('fast', model)).toBe('fast');+ expect(normalizeSpeedProfileForModel('turbo', model)).toBe(DEFAULT_SPEED_PROFILE_ID);+ // The case that matters: switching to a model that declares nothing.+ expect(normalizeSpeedProfileForModel('fast', {})).toBe(DEFAULT_SPEED_PROFILE_ID);+ });++ it('reads a record back, treating absence as the default', () => {+ expect(speedProfileIdFromRecord('fast')).toBe('fast');+ for (const v of [undefined, null, '', 7]) {+ expect(speedProfileIdFromRecord(v)).toBe(DEFAULT_SPEED_PROFILE_ID);+ }+ });++ it('treats absence, empty string and the default id as one request', () => {+ for (const v of [undefined, null, '', DEFAULT_SPEED_PROFILE_ID]) {+ expect(isDefaultSpeedProfileId(v)).toBe(true);+ }+ expect(isDefaultSpeedProfileId('fast')).toBe(false);+ });++ // The mode filter is what keeps the picker from offering — and the Steps/CFG+ // lock from honoring — a profile the server would decline.+ it('offers a profile only for the modes it declares', () => {+ expect(speedProfilesForMode(model, 'text')).toEqual([FAST]);+ expect(speedProfilesForMode(model, 'image')).toEqual([FAST]);+ expect(speedProfilesForMode(model, 'fflf')).toEqual([]);+ expect(speedProfilesForMode(model, 'extend')).toEqual([]);+ // An absent mode is the default text render.+ expect(speedProfilesForMode(model, null)).toEqual([FAST]);+ // A profile with no declared modes falls back to the two-stage set, NOT to+ // "unrestricted" — the server's decline check applies exactly that+ // fallback, and reading it permissively here would offer a profile on fflf+ // that the server then declines.+ const noModes = { speedProfiles: [{ id: 'any' }] };+ expect(speedProfilesForMode(noModes, 'text')).toEqual([{ id: 'any' }]);+ expect(speedProfilesForMode(noModes, 'image')).toEqual([{ id: 'any' }]);+ expect(speedProfilesForMode(noModes, 'fflf')).toEqual([]);+ });++ // The bug this guards: with TWO profiles, resolving the selection against the+ // unfiltered list would lock Steps/CFG to one this mode declines.+ it('resolves the active profile against the mode-filtered set', () => {+ const twoProfiles = { speedProfiles: [FAST, { id: 'blitz', steps: 4, guidance: 1, modes: ['fflf'] }] };+ expect(selectedSpeedProfile('blitz', twoProfiles, 'fflf')?.id).toBe('blitz');+ expect(selectedSpeedProfile('blitz', twoProfiles, 'text')).toBeNull();+ expect(selectedSpeedProfile('fast', twoProfiles, 'text')?.id).toBe('fast');+ });++ // Mirrors the server's own inference for an absent mode+ // (`rest.mode || (rest.sourceImagePath ? 'image' : 'text')`) — the two must+ // not disagree the moment a profile ships supporting 'text' but not 'image'.+ it('infers the first chunk mode exactly as the server does when mode is absent', () => {+ const ltx = { runtime: 'ltx25' };+ const modes = (o) => videoChainChunkModes({ model: ltx, chaining: false, ...o });+ expect(modes({ mode: null })).toEqual(['text']);+ expect(modes({ mode: null, hasSourceImage: true })).toEqual(['image']);+ // An explicit mode always wins over the inference.+ expect(modes({ mode: 'fflf', hasSourceImage: true })).toEqual(['fflf']);+ });++ it('derives the chunk modes a chain will actually run in', () => {+ const ltx = { runtime: 'ltx25' };+ const nonLtx = { runtime: 'wan22' };+ // Window continuity needs BOTH a positive window and an extend pipeline.+ expect(videoChainChunkModes({ model: ltx, mode: 'text', chaining: true, contextFrames: 22 }))+ .toEqual(['text', 'extend']);+ expect(videoChainChunkModes({ model: ltx, mode: 'text', chaining: true, contextFrames: 0 }))+ .toEqual(['text', 'image']);+ expect(videoChainChunkModes({ model: nonLtx, mode: 'text', chaining: true, contextFrames: 22 }))+ .toEqual(['text', 'image']);+ // Not chaining → one chunk, whatever the continuity setting says.+ expect(videoChainChunkModes({ model: ltx, mode: 'text', chaining: false, contextFrames: 22 }))+ .toEqual(['text']);+ });++ // resolveContextFrames reads absent / '' / non-finite as the 22-frame+ // DEFAULT, not as zero. Reading it as a frame hop here would show the Fast+ // picker (and grey out Steps/CFG) for a chain the server declines wholesale.+ it('treats an omitted contextFrames as the windowed default, exactly as the server does', () => {+ const ltx = { runtime: 'ltx25' };+ const modes = (contextFrames) => videoChainChunkModes({ model: ltx, mode: 'text', chaining: true, contextFrames });+ for (const absent of [undefined, null, '', Number.NaN, 'nonsense']) {+ expect(modes(absent)).toEqual(['text', 'extend']);+ }+ // An explicit 0 is a REAL value — it opts back into last-frame chaining.+ expect(modes(0)).toEqual(['text', 'image']);+ expect(modes('0')).toEqual(['text', 'image']);+ expect(modes(22)).toEqual(['text', 'extend']);+ });++ // The exact expression the submit builder uses+ // (`selectedSpeedProfile(id, model, videoChainChunkModes(...))?.id`). It must+ // agree with the PICKER's gate, or the form posts a schedule it already+ // decided doesn't apply — which the route then persists, echoes back on+ // reload, and seeds into a Retry as a profile the render never used.+ describe('submit gate matches the picker gate', () => {+ const model = { runtime: 'ltx25', speedProfiles: [FAST] };+ const submitted = (ctx) => selectedSpeedProfile(+ ctx.speedProfileId, model, videoChainChunkModes({ model, ...ctx }),+ )?.id;++ it('posts the profile for a request it really applies to', () => {+ expect(submitted({ speedProfileId: 'fast', mode: 'text', chaining: false })).toBe('fast');+ expect(submitted({ speedProfileId: 'fast', mode: 'image', chaining: false })).toBe('fast');+ });++ it('drops a stale selection after the user switches to an unsupported mode', () => {+ // The picker hides and Steps/CFG unlock, but state still holds 'fast'.+ expect(submitted({ speedProfileId: 'fast', mode: 'fflf', chaining: false })).toBeUndefined();+ expect(submitted({ speedProfileId: 'fast', mode: 'extend', chaining: false })).toBeUndefined();+ });++ it('drops it after the user raises Chunks onto a window-continuity chain', () => {+ expect(submitted({ speedProfileId: 'fast', mode: 'text', chaining: true, contextFrames: 22 }))+ .toBeUndefined();+ // …but keeps it on a frame hop, where every chunk qualifies.+ expect(submitted({ speedProfileId: 'fast', mode: 'text', chaining: true, contextFrames: 0 }))+ .toBe('fast');+ });++ it('posts nothing for the default profile', () => {+ expect(submitted({ speedProfileId: DEFAULT_SPEED_PROFILE_ID, mode: 'text', chaining: false }))+ .toBeUndefined();+ });+ });++ it('resolves the selected profile object, or null for the default', () => {+ expect(selectedSpeedProfile('fast', model, 'text')).toBe(FAST);+ expect(selectedSpeedProfile(DEFAULT_SPEED_PROFILE_ID, model, 'text')).toBeNull();+ expect(selectedSpeedProfile('fast', {}, 'text')).toBeNull();+ });+});+// @vitest-environment nodediff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex a2c7677983..01ef9408ca 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -162,6 +162,8 @@ export default function VideoGen() {contextFrames, setContextFrames,steps, setSteps, guidanceScale, setGuidanceScale, imageStrength, setImageStrength,i2vReferenceMode, setI2vReferenceMode, referenceModeSupported, effectiveImageStrength,++ speedProfileId, setSpeedProfileId,seed, setSeed, handleRandomSeed, tiling, setTiling,textEncoderId, setTextEncoderId, textEncoderOptions,disableAudio, setDisableAudio, noMusic, setNoMusic,@@ -1350,6 +1352,7 @@ export default function VideoGen() {seed={seed} onSeedChange={setSeed} onRandomSeed={handleRandomSeed}steps={steps} onStepsChange={setSteps}guidanceScale={guidanceScale} onGuidanceScaleChange={setGuidanceScale}+ speedProfileId={speedProfileId} onSpeedProfileChange={setSpeedProfileId}imageStrength={imageStrength} onImageStrengthChange={setImageStrength}i2vReferenceMode={i2vReferenceMode} onI2vReferenceModeChange={setI2vReferenceMode}effectiveImageStrength={effectiveImageStrength}diff --git a/data.reference/media-models.json b/data.reference/media-models.jsonindex c77e169a1d..698f39d432 100644--- a/data.reference/media-models.json+++ b/data.reference/media-models.json@@ -98,7 +98,25 @@},"estimatedDownloadGb": 67.7,"reviewedAt": "2026-08-09"- }+ },+ "speedProfiles": [+ {+ "id": "fast",+ "name": "Fast",+ "description": "Validated 8+3-step two-stage schedule at CFG 1.0 with stage-1 TeaCache. Softer detail and weaker prompt adherence than Quality.",+ "speedupLabel": "~35-45% faster",+ "steps": 8,+ "stage2Steps": 3,+ "guidance": 1,+ "teacache": true,+ "teacacheThresh": null,+ "requiresAdapter": "ltx-2.5-22b-distilled-lora-450.safetensors",+ "modes": [+ "text",+ "image"+ ]+ }+ ]},{"id": "minimax_h3_8bit",diff --git a/docs/README.md b/docs/README.mdindex 401810e81c..558bc565ca 100644--- a/docs/README.md+++ b/docs/README.md@@ -40,7 +40,7 @@ Identity & self: [digital-twin](./features/digital-twin.md) · [identity-system]Knowledge: [brain-system](./features/brain-system.md) · [messages-security](./features/messages-security.md)-Create: [writers-room](./features/writers-room.md) · [fableloom](./features/fableloom.md) · [openworld](./features/openworld.md) · [sprite-export-contract](./features/sprite-export-contract.md) · [video-text-encoders](./features/video-text-encoders.md)+Create: [writers-room](./features/writers-room.md) · [fableloom](./features/fableloom.md) · [openworld](./features/openworld.md) · [sprite-export-contract](./features/sprite-export-contract.md) · [video-text-encoders](./features/video-text-encoders.md) · [video-speed-profiles](./features/video-speed-profiles.md)Comms & voice: [openclaw-operator-chat](./features/openclaw-operator-chat.md) ([pre-build audit](./research/2026-03-31-openclaw-operator-chat-audit.md)) · [stacker-news](./features/stacker-news.md) · [voice](./features/voice.md)diff --git a/docs/features/video-speed-profiles.md b/docs/features/video-speed-profiles.mdnew file mode 100644index 0000000000..5d6fbf8206--- /dev/null+++ b/docs/features/video-speed-profiles.md@@ -0,0 +1,141 @@+# Video speed profiles++A **speed profile** is a named, pre-validated sampler configuration a user picks+in Video Gen instead of hand-tuning Steps and CFG. Selecting one swaps the whole+schedule at once — stage-1 and stage-2 step counts, guidance, and runtime+acceleration levers such as TeaCache — for a documented wall-time saving.++Shipped today: **Fast** on `ltx25_mlx_q8` (LTX-2.5 MLX Q8), labelled+`~35-45% faster`.++That label is deliberately conservative and traceable to the only numbers this+repo can cite: the step schedule measured ~30-35% off wall time in the+`PORTOS_T2V_TWO_STAGE` experiment (~1.4-1.5x), and the pin documents ~1.2x for+TeaCache at its calibrated threshold — ~1.7-1.85x combined. It is deliberately+not "2x", which would outrun the evidence, and on a pin without the TeaCache+kwarg the cache half degrades away entirely. Raise it only against an A/B+measured on 2.5 itself.++## Why it exists++The pinned `ltx-2-mlx` two-stage pipeline has always accepted+`enable_teacache` / `teacache_thresh` on `generate_and_save`, and PortOS never+passed either — so every LTX T2V/I2V render left a real, upstream-calibrated+speed lever switched off. The step schedule itself was also only reachable+through the hidden `PORTOS_T2V_TWO_STAGE` env experiment, which fires on a+"plain default render" heuristic and cannot be seen, chosen, or recorded.++This feature promotes that schedule to a user-facing choice, adds the TeaCache+lever alongside it, and — the part that makes it honest — reports what the+runner *actually* managed to apply.++## The honesty contract++Three rules govern the whole feature.++**1. Quality is a no-op, not a variant.** `SPEED_PROFILE_DEFAULT_ID`+(`'quality'`) resolves to `null`. A default render builds byte-identical spawn+args to one from before this feature existed and stamps no extra history+fields. Absence and `'quality'` are the same request on the client, in the+route, and in the service.++**2. An incompatible request degrades — it never 400s and never half-applies.**+A knob that only makes a render faster must not reject a submitted job. When a+profile can't apply, the render proceeds at the model's own sampler and the+reason is logged. `speedProfileDeclineReason()` returns (rather than throws) one+of:++| Code | When |+| --- | --- |+| `SPEED_PROFILE_UNSUPPORTED` | the model declares no such profile — including a forked/custom entry, or one whose `repo`/`revision` moved off the validated pin |+| `SPEED_PROFILE_MODE_UNSUPPORTED` | the mode routes through a different pipeline (`fflf`, `extend`, `a2v`, `ic-*`) than the schedule was measured on |+| `SPEED_PROFILE_SAMPLER_LOCKED` | the model pins its own validated schedule, so a profile would be a second authority over the same dials |++The UI applies the same mode gate, so a profile the server would decline is+never offered — a picker entry that silently does nothing is exactly the dead+speed affordance this replaces.++**Chained renders decline as a unit.** A chain is one clip, but its chunks do+not all run in the request's mode: chunk 0 keeps it, and chunks 1+ re-enter as+`extend` on a window-continuity chain (the default) or `image` on a frame hop.+`extend` routes through `ExtendPipeline`, which no two-stage profile is+validated for — so applying the profile per chunk would render chunk 0 fast and+the rest at the model default, stitching a visible seam mid-clip and inflating+the chain ETA. `resolveVideoSpeedProfileForModes()` therefore applies the+profile to every chunk or to none, and the decision is made once and pushed+down rather than re-derived per chunk.++**3. An unavailable lever is reported, not assumed.** Two questions can only be+answered inside the render process: is the pinned pipeline new enough to accept+`enable_teacache`, and is the distilled adapter the schedule was measured with+actually inside the model pack? `scripts/generate_ltx2.py` probes both, emits a+`STATUS:` line for each one it can't apply, and finishes with a single+`SPEEDPROFILE:<json>` line naming the outcome:++```json+{"id":"fast","steps":8,"stage2Steps":3,"cfgScale":1.0,+ "teacache":false,"teacacheThresh":null,+ "adapter":"ltx-2.3-22b-distilled-lora-384.safetensors",+ "degraded":["teacache","adapter"]}+```++The render still happens at the profile's step schedule; it is just slower than+the label promises, and the user is told so rather than left with a stopwatch —+both live (a `STATUS:` line during the render) and after the fact (the lightbox+shows `Speed profile: fast — reduced: teacache unavailable`).++## Where each piece lives++| Concern | Location |+| --- | --- |+| The declarative table + all resolution logic | `server/lib/videoSpeedProfiles.js` |+| Attached to registry entries at load | `applyVideoSpeedProfiles` in `server/lib/mediaModels.js` |+| Durable on disk for existing installs | `scripts/migrations/295-video-speed-profiles.js` |+| Request field | `speedProfileId` in `LOCAL_ONLY_VIDEO_PARAMS` (`server/routes/videoGen.js`) |+| Applied to the render | `resolveVideoSpeedProfile` + `resolveVideoSampler` in `server/services/videoGen/local.js` |+| Runner levers + capability probe | `--speed-profile` / `--teacache` / `--require-adapter` in `scripts/generate_ltx2.py` |+| Outcome parsed back | `SPEEDPROFILE:` in `server/services/videoGen/generateVideoHelpers.js` |+| Picker | `client/src/components/videoGen/AdvancedParamsPanel.jsx` |++## Sampler precedence++`resolveVideoSampler()` is the single place this is decided, shared by the+render path and the chained-render ETA so the two cannot drift:++1. `model.samplerLocked` — the model's own validated schedule, over everything.+2. An applicable speed profile — drives steps **and** guidance together.+3. An explicit `steps` / `guidanceScale` from the request.+4. The model's registry defaults.++A profile outranking explicit values is deliberate, and mirrors `samplerLocked`:+the UI disables both inputs while a profile is active, and a direct API caller+that sends both gets the profile it asked for rather than a hybrid whose speed+claim would be false.++## ETA bucketing++`server/services/videoGen/eta.js` scopes its samples to the model **and** the+speed profile. Unlike mode and LoRAs — which that module deliberately leaves out+of the sample key — a profile moves the cost curve's *slope* rather than adding+variance around it (CFG 1.0 drops the negative branch entirely, stage 2 runs+fewer steps, TeaCache skips residuals). Pooling the buckets would systematically+over-estimate every fast render and under-estimate every quality one.++The cost is that the first renders on a newly-picked profile show no estimate at+all. That is the same contract a newly-added model already has, and this module+treats a confidently wrong number as strictly worse than none.++## Adding a profile++1. Add it to `VIDEO_SPEED_PROFILES` under the entry id, with `shippedRepo` and+ `shippedRevision` set to the weights the schedule was **measured** against.+ Both are guarded: a re-pointed entry keeps no profile.+2. Set `modes` to only the modes that route through the pipeline you measured.+3. Name any adapter the schedule depends on in `requiresAdapter`, so a pack+ without it degrades loudly instead of rendering slower than the label claims.+4. Regenerate `data.reference/media-models.json` and extend migration 295's+ coverage if you are shipping to an entry id it does not already reach.++`validateSpeedProfileTable()` / `sanitizeSpeedProfiles()` warn about and strip a+malformed profile at load, so a hand-edited `data/media-models.json` can never+offer a schedule that would spawn a broken render.diff --git a/scripts/generate_ltx2.py b/scripts/generate_ltx2.pyindex 24cbea81f1..46f507be2d 100644--- a/scripts/generate_ltx2.py+++ b/scripts/generate_ltx2.py@@ -324,6 +324,151 @@ def _teacache_thresh_label(thresh: float | None) -> str:return f"{thresh}" if thresh is not None else "upstream default 0.5"+# ---------------------------------------------------------------------------+# Speed profiles (#4875)+#+# PortOS picks a named schedule declaratively (server/lib/videoSpeedProfiles.js)+# and hands it here as ordinary --steps/--stage2-steps/--cfg-scale plus the+# levers only this process can check: is the pinned two-stage pipeline new+# enough to accept `enable_teacache`, and is the distilled adapter the schedule+# was measured with actually inside the model pack?+#+# Neither question is fatal. A profile whose TeaCache is unavailable still+# renders at its step schedule — it is just slower than the label promises, and+# THAT is the thing the user must be told rather than left to infer from a+# stopwatch. So each unavailable lever is recorded in `degraded`, announced as a+# STATUS line, and reported to PortOS on a single SPEEDPROFILE: line that the+# history record keeps beside the requested profile id.+# ---------------------------------------------------------------------------++_SPEED_PROFILE_REPORT: dict = {}+++def _accepts_kwarg(fn, name: str) -> bool:+ """Does `fn` declare an EXPLICIT keyword parameter called `name`?++ Used to probe the pinned pipeline rather than assume a version.++ Deliberately strict in both directions:+ - a signature that can't be read at all is False, since a wrong True+ means a TypeError mid-render rather than a slow one;+ - a bare `**kwargs` is ALSO False. Such a wrapper would accept the+ argument without erroring, but nothing says it forwards it — and+ reporting `teacache: true` for a render that got no acceleration is+ exactly the misleading speed claim this feature exists to prevent.+ Degrading on an un-introspectable wrapper costs a real speed-up only+ in a case we cannot verify anyway.++ The KIND is checked, not just the name: a positional-only parameter (or a+ `**name` catch-all that happens to be spelled the same) matches by name but+ cannot be passed by keyword, so accepting it would raise TypeError at the+ call — the very outcome the probe exists to avoid.+ """+ try:+ params = inspect.signature(fn).parameters+ except (TypeError, ValueError):+ return False+ param = params.get(name)+ return param is not None and param.kind in (+ inspect.Parameter.POSITIONAL_OR_KEYWORD,+ inspect.Parameter.KEYWORD_ONLY,+ )+++def speed_profile_begin(args: argparse.Namespace) -> None:+ """Start a speed-profile report for this render. No-op without a profile."""+ global _SPEED_PROFILE_REPORT+ if not args.speed_profile:+ _SPEED_PROFILE_REPORT = {}+ return+ _SPEED_PROFILE_REPORT = {+ "id": args.speed_profile,+ "steps": args.steps,+ "stage2Steps": args.stage2_steps,+ "cfgScale": args.cfg_scale,+ "teacache": False,+ "teacacheThresh": args.teacache_thresh,+ "adapter": None,+ "degraded": [],+ }+++def speed_profile_degrade(lever: str, message: str) -> None:+ """Record a lever this render could not apply, and say so out loud."""+ if not _SPEED_PROFILE_REPORT:+ return+ if lever not in _SPEED_PROFILE_REPORT["degraded"]:+ _SPEED_PROFILE_REPORT["degraded"].append(lever)+ emit_status(message)+++def speed_profile_applied(**fields) -> None:+ """Record levers that DID apply (teacache=True, adapter=<filename>, …)."""+ if not _SPEED_PROFILE_REPORT:+ return+ _SPEED_PROFILE_REPORT.update(fields)+++def speed_profile_emit() -> None:+ """Emit the SPEEDPROFILE: line PortOS stamps onto the history record.++ Best-effort, exactly like emit_runtime_fingerprint: a reporting failure+ must never abort a render that is otherwise fine.+ """+ if not _SPEED_PROFILE_REPORT:+ return+ try:+ print(f"SPEEDPROFILE:{json.dumps(_SPEED_PROFILE_REPORT)}", file=sys.stderr, flush=True)+ except Exception as err: # pragma: no cover - defensive+ print(f"⚠️ speed profile report failed: {err}", file=sys.stderr, flush=True)+++def _two_stage_teacache_kwargs(generate_and_save, args: argparse.Namespace) -> dict:+ """TeaCache kwargs for the two-stage pipeline, or {} when unavailable.++ `enable_teacache` landed on `TI2VidTwoStagesPipeline.generate_and_save`+ after the pipelines were renamed; a pre-rename pin has the two-stage path+ but not the kwarg, and passing it there is a TypeError, not a slow render.+ """+ if not args.teacache:+ return {}+ if not _accepts_kwarg(generate_and_save, "enable_teacache"):+ speed_profile_degrade(+ "teacache",+ "TeaCache unavailable at this ltx-2-mlx pin — rendering the profile's "+ "step schedule without cache acceleration (slower than the profile's estimate).",+ )+ return {}+ kwargs = {"enable_teacache": True}+ # `teacache_thresh` is probed SEPARATELY rather than assumed to ride along+ # with `enable_teacache`. A pin that carries one but not the other would+ # raise TypeError on the call — turning a lever we could not apply into a+ # failed render, which is the one outcome this whole path exists to avoid.+ #+ # When the profile declares NO override there is nothing to lose: the kwarg+ # is omitted and the pin applies its own calibrated default (0.5), which is+ # exactly what the profile wanted. But when the profile named a specific+ # threshold and the pin cannot take it, the render samples at a DIFFERENT+ # threshold than the schedule specifies — a partly-applied profile, so it+ # is recorded as degraded rather than reported as a clean full run.+ if args.teacache_thresh is not None:+ if _accepts_kwarg(generate_and_save, "teacache_thresh"):+ kwargs["teacache_thresh"] = args.teacache_thresh+ else:+ speed_profile_applied(teacacheThresh=None)+ speed_profile_degrade(+ "teacacheThresh",+ f"This ltx-2-mlx pin takes no TeaCache threshold override, so the "+ f"profile's {args.teacache_thresh} is not in effect — sampling at the "+ "pin's own calibrated default instead.",+ )+ speed_profile_applied(teacache=True)+ emit_status(+ f"TeaCache active on Stage 1 (thresh={_teacache_thresh_label(kwargs.get('teacache_thresh'))})"+ )+ return kwargs++def configure_negative_prompt(negative_prompt: str) -> None:"""Thread PortOS' negative prompt into ltx-2-mlx's CFG encoder.@@ -545,9 +690,25 @@ def parse_args() -> argparse.Namespace:help="Disable TeaCache acceleration for supported LTX-2 denoise loops ""(extend and a2v Stage 1).")p.add_argument("--teacache-thresh", type=float, default=None,- help="rel_l1_thresh for TeaCache on extend/a2v Stage 1. Higher = more "+ help="rel_l1_thresh for TeaCache on extend/a2v Stage 1, and on the "+ "two-stage T2V/I2V Stage 1 when --teacache is passed. Higher = more ""skipping = faster but lower fidelity (~1.2x at 0.5, up to ~3x at 1.5). ""Omit to use the pipeline default (0.5).")+ p.add_argument("--speed-profile", default=None,+ help="Name of the PortOS speed profile driving this render "+ "(server/lib/videoSpeedProfiles.js). Purely a label: the schedule "+ "itself arrives as --steps/--stage2-steps/--cfg-scale. Enables the "+ "SPEEDPROFILE: report naming which levers actually applied.")+ p.add_argument("--teacache", action="store_true",+ help="Request TeaCache on the two-stage T2V/I2V Stage 1 denoise loop. "+ "Off by default there (unlike extend/a2v, where it is on unless "+ "--no-teacache). Degrades with an explicit status when the pinned "+ "pipeline predates the enable_teacache kwarg.")+ p.add_argument("--require-adapter", default=None,+ help="Distilled adapter filename this render's speed profile was "+ "measured with. Reported as degraded (never fatal) when the model "+ "pack does not carry it, so a slower render is never presented as "+ "the profile's validated speed.")p.add_argument("--gemma-max-length", type=int, default=None,help="Gemma prompt-encode sequence length (LTX2_GEMMA_MAX_LENGTH; ""upstream default 1024). PortOS lowers this on its one-shot "@@ -1051,7 +1212,7 @@ def _one_stage_kwargs(args: argparse.Namespace, **extra) -> dict:return kwargs-def _prefer_distilled_lora(pipe, requested: str | None) -> str:+def _prefer_distilled_lora(pipe, requested: str | None, required: str | None = None) -> str:"""Select the newest compatible distilled adapter already in model_dir.BasePipeline resolves a HuggingFace repo ID to its cached snapshot during@@ -1059,6 +1220,11 @@ def _prefer_distilled_lora(pipe, requested: str | None) -> str:That gives the bridge a safe point to prefer the 1.1 adapter withoutmaking a separate Hub metadata request. Repositories that do not carry 1.1keep using the legacy file; an explicit CLI value always wins.++ `required` is the adapter a speed profile's schedule was measured against+ (--require-adapter). Its absence from the pack is NOT fatal — the render+ proceeds on whatever adapter is there — but it is reported as a degraded+ lever so the profile's speed claim isn't presented as if it held."""selected = requestedif selected is None:@@ -1072,6 +1238,15 @@ def _prefer_distilled_lora(pipe, requested: str | None) -> str:)pipe._distilled_lora = selectedemit_status(f"Using distilled adapter {selected}")+ if required and selected != required:+ speed_profile_degrade(+ "adapter",+ f"Speed profile expects the {required} adapter, which this model pack "+ f"does not carry — rendering with {selected} instead (slower than the "+ "profile's estimate).",+ )+ else:+ speed_profile_applied(adapter=selected)return selected@@ -1094,11 +1269,16 @@ def run_two_stage(args: argparse.Namespace, image: str | None = None) -> str:distilled_lora_strength=args.lora_strength,**_gemma_kwargs(args),)- _prefer_distilled_lora(pipe, args.distilled_lora)+ _prefer_distilled_lora(pipe, args.distilled_lora, args.require_adapter)_apply_user_loras(pipe, args.user_lora_specs)bind_output_fps(pipe, args.fps)emit_stage(1, 1, 1, "Loaded")emit_status("Generating with CFG…")+ # Speed-profile TeaCache. Probed against THIS pin's signature rather than+ # assumed, and reported as degraded when the kwarg isn't there — see+ # _two_stage_teacache_kwargs. {} on every non-profile render, so a quality+ # render calls generate_and_save with exactly the arguments it always did.+ teacache_kwargs = _two_stage_teacache_kwargs(pipe.generate_and_save, args)return _run_with_ltx_stepwise_preview(pipe, args, lambda: pipe.generate_and_save(prompt=args.prompt,output_path=args.output,@@ -1109,6 +1289,7 @@ def run_two_stage(args: argparse.Namespace, image: str | None = None) -> str:stage1_steps=args.steps if args.steps is not None else 30,stage2_steps=args.stage2_steps,cfg_scale=args.cfg_scale if args.cfg_scale is not None else 3.0,+ **teacache_kwargs,**_image_conditioning_kwargs(pipe.generate_and_save, image, args.image_strength,args.i2v_reference_mode),**_rate_kwargs(pipe.generate_and_save, args.fps),@@ -1525,7 +1706,22 @@ def main() -> NoReturn:"ic": run_ic_lora,}runner = runners[args.mode]+ # Opens the speed-profile report (no-op without --speed-profile); the+ # runner fills in which levers applied, and the reconcile below catches the+ # case where the chosen pipeline path never reached the lever at all — e.g.+ # a caller that omitted --cfg-scale, so `text` took the one-stage pipeline+ # that has no Stage-1 TeaCache to enable. Reported as degraded rather than+ # left silently absent, which would read back as "the profile applied".+ speed_profile_begin(args)saved_path = runner(args)+ if args.teacache and not _SPEED_PROFILE_REPORT.get("teacache") \+ and "teacache" not in _SPEED_PROFILE_REPORT.get("degraded", []):+ speed_profile_degrade(+ "teacache",+ f"TeaCache was requested but the {args.mode} render did not route through a "+ "pipeline that supports it — rendering without cache acceleration.",+ )+ speed_profile_emit()if args.no_audio:maybe_strip_audio(saved_path)diff --git a/scripts/generate_ltx2.test.js b/scripts/generate_ltx2.test.jsindex 8e1813375b..326543515f 100644--- a/scripts/generate_ltx2.test.js+++ b/scripts/generate_ltx2.test.js@@ -569,3 +569,237 @@ describe.skipIf(!pyBin)('generate_ltx2.py', () => {expect(output.trim()).toBe('/tmp/previews');});});++// Speed profiles (#4875). The Node side decides the schedule declaratively;+// this process owns the two questions only it can answer — is the pinned+// pipeline new enough for `enable_teacache`, and is the required distilled+// adapter in the pack — and reports both back on one SPEEDPROFILE: line. All+// stdlib-only, so no mlx/ltx wheel is needed here.+describe.skipIf(!pyBin)('generate_ltx2.py speed-profile reporting', () => {+ const PROFILE_ARGS = [+ 'import argparse',+ 'def ns(**kw):',+ " d = dict(speed_profile='fast', steps=8, stage2_steps=3, cfg_scale=1.0,",+ " teacache=True, teacache_thresh=None, require_adapter='needed.safetensors', mode='text')",+ ' d.update(kw)',+ ' return argparse.Namespace(**d)',+ // Capture the STATUS:/SPEEDPROFILE: lines the helper writes to stderr.+ 'import contextlib, io',+ 'ERR = io.StringIO()',+ ].join('\n');++ const runProfile = (body) => runPython(`${importRunner}\n${PROFILE_ARGS}\n${body}`);++ // Python's print() ends lines with \r\n on Windows, so a plain split('\n')+ // leaves a trailing \r that trim()-ing the whole output cannot reach.+ const outLines = (out) => out.trim().split(/\r?\n/).map((l) => l.trimEnd());++ // A pin that HAS the kwarg (the shipped one) vs a pre-rename pin that does+ // not. The second case is the one that matters: passing the kwarg there is a+ // TypeError mid-render, not a slow render.+ const PIN_DEFS = [+ 'def modern(self, prompt, output_path, *, frame_rate, stage1_steps=None, enable_teacache=False, teacache_thresh=None): ...',+ 'def legacy(self, prompt, output_path, *, frame_rate, stage1_steps=None): ...',+ 'def kwargs_pin(self, prompt, output_path, **kw): ...',+ ].join('\n');++ it('passes the TeaCache kwargs through on a pin that accepts them', () => {+ const out = runProfile([+ PIN_DEFS,+ 'runner.speed_profile_begin(ns())',+ 'with contextlib.redirect_stderr(ERR):',+ ' kw = runner._two_stage_teacache_kwargs(modern, ns())',+ "print(sorted(kw.items()))",+ "print(runner._SPEED_PROFILE_REPORT['teacache'], runner._SPEED_PROFILE_REPORT['degraded'])",+ ].join('\n'));+ // No threshold override declared, so the kwarg is omitted entirely and+ // the pin applies its own calibrated default (0.5) — passing None would+ // just re-state the default through an argument some pins don't have.+ expect(out).toContain("[('enable_teacache', True)]");+ expect(out).toContain('True []');+ });++ // A bare **kwargs wrapper ACCEPTS the argument without erroring, but nothing+ // says it forwards it — so claiming the speed-up would be exactly the+ // misleading claim this whole path exists to prevent. Degrade instead.+ it('degrades on a bare **kwargs pin rather than claiming an unverifiable speed-up', () => {+ const out = runProfile([+ PIN_DEFS,+ 'runner.speed_profile_begin(ns())',+ 'with contextlib.redirect_stderr(ERR):',+ ' kw = runner._two_stage_teacache_kwargs(kwargs_pin, ns())',+ "print(kw, runner._SPEED_PROFILE_REPORT['teacache'], runner._SPEED_PROFILE_REPORT['degraded'])",+ ].join('\n'));+ expect(out.trim()).toBe("{} False ['teacache']");+ });++ // A pin carrying enable_teacache but NOT teacache_thresh must not be handed+ // the second kwarg — that is a TypeError mid-render, i.e. a lever we could+ // not apply turned into a failed render.+ // A positional-only parameter (or a `**name` catch-all spelled the same)+ // matches by NAME but cannot be passed by keyword — accepting it would raise+ // TypeError at the call, the very outcome the probe exists to avoid.+ it('rejects a same-named parameter that cannot actually be passed by keyword', () => {+ const out = runProfile([+ // positional-only (PEP 570) and a catch-all that happens to share the name+ 'def positional_only(self, enable_teacache=False, /, *, frame_rate=24): ...',+ 'def catch_all(self, *, frame_rate=24, **enable_teacache): ...',+ 'def keyword_ok(self, *, frame_rate=24, enable_teacache=False): ...',+ "print(runner._accepts_kwarg(positional_only, 'enable_teacache'))",+ "print(runner._accepts_kwarg(catch_all, 'enable_teacache'))",+ "print(runner._accepts_kwarg(keyword_ok, 'enable_teacache'))",+ ].join('\n'));+ expect(outLines(out)).toEqual(['False', 'False', 'True']);+ });++ it('probes teacache_thresh separately from enable_teacache', () => {+ const out = runProfile([+ 'def enable_only(self, prompt, output_path, *, frame_rate, stage1_steps=None, enable_teacache=False): ...',+ 'runner.speed_profile_begin(ns(teacache_thresh=0.8))',+ 'with contextlib.redirect_stderr(ERR):',+ ' kw = runner._two_stage_teacache_kwargs(enable_only, ns(teacache_thresh=0.8))',+ 'print(sorted(kw.items()))',+ // TeaCache itself applied, but the profile asked to sample at 0.8 and the+ // render did not — a partly-applied profile, so it is recorded as such+ // rather than reported as a clean full run.+ "print(runner._SPEED_PROFILE_REPORT['teacache'], runner._SPEED_PROFILE_REPORT['degraded'])",+ "print(runner._SPEED_PROFILE_REPORT['teacacheThresh'])",+ ].join('\n'));+ const [kw, state, thresh] = outLines(out);+ expect(kw).toBe("[('enable_teacache', True)]");+ expect(state).toBe("True ['teacacheThresh']");+ expect(thresh).toBe('None');+ });++ // The mirror case: NO override declared means nothing was lost — the pin's+ // own calibrated default is exactly what the profile wanted, so this must+ // NOT be reported as degraded.+ it('does not degrade when the profile declared no threshold to lose', () => {+ const out = runProfile([+ 'def enable_only(self, prompt, output_path, *, frame_rate, stage1_steps=None, enable_teacache=False): ...',+ 'runner.speed_profile_begin(ns(teacache_thresh=None))',+ 'with contextlib.redirect_stderr(ERR):',+ ' kw = runner._two_stage_teacache_kwargs(enable_only, ns(teacache_thresh=None))',+ "print(sorted(kw.items()), runner._SPEED_PROFILE_REPORT['degraded'])",+ ].join('\n'));+ expect(out.trim()).toBe("[('enable_teacache', True)] []");+ });++ it('omits teacache_thresh entirely when the profile declares no override', () => {+ const out = runProfile([+ PIN_DEFS,+ 'runner.speed_profile_begin(ns())',+ 'with contextlib.redirect_stderr(ERR):',+ ' kw = runner._two_stage_teacache_kwargs(modern, ns())',+ "print(sorted(kw.items()))",+ ].join('\n'));+ expect(out.trim()).toBe("[('enable_teacache', True)]");+ });++ // The core honesty rule: an unavailable lever degrades LOUDLY. The render+ // still happens at the profile's step schedule; it just isn't presented as+ // the full speed-up.+ it('degrades with an explicit status when the pin predates the kwarg', () => {+ const out = runProfile([+ PIN_DEFS,+ 'runner.speed_profile_begin(ns())',+ 'with contextlib.redirect_stderr(ERR):',+ ' kw = runner._two_stage_teacache_kwargs(legacy, ns())',+ 'print(kw)',+ "print(runner._SPEED_PROFILE_REPORT['degraded'])",+ "print([l for l in ERR.getvalue().splitlines() if l.startswith('STATUS:')])",+ ].join('\n'));+ expect(out).toContain('{}');+ expect(out).toContain("['teacache']");+ expect(out).toMatch(/STATUS:TeaCache unavailable/);+ });++ it('passes an explicit threshold override through', () => {+ const out = runProfile([+ PIN_DEFS,+ 'runner.speed_profile_begin(ns(teacache_thresh=0.8))',+ 'with contextlib.redirect_stderr(ERR):',+ ' kw = runner._two_stage_teacache_kwargs(modern, ns(teacache_thresh=0.8))',+ "print(kw['teacache_thresh'])",+ ].join('\n'));+ expect(out.trim()).toBe('0.8');+ });++ // DEFAULT PRESERVATION: without --speed-profile the whole mechanism is inert.+ it('is completely silent and emits nothing without a profile', () => {+ const out = runProfile([+ PIN_DEFS,+ 'runner.speed_profile_begin(ns(speed_profile=None))',+ 'with contextlib.redirect_stderr(ERR):',+ ' kw = runner._two_stage_teacache_kwargs(modern, ns(speed_profile=None, teacache=False))',+ " runner.speed_profile_degrade('teacache', 'should not appear')",+ ' runner.speed_profile_emit()',+ 'print(kw, runner._SPEED_PROFILE_REPORT, repr(ERR.getvalue()))',+ ].join('\n'));+ expect(out.trim()).toBe("{} {} ''");+ });++ it('never enables TeaCache when the profile did not ask for it', () => {+ const out = runProfile([+ PIN_DEFS,+ 'runner.speed_profile_begin(ns(teacache=False))',+ 'with contextlib.redirect_stderr(ERR):',+ ' kw = runner._two_stage_teacache_kwargs(modern, ns(teacache=False))',+ "print(kw, runner._SPEED_PROFILE_REPORT['degraded'])",+ ].join('\n'));+ expect(out.trim()).toBe('{} []');+ });++ it('emits a single parseable SPEEDPROFILE: line naming what applied', () => {+ const out = runProfile([+ PIN_DEFS,+ 'import json',+ 'runner.speed_profile_begin(ns())',+ 'with contextlib.redirect_stderr(ERR):',+ ' runner._two_stage_teacache_kwargs(modern, ns())',+ " runner.speed_profile_applied(adapter='needed.safetensors')",+ ' runner.speed_profile_emit()',+ "lines = [l for l in ERR.getvalue().splitlines() if l.startswith('SPEEDPROFILE:')]",+ 'print(len(lines))',+ "print(json.dumps(json.loads(lines[0][len('SPEEDPROFILE:'):]), sort_keys=True))",+ ].join('\n'));+ const [count, payload] = outLines(out);+ expect(count).toBe('1');+ expect(JSON.parse(payload)).toEqual({+ id: 'fast',+ steps: 8,+ stage2Steps: 3,+ cfgScale: 1.0,+ teacache: true,+ teacacheThresh: null,+ adapter: 'needed.safetensors',+ degraded: [],+ });+ });++ it('does not repeat a lever already recorded as degraded', () => {+ const out = runProfile([+ 'runner.speed_profile_begin(ns())',+ 'with contextlib.redirect_stderr(ERR):',+ " runner.speed_profile_degrade('teacache', 'first')",+ " runner.speed_profile_degrade('teacache', 'second')",+ "print(runner._SPEED_PROFILE_REPORT['degraded'])",+ ].join('\n'));+ expect(out.trim()).toBe("['teacache']");+ });++ it.each([+ ['omitted', [], ['None', 'False', 'None']],+ ['given', ['--speed-profile', 'fast', '--teacache', '--require-adapter', 'a.safetensors'], ['fast', 'True', 'a.safetensors']],+ ])('parses the speed-profile flags when %s', (_label, extra, expected) => {+ const out = runPython(`${importRunner}\n${[+ 'import sys',+ `sys.argv = ["generate_ltx2.py", "--mode", "text", "--prompt", "p", "--output", "/tmp/o.mp4", "--model", "m"] + ${JSON.stringify(extra)}`,+ 'a = runner.parse_args()',+ 'print(a.speed_profile)',+ 'print(a.teacache)',+ 'print(a.require_adapter)',+ ].join('\n')}`);+ expect(outLines(out)).toEqual(expected);+ });+});diff --git a/scripts/migrations/295-video-speed-profiles.js b/scripts/migrations/295-video-speed-profiles.jsnew file mode 100644index 0000000000..955c1e5b2a--- /dev/null+++ b/scripts/migrations/295-video-speed-profiles.js@@ -0,0 +1,72 @@+/**+ * Attach `speedProfiles` to shipped video models (issue #4875) in existing+ * installs.+ *+ * `data.reference/media-models.json` ships the profiles for fresh installs and+ * `mediaModels.js` backfills them at load — but `data/media-models.json` is the+ * gitignored, user-editable copy that is never merge-updated, so this migration+ * makes the change durable on disk instead of relying on the in-memory backfill+ * running every boot. Same arrangement as migration 237 (disclosures) and 238+ * (Finish edges).+ *+ * Preservation contract (identical to `applyVideoSpeedProfiles`):+ * - an entry that already has a `speedProfiles` key is left alone (user edit,+ * including an explicit `null` / `[]` meaning "no profiles on this model")+ * - an id the user deleted is NOT recreated+ * - a custom / user-added model is untouched (no shipped profile exists)+ * - an entry whose `repo` OR `revision` was re-pointed is skipped — a+ * validated sampler schedule must not be claimed for different weights+ * - entry order is preserved; nothing else on the entry is modified+ *+ * Additive only: an entry the sanitizer merely STRIPPED is never rewritten, so+ * a hand-edited bad profile is left for the load-time sanitizer to warn about+ * rather than being silently deleted from the user's file here.+ */++import { readFile } from 'fs/promises';+import { join } from 'path';+import { atomicWrite } from '../../server/lib/fileUtils.js';+import { applyVideoSpeedProfiles } from '../../server/lib/videoSpeedProfiles.js';+import { LEGACY_VIDEO_BUCKET_KEYS, VIDEO_BUCKETS } from '../../server/lib/mediaModelBuckets.js';++const REL_PATH = 'data/media-models.json';+// Both the canonical (#4142) and the legacy bucket spellings — an install that+// predates the rename can still be on either shape. Only keys actually holding+// an array are touched, so listing all four is safe on both.+const BUCKET_KEYS = [...VIDEO_BUCKETS, ...Object.values(LEGACY_VIDEO_BUCKET_KEYS)];++export default {+ async up({ rootDir }) {+ const path = join(rootDir, REL_PATH);+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) return;+ let config;+ try {+ config = JSON.parse(raw);+ } catch (err) {+ throw new Error(`Cannot migrate ${REL_PATH}: invalid JSON (${err.message})`, { cause: err });+ }+ if (!config?.video || typeof config.video !== 'object') return;++ let profiled = 0;+ for (const platform of BUCKET_KEYS) {+ const list = config.video[platform];+ if (!Array.isArray(list)) continue;+ const next = applyVideoSpeedProfiles(list);+ config.video[platform] = list.map((entry, i) => {+ const gained = Array.isArray(next[i]?.speedProfiles) && !(entry && 'speedProfiles' in entry);+ if (!gained) return entry;+ profiled += 1;+ return next[i];+ });+ }++ if (profiled > 0) {+ await atomicWrite(path, `${JSON.stringify(config, null, 2)}\n`);+ console.log(`📝 ${REL_PATH}: attached speed profiles to ${profiled} video ${profiled === 1 ? 'entry' : 'entries'}`);+ }+ },+};diff --git a/scripts/migrations/295-video-speed-profiles.test.js b/scripts/migrations/295-video-speed-profiles.test.jsnew file mode 100644index 0000000000..31ba0c0bfd--- /dev/null+++ b/scripts/migrations/295-video-speed-profiles.test.js@@ -0,0 +1,144 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './295-video-speed-profiles.js';+import { VIDEO_SPEED_PROFILES } from '../../server/lib/videoSpeedProfiles.js';++const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++const ENTRY_ID = 'ltx25_mlx_q8';+const spec = VIDEO_SPEED_PROFILES[ENTRY_ID];++// The entry as an existing install stores it, pre-migration.+const baseRegistry = (overrides = {}) => ({+ video: {+ macos: [+ {+ id: ENTRY_ID,+ name: 'LTX-2.5 MLX Q8',+ repo: spec.shippedRepo,+ revision: spec.shippedRevision,+ runtime: 'ltx25',+ steps: 8,+ guidance: 3.0,+ ...overrides,+ },+ { id: 'my_custom_model', name: 'My Custom Model', repo: 'example-org/example-video', source: 'user' },+ ],+ windows: [{ id: 'ltx_video', name: 'LTX-Video 0.9.5', runtime: 'cuda_video', steps: 25 }],+ defaultMacos: ENTRY_ID,+ },+});++const findMacos = (path, id) => readJson(path).video.macos.find((e) => e.id === id);++describe('migration 295 — video speed profiles', () => {+ let rootDir;+ let path;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-295-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ path = join(rootDir, 'data', 'media-models.json');+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ vi.restoreAllMocks();+ });++ it('attaches the shipped profiles to a pin-matching entry', async () => {+ writeJson(path, baseRegistry());+ await migration.up({ rootDir });+ const entry = findMacos(path, ENTRY_ID);+ expect(entry.speedProfiles).toHaveLength(spec.profiles.length);+ expect(entry.speedProfiles[0].id).toBe('fast');+ expect(entry.speedProfiles[0].steps).toBe(spec.profiles[0].steps);+ });++ it('leaves everything else on the entry, and its position, untouched', async () => {+ const before = baseRegistry();+ writeJson(path, before);+ await migration.up({ rootDir });+ const after = readJson(path);+ expect(after.video.macos.map((e) => e.id)).toEqual(before.video.macos.map((e) => e.id));+ const { speedProfiles: _added, ...rest } = after.video.macos[0];+ expect(rest).toEqual(before.video.macos[0]);+ expect(after.video.windows).toEqual(before.video.windows);+ expect(after.video.defaultMacos).toBe(ENTRY_ID);+ });++ it('does not touch a custom model', async () => {+ writeJson(path, baseRegistry());+ await migration.up({ rootDir });+ expect(findMacos(path, 'my_custom_model').speedProfiles).toBeUndefined();+ });++ it.each([+ ['an existing profiles key', { speedProfiles: [{ id: 'mine', steps: 4, guidance: 1, modes: ['text'] }] }],+ ['an explicit empty-list opt-out', { speedProfiles: [] }],+ ['an explicit null opt-out', { speedProfiles: null }],+ ])('preserves %s rather than overwriting the user', async (_label, overrides) => {+ writeJson(path, baseRegistry(overrides));+ await migration.up({ rootDir });+ expect(findMacos(path, ENTRY_ID).speedProfiles).toEqual(overrides.speedProfiles);+ });++ // The pin guard: a validated sampler schedule must not be claimed for+ // different weights, whichever half of the pin the user changed.+ it.each([+ ['a forked repo', { repo: 'someone/ltx-2.5-fork' }],+ ['a moved revision', { revision: 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef' }],+ ])('skips an entry with %s', async (_label, overrides) => {+ writeJson(path, baseRegistry(overrides));+ await migration.up({ rootDir });+ expect(findMacos(path, ENTRY_ID).speedProfiles).toBeUndefined();+ });++ it('rewrites nothing (and logs nothing) when there is no entry to profile', async () => {+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});+ const registry = { video: { macos: [{ id: 'my_custom_model', repo: 'example-org/example-video' }] } };+ writeJson(path, registry);+ const before = readFileSync(path, 'utf-8');+ await migration.up({ rootDir });+ expect(readFileSync(path, 'utf-8')).toBe(before);+ expect(log).not.toHaveBeenCalled();+ });++ it('is idempotent — a second run is a no-op', async () => {+ writeJson(path, baseRegistry());+ await migration.up({ rootDir });+ const after = readFileSync(path, 'utf-8');+ await migration.up({ rootDir });+ expect(readFileSync(path, 'utf-8')).toBe(after);+ });++ it('also covers the legacy bucket spellings', async () => {+ writeJson(path, {+ video: {+ mlx: [{+ id: ENTRY_ID, repo: spec.shippedRepo, revision: spec.shippedRevision, runtime: 'ltx25', steps: 8, guidance: 3.0,+ }],+ },+ });+ await migration.up({ rootDir });+ expect(readJson(path).video.mlx[0].speedProfiles).toHaveLength(spec.profiles.length);+ });++ it('is a no-op when the install has no registry file yet', async () => {+ await expect(migration.up({ rootDir })).resolves.toBeUndefined();+ });++ it('is a no-op when video is missing or not an object', async () => {+ writeJson(path, { image: [] });+ await expect(migration.up({ rootDir })).resolves.toBeUndefined();+ });++ it('fails loudly on invalid JSON rather than silently rewriting the file', async () => {+ writeFileSync(path, '{ not json');+ await expect(migration.up({ rootDir })).rejects.toThrow(/invalid JSON/);+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex e3d7306935..8441b6c0c7 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -129,6 +129,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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. || `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` text+image, `minimax_h3` / `minimax_h3_cuda` text+image+fflf off one shared array — also the mode ceiling in `videoGen/modeContract.js` — `hunyuan` text only, replacing the legacy unread `mode: 't2v'` field); `VIDEO_BASE_MODES` is the fallback for an unknown (user-added or peer-synced) runtime, deliberately the full base set so a custom model doesn't vanish from every picker. `resolveVideoSupportedModes(entry)` (declared non-empty list always wins) and `applyVideoSupportedModes(list)` — the read-time decoration `mediaModels.js#getVideoModels` applies, so the derived list never lands in `data/media-models.json` where it would read back as a *declared* list no later correction could reach. a2v and the IC-LoRA remix ids are NOT enumerated here: they're ltx2 pipeline capabilities, gated by runtime (`A2V_REQUIRES_LTX2` / `IC_LORA_REQUIRES_LTX2`). || `videoReferenceModes.js` | The i2v reference-mode contract (#4874) — what a supplied conditioning image PROMISES. `I2V_REFERENCE_MODES` (`anchor` \| `inspire`) + `I2V_REFERENCE_MODE_OPTIONS` (the label + the promise sentence the UI prints), `I2V_REFERENCE_MODE_RUNTIMES` (only `ltx25` can honor `inspire` — it needs per-image conditioning strength), `INSPIRE_DEFAULT_IMAGE_STRENGTH`, plus `normalizeI2vReferenceMode` / `isDefaultI2vReferenceMode` / `isKnownI2vReferenceMode` / `runtimeSupportsI2vReferenceMode` / `i2vReferenceModeLabel` / `resolveI2vReferenceStrength` and the one rule `i2vReferenceModeViolation({ model, mode, referenceMode, hasFirstImage })` → `{ code, message }` or null. Pure (no `ServerError`) because it is MIRRORED to `client/src/lib/videoReferenceModes.js`; `videoGen/modeContract.js#videoReferenceModeError` wraps it for the route + render boundaries. || `videoTextEncoders.js` | Swappable prompt conditioners for local video runtimes. MiniMax H3 reads the *unnormalized* hidden state after Qwen3-VL language layer 49 (layers 50-63, the final norm and `lm_head` are never evaluated), so any checkpoint carrying the same embedding + layers 0-49 + vision tower is a drop-in conditioner — swapping it changes how the model reads a prompt without touching the diffusion weights. `TEXT_ENCODERS_BY_RUNTIME` declares the shipped options per runtime (pinned repo/revision plus an explicit `files` LIST — one repackaged safetensors, or just the shards of an upstream checkpoint that carry parameters the loader actually builds; in code rather than the media-models registry so a stale `data/media-models.json` can't name a file the runner can't map); `videoTextEncoderOptions(model)` returns the TRUE list stock-first (it deliberately does NOT collapse a one-entry runtime to `[]` — that is a presentation rule, and folding it in here would change what the server believes a model supports and empty the "offers …" list in the error; `TextEncoderPicker` owns the hide-when-there-is-no-real-choice check), `isStockTextEncoder(id)` makes absence and the `stock` sentinel the same request, `resolveVideoTextEncoder(model, id)` returns `null` for the stock choice or throws `VIDEO_TEXT_ENCODER_UNSUPPORTED` (with the non-throwing `supportsVideoTextEncoder` + `videoTextEncoderUnsupportedError` split out so the request path can reject before staging uploads), and `downloadableVideoTextEncoders()` (deduped by id — the table is keyed by RUNTIME, so one conditioner can be offered by two) / `downloadableVideoTextEncoder(id)` feed the `/api/video-gen/text-encoders/:id/(download\|repair)` lane. Two loader-mechanics fields exist because a ComfyUI-packaged conditioner is namespaced differently from the HF checkpoint the MLX port matches: `keyPrefixMap` (`model.` → `model.language_model.`, `visual.` → `model.visual.`) is applied to every checkpoint key by `scripts/generate_minimax_h3.py` BEFORE the pinned loader sees it — no fork of the pinned runtime — and `finalNormKey` names where the runner synthesizes a ones-filled `norm.weight` for a checkpoint published without one (correct upstream, since H3 reads the state *before* the norm, but the pinned loader refuses to load with any parameter missing). Both are absent for an UPSTREAM Qwen3-VL-32B checkpoint, which already uses the loader namespace and ships its own norm. A candidate must BE Qwen3-VL-32B (the shim reuses upstream's config/tokenizer/processor) — a different Qwen generation is not a substitute however close its conditioning width looks; see docs/features/video-text-encoders.md. `publicTextEncoderOption(entry)` is the client projection and deliberately drops both, so the UI can't reimplement the remap. The `ltx25` table (#4320) uses a third mechanic, `configOverrides`, because an LTX-2.5 pack's OWN Gemma 4 tower wins over `--gemma` inside the pinned fork: the substitution is a standalone shim directory whose generated `config.json` is the substitute's own with these keys merged over it (only ever the `model_type` label a unified checkpoint gets wrong — never `text_config`/`quantization`), and a candidate must BE Gemma 4 12B at 48 layers / hidden 3840 / vocab 262144 / `k_eq_v`. `verified` gates a substitute out of BOTH lanes (picker AND download) until it has been A/B-rendered against its runtime's stock conditioner — required on every non-built-in entry and fail-closed on absence, so a new entry is unreachable until someone states a verdict; both ltx25 substitutes are `verified: false` today. `declaredVideoTextEncoders()` is the UNFILTERED table for shape/invariant checks only — never the render or download path, and `videoTextEncoderRuntimes()` enumerates the table's runtime keys so parity/shape tests cover every runtime rather than the one that happened to exist when they were written. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 418338a9aa..ea9c523ba8 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -133,6 +133,7 @@ export * from './mediaModels.js';export * from './videoContinuity.js';export * from './videoDisclosure.js';export * from './videoFinishProfiles.js';+export * from './videoSpeedProfiles.js';export * from './videoModeProfiles.js';export * from './videoReferenceModes.js';export * from './videoTextEncoders.js';diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.jsindex 668e5caada..1f4f3d857d 100644--- a/server/lib/mediaModels.js+++ b/server/lib/mediaModels.js@@ -71,6 +71,7 @@ import { RUNNER_FAMILIES } from './runners.js';import { ServerError } from './errorHandler.js';import { applyVideoDisclosures } from './videoDisclosure.js';import { applyVideoFinishProfiles, sanitizeFinishProfiles } from './videoFinishProfiles.js';+import { applyVideoSpeedProfiles, sanitizeSpeedProfiles } from './videoSpeedProfiles.js';import { applyVideoSupportedModes } from './videoModeProfiles.js';// fileUtils.ensureDir is async/Promise-returning; this module needs a// synchronous version because `loadMediaModels()` is called at import-time@@ -263,7 +264,11 @@ const DEFAULT_REGISTRY = {// `applyVideoFinishProfiles` attaches the shipped draft → delivery// `finishModelId` edges (lib/videoFinishProfiles.js) the same way, so the// Finish relationship is declared in one place instead of inline here.- mlx: applyVideoFinishProfiles(applyVideoDisclosures([+ // `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: 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 —@@ -485,8 +490,8 @@ const DEFAULT_REGISTRY = {precision: 'fp32',deprecated: true,},- ])),- cuda: applyVideoFinishProfiles(applyVideoDisclosures([+ ]))),+ cuda: 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@@ -522,7 +527,7 @@ const DEFAULT_REGISTRY = {supportsTiling: false,supportsDisableAudio: false,},- ])),+ ]))),defaultMlx: 'ltx23_distilled_q4',defaultCuda: 'ltx_video',},@@ -1064,7 +1069,12 @@ const normalizeRegistry = (parsed) => {const videoEntries = (entries, { upgradeLegacyCudaLtx = false } = {}) => {const normalized = backfillRuntime(upgradeMiniMaxH3OutputControls(dropRetiredEntries(entries)));const upgraded = upgradeLegacyCudaLtx ? upgradeLegacyCudaLtxRuntime(normalized) : normalized;- return sanitizeFinishProfiles(applyVideoFinishProfiles(applyVideoDisclosures(upgraded)));+ const decorated = sanitizeFinishProfiles(applyVideoFinishProfiles(applyVideoDisclosures(upgraded)));+ // applyVideoSpeedProfiles is the load-time twin of migration 295, and+ // sanitizeSpeedProfiles is its sibling of sanitizeFinishProfiles: a+ // 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.+ return sanitizeSpeedProfiles(applyVideoSpeedProfiles(decorated));};const normalizedBuckets = Object.fromEntries(VIDEO_BUCKETS.map((bucket) => [bucket, videoEntries(bucketResults[bucket].entries, {diff --git a/server/lib/videoSpeedProfiles.js b/server/lib/videoSpeedProfiles.jsnew file mode 100644index 0000000000..bf54862724--- /dev/null+++ b/server/lib/videoSpeedProfiles.js@@ -0,0 +1,466 @@+/**+ * Video render speed profiles (issue #4875).+ *+ * A *speed profile* is a named, pre-validated sampler configuration a user can+ * pick instead of hand-tuning steps and CFG: it swaps the whole schedule at+ * once (stage-1 / stage-2 step counts, guidance, and runtime acceleration+ * levers like TeaCache) for a documented wall-time saving.+ *+ * The relationship between a model and its profiles is DECLARED here — not+ * inferred from a runtime name — and attached to registry entries as+ * `speedProfiles` by `applyVideoSpeedProfiles`, the same load-time backfill+ * pattern `applyVideoDisclosures` (lib/videoDisclosure.js) and+ * `applyVideoFinishProfiles` (lib/videoFinishProfiles.js) use. Migration 295+ * makes it durable on disk for installs that already persisted+ * `data/media-models.json`.+ *+ * ## Why the DEFAULT profile is a first-class entry rather than "absence"+ *+ * `SPEED_PROFILE_DEFAULT_ID` ('quality') is the shipped contract: the exact+ * sampler the model has always rendered with. It exists as a named option so+ * the picker has something to show as selected, but it is deliberately a+ * NO-OP — `resolveVideoSpeedProfile` returns `null` for it, so a quality render+ * builds byte-identical spawn args to a render from before this feature+ * existed, and stamps no extra history fields. Absence and `'quality'` are the+ * same request (`isDefaultSpeedProfile`), exactly as `'stock'` and absence are+ * the same request in lib/videoTextEncoders.js.+ *+ * ## Why compatibility is checked rather than assumed+ *+ * A profile's numbers are validated against ONE pipeline on ONE set of weights.+ * Applying them anywhere else would be a speed claim we cannot back:+ *+ * - **Weights.** `shippedRepo` + `shippedRevision` must both still match the+ * entry. A user who re-pointed `repo` at a fork, or moved `revision` off+ * the pin the schedule was measured against, keeps no profile rather than+ * inheriting a claim about weights we can no longer vouch for. (The+ * finish-profile precedent guards `repo` only; a sampler schedule is+ * revision-sensitive in a way a draft→delivery edge is not, so this guards+ * both.)+ * - **Mode.** Only the modes in `profile.modes` route through the pipeline+ * the schedule was measured on. `fflf`/`extend`/`a2v`/`ic` run entirely+ * different pipelines (KeyframeInterpolation, Extend, A2Vid, IC-LoRA), so+ * a profile is DECLINED for them with an explicit reason instead of+ * silently applying numbers that mean nothing there.+ * - **Sampler lock.** A `samplerLocked` entry pins its own validated+ * schedule; a speed profile would be a second authority over the same+ * dials, so the two are mutually exclusive by construction (asserted by+ * `validateSpeedProfileTable`).+ *+ * Everything the RUNNER cannot promise ahead of time — is the pinned+ * `ltx_pipelines_mlx` new enough to accept `enable_teacache`? is the distilled+ * adapter actually in the model pack? — is probed by the Python helper at+ * render time, which emits a `SPEEDPROFILE:` line naming what it actually+ * applied. That is what keeps an unavailable lever from becoming a misleading+ * speed claim: the profile still renders (at its step schedule), the missing+ * lever is reported as `degraded`, and the history record says so.+ *+ * Pure module: no I/O, and no imports out to services (the one import is a+ * sibling lib constant).+ */++import { LTX2_FAMILY_RUNTIMES } from './runners.js';++/**+ * The implicit "unchanged" profile. Never resolves to an override.+ */+export const SPEED_PROFILE_DEFAULT_ID = 'quality';++/**+ * Modes that route through the LTX two-stage pipeline (`run_two_stage` in+ * scripts/generate_ltx2.py), which is the only pipeline the shipped schedules+ * below were measured on. Declared once so a new profile can't quietly widen+ * itself past what was validated.+ */+export const TWO_STAGE_SPEED_PROFILE_MODES = Object.freeze(['text', 'image']);++/**+ * Shipped profiles, keyed by registry entry id.+ *+ * `shippedRepo` / `shippedRevision` are the pin guards described above.+ * `profiles` is the list attached to the entry, in picker order. Each profile:+ *+ * id stable key — persisted in history and submitted by the UI+ * name picker label+ * description one line under the picker; states the trade honestly+ * speedupLabel the measured claim, or null when there is nothing to claim+ * steps stage-1 step count (overrides the entry's `steps`)+ * stage2Steps explicit stage-2 step count (null → pipeline default)+ * guidance CFG scale (1.0 drops the negative branch entirely, which is+ * where most of the saving comes from on a two-stage render)+ * teacache request stage-1 TeaCache from the runner+ * teacacheThresh rel_l1_thresh override, or null for the pin's calibrated+ * default (0.5 at the current LTX-2 pin)+ * requiresAdapter distilled-adapter filename the schedule was measured with,+ * or null when the profile doesn't depend on one+ * modes modes the profile may resolve for+ */+export const VIDEO_SPEED_PROFILES = Object.freeze({+ // LTX-2.5 Q8. The step schedule here is NOT invented: it is the same+ // 8 stage-1 / 3 stage-2 / CFG 1.0 configuration the env-gated+ // PORTOS_T2V_TWO_STAGE experiment measured at ~30-35% off wall time+ // (resolveT2vTwoStageOverride, server/services/videoGen/local.js), promoted+ // from a hidden env knob to a user-facing, capability-gated choice.+ //+ // The 2.5 pack adds the lever 2.3 did not have: its own distilled adapter+ // (ltx-2.5-22b-distilled-lora-450) plus a pinned runtime whose two-stage+ // `generate_and_save` accepts `enable_teacache`. TeaCache caches stage-1+ // residuals between steps against upstream's calibrated coefficients; PortOS+ // has always left it off on this path because it never passed the kwarg.+ ltx25_mlx_q8: Object.freeze({+ shippedRepo: 'MrMofer/ltx-2.5-mlx-q8',+ shippedRevision: 'f1b56e7dc89f71a9af2cddac787b89ed22a8b7fc',+ profiles: Object.freeze([+ Object.freeze({+ id: 'fast',+ name: 'Fast',+ description: 'Validated 8+3-step two-stage schedule at CFG 1.0 with stage-1 TeaCache. Softer detail and weaker prompt adherence than Quality.',+ // Deliberately conservative, and traceable to the two numbers this repo+ // can actually cite: the step schedule measured ~30-35% off wall time+ // (resolveT2vTwoStageOverride, i.e. ~1.4-1.5x), and the pin's own+ // --teacache-thresh help documents ~1.2x at the calibrated default —+ // ~1.7-1.85x combined, so ~35-45% off. NOT "2x": that would overstate+ // the evidence, and on a pin without the TeaCache kwarg the cache half+ // degrades away entirely (leaving only the ~30-35%). For a feature+ // whose whole contract is an honest speed claim, the label is the last+ // place to round up. Raise this only against an A/B measured on 2.5.+ speedupLabel: '~35-45% faster',+ steps: 8,+ stage2Steps: 3,+ guidance: 1.0,+ teacache: true,+ teacacheThresh: null,+ requiresAdapter: 'ltx-2.5-22b-distilled-lora-450.safetensors',+ modes: TWO_STAGE_SPEED_PROFILE_MODES,+ }),+ ]),+ }),+});++const isEntry = (entry) => !!entry && typeof entry === 'object' && typeof entry.id === 'string';++/**+ * Attach `speedProfiles` to shipped entries that don't already carry the key.+ * Pure; returns a new array and never mutates the input entries.+ *+ * Preservation contract (mirrors migration 295, and the two sibling+ * decorators):+ * - `'speedProfiles' in entry` → user/existing value wins (including `null`+ * or `[]`, the explicit "no speed profiles on this model" override)+ * - entry id not shipped → custom model, left as-is+ * - `repo` or `revision` differs from the pin → left as-is (see the pin+ * guard rationale in the module docblock)+ */+export const applyVideoSpeedProfiles = (list) => {+ if (!Array.isArray(list)) return list;+ return list.map((entry) => {+ if (!isEntry(entry)) return entry;+ if ('speedProfiles' in entry) return entry;+ const spec = VIDEO_SPEED_PROFILES[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, speedProfiles: spec.profiles.map((p) => ({ ...p })) };+ });+};++/**+ * Absence and the default id are the same request — so a client that always+ * submits its picker value doesn't create a second spelling of "unchanged".+ */+export const isDefaultSpeedProfile = (id) => id == null || id === '' || id === SPEED_PROFILE_DEFAULT_ID;++/**+ * The profiles a model declares, or `[]`. Deliberately does NOT prepend the+ * implicit default entry: that is a PRESENTATION rule (the picker owns it, the+ * same way `TextEncoderPicker` owns hide-when-there-is-no-real-choice), and+ * folding it in here would make every model look like it has a profile.+ */+export const videoSpeedProfiles = (model) => (+ Array.isArray(model?.speedProfiles) ? model.speedProfiles.filter((p) => typeof p?.id === 'string') : []+);++/**+ * Does this model offer any speed profile at all?+ */+export const supportsSpeedProfiles = (model) => videoSpeedProfiles(model).length > 0;++/**+ * Look up one declared profile by id. `null` for the default id, an unknown+ * id, or a model with none.+ */+export const findVideoSpeedProfile = (model, id) => (+ isDefaultSpeedProfile(id) ? null : videoSpeedProfiles(model).find((p) => p.id === id) || null+);++/**+ * Why a requested profile could not be applied — a machine-readable reason plus+ * a sentence the UI/log can show verbatim. `null` when the profile applies.+ *+ * Returned rather than thrown: the render still proceeds at the model's own+ * default sampler. The point of the feature is an honest fallback, not a 400+ * on a knob that only ever makes a render faster.+ */+export const speedProfileDeclineReason = ({ model, profileId, mode }) => {+ if (isDefaultSpeedProfile(profileId)) return null;+ if (model?.samplerLocked === true) {+ return {+ code: 'SPEED_PROFILE_SAMPLER_LOCKED',+ message: `${model?.name || model?.id || 'This model'} locks its own validated sampler, so speed profiles don't apply.`,+ };+ }+ const profile = findVideoSpeedProfile(model, profileId);+ if (!profile) {+ return {+ code: 'SPEED_PROFILE_UNSUPPORTED',+ message: `Speed profile "${profileId}" isn't offered by ${model?.name || model?.id || 'this model'} — rendering at its default sampler.`,+ };+ }+ const modes = Array.isArray(profile.modes) ? profile.modes : TWO_STAGE_SPEED_PROFILE_MODES;+ // Absence is read as the plain text render — which is only SAFE because the+ // caller resolves the runner's own inference first (see `inferEffectiveMode`+ // below, used by generateVideo). A direct caller that hands us a raw absent+ // `mode` alongside keyframes would otherwise be told the profile applies,+ // while buildLtx2Args infers `fflf` and runs an entirely different pipeline.+ const effectiveMode = mode == null || mode === '' ? 'text' : mode;+ if (!modes.includes(effectiveMode)) {+ return {+ code: 'SPEED_PROFILE_MODE_UNSUPPORTED',+ message: `The ${profile.name} profile is validated for ${modes.join('/')} renders only — ${effectiveMode} renders use a different pipeline and keep the default sampler.`,+ };+ }+ return null;+};++/**+ * Resolve the sampler override a requested speed profile implies.+ *+ * Returns `null` when nothing should change (default profile, unsupported+ * model, incompatible mode) — the caller then leaves every dial exactly where+ * it was. Otherwise returns the concrete override the render should use.+ *+ * @returns {{ id, steps, stage2Steps, guidance, teacache, teacacheThresh, requiresAdapter } | null}+ */+export const resolveVideoSpeedProfile = ({ model, profileId, mode }) => {+ if (speedProfileDeclineReason({ model, profileId, mode })) return null;+ const profile = findVideoSpeedProfile(model, profileId);+ if (!profile) return null;+ return {+ id: profile.id,+ steps: profile.steps,+ stage2Steps: profile.stage2Steps ?? null,+ guidance: profile.guidance,+ teacache: profile.teacache === true,+ teacacheThresh: profile.teacacheThresh ?? null,+ requiresAdapter: profile.requiresAdapter ?? null,+ };+};++/**+ * The mode a render will EFFECTIVELY run in when the caller omitted one.+ *+ * `buildLtx2Args` infers the helper mode from the conditioning it was handed —+ * `fflf` from multi-keyframes, `image` from a source image — so a gate that+ * read a raw absent `mode` as "text" would green-light a two-stage schedule for+ * a KeyframeInterpolation render the profile was never validated on. This is+ * that same inference, narrowed to what the gate needs, so the two agree by+ * construction rather than by comment.+ */+export const inferEffectiveVideoMode = ({ mode, keyframes, sourceImagePath, extendFromVideoPath, audioFilePath }) => {+ if (mode != null && mode !== '') return mode;+ if (Array.isArray(keyframes) && keyframes.length >= 2) return 'fflf';+ if (audioFilePath) return 'a2v';+ if (extendFromVideoPath) return 'extend';+ if (sourceImagePath) return 'image';+ return 'text';+};++/**+ * Resolve a profile for a MULTI-RENDER request (a chained render), where the+ * chunks do not all run in the same mode.+ *+ * A chained render is one clip. Applying the profile to the chunks whose mode+ * supports it and not to the rest would stitch a fast chunk (CFG 1.0, fewer+ * stage-2 steps, TeaCache) onto quality chunks — a visible seam mid-clip, and+ * a chain-level ETA that assumes a speed-up three quarters of the render never+ * takes. So the profile applies to the whole chain or to none of it.+ *+ * This is the same "degrade rather than half-apply" rule `resolveVideoSampler`+ * enforces for one render, lifted to the unit the user actually receives.+ *+ * @param {string[]} modes - every mode the chunks will run in+ * @returns the override when EVERY mode accepts it, otherwise `null`+ */+export const resolveVideoSpeedProfileForModes = ({ model, profileId, modes }) => {+ if (isDefaultSpeedProfile(profileId)) return null;+ const list = Array.isArray(modes) && modes.length > 0 ? modes : [null];+ if (list.some((mode) => speedProfileDeclineReason({ model, profileId, mode }))) return null;+ return resolveVideoSpeedProfile({ model, profileId, mode: list[0] });+};++/**+ * The first reason any of `modes` declines the profile, for logging. `null`+ * when every mode accepts it (or the request is the default profile).+ */+export const speedProfileDeclineReasonForModes = ({ model, profileId, modes }) => {+ if (isDefaultSpeedProfile(profileId)) return null;+ const list = Array.isArray(modes) && modes.length > 0 ? modes : [null];+ for (const mode of list) {+ const reason = speedProfileDeclineReason({ model, profileId, mode });+ if (reason) return reason;+ }+ return null;+};++/**+ * The effective sampler for one render — the SINGLE place the precedence+ * between a locked sampler, a speed profile, an explicit user value and the+ * model default is decided.+ *+ * Precedence, highest first:+ * 1. `model.samplerLocked` — the model's own validated schedule wins over+ * everything, including a user-typed value (pre-existing contract).+ * 2. An applicable speed profile — the user picked a named schedule, so it+ * drives steps AND guidance together. Same shape as a locked sampler:+ * the UI disables the two inputs while a profile is active, and a direct+ * API caller that sends both gets the profile it asked for rather than a+ * half-applied hybrid whose speed claim would be false.+ * 3. An explicit `steps` / `guidanceScale` from the request.+ * 4. The model's registry defaults.+ *+ * `stage2Steps` is `null` unless a profile asked for an explicit one, so the+ * pipeline keeps its own default on every other path.+ *+ * Exported and pure so the render path and the chained-render ETA agree by+ * construction instead of by two copies of the same rule.+ */+export const resolveVideoSampler = ({ model, steps, guidanceScale, speedProfile = null }) => {+ if (model?.samplerLocked === true) {+ return { steps: model.steps, guidance: model.guidance, stage2Steps: null };+ }+ if (speedProfile) {+ return {+ steps: speedProfile.steps,+ guidance: speedProfile.guidance,+ stage2Steps: speedProfile.stage2Steps ?? null,+ };+ }+ return {+ steps: steps ? Number(steps) : model?.steps,+ guidance: guidanceScale != null && guidanceScale !== '' ? Number(guidanceScale) : model?.guidance,+ stage2Steps: null,+ };+};++/**+ * Validate one platform's video list for speed-profile problems. Pure — returns+ * `{ id, profileId, 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:+ * - `speedProfiles` is an array (or absent)+ * - every profile has a non-empty string id, unique within the entry+ * - no profile reuses the reserved default id+ * - `steps` is a positive integer and `guidance` a finite non-negative number+ * — a profile that resolved to NaN steps would spawn a broken render+ * - `stage2Steps`, when present, is a positive integer+ * - `modes` is a non-empty array of strings+ * - the entry is not also `samplerLocked` (two authorities over one dial)+ */+export const validateSpeedProfileTable = (list) => {+ if (!Array.isArray(list)) return [];+ const problems = [];+ const fail = (id, profileId, reason) => problems.push({ id, profileId, reason });+ for (const entry of list) {+ if (!isEntry(entry)) continue;+ if (!('speedProfiles' in entry) || entry.speedProfiles == null) continue;+ if (!Array.isArray(entry.speedProfiles)) {+ fail(entry.id, null, 'speedProfiles must be an array');+ continue;+ }+ if (entry.speedProfiles.length > 0 && entry.samplerLocked === true) {+ fail(entry.id, null, 'a samplerLocked model cannot also declare speedProfiles');+ continue;+ }+ // Only buildLtx2Args emits the profile's runner flags. On any other runtime+ // the step schedule would still apply (resolveVideoSampler is runtime-blind)+ // while TeaCache and the adapter silently would not — and no SPEEDPROFILE:+ // report would come back, so history would read as a FULL speed-up that+ // never happened. Refuse the declaration rather than ship that gap.+ if (entry.speedProfiles.length > 0 && !LTX2_FAMILY_RUNTIMES.includes(entry.runtime)) {+ fail(entry.id, null, `speedProfiles need an LTX-2-family runtime (got "${entry.runtime || 'none'}") — no other builder emits their flags`);+ continue;+ }+ const seen = new Set();+ for (const profile of entry.speedProfiles) {+ const pid = profile?.id;+ if (typeof pid !== 'string' || pid.length === 0) {+ fail(entry.id, pid ?? null, 'profile id must be a non-empty string');+ continue;+ }+ if (pid === SPEED_PROFILE_DEFAULT_ID) {+ fail(entry.id, pid, `"${SPEED_PROFILE_DEFAULT_ID}" is the reserved default profile id`);+ continue;+ }+ if (seen.has(pid)) {+ fail(entry.id, pid, `duplicate profile id "${pid}"`);+ continue;+ }+ seen.add(pid);+ if (!Number.isInteger(profile.steps) || profile.steps <= 0) {+ fail(entry.id, pid, 'steps must be a positive integer');+ continue;+ }+ if (!Number.isFinite(profile.guidance) || profile.guidance < 0) {+ fail(entry.id, pid, 'guidance must be a finite number >= 0');+ continue;+ }+ if (profile.stage2Steps != null+ && (!Number.isInteger(profile.stage2Steps) || profile.stage2Steps <= 0)) {+ fail(entry.id, pid, 'stage2Steps must be a positive integer when present');+ continue;+ }+ if (!Array.isArray(profile.modes) || profile.modes.length === 0+ || profile.modes.some((m) => typeof m !== 'string' || m.length === 0)) {+ fail(entry.id, pid, 'modes must be a non-empty array of strings');+ continue;+ }+ // Both of these reach the helper's argv. A non-numeric threshold exits the+ // child at argparse (`type=float`) mid-job, and a non-string adapter name+ // throws out of spawn — so they belong in the same fail-closed check as+ // the sampler numbers rather than being trusted from a hand-edited file.+ if (profile.teacacheThresh != null+ && (!Number.isFinite(profile.teacacheThresh) || profile.teacacheThresh <= 0)) {+ fail(entry.id, pid, 'teacacheThresh must be a positive number when present');+ continue;+ }+ if (profile.requiresAdapter != null+ && (typeof profile.requiresAdapter !== 'string' || profile.requiresAdapter.length === 0)) {+ fail(entry.id, pid, 'requiresAdapter must be a non-empty string when present');+ }+ }+ }+ return problems;+};++/**+ * Load-time guard: strip every invalid `speedProfiles` list, logging each+ * problem. A user-edited (or migration-stale) registry must not be able to+ * offer a profile that would spawn a broken render, 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 sanitizeSpeedProfiles = (list) => {+ const problems = validateSpeedProfileTable(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 speedProfiles on "${p.id}" — ${p.reason}`);+ }+ return list.map((entry) => {+ if (!isEntry(entry) || !bad.has(entry.id)) return entry;+ const { speedProfiles: _dropped, ...rest } = entry;+ return rest;+ });+};diff --git a/server/lib/videoSpeedProfiles.parity.test.js b/server/lib/videoSpeedProfiles.parity.test.jsnew file mode 100644index 0000000000..c0b0d595b7--- /dev/null+++ b/server/lib/videoSpeedProfiles.parity.test.js@@ -0,0 +1,148 @@+/**+ * Cross-package parity for the speed-profile sentinel and mode gate (#4875).+ *+ * Like the prompt-conditioner sentinel next door, the OPTIONS themselves are+ * not mirrored — the server attaches each entry's own `speedProfiles`+ * (`applyVideoSpeedProfiles`) and the client reads them straight off the model,+ * so the picker offers whatever this install's registry declares. Two things+ * ARE duplicated, and each carries weight in both directions:+ *+ * 1. The "unchanged" sentinel. The client's submit builder DROPS the field+ * when it holds this value and the server treats an absent field and this+ * id identically (`isDefaultSpeedProfile`). Diverged, the client would+ * post `speedProfileId: 'quality'` to a server that reads it as a real+ * profile id, log a decline on every default render, and — worse —+ * persist it into history, splitting the ETA estimator's default bucket+ * in two so neither half accumulates enough samples to estimate from.+ *+ * 2. The mode gate. The panel hides a profile the current mode isn't in;+ * the server declines one for the same reason. Diverged, the picker would+ * offer a fast profile on an fflf render that silently renders at the+ * model's own sampler — exactly the dead speed affordance this feature+ * exists to avoid.+ *+ * Lives server-side because the server module can't load under the client+ * (jsdom) runner, while the pure client mirror loads fine here.+ */++import { describe, it, expect } from 'vitest';+import {+ SPEED_PROFILE_DEFAULT_ID, isDefaultSpeedProfile, applyVideoSpeedProfiles,+ speedProfileDeclineReason, VIDEO_SPEED_PROFILES, resolveVideoSpeedProfileForModes,+} from './videoSpeedProfiles.js';+import {+ DEFAULT_SPEED_PROFILE_ID as CLIENT_DEFAULT_SPEED_PROFILE_ID,+ normalizeSpeedProfileForModel,+ speedProfileIdFromRecord,+ speedProfilesForMode,+ speedProfilesForModel,+ isDefaultSpeedProfileId,+ videoChainChunkModes,+} from '../../client/src/lib/videoGenParams.js';+import { resolveContextFrames, resolveContinuityStrategy } from './videoContinuity.js';++// Every shipped entry, decorated exactly as the registry decorates it.+const decoratedEntries = Object.entries(VIDEO_SPEED_PROFILES).map(([id, spec]) => (+ applyVideoSpeedProfiles([{ id, repo: spec.shippedRepo, revision: spec.shippedRevision }])[0]+));++// Every mode PortOS can submit, so a profile that ever widens its `modes`+// can't drift the two sides apart.+const ALL_MODES = ['text', 'image', 'fflf', 'extend', 'a2v', 'ic-control', 'ic-colorize'];++describe('video speed-profile client/server parity', () => {+ it('mirrors the default sentinel exactly', () => {+ expect(CLIENT_DEFAULT_SPEED_PROFILE_ID).toBe(SPEED_PROFILE_DEFAULT_ID);+ });++ // The client emits this value in three places (initial state, the+ // model-change reconcile, the record restore). Every one must land on+ // something the server reads as "no override".+ it('normalizes to a value the server treats as unchanged, for every shipped model', () => {+ for (const model of decoratedEntries) {+ expect(isDefaultSpeedProfile(normalizeSpeedProfileForModel('not-a-profile', model))).toBe(true);+ expect(isDefaultSpeedProfile(normalizeSpeedProfileForModel(undefined, model))).toBe(true);+ expect(isDefaultSpeedProfile(speedProfileIdFromRecord(undefined))).toBe(true);+ expect(isDefaultSpeedProfile(speedProfileIdFromRecord(''))).toBe(true);+ }+ });++ it('agrees that a model with no profiles has none, and one with them keeps them', () => {+ expect(speedProfilesForModel({})).toEqual([]);+ for (const model of decoratedEntries) {+ expect(speedProfilesForModel(model).map((p) => p.id))+ .toEqual(model.speedProfiles.map((p) => p.id));+ // A real id survives normalization; only then is the picker "active".+ const id = model.speedProfiles[0].id;+ expect(normalizeSpeedProfileForModel(id, model)).toBe(id);+ expect(isDefaultSpeedProfileId(id)).toBe(isDefaultSpeedProfile(id));+ expect(isDefaultSpeedProfileId(SPEED_PROFILE_DEFAULT_ID)).toBe(true);+ }+ });++ // The gate the panel applies (`p.modes.includes(mode)`) must accept exactly+ // the modes the server does not decline — checked across every mode PortOS+ // can submit, so a profile that ever widens its `modes` can't drift the two.+ // Every SHIPPED profile declares `modes`, so the two sides' fallback for a+ // profile that DOESN'T would never be exercised by the loop below — and could+ // silently drift back apart. Both must read a missing field as the two-stage+ // set, not as "unrestricted": a permissive client would offer a profile on+ // fflf that the server then declines.+ it('agrees on the fallback for a profile that declares no modes', () => {+ const model = { id: 'x', speedProfiles: [{ id: 'bare', steps: 8, guidance: 1.0 }] };+ for (const mode of ALL_MODES) {+ const clientOffers = speedProfilesForMode(model, mode).some((p) => p.id === 'bare');+ const serverAccepts = speedProfileDeclineReason({ model, profileId: 'bare', mode }) === null;+ expect({ mode, offers: clientOffers }).toEqual({ mode, offers: serverAccepts });+ }+ // And that shared fallback IS the two-stage set.+ expect(speedProfilesForMode(model, 'text')).toHaveLength(1);+ expect(speedProfilesForMode(model, 'fflf')).toHaveLength(0);+ });++ // A chained render is one clip whose chunks run in different modes; the+ // server applies a profile only when EVERY chunk accepts it+ // (resolveVideoSpeedProfileForModes), and the picker gates on the same list.+ it('agrees on a multi-mode (chained) request', () => {+ for (const model of decoratedEntries) {+ for (const profile of model.speedProfiles) {+ for (const modes of [['text', 'image'], ['text', 'extend'], ['image', 'extend'], ['text']]) {+ const clientOffers = speedProfilesForMode(model, modes).some((p) => p.id === profile.id);+ const serverAccepts = resolveVideoSpeedProfileForModes({ model, profileId: profile.id, modes }) !== null;+ expect({ modes, offers: clientOffers }).toEqual({ modes, offers: serverAccepts });+ }+ }+ }+ });++ // The chain gate turns on resolveContinuityStrategy, whose input is+ // resolveContextFrames' output — and THAT reads absent/''/non-finite as the+ // 22-frame default rather than zero. A client that read an omitted value as+ // "no window" would offer Fast for a chain the server declines wholesale.+ it('derives the same continuation strategy for every contextFrames spelling', () => {+ const model = decoratedEntries[0];+ for (const requested of [undefined, null, '', Number.NaN, 0, '0', 22, 73]) {+ const serverStrategy = resolveContinuityStrategy({+ model, contextFrames: resolveContextFrames(requested),+ });+ const clientModes = videoChainChunkModes({+ model, mode: 'text', chaining: true, contextFrames: requested,+ });+ const clientStrategy = clientModes[1] === 'extend' ? 'window' : 'frame';+ expect({ requested: String(requested), strategy: clientStrategy })+ .toEqual({ requested: String(requested), strategy: serverStrategy });+ }+ });++ it('gates every shipped profile on the same modes the server accepts', () => {+ for (const model of decoratedEntries) {+ for (const profile of model.speedProfiles) {+ for (const mode of ALL_MODES) {+ const clientOffers = speedProfilesForMode(model, mode).some((p) => p.id === profile.id);+ const serverAccepts = speedProfileDeclineReason({ model, profileId: profile.id, mode }) === null;+ expect({ mode, offers: clientOffers }).toEqual({ mode, offers: serverAccepts });+ }+ }+ }+ });+});diff --git a/server/lib/videoSpeedProfiles.test.js b/server/lib/videoSpeedProfiles.test.jsnew file mode 100644index 0000000000..91699ab682--- /dev/null+++ b/server/lib/videoSpeedProfiles.test.js@@ -0,0 +1,378 @@+import { describe, it, expect, vi, afterEach } from 'vitest';++import {+ SPEED_PROFILE_DEFAULT_ID,+ VIDEO_SPEED_PROFILES,+ applyVideoSpeedProfiles,+ isDefaultSpeedProfile,+ videoSpeedProfiles,+ supportsSpeedProfiles,+ findVideoSpeedProfile,+ speedProfileDeclineReason,+ resolveVideoSpeedProfile,+ resolveVideoSpeedProfileForModes,+ inferEffectiveVideoMode,+ speedProfileDeclineReasonForModes,+ resolveVideoSampler,+ validateSpeedProfileTable,+ sanitizeSpeedProfiles,+} from './videoSpeedProfiles.js';++const SHIPPED_ID = 'ltx25_mlx_q8';+const spec = VIDEO_SPEED_PROFILES[SHIPPED_ID];++// A registry entry exactly as it ships, so the pin guards are exercised against+// the real values rather than a hand-typed copy that could drift from them.+const shippedEntry = (overrides = {}) => ({+ id: SHIPPED_ID,+ name: 'LTX-2.5 MLX Q8',+ repo: spec.shippedRepo,+ revision: spec.shippedRevision,+ runtime: 'ltx25',+ steps: 8,+ guidance: 3.0,+ ...overrides,+});++const decorated = (overrides = {}) => applyVideoSpeedProfiles([shippedEntry(overrides)])[0];++afterEach(() => vi.restoreAllMocks());++describe('applyVideoSpeedProfiles', () => {+ it('attaches the shipped profiles to a pin-matching entry', () => {+ const entry = decorated();+ expect(entry.speedProfiles).toHaveLength(spec.profiles.length);+ expect(entry.speedProfiles[0].id).toBe('fast');+ });++ it('returns copies rather than the frozen shipped objects', () => {+ const a = decorated().speedProfiles[0];+ const b = decorated().speedProfiles[0];+ expect(a).not.toBe(b);+ expect(a).toEqual(b);+ // A consumer mutating one entry's list must not corrupt the shipped table.+ a.steps = 999;+ expect(VIDEO_SPEED_PROFILES[SHIPPED_ID].profiles[0].steps).not.toBe(999);+ });++ it('skips an entry whose repo was re-pointed at a fork', () => {+ expect(decorated({ repo: 'someone/ltx-2.5-fork' }).speedProfiles).toBeUndefined();+ });++ // The revision guard is what this decorator adds over applyVideoFinishProfiles:+ // a sampler schedule is validated against ONE snapshot of the weights.+ it('skips an entry whose revision was moved off the validated pin', () => {+ expect(decorated({ revision: 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef' }).speedProfiles).toBeUndefined();+ });++ it('skips an entry with no revision at all', () => {+ const { revision: _drop, ...noRevision } = shippedEntry();+ expect(applyVideoSpeedProfiles([noRevision])[0].speedProfiles).toBeUndefined();+ });++ it('leaves an existing key alone, including an explicit opt-out', () => {+ expect(decorated({ speedProfiles: [] }).speedProfiles).toEqual([]);+ expect(decorated({ speedProfiles: null }).speedProfiles).toBeNull();+ });++ it('leaves custom and malformed entries untouched', () => {+ const custom = { id: 'my_model', repo: 'me/mine' };+ expect(applyVideoSpeedProfiles([custom])[0]).toEqual(custom);+ expect(applyVideoSpeedProfiles([null, 7])).toEqual([null, 7]);+ expect(applyVideoSpeedProfiles('nope')).toBe('nope');+ });+});++describe('the default profile is a no-op', () => {+ it('treats absence, empty string and the default id identically', () => {+ for (const id of [null, undefined, '', SPEED_PROFILE_DEFAULT_ID]) {+ expect(isDefaultSpeedProfile(id)).toBe(true);+ expect(findVideoSpeedProfile(decorated(), id)).toBeNull();+ expect(speedProfileDeclineReason({ model: decorated(), profileId: id, mode: 'text' })).toBeNull();+ expect(resolveVideoSpeedProfile({ model: decorated(), profileId: id, mode: 'text' })).toBeNull();+ }+ });++ it('leaves the sampler exactly where it was', () => {+ const model = decorated();+ const profile = resolveVideoSpeedProfile({ model, profileId: SPEED_PROFILE_DEFAULT_ID, mode: 'text' });+ expect(resolveVideoSampler({ model, steps: undefined, guidanceScale: undefined, speedProfile: profile }))+ .toEqual({ steps: 8, guidance: 3.0, stage2Steps: null });+ });+});++describe('speedProfileDeclineReason', () => {+ it('accepts the modes the profile was validated for', () => {+ for (const mode of ['text', 'image']) {+ expect(speedProfileDeclineReason({ model: decorated(), profileId: 'fast', mode })).toBeNull();+ }+ });++ it('treats an absent mode as the default text render', () => {+ expect(speedProfileDeclineReason({ model: decorated(), profileId: 'fast', mode: null })).toBeNull();+ expect(speedProfileDeclineReason({ model: decorated(), profileId: 'fast', mode: '' })).toBeNull();+ });++ it('declines the modes that route through a different pipeline', () => {+ for (const mode of ['fflf', 'extend', 'a2v', 'ic-control']) {+ const reason = speedProfileDeclineReason({ model: decorated(), profileId: 'fast', mode });+ expect(reason?.code).toBe('SPEED_PROFILE_MODE_UNSUPPORTED');+ expect(reason.message).toContain(mode);+ }+ });++ it('declines an id the model does not offer', () => {+ expect(speedProfileDeclineReason({ model: decorated(), profileId: 'turbo', mode: 'text' })?.code)+ .toBe('SPEED_PROFILE_UNSUPPORTED');+ // An undecorated (forked / custom) model offers nothing at all.+ expect(speedProfileDeclineReason({ model: shippedEntry(), profileId: 'fast', mode: 'text' })?.code)+ .toBe('SPEED_PROFILE_UNSUPPORTED');+ });++ it('declines on a samplerLocked model, whose own schedule is the authority', () => {+ const model = { ...decorated(), samplerLocked: true };+ expect(speedProfileDeclineReason({ model, profileId: 'fast', mode: 'text' })?.code)+ .toBe('SPEED_PROFILE_SAMPLER_LOCKED');+ expect(resolveVideoSpeedProfile({ model, profileId: 'fast', mode: 'text' })).toBeNull();+ });+});++describe('resolveVideoSpeedProfile', () => {+ it('returns the concrete override for a compatible request', () => {+ expect(resolveVideoSpeedProfile({ model: decorated(), profileId: 'fast', mode: 'text' })).toEqual({+ id: 'fast',+ steps: 8,+ stage2Steps: 3,+ guidance: 1.0,+ teacache: true,+ teacacheThresh: null,+ requiresAdapter: 'ltx-2.5-22b-distilled-lora-450.safetensors',+ });+ });++ it('returns null for every declined request', () => {+ expect(resolveVideoSpeedProfile({ model: decorated(), profileId: 'fast', mode: 'fflf' })).toBeNull();+ expect(resolveVideoSpeedProfile({ model: decorated(), profileId: 'nope', mode: 'text' })).toBeNull();+ });+});++describe('resolveVideoSampler precedence', () => {+ const model = decorated();+ const fast = resolveVideoSpeedProfile({ model, profileId: 'fast', mode: 'text' });++ it('gives a locked sampler the last word, over profile AND user values', () => {+ const locked = { ...model, samplerLocked: true, steps: 40, guidance: 6 };+ expect(resolveVideoSampler({ model: locked, steps: 12, guidanceScale: 2, speedProfile: fast }))+ .toEqual({ steps: 40, guidance: 6, stage2Steps: null });+ });++ it('lets a profile drive steps AND guidance together, over explicit values', () => {+ expect(resolveVideoSampler({ model, steps: 30, guidanceScale: 7, speedProfile: fast }))+ .toEqual({ steps: 8, guidance: 1.0, stage2Steps: 3 });+ });++ it('honors explicit user values when no profile applies', () => {+ expect(resolveVideoSampler({ model, steps: '30', guidanceScale: '7', speedProfile: null }))+ .toEqual({ steps: 30, guidance: 7, stage2Steps: null });+ });++ it('falls back to the registry defaults, treating 0/empty guidance as explicit', () => {+ expect(resolveVideoSampler({ model, steps: undefined, guidanceScale: undefined, speedProfile: null }))+ .toEqual({ steps: 8, guidance: 3.0, stage2Steps: null });+ // guidance 0 is a real request (no CFG), not "unset" — the `!= null && !== ''`+ // check exists precisely so it isn't collapsed into the model default.+ expect(resolveVideoSampler({ model, steps: undefined, guidanceScale: 0, speedProfile: null }).guidance).toBe(0);+ expect(resolveVideoSampler({ model, steps: undefined, guidanceScale: '', speedProfile: null }).guidance).toBe(3.0);+ });+});++describe('validateSpeedProfileTable / sanitizeSpeedProfiles', () => {+ // `runtime` defaults to a valid one so each case exercises the rule it names+ // rather than tripping the runtime gate first.+ const withProfile = (profile, extra = {}) => [{ id: 'm', runtime: 'ltx25', ...extra, speedProfiles: [profile] }];+ const base = { id: 'fast', name: 'Fast', steps: 8, stage2Steps: 3, guidance: 1.0, modes: ['text'] };++ it('passes the shipped table', () => {+ expect(validateSpeedProfileTable(applyVideoSpeedProfiles([shippedEntry()]))).toEqual([]);+ });++ it('passes an entry with no speedProfiles key, and an explicit opt-out', () => {+ expect(validateSpeedProfileTable([{ id: 'm' }])).toEqual([]);+ expect(validateSpeedProfileTable([{ id: 'm', speedProfiles: null }])).toEqual([]);+ // An empty list is a valid opt-out on ANY runtime — the gate is about+ // declaring a profile, not about carrying the key.+ expect(validateSpeedProfileTable([{ id: 'm', runtime: 'wan22', speedProfiles: [] }])).toEqual([]);+ });++ it.each([+ ['a non-array value', [{ id: 'm', runtime: 'ltx25', speedProfiles: 'fast' }], /must be an array/],+ ['a missing id', withProfile({ ...base, id: undefined }), /non-empty string/],+ ['the reserved default id', withProfile({ ...base, id: SPEED_PROFILE_DEFAULT_ID }), /reserved default/],+ ['NaN steps', withProfile({ ...base, steps: Number.NaN }), /positive integer/],+ ['zero steps', withProfile({ ...base, steps: 0 }), /positive integer/],+ ['non-integer steps', withProfile({ ...base, steps: 8.5 }), /positive integer/],+ ['missing guidance', withProfile({ ...base, guidance: undefined }), /finite number/],+ ['negative guidance', withProfile({ ...base, guidance: -1 }), /finite number/],+ ['zero stage2Steps', withProfile({ ...base, stage2Steps: 0 }), /positive integer/],+ ['empty modes', withProfile({ ...base, modes: [] }), /non-empty array/],+ ['non-string modes', withProfile({ ...base, modes: [7] }), /non-empty array/],+ ])('rejects %s', (_label, list, pattern) => {+ const problems = validateSpeedProfileTable(list);+ expect(problems).toHaveLength(1);+ expect(problems[0].reason).toMatch(pattern);+ });++ it.each([+ ['a non-numeric teacacheThresh', { teacacheThresh: 'high' }, /teacacheThresh must be a positive number/],+ ['a zero teacacheThresh', { teacacheThresh: 0 }, /teacacheThresh must be a positive number/],+ ['a non-string requiresAdapter', { requiresAdapter: 450 }, /requiresAdapter must be a non-empty string/],+ ['an empty requiresAdapter', { requiresAdapter: '' }, /requiresAdapter must be a non-empty string/],+ ])('rejects %s — both reach the helper argv', (_label, overrides, pattern) => {+ // A non-numeric threshold exits the child at argparse (type=float) mid-job;+ // a non-string adapter name throws ERR_INVALID_ARG_TYPE out of spawn.+ const problems = validateSpeedProfileTable(withProfile({ ...base, ...overrides }));+ expect(problems).toHaveLength(1);+ expect(problems[0].reason).toMatch(pattern);+ });++ it('accepts both optional fields when absent or well-formed', () => {+ expect(validateSpeedProfileTable(withProfile(base))).toEqual([]);+ expect(validateSpeedProfileTable(withProfile({+ ...base, teacacheThresh: 0.8, requiresAdapter: 'a.safetensors',+ }))).toEqual([]);+ expect(validateSpeedProfileTable(withProfile({+ ...base, teacacheThresh: null, requiresAdapter: null,+ }))).toEqual([]);+ });++ it('rejects a duplicate profile id within one entry', () => {+ const problems = validateSpeedProfileTable([{ id: 'm', runtime: 'ltx25', speedProfiles: [base, { ...base }] }]);+ expect(problems[0].reason).toMatch(/duplicate/);+ });++ // Only buildLtx2Args emits the profile's runner flags. Anywhere else the step+ // schedule would apply while TeaCache/adapter silently would not, and no+ // SPEEDPROFILE: report would come back — so history would read as a full+ // speed-up that never happened.+ it('rejects profiles declared on a runtime whose builder cannot emit their flags', () => {+ for (const runtime of ['mlx_video', 'wan22', 'minimax_h3', 'hunyuan', undefined]) {+ const problems = validateSpeedProfileTable(withProfile(base, { runtime }));+ expect(problems).toHaveLength(1);+ expect(problems[0].reason).toMatch(/LTX-2-family runtime/);+ }+ });++ it.each(['ltx2', 'ltx25'])('accepts profiles on the %s runtime', (runtime) => {+ expect(validateSpeedProfileTable(withProfile(base, { runtime }))).toEqual([]);+ });++ it('rejects a samplerLocked model that also declares profiles', () => {+ const problems = validateSpeedProfileTable(withProfile(base, { samplerLocked: true }));+ expect(problems[0].reason).toMatch(/samplerLocked/);+ });++ it('strips a bad entry at load and warns, leaving good entries untouched', () => {+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});+ const good = { id: 'good', runtime: 'ltx25', speedProfiles: [base] };+ const bad = { id: 'bad', runtime: 'ltx25', speedProfiles: [{ ...base, steps: Number.NaN }] };+ const out = sanitizeSpeedProfiles([good, bad]);+ expect(out[0]).toEqual(good);+ expect(out[1]).toEqual({ id: 'bad', runtime: 'ltx25' });+ expect(log).toHaveBeenCalledWith(expect.stringContaining('dropping speedProfiles on "bad"'));+ });++ it('returns the input array unchanged when the table is sound', () => {+ const list = [{ id: 'm', runtime: 'ltx25', speedProfiles: [base] }];+ expect(sanitizeSpeedProfiles(list)).toBe(list);+ });+});++describe('videoSpeedProfiles / supportsSpeedProfiles', () => {+ it('reads the decorated list and filters malformed entries', () => {+ expect(supportsSpeedProfiles(decorated())).toBe(true);+ expect(supportsSpeedProfiles(shippedEntry())).toBe(false);+ expect(videoSpeedProfiles({ speedProfiles: [{ id: 'a' }, {}, null] })).toEqual([{ id: 'a' }]);+ expect(videoSpeedProfiles(null)).toEqual([]);+ });+});++// A chained render is ONE clip whose chunks do not all run in the same mode+// (chunk 0 keeps the request's; chunks 1+ re-enter as `extend` on a window+// continuity chain, `image` on a frame hop). Applying the profile to only the+// chunks that accept it would stitch a fast chunk onto quality ones — a+// visible seam mid-clip — and inflate the chain ETA.+describe('resolveVideoSpeedProfileForModes (chained renders)', () => {+ const model = decorated();+ const args = (modes, profileId = 'fast') => ({ model, profileId, modes });++ it('applies when every chunk mode accepts the profile', () => {+ // Frame-hop chain: chunk 0 text/image, chunks 1+ image — all supported.+ expect(resolveVideoSpeedProfileForModes(args(['text', 'image']))?.id).toBe('fast');+ expect(resolveVideoSpeedProfileForModes(args(['image', 'image']))?.id).toBe('fast');+ expect(speedProfileDeclineReasonForModes(args(['text', 'image']))).toBeNull();+ });++ it('declines the WHOLE chain when any chunk mode does not', () => {+ // Window-continuity chain: chunks 1+ are `extend`, which routes through a+ // pipeline this schedule was never measured on.+ expect(resolveVideoSpeedProfileForModes(args(['text', 'extend']))).toBeNull();+ expect(speedProfileDeclineReasonForModes(args(['text', 'extend']))?.code)+ .toBe('SPEED_PROFILE_MODE_UNSUPPORTED');+ // Order doesn't matter — one bad mode is enough.+ expect(resolveVideoSpeedProfileForModes(args(['extend', 'image']))).toBeNull();+ });++ it('treats a single-chunk chain exactly like a lone render', () => {+ expect(resolveVideoSpeedProfileForModes(args(['text']))?.id).toBe('fast');+ expect(resolveVideoSpeedProfileForModes(args(['fflf']))).toBeNull();+ });++ it('falls back to the inferred text render for an empty or absent mode list', () => {+ for (const modes of [[], null, undefined]) {+ expect(resolveVideoSpeedProfileForModes(args(modes))?.id).toBe('fast');+ }+ });++ it('is a no-op for the default profile, whatever the modes', () => {+ expect(resolveVideoSpeedProfileForModes(args(['text', 'extend'], SPEED_PROFILE_DEFAULT_ID))).toBeNull();+ expect(speedProfileDeclineReasonForModes(args(['text', 'extend'], SPEED_PROFILE_DEFAULT_ID))).toBeNull();+ });+});++// buildLtx2Args infers the helper mode from the conditioning it is handed, so a+// gate reading a raw absent `mode` as "text" would green-light a two-stage+// schedule for a KeyframeInterpolation render the profile was never validated+// on. This is that same inference, and the two must agree.+describe('inferEffectiveVideoMode', () => {+ it('returns an explicit mode untouched, whatever the conditioning', () => {+ expect(inferEffectiveVideoMode({ mode: 'text', keyframes: [{}, {}] })).toBe('text');+ expect(inferEffectiveVideoMode({ mode: 'extend', sourceImagePath: '/a.png' })).toBe('extend');+ });++ it('infers from the conditioning when the mode is absent', () => {+ expect(inferEffectiveVideoMode({})).toBe('text');+ expect(inferEffectiveVideoMode({ mode: '' })).toBe('text');+ expect(inferEffectiveVideoMode({ sourceImagePath: '/a.png' })).toBe('image');+ expect(inferEffectiveVideoMode({ extendFromVideoPath: '/a.mp4' })).toBe('extend');+ expect(inferEffectiveVideoMode({ audioFilePath: '/a.wav' })).toBe('a2v');+ expect(inferEffectiveVideoMode({ keyframes: [{ index: 0 }, { index: 8 }] })).toBe('fflf');+ });++ it('needs two keyframes for fflf, matching buildLtx2Args', () => {+ expect(inferEffectiveVideoMode({ keyframes: [{ index: 0 }] })).toBe('text');+ expect(inferEffectiveVideoMode({ keyframes: [] })).toBe('text');+ });++ // The point of the whole helper: a direct caller that omits `mode` while+ // supplying keyframes must NOT be handed the two-stage schedule.+ it('declines a profile for conditioning that implies another pipeline', () => {+ const model = decorated();+ const args = (ctx) => ({ model, profileId: 'fast', mode: inferEffectiveVideoMode(ctx) });+ expect(resolveVideoSpeedProfile(args({ keyframes: [{ index: 0 }, { index: 8 }] }))).toBeNull();+ expect(resolveVideoSpeedProfile(args({ audioFilePath: '/a.wav' }))).toBeNull();+ expect(resolveVideoSpeedProfile(args({ extendFromVideoPath: '/a.mp4' }))).toBeNull();+ // …while a plain render, and an image render, still take it.+ expect(resolveVideoSpeedProfile(args({}))?.id).toBe('fast');+ expect(resolveVideoSpeedProfile(args({ sourceImagePath: '/a.png' }))?.id).toBe('fast');+ });+});diff --git a/server/routes/mediaJobs.js b/server/routes/mediaJobs.jsindex 14e05c27d6..898da9830b 100644--- a/server/routes/mediaJobs.js+++ b/server/routes/mediaJobs.js@@ -222,6 +222,10 @@ const RETRY_OVERRIDE_SCHEMA = z.object({// an override missing from here is silently dropped rather than rejected.i2vReferenceMode: z.enum(I2V_REFERENCE_MODES).nullable().optional(),textEncoderId: z.string().max(64).optional().transform(emptyToUndef),+ // Nullable, unlike textEncoderId: a speed profile OUTRANKS steps/guidanceScale+ // (resolveVideoSampler), so a retry that edits Steps on a profiled job would+ // otherwise be silently ignored. `null` clears it back to the default sampler.+ speedProfileId: z.string().max(64).nullable().optional().transform((v) => (v === '' ? null : v)),chunks: z.number().int().min(1).max(8).optional(),chunkPrompts: z.array(z.string().max(8000)).max(8).optional(),contextFrames: z.number().int().min(0).max(64).optional(),@@ -288,7 +292,7 @@ router.post('/:id/retry', asyncHandler(async (req, res) => {const bounds = VIDEO_RETRY_BOUNDS_SCHEMA.safeParse(rawOverrides);if (!bounds.success) throw new ServerError('Video retry settings are outside the supported range', { status: 400, code: 'VALIDATION_ERROR' });}- for (const key of ['seed', 'steps', 'guidanceScale', 'imageStrength', 'i2vReferenceMode']) {+ for (const key of ['seed', 'steps', 'guidanceScale', 'imageStrength', 'i2vReferenceMode', 'speedProfileId']) {if (rawOverrides[key] === null) delete params[key];}if (rawOverrides.chunks === 1) delete params.chunkPrompts;diff --git a/server/routes/mediaJobs.test.js b/server/routes/mediaJobs.test.jsindex 0be83bbd2b..50d3ce3f7f 100644--- a/server/routes/mediaJobs.test.js+++ b/server/routes/mediaJobs.test.js@@ -276,6 +276,34 @@ describe('mediaJobs routes', () => {});});+ // #4875 — resolveVideoSampler ranks a speed profile ABOVE explicit+ // steps/guidanceScale, so without a clear path a retry that edits Steps on a+ // profiled job would run at the profile's schedule and silently ignore it.+ it('POST /:id/retry can drop a speed profile so an edited sampler takes effect', async () => {+ jobStore.set('j-video-profile', {+ id: 'j-video-profile', kind: 'video', owner: null, status: 'failed',+ params: { prompt: 'old', modelId: 'ltx25_mlx_q8', speedProfileId: 'fast', steps: 8 },+ });+ const r = await request(makeApp())+ .post('/api/media-jobs/j-video-profile/retry')+ .send({ params: { speedProfileId: null, steps: 20 } });+ expect(r.status).toBe(200);+ expect(stubs.enqueueJob.mock.calls[0][0].params)+ .toEqual({ prompt: 'old', modelId: 'ltx25_mlx_q8', steps: 20 });+ });++ it('POST /:id/retry can switch a speed profile, and inherits it when untouched', async () => {+ jobStore.set('j-video-keep', {+ id: 'j-video-keep', kind: 'video', owner: null, status: 'failed',+ params: { prompt: 'old', speedProfileId: 'fast' },+ });+ const r = await request(makeApp())+ .post('/api/media-jobs/j-video-keep/retry')+ .send({ params: { prompt: 'new' } });+ expect(r.status).toBe(200);+ expect(stubs.enqueueJob.mock.calls[0][0].params.speedProfileId).toBe('fast');+ });+it('POST /:id/retry clears resettable numeric video controls with null', async () => {jobStore.set('j-video-clear', {id: 'j-video-clear', kind: 'video', owner: null, status: 'failed',diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 948e880db6..dd1f119b62 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -52,6 +52,7 @@ import {downloadableVideoTextEncoders, downloadableVideoTextEncoder, publicTextEncoderOption,isStockTextEncoder,} from '../lib/videoTextEncoders.js';+import { isDefaultSpeedProfile } from '../lib/videoSpeedProfiles.js';import {inspectModelCache, verifyModelCache, repairModelCache, repairCachedFile,verifyCachedRepoFiles, repairCachedRepoFiles, summarizeVerify, aggregateVerifies,@@ -182,6 +183,13 @@ export const LOCAL_ONLY_VIDEO_PARAMS = Object.freeze({// the service — the set is per-runtime, so a route-level enum would either// have to enumerate every runtime's options or reject a legitimate one.textEncoderId: z.string().min(1).max(64).optional(),+ // Named sampler schedule to render with (lib/videoSpeedProfiles.js). Loosely+ // validated here for the same reason as textEncoderId — the option list is+ // per-MODEL. Deliberately never rejected downstream either: an id this model+ // doesn't offer (or a mode the profile isn't validated for) falls back to the+ // 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(),});const generateBodySchema = z.object({@@ -1044,6 +1052,11 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {// resumed/remixed render carry a knob that never applied — and would differ// from what the service records in history for the same render....(isStockTextEncoder(body.textEncoderId) ? {} : { textEncoderId: body.textEncoderId }),+ // Same "absence IS the default" rule as textEncoderId: an explicit+ // 'quality' is semantically identical to omitting the field, so persisting+ // 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 }),disableAudio: body.disableAudio === true || body.disableAudio === 'true',sourceImagePath,audioFilePath,@@ -1110,6 +1123,9 @@ const ACTIVE_JOB_PARAM_FIELDS = [// A registry id, not a path — safe to echo so a reloading page restores the// conditioner the in-flight render is actually using.'textEncoderId',+ // 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','audioStartSec',// Grok jobs (#2859 phase 2): the semantic t2v/i2v mode ('mode' holds the// 'grok' discriminator for them) and the clip duration — both plaindiff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex a80c319a04..4693079bc1 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -734,9 +734,10 @@ describe('videoGen routes', () => {'i2vReferenceMode','tiling',// Not in the it.each table above: the route deliberately DROPS the- // stock value from persisted params, so the generic round-trip- // assertion can't cover it. Its own case is below.+ // stock/default value from persisted params, so the generic round-trip+ // assertion can't cover either. Their own cases are below.'textEncoderId',+ 'speedProfileId',]);const { getSettings } = await import('../services/settings.js');getSettings.mockResolvedValueOnce({ imageGen: grokReady, videoGen: { mode: 'grok' } });@@ -777,6 +778,30 @@ describe('videoGen routes', () => {expect(call[0].params.i2vReferenceMode).toBeUndefined();});+ // Same two halves for the speed profile (#4875): naming one keeps the+ // render local (grok has no sampler-schedule knob), and the default+ // 'quality' value is dropped from persisted params so a default render's+ // job params stay byte-identical to a request that never sent the field.+ it('keeps speedProfileId on the local path under a grok pin, without persisting the default 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', speedProfileId: 'quality' });+ expect(r.status).toBe(200);+ const [call] = mediaJobQueue.enqueueJob.mock.calls;+ expect(call[0].params.mode).not.toBe('grok');+ expect(call[0].params.speedProfileId).toBeUndefined();+ });++ it('persists a non-default speedProfileId on the local path under a grok pin', 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', speedProfileId: 'fast' });+ expect(r.status).toBe(200);+ const [call] = mediaJobQueue.enqueueJob.mock.calls;+ expect(call[0].params.mode).not.toBe('grok');+ expect(call[0].params.speedProfileId).toBe('fast');+ });+it('a grok pin degrades to local when the request carries local-only machinery', async () => {const { getSettings } = await import('../services/settings.js');getSettings.mockResolvedValueOnce({diff --git a/server/services/mediaJobQueue/sanitizeJob.js b/server/services/mediaJobQueue/sanitizeJob.jsindex d0bdd7f20c..5246f8bad5 100644--- a/server/services/mediaJobQueue/sanitizeJob.js+++ b/server/services/mediaJobQueue/sanitizeJob.js@@ -9,6 +9,8 @@ const PARAM_ALLOWLIST = new Set(['seed', 'tiling', 'disableAudio', 'mode', 'imageStrength','i2vReferenceMode','textEncoderId', 'chunks', 'chunkPrompts', 'contextFrames', 'loras',++ 'textEncoderId', 'speedProfileId', 'chunks', 'chunkPrompts', 'contextFrames', 'loras','cfgScale', 'guidance', 'quantize','runId', 'runtime', 'datasetId', 'characterId', 'characterName','triggerWord', 'rank', 'baseModelId', 'spriteRef', 'spriteWalk',diff --git a/server/services/mediaJobQueue/sanitizeJob.test.js b/server/services/mediaJobQueue/sanitizeJob.test.jsindex b2df8753bf..81b2a041ed 100644--- a/server/services/mediaJobQueue/sanitizeJob.test.js+++ b/server/services/mediaJobQueue/sanitizeJob.test.js@@ -10,6 +10,7 @@ describe('sanitizeJob', () => {params: {modelId: 'example-video-model',textEncoderId: 'example-encoder',+ speedProfileId: 'fast',chunks: 2,chunkPrompts: ['opening', 'climax'],contextFrames: 12,@@ -21,6 +22,10 @@ describe('sanitizeJob', () => {expect(sanitized.params).toEqual({modelId: 'example-video-model',textEncoderId: 'example-encoder',+ // #4875 — a profile OUTRANKS steps/CFG, so a queue row that hid it would+ // display an unused `steps` value and the retry editor would have no way+ // to see (or drop) the schedule actually driving the render.+ speedProfileId: 'fast',chunks: 2,chunkPrompts: ['opening', 'climax'],contextFrames: 12,diff --git a/server/services/videoGen/chainedVideo.js b/server/services/videoGen/chainedVideo.jsindex a8adce3bc1..5de426504f 100644--- a/server/services/videoGen/chainedVideo.js+++ b/server/services/videoGen/chainedVideo.js@@ -16,6 +16,10 @@ import { videoGenEvents } from './events.js';import { loadHistory, mutateVideoHistory } from './history.js';import { videoChainUnsupportedError } from './modeContract.js';import { estimateRenderMs } from './eta.js';+import {+ resolveVideoSpeedProfileForModes, speedProfileDeclineReasonForModes,+ resolveVideoSampler, inferEffectiveVideoMode,+} from '../../lib/videoSpeedProfiles.js';import { videoJobState } from './jobState.js';import { DEFAULT_NUM_FRAMES, resolveVideoDimensions } from './renderArgs.js';import { extractLastFrame } from './frameExtraction.js';@@ -115,9 +119,37 @@ export async function generateChainedVideo({ chunks, chunkPrompts, contextFrames// Deliberately placed AFTER the active chain and shared job are registered: it is the// first await in this function, and a cancel arriving during the history// read must still find the chain to stop.- const chainSteps = chainModel?.samplerLocked- ? chainModel.steps- : (rest.steps ? Number(rest.steps) : chainModel?.steps);+ // A chain's chunks do NOT all run in the request's mode: chunk 0 keeps it,+ // and chunks 1+ re-enter as `extend` on a window-continuity chain or `image`+ // on a frame hop (see the dispatch below — these two must stay in step).+ // `extend` routes through ExtendPipeline, which no two-stage speed profile is+ // validated for, so a Fast chain would render chunk 0 fast and the rest at+ // the model default: a visible seam mid-clip, plus a chain ETA claiming a+ // speed-up most of the render never takes. resolveVideoSpeedProfileForModes+ // therefore applies the profile to the whole chain or to none of it, and+ // `speedProfileId` is stripped from `rest` below so the per-chunk renders+ // agree with this decision instead of each re-deciding.+ const chainChunkModes = [+ inferEffectiveVideoMode(rest),+ ...(totalChunks > 1 ? [continuity === 'window' ? 'extend' : 'image'] : []),+ ];+ const chainSpeedProfile = resolveVideoSpeedProfileForModes({+ model: chainModel, profileId: rest.speedProfileId, modes: chainChunkModes,+ });+ const chainSpeedDeclined = chainSpeedProfile ? null : speedProfileDeclineReasonForModes({+ model: chainModel, profileId: rest.speedProfileId, modes: chainChunkModes,+ });+ if (chainSpeedDeclined) {+ console.log(`⚠️ Speed profile declined for chain [${outerJobId.slice(0, 8)}] ${chainSpeedDeclined.code}: ${chainSpeedDeclined.message}`);+ }+ // What every chunk will actually be handed. Absent (not 'quality') when the+ // chain declined, so a chunk stamps no profile it didn't render with.+ const chainSpeedProfileId = chainSpeedProfile ? rest.speedProfileId : undefined;+ // `resolveVideoSampler` is the SAME precedence rule generateVideo applies, so+ // the chain estimate can't drift from what the chunks actually render at.+ const { steps: chainSteps } = resolveVideoSampler({+ model: chainModel, steps: rest.steps, guidanceScale: rest.guidanceScale, speedProfile: chainSpeedProfile,+ });const chainDimensions = resolveVideoDimensions(chainModel, rest.width, rest.height);const chainEta = estimateRenderMs({history: await loadHistory(),@@ -126,6 +158,7 @@ export async function generateChainedVideo({ chunks, chunkPrompts, contextFramesheight: chainDimensions.height,numFrames: rest.numFrames ?? chainModel?.defaultFrames ?? DEFAULT_NUM_FRAMES,steps: chainSteps,+ speedProfileId: chainSpeedProfile?.id ?? null,chunks: totalChunks,});const chainEtaField = chainEta ? { etaMs: chainEta.etaMs } : {};@@ -242,6 +275,10 @@ export async function generateChainedVideo({ chunks, chunkPrompts, contextFramesgenerateVideo({...rest,+ // Decided ONCE for the chain above, not re-decided per chunk: `undefined`+ // when any chunk's mode declines the profile, so every chunk renders on+ // the same sampler and the stitched clip has no mid-clip seam.+ speedProfileId: chainSpeedProfileId,prompt: chunkPrompt,seed: chunkSeed,jobId: innerJobId,diff --git a/server/services/videoGen/eta.js b/server/services/videoGen/eta.jsindex 052757829c..ca29a59040 100644--- a/server/services/videoGen/eta.js+++ b/server/services/videoGen/eta.js@@ -74,15 +74,43 @@ const entryTime = (entry) => {};/**- * Timed, shape-complete history records for one model, newest first.- * `renderMs` is stamped by finalizeGeneratedVideo; entries that predate it- * (and non-render entries like downloaded videos) simply have no measurement- * and are excluded rather than guessed at.+ * Normalize a record's / request's speed profile to a single comparable key.+ * Absence and the default profile are the same bucket, exactly as they are the+ * same request everywhere else (lib/videoSpeedProfiles.js). Kept local rather+ * than imported so this module stays free of registry dependencies — the only+ * thing it needs is that two spellings of "unchanged" compare equal.*/-export const timedRenderSamples = (history, modelId) => {+const DEFAULT_SPEED_BUCKET = 'quality';+const speedBucket = (id) => (id == null || id === '' ? DEFAULT_SPEED_BUCKET : String(id));++/**+ * Timed, shape-complete history records for one model AND one speed profile,+ * newest first. `renderMs` is stamped by finalizeGeneratedVideo; entries that+ * predate it (and non-render entries like downloaded videos) simply have no+ * measurement and are excluded rather than guessed at.+ *+ * The speed profile is part of the sample key — unlike mode and LoRAs, which+ * the module docblock explains are deliberately left out. The difference is+ * magnitude and shape: a profile swaps the whole schedule (CFG 1.0 drops the+ * negative branch, stage 2 runs fewer steps, TeaCache skips residuals), so it+ * moves the COST CURVE's slope rather than adding variance around it. Pooling+ * the two buckets would systematically over-estimate every fast render and+ * under-estimate every quality one — a confidently wrong number, which this+ * module treats as strictly worse than no number at all. The cost is that the+ * first renders on a newly-picked profile have no estimate, which is exactly+ * what a newly-added model already does.+ *+ * A render whose profile partly degraded (the runner couldn't apply TeaCache,+ * say) still lands in its requested bucket: degradation is rare, surfaced to+ * the user at render time, and ordinary variance next to the slope difference+ * this split exists to capture.+ */+export const timedRenderSamples = (history, modelId, speedProfileId = null) => {if (!Array.isArray(history)) return [];+ const wantBucket = speedBucket(speedProfileId);return history- .filter((e) => e && e.modelId === modelId && Number.isFinite(Number(e.renderMs)) && Number(e.renderMs) > 0)+ .filter((e) => e && e.modelId === modelId && speedBucket(e.speedProfileId) === wantBucket+ && Number.isFinite(Number(e.renderMs)) && Number(e.renderMs) > 0).map((e) => ({workUnits: renderWorkUnits(e),durationMs: Number(e.renderMs),@@ -143,18 +171,21 @@ export const fitRenderCost = (samples) => {* @param {number} ctx.height* @param {number} ctx.numFrames - frames rendered PER CHUNK* @param {number} ctx.steps+ * @param {string|null} [ctx.speedProfileId=null] - the speed profile this render+ * will use (#4875). Samples are scoped to the matching profile; absence and+ * the default profile are the same bucket. See `timedRenderSamples`.* @param {number} [ctx.chunks=1] - chained-render chunk count. Each chunk is a* full render of its own and pays the fixed per-render cost again, so the* chain estimate is `chunks × per-chunk estimate` — not a single render* scaled by total frames.* @returns {{ etaMs: number, perChunkMs: number, chunks: number, basis: 'measured'|'linear'|'proportional', sampleCount: number } | null}- * null when history holds no usable measurement for this model.+ * null when history holds no usable measurement for this model + profile.*/-export const estimateRenderMs = ({ history, modelId, width, height, numFrames, steps, chunks = 1 }) => {+export const estimateRenderMs = ({ history, modelId, width, height, numFrames, steps, speedProfileId = null, chunks = 1 }) => {const workUnits = renderWorkUnits({ width, height, numFrames, steps });if (workUnits == null) return null;const chunkCount = Number.isFinite(Number(chunks)) && Number(chunks) > 0 ? Math.floor(Number(chunks)) : 1;- const samples = timedRenderSamples(history, modelId);+ const samples = timedRenderSamples(history, modelId, speedProfileId);if (!samples.length) return null;// Final backstop: an estimate that isn't a positive finite number is not andiff --git a/server/services/videoGen/eta.test.js b/server/services/videoGen/eta.test.jsindex baa41b8612..61b9c2efa6 100644--- a/server/services/videoGen/eta.test.js+++ b/server/services/videoGen/eta.test.js@@ -182,3 +182,39 @@ describe('estimateRenderMs', () => {expect(estimateRenderMs({ history, ...target }).etaMs).toBe(600_000);});});++// #4875 — a speed profile roughly halves render time, so its samples belong in+// their own cost bucket. These pin the split in BOTH directions: a fast render+// must not be estimated from quality history, and vice versa.+describe('speed-profile sample bucketing', () => {+ const target = { modelId: MODEL, width: 768, height: 512, numFrames: 121, steps: 30 };+ const quality = rec({ renderMs: 600_000 });+ const fast = { ...rec({ renderMs: 300_000 }), speedProfileId: 'fast' };++ it('treats an absent speedProfileId and the default id as the same bucket', () => {+ const history = [quality, { ...quality, speedProfileId: 'quality' }];+ expect(timedRenderSamples(history, MODEL)).toHaveLength(2);+ expect(timedRenderSamples(history, MODEL, 'quality')).toHaveLength(2);+ expect(timedRenderSamples(history, MODEL, '')).toHaveLength(2);+ });++ it('excludes profiled renders from the default bucket', () => {+ expect(timedRenderSamples([quality, fast], MODEL).map((s) => s.durationMs)).toEqual([600_000]);+ });++ it('excludes default renders from a profiled bucket', () => {+ expect(timedRenderSamples([quality, fast], MODEL, 'fast').map((s) => s.durationMs)).toEqual([300_000]);+ });++ it('estimates each bucket from its own measurements, not the pooled median', () => {+ const history = [quality, fast];+ expect(estimateRenderMs({ history, ...target }).etaMs).toBe(600_000);+ expect(estimateRenderMs({ history, ...target, speedProfileId: 'fast' }).etaMs).toBe(300_000);+ });++ it('returns no estimate for a profile this install has never measured', () => {+ // Deliberate: an honest "unknown" beats a confidently wrong number derived+ // from a different cost curve. Same contract as a newly-added model.+ expect(estimateRenderMs({ history: [quality], ...target, speedProfileId: 'fast' })).toBeNull();+ });+});diff --git a/server/services/videoGen/generateVideo.js b/server/services/videoGen/generateVideo.jsindex 7fe1db63d5..5e703535e0 100644--- a/server/services/videoGen/generateVideo.js+++ b/server/services/videoGen/generateVideo.js@@ -57,6 +57,10 @@ import {resolveT2vTwoStageOverride,} from './renderArgs.js';import { spawnAndWatchVideo } from './spawnWatch.js';+import {+ resolveVideoSpeedProfile, speedProfileDeclineReason, resolveVideoSampler,+ inferEffectiveVideoMode,+} from '../../lib/videoSpeedProfiles.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';@@ -117,7 +121,7 @@ export const listVideoModels = () => getVideoModels().map(decorateVideoModel);export const defaultVideoModelId = () => getDefaultVideoModelId();-export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId = defaultVideoModelId(), width = null, height = null, numFrames = null, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, uploadedTempPaths = [], lastImagePath = null, keyframes = null, extendFromVideoPath = null, audioFilePath = null, audioStartSec = null, mode = null, imageStrength = null, i2vReferenceMode = null, loras = null, icReferencePaths = null, icStrength = null, icAttentionStrength = null, icSkipStage2 = false, textEncoderId = null, hidden = false, jobId: providedJobId = null }) {+export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId = defaultVideoModelId(), width = null, height = null, numFrames = null, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, uploadedTempPaths = [], lastImagePath = null, keyframes = null, extendFromVideoPath = null, audioFilePath = null, audioStartSec = null, mode = null, imageStrength = null, i2vReferenceMode = null, loras = null, icReferencePaths = null, icStrength = null, icAttentionStrength = null, icSkipStage2 = false, textEncoderId = null, speedProfileId = 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@@ -336,15 +340,41 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', mconst w = Math.floor(Number(width) / resolutionStep) * resolutionStep;const h = Math.floor(Number(height) / resolutionStep) * resolutionStep;const actualSeed = seed != null && seed !== '' ? Number(seed) : Math.floor(Math.random() * 2147483647);- let actualSteps = model.samplerLocked ? model.steps : (steps ? Number(steps) : model.steps);- let actualGuidance = model.samplerLocked- ? model.guidance- : (guidanceScale != null && guidanceScale !== '' ? Number(guidanceScale) : model.guidance);+ // User-facing speed profile (#4875). Resolved BEFORE the sampler so it can+ // drive steps/guidance/stage-2 together — a half-applied schedule would make+ // the profile's speed claim false. `null` whenever the request is+ // incompatible (wrong mode, unpinned weights, samplerLocked model, unknown+ // id), in which case the render proceeds at its own default sampler and the+ // reason is logged rather than 400'd: a knob that only ever makes a render+ // faster must degrade, not reject.+ //+ // Resolved against the mode the runner will actually INFER, not the raw+ // (possibly absent) request field: buildLtx2Args derives fflf from keyframes+ // and image from a source frame, so gating on a bare `mode` would hand a+ // two-stage schedule to a KeyframeInterpolation render for any direct caller+ // that omits it (Writers Room batch dispatch, scripts).+ const speedProfileMode = inferEffectiveVideoMode({+ mode, keyframes, sourceImagePath, extendFromVideoPath, audioFilePath,+ });+ const speedProfile = resolveVideoSpeedProfile({ model, profileId: speedProfileId, mode: speedProfileMode });+ const speedProfileDeclined = speedProfile ? null : speedProfileDeclineReason({ model, profileId: speedProfileId, mode: speedProfileMode });+ if (speedProfileDeclined) {+ console.log(`⚠️ Speed profile declined [${jobId.slice(0, 8)}] ${speedProfileDeclined.code}: ${speedProfileDeclined.message}`);+ }+ const sampler = resolveVideoSampler({ model, steps, guidanceScale, speedProfile });+ let actualSteps = sampler.steps;+ let actualGuidance = sampler.guidance;+ let actualStage2Steps = sampler.stage2Steps;+ if (speedProfile) {+ console.log(`⚡ Speed profile "${speedProfile.id}" [${jobId.slice(0, 8)}]: ${actualSteps}+${actualStage2Steps} steps, cfg ${actualGuidance}${speedProfile.teacache ? ', teacache' : ''}`);+ }// Opt-in T2V Standard two-stage perf experiment — overrides steps/guidance// (and adds an explicit stage-2 step count) only for a plain default text- // render when PORTOS_T2V_TWO_STAGE is on. No-op otherwise.- let actualStage2Steps = null;- const t2vTwoStage = resolveT2vTwoStageOverride({+ // render when PORTOS_T2V_TWO_STAGE is on. No-op otherwise. Skipped entirely+ // once a speed profile applied: the profile IS the user-chosen schedule, and+ // letting the env experiment overwrite it would silently render something+ // other than what the picker promised.+ const t2vTwoStage = speedProfile ? null : resolveT2vTwoStageOverride({runtime: model.runtime, mode, guidanceScale, steps,sourceImagePath, uploadedTempPath, uploadedTempPaths,keyframes, extendFromVideoPath, audioFilePath,@@ -605,6 +635,15 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m// render apart from a user who happened to pick 8 steps — comparing it// against the default Standard render is the whole point of the knob....(t2vTwoStage ? { twoStageT2v: true, stage2Steps: actualStage2Steps } : {}),+ // Speed profile (#4875). Recorded as the REQUESTED id so a Remix+ // round-trips the schedule the user picked, and — critically — so the ETA+ // estimator can keep fast and quality samples in separate cost buckets+ // (see timedRenderSamples in ./eta.js): a profile roughly halves render+ // time, which is a different cost curve, not sample noise. Absent on a+ // quality render, so every pre-feature history row stays byte-identical.+ // What the runner ACTUALLY managed to apply is stamped separately by+ // finalizeGeneratedVideo from the child's SPEEDPROFILE: report.+ ...(speedProfile ? { speedProfileId: speedProfile.id, stage2Steps: actualStage2Steps } : {}),// 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@@ -650,7 +689,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 }));+ ({ 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 }));} catch (err) {job.status = 'error';const reason = err.message || 'Failed to build video gen args';@@ -665,6 +704,9 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', mawait spawnAndWatchVideo({jobId,+ // Keeps this render's ETA samples in its own cost bucket — a speed profile+ // changes the slope, not just the step count.+ speedProfileId: speedProfile?.id ?? null,cleanupTempFiles,stepwiseDir,job,diff --git a/server/services/videoGen/generateVideoHelpers.js b/server/services/videoGen/generateVideoHelpers.jsindex d06c668908..378b584d90 100644--- a/server/services/videoGen/generateVideoHelpers.js+++ b/server/services/videoGen/generateVideoHelpers.js@@ -135,6 +135,26 @@ export function makeVideoGenLineHandler({ job, jobId, pythonNoiseRe }) {return false;}}+ // What the runner ACTUALLY applied of a requested speed profile+ // (SPEEDPROFILE:<json> — see scripts/generate_ltx2.py). PortOS asks for a+ // schedule declaratively, but only the child can see whether the pinned+ // pipeline accepts `enable_teacache` and whether the distilled adapter is+ // in the pack; `degraded` names every lever it could not apply. Stamped on+ // the job so finalizeGeneratedVideo persists it, which is what keeps a+ // half-applied profile from reading back as a full speed claim.+ if (line.startsWith('SPEEDPROFILE:')) {+ try {+ const applied = JSON.parse(line.slice('SPEEDPROFILE:'.length));+ job.speedProfile = applied;+ const degraded = Array.isArray(applied?.degraded) ? applied.degraded : [];+ console.log(`⚡ speed profile [${jobId.slice(0, 8)}] ${applied?.id || '?'}${degraded.length ? ` — degraded: ${degraded.join(', ')}` : ''}`);+ 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:')) {@@ -546,7 +566,18 @@ export async function finalizeGeneratedVideo({ job, jobId, outputPath, filename,}: {};await mutateHistory((history) => {- history.unshift({ ...meta, thumbnail, ...timing, ...(job.runtime ? { runtime: job.runtime } : {}) });+ history.unshift({+ ...meta,+ thumbnail,+ ...timing,+ ...(job.runtime ? { runtime: job.runtime } : {}),+ // What the speed profile actually resolved to at render time (#4875).+ // `meta.speedProfileId` above is the REQUEST; this is the outcome, so a+ // render whose TeaCache or distilled adapter was unavailable reads back+ // 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 } : {}),+ });return history;});console.log(`✅ Video generated [${jobId.slice(0, 8)}]: ${filename}`);diff --git a/server/services/videoGen/generateVideoHelpers.test.js b/server/services/videoGen/generateVideoHelpers.test.jsindex 1d10d1e3dc..25ec1b817e 100644--- a/server/services/videoGen/generateVideoHelpers.test.js+++ b/server/services/videoGen/generateVideoHelpers.test.js@@ -250,6 +250,26 @@ describe('makeVideoGenLineHandler', () => {expect(handle('RUNTIME:{not json')).toBe(false);expect(job.runtime).toBeUndefined();});++ // #4875 — what the runner ACTUALLY applied of a requested speed profile.+ it('SPEEDPROFILE:<json> → stamps job.speedProfile and suppresses raw logging', () => {+ const applied = { id: 'fast', teacache: true, adapter: 'ltx-2.5-22b-distilled-lora-450.safetensors', degraded: [] };+ expect(handle('SPEEDPROFILE:' + JSON.stringify(applied))).toBe(true);+ expect(job.speedProfile).toEqual(applied);+ // A one-shot metadata line, not progress/status — no SSE frame.+ expect(sse).not.toHaveBeenCalled();+ });++ it('keeps the degraded lever list a render could not apply', () => {+ handle('SPEEDPROFILE:{"id":"fast","teacache":false,"degraded":["teacache"]}');+ expect(job.speedProfile.degraded).toEqual(['teacache']);+ expect(job.speedProfile.teacache).toBe(false);+ });++ it('malformed SPEEDPROFILE: line falls through to raw-logging and leaves job.speedProfile unset', () => {+ expect(handle('SPEEDPROFILE:{not json')).toBe(false);+ expect(job.speedProfile).toBeUndefined();+ });});describe('finalizeGeneratedVideo runtime persistence', () => {@@ -319,6 +339,31 @@ describe('finalizeGeneratedVideo runtime persistence', () => {expect(Date.parse(saved[0].renderCompletedAt)).toBeGreaterThanOrEqual(job.renderStartedAtMs);});+ it('persists what the runner actually applied of a speed profile (#4875)', async () => {+ const applied = { id: 'fast', teacache: false, adapter: 'ltx-2.3-22b-distilled-lora-384.safetensors', degraded: ['teacache', 'adapter'] };+ const job = { id: 'job-abcdef12', clients: [], speedProfile: applied };+ let saved = null;+ await finalizeGeneratedVideo({+ ...baseCtx(job),+ meta: { ...baseCtx(job).meta, speedProfileId: 'fast' },+ mutateHistory: async (fn) => { saved = await fn([]); return saved; },+ });+ // The REQUEST and the OUTCOME are separate fields on purpose: a degraded+ // render must not read back as a full speed claim.+ expect(saved[0].speedProfileId).toBe('fast');+ expect(saved[0].speedProfileApplied).toEqual(applied);+ });++ it('omits speedProfileApplied when the runner reported none (absent sentinel)', async () => {+ const job = { id: 'job-abcdef12', clients: [] };+ let saved = null;+ await finalizeGeneratedVideo({+ ...baseCtx(job),+ mutateHistory: async (fn) => { saved = await fn([]); return saved; },+ });+ expect('speedProfileApplied' in saved[0]).toBe(false);+ });+it('omits render timing entirely when the spawn instant was never observed (#3801)', async () => {const job = { id: 'job-abcdef12', clients: [] };let saved = null;diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex 7fc4a50f28..ccffc51e40 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -90,8 +90,14 @@ vi.mock('../settings.js', () => ({getSettings: vi.fn(async () => ({ videoGen: { acceptedModelTerms: [...settingsState.acceptedModelTerms] } })),}));-vi.mock('../../lib/mediaModels.js', () => ({- getVideoModels: vi.fn(() => [+// The SHIPPED speed-profile decorator runs over this fixture rather than the+// profiles being hand-copied onto the ltx25 entry: the mock carries the real+// repo + revision, so the pin guard is exercised and the fixture cannot drift+// from server/lib/videoSpeedProfiles.js.+vi.mock('../../lib/mediaModels.js', async () => {+ const { applyVideoSpeedProfiles } = await import('../../lib/videoSpeedProfiles.js');+ return ({+ getVideoModels: vi.fn(() => applyVideoSpeedProfiles([{ id: 'ltx2_unified', name: 'LTX-2 Unified', runtime: 'ltx2', repo: 'Lightricks/LTX-Video', steps: 30, guidance: 3.5 },{id: 'ltx25_mlx_q8', name: 'LTX-2.5 MLX Q8', runtime: 'ltx25',@@ -171,10 +177,11 @@ vi.mock('../../lib/mediaModels.js', () => ({targetRoles: ['high_noise_transformer', 'low_noise_transformer'],}],},- ]),+ ])),getDefaultVideoModelId: vi.fn(() => 'ltx2_unified'),getTextEncoderRepo: vi.fn(() => 'some/text-encoder'),-}));+});+});vi.mock('../../lib/sseUtils.js', () => ({broadcastSse: vi.fn(),@@ -1188,6 +1195,41 @@ describe('generateChainedVideo — continuation strategy (context window vs lastexpect(flagValue(renders[1], '--extend-from-video')).toBe(join(tmpdir(), `chaincontext-${innerJobIds[0]}.mp4`));});++ // #4875 — a chained render is ONE clip, so a speed profile applies to every+ // chunk or to none. Chunks 1+ re-enter as `extend` on a window-continuity+ // chain (the default), and no two-stage profile is validated for that+ // pipeline; applying it per chunk would render chunk 0 fast and the rest at+ // the model default, stitching a visible seam mid-clip.+ it('declines a speed profile for the whole chain when continuation runs as extend', async () => {+ const { renders } = await runChain(+ { modelId: 'ltx25_mlx_q8', contextFrames: 22, speedProfileId: 'fast' }, 2,+ );+ expect(renders).toHaveLength(2);+ for (const args of renders) {+ expect(args).not.toContain('--speed-profile');+ expect(args).not.toContain('--teacache');+ // Every chunk on the model's own sampler — no seam.+ expect(flagValue(args, '--steps')).toBe('8');+ expect(flagValue(args, '--cfg-scale')).toBe('3');+ }+ });++ it('applies a speed profile to every chunk of a frame-hop chain, where all modes qualify', async () => {+ // contextFrames: 0 → frame hop → chunks 1+ are `image`, which the profile+ // IS validated for, so the whole chain takes it.+ const { renders } = await runChain(+ { modelId: 'ltx25_mlx_q8', contextFrames: 0, speedProfileId: 'fast' }, 2,+ );+ expect(renders).toHaveLength(2);+ for (const args of renders) {+ expect(flagValue(args, '--speed-profile')).toBe('fast');+ expect(args).toContain('--teacache');+ expect(flagValue(args, '--steps')).toBe('8');+ expect(flagValue(args, '--cfg-scale')).toBe('1');+ expect(flagValue(args, '--stage2-steps')).toBe('3');+ }+ });});describe('generateChainedVideo — resolved geometry on the outer frames (#4588)', () => {@@ -5057,6 +5099,200 @@ describe('updateHistoryItemPrompt — trigger-weave provenance (#4665)', () => {});});+// #4875 — the user-facing speed profile. Three things must hold end to end:+// the profile's schedule and levers reach the helper's argv; an incompatible+// request degrades to the model's own sampler instead of half-applying; and a+// Quality render builds byte-identical argv to one from before the feature+// existed (the default-preservation contract).+describe('generateVideo — LTX-2.5 speed profile (#4875)', () => {+ const renderArgs = async ({ jobId, modelId = 'ltx25_mlx_q8', ...rest }) => {+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');+ const spawnMock = vi.mocked(spawnDetached);+ spawnMock.mockClear();+ await generateVideo({+ jobId,+ pythonPath: '/usr/bin/python3',+ modelId,+ prompt: 'a quiet street at dusk',+ width: 512, height: 512, numFrames: 25, fps: 24,+ ...rest,+ });+ const call = spawnMock.mock.calls.find(+ ([bin, args]) => (isLtx25Python(bin) || isLtx2Python(bin))+ && Array.isArray(args) && args.includes('--mode'),+ );+ expect(call).toBeTruthy();+ return call[1];+ };++ const valueAfter = (args, flag) => args[args.indexOf(flag) + 1];++ it('threads the profile schedule and its levers into the helper argv', async () => {+ const args = await renderArgs({ jobId: 'sp-fast', mode: 'text', speedProfileId: 'fast' });+ expect(valueAfter(args, '--steps')).toBe('8');+ expect(valueAfter(args, '--stage2-steps')).toBe('3');+ expect(valueAfter(args, '--cfg-scale')).toBe('1');+ expect(valueAfter(args, '--speed-profile')).toBe('fast');+ expect(args).toContain('--teacache');+ expect(valueAfter(args, '--require-adapter')).toBe('ltx-2.5-22b-distilled-lora-450.safetensors');+ // The profile declares no threshold override, so the pin's calibrated+ // default must be left alone rather than pinned to a literal here.+ expect(args).not.toContain('--teacache-thresh');+ });++ it('applies on image mode too — the other mode the schedule was validated for', async () => {+ const args = await renderArgs({ jobId: 'sp-image', mode: 'image', sourceImagePath: '/mock/first.png', speedProfileId: 'fast' });+ expect(valueAfter(args, '--speed-profile')).toBe('fast');+ expect(valueAfter(args, '--steps')).toBe('8');+ });++ // DEFAULT PRESERVATION: the whole point of 'quality' being a no-op.+ it.each([+ ['omitted', 'omitted', undefined],+ ['the explicit default id', 'explicit', 'quality'],+ ['an empty string', 'empty', ''],+ ])('leaves a render with %s byte-identical to the pre-feature argv', async (_name, label, speedProfileId) => {+ // Pin the seed and strip the per-job output path so the comparison is of+ // the SCHEDULE, not of the two values that are per-render by design.+ const strip = (a) => a.map((v) => String(v).replace(/sp-[a-z-]+\.mp4$/, "<job>.mp4"));+ const baseline = strip(await renderArgs({ jobId: `sp-base-${label}`, mode: 'text', seed: 7 }));+ const args = strip(await renderArgs({ jobId: `sp-default-${label}`, mode: 'text', seed: 7, speedProfileId }));+ expect(args).toEqual(baseline);+ expect(args.filter((a) => String(a).startsWith('--speed-profile')+ || String(a).startsWith('--teacache') || String(a).startsWith('--require-adapter'))).toEqual([]);+ expect(args).not.toContain('--stage2-steps');+ expect(valueAfter(args, '--steps')).toBe('8');+ expect(valueAfter(args, '--cfg-scale')).toBe('3');+ });++ it('declines on a mode the profile was never validated for, keeping the model sampler', async () => {+ const args = await renderArgs({+ jobId: 'sp-extend-declines',+ mode: 'extend',+ extendFromVideoPath: '/mock/source.mp4',+ speedProfileId: 'fast',+ });+ expect(args).not.toContain('--speed-profile');+ expect(args).not.toContain('--teacache');+ expect(valueAfter(args, '--steps')).toBe('8');+ expect(valueAfter(args, '--cfg-scale')).toBe('3');+ });++ // MODEL PIN COMPATIBILITY: the 2.3 entry points at different weights, so it+ // declares no profiles — asking for one must degrade, not half-apply.+ it('declines on a model that declares no profiles', async () => {+ const args = await renderArgs({ jobId: 'sp-wrong-model', modelId: 'ltx2_unified', mode: 'text', speedProfileId: 'fast' });+ expect(args).not.toContain('--speed-profile');+ expect(valueAfter(args, '--steps')).toBe('30');+ expect(valueAfter(args, '--cfg-scale')).toBe('3.5');+ });++ it('declines an id no model offers', async () => {+ const args = await renderArgs({ jobId: 'sp-unknown-id', mode: 'text', speedProfileId: 'turbo' });+ expect(args).not.toContain('--speed-profile');+ expect(valueAfter(args, '--steps')).toBe('8');+ expect(valueAfter(args, '--cfg-scale')).toBe('3');+ });++ // The profile owns steps AND CFG together — a half-override would give the+ // user neither the profile's speed nor their own setting.+ it('overrides explicit steps and CFG rather than blending with them', async () => {+ const args = await renderArgs({ jobId: 'sp-overrides-user', mode: 'text', speedProfileId: 'fast', steps: 30, guidanceScale: 7 });+ expect(valueAfter(args, '--steps')).toBe('8');+ expect(valueAfter(args, '--cfg-scale')).toBe('1');+ });++ describe('history metadata', () => {+ const metaFor = async (jobId, extra) => {+ let started = null;+ const onStarted = (e) => { if (e.generationId === jobId) started = e; };+ videoGenEvents.on('started', onStarted);+ await generateVideo({+ jobId,+ pythonPath: '/usr/bin/python3',+ modelId: 'ltx25_mlx_q8',+ prompt: 'a quiet street at dusk',+ width: 512, height: 512, numFrames: 25, fps: 24,+ mode: 'text',+ ...extra,+ });+ videoGenEvents.off('started', onStarted);+ expect(started).toBeTruthy();+ return started;+ };++ it('stamps the REQUESTED profile id and the effective schedule', async () => {+ const meta = await metaFor('sp-meta-fast', { speedProfileId: 'fast' });+ expect(meta.speedProfileId).toBe('fast');+ expect(meta.stage2Steps).toBe(3);+ expect(meta.steps).toBe(8);+ expect(meta.guidanceScale).toBe(1);+ });++ // The ETA estimator buckets on this field, so a Quality render must carry+ // NO key at all — an explicit 'quality' would be a second spelling of the+ // default and would not match pre-feature history.+ it('stamps nothing on a default render', async () => {+ const meta = await metaFor('sp-meta-default', {});+ expect(meta.speedProfileId).toBeUndefined();+ expect(meta.stage2Steps).toBeUndefined();+ });++ it('stamps nothing when the profile was declined', async () => {+ const meta = await metaFor('sp-meta-declined', { speedProfileId: 'turbo' });+ expect(meta.speedProfileId).toBeUndefined();+ });+ });+});++// #4875 — the chunk entries of a chain are written `hidden: true`, so the+// STITCHED record is the only one the user ever sees. Without inheriting the+// profile there, a chained render's lightbox shows no "Speed profile" row at+// all — including for a chain whose TeaCache or adapter was unavailable, which+// is exactly the silent speed claim the feature exists to prevent — and a Remix+// of the clip quietly reverts to Quality.+describe('stitchVideos — speed-profile inheritance (#4875)', () => {+ const chunk = (id, extra = {}) => ({+ id, filename: `${id}.mp4`, prompt: 'a shot', modelId: 'ltx25_mlx_q8',+ width: 512, height: 512, fps: 24, numFrames: 25, seed: 7, ...extra,+ });++ const stitchOf = async (entries) => {+ const { readJSONFile, atomicWrite } = await import('../../lib/fileUtils.js');+ const { probeFrameCount } = await import('../../lib/ffmpeg.js');+ vi.mocked(atomicWrite).mockClear();+ vi.mocked(probeFrameCount).mockImplementation(async () => 25);+ vi.mocked(readJSONFile).mockImplementation(async () => entries);+ return stitchVideos(entries.map((e) => e.id));+ };++ it('carries the requested profile and the runner outcome from the first chunk', async () => {+ const applied = { id: 'fast', teacache: false, degraded: ['teacache'] };+ const stitched = await stitchOf([+ chunk('c1', { speedProfileId: 'fast', speedProfileApplied: applied }),+ chunk('c2', { speedProfileId: 'fast', speedProfileApplied: applied }),+ ]);+ // Both halves: the REQUEST (what Remix round-trips, what the ETA buckets+ // on) and the OUTCOME (what stops a degraded run reading as a full one).+ expect(stitched.speedProfileId).toBe('fast');+ expect(stitched.speedProfileApplied).toEqual(applied);+ });++ it('stamps neither field for a Quality chain, so the record stays pre-feature shaped', async () => {+ const stitched = await stitchOf([chunk('c1'), chunk('c2')]);+ expect('speedProfileId' in stitched).toBe(false);+ expect('speedProfileApplied' in stitched).toBe(false);+ });++ it('carries the id alone when the runner reported no outcome', async () => {+ const stitched = await stitchOf([+ chunk('c1', { speedProfileId: 'fast' }), chunk('c2', { speedProfileId: 'fast' }),+ ]);+ expect(stitched.speedProfileId).toBe('fast');+ expect('speedProfileApplied' in stitched).toBe(false);+ });+});+// The reference-mode promise (#4874) at the RENDER boundary. The route gates it// too, but persisted-queue replays, retries and internal producers all reach// generateVideo directly — a hole here means a clip anchored under an Inspirediff --git a/server/services/videoGen/renderArgs.js b/server/services/videoGen/renderArgs.jsindex 4007cd2ca7..5c8404ddcf 100644--- a/server/services/videoGen/renderArgs.js+++ b/server/services/videoGen/renderArgs.js@@ -283,7 +283,7 @@ export const ltx25TextEncoderArgs = (textEncoder) => {return args;};-const buildLtx2Args = ({ model, ltxModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, i2vReferenceMode, disableAudio, outputPath, previewDir, textEncoderRepo, textEncoder, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 }) => {+const buildLtx2Args = ({ model, ltxModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, i2vReferenceMode, disableAudio, outputPath, previewDir, textEncoderRepo, textEncoder, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2, speedProfile }) => {assertByovRuntimeInstalled(model.runtime);// Map PortOS UI modes to the helper's subcommand. Native extend on ltx2// routes to ExtendPipeline.extend_from_video — conditions on the entire@@ -411,6 +411,30 @@ const buildLtx2Args = ({ model, ltxModelPath, prompt, negativePrompt, width, hei// Two-stage T2V experiment passes an explicit stage-2 step count; omitted// otherwise so the pipeline keeps its own default.if (stage2Steps != null) args.push('--stage2-steps', String(stage2Steps));+ // Speed-profile levers (#4875). Emitted ONLY for a resolved profile — a+ // quality render must build byte-identical args to one from before the+ // feature existed, so absence is the whole contract here.+ //+ // The helper, not this builder, decides whether each lever is actually+ // available: `--speed-profile` names the profile in the child's+ // SPEEDPROFILE: report, `--teacache` REQUESTS stage-1 caching (the helper+ // probes the pinned pipeline for the kwarg and reports `degraded` when it+ // isn't there), and `--require-adapter` names the distilled adapter the+ // schedule was measured with so a pack missing it degrades loudly instead+ // of rendering slower than the profile claims.+ if (speedProfile) {+ args.push('--speed-profile', speedProfile.id);+ if (speedProfile.teacache) {+ args.push('--teacache');+ if (speedProfile.teacacheThresh != null) {+ args.push('--teacache-thresh', String(speedProfile.teacacheThresh));+ }+ }+ // String()'d like every other value pushed here: spawn throws+ // ERR_INVALID_ARG_TYPE on a non-string argv entry, and a hand-edited+ // registry can put a number in this field.+ if (speedProfile.requiresAdapter) args.push('--require-adapter', String(speedProfile.requiresAdapter));+ }if (negativePrompt) args.push('--negative-prompt', negativePrompt);if (imageStrength != null) args.push('--image-strength', String(imageStrength));// The reference-mode promise (#4874). Emitted only when it is NOT the default so@@ -723,7 +747,7 @@ const buildHunyuanArgs = ({ model, prompt, negativePrompt, width, height, numFrareturn { bin: HUNYUAN_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 }) => {+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 }) => {// 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@@ -741,7 +765,7 @@ export const buildArgs = ({ pythonPath, modelId, model, wanModelPath, wanRequire// runtime. Existing notapalindrome models default to runtime: 'mlx_video'// (or undefined in legacy registries — see backfillRuntime in mediaModels.js).if (isLtx2FamilyRuntime(model.runtime)) {- return buildLtx2Args({ model, ltxModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, i2vReferenceMode, disableAudio, outputPath, previewDir, textEncoderRepo, textEncoder, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 });+ return buildLtx2Args({ model, ltxModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, i2vReferenceMode, disableAudio, outputPath, previewDir, textEncoderRepo, textEncoder, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2, speedProfile });}// IC-LoRA remix modes are an LTX-2 primitive (ICLoraPipeline) — no other// runtime has an equivalent. The route guards this too, but a non-routediff --git a/server/services/videoGen/spawnWatch.js b/server/services/videoGen/spawnWatch.jsindex 957cfd12e1..ff653917c9 100644--- a/server/services/videoGen/spawnWatch.js+++ b/server/services/videoGen/spawnWatch.js@@ -52,6 +52,7 @@ const MUXING_DONE_RE = /\[Decoding video \+ audio \+ muxing\]\s+done in/i;export async function spawnAndWatchVideo({jobId,+ speedProfileId = null,cleanupTempFiles,stepwiseDir,job,@@ -649,6 +650,10 @@ export async function spawnAndWatchVideo({height: h,numFrames: parsedNumFrames,steps: actualSteps,+ // Keeps this render's samples in its own cost bucket — a speed profile+ // changes the slope, not just the step count, so pooling the two would+ // over-estimate a fast render and under-estimate a quality one.+ speedProfileId,});job.etaMs = etaEstimate ? etaEstimate.etaMs : null;const etaFields = etaEstimatediff --git a/server/services/videoGen/stitchVideos.js b/server/services/videoGen/stitchVideos.jsindex c11ad445ff..2360b7d5bf 100644--- a/server/services/videoGen/stitchVideos.js+++ b/server/services/videoGen/stitchVideos.js@@ -205,6 +205,17 @@ export async function stitchVideos(videoIds, opts = {}) {'i2vReferenceMode','conditioning','renderInputsVersion',+ // Speed profile (#4875) — the REQUESTED schedule and what the runner+ // actually applied. Inherited for a stronger reason than the dials above:+ // a chain's chunk entries are written `hidden: true`, so this stitched+ // record is the ONLY one the user ever sees. Without it the lightbox's+ // "Speed profile" row never renders for a chained render — including a+ // chain whose TeaCache or adapter was unavailable, which is exactly the+ // silent speed claim the feature exists to prevent — and a Remix quietly+ // reverts to Quality. A chain applies its profile to every chunk or to+ // none (resolveVideoSpeedProfileForModes), so videos[0] speaks for all.+ 'speedProfileId',+ 'speedProfileApplied',].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