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(video): add long-form audio-image generation (#5458)
[._.]/ Adam Eivy30a69ad6b519
diff --git a/client/src/components/videoGen/AdvancedParamsPanel.jsx b/client/src/components/videoGen/AdvancedParamsPanel.jsxindex 94a2d06302..c3ff9ecaaf 100644--- a/client/src/components/videoGen/AdvancedParamsPanel.jsx+++ b/client/src/components/videoGen/AdvancedParamsPanel.jsx@@ -53,6 +53,7 @@ export default function AdvancedParamsPanel({const showDisableAudio = showAudioFlags && supportsVideoAudioControls(currentModel);const showPromptAudioControls = showAudioFlags && noMusic != null && supportsVideoAudioPromptControls(currentModel);const audioDisabled = showDisableAudio && disableAudio;+ const showFrames = !(mode === 'a2v' && currentModel?.audioDurationDriven === true);// Chunk chaining seeds chunk N+1 from chunk N's last frame, so it needs i2v —// the same predicate the picker uses, not a second reading of supportedModes.const showChunks = mode !== 'a2v' && isModelAllowedForMode(currentModel, 'image');@@ -139,7 +140,7 @@ export default function AdvancedParamsPanel({<div className="border-t border-port-border pt-3 space-y-3"><h2 className="text-xs font-medium text-gray-400 uppercase tracking-wide">Advanced</h2><div className="grid grid-cols-2 sm:grid-cols-3 gap-3">- <FormField label="Frames" labelClassName="block text-xs font-medium text-gray-400 mb-1">+ {showFrames && <FormField label="Frames" labelClassName="block text-xs font-medium text-gray-400 mb-1"><selectvalue={numFrames}onChange={(e) => onNumFramesChange(Number(e.target.value))}@@ -156,7 +157,7 @@ export default function AdvancedParamsPanel({Past 241 frames a single-pass render may swap or OOM at 48 GB. For reliable longer clips, render up to ~10s and then use <strong>Extend</strong> on the result — it conditions on the source's full latent rather than a single last frame.</p>)}- </FormField>+ </FormField>}{showChunks && (<div>diff --git a/client/src/components/videoGen/AdvancedParamsPanel.test.jsx b/client/src/components/videoGen/AdvancedParamsPanel.test.jsxindex 29a2ee31ed..efc8d14e29 100644--- a/client/src/components/videoGen/AdvancedParamsPanel.test.jsx+++ b/client/src/components/videoGen/AdvancedParamsPanel.test.jsx@@ -69,6 +69,26 @@ describe('AdvancedParamsPanel', () => {expect(screen.getByLabelText('Frames')).toBeTruthy();});+ it('hides the manual frame picker when A2V follows the uploaded audio duration', () => {+ renderPanel({+ mode: 'a2v',+ currentModel: {+ runtime: 'ltx25',+ supportedModes: [...MLX_MODES, 'a2v'],+ audioDurationDriven: true,+ frameStride: 8,+ maxNumFrames: 1017,+ },+ });+ expect(screen.queryByLabelText('Frames')).toBeNull();+ });++ it('offers the full 1017-frame LTX single-pass boundary outside duration-driven A2V', () => {+ renderPanel({ currentModel: { runtime: 'ltx25', supportedModes: [...MLX_MODES, 'a2v'] } });+ expect(screen.getByLabelText('Frames')).toHaveDisplayValue(/121/);+ expect([...screen.getByLabelText('Frames').options].map((option) => option.value)).toContain('1017');+ });+it('hides chunks for a Wan profile that cannot continue via image mode', () => {renderPanel({currentModel: { runtime: 'wan22', supportedModes: ['text'], frameStride: 4 },diff --git a/client/src/components/videoGen/AudioPanel.jsx b/client/src/components/videoGen/AudioPanel.jsxindex 948b33ff21..236e29085d 100644--- a/client/src/components/videoGen/AudioPanel.jsx+++ b/client/src/components/videoGen/AudioPanel.jsx@@ -1,16 +1,45 @@/**- * Audio-to-video (a2v) upload panel — dgrauet/ltx2 runtime only. The uploaded- * WAV/MP3/M4A drives the video's motion + audio track.+ * Audio-to-video (a2v) upload panel. The uploaded+ * WAV/MP3/M4A drives the video's motion + audio track and is previewable before+ * the render is submitted.** Presentational — the selected File, frame/fps (for the length hint), and the* "no compatible model installed" condition are owned by the VideoGen page.*/+import { useEffect, useState } from 'react';import { Upload, Music } from 'lucide-react';-import { formatBytes } from '../../utils/formatters';+import { formatBytes, formatDurationSec } from '../../utils/formatters';import FilePickerButton from '../ui/FilePickerButton';-import Ltx2RuntimeMissingNotice from './Ltx2RuntimeMissingNotice';-export default function AudioPanel({ audioFile, numFrames, fps, hasCompatibleModel, onPick, onClear }) {+export default function AudioPanel({+ audioFile,+ numFrames,+ fps,+ hasCompatibleModel,+ audioDurationDriven = false,+ arbitraryLengthAudio = false,+ maxReferenceAudioSeconds = 15,+ maxDurationSeconds = null,+ durationError = null,+ onDurationChange = null,+ onPick,+ onClear,+}) {+ const [audioDuration, setAudioDuration] = useState(null);+ const [previewUrl, setPreviewUrl] = useState('');++ useEffect(() => {+ setAudioDuration(null);+ onDurationChange?.(null);+ if (!audioFile) {+ setPreviewUrl('');+ return undefined;+ }+ const nextPreviewUrl = URL.createObjectURL(audioFile);+ setPreviewUrl(nextPreviewUrl);+ return () => URL.revokeObjectURL(nextPreviewUrl);+ }, [audioFile, onDurationChange]);+return (<div className="border border-port-border/50 rounded-lg p-2 space-y-1.5"><div className="flex items-center justify-between">@@ -20,10 +49,30 @@ export default function AudioPanel({ audioFile, numFrames, fps, hasCompatibleMod)}</div>{audioFile ? (- <div className="flex items-center gap-2 text-[11px] text-gray-300">- <Music className="w-3.5 h-3.5 text-port-accent" />- <span className="truncate" title={audioFile.name}>{audioFile.name}</span>- <span className="text-gray-500">{formatBytes(audioFile.size, 2)}</span>+ <div className="space-y-1.5">+ <div className="flex items-center gap-2 text-[11px] text-gray-300">+ <Music className="w-3.5 h-3.5 text-port-accent shrink-0" />+ <span className="truncate" title={audioFile.name}>{audioFile.name}</span>+ <span className="text-gray-500 shrink-0">{formatBytes(audioFile.size, 2)}</span>+ <span className="text-gray-500 shrink-0">+ {audioDuration == null ? 'Reading duration…' : formatDurationSec(audioDuration)}+ </span>+ </div>+ <audio+ aria-label="Preview selected audio"+ className="h-8 w-full"+ controls+ preload="metadata"+ src={previewUrl}+ onLoadedMetadata={(event) => {+ const duration = event.currentTarget.duration;+ const resolved = Number.isFinite(duration) ? duration : null;+ setAudioDuration(resolved);+ onDurationChange?.(resolved);+ }}+ >+ Your browser does not support audio playback.+ </audio></div>) : (<FilePickerButton@@ -36,9 +85,18 @@ export default function AudioPanel({ audioFile, numFrames, fps, hasCompatibleMod</FilePickerButton>)}<p className="text-[10px] text-gray-500 leading-snug">- Audio length should match {`${(numFrames / fps).toFixed(1)}s`} (frames ÷ fps). Longer clips are trimmed to fit; shorter clips fail.+ {audioDurationDriven+ ? (arbitraryLengthAudio+ ? `Video duration follows the audio. PortOS renders continuity-linked windows of up to ${maxReferenceAudioSeconds}s, then preserves the full source audio on the final video.`+ : (durationError+ ? `Video duration follows the selected audio and snaps to the model's temporal grid${maxDurationSeconds != null ? `, with up to ${maxDurationSeconds.toFixed(1)}s supported per render` : ''}.`+ : `Video duration follows the selected audio and snaps up to ${numFrames} frames on the model's temporal grid${maxDurationSeconds != null ? ` (up to ${maxDurationSeconds.toFixed(1)}s)` : ''}.`))+ : `Audio length should match ${(numFrames / fps).toFixed(1)}s (frames ÷ fps). Longer clips are trimmed to fit; shorter clips fail.`}</p>- {!hasCompatibleModel && <Ltx2RuntimeMissingNotice subject="a2v" />}+ {durationError && <p className="text-[11px] text-port-error leading-snug">{durationError}</p>}+ {!hasCompatibleModel && (+ <p className="text-[11px] text-port-warning">No audio-to-video model is available on this instance.</p>+ )}</div>);}diff --git a/client/src/components/videoGen/AudioPanel.test.jsx b/client/src/components/videoGen/AudioPanel.test.jsxindex d561b1a89d..4ebd5a2571 100644--- a/client/src/components/videoGen/AudioPanel.test.jsx+++ b/client/src/components/videoGen/AudioPanel.test.jsx@@ -1,8 +1,21 @@-import { describe, it, expect, vi } from 'vitest';+import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest';import { render, screen, fireEvent } from '@testing-library/react';import AudioPanel from './AudioPanel';describe('AudioPanel', () => {+ const originalCreateObjectURL = URL.createObjectURL;+ const originalRevokeObjectURL = URL.revokeObjectURL;++ beforeEach(() => {+ URL.createObjectURL = vi.fn(() => 'blob:audio-preview');+ URL.revokeObjectURL = vi.fn();+ });++ afterEach(() => {+ URL.createObjectURL = originalCreateObjectURL;+ URL.revokeObjectURL = originalRevokeObjectURL;+ });+it('renders the upload control when no file is picked', () => {render(<AudioPanel@@ -35,11 +48,35 @@ describe('AudioPanel', () => {);expect(screen.getByText('track.wav')).toBeTruthy();expect(screen.getByText(/2 MB/)).toBeTruthy();+ expect(screen.getByLabelText('Preview selected audio')).toHaveAttribute('src', 'blob:audio-preview');fireEvent.click(screen.getByText('Clear'));expect(onClear).toHaveBeenCalled();});- it('warns when no ltx2-compatible model is installed', () => {+ it('loads the selected audio metadata, shows its duration, and releases the preview URL', () => {+ const file = new File(['waveform'], 'scene.wav', { type: 'audio/wav' });+ const onDurationChange = vi.fn();+ const { unmount } = render(+ <AudioPanel+ audioFile={file}+ numFrames={121}+ fps={24}+ hasCompatibleModel+ onDurationChange={onDurationChange}+ onPick={vi.fn()}+ onClear={vi.fn()}+ />,+ );+ const player = screen.getByLabelText('Preview selected audio');+ Object.defineProperty(player, 'duration', { configurable: true, value: 41.04 });+ fireEvent.loadedMetadata(player);+ expect(screen.getByText('0:41')).toBeTruthy();+ expect(onDurationChange).toHaveBeenLastCalledWith(41.04);+ unmount();+ expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:audio-preview');+ });++ it('warns when no audio-to-video model is available', () => {render(<AudioPanelaudioFile={null}@@ -50,7 +87,7 @@ describe('AudioPanel', () => {onClear={vi.fn()}/>,);- expect(screen.getByText(/a2v requires an ltx2-runtime model/i)).toBeTruthy();+ expect(screen.getByText(/No audio-to-video model is available/i)).toBeTruthy();});it('does not warn when a compatible model exists', () => {@@ -64,6 +101,45 @@ describe('AudioPanel', () => {onClear={vi.fn()}/>,);- expect(screen.queryByText(/a2v requires an ltx2-runtime model/i)).toBeNull();+ expect(screen.queryByText(/No audio-to-video model is available/i)).toBeNull();+ });++ it('explains arbitrary-length H3 windowing without a frame-length warning', () => {+ render(+ <AudioPanel+ audioFile={null}+ numFrames={124}+ fps={24}+ hasCompatibleModel+ audioDurationDriven+ arbitraryLengthAudio+ maxReferenceAudioSeconds={15}+ onPick={vi.fn()}+ onClear={vi.fn()}+ />,+ );+ expect(screen.getByText(/continuity-linked windows of up to 15s/i)).toBeTruthy();+ expect(screen.getByText(/preserves the full source audio/i)).toBeTruthy();+ expect(screen.queryByText(/frames ÷ fps/i)).toBeNull();+ });++ it('does not claim a stale derived frame count when LTX audio exceeds the single-pass limit', () => {+ render(+ <AudioPanel+ audioFile={null}+ numFrames={985}+ fps={24}+ hasCompatibleModel+ audioDurationDriven+ maxDurationSeconds={42.375}+ durationError="This audio is too long for one LTX render."+ onPick={vi.fn()}+ onClear={vi.fn()}+ />,+ );+ expect(screen.queryByText(/985 frames/i)).toBeNull();+ expect(screen.getByText(/snaps to the model's temporal grid/i)).toBeTruthy();+ expect(screen.getByText(/up to 42\.4s/i)).toBeTruthy();+ expect(screen.getByText(/too long for one LTX render/i)).toBeTruthy();});});diff --git a/client/src/hooks/useVideoGenFieldState.js b/client/src/hooks/useVideoGenFieldState.jsindex 128de0c7e1..87afa8d6bb 100644--- a/client/src/hooks/useVideoGenFieldState.js+++ b/client/src/hooks/useVideoGenFieldState.js@@ -57,6 +57,9 @@ export function useVideoGenFieldState({const [extendFromVideoId, setExtendFromVideoId] = useState('');const [extendingFrame, setExtendingFrame] = useState(false);const [audioFile, setAudioFile] = useState(null);+ // Null means metadata has not loaded (or is unreadable), which is distinct+ // from a real numeric duration for validation and frame derivation.+ const [audioDurationSec, setAudioDurationSec] = useState(null);const audioHandoffRef = useRef(null);const [icReferenceFile, setIcReferenceFile] = useState(null);const [icReferenceVideoId, setIcReferenceVideoId] = useState('');@@ -67,6 +70,7 @@ export function useVideoGenFieldState({const staleModelToastRef = useRef(null);return {+ audioDurationSec, setAudioDurationSec,audioFile, setAudioFile, audioHandoffRef,backend, setBackend,chunks, setChunks,diff --git a/client/src/hooks/useVideoGenForm.js b/client/src/hooks/useVideoGenForm.jsindex 50dac1bff2..361b604204 100644--- a/client/src/hooks/useVideoGenForm.js+++ b/client/src/hooks/useVideoGenForm.js@@ -16,7 +16,7 @@ import { VIDEO_TILING_ENUM_SET } from '../lib/videoTilingOptions';import {MAX_CHUNKS,videoModelMemoryGb, isModelAllowedForMode,- normalizeFramesForModel, normalizeFpsForModel,+ normalizeFramesForModel, normalizeFpsForModel, audioDurationToFrames,icLoraSpecForMode,textEncoderOptionsForModel, normalizeTextEncoderForModel,textEncoderIdFromRecord,@@ -79,6 +79,7 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, rconst incomingHeight = searchParams.get('h');const {+ audioDurationSec, setAudioDurationSec,audioFile, setAudioFile, audioHandoffRef,backend, setBackend,chunks, setChunks,@@ -416,6 +417,19 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, rconst currentModel = models.find((m) => m.id === modelId);+ // LTX-2.5's A2V runner needs an explicit frame canvas even though the user+ // thinks in audio duration. Snap the browser-probed duration UP to the+ // model's causal-VAE grid for an honest preview. The server repeats this from+ // ffprobe on the staged upload, so direct API callers get the same contract.+ // MiniMax Ref2VA is excluded: its wrapper windows arbitrary audio internally.+ useEffect(() => {+ if (mode !== 'a2v' || currentModel?.audioDurationDriven !== true+ || currentModel?.arbitraryLengthAudio === true) return;+ const frames = audioDurationToFrames(audioDurationSec, fps, currentModel?.frameStride);+ if (frames == null || frames > Number(currentModel?.maxNumFrames)) return;+ setNumFrames(frames);+ }, [audioDurationSec, currentModel, fps, mode]);+// A source model can reach this hook either through a URL handoff before// /status has populated `models`, or from the in-page gallery after it has.// Resolve both cases here. The fallback is deliberately limited to models@@ -666,6 +680,7 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, r};const {+ a2vDurationError,a2vModeBlocked,chainingActive,extendModeBlocked,@@ -674,11 +689,13 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, rkeyframesError,maxSafeFrames,} = useVideoGenValidation({+ audioDurationSec,audioFile,chunks,currentModel,extendFromVideoId,extendingFrame,+ fps,height,icImageKind,icModeActive,@@ -692,6 +709,7 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, rnumFrames,pixelBudget: status?.fflfLtx2PixelBudget,sourceImageFile,+ sourceImageUpload,width,});@@ -821,14 +839,8 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, r// an empty extendFromVideoId.clearSourceImage();} else if (next === 'a2v') {- // a2v takes audio only — buildGeneratePayload omits sourceImageFile +- // sourceImage in this mode, so dropping them here keeps state honest- // (no stale image survives in the form to imply it's being used).- // The python helper supports an optional first-frame image, but the- // UI doesn't expose it yet (see PR description "Out of scope"). Once- // we add a gallery-pick path for the first frame, restore the source-- // image state pass-through here.- clearSourceImage();+ // Audio-to-video may also condition on a reference image (required by+ // MiniMax H3 Ref2VA, optional on LTX), so preserve the source picker.clearLastImage();setExtendFromVideoId('');// disableAudio strips the output audio track — in a2v mode that would@@ -838,7 +850,7 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, rsetDisableAudio(false);setNoMusic(false);setChunks(1);- // Auto-select to a compatible ltx2-runtime model is handled by the+ // Auto-select to a compatible audio-to-video runtime is handled by the// modelId-validation effect, which re-runs on every mode change.}};@@ -1268,7 +1280,8 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, r// ExtendextendFromVideoId, extendingFrame, handleExtendPick, extendModeBlocked,// Audio-to-video- audioFile, setAudioFile, a2vModeBlocked,+ audioDurationSec, setAudioDurationSec,+ audioFile, setAudioFile, a2vDurationError, a2vModeBlocked,// IC-LoRA remixicSpec, icModeActive, icImageKind, icLoraModeBlocked,icReferenceFile, icReferenceVideoId, icReferenceNames, icReferenceImageFiles,diff --git a/client/src/hooks/useVideoGenForm.test.jsx b/client/src/hooks/useVideoGenForm.test.jsxindex f2a54cb5a5..6723f7b3bc 100644--- a/client/src/hooks/useVideoGenForm.test.jsx+++ b/client/src/hooks/useVideoGenForm.test.jsx@@ -19,7 +19,17 @@ const { useVideoGenForm } = await import('./useVideoGenForm.js');// (server/lib/videoModeProfiles.js, #3737), so a model that reaches the client// without one is not a shape the picker has to handle.const RUNTIME_MODES = ['text', 'image', 'fflf', 'extend'];-const LTX2 = { id: 'ltx2-model', name: 'LTX-2.3', runtime: 'ltx2', lastFrameAnchored: true, supportedModes: RUNTIME_MODES };+const LTX2 = { id: 'ltx2-model', name: 'LTX-2.3', runtime: 'ltx2', lastFrameAnchored: true, supportedModes: [...RUNTIME_MODES, 'a2v'] };+const LTX25 = {+ id: 'ltx25-model',+ name: 'LTX-2.5',+ runtime: 'ltx25',+ lastFrameAnchored: true,+ supportedModes: [...RUNTIME_MODES, 'a2v'],+ audioDurationDriven: true,+ frameStride: 8,+ maxNumFrames: 1017,+};const MLX = { id: 'mlx-model', name: 'LTX distilled', runtime: 'mlx_video', lastFrameAnchored: false, supportedModes: RUNTIME_MODES };const WAN_T2V = { id: 'wan-t2v', name: 'Wan T2V', runtime: 'wan22', supportedModes: ['text'], frameStride: 4 };const WAN_TI2V = { id: 'wan-ti2v', name: 'Wan TI2V', runtime: 'wan22', supportedModes: ['text', 'image'], frameStride: 4 };@@ -43,6 +53,19 @@ const H3 = {{ id: 'heretic-bf16', label: 'Ultra-Heretic', description: 'Uncensored.', builtIn: false, sizeBytes: 51506295440 },],};+const H3_REF2VA = {+ id: 'minimax-h3-ref2va',+ name: 'MiniMax H3 Ref2VA',+ runtime: 'minimax_h3_ref2va',+ supportedModes: ['a2v'],+ requiresSourceImageForA2v: true,+ audioDurationDriven: true,+ arbitraryLengthAudio: true,+ maxReferenceAudioSeconds: 15,+ frameOptions: [107, 124, 141],+ fpsOptions: [24],+ defaultFrames: 124,+};const MODELS = [MLX, LTX2];const STATUS = { connected: true, defaultModel: MLX.id };@@ -243,6 +266,61 @@ describe('useVideoGenForm', () => {expect(result.current.buildGeneratePayload().audioFile).toBe(wav);});+ it('requires and submits both image and audio for MiniMax H3 Ref2VA', async () => {+ const { result } = render({ models: [MLX, H3_REF2VA] });+ await waitFor(() => expect(result.current.modelId).toBe(MLX.id));+ act(() => result.current.handleModeChange('a2v'));+ await waitFor(() => expect(result.current.modelId).toBe(H3_REF2VA.id));++ const wav = new File(['audio'], 'awakening.wav', { type: 'audio/wav' });+ act(() => result.current.setAudioFile(wav));+ expect(result.current.a2vModeBlocked).toBe(true);++ act(() => result.current.pickSourceImage('awakening-reference.png'));+ expect(result.current.a2vModeBlocked).toBe(false);+ expect(result.current.buildGeneratePayload()).toMatchObject({+ mode: 'a2v',+ modelId: H3_REF2VA.id,+ audioFile: wav,+ sourceImageFile: 'awakening-reference.png',+ });+ });++ it('derives an LTX-2.5 frame canvas from the full uploaded audio duration', async () => {+ const { result } = render({ models: [MLX, LTX25] });+ await waitFor(() => expect(result.current.modelId).toBe(MLX.id));+ act(() => result.current.handleModeChange('a2v'));+ await waitFor(() => expect(result.current.modelId).toBe(LTX25.id));++ const wav = new File(['audio'], 'forty-one-seconds.wav', { type: 'audio/wav' });+ act(() => {+ result.current.setAudioFile(wav);+ result.current.setAudioDurationSec(41.041281);+ });+ await waitFor(() => expect(result.current.numFrames).toBe(985));+ expect(result.current.a2vModeBlocked).toBe(false);+ expect(result.current.buildGeneratePayload()).toMatchObject({+ mode: 'a2v',+ modelId: LTX25.id,+ audioFile: wav,+ sourceImageFile: '',+ numFrames: 985,+ });+ });++ it('blocks an LTX-2.5 A2V file that exceeds its single-pass frame boundary', async () => {+ const { result } = render({ models: [MLX, LTX25] });+ await waitFor(() => expect(result.current.modelId).toBe(MLX.id));+ act(() => result.current.handleModeChange('a2v'));+ await waitFor(() => expect(result.current.modelId).toBe(LTX25.id));+ act(() => {+ result.current.setAudioFile(new File(['audio'], 'one-minute.wav', { type: 'audio/wav' }));+ result.current.setAudioDurationSec(60);+ });+ expect(result.current.a2vModeBlocked).toBe(true);+ expect(result.current.a2vDurationError).toMatch(/supports up to 42\.4s/i);+ });+it('clears sampler overrides on an automatic mode-compatible model fallback', async () => {const { result } = render({models: [WAN_T2V, WAN_TI2V],diff --git a/client/src/hooks/useVideoGenValidation.js b/client/src/hooks/useVideoGenValidation.jsindex 158aaaebad..f108245909 100644--- a/client/src/hooks/useVideoGenValidation.js+++ b/client/src/hooks/useVideoGenValidation.js@@ -1,5 +1,5 @@import { useMemo } from 'react';-import { isLtx2FamilyRuntime } from '../lib/runnerFamilies.js';+import { isAudioToVideoRuntime, isLtx2FamilyRuntime } from '../lib/runnerFamilies.js';import {computeFflfSafeFrames,icResolutionIssue,@@ -34,11 +34,13 @@ export function validateVideoKeyframes({/** Derives every submit-blocking predicate from the current VideoGen fields. */export function useVideoGenValidation({+ audioDurationSec,audioFile,chunks,currentModel,extendFromVideoId,extendingFrame,+ fps,height,icImageKind,icModeActive,@@ -52,6 +54,7 @@ export function useVideoGenValidation({numFrames,pixelBudget,sourceImageFile,+ sourceImageUpload,width,}) {const maxSafeFrames = useMemo(@@ -71,7 +74,28 @@ export function useVideoGenValidation({const extendModeBlocked = mode === 'extend' && (!extendFromVideoId || (!ltx2Runtime && (extendingFrame || !sourceImageFile)));- const a2vModeBlocked = mode === 'a2v' && (!audioFile || !ltx2Runtime);+ const a2vRuntime = isAudioToVideoRuntime(currentModel?.runtime);+ const a2vNeedsImage = currentModel?.requiresSourceImageForA2v === true;+ const maxAudioDurationSec = currentModel?.audioDurationDriven === true+ && currentModel?.arbitraryLengthAudio !== true+ && Number.isFinite(Number(currentModel?.maxNumFrames))+ && Number(currentModel.maxNumFrames) > 0+ && Number.isFinite(Number(fps))+ && Number(fps) > 0+ ? Number(currentModel.maxNumFrames) / Number(fps)+ : null;+ const a2vDurationError = mode === 'a2v'+ && maxAudioDurationSec != null+ && Number.isFinite(Number(audioDurationSec))+ && Number(audioDurationSec) > maxAudioDurationSec+ ? `${currentModel.name} supports up to ${maxAudioDurationSec.toFixed(1)}s in one audio-to-video render. Use MiniMax H3 Ref2VA for longer audio, or trim this file.`+ : null;+ const a2vModeBlocked = mode === 'a2v' && (+ !audioFile+ || !a2vRuntime+ || (a2vNeedsImage && !sourceImageFile && !sourceImageUpload)+ || !!a2vDurationError+ );const filledImageRefs = icReferenceImageFiles.filter(Boolean).length;const icLoraModeBlocked = icModeActive && ((icImageKind@@ -84,6 +108,7 @@ export function useVideoGenValidation({&& isModelAllowedForMode(currentModel, 'image') && chunks > 1;return {+ a2vDurationError,a2vModeBlocked,chainingActive,extendModeBlocked,diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 3bced30e92..943793ab63 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -55,7 +55,7 @@ grep -i "what you want to do" client/src/lib/README.md| `reviewerPins.js` | Client mirrors of the per-reviewer pin vocabularies — `MODEL_SELECTABLE_REVIEWERS` / `EFFORT_SELECTABLE_REVIEWERS` / `REVIEWER_EFFORT_LEVELS` / `reviewerEffortLevels` / `normalizeReviewerSlug` / `sanitizeReviewerModelInput` and their bounds. Dependency-free on purpose: the server suite imports it to pin the mirror against the server's own ladders, so it must not reach for a client-only package. Re-exported by `components/cos/constants.js`. || `loraEffect.js` | Mirror of the LoRA adapter-effect report vocabulary in `server/lib/loraEffect.js` (#4872): `LORA_EFFECT_STATUSES` (`ok`/`zero`/`nonfinite`/`unreadable`/`unmeasurable`), `LORA_EFFECT_BADGES` + `loraEffectBadge(status)` (badge label and Tailwind tone — only `zero` is styled as an error, because only `zero` refuses a render server-side), and `formatLoraEffect(report)`, the same one-line summary the server logs, returning `null` when the badge already says everything. Pinned by `loraEffect.parity.test.js`. || `loraTriggers.js` | Mirror of the trigger-word predicates in `server/lib/loraTriggers.js` (#4665): `firstTriggerWord` (the canonical activation token of a Civitai `trainedWords` list) and `promptHasTriggerWord` (whole-token, case-insensitive presence — `aria_tok` does not match inside `aria_token`). Plus `appendTriggerWords(prompt, words, effectivePrompt?)` — the "+ trigger" button's append, which adds ALL of a LoRA's words (the server only ever weaves the first) and judges presence against the composed prompt the page will actually submit. Lets the LoRA picker warn that the server is about to append a token, with the button and the hint sharing one presence rule. |-| `runnerFamilies.js` | Mirror of `server/lib/runners.js`. |+| `runnerFamilies.js` | Mirror of `server/lib/runners.js`, including the shared LTX + MiniMax H3 Ref2VA audio-to-video runtime predicate. || `slashdoCatalog.js` | Mirror of `server/lib/slashdoCatalog.js` — the launchable slashdo workflows (`SLASHDO_WORKFLOWS`, `slashdoWorkflowsForApp(isSwiftApp)`, `SLASHDO_APP_TYPES`) driving the app-overview Agent Operations buttons. Adds only the per-button Tailwind classes; pinned by `server/lib/slashdoCatalog.test.js`. || `issueLength.js` | Mirror of `server/lib/issueLength.js`. || `musicDuration.js` | Lyric-aware MiniMax Music 3 duration analysis: section/word detection, ending-cushioned auto-duration recommendations, and cap warnings. Mirrors `server/lib/musicDuration.js`. |@@ -77,7 +77,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`. `isDeliveryVideoModel(model, models)` is the other end of the same graph — true when some entry names `model` as its `finishModelId`, which is what makes a delivery render always decode on the full decoder (#5423). Mirrors `finishTargetForModel` / `isDeliveryVideoModel` 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), `selectVideoMemoryProfile(model, systemMemoryGb)` + `VIDEO_MEMORY_RESERVE_GB` (#5420 — which declared weight-placement profile this machine can actually hold, out of the `memoryProfiles` the server decorates onto the entry; the floors ride on the model so only the reserve is mirrored, and an unmeasured `systemMemoryGb` returns a `null` usable figure rather than reading as a box that is too small), `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`. |+| `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), `selectVideoMemoryProfile(model, systemMemoryGb)` + `VIDEO_MEMORY_RESERVE_GB` (#5420 — which declared weight-placement profile this machine can actually hold, out of the `memoryProfiles` the server decorates onto the entry; the floors ride on the model so only the reserve is mirrored, and an unmeasured `systemMemoryGb` returns a `null` usable figure rather than reading as a box that is too small), `computeFflfSafeFrames()` (FFLF/ltx2 pixel-budget back-solve, mirrors `server/services/videoGen/local.js`), and `isModelAllowedForMode()` (a2v uses the shared audio-runtime capability; IC remix remains LTX-only). 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. || `videoGenSubmission.js` | Builds the local, Grok, and federated video-generation request bodies from validated form state, including prompt envelopes and empty-value wire sentinels. || `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. |diff --git a/client/src/lib/runnerFamilies.js b/client/src/lib/runnerFamilies.jsindex 0e053bbab5..56becd2936 100644--- a/client/src/lib/runnerFamilies.js+++ b/client/src/lib/runnerFamilies.js@@ -34,7 +34,12 @@ export const isVideoLoraFamily = (family) => VIDEO_LORA_FAMILY_SET.has(family);// Gates asserting one of those facts ask this predicate instead of naming a// single runtime, which is what would silently exempt the other one.// Mirror of server/lib/runners.js.-export const MINIMAX_H3_RUNTIMES = Object.freeze(['minimax_h3', 'minimax_h3_cuda']);+export const MINIMAX_H3_REF2VA_RUNTIME = 'minimax_h3_ref2va';+export const MINIMAX_H3_RUNTIMES = Object.freeze([+ 'minimax_h3',+ 'minimax_h3_cuda',+ MINIMAX_H3_REF2VA_RUNTIME,+]);const MINIMAX_H3_RUNTIME_SET = new Set(MINIMAX_H3_RUNTIMES);export const isMiniMaxH3Runtime = (runtime) => MINIMAX_H3_RUNTIME_SET.has(runtime);// dgrauet's LTX-2.3 pin (`ltx2`) and the LTX-2.5 fork (`ltx25`) share the@@ -45,6 +50,12 @@ export const isMiniMaxH3Runtime = (runtime) => MINIMAX_H3_RUNTIME_SET.has(runtimexport const LTX2_FAMILY_RUNTIMES = Object.freeze(['ltx2', 'ltx25']);const LTX2_FAMILY_RUNTIME_SET = new Set(LTX2_FAMILY_RUNTIMES);export const isLtx2FamilyRuntime = (runtime) => LTX2_FAMILY_RUNTIME_SET.has(runtime);+export const AUDIO_TO_VIDEO_RUNTIMES = Object.freeze([+ ...LTX2_FAMILY_RUNTIMES,+ MINIMAX_H3_REF2VA_RUNTIME,+]);+const AUDIO_TO_VIDEO_RUNTIME_SET = new Set(AUDIO_TO_VIDEO_RUNTIMES);+export const isAudioToVideoRuntime = (runtime) => AUDIO_TO_VIDEO_RUNTIME_SET.has(runtime);// The family an INSTALLED LoRA belongs to. `loraCompatKey` is the refined key// (e.g. flux2-9b) written by the importer; `runnerFamily` is the coarse legacydiff --git a/client/src/lib/videoGenParams.js b/client/src/lib/videoGenParams.jsindex f4fee685b5..4acd834ae6 100644--- a/client/src/lib/videoGenParams.js+++ b/client/src/lib/videoGenParams.js@@ -4,16 +4,21 @@// predicate. Kept in lib/ (not hooks/) because none touch React state; the// page and any future consumer import them directly.-import { isLtx2FamilyRuntime } from './runnerFamilies';+import { isAudioToVideoRuntime, isLtx2FamilyRuntime } from './runnerFamilies';import { isDeliveryVideoModel } from './videoFinish.js';// Values follow LTX-2's 8k+1 latent boundary so the model doesn't silently// snap. 241 = 10s @ 24fps is the comfortable single-pass ceiling on 48 GB-// at standard widths; the higher options (265–481) push past that and may-// swap or OOM at 1280×704. For reliable clips longer than ~10s, use Extend-// mode (renders past a source video, conditioning on its full latent) —-// see the hint under the Frames dropdown.-export const FRAME_OPTIONS = [25, 49, 73, 97, 121, 145, 169, 193, 217, 241, 265, 313, 361, 481];+// at standard widths; the higher options push past that and may swap or OOM at+// 1280×704. 481 used to be the final picker entry even though neither the LTX+// runtime nor PortOS' 1024-frame request boundary stopped there. Keep useful+// 25/30/35/40-second choices plus the highest legal 8k+1 value under that API+// boundary so a proven long render is reproducible from the UI. For reliable+// clips longer than ~10s, Extend is still the lower-memory path.+export const FRAME_OPTIONS = [+ 25, 49, 73, 97, 121, 145, 169, 193, 217, 241, 265, 313, 361, 481,+ 601, 721, 841, 961, 1017,+];export const FPS_OPTIONS = [16, 24, 30];// Chain ceiling — mirrors the route's own 1..8 cap on `chunks` (and on the// per-chunk prompt list), which bounds worst-case wall time at 8 × ~5min.@@ -72,6 +77,22 @@ export const normalizeFramesForModel = (value, model) => isValidFrameCountForMod: nearestOption(value, frameOptionsForModel(model));export const normalizeFpsForModel = (value, model) => nearestOption(value, fpsOptionsForModel(model));+// Duration-driven LTX A2V needs enough pixel frames to cover the whole source+// audio, rounded UP to its causal-VAE grid. This is mirrored by+// server/services/videoGen/audioDuration.js; the server probes the staged file+// and remains authoritative, while this copy keeps the form's displayed frame+// count honest before submit.+export const audioDurationToFrames = (durationSeconds, fps, frameStride) => {+ const duration = Number(durationSeconds);+ const rate = Number(fps);+ const stride = Number(frameStride);+ if (!Number.isFinite(duration) || duration <= 0+ || !Number.isFinite(rate) || rate <= 0+ || !Number.isInteger(stride) || stride <= 0) return null;+ const targetFrames = duration * rate;+ return Math.max(1, Math.ceil((targetFrames - 1) / stride) * stride + 1);+};+// Muting and prompt-audio steering are separate capabilities. Hidden mute state// from a prior model must never alter a model (such as MiniMax H3) whose joint// audio track cannot be disabled.@@ -408,15 +429,14 @@ export const icResolutionIssue = (spec, width, height) => {};// The one mode-compatibility predicate — used by the Model dropdown and by-// every "can this model do i2v?" gate on the page. a2v and the IC-LoRA remix-// modes stay runtime-gated because they're ltx2 pipeline capabilities rather-// than per-entry facts (the remix ids come from the IC-LoRA weight registry);-// the server enforces the same rules in routes/videoGen.js (A2V_REQUIRES_LTX2 /-// IC_LORA_REQUIRES_LTX2). Every other mode is answered by `supportedModes`,+// every "can this model do i2v?" gate on the page. a2v is limited to declared+// audio-conditioning runtimes; IC-LoRA remains an LTX pipeline capability.+// Every other mode is answered by `supportedModes`,// which the server resolves for EVERY entry (server/lib/videoModeProfiles.js,// #3737), so an absent list means the payload didn't come from the registry.export const isModelAllowedForMode = (model, mode) => {if (!model) return false;- if (mode === 'a2v' || isIcLoraMode(mode)) return isLtx2FamilyRuntime(model.runtime);+ if (mode === 'a2v') return isAudioToVideoRuntime(model.runtime);+ if (isIcLoraMode(mode)) return isLtx2FamilyRuntime(model.runtime);return Array.isArray(model.supportedModes) && model.supportedModes.includes(mode);};diff --git a/client/src/lib/videoGenParams.test.js b/client/src/lib/videoGenParams.test.jsindex 563bdbd463..6bd870d0df 100644--- a/client/src/lib/videoGenParams.test.js+++ b/client/src/lib/videoGenParams.test.js@@ -3,7 +3,7 @@ import {videoModelMemoryGb, computeFflfSafeFrames, isModelAllowedForMode,VIDEO_EDGE_BOUNDS, videoEdgeBoundsForModel, FRAME_OPTIONS, FPS_OPTIONS,WAN_FRAME_OPTIONS, frameOptionsForModel, fpsOptionsForModel,- normalizeFramesForModel, normalizeFpsForModel,+ normalizeFramesForModel, normalizeFpsForModel, audioDurationToFrames,supportsVideoAudioControls, supportsVideoAudioPromptControls,IC_LORA_MODES, IC_LORA_MODE_VALUES, isIcLoraMode, icLoraSpecForMode,icResolutionIssue,@@ -87,8 +87,10 @@ describe('isModelAllowedForMode', () => {expect(isModelAllowedForMode(h3, 'image')).toBe(false);expect(isModelAllowedForMode(h3, 'fflf')).toBe(false);});- it('requires the ltx2 runtime for a2v', () => {+ it('requires a declared audio-to-video runtime for a2v', () => {expect(isModelAllowedForMode({ runtime: 'ltx2' }, 'a2v')).toBe(true);+ expect(isModelAllowedForMode({ runtime: 'ltx25' }, 'a2v')).toBe(true);+ expect(isModelAllowedForMode({ runtime: 'minimax_h3_ref2va' }, 'a2v')).toBe(true);expect(isModelAllowedForMode({ runtime: 'mlx_video' }, 'a2v')).toBe(false);});});@@ -101,10 +103,18 @@ describe('constants', () => {});it('frame/fps option lists are on the expected boundaries', () => {expect(FRAME_OPTIONS[0]).toBe(25);+ expect(FRAME_OPTIONS.at(-1)).toBe(1017);expect(FRAME_OPTIONS.every((f) => (f - 1) % 8 === 0)).toBe(true);expect(FPS_OPTIONS).toEqual([16, 24, 30]);expect(WAN_FRAME_OPTIONS.every((f) => (f - 1) % 4 === 0)).toBe(true);});+ it('derives the full audio canvas by rounding up to the temporal grid', () => {+ expect(audioDurationToFrames(41.041281, 24, 8)).toBe(985);+ expect(audioDurationToFrames(20, 24, 8)).toBe(481);+ expect(audioDurationToFrames(20.01, 24, 8)).toBe(481);+ expect(audioDurationToFrames(20.05, 24, 8)).toBe(489);+ expect(audioDurationToFrames(null, 24, 8)).toBeNull();+ });it('selects and normalizes model-aware Wan frame/fps values', () => {const wan = { frameStride: 4, fpsOptions: [16, 20, 24] };expect(frameOptionsForModel(wan)).toBe(WAN_FRAME_OPTIONS);diff --git a/client/src/lib/videoGenSubmission.js b/client/src/lib/videoGenSubmission.jsindex 0bfb05ec84..20f6125001 100644--- a/client/src/lib/videoGenSubmission.js+++ b/client/src/lib/videoGenSubmission.js@@ -118,10 +118,10 @@ export function buildVideoGenSubmission({keyframes: keyframesActive ? JSON.stringify(keyframes) : '',loraFilenames: (loraFamily && selectedLoras.length) ? selectedLoras.map((lora) => lora.filename) : undefined,loraScales: (loraFamily && selectedLoras.length) ? selectedLoras.map((lora) => lora.scale) : undefined,- sourceImageFile: (mode === 'image' || legacyFflf+ sourceImageFile: (mode === 'image' || mode === 'a2v' || legacyFflf|| (mode === 'extend' && !isLtx2FamilyRuntime(currentModel?.runtime)))? (sourceImageFile || '') : '',- sourceImage: (mode === 'image' || legacyFflf) ? (sourceImageUpload || '') : '',+ sourceImage: (mode === 'image' || mode === 'a2v' || legacyFflf) ? (sourceImageUpload || '') : '',lastImageFile: legacyFflf ? (lastImageFile || '') : '',lastImage: legacyFflf ? (lastImageUpload || '') : '',extendFromVideoId: (mode === 'extend' && isLtx2FamilyRuntime(currentModel?.runtime))diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex 92d222e399..151f9e7b9c 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -15,7 +15,7 @@* - extend: pick a previous render → its last frame becomes the source* image for a new image-to-video generation* - a2v: audio-to-video (uploaded WAV/MP3 drives the video's motion +- * audio track) — dgrauet/ltx2 runtime only+ * audio track) — LTX, or MiniMax H3 Ref2VA with an image* - ic-*: IC-LoRA remix modes (issue #3100) — a reference clip drives the* render through ICLoraPipeline with a per-mode IC-LoRA fused into* Stage 1. Today: `ic-control` (structure/motion from a depth/pose/@@ -37,7 +37,7 @@import { useState, useEffect, useRef, useCallback, useMemo } from 'react';import { useSearchParams } from 'react-router';-import { isMiniMaxH3Runtime, isLtx2FamilyRuntime } from '../lib/runnerFamilies';+import { isAudioToVideoRuntime, isMiniMaxH3Runtime } from '../lib/runnerFamilies';import { appendTriggerWords } from '../lib/loraTriggers';import Drawer from '../components/Drawer';import { ImageGenTab } from '../components/settings/ImageGenTab';@@ -175,7 +175,8 @@ export default function VideoGen() {keyframesMode, keyframes, keyframesSupported, keyframesActive, keyframesError, keyframesBlocked,toggleKeyframesMode, addKeyframe, updateKeyframe, removeKeyframe,extendFromVideoId, extendingFrame, handleExtendPick, extendModeBlocked,- audioFile, setAudioFile, a2vModeBlocked,+ setAudioDurationSec,+ audioFile, setAudioFile, a2vDurationError, a2vModeBlocked,icSpec, icModeActive, icLoraModeBlocked,icReferenceFile, icReferenceVideoId, icReferenceNames, icReferenceImageFiles,pickIcReferenceFile, pickIcReferenceVideoId,@@ -1125,14 +1126,42 @@ export default function VideoGen() {)}{mode === 'a2v' && (- <AudioPanel- audioFile={audioFile}- numFrames={numFrames}- fps={fps}- hasCompatibleModel={visibleModels.length > 0}- onPick={setAudioFile}- onClear={() => setAudioFile(null)}- />+ <div className="grid gap-3 lg:grid-cols-2">+ <FramePanel+ label={currentModel?.requiresSourceImageForA2v ? 'Reference image (required)' : 'Reference image (optional)'}+ file={sourceImageFile}+ upload={sourceImageUpload}+ uploadUrl={sourceUploadUrl}+ onBrowseGallery={() => setGalleryPicker({ kind: 'source' })}+ onUpload={uploadSourceImage}+ onClear={clearSourceImage}+ alt="Audio-to-video reference"+ hint={{+ text: 'This image establishes the subject, composition, and opening geometry.',+ title: currentModel?.arbitraryLengthAudio === true+ ? 'MiniMax H3 Ref2VA combines the image with each audio window. PortOS carries the prior window\'s last frame forward to keep long renders continuous.'+ : 'LTX-2.5 conditions frame one on this image while the uploaded audio drives motion and synchronization.',+ }}+ />+ <AudioPanel+ audioFile={audioFile}+ numFrames={numFrames}+ fps={fps}+ hasCompatibleModel={visibleModels.length > 0}+ audioDurationDriven={currentModel?.audioDurationDriven === true}+ arbitraryLengthAudio={currentModel?.arbitraryLengthAudio === true}+ maxReferenceAudioSeconds={currentModel?.maxReferenceAudioSeconds}+ maxDurationSeconds={currentModel?.audioDurationDriven === true+ && currentModel?.arbitraryLengthAudio !== true+ && Number(currentModel?.maxNumFrames) > 0+ ? Number(currentModel.maxNumFrames) / Number(fps)+ : null}+ durationError={a2vDurationError}+ onDurationChange={setAudioDurationSec}+ onPick={setAudioFile}+ onClear={() => setAudioFile(null)}+ />+ </div>)}{mode === 'extend' && (@@ -1403,9 +1432,10 @@ export default function VideoGen() {: textEncoderOptionBlocked ? `Download the ${selectedTextEncoder?.label || 'selected'} text encoder before generating`: icWeightsBlocked ? `Download the ${icSpec?.label || 'IC-LoRA'} weight before generating`: extendModeBlocked ? 'Pick a prior render and wait for the last frame to extract before generating'- : a2vModeBlocked ? (!isLtx2FamilyRuntime(currentModel?.runtime)- ? 'a2v mode requires an ltx2-runtime model — pick one from the Model dropdown'- : 'Pick an audio file before generating')+ : a2vModeBlocked ? (a2vDurationError || (!isAudioToVideoRuntime(currentModel?.runtime)+ ? 'a2v mode requires an audio-to-video model — pick one from the Model dropdown'+ : !audioFile ? 'Pick an audio file before generating'+ : 'Pick a reference image before generating with this model')): keyframesBlocked ? keyframesError: undefined}diff --git a/data.reference/media-models.json b/data.reference/media-models.jsonindex 52390d7c77..6d078c4762 100644--- a/data.reference/media-models.json+++ b/data.reference/media-models.json@@ -16,7 +16,7 @@"url": "https://pypi.org/project/mlx-video-with-audio/"},"estimatedDownloadGb": 53.5,- "reviewedAt": "2026-08-09"+ "reviewedAt": "2026-08-30"}},{@@ -33,7 +33,7 @@"url": "https://pypi.org/project/mlx-video-with-audio/"},"estimatedDownloadGb": 22.8,- "reviewedAt": "2026-08-09"+ "reviewedAt": "2026-08-30"}},{@@ -54,7 +54,7 @@"url": "https://github.com/dgrauet/ltx-2-mlx/blob/main/LICENSE"},"estimatedDownloadGb": 59.7,- "reviewedAt": "2026-08-09"+ "reviewedAt": "2026-08-30"}},{@@ -75,7 +75,7 @@"url": "https://github.com/dgrauet/ltx-2-mlx/blob/main/LICENSE"},"estimatedDownloadGb": 87.5,- "reviewedAt": "2026-08-09"+ "reviewedAt": "2026-08-30"}},{@@ -84,6 +84,9 @@"repo": "MrMofer/ltx-2.5-mlx-q8","revision": "f1b56e7dc89f71a9af2cddac787b89ed22a8b7fc","runtime": "ltx25",+ "audioDurationDriven": true,+ "frameStride": 8,+ "maxNumFrames": 1017,"steps": 8,"guidance": 3,"disclosure": {@@ -97,7 +100,7 @@"url": "https://github.com/MrMoferFRAN/ltx-2-mlx/blob/57952288076766abe27dda3a774b2c24f7346977/LICENSE"},"estimatedDownloadGb": 67.7,- "reviewedAt": "2026-08-09"+ "reviewedAt": "2026-08-30"},"speedProfiles": [{@@ -246,7 +249,7 @@"url": "https://github.com/PipeNetwork/minimax-h3-mlx/blob/fcd9e9b79a1d6018d91ac477c0968de1fa067e49/LICENSE"},"estimatedDownloadGb": 103.3,- "reviewedAt": "2026-08-09"+ "reviewedAt": "2026-08-30"},"termsGate": {"id": "minimax-h3-community-license-2026-08-02",@@ -272,6 +275,111 @@}]},+ {+ "id": "minimax_h3_ref2va_8bit",+ "name": "MiniMax H3 Ref2VA MLX 8-bit (image + arbitrary-length audio, ~71 GB, 128 GB RAM)",+ "repo": "Sawfwair/MiniMax-H3-Ref2VA-MLX-8bit",+ "revision": "61dc387ef1a7166425cdacd63c2340598dcc364f",+ "runtime": "minimax_h3_ref2va",+ "supportedModes": [+ "a2v"+ ],+ "requiresSourceImageForA2v": true,+ "audioDurationDriven": true,+ "arbitraryLengthAudio": true,+ "maxReferenceAudioSeconds": 15,+ "defaultFrames": 124,+ "frameOptions": [+ 107,+ 124,+ 141,+ 158,+ 175,+ 192,+ 209,+ 226,+ 243,+ 260,+ 277,+ 294,+ 311,+ 328,+ 345,+ 362+ ],+ "fpsOptions": [+ 24+ ],+ "defaultWidth": 512,+ "defaultHeight": 320,+ "resolutionStep": 32,+ "resolutionOptions": [+ {+ "label": "512x320 (draft)",+ "w": 512,+ "h": 320+ },+ {+ "label": "768x480",+ "w": 768,+ "h": 480+ },+ {+ "label": "1024x640",+ "w": 1024,+ "h": 640+ },+ {+ "label": "768x768 (1:1)",+ "w": 768,+ "h": 768+ }+ ],+ "memoryGb": 128,+ "steps": 9,+ "guidance": 0,+ "samplerLocked": true,+ "samplerNote": "MiniMax H3 Ref2VA is CFG-distilled. PortOS renders audio in up-to-15-second continuity-linked windows, then restores the exact source audio over the final video.",+ "supportsNegativePrompt": false,+ "supportsTiling": false,+ "supportsDisableAudio": false,+ "disclosure": {+ "modelCardUrl": "https://huggingface.co/Sawfwair/MiniMax-H3-Ref2VA-MLX-8bit",+ "weightsLicense": {+ "name": "MiniMax H3 Community License",+ "url": "https://huggingface.co/MiniMaxAI/MiniMax-H3/blob/6818f6c32d12b210915e44ad56a4228c2608f160/LICENSE"+ },+ "runtimeLicense": {+ "name": "Apache-2.0",+ "url": "https://github.com/sawfwair/mere-run/blob/v0.47.0/LICENSE"+ },+ "estimatedDownloadGb": 70.9,+ "reviewedAt": "2026-08-30"+ },+ "termsGate": {+ "id": "minimax-h3-community-license-2026-08-02",+ "title": "MiniMax H3 eligibility and terms",+ "summary": "MiniMax grants use only in its Applicable Territory. The license excludes the European Union, United Kingdom, Republic of Korea, and United States of America.",+ "acknowledgement": "I confirm I am in the Applicable Territory and agree to the MiniMax H3 Community License and its Acceptable Use Policy.",+ "licenseUrl": "https://huggingface.co/MiniMaxAI/MiniMax-H3/blob/6818f6c32d12b210915e44ad56a4228c2608f160/LICENSE",+ "excludedTerritories": [+ "European Union",+ "United Kingdom",+ "Republic of Korea",+ "United States of America"+ ]+ },+ "memoryProfiles": [+ {+ "id": "unified-8bit",+ "name": "Unified 8-bit Ref2VA",+ "description": "8-bit Ref2VA weights and conditioning components resident in Apple unified memory.",+ "minMemoryGb": 128,+ "minVramGb": null,+ "unified": true+ }+ ]+ },{"id": "wan22_ti2v_5b","name": "Wan 2.2 TI2V 5B Q8 (~17 GiB download, text + image)",@@ -304,7 +412,7 @@"url": "https://github.com/lpalbou/mlx-gen/blob/main/LICENSE"},"estimatedDownloadGb": 18.2,- "reviewedAt": "2026-08-09"+ "reviewedAt": "2026-08-30"}},{@@ -339,7 +447,7 @@"url": "https://github.com/lpalbou/mlx-gen/blob/main/LICENSE"},"estimatedDownloadGb": 42.4,- "reviewedAt": "2026-08-09"+ "reviewedAt": "2026-08-30"}},{@@ -374,7 +482,7 @@"url": "https://github.com/lpalbou/mlx-gen/blob/main/LICENSE"},"estimatedDownloadGb": 42.4,- "reviewedAt": "2026-08-09"+ "reviewedAt": "2026-08-30"}},{@@ -424,7 +532,7 @@"url": "https://github.com/lpalbou/mlx-gen/blob/main/LICENSE"},"estimatedDownloadGb": 44.9,- "reviewedAt": "2026-08-09"+ "reviewedAt": "2026-08-30"},"finishModelId": "wan22_t2v_a14b"},@@ -475,7 +583,7 @@"url": "https://github.com/lpalbou/mlx-gen/blob/main/LICENSE"},"estimatedDownloadGb": 44.9,- "reviewedAt": "2026-08-09"+ "reviewedAt": "2026-08-30"}},{@@ -505,7 +613,7 @@"url": "https://github.com/hao-ai-lab/FastVideo/blob/main/LICENSE"},"estimatedDownloadGb": 3.5,- "reviewedAt": "2026-08-09"+ "reviewedAt": "2026-08-30"}},{@@ -535,7 +643,7 @@"url": "https://github.com/hao-ai-lab/FastVideo/blob/main/LICENSE"},"estimatedDownloadGb": 10.2,- "reviewedAt": "2026-08-09"+ "reviewedAt": "2026-08-30"}},{@@ -565,7 +673,7 @@"url": "https://github.com/hao-ai-lab/FastVideo/blob/main/LICENSE"},"estimatedDownloadGb": 25.4,- "reviewedAt": "2026-08-09"+ "reviewedAt": "2026-08-30"}}],@@ -581,7 +689,7 @@"name": "Apache-2.0","url": "https://github.com/huggingface/diffusers/blob/main/LICENSE"},- "reviewedAt": "2026-08-09"+ "reviewedAt": "2026-08-30"}},{@@ -732,7 +840,7 @@"url": "https://github.com/huggingface/diffusers/blob/main/LICENSE"},"estimatedDownloadGb": 144.1,- "reviewedAt": "2026-08-09"+ "reviewedAt": "2026-08-30"},"termsGate": {"id": "minimax-h3-community-license-2026-08-02",diff --git a/scripts/generate_minimax_h3_ref2va.js b/scripts/generate_minimax_h3_ref2va.jsnew file mode 100644index 0000000000..e9d2789a67--- /dev/null+++ b/scripts/generate_minimax_h3_ref2va.js@@ -0,0 +1,299 @@+#!/usr/bin/env node++import { spawn } from 'child_process';+import { mkdtemp, rm } from 'fs/promises';+import { join } from 'path';+import { tmpdir } from 'os';+import { planRef2vaAudioSegments } from '../server/services/videoGen/ref2vaPlan.js';+import { isDirectlyInvoked } from './lib/directInvocation.js';++export const MAX_REF2VA_XFADE_INPUTS = 8;++let activeChild = null;+let cancellationSignal = null;++const signalChildGroup = (child, signal) => {+ if (!child?.pid) return;+ try {+ if (process.platform !== 'win32') process.kill(-child.pid, signal);+ else child.kill(signal);+ } catch {+ try { child.kill(signal); } catch { /* child already exited */ }+ }+};++const requestCancellation = (signal) => {+ cancellationSignal ||= signal;+ signalChildGroup(activeChild, signal);+};++const installCancellationHandlers = () => {+ const onTerm = () => requestCancellation('SIGTERM');+ const onInterrupt = () => requestCancellation('SIGINT');+ process.on('SIGTERM', onTerm);+ process.on('SIGINT', onInterrupt);+ return () => {+ process.off('SIGTERM', onTerm);+ process.off('SIGINT', onInterrupt);+ };+};++const spawnTracked = (bin, args) => {+ if (cancellationSignal) throw new Error(`Cancelled by ${cancellationSignal}`);+ // Each expensive child leads its own process group. The detached-job parent+ // may only be able to signal this wrapper PID on macOS; the handlers above+ // forward that cancellation to the active child and every descendant it+ // spawned (mere.run and ffmpeg included).+ const child = spawn(bin, args, {+ stdio: ['ignore', 'pipe', 'pipe'],+ detached: process.platform !== 'win32',+ });+ activeChild = child;+ child.once('close', () => {+ if (activeChild === child) activeChild = null;+ });+ return child;+};++const parseArgs = (argv) => {+ const out = {};+ for (let i = 0; i < argv.length; i += 2) {+ const key = argv[i];+ const value = argv[i + 1];+ if (!key?.startsWith('--') || value == null) throw new Error(`Invalid argument near ${key || '(end)'}`);+ out[key.slice(2)] = value;+ }+ return out;+};++const run = (bin, args, { forwardOutput = false } = {}) => new Promise((resolve, reject) => {+ let child;+ try {+ child = spawnTracked(bin, args);+ } catch (err) {+ reject(err);+ return;+ }+ let stderr = '';+ child.stdout.on('data', (chunk) => {+ if (forwardOutput) process.stderr.write(chunk);+ });+ child.stderr.on('data', (chunk) => {+ stderr = `${stderr}${chunk}`.slice(-8192);+ if (forwardOutput) process.stderr.write(chunk);+ });+ child.on('error', reject);+ child.on('close', (code, signal) => {+ if (cancellationSignal) reject(new Error(`Cancelled by ${cancellationSignal}`));+ else if (code === 0) resolve();+ else reject(new Error(`${bin} ${signal ? `was killed by ${signal}` : `exited ${code}`}: ${stderr.trim()}`));+ });+});++const probeDuration = (ffprobe, path) => new Promise((resolve, reject) => {+ let stdout = '';+ let stderr = '';+ let child;+ try {+ child = spawnTracked(ffprobe, [+ '-v', 'error', '-show_entries', 'format=duration',+ '-of', 'default=noprint_wrappers=1:nokey=1', path,+ ]);+ } catch (err) {+ reject(err);+ return;+ }+ child.stdout.on('data', (chunk) => { stdout += chunk; });+ child.stderr.on('data', (chunk) => { stderr = `${stderr}${chunk}`.slice(-4096); });+ child.on('error', reject);+ child.on('close', (code) => {+ const duration = Number(stdout.trim());+ if (cancellationSignal) reject(new Error(`Cancelled by ${cancellationSignal}`));+ else if (code === 0 && Number.isFinite(duration) && duration > 0) resolve(duration);+ else reject(new Error(`ffprobe could not read source audio duration: ${stderr.trim()}`));+ });+});++const decimals = (value) => Number(value).toFixed(6).replace(/0+$/, '').replace(/\.$/, '');++/**+ * Compose timeline-positioned clips with a bounded fan-in. A single ffmpeg+ * graph over every Ref2VA window eventually exceeds macOS' descriptor limit;+ * grouping at most eight inputs per pass makes supported duration independent+ * of that process limit while re-encoding each frame only O(log n) times.+ */+export const composeRef2vaSegments = async ({+ ffmpeg,+ workDir,+ pieces,+ runCommand = run,+ maxInputs = MAX_REF2VA_XFADE_INPUTS,+}) => {+ if (!Array.isArray(pieces) || pieces.length === 0) {+ throw new TypeError('pieces must contain at least one video');+ }+ if (!Number.isInteger(maxInputs) || maxInputs < 2) {+ throw new TypeError('maxInputs must be an integer of at least 2');+ }++ let level = 0;+ let pending = pieces.map((piece) => ({ ...piece }));+ while (pending.length > 1) {+ const next = [];+ for (let offset = 0; offset < pending.length; offset += maxInputs) {+ const batch = pending.slice(offset, offset + maxInputs);+ if (batch.length === 1) {+ next.push(batch[0]);+ continue;+ }++ const outputPath = join(workDir, `joined-${level}-${offset / maxInputs}.mp4`);+ const origin = batch[0].startSeconds;+ const filterSteps = batch.map((_, index) => (+ `[${index}:v]settb=AVTB,setpts=PTS-STARTPTS[piece${index}]`+ ));+ let currentLabel = 'piece0';+ let currentEnd = batch[0].endSeconds;+ for (let index = 1; index < batch.length; index += 1) {+ const piece = batch[index];+ const overlap = currentEnd - piece.startSeconds;+ if (!(overlap > 0)) throw new Error('Ref2VA video pieces must overlap for continuity');+ const nextLabel = `joined${index}`;+ filterSteps.push(+ `[${currentLabel}][piece${index}]xfade=transition=fade:duration=${decimals(overlap)}:offset=${decimals(piece.startSeconds - origin)}[${nextLabel}]`,+ );+ currentLabel = nextLabel;+ currentEnd = Math.max(currentEnd, piece.endSeconds);+ }+ await runCommand(ffmpeg, [+ '-v', 'error', ...batch.flatMap((piece) => ['-i', piece.path]),+ '-filter_complex', filterSteps.join(';'), '-map', `[${currentLabel}]`,+ '-an', '-c:v', 'libx264', '-preset', 'medium', '-crf', '18',+ '-pix_fmt', 'yuv420p', '-movflags', '+faststart', '-y', outputPath,+ ]);+ await Promise.all(batch.map((piece) => rm(piece.path, { force: true })));+ next.push({ path: outputPath, startSeconds: origin, endSeconds: currentEnd });+ }+ pending = next;+ level += 1;+ }+ return pending[0].path;+};++const main = async () => {+ const args = parseArgs(process.argv.slice(2));+ const required = ['runtime-bin', 'model-root', 'prompt', 'image', 'audio', 'width', 'height', 'fps', 'seed', 'steps', 'ffmpeg', 'ffprobe', 'output'];+ for (const key of required) {+ if (!args[key]) throw new Error(`Missing --${key}`);+ }++ const sourceDuration = await probeDuration(args.ffprobe, args.audio);+ const audioStart = Number(args['audio-start'] || 0);+ const segments = planRef2vaAudioSegments(sourceDuration, { startSeconds: audioStart });+ const workDir = await mkdtemp(join(tmpdir(), 'portos-h3-ref2va-'));+ let currentImage = args.image;+ const segmentPieces = [];++ process.stderr.write(`RUNTIME:${JSON.stringify({ runtime: 'minimax_h3_ref2va', versions: { 'mere.run': '0.47.0' } })}\n`);+ process.stderr.write(`STATUS:Planning ${segments.length} continuity-linked audio window${segments.length === 1 ? '' : 's'} for ${decimals(sourceDuration - audioStart)} seconds\n`);++ try {+ for (const segment of segments) {+ const displayIndex = segment.index + 1;+ const audioPath = join(workDir, `audio-${segment.index}.wav`);+ const rawVideoPath = join(workDir, `raw-${segment.index}.mp4`);+ const timelineVideoPath = join(workDir, `segment-${segment.index}.mp4`);+ const nextImagePath = join(workDir, `continuity-${segment.index}.png`);+ const outputDuration = decimals(segment.durationSeconds);+ const referenceDuration = decimals(segment.referenceDurationSeconds);+ const trimStart = decimals(segment.trimStartSeconds);+ // This marker describes work that is STARTING, so report completed+ // windows (0-based) rather than the display index. Reporting 3/3 at the+ // start of the final window left the UI parked at 100% throughout the+ // most expensive part of the render.+ process.stderr.write(`STAGE:ref2va-window:step:${segment.index}:${segments.length}:Rendering audio window ${displayIndex}/${segments.length}\n`);++ await run(args.ffmpeg, [+ '-v', 'error', '-ss', decimals(segment.referenceStartSeconds), '-i', args.audio,+ '-t', referenceDuration, '-vn', '-ac', '2', '-ar', '32000', '-c:a', 'pcm_s16le',+ '-y', audioPath,+ ]);++ await run(args['runtime-bin'], [+ 'video', 'generate', args.prompt,+ '--model-root', args['model-root'],+ '--reference', `image:${currentImage}`,+ '--reference', `audio:${audioPath}`,+ '--duration', referenceDuration,+ '--width', args.width,+ '--height', args.height,+ '--fps', args.fps,+ '--seed', String(Number(args.seed) + segment.index),+ '--steps', args.steps,+ '--h3-weight-mode', 'quantized',+ '--h3-acceleration', 'maximum',+ '--h3-window-frames', '124',+ '--h3-window-overlap', '35',+ '--output', rawVideoPath,+ ], { forwardOutput: true });++ // Preserve later windows' generated warm-up picture so xfade can blend+ // the overlapping source-audio interval instead of making a hard cut.+ // The first window has no preceding picture to blend against, so trim+ // any requested-offset warm-up there. tpad covers a runtime result that+ // lands one H3 cadence short.+ const timelineTrimStart = segment.index === 0 ? trimStart : '0';+ const timelineDuration = segment.index === 0 ? outputDuration : referenceDuration;+ await run(args.ffmpeg, [+ '-v', 'error', '-i', rawVideoPath, '-ss', timelineTrimStart,+ '-vf', 'tpad=stop_mode=clone:stop_duration=1', '-t', timelineDuration,+ '-an', '-c:v', 'libx264', '-preset', 'medium', '-crf', '18',+ '-pix_fmt', 'yuv420p', '-movflags', '+faststart', '-y', timelineVideoPath,+ ]);+ const timelineStart = segment.index === 0+ ? segment.startSeconds+ : segment.referenceStartSeconds;+ segmentPieces.push({+ path: timelineVideoPath,+ startSeconds: timelineStart,+ endSeconds: timelineStart + Number(timelineDuration),+ });++ if (displayIndex < segments.length) {+ await run(args.ffmpeg, [+ '-v', 'error', '-sseof', '-0.05', '-i', timelineVideoPath,+ '-frames:v', '1', '-y', nextImagePath,+ ]);+ currentImage = nextImagePath;+ }+ }++ process.stderr.write('STAGE:ref2va-mux\n');+ const concatenated = await composeRef2vaSegments({+ ffmpeg: args.ffmpeg,+ workDir,+ pieces: segmentPieces,+ });++ const finalDuration = decimals(sourceDuration - audioStart);+ await run(args.ffmpeg, [+ '-v', 'error', '-i', concatenated, '-ss', decimals(audioStart), '-i', args.audio,+ '-filter_complex', '[0:v]tpad=stop_mode=clone:stop_duration=1[v]',+ '-map', '[v]', '-map', '1:a:0', '-t', finalDuration,+ '-c:v', 'libx264', '-preset', 'medium', '-crf', '18', '-pix_fmt', 'yuv420p',+ '-c:a', 'aac', '-b:a', '192k', '-movflags', '+faststart', '-y', args.output,+ ]);+ process.stderr.write(`STATUS:MiniMax H3 Ref2VA saved ${args.output} with the full ${finalDuration}-second source audio\n`);+ process.stdout.write(`${JSON.stringify({ video_path: args.output, duration: Number(finalDuration), segments: segments.length })}\n`);+ } finally {+ await rm(workDir, { recursive: true, force: true });+ }+};++if (isDirectlyInvoked(import.meta.url)) {+ const removeCancellationHandlers = installCancellationHandlers();+ main().catch((err) => {+ process.stderr.write(`ERROR:${err.message}\n`);+ process.exitCode = 1;+ }).finally(removeCancellationHandlers);+}diff --git a/scripts/migrations/317-minimax-h3-ref2va.js b/scripts/migrations/317-minimax-h3-ref2va.jsnew file mode 100644index 0000000000..ce83db7eb0--- /dev/null+++ b/scripts/migrations/317-minimax-h3-ref2va.js@@ -0,0 +1,85 @@+/**+ * Add the MiniMax H3 Ref2VA MLX image+audio model to existing macOS video+ * registries. Fresh installs receive it from data.reference/media-models.json.+ */++import { readFile } from 'fs/promises';+import { join } from 'path';+import { atomicWrite } from '../../server/lib/fileUtils.js';+import { VIDEO_BUCKET_MLX, readVideoBucket } from '../../server/lib/mediaModelBuckets.js';++const REL_PATH = 'data/media-models.json';++export const MINIMAX_H3_REF2VA_ENTRY = Object.freeze({+ id: 'minimax_h3_ref2va_8bit',+ name: 'MiniMax H3 Ref2VA MLX 8-bit (image + arbitrary-length audio, ~71 GB, 128 GB RAM)',+ repo: 'Sawfwair/MiniMax-H3-Ref2VA-MLX-8bit',+ revision: '61dc387ef1a7166425cdacd63c2340598dcc364f',+ runtime: 'minimax_h3_ref2va',+ supportedModes: ['a2v'],+ requiresSourceImageForA2v: true,+ audioDurationDriven: true,+ arbitraryLengthAudio: true,+ maxReferenceAudioSeconds: 15,+ defaultFrames: 124,+ frameOptions: [107, 124, 141, 158, 175, 192, 209, 226, 243, 260, 277, 294, 311, 328, 345, 362],+ fpsOptions: [24],+ defaultWidth: 512,+ defaultHeight: 320,+ resolutionStep: 32,+ resolutionOptions: [+ { label: '512x320 (draft)', w: 512, h: 320 },+ { label: '768x480', w: 768, h: 480 },+ { label: '1024x640', w: 1024, h: 640 },+ { label: '768x768 (1:1)', w: 768, h: 768 },+ ],+ memoryGb: 128,+ steps: 9,+ guidance: 0,+ samplerLocked: true,+ samplerNote: 'MiniMax H3 Ref2VA is CFG-distilled. PortOS renders audio in up-to-15-second continuity-linked windows, then restores the exact source audio over the final video.',+ supportsNegativePrompt: false,+ supportsTiling: false,+ supportsDisableAudio: false,+});++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 });+ }+ const mlxEntries = readVideoBucket(config?.video, VIDEO_BUCKET_MLX);+ if (!Array.isArray(mlxEntries)) return;++ const shipped = readVideoBucket(config?._shippedDefaults?.video, VIDEO_BUCKET_MLX);+ const wasAlreadyShipped = Array.isArray(shipped)+ && shipped.includes(MINIMAX_H3_REF2VA_ENTRY.id);+ let present = mlxEntries.some((entry) => entry?.id === MINIMAX_H3_REF2VA_ENTRY.id);+ let changed = false;+ // A recorded-but-missing built-in is an intentional user deletion. This+ // matters when a lost/corrupt migrations ledger replays the migration:+ // never resurrect a model the install already received and removed.+ if (!present && !wasAlreadyShipped) {+ mlxEntries.push(structuredClone(MINIMAX_H3_REF2VA_ENTRY));+ present = true;+ changed = true;+ }+ if (Array.isArray(shipped) && present && !wasAlreadyShipped) {+ shipped.push(MINIMAX_H3_REF2VA_ENTRY.id);+ changed = true;+ }+ if (changed) {+ await atomicWrite(path, `${JSON.stringify(config, null, 2)}\n`);+ console.log(`📝 ${REL_PATH}: added MiniMax H3 Ref2VA MLX model`);+ }+ },+};diff --git a/scripts/migrations/317-minimax-h3-ref2va.test.js b/scripts/migrations/317-minimax-h3-ref2va.test.jsnew file mode 100644index 0000000000..06c0088692--- /dev/null+++ b/scripts/migrations/317-minimax-h3-ref2va.test.js@@ -0,0 +1,60 @@+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import migration, { MINIMAX_H3_REF2VA_ENTRY } from './317-minimax-h3-ref2va.js';++describe('317-minimax-h3-ref2va migration', () => {+ let rootDir;++ beforeEach(() => {+ rootDir = join(tmpdir(), `portos-test-317-${Date.now()}`);+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('adds the Ref2VA model and shipped-default marker', async () => {+ const initial = {+ video: { mlx: [{ id: 'ltx23_unified' }], cuda: [] },+ _shippedDefaults: { video: { mlx: ['ltx23_unified'] } },+ };+ writeFileSync(join(rootDir, 'data', 'media-models.json'), JSON.stringify(initial));++ await migration.up({ rootDir });++ const updated = JSON.parse(readFileSync(join(rootDir, 'data', 'media-models.json'), 'utf-8'));+ expect(updated.video.mlx).toContainEqual(MINIMAX_H3_REF2VA_ENTRY);+ expect(updated._shippedDefaults.video.mlx).toContain(MINIMAX_H3_REF2VA_ENTRY.id);+ });++ it('is idempotent and skips a missing registry', async () => {+ await migration.up({ rootDir });+ writeFileSync(join(rootDir, 'data', 'media-models.json'), JSON.stringify({ video: { mlx: [] } }));+ await migration.up({ rootDir });+ const firstPass = readFileSync(join(rootDir, 'data', 'media-models.json'), 'utf-8');+ await migration.up({ rootDir });+ expect(readFileSync(join(rootDir, 'data', 'media-models.json'), 'utf-8')).toBe(firstPass);+ });++ it('does not resurrect an intentionally deleted shipped model on ledger replay', async () => {+ const path = join(rootDir, 'data', 'media-models.json');+ const initial = {+ video: { mlx: [{ id: 'ltx23_unified' }], cuda: [] },+ _shippedDefaults: {+ video: { mlx: ['ltx23_unified', MINIMAX_H3_REF2VA_ENTRY.id] },+ },+ };+ writeFileSync(path, JSON.stringify(initial));+ const before = readFileSync(path, 'utf-8');++ await migration.up({ rootDir });++ expect(readFileSync(path, 'utf-8')).toBe(before);+ expect(JSON.parse(before).video.mlx).not.toContainEqual(+ expect.objectContaining({ id: MINIMAX_H3_REF2VA_ENTRY.id }),+ );+ });+});diff --git a/scripts/migrations/318-ltx25-a2v-duration.js b/scripts/migrations/318-ltx25-a2v-duration.jsnew file mode 100644index 0000000000..0405b1b330--- /dev/null+++ b/scripts/migrations/318-ltx25-a2v-duration.js@@ -0,0 +1,45 @@+/**+ * Persist the LTX-2.5 audio-duration contract for installs whose model registry+ * predates image+audio A2V exposure. The load-time twin in mediaModels.js makes+ * the fields available on this same boot; this migration keeps the user's file+ * explicit for later restarts and hand editing.+ */++import { readFile } from 'fs/promises';+import { join } from 'path';+import { atomicWrite } from '../../server/lib/fileUtils.js';+import { VIDEO_BUCKET_MLX, readVideoBucket } from '../../server/lib/mediaModelBuckets.js';+import { LTX25_AUDIO_PROFILE } from '../../server/lib/videoDurationProfiles.js';++const REL_PATH = 'data/media-models.json';+const PROFILE_KEYS = Object.freeze(['audioDurationDriven', 'frameStride', 'maxNumFrames']);++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 });+ }+ const entries = readVideoBucket(config?.video, VIDEO_BUCKET_MLX);+ if (!Array.isArray(entries)) return;+ const model = entries.find((entry) => (+ entry?.id === LTX25_AUDIO_PROFILE.id+ && entry.repo === LTX25_AUDIO_PROFILE.repo+ && entry.revision === LTX25_AUDIO_PROFILE.revision+ ));+ if (!model) return;+ const missing = PROFILE_KEYS.filter((key) => !Object.hasOwn(model, key));+ if (missing.length === 0) return;+ for (const key of missing) model[key] = LTX25_AUDIO_PROFILE[key];+ await atomicWrite(path, `${JSON.stringify(config, null, 2)}\n`);+ console.log(`📝 ${REL_PATH}: enabled duration-driven LTX-2.5 audio-to-video`);+ },+};diff --git a/scripts/migrations/318-ltx25-a2v-duration.test.js b/scripts/migrations/318-ltx25-a2v-duration.test.jsnew file mode 100644index 0000000000..71f3540f3d--- /dev/null+++ b/scripts/migrations/318-ltx25-a2v-duration.test.js@@ -0,0 +1,49 @@+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import migration from './318-ltx25-a2v-duration.js';++const PINNED = {+ id: 'ltx25_mlx_q8',+ repo: 'MrMofer/ltx-2.5-mlx-q8',+ revision: 'f1b56e7dc89f71a9af2cddac787b89ed22a8b7fc',+};++describe('318-ltx25-a2v-duration migration', () => {+ let rootDir;++ beforeEach(() => {+ rootDir = join(tmpdir(), `portos-test-318-${Date.now()}`);+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('adds only absent duration fields to the pinned shipped model', async () => {+ const initial = { video: { mlx: [{ ...PINNED, frameStride: 16 }], cuda: [] } };+ writeFileSync(join(rootDir, 'data', 'media-models.json'), JSON.stringify(initial));++ await migration.up({ rootDir });++ const updated = JSON.parse(readFileSync(join(rootDir, 'data', 'media-models.json'), 'utf-8'));+ expect(updated.video.mlx[0]).toMatchObject({+ ...PINNED,+ audioDurationDriven: true,+ frameStride: 16,+ maxNumFrames: 1017,+ });+ });++ it('preserves a repointed fork and is idempotent', async () => {+ const path = join(rootDir, 'data', 'media-models.json');+ writeFileSync(path, JSON.stringify({ video: { mlx: [{ ...PINNED, repo: 'example/ltx25-fork' }] } }));+ await migration.up({ rootDir });+ const first = readFileSync(path, 'utf-8');+ await migration.up({ rootDir });+ expect(readFileSync(path, 'utf-8')).toBe(first);+ expect(JSON.parse(first).video.mlx[0].audioDurationDriven).toBeUndefined();+ });+});diff --git a/scripts/setup-image-video.sh b/scripts/setup-image-video.shindex a233dcf361..0b468516bb 100755--- a/scripts/setup-image-video.sh+++ b/scripts/setup-image-video.sh@@ -13,6 +13,7 @@# INSTALL_LTX25 '1' to clone + uv-sync MrMofer's ltx-2.5 fork at ~/.portos/ltx-2.5-mlx (Apple Silicon). The 2.3 pin cannot load LTX-2.5 weights. Default: 0.# INSTALL_FASTVIDEO '1' to clone hao-ai-lab/FastVideo at ~/.portos/fastvideo and build an MLX venv for native Apple Silicon video generation (FastMetal models). Default: 0; opt in with INSTALL_FASTVIDEO=1.# INSTALL_MINIMAX_H3 '1' to install the pinned MiniMax H3 MLX runtime at ~/.portos/minimax-h3-mlx (Apple Silicon). Weights remain a separate explicit Video Gen download. Default: 0.+# INSTALL_MERERUN '1' to install the signed mere.run v0.47.0 runtime at ~/.portos/mere-run for MiniMax H3 Ref2VA image+audio generation (Apple Silicon). Weights remain a separate explicit Video Gen download. Default: 0.# INSTALL_MINIMAX_H3_CUDA '1' to install the MiniMax H3 CUDA runtime at ~/.portos/minimax-h3-cuda (Windows + NVIDIA), via diffusers' MiniMaxH3ModularPipeline. Weights remain a separate explicit Video Gen download (~144 GB). Default: 0.# INSTALL_FLUX2 '1' to also bootstrap a separate venv at ~/.portos/venv-flux2 for FLUX.2-klein (default: 1 on macOS, 0 elsewhere)# INSTALL_MUSICGEN '1' to bootstrap a venv at ~/.portos/venv-musicgen + clone ml-explore/mlx-examples to ~/.portos/mlx-examples for local MusicGen (MLX) background-music generation (pipeline audio stage). Default: 0; opt in with INSTALL_MUSICGEN=1 (macOS / Apple Silicon only).@@ -74,6 +75,16 @@ venv_python() {# shared with venv_python so the two probes can't drift apart.venv_exists() { [[ -x "$1/bin/python3" || -x "$1/Scripts/python.exe" ]]; }+# mere.run is a signed native binary and is the one setup path that does not+# need Python. Keep the bare-script default and every mixed install strict: only+# an explicit INSTALL_MERERUN=1 request with no other runtime selected may run+# on a machine without Python.+python_required() {+ local non_mere_requests+ non_mere_requests="${INSTALL_MFLUX:-0}${INSTALL_VIDEO:-0}${INSTALL_LTX2:-0}${INSTALL_LTX25:-0}${INSTALL_FASTVIDEO:-0}${INSTALL_WAN22:-0}${INSTALL_MINIMAX_H3:-0}${INSTALL_MINIMAX_H3_CUDA:-0}${INSTALL_MUSICGEN:-0}${INSTALL_AUDIOLDM2:-0}${INSTALL_ACESTEP:-0}${INSTALL_ACESTEP15:-0}${INSTALL_MINIMAX_MUSIC3:-0}${INSTALL_MINIMAX_MUSIC3_MLX:-0}${INSTALL_MUSCRIPTOR:-0}${INSTALL_FLUX2:-0}"+ [[ "${INSTALL_MERERUN:-0}" != "1" || "$non_mere_requests" == *[!0]* ]]+}+# Check out a pin (a commit SHA, tag, or branch name) in an already-fetched# clone. A bare `git checkout <branch>` lands on the *local* branch created at# clone time, which `git fetch origin` never advances — so re-running with a@@ -90,7 +101,7 @@ git_checkout_pin() {fi}-if ! have "$PYTHON_BIN"; then+if python_required && ! have "$PYTHON_BIN"; thenecho "❌ $PYTHON_BIN not found. Install Python 3.10+ first." >&2exit 1fi@@ -100,7 +111,7 @@ mkdir -p "${PORTOS_DATA}/videos"mkdir -p "${PORTOS_DATA}/video-thumbnails"# When the user only wants a specific BYOV runtime (set via INSTALL_LTX2 /-# INSTALL_WAN22 / INSTALL_MINIMAX_H3 / INSTALL_MINIMAX_H3_CUDA — or one of the self-contained MUSIC venvs+# INSTALL_WAN22 / INSTALL_MINIMAX_H3 / INSTALL_MERERUN / INSTALL_MINIMAX_H3_CUDA — or one of the self-contained MUSIC venvs# INSTALL_MUSICGEN / INSTALL_AUDIOLDM2 / INSTALL_ACESTEP / INSTALL_ACESTEP15 / INSTALL_MINIMAX_MUSIC3_MLX — typically from the# in-app installer), skip the mflux + legacy mlx_video preamble. Those# bring-your-own-venv runtimes are self-contained and don't depend on mflux;@@ -109,7 +120,7 @@ mkdir -p "${PORTOS_DATA}/video-thumbnails"# install ever starts — which on Linux/CPU/CUDA blocks the advertised# `INSTALL_ACESTEP=1 bash …` path. A bare `bash setup-image-video.sh` still# installs mflux as before.-ANY_BYOV="${INSTALL_LTX2:-0}${INSTALL_LTX25:-0}${INSTALL_FASTVIDEO:-0}${INSTALL_WAN22:-0}${INSTALL_MINIMAX_H3:-0}${INSTALL_MINIMAX_H3_CUDA:-0}${INSTALL_MUSICGEN:-0}${INSTALL_AUDIOLDM2:-0}${INSTALL_ACESTEP:-0}${INSTALL_ACESTEP15:-0}${INSTALL_MINIMAX_MUSIC3:-0}${INSTALL_MINIMAX_MUSIC3_MLX:-0}${INSTALL_MUSCRIPTOR:-0}"+ANY_BYOV="${INSTALL_LTX2:-0}${INSTALL_LTX25:-0}${INSTALL_FASTVIDEO:-0}${INSTALL_WAN22:-0}${INSTALL_MINIMAX_H3:-0}${INSTALL_MERERUN:-0}${INSTALL_MINIMAX_H3_CUDA:-0}${INSTALL_MUSICGEN:-0}${INSTALL_AUDIOLDM2:-0}${INSTALL_ACESTEP:-0}${INSTALL_ACESTEP15:-0}${INSTALL_MINIMAX_MUSIC3:-0}${INSTALL_MINIMAX_MUSIC3_MLX:-0}${INSTALL_MUSCRIPTOR:-0}"# "no BYOV runtime was requested" = the concatenation contains no non-zero# character. Matching a literal string of zeros instead made this a counting# exercise that the string and the variable list had to agree on — and they had@@ -528,6 +539,50 @@ if [[ "$INSTALL_MINIMAX_H3" == "1" ]]; thenecho " Weights remain uninstalled until you accept the model terms and choose Download in Video Gen."fi+INSTALL_MERERUN="${INSTALL_MERERUN:-0}"+if [[ "$INSTALL_MERERUN" == "1" ]]; then+ if ! is_macos || [[ "$(uname -m)" != "arm64" ]]; then+ echo "❌ MiniMax H3 Ref2VA through mere.run requires an Apple-Silicon Mac." >&2+ exit 1+ fi+ for command_name in curl hdiutil shasum; do+ if ! have "$command_name"; then+ echo "❌ INSTALL_MERERUN=1 requires ${command_name}." >&2+ exit 1+ fi+ done++ MERE_RUN_VERSION="0.47.0"+ MERE_RUN_DMG_SHA256="91833e45c5c4eda019eafbbc4a634ca7399c3bfb431822aaaa994fb404e603e2"+ MERE_RUN_URL="https://github.com/sawfwair/mere-run/releases/download/v${MERE_RUN_VERSION}/MereRun-${MERE_RUN_VERSION}.dmg"+ MERE_RUN_DIR="${HOME}/.portos/mere-run"+ MERE_RUN_BIN="${MERE_RUN_DIR}/mere.run"+ MERE_RUN_TMP="$(mktemp -d "${TMPDIR:-/tmp}/portos-mere-run.XXXXXX")"+ MERE_RUN_DMG="${MERE_RUN_TMP}/MereRun-${MERE_RUN_VERSION}.dmg"+ MERE_RUN_MOUNT="${MERE_RUN_TMP}/mount"+ mkdir -p "$MERE_RUN_MOUNT"+ mere_run_cleanup() {+ hdiutil detach "$MERE_RUN_MOUNT" -quiet >/dev/null 2>&1 || true+ rm -rf -- "$MERE_RUN_TMP"+ }+ trap mere_run_cleanup EXIT++ echo "📦 Downloading signed mere.run v${MERE_RUN_VERSION} release..."+ curl --fail --location --progress-bar "$MERE_RUN_URL" --output "$MERE_RUN_DMG"+ echo "${MERE_RUN_DMG_SHA256} ${MERE_RUN_DMG}" | shasum -a 256 --check+ hdiutil attach "$MERE_RUN_DMG" -nobrowse -readonly -mountpoint "$MERE_RUN_MOUNT" -quiet+ MERERUN_INSTALL_BIN_DEST="$MERE_RUN_BIN" bash "$MERE_RUN_MOUNT/.mere-run/install.sh"+ if [[ "$($MERE_RUN_BIN --version 2>/dev/null || true)" != "$MERE_RUN_VERSION" ]]; then+ echo "❌ mere.run installed, but its version does not match ${MERE_RUN_VERSION}." >&2+ exit 1+ fi+ hdiutil detach "$MERE_RUN_MOUNT" -quiet+ trap - EXIT+ rm -rf -- "$MERE_RUN_TMP"+ echo "✅ mere.run v${MERE_RUN_VERSION} ready: ${MERE_RUN_BIN}"+ echo " Weights remain uninstalled until you accept the model terms and choose Download in Video Gen."+fi+INSTALL_MINIMAX_H3_CUDA="${INSTALL_MINIMAX_H3_CUDA:-0}"if [[ "$INSTALL_MINIMAX_H3_CUDA" == "1" ]]; then# MiniMax H3 on NVIDIA, through diffusers' MiniMaxH3ModularPipeline. Unlike@@ -941,8 +996,9 @@ if [[ "$INSTALL_FLUX2" == "1" ]]; thenfifi-# ffmpeg — required for thumbnails, last-frame extraction, and stitch.-if ! have ffmpeg; then+# ffmpeg — required for thumbnails, last-frame extraction, stitch, and the+# Ref2VA continuity wrapper. Its distribution also provides ffprobe.+if ! have ffmpeg || ! have ffprobe; thenif is_macos && have brew; thenecho "📦 brew install ffmpeg"brew install ffmpeg@@ -951,10 +1007,26 @@ if ! have ffmpeg; thenfifi-PYTHON_PATH="$(command -v "$PYTHON_BIN")"+if [[ "$INSTALL_MERERUN" == "1" ]]; then+ MISSING_REF2VA_TOOLS=()+ for command_name in ffmpeg ffprobe; do+ if ! have "$command_name"; then MISSING_REF2VA_TOOLS+=("$command_name"); fi+ done+ if (( ${#MISSING_REF2VA_TOOLS[@]} > 0 )); then+ echo "❌ MiniMax H3 Ref2VA requires both ffmpeg and ffprobe; missing: ${MISSING_REF2VA_TOOLS[*]}." >&2+ echo " Install ffmpeg (for example, 'brew install ffmpeg') and retry from the Video Gen runtime panel." >&2+ exit 1+ fi+fi+echo ""echo "✅ Image/video stack ready."-echo " Python: $PYTHON_PATH"+if python_required; then+ PYTHON_PATH="$(command -v "$PYTHON_BIN")"+ echo " Python: $PYTHON_PATH"+else+ echo " Python: not required for this mere.run-only install"+fiecho " HF cache: ~/.cache/huggingface (HF default)"echo " LoRAs: ${PORTOS_DATA}/loras"echo " Videos: ${PORTOS_DATA}/videos"@@ -975,6 +1047,10 @@ if [[ "$INSTALL_MINIMAX_H3" == "1" ]]; thenecho " MiniMax H3: ${HOME}/.portos/minimax-h3-mlx/.venv/bin/python3 (MLX port @ ${MINIMAX_H3_PIN:0:12})"echo " Weights remain uninstalled until accepted and downloaded in Video Gen."fi+if [[ "$INSTALL_MERERUN" == "1" ]]; then+ echo " MiniMax H3 Ref2VA: ${HOME}/.portos/mere-run/mere.run (mere.run v${MERE_RUN_VERSION})"+ echo " Weights remain uninstalled until accepted and downloaded in Video Gen."+fiif [[ "$INSTALL_MUSICGEN" == "1" ]] && is_macos; thenecho " MusicGen: ${HOME}/.portos/venv-musicgen/bin/python3 (separate venv, MLX runtime @ ${HOME}/.portos/mlx-examples/musicgen)"fidiff --git a/scripts/setup-image-video.test.js b/scripts/setup-image-video.test.jsindex feacd649b6..0ade24a24a 100644--- a/scripts/setup-image-video.test.js+++ b/scripts/setup-image-video.test.js@@ -11,7 +11,16 @@ const SETUP_SCRIPT = join(REPO_ROOT, 'scripts', 'setup-image-video.sh');const source = readFileSync(SETUP_SCRIPT, 'utf8');const helper = source.match(/^venv_python\(\) \{\n(?:.*\n)*?^\}\n/m)?.[0];const existsHelper = source.match(/^venv_exists\(\) \{.*\}\n/m)?.[0];+const pythonRequiredHelper = source.match(/^python_required\(\) \{\n(?:.*\n)*?^\}\n/m)?.[0];const tempVenvs = [];+const installFlags = [+ 'INSTALL_MFLUX', 'INSTALL_VIDEO', 'INSTALL_LTX2', 'INSTALL_LTX25',+ 'INSTALL_FASTVIDEO', 'INSTALL_WAN22', 'INSTALL_MINIMAX_H3',+ 'INSTALL_MERERUN', 'INSTALL_MINIMAX_H3_CUDA', 'INSTALL_MUSICGEN',+ 'INSTALL_AUDIOLDM2', 'INSTALL_ACESTEP', 'INSTALL_ACESTEP15',+ 'INSTALL_MINIMAX_MUSIC3', 'INSTALL_MINIMAX_MUSIC3_MLX',+ 'INSTALL_MUSCRIPTOR', 'INSTALL_FLUX2',+];afterEach(() => {while (tempVenvs.length) rmSync(tempVenvs.pop(), { recursive: true, force: true });@@ -42,6 +51,16 @@ function venvExists(venv) {return result === 'yes';}+function pythonRequired(env = {}) {+ const installEnv = Object.fromEntries(installFlags.map((name) => [name, '0']));+ const result = execFileSync(+ 'bash',+ ['-c', `${pythonRequiredHelper}\npython_required && echo yes || echo no`],+ { encoding: 'utf8', env: { ...process.env, ...installEnv, ...env } },+ ).trim();+ return result === 'yes';+}+function shellIfBlocks(text) {const blocks = [];const stack = [];@@ -74,6 +93,22 @@ describe('setup-image-video venv layout handling (issue #4200)', () => {expect(existsHelper).toBeTruthy();});+ it('requires no Python only for an explicit mere.run-only install', () => {+ expect(pythonRequiredHelper).toBeTruthy();+ expect(pythonRequired({ INSTALL_MERERUN: '1' })).toBe(false);+ expect(pythonRequired({ INSTALL_MERERUN: '1', INSTALL_LTX25: '1' })).toBe(true);+ expect(pythonRequired({ INSTALL_MERERUN: '0' })).toBe(true);+ });++ it('requires both ffmpeg tools before reporting a mere.run install ready', () => {+ const strictGate = source.match(+ /if \[\[ "\$INSTALL_MERERUN" == "1" \]\]; then\n MISSING_REF2VA_TOOLS=\(\)\n(?:.*\n)*?^fi$/m,+ )?.[0];+ expect(strictGate).toContain('for command_name in ffmpeg ffprobe');+ expect(strictGate).toContain('exit 1');+ expect(source).toContain('not required for this mere.run-only install');+ });+// Windows CI runs Node directly; these bash-execution checks are POSIX-only,// while the portable structural guard below still covers every platform.it.skipIf(process.platform === 'win32')('passes Bash syntax validation', () => {diff --git a/server/lib/README.md b/server/lib/README.mdindex ed1b034d15..610bd4c002 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -148,13 +148,14 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `promptPartials.js` | Mustache-style partial expansion. || `mediaModelBuckets.js` | Names and resolves the video registry's two model buckets (#4142). The split is by RUNTIME FAMILY — `mlx` (Apple MLX runtimes) vs `cuda` (plain torch+CUDA, which runs on Windows *and* Linux) — not by operating system, which is why `activeVideoBucket()` keys on `process.platform === 'darwin'` instead of on "is this Windows". `readVideoBucket` / `readVideoDefault` / `matchesVideoBucket` resolve the canonical key first and fall back to the pre-#4142 `macos` / `windows` / `defaultMacos` / `defaultWindows` spellings, so any registry written by an older install still loads untouched; `canonicalizeVideoBuckets` performs the one-time rename (migration 270 and the load-time twin in `mediaModels.js`). Kept separate from `mediaModels.js` so `scripts/migrations/` can share the alias resolution without importing the registry loader, which seeds `data/` as a side effect. || `mediaModels.js` | Single source of truth for image/video model metadata. Entry fields are documented in the module docblock — note `repoFiles[]`, which narrows a model's own repo to an explicit file list for an aggregate repo that holds far more than the runner loads (MiniMax H3 CUDA). |-| `minimaxH3Memory.js` | The declared weight-placement table for the two MiniMax H3 entries (#5420) — H3 is the one video model whose components fit nowhere unassisted, so "does this box have enough" is a render gate, not a UI fact. `MINIMAX_H3_MEMORY_PROFILES` maps entry id → `{ shippedRepo, shippedRevision, profiles }`, each profile carrying an honest `minMemoryGb` host floor and (CUDA only) a `minVramGb` device floor, ordered best-first. Every capacity number is HOISTED from what already existed — the CUDA tiers are `resolve_offload_profile()`'s own thresholds in `scripts/generate_minimax_h3_cuda.py`, the host floors are the entries' `memoryGb` — the sole new number being `MINIMAX_H3_HOST_RESERVE_GB`, a policy reserve held back for the OS. `applyMiniMaxH3MemoryProfiles(list)` is the load-time backfill (twin of migration 317) and guards BOTH `repo` and `revision`, like the speed-profile decorator. `selectMiniMaxH3MemoryProfile({ model, totalMemoryGb })` picks the best profile the HOST can hold (VRAM is the runner's call — the server has no synchronous device view); `miniMaxH3MemoryDeclineReason()` RETURNS the fail-closed reason so the render path can 400 it and a status surface can show it, and returns `null` on an UNMEASURED host — "not measured" is a deferral to the runner, never the same as zero. `validateMiniMaxH3MemoryProfileTable` / `sanitizeMiniMaxH3MemoryProfiles` warn + strip a hand-edited table (NaN floor, duplicate/reserved id, mis-ordered tiers) at load. |+| `minimaxH3Memory.js` | The declared weight-placement table for the three MiniMax H3 entries (#5420) — H3 is the one video model family whose components fit nowhere unassisted, so "does this box have enough" is a render gate, not a UI fact. `MINIMAX_H3_MEMORY_PROFILES` maps entry id → `{ shippedRepo, shippedRevision, profiles }`, each profile carrying an honest `minMemoryGb` host floor and (CUDA only) a `minVramGb` device floor, ordered best-first. Every capacity number is HOISTED from what already existed — the CUDA tiers are `resolve_offload_profile()`'s own thresholds in `scripts/generate_minimax_h3_cuda.py`, the host floors are the entries' `memoryGb` — the sole new number being `MINIMAX_H3_HOST_RESERVE_GB`, a policy reserve held back for the OS. `applyMiniMaxH3MemoryProfiles(list)` is the load-time backfill (twin of migration 317) and guards BOTH `repo` and `revision`, like the speed-profile decorator. `selectMiniMaxH3MemoryProfile({ model, totalMemoryGb })` picks the best profile the HOST can hold (VRAM is the runner's call — the server has no synchronous device view); `miniMaxH3MemoryDeclineReason()` RETURNS the fail-closed reason so the render path can 400 it and a status surface can show it, and returns `null` on an UNMEASURED host — "not measured" is a deferral to the runner, never the same as zero. `validateMiniMaxH3MemoryProfileTable` / `sanitizeMiniMaxH3MemoryProfiles` warn + strip a hand-edited table (NaN floor, duplicate/reserved id, mis-ordered tiers) at load. || `videoContinuity.js` | How chunk N+1 of a chained video render is conditioned on chunk N. `resolveContextFrames(requested)` normalizes the tail-window size (absent → `DEFAULT_CONTEXT_FRAMES` = 22 ≈ 1s @ 24fps; an explicit `0` is preserved as "last frame only", NOT collapsed into the default) and clamps to `MIN_CONTEXT_FRAMES`..`MAX_CONTEXT_FRAMES`. `resolveContinuityStrategy({model, contextFrames})` picks `'window'` (LTX-2 `extend_from_video` conditioned on the prior chunk's last N frames — motion, not just a pose) or `'frame'` (extract the last frame, run i2v), degrading to `'frame'` on any runtime outside `CONTEXT_WINDOW_RUNTIMES` rather than rejecting. `extendLatentFrames` / `extendedPixelFrames` convert across the VAE's `LATENT_FRAME_STRIDE` (8 pixel frames per latent), `contextPrefixFrames({totalFrames, extendLatents})` measures how much of an extend render is echoed context to trim back off before stitching (0 = leave it alone), and `tailWindowStartFrame` gives the cut index for the window itself. Pure — importable from `prepareParams.js` without dragging in `local.js`. Mirrored for the picker in `client/src/lib/videoGenParams.js`, pinned by `videoContinuity.parity.test.js`. || `videoDisclosure.js` | Video Gen provenance/licensing + backend policy-scope facts (#3674). `VIDEO_MODEL_DISCLOSURES` maps each shipped video model id to `{ shippedRepo, disclosure }` (model card URL, weights license, runtime license, pinned-snapshot download size in decimal GB, review date) — every value checked against a primary upstream source, and any fact that could not be established is OMITTED so the UI renders "Unknown" instead of guessing. `applyVideoDisclosures(list)` is the load-time backfill (twin of migration 237) with the same preservation guards: an existing `disclosure` key wins, a custom id is skipped, and a `repo` pointed at a fork keeps Unknown. `VIDEO_BACKEND_DISCLOSURES` / `videoBackendDisclosure(id)` state where inference runs (`execution: local or hosted`) and whose policy applies — execution facts only, never a restrictiveness ranking. `APACHE_2` / `GEMMA_TERMS` are the shared license descriptors `videoTextEncoders.js` reuses, so a license-text correction reaches both tables from one edit. || `videoDraftDecoders.js` | Preview-fidelity ("draft") video decode (#5423). `VIDEO_DRAFT_DECODERS` declares each entry id → a separately downloaded decoder asset, pin-guarded on repo AND revision; `applyVideoDraftDecoders(list)` is the load-time backfill and `validateDraftDecoderTable` / `sanitizeDraftDecoders` warn + strip a hand-edited row (missing pin, a multi-shard or path-traversing file list, a runtime whose builder emits no draft flags) so a full decode can never report itself as a draft one. `DRAFT_DECODE_FULL` (`'full'`) is a deliberate NO-OP — `isFullDecode(id)` makes absence and that sentinel the same request, so a full-decode render builds byte-identical spawn args. `draftDecodeDeclineReason({ model, decodeId, models, runtimeRevision, assetCached })` RETURNS (never throws) the reason a draft decode does not apply — the model is a delivery target in the finish graph (`isDeliveryVideoModel`), it declares no decoder, the installed runner checkout is not the revision the asset was verified against, or the weights are not downloaded — because a knob that only makes a render cheaper must degrade rather than 400 a submitted job; `resolveVideoDraftDecoder()` returns the concrete asset or `null`. `publicVideoDraftDecodeOptions(model)` is the picker payload (empty for a model with no decoder, so the client renders no control) and `downloadableVideoDraftDecoders(list)` the download targets. The table ships NO entry, and as of 2026-08-30 that is a decision rather than a gap ([ADR](../../docs/decisions/2026-08-30-h3-draft-decoder-asset.md)): the shim substitutes one file into upstream’s checkpoint root under a STRICT key match, so a candidate must be a complete unquantized full-`VideoVAE` checkpoint — which every genuinely light decoder (TAE, quantized repack, decoder-only head) is not. || `videoFinishProfiles.js` | Draft → delivery ("Finish") relationships between video models (#3696). `VIDEO_FINISH_PROFILES` declares each fast draft entry id → `{ shippedRepo, finishModelId }`, only for pairs that share a runtime, base repo and supported modes (the same weights at a different step budget), so re-rendering the draft's seed reproduces its composition instead of re-rolling it. `applyVideoFinishProfiles(list)` is the load-time backfill (twin of migration 238) with the usual preservation guards (existing key wins, custom id skipped, forked `repo` skipped); `validateFinishProfileGraph(list)` returns the graph problems (missing / self-referencing / chained target, runtime / repo / supportedModes mismatch) and `sanitizeFinishProfiles(list)` warns + strips them at load so a typo can never surface a Finish button targeting nothing. `finishTargetForModel(model, availableModels)` resolves the delivery entry scoped to what this install can run. || `videoSpeedProfiles.js` | Named, pre-validated sampler schedules a user can pick instead of hand-tuning steps/CFG (#4875). `VIDEO_SPEED_PROFILES` declares each entry id → `{ shippedRepo, shippedRevision, profiles }`; `applyVideoSpeedProfiles(list)` is the load-time backfill (twin of migration 295) and guards BOTH `repo` and `revision` — unlike the finish-profile decorator, because a sampler schedule is revision-sensitive in a way a draft→delivery edge is not. `SPEED_PROFILE_DEFAULT_ID` (`'quality'`) is a deliberate NO-OP so a default render builds byte-identical spawn args and stamps no extra history fields; `isDefaultSpeedProfile(id)` makes absence and that sentinel the same request. `speedProfileDeclineReason({ model, profileId, mode })` RETURNS (never throws) the reason a profile does not apply — wrong mode, unpinned weights, `samplerLocked` model, unknown id — so a knob that only makes a render faster degrades instead of 400ing a submitted job, and `resolveVideoSpeedProfile()` returns the concrete override or `null`. `resolveVideoSpeedProfileForModes({ model, profileId, modes })` lifts that decline check to a CHAINED render — a chain is one clip whose chunks run in different modes (chunk 0 the request's, chunks 1+ `extend` on a window-continuity chain or `image` on a frame hop), so the profile applies to every chunk or to none rather than seaming a fast chunk onto quality ones. `resolveVideoSampler({ model, steps, guidanceScale, speedProfile })` is the SINGLE precedence rule (samplerLocked > profile > explicit request > registry default), shared by the render path and the chained-render ETA so the two cannot drift. `validateSpeedProfileTable(list)` / `sanitizeSpeedProfiles(list)` warn + strip a hand-edited profile (NaN steps, duplicate/reserved id, samplerLocked collision) at load rather than letting it spawn a broken render. What the RUNNER could actually apply — is the pinned pipeline new enough for `enable_teacache`, is the distilled adapter in the pack — is probed by `scripts/generate_ltx2.py` and reported back on a `SPEEDPROFILE:` line. |-| `videoModeProfiles.js` | The shipped `supportedModes` fact per video runtime (#3737), so "which modes does this model support?" has one answer on the registry entry instead of 25+ `runtime === '…'` comparisons. `VIDEO_RUNTIME_MODES` maps each runtime to the base semantic modes its helper's argv can actually render (`mlx_video`/`ltx2` text+image+fflf+extend, `wan22`/`fastvideo` text+image, `minimax_h3` / `minimax_h3_cuda` text+image+fflf off one shared array — also the mode ceiling in `videoGen/modeContract.js`); `VIDEO_BASE_MODES` is the fallback for an unknown (user-added or peer-synced) runtime, deliberately the full base set so a custom model doesn't vanish from every picker. `resolveVideoSupportedModes(entry)` (declared non-empty list always wins) and `applyVideoSupportedModes(list)` — the read-time decoration `mediaModels.js#getVideoModels` applies, so the derived list never lands in `data/media-models.json` where it would read back as a *declared* list no later correction could reach. a2v and the IC-LoRA remix ids are NOT enumerated here: they're ltx2 pipeline capabilities, gated by runtime (`A2V_REQUIRES_LTX2` / `IC_LORA_REQUIRES_LTX2`). |+| `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 semantic modes its helper can actually render, including `minimax_h3_ref2va` as a2v-only; `VIDEO_BASE_MODES` remains the non-audio fallback for an unknown runtime. `resolveVideoSupportedModes(entry)` and `applyVideoSupportedModes(list)` provide the read-time decoration used by `mediaModels.js#getVideoModels`. |+| `videoDurationProfiles.js` | Pure pinned duration/frame contracts shared by model-registry upgrades and migrations. LTX-2.5 A2V follows the full uploaded audio, rounds up to its 8n+1 temporal grid, and tops out at 1017 frames under the API's single-pass boundary. || `videoReferenceModes.js` | The i2v reference-mode contract (#4874) — what a supplied conditioning image PROMISES. `I2V_REFERENCE_MODES` (`anchor` \| `inspire`) + `I2V_REFERENCE_MODE_OPTIONS` (the label + the promise sentence the UI prints), `I2V_REFERENCE_MODE_RUNTIMES` (only `ltx25` can honor `inspire` — it needs per-image conditioning strength), `INSPIRE_DEFAULT_IMAGE_STRENGTH`, plus `normalizeI2vReferenceMode` / `isDefaultI2vReferenceMode` / `isKnownI2vReferenceMode` / `runtimeSupportsI2vReferenceMode` / `i2vReferenceModeLabel` / `resolveI2vReferenceStrength` and the one rule `i2vReferenceModeViolation({ model, mode, referenceMode, hasFirstImage })` → `{ code, message }` or null. Pure (no `ServerError`) because it is MIRRORED to `client/src/lib/videoReferenceModes.js`; `videoGen/modeContract.js#videoReferenceModeError` wraps it for the route + render boundaries. || `videoTextEncoders.js` | Swappable prompt conditioners for local video runtimes. MiniMax H3 reads the *unnormalized* hidden state after Qwen3-VL language layer 49 (layers 50-63, the final norm and `lm_head` are never evaluated), so any checkpoint carrying the same embedding + layers 0-49 + vision tower is a drop-in conditioner — swapping it changes how the model reads a prompt without touching the diffusion weights. `TEXT_ENCODERS_BY_RUNTIME` declares the shipped options per runtime (pinned repo/revision plus an explicit `files` LIST — one repackaged safetensors, or just the shards of an upstream checkpoint that carry parameters the loader actually builds; in code rather than the media-models registry so a stale `data/media-models.json` can't name a file the runner can't map); `videoTextEncoderOptions(model)` returns the TRUE list stock-first (it deliberately does NOT collapse a one-entry runtime to `[]` — that is a presentation rule, and folding it in here would change what the server believes a model supports and empty the "offers …" list in the error; `TextEncoderPicker` owns the hide-when-there-is-no-real-choice check), `isStockTextEncoder(id)` makes absence and the `stock` sentinel the same request, `resolveVideoTextEncoder(model, id)` returns `null` for the stock choice or throws `VIDEO_TEXT_ENCODER_UNSUPPORTED` (with the non-throwing `supportsVideoTextEncoder` + `videoTextEncoderUnsupportedError` split out so the request path can reject before staging uploads), and `downloadableVideoTextEncoders()` (deduped by id — the table is keyed by RUNTIME, so one conditioner can be offered by two) / `downloadableVideoTextEncoder(id)` feed the `/api/video-gen/text-encoders/:id/(download\|repair)` lane. Two loader-mechanics fields exist because a ComfyUI-packaged conditioner is namespaced differently from the HF checkpoint the MLX port matches: `keyPrefixMap` (`model.` → `model.language_model.`, `visual.` → `model.visual.`) is applied to every checkpoint key by `scripts/generate_minimax_h3.py` BEFORE the pinned loader sees it — no fork of the pinned runtime — and `finalNormKey` names where the runner synthesizes a ones-filled `norm.weight` for a checkpoint published without one (correct upstream, since H3 reads the state *before* the norm, but the pinned loader refuses to load with any parameter missing). Both are absent for an UPSTREAM Qwen3-VL-32B checkpoint, which already uses the loader namespace and ships its own norm. A candidate must BE Qwen3-VL-32B (the shim reuses upstream's config/tokenizer/processor) — a different Qwen generation is not a substitute however close its conditioning width looks; see docs/features/video-text-encoders.md. `publicTextEncoderOption(entry)` is the client projection and deliberately drops both, so the UI can't reimplement the remap. The `ltx25` table (#4320) uses a third mechanic, `configOverrides`, because an LTX-2.5 pack's OWN Gemma 4 tower wins over `--gemma` inside the pinned fork: the substitution is a standalone shim directory whose generated `config.json` is the substitute's own with these keys merged over it (only ever the `model_type` label a unified checkpoint gets wrong — never `text_config`/`quantization`), and a candidate must BE Gemma 4 12B at 48 layers / hidden 3840 / vocab 262144 / `k_eq_v`. `verified` gates a substitute out of BOTH lanes (picker AND download) until it has been A/B-rendered against its runtime's stock conditioner — required on every non-built-in entry and fail-closed on absence, so a new entry is unreachable until someone states a verdict; both ltx25 substitutes are `verified: false` today. `declaredVideoTextEncoders()` is the UNFILTERED table for shape/invariant checks only — never the render or download path, and `videoTextEncoderRuntimes()` enumerates the table's runtime keys so parity/shape tests cover every runtime rather than the one that happened to exist when they were written. || `providerModels.js` | Provider model resolution sentinels + helpers (`CODEX_CONFIGURED_DEFAULT` / `ANTIGRAVITY_CONFIGURED_DEFAULT` / `GROK_CONFIGURED_DEFAULT` / `KIMI_CONFIGURED_DEFAULT`, `resolveCliModel`, `filterSelectableModels`, Bedrock/OpenCode model mappers, model-flag scan helpers incl. `stripBrokenModelFlags`, `isCodexProvider`, `isKimiProvider`, `isAntigravityProvider`, `isCursorProvider`) plus reasoning-effort helpers for the claude/codex/agy/cursor CLIs (`CLAUDE_EFFORT_LEVELS` / `CODEX_EFFORT_LEVELS` / `ANTIGRAVITY_EFFORT_LEVELS` / `CURSOR_EFFORT_LEVELS` / `EFFORT_LEVELS`, `effortLevelsForProvider`, `resolveCliEffort` — clamps an out-of-range effort to the nearest level the target CLI accepts rather than dropping it, so a value saved against a wider ladder survives a provider switch — `hasEffortFlag`, `buildEffortArgs` — the one emitter of `--effort <level>` / `-c model_reasoning_effort=<level>`, and deliberately silent for cursor — and `foldCursorEffortIntoModel`, which carries a cursor level inside `--model` as Cursor’s own variant syntax (`gpt-5[effort=max]`) because `cursor-agent` has no `--effort` flag) plus codex startup-arg helpers (`CODEX_EFFORT_KEY`, `CODEX_UPDATE_CHECK_KEY`, `hasCodexUpdateCheckConfig`, `buildCodexStartupArgs` — the one emitter of `-c check_for_update_on_startup=false`, spread by every codex spawn builder to disable the blocking startup update modal) plus `PORTOS_CLI_CONFIG_KEYS` / `isPortosSuppliedConfigKey` — the exhaustive list of `-c <key>=<value>` config keys PortOS injects, read by the `cli-config-invalid` error analyzer to tell a rejected PortOS override apart from a bad line in the user's own CLI config file. |@@ -187,7 +188,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `grok.js` | xAI Grok Build (`grok`) provider helpers — id/endpoint constants (`GROK_API_ID`/`GROK_CLI_ID`/`GROK_TUI_ID`/`GROK_API_ENDPOINT`), `isGrokCommand`/`isGrokCliProvider`/`isGrokTuiProvider` predicates, `ensureGrokHeadlessArgs`/`ensureGrokTuiArgs` argv builders (grok reads its prompt from `--prompt-file /dev/stdin`, not raw stdin; model selection uses the `GROK_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Antigravity), and `prepareGrokPromptFile` (Windows temp-file delivery fallback). || `grokVideoClip.js` | Clip lengths grok's `image_to_video` actually delivers — `GROK_VIDEO_DURATIONS` (`[6, 10]`, measured in #3022: a 2s/3s request returns the same 6.04s clip), `GROK_VIDEO_DEFAULT_DURATION`, `resolveGrokDuration()` (validate an already-grok-shaped request, else default), and `nearestGrokDuration()` (round a length authored against another backend's continuous contract UP to the shortest clip that covers it — for translating a CD/commission `targetDurationSeconds`). Dependency-free so `validation.js` / `routes/videoGen.js` can derive their schemas from the same list the services gate on. || `kimi.js` | Moonshot AI Kimi Code (`kimi`) provider helpers — id constants (`KIMI_CLI_ID`/`KIMI_TUI_ID`), `isKimiCommand`/`isKimiCliProvider`/`isKimiTuiProvider` predicates, `ensureKimiHeadlessArgs` (model flag only — non-interactive mode is implicit in `--prompt`, and kimi has no `--print`/`--afk` and refuses approval flags alongside `--prompt`) / `ensureKimiTuiArgs` (`--yolo`) argv builders (model selection uses the `KIMI_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Grok/Antigravity), and `prepareKimiPrompt` (delivers the prompt as the `--prompt <value>` argv, not stdin). |-| `runners.js` | Image-runner family constants (`RUNNER_FAMILIES`, `loraCompatKey`), the separate `VIDEO_LORA_FAMILIES` + `videoLoraFamily` used by the video LoRA picker, and `isMiniMaxH3Runtime` / `MINIMAX_H3_RUNTIMES` — the predicate every gate asserting a MiniMax H3 model fact (24 fps, joint A/V, CFG-distilled, the 17n+5 grid) must use so the MLX and CUDA runtimes cannot drift apart. Mirrored to `client/src/lib/runnerFamilies.js`. |+| `runners.js` | Image-runner family constants (`RUNNER_FAMILIES`, `loraCompatKey`), video LoRA families, MiniMax H3 runtime predicates, and the shared `AUDIO_TO_VIDEO_RUNTIMES` / `isAudioToVideoRuntime` capability gate (LTX plus H3 Ref2VA). Mirrored to `client/src/lib/runnerFamilies.js`. || `codexAssistantExtract.js` | Strip Codex CLI banner + echoed metadata from session transcript. || `codexCliOutput.js` | Network/system error patterns for `agentErrorAnalysis.js`. || `contextBudget.js` | Context-window budgeter for editorial passes. `estimateTokens`/`estimateTokensFromChars` (chars/4), `usableInputTokens`, `manuscriptContentBudgetChars` (single-block content cap floored at a manuscript minimum so a standalone stage trims to fit a small window instead of overflowing a fixed 48–60K floor, #1488), `planManuscriptPass({ contextWindow, sections })` → `{ mode: 'whole' \| 'chunked', chunks }`. Also `fitContextToManuscriptFloor`/`capContextOverhead`/`trimContextToBudget` — trim a re-sent context block (scene map, character arcs, …) so a large reverse outline on a small window can't starve the manuscript chunk below a budget floor (#1459). Decides whole-manuscript vs chunked given a model's window. |diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex 06f3a60a14..2aca6f732f 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -21996,7 +21996,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 932+ "line": 938}]},@@ -22007,7 +22007,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1319+ "line": 1327}]},@@ -22018,7 +22018,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1295+ "line": 1303}]},@@ -22029,7 +22029,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1324+ "line": 1332}]},@@ -22040,7 +22040,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1353+ "line": 1361}]},@@ -22051,7 +22051,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1401+ "line": 1409}]},@@ -22062,7 +22062,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1373+ "line": 1381}]},@@ -22073,7 +22073,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1409+ "line": 1417}]},@@ -22084,7 +22084,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1405+ "line": 1413}]},@@ -22095,7 +22095,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 811+ "line": 817}]},@@ -22106,7 +22106,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 830+ "line": 836}]},@@ -22117,7 +22117,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1426+ "line": 1434}]},@@ -22128,7 +22128,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 452+ "line": 455}]},@@ -22139,7 +22139,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 456+ "line": 459}]},@@ -22150,7 +22150,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 524+ "line": 527}]},@@ -22161,7 +22161,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 777+ "line": 780}]},@@ -22172,7 +22172,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 762+ "line": 765}]},@@ -22183,7 +22183,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 665+ "line": 668}]},@@ -22194,7 +22194,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 745+ "line": 748}]},@@ -22205,7 +22205,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 494+ "line": 497}]},@@ -22216,7 +22216,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 496+ "line": 499}]},@@ -22227,7 +22227,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 490+ "line": 493}]},@@ -22238,7 +22238,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 402+ "line": 405}]},@@ -22249,7 +22249,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1443+ "line": 1451}]},@@ -22260,7 +22260,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 919+ "line": 925}]},@@ -22271,7 +22271,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 905+ "line": 911}]},@@ -22282,7 +22282,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 875+ "line": 881}]},@@ -22293,7 +22293,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 885+ "line": 891}]},@@ -22304,7 +22304,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1394+ "line": 1402}]},@@ -22315,7 +22315,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1432+ "line": 1440}]},diff --git a/server/lib/federatedMediaWire.js b/server/lib/federatedMediaWire.jsindex 971bbe7410..35e25d1bb3 100644--- a/server/lib/federatedMediaWire.js+++ b/server/lib/federatedMediaWire.js@@ -5,6 +5,10 @@ import { isPlainObject } from './objects.js';export const FEDERATED_MEDIA_WIRE_VERSION = 1;export const FEDERATED_MEDIA_STALE_AFTER_MS = 60_000;export const FEDERATED_MEDIA_MAX_CLOCK_SKEW_MS = 30_000;+// The shared API/federation ceiling for one video render. Keep this above the+// largest shipped model contract (LTX-2.5 currently tops out at 1017 frames)+// so provider capability projection never erases a locally-valid request.+export const FEDERATED_MEDIA_MAX_VIDEO_FRAMES = 1024;const FEDERATED_AUDIO_STYLES = ['ambient', 'cinematic', 'classical', 'electronic', 'folk', 'hip-hop',@@ -290,8 +294,8 @@ export const federatedMediaCapabilitySchema = z.object({lyrics: z.boolean(),autoDuration: z.boolean(),frameStride: z.number().int().min(1).max(64).nullable().optional(),- maxNumFrames: z.number().int().min(1).max(600).nullable().optional(),- frameOptions: z.array(z.number().int().min(1).max(600)).max(100).nullable().optional(),+ maxNumFrames: z.number().int().min(1).max(FEDERATED_MEDIA_MAX_VIDEO_FRAMES).nullable().optional(),+ frameOptions: z.array(z.number().int().min(1).max(FEDERATED_MEDIA_MAX_VIDEO_FRAMES)).max(100).nullable().optional(),fpsOptions: z.array(z.number().int().min(1).max(60)).max(20).nullable().optional(),resolutionOptions: z.array(z.object({w: z.number().int().min(64).max(2048),diff --git a/server/lib/federatedMediaWire.test.js b/server/lib/federatedMediaWire.test.jsindex ef2bac11f5..1bf6651d41 100644--- a/server/lib/federatedMediaWire.test.js+++ b/server/lib/federatedMediaWire.test.js@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest';import {FEDERATED_MEDIA_FEATURES,+ FEDERATED_MEDIA_MAX_VIDEO_FRAMES,federatedMediaAudioProfileSchema,federatedMediaDeclaresFeatures,federatedMediaDeniesFeature,@@ -136,7 +137,7 @@ describe('federated media status kind projection', () => {lyrics: false,autoDuration: false,frameStride: 4,- maxNumFrames: 121,+ maxNumFrames: 1017,frameOptions: [25, 49, 73, 97, 121],fpsOptions: [16, 20, 24],resolutionOptions: [{ w: 1344, h: 768, label: '16:9 H3 default' }],@@ -147,6 +148,10 @@ describe('federated media status kind projection', () => {kinds: ['video'],capabilities: [capability],})).success).toBe(true);+ expect(federatedMediaCapabilitySchema.safeParse({+ ...capability,+ maxNumFrames: FEDERATED_MEDIA_MAX_VIDEO_FRAMES + 1,+ }).success).toBe(false);});it('validates an older provider payload omitting the frame and canvas constraint fields', () => {diff --git a/server/lib/ffmpeg.js b/server/lib/ffmpeg.jsindex c07b7127e7..a054e04909 100644--- a/server/lib/ffmpeg.js+++ b/server/lib/ffmpeg.js@@ -183,11 +183,11 @@ export const hasAudioStream = async (videoPath) => {// Returns the basename on success, null when ffmpeg is missing or fails —// callers should treat null as "no thumbnail" rather than aborting the// parent operation.-// Probe a video's duration in seconds via ffprobe. Returns null when ffprobe is-// unavailable or the file has no parseable duration — callers must treat null as-// "unknown" rather than 0. Exported as `probeVideoDuration` for the cue-placement-// path (issue #863), which needs the episode length to lay arc cues onto the-// timeline.+// Probe a media file's duration in seconds via ffprobe. The implementation is+// container-level and works for audio-only files too. Returns null when ffprobe+// is unavailable or the file has no parseable duration — callers must treat null+// as "unknown" rather than 0. The historical `probeVideoDuration` export name is+// retained because cue placement already consumes it.const probeDurationSeconds = async (videoPath) => {const stdout = await runFfprobe(['-v', 'error',diff --git a/server/lib/index.js b/server/lib/index.jsindex af407fef54..8792d8ea64 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -148,6 +148,7 @@ export * from './videoDraftDecoders.js';export * from './videoFinishProfiles.js';export * from './videoSpeedProfiles.js';export * from './videoModeProfiles.js';+export * from './videoDurationProfiles.js';export * from './videoReferenceModes.js';export * from './videoTextEncoders.js';export * from './promptPartials.js';diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.jsindex d0ccba3764..1141020204 100644--- a/server/lib/mediaModels.js+++ b/server/lib/mediaModels.js@@ -81,6 +81,7 @@ import { applyVideoSpeedProfiles, sanitizeSpeedProfiles } from './videoSpeedProfimport { applyVideoDraftDecoders, sanitizeDraftDecoders } from './videoDraftDecoders.js';import { applyMiniMaxH3MemoryProfiles, sanitizeMiniMaxH3MemoryProfiles } from './minimaxH3Memory.js';import { applyVideoSupportedModes } from './videoModeProfiles.js';+import { LTX25_AUDIO_PROFILE } from './videoDurationProfiles.js';import {captureSystemCapabilities,hardwareRequirementsForMediaModel,@@ -268,6 +269,27 @@ export const upgradeMiniMaxH3OutputControls = (list) => {return upgradeMiniMaxH3DenoisingCount(withGeometry);};+// Existing installs already persisted the shipped LTX-2.5 row before its A2V+// duration contract was declared. Backfill only the untouched pinned model and+// only absent keys: a user-repointed fork or an explicit local override remains+// authoritative. Migration 318 persists the same fields, while this load-time+// twin matters on the boot that runs the migration because the registry cache is+// populated before migrations execute.+export const upgradeLtx25AudioControls = (list) => {+ if (!Array.isArray(list)) return list;+ return list.map((entry) => {+ if (!isPlainObject(entry)+ || entry.id !== LTX25_AUDIO_PROFILE.id+ || entry.repo !== LTX25_AUDIO_PROFILE.repo+ || entry.revision !== LTX25_AUDIO_PROFILE.revision) return entry;+ const missing = ['audioDurationDriven', 'frameStride', 'maxNumFrames']+ .filter((key) => !Object.hasOwn(entry, key));+ return missing.length === 0+ ? entry+ : { ...entry, ...Object.fromEntries(missing.map((key) => [key, LTX25_AUDIO_PROFILE[key]])) };+ });+};+const DEFAULT_REGISTRY = {_doc: 'PortOS media model registry. Edit to add models, tune defaults, or switch the text encoder. Restart the server to apply changes.',video: {@@ -301,7 +323,21 @@ const DEFAULT_REGISTRY = {{ id: 'ltx23_dgrauet_q8', name: 'LTX-2.3 dgrauet Q8 (~25 GB, true keyframes)', repo: 'dgrauet/ltx-2.3-mlx-q8', runtime: 'ltx2', steps: 8, guidance: 3.0 },// LTX-2.5 Q8 on MrMofer's ltx25 fork of dgrauet/ltx-2-mlx. The 2.3 pin// cannot load these weights; INSTALL_LTX25 provisions a sibling venv.- { id: 'ltx25_mlx_q8', name: 'LTX-2.5 MLX Q8 (~68 GB, Apple Silicon)', repo: 'MrMofer/ltx-2.5-mlx-q8', revision: 'f1b56e7dc89f71a9af2cddac787b89ed22a8b7fc', runtime: 'ltx25', steps: 8, guidance: 3.0 },+ {+ id: 'ltx25_mlx_q8',+ name: 'LTX-2.5 MLX Q8 (~68 GB, Apple Silicon)',+ repo: 'MrMofer/ltx-2.5-mlx-q8',+ revision: 'f1b56e7dc89f71a9af2cddac787b89ed22a8b7fc',+ runtime: 'ltx25',+ // A2V accepts an optional frame-one image. PortOS probes a direct audio+ // upload and rounds its full duration up to the LTX 8n+1 grid. 1017 is+ // the highest legal count under the route's 1024-frame single-pass cap.+ audioDurationDriven: true,+ frameStride: 8,+ maxNumFrames: 1017,+ steps: 8,+ guidance: 3.0,+ },// MiniMax H3 joint video+audio through PipeNetwork's pinned MLX port.// The quantized DiT is one HF snapshot; the released conditioner + VAEs// are an exact selective file set from MiniMax's upstream snapshot. Both@@ -385,6 +421,42 @@ const DEFAULT_REGISTRY = {],}],},+ // MiniMax H3 Ref2VA through the signed mere.run native runtime. The+ // checkpoint accepts at most 15 seconds of reference audio per call;+ // PortOS chains those windows and remuxes the exact source audio so the+ // user-facing mode has no arbitrary duration cap.+ {+ id: 'minimax_h3_ref2va_8bit',+ name: 'MiniMax H3 Ref2VA MLX 8-bit (image + arbitrary-length audio, ~71 GB, 128 GB RAM)',+ repo: 'Sawfwair/MiniMax-H3-Ref2VA-MLX-8bit',+ revision: '61dc387ef1a7166425cdacd63c2340598dcc364f',+ runtime: 'minimax_h3_ref2va',+ supportedModes: ['a2v'],+ requiresSourceImageForA2v: true,+ audioDurationDriven: true,+ arbitraryLengthAudio: true,+ maxReferenceAudioSeconds: 15,+ defaultFrames: 124,+ frameOptions: [...MINIMAX_H3_OUTPUT_PROFILE.frameOptions],+ fpsOptions: [24],+ defaultWidth: 512,+ defaultHeight: 320,+ resolutionStep: 32,+ resolutionOptions: [+ { label: '512x320 (draft)', w: 512, h: 320 },+ { label: '768x480', w: 768, h: 480 },+ { label: '1024x640', w: 1024, h: 640 },+ { label: '768x768 (1:1)', w: 768, h: 768 },+ ],+ memoryGb: 128,+ steps: 9,+ guidance: 0,+ samplerLocked: true,+ samplerNote: 'MiniMax H3 Ref2VA is CFG-distilled. PortOS renders audio in up-to-15-second continuity-linked windows, then restores the exact source audio over the final video.',+ supportsNegativePrompt: false,+ supportsTiling: false,+ supportsDisableAudio: false,+ },// Wan 2.2 through pinned MLX-Gen. Generation is cache-only: PortOS owns// the explicit base/adaptor downloads and uses the saved HF token.{@@ -1116,7 +1188,9 @@ const normalizeRegistry = (parsed) => {// model this install deleted — or a hand-edited typo — is dropped with a// warning instead of surfacing a Finish button targeting nothing.const videoEntries = (entries, { upgradeLegacyCudaLtx = false } = {}) => {- const normalized = backfillRuntime(upgradeMiniMaxH3OutputControls(dropRetiredEntries(entries)));+ const normalized = backfillRuntime(upgradeLtx25AudioControls(+ upgradeMiniMaxH3OutputControls(dropRetiredEntries(entries)),+ ));const upgraded = upgradeLegacyCudaLtx ? upgradeLegacyCudaLtxRuntime(normalized) : normalized;const decorated = sanitizeFinishProfiles(applyVideoFinishProfiles(applyVideoDisclosures(upgraded)));// applyVideoSpeedProfiles is the load-time twin of migration 295, anddiff --git a/server/lib/mediaModels.test.js b/server/lib/mediaModels.test.jsindex 9f24abcc25..c5debf99d6 100644--- a/server/lib/mediaModels.test.js+++ b/server/lib/mediaModels.test.js@@ -65,6 +65,9 @@ describe('mediaModels registry', () => {runtime: 'ltx25',repo: 'MrMofer/ltx-2.5-mlx-q8',revision: 'f1b56e7dc89f71a9af2cddac787b89ed22a8b7fc',+ audioDurationDriven: true,+ frameStride: 8,+ maxNumFrames: 1017,steps: 8,});expect(ltx25.disclosure.weightsLicense.name).toBe('LTX-2.x Community License');diff --git a/server/lib/minimaxH3Memory.js b/server/lib/minimaxH3Memory.jsindex 1bf5f18df9..bbc9ccba80 100644--- a/server/lib/minimaxH3Memory.js+++ b/server/lib/minimaxH3Memory.js@@ -111,6 +111,25 @@ export const MINIMAX_H3_MEMORY_PROFILES = Object.freeze({}),]),}),+ // Sawfwair's Ref2VA MLX port uses the same unified-memory placement shape:+ // one quantized DiT plus its conditioner and VAEs stay resident together.+ // The 128 GB floor is the shipped entry's existing `memoryGb` requirement,+ // hoisted here so render preflight enforces it rather than merely displaying+ // it on the model card.+ minimax_h3_ref2va_8bit: Object.freeze({+ shippedRepo: 'Sawfwair/MiniMax-H3-Ref2VA-MLX-8bit',+ shippedRevision: '61dc387ef1a7166425cdacd63c2340598dcc364f',+ profiles: Object.freeze([+ Object.freeze({+ id: 'unified-8bit',+ name: 'Unified 8-bit Ref2VA',+ description: '8-bit Ref2VA weights and conditioning components resident in Apple unified memory.',+ minMemoryGb: 128,+ minVramGb: null,+ unified: true,+ }),+ ]),+ }),// diffusers' MiniMaxH3ModularPipeline on NVIDIA. The three recipes and their// thresholds are `resolve_offload_profile()`'s own, moved here so the server// can preflight them and the runner can fail closed on the same table insteaddiff --git a/server/lib/minimaxH3Memory.test.js b/server/lib/minimaxH3Memory.test.jsindex 6ed58f141d..00d7489ee5 100644--- a/server/lib/minimaxH3Memory.test.js+++ b/server/lib/minimaxH3Memory.test.js@@ -13,6 +13,7 @@ import {} from './minimaxH3Memory.js';const MLX_SPEC = MINIMAX_H3_MEMORY_PROFILES.minimax_h3_8bit;+const REF2VA_SPEC = MINIMAX_H3_MEMORY_PROFILES.minimax_h3_ref2va_8bit;const CUDA_SPEC = MINIMAX_H3_MEMORY_PROFILES.minimax_h3_cuda;const mlxEntry = (overrides = {}) => ({@@ -29,6 +30,13 @@ const cudaEntry = (overrides = {}) => ({...overrides,});+const ref2vaEntry = (overrides = {}) => ({+ id: 'minimax_h3_ref2va_8bit',+ repo: REF2VA_SPEC.shippedRepo,+ revision: REF2VA_SPEC.shippedRevision,+ ...overrides,+});+const decorated = (entry) => applyMiniMaxH3MemoryProfiles([entry])[0];describe('applyMiniMaxH3MemoryProfiles', () => {@@ -40,6 +48,11 @@ describe('applyMiniMaxH3MemoryProfiles', () => {expect(next.memoryProfiles).toEqual([...MLX_SPEC.profiles]);});+ it('attaches the Ref2VA profile only to its pinned weights', () => {+ expect(decorated(ref2vaEntry()).memoryProfiles).toEqual([...REF2VA_SPEC.profiles]);+ expect(decorated(ref2vaEntry({ revision: 'deadbeef' }))).not.toHaveProperty('memoryProfiles');+ });+it('leaves an explicit user value alone, including a deliberate empty list', () => {expect(decorated(mlxEntry({ memoryProfiles: [] })).memoryProfiles).toEqual([]);expect(decorated(mlxEntry({ memoryProfiles: null })).memoryProfiles).toBeNull();@@ -74,6 +87,12 @@ describe('selectMiniMaxH3MemoryProfile', () => {expect(selectMiniMaxH3MemoryProfile({ model, totalMemoryGb: 127 }).profile).toBeNull();});+ it('enforces the shipped Ref2VA 128 GB floor', () => {+ const model = decorated(ref2vaEntry());+ expect(selectMiniMaxH3MemoryProfile({ model, totalMemoryGb: 128 }).profile.id).toBe('unified-8bit');+ expect(selectMiniMaxH3MemoryProfile({ model, totalMemoryGb: 96 }).profile).toBeNull();+ });+it('defers to the runner when the host was not measured', () => {// "Probe returned nothing" is not "this box has no memory" — an unmeasured// host gets the best profile unjudged rather than a refusal.@@ -95,6 +114,15 @@ describe('miniMaxH3MemoryDeclineReason', () => {expect(reason.message).toContain('64 GB');});+ it('refuses Ref2VA before spawn when the measured host is below its floor', () => {+ const reason = miniMaxH3MemoryDeclineReason({+ model: decorated(ref2vaEntry({ name: 'MiniMax H3 Ref2VA MLX 8-bit' })),+ totalMemoryGb: 96,+ });+ expect(reason).toMatchObject({ code: 'MINIMAX_H3_MEMORY_INSUFFICIENT' });+ expect(reason.message).toContain('128 GB');+ });+it('stays null for a box that fits, an unmeasured host, and a model with no table', () => {const model = decorated(cudaEntry());expect(miniMaxH3MemoryDeclineReason({ model, totalMemoryGb: 256 })).toBeNull();@@ -107,7 +135,9 @@ describe('validateMiniMaxH3MemoryProfileTable / sanitize', () => {const problemFor = (memoryProfiles) => validateMiniMaxH3MemoryProfileTable([{ id: 'x', memoryProfiles }])[0];it('accepts the shipped table and absent/null keys', () => {- expect(validateMiniMaxH3MemoryProfileTable(applyMiniMaxH3MemoryProfiles([mlxEntry(), cudaEntry()]))).toEqual([]);+ expect(validateMiniMaxH3MemoryProfileTable(+ applyMiniMaxH3MemoryProfiles([mlxEntry(), ref2vaEntry(), cudaEntry()]),+ )).toEqual([]);expect(validateMiniMaxH3MemoryProfileTable([{ id: 'x' }, { id: 'y', memoryProfiles: null }])).toEqual([]);});diff --git a/server/lib/runners.js b/server/lib/runners.jsindex 953957c44f..e6e8c81370 100644--- a/server/lib/runners.js+++ b/server/lib/runners.js@@ -54,7 +54,12 @@ export const isVideoLoraFamily = (family) => VIDEO_LORA_FAMILY_SET.has(family);// Gates asserting one of those facts ask this predicate instead of naming a// single runtime, which is what would silently exempt the other one.// Mirrored to client/src/lib/runnerFamilies.js.-export const MINIMAX_H3_RUNTIMES = Object.freeze(['minimax_h3', 'minimax_h3_cuda']);+export const MINIMAX_H3_REF2VA_RUNTIME = 'minimax_h3_ref2va';+export const MINIMAX_H3_RUNTIMES = Object.freeze([+ 'minimax_h3',+ 'minimax_h3_cuda',+ MINIMAX_H3_REF2VA_RUNTIME,+]);const MINIMAX_H3_RUNTIME_SET = new Set(MINIMAX_H3_RUNTIMES);export const isMiniMaxH3Runtime = (runtime) => MINIMAX_H3_RUNTIME_SET.has(runtime);// dgrauet's LTX-2.3 pin (`ltx2`) and the LTX-2.5 fork (`ltx25`) share the@@ -64,6 +69,12 @@ export const isMiniMaxH3Runtime = (runtime) => MINIMAX_H3_RUNTIME_SET.has(runtimexport const LTX2_FAMILY_RUNTIMES = Object.freeze(['ltx2', 'ltx25']);const LTX2_FAMILY_RUNTIME_SET = new Set(LTX2_FAMILY_RUNTIMES);export const isLtx2FamilyRuntime = (runtime) => LTX2_FAMILY_RUNTIME_SET.has(runtime);+export const AUDIO_TO_VIDEO_RUNTIMES = Object.freeze([+ ...LTX2_FAMILY_RUNTIMES,+ MINIMAX_H3_REF2VA_RUNTIME,+]);+const AUDIO_TO_VIDEO_RUNTIME_SET = new Set(AUDIO_TO_VIDEO_RUNTIMES);+export const isAudioToVideoRuntime = (runtime) => AUDIO_TO_VIDEO_RUNTIME_SET.has(runtime);// The family an INSTALLED LoRA belongs to. `loraCompatKey` is the refined key// (e.g. flux2-9b) written by the importer; `runnerFamily` is the coarse legacydiff --git a/server/lib/runners.test.js b/server/lib/runners.test.jsindex c0ea23d971..fffcd9f092 100644--- a/server/lib/runners.test.js+++ b/server/lib/runners.test.js@@ -3,7 +3,7 @@ import { readFileSync } from 'fs';import { dirname, join } from 'path';import { fileURLToPath } from 'url';-import { RUNNER_FAMILIES, VIDEO_LORA_FAMILIES, MINIMAX_H3_RUNTIMES, LTX2_FAMILY_RUNTIMES, videoLoraFamily, isMiniMaxH3Runtime, isLtx2FamilyRuntime, isMlxVideoLtxLoraCapable, loraFamilyOf, isMflux, isFlux2, isZImage, isErnie, isHiDream, isQwen, flux2VariantFromModel, loraCompatKey, composeCompatKey } from './runners.js';+import { RUNNER_FAMILIES, VIDEO_LORA_FAMILIES, MINIMAX_H3_RUNTIMES, LTX2_FAMILY_RUNTIMES, AUDIO_TO_VIDEO_RUNTIMES, videoLoraFamily, isMiniMaxH3Runtime, isLtx2FamilyRuntime, isAudioToVideoRuntime, isMlxVideoLtxLoraCapable, loraFamilyOf, isMflux, isFlux2, isZImage, isErnie, isHiDream, isQwen, flux2VariantFromModel, loraCompatKey, composeCompatKey } from './runners.js';const __dirname_self = dirname(fileURLToPath(import.meta.url));const CLIENT_MIRROR_PATH = join(__dirname_self, '..', '..', 'client', 'src', 'lib', 'runnerFamilies.js');@@ -129,7 +129,7 @@ describe('VIDEO_LORA_FAMILIES / videoLoraFamily', () => {expect(text).toMatch(/export const isMlxVideoLtxLoraCapable/);expect(text).toMatch(/export const loraFamilyOf/);expect(text).toMatch(/export const isMiniMaxH3Runtime/);- expect(text).toMatch(/'minimax_h3', 'minimax_h3_cuda'/);+ expect(text).toMatch(/MINIMAX_H3_REF2VA_RUNTIME = 'minimax_h3_ref2va'/);expect(text).toMatch(/export const isLtx2FamilyRuntime/);expect(text).toMatch(/'ltx2', 'ltx25'/);});@@ -205,14 +205,15 @@ describe('composeCompatKey', () => {});// H3's controls (24 fps, joint A/V, no CFG, the 17n+5 grid) are facts about the-// checkpoint, so the gates that assert them must cover BOTH runtimes. Naming+// checkpoint, so the gates that assert them must cover every H3 runtime. Naming// one runtime in a gate is precisely how the CUDA path would silently escape// a rule the MLX path enforces.describe('isMiniMaxH3Runtime', () => {- it('covers both H3 runtimes and nothing else', () => {- expect(MINIMAX_H3_RUNTIMES).toEqual(['minimax_h3', 'minimax_h3_cuda']);+ it('covers all H3 runtimes and nothing else', () => {+ expect(MINIMAX_H3_RUNTIMES).toEqual(['minimax_h3', 'minimax_h3_cuda', 'minimax_h3_ref2va']);expect(isMiniMaxH3Runtime('minimax_h3')).toBe(true);expect(isMiniMaxH3Runtime('minimax_h3_cuda')).toBe(true);+ expect(isMiniMaxH3Runtime('minimax_h3_ref2va')).toBe(true);});it.each(['mlx_video', 'ltx2', 'wan22', 'fastvideo', 'minimax', '', undefined, null])(@@ -227,6 +228,15 @@ describe('isMiniMaxH3Runtime', () => {});});+describe('isAudioToVideoRuntime', () => {+ it('covers both LTX pins plus MiniMax H3 Ref2VA', () => {+ expect(AUDIO_TO_VIDEO_RUNTIMES).toEqual(['ltx2', 'ltx25', 'minimax_h3_ref2va']);+ for (const runtime of AUDIO_TO_VIDEO_RUNTIMES) expect(isAudioToVideoRuntime(runtime)).toBe(true);+ expect(isAudioToVideoRuntime('minimax_h3')).toBe(false);+ expect(isAudioToVideoRuntime('mlx_video')).toBe(false);+ });+});+describe('isLtx2FamilyRuntime', () => {it('covers the 2.3 pin and the 2.5 fork, and nothing else', () => {expect(LTX2_FAMILY_RUNTIMES).toEqual(['ltx2', 'ltx25']);diff --git a/server/lib/validation.js b/server/lib/validation.jsindex a9bccd4699..10f9456c35 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -15,6 +15,7 @@ import { EFFORT_LEVELS } from './providerModels.js';import { MAX_TIMEOUT as AI_RUN_TIMEOUT_MAX_MS, MIN_TIMEOUT as AI_RUN_TIMEOUT_MIN_MS } from './aiToolkit/constants.js';import {FEDERATED_MEDIA_ASSET_MAX_COUNT,+ FEDERATED_MEDIA_MAX_VIDEO_FRAMES,federatedMediaInputAssetRefSchema,isFederatedMediaAudioPrompt,} from './federatedMediaWire.js';@@ -1016,7 +1017,7 @@ export const federatedMediaVideoJobSubmissionBaseSchema = federatedMediaJobRoutinegativePrompt: z.string().trim().max(4000).optional(),width: z.number().int().min(64).max(2048).optional(),height: z.number().int().min(64).max(2048).optional(),- numFrames: z.number().int().min(1).max(600).optional(),+ numFrames: z.number().int().min(1).max(FEDERATED_MEDIA_MAX_VIDEO_FRAMES).optional(),fps: z.number().int().min(1).max(60).optional(),steps: z.number().int().min(1).max(150).optional(),guidance: z.number().finite().min(0).max(30).optional(),diff --git a/server/lib/videoDisclosure.js b/server/lib/videoDisclosure.jsindex cf34184a16..ccd9337869 100644--- a/server/lib/videoDisclosure.js+++ b/server/lib/videoDisclosure.js@@ -27,7 +27,7 @@ import { ServerError } from './errorHandler.js';// Every shipped disclosure was checked against its upstream source on this// date. Bump it (and re-check) whenever an entry below changes.-export const VIDEO_DISCLOSURE_REVIEWED_AT = '2026-08-09';+export const VIDEO_DISCLOSURE_REVIEWED_AT = '2026-08-30';// License descriptors reused across entries. `url` points at the primary text// of the license, or at the model card when the card declares a custom license@@ -68,6 +68,10 @@ const RUNTIME_LICENSE = {name: 'Apache-2.0',url: 'https://github.com/PipeNetwork/minimax-h3-mlx/blob/fcd9e9b79a1d6018d91ac477c0968de1fa067e49/LICENSE',},+ minimax_h3_ref2va: {+ name: 'Apache-2.0',+ url: 'https://github.com/sawfwair/mere-run/blob/v0.47.0/LICENSE',+ },// The diffusers CUDA path executes no vendored source — the license that// governs the inference code is diffusers' own.cuda_video: { name: 'Apache-2.0', url: 'https://github.com/huggingface/diffusers/blob/main/LICENSE' },@@ -135,6 +139,17 @@ const customLicense = (repo) => ({ name: 'Custom — see model card', url: hfMod* Lightning entries include their `requiredWeights` LoRA files.*/export const VIDEO_MODEL_DISCLOSURES = Object.freeze({+ minimax_h3_ref2va_8bit: {+ shippedRepo: 'Sawfwair/MiniMax-H3-Ref2VA-MLX-8bit',+ disclosure: {+ modelCardUrl: hfModelCard('Sawfwair/MiniMax-H3-Ref2VA-MLX-8bit'),+ weightsLicense: MINIMAX_H3_WEIGHTS,+ runtimeLicense: RUNTIME_LICENSE.minimax_h3_ref2va,+ estimatedDownloadGb: 70.9,+ reviewedAt: VIDEO_DISCLOSURE_REVIEWED_AT,+ },+ termsGate: MINIMAX_H3_TERMS_GATE,+ },minimax_h3_8bit: {shippedRepo: 'pipenetwork/MiniMax-H3-MLX-8bit',disclosure: {diff --git a/server/lib/videoDurationProfiles.js b/server/lib/videoDurationProfiles.jsnew file mode 100644index 0000000000..7b800cea3e--- /dev/null+++ b/server/lib/videoDurationProfiles.js@@ -0,0 +1,14 @@+/**+ * Duration-driven video model contracts shared by the registry loader and+ * migrations. Keep this module pure: importing mediaModels.js from a migration+ * seeds the live registry as a side effect.+ */++export const LTX25_AUDIO_PROFILE = Object.freeze({+ id: 'ltx25_mlx_q8',+ repo: 'MrMofer/ltx-2.5-mlx-q8',+ revision: 'f1b56e7dc89f71a9af2cddac787b89ed22a8b7fc',+ audioDurationDriven: true,+ frameStride: 8,+ maxNumFrames: 1017,+});diff --git a/server/lib/videoModeProfiles.js b/server/lib/videoModeProfiles.jsindex 4d1561c842..945c6ddc6e 100644--- a/server/lib/videoModeProfiles.js+++ b/server/lib/videoModeProfiles.js@@ -20,10 +20,9 @@// narrow it, and narrowing to text-only would drop a user's own model out of// every picker.//-// `a2v` and the IC-LoRA remix ids are deliberately absent: they're ltx2-// *pipeline* capabilities, gated by runtime at both boundaries-// (A2V_REQUIRES_LTX2 / IC_LORA_REQUIRES_LTX2), and the remix ids are enumerated-// from the IC-LoRA weight registry rather than per model entry.+// `a2v` and the IC-LoRA remix ids are deliberately absent from the generic+// fallback. Audio-to-video is declared only by runtimes with an actual audio+// conditioning path; IC-LoRA remains an LTX-only pipeline capability.export const VIDEO_BASE_MODES = Object.freeze(['text', 'image', 'fflf', 'extend']);/**@@ -45,6 +44,9 @@ export const VIDEO_BASE_MODES = Object.freeze(['text', 'image', 'fflf', 'extend'* MLX port and the diffusers CUDA path expose the same three, because the* capability is the checkpoint partition's, not the runner's. Doubles as* the mode ceiling in videoGen/modeContract.js.+ * - `minimax_h3_ref2va` — mere.run's Ref2VA path requires one image and one+ * audio reference. PortOS windows long audio internally but exposes one+ * duration-driven a2v job to callers.* - `hunyuan` — compatibility-only shape for user-repointed or peer-synced* historical entries. The runtime is retired and renderArgs rejects it,* but retaining text-only prevents those records advertising modes the old@@ -58,12 +60,13 @@ const MINIMAX_H3_MODE_SET = Object.freeze(['text', 'image', 'fflf']);export const VIDEO_RUNTIME_MODES = Object.freeze({cuda_video: Object.freeze(['text', 'image']),mlx_video: Object.freeze(['text', 'image', 'fflf', 'extend']),- ltx2: Object.freeze(['text', 'image', 'fflf', 'extend']),- ltx25: Object.freeze(['text', 'image', 'fflf', 'extend']),+ ltx2: Object.freeze(['text', 'image', 'fflf', 'extend', 'a2v']),+ ltx25: Object.freeze(['text', 'image', 'fflf', 'extend', 'a2v']),wan22: Object.freeze(['text', 'image']),fastvideo: Object.freeze(['text', 'image']),minimax_h3: MINIMAX_H3_MODE_SET,minimax_h3_cuda: MINIMAX_H3_MODE_SET,+ minimax_h3_ref2va: Object.freeze(['a2v']),hunyuan: Object.freeze(['text']),});diff --git a/server/lib/videoModeProfiles.test.js b/server/lib/videoModeProfiles.test.jsindex ce0ffaee6f..54a6c1059a 100644--- a/server/lib/videoModeProfiles.test.js+++ b/server/lib/videoModeProfiles.test.js@@ -7,10 +7,11 @@ import {} from './videoModeProfiles.js';describe('VIDEO_RUNTIME_MODES', () => {- it('only enumerates base semantic modes', () => {+ it('only enumerates known semantic modes', () => {+ const knownModes = [...VIDEO_BASE_MODES, 'a2v'];for (const [runtime, modes] of Object.entries(VIDEO_RUNTIME_MODES)) {expect(modes.length, runtime).toBeGreaterThan(0);- for (const mode of modes) expect(VIDEO_BASE_MODES, `${runtime}/${mode}`).toContain(mode);+ for (const mode of modes) expect(knownModes, `${runtime}/${mode}`).toContain(mode);}});@@ -27,6 +28,15 @@ describe('VIDEO_RUNTIME_MODES', () => {expect(VIDEO_RUNTIME_MODES.minimax_h3).toContain('fflf');expect(VIDEO_RUNTIME_MODES.wan22).not.toContain('fflf');});++ it('declares audio-only semantics for MiniMax H3 Ref2VA', () => {+ expect(VIDEO_RUNTIME_MODES.minimax_h3_ref2va).toEqual(['a2v']);+ });++ it('declares A2V on both pinned LTX runtime generations', () => {+ expect(VIDEO_RUNTIME_MODES.ltx2).toContain('a2v');+ expect(VIDEO_RUNTIME_MODES.ltx25).toContain('a2v');+ });});describe('resolveVideoSupportedModes', () => {@@ -57,7 +67,7 @@ describe('applyVideoSupportedModes', () => {expect(out.map((e) => e.supportedModes)).toEqual([['text', 'image', 'fflf', 'extend'],['image'],- ['text', 'image', 'fflf', 'extend'],+ ['text', 'image', 'fflf', 'extend', 'a2v'],]);expect(entries[0].supportedModes).toBeUndefined();});diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex e1c02c1375..bf439d1095 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -65,7 +65,10 @@ import { saveUploadedGalleryVideo } from '../services/videoUpload.js';import { JSON_BODY_LIMIT_BYTES } from '../lib/uploadLimits.js';import { prepareRemoteMediaJob } from '../services/federatedMedia/remoteSubmission.js';import { collectRemoteInputAssets } from '../services/federatedMedia/inputAssets.js';-import { effectiveJobPrompt } from '../lib/federatedMediaWire.js';+import {+ FEDERATED_MEDIA_MAX_VIDEO_FRAMES,+ effectiveJobPrompt,+} from '../lib/federatedMediaWire.js';import { isRemoteMediaJob } from '../services/mediaJobQueue/remoteMediaJob.js';import { buildFederatedMediaRequest } from '../lib/federatedMediaRequest.js';import {@@ -110,12 +113,12 @@ export const isAudioMime = (mime, filename) => {return false;};-// FFLF accepts up to two image uploads (start and end frame); a2v takes-// one audio upload (audioFile); the IC-LoRA remix modes take one reference-// video upload (icReference). 100MB covers audio cases too (LTX-2's a2v-// expects only seconds of audio in practice). Per-fieldname mime filter-// rejects mismatched parts up-front so a stray .mp4 drag-drop can't get-// staged under any of these fields.+// FFLF accepts up to two image uploads (start and end frame); a2v takes one+// audio upload (audioFile); the IC-LoRA remix modes take one reference video+// upload (icReference). Audio duration is not capped: the 100MB transport cap+// is a file-size safety bound, so compressed inputs may be much longer than+// lossless PCM inputs. Per-fieldname mime filtering rejects mismatched parts+// up-front so a stray .mp4 drag-drop can't get staged under these fields.const frameImageUpload = uploadFields(['sourceImage', 'lastImage', 'audioFile', 'icReference'], {limits: { fileSize: 100 * 1024 * 1024 },fileFilter: (_req, file, cb) => {@@ -179,7 +182,7 @@ const listPreprocess = (v) => {// together so Grok eligibility and request validation cannot drift when a new// local-only knob is added.export const LOCAL_ONLY_VIDEO_PARAMS = Object.freeze({- numFrames: optionalInt(1, 1024, 'numFrames'),+ numFrames: optionalInt(1, FEDERATED_MEDIA_MAX_VIDEO_FRAMES, 'numFrames'),fps: optionalNum(1, 60, 'fps'),steps: optionalNum(1, 200, 'steps'),guidanceScale: optionalNum(0, 30, 'guidanceScale'),@@ -780,7 +783,10 @@ router.get('/models/:modelId/download', asyncHandler(async (req, res) => {const repos = modelDownloadTargets(model);if (repos.length === 0) throw new ServerError(`Model "${model.id}" has no HuggingFace repo on file.`, { status: 400, code: 'NO_REPO_FOR_MODEL' });const runtimeInfo = BYOV_RUNTIME_INFO[model.runtime];- const pythonPath = runtimeInfo && await isByovRuntimeReady(model.runtime) ? runtimeInfo.venvPython : null;+ const pythonPath = runtimeInfo?.hfDownloadPython !== false+ && await isByovRuntimeReady(model.runtime)+ ? runtimeInfo.venvPython+ : null;await startHfDownloadStream({ req, res, repos, pythonPath, force: req.query.force === '1' });}));@@ -1116,7 +1122,7 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {}const {- pythonPath, effectiveModelId, mode,+ pythonPath, effectiveModelId, effectiveNumFrames, mode,sourceImagePath, lastImagePath, audioFilePath, icReferencePaths,resolvedKeyframes, extendFromVideoPath,uploadedTempPath, uploadedTempPaths, loras, effectiveChunks, effectiveChunkPrompts, effectiveContextFrames,@@ -1131,7 +1137,9 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {modelId: body.modelId,width: body.width,height: body.height,- numFrames: body.numFrames,+ // Duration-driven A2V models derive this from ffprobe over the staged audio;+ // every other request passes the caller's value through unchanged.+ numFrames: effectiveNumFrames,fps: body.fps,steps: body.steps,guidanceScale: body.guidanceScale,diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex abcdb664bf..ccc23d5921 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -8,6 +8,11 @@ import { DEFAULT_CONTEXT_FRAMES, MAX_CONTEXT_FRAMES } from '../lib/videoContinuiconst compiledVisual = vi.hoisted(() => ({version: 1, compilerVersion: '1.0.0', status: 'locked', assets: [], adapters: [], omitted: [], warnings: [],}));+const probeVideoDuration = vi.hoisted(() => vi.fn(async () => 41.041281));+vi.mock('../lib/ffmpeg.js', async (importOriginal) => ({+ ...(await importOriginal()),+ probeVideoDuration,+}));const compileFableLoomVisualRequest = vi.hoisted(() => vi.fn(async ({ authoredPrompt, authoredNegativePrompt, sourceImagePath }) => ({prompt: authoredPrompt,negativePrompt: authoredNegativePrompt || '',@@ -92,7 +97,7 @@ vi.mock('../lib/pythonSetup.js', () => ({vi.mock('../services/videoGen/local.js', () => ({// The route checks `runtime` on the default model when validating a2v —- // include it so the a2v happy-path tests don't trip the A2V_REQUIRES_LTX2+ // include it so the a2v happy-path tests don't trip the runtime capability// guard. Tests that need to exercise the legacy runtime override the mock// per-test via mockReturnValueOnce.listVideoModels: vi.fn(() => [{@@ -119,7 +124,7 @@ vi.mock('../services/videoGen/local.js', () => ({// bring their own venv). Mirror the real export so the// "accepts BYOV-runtime when pythonPath missing" case passes and the// negative case (legacy mlx_video model) still 400s.- BYOV_VIDEO_RUNTIMES: new Set(['ltx2', 'wan22', 'minimax_h3']),+ BYOV_VIDEO_RUNTIMES: new Set(['ltx2', 'ltx25', 'wan22', 'minimax_h3', 'minimax_h3_ref2va']),// The route's /status response now surfaces the BYOV runtime list so the// client can drop its hardcoded copy. Mirror the real shape — only the// `id` and a couple of UI-display fields are read by /status.@@ -137,6 +142,13 @@ vi.mock('../services/videoGen/local.js', () => ({installEnvVar: 'INSTALL_MINIMAX_H3_CUDA', repoUrl: 'x', repoDir: '/tmp',installSourceLabel: 'pinned PyPI wheels',},+ minimax_h3_ref2va: {+ id: 'minimax_h3_ref2va', label: 'MiniMax H3 Ref2VA via mere.run',+ executable: '/tmp/mere.run', expectedVersion: '0.47.0',+ installEnvVar: 'INSTALL_MERERUN', repoUrl: 'https://github.com/sawfwair/mere-run',+ repoDir: '/tmp/mere-run', installSourceLabel: 'signed mere.run release',+ hfDownloadPython: false,+ },ltx2: { id: 'ltx2', label: 'LTX-2 MLX', venvPython: '/tmp/ltx2.py', installEnvVar: 'INSTALL_LTX2', repoUrl: 'x', repoDir: '/tmp' },wan22: {id: 'wan22', label: 'Wan 2.2 MLX', venvPython: '/tmp/wan22.py',@@ -330,6 +342,7 @@ describe('videoGen routes', () => {runtimeProbes.isByovRuntimeInstalled.mockReturnValue(false);runtimeProbes.isByovRuntimeReady.mockResolvedValue(false);runtimeProbes.isByovRuntimeCurrent.mockResolvedValue(false);+ probeVideoDuration.mockResolvedValue(41.041281);});describe('GET /status', () => {@@ -566,6 +579,32 @@ describe('videoGen routes', () => {}));});+ it('downloads Ref2VA through PortOS with the pinned snapshot and saved HF token path', async () => {+ const ref2va = {+ id: 'minimax_h3_ref2va_8bit',+ name: 'MiniMax H3 Ref2VA MLX 8-bit',+ runtime: 'minimax_h3_ref2va',+ repo: 'Sawfwair/MiniMax-H3-Ref2VA-MLX-8bit',+ revision: '61dc387ef1a7166425cdacd63c2340598dcc364f',+ supportedModes: ['a2v'],+ };+ videoGenService.listVideoModels.mockReturnValueOnce([ref2va]);++ const accepted = await request(app).get(`/api/video-gen/models/${ref2va.id}/download`);++ expect(accepted.status).toBe(200);+ expect(sseDownload.start).toHaveBeenCalledWith(expect.objectContaining({+ repos: [{+ repo: ref2va.repo,+ revision: ref2va.revision,+ only: [],+ }],+ pythonPath: null,+ force: false,+ }));+ expect(videoGenService.isByovRuntimeReady).not.toHaveBeenCalled();+ });+it('queues an H3 render without a recorded acknowledgement', async () => {videoGenService.listVideoModels.mockReturnValue([h3]);const render = await request(app).post('/api/video-gen/').send({@@ -1571,6 +1610,118 @@ describe('videoGen routes', () => {}));});+ it('queues LTX-2.5 image plus audio at the server-probed full duration', async () => {+ const ltx25 = {+ id: 'ltx25_mlx_q8',+ name: 'LTX-2.5 MLX Q8',+ runtime: 'ltx25',+ supportedModes: ['text', 'image', 'fflf', 'extend', 'a2v'],+ audioDurationDriven: true,+ frameStride: 8,+ maxNumFrames: 1017,+ };+ videoGenService.listVideoModels.mockReturnValueOnce([ltx25]);+ setPendingUpload({+ fieldname: 'audioFile',+ path: '/tmp/upload-forty-one-seconds.wav',+ originalname: 'forty-one-seconds.wav',+ mimetype: 'audio/wav',+ size: 4_000_000,+ });++ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'the tones awaken a dormant chamber',+ modelId: ltx25.id,+ mode: 'a2v',+ sourceImageFile: 'awakening-reference.png',+ fps: 24,+ numFrames: 121,+ });++ expect(r.status).toBe(200);+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'video',+ params: expect.objectContaining({+ modelId: ltx25.id,+ mode: 'a2v',+ sourceImagePath: '/mock/images/awakening-reference.png',+ numFrames: 985,+ audioFilePath: expect.stringMatching(/[\\/]mock[\\/]uploads[\\/]video-audio-.*\.wav$/),+ }),+ }));+ });++ it('queues MiniMax H3 Ref2VA only when image and audio conditioning are both present', async () => {+ const ref2va = {+ id: 'minimax_h3_ref2va_8bit',+ name: 'MiniMax H3 Ref2VA MLX 8-bit',+ runtime: 'minimax_h3_ref2va',+ supportedModes: ['a2v'],+ defaultFrames: 124,+ frameOptions: [107, 124, 141, 158],+ fpsOptions: [24],+ defaultWidth: 512,+ defaultHeight: 320,+ resolutionStep: 32,+ steps: 9,+ guidance: 0,+ samplerLocked: true,+ };+ videoGenService.listVideoModels.mockReturnValueOnce([ref2va]);+ setPendingUpload({+ fieldname: 'audioFile',+ path: '/tmp/upload-awakening.wav',+ originalname: 'awakening.wav',+ mimetype: 'audio/wav',+ size: 5_000_000,+ });++ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'the supplied tones release the chamber restraints',+ modelId: ref2va.id,+ mode: 'a2v',+ sourceImageFile: 'awakening-reference.png',+ });++ expect(r.status).toBe(200);+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'video',+ params: expect.objectContaining({+ modelId: ref2va.id,+ mode: 'a2v',+ sourceImagePath: '/mock/images/awakening-reference.png',+ audioFilePath: expect.stringMatching(/[\\/]mock[\\/]uploads[\\/]video-audio-.*\.wav$/),+ }),+ }));+ });++ it('rejects MiniMax H3 Ref2VA audio without a reference image', async () => {+ const ref2va = {+ id: 'minimax_h3_ref2va_8bit',+ name: 'MiniMax H3 Ref2VA MLX 8-bit',+ runtime: 'minimax_h3_ref2va',+ supportedModes: ['a2v'],+ };+ videoGenService.listVideoModels.mockReturnValueOnce([ref2va]);+ setPendingUpload({+ fieldname: 'audioFile',+ path: '/tmp/upload-awakening.wav',+ originalname: 'awakening.wav',+ mimetype: 'audio/wav',+ size: 5_000_000,+ });++ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'the supplied tones release the chamber restraints',+ modelId: ref2va.id,+ mode: 'a2v',+ });++ expect(r.status).toBe(400);+ expect(r.body.code).toBe('MINIMAX_H3_REF2VA_A2V_REQUIRES_IMAGE');+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();+ });+it('stages project audio and forwards the scene song offset for music-video a2v', async () => {getMusicVideoProject.mockResolvedValue({id: 'mv-example',@@ -1605,11 +1756,11 @@ describe('videoGen routes', () => {}));});- // a2v on a non-ltx2 model would fail later inside the worker- // (buildArgs throws A2V_REQUIRES_LTX2). The route catches it up front so+ // a2v on a runtime without audio conditioning would fail inside the worker.+ // The route catches it up front so// a typo / stale UI state doesn't pollute the persisted queue with a// doomed entry.- it('rejects mode=a2v paired with a non-ltx2 modelId (A2V_REQUIRES_LTX2)', async () => {+ it('rejects mode=a2v paired with a model that lacks audio conditioning', async () => {// Override the default ltx2-runtime model with a legacy mlx_video entry// for this single request.videoGenService.listVideoModels.mockReturnValueOnce([@@ -1628,8 +1779,8 @@ describe('videoGen routes', () => {modelId: 'ltx_legacy',});expect(r.status).toBe(400);- expect(r.body.error).toMatch(/ltx2-runtime/i);- expect(r.body.code).toBe('A2V_REQUIRES_LTX2');+ expect(r.body.error).toMatch(/audio-to-video runtime/i);+ expect(r.body.code).toBe('A2V_RUNTIME_UNSUPPORTED');expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();});diff --git a/server/services/federatedMedia/remoteSubmission.js b/server/services/federatedMedia/remoteSubmission.jsindex dc75b8224c..62d00f0dee 100644--- a/server/services/federatedMedia/remoteSubmission.js+++ b/server/services/federatedMedia/remoteSubmission.js@@ -13,7 +13,10 @@*/import { ServerError } from '../../lib/errorHandler.js';-import { FEDERATED_MEDIA_WIRE_VERSION } from '../../lib/federatedMediaWire.js';+import {+ FEDERATED_MEDIA_MAX_VIDEO_FRAMES,+ FEDERATED_MEDIA_WIRE_VERSION,+} from '../../lib/federatedMediaWire.js';import { federatedMediaVideoJobSubmissionBaseSchema } from '../../lib/validation.js';import { inputAssetRejection } from './inputAssets.js';@@ -44,8 +47,13 @@ export function negotiateVideoConstraints(request, capability) {console.log(`🌐 Federated render: adjusted fps from ${requestedFps} to ${bestFps} for ${capability.modelName || capability.modelId}`);// Rescale frame count to preserve clip duration (matches local reconciler)if (negotiated.numFrames !== undefined && Number.isFinite(Number(negotiated.numFrames)) && requestedFps > 0) {- const maxNumFrames = capability.maxNumFrames != null ? Number(capability.maxNumFrames) : 600;- const maxAllowed = Math.min(600, maxNumFrames > 0 ? maxNumFrames : 600);+ const maxNumFrames = capability.maxNumFrames != null+ ? Number(capability.maxNumFrames)+ : FEDERATED_MEDIA_MAX_VIDEO_FRAMES;+ const maxAllowed = Math.min(+ FEDERATED_MEDIA_MAX_VIDEO_FRAMES,+ maxNumFrames > 0 ? maxNumFrames : FEDERATED_MEDIA_MAX_VIDEO_FRAMES,+ );const rescaledFrames = Math.min(maxAllowed, Math.max(1, Math.round((Number(negotiated.numFrames) / requestedFps) * bestFps)));negotiated = { ...negotiated, numFrames: rescaledFrames };}@@ -68,7 +76,10 @@ export function negotiateVideoConstraints(request, capability) {const maxNumFrames = capability.maxNumFrames != null ? Number(capability.maxNumFrames) : null;const validOptions = capability.frameOptions.map(Number)- .filter((opt) => Number.isInteger(opt) && opt >= 1 && opt <= 600 && (maxNumFrames === null || opt <= maxNumFrames))+ .filter((opt) => Number.isInteger(opt)+ && opt >= 1+ && opt <= FEDERATED_MEDIA_MAX_VIDEO_FRAMES+ && (maxNumFrames === null || opt <= maxNumFrames)).sort((a, b) => a - b);if (validOptions.length === 0) {throw new ServerError(diff --git a/server/services/federatedMedia/remoteSubmission.test.js b/server/services/federatedMedia/remoteSubmission.test.jsindex 7d04288630..21135e6c9e 100644--- a/server/services/federatedMedia/remoteSubmission.test.js+++ b/server/services/federatedMedia/remoteSubmission.test.js@@ -113,7 +113,7 @@ describe('negotiateVideoConstraints', () => {expect(snappedWidth.height).toBe(1344);});- it('clamps rescaled frame count to maxNumFrames and 600', () => {+ it('clamps rescaled frame count to the capability maximum', () => {const capability = {modelId: 'wan22',frameStride: 4,@@ -127,6 +127,20 @@ describe('negotiateVideoConstraints', () => {expect(result.numFrames).toBe(297);});+ it('preserves the 1017-frame LTX-2.5 capability through fps negotiation', () => {+ const capability = {+ modelId: 'ltx25_mlx_q8',+ frameStride: 8,+ fpsOptions: [24],+ maxNumFrames: 1017,+ };++ expect(negotiateVideoConstraints({ numFrames: 1017, fps: 24 }, capability).numFrames).toBe(1017);+ // 800 frames at 16 fps would rescale past the provider ceiling; clamp to+ // 1017, which is already legal on the 8n+1 grid.+ expect(negotiateVideoConstraints({ numFrames: 800, fps: 16 }, capability).numFrames).toBe(1017);+ });+it('tie-breaks equal aspect ratios by closest area and ignores out-of-bounds options', () => {const capability = {modelId: 'custom',diff --git a/server/services/federatedMediaProvider.js b/server/services/federatedMediaProvider.jsindex 9e78ebae2f..da45f4366a 100644--- a/server/services/federatedMediaProvider.js+++ b/server/services/federatedMediaProvider.js@@ -22,6 +22,7 @@ import {FEDERATED_MEDIA_ASSET_MAX_COUNT,FEDERATED_MEDIA_ASSET_MIME_TYPES,FEDERATED_MEDIA_FEATURES,+ FEDERATED_MEDIA_MAX_VIDEO_FRAMES,FEDERATED_MEDIA_RESULT_EXTENSION,FEDERATED_MEDIA_STALE_AFTER_MS,FEDERATED_MEDIA_WIRE_VERSION,@@ -454,15 +455,21 @@ async function localGeneratorCapabilities(kind, pythonPath, { models, configured? Number(model.frameStride): null;const validFrameOptions = Array.isArray(model?.frameOptions)- ? model.frameOptions.filter((f) => Number.isInteger(f) && f >= 1 && f <= 600).slice(0, 100)+ ? model.frameOptions+ .filter((f) => Number.isInteger(f) && f >= 1 && f <= FEDERATED_MEDIA_MAX_VIDEO_FRAMES)+ .slice(0, 100): [];const validFpsOptions = Array.isArray(model?.fpsOptions)? model.fpsOptions.filter((f) => Number.isInteger(f) && f >= 1 && f <= 60).slice(0, 20): [];- const rawMaxNumFrames = Number.isInteger(Number(model?.maxNumFrames)) && Number(model.maxNumFrames) >= 1 && Number(model.maxNumFrames) <= 600+ const rawMaxNumFrames = Number.isInteger(Number(model?.maxNumFrames))+ && Number(model.maxNumFrames) >= 1+ && Number(model.maxNumFrames) <= FEDERATED_MEDIA_MAX_VIDEO_FRAMES? Number(model.maxNumFrames): (validFrameOptions.length > 0 ? Math.max(...validFrameOptions) : null);- const maxNumFrames = rawMaxNumFrames && rawMaxNumFrames <= 600 ? rawMaxNumFrames : null;+ const maxNumFrames = rawMaxNumFrames && rawMaxNumFrames <= FEDERATED_MEDIA_MAX_VIDEO_FRAMES+ ? rawMaxNumFrames+ : null;const validResolutions = Array.isArray(model?.resolutionOptions)? model.resolutionOptions.filter((opt) => Number.isInteger(Number(opt?.w)) && Number.isInteger(Number(opt?.h))diff --git a/server/services/federatedMediaProvider.test.js b/server/services/federatedMediaProvider.test.jsindex b2b638da64..bc16cf2bb3 100644--- a/server/services/federatedMediaProvider.test.js+++ b/server/services/federatedMediaProvider.test.js@@ -883,6 +883,7 @@ describe('federated media provider — prompt-free status and projection payloadrepo: 'example/wan22',supportedModes: ['text'],frameStride: 4,+ maxNumFrames: 1017,frameOptions: [25, 49, 73, 97, 121],resolutionOptions: [{ label: '1344x768 (16:9)', w: 1344, h: 768 }],}];@@ -909,7 +910,7 @@ describe('federated media provider — prompt-free status and projection payload});expect(videoCap).toMatchObject({frameStride: 4,- maxNumFrames: 121,+ maxNumFrames: 1017,frameOptions: [25, 49, 73, 97, 121],resolutionOptions: [{ label: '1344x768 (16:9)', w: 1344, h: 768 }],});diff --git a/server/services/videoGen/audioDuration.js b/server/services/videoGen/audioDuration.jsnew file mode 100644index 0000000000..41b3da46fe--- /dev/null+++ b/server/services/videoGen/audioDuration.js@@ -0,0 +1,19 @@+/**+ * Convert an audio duration into the smallest frame canvas that covers it on a+ * runtime's causal-VAE temporal grid. Kept pure so route preparation can reject+ * an over-limit upload before it reaches the persistent media queue.+ */+export const audioDurationToFrames = (durationSeconds, fps, frameStride) => {+ const duration = Number(durationSeconds);+ const rate = Number(fps);+ const stride = Number(frameStride);+ if (!Number.isFinite(duration) || duration <= 0) {+ throw new TypeError('durationSeconds must be positive');+ }+ if (!Number.isFinite(rate) || rate <= 0) throw new TypeError('fps must be positive');+ if (!Number.isInteger(stride) || stride <= 0) {+ throw new TypeError('frameStride must be a positive integer');+ }+ const targetFrames = duration * rate;+ return Math.max(1, Math.ceil((targetFrames - 1) / stride) * stride + 1);+};diff --git a/server/services/videoGen/audioDuration.test.js b/server/services/videoGen/audioDuration.test.jsnew file mode 100644index 0000000000..617191d001--- /dev/null+++ b/server/services/videoGen/audioDuration.test.js@@ -0,0 +1,17 @@+import { describe, expect, it } from 'vitest';+import { audioDurationToFrames } from './audioDuration.js';++describe('audioDurationToFrames', () => {+ it('covers the whole source while snapping up to LTX 8n+1', () => {+ expect(audioDurationToFrames(41.041281, 24, 8)).toBe(985);+ expect(audioDurationToFrames(20, 24, 8)).toBe(481);+ expect(audioDurationToFrames(20.01, 24, 8)).toBe(481);+ expect(audioDurationToFrames(20.05, 24, 8)).toBe(489);+ });++ it('rejects invalid inputs instead of collapsing them to a default clip', () => {+ expect(() => audioDurationToFrames(0, 24, 8)).toThrow(/durationSeconds/);+ expect(() => audioDurationToFrames(5, 0, 8)).toThrow(/fps/);+ expect(() => audioDurationToFrames(5, 24, 0)).toThrow(/frameStride/);+ });+});diff --git a/server/services/videoGen/generateVideo.js b/server/services/videoGen/generateVideo.jsindex 57edc38a49..5f3dc120e4 100644--- a/server/services/videoGen/generateVideo.js+++ b/server/services/videoGen/generateVideo.js@@ -30,7 +30,7 @@ import {isHardwareCompatible,withHardwareCompatibility,} from '../../lib/systemCapabilities.js';-import { findFfmpeg } from '../../lib/ffmpeg.js';+import { findFfmpeg, findFfprobe } from '../../lib/ffmpeg.js';import { inspectModelCache, findCachedRepoFile, findCachedRepoFiles } from '../../lib/hfCache.js';import { safeChildProcessOptions } from '../../lib/processEnv.js';import { describeRenderConditioning, RENDER_INPUTS_VERSION } from './generateVideoHelpers.js';@@ -281,6 +281,23 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m}ltxModelPath = cache.snapshotPath;}+ let ref2vaModelPath = null;+ if (model.runtime === 'minimax_h3_ref2va') {+ if (typeof model.revision !== 'string' || !model.revision) {+ throw new ServerError(+ `MiniMax H3 Ref2VA model "${modelId}" is missing an immutable Hugging Face revision.`,+ { status: 500, code: 'VIDEO_MODEL_MISCONFIGURED' },+ );+ }+ const cache = await inspectModelCache(model.repo, { revision: model.revision });+ if (!cache.cached || !cache.snapshotPath) {+ throw new ServerError(+ `${model.name} revision ${model.revision.slice(0, 8)} is not fully cached. Download or repair it in Video Gen before rendering.`,+ { status: 400, code: 'MINIMAX_H3_REF2VA_MODEL_NOT_CACHED' },+ );+ }+ ref2vaModelPath = cache.snapshotPath;+ }// Substituted prompt conditioner (#4081). `resolveVideoTextEncoder` returns// null for the stock choice — the whole override path stays dormant then —// and throws a 400 when the model's runtime has no remap for the requested@@ -542,6 +559,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m}const hasMultiKeyframes = Array.isArray(keyframes) && keyframes.length >= 2;const ffmpeg = (sourceImagePath || lastImageWillBeUsed || hasMultiKeyframes) ? await findFfmpeg() : null;+ const ffprobe = model.runtime === 'minimax_h3_ref2va' ? await findFfprobe() : null;const resizeImage = async (srcPath, tag) => {if (!srcPath || !ffmpeg) return { resolved: srcPath, tempPath: null };const resizedPath = join(tmpdir(), `resized-${tag}-${jobId}.png`);@@ -801,7 +819,50 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m// logic of the spawn-error handler so failure modes converge.let bin, args;try {- ({ bin, args } = buildArgs({ pythonPath, modelId, model: loraCapableModel, wanModelPath, wanRequiredWeights, ltxModelPath, prompt: renderPrompt, negativePrompt, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, steps: actualSteps, stage2Steps: actualStage2Steps, guidance: actualGuidance, seed: actualSeed, tiling, disableAudio, sourceImagePath: resolvedSourceImage, lastImagePath: resolvedLastImage, keyframes: resolvedKeyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength: actualImageStrength, i2vReferenceMode: effectiveReferenceMode, textEncoderRepo: actualTextEncoderRepo, textEncoder: resolvedTextEncoder, outputPath, previewDir: stepwiseDir, loras: resolvedLoras, icReferencePaths: resolvedIcReferencePaths, icLoraWeightPath, icStrength: actualIcStrength, icAttentionStrength: actualIcAttentionStrength, icSkipStage2, speedProfile, draftDecoder }));+ ({ bin, args } = buildArgs({+ pythonPath,+ modelId,+ model: loraCapableModel,+ wanModelPath,+ wanRequiredWeights,+ ltxModelPath,+ ref2vaModelPath,+ prompt: renderPrompt,+ negativePrompt,+ width: w,+ height: h,+ numFrames: parsedNumFrames,+ fps: parsedFps,+ steps: actualSteps,+ stage2Steps: actualStage2Steps,+ guidance: actualGuidance,+ seed: actualSeed,+ tiling,+ disableAudio,+ sourceImagePath: resolvedSourceImage,+ lastImagePath: resolvedLastImage,+ keyframes: resolvedKeyframes,+ extendFromVideoPath,+ audioFilePath,+ audioStartSec,+ mode,+ imageStrength: actualImageStrength,+ i2vReferenceMode: effectiveReferenceMode,+ textEncoderRepo: actualTextEncoderRepo,+ textEncoder: resolvedTextEncoder,+ outputPath,+ previewDir: stepwiseDir,+ loras: resolvedLoras,+ icReferencePaths: resolvedIcReferencePaths,+ icLoraWeightPath,+ icStrength: actualIcStrength,+ icAttentionStrength: actualIcAttentionStrength,+ icSkipStage2,+ speedProfile,+ draftDecoder,+ ffmpegPath: ffmpeg,+ ffprobePath: ffprobe,+ }));} catch (err) {job.status = 'error';const reason = err.message || 'Failed to build video gen args';diff --git a/server/services/videoGen/minimaxH3Controls.js b/server/services/videoGen/minimaxH3Controls.jsindex dd6c18926d..eb2a374046 100644--- a/server/services/videoGen/minimaxH3Controls.js+++ b/server/services/videoGen/minimaxH3Controls.js@@ -15,7 +15,7 @@* caller with teardown to run (`await cleanupStaged()`) can do it before* throwing. Same convention as `videoModeContractError`.*- * Covers BOTH H3 runtimes. The controls are facts about the checkpoint — 24+ * Covers every H3 runtime. The controls are facts about the checkpoint — 24* fps, joint video+audio, CFG-distilled, a 17n+5 frame grid — so the MLX port* and the diffusers CUDA path enforce the identical set. The one thing that* genuinely differs is the legal frame WINDOW (diffusers requires the snappeddiff --git a/server/services/videoGen/modeContract.js b/server/services/videoGen/modeContract.jsindex f1f9dcab2f..04898d44f0 100644--- a/server/services/videoGen/modeContract.js+++ b/server/services/videoGen/modeContract.js@@ -55,9 +55,11 @@ const DEFAULT_MESSAGES = Object.freeze({imageRequiresFirst: ({ model }) => `${model.name} image-to-video requires a source image — choose an existing gallery image or upload one.`,imageLastConflict: ({ model }) => `${model.name} image-to-video takes a single first-frame image — switch to FFLF mode to use a last frame.`,fflfRequiresImage: ({ model }) => `${model.name} FFLF requires a first and/or last frame image.`,+ a2vRequiresFirst: ({ model }) => `${model.name} audio-to-video requires a reference image.`,+ a2vRequiresAudio: ({ model }) => `${model.name} audio-to-video requires an audio file.`,});-// H3's two runtimes share ONE row: the mode rules come from the fl2va+// H3's text/image runtimes share ONE row: the mode rules come from the fl2va// checkpoint partition, not from the MLX / diffusers runner in front of it, and// the error codes are the same `MINIMAX_H3_*` contract on both — so both keys// below reference this object rather than each carrying a copy, which is@@ -77,6 +79,19 @@ const MINIMAX_H3_CONTRACT = Object.freeze({}),});+const MINIMAX_H3_REF2VA_CONTRACT = Object.freeze({+ codePrefix: 'MINIMAX_H3_REF2VA',+ modeCeiling: VIDEO_RUNTIME_MODES.minimax_h3_ref2va,+ extraConditioningUnsupported: false,+ a2vRequiresFirst: true,+ a2vRequiresAudio: true,+ messages: Object.freeze({+ modeUnsupported: ({ model }) => `${model.name} supports image-and-audio to video only.`,+ a2vRequiresFirst: () => 'MiniMax H3 Ref2VA audio-to-video requires a reference image — choose an existing gallery image or upload one.',+ a2vRequiresAudio: () => 'MiniMax H3 Ref2VA audio-to-video requires an audio file.',+ }),+});+/*** The per-runtime rows. `modeCeiling` is the set of modes the *helper* has* arguments for — a `null` ceiling means the registry entry's `supportedModes`@@ -94,8 +109,7 @@ const VIDEO_MODE_CONTRACTS = Object.freeze({// wan22 row (text + image) rather than leaving it unconstrained.modeCeiling: null,// The wan22 lane rejects multi-keyframe / extend / audio / IC inputs by- // runtime elsewhere (KEYFRAMES_REQUIRE_LTX2, A2V_REQUIRES_LTX2,- // IC_LORA_REQUIRES_LTX2), so folding them in here would double-report.+ // runtime elsewhere, so folding them in here would double-report.extraConditioningUnsupported: false,messages: {modeUnsupported: ({ model, requestedMode }) => `${model.name} does not support ${requestedMode}-to-video. Choose a compatible Wan model.`,@@ -123,6 +137,7 @@ const VIDEO_MODE_CONTRACTS = Object.freeze({},minimax_h3: MINIMAX_H3_CONTRACT,minimax_h3_cuda: MINIMAX_H3_CONTRACT,+ minimax_h3_ref2va: MINIMAX_H3_REF2VA_CONTRACT,});// An empty array is "no references", not "references present" — and an empty@@ -172,7 +187,13 @@ export const videoModeContractError = ({}) => {const contract = VIDEO_MODE_CONTRACTS[model?.runtime];if (!contract) return null;- const { codePrefix, modeCeiling, extraConditioningUnsupported } = contract;+ const {+ codePrefix,+ modeCeiling,+ extraConditioningUnsupported,+ a2vRequiresFirst,+ a2vRequiresAudio,+ } = contract;const messages = { ...DEFAULT_MESSAGES, ...contract.messages };const requestedMode = mode || (hasFirstImage ? 'image' : 'text');const declaredModes = resolveVideoSupportedModes(model);@@ -197,6 +218,12 @@ export const videoModeContractError = ({if (requestedMode === 'image' && !hasFirstImage) {return fail('imageRequiresFirst', `${codePrefix}_I2V_REQUIRES_IMAGE`);}+ if (requestedMode === 'a2v' && a2vRequiresFirst && !hasFirstImage) {+ return fail('a2vRequiresFirst', `${codePrefix}_A2V_REQUIRES_IMAGE`);+ }+ if (requestedMode === 'a2v' && a2vRequiresAudio && !isPresent(audioFile)) {+ return fail('a2vRequiresAudio', `${codePrefix}_A2V_REQUIRES_AUDIO`);+ }// The last-frame pair rules only mean something on a runtime that can anchor// one, so they key off the resolved mode set rather than the runtime name — a// profile that never declares 'fflf' (every wan22 profile today) keeps itsdiff --git a/server/services/videoGen/modeContract.test.js b/server/services/videoGen/modeContract.test.jsindex bbf8a5b7cb..ccd9f7fb1d 100644--- a/server/services/videoGen/modeContract.test.js+++ b/server/services/videoGen/modeContract.test.js@@ -10,10 +10,11 @@ import {const wan = (supportedModes) => ({ runtime: 'wan22', name: 'Example Wan Profile', supportedModes });const fv = (supportedModes) => ({ runtime: 'fastvideo', name: 'Example FastVideo Model', supportedModes });const h3 = (supportedModes) => ({ runtime: 'minimax_h3', name: 'Example H3', supportedModes });+const ref2va = (supportedModes = ['a2v']) => ({ runtime: 'minimax_h3_ref2va', name: 'Example H3 Ref2VA', supportedModes });describe('videoModeContractError — shared gate', () => {it('gates exactly the runtimes that declare a contract row', () => {- expect([...VIDEO_MODE_GATED_RUNTIMES].sort()).toEqual(['fastvideo', 'minimax_h3', 'minimax_h3_cuda', 'wan22']);+ expect([...VIDEO_MODE_GATED_RUNTIMES].sort()).toEqual(['fastvideo', 'minimax_h3', 'minimax_h3_cuda', 'minimax_h3_ref2va', 'wan22']);});it.each(['ltx2', 'mlx_video', undefined])('leaves the %s runtime ungated', (runtime) => {@@ -34,6 +35,24 @@ describe('videoModeContractError — shared gate', () => {});});+describe('videoModeContractError — minimax_h3_ref2va', () => {+ it('requires both a source image and an audio file', () => {+ expect(videoModeContractError({ model: ref2va(), mode: 'a2v', audioFile: '/mock/audio.wav' }))+ .toMatchObject({ code: 'MINIMAX_H3_REF2VA_A2V_REQUIRES_IMAGE' });+ expect(videoModeContractError({ model: ref2va(), mode: 'a2v', hasFirstImage: true }))+ .toMatchObject({ code: 'MINIMAX_H3_REF2VA_A2V_REQUIRES_AUDIO' });+ expect(videoModeContractError({+ model: ref2va(), mode: 'a2v', hasFirstImage: true, audioFile: '/mock/audio.wav',+ })).toBeNull();+ });++ it('rejects non-a2v modes even when a registry was hand-widened', () => {+ expect(videoModeContractError({+ model: ref2va(['a2v', 'image']), mode: 'image', hasFirstImage: true,+ })).toMatchObject({ code: 'MINIMAX_H3_REF2VA_MODE_UNSUPPORTED' });+ });+});+describe('videoModeContractError — wan22 codes and messages', () => {it('rejects a mode the profile does not declare', () => {const err = videoModeContractError({ model: wan(['text']), mode: 'image', hasFirstImage: true });diff --git a/server/services/videoGen/prepareParams.js b/server/services/videoGen/prepareParams.jsindex b3a2f03362..8f157782f6 100644--- a/server/services/videoGen/prepareParams.js+++ b/server/services/videoGen/prepareParams.js@@ -31,9 +31,14 @@ import { randomUUID } from 'crypto';import { join, extname } from 'path';import { ServerError } from '../../lib/errorHandler.js';import { PATHS, ensureDir, resolveGalleryImage } from '../../lib/fileUtils.js';-import { safeUnder } from '../../lib/ffmpeg.js';+import { probeVideoDuration, safeUnder } from '../../lib/ffmpeg.js';import { RENDER_TARGET } from '../../lib/renderTargets.js';-import { videoLoraFamily, isMiniMaxH3Runtime, isLtx2FamilyRuntime } from '../../lib/runners.js';+import {+ videoLoraFamily,+ isMiniMaxH3Runtime,+ isLtx2FamilyRuntime,+ isAudioToVideoRuntime,+} from '../../lib/runners.js';import {isStockTextEncoder, supportsVideoTextEncoder, videoTextEncoderUnsupportedError,} from '../../lib/videoTextEncoders.js';@@ -65,6 +70,7 @@ import {// module mock local.js wholesale, and a mocked rule table would assert nothing.import { videoModeContractError, videoChainUnsupportedError, videoReferenceModeError } from './modeContract.js';import { resolveByovRuntimeLoraCapable, videoLoraUnsupportedError } from './runtimes.js';+import { audioDurationToFrames } from './audioDuration.js';// Retries reuse persisted worker parameters instead of passing through the// multipart preparation path. Keep the model/mode gates here so a model edit@@ -136,10 +142,13 @@ export async function validateVideoRetryParams(params = {}) {);}}- if ((mode === 'a2v' || icLoraSpecForMode(mode)) && !isLtx2FamilyRuntime(model.runtime)) {+ if ((mode === 'a2v' && !isAudioToVideoRuntime(model.runtime))+ || (icLoraSpecForMode(mode) && !isLtx2FamilyRuntime(model.runtime))) {throw new ServerError(- `${mode} mode requires an ltx2-runtime model. Model "${modelId}" runs on "${model.runtime || 'mlx_video'}".`,- { status: 400, code: mode === 'a2v' ? 'A2V_REQUIRES_LTX2' : 'IC_LORA_REQUIRES_LTX2' },+ mode === 'a2v'+ ? `a2v mode requires an audio-to-video runtime. Model "${modelId}" runs on "${model.runtime || 'mlx_video'}".`+ : `${mode} mode requires an ltx2-runtime model. Model "${modelId}" runs on "${model.runtime || 'mlx_video'}".`,+ { status: 400, code: mode === 'a2v' ? 'A2V_RUNTIME_UNSUPPORTED' : 'IC_LORA_REQUIRES_LTX2' },);}if (Array.isArray(params.loras) && params.loras.length > 0 && !videoLoraFamily(model)) {@@ -547,16 +556,15 @@ async function resolvePreparedParams({{ status: 400, code: 'IC_LORA_MODE_MISMATCH' },);}- // a2v needs the dgrauet runtime — the legacy mlx_video pipeline has no- // audio-conditioned mode. The worker also catches this in buildArgs (with- // A2V_REQUIRES_LTX2), but checking here keeps the route's "fail fast+ // a2v needs a runtime with an audio-conditioning path. The worker also+ // catches this in buildArgs, but checking here keeps the route's "fail fast// before enqueue" contract so a bad modelId can't pollute the persisted// queue with a doomed entry.- if (body.mode === 'a2v' && effectiveModel && !isLtx2FamilyRuntime(effectiveModel.runtime)) {+ if (body.mode === 'a2v' && effectiveModel && !isAudioToVideoRuntime(effectiveModel.runtime)) {await cleanupStaged();throw new ServerError(- `a2v mode requires an ltx2-runtime model. Model "${effectiveModelId}" runs on "${effectiveModel.runtime || 'mlx_video'}".`,- { status: 400, code: 'A2V_REQUIRES_LTX2' },+ `a2v mode requires an audio-to-video runtime. Model "${effectiveModelId}" runs on "${effectiveModel.runtime || 'mlx_video'}".`,+ { status: 400, code: 'A2V_RUNTIME_UNSUPPORTED' },);}// Chunk chaining needs image-to-video on any runtime — the same rule@@ -586,6 +594,7 @@ async function resolvePreparedParams({hasLastImage: hasDeclaredLastImage,keyframes: body.keyframes,extendFromVideo: body.extendFromVideoId,+ audioFile: uploads.audioFile || body.musicVideo,});if (modeContractError) {await cleanupStaged();@@ -644,6 +653,7 @@ async function resolvePreparedParams({let sourceImagePath = null;let lastImagePath = null;let audioFilePath = null;+ let effectiveNumFrames = body.numFrames;let icReferenceUploadPath = null;let uploadedTempPath = null;const extraUploadedTempPaths = [];@@ -676,6 +686,7 @@ async function resolvePreparedParams({hasFirstImage: Boolean(sourceImagePath),hasLastImage: hasDeclaredLastImage,sourceResolved: true,+ audioFile: uploads.audioFile || body.musicVideo,keyframes: body.keyframes,extendFromVideo: body.extendFromVideoId,});@@ -774,6 +785,45 @@ async function resolvePreparedParams({audioFilePath = await stageExistingAudioDurable(sourceAudioPath);extraUploadedTempPaths.push(audioFilePath);}+ // A direct-upload LTX-2.5 A2V request follows the whole audio file. The MLX+ // pipeline still requires an explicit 8n+1 frame canvas, so derive that canvas+ // from the durable upload rather than trusting browser metadata (or forcing an+ // API caller to probe the file itself). MiniMax Ref2VA is deliberately excluded:+ // its wrapper windows arbitrary-length audio and owns its duration internally.+ // Music-video jobs also keep their explicit scene canvas because they select a+ // slice of a longer song with audioStartSec.+ if (body.mode === 'a2v' && audioFilePath+ && effectiveModel?.audioDurationDriven === true+ && effectiveModel?.arbitraryLengthAudio !== true+ && !body.musicVideo) {+ const durationSeconds = await probeVideoDuration(audioFilePath);+ if (durationSeconds == null) {+ await cleanupStaged();+ throw new ServerError(+ 'Could not read the uploaded audio duration. Upload a valid WAV, MP3, M4A, AAC, FLAC, or OGG file.',+ { status: 400, code: 'VIDEO_GEN_AUDIO_DURATION_UNREADABLE' },+ );+ }+ const frameStride = Number(effectiveModel.frameStride);+ const fps = Number(body.fps ?? 24);+ const maxNumFrames = Number(effectiveModel.maxNumFrames);+ if (!Number.isInteger(frameStride) || frameStride <= 0+ || !Number.isInteger(maxNumFrames) || maxNumFrames <= 0) {+ await cleanupStaged();+ throw new ServerError(+ `${effectiveModel.name} is missing its duration-driven frameStride/maxNumFrames contract.`,+ { status: 500, code: 'VIDEO_MODEL_MISCONFIGURED' },+ );+ }+ effectiveNumFrames = audioDurationToFrames(durationSeconds, fps, frameStride);+ if (effectiveNumFrames > maxNumFrames) {+ await cleanupStaged();+ throw new ServerError(+ `${effectiveModel.name} supports up to ${(maxNumFrames / fps).toFixed(1)}s in one audio-to-video render; this file is ${durationSeconds.toFixed(1)}s. Use MiniMax H3 Ref2VA for longer audio, or trim the file.`,+ { status: 400, code: 'VIDEO_GEN_AUDIO_TOO_LONG' },+ );+ }+ }if (uploads.icReference) {// IC-LoRA reference clip — same durable staging + cleanup tracking as the// audio upload above. A history-picked reference needs neither (it already@@ -1032,6 +1082,7 @@ async function resolvePreparedParams({pythonPath,effectiveModel,effectiveModelId,+ effectiveNumFrames,mode: body.mode,sourceImagePath,lastImagePath,diff --git a/server/services/videoGen/prepareParams.test.js b/server/services/videoGen/prepareParams.test.jsindex 11053439ce..e2f243b6f1 100644--- a/server/services/videoGen/prepareParams.test.js+++ b/server/services/videoGen/prepareParams.test.js@@ -6,6 +6,12 @@ import { resolve as resolvePath } from 'path';// on Windows, so compare against a separator-normalized copy.const posix = (p) => String(p).split('\\').join('/');+const probeVideoDuration = vi.hoisted(() => vi.fn(async () => 41.041281));+vi.mock('../../lib/ffmpeg.js', async (importOriginal) => ({+ ...(await importOriginal()),+ probeVideoDuration,+}));+vi.mock('../settings.js', () => ({getSettings: vi.fn(async () => ({imageGen: { local: { pythonPath: '/usr/bin/python3' }, grok: { enabled: true, grokPath: '/usr/bin/grok', aspectRatio: '16:9' } },@@ -19,7 +25,7 @@ vi.mock('./local.js', () => ({listVideoModels: vi.fn(() => [{ id: 'ltx2_unified', name: 'LTX-2 Unified', runtime: 'ltx2' }]),defaultVideoModelId: vi.fn(() => 'ltx2_unified'),loadHistory: vi.fn(async () => []),- BYOV_VIDEO_RUNTIMES: new Set(['ltx2', 'wan22', 'minimax_h3']),+ BYOV_VIDEO_RUNTIMES: new Set(['ltx2', 'ltx25', 'wan22', 'minimax_h3']),DEFAULT_NUM_FRAMES: 121,}));@@ -134,6 +140,7 @@ describe('cleanupMultipartTemp', () => {describe('prepareVideoGenParams', () => {beforeEach(() => {vi.clearAllMocks();+ probeVideoDuration.mockResolvedValue(41.041281);listVideoModels.mockReturnValue([{id: 'ltx2_unified', name: 'LTX-2 Unified', runtime: 'ltx2', supportedModes: ['text', 'image', 'fflf'],}]);@@ -159,6 +166,51 @@ describe('prepareVideoGenParams', () => {expect(unlink).toHaveBeenCalledWith('/tmp/multipart-sourceImage-frame.png');});+ it('probes LTX-2.5 audio and derives a full-duration 8n+1 frame canvas', async () => {+ const ltx25 = {+ id: 'ltx25_mlx_q8',+ name: 'LTX-2.5 MLX Q8',+ runtime: 'ltx25',+ supportedModes: ['text', 'image', 'fflf', 'extend', 'a2v'],+ audioDurationDriven: true,+ frameStride: 8,+ maxNumFrames: 1017,+ };+ listVideoModels.mockReturnValue([ltx25]);++ const prepared = await prepare(+ { modelId: ltx25.id, mode: 'a2v', fps: 24, numFrames: 121 },+ { sourceImage: upload('sourceImage'), audioFile: upload('audioFile', 'awakening.wav') },+ );++ expect(probeVideoDuration).toHaveBeenCalledWith(prepared.audioFilePath);+ expect(prepared.effectiveNumFrames).toBe(985);+ expect(posix(prepared.sourceImagePath)).toMatch(/^\/mock\/uploads\/video-source-.*\.png$/);+ expect(posix(prepared.audioFilePath)).toMatch(/^\/mock\/uploads\/video-audio-.*\.wav$/);+ });++ it('rejects and cleans up LTX-2.5 audio beyond the single-pass boundary', async () => {+ const ltx25 = {+ id: 'ltx25_mlx_q8',+ name: 'LTX-2.5 MLX Q8',+ runtime: 'ltx25',+ supportedModes: ['a2v'],+ audioDurationDriven: true,+ frameStride: 8,+ maxNumFrames: 1017,+ };+ listVideoModels.mockReturnValue([ltx25]);+ probeVideoDuration.mockResolvedValue(60);++ await expect(prepare(+ { modelId: ltx25.id, mode: 'a2v', fps: 24, numFrames: 121 },+ { audioFile: upload('audioFile', 'one-minute.wav') },+ )).rejects.toMatchObject({ status: 400, code: 'VIDEO_GEN_AUDIO_TOO_LONG' });+ expect([...new Set(unlinkedDurablePaths())]).toEqual([+ expect.stringMatching(/^\/mock\/uploads\/video-audio-.*\.wav$/),+ ]);+ });+it('short-circuits for grok without staging local-only inputs', async () => {const prepared = await prepare({ backend: 'grok', sourceImageFile: 'still.png' });expect(prepared.backend).toBe('grok');diff --git a/server/services/videoGen/ref2vaPlan.js b/server/services/videoGen/ref2vaPlan.jsnew file mode 100644index 0000000000..07fd214bfc--- /dev/null+++ b/server/services/videoGen/ref2vaPlan.js@@ -0,0 +1,48 @@+export const MAX_REF2VA_AUDIO_SECONDS = 15;+export const REF2VA_SEAM_WARMUP_SECONDS = 3;++export const planRef2vaAudioSegments = (+ durationSeconds,+ {+ startSeconds = 0,+ maxSegmentSeconds = MAX_REF2VA_AUDIO_SECONDS,+ seamWarmupSeconds = REF2VA_SEAM_WARMUP_SECONDS,+ } = {},+) => {+ const duration = Number(durationSeconds);+ const start = Number(startSeconds);+ const maxSegment = Number(maxSegmentSeconds);+ const seamWarmup = Number(seamWarmupSeconds);+ if (!Number.isFinite(duration) || duration <= 0) throw new TypeError('durationSeconds must be positive');+ if (!Number.isFinite(start) || start < 0 || start >= duration) throw new TypeError('startSeconds must be within the audio');+ if (!Number.isFinite(maxSegment) || maxSegment <= 0 || maxSegment > MAX_REF2VA_AUDIO_SECONDS) {+ throw new TypeError(`maxSegmentSeconds must be between 0 and ${MAX_REF2VA_AUDIO_SECONDS}`);+ }+ if (!Number.isFinite(seamWarmup) || seamWarmup < 0 || seamWarmup >= maxSegment) {+ throw new TypeError('seamWarmupSeconds must be non-negative and shorter than maxSegmentSeconds');+ }++ const segments = [];+ let outputStart = start;+ while (outputStart < duration - 1e-6) {+ // H3 fades in at the beginning of every invocation. Later invocations read+ // three seconds of already-rendered audio as warm-up, then PortOS blends+ // that overlapping picture with the prior window. The delivered timeline+ // remains exact while every reference request stays within H3's 15-second cap.+ // A non-zero requested source offset can use the same warm-up immediately;+ // at absolute zero there is no earlier source audio to borrow.+ const trimStartSeconds = outputStart > 0 ? Math.min(seamWarmup, outputStart) : 0;+ const outputCapacity = maxSegment - trimStartSeconds;+ const segmentDuration = Math.min(outputCapacity, duration - outputStart);+ segments.push({+ index: segments.length,+ startSeconds: outputStart,+ durationSeconds: segmentDuration,+ referenceStartSeconds: outputStart - trimStartSeconds,+ referenceDurationSeconds: trimStartSeconds + segmentDuration,+ trimStartSeconds,+ });+ outputStart += segmentDuration;+ }+ return segments;+};diff --git a/server/services/videoGen/ref2vaPlan.test.js b/server/services/videoGen/ref2vaPlan.test.jsnew file mode 100644index 0000000000..372bfe1852--- /dev/null+++ b/server/services/videoGen/ref2vaPlan.test.js@@ -0,0 +1,60 @@+import { describe, expect, it } from 'vitest';+import { MAX_REF2VA_AUDIO_SECONDS, planRef2vaAudioSegments } from './ref2vaPlan.js';++describe('planRef2vaAudioSegments', () => {+ it('splits arbitrary audio into legal Ref2VA conditioning windows', () => {+ expect(planRef2vaAudioSegments(41.041281)).toEqual([+ {+ index: 0, startSeconds: 0, durationSeconds: 15,+ referenceStartSeconds: 0, referenceDurationSeconds: 15, trimStartSeconds: 0,+ },+ {+ index: 1, startSeconds: 15, durationSeconds: 12,+ referenceStartSeconds: 12, referenceDurationSeconds: 15, trimStartSeconds: 3,+ },+ {+ index: 2, startSeconds: 27, durationSeconds: 12,+ referenceStartSeconds: 24, referenceDurationSeconds: 15, trimStartSeconds: 3,+ },+ {+ index: 3, startSeconds: 39, durationSeconds: 2.041280999999998,+ referenceStartSeconds: 36, referenceDurationSeconds: 5.041280999999998, trimStartSeconds: 3,+ },+ ]);+ });++ it('uses source audio before a requested offset as the first seam warm-up', () => {+ const segments = planRef2vaAudioSegments(40, { startSeconds: 12 });+ expect(segments).toEqual([+ {+ index: 0, startSeconds: 12, durationSeconds: 12,+ referenceStartSeconds: 9, referenceDurationSeconds: MAX_REF2VA_AUDIO_SECONDS, trimStartSeconds: 3,+ },+ {+ index: 1, startSeconds: 24, durationSeconds: 12,+ referenceStartSeconds: 21, referenceDurationSeconds: MAX_REF2VA_AUDIO_SECONDS, trimStartSeconds: 3,+ },+ {+ index: 2, startSeconds: 36, durationSeconds: 4,+ referenceStartSeconds: 33, referenceDurationSeconds: 7, trimStartSeconds: 3,+ },+ ]);+ });++ it('can disable warm-up while retaining the legal reference cap', () => {+ expect(planRef2vaAudioSegments(16, { seamWarmupSeconds: 0 })).toEqual([+ {+ index: 0, startSeconds: 0, durationSeconds: 15,+ referenceStartSeconds: 0, referenceDurationSeconds: 15, trimStartSeconds: 0,+ },+ {+ index: 1, startSeconds: 15, durationSeconds: 1,+ referenceStartSeconds: 15, referenceDurationSeconds: 1, trimStartSeconds: 0,+ },+ ]);+ });++ it.each([0, -1, Number.NaN])('rejects invalid duration %s', (duration) => {+ expect(() => planRef2vaAudioSegments(duration)).toThrow('durationSeconds must be positive');+ });+});diff --git a/server/services/videoGen/ref2vaWrapper.test.js b/server/services/videoGen/ref2vaWrapper.test.jsnew file mode 100644index 0000000000..33137ffd25--- /dev/null+++ b/server/services/videoGen/ref2vaWrapper.test.js@@ -0,0 +1,189 @@+import { execFile, spawn } from 'child_process';+import { chmod, mkdtemp, readFile, rm, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { dirname, join } from 'path';+import { fileURLToPath } from 'url';+import { promisify } from 'util';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { findFfmpeg, findFfprobe } from '../../lib/ffmpeg.js';+import {+ composeRef2vaSegments,+ MAX_REF2VA_XFADE_INPUTS,+} from '../../../scripts/generate_minimax_h3_ref2va.js';++const execFileAsync = promisify(execFile);+const WRAPPER = join(+ dirname(fileURLToPath(import.meta.url)),+ '..', '..', '..', 'scripts', 'generate_minimax_h3_ref2va.js',+);++describe('MiniMax H3 Ref2VA arbitrary-length wrapper', () => {+ let root;+ let ffmpeg;+ let ffprobe;+ let wrapperProcess;++ beforeEach(async () => {+ root = await mkdtemp(join(tmpdir(), 'portos-ref2va-wrapper-test-'));+ ffmpeg = await findFfmpeg();+ ffprobe = await findFfprobe();+ });++ afterEach(async () => {+ if (wrapperProcess && wrapperProcess.exitCode == null && wrapperProcess.signalCode == null) {+ wrapperProcess.kill('SIGKILL');+ }+ await rm(root, { recursive: true, force: true });+ });++ it('keeps each xfade pass below a bounded input count for long timelines', async () => {+ const calls = [];+ const pieces = Array.from({ length: 65 }, (_, index) => ({+ path: join(root, `segment-${index}.mp4`),+ startSeconds: index === 0 ? 0 : index * 12,+ endSeconds: (index === 0 ? 0 : index * 12) + 15,+ }));++ await composeRef2vaSegments({+ ffmpeg: '/mock/ffmpeg',+ workDir: root,+ pieces,+ runCommand: async (_bin, args) => { calls.push(args); },+ });++ expect(calls.length).toBeGreaterThan(1);+ expect(Math.max(...calls.map((args) => args.filter((arg) => arg === '-i').length)))+ .toBe(MAX_REF2VA_XFADE_INPUTS);+ });++ it.skipIf(process.platform === 'win32')('forwards wrapper cancellation to the active runtime process group', async () => {+ const audio = join(root, 'source.wav');+ const image = join(root, 'source.png');+ const output = join(root, 'output.mp4');+ const runtimePidFile = join(root, 'runtime.pid');+ const fakeFfmpeg = join(root, 'fake-ffmpeg');+ const fakeFfprobe = join(root, 'fake-ffprobe');+ const fakeRuntime = join(root, 'fake-mere-run');++ await Promise.all([+ writeFile(audio, ''),+ writeFile(image, ''),+ writeFile(fakeFfmpeg, '#!/bin/sh\nfor last do :; done\n: > "$last"\n'),+ writeFile(fakeFfprobe, '#!/bin/sh\nprintf "5\\n"\n'),+ writeFile(fakeRuntime, '#!/bin/sh\nprintf "%s" "$$" > "$FAKE_RUNTIME_PID_FILE"\ntrap \'exit 143\' TERM INT\nwhile :; do sleep 1; done\n'),+ ]);+ await Promise.all([fakeFfmpeg, fakeFfprobe, fakeRuntime].map((path) => chmod(path, 0o755)));++ wrapperProcess = spawn(process.execPath, [+ WRAPPER,+ '--runtime-bin', fakeRuntime,+ '--model-root', root,+ '--prompt', 'one continuous awakening',+ '--image', image,+ '--audio', audio,+ '--width', '64',+ '--height', '64',+ '--fps', '24',+ '--seed', '17',+ '--steps', '9',+ '--ffmpeg', fakeFfmpeg,+ '--ffprobe', fakeFfprobe,+ '--output', output,+ ], {+ env: { ...process.env, FAKE_RUNTIME_PID_FILE: runtimePidFile },+ stdio: 'ignore',+ });++ await vi.waitFor(async () => {+ expect(Number(await readFile(runtimePidFile, 'utf8'))).toBeGreaterThan(0);+ }, { timeout: 5000, interval: 25 });+ const runtimePid = Number(await readFile(runtimePidFile, 'utf8'));++ wrapperProcess.kill('SIGTERM');+ await vi.waitFor(() => {+ expect(wrapperProcess.exitCode != null || wrapperProcess.signalCode != null).toBe(true);+ }, { timeout: 5000, interval: 25 });+ await vi.waitFor(() => {+ let alive = true;+ try { process.kill(runtimePid, 0); } catch { alive = false; }+ expect(alive).toBe(false);+ }, { timeout: 5000, interval: 25 });+ }, 15000);++ it('renders and crossfades every <=15s window, carries its last frame, and restores the full source audio', async () => {+ if (!ffmpeg || !ffprobe) return;+ const audio = join(root, 'source.wav');+ const image = join(root, 'source.png');+ const output = join(root, 'output.mp4');+ const calls = join(root, 'calls.jsonl');+ const fakeRuntime = join(root, 'fake-mere-run.js');++ await execFileAsync(ffmpeg, [+ '-v', 'error', '-f', 'lavfi', '-i', 'sine=frequency=440:sample_rate=32000:duration=31.25',+ '-ac', '2', '-c:a', 'pcm_s16le', '-y', audio,+ ]);+ await execFileAsync(ffmpeg, [+ '-v', 'error', '-f', 'lavfi', '-i', 'color=c=black:s=64x64',+ '-frames:v', '1', '-y', image,+ ]);+ await writeFile(fakeRuntime, `#!/usr/bin/env node+import { appendFileSync } from 'fs';+import { execFileSync } from 'child_process';+const args = process.argv.slice(2);+const value = (flag) => args[args.indexOf(flag) + 1];+const references = args.flatMap((arg, index) => arg === '--reference' ? [args[index + 1]] : []);+appendFileSync(process.env.FAKE_MERE_LOG, JSON.stringify({ duration: value('--duration'), references }) + '\\n');+execFileSync(process.env.FAKE_FFMPEG, [+ '-v', 'error', '-f', 'lavfi', '-i', 'color=c=navy:s=' + value('--width') + 'x' + value('--height') + ':r=' + value('--fps') + ':d=' + value('--duration'),+ '-an', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-y', value('--output'),+]);+`);+ await chmod(fakeRuntime, 0o755);++ const { stderr } = await execFileAsync(process.execPath, [+ WRAPPER,+ '--runtime-bin', fakeRuntime,+ '--model-root', root,+ '--prompt', 'one continuous awakening',+ '--image', image,+ '--audio', audio,+ '--width', '64',+ '--height', '64',+ '--fps', '24',+ '--seed', '17',+ '--steps', '9',+ '--ffmpeg', ffmpeg,+ '--ffprobe', ffprobe,+ '--output', output,+ ], {+ env: { ...process.env, FAKE_FFMPEG: ffmpeg, FAKE_MERE_LOG: calls },+ timeout: 120000,+ });++ expect(stderr).toContain('STAGE:ref2va-window:step:0:3:Rendering audio window 1/3');+ expect(stderr).toContain('STAGE:ref2va-window:step:1:3:Rendering audio window 2/3');+ expect(stderr).toContain('STAGE:ref2va-window:step:2:3:Rendering audio window 3/3');+ expect(stderr).not.toContain('STAGE:ref2va-window:step:3:3');++ const invocations = (await readFile(calls, 'utf8')).trim().split('\n').map(JSON.parse);+ // Every later call borrows three seconds of prior audio as startup warm-up,+ // still under the 15-second reference cap. The wrapper crossfades those+ // overlapping seconds, so the delivered duration remains 31.25 seconds.+ expect(invocations.map((call) => Number(call.duration))).toEqual([15, 15, 7.25]);+ expect(invocations[0].references[0]).toBe(`image:${image}`);+ expect(invocations[1].references[0]).toMatch(/image:.*continuity-0\.png$/);+ expect(invocations[2].references[0]).toMatch(/image:.*continuity-1\.png$/);+ expect(invocations.every((call) => call.references[1]?.startsWith('audio:'))).toBe(true);++ const { stdout } = await execFileAsync(ffprobe, [+ '-v', 'error', '-show_entries', 'format=duration',+ '-of', 'default=noprint_wrappers=1:nokey=1', output,+ ]);+ expect(Number(stdout.trim())).toBeCloseTo(31.25, 1);+ const { stdout: audioStreams } = await execFileAsync(ffprobe, [+ '-v', 'error', '-select_streams', 'a', '-show_entries', 'stream=index',+ '-of', 'csv=p=0', output,+ ]);+ expect(audioStreams.trim()).not.toBe('');+ }, 120000);+});diff --git a/server/services/videoGen/renderArgs.js b/server/services/videoGen/renderArgs.jsindex 2235b7475a..a4e079f2fc 100644--- a/server/services/videoGen/renderArgs.js+++ b/server/services/videoGen/renderArgs.js@@ -42,6 +42,8 @@ import {MINIMAX_H3_DRAFT_DECODER_SHIM_DIR,MINIMAX_H3_PROMPT_EMBEDDING_CACHE_DIR,MINIMAX_H3_EXPECTED_REVISION,+ MERE_RUN_BIN,+ MINIMAX_H3_REF2VA_HELPER_SCRIPT,MINIMAX_H3_CUDA_VENV_PYTHON,MINIMAX_H3_CUDA_HELPER_SCRIPT,MINIMAX_H3_CUDA_OFFLOAD_PROFILES,@@ -605,7 +607,7 @@ const buildWan22Args = ({ model, wanModelPath, wanRequiredWeights, prompt, negatreturn { bin: WAN22_VENV_PYTHON, args };};-// Everything both H3 builders must clear before they start assembling argv:+// Everything every H3 builder must clear before it starts assembling argv:// the venv is installed, the mode/source combination is legal, H3's fixed// controls were not overridden, and the entry carries its pin. The two lanes// had carried byte-identical copies of all four — the same shape that put the@@ -652,7 +654,7 @@ const assertMiniMaxH3Preflight = ({if (memoryDecline) throw new ServerError(memoryDecline.message, { status: 400, code: memoryDecline.code });};-// The capacity contract both H3 runners are handed: the host floor below which+// The capacity contract every H3 runner is handed: the host floor below which// NO declared placement profile can run, and the reserve PortOS holds back for// the OS. Sent as argv rather than left to each runner's own constants so the// server-side gate above and the runner-side enforcement cannot state different@@ -834,7 +836,58 @@ const buildMiniMaxH3CudaArgs = ({ model, prompt, negativePrompt, width, height,return { bin: MINIMAX_H3_CUDA_VENV_PYTHON, args };};-export const buildArgs = ({ pythonPath, modelId, model, wanModelPath, wanRequiredWeights, ltxModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, i2vReferenceMode, textEncoderRepo, textEncoder, outputPath, previewDir, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2, speedProfile, draftDecoder }) => {+export const buildMiniMaxH3Ref2vaArgs = ({+ model, ref2vaModelPath, prompt, negativePrompt, width, height, numFrames, fps,+ steps, seed, sourceImagePath, audioFilePath, audioStartSec, mode, tiling,+ disableAudio, outputPath, ffmpegPath, ffprobePath,+}) => {+ assertMiniMaxH3Preflight({+ runtimeId: 'minimax_h3_ref2va',+ repoLabel: 'repo or revision',+ model,+ mode,+ sourceImagePath,+ audioFilePath,+ audioStartSec,+ negativePrompt,+ disableAudio,+ tiling,+ numFrames,+ fps,+ });+ if (!ref2vaModelPath) {+ throw new ServerError(+ `${model.name} is not fully cached. Download or repair it in Video Gen before rendering.`,+ { status: 400, code: 'MINIMAX_H3_REF2VA_MODEL_NOT_CACHED' },+ );+ }+ if (!ffmpegPath || !ffprobePath) {+ throw new ServerError(+ 'ffmpeg and ffprobe are required for arbitrary-length MiniMax H3 Ref2VA rendering.',+ { status: 400, code: 'MINIMAX_H3_REF2VA_FFMPEG_REQUIRED' },+ );+ }+ const args = [+ MINIMAX_H3_REF2VA_HELPER_SCRIPT,+ '--runtime-bin', MERE_RUN_BIN,+ '--model-root', ref2vaModelPath,+ '--prompt', prompt,+ '--image', sourceImagePath,+ '--audio', audioFilePath,+ '--width', String(width),+ '--height', String(height),+ '--fps', String(fps),+ '--seed', String(seed),+ '--steps', String(steps),+ '--ffmpeg', ffmpegPath,+ '--ffprobe', ffprobePath,+ '--output', outputPath,+ ];+ if (audioStartSec != null) args.push('--audio-start', String(audioStartSec));+ return { bin: process.execPath, args };+};++export const buildArgs = ({ pythonPath, modelId, model, wanModelPath, wanRequiredWeights, ltxModelPath, ref2vaModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, i2vReferenceMode, textEncoderRepo, textEncoder, outputPath, previewDir, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2, speedProfile, draftDecoder, ffmpegPath, ffprobePath }) => {// 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@@ -900,6 +953,13 @@ export const buildArgs = ({ pythonPath, modelId, model, wanModelPath, wanRequireif (model.runtime === 'minimax_h3_cuda') {return buildMiniMaxH3CudaArgs({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths, mode, tiling, disableAudio, outputPath });}+ if (model.runtime === 'minimax_h3_ref2va') {+ return buildMiniMaxH3Ref2vaArgs({+ model, ref2vaModelPath, prompt, negativePrompt, width, height, numFrames,+ fps, steps, seed, sourceImagePath, audioFilePath, audioStartSec, mode,+ tiling, disableAudio, outputPath, ffmpegPath, ffprobePath,+ });+ }// Migration 315 removes the shipped Hunyuan profile, but a user-repointed// or peer-synced historical entry may still declare its retired runtime.// Fail closed instead of falling through to a legacy MLX/CUDA helper that@@ -918,8 +978,8 @@ export const buildArgs = ({ pythonPath, modelId, model, wanModelPath, wanRequire}if (mode === 'a2v') {throw new ServerError(- 'a2v mode is only supported on the ltx2 runtime. Pick a model with runtime: "ltx2" in data/media-models.json.',- { status: 400, code: 'A2V_REQUIRES_LTX2' },+ 'a2v mode requires an audio-to-video runtime.',+ { status: 400, code: 'A2V_RUNTIME_UNSUPPORTED' },);}// Every BYOV runtime has declined above; the remaining declared CUDA runtimediff --git a/server/services/videoGen/runtimes.js b/server/services/videoGen/runtimes.jsindex 95ea6d005c..af9de09eb4 100644--- a/server/services/videoGen/runtimes.js+++ b/server/services/videoGen/runtimes.js@@ -79,6 +79,14 @@ export const MINIMAX_H3_DRAFT_DECODER_SHIM_DIR = join(homedir(), '.portos', 'min// the pin verification /status and the render helper both run.export const MINIMAX_H3_PROMPT_EMBEDDING_CACHE_DIR = join(homedir(), '.portos', 'minimax-h3-prompt-embeddings');+// MiniMax H3 Ref2VA runtime — the signed mere.run release provides the native+// MLX implementation and stays separate from model weights. PortOS installs it+// into a user-owned directory so the in-app flow never needs sudo.+export const MERE_RUN_VERSION = '0.47.0';+export const MERE_RUN_DIR = join(homedir(), '.portos', 'mere-run');+export const MERE_RUN_BIN = join(MERE_RUN_DIR, 'mere.run');+export const MINIMAX_H3_REF2VA_HELPER_SCRIPT = join(PATHS.root, 'scripts', 'generate_minimax_h3_ref2va.js');+// MiniMax H3 on CUDA — the diffusers `MiniMaxH3ModularPipeline` rather than a// pinned source checkout, so this runtime is a plain pip venv with no revision// to verify and no source package to keep clean.@@ -125,6 +133,24 @@ const RUNTIME_FINGERPRINT_SCRIPT = join(PATHS.root, 'scripts', 'runtime_fingerpr// this probe the UI would hide the install banner and renders would fail// with a deep ImportError inside the runner script.export const BYOV_RUNTIME_INFO = Object.freeze({+ minimax_h3_ref2va: {+ id: 'minimax_h3_ref2va',+ label: 'MiniMax H3 Ref2VA MLX',+ venvPython: MERE_RUN_BIN,+ repoDir: MERE_RUN_DIR,+ installEnvVar: 'INSTALL_MERERUN',+ cacheOnly: true,+ killProcessGroup: true,+ repoUrl: `https://github.com/sawfwair/mere-run/releases/tag/v${MERE_RUN_VERSION}`,+ installSourceLabel: `signed mere.run v${MERE_RUN_VERSION} release`,+ expectedVersion: MERE_RUN_VERSION,+ probeArgs: ['--version'],+ fingerprintProbeArgs: ['--version'],+ fingerprintVersionKey: 'mere.run',+ // The PortOS Hugging Face downloader must use its own Python helper and+ // saved token; mere.run is an executable, not a Python interpreter.+ hfDownloadPython: false,+ },minimax_h3: {id: 'minimax_h3',label: 'MiniMax H3 MLX',@@ -330,7 +356,7 @@ export async function isByovRuntimeReady(runtimeId) {// executable package have passed the clean-status check. Keep this ahead of// the positive readiness cache too: a checkout can be edited after an// earlier successful probe.- if (info.expectedRevision && !await isByovRuntimeCurrent(runtimeId)) return false;+ if ((info.expectedRevision || info.expectedVersion) && !await isByovRuntimeCurrent(runtimeId)) return false;if (readyCache.get(runtimeId) === true) return true;const probeOk = await runVenvProbe(info.venvPython, info.probeArgs || ['-c', info.importProbe], `${runtimeId} readiness`,@@ -507,6 +533,22 @@ export function byovRuntimeExpectedRevision(runtimeId) {export async function isByovRuntimeCurrent(runtimeId) {const info = BYOV_RUNTIME_INFO[runtimeId];+ if (info?.expectedVersion) {+ if (!existsSync(info.venvPython)) return false;+ return new Promise((resolve) => {+ let stdout = '';+ const child = spawn(info.venvPython, ['--version'], safeChildProcessOptions({+ stdio: ['ignore', 'pipe', 'ignore'],+ }));+ const timer = setTimeout(() => { if (!child.killed) child.kill('SIGKILL'); resolve(false); }, 10000);+ child.stdout.on('data', (chunk) => { if (stdout.length < 128) stdout += chunk.toString(); });+ child.on('close', (code) => {+ clearTimeout(timer);+ resolve(code === 0 && stdout.trim() === info.expectedVersion);+ });+ child.on('error', () => { clearTimeout(timer); resolve(false); });+ });+ }if (!info?.expectedRevision) return true;if (!existsSync(join(info.repoDir, '.git'))) return false;return new Promise((resolve) => {@@ -576,7 +618,8 @@ async function probeRuntimeFingerprint(runtimeId) {let out = '';const child = spawn(info.venvPython,- [RUNTIME_FINGERPRINT_SCRIPT, runtimeId, ...(info.fingerprintPackages || [])],+ info.fingerprintProbeArgs+ || [RUNTIME_FINGERPRINT_SCRIPT, runtimeId, ...(info.fingerprintPackages || [])],safeChildProcessOptions({ stdio: ['ignore', 'pipe', 'ignore'] }),);const timer = setTimeout(() => { if (!child.killed) child.kill('SIGKILL'); resolve({ error: 'timeout' }); }, 15000);@@ -584,9 +627,16 @@ async function probeRuntimeFingerprint(runtimeId) {child.on('close', (code) => {clearTimeout(timer);if (code !== 0) return resolve({ error: `exit ${code}` });- // The probe prints exactly one JSON line; take the last non-empty line- // defensively in case a venv import prints a stray warning to stdout.const lastLine = out.trim().split('\n').filter(Boolean).pop() || '';+ if (info.fingerprintProbeArgs) {+ return resolve({+ runtime: runtimeId,+ versions: { [info.fingerprintVersionKey || runtimeId]: lastLine },+ ...hostRuntimeFingerprint(),+ });+ }+ // The Python probe prints exactly one JSON line; take the last non-empty+ // line defensively in case a venv import prints a stray warning.try { resolve(JSON.parse(lastLine)); } catch { resolve({ error: 'unparseable' }); }});child.on('error', () => { clearTimeout(timer); resolve({ error: 'spawn-failed' }); });diff --git a/server/services/videoGen/runtimes.test.js b/server/services/videoGen/runtimes.test.jsindex 1945b30081..dcce20ad2e 100644--- a/server/services/videoGen/runtimes.test.js+++ b/server/services/videoGen/runtimes.test.js@@ -22,7 +22,7 @@ vi.mock('../../lib/childProcess.js', async (importOriginal) => ({import {BYOV_RUNTIME_INFO, BYOV_VIDEO_RUNTIMES, MINIMAX_H3_CUDA_OFFLOAD_PROFILES,byovRuntimeLoraCapable, invalidateByovLoraCapabilityCache, invalidateByovReadyCache,- isByovRuntimeReady, isPinnedSourceStatusClean, modelAnchorsLastFrame,+ isByovRuntimeCurrent, isByovRuntimeReady, isPinnedSourceStatusClean, modelAnchorsLastFrame,resolveByovRuntimeLoraCapable, runtimeIsCacheOnly, runtimeNeedsProcessGroupKill,routesToWindowsHelper, LTX25_EXPECTED_REVISION,} from './runtimes.js';@@ -78,6 +78,32 @@ describe('retired runtime filtering', () => {});});+describe('MiniMax H3 Ref2VA runtime', () => {+ it('uses the signed user-local mere.run install and PortOS HF downloader', () => {+ expect(BYOV_RUNTIME_INFO.minimax_h3_ref2va).toMatchObject({+ installEnvVar: 'INSTALL_MERERUN',+ expectedVersion: '0.47.0',+ probeArgs: ['--version'],+ cacheOnly: true,+ killProcessGroup: true,+ hfDownloadPython: false,+ });+ });++ it('accepts only the pinned mere.run version as current', async () => {+ runtimeMocks.spawn.mockImplementationOnce(() => statusChild('0.47.0\n'));+ await expect(isByovRuntimeCurrent('minimax_h3_ref2va')).resolves.toBe(true);+ expect(runtimeMocks.spawn).toHaveBeenCalledWith(+ BYOV_RUNTIME_INFO.minimax_h3_ref2va.venvPython,+ ['--version'],+ expect.objectContaining({ stdio: ['ignore', 'pipe', 'ignore'] }),+ );++ runtimeMocks.spawn.mockImplementationOnce(() => statusChild('0.46.1\n'));+ await expect(isByovRuntimeCurrent('minimax_h3_ref2va')).resolves.toBe(false);+ });+});+describe('isPinnedSourceStatusClean', () => {it('accepts the exact revision when the scoped source package is clean', () => {expect(isPinnedSourceStatusClean([