Skip to content

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

feat: add versioned audio-reactive music videos

[._.]/ Adam Eivyaef7cf39c3d8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 4fd387dd04..1e73cf7111 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -5,6 +5,7 @@
- **Malware scans now leave a durable, reviewable report trail.** Git-link scans save an owned markdown artifact, surface it from the completed agent summary and Review Hub, and mark repositories with an explicit `DANGEROUS` verdict using a skull danger treatment on the Git links card.
- **Slashdo-free TUI agent PRs now complete their lifecycle.** Codex, Antigravity, OpenCode, and lean Claude agents hand committed work back to PortOS so it can generate a non-empty PR description, run configured reviewers, and merge after the selected gates pass instead of leaving an ownerless PR open.
- **Music Video projects now save their scene-video renderer and model.** Directors can choose local or Grok generation per project, pick an image-to-video-capable local model, see cut-pacing warnings, selectively continue clips on native LTX runtimes, generate all missing media from the board, and play or download the audio-backed final render in place.
+- **Music Video projects can now be forked into editable versions and rendered with local song-reactive motion.** A fork keeps the source board and scene media while clearing the final master, records its parent/root lineage, and opens immediately as the next version. Projects with the LTX-2.3 audio-reactive LoRA installed can condition each cut on its exact song segment while stripping generated clip audio and automatically directing the model away from singing, lip-sync, performers, and visible musical performance.
## Agent workspaces
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index c5768cfe48..ffb946a806 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -1,12 +1,13 @@
import { useEffect, useState, useCallback, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
-import { Plus, Film, Trash2, Music, Activity, ArrowUp, ArrowDown, Image as ImageIcon, Video, Wand2, Download } from 'lucide-react';
+import { Plus, Film, Trash2, Music, Activity, ArrowUp, ArrowDown, Image as ImageIcon, Video, Wand2, Download, Copy } from 'lucide-react';
import toast from '../components/ui/Toast';
import PageHeader from '../components/PageHeader';
import Drawer from '../components/Drawer.jsx';
import {
listMusicVideoProjects,
createMusicVideoProject,
+ cloneMusicVideoProject,
updateMusicVideoProject,
deleteMusicVideoProject,
analyzeMusicVideoProject,
@@ -29,7 +30,7 @@ import MidiInstallModal from '../components/install/MidiInstallModal.jsx';
import MidiGatedModal from '../components/install/MidiGatedModal.jsx';
import MidiVisualization from '../components/songs/MidiVisualization.jsx';
import { generateImage } from '../services/apiSystem.js';
-import { generateVideo, getVideoGenStatus } from '../services/apiImageVideo.js';
+import { generateVideo, getVideoGenStatus, listLorasFull } from '../services/apiImageVideo.js';
import { listTracks, trackAudioUrl } from '../services/apiTracks.js';
import BeatTimeline from '../components/musicVideo/BeatTimeline.jsx';
import { autoArrangeScenes } from '../lib/beatGrid.js';
@@ -46,6 +47,7 @@ import { clampBpm } from '../lib/metronome.js';
// clampBpm's own ceiling (320, metronome-focused) is looser than what the
// manual-tempo endpoint accepts.
const MUSIC_VIDEO_MANUAL_BPM_MAX = 300;
+const AUDIO_REACTIVE_PERFORMANCE_GUARD = 'The music drives only environmental motion, lighting, particles, reflections, fabric, and subtle camera accents. No singing, lip-sync, speaking, mouth movement, dancing, instruments, performers, or musical performance.';
const MODES = ['director', 'autonomous'];
@@ -112,8 +114,10 @@ export default function MusicVideo() {
const [analyzing, setAnalyzing] = useState(false);
const [arranging, setArranging] = useState(false);
const [planning, setPlanning] = useState(false);
+ const [cloning, setCloning] = useState(false);
const [createOpen, setCreateOpen] = useState(false);
const [videoModels, setVideoModels] = useState([]);
+ const [videoLoras, setVideoLoras] = useState([]);
const [defaultVideoModel, setDefaultVideoModel] = useState('');
const [videoSettingsSaving, setVideoSettingsSaving] = useState(false);
const [form, setForm] = useState({ name: '', mode: 'director', trackId: '' });
@@ -238,6 +242,9 @@ export default function MusicVideo() {
setVideoModels([]);
setDefaultVideoModel('');
});
+ listLorasFull({ silent: true })
+ .then((loras) => setVideoLoras(Array.isArray(loras) ? loras : []))
+ .catch(() => setVideoLoras([]));
}, []);
const trackName = useCallback((id) => tracks.find((t) => t.id === id)?.title || id || '—', [tracks]);
@@ -290,6 +297,19 @@ export default function MusicVideo() {
.catch((err) => toast.error(err?.message || 'Failed to delete project'));
};
+ const handleClone = () => {
+ if (!selected || cloning) return;
+ setCloning(true);
+ cloneMusicVideoProject(selected.id, {}, { silent: true })
+ .then((project) => {
+ setProjects((prev) => [...prev, project]);
+ navigate(`/music-video/${project.id}`);
+ toast.success(`Created ${project.name}`);
+ })
+ .catch((err) => toast.error(err?.message || 'Failed to clone project'))
+ .finally(() => setCloning(false));
+ };
+
// Audio → MIDI transcription (MuScriptor): turn the project's source audio
// into a .mid. The server persists the pointer on the project at completion;
// the terminal frame carries it, merged here keyed on the captured projectId
@@ -460,9 +480,24 @@ export default function MusicVideo() {
// distinct from pinning the model that happens to be default today.
modelId: selected?.videoSettings?.modelId || '',
grokDuration: selected?.videoSettings?.grokDuration || 10,
+ generationMode: selected?.videoSettings?.generationMode || 'image',
+ audioReactiveLora: selected?.videoSettings?.audioReactiveLora || '',
+ audioReactiveScale: selected?.videoSettings?.audioReactiveScale ?? 1.2,
};
const effectiveVideoModelId = savedVideoSettings.modelId || defaultVideoModel;
const activeVideoModel = videoModels.find((model) => model.id === effectiveVideoModelId) || null;
+ const audioReactiveModels = videoModels.filter((model) =>
+ model.runtime === 'ltx2' && /ltx.?2\.3|ltx23/i.test(`${model.id} ${model.name || ''} ${model.repo || ''}`));
+ const detectedAudioReactiveLora = videoLoras.find((lora) =>
+ lora.filename === savedVideoSettings.audioReactiveLora)
+ || videoLoras.find((lora) => /audio-reactive/i.test(`${lora.filename} ${lora.name || ''}`)
+ && (lora.loraCompatKey || lora.runnerFamily) === 'ltx-video')
+ || null;
+ const audioReactiveReady = !!(activeVideoModel?.runtime === 'ltx2'
+ && /ltx.?2\.3|ltx23/i.test(`${activeVideoModel.id} ${activeVideoModel.name || ''} ${activeVideoModel.repo || ''}`)
+ && detectedAudioReactiveLora);
+ const audioReactiveSelected = savedVideoSettings.backend === 'local'
+ && savedVideoSettings.generationMode === 'audioReactive';
const authoredCutDurations = (selected?.scenes || [])
.filter((scene) => typeof scene.startSec === 'number' && typeof scene.endSec === 'number' && scene.endSec > scene.startSec)
.map((scene) => scene.endSec - scene.startSec);
@@ -687,8 +722,16 @@ export default function MusicVideo() {
// a non-OK response, so the catch owns the only error toast (no double-toast).
const handleGenerateVideo = (scene) => {
if (!scene.referenceImageId) { toast.error('Generate a reference frame first'); return; }
- const prompt = buildShotPrompt(scene);
- if (!prompt) { toast.error('Add a shot prompt first'); return; }
+ const basePrompt = buildShotPrompt(scene);
+ if (!basePrompt) { toast.error('Add a shot prompt first'); return; }
+ const audioReactive = audioReactiveSelected;
+ if (audioReactive && !audioReactiveReady) {
+ toast.error('Audio-reactive generation requires an installed LTX-2.3 audio-reactive LoRA and an LTX-2.3 local model');
+ return;
+ }
+ const prompt = audioReactive
+ ? `${basePrompt}. ${AUDIO_REACTIVE_PERFORMANCE_GUARD}`
+ : basePrompt;
videoLane.startScene(scene.sceneId);
generateVideo({
prompt,
@@ -696,8 +739,13 @@ export default function MusicVideo() {
...(savedVideoSettings.backend === 'grok'
? { grokDuration: savedVideoSettings.grokDuration }
: { modelId: savedVideoSettings.modelId || undefined, disableAudio: true }),
- mode: 'image',
+ mode: audioReactive ? 'a2v' : 'image',
sourceImageFile: scene.referenceImageId,
+ ...(audioReactive ? {
+ audioStartSec: scene.startSec || 0,
+ loraFilenames: [detectedAudioReactiveLora.filename],
+ loraScales: [savedVideoSettings.audioReactiveScale],
+ } : {}),
musicVideo: JSON.stringify({ projectId: selected.id, sceneId: scene.sceneId }),
})
.then((res) => {
@@ -833,9 +881,14 @@ export default function MusicVideo() {
))}
</select>
{selected && (
- <span className={`text-[10px] px-1.5 py-0.5 rounded ${STATUS_COLORS[selected.status] || 'bg-port-border'}`}>
- {selected.status}
- </span>
+ <>
+ <span className="text-[10px] px-1.5 py-0.5 rounded bg-port-border">
+ v{selected.version || 1}
+ </span>
+ <span className={`text-[10px] px-1.5 py-0.5 rounded ${STATUS_COLORS[selected.status] || 'bg-port-border'}`}>
+ {selected.status}
+ </span>
+ </>
)}
<button
type="button"
@@ -861,9 +914,9 @@ export default function MusicVideo() {
{selected && (
<div className="space-y-3">
<div className="bg-port-card border border-port-border rounded-lg p-3">
- <div className="flex items-center justify-between gap-2 flex-wrap">
- <h2 className="text-lg font-semibold">{selected.name}</h2>
- <div className="flex items-center gap-2">
+ <div className="flex items-start justify-between gap-2 flex-wrap">
+ <h2 className="text-lg font-semibold shrink-0">{selected.name}</h2>
+ <div className="min-w-0 flex flex-1 flex-wrap items-center justify-end gap-2">
<button onClick={handleAnalyze} disabled={analyzing || (!selected.trackId && !selected.uploadedAudioFilename)}
title={!selected.trackId && !selected.uploadedAudioFilename ? 'Link a track first' : 'Analyze beat grid'}
className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0 disabled:opacity-50">
@@ -922,6 +975,31 @@ export default function MusicVideo() {
</select>
{savedVideoSettings.backend === 'local' && (
<>
+ <label htmlFor="mv-generation-mode" className="sr-only">Scene generation mode</label>
+ <select
+ id="mv-generation-mode"
+ value={savedVideoSettings.generationMode}
+ onChange={(e) => {
+ const generationMode = e.target.value;
+ const compatibleModel = audioReactiveModels.find((model) => model.id === effectiveVideoModelId)
+ || audioReactiveModels[0];
+ handleVideoSettingsChange({
+ generationMode,
+ ...(generationMode === 'audioReactive' && detectedAudioReactiveLora
+ ? { audioReactiveLora: detectedAudioReactiveLora.filename }
+ : {}),
+ ...(generationMode === 'audioReactive' && compatibleModel
+ ? { modelId: compatibleModel.id }
+ : {}),
+ });
+ }}
+ disabled={videoSettingsSaving || Object.keys(genVideoScenes).length > 0}
+ title="Prompt motion uses the reference frame; audio reactive also conditions motion on this scene's song segment"
+ className="bg-port-bg border border-port-border rounded px-1.5 py-1.5 text-sm disabled:opacity-50"
+ >
+ <option value="image">Prompt motion</option>
+ <option value="audioReactive" disabled={!detectedAudioReactiveLora}>Audio reactive</option>
+ </select>
<label htmlFor="mv-video-model" className="sr-only">Local video model</label>
<select
id="mv-video-model"
@@ -936,10 +1014,33 @@ export default function MusicVideo() {
? `Local default · ${videoModels.find((model) => model.id === defaultVideoModel)?.name || defaultVideoModel}`
: 'Local default model'}
</option>
- {videoModels.map((model) => (
+ {(audioReactiveSelected ? audioReactiveModels : videoModels).map((model) => (
<option key={model.id} value={model.id}>{model.name || model.id}</option>
))}
</select>
+ {audioReactiveSelected && (
+ <>
+ <label htmlFor="mv-audio-reactive-scale" className="sr-only">Audio reactive LoRA strength</label>
+ <select
+ id="mv-audio-reactive-scale"
+ value={savedVideoSettings.audioReactiveScale}
+ onChange={(e) => handleVideoSettingsChange({ audioReactiveScale: Number(e.target.value) })}
+ disabled={videoSettingsSaving || Object.keys(genVideoScenes).length > 0}
+ title="How strongly the song drives visible motion"
+ className="bg-port-bg border border-port-border rounded px-1.5 py-1.5 text-sm disabled:opacity-50"
+ >
+ <option value={1}>Reactive 1.0×</option>
+ <option value={1.2}>Reactive 1.2×</option>
+ <option value={1.5}>Reactive 1.5×</option>
+ </select>
+ <span
+ className={`text-[10px] px-1.5 py-0.5 rounded ${audioReactiveReady ? 'bg-port-success/20 text-port-success' : 'bg-port-error/20 text-port-error'}`}
+ title={detectedAudioReactiveLora?.filename || 'Audio-reactive LoRA not installed'}
+ >
+ {audioReactiveReady ? 'song-conditioned · no vocals' : 'audio-reactive unavailable'}
+ </span>
+ </>
+ )}
</>
)}
{savedVideoSettings.backend === 'grok' && (
@@ -969,7 +1070,7 @@ export default function MusicVideo() {
</button>
<button
onClick={handleGenerateMissingVideos}
- disabled={videoSettingsSaving || sceneCount === 0 || missingVideoCount === 0 || referenceFrameCount !== sceneCount || Object.keys(genVideoScenes).length > 0}
+ disabled={videoSettingsSaving || sceneCount === 0 || missingVideoCount === 0 || referenceFrameCount !== sceneCount || Object.keys(genVideoScenes).length > 0 || (audioReactiveSelected && !audioReactiveReady)}
title={referenceFrameCount !== sceneCount
? 'Generate every reference frame first'
: (missingVideoCount > 0 ? `Generate ${missingVideoCount} missing scene video${missingVideoCount === 1 ? '' : 's'}` : 'Every scene has a video')}
@@ -977,6 +1078,14 @@ export default function MusicVideo() {
>
<Video size={15} /> Videos {renderableSceneCount}/{sceneCount}
</button>
+ <button
+ onClick={handleClone}
+ disabled={cloning}
+ title={`Create an editable v${(selected.version || 1) + 1}; keep scene media attached and clear the final render`}
+ className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0 disabled:opacity-50"
+ >
+ <Copy size={15} /> {cloning ? 'Forking…' : `Fork v${(selected.version || 1) + 1}`}
+ </button>
{render ? (
<button onClick={handleCancelRender} title="Cancel render"
className="flex items-center gap-1 bg-port-warning/20 text-port-warning border border-port-border rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0">
@@ -1266,13 +1375,13 @@ export default function MusicVideo() {
muted playsInline preload="metadata" controls />
)}
<button onClick={() => handleGenerateVideo(scene)}
- disabled={videoSettingsSaving || !scene.referenceImageId || !!genVideoScenes[scene.sceneId]}
+ disabled={videoSettingsSaving || !scene.referenceImageId || !!genVideoScenes[scene.sceneId] || (audioReactiveSelected && !audioReactiveReady)}
className="flex items-center gap-1 bg-port-border hover:bg-port-border/70 disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[40px] sm:min-h-0 whitespace-nowrap"
title={scene.referenceImageId ? "Generate this scene's video from its reference frame (i2v)" : 'Generate a reference frame first'}>
{genVideoScenes[scene.sceneId] ? <Activity size={14} className="animate-spin" /> : <Video size={14} />}
{genVideoScenes[scene.sceneId] ? 'Generating video…' : (scene.videoHistoryId ? 'Regenerate video' : 'Generate video')}
</button>
- {scene.videoHistoryId && savedVideoSettings.backend === 'local' && activeVideoModel?.runtime === 'ltx2' && (
+ {scene.videoHistoryId && savedVideoSettings.backend === 'local' && savedVideoSettings.generationMode === 'image' && activeVideoModel?.runtime === 'ltx2' && (
<button
onClick={() => handleContinueVideo(scene)}
disabled={videoSettingsSaving || !!genVideoScenes[scene.sceneId]}
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index b92d5045c4..f95aa6f617 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -36,6 +36,7 @@ const { sseState, ytSseStates, getYtSseState } = vi.hoisted(() => {
vi.mock('../services/apiMusicVideo.js', () => ({
listMusicVideoProjects: vi.fn(async () => []),
createMusicVideoProject: vi.fn(),
+ cloneMusicVideoProject: vi.fn(),
updateMusicVideoProject: vi.fn(async (id, patch) => ({ id, ...patch })),
deleteMusicVideoProject: vi.fn(),
analyzeMusicVideoProject: vi.fn(),
@@ -54,6 +55,12 @@ vi.mock('../services/apiMusicVideo.js', () => ({
vi.mock('../services/apiSystem.js', () => ({ generateImage: vi.fn() }));
vi.mock('../services/apiImageVideo.js', () => ({
generateVideo: vi.fn(),
+ listLorasFull: vi.fn(async () => [{
+ filename: 'audio-reactive.safetensors',
+ name: 'Audio Reactive',
+ loraCompatKey: 'ltx-video',
+ recommendedScale: 1.2,
+ }]),
getVideoGenStatus: vi.fn(async () => ({
connected: true,
defaultModel: 'ltx23_distilled_q4',
@@ -87,7 +94,7 @@ vi.mock('../components/PageHeader', () => ({ default: ({ title }) => <div>{title
import MusicVideo from './MusicVideo.jsx';
import {
- listMusicVideoProjects, createMusicVideoProject, renderMusicVideoProject, planMusicVideoProject, updateMusicVideoProject,
+ listMusicVideoProjects, createMusicVideoProject, cloneMusicVideoProject, renderMusicVideoProject, planMusicVideoProject, updateMusicVideoProject,
deleteMusicVideoProject, transcribeMusicVideoMidi,
} from '../services/apiMusicVideo.js';
import { importTrackFromYoutube, trackImportEventsUrl, listTracks } from '../services/apiTracks.js';
@@ -224,6 +231,59 @@ describe('MusicVideo project video renderer', () => {
sourceImageFile: 'img1',
})));
});
+
+ it('uses project audio as no-vocals conditioning at the scene song offset', async () => {
+ generateVideo.mockResolvedValue({ jobId: 'audio-reactive-job' });
+ await openProject(PROJECT_NO_CLIP);
+
+ fireEvent.change(await screen.findByLabelText('Scene generation mode'), {
+ target: { value: 'audioReactive' },
+ });
+ await waitFor(() => expect(updateMusicVideoProject).toHaveBeenCalledWith(
+ 'mv-2',
+ {
+ videoSettings: expect.objectContaining({
+ generationMode: 'audioReactive',
+ audioReactiveLora: 'audio-reactive.safetensors',
+ modelId: 'ltx23_distilled_q4',
+ }),
+ },
+ { silent: true },
+ ));
+
+ fireEvent.click(screen.getByRole('button', { name: /^Generate video$/ }));
+ await waitFor(() => expect(generateVideo).toHaveBeenCalledWith(expect.objectContaining({
+ backend: 'local',
+ modelId: 'ltx23_distilled_q4',
+ mode: 'a2v',
+ sourceImageFile: 'img1',
+ audioStartSec: 0,
+ disableAudio: true,
+ loraFilenames: ['audio-reactive.safetensors'],
+ loraScales: [1.2],
+ prompt: expect.stringMatching(/No singing, lip-sync, speaking, mouth movement/i),
+ })));
+ });
+});
+
+describe('MusicVideo project versions', () => {
+ it('forks the open project and navigates to the editable next version', async () => {
+ cloneMusicVideoProject.mockResolvedValue({
+ ...PROJECT_WITH_CLIP,
+ id: 'mv-v2',
+ name: 'Neon Run v2',
+ version: 2,
+ parentProjectId: 'mv-1',
+ renderHistoryId: null,
+ });
+ await openProject(PROJECT_WITH_CLIP);
+
+ fireEvent.click(await screen.findByRole('button', { name: /^Fork v2$/ }));
+
+ await waitFor(() => expect(cloneMusicVideoProject).toHaveBeenCalledWith('mv-1', {}, { silent: true }));
+ await screen.findByRole('heading', { level: 2, name: 'Neon Run v2' });
+ expect(screen.getByText('v2')).toBeTruthy();
+ });
});
describe('MusicVideo audio preview + download', () => {
diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.js
index a449e3ad0c..a2c99c95a3 100644
--- a/client/src/services/apiMusicVideo.js
+++ b/client/src/services/apiMusicVideo.js
@@ -9,6 +9,9 @@ export const getMusicVideoProject = (id, options = {}) => request(`/music-video/
export const createMusicVideoProject = (data, options = {}) => request('/music-video', {
method: 'POST', body: JSON.stringify(data), ...options,
});
+export const cloneMusicVideoProject = (id, data = {}, options = {}) => request(`/music-video/${encodeURIComponent(id)}/clone`, {
+ method: 'POST', body: JSON.stringify(data), ...options,
+});
export const updateMusicVideoProject = (id, patch, options = {}) => request(`/music-video/${encodeURIComponent(id)}`, {
method: 'PATCH', body: JSON.stringify(patch), ...options,
});
diff --git a/scripts/generate_ltx2.py b/scripts/generate_ltx2.py
index 9b5209c481..1bf35652ba 100644
--- a/scripts/generate_ltx2.py
+++ b/scripts/generate_ltx2.py
@@ -178,6 +178,42 @@ def _rate_kwargs(func, fps: float) -> dict:
return {name: fps} if name else {}
+def _bind_combined_image_conditioning_rate(module, fps: float):
+ """Supply frame_rate for the v0.14.x A2V caller that omits it.
+
+ ltx-pipelines-mlx 0.14.8 made ``combined_image_conditionings.frame_rate``
+ mandatory, but its two-stage A2V pipeline still calls that helper twice
+ without the new keyword when an input image is present. Patch the imported
+ orchestration helper for this render only. Pins whose helper predates the
+ parameter are left untouched; already-correct callers may still pass their
+ own rate and win over this default.
+ """
+ original = getattr(module, "combined_image_conditionings", None)
+ if original is None:
+ return lambda: None
+ try:
+ has_frame_rate = "frame_rate" in inspect.signature(original).parameters
+ except (TypeError, ValueError):
+ has_frame_rate = False
+ if not has_frame_rate:
+ return lambda: None
+
+ def combined_image_conditionings_with_rate(*args, **kwargs):
+ kwargs.setdefault("frame_rate", fps)
+ return original(*args, **kwargs)
+
+ module.combined_image_conditionings = combined_image_conditionings_with_rate
+ return lambda: setattr(module, "combined_image_conditionings", original)
+
+
+def _patch_a2v_image_conditioning_rate(fps: float):
+ try:
+ orchestration = importlib.import_module("ltx_pipelines_mlx.utils._orchestration")
+ except ImportError:
+ return lambda: None
+ return _bind_combined_image_conditioning_rate(orchestration, fps)
+
+
def _import_image_conditioning_input():
"""v0.14.x ImageConditioningInput (per-image strength field), or None on old pins.
@@ -801,6 +837,7 @@ def run_a2v(args: argparse.Namespace) -> str:
args.teacache_thresh)
if _A2V_TC_CONFIG["enable"]:
emit_status(f"TeaCache active on A2V Stage 1 (thresh={_teacache_thresh_label(args.teacache_thresh)})")
+ restore_image_rate = _patch_a2v_image_conditioning_rate(args.fps)
try:
return pipe.generate_and_save(
prompt=args.prompt,
@@ -818,6 +855,7 @@ def run_a2v(args: argparse.Namespace) -> str:
**_rate_kwargs(pipe.generate_and_save, args.fps),
)
finally:
+ restore_image_rate()
_A2V_TC_CONFIG = None
diff --git a/scripts/generate_ltx2_teacache_test.py b/scripts/generate_ltx2_teacache_test.py
index 089d320abf..74cbb1fc02 100644
--- a/scripts/generate_ltx2_teacache_test.py
+++ b/scripts/generate_ltx2_teacache_test.py
@@ -142,6 +142,33 @@ class GenerateLtx2TeaCacheTest(unittest.TestCase):
self.assertEqual(self.helper._rate_kwargs(kwargs_only, 24.0), {})
self.assertEqual(self.helper._rate_kwargs(fps_only, 24.0), {"fps": 24.0})
+ def test_a2v_image_conditioning_compat_supplies_missing_frame_rate(self):
+ calls = []
+
+ def combined(images, *, frame_rate):
+ calls.append((images, frame_rate))
+ return "conditioned"
+
+ orchestration = SimpleNamespace(combined_image_conditionings=combined)
+ restore = self.helper._bind_combined_image_conditioning_rate(orchestration, 24.0)
+ self.assertEqual(orchestration.combined_image_conditionings(["frame"]), "conditioned")
+ self.assertEqual(
+ orchestration.combined_image_conditionings(["frame"], frame_rate=30.0),
+ "conditioned",
+ )
+ self.assertEqual(calls, [(["frame"], 24.0), (["frame"], 30.0)])
+ restore()
+ self.assertIs(orchestration.combined_image_conditionings, combined)
+
+ def test_a2v_image_conditioning_compat_ignores_old_helper(self):
+ def combined(images):
+ return images
+
+ orchestration = SimpleNamespace(combined_image_conditionings=combined)
+ restore = self.helper._bind_combined_image_conditioning_rate(orchestration, 24.0)
+ self.assertIs(orchestration.combined_image_conditionings, combined)
+ restore()
+
def test_one_stage_kwargs_omits_num_steps_when_steps_unset(self):
args = SimpleNamespace(
prompt="p", output="o.mp4", height=480, width=704,
@@ -311,6 +338,7 @@ class GenerateLtx2TeaCacheTest(unittest.TestCase):
model="m", gemma="g", extend_from_video="in.mp4", prompt="p",
extend_frames=2, extend_direction="after", seed=0, steps=None,
cfg_scale=None, no_teacache=False, teacache_thresh=None,
+ user_lora_specs=[],
)
try:
self.helper._EXTEND_TC_CONFIG = None
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index 4f91ae97b7..262b37d25e 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -34,6 +34,9 @@ export const musicVideoVideoSettingsSchema = z.object({
backend: z.enum(['local', 'grok']).optional(),
modelId: z.string().max(64).nullable().optional(),
grokDuration: z.union([z.literal(6), z.literal(10)]).optional(),
+ generationMode: z.enum(['image', 'audioReactive']).optional(),
+ audioReactiveLora: z.string().max(255).regex(/^[^/\\]+\.safetensors$/i).nullable().optional(),
+ audioReactiveScale: z.number().min(0).max(2).optional(),
}).strict();
export const musicVideoProjectCreateSchema = z.object({
@@ -59,6 +62,14 @@ export const musicVideoProjectUpdateSchema = z.object({
renderHistoryId: z.string().max(64).nullable().optional(),
}).strict();
+// Fork a project into its next editable version. The server derives lineage and
+// version numbers from the source; callers may only override the display name
+// and choose whether generated scene media should remain attached.
+export const musicVideoProjectCloneSchema = z.object({
+ name: z.string().min(1).max(200).optional(),
+ includeGeneratedMedia: z.boolean().optional(),
+}).strict();
+
// A scene on the director board. `startSec`/`endSec` place it on the timeline;
// `prompt` drives the shot's video; `framePrompt`/`referenceImageId` are the
// reference-frame inputs the i2v generation (Phase 1b) will consume.
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index 5f521bbbdb..113379c650 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -13,6 +13,7 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import {
validateRequest,
musicVideoProjectCreateSchema,
+ musicVideoProjectCloneSchema,
musicVideoProjectUpdateSchema,
musicVideoSceneCreateSchema,
musicVideoSceneUpdateSchema,
@@ -27,6 +28,7 @@ import {
listProjects,
getProject,
createProject,
+ cloneProject,
updateProject,
deleteProject,
setProjectAnalysis,
@@ -64,6 +66,11 @@ router.post('/', asyncHandler(async (req, res) => {
res.status(201).json(project);
}));
+router.post('/:id/clone', asyncHandler(async (req, res) => {
+ const options = validateRequest(musicVideoProjectCloneSchema, req.body || {});
+ res.status(201).json(await cloneProject(req.params.id, options));
+}));
+
router.patch('/:id', asyncHandler(async (req, res) => {
const data = validateRequest(musicVideoProjectUpdateSchema, req.body);
const updated = await updateProject(req.params.id, data);
diff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.js
index eeb9b0b5c1..8dc7716fe2 100644
--- a/server/routes/musicVideo.test.js
+++ b/server/routes/musicVideo.test.js
@@ -7,6 +7,9 @@ vi.mock('../services/musicVideo/projects.js', () => ({
listProjects: vi.fn(async () => [{ id: 'mv-1', name: 'A' }]),
getProject: vi.fn(),
createProject: vi.fn(async (d) => ({ id: 'mv-new', ...d })),
+ cloneProject: vi.fn(async (id, options) => ({
+ id: 'mv-clone', name: options.name || 'A v2', version: 2, parentProjectId: id,
+ })),
updateProject: vi.fn(async (id, p) => ({ id, ...p })),
deleteProject: vi.fn(async () => ({ ok: true })),
setProjectAnalysis: vi.fn(async (id, analysis) => ({ id, audioAnalysis: analysis, status: 'analyzed' })),
@@ -101,6 +104,23 @@ describe('musicVideo routes', () => {
expect(r.status).toBe(400);
});
+ it('POST /:id/clone creates the next version and accepts an optional name', async () => {
+ const r = await request(app).post('/api/music-video/mv-1/clone')
+ .send({ name: 'Director Cut', includeGeneratedMedia: true });
+ expect(r.status).toBe(201);
+ expect(r.body).toMatchObject({ id: 'mv-clone', name: 'Director Cut', version: 2, parentProjectId: 'mv-1' });
+ expect(svc.cloneProject).toHaveBeenCalledWith('mv-1', {
+ name: 'Director Cut',
+ includeGeneratedMedia: true,
+ });
+ });
+
+ it('POST /:id/clone rejects unsupported options', async () => {
+ const r = await request(app).post('/api/music-video/mv-1/clone').send({ copyFinalRender: true });
+ expect(r.status).toBe(400);
+ expect(svc.cloneProject).not.toHaveBeenCalled();
+ });
+
it('PATCH /:id updates', async () => {
const r = await request(app).patch('/api/music-video/mv-1').send({ name: 'Renamed' });
expect(r.status).toBe(200);
@@ -108,7 +128,14 @@ describe('musicVideo routes', () => {
});
it('PATCH /:id accepts bounded project video-renderer settings', async () => {
- const videoSettings = { backend: 'local', modelId: 'ltx23_dgrauet_q4', grokDuration: 10 };
+ const videoSettings = {
+ backend: 'local',
+ modelId: 'ltx23_dgrauet_q4',
+ grokDuration: 10,
+ generationMode: 'audioReactive',
+ audioReactiveLora: 'audio-reactive.safetensors',
+ audioReactiveScale: 1.2,
+ };
const r = await request(app).patch('/api/music-video/mv-1').send({ videoSettings });
expect(r.status).toBe(200);
expect(svc.updateProject).toHaveBeenCalledWith('mv-1', { videoSettings });
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 7feb3888fd..62e9d06dc1 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -21,6 +21,8 @@ import { safeUnder } from '../lib/ffmpeg.js';
import { grokVideoDurationSchema } from '../lib/validation.js';
import { IMAGE_GEN_MODE } from '../services/imageGen/modes.js';
import { getSettings } from '../services/settings.js';
+import { getProject as getMusicVideoProject } from '../services/musicVideo/projects.js';
+import { getTrack } from '../services/tracks/index.js';
import { checkPackages, isAllowedPython } from '../lib/pythonSetup.js';
import { safeChildProcessEnv } from '../lib/processEnv.js';
import { createLineReader } from '../lib/streamLines.js';
@@ -149,6 +151,7 @@ const generateBodySchema = z.object({
guidanceScale: optionalNum(0, 30, 'guidanceScale'),
seed: optionalNum(0, Number.MAX_SAFE_INTEGER, 'seed'),
imageStrength: optionalNum(0, 1, 'imageStrength'),
+ audioStartSec: optionalNum(0, 36000, 'audioStartSec'),
tiling: z.enum(['auto', 'none', 'spatial', 'temporal']).optional(),
disableAudio: z.union([z.boolean(), z.literal('true'), z.literal('false')]).optional(),
sourceImageFile: z.string().max(512).optional(),
@@ -817,6 +820,25 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
return durablePath;
};
+ // Music-video a2v jobs reuse an existing library track rather than uploading
+ // the same song for every cut. Copy it into the queue-owned uploads area so
+ // the worker may safely delete its input on completion without ever touching
+ // the source track under data/music.
+ const stageExistingAudioDurable = async (sourcePath) => {
+ const ext = extname(sourcePath) || '.bin';
+ const durablePath = join(PATHS.uploads, `video-audio-${randomUUID()}${ext}`);
+ await copyFile(sourcePath, durablePath).catch(async (err) => {
+ await unlink(durablePath).catch(() => {});
+ await cleanupAllStaged();
+ throw new ServerError(
+ `Failed to stage project audio: ${err.message}`,
+ { status: 500, code: 'VIDEO_GEN_AUDIO_STAGE_FAILED' },
+ );
+ });
+ stagedDurablePaths.push(durablePath);
+ return durablePath;
+ };
+
// Resolution precedence on each frame side: a fresh upload always wins over
// a gallery filename so users can override a stale gallery pick by dropping
// in a new file without first clearing the picker.
@@ -831,10 +853,10 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
// unlinks the OS temp file (cheap) instead of also unlinking a freshly-
// copied 100MB durable file under data/uploads (wasted disk I/O on every
// bad request).
- if (body.mode === 'a2v' && !uploads.audioFile) {
+ if (body.mode === 'a2v' && !uploads.audioFile && !body.musicVideo) {
await cleanupAllStaged();
throw new ServerError(
- 'a2v mode requires an audioFile upload (multipart field name: audioFile).',
+ 'a2v mode requires an audioFile upload or a music-video project audio source.',
{ status: 400, code: 'VIDEO_GEN_AUDIO_REQUIRED' },
);
}
@@ -1051,6 +1073,22 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
// worker drops it on terminal events the same way it drops lastImage.
audioFilePath = await stageUploadDurable(uploads.audioFile, 'audio');
extraUploadedTempPaths.push(audioFilePath);
+ } else if (body.mode === 'a2v' && body.musicVideo) {
+ const project = await getMusicVideoProject(body.musicVideo.projectId);
+ const sceneExists = project?.scenes?.some((scene) => scene.sceneId === body.musicVideo.sceneId);
+ if (!project || !sceneExists) {
+ await cleanupAllStaged();
+ throw new ServerError('Music-video project or scene not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ const track = project.trackId ? await getTrack(project.trackId) : null;
+ const filename = track?.audioFilename || project.uploadedAudioFilename;
+ const sourceAudioPath = filename ? safeUnder(PATHS.music, filename) : null;
+ if (!sourceAudioPath || !existsSync(sourceAudioPath)) {
+ await cleanupAllStaged();
+ throw new ServerError('Music-video project audio is unavailable', { status: 400, code: 'VIDEO_GEN_PROJECT_AUDIO_MISSING' });
+ }
+ audioFilePath = await stageExistingAudioDurable(sourceAudioPath);
+ extraUploadedTempPaths.push(audioFilePath);
}
if (uploads.icReference) {
// IC-LoRA reference clip — same durable staging + cleanup tracking as the
@@ -1286,6 +1324,7 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
disableAudio: body.disableAudio === true || body.disableAudio === 'true',
sourceImagePath,
audioFilePath,
+ audioStartSec: body.audioStartSec,
uploadedTempPath,
uploadedTempPaths: extraUploadedTempPaths,
lastImagePath,
@@ -1330,6 +1369,7 @@ const ACTIVE_JOB_PARAM_FIELDS = [
'width', 'height', 'numFrames', 'fps',
'steps', 'guidanceScale', 'seed',
'tiling', 'disableAudio', 'mode', 'chunks', 'imageStrength',
+ 'audioStartSec',
// Grok jobs (#2859 phase 2): the semantic t2v/i2v mode ('mode' holds the
// 'grok' discriminator for them) and the clip duration — both plain
// values, safe to echo for the reloading page's form restore.
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index 89bf2e4d4d..1326a5d270 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -7,6 +7,14 @@ vi.mock('../services/settings.js', () => ({
getSettings: vi.fn(async () => ({ imageGen: { local: { pythonPath: '/usr/bin/python3' } } })),
}));
+vi.mock('../services/musicVideo/projects.js', () => ({
+ getProject: vi.fn(),
+}));
+
+vi.mock('../services/tracks/index.js', () => ({
+ getTrack: vi.fn(),
+}));
+
vi.mock('../lib/pythonSetup.js', () => ({
checkPackages: vi.fn(async () => ({ installed: ['mflux', 'mlx'], missing: [], missingPip: [] })),
isAllowedPython: vi.fn(() => true),
@@ -92,7 +100,14 @@ vi.mock('../lib/multipart.js', () => ({
vi.mock('../lib/fileUtils.js', () => ({
tryReadFile: vi.fn().mockResolvedValue(null),
- PATHS: { root: '/mock', data: '/mock/data', images: '/mock/images', videos: '/mock/videos', uploads: '/mock/uploads' },
+ PATHS: {
+ root: '/mock',
+ data: '/mock/data',
+ images: '/mock/images',
+ videos: '/mock/videos',
+ uploads: '/mock/uploads',
+ music: '/mock/music',
+ },
// Route awaits ensureDir before staging the upload; no-op for tests since
// we mock copyFile too.
ensureDir: vi.fn(async () => {}),
@@ -121,6 +136,8 @@ vi.mock('fs/promises', () => ({
import * as videoGenService from '../services/videoGen/local.js';
import * as mediaJobQueue from '../services/mediaJobQueue/index.js';
+import { getProject as getMusicVideoProject } from '../services/musicVideo/projects.js';
+import { getTrack } from '../services/tracks/index.js';
import { resolveGalleryImage } from '../lib/fileUtils.js';
import { listIcLoraWeights } from '../lib/icLoraWeights.js';
import videoGenRoutes, { isAudioMime } from './videoGen.js';
@@ -776,6 +793,40 @@ describe('videoGen routes', () => {
}));
});
+ it('stages project audio and forwards the scene song offset for music-video a2v', async () => {
+ getMusicVideoProject.mockResolvedValue({
+ id: 'mv-example',
+ trackId: 'track-example',
+ scenes: [{ sceneId: 'scene-example' }],
+ });
+ getTrack.mockResolvedValue({ id: 'track-example', audioFilename: 'example-song.wav' });
+
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'rain pulses with the percussion; no performers',
+ mode: 'a2v',
+ sourceImageFile: 'reference.png',
+ audioStartSec: 42.5,
+ disableAudio: true,
+ musicVideo: { projectId: 'mv-example', sceneId: 'scene-example' },
+ });
+
+ expect(r.status).toBe(200);
+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({
+ kind: 'video',
+ params: expect.objectContaining({
+ mode: 'a2v',
+ sourceImagePath: '/mock/images/reference.png',
+ audioStartSec: 42.5,
+ disableAudio: true,
+ audioFilePath: expect.stringMatching(/\/mock\/uploads\/video-audio-.*\.wav$/),
+ uploadedTempPaths: expect.arrayContaining([
+ expect.stringMatching(/\/mock\/uploads\/video-audio-.*\.wav$/),
+ ]),
+ musicVideo: { projectId: 'mv-example', sceneId: 'scene-example' },
+ }),
+ }));
+ });
+
// a2v on a non-ltx2 model would fail later inside the worker
// (buildArgs throws A2V_REQUIRES_LTX2). The route catches it up front so
// a typo / stale UI state doesn't pollute the persisted queue with a
diff --git a/server/services/musicVideo/projects.js b/server/services/musicVideo/projects.js
index 31e3583981..480198e75e 100644
--- a/server/services/musicVideo/projects.js
+++ b/server/services/musicVideo/projects.js
@@ -69,6 +69,12 @@ export async function createProject(input) {
return project;
}
+export async function cloneProject(id, options = {}) {
+ const project = await (await selectBackend()).cloneProject(id, options);
+ announceNewProject(project.id);
+ return project;
+}
+
export async function updateProject(id, patch) {
const next = await (await selectBackend()).updateProject(id, patch);
emitRecordUpdated('musicVideoProject', id);
diff --git a/server/services/musicVideo/projectsDB.js b/server/services/musicVideo/projectsDB.js
index af5a211a46..cd2d38bce9 100644
--- a/server/services/musicVideo/projectsDB.js
+++ b/server/services/musicVideo/projectsDB.js
@@ -16,6 +16,7 @@ import {
mirrorStatus,
mirrorTimestamp,
buildProjectRecord,
+ cloneProjectRecord,
applyProjectPatch,
setAudioAnalysis,
setMidiTranscription,
@@ -93,6 +94,23 @@ export async function createProject(input) {
return project;
}
+export async function cloneProject(id, options = {}) {
+ return withTransaction(async (client) => {
+ const sel = await client.query(`SELECT data FROM music_video_projects WHERE id = $1 FOR SHARE`, [id]);
+ const source = rowToProject(sel.rows[0]);
+ if (!source || source.deleted) {
+ throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ const clone = cloneProjectRecord(source, {
+ ...options,
+ id: `mv-${randomUUID()}`,
+ now: new Date().toISOString(),
+ });
+ await persist(client.query.bind(client), clone);
+ return clone;
+ });
+}
+
// Lock the row, apply `mutate(project)`, persist, return the mutator's result.
// Throws NOT_FOUND when the row is absent or tombstoned (a post-delete write
// must not resurrect the row).
diff --git a/server/services/musicVideo/projectsFile.js b/server/services/musicVideo/projectsFile.js
index 3d3436684c..0efa447cad 100644
--- a/server/services/musicVideo/projectsFile.js
+++ b/server/services/musicVideo/projectsFile.js
@@ -13,6 +13,7 @@ import { PATHS, readJSONFile, atomicWrite, ensureDir } from '../../lib/fileUtils
import { ServerError } from '../../lib/errorHandler.js';
import {
buildProjectRecord,
+ cloneProjectRecord,
applyProjectPatch,
setAudioAnalysis,
setMidiTranscription,
@@ -68,6 +69,20 @@ export async function createProject(input) {
return project;
}
+export async function cloneProject(id, options = {}) {
+ const all = await loadAll();
+ const source = all.find((project) => project.id === id && !project.deleted);
+ if (!source) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ const clone = cloneProjectRecord(source, {
+ ...options,
+ id: `mv-${randomUUID()}`,
+ now: new Date().toISOString(),
+ });
+ all.push(clone);
+ await saveAll(all);
+ return clone;
+}
+
// Locate a live (non-tombstoned) project for a user-facing mutator, or throw 404.
async function loadAllAndIndex(id) {
const all = await loadAll();
diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.js
index f1bd7719fa..613e7ba35f 100644
--- a/server/services/musicVideo/projectsLogic.js
+++ b/server/services/musicVideo/projectsLogic.js
@@ -65,6 +65,9 @@ export function buildProjectRecord(input, { id, now }) {
return {
id,
name,
+ version: 1,
+ parentProjectId: null,
+ rootProjectId: null,
status: 'draft',
mode,
createdAt: now,
@@ -76,6 +79,9 @@ export function buildProjectRecord(input, { id, now }) {
backend: videoSettings.backend ?? 'local',
modelId: videoSettings.modelId ?? null,
grokDuration: videoSettings.grokDuration ?? 10,
+ generationMode: videoSettings.generationMode ?? 'image',
+ audioReactiveLora: videoSettings.audioReactiveLora ?? null,
+ audioReactiveScale: videoSettings.audioReactiveScale ?? 1.2,
},
audioAnalysis: null,
midiTranscription: null,
@@ -88,6 +94,48 @@ export function buildProjectRecord(input, { id, now }) {
};
}
+/** Build an independently editable next version while reusing immutable media assets. */
+export function cloneProjectRecord(source, {
+ id,
+ now,
+ name,
+ includeGeneratedMedia = true,
+}) {
+ const nameMatch = typeof source.name === 'string' ? source.name.match(/^(.*?)(?:\s+v(\d+))?$/i) : null;
+ const inferredVersion = Number(nameMatch?.[2]) || 1;
+ const sourceVersion = Number.isInteger(source.version) && source.version > 0
+ ? source.version
+ : inferredVersion;
+ const version = sourceVersion + 1;
+ const baseName = nameMatch?.[1]?.trim() || source.name || 'Music Video';
+ const scenes = (source.scenes || []).map((scene, order) => ({
+ ...scene,
+ sceneId: `mvs-${randomUUID()}`,
+ order,
+ referenceImageId: includeGeneratedMedia ? (scene.referenceImageId ?? null) : null,
+ videoHistoryId: includeGeneratedMedia ? (scene.videoHistoryId ?? null) : null,
+ }));
+ const mediaReady = includeGeneratedMedia
+ && scenes.length > 0
+ && scenes.every((scene) => scene.referenceImageId && scene.videoHistoryId);
+
+ return {
+ ...source,
+ id,
+ name: name?.trim() || `${baseName} v${version}`,
+ version,
+ parentProjectId: source.id,
+ rootProjectId: source.rootProjectId || source.id,
+ status: source.audioAnalysis ? (mediaReady ? 'ready' : 'analyzed') : 'draft',
+ createdAt: now,
+ updatedAt: now,
+ scenes,
+ renderHistoryId: null,
+ deleted: false,
+ deletedAt: null,
+ };
+}
+
/** Merge a project metadata patch, validating status. Returns the next record. */
export function applyProjectPatch(project, patch) {
if (patch.status && !MUSIC_VIDEO_STATUSES.includes(patch.status)) {
@@ -110,6 +158,9 @@ export function applyProjectPatch(project, patch) {
backend: 'local',
modelId: null,
grokDuration: 10,
+ generationMode: 'image',
+ audioReactiveLora: null,
+ audioReactiveScale: 1.2,
...project.videoSettings,
...conceptMergedPatch.videoSettings,
},
diff --git a/server/services/musicVideo/projectsLogic.test.js b/server/services/musicVideo/projectsLogic.test.js
index e73f963c74..079c2d89d3 100644
--- a/server/services/musicVideo/projectsLogic.test.js
+++ b/server/services/musicVideo/projectsLogic.test.js
@@ -1,6 +1,7 @@
import { describe, it, expect } from 'vitest';
import {
buildProjectRecord,
+ cloneProjectRecord,
applyProjectPatch,
setAudioAnalysis,
setMidiTranscription,
@@ -21,6 +22,7 @@ describe('buildProjectRecord', () => {
const p = buildProjectRecord({ name: 'Neon Nights', trackId: 'track-9' }, { id: 'mv-x', now: '2026-01-01T00:00:00.000Z' });
expect(p).toMatchObject({
id: 'mv-x', name: 'Neon Nights', status: 'draft', mode: 'director',
+ version: 1, parentProjectId: null, rootProjectId: null,
trackId: 'track-9', uploadedAudioFilename: null, concept: null,
videoSettings: { backend: 'local', modelId: null, grokDuration: 10 },
audioAnalysis: null, midiTranscription: null, scenes: [], renderHistoryId: null,
@@ -36,6 +38,74 @@ describe('buildProjectRecord', () => {
});
});
+describe('cloneProjectRecord', () => {
+ it('creates an editable next version with fresh scene ids and reusable media', () => {
+ const source = {
+ ...baseProject(),
+ status: 'complete',
+ renderHistoryId: 'final-1',
+ audioAnalysis: {
+ bpm: 120, beats: [0], downbeats: [0],
+ sections: [{ label: 'S', startSec: 0, endSec: 5 }],
+ durationSec: 5,
+ },
+ scenes: [{
+ sceneId: 'scene-old',
+ order: 0,
+ prompt: 'Tracking shot',
+ referenceImageId: 'frame.png',
+ videoHistoryId: 'clip-1',
+ }],
+ };
+
+ const clone = cloneProjectRecord(source, {
+ id: 'mv-2',
+ now: '2026-01-02T00:00:00.000Z',
+ });
+
+ expect(clone).toMatchObject({
+ id: 'mv-2',
+ name: 'Test MV v2',
+ version: 2,
+ parentProjectId: 'mv-1',
+ rootProjectId: 'mv-1',
+ status: 'ready',
+ renderHistoryId: null,
+ createdAt: '2026-01-02T00:00:00.000Z',
+ updatedAt: '2026-01-02T00:00:00.000Z',
+ });
+ expect(clone.scenes[0]).toMatchObject({
+ order: 0,
+ referenceImageId: 'frame.png',
+ videoHistoryId: 'clip-1',
+ });
+ expect(clone.scenes[0].sceneId).not.toBe('scene-old');
+ expect(source.scenes[0].sceneId).toBe('scene-old');
+ });
+
+ it('can fork the board without carrying generated media', () => {
+ const source = {
+ ...baseProject(),
+ version: 2,
+ rootProjectId: 'mv-root',
+ scenes: [{ sceneId: 'old', order: 0, referenceImageId: 'frame.png', videoHistoryId: 'clip-1' }],
+ };
+ const clone = cloneProjectRecord(source, {
+ id: 'mv-3',
+ now: '2026-01-03T00:00:00.000Z',
+ includeGeneratedMedia: false,
+ });
+
+ expect(clone).toMatchObject({
+ version: 3,
+ parentProjectId: 'mv-1',
+ rootProjectId: 'mv-root',
+ name: 'Test MV v3',
+ });
+ expect(clone.scenes[0]).toMatchObject({ referenceImageId: null, videoHistoryId: null });
+ });
+});
+
describe('applyProjectPatch', () => {
it('merges fields and bumps updatedAt', () => {
const next = applyProjectPatch(baseProject(), { name: 'Renamed', trackId: 't2' });
@@ -166,7 +236,14 @@ describe('applyProjectPatch', () => {
name: 'A',
videoSettings: { backend: 'grok', grokDuration: 6 },
}, { id: 'mv-2', now: 'n' });
- expect(project.videoSettings).toEqual({ backend: 'grok', modelId: null, grokDuration: 6 });
+ expect(project.videoSettings).toEqual({
+ backend: 'grok',
+ modelId: null,
+ grokDuration: 6,
+ generationMode: 'image',
+ audioReactiveLora: null,
+ audioReactiveScale: 1.2,
+ });
const next = applyProjectPatch(project, {
videoSettings: { backend: 'local', modelId: 'ltx23_distilled_q4' },
@@ -175,6 +252,9 @@ describe('applyProjectPatch', () => {
backend: 'local',
modelId: 'ltx23_distilled_q4',
grokDuration: 6,
+ generationMode: 'image',
+ audioReactiveLora: null,
+ audioReactiveScale: 1.2,
});
});
});
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index 0e05305a21..d562e2430b 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -352,7 +352,7 @@ export const icLoraArgs = ({ mode, width, height, icReferencePaths, icLoraWeight
return args;
};
-const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, disableAudio, outputPath, textEncoderRepo, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 }) => {
+const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, disableAudio, outputPath, textEncoderRepo, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 }) => {
assertByovRuntimeInstalled('ltx2');
// Map PortOS UI modes to the helper's subcommand. Native extend on ltx2
// routes to ExtendPipeline.extend_from_video — conditions on the entire
@@ -502,6 +502,7 @@ const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames
}
if (helperMode === 'a2v') {
args.push('--audio', audioFilePath);
+ if (audioStartSec != null) args.push('--audio-start', String(audioStartSec));
// Optional first-frame conditioning — when the user supplied a source
// image, AudioToVideoPipeline conditions frame 0 the same way I2V does
// so motion + audio sync to the chosen still.
@@ -587,12 +588,12 @@ const buildHunyuanArgs = ({ model, prompt, negativePrompt, width, height, numFra
return { bin: HUNYUAN_VENV_PYTHON, args };
};
-const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, textEncoderRepo, outputPath, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 }) => {
+const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, textEncoderRepo, outputPath, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 }) => {
// Route to the dgrauet/ltx-2-mlx helper when the model declares the new
// runtime. Existing notapalindrome models default to runtime: 'mlx_video'
// (or undefined in legacy registries — see backfillRuntime in mediaModels.js).
if (model.runtime === 'ltx2') {
- return buildLtx2Args({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, disableAudio, outputPath, textEncoderRepo, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 });
+ return buildLtx2Args({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, disableAudio, outputPath, textEncoderRepo, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 });
}
// IC-LoRA remix modes are an LTX-2 primitive (ICLoraPipeline) — no other
// runtime has an equivalent. The route guards this too, but a non-route
@@ -716,7 +717,7 @@ export const DEFAULT_NUM_FRAMES = 121;
// a still regardless of how many frames carry it.
export const IC_STILL_REFERENCE_FRAMES = 9;
-export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId = defaultVideoModelId(), width = 768, height = 512, numFrames = DEFAULT_NUM_FRAMES, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, uploadedTempPaths = [], lastImagePath = null, keyframes = null, extendFromVideoPath = null, audioFilePath = null, mode = null, imageStrength = null, loras = null, icReferencePaths = null, icStrength = null, icAttentionStrength = null, icSkipStage2 = false, hidden = false, jobId: providedJobId = null }) {
+export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId = defaultVideoModelId(), width = 768, height = 512, numFrames = DEFAULT_NUM_FRAMES, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, uploadedTempPaths = [], lastImagePath = null, keyframes = null, extendFromVideoPath = null, audioFilePath = null, audioStartSec = null, mode = null, imageStrength = null, loras = null, icReferencePaths = null, icStrength = null, icAttentionStrength = null, icSkipStage2 = false, hidden = false, jobId: providedJobId = null }) {
uploadedTempPaths = Array.isArray(uploadedTempPaths) ? uploadedTempPaths : [];
if (!prompt?.trim()) throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
// Single-flight is now enforced by the mediaJobQueue worker upstream — only
@@ -1029,7 +1030,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// logic of the spawn-error handler so failure modes converge.
let bin, args;
try {
- ({ bin, args } = buildArgs({ pythonPath, modelId, model, prompt, 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, mode, imageStrength: actualImageStrength, textEncoderRepo: actualTextEncoderRepo, outputPath, loras: resolvedLoras, icReferencePaths: resolvedIcReferencePaths, icLoraWeightPath, icStrength: actualIcStrength, icAttentionStrength: actualIcAttentionStrength, icSkipStage2 }));
+ ({ bin, args } = buildArgs({ pythonPath, modelId, model, prompt, negativePrompt, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, steps: actualSteps, stage2Steps: actualStage2Steps, guidance: actualGuidance, seed: actualSeed, tiling, disableAudio, sourceImagePath: resolvedSourceImage, lastImagePath: resolvedLastImage, keyframes: resolvedKeyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength: actualImageStrength, textEncoderRepo: actualTextEncoderRepo, outputPath, loras: resolvedLoras, icReferencePaths: resolvedIcReferencePaths, icLoraWeightPath, icStrength: actualIcStrength, icAttentionStrength: actualIcAttentionStrength, icSkipStage2 }));
} catch (err) {
job.status = 'error';
const reason = err.message || 'Failed to build video gen args';
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index 7a2fc554ed..b958758e8c 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -428,6 +428,43 @@ describe('generateVideo — ltx2 FFLF image resizing', () => {
});
});
+describe('generateVideo — LTX audio-reactive conditioning', () => {
+ it('threads the song offset while disabling generated clip audio', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
+ spawnMock.mockClear();
+
+ await generateVideo({
+ jobId: 'audio-reactive-offset-test',
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx2_unified',
+ prompt: 'streetlights pulse with the music; no performers',
+ width: 512,
+ height: 512,
+ numFrames: 25,
+ fps: 24,
+ mode: 'a2v',
+ sourceImagePath: '/mock/source.png',
+ audioFilePath: '/mock/song.wav',
+ audioStartSec: 42.5,
+ disableAudio: true,
+ });
+
+ const renderCall = spawnMock.mock.calls.find(
+ ([bin, args]) => String(bin).includes('.portos/ltx-2-mlx/.venv/bin/python3')
+ && Array.isArray(args)
+ && args.includes('--mode')
+ && args.includes('a2v'),
+ );
+ expect(renderCall).toBeTruthy();
+ expect(renderCall[1]).toEqual(expect.arrayContaining([
+ '--audio', '/mock/song.wav',
+ '--audio-start', '42.5',
+ '--no-audio',
+ ]));
+ });
+});
+
describe('generateVideo — PORTOS_T2V_TWO_STAGE arg threading', () => {
afterEach(() => { delete process.env.PORTOS_T2V_TWO_STAGE; });