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
Bring an earlier draft's and unfiled media into a music video's assets (#11567)
[._.]/9ddb94914a6a
diff --git a/client/src/components/musicVideo/stages/AssetsStage.jsx b/client/src/components/musicVideo/stages/AssetsStage.jsxindex 8aed5eb2bc..073a1b7e26 100644--- a/client/src/components/musicVideo/stages/AssetsStage.jsx+++ b/client/src/components/musicVideo/stages/AssetsStage.jsx@@ -1,11 +1,11 @@import { useCallback, useEffect, useState } from 'react';import { useSearchParams } from 'react-router';-import { Activity, Ban, Film, Image as ImageIcon, Pencil, Search, Star, Trash2 } from 'lucide-react';+import { Activity, Ban, Check, Film, FolderInput, Image as ImageIcon, Library, Pencil, Search, Star, Trash2 } from 'lucide-react';import TabPills from '../../ui/TabPills.jsx';import InfiniteScrollFooter from '../../ui/InfiniteScrollFooter.jsx';import { DeleteConfirm, filterPool, poolKey, usedLabel } from '../SceneTakePicker.jsx';import { shotNumbers as numberShots } from '../ShotStepper.jsx';-import { deleteMusicVideoPoolAssets, getMusicVideoMediaPool, markMusicVideoPoolAssets, searchMusicVideoMediaPool } from '../../../services/apiMusicVideo.js';+import { addMusicVideoLibraryMedia, deleteMusicVideoPoolAssets, getMusicVideoMediaPool, importMusicVideoPool, listMusicVideoProjectSummaries, markMusicVideoPoolAssets, searchMusicVideoLibrary, searchMusicVideoMediaPool } from '../../../services/apiMusicVideo.js';import { takeThumbUrl, takeClipUrl } from '../../../lib/musicVideoTakes.js';import { formatCount } from '../../../utils/formatters.js';@@ -33,7 +33,8 @@ const ACTION = 'inline-flex min-h-[44px] items-center gap-1 rounded border borde* with the floor (takes a cut shot or a re-plan left behind) last. Search the* prompts or a shot number, sort them ★ ingredient or ✕ bad, delete bad ones* from the media library (the server refuses anything a shot uses), and jump- * to the shot a file was made for. The open tab and file are in the URL+ * to the shot a file was made for. "Add media from another video" files an+ * earlier draft's stills and clips in too (they land on the floor). The open tab and file are in the URL* (`?kind=clips&asset=<id>`).*/export default function AssetsStage({ board }) {@@ -108,6 +109,23 @@ export default function AssetsStage({ board }) {if (picked && gone.has(poolKey(picked))) setParams({ asset: null });setConfirmDelete(null);});+ // Add media from another video (an earlier draft): its stills and clips join this one's assets and stats outro.+ const [importing, setImporting] = useState(null);+ const [imported, setImported] = useState(null);+ const [librarySearch, setLibrarySearch] = useState(false);+ const openImport = () => {+ setImporting({ projects: null, fromId: '' });+ listMusicVideoProjectSummaries({ limit: 100 }, { silent: true })+ .then((res) => setImporting((prev) => prev && { ...prev, projects: (res.items || []).filter((p) => p.id !== projectId) }))+ .catch((err) => { setImporting(null); setError(err?.message || 'Could not list the other videos'); });+ };+ const runImport = () => run(async () => {+ const from = importing.projects.find((p) => p.id === importing.fromId);+ const result = await importMusicVideoPool(projectId, importing.fromId, { silent: true });+ setPool(result.items || []);+ setImporting(null);+ setImported(`Added ${formatCount(result.added, { fallback: '0' })} stills and clips from ${from?.name || 'that video'}${result.added < result.total ? ` (${formatCount(result.total - result.added)} were already here)` : ''}.`);+ });// A shot using it keeps it: the server refuses to delete it, so it's never offered.const badHere = filter === 'bad' ? items.filter((item) => !inUse(item)) : [];const showMore = useCallback(() => setShown((n) => n + PAGE), []);@@ -174,6 +192,35 @@ export default function AssetsStage({ board }) {<Trash2 size={14} aria-hidden="true" />Delete {formatCount(badHere.length)} bad</button>))}+ {importing ? (+ <div className="flex flex-wrap items-center gap-2 rounded border border-port-border p-2 text-xs">+ <label htmlFor="mv-assets-import" className="shrink-0">Add media from</label>+ <select id="mv-assets-import" value={importing.fromId} disabled={!importing.projects || working}+ onChange={(e) => setImporting((prev) => ({ ...prev, fromId: e.target.value }))}+ className="min-h-[44px] min-w-0 flex-1 basis-48 rounded border border-port-border bg-port-bg px-2 text-sm sm:min-h-[32px]">+ <option value="">{importing.projects ? 'Pick a video' : 'Loading videos…'}</option>+ {(importing.projects || []).map((p) => <option key={p.id} value={p.id}>{p.name || 'Untitled'}{p.version > 1 ? ` (v${p.version})` : ''}</option>)}+ </select>+ <button type="button" disabled={!importing.fromId || working} onClick={runImport}+ className="inline-flex min-h-[44px] items-center gap-1 rounded bg-port-accent px-3 font-medium text-white disabled:opacity-50 sm:min-h-[32px]">+ {working && <Activity size={14} className="animate-spin" />}Add+ </button>+ <button type="button" disabled={working} onClick={() => setImporting(null)} className={ACTION}>Cancel</button>+ </div>+ ) : librarySearch ? (+ <LibraryAdd projectId={projectId} onCancel={() => setLibrarySearch(false)}+ onAdded={(result) => { setPool(result.items || []); setLibrarySearch(false); setImported(`Added ${formatCount(result.added, { fallback: '0' })} from the media library.`); }} />+ ) : (+ <div className="flex flex-wrap gap-2">+ <button type="button" onClick={() => { setImported(null); openImport(); }} className={ACTION}>+ <FolderInput size={14} aria-hidden="true" />Add media from another video+ </button>+ <button type="button" onClick={() => { setImported(null); setLibrarySearch(true); }} className={ACTION}>+ <Library size={14} aria-hidden="true" />Add from the media library+ </button>+ </div>+ )}+ {imported && <p role="status" className="text-xs text-port-success">{imported}</p>}{error && <p role="alert" className="text-xs text-port-error">{error}</p>}{!pool && !error && <p className="flex items-center gap-2 text-xs text-port-text-muted"><Activity size={14} className="animate-spin" />Gathering every still and clip made for this video…</p>}{pool && items.length === 0 && (@@ -209,3 +256,85 @@ export default function AssetsStage({ board }) {</div>);}++/**+ * "Add from the media library": stills and clips made for the video but never+ * filed under it (rendered before renders named their video). Search the+ * prompts, tap to pick (or Pick all), then Add.+ */+function LibraryAdd({ projectId, onAdded, onCancel }) {+ const [query, setQuery] = useState('');+ const [found, setFound] = useState(null);+ const [picked, setPicked] = useState(() => new Set());+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState(null);++ useEffect(() => {+ const q = query.trim();+ setFound(null); setPicked(new Set());+ if (!q) return undefined;+ let active = true;+ const timer = setTimeout(() => {+ searchMusicVideoLibrary(projectId, q, { silent: true })+ .then((res) => { if (active) setFound(res); })+ .catch((err) => { if (active) setError(err?.message || 'Search failed'); });+ }, 300);+ return () => { active = false; clearTimeout(timer); };+ }, [projectId, query]);++ const toggle = (key) => setPicked((prev) => { const next = new Set(prev); if (next.has(key)) next.delete(key); else next.add(key); return next; });+ const items = found?.items || [];+ const add = () => {+ setBusy(true); setError(null);+ addMusicVideoLibraryMedia(projectId, items.filter((item) => picked.has(poolKey(item))).map(({ kind, assetId }) => ({ kind, assetId })), { silent: true })+ .then(onAdded)+ .catch((err) => setError(err?.message || 'Could not add them'))+ .finally(() => setBusy(false));+ };++ return (+ <div className="space-y-2 rounded border border-port-border p-2">+ <label htmlFor="mv-assets-library" className="flex items-center gap-2 rounded border border-port-border bg-port-bg px-2">+ <Library size={14} aria-hidden="true" className="shrink-0 text-port-text-muted" />+ <span className="sr-only">Search the media library by prompt</span>+ <input id="mv-assets-library" type="search" value={query} onChange={(e) => setQuery(e.target.value)} autoFocus+ placeholder="Search the media library by prompt" className="min-h-[44px] min-w-0 flex-1 bg-transparent text-sm outline-none sm:min-h-[32px]" />+ </label>+ <div className="flex flex-wrap items-center gap-2 text-xs">+ <span className="min-w-0 flex-1 text-port-text-muted">+ {!query.trim() ? 'Media not in this video yet.' : !found ? 'Searching…'+ : `${formatCount(items.length, { fallback: '0' })}${found.more ? '+' : ''} not in this video yet`}+ </span>+ {items.length > 0 && (+ <button type="button" disabled={busy} onClick={() => setPicked(picked.size === items.length ? new Set() : new Set(items.map(poolKey)))} className={ACTION}>+ {picked.size === items.length ? 'Pick none' : 'Pick all'}+ </button>+ )}+ <button type="button" disabled={!picked.size || busy} onClick={add}+ className="inline-flex min-h-[44px] items-center gap-1 rounded bg-port-accent px-3 font-medium text-white disabled:opacity-50 sm:min-h-[32px]">+ {busy && <Activity size={14} className="animate-spin" />}Add {formatCount(picked.size, { fallback: '0' })}+ </button>+ <button type="button" disabled={busy} onClick={onCancel} className={ACTION}>Cancel</button>+ </div>+ {error && <p role="alert" className="text-xs text-port-error">{error}</p>}+ {items.length > 0 && (+ <ul className="grid max-h-[60vh] grid-cols-3 gap-2 overflow-y-auto sm:grid-cols-4 lg:grid-cols-6" aria-label="Media library matches">+ {items.map((item) => {+ const key = poolKey(item);+ const on = picked.has(key);+ return (+ <li key={key}>+ <button type="button" onClick={() => toggle(key)} aria-pressed={on} aria-label={`${NOUN[item.kind]}: ${String(item.prompt || '').slice(0, 80)}`}+ className={`relative block w-full overflow-hidden rounded border ${on ? 'border-port-accent ring-2 ring-port-accent' : 'border-port-border'}`}>+ <img src={takeThumbUrl(item)} alt="" loading="lazy" className="block aspect-video w-full bg-black object-cover" />+ {item.kind === 'video' && <span className="port-media-overlay-strong absolute bottom-1 right-1 inline-flex items-center gap-0.5 rounded px-1 text-[10px] leading-tight"><Film size={10} aria-hidden="true" />clip</span>}+ {on && <span className="port-media-overlay-strong absolute right-1 top-1 rounded p-0.5 text-port-accent"><Check size={12} aria-hidden="true" /></span>}+ </button>+ </li>+ );+ })}+ </ul>+ )}+ </div>+ );+}diff --git a/client/src/components/musicVideo/stages/AssetsStage.test.jsx b/client/src/components/musicVideo/stages/AssetsStage.test.jsxindex 1af1c24bfe..09de18bbb5 100644--- a/client/src/components/musicVideo/stages/AssetsStage.test.jsx+++ b/client/src/components/musicVideo/stages/AssetsStage.test.jsx@@ -14,6 +14,10 @@ vi.mock('../../../services/apiMusicVideo.js', () => ({markMusicVideoPoolAssets: vi.fn(async () => ({ assetMarks: { 'image:early.png': 'bad' } })),deleteMusicVideoPoolAssets: vi.fn(async () => ({ deleted: 1 })),searchMusicVideoMediaPool: vi.fn(async () => ({ items: [] })),+ listMusicVideoProjectSummaries: vi.fn(async () => ({ items: [{ id: 'mv-1', name: 'This video' }, { id: 'mv-draft', name: 'Early draft' }] })),+ searchMusicVideoLibrary: vi.fn(async () => ({ items: [{ kind: 'image', assetId: 'sheet.png', prompt: 'Director sheet' }, { kind: 'video', assetId: 'old-clip', prompt: 'Director turns' }], more: false })),+ addMusicVideoLibraryMedia: vi.fn(async () => ({ added: 1, items: [...pool, { kind: 'image', assetId: 'sheet.png', sceneId: null, clipIds: [] }] })),+ importMusicVideoPool: vi.fn(async () => ({ added: 2, total: 3, items: [...pool, { kind: 'image', assetId: 'draft.png', sceneId: null, clipIds: [] }] })),}));const { default: AssetsStage } = await import('./AssetsStage.jsx');const api = await import('../../../services/apiMusicVideo.js');@@ -49,4 +53,29 @@ describe('Music video Assets page', () => {fireEvent.click(screen.getByRole('button', { name: 'Open shot 1' }));expect(onEditShot).toHaveBeenCalledWith('s1');});++ // Uniquely catches the import offering this video as its own source, or the page not showing what it filed.+ it('adds an earlier draft\'s media from a picker of the other videos', async () => {+ renderPage();+ fireEvent.click(await screen.findByRole('button', { name: 'Add media from another video' }));+ const picker = screen.getByLabelText('Add media from');+ await waitFor(() => expect(within(picker).getAllByRole('option').map((o) => o.textContent)).toEqual(['Pick a video', 'Early draft']));+ fireEvent.change(picker, { target: { value: 'mv-draft' } });+ fireEvent.click(screen.getByRole('button', { name: 'Add' }));+ await waitFor(() => expect(api.importMusicVideoPool).toHaveBeenCalledWith('mv-1', 'mv-draft', { silent: true }));+ expect(await screen.findByText('Added 2 stills and clips from Early draft (1 were already here).')).toBeTruthy();+ await waitFor(() => expect(tiles()).toHaveLength(5));+ });++ // Uniquely catches the library add sending files that weren't picked, or the page not showing what it filed.+ it('adds picked media from a library prompt search', async () => {+ renderPage();+ fireEvent.click(await screen.findByRole('button', { name: 'Add from the media library' }));+ fireEvent.change(screen.getByLabelText('Search the media library by prompt'), { target: { value: 'director' } });+ fireEvent.click(await screen.findByRole('button', { name: 'still: Director sheet' }));+ fireEvent.click(screen.getByRole('button', { name: 'Add 1' }));+ await waitFor(() => expect(api.addMusicVideoLibraryMedia).toHaveBeenCalledWith('mv-1', [{ kind: 'image', assetId: 'sheet.png' }], { silent: true }));+ expect(await screen.findByText('Added 1 from the media library.')).toBeTruthy();+ await waitFor(() => expect(tiles()).toHaveLength(5));+ });});diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex c46594bad0..eaeb18fe14 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -191,6 +191,17 @@ export const markMusicVideoPoolAssets = (id, items, mark, options = {}) => requeexport const deleteMusicVideoPoolAssets = (id, items, options = {}) => request(`/music-video/${encodeURIComponent(id)}/media-pool/delete`, {method: 'POST', body: JSON.stringify({ items }), ...options,});+// Asset manager: file another video's whole pool (an earlier draft) into this one → { added, total, items }.+export const importMusicVideoPool = (id, fromProjectId, options = {}) => request(`/music-video/${encodeURIComponent(id)}/media-pool/import`, {+ method: 'POST', body: JSON.stringify({ fromProjectId }), ...options,+});+// Asset manager: library stills and clips whose prompts hold every word, not in this video yet → { items, more }.+export const searchMusicVideoLibrary = (id, q, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/media-pool/library?q=${encodeURIComponent(q)}`, options);+// Asset manager: file library stills and clips into this video → { added, items }.+export const addMusicVideoLibraryMedia = (id, items, options = {}) => request(`/music-video/${encodeURIComponent(id)}/media-pool/add`, {+ method: 'POST', body: JSON.stringify({ items }), ...options,+});// Put a pool still or clip on a shot as its selection; `withAssetId` brings its partner → { scene }.export const placeMusicVideoPoolItem = (id, sceneId, body, options = {}) => request(`${takesPath(id, sceneId)}/use`, {method: 'POST', body: JSON.stringify(body), ...options,diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex d03bc2c598..d1ee1d59da 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -348,6 +348,21 @@ export const musicVideoPoolDeleteSchema = z.object({items: z.array(musicVideoPoolAssetSchema).min(1).max(500),}).strict();+/** File another music video's whole pool (an earlier draft) into this video's collection. */+export const musicVideoPoolImportSchema = z.object({+ fromProjectId: z.string().min(1).max(200),+}).strict();++/** Search the whole media library for stills and clips to add to a video's assets. */+export const musicVideoLibrarySearchQuerySchema = z.object({+ q: z.string().trim().min(1).max(200),+}).strict();++/** File stills and clips from the media library into a video's assets. */+export const musicVideoPoolAddSchema = z.object({+ items: z.array(musicVideoPoolAssetSchema).min(1).max(500),+}).strict();+// Put an unused still or clip from the project's pool on a shot; `withAssetId` is its partner (a still's clip, a clip's still).// `endImage` puts a still on the shot's end frame; only a start still pairs with a clip.export const musicVideoPoolUseSchema = z.object({diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex 845c25b1bb..ee0d4807d1 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -12,7 +12,7 @@ import { existsSync } from 'fs';import { unlink } from 'fs/promises';import { pipeline } from 'stream/promises';import { Router } from 'express';-import { musicVideoSongStyleSunoSchema, musicVideoProjectListQuerySchema, musicVideoFinishedOutsideSchema, musicVideoProductionDraftSchema, musicVideoProductionApprovalSchema, musicVideoShotLockSchema, musicVideoProductionProofSchema, musicVideoProductionImportSchema, musicVideoContinueShotSchema, musicVideoPoolUseSchema, musicVideoPoolMarkSchema, musicVideoPoolSearchQuerySchema, musicVideoPoolDeleteSchema, musicVideoProductionFeedbackSchema, musicVideoProductionFeedbackResolutionSchema, musicVideoLyricAnchorSyncSchema, musicVideoProductionReviseSchema, musicVideoProductionRevertSchema } from '../lib/musicVideoValidation.js';+import { musicVideoSongStyleSunoSchema, musicVideoProjectListQuerySchema, musicVideoFinishedOutsideSchema, musicVideoProductionDraftSchema, musicVideoProductionApprovalSchema, musicVideoShotLockSchema, musicVideoProductionProofSchema, musicVideoProductionImportSchema, musicVideoContinueShotSchema, musicVideoPoolUseSchema, musicVideoPoolMarkSchema, musicVideoPoolSearchQuerySchema, musicVideoPoolDeleteSchema, musicVideoPoolImportSchema, musicVideoLibrarySearchQuerySchema, musicVideoPoolAddSchema, musicVideoProductionFeedbackSchema, musicVideoProductionFeedbackResolutionSchema, musicVideoLyricAnchorSyncSchema, musicVideoProductionReviseSchema, musicVideoProductionRevertSchema } from '../lib/musicVideoValidation.js';import { productionReadiness } from '../services/musicVideo/productionReview.js';import { finishedOutsideBlocker } from '../lib/musicVideoFinishedOutside.js';import { getProductionReview, saveProductionDraft, prepareProductionReview, approveProductionReview, lockProductionShots, renderProductionProof, requireProductionReviewer, importProductionPlanning, bindProductionShot, addProductionFeedback, closeProductionFeedback, syncLyricAnchors, removeStaleStoryboardRows, reviseProductionFromFeedback, revertProductionInput } from '../services/musicVideo/productionReviewService.js';@@ -1584,6 +1584,35 @@ router.patch('/:id/media-pool/marks', asyncHandler(async (req, res) => {res.json(await markMediaPoolAssets(req.params.id, items.map((item) => `${item.kind}:${item.assetId}`), mark));}));+// Bring an earlier draft's stills and clips into this video's assets (references; the draft is untouched).+router.post('/:id/media-pool/import', asyncHandler(async (req, res) => {+ const { fromProjectId } = validateRequest(musicVideoPoolImportSchema, req.body);+ if (fromProjectId === req.params.id) throw new ServerError('Pick another video', { status: 400, code: 'VALIDATION_ERROR' });+ const [project, from] = await Promise.all([getProject(req.params.id), getProject(fromProjectId)]);+ if (!project || !from) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const { importMusicVideoPool, getMusicVideoMediaPool } = await import('../services/musicVideo/mediaPool.js');+ const result = await importMusicVideoPool(project, from);+ res.json({ ...result, items: (await getMusicVideoMediaPool(project)).items });+}));++// Media made for this video but never filed: search the whole library by prompt, then add picks.+router.get('/:id/media-pool/library', asyncHandler(async (req, res) => {+ const { q } = validateRequest(musicVideoLibrarySearchQuerySchema, req.query);+ const project = await getProject(req.params.id);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const { searchMediaLibraryForPool } = await import('../services/musicVideo/mediaPool.js');+ res.json(await searchMediaLibraryForPool(project, q));+}));++router.post('/:id/media-pool/add', asyncHandler(async (req, res) => {+ const { items } = validateRequest(musicVideoPoolAddSchema, req.body);+ const project = await getProject(req.params.id);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const { addLibraryMediaToPool, getMusicVideoMediaPool } = await import('../services/musicVideo/mediaPool.js');+ const result = await addLibraryMediaToPool(project, items);+ res.json({ ...result, items: (await getMusicVideoMediaPool(project)).items });+}));+router.post('/:id/media-pool/delete', asyncHandler(async (req, res) => {const { items } = validateRequest(musicVideoPoolDeleteSchema, req.body);const project = await getProject(req.params.id);diff --git a/server/routes/musicVideoTakes.test.js b/server/routes/musicVideoTakes.test.jsindex 80f0116851..a968dc9bde 100644--- a/server/routes/musicVideoTakes.test.js+++ b/server/routes/musicVideoTakes.test.js@@ -677,3 +677,58 @@ describe('pool deletion and selection admission', () => {expect((await reload()).name).toBe('Queue recovered');});});++describe('media from an earlier draft', () => {+ // Uniquely catches an import that copies nothing the draft's shots hold, skips the stats tally, or restamps the draft's clips.+ it('files the draft\'s stills and clips into this video\'s assets and stats, leaving the draft as it was', async () => {+ for (const name of ['draft-still.png', 'draft-floor.png', 'mine.png']) seedImage(name);+ seedVideoHistory([{ id: 'draft-clip', filename: 'draft-clip.mp4', prompt: 'draft motion' }]);+ await addTake(sceneA.sceneId, { kind: 'image', assetId: 'mine.png', source: 'generated' });+ const draft = await projects.createProject({ name: 'Example Draft' });+ const draftShot = await projects.addProjectScene(draft.id, { prompt: 'an early idea' });+ const draftTake = (body) => request(app).post(`/api/music-video/${draft.id}/scenes/${draftShot.sceneId}/takes`).send(body);+ await draftTake({ kind: 'image', assetId: 'draft-still.png', source: 'generated' });+ await draftTake({ kind: 'image', assetId: 'draft-floor.png', source: 'generated' });+ await draftTake({ kind: 'video', assetId: 'draft-clip', source: 'generated' });+ await draftTake({ kind: 'image', assetId: 'mine.png', source: 'generated' });++ const imported = await request(app).post(`${base()}/media-pool/import`).send({ fromProjectId: draft.id });+ expect(imported.status).toBe(200);+ expect(imported.body).toMatchObject({ added: 3, total: 4 });+ const fromDraft = imported.body.items.filter((item) => item.assetId.startsWith('draft-'));+ expect(fromDraft.map((item) => `${item.kind}:${item.assetId}`).sort()).toEqual(['image:draft-floor.png', 'image:draft-still.png', 'video:draft-clip']);+ expect(fromDraft.every((item) => item.sceneId === null && item.inUseBy.length === 0)).toBe(true);+ // Again is a no-op.+ expect((await request(app).post(`${base()}/media-pool/import`).send({ fromProjectId: draft.id })).body).toMatchObject({ added: 0 });++ const stats = (await request(app).get(`${base()}/stats-outro`)).body.stats;+ expect(stats.stills.made).toBe(3);+ expect(stats.clips.made).toBe(1);+ const { loadHistory } = await import('../services/videoGen/history.js');+ expect((await loadHistory()).find((entry) => entry.id === 'draft-clip').musicVideo.projectId).toBe(draft.id);+ expect((await request(app).post(`${base()}/media-pool/import`).send({ fromProjectId: project.id })).status).toBe(400);+ expect((await request(app).post(`${base()}/media-pool/import`).send({ fromProjectId: 'mv-missing' })).status).toBe(404);+ });+});++describe('media from the library', () => {+ // Uniquely catches a library search offering files already in the video, missing a clip, or an add that files nothing.+ it('finds unfiled stills and clips by prompt and adds the picks to this video\'s assets', async () => {+ for (const name of ['sheet.png', 'filed.png', 'other.png']) seedImage(name);+ writeFileSync(join(ROOT(), 'images', 'sheet.metadata.json'), JSON.stringify({ prompt: 'Character reference sheet for The Director', createdAt: '2026-01-02T00:00:00Z' }));+ writeFileSync(join(ROOT(), 'images', 'filed.metadata.json'), JSON.stringify({ prompt: 'The Director at her desk' }));+ writeFileSync(join(ROOT(), 'images', 'other.metadata.json'), JSON.stringify({ prompt: 'A mountain lake' }));+ seedVideoHistory([{ id: 'director-clip', filename: 'director-clip.mp4', prompt: 'The director turns', createdAt: '2026-01-03T00:00:00Z' }]);+ await addTake(sceneA.sceneId, { kind: 'image', assetId: 'filed.png', source: 'generated' });++ const found = await request(app).get(`${base()}/media-pool/library?q=${encodeURIComponent('director')}`);+ expect(found.body.items.map((item) => `${item.kind}:${item.assetId}`)).toEqual(['video:director-clip', 'image:sheet.png']);+ expect((await request(app).get(`${base()}/media-pool/library?q=`)).status).toBe(400);++ const added = await request(app).post(`${base()}/media-pool/add`).send({ items: found.body.items.map(({ kind, assetId }) => ({ kind, assetId })) });+ expect(added.body.added).toBe(2);+ expect(added.body.items.map((item) => item.assetId).sort()).toEqual(['director-clip', 'filed.png', 'sheet.png']);+ expect((await request(app).get(`${base()}/media-pool/library?q=director`)).body.items).toEqual([]);+ expect((await request(app).post(`${base()}/media-pool/add`).send({ items: [{ kind: 'image', assetId: 'missing.png' }] })).status).toBe(400);+ });+});diff --git a/server/services/musicVideo/mediaPool.js b/server/services/musicVideo/mediaPool.jsindex 9d6d207abd..1f7a5bda48 100644--- a/server/services/musicVideo/mediaPool.js+++ b/server/services/musicVideo/mediaPool.js@@ -250,6 +250,74 @@ export async function getMusicVideoMediaPool(project) {return { collectionId: collection?.id || null, items };}+/**+ * File every still and clip of another video's pool (an earlier draft of the+ * same song) into `project`'s collection, so its Assets page and stats outro+ * count them. References only: no file is copied, the other video is not+ * changed, and its clips keep their own provenance stamp. Resolves+ * `{ added, total }`: how many were new here, of the other video's pool.+ */+export async function importMusicVideoPool(project, fromProject) {+ const [{ findOrCreateMusicVideoCollection, bulkUpdateCollectionItems }, { items }] = await Promise.all([+ import('../mediaCollections.js'), getMusicVideoMediaPool(fromProject),+ ]);+ const collection = await findOrCreateMusicVideoCollection({ projectId: project.id, projectName: project.name });+ const present = new Set([...collection.items.map((item) => `${item.kind}:${item.ref}`),+ ...projectTakeAssets(project).map((asset) => `${asset.kind}:${asset.ref}`)]);+ const add = items.filter((item) => !present.has(`${item.kind}:${item.assetId}`)+ && !item.assetId.includes(':') && !item.assetId.includes('/'))+ .map((item) => ({ kind: item.kind, ref: item.assetId }));+ if (add.length) await bulkUpdateCollectionItems(collection.id, { add });+ console.log(`🗂️ music-video media pool: filed ${add.length} of ${items.length} item(s) from ${fromProject.id} into ${project.id}`);+ return { added: add.length, total: items.length };+}++const LIBRARY_MATCH_MAX = 300;++/**+ * Stills and clips in the whole media library whose prompts hold every word of+ * `query` and that are not in `project`'s pool yet: media made for the video+ * but never filed (rendered before renders named their video). Newest first,+ * at most 300: `{ items: [{ kind, assetId, prompt, createdAt }], more }`.+ */+export async function searchMediaLibraryForPool(project, query) {+ const words = String(query).toLowerCase().split(/\s+/).filter(Boolean);+ if (!words.length) return { items: [], more: false };+ const [{ items: pool }, { listGallery }, { loadHistory }] = await Promise.all([+ getMusicVideoMediaPool(project), import('../imageGen/local.js'), import('../videoGen/history.js'),+ ]);+ const inPool = new Set(pool.map((item) => `${item.kind}:${item.assetId}`));+ const matches = (prompt) => typeof prompt === 'string' && words.every((word) => prompt.toLowerCase().includes(word));+ const found = [+ ...(await listGallery()).filter((image) => matches(image.prompt) && !inPool.has(`image:${image.filename}`))+ .map((image) => ({ kind: 'image', assetId: image.filename, prompt: image.prompt, createdAt: image.createdAt || null })),+ ...(await loadHistory()).filter((entry) => entry?.id && matches(entry.prompt) && !inPool.has(`video:${entry.id}`))+ .map((entry) => ({ kind: 'video', assetId: entry.id, prompt: entry.prompt, createdAt: entry.createdAt || null })),+ ].sort((a, b) => String(b.createdAt || '').localeCompare(String(a.createdAt || '')));+ return { items: found.slice(0, LIBRARY_MATCH_MAX), more: found.length > LIBRARY_MATCH_MAX };+}++/**+ * File stills and clips from the media library into `project`'s collection+ * (the Assets page's "Add from the library"). Only files the library holds;+ * a clip keeps whatever provenance stamp it has. Resolves `{ added }`.+ */+export async function addLibraryMediaToPool(project, items) {+ const [{ findOrCreateMusicVideoCollection, bulkUpdateCollectionItems }, { resolveGalleryImage }, { getHistoryItem }, { ServerError }] = await Promise.all([+ import('../mediaCollections.js'), import('../../lib/pathSafety.js'), import('../videoGen/history.js'), import('../../lib/errorHandler.js'),+ ]);+ for (const { kind, assetId } of items) {+ const exists = kind === 'image' ? resolveGalleryImage(assetId) : await getHistoryItem(assetId);+ if (!exists) throw new ServerError(`${kind === 'image' ? 'Image' : 'Video'} not found in this install's media library`, { status: 400, code: 'TAKE_ASSET_NOT_FOUND' });+ }+ const collection = await findOrCreateMusicVideoCollection({ projectId: project.id, projectName: project.name });+ const present = new Set(collection.items.map((item) => `${item.kind}:${item.ref}`));+ const add = [...new Map(items.filter(({ kind, assetId }) => !present.has(`${kind}:${assetId}`))+ .map(({ kind, assetId }) => [`${kind}:${assetId}`, { kind, ref: assetId }])).values()];+ if (add.length) await bulkUpdateCollectionItems(collection.id, { add });+ return { added: add.length };+}+/*** The pool items (`{ kind, assetId }`) whose prompts hold every word of `query`, case-insensitively:* the take's prompt, the prompt saved beside a still (its image sidecar) and a clip's history prompt.