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: music-video scene takes, visual spec and external-asset handoff (#8965)
[._.]/ Adam Eivy3f3cd982af24
diff --git a/client/src/components/musicVideo/ContactSheetDrawer.jsx b/client/src/components/musicVideo/ContactSheetDrawer.jsxnew file mode 100644index 0000000000..67006fd8d3--- /dev/null+++ b/client/src/components/musicVideo/ContactSheetDrawer.jsx@@ -0,0 +1,35 @@+import Drawer from '../Drawer.jsx';+import SceneTakeStrip from './SceneTakeStrip.jsx';++/**+ * Project contact sheet (#8965): every scene's frame and clip takes side by+ * side, so the director can compare candidates across the whole video, pick+ * the ones the render uses, and reject the misses in one pass. Opened from the+ * board's handoff row; its open state lives in the URL (`?sheet=contact`).+ */+export default function ContactSheetDrawer({ open, onClose, project, busy, onSelectTake, onReviewTake, onOpenPreview }) {+ const scenes = project?.scenes || [];+ return (+ <Drawer open={open} onClose={onClose} title="Contact sheet" subtitle={project?.name} size="xl" closeLabel="Close contact sheet">+ {scenes.length === 0 && <p className="text-sm text-port-text-muted">No scenes yet.</p>}+ <ol className="space-y-3">+ {scenes.map((scene, index) => (+ <li key={scene.sceneId} className="rounded border border-port-border p-2 space-y-2">+ <div className="text-sm font-medium truncate">+ {index + 1}. {scene.sectionLabel || scene.label || `Scene ${index + 1}`}+ </div>+ {!(scene.takes?.length || scene.referenceImageId || scene.videoHistoryId) && (+ <p className="text-[11px] text-port-text-muted">No takes yet.</p>+ )}+ {['image', 'video'].map((kind) => (+ <SceneTakeStrip key={kind} scene={scene} kind={kind} busy={busy} large+ onSelect={(take) => onSelectTake(scene, take)}+ onReview={(take, review) => onReviewTake(scene, take, review)}+ onOpenPreview={onOpenPreview} />+ ))}+ </li>+ ))}+ </ol>+ </Drawer>+ );+}diff --git a/client/src/components/musicVideo/HandoffControls.jsx b/client/src/components/musicVideo/HandoffControls.jsxnew file mode 100644index 0000000000..2e2beef022--- /dev/null+++ b/client/src/components/musicVideo/HandoffControls.jsx@@ -0,0 +1,44 @@+import { useState } from 'react';+import { Download, Upload, Activity, LayoutGrid } from 'lucide-react';+import FilePickerButton from '../ui/FilePickerButton';++const PROVIDERS = [['midjourney', 'Midjourney'], ['external', 'Other tool']];+const HANDOFF_ACCEPT = 'image/png,image/jpeg,image/webp,image/gif,video/mp4,video/quicktime,video/webm';++/**+ * External-asset handoff (#8965) for tools PortOS does not drive, such as+ * Midjourney: export a manifest of per-scene prompts, file tags and reference+ * files; generate by hand; then import the downloads. Files whose names keep a+ * scene's tag (e.g. `S03-1a2b3c4d`) land on that exact scene as imported takes+ * with the chosen provider recorded. PortOS never contacts the external tool.+ */+export default function HandoffControls({ projectId, busy, onExport, onImport, onOpenContactSheet }) {+ const [provider, setProvider] = useState('midjourney');+ const selectId = `mv-handoff-provider-${projectId}`;+ return (+ <div className="mt-2 flex flex-wrap items-center gap-2 text-xs">+ <span className="text-port-text-muted">External handoff</span>+ <label htmlFor={selectId} className="sr-only">Handoff provider</label>+ <select id={selectId} value={provider} onChange={(e) => setProvider(e.target.value)}+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-xs min-h-[44px] sm:min-h-0">+ {PROVIDERS.map(([value, label]) => <option key={value} value={value}>{label}</option>)}+ </select>+ <button type="button" onClick={onExport} disabled={busy}+ className="flex items-center gap-1 bg-port-border hover:bg-port-border/70 disabled:opacity-50 rounded px-2 py-1 min-h-[44px] sm:min-h-0"+ title="Download per-scene prompts, file tags and reference files as JSON">+ <Download size={13} /> Export prompts+ </button>+ <FilePickerButton multiple accept={HANDOFF_ACCEPT} disabled={busy}+ onChange={(e) => onImport(Array.from(e.target.files || []), provider)}+ ariaLabel="Import generated files"+ className="flex items-center gap-1 bg-port-border hover:bg-port-border/70 rounded px-2 py-1 min-h-[44px] sm:min-h-0 cursor-pointer">+ {busy ? <Activity size={13} className="animate-spin" /> : <Upload size={13} />} Import generated files+ </FilePickerButton>+ <button type="button" onClick={onOpenContactSheet}+ className="flex items-center gap-1 bg-port-bg border border-port-border hover:bg-port-border/40 rounded px-2 py-1 min-h-[44px] sm:min-h-0"+ title="Review every scene's takes side by side">+ <LayoutGrid size={13} /> Contact sheet+ </button>+ </div>+ );+}diff --git a/client/src/components/musicVideo/SceneCard.jsx b/client/src/components/musicVideo/SceneCard.jsxindex fcb03d1127..b7a423a830 100644--- a/client/src/components/musicVideo/SceneCard.jsx+++ b/client/src/components/musicVideo/SceneCard.jsx@@ -1,6 +1,7 @@import { useRef, useState } from 'react';-import { Trash2, Activity, ArrowUp, ArrowDown, Image as ImageIcon, Video, Maximize2, AlertTriangle } from 'lucide-react';+import { Trash2, Activity, ArrowUp, ArrowDown, Image as ImageIcon, Video, Maximize2, AlertTriangle, ImagePlus } from 'lucide-react';import { formatDurationSec } from '../../utils/formatters.js';+import SceneTakeStrip from './SceneTakeStrip.jsx';// The two timeline-bound scene fields rendered as identical number inputs.const SCENE_TIME_FIELDS = [['Start', 'startSec'], ['End', 'endSec']];@@ -17,13 +18,18 @@ const COVERAGE_TOLERANCE_SEC = 0.25;* (`image:<filename>`) or clip (`video:<historyId>`). The frame thumb is the* whole button; the clip keeps native play/pause and uses a corner expand* control so the open handler never fights the player.+ *+ * Each slot's takes (#8965) render as a review strip under it: a regenerate+ * adds a candidate rather than replacing the selection, and the director picks,+ * rejects, or notes takes there. `onImportTake` adds an externally generated+ * frame (gallery pick or upload) as a take.*/export default function SceneCard({scene, index, isLast, generatingFrame, generatingVideo,settingsSaving, videoBlockedReason, canContinueShot,onMove, onDelete, onEditLocal, onSave,onGenerateFrame, onGenerateVideo, onContinueVideo,- onOpenPreview,+ onOpenPreview, onSelectTake, onReviewTake, onImportTake, takeBusy = false,}) {// Pause the inline clip before opening the lightbox so the user can't hear// two desynced copies — MediaLightbox autoplays unmuted, and the thumb's@@ -138,14 +144,29 @@ export default function SceneCard({/></button>)}- <button onClick={() => onGenerateFrame(scene)} disabled={!!generatingFrame}- 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-[44px] sm:min-h-0 whitespace-nowrap"- title="Generate a still reference frame for this scene">- {generatingFrame ? <Activity size={14} className="animate-spin" /> : <ImageIcon size={14} />}- {generatingFrame ? 'Generating frame…' : (scene.referenceImageId ? 'Regenerate frame' : 'Generate frame')}- </button>+ <div className="flex flex-col gap-1">+ <button onClick={() => onGenerateFrame(scene)} disabled={!!generatingFrame}+ 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-[44px] sm:min-h-0 whitespace-nowrap"+ title={scene.referenceImageId+ ? 'Render another candidate frame — your selected frame stays until you pick a new one'+ : 'Generate a still reference frame for this scene'}>+ {generatingFrame ? <Activity size={14} className="animate-spin" /> : <ImageIcon size={14} />}+ {generatingFrame ? 'Generating frame…' : (scene.referenceImageId ? 'New frame take' : 'Generate frame')}+ </button>+ {onImportTake && (+ <button type="button" onClick={() => onImportTake(scene)} disabled={takeBusy}+ 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-[44px] sm:min-h-0 whitespace-nowrap"+ title="Add a frame from the gallery or an upload (e.g. made in an external tool) as a take">+ <ImagePlus size={14} /> Import take+ </button>+ )}+ </div></div></div>+ <SceneTakeStrip scene={scene} kind="image" busy={takeBusy}+ onSelect={(take) => onSelectTake?.(scene, take)}+ onReview={(take, review) => onReviewTake?.(scene, take, review)}+ onOpenPreview={onOpenPreview} />{/* Scene clip — i2v video generated from the reference frame (Phase 1) */}<div className="flex items-center gap-2 flex-wrap">{scene.videoHistoryId && (@@ -187,7 +208,7 @@ export default function SceneCard({title={videoBlockedReason|| (scene.referenceImageId ? "Generate this scene's video from its reference frame (i2v)" : 'Generate a reference frame first')}>{generatingVideo ? <Activity size={14} className="animate-spin" /> : <Video size={14} />}- {generatingVideo ? 'Generating video…' : (scene.videoHistoryId ? 'Regenerate video' : 'Generate video')}+ {generatingVideo ? 'Generating video…' : (scene.videoHistoryId ? 'New video take' : 'Generate video')}</button>{scene.videoHistoryId && canContinueShot && (<button@@ -200,6 +221,10 @@ export default function SceneCard({</button>)}</div>+ <SceneTakeStrip scene={scene} kind="video" busy={takeBusy}+ onSelect={(take) => onSelectTake?.(scene, take)}+ onReview={(take, review) => onReviewTake?.(scene, take, review)}+ onOpenPreview={onOpenPreview} /></div>);}diff --git a/client/src/components/musicVideo/SceneTakeStrip.jsx b/client/src/components/musicVideo/SceneTakeStrip.jsxnew file mode 100644index 0000000000..056f23c256--- /dev/null+++ b/client/src/components/musicVideo/SceneTakeStrip.jsx@@ -0,0 +1,111 @@+import { useState } from 'react';+import { Check, RotateCcw, X, MessageSquare } from 'lucide-react';+import { sceneTakeList, takePreviewKey, takeThumbUrl, takeProvenance, TAKE_SLOT } from '../../lib/musicVideoTakes.js';++const KIND_LABEL = { image: 'Frame takes', video: 'Clip takes' };++/**+ * Side-by-side review of one scene slot's takes (#8965): every render or+ * import is a candidate; the director explicitly picks the one the render uses,+ * rejects the ones that miss (with a note for the next attempt), and restores a+ * rejected take by selecting it. Used compactly on each SceneCard and at a+ * larger size in the project contact sheet.+ *+ * A legacy take (a pre-takes selection the server hasn't materialized yet) is+ * shown but has no actions — it has no take id to address.+ */+export default function SceneTakeStrip({+ scene, kind, busy = false, large = false, onSelect, onReview, onOpenPreview,+}) {+ const [noteFor, setNoteFor] = useState(null);+ const [noteDraft, setNoteDraft] = useState('');+ const takes = sceneTakeList(scene, kind);+ const selected = scene[TAKE_SLOT[kind]] || null;+ if (takes.length === 0) return null;++ const openNote = (take) => { setNoteFor(take.takeId); setNoteDraft(take.note || ''); };+ const saveNote = (take) => {+ setNoteFor(null);+ if ((take.note || '') !== noteDraft.trim()) onReview?.(take, { note: noteDraft.trim() || null });+ };+ const thumbClass = large ? 'w-40' : 'w-24';+ const noteInputId = (take) => `mv-take-note-${scene.sceneId}-${take.takeId}`;++ return (+ <div className="space-y-1">+ <div className="text-[11px] text-port-text-muted">+ {KIND_LABEL[kind]} ({takes.length})+ </div>+ <ul className="flex gap-2 overflow-x-auto pb-1" aria-label={`${KIND_LABEL[kind]} for ${scene.label || `scene ${scene.order + 1}`}`}>+ {takes.map((take) => {+ const isSelected = take.assetId === selected;+ const rejected = take.status === 'rejected';+ return (+ <li key={take.takeId || `legacy-${take.assetId}`} className={`${thumbClass} shrink-0 space-y-1`}>+ <button+ type="button"+ onClick={() => onOpenPreview?.(takePreviewKey(take))}+ aria-label={`View ${kind === 'image' ? 'frame' : 'clip'} take full size`}+ className={`block w-full rounded overflow-hidden border focus:outline-none focus:ring-2 focus:ring-port-accent ${isSelected ? 'border-port-accent ring-2 ring-port-accent' : 'border-port-border'} ${rejected ? 'opacity-40' : ''}`}+ >+ <img src={takeThumbUrl(take)} alt="" loading="lazy" className="w-full aspect-video object-cover block bg-black" />+ </button>+ <div className="text-[10px] text-port-text-muted truncate" title={take.originalName || take.prompt || takeProvenance(take)}>+ {isSelected ? <span className="text-port-accent">Selected · </span> : null}+ {rejected ? 'rejected · ' : ''}{takeProvenance(take)}+ </div>+ {take.note && noteFor !== take.takeId && (+ <p className="text-[10px] text-port-warning break-words">{take.note}</p>+ )}+ {take.takeId && (+ <div className="flex flex-wrap gap-1">+ {!isSelected && (+ <button type="button" disabled={busy} onClick={() => onSelect?.(take)}+ className="inline-flex items-center gap-0.5 rounded bg-port-accent/20 text-port-accent px-1.5 py-0.5 text-[10px] min-h-[32px] sm:min-h-0 disabled:opacity-50"+ title="Use this take for the scene">+ <Check size={11} /> Use+ </button>+ )}+ {rejected ? (+ <button type="button" disabled={busy} onClick={() => onReview?.(take, { status: 'candidate' })}+ className="inline-flex items-center gap-0.5 rounded bg-port-border px-1.5 py-0.5 text-[10px] min-h-[32px] sm:min-h-0 disabled:opacity-50"+ title="Restore this take as a candidate">+ <RotateCcw size={11} /> Restore+ </button>+ ) : (+ <button type="button" disabled={busy} onClick={() => { onReview?.(take, { status: 'rejected' }); openNote(take); }}+ className="inline-flex items-center gap-0.5 rounded bg-port-border px-1.5 py-0.5 text-[10px] min-h-[32px] sm:min-h-0 disabled:opacity-50"+ title={isSelected ? 'Reject — clears the selection so the next render fills it' : 'Reject this take'}>+ <X size={11} /> Reject+ </button>+ )}+ <button type="button" disabled={busy} onClick={() => openNote(take)}+ aria-label="Edit take note"+ className="inline-flex items-center rounded bg-port-border px-1.5 py-0.5 text-[10px] min-h-[32px] sm:min-h-0 disabled:opacity-50"+ title="Note what to change on the next attempt">+ <MessageSquare size={11} />+ </button>+ </div>+ )}+ {noteFor === take.takeId && (+ <div>+ <label htmlFor={noteInputId(take)} className="sr-only">Take note</label>+ <input+ id={noteInputId(take)}+ value={noteDraft}+ maxLength={1000}+ onChange={(e) => setNoteDraft(e.target.value)}+ onBlur={() => saveNote(take)}+ onKeyDown={(e) => { if (e.key === 'Enter') e.currentTarget.blur(); }}+ placeholder="What to change next time"+ className="w-full bg-port-bg border border-port-border rounded px-1 py-0.5 text-[11px]"+ />+ </div>+ )}+ </li>+ );+ })}+ </ul>+ </div>+ );+}diff --git a/client/src/components/musicVideo/VisualSpecPanel.jsx b/client/src/components/musicVideo/VisualSpecPanel.jsxnew file mode 100644index 0000000000..3c5052c21b--- /dev/null+++ b/client/src/components/musicVideo/VisualSpecPanel.jsx@@ -0,0 +1,149 @@+import { useState } from 'react';+import { ImagePlus, Trash2, Plus, Palette } from 'lucide-react';+import useFieldDraft from '../../hooks/useFieldDraft.js';+import MoodBoardReferenceStrip from '../moodBoard/MoodBoardReferenceStrip.jsx';+import { MAX_CONDITIONING_REFERENCES } from '../../hooks/useMusicVideoSceneMedia.js';++const ROLES = [+ ['mood', 'Mood'], ['character', 'Character'], ['wardrobe', 'Wardrobe'],+ ['set', 'Set'], ['prop', 'Prop'], ['style', 'Style'],+];+const MAX_PALETTE = 12;+const MAX_REFERENCES = 24;++/**+ * The project's reusable visual specification (#8965): moodboard/reference+ * images with a role (character, wardrobe, set, …), a palette, typography and+ * camera rules. Palette/camera/typography are appended to every generated+ * prompt; references ticked "Condition frames" are sent to reference-frame+ * renders as real conditioning images, not just prose.+ *+ * `onSave(patch)` persists a partial `visualSpec` (the server merges it per+ * sub-field); `references` and `palette` are always sent whole. Keyed by the+ * project id at the call site, so a draft never carries across projects.+ */+export default function VisualSpecPanel({ project, onSave, onAddReference }) {+ const spec = project.visualSpec || {};+ const references = spec.references || [];+ const palette = spec.palette || [];+ const [color, setColor] = useState('#336699');+ const typography = useFieldDraft(spec.typography, (v) => onSave({ typography: v }));+ const cameraRules = useFieldDraft(spec.cameraRules, (v) => onSave({ cameraRules: v }));+ const idFor = (suffix) => `mv-spec-${project.id}-${suffix}`;++ const saveReferences = (next) => onSave({ references: next });+ const updateRef = (id, patch) => saveReferences(references.map((r) => (r.id === id ? { ...r, ...patch } : r)));+ const flagged = references.filter((r) => r.condition).length;++ return (+ <details className="mt-2 rounded border border-port-border bg-port-bg/40 p-2 group">+ <summary className="cursor-pointer text-xs text-port-text-muted select-none min-h-[32px] flex items-center gap-2">+ <Palette size={13} />+ <span>Visual spec</span>+ <span>· {references.length} reference{references.length === 1 ? '' : 's'}</span>+ {flagged > 0 && <span className="text-port-accent">· {flagged} conditioning</span>}+ {palette.length > 0 && (+ <span className="flex gap-0.5" aria-hidden="true">+ {palette.map((c) => <span key={c} className="inline-block w-3 h-3 rounded-sm border border-port-border" style={{ backgroundColor: c }} />)}+ </span>+ )}+ </summary>+ <div className="mt-2 space-y-3">+ <div className="space-y-1">+ <div className="flex items-center justify-between gap-2">+ <span className="text-xs text-port-text-muted">References</span>+ <button type="button" onClick={onAddReference} disabled={references.length >= MAX_REFERENCES}+ className="flex items-center gap-1 bg-port-border hover:bg-port-border/70 disabled:opacity-50 rounded px-2 py-1 text-xs min-h-[44px] sm:min-h-0">+ <ImagePlus size={13} /> Add reference+ </button>+ </div>+ {references.length === 0 && (+ <p className="text-[11px] text-port-text-muted">+ Add character, wardrobe, set or mood images. Tick “Condition frames” to send one to every reference-frame render.+ </p>+ )}+ <ul className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-2">+ {references.map((ref) => (+ <li key={ref.id} className="flex gap-2 rounded border border-port-border p-1.5 min-w-0">+ <img src={`/data/images/${encodeURIComponent(ref.imageId)}`} alt="" loading="lazy" className="w-16 h-16 object-cover rounded shrink-0 bg-black" />+ <div className="min-w-0 flex-1 space-y-1">+ <div className="flex gap-1">+ <label htmlFor={idFor(`role-${ref.id}`)} className="sr-only">Reference role</label>+ <select id={idFor(`role-${ref.id}`)} value={ref.role || 'mood'}+ onChange={(e) => updateRef(ref.id, { role: e.target.value })}+ className="bg-port-bg border border-port-border rounded px-1 py-0.5 text-[11px]">+ {ROLES.map(([value, label]) => <option key={value} value={value}>{label}</option>)}+ </select>+ <button type="button" onClick={() => saveReferences(references.filter((r) => r.id !== ref.id))}+ aria-label="Remove reference" title="Remove reference"+ className="ml-auto min-h-[32px] min-w-[32px] inline-flex items-center justify-center text-port-error">+ <Trash2 size={12} />+ </button>+ </div>+ <label htmlFor={idFor(`label-${ref.id}`)} className="sr-only">Reference label</label>+ <input id={idFor(`label-${ref.id}`)} defaultValue={ref.label || ''} maxLength={120}+ placeholder="Label (e.g. lead singer)"+ onBlur={(e) => { if (e.target.value !== (ref.label || '')) updateRef(ref.id, { label: e.target.value }); }}+ className="w-full bg-port-bg border border-port-border rounded px-1 py-0.5 text-[11px]" />+ <label className="flex items-center gap-1 text-[11px]">+ <input type="checkbox" checked={!!ref.condition}+ disabled={!ref.condition && flagged >= MAX_CONDITIONING_REFERENCES}+ onChange={(e) => updateRef(ref.id, { condition: e.target.checked })} />+ Condition frames+ </label>+ </div>+ </li>+ ))}+ </ul>+ {flagged > 0 && (+ <p className="text-[11px] text-port-text-muted">+ Conditioning needs an image backend that accepts reference images (local FLUX.2 or Qwen Image 2.1, or a cloud image CLI); others refuse the render and say so. At most {MAX_CONDITIONING_REFERENCES} per frame.+ </p>+ )}+ </div>++ <div className="space-y-1">+ <span className="text-xs text-port-text-muted">Palette</span>+ <div className="flex flex-wrap items-center gap-1">+ {palette.map((c) => (+ <button key={c} type="button" onClick={() => onSave({ palette: palette.filter((p) => p !== c) })}+ aria-label={`Remove ${c} from palette`} title={`Remove ${c}`}+ className="w-7 h-7 rounded border border-port-border" style={{ backgroundColor: c }} />+ ))}+ <label htmlFor={idFor('color')} className="sr-only">Palette color</label>+ <input id={idFor('color')} type="color" value={color} onChange={(e) => setColor(e.target.value)}+ className="w-9 h-9 bg-transparent border border-port-border rounded" />+ <button type="button" disabled={palette.length >= MAX_PALETTE || palette.includes(color.toLowerCase())}+ onClick={() => onSave({ palette: [...palette, color.toLowerCase()] })}+ className="flex items-center gap-1 bg-port-border hover:bg-port-border/70 disabled:opacity-50 rounded px-2 py-1 text-xs min-h-[44px] sm:min-h-0">+ <Plus size={13} /> Add color+ </button>+ </div>+ </div>++ <div className="grid grid-cols-1 md:grid-cols-2 gap-2">+ <div>+ <label htmlFor={idFor('camera')} className="block text-xs text-port-text-muted mb-1">Camera rules</label>+ <textarea id={idFor('camera')} rows={2} maxLength={2000}+ value={cameraRules.value} onChange={cameraRules.onChange} onBlur={cameraRules.onBlur}+ placeholder="Lenses, framing, movement — e.g. 35mm, locked-off wides, slow push-ins only"+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm" />+ </div>+ <div>+ <label htmlFor={idFor('type')} className="block text-xs text-port-text-muted mb-1">Typography</label>+ <textarea id={idFor('type')} rows={2} maxLength={1000}+ value={typography.value} onChange={typography.onChange} onBlur={typography.onBlur}+ placeholder="On-screen text style — e.g. condensed sans, all caps, lower-third titles"+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm" />+ </div>+ </div>++ <MoodBoardReferenceStrip+ value={spec.moodBoardId || ''}+ onChange={(id) => onSave({ moodBoardId: id || null })}+ newBoardName={project.name}+ />+ </div>+ </details>+ );+}diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex d57e085df1..9654415b7d 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -249,7 +249,8 @@ grep -i "what you want to do" client/src/hooks/README.md| `useMusicVideoMidiJob` | `useMidiTranscription` bound to the music-video API surface, plus the MuScriptor model-size picker state (read fresh at each kickoff). Returns the slot (`active`/`stage`/`stageLabel`/`context`/`start(projectId)`/`cancel`/`installGate`/`gatedGate`) plus `{ model, setModel }`; `onTranscribed(projectId, midiTranscription)` fires on a non-discarded terminal frame. | The Music Video MIDI button + model select. || `useMusicVideoRenderJob` | The final-render job (#1760 Phase 2): kickoff (409 → attach to the existing job), SSE progress, terminal-frame handling and non-terminal stream-close recovery. Thin `useSseJobSlot` adapter with 0–1 progress conversion; returns `{ active, pending, context, job, progress, start(projectId), cancel }`; `onRendered(projectId, result)` / `onFailed(projectId)` key on the projectId captured at kickoff. | The Music Video "Render final" control. || `useMusicVideoModelSettings` | A project's saved render pins — video backend/model/generation-mode/audio-reactive LoRA + the image-side frame pin — with the Video Gen catalog they read from. Optimistic-local + silent PATCH, rollback + toast on failure; `saving` gates the dependent generate buttons. Returns `{ models, modelsLoading, defaultModel, saving, settings, effectiveModelId, activeModel, audioReactiveModels, audioReactiveLoras, detectedAudioReactiveLora, audioReactiveReady, audioReactiveSelected, videoBlockedReason, change, changeFramePin }`. `videoBlockedReason` is the single "why can't I generate" string (an unavailable audio-reactive setup) shared by the disabled buttons, their tooltips, and the blocked-call toast. | The Music Video renderer selects and anything building a scene-clip job payload from them. |-| `useMusicVideoSceneMedia` | Both per-scene generation lanes (reference frame + scene clip) over `useSceneRenderLifecycle`, the frame/shot prompt builders (concept-style suffix), and the batch "generate the missing ones" actions. Returns `{ genScenes, genVideoScenes, buildFramePrompt, buildShotPrompt, generateFrame, generateSceneVideo, continueSceneVideo, generateMissingFrames, generateMissingVideos }`. | The Music Video scene board — don't re-wire the two lanes or re-derive the i2v/a2v/extend payloads. |+| `useMusicVideoSceneMedia` | Both per-scene generation lanes (reference frame + scene clip) over `useSceneRenderLifecycle`, the frame/shot prompt builders (concept-style + visual-spec direction suffix), visual-spec reference-image conditioning with explicit unsupported-backend feedback (#8965), and the batch "generate the missing ones" actions. Returns `{ genScenes, genVideoScenes, conditioning, buildFramePrompt, buildShotPrompt, generateFrame, generateSceneVideo, continueSceneVideo, generateMissingFrames, generateMissingVideos }`. | The Music Video scene board — don't re-wire the two lanes or re-derive the i2v/a2v/extend payloads. |+| `useMusicVideoTakes` | Scene-take review + external-asset handoff for the Music Video board (#8965): serialized select / reject / note / gallery-import take mutations folded back as scene patches, the handoff manifest download, and the handoff import (gallery upload per file, then scene association by file tag with provider provenance). Returns `{ busy, selectTake, reviewTake, importTake, exportHandoff, importHandoffFiles }`. | The Music Video board's take strips, contact sheet and handoff row — don't re-sequence take mutations per call site. || `useMusicVideoManualTempo` | The manual-tempo fallback for a project whose auto-detected BPM is null: BPM/offset drafts (reset on project switch), tap-tempo estimation, and the persisted `setMusicVideoManualTempo` call. Returns `{ bpm, setBpm, offset, setOffset, saving, tap, submit }`. | The Music Video "No tempo detected" row. || `useCanvasDprSize` | DevicePixelRatio-aware canvas sizing shared by the piano-roll renderers (`<PianoRoll>`, `<MidiPianoRoll>`): sizes the bitmap to container-width × height (or the container height when `height` is `undefined`) at the DPR, applies the transform, and redraws via a `drawRef` on mount + every `ResizeObserver` resize (observer created once per height, never churned by draw-closure changes). Returns a ref holding the current CSS width so draw code doesn't measure the DOM per frame. | Both piano-roll canvases. || `useCanvasRollPalette` | Resolves a canvas palette into a ref — `rollPalette` by default, or any resolver passed as the second argument (the Core Assembly avatar reads `--port-accent-2`), re-resolving on theme switch (`data-port-theme` MutationObserver) and repainting through a `drawRef`. Hands back a ref, not state, so a theme swap redraws the imperative canvas without a React re-render. | Both piano-roll canvases need theme-aware accent/bg colors that canvas `fillStyle` can't read from CSS vars. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 34e3bcc420..20a57a52b3 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -64,6 +64,7 @@ export { default as useMusicVideoMidiJob } from './useMusicVideoMidiJob.js';export { default as useMusicVideoModelSettings } from './useMusicVideoModelSettings.js';export { default as useMusicVideoRenderJob } from './useMusicVideoRenderJob.js';export { default as useMusicVideoSceneMedia } from './useMusicVideoSceneMedia.js';+export { default as useMusicVideoTakes } from './useMusicVideoTakes.js';export { default as useMusicVideoYoutubeImport } from './useMusicVideoYoutubeImport.js';export { default as useBeeperOutbox } from './useBeeperOutbox.js';export { default as useBeeperRealtime } from './useBeeperRealtime.js';diff --git a/client/src/hooks/useMusicVideoSceneMedia.js b/client/src/hooks/useMusicVideoSceneMedia.jsindex edb807a8f4..81c578c4df 100644--- a/client/src/hooks/useMusicVideoSceneMedia.js+++ b/client/src/hooks/useMusicVideoSceneMedia.js@@ -1,5 +1,5 @@import toast from '../components/ui/Toast';-import { updateMusicVideoScene } from '../services/apiMusicVideo.js';+import { addMusicVideoSceneTake } from '../services/apiMusicVideo.js';import { generateImage } from '../services/apiSystem.js';import { generateVideo } from '../services/apiImageVideo.js';import useSceneRenderLifecycle from './useSceneRenderLifecycle.js';@@ -9,6 +9,41 @@ import { isLtx2FamilyRuntime } from '../lib/runnerFamilies';// has to rule out anything that reads as a performance of it.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.';+// The image backends accept at most four reference images for most models+// (server imageGen/prepareParams.js), mirrored by the server's+// MUSIC_VIDEO_MAX_CONDITIONING_REFERENCES.+export const MAX_CONDITIONING_REFERENCES = 4;++// Refusals the image route returns when the resolved backend can't consume+// reference images — surfaced as explicit capability feedback, never retried+// silently without the references.+const REFERENCE_CAPABILITY_CODES = new Set([+ 'REFERENCE_IMAGES_FLUX2_ONLY',+ 'IMAGE_EDIT_UNSUPPORTED_MODE',+ 'TOO_MANY_REFERENCE_IMAGES',+ 'TOO_MANY_INPUT_IMAGES',+]);++/**+ * The project-wide visual direction appended to every generated prompt —+ * palette, camera rules and typography from the visual spec (#8965). Kept in+ * step with `visualDirection` in server/services/musicVideo/handoff.js, which+ * composes the same suffix for the external-tool handoff manifest.+ */+export function visualDirection(spec) {+ if (!spec) return '';+ return [+ spec.palette?.length ? `color palette ${spec.palette.join(' ')}` : '',+ spec.cameraRules?.trim() ? `camera: ${spec.cameraRules.trim()}` : '',+ spec.typography?.trim() ? `typography: ${spec.typography.trim()}` : '',+ ].filter(Boolean).join('; ');+}++/** The spec references flagged to condition reference frames, capped to the backend limit. */+export function conditioningReferences(spec) {+ return (spec?.references || []).filter((ref) => ref.condition).slice(0, MAX_CONDITIONING_REFERENCES);+}+/*** Per-scene media generation for a music-video project: the reference-frame* (image) lane and the scene-clip (i2v / a2v / native-extend) lane.@@ -26,6 +61,11 @@ const AUDIO_REACTIVE_PERFORMANCE_GUARD = 'The music drives only environmental mo* patch)` merges ONLY the given scene fields via a functional update, so a* render that resolves after the user edited the board can't clobber those* edits with a stale project snapshot.+ *+ * Finished renders land as scene TAKES (#8965): the durable attach events carry+ * the scene's current selection plus its full take list, and a new take only+ * fills an unselected slot — so a late render never replaces the frame or clip+ * the director chose.*/export default function useMusicVideoSceneMedia({ project, videoSettings, applyScenePatch } = {}) {const frameLane = useSceneRenderLifecycle({@@ -33,7 +73,8 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyScompletedEvent: 'image-gen:completed',failedEvent: 'image-gen:failed',canceledEvent: 'image-gen:canceled',- apply: ({ projectId, sceneId, referenceImageId }) => applyScenePatch?.(projectId, sceneId, { referenceImageId }),+ apply: ({ projectId, sceneId, referenceImageId, takes }) =>+ applyScenePatch?.(projectId, sceneId, { referenceImageId, ...(Array.isArray(takes) ? { takes } : {}) }),failMessage: 'Frame render failed',});const videoLane = useSceneRenderLifecycle({@@ -41,22 +82,26 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyScompletedEvent: 'video-gen:completed',failedEvent: 'video-gen:failed',canceledEvent: 'video-gen:canceled',- apply: ({ projectId, sceneId, videoHistoryId }) => applyScenePatch?.(projectId, sceneId, { videoHistoryId }),+ apply: ({ projectId, sceneId, videoHistoryId, takes }) =>+ applyScenePatch?.(projectId, sceneId, { videoHistoryId, ...(Array.isArray(takes) ? { takes } : {}) }),failMessage: 'Scene video render failed',});const genScenes = frameLane.genScenes;const genVideoScenes = videoLane.genScenes;const style = project?.concept?.style?.trim();+ const direction = visualDirection(project?.visualSpec);+ const conditioning = conditioningReferences(project?.visualSpec);// The image prompt for a scene's reference frame: its frame prompt (or the- // shot prompt as a fallback) suffixed with the project's global concept style.+ // shot prompt as a fallback) suffixed with the project's global concept style+ // and the visual spec's palette/camera/typography direction.const buildFramePrompt = (scene) =>- [(scene.framePrompt?.trim() || scene.prompt?.trim() || ''), style].filter(Boolean).join(', ');+ [(scene.framePrompt?.trim() || scene.prompt?.trim() || ''), style, direction].filter(Boolean).join(', ');// The i2v prompt for a scene's clip: its shot prompt (or the frame prompt as a- // fallback) suffixed with the same style. The reference frame already fixes- // the look; this prompt guides the motion.+ // fallback) suffixed the same way. The reference frame already fixes the+ // look; this prompt guides the motion.const buildShotPrompt = (scene) =>- [(scene.prompt?.trim() || scene.framePrompt?.trim() || ''), style].filter(Boolean).join(', ');+ [(scene.prompt?.trim() || scene.framePrompt?.trim() || ''), style, direction].filter(Boolean).join(', ');/*** Render a still reference frame for one scene from its frame prompt. The@@ -64,14 +109,23 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyS* server-side (musicVideoSceneImageHook → music-video:scene-image); we record* the job id and let the terminal image-gen:completed/failed event clear the* spinner (so a failed render doesn't strand the button). The synchronous- * external SD-API lane returns a finished filename inline — attach it here.+ * external SD-API lane returns a finished filename inline — add it as a take.+ *+ * References flagged "condition" on the visual spec ride along as real+ * conditioning inputs (`referenceImageFiles`). A backend that can't consume+ * them refuses the render, and the toast names that capability gap instead of+ * quietly rendering without the references.*/const generateFrame = (scene) => {const prompt = buildFramePrompt(scene);if (!prompt) { toast.error('Add a frame prompt or shot prompt first'); return; }const projectId = project.id;frameLane.startScene(scene.sceneId);- generateImage({ prompt, musicVideo: { projectId, sceneId: scene.sceneId } }, { silent: true })+ generateImage({+ prompt,+ ...(conditioning.length ? { referenceImageFiles: conditioning.map((ref) => ref.imageId) } : {}),+ musicVideo: { projectId, sceneId: scene.sceneId },+ }, { silent: true }).then((res) => {const stillRunning = res?.status === 'queued' || res?.status === 'running';if (stillRunning) {@@ -85,14 +139,20 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyS}const filename = res?.filename;if (filename) {- applyScenePatch?.(projectId, scene.sceneId, { referenceImageId: filename });- updateMusicVideoScene(projectId, scene.sceneId, { referenceImageId: filename }, { silent: true })+ addMusicVideoSceneTake(projectId, scene.sceneId, { kind: 'image', assetId: filename, source: 'generated' }, { silent: true })+ .then(({ scene: updated }) => applyScenePatch?.(projectId, scene.sceneId, {+ referenceImageId: updated.referenceImageId, takes: updated.takes,+ })).catch((err) => toast.error(err?.message || 'Failed to attach frame'));}frameLane.clearScene(scene.sceneId);}).catch((err) => {- toast.error(err?.message || 'Frame generation failed');+ if (conditioning.length && REFERENCE_CAPABILITY_CODES.has(err?.code)) {+ toast.error(`The current image backend can't condition on ${conditioning.length} reference image${conditioning.length === 1 ? '' : 's'}: ${err.message}. Switch the image backend, or untick "Condition frames" on the visual-spec references.`);+ } else {+ toast.error(err?.message || 'Frame generation failed');+ }frameLane.clearScene(scene.sceneId);});};@@ -210,6 +270,7 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applySreturn {genScenes,genVideoScenes,+ conditioning,buildFramePrompt,buildShotPrompt,generateFrame,diff --git a/client/src/hooks/useMusicVideoTakes.js b/client/src/hooks/useMusicVideoTakes.jsnew file mode 100644index 0000000000..f5679af8c6--- /dev/null+++ b/client/src/hooks/useMusicVideoTakes.js@@ -0,0 +1,111 @@+import { useRef, useState } from 'react';+import toast from '../components/ui/Toast';+import {+ addMusicVideoSceneTake,+ selectMusicVideoSceneTake,+ reviewMusicVideoSceneTake,+ getMusicVideoHandoff,+ importMusicVideoHandoff,+} from '../services/apiMusicVideo.js';+import { uploadGalleryImage } from '../services/apiSystem.js';+import { uploadGalleryVideo } from '../services/apiImageVideo.js';+import { downloadBlob } from '../lib/downloadBlob.js';+import { readFileAsBase64, validateImageFile, JSON_UPLOAD_MAX_FILE_SIZE } from '../utils/fileUpload.js';++const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;+const handoffFilename = (name) => `${String(name || 'music-video').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'music-video'}-handoff.json`;++/**+ * Scene-take review + external-asset handoff actions for the Music Video board+ * (#8965). Every mutation resolves to the server's updated scene, which is+ * folded back through `applyScenePatch` (selection fields + take list only), so+ * a take action never clobbers a scene prompt the director is still editing.+ * Take mutations run one at a time: a Reject followed by its note must land in+ * order, or the older response could overwrite the newer take list locally.+ *+ * Handoff import uploads each picked file through the ordinary gallery upload+ * routes (image → data/images, video → video history), then asks the server to+ * associate them with scenes by the file tags the exported manifest assigned.+ */+export default function useMusicVideoTakes({ project, applyScenePatch }) {+ const [busy, setBusy] = useState(false);+ const chainRef = useRef(Promise.resolve());++ const applyScene = (projectId, scene) => applyScenePatch?.(projectId, scene.sceneId, {+ referenceImageId: scene.referenceImageId ?? null,+ videoHistoryId: scene.videoHistoryId ?? null,+ takes: scene.takes || [],+ });++ // Serialize take mutations; a failure toasts and leaves the chain usable.+ const runTakeOp = (work, failMessage) => {+ const projectId = project.id;+ const run = chainRef.current.then(() => work(projectId));+ chainRef.current = run.then((scene) => { if (scene) applyScene(projectId, scene); })+ .catch((err) => toast.error(err?.message || failMessage));+ return chainRef.current;+ };++ const selectTake = (scene, take) => runTakeOp(+ (projectId) => selectMusicVideoSceneTake(projectId, scene.sceneId, take.takeId, { silent: true }),+ 'Failed to select take',+ );++ const reviewTake = (scene, take, review) => runTakeOp(+ (projectId) => reviewMusicVideoSceneTake(projectId, scene.sceneId, take.takeId, review, { silent: true }),+ 'Failed to update take',+ );++ // A frame picked from (or uploaded into) the gallery for one scene.+ const importTake = (scene, item) => runTakeOp(+ (projectId) => addMusicVideoSceneTake(projectId, scene.sceneId, {+ kind: 'image', assetId: item.filename, source: 'imported',+ }, { silent: true }).then((res) => res.scene),+ 'Failed to import take',+ );++ const exportHandoff = () => getMusicVideoHandoff(project.id, { silent: true })+ .then((manifest) => {+ downloadBlob(JSON.stringify(manifest, null, 2), handoffFilename(project.name), 'application/json');+ toast.success(`Exported prompts for ${plural(manifest.scenes.length, 'scene')}`);+ })+ .catch((err) => toast.error(err?.message || 'Handoff export failed'));++ const importHandoffFiles = async (files, provider) => {+ if (!files.length) return;+ const projectId = project.id;+ setBusy(true);+ const items = [];+ const failures = [];+ for (const file of files) {+ const isVideo = typeof file.type === 'string' && file.type.startsWith('video/');+ const invalid = isVideo ? null : validateImageFile(file, JSON_UPLOAD_MAX_FILE_SIZE);+ if (invalid) { failures.push(invalid); continue; }+ const base64 = await readFileAsBase64(file).catch(() => null);+ if (!base64) { failures.push(`Failed to read ${file.name}`); continue; }+ // Sequential on purpose: each upload is a whole file in one JSON body.+ const saved = await (isVideo+ ? uploadGalleryVideo(base64, file.name, { silent: true })+ : uploadGalleryImage(base64, { silent: true })+ ).catch((err) => { failures.push(`${file.name}: ${err?.message || 'upload failed'}`); return null; });+ const assetId = isVideo ? saved?.id : saved?.filename;+ if (assetId) items.push({ kind: isVideo ? 'video' : 'image', assetId, originalName: file.name });+ }+ if (items.length) {+ await importMusicVideoHandoff(projectId, { provider, items }, { silent: true })+ .then(({ project: next, imported, skipped }) => {+ const touched = new Set(imported.map((i) => i.sceneId));+ for (const scene of next.scenes || []) if (touched.has(scene.sceneId)) applyScene(projectId, scene);+ if (imported.length) toast.success(`Imported ${plural(imported.length, 'take')} from ${provider}`);+ if (skipped.length) {+ toast.error(`${plural(skipped.length, 'file')} matched no scene tag — they're in the gallery; use "Import take" on a scene to place them`);+ }+ })+ .catch((err) => failures.push(err?.message || 'Handoff import failed'));+ }+ setBusy(false);+ if (failures.length) toast.error(failures.slice(0, 3).join(' · '));+ };++ return { busy, selectTake, reviewTake, importTake, exportHandoff, importHandoffFiles };+}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 6eb5a64515..6306c2d207 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -58,6 +58,7 @@ grep -i "what you want to do" client/src/lib/README.md| `backupExcludes.js` | CLIENT MIRROR of the backup-exclude block in `server/lib/sharedSchemas.js` (#7241) — `anchorUserExclude` / `anchorUserExcludes` / `isSafeExcludePattern` / `EXCLUDE_PATTERN_MAX_LENGTH`. The Backup settings tab anchors a newly added exclude and renders the effective list with these, so the chip the user sees is the rsync filter the server will actually run instead of an unanchored pattern that matches at any depth. || `beatColors.js` | `BEAT_KIND_COLORS` + `getBeatKindColor(kind)` — per-kind display colors for reader-map emotional beats (kinds defined server-side in `storyArc.js`). Keeps every beat visualization consistent. || `beatGrid.js` | Music-video beat-quantized timeline arranger (#1854). `buildBeatGridPoints(audioAnalysis)` merges beats/downbeats/section edges into one ranked snap-point list; `snapTimeToGrid(timeSec, gridPoints, toleranceSec)` finds the nearest point within tolerance; `computeSceneSpans(scenes, durationSec)` lays out scenes without a persisted `startSec`/`endSec` contiguously as a display-only fallback; `computeDragSpan({kind, startSpan, deltaSec, gridPoints, ...})` resolves a timeline drag gesture (`'move'` or `'right'` — no `'left'`, since the render can only trim from a clip's own frame 0) into a new span; `shouldMarkBeatAligned({kind, snapped, wasPersisted})` gates the `beatAligned` flag so a reposition-only drag can't silently promote an unpersisted scene's placeholder fallback duration into a "saved exactly" render duration; `autoArrangeScenes(scenes, audioAnalysis)` proposes a full `{ sceneId, startSec, endSec, beatAligned }[]` arrangement by distributing scenes across song sections weighted by each section's `energy` (#1915). Used by `components/musicVideo/BeatTimeline.jsx` and `pages/MusicVideo.jsx`. |+| `musicVideoTakes.js` | Music-video scene takes view helpers (#8965): `sceneTakeList(scene, kind)` lists a scene's image/video takes with an un-materialized pre-takes selection appended as a read-only `legacy` take; `takePreviewKey`, `takeThumbUrl`, `takeProvenance`; `TAKE_SLOT` maps a take kind to its selection field. Used by `components/musicVideo/SceneTakeStrip.jsx` and `pages/MusicVideo.jsx`. || `bibleLimits.js` | `BIBLE_LIMITS` re-exported from the pure leaf `server/lib/bibleLimits.js`, plus the client-only `capImageRefs` / `appendImageRefById` for the optimistic imageRefs-append paths. || `characterEvolution.js` | The five-stage character evolution lens as the editors consume it. Re-exports `EVOLUTION_STAGES` / `EVOLUTION_OUTCOMES` / `EVOLUTION_STAGE_LABELS` / `EVOLUTION_STAGE_TEXT_FIELDS` / `EVOLUTION_EVIDENCE_FIELDS` / `EVOLUTION_EVIDENCE_STATUSES` / `CHARACTER_EVOLUTION_LIMITS` / `evolutionEvidenceStatus` / `isDeclaredEvolution` from the pure leaf `server/lib/characterEvolution.js` (a guard in `server/lib/characterEvolution.test.js` fails if this file ever restates a vocabulary instead of re-exporting it), adds the editor descriptors `EVOLUTION_STAGE_EDITOR_FIELDS` / `EVOLUTION_OUTCOME_HINTS` (#6440), and the draft-mutation helpers `evolutionStage` / `patchEvolution` / `patchEvolutionStage` / `patchEvolutionEvidence` that keep an editor's draft collapsing to the same shape the server sanitizer produces — so a present-but-empty field is a real clear (#6441). || `characterFramework.js` | The narrative-character framework as the editors consume it. Re-exports `CHARACTER_ARC_TYPES` / `CHARACTER_FRAMEWORK_FIELDS` / `CHARACTER_FRAMEWORK_TEXT_FIELDS` / `CHARACTER_FRAMEWORK_LIMITS` / `CHARACTER_PSYCHOLOGY_LIMITS` / `CHARACTER_SLIDER_AXES` / `PSYCHOLOGY_ASSESSMENTS` / `PSYCHOLOGY_DRIVE_AXES` / `RELATIONSHIP_LINK_TYPES` from the pure leaf `server/lib/characterFramework.js`, and adds the editor descriptors `CHARACTER_FRAMEWORK_EDITOR_FIELDS` (Ghost → Wound → Lie → Need → Want, with labels/placeholders/caps), `CHARACTER_MOTIVATIONS_FIELD`, `CHARACTER_SECRETS_FIELD`, `CHARACTER_PSYCHOLOGY_EDITOR_FIELDS` / `CHARACTER_PSYCHOLOGY_NOTE_FIELD` / `CHARACTER_PSYCHOLOGY_DRIVE_HINTS` (#6414), and `CHARACTER_SLIDER_MIN` / `CHARACTER_SLIDER_MAX`. Shared by the Universe cast editor and the Writers Room bible so the two never restate the same field copy (#6417). |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 42751950d5..16f10da565 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -66,6 +66,7 @@ export * from './issueLength.js';export * from './issueRefs.js';export * from './musicDuration.js';export * from './muscriptorModels.js';+export * from './musicVideoTakes.js';export * from './pipelineImageDefaults.js';export * from './reverseOutlineGrid.js';export * from './reviewerModels.js';diff --git a/client/src/lib/musicVideoTakes.js b/client/src/lib/musicVideoTakes.jsnew file mode 100644index 0000000000..f2fcd084ac--- /dev/null+++ b/client/src/lib/musicVideoTakes.js@@ -0,0 +1,36 @@+/**+ * Music Video scene takes (#8965) — client-side view helpers.+ *+ * A scene slot (`referenceImageId` / `videoHistoryId`) is the director's+ * selection among the scene's immutable `takes`. A pre-#8965 record has a+ * selection but no takes list yet (the server materializes it on the scene's+ * next take operation), so the board shows that selection as a read-only+ * `legacy` take rather than hiding it.+ */++export const TAKE_SLOT = Object.freeze({ image: 'referenceImageId', video: 'videoHistoryId' });++/** The takes of one kind for a scene, with an un-materialized selection appended. */+export function sceneTakeList(scene, kind) {+ const selected = scene?.[TAKE_SLOT[kind]] || null;+ const takes = (Array.isArray(scene?.takes) ? scene.takes : []).filter((t) => t?.kind === kind);+ if (selected && !takes.some((t) => t.assetId === selected)) {+ return [...takes, { takeId: null, kind, assetId: selected, source: 'legacy', status: 'candidate', note: null }];+ }+ return takes;+}++/** Preview/lightbox key for a take (`image:<filename>` / `video:<historyId>`). */+export const takePreviewKey = (take) => `${take.kind}:${take.assetId}`;++/** Thumbnail URL for a take: the gallery still, or the clip's generated poster. */+export const takeThumbUrl = (take) => (take.kind === 'image'+ ? `/data/images/${encodeURIComponent(take.assetId)}`+ : `/data/video-thumbnails/${encodeURIComponent(take.assetId)}.jpg`);++/** Short provenance label: the external provider for an import, else the source. */+export function takeProvenance(take) {+ if (take.source === 'imported') return take.provider ? `imported · ${take.provider}` : 'imported';+ if (take.source === 'generated') return 'generated';+ return take.source || 'take';+}diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex c453bb5bf1..43d6235543 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -1,5 +1,5 @@import { useEffect, useState, useCallback, useMemo, useRef } from 'react';-import { useParams, useNavigate } from 'react-router';+import { useParams, useNavigate, useSearchParams } from 'react-router';import { Plus, Film } from 'lucide-react';import toast from '../components/ui/Toast';import AutoSizeTextarea from '../components/ui/AutoSizeTextarea';@@ -25,6 +25,7 @@ import useMusicVideoRenderJob from '../hooks/useMusicVideoRenderJob.js';import useMusicVideoModelSettings from '../hooks/useMusicVideoModelSettings.js';import useMusicVideoManualTempo from '../hooks/useMusicVideoManualTempo.js';import useMusicVideoSceneMedia from '../hooks/useMusicVideoSceneMedia.js';+import useMusicVideoTakes from '../hooks/useMusicVideoTakes.js';import useHydratedPreviewRoute from '../hooks/useHydratedPreviewRoute.js';import { normalizeImage, normalizeVideo } from '../components/media/normalize.js';import { useVideoFileSrc } from '../hooks/useVideoFileSrc.js';@@ -40,9 +41,14 @@ import RenderStatusPanel from '../components/musicVideo/RenderStatusPanel.jsx';import AnalysisPanel from '../components/musicVideo/AnalysisPanel.jsx';import SceneCard from '../components/musicVideo/SceneCard.jsx';import LyricsPanel from '../components/musicVideo/LyricsPanel.jsx';+import VisualSpecPanel from '../components/musicVideo/VisualSpecPanel.jsx';+import HandoffControls from '../components/musicVideo/HandoffControls.jsx';+import ContactSheetDrawer from '../components/musicVideo/ContactSheetDrawer.jsx';+import GalleryImagePicker from '../components/imageGen/GalleryImagePicker.jsx';import { autoArrangeScenes } from '../lib/beatGrid.js';import { isLtx2FamilyRuntime } from '../lib/runnerFamilies';import { videoPosterForJob } from '../lib/creativeDirectorPreview.js';+import { sceneTakeList } from '../lib/musicVideoTakes.js';const STATUS_COLORS = {draft: 'bg-port-border text-port-text',@@ -112,6 +118,21 @@ export default function MusicVideo() {videoSettings,applyScenePatch: patchScene,});+ const takes = useMusicVideoTakes({ project: selected, applyScenePatch: patchScene });+ // The one gallery picker on the page, aimed at either the visual spec's+ // references or one scene's frame takes. Cleared on a project switch so a+ // picker opened for one project can never write into another.+ const [pickerTarget, setPickerTarget] = useState(null);+ useEffect(() => { setPickerTarget(null); }, [selectedId]);+ // Contact sheet open state lives in the URL (?sheet=contact) so it survives a+ // reload and Back closes it.+ const [searchParams, setSearchParams] = useSearchParams();+ const contactSheetOpen = searchParams.get('sheet') === 'contact';+ const setContactSheetOpen = (open) => setSearchParams((prev) => {+ const next = new URLSearchParams(prev);+ if (open) next.set('sheet', 'contact'); else next.delete('sheet');+ return next;+ });// Preparation is already resolving the project's audio at kickoff;// relinking the track now would leave the project pointing at a NEW track@@ -366,6 +387,29 @@ export default function MusicVideo() {saveScene(sceneId, patch);};+ // Visual spec (#8965) — optimistic local merge, then a chained PATCH whose+ // response carries server-minted reference ids back onto the board.+ const visualSpecSaveChain = useRef(Promise.resolve());+ const saveVisualSpec = (patch) => {+ const projectId = selected.id;+ patchProject(projectId, (p) => ({ visualSpec: { ...(p.visualSpec || {}), ...patch } }));+ visualSpecSaveChain.current = visualSpecSaveChain.current+ .then(() => updateMusicVideoProject(projectId, { visualSpec: patch }, { silent: true }))+ .then((proj) => { if (proj?.visualSpec) patchProject(projectId, { visualSpec: proj.visualSpec }); })+ .catch((err) => toast.error(err?.message || 'Failed to save visual spec'));+ };+ const handlePickerSelect = (item) => {+ if (!item?.filename || !pickerTarget || !selected) return;+ if (pickerTarget.type === 'reference') {+ const references = selected.visualSpec?.references || [];+ if (references.some((ref) => ref.imageId === item.filename)) return;+ saveVisualSpec({ references: [...references, { imageId: item.filename, role: 'mood', condition: false }] });+ return;+ }+ const scene = (selected.scenes || []).find((s) => s.sceneId === pickerTarget.sceneId);+ if (scene) takes.importTake(scene, item);+ };+const handleDeleteScene = (sceneId) => {deleteMusicVideoScene(selected.id, sceneId, { silent: true }).then((proj) => replaceProject(proj))@@ -421,15 +465,18 @@ export default function MusicVideo() {`Music Video: ${selected.name}`,));}+ // Every take (#8965), selected first, so the take strips and contact sheet+ // can open any candidate in the shared lightbox.for (const scene of selected.scenes || []) {- if (scene.referenceImageId) {- items.push(normalizeImage({- filename: scene.referenceImageId,- prompt: scene.framePrompt || scene.prompt || '',- }));+ const frames = sceneTakeList(scene, 'image')+ .sort((a, b) => (b.assetId === scene.referenceImageId) - (a.assetId === scene.referenceImageId));+ for (const take of frames) {+ items.push(normalizeImage({ filename: take.assetId, prompt: take.prompt || scene.framePrompt || scene.prompt || '' }));}- if (scene.videoHistoryId) {- items.push(videoItem(scene.videoHistoryId, `${scene.videoHistoryId}.mp4`, scene.prompt || ''));+ const clips = sceneTakeList(scene, 'video')+ .sort((a, b) => (b.assetId === scene.videoHistoryId) - (a.assetId === scene.videoHistoryId));+ for (const take of clips) {+ items.push(videoItem(take.assetId, `${take.assetId}.mp4`, take.prompt || scene.prompt || ''));}}// Scenes can reuse the same frame/clip (ProjectToolbar surfaces a@@ -450,6 +497,25 @@ export default function MusicVideo() {<MidiInstallModal {...midi.installGate} /><MidiGatedModal {...midi.gatedGate} /><MediaPreview preview={preview} setPreview={setPreview} items={previewItems} />+ {pickerTarget && (+ <GalleryImagePicker+ open+ allowUpload+ onClose={() => setPickerTarget(null)}+ onSelect={handlePickerSelect}+ />+ )}+ {selected && (+ <ContactSheetDrawer+ open={contactSheetOpen}+ onClose={() => setContactSheetOpen(false)}+ project={selected}+ busy={takes.busy}+ onSelectTake={takes.selectTake}+ onReviewTake={takes.reviewTake}+ onOpenPreview={openPreview}+ />+ )}<PageHeader icon={Film} title="Music Video" subtitle="Director-controlled, beat-aware music videos" /><CreateProjectDrawer@@ -562,6 +628,19 @@ export default function MusicVideo() {/></div></div>+ <VisualSpecPanel+ key={selected.id}+ project={selected}+ onSave={saveVisualSpec}+ onAddReference={() => setPickerTarget({ type: 'reference' })}+ />+ <HandoffControls+ projectId={selected.id}+ busy={takes.busy}+ onExport={takes.exportHandoff}+ onImport={takes.importHandoffFiles}+ onOpenContactSheet={() => setContactSheetOpen(true)}+ /><TrackPanelproject={selected}tracks={tracks}@@ -625,6 +704,10 @@ export default function MusicVideo() {onGenerateVideo={sceneMedia.generateSceneVideo}onContinueVideo={sceneMedia.continueSceneVideo}onOpenPreview={openPreview}+ takeBusy={takes.busy}+ onSelectTake={takes.selectTake}+ onReviewTake={takes.reviewTake}+ onImportTake={(target) => setPickerTarget({ type: 'take', sceneId: target.sceneId })}/>))}</div>diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex d907e57d18..09423c90ec 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -58,8 +58,13 @@ vi.mock('../services/apiMusicVideo.js', () => ({transcribeMusicVideoMidi: vi.fn(async () => ({ jobId: 'midi-job-1', model: 'medium' })),musicVideoMidiEventsUrl: (jobId) => `/api/music-video/transcribe-midi/${jobId}/events`,cancelMusicVideoMidiTranscription: vi.fn(async () => ({ ok: true })),+ addMusicVideoSceneTake: vi.fn(),+ selectMusicVideoSceneTake: vi.fn(),+ reviewMusicVideoSceneTake: vi.fn(),+ getMusicVideoHandoff: vi.fn(),+ importMusicVideoHandoff: vi.fn(),}));-vi.mock('../services/apiSystem.js', () => ({ generateImage: vi.fn() }));+vi.mock('../services/apiSystem.js', () => ({ generateImage: vi.fn(), uploadGalleryImage: vi.fn() }));vi.mock('../hooks/useProviderModels', () => ({default: () => ({providers: [], selectedProviderId: '', selectedModel: '', availableModels: [],@@ -72,6 +77,7 @@ vi.mock('../hooks/useMidiNotes.js', () => ({}));vi.mock('../services/apiImageVideo.js', () => ({generateVideo: vi.fn(),+ uploadGalleryVideo: vi.fn(),listLorasFull: vi.fn(async () => [{filename: 'audio-reactive.safetensors',name: 'Audio Reactive',@@ -134,7 +140,9 @@ import {listMusicVideoProjects, createMusicVideoProject, cloneMusicVideoProject, renderMusicVideoProject, planMusicVideoProject, updateMusicVideoProject,deleteMusicVideoProject, transcribeMusicVideoMidi, cancelMusicVideoRender,importMusicVideoLyrics, updateMusicVideoScene,+ selectMusicVideoSceneTake, reviewMusicVideoSceneTake, importMusicVideoHandoff,} from '../services/apiMusicVideo.js';+import { generateImage, uploadGalleryImage } from '../services/apiSystem.js';import { importTrackFromYoutube, trackImportEventsUrl, listTracks } from '../services/apiTracks.js';import { generateVideo, getVideoGenStatus } from '../services/apiImageVideo.js';@@ -782,7 +790,9 @@ describe('MusicVideo YouTube audio import (#1945)', () => {it('disables the Import button until a URL is entered', async () => {await openProject(PROJECT_NO_CLIP);- const importBtns = screen.getAllByRole('button', { name: /Import/i });+ // Exact name: the board also carries "Import take" / handoff import controls.+ const importBtns = screen.getAllByRole('button', { name: /^Import$/i });+ expect(importBtns.length).toBeGreaterThan(0);importBtns.forEach((btn) => expect(btn).toHaveProperty('disabled', true));});@@ -1037,3 +1047,91 @@ describe('MusicVideo media lightbox (#3718)', () => {expect(dialog.getAttribute('aria-label')).toMatch(/img1|image:img1/);});});++describe('MusicVideo visual spec, takes and handoff (#8965)', () => {+ const SPEC_PROJECT = {+ ...PROJECT_NO_CLIP,+ id: 'mv-spec',+ name: 'Spec Project',+ concept: { style: 'grainy 16mm' },+ visualSpec: {+ palette: ['#112233'],+ cameraRules: 'locked-off wides',+ typography: '',+ references: [+ { id: 'r1', imageId: 'mood.png', role: 'character', label: 'Lead', note: '', condition: true },+ { id: 'r2', imageId: 'set.png', role: 'set', label: 'Pier', note: '', condition: false },+ ],+ },+ scenes: [{ sceneId: 's1', order: 0, prompt: 'waves', framePrompt: 'harbor at dawn', referenceImageId: null, videoHistoryId: null, takes: [] }],+ };++ it('sends flagged references as conditioning inputs and names the capability gap when the backend refuses them', async () => {+ generateImage.mockRejectedValueOnce(Object.assign(+ new Error('Reference images are only supported for FLUX.2 and Qwen Image 2.1 models on the local backend'),+ { code: 'REFERENCE_IMAGES_FLUX2_ONLY', status: 400 },+ ));+ await openProject(SPEC_PROJECT);+ fireEvent.click(screen.getByRole('button', { name: /^Generate frame$/ }));+ await waitFor(() => expect(generateImage).toHaveBeenCalledWith({+ prompt: 'harbor at dawn, grainy 16mm, color palette #112233; camera: locked-off wides',+ referenceImageFiles: ['mood.png'],+ musicVideo: { projectId: 'mv-spec', sceneId: 's1' },+ }, { silent: true }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith(+ expect.stringMatching(/can't condition on 1 reference image: Reference images are only supported/),+ ));+ });++ it('keeps a new render as a candidate and lets the director explicitly pick and reject takes', async () => {+ const scene = {+ sceneId: 's1', order: 0, prompt: 'waves', referenceImageId: 'take-a.png', videoHistoryId: null,+ takes: [+ { takeId: 't-a', kind: 'image', assetId: 'take-a.png', source: 'generated', provider: 'portos', status: 'candidate', note: null },+ { takeId: 't-b', kind: 'image', assetId: 'take-b.png', source: 'imported', provider: 'midjourney', status: 'candidate', note: null },+ ],+ };+ selectMusicVideoSceneTake.mockResolvedValueOnce({ ...scene, referenceImageId: 'take-b.png' });+ reviewMusicVideoSceneTake.mockResolvedValueOnce({+ ...scene,+ referenceImageId: 'take-b.png',+ takes: [{ ...scene.takes[0], status: 'rejected' }, scene.takes[1]],+ });+ await openProject({ ...PROJECT_NO_CLIP, id: 'mv-takes', name: 'Takes Project', scenes: [scene] });++ const strip = screen.getByRole('list', { name: /Frame takes/ });+ expect(within(strip).getByText(/imported · midjourney/)).toBeTruthy();+ fireEvent.click(within(strip).getByRole('button', { name: /Use/ }));+ await waitFor(() => expect(selectMusicVideoSceneTake).toHaveBeenCalledWith('mv-takes', 's1', 't-b', { silent: true }));+ // The server's answer moves the selection; the other take now offers "Use".+ await waitFor(() => expect(within(strip).getAllByText(/Selected/)).toHaveLength(1));+ const items = within(strip).getAllByRole('listitem');+ expect(within(items[1]).queryByRole('button', { name: /Use/ })).toBeNull();++ fireEvent.click(within(items[0]).getByRole('button', { name: /Reject/ }));+ await waitFor(() => expect(reviewMusicVideoSceneTake).toHaveBeenCalledWith('mv-takes', 's1', 't-a', { status: 'rejected' }, { silent: true }));+ await waitFor(() => expect(within(items[0]).getByRole('button', { name: /Restore/ })).toBeTruthy());+ });++ it('imports externally generated files through the gallery upload, then associates them by scene tag with provider provenance', async () => {+ uploadGalleryImage.mockResolvedValueOnce({ filename: 'upload-0001.png', path: '/data/images/upload-0001.png' });+ const importedTake = { takeId: 't-mj', kind: 'image', assetId: 'upload-0001.png', source: 'imported', provider: 'midjourney', status: 'candidate', note: null, originalName: 'S01-s1-harbor.png' };+ importMusicVideoHandoff.mockResolvedValueOnce({+ project: { ...SPEC_PROJECT, scenes: [{ ...SPEC_PROJECT.scenes[0], referenceImageId: 'upload-0001.png', takes: [importedTake] }] },+ imported: [{ sceneId: 's1', takeId: 't-mj', kind: 'image', assetId: 'upload-0001.png', originalName: 'S01-s1-harbor.png' }],+ skipped: [],+ });+ await openProject(SPEC_PROJECT);++ const file = new File(['png-bytes'], 'S01-s1-harbor.png', { type: 'image/png' });+ fireEvent.change(screen.getByLabelText('Import generated files'), { target: { files: [file] } });+ await waitFor(() => expect(importMusicVideoHandoff).toHaveBeenCalledWith('mv-spec', {+ provider: 'midjourney',+ items: [{ kind: 'image', assetId: 'upload-0001.png', originalName: 'S01-s1-harbor.png' }],+ }, { silent: true }));+ expect(uploadGalleryImage).toHaveBeenCalledTimes(1);+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Imported 1 take from midjourney'));+ // The imported take filled the empty slot on the board.+ expect(await screen.findByRole('button', { name: 'View scene 1 reference frame full size' })).toBeTruthy();+ });+});diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex d9f2f8e8b9..24c483ee2b 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -65,6 +65,33 @@ export const reorderMusicVideoScenes = (id, sceneIds, options = {}) =>method: 'POST', body: JSON.stringify({ sceneIds }), ...options,});+// ---- Scene takes (#8965) ----+// Every render/import for a scene slot is an immutable take; the scene's+// referenceImageId / videoHistoryId is the explicit selection among them.+// addMusicVideoSceneTake body: { kind: 'image'|'video', assetId, source?, provider?, originalName? }+// → { scene, take }. select / review resolve to the updated scene.+const takesPath = (id, sceneId) => `/music-video/${encodeURIComponent(id)}/scenes/${encodeURIComponent(sceneId)}/takes`;+export const addMusicVideoSceneTake = (id, sceneId, body, options = {}) => request(takesPath(id, sceneId), {+ method: 'POST', body: JSON.stringify(body), ...options,+});+export const selectMusicVideoSceneTake = (id, sceneId, takeId, options = {}) =>+ request(`${takesPath(id, sceneId)}/${encodeURIComponent(takeId)}/select`, { method: 'POST', ...options });+export const reviewMusicVideoSceneTake = (id, sceneId, takeId, review, options = {}) =>+ request(`${takesPath(id, sceneId)}/${encodeURIComponent(takeId)}`, {+ method: 'PATCH', body: JSON.stringify(review), ...options,+ });++// ---- External-asset handoff (#8965) ----+// Export the per-scene prompt/reference manifest for a tool PortOS doesn't+// drive (e.g. Midjourney), and import what was generated there. Import body:+// { provider, items: [{ kind, assetId, sceneId?, originalName? }] } where each+// asset was already stored through the gallery upload routes; resolves to+// { project, imported, skipped }.+export const getMusicVideoHandoff = (id, options = {}) => request(`/music-video/${encodeURIComponent(id)}/handoff`, options);+export const importMusicVideoHandoff = (id, body, options = {}) => request(`/music-video/${encodeURIComponent(id)}/handoff/import`, {+ method: 'POST', body: JSON.stringify(body), ...options,+});+// ---- Audio → MIDI transcription (MuScriptor) ----// Transcribe the project's source audio into a .mid via the local MuScriptor// sidecar. Kickoff resolves to { jobId, model } (503 with an install hint whendiff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex a999c19830..c8ed8a8855 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -74,6 +74,91 @@ export const musicVideoPacingSchema = z.object({const lyricCueList = z.array(musicVideoLyricCueSchema).max(2000);const phraseList = z.array(musicVideoPhraseSchema).max(500);+// ---- Visual specification + scene takes (#8965) ----------------------------++// A gallery image basename (under data/images). Every generated, uploaded, or+// imported still lands there, so this is the one reference vocabulary the image+// route's `referenceImageFiles` and the peer-sync `image` asset kind share.+const galleryImageName = z.string().min(1).max(256)+ .regex(/^[^/\\]+\.(png|jpg|jpeg|webp)$/i, 'must be a gallery image basename (png/jpg/jpeg/webp)');+// A video-history id (the scene clip vocabulary `videoHistoryId` already uses).+const videoHistoryIdSchema = z.string().min(1).max(64).regex(/^[A-Za-z0-9._-]+$/, 'must be a video history id');++export const MUSIC_VIDEO_REFERENCE_ROLES = ['mood', 'character', 'wardrobe', 'set', 'prop', 'style'];+// The image backends accept at most four reference images for most models+// (imageGen/prepareParams.js referenceCap), so a project conditions each+// reference frame on at most this many of its flagged references.+export const MUSIC_VIDEO_MAX_CONDITIONING_REFERENCES = 4;++// One moodboard/reference asset. `condition: true` sends the image to frame+// generation as a real conditioning input (`referenceImageFiles`) rather than+// only describing it in prose.+export const musicVideoVisualReferenceSchema = z.object({+ id: z.string().min(1).max(64).optional(),+ imageId: galleryImageName,+ role: z.enum(MUSIC_VIDEO_REFERENCE_ROLES).optional(),+ label: z.string().max(120).optional(),+ note: z.string().max(1000).optional(),+ condition: z.boolean().optional(),+}).strict();++// The project's reusable visual specification. A patch merges per sub-field+// (like `concept`), and `references` / `palette` replace their list whole.+export const musicVideoVisualSpecSchema = z.object({+ references: z.array(musicVideoVisualReferenceSchema).max(24).optional(),+ palette: z.array(z.string().regex(/^#[0-9a-f]{6}$/i, 'palette colors are #rrggbb')).max(12).optional(),+ typography: z.string().max(1000).optional(),+ cameraRules: z.string().max(2000).optional(),+ // An existing Mood Board this project draws inspiration from (display link).+ moodBoardId: z.string().max(64).nullable().optional(),+}).strict().refine(+ (spec) => (spec.references || []).filter((ref) => ref.condition).length <= MUSIC_VIDEO_MAX_CONDITIONING_REFERENCES,+ { message: `at most ${MUSIC_VIDEO_MAX_CONDITIONING_REFERENCES} references can condition frames`, path: ['references'] },+);++export const MUSIC_VIDEO_TAKE_KINDS = ['image', 'video'];+export const MUSIC_VIDEO_TAKE_STATUSES = ['candidate', 'rejected'];++// Provider label for provenance — free text so a new external tool needs no+// schema change, but bounded to a slug so it can't smuggle a URL or a secret.+const providerSlug = z.string().min(1).max(40).regex(/^[a-z0-9][a-z0-9._-]*$/i, 'provider must be a short slug');++// A candidate asset offered for a scene slot outside the media-job hooks: an+// external-tool import, or a synchronous-lane render the client already holds.+// `assetId` is validated against its kind (gallery basename / history id) and+// then existence-checked by the route before it can reach the record.+export const musicVideoTakeInputSchema = z.object({+ kind: z.enum(MUSIC_VIDEO_TAKE_KINDS),+ assetId: z.string().min(1).max(256),+ source: z.enum(['generated', 'imported']).optional(),+ provider: providerSlug.optional(),+ originalName: z.string().max(255).optional(),+}).strict().superRefine((take, ctx) => {+ const check = take.kind === 'image' ? galleryImageName : videoHistoryIdSchema;+ const parsed = check.safeParse(take.assetId);+ if (!parsed.success) ctx.addIssue({ code: 'custom', path: ['assetId'], message: parsed.error.issues[0].message });+});++// Review a take: reject/restore it and/or leave a note for regeneration.+export const musicVideoTakeReviewSchema = z.object({+ status: z.enum(MUSIC_VIDEO_TAKE_STATUSES).optional(),+ note: z.string().max(1000).nullable().optional(),+}).strict().refine((r) => r.status !== undefined || r.note !== undefined, { message: 'status or note is required' });++// Import externally generated assets (e.g. a Midjourney handoff). Each item is+// an asset the client already stored through the existing gallery upload+// routes; `sceneId` is optional when `originalName` carries the scene file tag+// from the exported handoff manifest.+export const musicVideoHandoffImportSchema = z.object({+ provider: providerSlug,+ items: z.array(z.object({+ kind: z.enum(MUSIC_VIDEO_TAKE_KINDS),+ assetId: z.string().min(1).max(256),+ sceneId: z.string().min(1).max(64).optional(),+ originalName: z.string().max(255).optional(),+ }).strict()).min(1).max(200),+}).strict();+// Import lyric cues from pasted text: LRC (`[mm:ss.xx] line`), SRT/WebVTT// cue blocks, or plain lines (untimed). `auto` sniffs the format.export const musicVideoLyricsImportSchema = z.object({@@ -91,6 +176,7 @@ export const musicVideoProjectCreateSchema = z.object({trackId: z.string().max(64).nullable().optional(),uploadedAudioFilename: z.string().max(256).nullable().optional(),concept: musicVideoConceptSchema.nullable().optional(),+ visualSpec: musicVideoVisualSpecSchema.optional(),videoSettings: musicVideoVideoSettingsSchema.optional(),}).strict();@@ -101,6 +187,7 @@ export const musicVideoProjectUpdateSchema = z.object({trackId: z.string().max(64).nullable().optional(),uploadedAudioFilename: z.string().max(256).nullable().optional(),concept: musicVideoConceptSchema.nullable().optional(),+ visualSpec: musicVideoVisualSpecSchema.optional(),videoSettings: musicVideoVideoSettingsSchema.optional(),renderHistoryId: z.string().max(64).nullable().optional(),lyricCues: lyricCueList.optional(),diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 5f3c1a3b56..72d61a292b 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -587,7 +587,15 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// to the OLD track — an edit that then wins LWW onto the upgraded peer.// Gating makes a v1 receiver reject the ahead-version transfer until it// upgrades; pre-#8964 records need no rewrite (absent `loop` = legacy loop).- musicVideoProjects: 2,+ // v3 = immutable scene takes + explicit selection and the project visual spec+ // (#8965). A v2 receiver stores the body verbatim but mis-executes it: its+ // completion hooks overwrite `referenceImageId`/`videoHistoryId` with the+ // newest render — replacing a take the director explicitly selected — and+ // record no take for it, an edit that then wins LWW onto the upgraded peer.+ // Gating makes a v2 receiver reject the ahead-version transfer until it+ // upgrades; pre-#8965 records need no rewrite (a selected slot with no take+ // is materialized as a `legacy` take on first use).+ musicVideoProjects: 3,// v1 = Creative Commission FEEDBACK federation (PostgreSQL `commission_feedback`)// via the per-record peer-sync push pipeline (record kind `commissionFeedback`,// sync category `commissionFeedback`, #2686 — split-record follow-up to #2657).diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex 7ee901ecb5..8156473bcb 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -212,11 +212,11 @@ const generateSchema = z.object({role: z.literal('image').optional(),}).optional(),// Music Video scene reference-frame render (#1760 Phase 1b). When present, the- // mediaJobQueue completion hook (`musicVideoSceneImageHook`) files the finished- // render onto the project scene's `referenceImageId` — durably, even if the+ // mediaJobQueue completion hook (`musicVideoSceneImageHook`) appends the+ // finished render to the project scene's takes (#8965) — durably, even if the// director board unmounted mid-render. Only the async local/Codex lanes ride// the queue this hook listens to; the synchronous external SD-API lane returns- // the filename inline and the client PATCHes `referenceImageId` directly. Rides+ // the filename inline and the client adds it through the scene takes route. Rides// into job.params untouched via `...params` (like `writersRoom`). JSON-only.musicVideo: z.object({projectId: z.string().min(1).max(200),diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex 73e0f75c05..9e16bb2858 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -22,12 +22,16 @@ import {musicVideoManualAnalysisSchema,musicVideoTranscribeMidiRequestSchema,musicVideoLyricsImportSchema,+ musicVideoTakeInputSchema,+ musicVideoTakeReviewSchema,+ musicVideoHandoffImportSchema,isPaginationRequested,paginateArray,} from '../lib/validation.js';import { recordRenderPinFields } from '../lib/sharedSchemas.js';import { PATHS } from '../lib/fileUtils.js';import { safeUnder } from '../lib/ffmpeg.js';+import { resolveGalleryImage } from '../lib/pathSafety.js';import {listProjects,getProject,@@ -41,7 +45,13 @@ import {deleteScene,reorderProjectScenes,setProjectMidiTranscription,+ appendSceneTakes,+ appendTakesAcrossScenes,+ selectSceneTake,+ reviewSceneTake,} from '../services/musicVideo/projects.js';+import { buildHandoffManifest, matchSceneByFileTag } from '../services/musicVideo/handoff.js';+import { getHistoryItem } from '../services/videoGen/history.js';import {startMidiTranscription,attachMidiTranscriptionSseClient,@@ -297,4 +307,78 @@ router.post('/:id/scenes/reorder', asyncHandler(async (req, res) => {res.json(updated);}));+// --- Scene takes (#8965) ---+// Every render or import for a scene slot is kept as an immutable take; the+// slot field is the director's explicit selection among them. A take's asset+// must already exist in this install's media stores — an image in the gallery,+// a clip in the video history (both reached through the existing upload+// routes) — so a take can never point at an arbitrary file.+async function takeAssetExists(kind, assetId) {+ if (kind === 'image') return Boolean(resolveGalleryImage(assetId));+ return Boolean(await getHistoryItem(assetId));+}++// Add one candidate take to a scene: the synchronous image lane's inline+// render, or an asset the director imports from the gallery.+router.post('/:id/scenes/:sceneId/takes', asyncHandler(async (req, res) => {+ const { kind, assetId, source = 'imported', provider, originalName } = validateRequest(musicVideoTakeInputSchema, req.body);+ if (!(await takeAssetExists(kind, assetId))) {+ throw new ServerError(`${kind === 'image' ? 'Image' : 'Video'} not found in this install's media library`, { status: 400, code: 'TAKE_ASSET_NOT_FOUND' });+ }+ const { scene, appended } = await appendSceneTakes(req.params.id, req.params.sceneId, [{+ kind, assetId, source, provider: provider ?? (source === 'generated' ? 'portos' : null), originalName,+ }]);+ res.status(201).json({ scene, take: appended[0] });+}));++router.post('/:id/scenes/:sceneId/takes/:takeId/select', asyncHandler(async (req, res) => {+ res.json(await selectSceneTake(req.params.id, req.params.sceneId, req.params.takeId));+}));++router.patch('/:id/scenes/:sceneId/takes/:takeId', asyncHandler(async (req, res) => {+ const review = validateRequest(musicVideoTakeReviewSchema, req.body);+ res.json(await reviewSceneTake(req.params.id, req.params.sceneId, req.params.takeId, review));+}));++// --- External-asset handoff (#8965) ---+// Export per-scene prompts + reference files for a tool PortOS does not drive+// (e.g. Midjourney), and import what the director generated there. Nothing+// here contacts the external service.+router.get('/:id/handoff', asyncHandler(async (req, res) => {+ const project = await getProject(req.params.id);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ res.json(buildHandoffManifest(project));+}));++// Associate already-uploaded assets with scenes. An item names its scene+// explicitly or carries the manifest's file tag in `originalName`; an item that+// resolves to no scene, or whose asset isn't in this install's media stores, is+// reported in `skipped` rather than guessed. All matched items land in one+// record write with `imported` source + provider provenance.+router.post('/:id/handoff/import', asyncHandler(async (req, res) => {+ const { provider, items } = validateRequest(musicVideoHandoffImportSchema, req.body);+ const project = await getProject(req.params.id);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const sceneIds = new Set((project.scenes || []).map((scene) => scene.sceneId));+ const accepted = [];+ const skipped = [];+ for (const item of items) {+ const sceneId = item.sceneId || matchSceneByFileTag(project.scenes, item.originalName);+ const skip = (reason) => skipped.push({ assetId: item.assetId, originalName: item.originalName ?? null, reason });+ if (!sceneId || !sceneIds.has(sceneId)) { skip('no-matching-scene'); continue; }+ if (!musicVideoTakeInputSchema.safeParse({ kind: item.kind, assetId: item.assetId }).success+ || !(await takeAssetExists(item.kind, item.assetId))) { skip('asset-not-found'); continue; }+ accepted.push({ sceneId, kind: item.kind, assetId: item.assetId, source: 'imported', provider, originalName: item.originalName });+ }+ if (accepted.length === 0) {+ return res.json({ project, imported: [], skipped });+ }+ const { project: next, appended } = await appendTakesAcrossScenes(project.id, accepted);+ res.json({+ project: next,+ imported: appended.map(({ sceneId, take }) => ({ sceneId, takeId: take.takeId, kind: take.kind, assetId: take.assetId, originalName: take.originalName })),+ skipped,+ });+}));+export default router;diff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.jsindex 24aa3076fb..9e25114657 100644--- a/server/routes/musicVideo.test.js+++ b/server/routes/musicVideo.test.js@@ -18,6 +18,11 @@ vi.mock('../services/musicVideo/projects.js', () => ({deleteScene: vi.fn(async (id) => ({ id, scenes: [] })),reorderProjectScenes: vi.fn(async (id, ids) => ({ id, scenes: ids.map((sceneId, order) => ({ sceneId, order })) })),setProjectMidiTranscription: vi.fn(async (id, midi) => ({ id, midiTranscription: midi })),+ // Scene takes (#8965) — exercised against the real store in musicVideoTakes.test.js.+ appendSceneTakes: vi.fn(),+ appendTakesAcrossScenes: vi.fn(),+ selectSceneTake: vi.fn(),+ reviewSceneTake: vi.fn(),}));// Keeps the real `buildManualAnalysisFromCached` (pure arithmetic, worthdiff --git a/server/routes/musicVideoTakes.test.js b/server/routes/musicVideoTakes.test.jsnew file mode 100644index 0000000000..5876758b1b--- /dev/null+++ b/server/routes/musicVideoTakes.test.js@@ -0,0 +1,189 @@+/**+ * Music Video scene takes + external-asset handoff routes (#8965), exercised+ * through the real router and the real file-backed project store. Covers the+ * explicit-selection contract (select / reject / note survive a re-read), the+ * existence check that keeps a take from pointing at an arbitrary file, and a+ * synthetic Midjourney-style handoff round trip: export → files named with the+ * scene tags → import → exact scene association + provider provenance.+ */++import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import express from 'express';+import { mkdirSync, rmSync, writeFileSync } from 'fs';+import { join } from 'path';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';++const ROOT = () => lazyTempDataRoot('mv-takes-route-test-');+vi.mock('../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), { dataRoot: ROOT }));+vi.mock('../services/settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));++const { default: musicVideoRoutes } = await import('./musicVideo.js');+const projects = await import('../services/musicVideo/projects.js');++const app = express();+app.use(express.json());+app.use('/api/music-video', musicVideoRoutes);+app.use(errorMiddleware);++function seedImage(name) {+ mkdirSync(join(ROOT(), 'images'), { recursive: true });+ writeFileSync(join(ROOT(), 'images', name), 'png-bytes');+}+function seedVideoHistory(rows) {+ writeFileSync(join(ROOT(), 'video-history.json'), JSON.stringify(rows));+}++let project;+let sceneA;+let sceneB;+beforeEach(async () => {+ rmSync(join(ROOT(), 'music-video-projects.json'), { force: true });+ rmSync(join(ROOT(), 'images'), { recursive: true, force: true });+ seedVideoHistory([]);+ project = await projects.createProject({ name: 'Example Video' });+ sceneA = await projects.addProjectScene(project.id, { prompt: 'a lighthouse at dusk', framePrompt: 'lighthouse still' });+ sceneB = await projects.addProjectScene(project.id, { prompt: 'waves crash' });+});+afterAll(cleanupTempDataRoots);++const base = () => `/api/music-video/${project.id}`;+const addTake = (sceneId, body) => request(app).post(`${base()}/scenes/${sceneId}/takes`).send(body);+const reload = async () => projects.getProject(project.id);++describe('scene takes routes', () => {+ it('adds takes, keeps the first as the selection, and persists an explicit select + reject across reloads', async () => {+ seedImage('take-1.png');+ seedImage('take-2.png');+ const first = await addTake(sceneA.sceneId, { kind: 'image', assetId: 'take-1.png', source: 'generated' });+ expect(first.status).toBe(201);+ expect(first.body.scene.referenceImageId).toBe('take-1.png');+ expect(first.body.take).toMatchObject({ source: 'generated', provider: 'portos', status: 'candidate' });++ const second = await addTake(sceneA.sceneId, { kind: 'image', assetId: 'take-2.png' });+ expect(second.body.scene.referenceImageId).toBe('take-1.png');++ const sel = await request(app).post(`${base()}/scenes/${sceneA.sceneId}/takes/${second.body.take.takeId}/select`);+ expect(sel.status).toBe(200);+ expect(sel.body.referenceImageId).toBe('take-2.png');++ const rej = await request(app).patch(`${base()}/scenes/${sceneA.sceneId}/takes/${first.body.take.takeId}`)+ .send({ status: 'rejected', note: 'wrong wardrobe' });+ expect(rej.status).toBe(200);++ const stored = (await reload()).scenes.find((s) => s.sceneId === sceneA.sceneId);+ expect(stored.referenceImageId).toBe('take-2.png');+ expect(stored.takes.map((t) => [t.assetId, t.status, t.note])).toEqual([+ ['take-1.png', 'rejected', 'wrong wardrobe'],+ ['take-2.png', 'candidate', null],+ ]);+ });++ it('rejecting the selected take clears the slot so the next take fills it', async () => {+ seedImage('a.png');+ seedImage('b.png');+ const a = await addTake(sceneA.sceneId, { kind: 'image', assetId: 'a.png' });+ await request(app).patch(`${base()}/scenes/${sceneA.sceneId}/takes/${a.body.take.takeId}`).send({ status: 'rejected' });+ expect((await reload()).scenes[0].referenceImageId).toBeNull();+ const b = await addTake(sceneA.sceneId, { kind: 'image', assetId: 'b.png' });+ expect(b.body.scene.referenceImageId).toBe('b.png');+ });++ it('refuses a take whose asset is not in the media library, or that names a path', async () => {+ const missing = await addTake(sceneA.sceneId, { kind: 'image', assetId: 'nope.png' });+ expect(missing.status).toBe(400);+ expect(missing.body.code).toBe('TAKE_ASSET_NOT_FOUND');+ const traversal = await addTake(sceneA.sceneId, { kind: 'image', assetId: '../settings.png' });+ expect(traversal.status).toBe(400);+ const clip = await addTake(sceneA.sceneId, { kind: 'video', assetId: 'clip-9' });+ expect(clip.status).toBe(400);+ seedVideoHistory([{ id: 'clip-9', filename: 'clip-9.mp4' }]);+ const ok = await addTake(sceneA.sceneId, { kind: 'video', assetId: 'clip-9' });+ expect(ok.status).toBe(201);+ expect(ok.body.scene.videoHistoryId).toBe('clip-9');+ expect((await reload()).scenes[0].takes.map((t) => t.kind)).toEqual(['video']);+ });++ it('materializes a pre-takes selection as a legacy take instead of losing it', async () => {+ // A pre-#8965 scene: a selected frame with no takes list at all.+ await projects.updateScene(project.id, sceneB.sceneId, { referenceImageId: 'legacy.png' });+ const raw = await reload();+ // updateScene records the slot as a take; strip it to model an old record.+ const { mergeProjectsFromSync } = projects;+ await mergeProjectsFromSync([{+ ...raw,+ updatedAt: new Date(Date.now() + 1000).toISOString(),+ scenes: raw.scenes.map((s) => (s.sceneId === sceneB.sceneId ? { ...s, takes: undefined } : s)),+ }]);+ seedImage('fresh.png');+ const added = await addTake(sceneB.sceneId, { kind: 'image', assetId: 'fresh.png' });+ expect(added.body.scene.referenceImageId).toBe('legacy.png');+ expect(added.body.scene.takes.map((t) => [t.assetId, t.source])).toEqual([+ ['legacy.png', 'legacy'],+ ['fresh.png', 'imported'],+ ]);+ });+});++describe('external-asset handoff', () => {+ it('exports per-scene prompts + tags without machine-local settings, and imports tagged files back onto their exact scenes', async () => {+ seedImage('ref-mood.png');+ const patched = await request(app).patch(base()).send({+ concept: { style: 'grainy 16mm' },+ visualSpec: {+ palette: ['#112233', '#AABBCC'],+ cameraRules: 'locked-off wide shots',+ references: [{ imageId: 'ref-mood.png', role: 'mood', label: 'Harbor mood', condition: true }],+ },+ imageMode: 'local',+ imageModelId: 'example-model',+ });+ expect(patched.status).toBe(200);++ const exported = await request(app).get(`${base()}/handoff`);+ expect(exported.status).toBe(200);+ const manifest = exported.body;+ expect(manifest).toMatchObject({ format: 'portos.music-video.handoff', version: 1 });+ expect(JSON.stringify(manifest)).not.toMatch(/imageModelId|example-model|videoSettings|\/Users\//);+ expect(manifest.visualSpec.references[0]).toMatchObject({ filename: 'ref-mood.png', condition: true });+ const [tagA, tagB] = manifest.scenes.map((s) => s.fileTag);+ expect(manifest.scenes[0].framePrompt).toBe('lighthouse still, grainy 16mm, color palette #112233 #aabbcc; camera: locked-off wide shots');+ expect(manifest.scenes[0].referenceFiles).toEqual(['ref-mood.png']);++ // Reorder between export and import: the tag's order prefix is cosmetic.+ const reordered = await request(app).post(`${base()}/scenes/reorder`).send({ sceneIds: [sceneB.sceneId, sceneA.sceneId] });+ expect(reordered.status).toBe(200);++ // The files come back through the gallery upload route (seeded here) under+ // new basenames; only the ORIGINAL names carry the tags.+ seedImage('upload-0001.png');+ seedImage('upload-0002.png');+ seedImage('upload-0003.png');+ const imported = await request(app).post(`${base()}/handoff/import`).send({+ provider: 'midjourney',+ items: [+ { kind: 'image', assetId: 'upload-0001.png', originalName: `user_${tagA}_harbor_v1.png` },+ { kind: 'image', assetId: 'upload-0002.png', originalName: `${tagB.toLowerCase()}-waves.png` },+ { kind: 'image', assetId: 'upload-0003.png', originalName: 'untagged.png' },+ { kind: 'image', assetId: 'upload-9999.png', originalName: `${tagA}-missing.png` },+ ],+ });+ expect(imported.status).toBe(200);+ expect(imported.body.imported.map((i) => [i.sceneId, i.assetId])).toEqual([+ [sceneA.sceneId, 'upload-0001.png'],+ [sceneB.sceneId, 'upload-0002.png'],+ ]);+ expect(imported.body.skipped.map((s) => [s.assetId, s.reason])).toEqual([+ ['upload-0003.png', 'no-matching-scene'],+ ['upload-9999.png', 'asset-not-found'],+ ]);++ const stored = await reload();+ const a = stored.scenes.find((s) => s.sceneId === sceneA.sceneId);+ expect(a.takes[0]).toMatchObject({+ assetId: 'upload-0001.png', source: 'imported', provider: 'midjourney', originalName: `user_${tagA}_harbor_v1.png`,+ });+ expect(a.referenceImageId).toBe('upload-0001.png');+ });+});diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex c4ccd53ff8..7c5bc41ced 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -444,8 +444,8 @@ const generateBodySchema = z.object({z.array(z.number().min(0).max(2)).max(8).optional(),),// Music Video director-board i2v render (#1760 Phase 1). When present, the- // mediaJobQueue completion hook (`musicVideoSceneVideoHook`) files the finished- // clip's history id onto the project scene's `videoHistoryId` — durably, even+ // mediaJobQueue completion hook (`musicVideoSceneVideoHook`) appends the+ // finished clip's history id to the project scene's takes (#8965) — durably, even// if the director board unmounted mid-render (the i2v counterpart to the// Phase 1b reference-frame `musicVideo` tag on the image route). The shot// prompt rides in `prompt` and the reference frame in `sourceImageFile`, sodiff --git a/server/services/musicVideo/events.js b/server/services/musicVideo/events.jsindex 67fd78e820..590c96e2f2 100644--- a/server/services/musicVideo/events.js+++ b/server/services/musicVideo/events.js@@ -3,16 +3,17 @@ import { EventEmitter } from 'events';// Event bus for Music Video async side effects that need to reach the client// after the originating HTTP request has returned. It carries two events://-// 'scene-image' → { projectId, sceneId, referenceImageId }-// 'scene-video' → { projectId, sceneId, videoHistoryId }+// 'scene-image' → { projectId, sceneId, referenceImageId, takes, takeId }+// 'scene-video' → { projectId, sceneId, videoHistoryId, takes, takeId }//// emitted by `musicVideoSceneImageHook` / `musicVideoSceneVideoHook` once an// async (local/Codex) reference-frame render or i2v scene clip has been durably-// filed onto the project scene's `referenceImageId` / `videoHistoryId` (#1760-// Phase 1b / Phase 1). socket.js bridges them to `music-video:scene-image` /+// appended to the project scene's takes (#8965). `referenceImageId` /+// `videoHistoryId` carry the scene's CURRENT selection (a new take only fills+// an empty slot), `takes` the full candidate list. socket.js bridges them to `music-video:scene-image` /// `music-video:scene-video` on Socket.IO so the director scene board updates// reactively without a refetch — the durable, hook-driven counterpart to the// synchronous external-SD-API lane (which returns the image filename inline and-// lets the client PATCH `referenceImageId` directly; video renders always ride-// the queue, so the clip attach is hook-only).+// lets the client add it as a take through the takes route; video renders+// always ride the queue, so the clip attach is hook-only).export const musicVideoEvents = new EventEmitter();diff --git a/server/services/musicVideo/handoff.js b/server/services/musicVideo/handoff.jsnew file mode 100644index 0000000000..20bbd7334f--- /dev/null+++ b/server/services/musicVideo/handoff.js@@ -0,0 +1,123 @@+/**+ * Music Video external-asset handoff (#8965) — provider-neutral export/import+ * for tools PortOS does not drive, such as Midjourney.+ *+ * PortOS never automates the external tool (Midjourney's guidelines prohibit+ * unauthorized automation and it has no general public API): the director+ * exports a manifest of per-scene prompts and reference files, generates by+ * hand, then imports the downloaded files through the ordinary gallery upload+ * routes. Scene association survives the round trip through a FILE TAG+ * (`S03-1a2b3c4d`) the manifest assigns each scene: a downloaded file whose+ * name carries the tag is matched back to its exact scene by the scene id the+ * tag encodes — the `S03` order prefix is cosmetic, so reordering the board+ * between export and import can't misfile an asset.+ *+ * The manifest is built from an explicit field allowlist, so machine-local+ * render pins, renderer settings and server paths never leave the install.+ */++export const HANDOFF_FORMAT = 'portos.music-video.handoff';+export const HANDOFF_VERSION = 1;++const sceneShortId = (sceneId) => String(sceneId || '')+ .replace(/^mvs-/, '')+ .replace(/[^a-z0-9]/gi, '')+ .slice(0, 8)+ .toLowerCase();++/** The tag a scene's externally generated files carry in their filename. */+function sceneFileTag(scene, index) {+ return `S${String(index + 1).padStart(2, '0')}-${sceneShortId(scene.sceneId)}`;+}++const FILE_TAG_RE = /(?:^|[^a-z0-9])s\d{1,3}[-_]([a-z0-9]{8})(?![a-z0-9])/gi;++/**+ * Resolve an imported file's original name to the scene whose tag it carries.+ * Returns null when the name carries no tag, a tag no scene owns, or tags for+ * two different scenes — an ambiguous file is never guessed onto a scene.+ */+export function matchSceneByFileTag(scenes, originalName) {+ if (typeof originalName !== 'string' || !originalName) return null;+ const byShort = new Map();+ for (const scene of scenes || []) {+ const short = sceneShortId(scene.sceneId);+ // Two scenes sharing a short id make that tag ambiguous for both.+ byShort.set(short, byShort.has(short) ? null : scene.sceneId);+ }+ const matched = new Set();+ for (const [, short] of originalName.matchAll(FILE_TAG_RE)) {+ const sceneId = byShort.get(short.toLowerCase());+ if (sceneId) matched.add(sceneId);+ }+ return matched.size === 1 ? [...matched][0] : null;+}++/**+ * The project-wide visual direction appended to generated prompts — palette,+ * camera rules and typography from the visual spec. Kept in step with+ * `visualDirection` in client/src/hooks/useMusicVideoSceneMedia.js, which+ * composes the same suffix for PortOS's own renders.+ */+export function visualDirection(spec) {+ if (!spec) return '';+ return [+ spec.palette?.length ? `color palette ${spec.palette.join(' ')}` : '',+ spec.cameraRules?.trim() ? `camera: ${spec.cameraRules.trim()}` : '',+ spec.typography?.trim() ? `typography: ${spec.typography.trim()}` : '',+ ].filter(Boolean).join('; ');+}++function composePrompt(primary, fallback, project) {+ return [+ primary?.trim() || fallback?.trim() || '',+ project.concept?.style?.trim() || '',+ visualDirection(project.visualSpec),+ ].filter(Boolean).join(', ');+}++/** Build the export manifest for a project. */+export function buildHandoffManifest(project, { now = new Date().toISOString() } = {}) {+ const spec = project.visualSpec || null;+ const references = (spec?.references || []).map((ref) => ({+ id: ref.id,+ role: ref.role,+ label: ref.label,+ note: ref.note,+ condition: ref.condition === true,+ filename: ref.imageId,+ url: `/data/images/${encodeURIComponent(ref.imageId)}`,+ }));+ const conditioning = references.filter((ref) => ref.condition).map((ref) => ref.filename);+ return {+ format: HANDOFF_FORMAT,+ version: HANDOFF_VERSION,+ exportedAt: now,+ project: { id: project.id, name: project.name, version: project.version || 1 },+ instructions: 'Generate each scene in your external tool, keep the scene file tag (for example S03-1a2b3c4d) in every downloaded filename, then import the files on the Music Video board. PortOS never contacts the external service; attach the reference files yourself.',+ concept: { prompt: project.concept?.prompt || '', style: project.concept?.style || '' },+ visualSpec: {+ palette: spec?.palette || [],+ typography: spec?.typography || '',+ cameraRules: spec?.cameraRules || '',+ references,+ },+ scenes: (project.scenes || []).map((scene, index) => ({+ sceneId: scene.sceneId,+ order: index,+ fileTag: sceneFileTag(scene, index),+ label: scene.sectionLabel || scene.label || `Scene ${index + 1}`,+ startSec: scene.startSec ?? null,+ endSec: scene.endSec ?? null,+ lyricText: scene.lyricText || '',+ visualIntent: scene.visualIntent || '',+ framePrompt: composePrompt(scene.framePrompt, scene.prompt, project),+ shotPrompt: composePrompt(scene.prompt, scene.framePrompt, project),+ referenceFiles: conditioning,+ selected: {+ referenceImageId: scene.referenceImageId || null,+ videoHistoryId: scene.videoHistoryId || null,+ },+ })),+ };+}diff --git a/server/services/musicVideo/projects.js b/server/services/musicVideo/projects.jsindex ee60e7e382..44b19ec7e9 100644--- a/server/services/musicVideo/projects.js+++ b/server/services/musicVideo/projects.js@@ -157,6 +157,36 @@ export async function reorderProjectScenes(id, orderedIds) {return next;}+// ---- scene takes (#8965) ----+// Append candidate takes to one scene: `{ scene, appended }`. A take fills its+// slot only while the slot is empty — never replaces a selection (takes.js).+export async function appendSceneTakes(id, sceneId, inputs) {+ const result = await (await selectBackend()).appendSceneTakes(id, sceneId, inputs);+ emitRecordUpdated('musicVideoProject', id);+ return result;+}++/** Append takes across scenes in one write (handoff import): `{ project, appended }`. */+export async function appendTakesAcrossScenes(id, items) {+ const result = await (await selectBackend()).appendTakesAcrossScenes(id, items);+ emitRecordUpdated('musicVideoProject', id);+ return result;+}++/** Explicitly select a take for its scene slot. Returns the updated scene. */+export async function selectSceneTake(id, sceneId, takeId) {+ const scene = await (await selectBackend()).selectSceneTake(id, sceneId, takeId);+ emitRecordUpdated('musicVideoProject', id);+ return scene;+}++/** Reject/restore a take and/or set its note. Returns the updated scene. */+export async function reviewSceneTake(id, sceneId, takeId, review) {+ const scene = await (await selectBackend()).reviewSceneTake(id, sceneId, takeId, review);+ emitRecordUpdated('musicVideoProject', id);+ return scene;+}+/** Merge an incoming batch of project records from a peer (LWW, tombstone-aware). */export async function mergeProjectsFromSync(remoteProjects, options = {}) {return (await selectBackend()).mergeProjectsFromSync(remoteProjects, options);diff --git a/server/services/musicVideo/projectsDB.js b/server/services/musicVideo/projectsDB.jsindex 65387764dc..83a5f4e105 100644--- a/server/services/musicVideo/projectsDB.js+++ b/server/services/musicVideo/projectsDB.js@@ -5,6 +5,7 @@ import { withTransaction } from '../../lib/db.js';import { ServerError } from '../../lib/errorHandler.js';import { createProjectDbStore } from '../projectDbStore.js';import * as logic from './projectsLogic.js';+import * as takes from './takes.js';const store = createProjectDbStore({table: 'music_video_projects',@@ -85,3 +86,32 @@ export async function reorderProjectScenes(id, orderedIds) {const { project } = await withLockedProject(id, (current) => ({ project: logic.reorderScenes(current, orderedIds) }));return project;}++// ---- scene takes (#8965) — each operation runs under the project row lock,+// so a job completion and a director's select/reject can't interleave. -------+async function mutateLocked(id, transform) {+ const { result } = await withLockedProject(id, (current) => {+ const outcome = transform(current);+ return { project: outcome.project, result: outcome };+ });+ return result;+}++export async function appendSceneTakes(id, sceneId, inputs) {+ const { scene, appended } = await mutateLocked(id, (p) => takes.appendSceneTakes(p, sceneId, inputs));+ return { scene, appended };+}++export async function appendTakesAcrossScenes(id, items) {+ return mutateLocked(id, (p) => takes.appendTakesAcrossScenes(p, items));+}++export async function selectSceneTake(id, sceneId, takeId) {+ const { scene } = await mutateLocked(id, (p) => takes.selectSceneTake(p, sceneId, takeId));+ return scene;+}++export async function reviewSceneTake(id, sceneId, takeId, review) {+ const { scene } = await mutateLocked(id, (p) => takes.reviewSceneTake(p, sceneId, takeId, review));+ return scene;+}diff --git a/server/services/musicVideo/projectsFile.js b/server/services/musicVideo/projectsFile.jsindex aaa923cdf6..c57d7b6031 100644--- a/server/services/musicVideo/projectsFile.js+++ b/server/services/musicVideo/projectsFile.js@@ -6,6 +6,7 @@ import { PATHS } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';import { createProjectFileStore } from '../projectFileStore.js';import * as logic from './projectsLogic.js';+import * as takes from './takes.js';const store = createProjectFileStore({file: join(PATHS.data, 'music-video-projects.json'),@@ -87,3 +88,31 @@ export async function reorderProjectScenes(id, orderedIds) {await saveAll(all);return all[idx];}++// ---- scene takes (#8965) — one load/modify/save per take operation ----------+async function mutateProject(id, transform) {+ const { all, idx } = await loadAllAndIndex(id);+ const outcome = transform(all[idx]);+ all[idx] = outcome.project;+ await saveAll(all);+ return outcome;+}++export async function appendSceneTakes(id, sceneId, inputs) {+ const { scene, appended } = await mutateProject(id, (p) => takes.appendSceneTakes(p, sceneId, inputs));+ return { scene, appended };+}++export async function appendTakesAcrossScenes(id, items) {+ return mutateProject(id, (p) => takes.appendTakesAcrossScenes(p, items));+}++export async function selectSceneTake(id, sceneId, takeId) {+ const { scene } = await mutateProject(id, (p) => takes.selectSceneTake(p, sceneId, takeId));+ return scene;+}++export async function reviewSceneTake(id, sceneId, takeId, review) {+ const { scene } = await mutateProject(id, (p) => takes.reviewSceneTake(p, sceneId, takeId, review));+ return scene;+}diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.jsindex 1de6d54a9c..8cdcdd2783 100644--- a/server/services/musicVideo/projectsLogic.js+++ b/server/services/musicVideo/projectsLogic.js@@ -29,6 +29,7 @@ import { persistedRenderPinFields } from '../../lib/renderTargets.js';import { sanitizeProjectForSync } from '../../lib/projectStoreKit.js';import { isStr } from '../../lib/textUtils.js';import { normalizeLyricCues, normalizePhrases, invalidateTimedText } from './timedText.js';+import { ensureSceneTakes, TAKE_SLOT } from './takes.js';export { sanitizeProjectForSync } from '../../lib/projectStoreKit.js';@@ -59,6 +60,31 @@ function parseSceneOrThrow(schema, input) {return parsed.data;}+/**+ * Normalize a validated visual specification (#8965): every reference persists+ * a stable id and explicit defaults so edits stay addressable and a peer reads+ * the same shape. `base` is the stored spec a partial patch merges onto — each+ * sub-field present in the patch replaces its stored value; absent ones keep it.+ */+function normalizeVisualSpec(patch, base = null) {+ const merged = { ...(base || {}), ...(patch || {}) };+ const references = (Array.isArray(merged.references) ? merged.references : []).map((ref) => ({+ id: typeof ref.id === 'string' && ref.id ? ref.id : `mvr-${randomUUID()}`,+ imageId: ref.imageId,+ role: ref.role || 'mood',+ label: typeof ref.label === 'string' ? ref.label : '',+ note: typeof ref.note === 'string' ? ref.note : '',+ condition: ref.condition === true,+ }));+ return {+ references,+ palette: Array.isArray(merged.palette) ? merged.palette.map((c) => c.toLowerCase()) : [],+ typography: typeof merged.typography === 'string' ? merged.typography : '',+ cameraRules: typeof merged.cameraRules === 'string' ? merged.cameraRules : '',+ moodBoardId: typeof merged.moodBoardId === 'string' && merged.moodBoardId ? merged.moodBoardId : null,+ };+}+/** Build a fresh project record from validated create input. */export function buildProjectRecord(input, { id, now }) {const {@@ -79,6 +105,9 @@ export function buildProjectRecord(input, { id, now }) {trackId,uploadedAudioFilename,concept,+ // #8965 — the reusable visual specification (moodboard/reference assets,+ // palette, typography, camera rules). Null until the director sets one.+ visualSpec: input.visualSpec ? normalizeVisualSpec(input.visualSpec) : null,videoSettings: {backend: videoSettings.backend ?? 'local',modelId: videoSettings.modelId ?? null,@@ -127,6 +156,9 @@ export function cloneProjectRecord(source, {order,referenceImageId: includeGeneratedMedia ? (scene.referenceImageId ?? null) : null,videoHistoryId: includeGeneratedMedia ? (scene.videoHistoryId ?? null) : null,+ // Takes are immutable pointers to shared media, so a media-keeping clone+ // carries the whole candidate history; a clean clone starts empty.+ takes: includeGeneratedMedia ? ensureSceneTakes(scene, now) : [],}));const mediaReady = includeGeneratedMedia&& scenes.length > 0@@ -160,9 +192,11 @@ export function applyProjectPatch(project, patch) {// 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.// Edited cue/phrase lists replace the stored list whole, normalized so every- // entry persists a stable id and a forward time range (timedText.js).+ // entry persists a stable id and a forward time range (timedText.js). A+ // `visualSpec` patch merges per sub-field the same way (#8965).const timedPatch = {...patch,+ ...(patch.visualSpec ? { visualSpec: normalizeVisualSpec(patch.visualSpec, project.visualSpec) } : {}),...(Array.isArray(patch.lyricCues) ? { lyricCues: normalizeLyricCues(patch.lyricCues) } : {}),...(Array.isArray(patch.phrases) ? { phrases: normalizePhrases(patch.phrases) } : {}),};@@ -268,6 +302,9 @@ function buildScene(input, { order }) {visualIntent: input.visualIntent ?? null,referenceImageId: null,videoHistoryId: null,+ // #8965 — immutable candidate takes; the two slot fields above are the+ // director's selection among them (see takes.js).+ takes: [],};}@@ -311,7 +348,11 @@ export function applySceneUpdate(project, sceneId, patch) {const scenes = project.scenes || [];const idx = scenes.findIndex((s) => s.sceneId === sceneId);if (idx < 0) throw new ServerError('Scene not found', { status: 404, code: 'NOT_FOUND' });- const updated = { ...scenes[idx], ...data };+ const merged = { ...scenes[idx], ...data };+ // Setting a slot directly (an older client, or a hand edit) still records the+ // asset as a take so the candidate list stays a superset of the selection.+ const touchesSlot = Object.values(TAKE_SLOT).some((field) => typeof data[field] === 'string');+ const updated = touchesSlot ? { ...merged, takes: ensureSceneTakes(merged, undefined, 'manual') } : merged;// The partial-patch schema can't enforce endSec >= startSec (the paired value// may be unchanged on the record), so validate the merged range here.if (updated.startSec != null && updated.endSec != null && updated.endSec < updated.startSec) {diff --git a/server/services/musicVideo/projectsLogic.test.js b/server/services/musicVideo/projectsLogic.test.jsindex 06516a0936..d1f62a1450 100644--- a/server/services/musicVideo/projectsLogic.test.js+++ b/server/services/musicVideo/projectsLogic.test.js@@ -110,6 +110,12 @@ describe('cloneProjectRecord', () => {});expect(clone.scenes[0].sceneId).not.toBe('scene-old');expect(source.scenes[0].sceneId).toBe('scene-old');+ // A pre-#8965 scene's selections become takes on the clone, so the new+ // version's candidate list is never missing what it already shows.+ expect(clone.scenes[0].takes.map((t) => [t.kind, t.assetId, t.source])).toEqual([+ ['image', 'frame.png', 'legacy'],+ ['video', 'clip-1', 'legacy'],+ ]);});it('can fork the board without carrying generated media', () => {@@ -131,7 +137,7 @@ describe('cloneProjectRecord', () => {rootProjectId: 'mv-root',name: 'Test MV v3',});- expect(clone.scenes[0]).toMatchObject({ referenceImageId: null, videoHistoryId: null });+ expect(clone.scenes[0]).toMatchObject({ referenceImageId: null, videoHistoryId: null, takes: [] });});});@@ -260,6 +266,20 @@ describe('applyProjectPatch', () => {expect(next.concept).toBeNull();});+ it('merges a visualSpec patch per sub-field and gives every reference a stable id (#8965)', () => {+ const first = applyProjectPatch(baseProject(), {+ visualSpec: { palette: ['#AABBCC'], references: [{ imageId: 'mood.png', condition: true }] },+ });+ const [ref] = first.visualSpec.references;+ expect(ref).toMatchObject({ imageId: 'mood.png', role: 'mood', condition: true, label: '' });+ expect(ref.id).toMatch(/^mvr-/);+ expect(first.visualSpec.palette).toEqual(['#aabbcc']);+ // A later edit of one sub-field keeps the others (and the minted id).+ const second = applyProjectPatch(first, { visualSpec: { cameraRules: 'handheld only' } });+ expect(second.visualSpec).toMatchObject({ palette: ['#aabbcc'], cameraRules: 'handheld only' });+ expect(second.visualSpec.references[0].id).toBe(ref.id);+ });+it('persists explicit renderer settings and merges later partial changes', () => {const project = buildProjectRecord({name: 'A',diff --git a/server/services/musicVideo/takes.js b/server/services/musicVideo/takes.jsnew file mode 100644index 0000000000..2b681a9d04--- /dev/null+++ b/server/services/musicVideo/takes.js@@ -0,0 +1,198 @@+/**+ * Music Video scene takes (#8965) — pure record transforms.+ *+ * A scene slot (`referenceImageId` for the still, `videoHistoryId` for the+ * clip) used to hold only the newest render: every completion overwrote it, so+ * an earlier render the director preferred was lost, and two out-of-order jobs+ * could replace a frame the director had already approved. Now every asset+ * offered for a slot becomes an immutable take in `scene.takes`, and the slot+ * field is the director's explicit SELECTION of one of them:+ *+ * - a completed/imported asset is APPENDED as a candidate and only fills the+ * slot while the slot is empty (initial generation) — it never replaces a+ * selection;+ * - selecting a take is an explicit action (`selectSceneTake`);+ * - rejecting the selected take clears the slot, so the next completion (or+ * "Generate missing") fills it — selective regeneration.+ *+ * The slot fields keep their names so render.js, the peer-sync asset manifest+ * and older records read the selection unchanged. Pre-#8965 scenes carry no+ * `takes`; `ensureSceneTakes` materializes their selected asset as a `legacy`+ * take the first time a take operation touches the scene (no record rewrite).+ */++import { randomUUID } from 'crypto';+import { ServerError } from '../../lib/errorHandler.js';+import { isNonBlankStr, trimTo } from '../../lib/textUtils.js';++export const TAKE_SLOT = Object.freeze({ image: 'referenceImageId', video: 'videoHistoryId' });++// Per-scene cap. Takes are small pointer records, but an unattended "regenerate+// until it looks right" loop must not grow one project row without bound. When+// full, the oldest rejected take is dropped first, then the oldest unselected+// candidate; a selected take is never pruned.+export const MAX_SCENE_TAKES = 60;++// Optional provenance text: bounded, and null (not '') when absent.+const clip = (v, max) => (isNonBlankStr(v) ? trimTo(v, max) : null);++// A basename only — an imported file's name is provenance, never a path.+const takeOriginalName = (name) => (isNonBlankStr(name) ? clip(name.split(/[\\/]/).pop(), 200) : null);++function buildTake({ kind, assetId, source, provider = null, jobId = null, prompt = null, sourceImageId = null, originalName = null, now }) {+ return {+ takeId: `mvt-${randomUUID()}`,+ kind,+ assetId,+ source,+ provider: clip(provider, 40),+ jobId: clip(jobId, 128),+ prompt: clip(prompt, 2000),+ sourceImageId: clip(sourceImageId, 256),+ originalName: takeOriginalName(originalName),+ status: 'candidate',+ note: null,+ createdAt: now,+ };+}++/**+ * The scene's takes, with any selected slot asset that has no take yet+ * materialized as a take — `legacy` for a pre-#8965 record, `manual` for a slot+ * set through the plain scene PATCH. Returns the same array when nothing needed+ * adding.+ */+export function ensureSceneTakes(scene, now = new Date().toISOString(), source = 'legacy') {+ const takes = Array.isArray(scene?.takes) ? scene.takes : [];+ const added = [];+ for (const [kind, field] of Object.entries(TAKE_SLOT)) {+ const assetId = scene?.[field];+ if (!isNonBlankStr(assetId)) continue;+ if (takes.some((t) => t?.kind === kind && t.assetId === assetId)) continue;+ added.push(buildTake({ kind, assetId, source, now }));+ }+ return added.length ? [...takes, ...added] : takes;+}++// Drop the oldest prunable take until the list fits the cap.+function pruneTakes(takes, scene) {+ if (takes.length <= MAX_SCENE_TAKES) return takes;+ const selected = new Set(Object.entries(TAKE_SLOT)+ .map(([kind, field]) => (isNonBlankStr(scene[field]) ? `${kind}:${scene[field]}` : null))+ .filter(Boolean));+ const next = takes.slice();+ for (const wanted of ['rejected', 'candidate']) {+ for (let i = 0; i < next.length && next.length > MAX_SCENE_TAKES;) {+ const t = next[i];+ if (t.status === wanted && !selected.has(`${t.kind}:${t.assetId}`)) next.splice(i, 1);+ else i += 1;+ }+ }+ return next;+}++function findSceneIndex(project, sceneId) {+ const idx = (project.scenes || []).findIndex((s) => s.sceneId === sceneId);+ if (idx < 0) throw new ServerError('Scene not found', { status: 404, code: 'NOT_FOUND' });+ return idx;+}++function replaceScene(project, idx, scene) {+ const scenes = project.scenes.slice();+ scenes[idx] = scene;+ return { ...project, scenes, updatedAt: new Date().toISOString() };+}++/**+ * Append candidate takes to one scene. Idempotent per asset: an asset already+ * present as a take of that kind is not duplicated (a replayed job completion+ * or a re-import is a no-op for the list). A slot is filled only while it is+ * empty, by the first appended take of that kind; an existing selection is+ * never replaced. Returns `{ scene, appended }` — `appended` lists the take+ * for every input, whether newly created or already present.+ */+function appendToScene(scene, inputs, now) {+ let takes = ensureSceneTakes(scene, now);+ const next = { ...scene };+ const appended = [];+ for (const input of inputs) {+ const existing = takes.find((t) => t.kind === input.kind && t.assetId === input.assetId);+ const take = existing || buildTake({ ...input, now });+ if (!existing) takes = [...takes, take];+ appended.push(take);+ const field = TAKE_SLOT[input.kind];+ if (!isNonBlankStr(next[field]) && take.status !== 'rejected') next[field] = take.assetId;+ }+ next.takes = pruneTakes(takes, next);+ return { scene: next, appended };+}++/** Append takes to one scene. Throws 404 for a deleted/unknown scene. */+export function appendSceneTakes(project, sceneId, inputs) {+ const idx = findSceneIndex(project, sceneId);+ const { scene, appended } = appendToScene(project.scenes[idx], inputs, new Date().toISOString());+ return { project: replaceScene(project, idx, scene), scene, appended };+}++/**+ * Append takes across scenes in one record write (a handoff import). `items`+ * are `{ sceneId, ...takeInput }`; every sceneId must exist or the whole batch+ * is refused, so a partially applied import can't strand half a handoff.+ */+export function appendTakesAcrossScenes(project, items) {+ const bySceneId = new Map();+ items.forEach((item, index) => {+ findSceneIndex(project, item.sceneId);+ const list = bySceneId.get(item.sceneId) || [];+ list.push({ item, index });+ bySceneId.set(item.sceneId, list);+ });+ const now = new Date().toISOString();+ // Reported in INPUT order, so a caller can pair each result with its item.+ const appended = new Array(items.length);+ const scenes = project.scenes.map((scene) => {+ const entries = bySceneId.get(scene.sceneId);+ if (!entries) return scene;+ const result = appendToScene(scene, entries.map((e) => e.item), now);+ entries.forEach((e, i) => { appended[e.index] = { sceneId: scene.sceneId, take: result.appended[i] }; });+ return result.scene;+ });+ return { project: { ...project, scenes, updatedAt: now }, appended };+}++function locateTake(project, sceneId, takeId) {+ const idx = findSceneIndex(project, sceneId);+ const scene = project.scenes[idx];+ const takes = ensureSceneTakes(scene);+ const take = takes.find((t) => t.takeId === takeId);+ if (!take) throw new ServerError('Take not found', { status: 404, code: 'NOT_FOUND' });+ return { idx, scene, takes, take };+}++/** Explicitly select a take for its slot. Selecting a rejected take restores it. */+export function selectSceneTake(project, sceneId, takeId) {+ const { idx, scene, takes, take } = locateTake(project, sceneId, takeId);+ const nextTakes = takes.map((t) => (t.takeId === takeId && t.status === 'rejected' ? { ...t, status: 'candidate' } : t));+ const next = { ...scene, takes: nextTakes, [TAKE_SLOT[take.kind]]: take.assetId };+ return { project: replaceScene(project, idx, next), scene: next };+}++/**+ * Reject/restore a take and/or set its review note. Rejecting the SELECTED take+ * clears the slot so the scene reads as "needs a take" again.+ */+export function reviewSceneTake(project, sceneId, takeId, { status, note }) {+ const { idx, scene, takes, take } = locateTake(project, sceneId, takeId);+ const updated = {+ ...take,+ ...(status !== undefined ? { status } : {}),+ ...(note !== undefined ? { note: note && note.trim() ? note.trim().slice(0, 1000) : null } : {}),+ };+ const field = TAKE_SLOT[take.kind];+ const next = {+ ...scene,+ takes: takes.map((t) => (t.takeId === takeId ? updated : t)),+ ...(updated.status === 'rejected' && scene[field] === take.assetId ? { [field]: null } : {}),+ };+ return { project: replaceScene(project, idx, next), scene: next };+}diff --git a/server/services/musicVideoSceneHooks.test.js b/server/services/musicVideoSceneHooks.test.jsnew file mode 100644index 0000000000..eda2d25060--- /dev/null+++ b/server/services/musicVideoSceneHooks.test.js@@ -0,0 +1,151 @@+/**+ * Music Video scene completion hooks (#8965) against the real file-backed+ * project store: a completed image/video job becomes an immutable scene take,+ * fills the slot only while it is unselected, never replaces a selection, and a+ * late completion can't resurrect a deleted scene or project. The tag-decode /+ * serialize scaffolding itself is covered by mediaJobImageHook.test.js.+ */++import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';+import { mkdtempSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'mv-scene-hooks-test-'));++vi.mock('../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT } };+});+vi.mock('./settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));++const { mediaJobEvents } = await import('./mediaJobQueue/index.js');+const { musicVideoEvents } = await import('./musicVideo/events.js');+const projects = await import('./musicVideo/projects.js');+const imageHook = await import('./musicVideoSceneImageHook.js');+const videoHook = await import('./musicVideoSceneVideoHook.js');++async function waitFor(predicate, { timeoutMs = 2000, intervalMs = 5 } = {}) {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ if (await predicate()) return;+ await new Promise((r) => setTimeout(r, intervalMs));+ }+ throw new Error('waitFor: predicate never became true');+}++const imageJob = (projectId, sceneId, filename, queuedAt) => ({+ kind: 'image', id: filename.replace(/\.png$/, ''), queuedAt,+ params: { musicVideo: { projectId, sceneId }, prompt: `frame ${filename}` },+ result: { filename },+});+const videoJob = (projectId, sceneId, id) => ({+ kind: 'video', id,+ params: { musicVideo: { projectId, sceneId }, prompt: 'slow dolly', sourceImagePath: '/abs/server/path/images/frame-a.png' },+ result: { generationId: id },+});++async function sceneOf(projectId, sceneId) {+ const project = await projects.getProject(projectId);+ return project?.scenes.find((s) => s.sceneId === sceneId);+}++describe('music-video scene completion hooks → takes', () => {+ let emitted;+ const capture = (event) => (data) => emitted.push({ event, ...data });+ const onImage = capture('scene-image');+ const onVideo = capture('scene-video');+ let project;+ let scene;++ beforeEach(async () => {+ rmSync(join(TEST_DATA_ROOT, 'music-video-projects.json'), { force: true });+ imageHook.__testing.reset();+ videoHook.__testing.reset();+ imageHook.initMusicVideoSceneImageHook();+ videoHook.initMusicVideoSceneVideoHook();+ emitted = [];+ musicVideoEvents.on('scene-image', onImage);+ musicVideoEvents.on('scene-video', onVideo);+ project = await projects.createProject({ name: 'Example Video' });+ scene = await projects.addProjectScene(project.id, { prompt: 'a lighthouse at dusk' });+ });++ afterEach(() => {+ imageHook.__testing.reset();+ videoHook.__testing.reset();+ musicVideoEvents.off('scene-image', onImage);+ musicVideoEvents.off('scene-video', onVideo);+ });++ afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));++ it('keeps both of two out-of-order renders; the first to land fills the empty slot', async () => {+ // The newer-queued render completes first, then the older one lands late —+ // before #8965 the older render was dropped (or, reversed, overwrote the+ // newer frame). Now both are candidates and the selection stays put.+ mediaJobEvents.emit('completed', imageJob(project.id, scene.sceneId, 'newer.png', '2026-09-01T00:00:02.000Z'));+ await waitFor(() => emitted.length === 1);+ mediaJobEvents.emit('completed', imageJob(project.id, scene.sceneId, 'older.png', '2026-09-01T00:00:01.000Z'));+ await waitFor(() => emitted.length === 2);++ const stored = await sceneOf(project.id, scene.sceneId);+ expect(stored.takes.map((t) => t.assetId)).toEqual(['newer.png', 'older.png']);+ expect(stored.takes.every((t) => t.source === 'generated' && t.provider === 'portos' && t.status === 'candidate')).toBe(true);+ expect(stored.takes[1]).toMatchObject({ jobId: 'older', prompt: 'frame older.png' });+ expect(stored.referenceImageId).toBe('newer.png');+ // The socket payload carries the current selection + the full list.+ expect(emitted[1]).toMatchObject({ event: 'scene-image', sceneId: scene.sceneId, referenceImageId: 'newer.png' });+ expect(emitted[1].takes).toHaveLength(2);+ });++ it('never replaces an explicitly selected take, and a replayed completion adds no duplicate', async () => {+ mediaJobEvents.emit('completed', imageJob(project.id, scene.sceneId, 'first.png'));+ mediaJobEvents.emit('completed', imageJob(project.id, scene.sceneId, 'second.png'));+ await waitFor(() => emitted.length === 2);+ const second = (await sceneOf(project.id, scene.sceneId)).takes.find((t) => t.assetId === 'second.png');+ await projects.selectSceneTake(project.id, scene.sceneId, second.takeId);++ mediaJobEvents.emit('completed', imageJob(project.id, scene.sceneId, 'third.png'));+ mediaJobEvents.emit('completed', imageJob(project.id, scene.sceneId, 'first.png')); // replay+ await waitFor(() => emitted.length === 4);++ const stored = await sceneOf(project.id, scene.sceneId);+ expect(stored.referenceImageId).toBe('second.png');+ expect(stored.takes.map((t) => t.assetId)).toEqual(['first.png', 'second.png', 'third.png']);+ });++ it('records a clip take with its source frame as a basename, filling only an empty video slot', async () => {+ mediaJobEvents.emit('completed', videoJob(project.id, scene.sceneId, 'clip-1'));+ mediaJobEvents.emit('completed', videoJob(project.id, scene.sceneId, 'clip-2'));+ await waitFor(() => emitted.length === 2);+ const stored = await sceneOf(project.id, scene.sceneId);+ expect(stored.videoHistoryId).toBe('clip-1');+ expect(stored.takes.map((t) => [t.kind, t.assetId, t.sourceImageId])).toEqual([+ ['video', 'clip-1', 'frame-a.png'],+ ['video', 'clip-2', 'frame-a.png'],+ ]);+ expect(emitted[1]).toMatchObject({ event: 'scene-video', videoHistoryId: 'clip-1' });+ });++ it('a late completion cannot resurrect a deleted scene or a deleted project', async () => {+ const other = await projects.addProjectScene(project.id, { prompt: 'second scene' });+ await projects.deleteScene(project.id, scene.sceneId);+ mediaJobEvents.emit('completed', imageJob(project.id, scene.sceneId, 'late.png'));+ // A render for the surviving scene proves the hook ran past the failed one.+ mediaJobEvents.emit('completed', imageJob(project.id, other.sceneId, 'kept.png'));+ await waitFor(() => emitted.length === 1);+ const afterSceneDelete = await projects.getProject(project.id);+ expect(afterSceneDelete.scenes.map((s) => s.sceneId)).toEqual([other.sceneId]);+ expect(emitted[0].sceneId).toBe(other.sceneId);++ await projects.deleteProject(project.id);+ mediaJobEvents.emit('completed', videoJob(project.id, other.sceneId, 'late-clip'));+ await new Promise((r) => setTimeout(r, 40));+ expect(await projects.getProject(project.id)).toBeNull();+ const tombstone = await projects.getProject(project.id, { includeDeleted: true });+ expect(tombstone.deleted).toBe(true);+ expect(tombstone.scenes[0].takes.map((t) => t.assetId)).toEqual(['kept.png']);+ expect(emitted).toHaveLength(1);+ });+});diff --git a/server/services/musicVideoSceneImageHook.js b/server/services/musicVideoSceneImageHook.jsindex b067eedac5..32c9d05194 100644--- a/server/services/musicVideoSceneImageHook.js+++ b/server/services/musicVideoSceneImageHook.js@@ -2,8 +2,10 @@* Music Video scene reference-frame attach hook (issue #1760, Phase 1b).** Subscribes to mediaJobEvents and, for each completed image job that carries- * `params.musicVideo`, files the rendered filename onto that project scene's- * `referenceImageId` — server-side, independent of any mounted client. This is+ * `params.musicVideo`, appends the rendered filename to that project scene's+ * immutable takes (#8965) — server-side, independent of any mounted client. The+ * take becomes the scene's `referenceImageId` only while that slot is still+ * unselected; it never replaces a frame the director already selected. This is* the durable counterpart to the director board's optimistic generate-then-* attach: a long-running local/Codex render that completes after the user* navigated away, refreshed, or moved their cursor still lands on the scene@@ -21,14 +23,13 @@* client so the board updates reactively.** The shared completion-hook scaffold (tag-decode, per-project serialization,- * the newest-render-wins guard, best-effort error handling, idempotent init/- * reset) lives in `createMediaJobImageHook` (#1791) — this file is just the+ * best-effort error handling, idempotent init/reset) lives in `createMediaJobImageHook` (#1791) — this file is just the* music-video-specific config. Mounted once at server boot from server/index.js* (after the media job queue is running).*/import { createMediaJobImageHook } from './mediaJobImageHook.js';-import { updateScene } from './musicVideo/projects.js';+import { appendSceneTakes } from './musicVideo/projects.js';import { musicVideoEvents } from './musicVideo/events.js';const hook = createMediaJobImageHook({@@ -44,16 +45,28 @@ const hook = createMediaJobImageHook({// (file backend) and the later write would clobber the earlier scene's// `referenceImageId`. Different projects still attach concurrently.serializeKey: ({ projectId }) => projectId,- // Newest-render-wins per scene: the GPU lane is FIFO, but the Codex lane and- // renders kicked off from another client can complete out of order — drop an- // older render so it can't overwrite a newer reference frame.- sceneKey: ({ projectId, sceneId }) => `${projectId}:${sceneId}`,+ // No newest-render-wins guard (#8965): renders that complete out of order+ // are all kept as takes, and none of them can displace a selection, so an+ // older render is a candidate rather than something to drop.describe: ({ projectId, sceneId }) => `${projectId}/${sceneId}`,- attach: ({ projectId, sceneId, filename }) =>- updateScene(projectId, sceneId, { referenceImageId: filename }),- onAttached: ({ projectId, sceneId, filename }) => {- musicVideoEvents.emit('scene-image', { projectId, sceneId, referenceImageId: filename });- console.log(`🎞️ music-video scene image ${projectId.slice(0, 8)}/${sceneId} ← ${filename}`);+ // A deleted project/scene 404s here, so a late completion can't resurrect it.+ attach: ({ projectId, sceneId, filename, job }) => appendSceneTakes(projectId, sceneId, [{+ kind: 'image',+ assetId: filename,+ source: 'generated',+ provider: 'portos',+ jobId: typeof job.id === 'string' ? job.id : null,+ prompt: typeof job.params?.prompt === 'string' ? job.params.prompt : null,+ }]),+ onAttached: ({ projectId, sceneId, filename }, { scene, appended }) => {+ musicVideoEvents.emit('scene-image', {+ projectId,+ sceneId,+ referenceImageId: scene.referenceImageId ?? null,+ takes: scene.takes,+ takeId: appended[0]?.takeId ?? null,+ });+ console.log(`🎞️ music-video scene image take ${projectId.slice(0, 8)}/${sceneId} ← ${filename}`);},});diff --git a/server/services/musicVideoSceneImageHook.test.js b/server/services/musicVideoSceneImageHook.test.jsdeleted file mode 100644index 3381b39305..0000000000--- a/server/services/musicVideoSceneImageHook.test.js+++ /dev/null@@ -1,131 +0,0 @@-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';--// Mock the project store so the hook's tag-decode + serialize + emit logic is-// exercised without touching disk or a DB. `updateScene` is reprogrammed-// per-test to stand in for the durable attach.-const updateScene = vi.fn(async (projectId, sceneId, patch) => ({- sceneId, ...patch,-}));-vi.mock('./musicVideo/projects.js', () => ({ updateScene }));--const { mediaJobEvents } = await import('./mediaJobQueue/index.js');-const { musicVideoEvents } = await import('./musicVideo/events.js');-const hook = await import('./musicVideoSceneImageHook.js');--async function waitFor(predicate, { timeoutMs = 1000, intervalMs = 5 } = {}) {- const deadline = Date.now() + timeoutMs;- while (Date.now() < deadline) {- if (predicate()) return;- await new Promise((r) => setTimeout(r, intervalMs));- }- throw new Error('waitFor: predicate never became true');-}--const tag = (over = {}) => ({ projectId: 'mv-1', sceneId: 'mvs-1', ...over });-const completedImageJob = ({ params = {}, filename = 'job-abc.png', id = 'job-abc', queuedAt } = {}) => ({- kind: 'image', id, params, result: { filename }, ...(queuedAt ? { queuedAt } : {}),-});--describe('musicVideoSceneImageHook', () => {- let emitted;- const capture = (data) => emitted.push(data);-- beforeEach(() => {- hook.__testing.reset();- hook.initMusicVideoSceneImageHook();- updateScene.mockReset();- updateScene.mockImplementation(async (projectId, sceneId, patch) => ({ sceneId, ...patch }));- emitted = [];- musicVideoEvents.on('scene-image', capture);- });-- afterEach(() => {- hook.__testing.reset();- musicVideoEvents.off('scene-image', capture);- });-- it('attaches the rendered filename and emits scene-image for a musicVideo-tagged job', async () => {- mediaJobEvents.emit('completed', completedImageJob({- params: { musicVideo: tag(), prompt: 'a neon skyline' },- filename: 'job-abc.png', id: 'job-abc',- }));- await waitFor(() => emitted.length > 0);- expect(updateScene).toHaveBeenCalledWith('mv-1', 'mvs-1', { referenceImageId: 'job-abc.png' });- expect(emitted[0]).toEqual({ projectId: 'mv-1', sceneId: 'mvs-1', referenceImageId: 'job-abc.png' });- });-- it('ignores a completed job with no musicVideo tag', async () => {- mediaJobEvents.emit('completed', completedImageJob({- params: { writersRoom: { workId: 'w', analysisId: 'a', sceneId: 's' } },- }));- // Give the async IIFE a chance to run before asserting it did nothing.- await new Promise((r) => setTimeout(r, 20));- expect(updateScene).not.toHaveBeenCalled();- expect(emitted).toHaveLength(0);- });-- it('ignores a non-image job kind', async () => {- mediaJobEvents.emit('completed', { kind: 'video', id: 'v1', params: { musicVideo: tag() }, result: { filename: 'v1.mp4' } });- await new Promise((r) => setTimeout(r, 20));- expect(updateScene).not.toHaveBeenCalled();- expect(emitted).toHaveLength(0);- });-- it('skips a tag missing projectId or sceneId', async () => {- mediaJobEvents.emit('completed', completedImageJob({ params: { musicVideo: { projectId: 'mv-1' } } }));- mediaJobEvents.emit('completed', completedImageJob({ params: { musicVideo: { sceneId: 'mvs-1' } } }));- await new Promise((r) => setTimeout(r, 20));- expect(updateScene).not.toHaveBeenCalled();- expect(emitted).toHaveLength(0);- });-- it('does not emit (or throw) when the attach fails — project/scene deleted mid-render', async () => {- updateScene.mockRejectedValueOnce(Object.assign(new Error('Project not found'), { status: 404 }));- mediaJobEvents.emit('completed', completedImageJob({ params: { musicVideo: tag() } }));- await waitFor(() => updateScene.mock.calls.length > 0);- // The failed attach must not surface as a scene-image event.- await new Promise((r) => setTimeout(r, 20));- expect(emitted).toHaveLength(0);- });-- it('does not let an older render (earlier queuedAt) overwrite a newer frame on the same scene', async () => {- // Newer render lands first, then an out-of-order older one completes.- mediaJobEvents.emit('completed', completedImageJob({- params: { musicVideo: tag() }, filename: 'new.png', id: 'b', queuedAt: '2026-06-29T00:00:02.000Z',- }));- await waitFor(() => updateScene.mock.calls.length > 0);- mediaJobEvents.emit('completed', completedImageJob({- params: { musicVideo: tag() }, filename: 'old.png', id: 'a', queuedAt: '2026-06-29T00:00:01.000Z',- }));- // Give the older job's handler a chance to run and be dropped.- await new Promise((r) => setTimeout(r, 30));- // The newer frame attached; the older one was skipped (never re-attached).- expect(updateScene).toHaveBeenCalledTimes(1);- expect(updateScene).toHaveBeenCalledWith('mv-1', 'mvs-1', { referenceImageId: 'new.png' });- expect(emitted.map((e) => e.referenceImageId)).toEqual(['new.png']);- });-- it('serializes attaches for the same project so concurrent renders do not clobber', async () => {- // Resolve order is gated by the queue: a slow first attach must settle before- // the second begins, so updateScene is never re-entered for the same project.- const order = [];- let resolveFirst;- updateScene- .mockImplementationOnce(() => new Promise((resolve) => {- order.push('start-1');- resolveFirst = () => { order.push('end-1'); resolve({ referenceImageId: 'a.png' }); };- }))- .mockImplementationOnce(async () => { order.push('start-2'); return { referenceImageId: 'b.png' }; });-- mediaJobEvents.emit('completed', completedImageJob({ params: { musicVideo: tag({ sceneId: 'mvs-1' }) }, filename: 'a.png', id: 'a' }));- mediaJobEvents.emit('completed', completedImageJob({ params: { musicVideo: tag({ sceneId: 'mvs-2' }) }, filename: 'b.png', id: 'b' }));-- await waitFor(() => order.includes('start-1'));- // The second attach must NOT have started while the first is still pending.- await new Promise((r) => setTimeout(r, 20));- expect(order).toEqual(['start-1']);- resolveFirst();- await waitFor(() => order.includes('start-2'));- expect(order).toEqual(['start-1', 'end-1', 'start-2']);- });-});diff --git a/server/services/musicVideoSceneVideoHook.js b/server/services/musicVideoSceneVideoHook.jsindex 6356ae4b9e..3a479c8fb4 100644--- a/server/services/musicVideoSceneVideoHook.js+++ b/server/services/musicVideoSceneVideoHook.js@@ -2,8 +2,10 @@* Music Video scene i2v-clip attach hook (issue #1760, Phase 1).** Subscribes to mediaJobEvents and, for each completed VIDEO job that carries- * `params.musicVideo`, files the resulting history id onto that project scene's- * `videoHistoryId` — server-side, independent of any mounted client. This is the+ * `params.musicVideo`, appends the resulting history id to that project scene's+ * immutable takes (#8965) — server-side, independent of any mounted client. The+ * take becomes the scene's `videoHistoryId` only while that slot is still+ * unselected; it never replaces a clip the director already selected. This is the* i2v counterpart to the Phase 1b reference-frame hook* (`musicVideoSceneImageHook`): a scene's video is generated from its chosen* reference frame via the video route's `image` (i2v) mode, and a long local/@@ -22,15 +24,15 @@* echo the field still attaches the right clip.** The shared completion-hook scaffold (tag-decode, per-project serialization,- * the newest-render-wins guard, best-effort error handling, idempotent init/- * reset) lives in `createMediaJobImageHook` (#1791) — generalized to the video+ * best-effort error handling, idempotent init/reset) lives in `createMediaJobImageHook` (#1791) — generalized to the video* `kind` in #1760 Phase 1. This file is just the music-video-video config,* structurally identical to its scene-image sibling. Mounted once at server boot* from server/index.js (after the media job queue is running).*/import { createMediaJobImageHook } from './mediaJobImageHook.js';-import { updateScene } from './musicVideo/projects.js';+import { basename } from 'path';+import { appendSceneTakes } from './musicVideo/projects.js';import { musicVideoEvents } from './musicVideo/events.js';const hook = createMediaJobImageHook({@@ -55,16 +57,30 @@ const hook = createMediaJobImageHook({// backend) and the later write would clobber the earlier scene's// `videoHistoryId`. Different projects still attach concurrently.serializeKey: ({ projectId }) => projectId,- // Newest-render-wins per scene: a clip kicked off from another client (or after- // a refresh cleared the local spinner) can complete out of order — drop an- // older render so it can't overwrite a newer clip.- sceneKey: ({ projectId, sceneId }) => `${projectId}:${sceneId}`,+ // No newest-render-wins guard (#8965): out-of-order clips are all kept as+ // takes, and none of them can displace a selection.describe: ({ projectId, sceneId }) => `${projectId}/${sceneId}`,- attach: ({ projectId, sceneId, videoHistoryId }) =>- updateScene(projectId, sceneId, { videoHistoryId }),- onAttached: ({ projectId, sceneId, videoHistoryId }) => {- musicVideoEvents.emit('scene-video', { projectId, sceneId, videoHistoryId });- console.log(`🎬 music-video scene clip ${projectId.slice(0, 8)}/${sceneId} ← ${videoHistoryId.slice(0, 8)}`);+ // A deleted project/scene 404s here, so a late completion can't resurrect it.+ attach: ({ projectId, sceneId, videoHistoryId, job }) => appendSceneTakes(projectId, sceneId, [{+ kind: 'video',+ assetId: videoHistoryId,+ source: 'generated',+ provider: 'portos',+ jobId: typeof job.id === 'string' ? job.id : null,+ prompt: typeof job.params?.prompt === 'string' ? job.params.prompt : null,+ // The frame this clip was generated from — a basename only; job params+ // carry the server's absolute path, which never belongs on a synced record.+ sourceImageId: typeof job.params?.sourceImagePath === 'string' ? basename(job.params.sourceImagePath) : null,+ }]),+ onAttached: ({ projectId, sceneId, videoHistoryId }, { scene, appended }) => {+ musicVideoEvents.emit('scene-video', {+ projectId,+ sceneId,+ videoHistoryId: scene.videoHistoryId ?? null,+ takes: scene.takes,+ takeId: appended[0]?.takeId ?? null,+ });+ console.log(`🎬 music-video scene clip take ${projectId.slice(0, 8)}/${sceneId} ← ${videoHistoryId.slice(0, 8)}`);},});diff --git a/server/services/musicVideoSceneVideoHook.test.js b/server/services/musicVideoSceneVideoHook.test.jsdeleted file mode 100644index 1ed9ae2db1..0000000000--- a/server/services/musicVideoSceneVideoHook.test.js+++ /dev/null@@ -1,129 +0,0 @@-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';--// Mock the project store so the hook's tag-decode + serialize + emit logic is-// exercised without touching disk or a DB. `updateScene` is reprogrammed-// per-test to stand in for the durable attach.-const updateScene = vi.fn(async (projectId, sceneId, patch) => ({ sceneId, ...patch }));-vi.mock('./musicVideo/projects.js', () => ({ updateScene }));--const { mediaJobEvents } = await import('./mediaJobQueue/index.js');-const { musicVideoEvents } = await import('./musicVideo/events.js');-const hook = await import('./musicVideoSceneVideoHook.js');--async function waitFor(predicate, { timeoutMs = 1000, intervalMs = 5 } = {}) {- const deadline = Date.now() + timeoutMs;- while (Date.now() < deadline) {- if (predicate()) return;- await new Promise((r) => setTimeout(r, intervalMs));- }- throw new Error('waitFor: predicate never became true');-}--const tag = (over = {}) => ({ projectId: 'mv-1', sceneId: 'mvs-1', ...over });-// A completed video job: the queue stores the videoGenEvents 'completed' payload-// as job.result, which echoes the history id as generationId.-const completedVideoJob = ({ params = {}, id = 'vid-abc', generationId, queuedAt } = {}) => ({- kind: 'video', id, params,- result: { generationId: generationId ?? id, filename: `${id}.mp4`, path: `/data/videos/${id}.mp4` },- ...(queuedAt ? { queuedAt } : {}),-});--describe('musicVideoSceneVideoHook', () => {- let emitted;- const capture = (data) => emitted.push(data);-- beforeEach(() => {- hook.__testing.reset();- hook.initMusicVideoSceneVideoHook();- updateScene.mockReset();- updateScene.mockImplementation(async (projectId, sceneId, patch) => ({ sceneId, ...patch }));- emitted = [];- musicVideoEvents.on('scene-video', capture);- });-- afterEach(() => {- hook.__testing.reset();- musicVideoEvents.off('scene-video', capture);- });-- it('attaches the clip history id and emits scene-video for a musicVideo-tagged video job', async () => {- mediaJobEvents.emit('completed', completedVideoJob({- params: { musicVideo: tag(), prompt: 'a neon skyline dolly' }, id: 'vid-abc',- }));- await waitFor(() => emitted.length > 0);- expect(updateScene).toHaveBeenCalledWith('mv-1', 'mvs-1', { videoHistoryId: 'vid-abc' });- expect(emitted[0]).toEqual({ projectId: 'mv-1', sceneId: 'mvs-1', videoHistoryId: 'vid-abc' });- });-- it('falls back to job.id when the result omits generationId', async () => {- mediaJobEvents.emit('completed', { kind: 'video', id: 'vid-xyz', params: { musicVideo: tag() }, result: { filename: 'vid-xyz.mp4' } });- await waitFor(() => emitted.length > 0);- expect(updateScene).toHaveBeenCalledWith('mv-1', 'mvs-1', { videoHistoryId: 'vid-xyz' });- expect(emitted[0].videoHistoryId).toBe('vid-xyz');- });-- it('ignores a completed job with no musicVideo tag', async () => {- mediaJobEvents.emit('completed', completedVideoJob({ params: { prompt: 'plain video-gen render' } }));- await new Promise((r) => setTimeout(r, 20));- expect(updateScene).not.toHaveBeenCalled();- expect(emitted).toHaveLength(0);- });-- it('ignores a non-video job kind (the image hook owns those)', async () => {- mediaJobEvents.emit('completed', { kind: 'image', id: 'img1', params: { musicVideo: tag() }, result: { filename: 'img1.png' } });- await new Promise((r) => setTimeout(r, 20));- expect(updateScene).not.toHaveBeenCalled();- expect(emitted).toHaveLength(0);- });-- it('skips a tag missing projectId or sceneId', async () => {- mediaJobEvents.emit('completed', completedVideoJob({ params: { musicVideo: { projectId: 'mv-1' } } }));- mediaJobEvents.emit('completed', completedVideoJob({ params: { musicVideo: { sceneId: 'mvs-1' } } }));- await new Promise((r) => setTimeout(r, 20));- expect(updateScene).not.toHaveBeenCalled();- expect(emitted).toHaveLength(0);- });-- it('does not emit (or throw) when the attach fails — project/scene deleted mid-render', async () => {- updateScene.mockRejectedValueOnce(Object.assign(new Error('Project not found'), { status: 404 }));- mediaJobEvents.emit('completed', completedVideoJob({ params: { musicVideo: tag() } }));- await waitFor(() => updateScene.mock.calls.length > 0);- await new Promise((r) => setTimeout(r, 20));- expect(emitted).toHaveLength(0);- });-- it('does not let an older render (earlier queuedAt) overwrite a newer clip on the same scene', async () => {- mediaJobEvents.emit('completed', completedVideoJob({- params: { musicVideo: tag() }, id: 'new', queuedAt: '2026-06-29T00:00:02.000Z',- }));- await waitFor(() => updateScene.mock.calls.length > 0);- mediaJobEvents.emit('completed', completedVideoJob({- params: { musicVideo: tag() }, id: 'old', queuedAt: '2026-06-29T00:00:01.000Z',- }));- await new Promise((r) => setTimeout(r, 30));- expect(updateScene).toHaveBeenCalledTimes(1);- expect(updateScene).toHaveBeenCalledWith('mv-1', 'mvs-1', { videoHistoryId: 'new' });- expect(emitted.map((e) => e.videoHistoryId)).toEqual(['new']);- });-- it('serializes attaches for the same project so concurrent renders do not clobber', async () => {- const order = [];- let resolveFirst;- updateScene- .mockImplementationOnce(() => new Promise((resolve) => {- order.push('start-1');- resolveFirst = () => { order.push('end-1'); resolve({ videoHistoryId: 'a' }); };- }))- .mockImplementationOnce(async () => { order.push('start-2'); return { videoHistoryId: 'b' }; });-- mediaJobEvents.emit('completed', completedVideoJob({ params: { musicVideo: tag({ sceneId: 'mvs-1' }) }, id: 'a' }));- mediaJobEvents.emit('completed', completedVideoJob({ params: { musicVideo: tag({ sceneId: 'mvs-2' }) }, id: 'b' }));-- await waitFor(() => order.includes('start-1'));- await new Promise((r) => setTimeout(r, 20));- expect(order).toEqual(['start-1']);- resolveFirst();- await waitFor(() => order.includes('start-2'));- expect(order).toEqual(['start-1', 'end-1', 'start-2']);- });-});diff --git a/server/services/sharing/peerSyncAssets.js b/server/services/sharing/peerSyncAssets.jsindex ff9bd60d37..de574741c3 100644--- a/server/services/sharing/peerSyncAssets.js+++ b/server/services/sharing/peerSyncAssets.js@@ -513,6 +513,9 @@ async function reconcileVideoThumbnail(filename, videoPath, peerId) {* `videoHistory` dataSync category; this adds the bytes. Falls back to the* `<id>.mp4` convention (`collectionVideoRefToFilename`) when the row hasn't* synced yet — a missing file is skipped, so a wrong guess never ships.+ * - every scene take (`scene.takes[]`, #8965) of either kind, and the visual+ * spec's reference images (`visualSpec.references[].imageId`), so a peer can+ * review and select any candidate, not only the current selection.* - per-scene reference-frame stills (`scene.referenceImageId`, #1760 Phase 1b* — a gallery basename under PATHS.images, the same store every other gen'd* image uses). Hashed sidecar-aware via `hashImageForManifest` so a peer that@@ -549,9 +552,16 @@ export async function referenceMusicVideoAssetManifest(project, { linkedTrack }if (audio) dedup.set(`${audio.kind}:${audio.filename}`, audio);}const scenes = Array.isArray(project?.scenes) ? project.scenes : [];- const videoIds = [...new Set(- scenes.map((s) => (isStr(s?.videoHistoryId) ? s.videoHistoryId : null)).filter(Boolean),- )];+ // Every scene take (#8965) is a candidate the director can select on any+ // peer, so its bytes ride along with the selected slot's. Take kinds are+ // peer-supplied data — only the two known kinds contribute.+ const takeIds = (kind) => scenes.flatMap((s) => (Array.isArray(s?.takes) ? s.takes : [])+ .filter((t) => t?.kind === kind && isStr(t.assetId))+ .map((t) => t.assetId));+ const videoIds = [...new Set([+ ...scenes.map((s) => (isStr(s?.videoHistoryId) ? s.videoHistoryId : null)).filter(Boolean),+ ...takeIds('video'),+ ])];if (videoIds.length) {const byId = await videoHistoryFilenamesById();const entries = videoIds.map((id) =>@@ -561,9 +571,14 @@ export async function referenceMusicVideoAssetManifest(project, { linkedTrack }if (entry) dedup.set(`${entry.kind}:${entry.filename}`, entry);}}- const imageNames = [...new Set(- scenes.map((s) => (isStr(s?.referenceImageId) ? s.referenceImageId : null)).filter(Boolean),- )];+ // Reference frames, image takes, and the visual spec's moodboard/reference+ // images (#8965) all live in the gallery under the `image` asset kind.+ const specRefs = Array.isArray(project?.visualSpec?.references) ? project.visualSpec.references : [];+ const imageNames = [...new Set([+ ...scenes.map((s) => (isStr(s?.referenceImageId) ? s.referenceImageId : null)).filter(Boolean),+ ...takeIds('image'),+ ...specRefs.map((r) => (isStr(r?.imageId) ? r.imageId : null)).filter(Boolean),+ ])];if (imageNames.length) {const entries = imageNames.map(imageAssetReference);for (const entry of entries) {diff --git a/server/services/sharing/peerSyncAssets.test.js b/server/services/sharing/peerSyncAssets.test.jsindex 03eff4e966..7602b69e8c 100644--- a/server/services/sharing/peerSyncAssets.test.js+++ b/server/services/sharing/peerSyncAssets.test.js@@ -161,6 +161,43 @@ describe('buildMusicVideoAssetManifest — master audio', () => {});});+describe('buildMusicVideoAssetManifest — scene takes + visual spec (#8965)', () => {+ beforeEach(() => {+ tempRoot = mkdtempSync(join(tmpdir(), 'portos-mv-takes-assets-'));+ vi.mocked(getTrack).mockReset().mockResolvedValue(null);+ });+ afterEach(() => {+ if (tempRoot) rmSync(tempRoot, { recursive: true, force: true });+ });++ it('ships every take and moodboard reference a peer may select, not only the selected slot', async () => {+ for (const name of ['selected.png', 'candidate.png', 'mood.png']) writeImage(name, Buffer.from(name));+ writeVideo('clip-a.mp4', Buffer.from('a'));+ writeVideo('clip-b.mp4', Buffer.from('b'));+ const manifest = await buildMusicVideoAssetManifest({+ trackId: null,+ uploadedAudioFilename: null,+ visualSpec: { references: [{ id: 'r1', imageId: 'mood.png' }, { id: 'r2', imageId: '../escape.png' }] },+ scenes: [{+ sceneId: 's1',+ referenceImageId: 'selected.png',+ videoHistoryId: 'clip-a',+ takes: [+ { kind: 'image', assetId: 'selected.png' },+ { kind: 'image', assetId: 'candidate.png', status: 'rejected' },+ { kind: 'video', assetId: 'clip-b' },+ { kind: 'bogus', assetId: 'clip-a.mp4' },+ ],+ }],+ });+ const keys = manifest.map((m) => `${m.kind}:${m.filename}`).sort();+ expect(keys).toEqual([+ 'image:candidate.png', 'image:mood.png', 'image:selected.png',+ 'video:clip-a.mp4', 'video:clip-b.mp4',+ ]);+ });+});+describe('buildProjectAssetManifest — first-pass music bed (#1928)', () => {beforeEach(() => {tempRoot = mkdtempSync(join(tmpdir(), 'portos-cd-assets-'));