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: universe canon references, handoff zip bundle, clip import, non-MP4 playback (#8978)
[._.]/ Adam Eivyd448b5f98664
diff --git a/client/src/components/musicVideo/HandoffControls.jsx b/client/src/components/musicVideo/HandoffControls.jsxindex 2e2beef022..3f5f480fe0 100644--- a/client/src/components/musicVideo/HandoffControls.jsx+++ b/client/src/components/musicVideo/HandoffControls.jsx@@ -1,5 +1,5 @@import { useState } from 'react';-import { Download, Upload, Activity, LayoutGrid } from 'lucide-react';+import { Download, FileArchive, Upload, Activity, LayoutGrid } from 'lucide-react';import FilePickerButton from '../ui/FilePickerButton';const PROVIDERS = [['midjourney', 'Midjourney'], ['external', 'Other tool']];@@ -12,7 +12,7 @@ const HANDOFF_ACCEPT = 'image/png,image/jpeg,image/webp,image/gif,video/mp4,vide* 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 }) {+export default function HandoffControls({ projectId, busy, onExport, onExportBundle, onImport, onOpenContactSheet }) {const [provider, setProvider] = useState('midjourney');const selectId = `mv-handoff-provider-${projectId}`;return (@@ -28,6 +28,13 @@ export default function HandoffControls({ projectId, busy, onExport, onImport, otitle="Download per-scene prompts, file tags and reference files as JSON"><Download size={13} /> Export prompts</button>+ {onExportBundle && (+ <button type="button" onClick={onExportBundle} 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 the manifest plus every reference image and selected frame as one zip">+ <FileArchive size={13} /> Export bundle+ </button>+ )}<FilePickerButton multiple accept={HANDOFF_ACCEPT} disabled={busy}onChange={(e) => onImport(Array.from(e.target.files || []), provider)}ariaLabel="Import generated files"diff --git a/client/src/components/musicVideo/SceneCard.jsx b/client/src/components/musicVideo/SceneCard.jsxindex b7a423a830..49d060b61e 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, ImagePlus } from 'lucide-react';+import { Trash2, Activity, ArrowUp, ArrowDown, Image as ImageIcon, Video, Maximize2, AlertTriangle, ImagePlus, Clapperboard } from 'lucide-react';import { formatDurationSec } from '../../utils/formatters.js';+import { useVideoFileSrc } from '../../hooks/useVideoFileSrc.js';import SceneTakeStrip from './SceneTakeStrip.jsx';// The two timeline-bound scene fields rendered as identical number inputs.@@ -22,19 +23,29 @@ const COVERAGE_TOLERANCE_SEC = 0.25;* 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.+ * frame (gallery pick or upload) as a take; `onImportClipTake` (#8978) does the+ * same for an existing gallery clip.*/export default function SceneCard({scene, index, isLast, generatingFrame, generatingVideo,settingsSaving, videoBlockedReason, canContinueShot,onMove, onDelete, onEditLocal, onSave,onGenerateFrame, onGenerateVideo, onContinueVideo,- onOpenPreview, onSelectTake, onReviewTake, onImportTake, takeBusy = false,+ onOpenPreview, onSelectTake, onReviewTake, onImportTake, onImportClipTake, 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// native controls let the user unmute it first (muted is only initial).const clipPlayerRef = useRef(null);+ // Resolve the clip's real stored filename rather than assuming `<id>.mp4` —+ // an imported .mov/.webm keeps its own container (videoUpload.js), so the+ // reconstructed path 404s for it (#8978). Falls back to the historical+ // reconstruction while the lookup is in flight or if it fails, same as+ // useVideoFileSrc's other ScenePreview-style callers.+ const clipFile = useVideoFileSrc(scene.videoHistoryId, { enabled: !!scene.videoHistoryId });+ const clipSrc = scene.videoHistoryId+ ? (clipFile.src || `/data/videos/${scene.videoHistoryId}.mp4`)+ : null;// Source-clip length, read from the inline player's metadata and keyed to// the clip it was measured from so a regenerated clip is re-measured.const [clipMeta, setClipMeta] = useState(null);@@ -173,7 +184,7 @@ export default function SceneCard({<div className="relative w-40 shrink-0"><videoref={clipPlayerRef}- src={`/data/videos/${scene.videoHistoryId}.mp4`}+ src={clipSrc}className="w-full aspect-video object-cover rounded border border-port-border bg-black"mutedplaysInline@@ -220,6 +231,13 @@ export default function SceneCard({<Video size={14} /> Continue shot</button>)}+ {onImportClipTake && (+ <button type="button" onClick={() => onImportClipTake(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="Pick an existing clip from the gallery (e.g. made in an external tool) as a take">+ <Clapperboard size={14} /> Import clip take+ </button>+ )}</div><SceneTakeStrip scene={scene} kind="video" busy={takeBusy}onSelect={(take) => onSelectTake?.(scene, take)}diff --git a/client/src/components/musicVideo/VisualSpecPanel.jsx b/client/src/components/musicVideo/VisualSpecPanel.jsxindex 3c5052c21b..d94033959b 100644--- a/client/src/components/musicVideo/VisualSpecPanel.jsx+++ b/client/src/components/musicVideo/VisualSpecPanel.jsx@@ -1,8 +1,11 @@import { useState } from 'react';-import { ImagePlus, Trash2, Plus, Palette } from 'lucide-react';+import { ImagePlus, Trash2, Plus, Palette, Sparkles } from 'lucide-react';import useFieldDraft from '../../hooks/useFieldDraft.js';import MoodBoardReferenceStrip from '../moodBoard/MoodBoardReferenceStrip.jsx';import { MAX_CONDITIONING_REFERENCES } from '../../hooks/useMusicVideoSceneMedia.js';+import { getUniverse } from '../../services/apiUniverseBuilder.js';+import { pullUniverseCanonReferences } from '../../lib/musicVideoUniverseRefs.js';+import toast from '../ui/Toast';const ROLES = [['mood', 'Mood'], ['character', 'Character'], ['wardrobe', 'Wardrobe'],@@ -27,6 +30,7 @@ export default function VisualSpecPanel({ project, onSave, onAddReference }) {const references = spec.references || [];const palette = spec.palette || [];const [color, setColor] = useState('#336699');+ const [pulling, setPulling] = useState(false);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}`;@@ -35,6 +39,28 @@ export default function VisualSpecPanel({ project, onSave, onAddReference }) {const updateRef = (id, patch) => saveReferences(references.map((r) => (r.id === id ? { ...r, ...patch } : r)));const flagged = references.filter((r) => r.condition).length;+ // "Pull from universe" (#8978) — reuse the linked universe's canon+ // characters/places/objects as references instead of re-picking every one+ // by hand through Add reference. Idempotent: images already present are+ // skipped, so a second click adds nothing new.+ const universeId = project.concept?.universeId || null;+ const handlePullFromUniverse = () => {+ if (!universeId || pulling) return;+ setPulling(true);+ getUniverse(universeId, { silent: true })+ .then((universe) => {+ const { next, added, skipped } = pullUniverseCanonReferences(universe, references);+ if (added > 0) saveReferences(next);+ if (added > 0) {+ toast.success(`Pulled ${added} reference${added === 1 ? '' : 's'} from the universe${skipped ? ` (${skipped} skipped)` : ''}`);+ } else {+ toast.error(skipped ? 'Every canon image is already a reference' : 'This universe has no canon images to pull yet');+ }+ })+ .catch((err) => toast.error(err?.message || 'Failed to load the universe'))+ .finally(() => setPulling(false));+ };+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">@@ -52,10 +78,19 @@ export default function VisualSpecPanel({ project, onSave, onAddReference }) {<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 className="flex items-center gap-1.5 flex-wrap">+ {universeId && (+ <button type="button" onClick={handlePullFromUniverse} disabled={pulling || 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"+ title="Add this project's linked universe's canon character/place/object images as references">+ <Sparkles size={13} /> {pulling ? 'Pulling…' : 'Pull from universe'}+ </button>+ )}+ <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></div>{references.length === 0 && (<p className="text-[11px] text-port-text-muted">diff --git a/client/src/hooks/useMusicVideoTakes.js b/client/src/hooks/useMusicVideoTakes.jsindex cdaa9bf38f..32dd8b1fd4 100644--- a/client/src/hooks/useMusicVideoTakes.js+++ b/client/src/hooks/useMusicVideoTakes.js@@ -5,6 +5,7 @@ import {selectMusicVideoSceneTake,reviewMusicVideoSceneTake,getMusicVideoHandoff,+ getMusicVideoHandoffBundle,importMusicVideoHandoff,} from '../services/apiMusicVideo.js';import { uploadGalleryImage } from '../services/apiSystem.js';@@ -29,7 +30,9 @@ function handoffFileProblem(file, isVideo) {}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`;+const handoffSlug = (name) => String(name || 'music-video').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'music-video';+const handoffFilename = (name) => `${handoffSlug(name)}-handoff.json`;+const handoffBundleFilename = (name) => `${handoffSlug(name)}-handoff.zip`;/*** Scene-take review + external-asset handoff actions for the Music Video board@@ -80,6 +83,16 @@ export default function useMusicVideoTakes({ project, applyScenePatch }) {'Failed to import take',);+ // A clip picked from the video-history gallery for one scene (#8978). Same+ // append-only contract as importTake: it fills the scene's video slot only+ // while empty (appendSceneTakes), never replacing an existing selection.+ const importClipTake = (scene, item) => runTakeOp(+ (projectId) => addMusicVideoSceneTake(projectId, scene.sceneId, {+ kind: 'video', assetId: item.id, source: 'imported',+ }, { silent: true }).then((res) => res.scene),+ 'Failed to import clip take',+ );+const exportHandoff = () => getMusicVideoHandoff(project.id, { silent: true }).then((manifest) => {downloadBlob(JSON.stringify(manifest, null, 2), handoffFilename(project.name), 'application/json');@@ -87,6 +100,16 @@ export default function useMusicVideoTakes({ project, applyScenePatch }) {}).catch((err) => toast.error(err?.message || 'Handoff export failed'));+ // Downloadable ZIP counterpart (#8978): manifest.json plus every reference+ // image and each scene's selected frame, so nothing has to be saved out of+ // the gallery by hand before attaching it in the external tool.+ const exportHandoffBundle = () => getMusicVideoHandoffBundle(project.id, { silent: true })+ .then((buffer) => {+ downloadBlob(buffer, handoffBundleFilename(project.name), 'application/zip');+ toast.success('Exported handoff bundle');+ })+ .catch((err) => toast.error(err?.message || 'Handoff bundle export failed'));+const importHandoffFiles = async (files, provider) => {if (!files.length) return;if (files.length > MAX_HANDOFF_FILES) {@@ -127,5 +150,5 @@ export default function useMusicVideoTakes({ project, applyScenePatch }) {if (failures.length) toast.error(failures.slice(0, 3).join(' · '));};- return { busy, selectTake, reviewTake, importTake, exportHandoff, importHandoffFiles };+ return { busy, selectTake, reviewTake, importTake, importClipTake, exportHandoff, exportHandoffBundle, importHandoffFiles };}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 6306c2d207..9c52896862 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -59,6 +59,7 @@ grep -i "what you want to do" client/src/lib/README.md| `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`. |+| `musicVideoUniverseRefs.js` | `pullUniverseCanonReferences(universe, existingReferences)` (#8978) maps a linked universe's characters/places/objects to visual-spec references (character/set/prop roles), skipping images already present and capping at `MUSIC_VIDEO_MAX_REFERENCES` (24, mirrors the server schema). Returns `{ next, added, skipped }`; the caller persists `next` via the ordinary visualSpec PATCH. Used by `components/musicVideo/VisualSpecPanel.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 16f10da565..608dc7534a 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -67,6 +67,7 @@ export * from './issueRefs.js';export * from './musicDuration.js';export * from './muscriptorModels.js';export * from './musicVideoTakes.js';+export * from './musicVideoUniverseRefs.js';export * from './pipelineImageDefaults.js';export * from './reverseOutlineGrid.js';export * from './reviewerModels.js';diff --git a/client/src/lib/musicVideoUniverseRefs.js b/client/src/lib/musicVideoUniverseRefs.jsnew file mode 100644index 0000000000..d4d4fd0939--- /dev/null+++ b/client/src/lib/musicVideoUniverseRefs.js@@ -0,0 +1,64 @@+// Map a linked universe's canon (characters/places/objects) onto a music+// video project's visual-spec references (#8978 "Pull from universe"). Pure+// and read-only: the caller owns persisting the result via the ordinary+// visualSpec PATCH (see VisualSpecPanel.jsx).+//+// Mirrors the server's 24-reference cap+// (server/lib/musicVideoValidation.js musicVideoVisualSpecSchema) so a pull+// can never produce a spec the server would reject.++export const MUSIC_VIDEO_MAX_REFERENCES = 24;++// Canon kind → visual-spec reference role (server/lib/musicVideoValidation.js+// MUSIC_VIDEO_REFERENCE_ROLES). Characters are the obvious "character" role;+// places and props are the closest existing roles, since the visual spec has+// no dedicated "place"/"object" bucket.+const KIND_ROLE = Object.freeze({+ characters: 'character',+ places: 'set',+ objects: 'prop',+});++// The best available reference image for a canon entry: the pinned primary,+// else the first rendered ref. An entry with neither has nothing to pull.+function entryImage(entry) {+ if (entry?.primaryImageRef) return entry.primaryImageRef;+ const refs = Array.isArray(entry?.imageRefs) ? entry.imageRefs : [];+ return refs[0] || null;+}++/**+ * Build the visual-spec `references` array that results from pulling a+ * universe's canon images into `existingReferences`. Idempotent: an image+ * already present (by `imageId`) is skipped, so calling this again with the+ * same universe/references adds nothing new. Respects the 24-reference cap —+ * additions beyond it are counted in `skipped` rather than added.+ *+ * Returns `{ next, added, skipped }`. `next` is the full array to persist+ * (unchanged, by reference-equal content, when `added === 0` — but a caller+ * that wants to avoid a no-op save should check `added` itself).+ */+export function pullUniverseCanonReferences(universe, existingReferences = []) {+ const existingIds = new Set(existingReferences.map((ref) => ref.imageId));+ const candidates = [];+ let skippedNoImage = 0;+ let skippedDuplicate = 0;+ for (const [field, role] of Object.entries(KIND_ROLE)) {+ const list = Array.isArray(universe?.[field]) ? universe[field] : [];+ for (const entry of list) {+ const imageId = entryImage(entry);+ if (!imageId) { skippedNoImage += 1; continue; }+ if (existingIds.has(imageId)) { skippedDuplicate += 1; continue; }+ existingIds.add(imageId); // two canon entries sharing one image only add it once+ candidates.push({ imageId, role, label: (entry.name || '').slice(0, 120), condition: false });+ }+ }+ const room = Math.max(0, MUSIC_VIDEO_MAX_REFERENCES - existingReferences.length);+ const additions = candidates.slice(0, room);+ const skippedCap = candidates.length - additions.length;+ return {+ next: additions.length ? [...existingReferences, ...additions] : existingReferences,+ added: additions.length,+ skipped: skippedNoImage + skippedDuplicate + skippedCap,+ };+}diff --git a/client/src/lib/musicVideoUniverseRefs.test.js b/client/src/lib/musicVideoUniverseRefs.test.jsnew file mode 100644index 0000000000..f103798fae--- /dev/null+++ b/client/src/lib/musicVideoUniverseRefs.test.js@@ -0,0 +1,63 @@+import { describe, it, expect } from 'vitest';+import { pullUniverseCanonReferences, MUSIC_VIDEO_MAX_REFERENCES } from './musicVideoUniverseRefs.js';++describe('pullUniverseCanonReferences', () => {+ it('maps characters/places/objects to character/set/prop references, preferring primaryImageRef over imageRefs[0]', () => {+ const universe = {+ characters: [+ { id: 'c1', name: 'Nyra', primaryImageRef: 'nyra-primary.png', imageRefs: ['nyra-other.png'] },+ { id: 'c2', name: 'No Image' }, // no image at all — nothing to pull+ ],+ places: [{ id: 'p1', name: 'Harbor', imageRefs: ['harbor.png'] }],+ objects: [{ id: 'o1', name: 'Lantern', primaryImageRef: 'lantern.png' }],+ };+ const { next, added, skipped } = pullUniverseCanonReferences(universe, []);+ expect(added).toBe(3);+ expect(skipped).toBe(1); // 'No Image' has neither primaryImageRef nor imageRefs+ expect(next).toEqual([+ { imageId: 'nyra-primary.png', role: 'character', label: 'Nyra', condition: false },+ { imageId: 'harbor.png', role: 'set', label: 'Harbor', condition: false },+ { imageId: 'lantern.png', role: 'prop', label: 'Lantern', condition: false },+ ]);+ });++ it('is idempotent: an image already present as a reference is skipped, not duplicated', () => {+ const universe = { characters: [{ id: 'c1', name: 'Nyra', primaryImageRef: 'nyra.png' }], places: [], objects: [] };+ const existing = [{ id: 'r0', imageId: 'nyra.png', role: 'character', condition: false }];+ const { next, added, skipped } = pullUniverseCanonReferences(universe, existing);+ expect(added).toBe(0);+ expect(skipped).toBe(1);+ expect(next).toBe(existing); // unchanged reference — no-op save+ });++ it('two canon entries sharing one image only add it once', () => {+ const universe = {+ characters: [+ { id: 'c1', name: 'Twin A', primaryImageRef: 'shared.png' },+ { id: 'c2', name: 'Twin B', primaryImageRef: 'shared.png' },+ ],+ places: [], objects: [],+ };+ const { next, added } = pullUniverseCanonReferences(universe, []);+ expect(added).toBe(1);+ expect(next).toHaveLength(1);+ });++ it('respects the 24-reference cap, reporting the overflow as skipped', () => {+ const characters = Array.from({ length: 20 }, (_, i) => ({ id: `c${i}`, name: `Char ${i}`, primaryImageRef: `char-${i}.png` }));+ const universe = { characters, places: [], objects: [] };+ // 20 existing references already fill most of the 24-cap; room for only 4 more.+ const existing = Array.from({ length: 20 }, (_, i) => ({ id: `x${i}`, imageId: `existing-${i}.png`, role: 'mood', condition: false }));+ const { next, added, skipped } = pullUniverseCanonReferences(universe, existing);+ expect(added).toBe(4);+ expect(skipped).toBe(16);+ expect(next).toHaveLength(MUSIC_VIDEO_MAX_REFERENCES);+ });++ it('truncates an overlong canon name to the 120-char reference label limit', () => {+ const longName = 'X'.repeat(200);+ const universe = { characters: [{ id: 'c1', name: longName, primaryImageRef: 'c.png' }], places: [], objects: [] };+ const { next } = pullUniverseCanonReferences(universe, []);+ expect(next[0].label).toHaveLength(120);+ });+});diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex 43d6235543..acb15f0179 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -45,6 +45,7 @@ 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 GalleryVideoPicker from '../components/videoGen/GalleryVideoPicker.jsx';import { autoArrangeScenes } from '../lib/beatGrid.js';import { isLtx2FamilyRuntime } from '../lib/runnerFamilies';import { videoPosterForJob } from '../lib/creativeDirectorPreview.js';@@ -409,6 +410,13 @@ export default function MusicVideo() {const scene = (selected.scenes || []).find((s) => s.sceneId === pickerTarget.sceneId);if (scene) takes.importTake(scene, item);};+ // Per-scene "Import clip take" (#8978) — pick an existing video-history+ // clip and add it as a take, mirroring handlePickerSelect's image path.+ const handleClipPickerSelect = (item) => {+ if (!item?.id || !pickerTarget || pickerTarget.type !== 'clip' || !selected) return;+ const scene = (selected.scenes || []).find((s) => s.sceneId === pickerTarget.sceneId);+ if (scene) takes.importClipTake(scene, item);+ };const handleDeleteScene = (sceneId) => {deleteMusicVideoScene(selected.id, sceneId, { silent: true })@@ -497,7 +505,7 @@ export default function MusicVideo() {<MidiInstallModal {...midi.installGate} /><MidiGatedModal {...midi.gatedGate} /><MediaPreview preview={preview} setPreview={setPreview} items={previewItems} />- {pickerTarget && (+ {pickerTarget && pickerTarget.type !== 'clip' && (<GalleryImagePickeropenallowUpload@@ -505,6 +513,13 @@ export default function MusicVideo() {onSelect={handlePickerSelect}/>)}+ {pickerTarget && pickerTarget.type === 'clip' && (+ <GalleryVideoPicker+ open+ onClose={() => setPickerTarget(null)}+ onSelect={handleClipPickerSelect}+ />+ )}{selected && (<ContactSheetDraweropen={contactSheetOpen}@@ -638,6 +653,7 @@ export default function MusicVideo() {projectId={selected.id}busy={takes.busy}onExport={takes.exportHandoff}+ onExportBundle={takes.exportHandoffBundle}onImport={takes.importHandoffFiles}onOpenContactSheet={() => setContactSheetOpen(true)}/>@@ -708,6 +724,7 @@ export default function MusicVideo() {onSelectTake={takes.selectTake}onReviewTake={takes.reviewTake}onImportTake={(target) => setPickerTarget({ type: 'take', sceneId: target.sceneId })}+ onImportClipTake={(target) => setPickerTarget({ type: 'clip', sceneId: target.sceneId })}/>))}</div>diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex 09423c90ec..830070d86b 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -2,7 +2,7 @@* Focused tests for the music-video Render control (#1760 Phase 2): the button* gates on a scene having a generated clip, and clicking it kicks off the render.*/-import { describe, it, expect, vi, beforeEach } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { render, screen, waitFor, fireEvent, within, act } from '@testing-library/react';import { findEnabledByRole } from '../test/enabledBarrier.js';import { MemoryRouter, Routes, Route, useNavigate, useLocation } from 'react-router';@@ -62,8 +62,11 @@ vi.mock('../services/apiMusicVideo.js', () => ({selectMusicVideoSceneTake: vi.fn(),reviewMusicVideoSceneTake: vi.fn(),getMusicVideoHandoff: vi.fn(),+ getMusicVideoHandoffBundle: vi.fn(),importMusicVideoHandoff: vi.fn(),}));+vi.mock('../services/apiUniverseBuilder.js', () => ({ getUniverse: vi.fn() }));+vi.mock('../lib/downloadBlob.js', () => ({ downloadBlob: vi.fn() }));vi.mock('../services/apiSystem.js', () => ({ generateImage: vi.fn(), uploadGalleryImage: vi.fn() }));vi.mock('../hooks/useProviderModels', () => ({default: () => ({@@ -141,10 +144,13 @@ import {deleteMusicVideoProject, transcribeMusicVideoMidi, cancelMusicVideoRender,importMusicVideoLyrics, updateMusicVideoScene,selectMusicVideoSceneTake, reviewMusicVideoSceneTake, importMusicVideoHandoff,+ addMusicVideoSceneTake, getMusicVideoHandoffBundle,} 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';+import { generateVideo, getVideoGenStatus, getVideoHistoryItem } from '../services/apiImageVideo.js';+import { getUniverse } from '../services/apiUniverseBuilder.js';+import { downloadBlob } from '../lib/downloadBlob.js';const PROJECT_ANALYZED = {...PROJECT_NO_CLIP,@@ -1134,4 +1140,98 @@ describe('MusicVideo visual spec, takes and handoff (#8965)', () => {// The imported take filled the empty slot on the board.expect(await screen.findByRole('button', { name: 'View scene 1 reference frame full size' })).toBeTruthy();});++ it('downloads the ZIP handoff bundle from Export bundle (#8978)', async () => {+ getMusicVideoHandoffBundle.mockResolvedValueOnce(new ArrayBuffer(8));+ await openProject(SPEC_PROJECT);+ fireEvent.click(await screen.findByRole('button', { name: /^Export bundle$/ }));+ await waitFor(() => expect(getMusicVideoHandoffBundle).toHaveBeenCalledWith('mv-spec', { silent: true }));+ await waitFor(() => expect(downloadBlob).toHaveBeenCalledWith(+ expect.any(ArrayBuffer), 'spec-project-handoff.zip', 'application/zip',+ ));+ });+});++describe('MusicVideo pull references from universe (#8978)', () => {+ const UNIVERSE_PROJECT = {+ ...PROJECT_NO_CLIP,+ id: 'mv-universe',+ name: 'Universe Project',+ concept: { universeId: 'u1' },+ visualSpec: { references: [{ id: 'r0', imageId: 'harbor.png', role: 'mood', condition: false }] },+ };++ it('adds the universe\'s canon images as new references, skipping ones already present', async () => {+ getUniverse.mockResolvedValueOnce({+ characters: [{ id: 'c1', name: 'Nyra', primaryImageRef: 'nyra.png' }],+ places: [{ id: 'p1', name: 'Harbor', imageRefs: ['harbor.png'] }], // already a reference+ objects: [],+ });+ await openProject(UNIVERSE_PROJECT);++ fireEvent.click(await screen.findByRole('button', { name: /^Pull from universe$/ }));+ await waitFor(() => expect(getUniverse).toHaveBeenCalledWith('u1', { silent: true }));+ await waitFor(() => expect(updateMusicVideoProject).toHaveBeenCalledWith(+ 'mv-universe',+ { visualSpec: { references: [+ { id: 'r0', imageId: 'harbor.png', role: 'mood', condition: false },+ { imageId: 'nyra.png', role: 'character', label: 'Nyra', condition: false },+ ] } },+ { silent: true },+ ));+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith(expect.stringMatching(/Pulled 1 reference/)));+ });++ it('is idempotent — a second pull adds nothing once every canon image is already a reference', async () => {+ getUniverse.mockResolvedValue({+ characters: [], places: [{ id: 'p1', name: 'Harbor', imageRefs: ['harbor.png'] }], objects: [],+ });+ await openProject(UNIVERSE_PROJECT);+ fireEvent.click(await screen.findByRole('button', { name: /^Pull from universe$/ }));+ await waitFor(() => expect(getUniverse).toHaveBeenCalledTimes(1));+ expect(updateMusicVideoProject).not.toHaveBeenCalled();+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Every canon image is already a reference'));+ });++ it('does not offer Pull from universe when the project has no linked universe', async () => {+ await openProject(PROJECT_NO_CLIP);+ expect(screen.queryByRole('button', { name: /Pull from universe/i })).toBeNull();+ });+});++describe('MusicVideo per-scene clip import (#8978)', () => {+ it('imports a picked video-history clip as a candidate take for the scene, filling the empty slot', async () => {+ addMusicVideoSceneTake.mockResolvedValueOnce({+ scene: { ...PROJECT_NO_CLIP.scenes[0], videoHistoryId: 'rh-9', takes: [{ takeId: 't1', kind: 'video', assetId: 'rh-9', status: 'candidate' }] },+ });+ await openProject(PROJECT_NO_CLIP);++ fireEvent.click(await screen.findByRole('button', { name: /^Import clip take$/ }));+ const dialog = await screen.findByRole('dialog', { name: /Pick a video from your gallery/i });+ fireEvent.click(within(dialog).getByText('(no prompt)').closest('.bg-port-card').querySelector('button'));++ await waitFor(() => expect(addMusicVideoSceneTake).toHaveBeenCalledWith(+ 'mv-2', 's1', { kind: 'video', assetId: 'rh-9', source: 'imported' }, { silent: true },+ ));+ });+});++describe('MusicVideo scene clip non-MP4 playback (#8978)', () => {+ afterEach(() => {+ // Restore the file-level default so later tests keep seeing the 404+ // (reconstruction-fallback) behavior for 'h1'/'h2'.+ getVideoHistoryItem.mockImplementation((id) => (id === 'rh-9'+ ? Promise.resolve({ id: 'rh-9', filename: 'final.mp4' })+ : Promise.reject(Object.assign(new Error('Not found'), { status: 404 }))));+ });++ it('resolves the clip\'s real stored filename for inline playback instead of assuming .mp4', async () => {+ getVideoHistoryItem.mockImplementation((id) => (id === 'h1'+ ? Promise.resolve({ id: 'h1', filename: 'h1.mov' })+ : Promise.reject(Object.assign(new Error('Not found'), { status: 404 }))));+ await openProject(PROJECT_WITH_CLIP);++ await waitFor(() => expect(document.querySelector('video[src="/data/videos/h1.mov"]')).toBeTruthy());+ expect(document.querySelector('video[src="/data/videos/h1.mp4"]')).toBeNull();+ });});diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex 24c483ee2b..0156aeb8aa 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -88,6 +88,12 @@ export const reviewMusicVideoSceneTake = (id, sceneId, takeId, review, options =// 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);+// The downloadable ZIP counterpart (#8978) — manifest.json plus reference+// images and each scene's selected frame. Resolves to an ArrayBuffer; wrap it+// in downloadBlob(..., 'application/zip') to trigger the save.+export const getMusicVideoHandoffBundle = (id, options = {}) => request(`/music-video/${encodeURIComponent(id)}/handoff/bundle`, {+ responseType: 'arraybuffer', ...options,+});export const importMusicVideoHandoff = (id, body, options = {}) => request(`/music-video/${encodeURIComponent(id)}/handoff/import`, {method: 'POST', body: JSON.stringify(body), ...options,});diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex 9e16bb2858..56684d69f7 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -50,7 +50,7 @@ import {selectSceneTake,reviewSceneTake,} from '../services/musicVideo/projects.js';-import { buildHandoffManifest, matchSceneByFileTag } from '../services/musicVideo/handoff.js';+import { buildHandoffManifest, buildHandoffBundle, matchSceneByFileTag } from '../services/musicVideo/handoff.js';import { getHistoryItem } from '../services/videoGen/history.js';import {startMidiTranscription,@@ -350,6 +350,18 @@ router.get('/:id/handoff', asyncHandler(async (req, res) => {res.json(buildHandoffManifest(project));}));+// Downloadable ZIP counterpart (#8978): the manifest plus every reference+// image and each scene's selected frame, so nothing has to be saved out of+// the gallery by hand before attaching it in the external tool.+router.get('/:id/handoff/bundle', asyncHandler(async (req, res) => {+ const project = await getProject(req.params.id);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const { zip } = await buildHandoffBundle(project);+ res.set('Content-Type', 'application/zip');+ res.set('Content-Disposition', `attachment; filename="music-video-${project.id}-handoff.zip"`);+ res.send(zip);+}));+// 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, isdiff --git a/server/routes/musicVideoTakes.test.js b/server/routes/musicVideoTakes.test.jsindex d96a418fd5..9ee7da4e41 100644--- a/server/routes/musicVideoTakes.test.js+++ b/server/routes/musicVideoTakes.test.js@@ -187,6 +187,25 @@ describe('external-asset handoff', () => {expect(a.referenceImageId).toBe('upload-0001.png');});+ it('serves a downloadable ZIP bundle carrying the manifest plus its reference images', async () => {+ seedImage('ref-mood.png');+ const patched = await request(app).patch(base()).send({+ visualSpec: { references: [{ imageId: 'ref-mood.png', role: 'mood', condition: false }] },+ });+ expect(patched.status).toBe(200);++ const res = await request(app).get(`${base()}/handoff/bundle`);+ expect(res.status).toBe(200);+ expect(res.headers['content-type']).toContain('application/zip');+ expect(res.headers['content-disposition']).toMatch(/attachment; filename=".*\.zip"/);+ // The fetch-based test harness reads the body as text — real ZIP-content+ // assertions (missing-file reporting, per-entry bytes) live in the real+ // file-store service test (handoff.test.js `buildHandoffBundle`); this+ // route test only proves the wiring returns a non-empty ZIP-signed body.+ expect(res.text.slice(0, 2)).toBe('PK');+ expect(res.text.length).toBeGreaterThan(0);+ });+it('round-trips a short hand-authored scene id through its file tag', async () => {const raw = await reload();await projects.mergeProjectsFromSync([{diff --git a/server/services/musicVideo/handoff.js b/server/services/musicVideo/handoff.jsindex aea69699f6..3582a19705 100644--- a/server/services/musicVideo/handoff.js+++ b/server/services/musicVideo/handoff.js@@ -16,6 +16,10 @@* render pins, renderer settings and server paths never leave the install.*/+import { readFile } from 'fs/promises';+import { resolveGalleryImage } from '../../lib/pathSafety.js';+import { createZip } from '../../lib/zipWriter.js';+export const HANDOFF_FORMAT = 'portos.music-video.handoff';export const HANDOFF_VERSION = 1;@@ -123,3 +127,47 @@ export function buildHandoffManifest(project, { now = new Date().toISOString() }})),};}++/**+ * Build the downloadable ZIP counterpart of `buildHandoffManifest` (#8978):+ * the same JSON manifest (with a `missing` list appended) plus the visual+ * spec's reference images and each scene's currently-selected reference+ * frame — so the director doesn't have to save every reference out of the+ * gallery by hand before attaching it in the external tool. A reference or+ * frame this install can't resolve on disk (deleted out from under the+ * record) is reported in `missing` rather than failing the whole download.+ *+ * Returns `{ manifest, zip }` — `manifest` is the JSON actually written into+ * the archive (so a caller/test can inspect `missing` without re-parsing the+ * zip), `zip` is the archive Buffer.+ */+export async function buildHandoffBundle(project) {+ const manifest = buildHandoffManifest(project);+ const files = [];+ const missing = [];+ const seen = new Set();+ const addImage = async (filename, archivePath) => {+ if (!filename || seen.has(archivePath)) return;+ seen.add(archivePath);+ const resolved = resolveGalleryImage(filename);+ if (!resolved) { missing.push({ filename, path: archivePath }); return; }+ try {+ files.push({ name: archivePath, data: await readFile(resolved) });+ } catch {+ missing.push({ filename, path: archivePath });+ }+ };+ for (const ref of manifest.visualSpec.references) {+ await addImage(ref.filename, `references/${ref.filename}`);+ }+ for (const scene of manifest.scenes) {+ const frame = scene.selected?.referenceImageId;+ if (frame) await addImage(frame, `scenes/${scene.fileTag}-${frame}`);+ }+ const bundleManifest = { ...manifest, missing };+ const zip = createZip([+ { name: 'manifest.json', data: JSON.stringify(bundleManifest, null, 2) },+ ...files,+ ]);+ return { manifest: bundleManifest, zip };+}diff --git a/server/services/musicVideo/handoff.test.js b/server/services/musicVideo/handoff.test.jsnew file mode 100644index 0000000000..d11807b845--- /dev/null+++ b/server/services/musicVideo/handoff.test.js@@ -0,0 +1,88 @@+/**+ * Handoff ZIP bundle (#8978) — buildHandoffBundle exercised against the real+ * file-backed project store and the real gallery image directory, so the+ * archive-content and missing-file reporting are proven against actual bytes+ * on disk rather than a mocked resolver.+ */++import { describe, it, expect, vi, afterAll } from 'vitest';+import { mkdirSync, writeFileSync } from 'fs';+import { join } from 'path';+import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../../lib/mockPathsDataRoot.js';+import { collectZipEntries } from '../../lib/zipStream.js';++const ROOT = () => lazyTempDataRoot('mv-handoff-bundle-test-');+vi.mock('../../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), { dataRoot: ROOT }));+vi.mock('../settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));++const projects = await import('./projects.js');+const { buildHandoffBundle } = await import('./handoff.js');++afterAll(cleanupTempDataRoots);++function seedImage(name) {+ mkdirSync(join(ROOT(), 'images'), { recursive: true });+ writeFileSync(join(ROOT(), 'images', name), `bytes-for-${name}`);+}++// Read every entry out of a zip Buffer via a temp file (collectZipEntries+// streams from disk) and return them as { path: string }.+async function readZipEntries(zipBuf) {+ const zipPath = join(ROOT(), `bundle-${Date.now()}.zip`);+ writeFileSync(zipPath, zipBuf);+ const entries = {};+ await collectZipEntries(zipPath, {+ match: () => true,+ onMatch: (buf, entryPath) => { entries[entryPath] = buf; },+ });+ return entries;+}++describe('buildHandoffBundle', () => {+ it('bundles the manifest, every reference image and each scene\'s selected frame, reporting a missing file rather than failing', async () => {+ seedImage('ref-mood.png');+ seedImage('scene-frame.png');+ // 'ref-deleted.png' is referenced but never written to disk.++ const project = await projects.createProject({ name: 'Bundle Test' });+ const scene = await projects.addProjectScene(project.id, { prompt: 'a lighthouse at dusk' });+ await projects.updateProject(project.id, {+ visualSpec: {+ references: [+ { imageId: 'ref-mood.png', role: 'mood', condition: false },+ { imageId: 'ref-deleted.png', role: 'style', condition: false },+ ],+ },+ });+ await projects.updateScene(project.id, scene.sceneId, { referenceImageId: 'scene-frame.png' });+ const stored = await projects.getProject(project.id);++ const { manifest, zip } = await buildHandoffBundle(stored);++ // Missing file reported, not thrown.+ expect(manifest.missing).toEqual([{ filename: 'ref-deleted.png', path: 'references/ref-deleted.png' }]);++ const entries = await readZipEntries(zip);+ expect(Object.keys(entries).sort()).toEqual([+ 'manifest.json',+ 'references/ref-mood.png',+ `scenes/${manifest.scenes[0].fileTag}-scene-frame.png`,+ ].sort());++ expect(entries['references/ref-mood.png'].toString()).toBe('bytes-for-ref-mood.png');+ expect(entries[`scenes/${manifest.scenes[0].fileTag}-scene-frame.png`].toString()).toBe('bytes-for-scene-frame.png');++ // manifest.json inside the zip is the same object buildHandoffBundle returned.+ const manifestInZip = JSON.parse(entries['manifest.json'].toString());+ expect(manifestInZip).toEqual(manifest);+ expect(manifestInZip.format).toBe('portos.music-video.handoff');+ });++ it('never fails for a project with no references or selected frames', async () => {+ const project = await projects.createProject({ name: 'Empty Bundle Test' });+ const { manifest, zip } = await buildHandoffBundle(project);+ expect(manifest.missing).toEqual([]);+ const entries = await readZipEntries(zip);+ expect(Object.keys(entries)).toEqual(['manifest.json']);+ });+});