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
Sort a music video's unused stills and clips, and clean up deleted ones (#11265)
[._.]/77a12214b790
diff --git a/client/src/components/musicVideo/SceneTakePicker.jsx b/client/src/components/musicVideo/SceneTakePicker.jsxindex d813e7bc68..dd25a1aff3 100644--- a/client/src/components/musicVideo/SceneTakePicker.jsx+++ b/client/src/components/musicVideo/SceneTakePicker.jsx@@ -1,8 +1,8 @@import { useEffect, useState } from 'react';-import { X, Search, Film, Activity } from 'lucide-react';+import { X, Search, Film, Activity, Star, Ban, Trash2 } from 'lucide-react';import Modal from '../ui/Modal.jsx';import TabPills from '../ui/TabPills.jsx';-import { getMusicVideoMediaPool } from '../../services/apiMusicVideo.js';+import { deleteMusicVideoPoolAssets, getMusicVideoMediaPool, markMusicVideoPoolAssets } from '../../services/apiMusicVideo.js';import { takeThumbUrl, takeClipUrl } from '../../lib/musicVideoTakes.js';import { formatCount } from '../../utils/formatters.js';@@ -14,6 +14,15 @@ const POOL_KIND = { image: 'image', video: 'video', endImage: 'image' };/** 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).+const MARK_FILTERS = [+ { id: 'all', label: 'All' }, { id: 'ingredient', label: '★ Ingredients' }, { id: 'unsorted', label: 'Unsorted' }, { id: 'bad', label: '✕ Bad' },+];+const markOf = (item) => item.mark || 'unsorted';+const poolKey = (item) => `${item.kind}:${item.assetId}`;+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]';+/** Items of one kind matching a search over their prompt, or a shot number ("12" or "#12"). */export function filterPool(items, { kind, query, shotNumbers }) {const needle = query.trim().toLowerCase().replace(/^#/, '');@@ -30,6 +39,10 @@ export function filterPool(items, { kind, query, shotNumbers }) {* 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.* `onPlace({ kind, assetId, withAssetId? })` puts it on the shot.+ *+ * It is also where the video's assets are sorted: mark one ★ ingredient (good,+ * not placed yet) or ✕ bad, filter by mark, and delete bad ones from the+ * media library (the server refuses anything a shot uses).*/export default function SceneTakePicker({ open, onClose, projectId, scene, kind, shotNumbers = new Map(), onPlace, busy = false }) {const [pool, setPool] = useState(null);@@ -38,11 +51,14 @@ export default function SceneTakePicker({ open, onClose, projectId, scene, kind,const [query, setQuery] = useState('');const [shown, setShown] = useState(PAGE);const [picked, setPicked] = useState(null);+ const [markFilter, setMarkFilter] = useState('all');+ const [confirmDelete, setConfirmDelete] = useState(null);+ const [working, setWorking] = useState(false);useEffect(() => {if (!open) return undefined;let active = true;- setPool(null); setError(null); setPicked(null); setQuery(''); setShown(PAGE);+ setPool(null); setError(null); setPicked(null); setQuery(''); setShown(PAGE); setMarkFilter('all'); setConfirmDelete(null);getMusicVideoMediaPool(projectId, { silent: true }).then((res) => {if (!active) return;@@ -60,7 +76,10 @@ export default function SceneTakePicker({ open, onClose, projectId, scene, kind,const counts = { shot: 0, others: 0, floor: 0 };for (const item of ofKind) counts[poolGroup(item, scene.sceneId)] += 1;const activeGroup = group;- const items = ofKind.filter((item) => poolGroup(item, scene.sceneId) === activeGroup);+ const inGroup = ofKind.filter((item) => poolGroup(item, scene.sceneId) === activeGroup);+ const markCounts = { all: inGroup.length, ingredient: 0, unsorted: 0, bad: 0 };+ for (const item of inGroup) markCounts[markOf(item)] += 1;+ const items = markFilter === 'all' ? inGroup : inGroup.filter((item) => markOf(item) === markFilter);const noun = SLOT_NOUN[kind];const itemNoun = SLOT_NOUN[POOL_KIND[kind]];const shotName = shotNumbers.get(scene.sceneId) ? `Shot ${shotNumbers.get(scene.sceneId)}` : 'this shot';@@ -69,6 +88,24 @@ export default function SceneTakePicker({ open, onClose, projectId, scene, kind,const place = (withAssetId) => Promise.resolve(onPlace?.({ kind, assetId: picked.assetId, ...(withAssetId ? { withAssetId } : {}) })).then((placed) => { if (placed !== false) onClose?.(); });+ const run = (work) => { setWorking(true); setError(null); return work().catch((err) => setError(err?.message || 'That did not work')).finally(() => setWorking(false)); };+ // Tapping the active mark clears it; a rejected take then reads as bad again, as the server sees it.+ const toggleMark = (mark) => run(async () => {+ const next = picked.mark === mark ? null : mark;+ await markMusicVideoPoolAssets(projectId, [{ kind: picked.kind, assetId: picked.assetId }], next, { silent: true });+ const display = next || (picked.takeStatus === 'rejected' ? 'bad' : null);+ setPool((prev) => prev.map((item) => (poolKey(item) === poolKey(picked) ? { ...item, mark: display } : item)));+ setPicked((prev) => ({ ...prev, mark: display }));+ });+ const remove = (targets) => run(async () => {+ await deleteMusicVideoPoolAssets(projectId, targets.map(({ kind: k, assetId }) => ({ kind: k, assetId })), { silent: true });+ const gone = new Set(targets.map(poolKey));+ setPool((prev) => prev.filter((item) => !gone.has(poolKey(item))));+ setPicked((prev) => (prev && gone.has(poolKey(prev)) ? null : prev));+ setConfirmDelete(null);+ });+ const badHere = markFilter === 'bad' ? items : [];+return (<Modal open={open} onClose={onClose} size="2xl" align="top" usePortal ariaLabel={`Swap ${noun} for ${shotName}`}panelClassName="bg-port-card border border-port-border rounded-lg p-3 space-y-2">@@ -78,7 +115,7 @@ export default function SceneTakePicker({ open, onClose, projectId, scene, kind,<X size={16} /></button></div>- <TabPills activeTab={activeGroup} onChange={(id) => { setGroup(id); setShown(PAGE); setPicked(null); }}+ <TabPills activeTab={activeGroup} onChange={(id) => { setGroup(id); setShown(PAGE); setPicked(null); setConfirmDelete(null); }}tabs={[{ id: 'shot', label: 'This shot', count: counts.shot }, { id: 'others', label: 'Other shots', count: counts.others }, { id: 'floor', label: 'Floor', count: counts.floor }]} /><label htmlFor={`mv-pool-search-${scene.sceneId}`} className="flex items-center gap-2 rounded border border-port-border bg-port-bg px-2"><Search size={14} aria-hidden="true" className="shrink-0 text-port-text-muted" />@@ -86,6 +123,15 @@ export default function SceneTakePicker({ open, onClose, projectId, scene, kind,<input id={`mv-pool-search-${scene.sceneId}`} type="search" value={query} onChange={(e) => { setQuery(e.target.value); setShown(PAGE); }}placeholder="Search prompts or shot #" 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 gap-1" role="group" aria-label="Show by mark">+ {MARK_FILTERS.map((filter) => (+ <button key={filter.id} type="button" aria-pressed={markFilter === filter.id}+ onClick={() => { setMarkFilter(filter.id); setShown(PAGE); setConfirmDelete(null); }}+ className={`${CHIP} ${markFilter === filter.id ? 'border-port-accent text-port-accent' : 'border-port-border'} ${filter.id === 'bad' ? 'text-port-error' : ''}`}>+ {filter.label} {formatCount(markCounts[filter.id], { fallback: '0' })}+ </button>+ ))}+ </div>{picked && (<div className="space-y-2 rounded border border-port-border p-2">{kind === 'video'@@ -98,14 +144,35 @@ export default function SceneTakePicker({ open, onClose, projectId, scene, kind,{busy && <Activity size={14} className="animate-spin" />}Use {noun}</button>{partner && (- <button type="button" disabled={busy} onClick={() => place(partner)}- className="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]">+ <button type="button" disabled={busy} onClick={() => place(partner)} className={ACTION}>Use {noun} + its {kind === 'image' ? 'clip' : 'still'}</button>)}+ <button type="button" disabled={working} onClick={() => toggleMark('ingredient')} aria-pressed={picked.mark === 'ingredient'}+ title="Good, not placed yet: keep it as an ingredient" className={`${ACTION} ${picked.mark === 'ingredient' ? 'border-port-warning text-port-warning' : ''}`}>+ <Star size={14} aria-hidden="true" />Ingredient+ </button>+ <button type="button" disabled={working} onClick={() => toggleMark('bad')} aria-pressed={picked.mark === 'bad'}+ 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>+ <button type="button" disabled={working} onClick={() => setConfirmDelete('picked')} className={ACTION}>+ <Trash2 size={14} aria-hidden="true" />Delete+ </button></div>+ {confirmDelete === 'picked' && (+ <DeleteConfirm count={1} noun={itemNoun} working={working} onConfirm={() => remove([picked])} onCancel={() => setConfirmDelete(null)} />+ )}</div>)}+ {badHere.length > 0 && (confirmDelete === 'bad'+ ? <DeleteConfirm count={badHere.length} noun={itemNoun} working={working} onConfirm={() => remove(badHere)} onCancel={() => setConfirmDelete(null)} />+ : (+ <button type="button" disabled={working} onClick={() => setConfirmDelete('bad')}+ className="inline-flex min-h-[44px] w-full items-center justify-center gap-1 rounded border border-port-error text-xs text-port-error disabled:opacity-50 sm:min-h-[32px]">+ <Trash2 size={14} aria-hidden="true" />Delete {formatCount(badHere.length)} bad+ </button>+ ))}{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 && (@@ -119,9 +186,14 @@ export default function SceneTakePicker({ open, onClose, projectId, scene, kind,<li key={item.assetId}><button type="button" onClick={() => setPicked(item)} aria-pressed={selected}aria-label={`${itemNoun}${number ? ` from shot ${number}` : ''}${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.takeStatus === 'rejected' ? 'opacity-60' : ''}`}>+ 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" />{number && <span className="port-media-overlay-strong absolute left-1 top-1 rounded px-1 text-[10px] leading-tight">#{number}</span>}+ {item.mark && (+ <span className={`port-media-overlay-strong absolute right-1 top-1 rounded px-0.5 ${item.mark === 'bad' ? 'text-port-error' : 'text-port-warning'}`}>+ {item.mark === 'bad' ? <Ban size={11} aria-label="bad" /> : <Star size={11} aria-label="ingredient" />}+ </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'}@@ -141,3 +213,16 @@ export default function SceneTakePicker({ open, onClose, projectId, scene, kind,</Modal>);}++function DeleteConfirm({ count, noun, working, onConfirm, onCancel }) {+ return (+ <div className="flex flex-wrap items-center gap-2 rounded border border-port-error/50 p-2 text-xs">+ <span className="min-w-0 flex-1">Delete {count === 1 ? `this ${noun}` : `${formatCount(count)} ${noun}s`} from the media library? This can't be undone.</span>+ <button type="button" disabled={working} onClick={onConfirm}+ className="inline-flex min-h-[44px] items-center gap-1 rounded bg-port-error px-3 font-medium text-white disabled:opacity-50 sm:min-h-[32px]">+ {working && <Activity size={14} className="animate-spin" />}Yes, delete+ </button>+ <button type="button" disabled={working} onClick={onCancel} className={ACTION}>Keep</button>+ </div>+ );+}diff --git a/client/src/components/musicVideo/SceneTakePicker.test.jsx b/client/src/components/musicVideo/SceneTakePicker.test.jsxindex de3b80e85f..77167c9438 100644--- a/client/src/components/musicVideo/SceneTakePicker.test.jsx+++ b/client/src/components/musicVideo/SceneTakePicker.test.jsx@@ -5,10 +5,16 @@ const pool = [{ kind: 'image', assetId: 'mine.png', sceneId: 's8', prompt: 'Film strip held to the lamp', clipIds: [] },{ kind: 'image', assetId: 'other.png', sceneId: 's12', prompt: 'Splicer close-up', clipIds: ['clip-12'] },{ kind: 'image', assetId: 'floor.png', sceneId: null, prompt: 'Reel on the floor', clipIds: [] },+ { kind: 'image', assetId: 'blurry.png', sceneId: null, prompt: 'Out of focus', clipIds: [], mark: 'bad' },{ kind: 'video', assetId: 'clip-12', sceneId: 's12', sourceImageId: 'other.png' },];-vi.mock('../../services/apiMusicVideo.js', () => ({ getMusicVideoMediaPool: vi.fn(async () => ({ items: pool })) }));+vi.mock('../../services/apiMusicVideo.js', () => ({+ getMusicVideoMediaPool: vi.fn(async () => ({ items: pool })),+ markMusicVideoPoolAssets: vi.fn(async () => ({})),+ deleteMusicVideoPoolAssets: vi.fn(async () => ({ deleted: 1 })),+}));const { default: SceneTakePicker } = await import('./SceneTakePicker.jsx');+const api = await import('../../services/apiMusicVideo.js');describe('Swap from unused', () => {// Uniquely catches the picker offering the wrong kind or group, a shot-number search missing, or the partner clip dropped.@@ -31,4 +37,25 @@ describe('Swap from unused', () => {fireEvent.change(screen.getByLabelText('Search prompts or shot number'), { target: { value: 'reel' } });expect(screen.getAllByRole('listitem')).toHaveLength(1);});++ // Uniquely catches a mark that never reaches the server, a Bad filter that misses a mark, or a delete that skips its confirm.+ it('marks a floor still as an ingredient, and deletes the bad ones after a confirm', async () => {+ render(<SceneTakePicker open projectId="mv-1" scene={{ sceneId: 's8' }} kind="image" onPlace={vi.fn()} shotNumbers={new Map([['s8', 8]])} />);+ fireEvent.click(await screen.findByRole('tab', { name: /Floor/ }));+ fireEvent.click(screen.getByRole('button', { name: /still: Reel on the floor/ }));+ fireEvent.click(screen.getByRole('button', { name: 'Ingredient' }));+ await waitFor(() => expect(api.markMusicVideoPoolAssets).toHaveBeenCalledWith('mv-1', [{ kind: 'image', assetId: 'floor.png' }], 'ingredient', { silent: true }));+ expect(await screen.findByRole('button', { name: '★ Ingredients 1' })).toBeTruthy();+ // Tapping the active mark clears it.+ fireEvent.click(screen.getByRole('button', { name: 'Ingredient' }));+ await waitFor(() => expect(api.markMusicVideoPoolAssets).toHaveBeenLastCalledWith('mv-1', [{ kind: 'image', assetId: 'floor.png' }], null, { silent: true }));+ expect(await screen.findByRole('button', { name: '★ Ingredients 0' })).toBeTruthy();++ fireEvent.click(screen.getByRole('button', { name: '✕ Bad 1' }));+ fireEvent.click(screen.getByRole('button', { name: 'Delete 1 bad' }));+ expect(api.deleteMusicVideoPoolAssets).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Yes, delete' }));+ await waitFor(() => expect(api.deleteMusicVideoPoolAssets).toHaveBeenCalledWith('mv-1', [{ kind: 'image', assetId: 'blurry.png' }], { silent: true }));+ expect(await screen.findByRole('button', { name: '✕ Bad 0' })).toBeTruthy();+ });});diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex 5a50111f24..4c9359b7d7 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -172,6 +172,14 @@ export const selectMusicVideoSceneTake = (id, sceneId, takeId, options = {}) =>request(`${takesPath(id, sceneId)}/${encodeURIComponent(takeId)}/select`, { method: 'POST', ...options });// The project's unused stills and clips (the shot card's "Swap from unused") → { collectionId, items }.export const getMusicVideoMediaPool = (id, options = {}) => request(`/music-video/${encodeURIComponent(id)}/media-pool`, options);+// Asset manager: mark unused pool items ★ 'ingredient' / ✕ 'bad' (null clears) → { assetMarks }.+export const markMusicVideoPoolAssets = (id, items, mark, options = {}) => request(`/music-video/${encodeURIComponent(id)}/media-pool/marks`, {+ method: 'PATCH', body: JSON.stringify({ items, mark }), ...options,+});+// Asset manager: delete unused pool items from the media library → { deleted }.+export const deleteMusicVideoPoolAssets = (id, items, options = {}) => request(`/music-video/${encodeURIComponent(id)}/media-pool/delete`, {+ 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 cedf24f42b..d28e0c0b57 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -319,6 +319,26 @@ export const musicVideoTakeInputSchema = z.object({if (!parsed.success) ctx.addIssue({ code: 'custom', path: ['assetId'], message: parsed.error.issues[0].message });});+/** One still or clip in a video's media pool, as the asset manager names it. */+const musicVideoPoolAssetSchema = z.object({+ kind: z.enum(['image', 'video']),+ assetId: z.string().min(1).max(256),+}).strict().superRefine((input, ctx) => {+ const parsed = (input.kind === 'video' ? videoHistoryIdSchema : galleryImageName).safeParse(input.assetId);+ if (!parsed.success) ctx.addIssue({ code: 'custom', path: ['assetId'], message: parsed.error.issues[0].message });+});++/** ★ ingredient (good, not placed) or ✕ bad (to clean up); null clears the mark. */+export const musicVideoPoolMarkSchema = z.object({+ items: z.array(musicVideoPoolAssetSchema).min(1).max(500),+ mark: z.enum(['ingredient', 'bad']).nullable(),+}).strict();++/** Delete unused stills and clips from the media library (the asset manager's "Delete bad"). */+export const musicVideoPoolDeleteSchema = 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 d51d5e4d92..bc64807c47 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, musicVideoProductionFeedbackSchema, musicVideoProductionFeedbackResolutionSchema, musicVideoProductionReviseSchema, musicVideoProductionRevertSchema } from '../lib/musicVideoValidation.js';+import { musicVideoSongStyleSunoSchema, musicVideoProjectListQuerySchema, musicVideoFinishedOutsideSchema, musicVideoProductionDraftSchema, musicVideoProductionApprovalSchema, musicVideoShotLockSchema, musicVideoProductionProofSchema, musicVideoProductionImportSchema, musicVideoContinueShotSchema, musicVideoPoolUseSchema, musicVideoPoolMarkSchema, musicVideoPoolDeleteSchema, musicVideoProductionFeedbackSchema, musicVideoProductionFeedbackResolutionSchema, 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, reviseProductionFromFeedback, revertProductionInput } from '../services/musicVideo/productionReviewService.js';@@ -116,6 +116,7 @@ import {appendTakesAcrossScenes,selectSceneTake,placeMediaPoolItem,+ markMediaPoolAssets,reviewSceneTake,refreshSongStyleFromSuno,} from '../services/musicVideo/projects.js';@@ -1544,6 +1545,20 @@ router.get('/:id/media-pool', asyncHandler(async (req, res) => {res.json(await getMusicVideoMediaPool(project));}));+// The asset manager: mark unused stills and clips ★ ingredient / ✕ bad, or delete them from the library.+router.patch('/:id/media-pool/marks', asyncHandler(async (req, res) => {+ const { items, mark } = validateRequest(musicVideoPoolMarkSchema, req.body);+ res.json({ assetMarks: await markMediaPoolAssets(req.params.id, items.map((item) => `${item.kind}:${item.assetId}`), mark) });+}));++router.post('/:id/media-pool/delete', asyncHandler(async (req, res) => {+ const { items } = validateRequest(musicVideoPoolDeleteSchema, req.body);+ const project = await getProject(req.params.id);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const { deleteMusicVideoPoolAssets } = await import('../services/musicVideo/mediaPool.js');+ res.json(await deleteMusicVideoPoolAssets(project, items));+}));+router.post('/:id/scenes/:sceneId/takes/use', asyncHandler(async (req, res) => {const { kind, assetId, withAssetId } = validateRequest(musicVideoPoolUseSchema, req.body);const otherKind = kind === 'video' ? 'image' : 'video';diff --git a/server/routes/musicVideoTakes.test.js b/server/routes/musicVideoTakes.test.jsindex 5ef1d1b430..a3e5ba8607 100644--- a/server/routes/musicVideoTakes.test.js+++ b/server/routes/musicVideoTakes.test.js@@ -308,3 +308,51 @@ describe('renders made for a video with no shot', () => {expect(pool.find((item) => item.assetId === 'test-clip')).toMatchObject({ kind: 'video', sceneId: null, sourceImageId: 'frame.png' });});});++describe('the shot asset manager', () => {+ // Uniquely catches a deleted still or clip leaving a take, mark or collection row pointing at a file that is gone, and a shot's own still being deletable.+ it('marks unused assets, refuses a shot\'s own, and forgets deleted ones everywhere', async () => {+ for (const name of ['keep.png', 'bad.png', 'used.png', 'b-used.png']) seedImage(name);+ seedVideoHistory([{ id: 'b-clip', filename: 'b-clip.mp4' }, { id: 'bad-clip', filename: 'bad-clip.mp4' }]);+ await addTake(sceneA.sceneId, { kind: 'image', assetId: 'used.png', source: 'generated' });+ await addTake(sceneA.sceneId, { kind: 'image', assetId: 'keep.png', source: 'generated' });+ await addTake(sceneB.sceneId, { kind: 'image', assetId: 'b-used.png', source: 'generated' });+ await addTake(sceneB.sceneId, { kind: 'image', assetId: 'bad.png', source: 'generated' });+ await addTake(sceneB.sceneId, { kind: 'video', assetId: 'b-clip', source: 'generated' });+ await addTake(sceneB.sceneId, { kind: 'video', assetId: 'bad-clip', source: 'generated' });+ const marks = (items, mark) => request(app).patch(`${base()}/media-pool/marks`).send({ items, mark });++ expect((await marks([{ kind: 'image', assetId: 'keep.png' }], 'ingredient')).body.assetMarks).toEqual({ 'image:keep.png': 'ingredient' });+ await marks([{ kind: 'image', assetId: 'bad.png' }], 'bad');+ const pool = (await request(app).get(`${base()}/media-pool`)).body.items;+ expect(pool.find((item) => item.assetId === 'keep.png').mark).toBe('ingredient');++ const refused = await request(app).post(`${base()}/media-pool/delete`).send({ items: [{ kind: 'image', assetId: 'used.png' }] });+ expect(refused.status).toBe(409);+ // Nor a still another video's shot uses, though it sits in this video's collection.+ seedImage('shared.png');+ const other = await projects.createProject({ name: 'Second Video' });+ const otherScene = await projects.addProjectScene(other.id, { prompt: 'an empty stage' });+ await request(app).post(`/api/music-video/${other.id}/scenes/${otherScene.sceneId}/takes`).send({ kind: 'image', assetId: 'shared.png', source: 'generated' });+ const { fileMusicVideoMedia } = await import('../services/musicVideo/mediaPool.js');+ await fileMusicVideoMedia(await reload(), [{ kind: 'image', ref: 'shared.png' }]);+ expect((await request(app).post(`${base()}/media-pool/delete`).send({ items: [{ kind: 'image', assetId: 'shared.png' }] })).status).toBe(409);+ // A mark can be cleared again.+ await marks([{ kind: 'image', assetId: 'shared.png' }], 'bad');+ expect((await marks([{ kind: 'image', assetId: 'shared.png' }], null)).body.assetMarks).toEqual({ 'image:keep.png': 'ingredient', 'image:bad.png': 'bad' });++ const deleted = await request(app).post(`${base()}/media-pool/delete`).send({ items: [{ kind: 'image', assetId: 'bad.png' }] });+ expect(deleted.status).toBe(200);+ // A clip deleted from Media history is forgotten the same way.+ const { deleteHistoryItem } = await import('../services/videoGen/historyOps.js');+ await deleteHistoryItem('bad-clip');++ const stored = await reload();+ const takeIds = stored.scenes.flatMap((scene) => (scene.takes || []).map((take) => take.assetId));+ expect(takeIds).not.toContain('bad.png');+ expect(takeIds).not.toContain('bad-clip');+ expect(stored.assetMarks).toEqual({ 'image:keep.png': 'ingredient' });+ const { getCollection, musicVideoCollectionId } = await import('../services/mediaCollections.js');+ expect((await getCollection(musicVideoCollectionId(project.id))).items.map((item) => item.ref).sort()).toEqual(['b-clip', 'b-used.png', 'keep.png', 'shared.png', 'used.png']);+ });+});diff --git a/server/services/galleryImageDeletion.js b/server/services/galleryImageDeletion.jsindex fb7a33d52f..63390f897e 100644--- a/server/services/galleryImageDeletion.js+++ b/server/services/galleryImageDeletion.js@@ -1,6 +1,7 @@/*** Gallery image deletion as one durable workflow: the image, its sidecars and- * derived index row, then every universe canon `imageRefs[]` entry naming it.+ * derived index row, then every universe canon `imageRefs[]` entry naming it+ * and every music video's unused takes, marks and collection rows.* One backup admission spans both halves, so a snapshot cannot capture canon* rows that still reference bytes the delete has already removed.*/@@ -8,7 +9,7 @@ import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';import { deleteImage } from './imageGen/local.js';import { purgeImageRefFromAllUniverses } from './universeCanon.js';-export function deleteGalleryImage(filename) {+export function deleteGalleryImage(filename, { forgetInMusicVideos = true } = {}) {return withBackupAssetPublication(async () => {const result = await deleteImage(filename);// Best-effort: a purge failure must not fail the gallery delete itself.@@ -19,6 +20,9 @@ export function deleteGalleryImage(filename) {if (universePurge.removed > 0) {console.log(`🧹 Purged ${universePurge.removed} canon ref(s) for ${filename}`);}+ // Music videos forget it too (their unused takes, marks and collection rows);+ // a batch delete from a video's asset manager forgets its whole batch at once.+ if (forgetInMusicVideos) await import('./musicVideo/mediaPool.js').then((m) => m.forgetDeletedMusicVideoAssets([`image:${filename}`]));return { ...result, canonRefsRemoved: universePurge.removed };});}diff --git a/server/services/musicVideo/mediaPool.js b/server/services/musicVideo/mediaPool.jsindex cb0d70631c..41256e4555 100644--- a/server/services/musicVideo/mediaPool.js+++ b/server/services/musicVideo/mediaPool.js@@ -51,6 +51,43 @@ export function droppedTakeAssets(before, after) {return projectTakeAssets(before).filter((asset) => !kept.has(`${asset.kind}:${asset.ref}`));}+/**+ * Mark assets ★ ingredient (good, unplaced) or ✕ bad (to clean up); null+ * clears the mark. Marks live on the project (`assetMarks`, keyed+ * `<image|video>:<ref>`), so a still bad for one video stays fine in another.+ */+export function markPoolAssets(project, keys, mark) {+ const assetMarks = { ...(project.assetMarks || {}) };+ for (const key of keys) {+ if (mark) assetMarks[key] = mark;+ else delete assetMarks[key];+ }+ return { project: { ...project, assetMarks } };+}++/**+ * Forget assets whose files are gone: their takes on every shot that does not+ * use them now, and their marks. A shot still using one keeps it, so its+ * missing media is reported where the shot is, not silently cleared.+ */+function forgetPoolAssets(project, keys) {+ const gone = new Set(keys);+ const used = usedKeys(project);+ let removed = 0;+ const scenes = (project.scenes || []).map((scene) => {+ if (!Array.isArray(scene.takes)) return scene;+ const takes = scene.takes.filter((take) => {+ const key = `${KIND_OF_SLOT[take?.kind]}:${take?.assetId}`;+ const drop = gone.has(key) && !used.has(key);+ if (drop) removed += 1;+ return !drop;+ });+ return takes.length === scene.takes.length ? scene : { ...scene, takes };+ });+ const assetMarks = Object.fromEntries(Object.entries(project.assetMarks || {}).filter(([key]) => !gone.has(key)));+ return { project: { ...project, scenes, assetMarks }, removed };+}+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)));@@ -86,8 +123,11 @@ function buildMediaPool(project, collectionItems = [], history = new Map()) {if (item.kind !== 'video' || !item.sourceImageId) continue;clipsByStill.set(item.sourceImageId, [...(clipsByStill.get(item.sourceImageId) || []), item.assetId]);}+ const marks = project?.assetMarks || {};return items.filter((item) => !used.has(`${item.kind}:${item.assetId}`))+ // A rejected take counts as bad until the director marks it otherwise.+ .map((item) => ({ ...item, mark: marks[`${item.kind}:${item.assetId}`] || (item.takeStatus === 'rejected' ? 'bad' : null) })).map((item) => (item.kind === 'image' ? { ...item, clipIds: clipsByStill.get(item.assetId) || [] } : item)).sort((a, b) => String(b.addedAt || '').localeCompare(String(a.addedAt || '')));}@@ -155,3 +195,56 @@ export async function getMusicVideoMediaPool(project) {: item.sourceImageId && !resolveGalleryImage(item.sourceImageId) ? { ...item, sourceImageId: null } : item));return { collectionId: collection?.id || null, items };}++/**+ * After stills or clips (`<image|video>:<ref>` keys) are deleted from the+ * media library: forget them on every music video that held them (unused+ * takes, marks, collection rows), in one pass per project, so nothing points+ * at a file that is gone. Best-effort, like the other filing.+ */+export async function forgetDeletedMusicVideoAssets(keys) {+ const gone = new Set(keys);+ try {+ const [{ listProjects, mutateProjectRecord }, { getCollection, musicVideoCollectionId, bulkUpdateCollectionItems }] = await Promise.all([+ import('./projects.js'), import('../mediaCollections.js'),+ ]);+ for (const project of await listProjects()) {+ const held = Object.keys(project.assetMarks || {}).some((key) => gone.has(key))+ || (project.scenes || []).some((scene) => (scene.takes || []).some((take) => gone.has(`${KIND_OF_SLOT[take?.kind]}:${take?.assetId}`)));+ // The take removal files dropped takes into the collection, so the rows go after it.+ if (held) await mutateProjectRecord(project.id, (current) => forgetPoolAssets(current, keys));+ const collection = await getCollection(musicVideoCollectionId(project.id)).catch(() => null);+ const rows = (collection?.items || []).map((item) => `${item.kind}:${item.ref}`).filter((key) => gone.has(key));+ if (rows.length) await bulkUpdateCollectionItems(collection.id, { remove: rows });+ }+ } catch (err) {+ console.error(`❌ music-video media pool: forgetting ${keys.length} deleted asset(s) failed: ${err.message}`);+ }+}++/**+ * Delete unused stills and clips of a video from the media library (the asset+ * manager's "Delete"): only assets in the video's pool, so a shot's still or+ * clip and media this video never made are refused. Each delete then forgets+ * the batch on every music video (forgetDeletedMusicVideoAssets).+ */+export async function deleteMusicVideoPoolAssets(project, items) {+ const { ServerError } = await import('../../lib/errorHandler.js');+ const pool = new Set((await getMusicVideoMediaPool(project)).items.map((item) => `${item.kind}:${item.assetId}`));+ // A shot on any music video using it keeps it, not only this video's shots.+ const { listProjects } = await import('./projects.js');+ const usedAnywhere = new Set((await listProjects()).flatMap((other) => [...usedKeys(other)]));+ const keys = items.map((item) => `${item.kind}:${item.assetId}`);+ const refused = keys.filter((key) => !pool.has(key) || usedAnywhere.has(key));+ if (refused.length) {+ throw new ServerError(`${refused.length} of these ${refused.length === 1 ? 'is' : 'are'} on a shot or not made for this video`, { status: 409, code: 'POOL_ASSET_IN_USE' });+ }+ const [{ deleteGalleryImage }, { deleteHistoryItem }] = await Promise.all([+ import('../galleryImageDeletion.js'), import('../videoGen/historyOps.js'),+ ]);+ for (const item of items) {+ await (item.kind === 'image' ? deleteGalleryImage : deleteHistoryItem)(item.assetId, { forgetInMusicVideos: false });+ }+ await forgetDeletedMusicVideoAssets(keys);+ return { deleted: items.length };+}diff --git a/server/services/musicVideo/projects.js b/server/services/musicVideo/projects.jsindex d711bd5997..5e970e536e 100644--- a/server/services/musicVideo/projects.js+++ b/server/services/musicVideo/projects.js@@ -311,6 +311,13 @@ export async function mergeProjectNextScene(id, sceneId, options = {}) {});}+/** Mark unused assets ★ ingredient or ✕ bad (null clears); returns the project's marks. */+export async function markMediaPoolAssets(id, keys, mark) {+ const { markPoolAssets } = await import('./mediaPool.js');+ const { project } = await mutateProjectRecord(id, (current) => markPoolAssets(current, keys, mark));+ return project.assetMarks || {};+}+// ---- scene takes (#8965) ----// Append candidate takes to one scene: `{ scene, appended }`. A take fills its// slot only while the slot is empty — never replaces a selection (takes.js).diff --git a/server/services/videoGen/historyOps.js b/server/services/videoGen/historyOps.jsindex 55dfb8d774..a00bb9a7c8 100644--- a/server/services/videoGen/historyOps.js+++ b/server/services/videoGen/historyOps.js@@ -41,7 +41,7 @@ export async function setHistoryItemHidden(id, hidden) {return result;}-export async function deleteHistoryItem(id) {+export async function deleteHistoryItem(id, { forgetInMusicVideos = true } = {}) {// One lease covers the history read, file removals, history rewrite, and// derived row removal; per-file admission would leave gaps between stores.return withBackupAssetPublication(async () => {@@ -75,6 +75,9 @@ export async function deleteHistoryItem(id) {await import('../mediaAssetIndex/index.js').then((m) => m.unindexVideo(id)).catch((err) => console.error(`❌ Media index video delete hook: ${err.message}`));+ // Music videos forget it too (their unused takes, marks and collection rows);+ // a batch delete from a video's asset manager forgets its whole batch at once.+ if (forgetInMusicVideos) await import('../musicVideo/mediaPool.js').then((m) => m.forgetDeletedMusicVideoAssets([`video:${id}`]));console.log(`🗑️ Deleted video: ${item.filename}`);return { ok: true };});