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: finish music video director workflow
[._.]/ Adam Eivyf60f4b5fbe11
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 30627af5fd..4fd387dd04 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -4,6 +4,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.## Agent workspaces@@ -25,6 +26,7 @@## Fixed+- **Music Video final renders now honor the authored song timeline.** Scene clips loop when their generated source is shorter than the beat-aligned cut, so an arrangement can cover the full track instead of being silently truncated to each model's native clip length.- **The task form's Screenshot and Attach buttons work again — a stuck notification was eating the clicks.** A notice that never goes away (the "Install out of sync" warning, "Update available", "New build available") parks in the bottom-right corner, and on a desktop window it landed on top of the Chief of Staff task form and silently absorbed every click meant for the buttons underneath. They did nothing at all — no file picker, no error, nothing in the browser console — which is why it read as a broken button rather than something covering one, and why the same page still worked on a phone, where the layout puts those buttons elsewhere. On a 1280×720 window the notice covered a 520×86px block starting at the exact pixel the Attach button begins. Notices that never dismiss themselves now fold into a small badge in the corner after 8 seconds (1600px², clear of the page); clicking the badge brings the message back, and it stays open while you hover it or use its buttons. Toasts with a set lifetime — including the manuscript Undo prompt — are untouched.- **CoS agent PRs no longer open with TUI startup noise as their description.** A PR that PortOS opened for a Codex/Antigravity/OpenCode agent led with the session's own lifecycle log — `📟 TUI session started: … (codex …)`, `💡 Open the Shell tab…`, `📟 Prompt pasted…` — before getting to what the agent actually did. The PR description now starts at the agent's completion summary and drops PortOS's status lines, along with the trailing `## Branch` / `## PR` section that only repeats what the PR page already shows.- **Review Hub success-rate alerts now require recent runs.** Low lifetime rates for task types that have been idle no longer appear as current health anomalies; alerts are shown only after enough runs occur in the rolling 30-day performance window.diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex 58484001db..c5768cfe48 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -3,6 +3,7 @@ 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 toast from '../components/ui/Toast';import PageHeader from '../components/PageHeader';+import Drawer from '../components/Drawer.jsx';import {listMusicVideoProjects,createMusicVideoProject,@@ -28,15 +29,17 @@ 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 } from '../services/apiImageVideo.js';+import { generateVideo, getVideoGenStatus } from '../services/apiImageVideo.js';import { listTracks, trackAudioUrl } from '../services/apiTracks.js';import BeatTimeline from '../components/musicVideo/BeatTimeline.jsx';import { autoArrangeScenes } from '../lib/beatGrid.js';import useSceneRenderLifecycle from '../hooks/useSceneRenderLifecycle.js';+import { useVideoFileSrc } from '../hooks/useVideoFileSrc.js';import useYoutubeTrackImport from '../hooks/useYoutubeTrackImport.js';import { useSseProgress, isTerminalSseFrame } from '../hooks/useSseProgress.js';import { formatDurationSec } from '../utils/formatters.js';import { MUSCRIPTOR_MODELS, DEFAULT_MUSCRIPTOR_MODEL } from '../lib/muscriptorModels.js';+import { GROK_VIDEO_DURATIONS } from '../lib/grokVideoClip.js';import { clampBpm } from '../lib/metronome.js';// Matches musicVideoManualAnalysisSchema's `bpm.max` on the server —@@ -109,6 +112,10 @@ export default function MusicVideo() {const [analyzing, setAnalyzing] = useState(false);const [arranging, setArranging] = useState(false);const [planning, setPlanning] = useState(false);+ const [createOpen, setCreateOpen] = useState(false);+ const [videoModels, setVideoModels] = useState([]);+ const [defaultVideoModel, setDefaultVideoModel] = useState('');+ const [videoSettingsSaving, setVideoSettingsSaving] = useState(false);const [form, setForm] = useState({ name: '', mode: 'director', trackId: '' });// The project a detail-view YouTube import is bound to (captured at kickoff).// The import's shared UI slot (progress button + disabled track controls)@@ -219,6 +226,18 @@ export default function MusicVideo() {.then((data) => { setProjects(data || []); setLoading(false); }).catch((err) => { toast.error(err?.message || 'Failed to load music video projects'); setLoading(false); });listTracks({ silent: true }).then((t) => setTracks(t || [])).catch(() => setTracks([]));+ getVideoGenStatus({ silent: true })+ .then((status) => {+ // Music-video scenes always start from a reference frame. Hide+ // explicitly text-only models, while retaining general LTX models+ // whose runtime supports both text and image conditioning.+ setVideoModels((status?.models || []).filter((model) => model.mode !== 't2v' && !model.deprecated));+ setDefaultVideoModel(status?.defaultModel || '');+ })+ .catch(() => {+ setVideoModels([]);+ setDefaultVideoModel('');+ });}, []);const trackName = useCallback((id) => tracks.find((t) => t.id === id)?.title || id || '—', [tracks]);@@ -249,6 +268,7 @@ export default function MusicVideo() {setProjects((prev) => [...prev, proj]);selectProject(proj.id);setForm({ name: '', mode: 'director', trackId: '' });+ setCreateOpen(false);toast.success('Project created');}).catch((err) => toast.error(err?.message || 'Failed to create project'));@@ -429,6 +449,27 @@ export default function MusicVideo() {const renderTargetsSelected = !!(render && selected && render.projectId === selected.id);// The number of scenes that already have a generated clip — the render's inputs.const renderableSceneCount = (selected?.scenes || []).filter((s) => s.videoHistoryId).length;+ const sceneCount = selected?.scenes?.length || 0;+ const referenceFrameCount = (selected?.scenes || []).filter((s) => s.referenceImageId).length;+ const missingFrameCount = sceneCount - referenceFrameCount;+ const missingVideoCount = sceneCount - renderableSceneCount;+ const finalVideo = useVideoFileSrc(selected?.renderHistoryId, { enabled: !!selected?.renderHistoryId });+ const savedVideoSettings = {+ backend: selected?.videoSettings?.backend || 'local',+ // Empty is an intentional "follow the local Video Gen default" choice,+ // distinct from pinning the model that happens to be default today.+ modelId: selected?.videoSettings?.modelId || '',+ grokDuration: selected?.videoSettings?.grokDuration || 10,+ };+ const effectiveVideoModelId = savedVideoSettings.modelId || defaultVideoModel;+ const activeVideoModel = videoModels.find((model) => model.id === effectiveVideoModelId) || null;+ const authoredCutDurations = (selected?.scenes || [])+ .filter((scene) => typeof scene.startSec === 'number' && typeof scene.endSec === 'number' && scene.endSec > scene.startSec)+ .map((scene) => scene.endSec - scene.startSec);+ const averageCutSec = authoredCutDurations.length > 0+ ? authoredCutDurations.reduce((sum, duration) => sum + duration, 0) / authoredCutDurations.length+ : null;+ const longCutCount = authoredCutDurations.filter((duration) => duration > 10).length;// React to terminal SSE frames: record the render on the project, surface the// outcome, and clear the in-flight job. Functional update keys on the captured@@ -512,6 +553,33 @@ export default function MusicVideo() {.catch((err) => toast.error(err?.message || 'Failed to save scene'));};+ // Renderer/model is a project-level production decision, not a transient+ // browser preference. Save each change before allowing new video jobs so the+ // job payload and the board's displayed setting cannot disagree.+ const handleVideoSettingsChange = (patch) => {+ if (!selected || videoSettingsSaving) return;+ const projectId = selected.id;+ const previous = selected.videoSettings;+ const next = { ...savedVideoSettings, ...patch };+ setProjects((prev) => prev.map((project) => (project.id === projectId+ ? { ...project, videoSettings: next }+ : project)));+ setVideoSettingsSaving(true);+ updateMusicVideoProject(projectId, { videoSettings: patch }, { silent: true })+ .then((project) => {+ setProjects((prev) => prev.map((current) => (current.id === projectId+ ? { ...current, videoSettings: project.videoSettings, updatedAt: project.updatedAt }+ : current)));+ })+ .catch((err) => {+ setProjects((prev) => prev.map((project) => (project.id === projectId+ ? { ...project, videoSettings: previous }+ : project)));+ toast.error(err?.message || 'Failed to save video renderer');+ })+ .finally(() => setVideoSettingsSaving(false));+ };+// Project-level concept/style (issue #3168) — optimistic-local + silent-PATCH on// commit, same as commitSceneTiming below. Sends only the changed sub-field;// the server merges it into the existing concept (applyProjectPatch), so a@@ -624,6 +692,10 @@ export default function MusicVideo() {videoLane.startScene(scene.sceneId);generateVideo({prompt,+ backend: savedVideoSettings.backend,+ ...(savedVideoSettings.backend === 'grok'+ ? { grokDuration: savedVideoSettings.grokDuration }+ : { modelId: savedVideoSettings.modelId || undefined, disableAudio: true }),mode: 'image',sourceImageFile: scene.referenceImageId,musicVideo: JSON.stringify({ projectId: selected.id, sceneId: scene.sceneId }),@@ -640,20 +712,80 @@ export default function MusicVideo() {});};+ // Selective native continuation for ltx2 models. It replaces only this+ // scene's attached clip when the continuation finishes, preserving the+ // reference frame and authored timeline span. Passing sourceImageFile keeps+ // the music-video route's fail-closed reference-frame contract intact while+ // extendFromVideoId supplies the actual native continuation source.+ const handleContinueVideo = (scene) => {+ if (!scene.videoHistoryId || !scene.referenceImageId) return;+ if (savedVideoSettings.backend !== 'local' || activeVideoModel?.runtime !== 'ltx2') {+ toast.error('Choose an LTX local model with native continuation support');+ return;+ }+ const prompt = buildShotPrompt(scene);+ videoLane.startScene(scene.sceneId);+ generateVideo({+ prompt,+ backend: 'local',+ modelId: effectiveVideoModelId || undefined,+ disableAudio: true,+ mode: 'extend',+ extendFromVideoId: scene.videoHistoryId,+ sourceImageFile: scene.referenceImageId,+ musicVideo: JSON.stringify({ projectId: selected.id, sceneId: scene.sceneId }),+ })+ .then((res) => {+ const jobId = res?.jobId || res?.generationId;+ if (!jobId) { videoLane.clearScene(scene.sceneId); return; }+ videoLane.trackJob(jobId, scene.sceneId);+ })+ .catch((err) => {+ toast.error(err?.message || 'Shot continuation failed');+ videoLane.clearScene(scene.sceneId);+ });+ };++ const handleGenerateMissingFrames = () => {+ const scenes = (selected?.scenes || []).filter((scene) =>+ !scene.referenceImageId && !genScenes[scene.sceneId] && buildFramePrompt(scene));+ if (scenes.length === 0) {+ toast.info('Every scene already has a reference frame');+ return;+ }+ scenes.forEach(handleGenerateFrame);+ };++ const handleGenerateMissingVideos = () => {+ const scenes = (selected?.scenes || []).filter((scene) =>+ scene.referenceImageId && !scene.videoHistoryId && !genVideoScenes[scene.sceneId] && buildShotPrompt(scene));+ if (scenes.length === 0) {+ toast.info(referenceFrameCount < sceneCount+ ? 'Generate every reference frame before generating the remaining videos'+ : 'Every scene already has a video');+ return;+ }+ scenes.forEach(handleGenerateVideo);+ };+return (<div className="space-y-4"><MidiInstallModal {...midiJob.installGate} /><MidiGatedModal {...midiJob.gatedGate} /><PageHeader icon={Film} title="Music Video" subtitle="Director-controlled, beat-aware music videos" />- <div className="grid grid-cols-1 md:grid-cols-3 gap-4">- {/* Projects + create */}- <div className="space-y-3">- <form onSubmit={handleCreate} className="bg-port-card border border-port-border rounded-lg p-3 space-y-2">+ <Drawer+ open={createOpen}+ onClose={() => setCreateOpen(false)}+ title="New music video"+ subtitle="Choose the audio now or attach it later"+ >+ <form onSubmit={handleCreate} className="space-y-3"><label htmlFor="mv-name" className="block text-sm font-medium">New project</label><inputid="mv-name" value={form.name} onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}- placeholder="Project name" className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm"+ placeholder="Project name" autoFocus+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm"/><label htmlFor="mv-mode" className="block text-xs text-port-text-muted">Mode</label><select id="mv-mode" value={form.mode} onChange={(e) => setForm((f) => ({ ...f, mode: e.target.value }))}@@ -681,35 +813,51 @@ export default function MusicVideo() {className="w-full flex items-center justify-center gap-1 bg-port-accent text-white rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0 disabled:opacity-50"><Plus size={16} /> Create</button>- </form>-- <div className="space-y-1">- {loading && <p className="text-sm text-port-text-muted">Loading…</p>}- {!loading && projects.length === 0 && <p className="text-sm text-port-text-muted">No projects yet.</p>}- {projects.map((p) => (- <button key={p.id} onClick={() => selectProject(p.id)}- className={`w-full text-left px-3 py-2 rounded border ${selectedId === p.id ? 'border-port-accent bg-port-accent/10' : 'border-port-border bg-port-card'}`}>- <div className="flex items-center justify-between gap-2">- <span className="text-sm truncate">{p.name}</span>- <span className={`text-[10px] px-1.5 py-0.5 rounded ${STATUS_COLORS[p.status] || 'bg-port-border'}`}>{p.status}</span>- </div>- <div className="text-xs text-port-text-muted flex items-center gap-1 mt-0.5">- <Music size={11} /> {trackName(p.trackId)} · {p.scenes?.length || 0} scenes- </div>- </button>- ))}- </div>- </div>+ </form>+ </Drawer>++ <div className="bg-port-card border border-port-border rounded-lg p-3 flex flex-wrap items-center gap-2">+ <label htmlFor="mv-project-picker" className="text-xs text-port-text-muted">Project</label>+ <select+ id="mv-project-picker"+ value={selectedId || ''}+ onChange={(e) => selectProject(e.target.value || null)}+ disabled={loading || ytImportEdit.active}+ className="min-w-0 flex-1 sm:max-w-md bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm disabled:opacity-50"+ >+ <option value="">{loading ? 'Loading projects…' : 'Select a project…'}</option>+ {projects.map((project) => (+ <option key={project.id} value={project.id}>+ {project.name} · {project.scenes?.length || 0} scenes · {project.status}+ </option>+ ))}+ </select>+ {selected && (+ <span className={`text-[10px] px-1.5 py-0.5 rounded ${STATUS_COLORS[selected.status] || 'bg-port-border'}`}>+ {selected.status}+ </span>+ )}+ <button+ type="button"+ onClick={() => setCreateOpen(true)}+ className="flex items-center gap-1 bg-port-accent text-white rounded px-3 py-1.5 text-sm min-h-[40px] sm:min-h-0"+ >+ <Plus size={15} /> New project+ </button>+ </div>- {/* Detail / scene board */}- <div className="md:col-span-2">+ <div>{!selected && !loading && routeProjectId && (<p className="text-sm text-port-text-muted">Project not found — it may have been deleted.{' '}<button onClick={() => navigate('/music-video')} className="text-port-accent underline">Back to projects</button></p>)}- {!selected && (loading || !routeProjectId) && <p className="text-sm text-port-text-muted">Select or create a project to open its scene board.</p>}+ {!selected && (loading || !routeProjectId) && (+ <div className="bg-port-card border border-port-border rounded-lg p-6 text-center">+ <p className="text-sm text-port-text-muted">Select a project above or create one to open its scene board.</p>+ </div>+ )}{selected && (<div className="space-y-3"><div className="bg-port-card border border-port-border rounded-lg p-3">@@ -760,16 +908,89 @@ export default function MusicVideo() {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"><Wand2 size={15} /> {arranging ? 'Arranging…' : 'Auto-arrange'}</button>+ <label htmlFor="mv-video-backend" className="sr-only">Scene video renderer</label>+ <select+ id="mv-video-backend"+ value={savedVideoSettings.backend}+ onChange={(e) => handleVideoSettingsChange({ backend: e.target.value })}+ disabled={videoSettingsSaving || Object.keys(genVideoScenes).length > 0}+ title="Saved renderer for this project's scene videos"+ className="bg-port-bg border border-port-border rounded px-1.5 py-1.5 text-sm disabled:opacity-50"+ >+ <option value="local">Local video</option>+ <option value="grok">Grok video</option>+ </select>+ {savedVideoSettings.backend === 'local' && (+ <>+ <label htmlFor="mv-video-model" className="sr-only">Local video model</label>+ <select+ id="mv-video-model"+ value={savedVideoSettings.modelId}+ onChange={(e) => handleVideoSettingsChange({ modelId: e.target.value })}+ disabled={videoSettingsSaving || Object.keys(genVideoScenes).length > 0 || videoModels.length === 0}+ title="Saved local image-to-video model for this project"+ className="max-w-[240px] bg-port-bg border border-port-border rounded px-1.5 py-1.5 text-sm disabled:opacity-50"+ >+ <option value="">+ {defaultVideoModel+ ? `Local default · ${videoModels.find((model) => model.id === defaultVideoModel)?.name || defaultVideoModel}`+ : 'Local default model'}+ </option>+ {videoModels.map((model) => (+ <option key={model.id} value={model.id}>{model.name || model.id}</option>+ ))}+ </select>+ </>+ )}+ {savedVideoSettings.backend === 'grok' && (+ <>+ <label htmlFor="mv-grok-duration" className="sr-only">Grok scene clip duration</label>+ <select+ id="mv-grok-duration"+ value={savedVideoSettings.grokDuration}+ onChange={(e) => handleVideoSettingsChange({ grokDuration: Number(e.target.value) })}+ disabled={videoSettingsSaving || Object.keys(genVideoScenes).length > 0}+ title="Native duration for each Grok scene clip"+ className="bg-port-bg border border-port-border rounded px-1.5 py-1.5 text-sm disabled:opacity-50"+ >+ {GROK_VIDEO_DURATIONS.map((duration) => (+ <option key={duration} value={duration}>{duration}s clips</option>+ ))}+ </select>+ </>+ )}+ <button+ onClick={handleGenerateMissingFrames}+ disabled={sceneCount === 0 || missingFrameCount === 0 || Object.keys(genScenes).length > 0}+ title={missingFrameCount > 0 ? `Generate ${missingFrameCount} missing reference frame${missingFrameCount === 1 ? '' : 's'}` : 'Every scene has a reference frame'}+ 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"+ >+ <ImageIcon size={15} /> Frames {referenceFrameCount}/{sceneCount}+ </button>+ <button+ onClick={handleGenerateMissingVideos}+ disabled={videoSettingsSaving || sceneCount === 0 || missingVideoCount === 0 || referenceFrameCount !== sceneCount || Object.keys(genVideoScenes).length > 0}+ title={referenceFrameCount !== sceneCount+ ? 'Generate every reference frame first'+ : (missingVideoCount > 0 ? `Generate ${missingVideoCount} missing scene video${missingVideoCount === 1 ? '' : 's'}` : 'Every scene has a video')}+ 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"+ >+ <Video size={15} /> Videos {renderableSceneCount}/{sceneCount}+ </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"><Activity size={15} className="animate-spin" /> {renderProgress}% · Cancel</button>) : (- <button onClick={handleRender} disabled={renderableSceneCount === 0}- title={renderableSceneCount === 0 ? 'Generate at least one scene video first' : 'Render the music video over the track'}+ <button onClick={handleRender} disabled={sceneCount === 0 || renderableSceneCount !== sceneCount}+ title={sceneCount === 0+ ? 'Add scenes first'+ : renderableSceneCount !== sceneCount+ ? `Generate videos for all ${sceneCount} scenes first`+ : 'Render the complete music video over the track'}className="flex items-center gap-1 bg-port-accent text-white rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0 disabled:opacity-50">- <Film size={15} /> Render+ <Film size={15} /> Render final</button>)}<button onClick={() => handleDelete(selected.id)} title="Delete project"@@ -882,10 +1103,36 @@ export default function MusicVideo() {</div>)}{!render && selected.renderHistoryId && (- <div className="mt-2 text-xs flex items-center gap-2">- <Film size={14} className="text-port-success" />- <a href={`/media/history?preview=${encodeURIComponent(`video:${selected.renderHistoryId}`)}`}- className="text-port-accent">View rendered music video →</a>+ <div className="mt-3 border border-port-success/40 bg-port-success/5 rounded-lg p-3 space-y-2">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <span className="text-sm font-medium flex items-center gap-1.5">+ <Film size={15} className="text-port-success" /> Final music video+ </span>+ <div className="flex items-center gap-2 text-xs">+ {finalVideo.src && (+ <a+ href={finalVideo.src}+ download+ className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1 hover:bg-port-border/40"+ >+ <Download size={13} /> Download MP4+ </a>+ )}+ <a href={`/media/history?preview=${encodeURIComponent(`video:${selected.renderHistoryId}`)}`}+ className="text-port-accent">Open in Media History →</a>+ </div>+ </div>+ {finalVideo.resolving && <p className="text-xs text-port-text-muted">Loading final video…</p>}+ {finalVideo.src && (+ <video+ src={finalVideo.src}+ controls+ playsInline+ preload="metadata"+ className="w-full max-h-[65vh] rounded bg-black border border-port-border"+ aria-label="Play final music video"+ />+ )}</div>)}{selected.audioAnalysis && (@@ -894,8 +1141,15 @@ export default function MusicVideo() {<span>Duration: {formatDurationSec(selected.audioAnalysis.durationSec)}</span><span>Beats: {selected.audioAnalysis.beats?.length || 0}</span><span>Sections: {selected.audioAnalysis.sections?.length || 0}</span>+ {averageCutSec != null && <span>Average cut: {averageCutSec.toFixed(1)}s</span>}</div>)}+ {longCutCount > 0 && (+ <p className="mt-2 rounded border border-port-warning/40 bg-port-warning/10 px-2 py-1.5 text-xs text-port-warning">+ {longCutCount} authored cut{longCutCount === 1 ? ' is' : 's are'} longer than 10s.+ Add more shots, then Auto-arrange: higher-energy sections receive shorter cuts and every boundary stays music-led.+ </p>+ )}{selected.audioAnalysis && !selected.audioAnalysis.bpm && (<div className="mt-2 flex flex-wrap items-end gap-2 text-xs bg-port-bg border border-port-border rounded-lg p-2"><span className="text-port-text-muted w-full">No tempo detected — set it by ear to unlock the beat grid:</span>@@ -935,11 +1189,23 @@ export default function MusicVideo() {</div>{(selected.scenes || []).length === 0 && <p className="text-sm text-port-text-muted">No scenes yet — add one to start the board.</p>}- <div className="space-y-2">+ <div className="grid grid-cols-1 xl:grid-cols-2 gap-3">{(selected.scenes || []).map((scene, idx) => (<div key={scene.sceneId} className="bg-port-card border border-port-border rounded-lg p-3 space-y-2"><div className="flex items-center justify-between gap-2">- <span className="text-xs font-mono text-port-text-muted">#{scene.order + 1}</span>+ <div className="min-w-0">+ <div className="text-sm font-medium truncate">+ {scene.sectionLabel || scene.label || `Scene ${scene.order + 1}`}+ </div>+ <div className="text-[11px] text-port-text-muted">+ #{scene.order + 1}+ {typeof scene.startSec === 'number' && typeof scene.endSec === 'number'+ ? ` · ${formatDurationSec(scene.endSec - scene.startSec)} · ${formatDurationSec(scene.startSec)}–${formatDurationSec(scene.endSec)}`+ : ''}+ {scene.referenceImageId ? ' · frame ready' : ''}+ {scene.videoHistoryId ? ' · video ready' : ''}+ </div>+ </div><div className="flex items-center gap-1"><button onClick={() => moveScene(idx, -1)} disabled={idx === 0} aria-label="Move up" className="p-1 disabled:opacity-30" title="Move up"><ArrowUp size={14} /></button><button onClick={() => moveScene(idx, 1)} disabled={idx === selected.scenes.length - 1} aria-label="Move down" className="p-1 disabled:opacity-30" title="Move down"><ArrowDown size={14} /></button>@@ -982,13 +1248,13 @@ export default function MusicVideo() {<div className="flex items-center gap-2">{scene.referenceImageId && (<img src={`/data/images/${scene.referenceImageId}`} alt="Reference frame"- className="w-16 h-16 object-cover rounded border border-port-border" />+ className="w-32 aspect-video object-cover rounded border border-port-border" />)}<button onClick={() => handleGenerateFrame(scene)} disabled={!!genScenes[scene.sceneId]}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="Generate a still reference frame for this scene">{genScenes[scene.sceneId] ? <Activity size={14} className="animate-spin" /> : <ImageIcon size={14} />}- {genScenes[scene.sceneId] ? 'Rendering…' : (scene.referenceImageId ? 'Regenerate frame' : 'Generate frame')}+ {genScenes[scene.sceneId] ? 'Generating frame…' : (scene.referenceImageId ? 'Regenerate frame' : 'Generate frame')}</button></div></div>@@ -996,16 +1262,26 @@ export default function MusicVideo() {<div className="flex items-center gap-2 flex-wrap">{scene.videoHistoryId && (<video src={`/data/videos/${scene.videoHistoryId}.mp4`}- className="w-28 h-16 object-cover rounded border border-port-border bg-black"+ className="w-40 aspect-video object-cover rounded border border-port-border bg-black"muted playsInline preload="metadata" controls />)}<button onClick={() => handleGenerateVideo(scene)}- disabled={!scene.referenceImageId || !!genVideoScenes[scene.sceneId]}+ disabled={videoSettingsSaving || !scene.referenceImageId || !!genVideoScenes[scene.sceneId]}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] ? 'Rendering…' : (scene.videoHistoryId ? 'Regenerate video' : 'Generate video')}+ {genVideoScenes[scene.sceneId] ? 'Generating video…' : (scene.videoHistoryId ? 'Regenerate video' : 'Generate video')}</button>+ {scene.videoHistoryId && savedVideoSettings.backend === 'local' && activeVideoModel?.runtime === 'ltx2' && (+ <button+ onClick={() => handleContinueVideo(scene)}+ disabled={videoSettingsSaving || !!genVideoScenes[scene.sceneId]}+ className="flex items-center gap-1 bg-port-bg border border-port-border hover:bg-port-border/40 disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[40px] sm:min-h-0 whitespace-nowrap"+ title="Native-extend this clip from its final latent frames and attach the longer result to this scene"+ >+ <Video size={14} /> Continue shot+ </button>+ )}</div></div>))}@@ -1014,6 +1290,5 @@ export default function MusicVideo() {)}</div></div>- </div>);}diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex 34306e7cda..b92d5045c4 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -52,7 +52,18 @@ vi.mock('../services/apiMusicVideo.js', () => ({cancelMusicVideoMidiTranscription: vi.fn(async () => ({ ok: true })),}));vi.mock('../services/apiSystem.js', () => ({ generateImage: vi.fn() }));-vi.mock('../services/apiImageVideo.js', () => ({ generateVideo: vi.fn() }));+vi.mock('../services/apiImageVideo.js', () => ({+ generateVideo: vi.fn(),+ getVideoGenStatus: vi.fn(async () => ({+ connected: true,+ defaultModel: 'ltx23_distilled_q4',+ models: [+ { id: 'ltx23_distilled_q4', name: 'LTX-2.3 Distilled Q4', runtime: 'ltx2' },+ { id: 'wan22_t2v_a14b', name: 'Wan T2V', mode: 't2v' },+ ],+ })),+ listVideoHistory: vi.fn(async () => [{ id: 'rh-9', filename: 'final.mp4' }]),+}));vi.mock('../services/apiTracks.js', () => ({listTracks: vi.fn(async () => []),trackAudioUrl: (filename) => `/data/music/${encodeURIComponent(filename)}`,@@ -80,6 +91,7 @@ import {deleteMusicVideoProject, transcribeMusicVideoMidi,} from '../services/apiMusicVideo.js';import { importTrackFromYoutube, trackImportEventsUrl, listTracks } from '../services/apiTracks.js';+import { generateVideo } from '../services/apiImageVideo.js';const PROJECT_ANALYZED = {...PROJECT_NO_CLIP,@@ -110,9 +122,15 @@ const settle = () => act(async () => {});const openProject = async (project) => {listMusicVideoProjects.mockResolvedValue([project]);renderMV();- // Project list button appears, then select it to open the board.- const btn = await screen.findByRole('button', { name: new RegExp(project.name) });- fireEvent.click(btn);+ const picker = await screen.findByLabelText('Project');+ await act(async () => {+ fireEvent.change(picker, { target: { value: project.id } });+ });+ await screen.findByRole('heading', { level: 2, name: project.name });+};++const openCreateForm = async () => {+ fireEvent.click(await screen.findByRole('button', { name: /New project/i }));};// Probes/harness for the URL-nav backstop test: a location readout plus a@@ -147,7 +165,7 @@ beforeEach(() => {describe('MusicVideo render control (#1760)', () => {it('enables Render and kicks off the job when a scene has a clip', async () => {await openProject(PROJECT_WITH_CLIP);- const renderBtn = await screen.findByRole('button', { name: /^Render$/ });+ const renderBtn = await screen.findByRole('button', { name: /^Render final$/ });expect(renderBtn).toHaveProperty('disabled', false);fireEvent.click(renderBtn);@@ -156,18 +174,58 @@ describe('MusicVideo render control (#1760)', () => {it('disables Render when no scene has a generated clip', async () => {await openProject(PROJECT_NO_CLIP);- const renderBtn = await screen.findByRole('button', { name: /^Render$/ });+ const renderBtn = await screen.findByRole('button', { name: /^Render final$/ });expect(renderBtn).toHaveProperty('disabled', true);});it('shows the rendered-video link once a project carries a renderHistoryId', async () => {await openProject({ ...PROJECT_WITH_CLIP, renderHistoryId: 'rh-9' });- const link = await screen.findByText(/View rendered music video/i);+ await screen.findByText(/Download MP4/i);+ const link = await screen.findByText(/Open in Media History/i);// Media History matches video items by their `video:<id>` key via ?preview=.expect(link.closest('a').getAttribute('href')).toContain('preview=video%3Arh-9');});});+describe('MusicVideo project video renderer', () => {+ it('persists the local model and uses it for scene generation', async () => {+ generateVideo.mockResolvedValue({ jobId: 'video-job-1' });+ await openProject(PROJECT_NO_CLIP);++ const model = await screen.findByLabelText('Local video model');+ fireEvent.change(model, { target: { value: 'ltx23_distilled_q4' } });+ await waitFor(() => expect(updateMusicVideoProject).toHaveBeenCalledWith(+ 'mv-2',+ { videoSettings: { 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: 'image',+ sourceImageFile: 'img1',+ })));+ });++ it('continues an existing scene through the local model native extend mode', async () => {+ generateVideo.mockResolvedValue({ jobId: 'video-job-2' });+ await openProject(PROJECT_WITH_CLIP);++ fireEvent.click(await screen.findByRole('button', { name: /^Continue shot$/ }));++ await waitFor(() => expect(generateVideo).toHaveBeenCalledWith(expect.objectContaining({+ backend: 'local',+ modelId: 'ltx23_distilled_q4',+ disableAudio: true,+ mode: 'extend',+ extendFromVideoId: 'h1',+ sourceImageFile: 'img1',+ })));+ });+});+describe('MusicVideo audio preview + download', () => {it('shows preview player + download link for a linked track', async () => {listTracks.mockResolvedValue([{ id: 't1', title: 'Neon Song', audioFilename: 'neon song.mp3' }]);@@ -188,7 +246,7 @@ describe('MusicVideo audio preview + download', () => {it('renders no audio controls when the project has no audio', async () => {await openProject({ ...PROJECT_WITH_CLIP, trackId: null, uploadedAudioFilename: null });// Board opened (Render button present) but no audio surface.- await screen.findByRole('button', { name: /^Render$/ });+ await screen.findByRole('button', { name: /^Render final$/ });expect(screen.queryByLabelText('Preview track audio')).toBeNull();expect(screen.queryByRole('link', { name: /Download audio/i })).toBeNull();});@@ -293,12 +351,13 @@ describe('MusicVideo concept & style editor (#3168)', () => {const projectB = { ...PROJECT_NO_CLIP, id: 'mv-3', name: 'Other Project', concept: { prompt: 'B original' } };listMusicVideoProjects.mockResolvedValue([PROJECT_NO_CLIP, projectB]);renderMV();- fireEvent.click(await screen.findByRole('button', { name: new RegExp(PROJECT_NO_CLIP.name) }));+ const picker = await screen.findByLabelText('Project');+ fireEvent.change(picker, { target: { value: PROJECT_NO_CLIP.id } });const conceptField = await screen.findByLabelText('Concept');fireEvent.change(conceptField, { target: { value: 'A unsaved draft' } });// No blur — switch projects while the edit is still pending.- fireEvent.click(screen.getByRole('button', { name: new RegExp(projectB.name) }));+ fireEvent.change(picker, { target: { value: projectB.id } });await waitFor(() => expect(screen.getByLabelText('Concept')).toHaveValue('B original'));fireEvent.blur(screen.getByLabelText('Concept'));@@ -328,11 +387,7 @@ describe('MusicVideo concept & style editor (#3168)', () => {describe('MusicVideo YouTube audio import (#1945)', () => {it('starts an import from the detail view and attaches the finished track to the project', async () => {await openProject(PROJECT_NO_CLIP);- // Two matches now (create form + detail-view row share the same- // placeholder/aria-label) — the create form's carries the `mv-yt-create`- // id, so the other one is the detail view's.- const urlInput = screen.getAllByPlaceholderText(/Import audio from a YouTube URL/i)- .find((el) => el.id !== 'mv-yt-create');+ const urlInput = screen.getByPlaceholderText(/Import audio from a YouTube URL/i);fireEvent.change(urlInput, { target: { value: 'https://youtu.be/dQw4w9WgXcQ' } });const row = urlInput.closest('div');fireEvent.click(within(row).getByRole('button', { name: /Import/i }));@@ -346,7 +401,7 @@ describe('MusicVideo YouTube audio import (#1945)', () => {getYtSseState(url).latest = {type: 'complete', trackId: 'track-yt-1', track: { id: 'track-yt-1', title: 'Imported Song' },};- fireEvent.change(screen.getByPlaceholderText('Project name'), { target: { value: 'x' } });+ fireEvent.change(urlInput, { target: { value: 'https://youtu.be/refresh' } });await waitFor(() => expect(updateMusicVideoProject).toHaveBeenCalledWith('mv-2', { trackId: 'track-yt-1' }, { silent: true }));});@@ -358,6 +413,7 @@ describe('MusicVideo YouTube audio import (#1945)', () => {it('running the create-form and detail-view imports at once does not orphan either job', async () => {await openProject(PROJECT_NO_CLIP);+ await openCreateForm();importTrackFromYoutube.mockResolvedValueOnce({ jobId: 'yt-job-create' }).mockResolvedValueOnce({ jobId: 'yt-job-edit' });@@ -401,8 +457,8 @@ describe('MusicVideo YouTube audio import (#1945)', () => {const projectB = { ...PROJECT_NO_CLIP, id: 'mv-3', name: 'Other Project' };listMusicVideoProjects.mockResolvedValue([PROJECT_NO_CLIP, projectB]);renderMV();- const listBtnA = await screen.findByRole('button', { name: new RegExp(PROJECT_NO_CLIP.name) });- fireEvent.click(listBtnA);+ const picker = await screen.findByLabelText('Project');+ fireEvent.change(picker, { target: { value: PROJECT_NO_CLIP.id } });const editInput = screen.getAllByPlaceholderText(/Import audio from a YouTube URL/i).find((el) => el.id !== 'mv-yt-create');@@ -413,16 +469,16 @@ describe('MusicVideo YouTube audio import (#1945)', () => {// Switching to the OTHER project while this one's import is in flight// must be blocked — it would silently orphan the in-flight job's SSE// subscription and misattribute its progress UI to the new selection.- fireEvent.click(screen.getByRole('button', { name: new RegExp(projectB.name) }));+ fireEvent.change(picker, { target: { value: projectB.id } });expect(toast.error).toHaveBeenCalledWith(expect.stringMatching(/before switching projects/i));- expect(listBtnA).toHaveClass('border-port-accent');+ expect(picker).toHaveValue(PROJECT_NO_CLIP.id);});it('bounces URL-driven navigation (deep link / Back / ⌘K) away from a project with an in-flight import back to it', async () => {listMusicVideoProjects.mockResolvedValue([PROJECT_NO_CLIP]); // mv-2renderMVWithNav('/music-video/mv-3');// Open mv-2 and start its detail-view import.- fireEvent.click(await screen.findByRole('button', { name: new RegExp(PROJECT_NO_CLIP.name) }));+ fireEvent.change(await screen.findByLabelText('Project'), { target: { value: PROJECT_NO_CLIP.id } });await waitFor(() => expect(screen.getByTestId('loc').textContent).toBe('/music-video/mv-2'));const editInput = screen.getAllByPlaceholderText(/Import audio from a YouTube URL/i).find((el) => el.id !== 'mv-yt-create');@@ -454,6 +510,7 @@ describe('MusicVideo YouTube audio import (#1945)', () => {it('pressing Enter in the create-form URL input starts the import instead of submitting the form', async () => {listMusicVideoProjects.mockResolvedValue([]);renderMV();+ await openCreateForm();const createInput = await screen.findByPlaceholderText(/Import audio from a YouTube URL/i);fireEvent.change(createInput, { target: { value: 'https://youtu.be/enterkey' } });fireEvent.keyDown(createInput, { key: 'Enter' });@@ -466,6 +523,7 @@ describe('MusicVideo YouTube audio import (#1945)', () => {let resolveKickoff;importTrackFromYoutube.mockImplementation(() => new Promise((resolve) => { resolveKickoff = resolve; }));renderMV();+ await openCreateForm();const createInput = await screen.findByPlaceholderText(/Import audio from a YouTube URL/i);fireEvent.change(createInput, { target: { value: 'https://youtu.be/doubleclick' } });const importBtn = within(createInput.closest('div')).getByRole('button', { name: /Import/i });@@ -481,8 +539,8 @@ describe('MusicVideo YouTube audio import (#1945)', () => {let resolveKickoff;importTrackFromYoutube.mockImplementation(() => new Promise((resolve) => { resolveKickoff = resolve; }));renderMV();- const listBtnA = await screen.findByRole('button', { name: new RegExp(PROJECT_NO_CLIP.name) });- fireEvent.click(listBtnA);+ const picker = await screen.findByLabelText('Project');+ fireEvent.change(picker, { target: { value: PROJECT_NO_CLIP.id } });const editInput = screen.getAllByPlaceholderText(/Import audio from a YouTube URL/i).find((el) => el.id !== 'mv-yt-create');@@ -493,9 +551,9 @@ describe('MusicVideo YouTube audio import (#1945)', () => {// would attach with nobody listening once it lands.expect(importTrackFromYoutube).toHaveBeenCalledTimes(1);- fireEvent.click(screen.getByRole('button', { name: new RegExp(projectB.name) }));+ fireEvent.change(picker, { target: { value: projectB.id } });expect(toast.error).toHaveBeenCalledWith(expect.stringMatching(/before switching projects/i));- expect(listBtnA).toHaveClass('border-port-accent');+ expect(picker).toHaveValue(PROJECT_NO_CLIP.id);resolveKickoff({ jobId: 'yt-job-pending' });// Settle the kickoff's .then (jobId + SSE-subscription state) inside act —@@ -506,6 +564,7 @@ describe('MusicVideo YouTube audio import (#1945)', () => {it('blocks creating the project while the create-form YouTube import is in flight', async () => {listMusicVideoProjects.mockResolvedValue([]);renderMV();+ await openCreateForm();const nameInput = await screen.findByPlaceholderText('Project name');fireEvent.change(nameInput, { target: { value: 'New MV' } });const createInput = screen.getAllByPlaceholderText(/Import audio from a YouTube URL/i)@@ -522,7 +581,7 @@ describe('MusicVideo YouTube audio import (#1945)', () => {it('blocks relinking the track while a render is in progress for the selected project', async () => {await openProject(PROJECT_WITH_CLIP);- fireEvent.click(await screen.findByRole('button', { name: /^Render$/ }));+ fireEvent.click(await screen.findByRole('button', { name: /^Render final$/ }));await waitFor(() => expect(renderMusicVideoProject).toHaveBeenCalled());const trackSelect = screen.getByLabelText('Change track');diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.jsindex cd0cde89c6..624219e38e 100644--- a/client/src/services/apiImageVideo.js+++ b/client/src/services/apiImageVideo.js@@ -152,7 +152,7 @@ export async function createImageGenVenv() {}// Video gen-export const getVideoGenStatus = () => request('/video-gen/status');+export const getVideoGenStatus = (options = {}) => request('/video-gen/status', options);export const listVideoModels = (options) => request('/video-gen/models', options);// `{ models: [...], textEncoder: { repo, cached, sizeBytes } }`. Same shape// contract as the image variant + a text-encoder block since the activediff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex 6ac30a6590..4f91ae97b7 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -26,6 +26,16 @@ export const musicVideoConceptSchema = z.object({universeId: z.string().max(64).nullable().optional(),}).strict();+// Renderer settings travel with the project so reopening a director board (or+// opening it on a sync peer) cannot silently change provider/model. `modelId`+// is optional because Grok does not consume it; the video-gen route performs+// the authoritative installed-model validation when a local render starts.+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(),+}).strict();+export const musicVideoProjectCreateSchema = z.object({name: z.string().min(1).max(200),mode: z.enum(MUSIC_VIDEO_MODES).optional(),@@ -35,6 +45,7 @@ export const musicVideoProjectCreateSchema = z.object({trackId: z.string().max(64).nullable().optional(),uploadedAudioFilename: z.string().max(256).nullable().optional(),concept: musicVideoConceptSchema.nullable().optional(),+ videoSettings: musicVideoVideoSettingsSchema.optional(),}).strict();export const musicVideoProjectUpdateSchema = z.object({@@ -44,6 +55,7 @@ export const musicVideoProjectUpdateSchema = z.object({trackId: z.string().max(64).nullable().optional(),uploadedAudioFilename: z.string().max(256).nullable().optional(),concept: musicVideoConceptSchema.nullable().optional(),+ videoSettings: musicVideoVideoSettingsSchema.optional(),renderHistoryId: z.string().max(64).nullable().optional(),}).strict();diff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.jsindex 749851e49f..eeb9b0b5c1 100644--- a/server/routes/musicVideo.test.js+++ b/server/routes/musicVideo.test.js@@ -107,6 +107,20 @@ describe('musicVideo routes', () => {expect(r.body.name).toBe('Renamed');});+ it('PATCH /:id accepts bounded project video-renderer settings', async () => {+ const videoSettings = { backend: 'local', modelId: 'ltx23_dgrauet_q4', grokDuration: 10 };+ 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 });+ });++ it('PATCH /:id rejects invalid video-renderer settings', async () => {+ const r = await request(app).patch('/api/music-video/mv-1')+ .send({ videoSettings: { backend: 'cloud-surprise', grokDuration: 9 } });+ expect(r.status).toBe(400);+ expect(svc.updateProject).not.toHaveBeenCalled();+ });+it('DELETE /:id soft-deletes', async () => {const r = await request(app).delete('/api/music-video/mv-1');expect(r.status).toBe(200);diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.jsindex a4f2e555c5..f1bd7719fa 100644--- a/server/services/musicVideo/projectsLogic.js+++ b/server/services/musicVideo/projectsLogic.js@@ -60,6 +60,7 @@ export function buildProjectRecord(input, { id, now }) {const {name, mode = 'director', trackId = null,uploadedAudioFilename = null, concept = null,+ videoSettings = {},} = input;return {id,@@ -71,6 +72,11 @@ export function buildProjectRecord(input, { id, now }) {trackId,uploadedAudioFilename,concept,+ videoSettings: {+ backend: videoSettings.backend ?? 'local',+ modelId: videoSettings.modelId ?? null,+ grokDuration: videoSettings.grokDuration ?? 10,+ },audioAnalysis: null,midiTranscription: null,scenes: [],@@ -92,9 +98,23 @@ export function applyProjectPatch(project, patch) {// below, so a caller sending only the sub-field it edited (e.g. { style: '…' })// can't clobber a sibling sub-field (e.g. prompt) set concurrently by another// sync peer (#3168). An explicit `concept: null` still clears it outright.- const mergedPatch = ('concept' in patch && patch.concept && project.concept)+ const conceptMergedPatch = ('concept' in patch && patch.concept && project.concept)? { ...patch, concept: { ...project.concept, ...patch.concept } }: patch;+ // Renderer settings are edited independently in the UI. Merge a partial+ // change so picking a model cannot discard the provider or Grok duration.+ const mergedPatch = ('videoSettings' in conceptMergedPatch && conceptMergedPatch.videoSettings)+ ? {+ ...conceptMergedPatch,+ videoSettings: {+ backend: 'local',+ modelId: null,+ grokDuration: 10,+ ...project.videoSettings,+ ...conceptMergedPatch.videoSettings,+ },+ }+ : conceptMergedPatch;// Changing the audio source invalidates the cached beat/tempo analysis —// it was computed from the OLD track. AI Plan / Auto-arrange / BeatTimeline// gate on `audioAnalysis` truthiness, and the render's beat-snap step readsdiff --git a/server/services/musicVideo/projectsLogic.test.js b/server/services/musicVideo/projectsLogic.test.jsindex 0f45ebd30c..e73f963c74 100644--- a/server/services/musicVideo/projectsLogic.test.js+++ b/server/services/musicVideo/projectsLogic.test.js@@ -22,6 +22,7 @@ describe('buildProjectRecord', () => {expect(p).toMatchObject({id: 'mv-x', name: 'Neon Nights', status: 'draft', mode: 'director',trackId: 'track-9', uploadedAudioFilename: null, concept: null,+ videoSettings: { backend: 'local', modelId: null, grokDuration: 10 },audioAnalysis: null, midiTranscription: null, scenes: [], renderHistoryId: null,deleted: false, deletedAt: null,});@@ -159,6 +160,23 @@ describe('applyProjectPatch', () => {const next = applyProjectPatch(withConcept, { concept: null });expect(next.concept).toBeNull();});++ it('persists explicit renderer settings and merges later partial changes', () => {+ const project = buildProjectRecord({+ name: 'A',+ videoSettings: { backend: 'grok', grokDuration: 6 },+ }, { id: 'mv-2', now: 'n' });+ expect(project.videoSettings).toEqual({ backend: 'grok', modelId: null, grokDuration: 6 });++ const next = applyProjectPatch(project, {+ videoSettings: { backend: 'local', modelId: 'ltx23_distilled_q4' },+ });+ expect(next.videoSettings).toEqual({+ backend: 'local',+ modelId: 'ltx23_distilled_q4',+ grokDuration: 6,+ });+ });});describe('setAudioAnalysis', () => {diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.jsindex ab7c6f5326..ab94b688e9 100644--- a/server/services/musicVideo/render.js+++ b/server/services/musicVideo/render.js@@ -144,9 +144,10 @@ export async function resolveSceneClips(project) {// Pure: trim each clip's out-point so its cumulative cut lands on the nearest// analyzed beat, when one is within `toleranceSec` and the trim keeps the clip-// at least `minClipSec` long. Snapping only ever SHORTENS a clip (a clip can't-// be extended past its rendered length), so a cut can move earlier onto a beat-// but never later. Returns a NEW clips array with adjusted `outSec`/`duration`.+// at least `minClipSec` long. This derived, non-authored snap only SHORTENS a+// source clip. A director-authored beatAligned span is handled separately+// below and may exceed the native clip because the ffmpeg builder loops it.+// Returns a NEW clips array with adjusted `outSec`/`duration`.// With no beats (no analysis) and no persisted scene arrangement, clips are// returned unchanged.//@@ -155,10 +156,10 @@ export async function resolveSceneClips(project) {// the BeatTimeline drag-snap arranger, #1854), that scene's saved duration is// honored EXACTLY instead of being re-derived from the live beat grid: the// director already snapped and saved it, so the render shouldn't silently-// recompute a different cut from whatever the grid says today. Clamped to the-// clip's own rendered length (a saved duration can't make a clip longer than-// what was actually generated) and to `minClipSec`. The running cursor still-// advances by the honored duration so any later, non-aligned clips keep+// recompute a different cut from whatever the grid says today. The ffmpeg+// builder loops finite source clips, so a saved music-video span may exceed a+// clip's native duration; it is still floored to `minClipSec`. The running+// cursor advances by the honored duration so any later, non-aligned clips keep// snapping against the correct cumulative position.export function beatSnapClips(clips, beats, { toleranceSec = 0.12, minClipSec = 0.4, scenes = null } = {}) {const grid = Array.isArray(beats) ? beats.filter((b) => typeof b === 'number' && b >= 0).sort((a, b) => a - b) : [];@@ -170,9 +171,11 @@ export function beatSnapClips(clips, beats, { toleranceSec = 0.12, minClipSec =if (scene?.beatAligned && typeof scene.startSec === 'number' && typeof scene.endSec === 'number' && scene.endSec > scene.startSec) {// inSec stays 0 here deliberately: this only ever trims how much of the// clip plays, never which frames — there is no in-point/out-point- // distinction. The BeatTimeline client intentionally exposes only a- // right-edge (out-point) trim handle for the same reason (#1854).- const outSec = Math.min(clip.duration, Math.max(minClipSec, scene.endSec - scene.startSec));+ // distinction. A planned music-video scene commonly spans much longer+ // than one generated 6–10s source clip; buildMusicVideoFfmpegArgs loops+ // that input, so the authored timeline duration is allowed to exceed the+ // source duration instead of silently truncating the final song.+ const outSec = Math.max(minClipSec, scene.endSec - scene.startSec);running += outSec;return { ...clip, inSec: 0, outSec, duration: outSec };}@@ -211,7 +214,11 @@ export function buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDconst fps = clips[0].fps || 24;const inputs = [];- for (const c of clips) inputs.push('-i', c.videoPath);+ // A generated scene clip is a reusable shot source, while the director's+ // timeline owns how long that shot appears in the music video. Loop each+ // finite clip input so a 6–10s Grok/local result can fill a longer verse or+ // chorus span; the per-input trim below still makes every loop finite.+ for (const c of clips) inputs.push('-stream_loop', '-1', '-i', c.videoPath);const audioIdx = clips.length; // master audio is the last inputinputs.push('-i', audioPath);diff --git a/server/services/musicVideo/render.test.js b/server/services/musicVideo/render.test.jsindex a0acb71435..9cb0765f76 100644--- a/server/services/musicVideo/render.test.js+++ b/server/services/musicVideo/render.test.js@@ -48,6 +48,7 @@ describe('buildMusicVideoFfmpegArgs', () => {const maps = args.reduce((acc, a, i) => (a === '-map' ? [...acc, args[i + 1]] : acc), []);expect(maps).toEqual(['[outv]', '2:a']);expect(args).toContain('-shortest');+ expect(args.filter((arg) => arg === '-stream_loop')).toHaveLength(2);});it('totalDuration is the min of video and audio length', () => {@@ -113,10 +114,11 @@ describe('beatSnapClips', () => {expect(out[0].duration).toBeCloseTo(1.2, 5);});- it('clamps a persisted duration to the clip\'s own rendered length', () => {+ it('allows a persisted duration to exceed the source clip so ffmpeg can loop it', () => {const scenes = [{ sceneId: 's1', startSec: 0, endSec: 100, beatAligned: true }];const out = beatSnapClips([clip({ sceneId: 's1', duration: 2, outSec: 2 })], null, { scenes });- expect(out[0].outSec).toBe(2);+ expect(out[0].outSec).toBe(100);+ expect(out[0].duration).toBe(100);});it('clamps a persisted duration to minClipSec', () => {