Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: make Music Video autonomous-run output visible and drop the duplicate stage strip (#9585)
[._.]/ Adam Eivy0f76bc57a00e
diff --git a/client/src/components/musicVideo/AutonomousRunPanel.jsx b/client/src/components/musicVideo/AutonomousRunPanel.jsxindex ee262228f8..b5db712ea7 100644--- a/client/src/components/musicVideo/AutonomousRunPanel.jsx+++ b/client/src/components/musicVideo/AutonomousRunPanel.jsx@@ -1,7 +1,9 @@import { useState } from 'react';-import { AlertTriangle, CheckCircle2, Circle, CircleDot, Loader2, Pause, Play, Wand2, X, XCircle } from 'lucide-react';+import { Link } from 'react-router';+import { AlertTriangle, CheckCircle2, Circle, CircleDot, ExternalLink, Loader2, Pause, Play, Wand2, X, XCircle } from 'lucide-react';import {- AUTONOMOUS_CHECKPOINT_LABELS, AUTONOMOUS_STATUS_LABELS, autonomousStageRows, isAutonomousLive,+ AUTONOMOUS_CHECKPOINT_LABELS, AUTONOMOUS_SONG_STEP_LABELS, AUTONOMOUS_STATUS_LABELS, AUTONOMOUS_VIEWABLE_STAGES,+ autonomousStageOutput, autonomousStageRows, isAutonomousLive,} from '../../lib/musicVideoAutonomous.js';const STATUS_TONES = {@@ -17,14 +19,39 @@ const STAGE_MARKS = {const inputClass = 'w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm';const buttonClass = 'flex items-center gap-1 rounded border border-port-border bg-port-bg px-3 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50';+/** The read-only output of one stage the director opened from the checklist. */+function StageOutput({ run, row, editableBelow }) {+ const fields = autonomousStageOutput(run, row.id);+ return (+ <div id={`mv-run-stage-${row.id}`} role="region" aria-label={`${row.label} output`} className="rounded border border-port-border bg-port-bg p-2 space-y-2 min-w-0">+ {fields.length === 0 && <p className="text-xs text-port-text-muted">This stage did not store anything to show.</p>}+ {fields.map((field) => (+ <div key={field.key} className="min-w-0">+ <div className="text-xs text-port-text-muted">{field.label}</div>+ {field.href ? (+ <Link to={field.href} className="inline-flex items-center gap-1 text-sm text-port-accent hover:underline min-h-[44px] sm:min-h-0">+ {field.text} <ExternalLink size={12} aria-hidden="true" />+ </Link>+ ) : (+ <p className={`text-sm break-words ${field.multiline ? 'whitespace-pre-wrap' : ''} ${field.mono ? 'font-mono text-xs' : ''}`}>{field.text}</p>+ )}+ </div>+ ))}+ {editableBelow && <p className="text-xs text-port-text-muted">Edit this in the approval box below before continuing.</p>}+ </div>+ );+}+/*** The fully-autonomous run on a project: where it is in the pipeline, what it is* waiting for, and the few things the director can do — approve a checkpoint* (optionally with edited lyrics or Suno style), retry the stage that stopped,- * pause, or cancel. Progress arrives over `music-video:autonomous` through+ * pause, or cancel. A finished stage's output (brief, lyrics, style, song) opens+ * read-only from its checklist row; the open row is the caller's URL state+ * (`selectedStage` / `onSelectStage`). Progress arrives over `music-video:autonomous` through* `useAutonomousMusicVideo`; this panel only renders the run it is given.*/-export default function AutonomousRunPanel({ project, auto }) {+export default function AutonomousRunPanel({ project, auto, selectedStage = null, onSelectStage }) {const run = project?.autonomousRun;const [edit, setEdit] = useState(null); // { for: stage, value } — the director's edit at a checkpointif (!run) return null;@@ -39,6 +66,9 @@ export default function AutonomousRunPanel({ project, auto }) {const changed = editable && draft !== editable.value;const canRetry = ['needs-human', 'failed', 'stopped'].includes(run.status) || run.interrupted;const tone = STATUS_TONES[run.status] || '';+ // A stale or hand-edited `?run-stage=` that names no finished, viewable stage opens nothing.+ const selectedRow = rows.find((row) => row.id === selectedStage && row.status === 'done' && AUTONOMOUS_VIEWABLE_STAGES.includes(row.id)) || null;+ const selected = selectedRow?.id || null;return (<section className="bg-port-card border border-port-border rounded-lg p-3 space-y-3 min-w-0" aria-label="Autonomous run">@@ -53,16 +83,42 @@ export default function AutonomousRunPanel({ project, auto }) {<ol aria-label="Autonomous stages" className="grid grid-cols-[repeat(auto-fit,minmax(min(100%,11rem),1fr))] gap-x-3 gap-y-1 text-xs">{rows.map((row) => {const { Icon, cls, label } = STAGE_MARKS[row.status] || STAGE_MARKS.pending;- return (- <li key={row.id} aria-current={row.current ? 'step' : undefined} className={`flex min-w-0 items-center gap-1 ${row.current ? 'font-medium text-port-text' : 'text-port-text-muted'}`}>- {row.current && row.status === 'pending' ? <CircleDot size={13} className="shrink-0 text-port-accent" aria-hidden="true" /> : <Icon size={13} className={`shrink-0 ${cls}`} aria-hidden="true" />}+ const mark = row.current && row.status === 'pending' ? <CircleDot size={13} className="shrink-0 text-port-accent" aria-hidden="true" /> : <Icon size={13} className={`shrink-0 ${cls}`} aria-hidden="true" />;+ const content = (+ <>+ {mark}<span className="truncate">{row.label}</span><span className="sr-only">({label})</span>+ </>+ );+ const tone = row.current ? 'font-medium text-port-text' : 'text-port-text-muted';+ // Only a stage that finished and keeps something to show opens.+ const openable = row.status === 'done' && AUTONOMOUS_VIEWABLE_STAGES.includes(row.id) && onSelectStage;+ return (+ <li key={row.id} aria-current={row.current ? 'step' : undefined} className="min-w-0">+ {openable ? (+ <button+ type="button"+ aria-expanded={selected === row.id}+ aria-controls={`mv-run-stage-${row.id}`}+ onClick={() => onSelectStage(selected === row.id ? null : row.id)}+ className={`flex w-full min-w-0 items-center gap-1 rounded px-1 -mx-1 min-h-[44px] sm:min-h-0 hover:bg-port-bg ${selected === row.id ? 'bg-port-bg' : ''} ${tone}`}+ >+ {content}+ </button>+ ) : (+ <span className={`flex min-w-0 items-center gap-1 ${tone}`}>{content}</span>+ )}+ {row.id === 'song' && row.status === 'running' && row.step && (+ <p role="status" className="pl-[17px] text-port-accent break-words">{AUTONOMOUS_SONG_STEP_LABELS[row.step] || row.step}…</p>+ )}</li>);})}</ol>+ {selectedRow && <StageOutput run={run} row={selectedRow} editableBelow={!!editable && awaiting === selectedRow.id} />}+{run.error && (<p role="status" className="flex items-start gap-1 text-xs text-port-warning break-words min-w-0"><AlertTriangle size={13} className="mt-0.5 shrink-0" aria-hidden="true" /> <span className="min-w-0">{run.error}</span>diff --git a/client/src/components/musicVideo/AutonomousRunPanel.test.jsx b/client/src/components/musicVideo/AutonomousRunPanel.test.jsxindex 7976e7605c..6ec5e6fddc 100644--- a/client/src/components/musicVideo/AutonomousRunPanel.test.jsx+++ b/client/src/components/musicVideo/AutonomousRunPanel.test.jsx@@ -9,6 +9,7 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import { useState } from 'react';import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';+import { MemoryRouter, useSearchParams } from 'react-router';const listeners = vi.hoisted(() => new Map());vi.mock('../../services/socket', () => ({@@ -43,10 +44,22 @@ const baseRun = (over = {}) => ({brief: { origin: { kind: 'manual' } }, stages: stages(), output: { lyrics: '[verse]\nrain', sunoStyle: 'synthwave' }, ...over,});-function Harness({ initial }) {+// The page owns `?run-stage=`; the harness does the same so the panel's rows drive a real URL.+function PanelWithUrl({ project, auto }) {+ const [params, setParams] = useSearchParams();+ const onSelectStage = (id) => setParams((prev) => { const next = new URLSearchParams(prev); if (id) next.set('run-stage', id); else next.delete('run-stage'); return next; });+ return (+ <>+ <AutonomousRunPanel project={project} auto={auto} selectedStage={params.get('run-stage')} onSelectStage={onSelectStage} />+ <div data-testid="search">{params.toString()}</div>+ </>+ );+}++function Harness({ initial, url = '/music-video/mv-1' }) {const [project, setProject] = useState({ id: 'mv-1', autonomousRun: initial });const auto = useAutonomousMusicVideo({ project, replaceProject: setProject });- return <AutonomousRunPanel project={project} auto={auto} />;+ return <MemoryRouter initialEntries={[url]}><PanelWithUrl project={project} auto={auto} /></MemoryRouter>;}beforeEach(() => {@@ -105,6 +118,76 @@ describe('AutonomousRunPanel', () => {});});+describe('AutonomousRunPanel stage output', () => {+ const finished = (over = {}) => baseRun({+ status: 'running', stage: 'song',+ stages: stages({ style: { status: 'done' }, song: { status: 'done' } }),+ output: {+ title: 'Neon Rain', musicalDescription: 'Slow synthwave.', concept: { prompt: 'A courier in rain', style: 'Teal and magenta' },+ lyrics: '[verse]\nrain on glass', sunoStyle: 'synthwave, 90 bpm', moodBoardId: 'board-1', moodBoard: { name: 'Neon Rain board' },+ sunoSongIds: ['song-a', 'song-b'], songSource: 'suno',+ },+ ...over,+ });++ it('opens a finished stage’s output read-only from its row and writes the choice to the URL', () => {+ render(<Harness initial={finished()} />);+ expect(screen.queryByRole('region', { name: /lyrics output/i })).toBeNull();+ const row = screen.getByRole('button', { name: /lyrics/i });+ expect(row.getAttribute('aria-expanded')).toBe('false');++ fireEvent.click(row);+ const region = screen.getByRole('region', { name: /lyrics output/i });+ expect(region.textContent).toContain('rain on glass');+ expect(row.getAttribute('aria-expanded')).toBe('true');+ expect(screen.getByTestId('search').textContent).toBe('run-stage=lyrics');+ // Read-only: the stage output is text, not a form field.+ expect(region.querySelector('textarea, input')).toBeNull();++ fireEvent.click(row);+ expect(screen.queryByRole('region', { name: /lyrics output/i })).toBeNull();+ expect(screen.getByTestId('search').textContent).toBe('');+ });++ it('deep-links: a ?run-stage= URL opens that stage, and the style and song outputs stay viewable after the run moved on', () => {+ const { unmount } = render(<Harness initial={finished()} url="/music-video/mv-1?run-stage=style" />);+ const style = screen.getByRole('region', { name: /mood board & style output/i });+ expect(style.textContent).toContain('synthwave, 90 bpm');+ expect(style.textContent).toContain('Teal and magenta');+ // The run's mood board is a link to the board page.+ expect(screen.getByRole('link', { name: /neon rain board/i }).getAttribute('href')).toBe('/mood-boards/board-1');+ unmount();++ render(<Harness initial={finished({ status: 'completed', stage: 'produce' })} url="/music-video/mv-1?run-stage=song" />);+ expect(screen.getByRole('region', { name: /song output/i }).textContent).toContain('song-a, song-b');+ });++ it('opens nothing for a stage that has not finished, is not viewable, or is not a stage at all', () => {+ render(<Harness initial={finished({ stages: stages({ lyrics: { status: 'running' } }) })} url="/music-video/mv-1?run-stage=lyrics" />);+ expect(screen.queryByRole('region', { name: / output$/i })).toBeNull();+ // Unfinished and non-viewable rows are plain text, not buttons.+ expect(screen.queryByRole('button', { name: /produce video/i })).toBeNull();+ expect(screen.queryByRole('button', { name: /analyze song/i })).toBeNull();+ });++ it('points a checkpoint stage at the approval box instead of offering a second editor', () => {+ render(<Harness initial={finished({ status: 'awaiting-approval', awaiting: 'lyrics', stage: 'style', stages: stages({ style: { status: 'pending' } }) })} url="/music-video/mv-1?run-stage=lyrics" />);+ expect(screen.getByRole('region', { name: /lyrics output/i }).textContent).toMatch(/edit this in the approval box/i);+ expect(screen.getAllByLabelText(/lyrics \(edit before continuing\)/i)).toHaveLength(1);+ });++ it('shows the Song stage’s current sub-step while it runs and updates it from a pushed event', async () => {+ const running = (step) => baseRun({ stage: 'song', stages: stages({ style: { status: 'done' }, song: { status: 'running', step } }) });+ render(<Harness initial={running('generating')} />);+ expect(screen.getByRole('status').textContent).toContain('Generating the song on Suno');++ await act(async () => {+ listeners.get('music-video:autonomous')({ projectId: 'mv-1', run: running('exporting'), project: { id: 'mv-1', autonomousRun: running('exporting') } });+ });+ expect(screen.getByRole('status').textContent).toContain('Exporting the M4A');+ });+});+describe('AutonomousStartDrawer', () => {it('starts a run from the prompt alone, sending the free tools, no checkpoints and no blank optionals', async () => {api.startAutonomousMusicVideo.mockResolvedValue({ project: { id: 'mv-new', name: 'New' }, run: baseRun() });diff --git a/client/src/components/musicVideo/MusicVideoLayout.jsx b/client/src/components/musicVideo/MusicVideoLayout.jsxindex 54bda05e0a..561f90706d 100644--- a/client/src/components/musicVideo/MusicVideoLayout.jsx+++ b/client/src/components/musicVideo/MusicVideoLayout.jsx@@ -1,6 +1,6 @@import { useEffect, useRef, useState } from 'react';import {- AlertTriangle, ArrowRight, CheckCircle2, Circle, CircleDot, Clapperboard, Film, Layers, LayoutGrid, Music, Play,+ AlertTriangle, ArrowRight, CheckCircle2, CircleDot, Clapperboard, Film, Layers, LayoutGrid, Music, Play,Send, SlidersHorizontal, Users,} from 'lucide-react';import TabPills from '../ui/TabPills.jsx';@@ -14,11 +14,13 @@ const STAGE_ICONS = {setup: SlidersHorizontal, 'cast-sets': Users, board: LayoutGrid, produce: Clapperboard, compose: Layers, review: Film,publish: Send,};-const STATE_MARKS = {- done: { Icon: CheckCircle2, cls: 'text-port-success', label: 'done' },- active: { Icon: CircleDot, cls: 'text-port-accent', label: 'in progress' },- blocked: { Icon: AlertTriangle, cls: 'text-port-warning', label: 'needs you' },- todo: { Icon: Circle, cls: 'text-port-text-muted', label: 'not started' },+// The tab bar is the one stage row, so each tab carries its own status mark. The+// quiet marks (done, in progress) drop out below `lg`, where the bar is icons+// only; "needs you" always shows.+const STAGE_TRAILING = {+ done: <CheckCircle2 size={12} className="shrink-0 text-port-success max-lg:hidden" aria-label="done" />,+ active: <CircleDot size={12} className="shrink-0 text-port-accent max-lg:hidden" aria-label="in progress" />,+ blocked: <AlertTriangle size={12} className="shrink-0 text-port-warning" aria-label="needs you" />,};// Below `lg` the preview is a mini-player pinned above the bottom tab bar (or@@ -27,34 +29,11 @@ const STATE_MARKS = {// scroll container's md:p-6, which sticky offsets are measured inside of).const DOCK_CLASSES = 'max-lg:fixed max-lg:inset-x-0 max-lg:bottom-0 max-lg:z-30 max-lg:max-h-[70vh] max-lg:overflow-y-auto max-md:bottom-[calc(env(safe-area-inset-bottom)+3rem)] lg:sticky lg:top-[calc(var(--mv-header-h,9rem)-0.75rem)] lg:max-h-[calc(100vh-var(--mv-header-h,9rem)-2rem)] lg:overflow-y-auto';-/** Progress through the pipeline. Status only — the tabs below are the navigation. */-function ProgressStrip({ stages, current }) {- return (- <ol aria-label="Progress" className="flex min-w-0 items-center gap-x-3 gap-y-1 overflow-hidden text-xs">- {stages.map((stage) => {- const { Icon, cls, label } = STATE_MARKS[stage.state];- const isCurrent = stage.id === current;- return (- <li- key={stage.id}- aria-current={isCurrent ? 'step' : undefined}- data-state={stage.state}- className={`flex shrink-0 items-center gap-1 ${isCurrent ? 'font-medium text-port-text' : 'text-port-text-muted'}`}- >- <Icon size={13} className={`shrink-0 ${cls}`} aria-hidden="true" />- <span className={isCurrent ? '' : 'max-sm:sr-only'}>{stage.title}</span>- <span className="sr-only">({label})</span>- </li>- );- })}- </ol>- );-}-/**- * The Music Video project frame: a sticky header (name, track, spend, the- * progress strip and the one next action for the project's stage), the stage- * tabs — on top from `md` up, a bottom tab bar on a phone — the active stage's+ * The Music Video project frame: a sticky header (name, track, spend and the+ * one next action for the project's stage), the stage tabs — the single stage+ * row, each tab marking its stage done / in progress / needs you — on top from+ * `md` up, a bottom tab bar on a phone — the active stage's* content, and the docked preview player beside it on the Board, Compose and* Review tabs.*@@ -97,9 +76,7 @@ export default function MusicVideoLayout({id: entry.id,label: entry.label,icon: STAGE_ICONS[entry.id],- trailing: entry.state === 'blocked'- ? <AlertTriangle size={12} className="shrink-0 text-port-warning" aria-label="needs you" />- : entry.state === 'done' ? <CheckCircle2 size={12} className="shrink-0 text-port-success max-lg:hidden" aria-label="done" /> : null,+ trailing: STAGE_TRAILING[entry.state] || null,}));const showSpend = spend.spentUsd > 0 || spend.capUsd != null;const ActionIcon = nextAction?.kind === 'goto' ? ArrowRight : Play;@@ -112,20 +89,6 @@ export default function MusicVideoLayout({><div className="flex min-w-0 items-center gap-3"><h2 className="min-w-0 flex-1 truncate text-lg font-semibold">{project.name}</h2>- {nextAction && (- <button- type="button"- onClick={onNextAction}- disabled={nextAction.disabled}- title={nextAction.reason}- className="flex min-h-[44px] shrink-0 items-center gap-1 rounded bg-port-accent px-3 py-1.5 text-sm text-white disabled:opacity-50 sm:min-h-0"- >- <ActionIcon size={14} aria-hidden="true" /> {nextAction.label}- </button>- )}- </div>- <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1">- <ProgressStrip stages={progress.stages} current={progress.current} /><span className="flex min-w-0 items-center gap-1 text-xs text-port-text-muted max-sm:hidden"><Music size={12} className="shrink-0" aria-hidden="true" /><span className="truncate">{trackLabel}</span>@@ -137,6 +100,17 @@ export default function MusicVideoLayout({</span></Pill>)}+ {nextAction && (+ <button+ type="button"+ onClick={onNextAction}+ disabled={nextAction.disabled}+ title={nextAction.reason}+ className="flex min-h-[44px] shrink-0 items-center gap-1 rounded bg-port-accent px-3 py-1.5 text-sm text-white disabled:opacity-50 sm:min-h-0"+ >+ <ActionIcon size={14} aria-hidden="true" /> {nextAction.label}+ </button>+ )}</div><navaria-label="Stages"diff --git a/client/src/components/musicVideo/MusicVideoLayout.test.jsx b/client/src/components/musicVideo/MusicVideoLayout.test.jsxindex 754a9f1c99..aa9d9b3d25 100644--- a/client/src/components/musicVideo/MusicVideoLayout.test.jsx+++ b/client/src/components/musicVideo/MusicVideoLayout.test.jsx@@ -4,6 +4,22 @@ import MusicVideoLayout from './MusicVideoLayout.jsx';import { MUSIC_VIDEO_STAGES } from '../../lib/musicVideoStages.js';describe('music-video stage navigation', () => {+ it('renders one stage row: the tabs carry the status marks, with no separate progress strip', () => {+ const states = ['done', 'active', 'blocked', 'todo', 'todo', 'todo', 'todo'];+ render(<MusicVideoLayout project={{ id: 'example-project', name: 'Example Project' }} stage="cast-sets" trackLabel="Example Track"+ onStageChange={() => {}} progress={{ current: 'cast-sets', stages: MUSIC_VIDEO_STAGES.map((stage, i) => ({ ...stage, state: states[i] })) }}+ spend={{ spentUsd: 3, capUsd: 10 }} />);+ expect(screen.queryByRole('list', { name: 'Progress' })).not.toBeInTheDocument();+ const tabs = within(screen.getByRole('navigation', { name: 'Stages' })).getAllByRole('tab');+ expect(tabs).toHaveLength(MUSIC_VIDEO_STAGES.length);+ expect(within(tabs[0]).getByLabelText('done')).toBeInTheDocument();+ expect(within(tabs[1]).getByLabelText('in progress')).toBeInTheDocument();+ expect(within(tabs[2]).getByLabelText('needs you')).toBeInTheDocument();+ // The track and spend chips survive the strip's removal.+ expect(screen.getByText('Example Track')).toBeInTheDocument();+ expect(screen.getByText(/\$3\.00 \/ \$10\.00/)).toBeInTheDocument();+ });+it('keeps every fixed stage in the compact icon row after adding Publish', () => {render(<MusicVideoLayout project={{ id: 'example-project', name: 'Example Project' }} stage="publish"onStageChange={() => {}} progress={{ current: 'publish', stages: MUSIC_VIDEO_STAGES.map((stage) => ({ ...stage, state: 'todo' })) }}diff --git a/client/src/components/musicVideo/StyleReferencesPanel.jsx b/client/src/components/musicVideo/StyleReferencesPanel.jsxindex c2e3b6a046..8534b47f7f 100644--- a/client/src/components/musicVideo/StyleReferencesPanel.jsx+++ b/client/src/components/musicVideo/StyleReferencesPanel.jsx@@ -1,9 +1,50 @@-import { useEffect, useState } from 'react';+import { useEffect, useMemo, useState } from 'react';+import { Link } from 'react-router';+import { ExternalLink } from 'lucide-react';import useMounted from '../../hooks/useMounted.js';+import { getMoodBoard } from '../../services/apiMoodBoard.js';+import { moodBoardItemSrc } from '../../lib/moodBoardItemSrc.js';import { uploadGalleryImage } from '../../services/apiSystem.js';import { IMAGE_ACCEPT, readFileAsBase64, validateImageFile } from '../../utils/fileUpload.js';import toast from '../ui/Toast';+const LINKED_THUMBS = 6;++/**+ * The mood board linked to the project (`visualSpec.moodBoardId` — the one an+ * autonomous run creates or the creative setup picks): its name, a few pinned+ * images and a link to the board, so an empty uploader below is not read as+ * "no moodboard". Read-only; the board page is where it is edited.+ */+function LinkedMoodBoard({ boardId }) {+ const [board, setBoard] = useState(null); // null = not loaded (or failed), else the full board+ useEffect(() => {+ let active = true;+ setBoard(null);+ getMoodBoard(boardId, { silent: true }).then((data) => { if (active) setBoard(data || null); }, () => {});+ return () => { active = false; };+ }, [boardId]);+ const thumbs = useMemo(() => (Array.isArray(board?.items) ? board.items : [])+ .map((item) => ({ id: item.id, src: moodBoardItemSrc(item) })).filter((t) => t.src).slice(0, LINKED_THUMBS), [board]);+ return (+ <div className="rounded border border-port-border bg-port-bg p-2 space-y-2" data-testid="linked-mood-board">+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs">+ <span className="text-port-text-muted">Linked mood board</span>+ <Link to={`/mood-boards/${encodeURIComponent(boardId)}`} className="inline-flex items-center gap-1 text-port-accent hover:underline min-h-[44px] sm:min-h-0">+ {board?.name || 'Open mood board'} <ExternalLink size={12} aria-hidden="true" />+ </Link>+ </div>+ {thumbs.length > 0 && (+ <ul className="flex flex-wrap gap-1">+ {thumbs.map((t, i) => (+ <li key={t.id || i}><img src={t.src} alt={`Mood board image ${i + 1}`} loading="lazy" className="h-12 w-12 rounded object-cover" /></li>+ ))}+ </ul>+ )}+ </div>+ );+}+/** Project-owned moodboard; uploads do not invoke an AI provider. */export default function StyleReferencesPanel({ project, onSave, onPendingChange }) {const mounted = useMounted();@@ -59,6 +100,7 @@ export default function StyleReferencesPanel({ project, onSave, onPendingChange<section aria-label="Project moodboard" className="rounded-lg border border-port-border bg-port-card p-3 space-y-2"><h3 className="text-sm font-medium">Project moodboard</h3><p className="text-xs text-port-text-muted">Up to eight style images. Add captions describing palette, lighting, lens and grain. Identity references take priority; models use as many style images as their remaining slots allow, or caption text when references are unsupported.</p>+ {project.visualSpec?.moodBoardId && <LinkedMoodBoard boardId={project.visualSpec.moodBoardId} />}<fieldset disabled={busy} className="space-y-2"><label htmlFor={`mv-style-upload-${project.id}`} className="block text-xs">Upload style images<input id={`mv-style-upload-${project.id}`} type="file" aria-label="Upload style images" accept={IMAGE_ACCEPT} multiple disabled={references.length >= 8 || busy}diff --git a/client/src/components/musicVideo/StyleReferencesPanel.test.jsx b/client/src/components/musicVideo/StyleReferencesPanel.test.jsxindex 307d74b828..b5d92c1e79 100644--- a/client/src/components/musicVideo/StyleReferencesPanel.test.jsx+++ b/client/src/components/musicVideo/StyleReferencesPanel.test.jsx@@ -1,12 +1,34 @@import { describe, it, expect, vi } from 'vitest';import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';+import { MemoryRouter } from 'react-router';import StyleReferencesPanel from './StyleReferencesPanel.jsx';+import { getMoodBoard } from '../../services/apiMoodBoard.js';++vi.mock('../../services/apiMoodBoard.js', () => ({ getMoodBoard: vi.fn() }));vi.mock('../../services/apiSystem.js', () => ({ uploadGalleryImage: vi.fn(async () => ({ filename: 'uploaded.png' })) }));vi.mock('../../utils/fileUpload.js', () => ({ IMAGE_ACCEPT: 'image/png,image/jpeg,image/webp', readFileAsBase64: vi.fn(async () => 'encoded'), validateImageFile: vi.fn(() => null) }));vi.mock('../ui/Toast', () => ({ default: { error: vi.fn() } }));describe('project moodboard', () => {+ it('shows the mood board the project links to (an autonomous run’s board), not just an empty uploader', async () => {+ getMoodBoard.mockResolvedValue({ id: 'board-1', name: 'Example Board', items: [{ id: 'i1', type: 'image', imageUrl: '/data/images/pin.png' }] });+ render(<MemoryRouter><StyleReferencesPanel project={{ id: 'example', visualSpec: { moodBoardId: 'board-1' } }} onSave={vi.fn()} /></MemoryRouter>);+ const link = await screen.findByRole('link', { name: /example board/i });+ expect(link.getAttribute('href')).toBe('/mood-boards/board-1');+ expect(await screen.findByAltText('Mood board image 1')).toBeTruthy();+ expect(getMoodBoard).toHaveBeenCalledWith('board-1', { silent: true });+ });++ it('renders no linked-board block without a link, and still links when the board fails to load', async () => {+ const { unmount } = render(<MemoryRouter><StyleReferencesPanel project={{ id: 'example' }} onSave={vi.fn()} /></MemoryRouter>);+ expect(screen.queryByTestId('linked-mood-board')).toBeNull();+ unmount();+ getMoodBoard.mockRejectedValue(new Error('gone'));+ render(<MemoryRouter><StyleReferencesPanel project={{ id: 'example', visualSpec: { moodBoardId: 'board-2' } }} onSave={vi.fn()} /></MemoryRouter>);+ expect(await screen.findByRole('link', { name: /open mood board/i })).toBeTruthy();+ });+it('uploads, captions and saves references, holding generation pending through the save', async () => {let finish;const onSave = vi.fn(() => new Promise((resolve) => { finish = resolve; }));diff --git a/client/src/lib/musicVideoAutonomous.js b/client/src/lib/musicVideoAutonomous.jsindex ada9f23b57..ada1dd5984 100644--- a/client/src/lib/musicVideoAutonomous.js+++ b/client/src/lib/musicVideoAutonomous.js@@ -71,10 +71,51 @@ export function autonomousStageRows(run) {return AUTONOMOUS_STAGES.map((stage) => {const state = run.stages?.[stage.id] || {};const current = run.stage === stage.id;- return { id: stage.id, label: stage.label, status: state.status || 'pending', current, error: state.error || null };+ return { id: stage.id, label: stage.label, status: state.status || 'pending', current, error: state.error || null, step: state.step || null };});}+/** The stages whose output stays viewable on the run panel, in pipeline order. */+export const AUTONOMOUS_VIEWABLE_STAGES = Object.freeze(['brief', 'lyrics', 'style', 'song']);++/** What the Song stage is doing right now (the server's `stages.song.step`). */+export const AUTONOMOUS_SONG_STEP_LABELS = Object.freeze({+ opening: 'Opening Suno in the PortOS Browser',+ generating: 'Generating the song on Suno',+ exporting: 'Exporting the M4A',+ validating: 'Validating the audio',+ importing: 'Importing into the music library',+});++/**+ * What a completed stage produced, read-only: `[{ key, label, text?, href? }]`+ * (empty when the stage stored nothing). A text field carries `multiline` when+ * it should keep its line breaks (lyrics).+ */+export function autonomousStageOutput(run, stageId) {+ const out = run?.output || {};+ const fields = [];+ const add = (key, label, text, extra = {}) => {+ if (typeof text === 'string' && text.trim()) fields.push({ key, label, text, ...extra });+ };+ if (stageId === 'brief') {+ add('title', 'Title', out.title);+ add('musicalDescription', 'Musical description', out.musicalDescription);+ add('concept', 'Visual concept', out.concept?.prompt);+ } else if (stageId === 'lyrics') {+ add('lyrics', 'Lyrics', out.lyrics, { multiline: true });+ } else if (stageId === 'style') {+ add('sunoStyle', 'Suno style prompt', out.sunoStyle);+ add('conceptStyle', 'Visual style', out.concept?.style);+ if (out.moodBoardId) fields.push({ key: 'moodBoard', label: 'Mood board', href: `/mood-boards/${encodeURIComponent(out.moodBoardId)}`, text: out.moodBoard?.name || 'Open mood board' });+ } else if (stageId === 'song') {+ add('songSource', 'Source', out.songSource ? AUTONOMOUS_SONG_SOURCE_LABELS[out.songSource] || out.songSource : null);+ add('songFallbackReason', 'Why Suno was skipped', out.songFallbackReason);+ add('sunoSongIds', 'Suno song ids', Array.isArray(out.sunoSongIds) ? out.sunoSongIds.join(', ') : null, { mono: true });+ }+ return fields;+}+/** True while the run can still move (or be nudged): the project page keeps its panel prominent. */export const isAutonomousLive = (run) => !!run && AUTONOMOUS_LIVE_STATUSES.includes(run.status);diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex 776f73093d..addd8eba40 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -37,6 +37,8 @@ import useMusicVideoRevisions from '../hooks/useMusicVideoRevisions.js';import useMusicVideoAutoReview from '../hooks/useMusicVideoAutoReview.js';import useMusicVideoProduction from '../hooks/useMusicVideoProduction.js';import useAutonomousMusicVideo from '../hooks/useAutonomousMusicVideo.js';+import useDrawerTab from '../hooks/useDrawerTab.js';+import { AUTONOMOUS_VIEWABLE_STAGES } from '../lib/musicVideoAutonomous.js';import useMusicVideoModelSettings from '../hooks/useMusicVideoModelSettings.js';import useMusicVideoManualTempo from '../hooks/useMusicVideoManualTempo.js';import useMusicVideoSceneMedia from '../hooks/useMusicVideoSceneMedia.js';@@ -209,6 +211,8 @@ export default function MusicVideo() {const autoReview = useMusicVideoAutoReview({ project: selected, replaceProject, submitSections: revisions.submitSections });const production = useMusicVideoProduction({ project: selected, replaceProject });const autonomous = useAutonomousMusicVideo({ project: selected, replaceProject });+ // Which finished autonomous stage's output is open (`?run-stage=lyrics`).+ const [runStage, setRunStage] = useDrawerTab('run-stage', null, AUTONOMOUS_VIEWABLE_STAGES);// Cast & Sets check-in (before the plan) and the development files it saves.const castSets = useMusicVideoCastAndSets({ project: selected, replaceProject });const devArtifacts = useMusicVideoDevArtifacts({ project: selected, replaceProject });@@ -1068,7 +1072,7 @@ export default function MusicVideo() {) : null}><div className="space-y-3 min-w-0">- <AutonomousRunPanel key={`autonomous-${selected.id}`} project={selected} auto={autonomous} />+ <AutonomousRunPanel key={`autonomous-${selected.id}`} project={selected} auto={autonomous} selectedStage={runStage} onSelectStage={setRunStage} /><StageView key={selected.id} board={board} /></div></MusicVideoLayout>diff --git a/server/services/musicVideo/autonomousService.js b/server/services/musicVideo/autonomousService.jsindex dbebbee597..fd6ad3c011 100644--- a/server/services/musicVideo/autonomousService.js+++ b/server/services/musicVideo/autonomousService.js@@ -223,6 +223,8 @@ const STAGES = {song = await deps.generateSunoSong(fields, {songIds: run.output.sunoSongIds,signal: controller.signal,+ // The long stage's sub-step rides the run record (and its socket event) so the page can show it.+ onProgress: (step) => { patchRun(project.id, (r) => stagePatch(r, 'song', { step })).catch(() => {}); },// Stored the moment Suno accepts the request, so a failed download retries// the same songs instead of spending credits on another generation.onSubmitted: (ids) => { submitted = true; return save({ output: { sunoSongIds: ids } }); },@@ -300,7 +302,7 @@ async function advance(projectId) {await park(projectId, 'failed', { error: `Unknown stage "${stage}"`, errorCode: 'UNKNOWN_STAGE' });return;}- await patchRun(projectId, (r) => stagePatch(r, stage, { status: 'running', startedAt: new Date().toISOString(), error: null }));+ await patchRun(projectId, (r) => stagePatch(r, stage, { status: 'running', startedAt: new Date().toISOString(), error: null, step: null }));let result;try {result = await executor({ project, run, save: (patch) => patchRun(projectId, () => patch) });@@ -308,7 +310,7 @@ async function advance(projectId) {// A stop/cancel mid-stage (it cancels the song operation) must not become a failure.const latest = projectAutonomousRun(await getProject(projectId));if (latest?.status !== 'running' || latest.processId !== PROCESS_ID) return;- await patchRun(projectId, (r) => stagePatch(r, stage, { status: 'failed', error: trimTo(err.message, 500) }));+ await patchRun(projectId, (r) => stagePatch(r, stage, { status: 'failed', error: trimTo(err.message, 500), step: null }));await park(projectId, isLoginRequired(err) ? 'needs-human' : 'failed', { error: trimTo(err.message, 500), errorCode: err.code || null });return;}@@ -322,7 +324,7 @@ async function advance(projectId) {const checkpoint = run.brief.checkpoints.includes(stage);await patchRun(projectId, (r) => ({output: result.output,- ...stagePatch(r, stage, { status: 'done', finishedAt }),+ ...stagePatch(r, stage, { status: 'done', finishedAt, step: null }),...(checkpoint ? { status: 'awaiting-approval', awaiting: stage, stage: next } : next ? { stage: next } : { status: 'completed', stage }),}));console.log(`🎬 Autonomous music video ${short(run.id)} finished ${stage}${checkpoint ? ' — waiting for approval' : ''}`);diff --git a/server/services/musicVideo/autonomousService.test.js b/server/services/musicVideo/autonomousService.test.jsindex 676cb699ea..c2562440b2 100644--- a/server/services/musicVideo/autonomousService.test.js+++ b/server/services/musicVideo/autonomousService.test.js@@ -195,6 +195,28 @@ describe('checkpoints', () => {});});+describe('song sub-step', () => {+ it('records the Suno sub-step on the run, pushes it over the autonomous event, and clears it when the stage settles', async () => {+ const pushed = [];+ const onEvent = (event) => pushed.push(event.run.stages.song.step);+ musicVideoEvents.on('autonomous', onEvent);+ try {+ doubles.generateSunoSong.mockImplementationOnce(async (_fields, opts) => {+ await opts.onSubmitted(['song-a', 'song-b']);+ opts.onProgress('exporting');+ await vi.waitFor(() => expect(runOf().stages.song.step).toBe('exporting'));+ return { songId: 'song-a', songIds: ['song-a', 'song-b'], filename: 'music-song-a.mp3' };+ });+ await service.startAutonomousVideo({ prompt: 'p' });+ await vi.waitFor(() => expect(calls).toContain('production'));+ } finally {+ musicVideoEvents.off('autonomous', onEvent);+ }+ expect(pushed).toContain('exporting');+ expect(runOf().stages.song).toMatchObject({ status: 'done', step: null });+ });+});+describe('failure and retry', () => {it('parks needs-human on a signed-out Suno, then retries that stage with the same inputs', async () => {doubles.generateSunoSong.mockImplementationOnce(async () => {diff --git a/server/services/musicVideo/autonomousSuno.js b/server/services/musicVideo/autonomousSuno.jsindex a3b1a6d32e..553877e62d 100644--- a/server/services/musicVideo/autonomousSuno.js+++ b/server/services/musicVideo/autonomousSuno.js@@ -228,7 +228,7 @@ async function watchDownloadsDir(listDownloads, baseline, signal, pollMs) {/** One bounded export, including waiting for the browser to finish saving. */async function downloadSunoAudio(page, songId, path, {timeoutMs = SUNO_AUDIO_TIMEOUT_MS, signal, validateAudio = validateSunoAudio,- listDownloads = defaultListDownloads, downloadPollMs = DOWNLOAD_POLL_MS,+ listDownloads = defaultListDownloads, downloadPollMs = DOWNLOAD_POLL_MS, onProgress,} = {}) {const controller = new AbortController();const deadline = Date.now() + timeoutMs;@@ -297,6 +297,7 @@ async function downloadSunoAudio(page, songId, path, {await bounded('save-download', () => download.saveAs(path));if (await bounded('check-download', () => download.failure())) throw error('SUNO_AUDIO_DOWNLOAD_FAILED', 'browser-download-failed');}+ onProgress?.('validating');if (!await bounded('validate-audio', () => validateAudio(path, { signal: controller.signal, timeoutMs: remaining() }))) throw error('SUNO_AUDIO_INVALID', 'invalid-audio');} catch (err) {if (err instanceof ServerError) throw err;@@ -334,8 +335,15 @@ async function closeSunoBrowser(page, browser) {// A single-id resume (or a one-render result) falls back to the only id.const pickRender = (ids) => ids[1] ?? ids[0];-/** Generate (or resume) a song and import its completed, validated M4A. */+/**+ * Generate (or resume) a song and import its completed, validated M4A.+ * `deps.onProgress(step)` reports the long stage's sub-steps — `opening`,+ * `generating`, `exporting`, `validating`, `importing` — so the run can show+ * where a ten-minute stage is; a throwing reporter never fails the song.+ */export async function generateSunoSong(fields, deps = {}) {+ const report = (name) => { try { deps.onProgress?.(name); } catch { /* progress is advisory */ } };+ const exportDeps = { ...deps, onProgress: report };const connect = deps.connect || connectPortosBrowser;const importAudio = deps.importAudio || (async (path, name) => {const { importUploadedTrack } = await import('../pipeline/musicLibrary.js');@@ -346,19 +354,23 @@ export async function generateSunoSong(fields, deps = {}) {try {const songIds = await serialize(async () => {deps.signal?.throwIfAborted();+ report('opening');const { browser, context } = await connect();let page;try {page = await context.newPage();+ if (!deps.songIds?.length) report('generating');const ids = deps.songIds?.length ? deps.songIds : await submitSunoSong(page, fields, deps);if (!deps.songIds?.length) await deps.onSubmitted?.(ids);- await downloadSunoAudio(page, pickRender(ids), path, deps);+ report('exporting');+ await downloadSunoAudio(page, pickRender(ids), path, exportDeps);return ids;} finally {await closeSunoBrowser(page, browser); // disconnect; keep the shared browser running}});deps.signal?.throwIfAborted();+ report('importing');const { filename, sizeBytes } = await importAudio(path, 'song.m4a');return { songId: pickRender(songIds), songIds, filename, sizeBytes };} finally {diff --git a/server/services/musicVideo/autonomousSuno.test.js b/server/services/musicVideo/autonomousSuno.test.jsindex a0fe6f1b47..ad1617f5ee 100644--- a/server/services/musicVideo/autonomousSuno.test.js+++ b/server/services/musicVideo/autonomousSuno.test.js@@ -204,6 +204,19 @@ describe('generateSunoSong M4A export', () => {await expect(stat(w.savedPath())).rejects.toMatchObject({ code: 'ENOENT' });});+ it('reports each sub-step in order, skips generating on a resume, and survives a throwing reporter', async () => {+ const steps = [];+ await generateSunoSong(fields, { ...workflow(), sleep: noSleep, onProgress: (step) => steps.push(step) });+ expect(steps).toEqual(['opening', 'generating', 'exporting', 'validating', 'importing']);++ const resumed = [];+ await generateSunoSong(fields, { ...workflow(), songIds: [NEW_A], onProgress: (step) => resumed.push(step) });+ expect(resumed).toEqual(['opening', 'exporting', 'validating', 'importing']);++ const out = await generateSunoSong(fields, { ...workflow(), songIds: [NEW_A], onProgress: () => { throw new Error('reporter broke'); } });+ expect(out.filename).toBe('music-example.m4a');+ });+it('imports an M4A the PortOS Browser saved to its download directory when Playwright emits no download event', async () => {const dir = await mkdtemp(join(tmpdir(), 'portos-suno-test-'));try {