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
Music video: Previous / Next shot buttons, and Swap lists frames other shots use (#11458)
[._.]/20cb55bfd75b
diff --git a/client/src/components/musicVideo/SceneCard.jsx b/client/src/components/musicVideo/SceneCard.jsxindex c5a7b62112..d62cbceb27 100644--- a/client/src/components/musicVideo/SceneCard.jsx+++ b/client/src/components/musicVideo/SceneCard.jsx@@ -6,7 +6,7 @@ import SceneClipTiming from './SceneClipTiming.jsx';import SceneRejectUnused from './SceneRejectUnused.jsx';import { MUSIC_VIDEO_MEDIUM_LABELS } from '../../../../server/lib/musicVideoMediumPlan.js';import { useEffect, useRef, useState } from 'react';-import { Trash2, Activity, ArrowUp, ArrowDown, ChevronRight, Video, Maximize2, AlertTriangle, Clapperboard, Shuffle } from 'lucide-react';+import { Trash2, Activity, ArrowUp, ArrowDown, ChevronLeft, ChevronRight, Video, Maximize2, AlertTriangle, Clapperboard, Shuffle } from 'lucide-react';import OverflowMenu from '../ui/OverflowMenu.jsx';import SceneTakePicker from './SceneTakePicker.jsx';import VideoStartTrimControl from '../media/VideoStartTrimControl.jsx';@@ -117,7 +117,7 @@ export default function SceneCard({project = null, onGenerateFrame, onGenerateVideo, onContinueVideo, onGenerateEndFrame, generatingEndFrame = false, onContinueFromPrevious, previousHasClip = false,onOpenPreview, onSelectTake, onReviewTake, onRejectUnusedTakes = null, onSwapFrames = null, onMarkTake = null, onImportTake, onImportClipTake, onPlacePoolItem, onTrimClip, projectId = null, aspect = '16:9', videoModels = [], defaultVideoModel = '', shotNumbers = undefined, takeBusy = false, layered = false, documentComposition = false,lipSyncBackend = '', songDurationSec = null, onSplit, onMergeNext, onMoveStart = null, nextEndSec = null, falVideoSettings = null, onSeek, performanceReview = null, onRepairPerformance, repairBusy = false,- expanded, onToggleExpand, footageOptional = false, failedScenes = null, songReview = null,+ expanded, onToggleExpand, stepShot = null, footageOptional = false, failedScenes = null, songReview = null,}) {const detailsRef = useRef(null);@@ -396,7 +396,7 @@ export default function SceneCard({><summaryonClick={() => onSeek?.(scene)}- className="flex min-h-[44px] cursor-pointer select-none items-center gap-3 p-2 marker:content-none flex-wrap group-open:pr-40 sm:group-open:pr-52 [&::-webkit-details-marker]:hidden"+ className="flex min-h-[44px] cursor-pointer select-none items-center gap-3 p-2 marker:content-none flex-wrap group-open:pr-52 sm:group-open:pr-72 [&::-webkit-details-marker]:hidden"><ChevronRight size={14} aria-hidden="true" className="shrink-0 text-port-text-muted transition-transform group-open:rotate-90" /><ScenePoster scene={scene} iconSize={14} className="aspect-video w-16 shrink-0 rounded border border-port-border sm:w-20 max-sm:group-open:hidden" />@@ -440,6 +440,18 @@ export default function SceneCard({{/* The open card's lock and "…" menu sit in its top-right corner. A move swaps thisshot with its neighbor; the song timing and lyric stay with the slot. */}<div className="absolute right-2 top-2 z-10 flex items-center gap-1">+ {stepShot && (+ <>+ <button type="button" onClick={stepShot.prev || undefined} disabled={!stepShot.prev} aria-label="Previous shot" title="Previous shot"+ className="inline-flex min-h-[44px] min-w-[44px] items-center justify-center rounded-lg border border-port-border text-port-text hover:bg-port-border disabled:opacity-40 sm:min-h-[32px] sm:min-w-[32px]">+ <ChevronLeft size={16} aria-hidden="true" />+ </button>+ <button type="button" onClick={stepShot.next || undefined} disabled={!stepShot.next} aria-label="Next shot" title="Next shot"+ className="inline-flex min-h-[44px] min-w-[44px] items-center justify-center rounded-lg border border-port-border text-port-text hover:bg-port-border disabled:opacity-40 sm:min-h-[32px] sm:min-w-[32px]">+ <ChevronRight size={16} aria-hidden="true" />+ </button>+ </>+ )}<ShotLockButton scene={scene} compact /><OverflowMenu label="Shot actions" items={[{ id: 'earlier', label: 'Move earlier', icon: ArrowUp, onSelect: () => onMove(index, -1), disabled: index === 0 || documentComposition },diff --git a/client/src/components/musicVideo/SceneTakePicker.jsx b/client/src/components/musicVideo/SceneTakePicker.jsxindex 95a0f638be..40701d7efd 100644--- a/client/src/components/musicVideo/SceneTakePicker.jsx+++ b/client/src/components/musicVideo/SceneTakePicker.jsx@@ -9,13 +9,14 @@ import { formatCount } from '../../utils/formatters.js';const PAGE = 60;const SLOT_NOUN = { image: 'still', video: 'clip', endImage: 'end frame' };-// An end frame is picked from the same unused stills as a start frame.+// An end frame is picked from the same stills as a start frame.const POOL_KIND = { image: 'image', video: 'video', endImage: 'image' };+const SLOT_FIELD = { image: 'referenceImageId', video: 'videoHistoryId', endImage: 'endImageId' };/** Which tab a pool item belongs on for this shot: its own takes, another shot's, or the floor. */export const poolGroup = (item, sceneId) => (!item.sceneId ? 'floor' : item.sceneId === sceneId ? 'shot' : 'others');-// The director's sort of unused assets: ★ ingredients (good, not placed), unsorted, ✕ bad (to clean up).+// The director's sort of the video's assets: ★ ingredients (good, not placed), unsorted, ✕ bad (to clean up).const MARK_FILTERS = [{ id: 'all', label: 'All' }, { id: 'ingredient', label: '★ Ingredients' }, { id: 'unsorted', label: 'Unsorted' }, { id: 'bad', label: '✕ Bad' },];@@ -25,8 +26,8 @@ const OTHER_FRAME = { image: { field: 'endImageId', takeKind: 'endImage', promptendImage: { field: 'referenceImageId', takeKind: 'image', prompt: 'framePrompt', label: 'Start frame' } };/**- * The shot's frame in the other slot as a pool item, or null. The pool lists only- * unused stills, and that frame is in use, so it is added here, listed first on This shot.+ * The shot's frame in the other slot as a pool item, or null: labeled and listed+ * first on This shot, in place of its plain pool entry.*/function otherFrameItem(scene, kind) {const other = OTHER_FRAME[kind];@@ -36,6 +37,11 @@ function otherFrameItem(scene, kind) {return { kind: 'image', assetId, sceneId: scene.sceneId, prompt: take?.prompt || scene[other.prompt] || null, clipIds: [], ownFrame: other.label };}const poolKey = (item) => `${item.kind}:${item.assetId}`;+/** "Used on #3, #12" for an item other shots (or this one) use now, else null. */+const usedLabel = (item, shotNumbers) => {+ const numbers = (item.inUseBy || []).map((id) => shotNumbers.get(id)).filter(Boolean);+ return item.inUseBy?.length ? `Used on ${numbers.length ? numbers.map((n) => `#${n}`).join(', ') : 'a shot'}` : null;+};const CHIP = 'min-h-[44px] rounded border px-2 text-xs sm:min-h-[28px]';const ACTION = 'inline-flex min-h-[44px] items-center gap-1 rounded border border-port-border px-3 text-xs disabled:opacity-50 sm:min-h-[32px]';@@ -48,9 +54,9 @@ export function filterPool(items, { kind, query, shotNumbers }) {}/**- * "Swap from unused": every still (or clip) generated for this video that no- * shot uses now, as a searchable contact sheet in three tabs: this shot's- * other takes, other shots' unused takes, and the floor (takes a cut shot, a+ * "Swap": every still (or clip) generated for this video, as a searchable+ * contact sheet in three tabs: this shot's other takes, other shots' takes+ * (one another shot uses is marked "In use"), and the floor (takes a cut shot, a* re-plan or a merge left behind). Tap one to see it full size, then use it,* or use it with its partner: a still's rendered clip, or a clip's still.* `kind: 'endImage'` picks a still for the shot's end frame, on its own.@@ -86,12 +92,15 @@ export default function SceneTakePicker({ open, onClose, projectId, scene, kind,const groups = new Set(items.filter((item) => item.kind === POOL_KIND[kind]).map((item) => poolGroup(item, scene.sceneId)));setGroup(hasOwnFrame ? 'shot' : ['shot', 'others', 'floor'].find((g) => groups.has(g)) || 'shot');})- .catch((err) => { if (active) setError(err?.message || 'Could not load the unused takes'); });+ .catch((err) => { if (active) setError(err?.message || 'Could not load the takes'); });return () => { active = false; };}, [open, projectId, scene.sceneId, kind, hasOwnFrame]);const own = pool ? otherFrameItem(scene, kind) : null;- const ofKind = pool ? filterPool([...(own ? [own] : []), ...pool.filter((item) => !own || poolKey(item) !== poolKey(own))],+ // What already fills this slot isn't offered back; a frame other shots use is, marked with where it's used.+ const current = scene[SLOT_FIELD[kind]];+ const offered = pool ? pool.filter((item) => (!own || poolKey(item) !== poolKey(own)) && !(item.kind === POOL_KIND[kind] && item.assetId === current)) : [];+ const ofKind = pool ? filterPool([...(own ? [own] : []), ...offered],{ kind: POOL_KIND[kind], query, shotNumbers }) : [];const counts = { shot: 0, others: 0, floor: 0 };for (const item of ofKind) counts[poolGroup(item, scene.sceneId)] += 1;@@ -123,7 +132,8 @@ export default function SceneTakePicker({ open, onClose, projectId, scene, kind,setPicked((prev) => (prev && gone.has(poolKey(prev)) ? null : prev));setConfirmDelete(null);});- const badHere = markFilter === 'bad' ? items : [];+ // A shot using it keeps it: the server refuses to delete it, so it's never offered.+ const badHere = markFilter === 'bad' ? items.filter((item) => !item.inUseBy?.length) : [];// The next page loads when the bottom of the grid scrolls into view.const showMore = useCallback(() => setShown((n) => n + PAGE), []);@@ -159,6 +169,7 @@ export default function SceneTakePicker({ open, onClose, projectId, scene, kind,{kind === 'video'? <video key={picked.assetId} src={takeClipUrl(picked)} poster={takeThumbUrl(picked)} controls autoPlay muted loop playsInline className="w-full aspect-video rounded bg-black object-contain" />: <img src={takeThumbUrl(picked)} alt="" className="w-full aspect-video rounded bg-black object-contain" />}+ {!picked.ownFrame && usedLabel(picked, shotNumbers) && <p className="text-[11px] text-port-text-muted">{usedLabel(picked, shotNumbers)}</p>}{picked.prompt && <p className="line-clamp-2 text-[11px] text-port-text-muted">{picked.prompt}</p>}<div className="flex flex-wrap gap-2"><button type="button" disabled={busy} onClick={() => place(null)}@@ -179,9 +190,11 @@ export default function SceneTakePicker({ open, onClose, projectId, scene, kind,title="Failed or unusable: clean it up later" className={`${ACTION} ${picked.mark === 'bad' ? 'border-port-error text-port-error' : ''}`}><Ban size={14} aria-hidden="true" />Bad</button>+ {!picked.inUseBy?.length && (<button type="button" disabled={working} onClick={() => setConfirmDelete('picked')} className={ACTION}><Trash2 size={14} aria-hidden="true" />Delete</button>+ )}</>)}</div>{confirmDelete === 'picked' && (@@ -200,16 +213,16 @@ export default function SceneTakePicker({ open, onClose, projectId, scene, kind,{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 {itemNoun} made for this video…</p>}{pool && items.length === 0 && (- <p className="text-xs text-port-text-muted">{query ? `No unused ${itemNoun}s match.` : `No unused ${itemNoun}s here.`}</p>+ <p className="text-xs text-port-text-muted">{query ? `No ${itemNoun}s match.` : `No ${itemNoun}s here.`}</p>)}- <ul className="grid grid-cols-3 gap-2 sm:grid-cols-4 lg:grid-cols-6 xl:grid-cols-8" aria-label={`Unused ${itemNoun}s`}>+ <ul className="grid grid-cols-3 gap-2 sm:grid-cols-4 lg:grid-cols-6 xl:grid-cols-8" aria-label={`${itemNoun[0].toUpperCase()}${itemNoun.slice(1)}s`}>{items.slice(0, shown).map((item) => {const number = item.sceneId ? shotNumbers.get(item.sceneId) : null;const selected = picked?.assetId === item.assetId;return (<li key={item.assetId}><button type="button" onClick={() => setPicked(item)} aria-pressed={selected}- aria-label={`${item.ownFrame ? `This shot's ${item.ownFrame.toLowerCase()}` : `${itemNoun}${number ? ` from shot ${number}` : ''}`}${item.prompt ? `: ${item.prompt.slice(0, 80)}` : ''}`}+ aria-label={`${item.ownFrame ? `This shot's ${item.ownFrame.toLowerCase()}` : `${itemNoun}${number ? ` from shot ${number}` : ''}${usedLabel(item, shotNumbers) ? `, ${usedLabel(item, shotNumbers).toLowerCase()}` : ''}`}${item.prompt ? `: ${item.prompt.slice(0, 80)}` : ''}`}className={`relative block w-full overflow-hidden rounded border ${selected ? 'border-port-accent ring-2 ring-port-accent' : 'border-port-border'} ${item.mark === 'bad' ? 'opacity-50' : ''}`}><img src={takeThumbUrl(item)} alt="" loading="lazy" className="block aspect-video w-full bg-black object-cover" />{(item.ownFrame || number) && <span className="port-media-overlay-strong absolute left-1 top-1 rounded px-1 text-[10px] leading-tight">{item.ownFrame || `#${number}`}</span>}@@ -218,6 +231,9 @@ export default function SceneTakePicker({ open, onClose, projectId, scene, kind,{item.mark === 'bad' ? <Ban size={11} aria-label="bad" /> : <Star size={11} aria-label="ingredient" />}</span>)}+ {!item.ownFrame && item.inUseBy?.length > 0 && (+ <span className="port-media-overlay-strong absolute bottom-1 left-1 rounded px-1 text-[10px] leading-tight">In use</span>+ )}{(kind === 'video' || item.clipIds?.length > 0) && (<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" />{kind === 'video' ? 'clip' : 'has clip'}diff --git a/client/src/components/musicVideo/SceneTakePicker.test.jsx b/client/src/components/musicVideo/SceneTakePicker.test.jsxindex f26a7cf1fa..2c0e6bb352 100644--- a/client/src/components/musicVideo/SceneTakePicker.test.jsx+++ b/client/src/components/musicVideo/SceneTakePicker.test.jsx@@ -59,6 +59,28 @@ describe('Swap from unused', () => {expect(await screen.findByRole('button', { name: '✕ Bad 0' })).toBeTruthy();});+ // Uniquely catches a frame another shot uses dropping out of the picker, or one this slot holds being offered back.+ it('offers a still another shot uses, says where, and never offers to delete it', async () => {+ api.getMusicVideoMediaPool.mockImplementationOnce(async () => ({ items: [+ { kind: 'image', assetId: 'start-12.png', sceneId: 's12', prompt: 'Splicer close-up', clipIds: [], inUseBy: ['s12'], mark: 'bad' },+ { kind: 'image', assetId: 'mine-now.png', sceneId: 's8', prompt: 'Current still', clipIds: [], inUseBy: ['s8'] },+ ] }));+ const onPlace = vi.fn(async () => {});+ render(<SceneTakePicker open projectId="mv-1" scene={{ sceneId: 's8', referenceImageId: 'mine-now.png' }} kind="image" onPlace={onPlace}+ shotNumbers={new Map([['s8', 8], ['s12', 12]])} />);+ fireEvent.click(await screen.findByRole('tab', { name: /Other shots/ }));+ fireEvent.click(screen.getByRole('button', { name: /still from shot 12, used on #12/ }));+ expect(screen.getByText('Used on #12')).toBeTruthy();+ expect(screen.queryByRole('button', { name: 'Delete' })).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: '✕ Bad 1' }));+ expect(screen.queryByRole('button', { name: /Delete 1 bad/ })).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Use still' }));+ expect(onPlace).toHaveBeenCalledWith({ kind: 'image', assetId: 'start-12.png' });+ // The still already in this slot isn't offered back.+ fireEvent.click(screen.getByRole('tab', { name: /This shot/ }));+ expect(screen.queryByRole('button', { name: /Current still/ })).toBeNull();+ });+// Uniquely catches the grid stopping at its first page instead of loading more as its bottom scrolls into view.it('loads the next page of stills when the bottom of the grid comes into view', async () => {const many = Array.from({ length: 70 }, (_, i) => ({ kind: 'image', assetId: `f${i}.png`, sceneId: null, prompt: `Frame ${i}`, clipIds: [] }));diff --git a/client/src/components/musicVideo/stages/BoardStage.jsx b/client/src/components/musicVideo/stages/BoardStage.jsxindex 64c1e80d2a..6b84ddc5fc 100644--- a/client/src/components/musicVideo/stages/BoardStage.jsx+++ b/client/src/components/musicVideo/stages/BoardStage.jsx@@ -102,6 +102,15 @@ export default function BoardStage({ board }) {: inspectorRef.current?.querySelector('summary');if (target) { target.focus({ preventScroll: true }); focusAfterNavigation.current = null; }}, [activeSceneId]);+ // The open card's Previous / Next shot buttons walk every shot in song order, filter or not.+ const songOrder = [...scenes].sort((a, b) => (numbers.get(a.sceneId) ?? Infinity) - (numbers.get(b.sceneId) ?? Infinity));+ const openShot = (scene) => scene && (() => {+ focusAfterNavigation.current = { target: 'inspector' };+ board.seekToScene?.(scene);+ onToggleSceneExpand?.(scene.sceneId, true);+ });+ const activeAt = songOrder.findIndex((scene) => scene.sceneId === activeSceneId);+ const stepShot = activeAt === -1 ? null : { prev: openShot(songOrder[activeAt - 1]), next: openShot(songOrder[activeAt + 1]) };// j / k step through the listed scenes (opening one, which also routes to it).useEffect(() => {const ids = visibleIds ? visibleIds.split('\n') : [];@@ -189,6 +198,7 @@ export default function BoardStage({ board }) {project={project}expanded={activeSceneId === scene.sceneId}onToggleExpand={toggleInspector}+ stepShot={stepShot}performanceReview={performanceReviews.get(`${scene.sceneId}:${scene.videoHistoryId}`)}index={idx}shotNumber={numbers.get(scene.sceneId)}diff --git a/client/src/components/musicVideo/stages/BoardStage.test.jsx b/client/src/components/musicVideo/stages/BoardStage.test.jsxindex 45e968135b..ba86f517b1 100644--- a/client/src/components/musicVideo/stages/BoardStage.test.jsx+++ b/client/src/components/musicVideo/stages/BoardStage.test.jsx@@ -54,6 +54,17 @@ describe('BoardStage scene filter', () => {fireEvent.keyDown(window, { key: 'k' });expect(second.onToggleSceneExpand).toHaveBeenLastCalledWith('s1', true);});++ it('the open card steps to the neighboring shots in song order, past the filter', () => {+ // Listed out of song order, and shot 2 has its clip so ?scenes=missing hides it.+ const shuffled = [scene(3), scene(1), scene(2)];+ const b = board(shuffled, { activeSceneId: 's1', seekToScene: vi.fn() });+ renderBoard(b, '/?scenes=missing');+ expect(screen.getByRole('button', { name: 'Previous shot' }).disabled).toBe(true);+ fireEvent.click(screen.getByRole('button', { name: 'Next shot' }));+ expect(b.seekToScene).toHaveBeenLastCalledWith(expect.objectContaining({ sceneId: 's2' }));+ expect(b.onToggleSceneExpand).toHaveBeenLastCalledWith('s2', true);+ });});describe('BoardStage thumbnail media badges', () => {diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex 43f8a3765c..82a63932b9 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -1550,7 +1550,7 @@ router.post('/:id/scenes/:sceneId/continue-from-previous', asyncHandler(async (rres.json(await continueFromPreviousShot(req.params.id, req.params.sceneId, { keepStillAsEnd }));}));-// Every still and clip generated for this video that no shot uses now (the shot card's "Swap from unused").+// Every still and clip generated for this video, each naming the shots using it now (the shot card's Swap picker).router.get('/:id/media-pool', asyncHandler(async (req, res) => {const project = await getProject(req.params.id);if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });diff --git a/server/routes/musicVideoTakes.test.js b/server/routes/musicVideoTakes.test.jsindex 395569685b..940a97e7db 100644--- a/server/routes/musicVideoTakes.test.js+++ b/server/routes/musicVideoTakes.test.js@@ -225,8 +225,8 @@ describe('external-asset handoff', () => {});describe('swapping a shot from unused takes', () => {- // Uniquely catches a cut shot's takes vanishing from the picker, a clip losing its still, and a used take offered as unused.- it('lists every unused still and clip, keeps a cut shot\'s takes on the floor, and puts a still with its clip on a shot', async () => {+ // Uniquely catches a cut shot's takes vanishing from the picker, a clip losing its still, and a frame placed on a shot dropping out of every other shot's picker.+ it('lists every still and clip with the shots using it, keeps a cut shot\'s takes on the floor, and puts a still with its clip on a shot', async () => {for (const name of ['a-1.png', 'a-2.png', 'b-1.png', 'b-2.png']) seedImage(name);seedVideoHistory([{ id: 'clip-b2', prompt: 'waves in slow motion' }, { id: 'clip-a1' }, { id: 'clip-a1-trim' }]);await addTake(sceneA.sceneId, { kind: 'image', assetId: 'a-1.png', source: 'generated' });@@ -236,10 +236,13 @@ describe('swapping a shot from unused takes', () => {await addTake(sceneB.sceneId, { kind: 'image', assetId: 'b-2.png', source: 'generated' });await addTake(sceneB.sceneId, { kind: 'video', assetId: 'clip-b2', source: 'generated', sourceImageId: 'b-2.png' });const pool = async () => (await request(app).get(`${base()}/media-pool`)).body.items;+ const inUse = async () => (await pool()).filter((item) => item.inUseBy.length).map((item) => item.assetId).sort();- // Selected stills and clips are in use; the rest are offered, each naming the shot that holds it.- expect((await pool()).map((item) => [item.kind, item.assetId, item.sceneId]).sort()).toEqual([- ['image', 'a-2.png', sceneA.sceneId], ['image', 'b-2.png', sceneB.sceneId], ['video', 'clip-b2', sceneB.sceneId],+ // Everything is offered, each naming the shot that holds it; selected stills and clips name the shots using them.+ expect((await pool()).map((item) => [item.kind, item.assetId, item.sceneId, item.inUseBy]).sort()).toEqual([+ ['image', 'a-1.png', sceneA.sceneId, [sceneA.sceneId]], ['image', 'a-2.png', sceneA.sceneId, []],+ ['image', 'b-1.png', sceneB.sceneId, [sceneB.sceneId]], ['image', 'b-2.png', sceneB.sceneId, []],+ ['video', 'clip-a1', sceneA.sceneId, [sceneA.sceneId]], ['video', 'clip-b2', sceneB.sceneId, []],]);// Cutting shot B leaves its takes on the floor, the clip still paired with the still it was rendered from.@@ -254,18 +257,18 @@ describe('swapping a shot from unused takes', () => {expect(used.status).toBe(200);expect(used.body.scene).toMatchObject({ referenceImageId: 'b-2.png', videoHistoryId: 'clip-b2' });expect(used.body.scene.takes.find((take) => take.assetId === 'clip-b2')).toMatchObject({ source: 'reused', sourceImageId: 'b-2.png' });- expect((await pool()).map((item) => item.assetId).sort()).toEqual(['a-1.png', 'a-2.png', 'b-1.png', 'clip-a1']);+ expect(await inUse()).toEqual(['b-2.png', 'clip-b2']);// A clip cut from a later start frame ("Start clip here") lands as a trimmed take.const trimmed = await addTake(sceneA.sceneId, { kind: 'video', assetId: 'clip-a1-trim', source: 'trimmed' });expect(trimmed.status).toBe(201);expect(trimmed.body.take).toMatchObject({ kind: 'video', assetId: 'clip-a1-trim', source: 'trimmed' });- // Any unused still can become the shot's end frame, and leaves the pool.+ // Any still can become the shot's end frame, and stays listed as in use.const end = await request(app).post(`${base()}/scenes/${sceneA.sceneId}/takes/use`).send({ kind: 'endImage', assetId: 'b-1.png' });expect(end.status).toBe(200);expect(end.body.scene).toMatchObject({ referenceImageId: 'b-2.png', endImageId: 'b-1.png' });- expect((await pool()).map((item) => item.assetId).sort()).toEqual(['a-1.png', 'a-2.png', 'clip-a1', 'clip-a1-trim']);+ expect(await inUse()).toEqual(['b-1.png', 'b-2.png', 'clip-b2']);expect((await request(app).post(`${base()}/scenes/${sceneA.sceneId}/takes/use`).send({ kind: 'image', assetId: 'missing.png' })).status).toBe(400);expect((await request(app).post(`${base()}/scenes/${sceneA.sceneId}/takes/use`).send({ kind: 'endImage', assetId: 'a-1.png', withAssetId: 'clip-a1' })).status).toBe(400);diff --git a/server/services/musicVideo/mediaPool.js b/server/services/musicVideo/mediaPool.jsindex 5611db5754..c913c85846 100644--- a/server/services/musicVideo/mediaPool.js+++ b/server/services/musicVideo/mediaPool.js@@ -91,15 +91,31 @@ function forgetPoolAssets(project, keys) {const usedKeys = (project) => new Set((project?.scenes || []).flatMap((scene) => Object.entries(TAKE_SLOT).map(([slot, field]) => (scene[field] ? `${KIND_OF_SLOT[slot]}:${scene[field]}` : null)).filter(Boolean)));+/** Each `<kind>:<id>` a shot uses now, mapped to the shots using it (still, clip or end frame slot), in board order. */+const shotsUsing = (project) => {+ const using = new Map();+ for (const scene of project?.scenes || []) {+ for (const [slot, field] of Object.entries(TAKE_SLOT)) {+ if (!scene[field]) continue;+ const key = `${KIND_OF_SLOT[slot]}:${scene[field]}`;+ const ids = using.get(key) || [];+ if (!ids.includes(scene.sceneId)) using.set(key, [...ids, scene.sceneId]);+ }+ }+ return using;+};+/**- * The pool the picker shows: every asset in the collection or on the board that- * no shot uses now (not selected in any shot's still, clip or end frame slot).- * Each item names the shot whose takes hold it (null on the floor), the take's- * prompt and status, a clip's still, and the clips rendered from a still.- * `history` maps a video id to its history entry. Newest first.+ * The pool the picker shows: every asset in the collection or on the board,+ * including ones a shot uses now, since a frame placed on one shot can be right+ * for another too. `inUseBy` lists the shots using it (still, clip or end frame+ * slot). Each item names the shot whose takes hold it (else the first shot using+ * it, else null on the floor), the take's prompt and status, a clip's still, and+ * the clips rendered from a still. `history` maps a video id to its history entry.+ * Newest first.*/function buildMediaPool(project, collectionItems = [], history = new Map()) {- const used = usedKeys(project);+ const using = shotsUsing(project);const byKey = new Map();const add = (kind, ref, fields) => {const key = `${kind}:${ref}`;@@ -125,7 +141,10 @@ function buildMediaPool(project, collectionItems = [], history = new Map()) {}const marks = project?.assetMarks || {};return items- .filter((item) => !used.has(`${item.kind}:${item.assetId}`))+ .map((item) => {+ const inUseBy = using.get(`${item.kind}:${item.assetId}`) || [];+ return { ...item, sceneId: item.sceneId || inUseBy[0] || null, inUseBy };+ })// Bad is only ever the director's own mark: a take rejected from one shot may be right for another..map((item) => ({ ...item, mark: marks[`${item.kind}:${item.assetId}`] || null })).map((item) => (item.kind === 'image' ? { ...item, clipIds: clipsByStill.get(item.assetId) || [] } : item))@@ -174,7 +193,7 @@ async function stampClipProvenance(clips) {}/**- * The unused stills and clips for a project's picker, backfilling its+ * Every still and clip for a project's picker, backfilling its* collection first. An asset no longer in the media library (deleted from the* gallery or history) is left out rather than shown as a broken tile.*/