Skip to content

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

perf(music-video): open one project by id and page bounded summaries for the index (#10169)

Adam Eivyd3ed6aea8e2b
diff --git a/client/src/components/musicVideo/MusicVideoProjectCard.jsx b/client/src/components/musicVideo/MusicVideoProjectCard.jsx
index 41b0f01684..7a4d0208dc 100644
--- a/client/src/components/musicVideo/MusicVideoProjectCard.jsx
+++ b/client/src/components/musicVideo/MusicVideoProjectCard.jsx
@@ -39,7 +39,9 @@ export default function MusicVideoProjectCard({
onVersionStep,
}) {
const [playing, setPlaying] = useState(false);
- const preview = selectMusicVideoPreview(project);
+ // The index loads bounded summaries (#10169) that carry these derived values; a
+ // full record (just created or forked) still derives them from its own fields.
+ const preview = project.preview || selectMusicVideoPreview(project);
// When preview target changes, stop playing
useEffect(() => {
@@ -52,16 +54,23 @@ export default function MusicVideoProjectCard({
});
const scenes = Array.isArray(project.scenes) ? project.scenes : [];
- const scenesWithClips = scenes.filter((s) => s.videoHistoryId).length;
- const scenesWithFrames = scenes.filter((s) => s.referenceImageId).length;
- const scenesProgressPct = scenes.length > 0 ? Math.round((scenesWithClips / scenes.length) * 100) : 0;
+ const sceneCount = project.sceneCount ?? scenes.length;
+ const scenesWithClips = project.clipCount ?? scenes.filter((s) => s.videoHistoryId).length;
+ const scenesWithFrames = project.frameCount ?? scenes.filter((s) => s.referenceImageId).length;
+ const scenesProgressPct = sceneCount > 0 ? Math.round((scenesWithClips / sceneCount) * 100) : 0;
- const { current: currentStageId } = deriveStages(project);
+ const currentStageId = project.stage || deriveStages(project).current;
const currentStageObj = MUSIC_VIDEO_STAGES.find((s) => s.id === currentStageId);
const stageLabel = currentStageObj?.label || currentStageId;
- const pill = projectRunPill(project);
- const spend = projectSpend(project);
+ // A summary can't derive attention items, so it carries the run flags instead.
+ const pill = project.preview
+ ? (project.runInterrupted ? { id: 'interrupted', label: 'Interrupted', tone: 'warn' }
+ : project.runAwaiting ? { id: 'needs-you', label: 'Needs you', tone: 'warn' }
+ : (project.runStatus === 'running' || project.status === 'rendering') ? { id: 'running', label: 'Running', tone: 'muted' }
+ : null)
+ : projectRunPill(project);
+ const spend = project.spend || projectSpend(project);
const audioTitle = trackLabel || project.uploadedAudioFilename || null;
const conceptText = project.concept?.style || project.concept?.prompt || null;
const palette = Array.isArray(project.visualSpec?.palette) ? project.visualSpec.palette : [];
@@ -290,7 +299,7 @@ export default function MusicVideoProjectCard({
<div className="space-y-1 pt-1.5 border-t border-port-border/40 text-[11px]">
<div className="flex items-center justify-between text-port-text-muted">
<span>
- {projectShotSummary(project)}
+ {project.shotSummary || projectShotSummary(project)}
{scenesWithClips > 0 ? ` · ${scenesWithClips} clip${scenesWithClips === 1 ? '' : 's'}` : ''}
{scenesWithFrames > 0 && scenesWithClips === 0 ? ` · ${scenesWithFrames} frame${scenesWithFrames === 1 ? '' : 's'}` : ''}
</span>
@@ -300,7 +309,7 @@ export default function MusicVideoProjectCard({
</span>
) : null}
</div>
- {scenes.length > 0 && (
+ {sceneCount > 0 && (
<div className="h-1 bg-port-bg rounded overflow-hidden">
<div
className="h-full bg-port-accent transition-all duration-300"
diff --git a/client/src/components/musicVideo/MusicVideoProjectCard.test.jsx b/client/src/components/musicVideo/MusicVideoProjectCard.test.jsx
index 21c98d9d6b..b5db2dc21d 100644
--- a/client/src/components/musicVideo/MusicVideoProjectCard.test.jsx
+++ b/client/src/components/musicVideo/MusicVideoProjectCard.test.jsx
@@ -38,6 +38,28 @@ const BASE_PROJECT = {
};
describe('MusicVideoProjectCard', () => {
+ it('renders a bounded summary (no scenes/runs) the same as a full record (#10169)', () => {
+ const { scenes, ...rest } = BASE_PROJECT;
+ const summary = {
+ ...rest,
+ audioAnalysis: { bpm: 128 },
+ midiTranscription: true,
+ stage: 'board',
+ spend: { spentUsd: 1.5, capUsd: 5 },
+ shotSummary: '2 scenes',
+ sceneCount: 2,
+ clipCount: 1,
+ frameCount: 2,
+ preview: { kind: 'none', label: 'No render yet' },
+ };
+ render(<MusicVideoProjectCard project={summary} onSelect={vi.fn()} />);
+ expect(screen.getByText('Board')).toBeInTheDocument();
+ expect(screen.getByText('128 BPM')).toBeInTheDocument();
+ expect(screen.getByText(/2 scenes · 1 clip/)).toBeInTheDocument();
+ expect(screen.getByTitle('50% clips rendered')).toBeInTheDocument();
+ expect(screen.getByText(/\$1\.50/)).toBeInTheDocument();
+ });
+
it('renders richly detailed metadata and configuration options', () => {
const onSelect = vi.fn();
render(
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index 3a1f9fbea4..9cdd8315aa 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -9,8 +9,10 @@ import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';
import { useConfirmDelete } from '../hooks/useConfirmDelete';
import PageHeader from '../components/PageHeader';
import Banner from '../components/ui/Banner.jsx';
+import { usePagedCollection } from '../hooks/usePagedCollection';
+import InfiniteScrollFooter from '../components/ui/InfiniteScrollFooter';
import {
- listMusicVideoProjects,
+ listMusicVideoProjectSummaries,
createMusicVideoProject,
cloneMusicVideoProject,
updateMusicVideoProject,
@@ -141,13 +143,62 @@ export default function MusicVideo() {
return next;
});
const navigate = useNavigate();
- const [projects, setProjects] = useState([]);
+ // The index and picker read bounded summaries; an open project is its own
+ // single-record fetch (#10169), so neither load can fail the other.
+ const [selectedProject, setSelectedProject] = useState(null);
+ // The last failed/absent read of the open project, keyed by id so it never
+ // outlives a navigation; it stays up during a retry and clears on success.
+ const [selectedFault, setSelectedFault] = useState(null);
+ const [selectedFetching, setSelectedFetching] = useState(false);
+ const [selectedReload, setSelectedReload] = useState(0);
+ const deferredPatches = useRef(new Map());
const [tracks, setTracks] = useState([]);
const [universes, setUniverses] = useState(null);
const selectedId = routeProjectId || null;
- const [loading, setLoading] = useState(true);
- const [projectsError, setProjectsError] = useState(null);
- const projectsLoadPending = useRef(false);
+ // Summaries load for the index, or once the header picker is used on a deep link;
+ // once wanted they stay loaded (disabling the hook would reset its items).
+ const [summariesWanted, setSummariesWanted] = useState(!selectedId);
+ if (!selectedId && !summariesWanted) setSummariesWanted(true);
+ const fetchSummariesPage = useCallback(
+ ({ cursor, signal }) => listMusicVideoProjectSummaries({ cursor, limit: 30 }, { signal, silent: true }),
+ [],
+ );
+ const summaries = usePagedCollection(fetchSummariesPage, { enabled: summariesWanted });
+ // Same stickiness for the list: the banner outlives the retry that clears `summaries.error`.
+ const [listError, setListError] = useState(null);
+ useEffect(() => {
+ if (summaries.error) setListError(summaries.error.message || 'Failed to load music video projects');
+ else if (summaries.loaded) setListError(null);
+ }, [summaries.error, summaries.loaded]);
+ const selectedLoaded = selectedProject?.id === selectedId;
+ const fault = selectedFault?.id === selectedId ? selectedFault : null;
+ const loading = selectedId ? !selectedLoaded && (selectedFetching || !fault) : (summaries.loading || !summaries.loaded) && !summaries.error;
+ const projectsError = selectedId ? (fault?.notFound ? null : fault?.message) : listError;
+
+ useEffect(() => {
+ if (!selectedId) return undefined;
+ let cancelled = false;
+ setSelectedFetching(true);
+ getMusicVideoProject(selectedId, { silent: true })
+ .then((project) => {
+ if (cancelled) return;
+ setSelectedFault(project ? null : { id: selectedId, notFound: true });
+ const patches = deferredPatches.current.get(selectedId) || [];
+ deferredPatches.current.delete(selectedId);
+ if (project) setSelectedProject(patches.reduce((current, apply) => apply(current), project));
+ })
+ .catch((err) => {
+ if (!cancelled) setSelectedFault({ id: selectedId, notFound: err?.status === 404, message: err?.message || 'Failed to load music video project' });
+ })
+ .finally(() => { if (!cancelled) setSelectedFetching(false); });
+ return () => { cancelled = true; };
+ }, [selectedId, selectedReload]);
+
+ const loadProjects = selectedId
+ ? () => setSelectedReload((n) => n + 1)
+ : () => { if (!summaries.loading) summaries.refreshFirst(); };
+ const selected = selectedLoaded ? selectedProject : null;
+
const [analyzing, setAnalyzing] = useState(false);
const [arranging, setArranging] = useState(false);
const [creativeSetupPending, setCreativeSetupPending] = useState(false);
@@ -161,7 +212,6 @@ export default function MusicVideo() {
const [aligningLyrics, setAligningLyrics] = useState(false);
const [creating, setCreating] = useState(false);
const [form, setForm] = useState(emptyCreateForm);
- const selected = projects.find((p) => p.id === selectedId) || null;
// Which stage tab is open. The URL is the source of truth; with none (or an
// unknown one) the tab is the stage the project was in when it was opened,
@@ -184,11 +234,23 @@ export default function MusicVideo() {
const [renamingId, setRenamingId] = useState(null);
const renaming = !!selected && renamingId === selected.id;
const [renameDraft, setRenameDraft] = useState('');
- const replaceProject = (next) => setProjects((prev) => prev.map((p) => (p.id === next.id ? next : p)));
- const sortedProjects = useMemo(
- () => [...projects].sort(compareMusicVideoProjectsNewestFirst),
- [projects],
- );
+ // A full record replaces its summary in the index list; the project card
+ // derives from whichever it holds, so no summary-only field can go stale.
+ const replaceProject = (next) => {
+ setSelectedProject((prev) => (prev?.id === next.id ? next : prev));
+ summaries.setItems((prev) => prev.map((p) => (p.id === next.id ? next : p)));
+ };
+ // Open a project the page just received whole (created, forked, started).
+ const openProject = (proj) => {
+ summaries.setItems((prev) => [proj, ...prev.filter((p) => p.id !== proj.id)]);
+ setSelectedProject(proj);
+ };
+ // The open project leads; summaries fill in the rest of the picker.
+ const sortedProjects = useMemo(() => {
+ const byId = new Map(summaries.items.map((p) => [p.id, p]));
+ if (selected) byId.set(selected.id, selected);
+ return [...byId.values()].sort(compareMusicVideoProjectsNewestFirst);
+ }, [selected, summaries.items]);
const productionReview = useMusicVideoProductionReview({ project: selected, replaceProject });
const progress = useMemo(() => deriveStages(selected, productionReview.readiness), [selected, productionReview.readiness]);
const [openedStage, setOpenedStage] = useState({ id: null, stage: null });
@@ -211,14 +273,22 @@ export default function MusicVideo() {
// that resolves after the user edited the board can't clobber those edits with
// a stale project snapshot. `patch` may be a function of the current record
// when the merge has to read a field it is also writing.
- const patchProject = (projectId, patch) =>
- setProjects((prev) => prev.map((p) => (p.id === projectId
- ? { ...p, ...(typeof patch === 'function' ? patch(p) : patch) }
- : p)));
- const patchScene = (projectId, sceneId, patch) =>
- setProjects((prev) => prev.map((p) => (p.id === projectId
- ? { ...p, scenes: (p.scenes || []).map((s) => (s.sceneId === sceneId ? { ...s, ...patch } : s)) }
- : p)));
+ const patchProject = (projectId, patch) => {
+ const apply = (project) => ({ ...project, ...(typeof patch === 'function' ? patch(project) : patch) });
+ // The picker and index show a project's name/status/recency, so keep those current.
+ summaries.setItems((prev) => prev.map((p) => {
+ if (p.id !== projectId) return p;
+ const { name, status, updatedAt } = apply(p);
+ return { ...p, name, status, updatedAt };
+ }));
+ if (projectId === selectedId) setSelectedProject((prev) => (prev?.id === projectId ? apply(prev) : prev));
+ // A project that isn't open (a render finished after the user navigated away)
+ // takes the patch when it is next fetched.
+ else deferredPatches.current.set(projectId, [...(deferredPatches.current.get(projectId) || []), apply]);
+ };
+ const patchScene = (projectId, sceneId, patch) => patchProject(projectId, (project) => ({
+ scenes: (project.scenes || []).map((s) => (s.sceneId === sceneId ? { ...s, ...patch } : s)),
+ }));
const youtube = useMusicVideoYoutubeImport({
routeProjectId,
@@ -305,7 +375,7 @@ export default function MusicVideo() {
if (value) next.set('q', value); else next.delete('q');
return next;
}, { replace: true });
- const projectGroups = useMemo(() => groupMusicVideoProjects(projects, nameQuery), [projects, nameQuery]);
+ const projectGroups = useMemo(() => groupMusicVideoProjects(sortedProjects, nameQuery), [sortedProjects, nameQuery]);
const [pickedVersion, setPickedVersion] = useState({}); // rootId -> project id
useEffect(() => {
const onRunEvent = (data) => {
@@ -341,27 +411,6 @@ export default function MusicVideo() {
navigate(id ? `/music-video/${id}${search ? `?${search}` : ''}` : `/music-video${search ? `?${search}` : ''}`);
};
- const loadProjects = useCallback(async () => {
- if (projectsLoadPending.current) return;
- projectsLoadPending.current = true;
- setLoading(true);
- try {
- const data = await listMusicVideoProjects({ silent: true });
- const sorted = Array.isArray(data) ? [...data].sort(compareMusicVideoProjectsNewestFirst) : [];
- setProjects(sorted);
- setProjectsError(null);
- } catch (err) {
- setProjectsError(err?.message || 'Failed to load music video projects');
- } finally {
- projectsLoadPending.current = false;
- setLoading(false);
- }
- }, []);
-
- useEffect(() => {
- loadProjects();
- }, [loadProjects]);
-
useEffect(() => {
listTracks({ silent: true }).then((t) => setTracks(t || [])).catch(() => setTracks([]));
listUniverseNames({ silent: true }).then((u) => setUniverses(u || [])).catch(() => setUniverses([]));
@@ -403,7 +452,7 @@ export default function MusicVideo() {
...(form.mode === 'autonomous' ? { automation: automationFromDraft(form.automation) } : {}),
}, { silent: true })
.then((proj) => {
- setProjects((prev) => [proj, ...prev]);
+ openProject(proj);
selectProject(proj.id);
setForm(emptyCreateForm());
setCreateOpen(false);
@@ -433,7 +482,7 @@ export default function MusicVideo() {
}
deleteMusicVideoProject(id, { silent: true })
.then(() => {
- setProjects((prev) => prev.filter((p) => p.id !== id));
+ summaries.setItems((prev) => prev.filter((p) => p.id !== id));
if (selectedId === id) navigate('/music-video');
})
.catch((err) => toast.error(err?.message || 'Failed to delete project'));
@@ -448,7 +497,7 @@ export default function MusicVideo() {
setCloningId(target.id);
cloneMusicVideoProject(target.id, options, { silent: true })
.then((project) => {
- setProjects((prev) => [project, ...prev]);
+ openProject(project);
navigate(`/music-video/${project.id}${songRevision === true ? "/setup" : ""}`);
toast.success(`Created ${project.name}`);
})
@@ -620,7 +669,7 @@ export default function MusicVideo() {
.then((target) => updateMusicVideoProject(target.id, patch, { silent: true }).then((proj) => ({ proj, forked: target !== selected })))
.then(({ proj, forked }) => {
if (forked) {
- setProjects((prev) => [proj, ...prev]);
+ openProject(proj);
navigate(`/music-video/${proj.id}/setup`);
} else replaceProject(proj);
if (cleared.length > 0) toast.success('Track changed — re-run Analyze and Align words');
@@ -1084,13 +1133,14 @@ export default function MusicVideo() {
id="mv-project-picker"
value={selectedId || ''}
onChange={(e) => selectProject(e.target.value || null)}
+ onFocus={() => setSummariesWanted(true)}
disabled={loading || youtube.editJob.active}
className="min-w-0 w-full sm:w-72 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm disabled:opacity-50"
>
<option value="">{loading ? 'Loading projects…' : 'Select a project…'}</option>
{sortedProjects.map((project) => (
<option key={project.id} value={project.id}>
- {project.name} · {projectShotSummary(project)}
+ {project.name} · {project.shotSummary || projectShotSummary(project)}
</option>
))}
</select>
@@ -1209,14 +1259,14 @@ export default function MusicVideo() {
open={autonomousOpen}
onClose={() => setAutonomousOpen(false)}
onStarted={(proj) => {
- setProjects((prev) => [proj, ...prev]);
+ openProject(proj);
selectProject(proj.id);
setAutonomousOpen(false);
}}
/>
<div id={MUSIC_VIDEO_SCROLL_ID} className="min-h-0 flex-1 overflow-auto p-4 md:p-6">
- {projectsError && (
+ {projectsError && !selected && (
<Banner tone="error" size="md" title="Music video projects unavailable" className="mb-4" actions={(
<button
type="button"
@@ -1245,7 +1295,7 @@ export default function MusicVideo() {
<div className="text-center py-8 text-sm text-port-text-muted">
Loading projects…
</div>
- ) : projectsError ? null : projects.length === 0 ? (
+ ) : projectsError ? null : sortedProjects.length === 0 ? (
<div className="text-center py-6 text-sm text-port-text-muted">
No music video projects yet. Create your first project above to get started.
</div>
@@ -1253,7 +1303,7 @@ export default function MusicVideo() {
<div className="space-y-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<h2 className="text-sm font-semibold uppercase tracking-wider text-port-text-muted">
- Projects ({projectGroups.length})
+ Projects ({summaries.hasMore ? `${projectGroups.length}+` : projectGroups.length})
</h2>
<label htmlFor="mv-project-filter" className="sr-only">Filter projects by name</label>
<input
@@ -1295,6 +1345,13 @@ export default function MusicVideo() {
);
})}
</div>
+ <InfiniteScrollFooter
+ hasMore={summaries.hasMore}
+ loading={summaries.loading}
+ error={summaries.error}
+ onLoadMore={summaries.loadMore}
+ label="Load more projects"
+ />
</div>
)}
</div>
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index 1660765bff..d64869045c 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -44,6 +44,10 @@ vi.mock('../hooks/useMusicVideoProductionReview.js', () => ({ default: ({ projec
vi.mock('../services/apiMusicVideo.js', () => ({
listMusicVideoProjects: vi.fn(async () => []),
+ listMusicVideoProjectSummaries: vi.fn(async (params, options) => {
+ const res = await listMusicVideoProjects(params, options);
+ return Array.isArray(res) ? { items: res, total: res.length, nextCursor: null } : res;
+ }),
createMusicVideoProject: vi.fn(),
cloneMusicVideoProject: vi.fn(),
updateMusicVideoProject: vi.fn(async (id, patch) => ({
@@ -236,7 +240,7 @@ vi.mock('../components/PageHeader', () => ({ default: ({ title, actions }) => <d
import MusicVideo from './MusicVideo.jsx';
import {
- listMusicVideoProjects, createMusicVideoProject, cloneMusicVideoProject, renderMusicVideoProject, planMusicVideoProject, updateMusicVideoProject,
+ listMusicVideoProjects, listMusicVideoProjectSummaries, createMusicVideoProject, cloneMusicVideoProject, renderMusicVideoProject, planMusicVideoProject, updateMusicVideoProject,
deleteMusicVideoProject, transcribeMusicVideoMidi, cancelMusicVideoRender, analyzeMusicVideoProject,
importMusicVideoLyrics, importMusicVideoTrackLyrics, separateMusicVideoVocals, alignMusicVideoLyrics, updateMusicVideoScene, splitMusicVideoScene,
selectMusicVideoSceneTake, reviewMusicVideoSceneTake, importMusicVideoHandoff,
@@ -379,7 +383,15 @@ beforeEach(() => {
// Keep the real artifact iframe and src assertions without navigating to its API URL.
window.happyDOM.settings.navigation.disableChildFrameNavigation = true;
vi.clearAllMocks();
- getMusicVideoProject.mockImplementation(async id => (await listMusicVideoProjects()).find(project => project.id === id));
+ listMusicVideoProjects.mockReset();
+ listMusicVideoProjects.mockResolvedValue([]);
+ listMusicVideoProjectSummaries.mockReset();
+ listMusicVideoProjectSummaries.mockImplementation(async (params, options) => {
+ const res = await listMusicVideoProjects(params, options);
+ return Array.isArray(res) ? { items: res, total: res.length, nextCursor: null } : res;
+ });
+ getMusicVideoProject.mockReset();
+ getMusicVideoProject.mockImplementation(async id => (await listMusicVideoProjects({ silent: true })).find(project => project.id === id));
sseState.latest = null;
sseState.closed = false;
sseState.isOpen = true;
@@ -404,7 +416,14 @@ describe('MusicVideo project load recovery (#9761)', () => {
expect(screen.queryByText(/No music video projects yet/)).not.toBeInTheDocument();
expect(screen.queryByText(/Project not found/)).not.toBeInTheDocument();
expect(screen.getByTestId('loc')).toHaveTextContent(path);
- expect(listMusicVideoProjects).toHaveBeenCalledWith({ silent: true });
+ if (path === '/music-video') {
+ expect(listMusicVideoProjectSummaries).toHaveBeenCalledWith(
+ expect.objectContaining({ limit: 30 }),
+ expect.objectContaining({ silent: true }),
+ );
+ } else {
+ expect(getMusicVideoProject).toHaveBeenCalledWith('mv-2', { silent: true });
+ }
fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent('Still unavailable'));
@@ -412,7 +431,7 @@ describe('MusicVideo project load recovery (#9761)', () => {
fireEvent.click(retry);
expect(screen.getByRole('button', { name: 'Retrying…' })).toBeDisabled();
fireEvent.click(retry);
- expect(listMusicVideoProjects).toHaveBeenCalledTimes(3);
+ expect(path === '/music-video' ? listMusicVideoProjectSummaries : getMusicVideoProject).toHaveBeenCalledTimes(3);
expect(screen.queryByText(/No music video projects yet/)).not.toBeInTheDocument();
expect(screen.queryByText(/Project not found/)).not.toBeInTheDocument();
@@ -439,6 +458,71 @@ describe('MusicVideo project load recovery (#9761)', () => {
});
});
+describe('MusicVideo bounded summary index and project isolation (#10169)', () => {
+ it('opening /music-video/:id makes one project GET and no full-list call', async () => {
+ getMusicVideoProject.mockResolvedValue(PROJECT_WITH_CLIP);
+ render(
+ <MemoryRouter initialEntries={['/music-video/mv-1/board']}>
+ {MV_ROUTES}
+ </MemoryRouter>,
+ );
+ await screen.findByRole('heading', { level: 2, name: PROJECT_WITH_CLIP.name });
+ expect(getMusicVideoProject).toHaveBeenCalledTimes(1);
+ expect(getMusicVideoProject).toHaveBeenCalledWith('mv-1', { silent: true });
+ expect(listMusicVideoProjects).not.toHaveBeenCalled();
+ expect(listMusicVideoProjectSummaries).not.toHaveBeenCalled();
+ });
+
+ it('the index view loads summaries with cursor pagination', async () => {
+ listMusicVideoProjectSummaries.mockResolvedValue({
+ items: [
+ {
+ id: 'mv-summary-1',
+ name: 'Summary Video',
+ version: 1,
+ rootProjectId: 'mv-summary-1',
+ versionRoot: 'mv-summary-1',
+ stage: 'board',
+ status: 'ready',
+ runStatus: null,
+ poster: null,
+ preview: { kind: 'none', label: 'No render yet' },
+ spend: { spentUsd: 0, capUsd: null },
+ updatedAt: '2026-10-04T00:00:00Z',
+ sceneCount: 3,
+ shotSummary: '3 scenes',
+ },
+ ],
+ total: 1,
+ nextCursor: null,
+ });
+ render(
+ <MemoryRouter initialEntries={['/music-video']}>
+ {MV_ROUTES}
+ </MemoryRouter>,
+ );
+ expect(await screen.findByTestId('mv-project-grid')).toHaveTextContent('Summary Video');
+ expect(listMusicVideoProjectSummaries).toHaveBeenCalledWith(
+ expect.objectContaining({ limit: 30 }),
+ expect.anything(),
+ );
+ });
+
+ it('a list failure does not break an open project', async () => {
+ getMusicVideoProject.mockResolvedValue(PROJECT_WITH_CLIP);
+ listMusicVideoProjectSummaries.mockRejectedValueOnce(new Error('List network failure'));
+ listMusicVideoProjects.mockRejectedValueOnce(new Error('List network failure'));
+ render(
+ <MemoryRouter initialEntries={['/music-video/mv-1/board']}>
+ {MV_ROUTES}
+ </MemoryRouter>,
+ );
+ await screen.findByRole('heading', { level: 2, name: PROJECT_WITH_CLIP.name });
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ expect(screen.getByRole('heading', { level: 2, name: PROJECT_WITH_CLIP.name })).toBeInTheDocument();
+ });
+});
+
describe('MusicVideo project header', () => {
it('hides New project / Autonomous inside a project and renames it from the header', async () => {
await openProject(PROJECT_WITH_CLIP);
@@ -2600,7 +2684,7 @@ describe('MusicVideo main page project cards', () => {
});
it('navigates to project when clicking Open on its card', async () => {
- listMusicVideoProjects.mockResolvedValueOnce([PROJECT_WITH_CLIP]);
+ listMusicVideoProjects.mockResolvedValue([PROJECT_WITH_CLIP]);
renderMV();
const card = await screen.findByTestId(`mv-project-card-${PROJECT_WITH_CLIP.id}`);
diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.js
index 816613e99e..cd6f49f983 100644
--- a/client/src/services/apiMusicVideo.js
+++ b/client/src/services/apiMusicVideo.js
@@ -5,6 +5,14 @@ import { request } from './apiCore.js';
// request()'s auto-toast with `{ silent: true }` when it owns its own error UI.
export const listMusicVideoProjects = (options = {}) => request('/music-video', options);
+// Bounded, newest-first summary page (#10169) — `{ items, total, nextCursor }`
+// for the index and header picker, never the full project records.
+export const listMusicVideoProjectSummaries = ({ cursor, limit } = {}, options = {}) => {
+ const query = new URLSearchParams({ summary: '1' });
+ if (limit != null) query.set('limit', String(limit));
+ if (cursor != null) query.set('cursor', String(cursor));
+ return request(`/music-video?${query}`, options);
+};
export const createMusicVideoProject = (data, options = {}) => request('/music-video', {
method: 'POST', body: JSON.stringify(data), ...options,
});
diff --git a/server/lib/README.md b/server/lib/README.md
index 050dceebfc..2b11a0edf1 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -844,6 +844,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `musicVideoMediaPolicy.js` | Whole-workflow media modes, legacy intent, selection admission and independent document renderer choice. |
+| `musicVideoSummary.js` | `summarizeMusicVideoProject(project, readiness)` bounded index/picker projection (stage, run status, spend, preview/poster, card badges) and `compareMusicVideoProjectsNewestFirst` for `GET /api/music-video?summary=1` (#10169). |
+
| `sandboxDelegation.js` | Bounded tool-free worker context, route configuration, and fidelity evaluation schemas. |
| `forgeMaintenanceTasks.js` | Current forge-maintenance screening version, queue-compatible identity check, task classification, and legacy refusal reason. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 8704ad8887..112355d777 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -826,6 +826,7 @@ export * from './scheduleExecutionFieldsValidation.js';
export * from './codeAnimationSound.js';
export * from './musicVideoMediaPolicy.js';
+export * from './musicVideoSummary.js';
export * from './sandboxDelegation.js';
export * from './forgeMaintenanceTasks.js';
diff --git a/server/lib/musicVideoSummary.js b/server/lib/musicVideoSummary.js
new file mode 100644
index 0000000000..0e657623aa
--- /dev/null
+++ b/server/lib/musicVideoSummary.js
@@ -0,0 +1,154 @@
+/**
+ * Music Video project summary projection (#10169).
+ *
+ * `GET /api/music-video?summary=1` returns one bounded record per project — just
+ * what the project index card and the header picker render — so the index never
+ * ships every project's scenes, excerpts, revisions, runs and reviews. The stage
+ * / spend / preview rules mirror `client/src/lib/musicVideoStages.js` and
+ * `musicVideoPreview.js`, which still derive them for a full record.
+ */
+import { isLayeredComposition, sceneRenderReady } from './musicVideoLayers.js';
+
+const STAGE_IDS = ['setup', 'cast-sets', 'board', 'produce', 'compose', 'review', 'publish'];
+const RESUMABLE_RUN_STATUSES = new Set(['running', 'stopped', 'limit-reached', 'blocked', 'needs-replan']);
+const FOOTAGE_OPTIONAL_MODES = new Set(['code', 'document', 'eidoverse']);
+
+const nonEmptyString = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);
+const imageSrc = (assetId) => (/^(https?:|data:|blob:)/i.test(assetId) || assetId.startsWith('/') ? assetId : `/data/images/${assetId}`);
+const imageFallback = (assetId) => (assetId.includes('.') ? null : `/data/images/${assetId}.png`);
+
+const currentRun = (project) => {
+ const runs = Array.isArray(project.productionRuns) ? project.productionRuns : [];
+ return runs.find((r) => RESUMABLE_RUN_STATUSES.has(r.status)) || runs[runs.length - 1] || null;
+};
+
+function projectSpend(project, run) {
+ const runs = Array.isArray(project.productionRuns) ? project.productionRuns : [];
+ const spentUsd = runs.reduce((sum, r) => {
+ const spent = Number(r?.usage?.spentUsd);
+ return sum + (Number.isFinite(spent) ? spent : 0);
+ }, 0);
+ const capUsd = run?.limits?.spendCapUsd ?? project.automation?.budgetUsd ?? null;
+ return { spentUsd, capUsd };
+}
+
+function composeDone(project, mode) {
+ const composition = project.composition || {};
+ if (mode === 'composed') return (composition.textCues || []).length > 0;
+ if (mode === 'document') return Boolean(composition.document);
+ if (mode === 'eidoverse') return Boolean(composition.eidoverseScene?.inlineScript);
+ if (mode === 'code') return Boolean(composition.codeVideo?.generatedAt || (composition.codeVideo?.sections || []).length > 0);
+ return true;
+}
+
+// The first stage not yet done; a live production run pins Produce.
+function currentStage(project, readiness, run) {
+ if (run && RESUMABLE_RUN_STATUSES.has(run.status)) return 'produce';
+ const scenes = project.scenes || [];
+ const mode = project.composition?.mode || 'concat';
+ const layered = isLayeredComposition(project);
+ const planned = Boolean(readiness?.storyboard?.approved);
+ const proofApproved = Boolean(readiness?.proof?.approved);
+ const footageReady = FOOTAGE_OPTIONAL_MODES.has(mode) || scenes.every((scene) => sceneRenderReady(scene, { layered }));
+ const done = {
+ setup: Boolean(project.trackId || project.uploadedAudioFilename) && Boolean(project.audioAnalysis),
+ 'cast-sets': Boolean(readiness?.art?.approved),
+ board: planned,
+ produce: planned && footageReady && proofApproved,
+ compose: proofApproved && composeDone(project, mode),
+ review: Boolean(project.renderHistoryId),
+ publish: Object.keys(project.publishKit?.posts || {}).length > 0,
+ };
+ return STAGE_IDS.find((id) => !done[id]) || 'publish';
+}
+
+function projectPreview(project) {
+ const finalId = nonEmptyString(project.renderHistoryId);
+ const video = (jobId, label, src = `/data/videos/${jobId}.mp4`) => ({
+ kind: 'video', jobId, src, poster: jobId ? `/data/video-thumbnails/${jobId}.jpg` : null, label,
+ });
+ if (finalId) return video(finalId, 'Final video');
+
+ const excerpts = Array.isArray(project.excerpts) ? project.excerpts : [];
+ const excerpt = [...excerpts].reverse().find((e) => e.status === 'complete' && (e.filename || e.jobId));
+ if (excerpt) {
+ const jobId = nonEmptyString(excerpt.jobId);
+ const filename = nonEmptyString(excerpt.filename);
+ return video(jobId, excerpt.label || 'Latest excerpt', filename ? `/data/videos/${filename}` : (jobId ? `/data/videos/${jobId}.mp4` : null));
+ }
+
+ const scenes = Array.isArray(project.scenes) ? project.scenes : [];
+ for (let i = scenes.length - 1; i >= 0; i -= 1) {
+ const jobId = nonEmptyString(scenes[i]?.videoHistoryId);
+ if (jobId) return video(jobId, `Scene ${i + 1} clip`);
+ }
+ for (let i = scenes.length - 1; i >= 0; i -= 1) {
+ const frameId = nonEmptyString(scenes[i]?.referenceImageId);
+ if (frameId) return { kind: 'image', src: imageSrc(frameId), fallbackSrc: imageFallback(frameId), label: `Scene ${i + 1} frame` };
+ }
+ const reference = project.visualSpec?.references?.[0];
+ const refId = nonEmptyString(reference?.imageId);
+ if (refId) return { kind: 'image', src: imageSrc(refId), fallbackSrc: imageFallback(refId), label: reference.label || 'Style reference' };
+ return { kind: 'none', label: 'No render yet' };
+}
+
+function shotSummary(project) {
+ const draft = project.productionReview?.draft;
+ const document = project.composition?.mode === 'document' && draft?.storyboardSource === 'document';
+ const count = (document ? draft.storyboard : project.scenes)?.length || 0;
+ return `${count} ${document ? 'document shot' : 'scene'}${count === 1 ? '' : 's'}`;
+}
+
+/** Newest created first, then newest updated — the order the index and picker show. */
+export function compareMusicVideoProjectsNewestFirst(a, b) {
+ const created = (Date.parse(b?.createdAt || b?.updatedAt) || 0) - (Date.parse(a?.createdAt || a?.updatedAt) || 0);
+ return created || (Date.parse(b?.updatedAt) || 0) - (Date.parse(a?.updatedAt) || 0);
+}
+
+/**
+ * Bounded projection of one project. `readiness` is the server's
+ * `productionReadiness(project)` (approvals decide the stage, and only the
+ * server computes them). Nested objects keep the shape of the full record so
+ * the project card reads a summary and a full project the same way.
+ */
+export function summarizeMusicVideoProject(project, readiness) {
+ const run = currentRun(project);
+ const scenes = Array.isArray(project.scenes) ? project.scenes : [];
+ const preview = projectPreview(project);
+ const video = project.videoSettings || {};
+ const concept = project.concept || {};
+ return {
+ id: project.id,
+ name: project.name,
+ version: project.version || 1,
+ rootProjectId: project.rootProjectId || project.id,
+ versionRoot: project.rootProjectId || project.id,
+ parentProjectId: project.parentProjectId || null,
+ mode: project.mode || 'director',
+ status: project.status || 'draft',
+ stage: currentStage(project, readiness, run),
+ runStatus: project.autonomousRun?.status || run?.status || null,
+ runInterrupted: Boolean(project.autonomousRun?.interrupted || project.castAndSets?.interrupted || run?.interrupted),
+ runAwaiting: project.autonomousRun?.status === 'awaiting-approval',
+ poster: preview.poster || (preview.kind === 'image' ? preview.src : null),
+ preview,
+ spend: projectSpend(project, run),
+ shotSummary: shotSummary(project),
+ sceneCount: scenes.length,
+ clipCount: scenes.filter((s) => s.videoHistoryId).length,
+ frameCount: scenes.filter((s) => s.referenceImageId).length,
+ createdAt: project.createdAt,
+ updatedAt: project.updatedAt,
+ trackId: project.trackId || null,
+ uploadedAudioFilename: project.uploadedAudioFilename || null,
+ audioAnalysis: project.audioAnalysis?.bpm ? { bpm: project.audioAnalysis.bpm } : null,
+ videoSettings: {
+ backend: video.backend, modelId: video.modelId, generationMode: video.generationMode, audioReactiveLora: video.audioReactiveLora,
+ },
+ vocalStemFilename: project.vocalStemFilename || null,
+ midiTranscription: Boolean(project.midiTranscription),
+ composition: { mode: project.composition?.mode },
+ concept: { style: concept.style || concept.prompt || null, universeId: concept.universeId || null },
+ visualSpec: { palette: Array.isArray(project.visualSpec?.palette) ? project.visualSpec.palette.slice(0, 5) : [] },
+ };
+}
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index acb2e18f54..f3a2653a20 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -1305,3 +1305,13 @@ export const musicVideoProductionFeedbackSchema = z.object({
export const musicVideoProductionFeedbackResolutionSchema = z.object({
feedbackId: z.string().min(1).max(128), resolution: z.string().trim().min(1).max(8000), password: z.string().max(1024).optional(),
}).strict();
+
+// GET /api/music-video query (#10169). Passthrough strings, like the other list
+// queries: `parsePagination` clamps `limit`/`offset`, and a malformed `cursor`
+// (an offset the summary page issued) falls back to the first page.
+export const musicVideoProjectListQuerySchema = z.object({
+ summary: z.enum(['1', 'true', '0', 'false']).optional(),
+ limit: z.string().optional(),
+ offset: z.string().optional(),
+ cursor: z.string().max(64).optional(),
+});
diff --git a/server/routeValidationConventions.test.js b/server/routeValidationConventions.test.js
index 4ee7137eef..5e08ed23d8 100644
--- a/server/routeValidationConventions.test.js
+++ b/server/routeValidationConventions.test.js
@@ -282,7 +282,6 @@ const UNVALIDATED_QUERY_BASELINE = [
'routes/moltworldTools.js GET /status',
'routes/moodBoard.js GET /',
'routes/music.js POST /setup/runtime-install',
- 'routes/musicVideo.js GET /',
'routes/notifications.js GET /',
'routes/openclaw.js GET /sessions/:id/messages',
'routes/peerSync.js GET /cos-agent-archive',
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index a50ad6a2a6..b2881bfc97 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -11,7 +11,8 @@
import { existsSync } from 'fs';
import { unlink } from 'fs/promises';
import { Router } from 'express';
-import { musicVideoProductionDraftSchema, musicVideoProductionApprovalSchema, musicVideoProductionProofSchema, musicVideoProductionImportSchema, musicVideoProductionFeedbackSchema, musicVideoProductionFeedbackResolutionSchema } from '../lib/musicVideoValidation.js';
+import { musicVideoProjectListQuerySchema, musicVideoProductionDraftSchema, musicVideoProductionApprovalSchema, musicVideoProductionProofSchema, musicVideoProductionImportSchema, musicVideoProductionFeedbackSchema, musicVideoProductionFeedbackResolutionSchema } from '../lib/musicVideoValidation.js';
+import { productionReadiness } from '../services/musicVideo/productionReview.js';
import { getProductionReview, saveProductionDraft, prepareProductionReview, approveProductionReview, renderProductionProof, requireProductionReviewer, importProductionPlanning, bindProductionShot, addProductionFeedback, closeProductionFeedback } from '../services/musicVideo/productionReviewService.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import {
@@ -182,6 +183,10 @@ import {
getCastAndSets,
presentProjectCastAndSets,
} from '../services/musicVideo/castAndSetsService.js';
+import {
+ summarizeMusicVideoProject,
+ compareMusicVideoProjectsNewestFirst,
+} from '../lib/musicVideoSummary.js';
const router = Router();
@@ -200,15 +205,29 @@ const projectUpdateSchema = musicVideoProjectUpdateSchema.extend(recordRenderPin
// Backward-compatible by default: returns the full projects array. When a client
// passes `limit`/`offset`, the response becomes the bounded
// `{ items, total, limit, offset }` envelope every paginated PortOS list shares.
+// `summary=1` (#10169) swaps each record for its bounded summary projection —
+// newest first, with a `nextCursor` — for the project index and header picker, so
+// they never load every project's scenes, runs and reviews.
// Both pins are process-local, so only the server can say which stages a restart orphaned.
const presentProjectForRead = (project) => presentProjectAutonomousRun(presentProjectCastAndSets(project));
router.get('/', asyncHandler(async (req, res) => {
+ const query = validateRequest(musicVideoProjectListQuerySchema, req.query);
const projects = (await listProjects()).map(presentProjectForRead);
- if (!isPaginationRequested(req.query)) {
+ if (query.summary === '1' || query.summary === 'true') {
+ const summaries = projects.sort(compareMusicVideoProjectsNewestFirst)
+ .map((project) => summarizeMusicVideoProject(project, productionReadiness(project)));
+ // The cursor is the next page's offset; `cursor` wins over `offset`.
+ const cursor = parseInt(query.cursor, 10);
+ const page = paginateArray(summaries, Number.isInteger(cursor) && cursor >= 0 ? { ...query, offset: String(cursor) } : query,
+ { defaultLimit: 50, maxLimit: 500 });
+ const next = page.offset + page.items.length;
+ return res.json({ ...page, nextCursor: next < page.total ? String(next) : null });
+ }
+ if (!isPaginationRequested(query)) {
return res.json(projects);
}
- res.json(paginateArray(projects, req.query, { defaultLimit: 50, maxLimit: 500 }));
+ res.json(paginateArray(projects, query, { defaultLimit: 50, maxLimit: 500 }));
}));
router.get('/:id', asyncHandler(async (req, res) => {
diff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.js
index 193dfbb0bd..180a09eec8 100644
--- a/server/routes/musicVideo.test.js
+++ b/server/routes/musicVideo.test.js
@@ -124,6 +124,60 @@ describe('musicVideo routes', () => {
expect(r.body.offset).toBe(1);
});
+ it('GET /?summary=1 returns bounded summary projections with cursor pagination (#10169)', async () => {
+ const p1 = {
+ id: 'mv-older',
+ name: 'Older Project',
+ version: 1,
+ createdAt: '2026-01-01T00:00:00Z',
+ updatedAt: '2026-01-01T00:00:00Z',
+ scenes: [{ sceneId: 's1' }],
+ productionRuns: [{ status: 'complete', usage: { spentUsd: 1.25 } }],
+ };
+ const p2 = {
+ id: 'mv-newer',
+ name: 'Newer Project',
+ version: 2,
+ rootProjectId: 'mv-root',
+ createdAt: '2026-02-01T00:00:00Z',
+ updatedAt: '2026-02-01T00:00:00Z',
+ scenes: [{ sceneId: 's1' }, { sceneId: 's2' }],
+ productionRuns: [{ status: 'running', limits: { spendCapUsd: 5.0 }, usage: { spentUsd: 0.5 } }],
+ };
+ svc.listProjects.mockResolvedValue([p1, p2]);
+
+ // Page 1: limit=1
+ const r1 = await request(app).get('/api/music-video?summary=1&limit=1');
+ expect(r1.status).toBe(200);
+ expect(r1.body.total).toBe(2);
+ expect(r1.body.limit).toBe(1);
+ expect(r1.body.offset).toBe(0);
+ expect(r1.body.nextCursor).toBe('1');
+ expect(r1.body.items).toHaveLength(1);
+
+ const first = r1.body.items[0];
+ expect(first.id).toBe('mv-newer');
+ expect(first.name).toBe('Newer Project');
+ expect(first.version).toBe(2);
+ expect(first.rootProjectId).toBe('mv-root');
+ expect(first.versionRoot).toBe('mv-root');
+ expect(first.stage).toBe('produce');
+ expect(first.status).toBe('draft');
+ expect(first.runStatus).toBe('running');
+ expect(first.spend).toEqual({ spentUsd: 0.5, capUsd: 5.0 });
+ expect(first.updatedAt).toBe('2026-02-01T00:00:00Z');
+ expect(first.scenes).toBeUndefined();
+
+ // Page 2: limit=1, cursor=1
+ const r2 = await request(app).get(`/api/music-video?summary=1&limit=1&cursor=${r1.body.nextCursor}`);
+ expect(r2.status).toBe(200);
+ expect(r2.body.total).toBe(2);
+ expect(r2.body.offset).toBe(1);
+ expect(r2.body.nextCursor).toBeNull();
+ expect(r2.body.items).toHaveLength(1);
+ expect(r2.body.items[0].id).toBe('mv-older');
+ });
+
it('GET /:id 404s when missing', async () => {
svc.getProject.mockResolvedValue(null);
const r = await request(app).get('/api/music-video/mv-x');