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

feat(music-video): per-stage LLM routing and an optional lyrics review pass

Claude7a72ac93cebb
diff --git a/client/src/components/cos/tabs/schedule/MusicVideoAutopilotSettings.jsx b/client/src/components/cos/tabs/schedule/MusicVideoAutopilotSettings.jsx
index 0a1db1e8e4..1ae8773439 100644
--- a/client/src/components/cos/tabs/schedule/MusicVideoAutopilotSettings.jsx
+++ b/client/src/components/cos/tabs/schedule/MusicVideoAutopilotSettings.jsx
@@ -1,5 +1,6 @@
import CodeAuthoringPicker from '../../../musicVideo/CodeAuthoringPicker.jsx';
import MediaModePicker from '../../../musicVideo/MediaModePicker.jsx';
+import MusicVideoLlmStagesPicker from '../../../musicVideo/MusicVideoLlmStagesPicker.jsx';
import { useEffect, useState } from 'react';
import ToggleChip from '../../../ui/ToggleChip';
import ProviderModelSelector from '../../../ProviderModelSelector';
@@ -116,13 +117,22 @@ export default function MusicVideoAutopilotSettings({ taskType, config, onUpdate
onEffortChange={setEffort}
emptyProviderOption="Auto — a TUI provider when one is eligible"
emptyModelOption="Provider default"
- label="Writes the brief and lyrics"
+ label="Direction LLM (brief, lyrics and every stage on Default)"
disabled={updating}
modelDisabled={llm.availableModels.length === 0}
compact
/>
)}
+ <MusicVideoLlmStagesPicker
+ idPrefix="mv-ap"
+ value={draft.llmStages}
+ onChange={(llmStages) => patch({ llmStages })}
+ lyricsReview={draft.lyricsReview}
+ onLyricsReviewChange={(lyricsReview) => patch({ lyricsReview })}
+ disabled={updating}
+ />
+
<button type="submit" disabled={updating} className="w-full bg-port-accent text-white rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50">
{updating ? 'Saving…' : 'Save settings'}
</button>
diff --git a/client/src/components/musicVideo/AutomationBriefFields.jsx b/client/src/components/musicVideo/AutomationBriefFields.jsx
index 5f43a9f55b..b9e469ecf2 100644
--- a/client/src/components/musicVideo/AutomationBriefFields.jsx
+++ b/client/src/components/musicVideo/AutomationBriefFields.jsx
@@ -1,8 +1,12 @@
import ToggleChip from '../ui/ToggleChip.jsx';
import MusicVideoLlmPicker from './MusicVideoLlmPicker.jsx';
+import MusicVideoLlmStagesPicker from './MusicVideoLlmStagesPicker.jsx';
import { MUSIC_VIDEO_AUTOMATION_TOOLS, MUSIC_VIDEO_AUTOMATION_TOOL_IDS } from '../../lib/musicVideoAutomation.js';
const GROUPS = [['image', 'Image'], ['video', 'Video'], ['code', 'Code']];
+// The LLM stages a saved project runs from its brief. The brief and lyric
+// stages belong to an autonomous run, which keeps its own pins on the run.
+const PROJECT_LLM_STAGES = ['castAndSets', 'plan', 'authoring'];
const inputClass = 'w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm';
/** Tool picker + guidance + direction LLM + budget for an automation-first music video. */
@@ -59,6 +63,7 @@ export default function AutomationBriefFields({ idPrefix, draft, onChange }) {
/>
</div>
<MusicVideoLlmPicker idPrefix={idPrefix} value={draft.llm} onChange={(llm) => onChange({ llm })} />
+ <MusicVideoLlmStagesPicker idPrefix={idPrefix} value={draft.llmStages} onChange={(llmStages) => onChange({ llmStages })} stages={PROJECT_LLM_STAGES} />
<div className="grid grid-cols-[repeat(auto-fit,minmax(min(100%,12rem),18rem))] gap-3">
<div>
<label htmlFor={`${idPrefix}-checkin`} className="block text-xs text-port-text-muted mb-1">Cast &amp; Sets check-in</label>
diff --git a/client/src/components/musicVideo/AutonomousRunPanel.jsx b/client/src/components/musicVideo/AutonomousRunPanel.jsx
index a9d68656cc..323a73bd03 100644
--- a/client/src/components/musicVideo/AutonomousRunPanel.jsx
+++ b/client/src/components/musicVideo/AutonomousRunPanel.jsx
@@ -2,10 +2,13 @@ import { useState } from 'react';
import { Link } from 'react-router';
import { AlertTriangle, CheckCircle2, Circle, CircleDot, ExternalLink, Loader2, Pause, Play, RotateCcw, Wand2, X, XCircle } from 'lucide-react';
import {
- AUTONOMOUS_CHECKPOINT_LABELS, AUTONOMOUS_SONG_STEP_LABELS, AUTONOMOUS_STATUS_LABELS, AUTONOMOUS_VIEWABLE_STAGES,
+ AUTONOMOUS_CHECKPOINT_LABELS, AUTONOMOUS_LYRICS_STEP_LABELS, AUTONOMOUS_SONG_STEP_LABELS, AUTONOMOUS_STATUS_LABELS, AUTONOMOUS_VIEWABLE_STAGES,
autonomousStageOutput, autonomousStageRows, isAutonomousLive,
} from '../../lib/musicVideoAutonomous.js';
+// The stages that report a sub-step while they run (the server's `stages[id].step`).
+const STEP_LABELS = { lyrics: AUTONOMOUS_LYRICS_STEP_LABELS, song: AUTONOMOUS_SONG_STEP_LABELS };
+
const STATUS_TONES = {
running: 'text-port-accent', 'awaiting-approval': 'text-port-warning', 'needs-human': 'text-port-warning', stopped: 'text-port-warning',
completed: 'text-port-success', failed: 'text-port-error', canceled: 'text-port-text-muted',
@@ -110,8 +113,8 @@ export default function AutonomousRunPanel({ project, auto, selectedStage = null
) : (
<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>
+ {STEP_LABELS[row.id] && row.status === 'running' && row.step && (
+ <p role="status" className="pl-[17px] text-port-accent break-words">{STEP_LABELS[row.id][row.step] || row.step}…</p>
)}
</li>
);
diff --git a/client/src/components/musicVideo/AutonomousStartDrawer.jsx b/client/src/components/musicVideo/AutonomousStartDrawer.jsx
index 955cecbced..61471c52c1 100644
--- a/client/src/components/musicVideo/AutonomousStartDrawer.jsx
+++ b/client/src/components/musicVideo/AutonomousStartDrawer.jsx
@@ -8,6 +8,7 @@ import ToolPicker from './ToolPicker.jsx';
import MoodBoardPicker from './MoodBoardPicker.jsx';
import SongSourcePicker from './SongSourcePicker.jsx';
import ProviderModelSelector from '../ProviderModelSelector.jsx';
+import MusicVideoLlmStagesPicker from './MusicVideoLlmStagesPicker.jsx';
import toast from '../ui/Toast';
import useProviderModels from '../../hooks/useProviderModels.js';
import { startAutonomousMusicVideo } from '../../services/apiMusicVideo.js';
@@ -176,13 +177,22 @@ export default function AutonomousStartDrawer({ open, onClose, onStarted }) {
onEffortChange={setEffort}
emptyProviderOption="Auto — a TUI provider when one is eligible"
emptyModelOption="Provider default"
- label="Writes the brief and lyrics"
+ label="Direction LLM (brief, lyrics and every stage on Default)"
disabled={submitting}
modelDisabled={llm.availableModels.length === 0}
compact
/>
)}
+ <MusicVideoLlmStagesPicker
+ idPrefix="mv-auto-start"
+ value={draft.llmStages}
+ onChange={(llmStages) => patch({ llmStages })}
+ lyricsReview={draft.lyricsReview}
+ onLyricsReviewChange={(lyricsReview) => patch({ lyricsReview })}
+ disabled={submitting}
+ />
+
<button
type="submit"
disabled={!valid || submitting}
diff --git a/client/src/components/musicVideo/AutopilotBriefLlm.test.jsx b/client/src/components/musicVideo/AutopilotBriefLlm.test.jsx
index 386f766a34..0ae24d459c 100644
--- a/client/src/components/musicVideo/AutopilotBriefLlm.test.jsx
+++ b/client/src/components/musicVideo/AutopilotBriefLlm.test.jsx
@@ -112,6 +112,32 @@ describe('AutopilotPanel direction LLM (#9545)', () => {
expect(onSave.mock.calls[0][0].llm).toBeNull();
});
+ it('pins a model per stage from the collapsed "Models per stage" section, and clears a saved stage with null', async () => {
+ const onSave = vi.fn();
+ await renderBrief({ ...BASE, llmStages: { castAndSets: { providerId: 'cloud-api', model: 'big', effort: null } } }, onSave);
+ expect(screen.getByText(/Per stage: Cast & sets direction → cloud-api · big/)).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Edit brief' }));
+
+ // A saved stage pin opens the section; only the stages a saved project runs are offered.
+ const section = within(await screen.findByTestId('mv-auto-mv-1-llm-stages'));
+ expect(section.getByRole('button', { name: /Models per stage/ })).toHaveAttribute('aria-expanded', 'true');
+ expect(section.queryByLabelText('Lyrics draft')).not.toBeInTheDocument();
+ const planRow = within(await screen.findByTestId('mv-auto-mv-1-stage-plan-llm'));
+ const plan = await planRow.findByLabelText('Shot plan');
+ expect(planRow.getByRole('option', { name: 'Default (use direction LLM)' })).toBeInTheDocument();
+ fireEvent.change(plan, { target: { value: 'claude-tui' } });
+ fireEvent.change(await planRow.findByLabelText('Model'), { target: { value: 'opus' } });
+
+ const castRow = within(screen.getByTestId('mv-auto-mv-1-stage-castAndSets-llm'));
+ const cast = await castRow.findByLabelText('Cast & sets direction');
+ await waitFor(() => expect(cast).toHaveValue('cloud-api'));
+ fireEvent.change(cast, { target: { value: '' } });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Save brief' }));
+ await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
+ expect(onSave.mock.calls[0][0].llmStages).toEqual({ castAndSets: null, plan: { providerId: 'claude-tui', model: 'opus', effort: null } });
+ });
+
it('shows the route each stage last ran on, including a pin it replaced', async () => {
const routes = {
plan: { providerId: 'claude-tui', model: 'opus', effort: 'high', transport: 'tui', source: 'tui-preferred' },
diff --git a/client/src/components/musicVideo/AutopilotPanel.jsx b/client/src/components/musicVideo/AutopilotPanel.jsx
index 35850ac4ff..1ef527f83e 100644
--- a/client/src/components/musicVideo/AutopilotPanel.jsx
+++ b/client/src/components/musicVideo/AutopilotPanel.jsx
@@ -9,7 +9,7 @@ import ToggleChip from '../ui/ToggleChip.jsx';
import MediumPlanSummary from './MediumPlanSummary.jsx';
import { codeFirstProductionAssets } from '../../../../server/lib/musicVideoMediumPlan.js';
import {
- DEFAULT_AUTOMATION_TOOLS, MUSIC_VIDEO_AUTOMATION_TOOLS, automationDraftFrom, automationFromDraft, llmRouteLabel,
+ DEFAULT_AUTOMATION_TOOLS, MUSIC_VIDEO_AUTOMATION_TOOLS, MUSIC_VIDEO_LLM_STAGES, MUSIC_VIDEO_LLM_STAGE_LABELS, automationDraftFrom, automationFromDraft, llmRouteLabel,
} from '../../lib/musicVideoAutomation.js';
import { RESUMABLE_RUN_STATUSES, currentProductionRun } from '../../lib/musicVideoStages.js';
import { formatCount, formatUsd } from '../../utils/formatters.js';
@@ -35,7 +35,10 @@ const briefToolLabel = new Map(MUSIC_VIDEO_AUTOMATION_TOOLS.map((t) => [t.id, t.
const actionClass = 'text-sm text-port-accent min-h-[44px] sm:min-h-0 px-1';
const routeLabel = (route) => `${toolLabel.get(`${route.kind}:${route.mode}`) || `${route.kind} ${route.mode}`}${route.model ? ` · ${route.model}` : ''}`;
-const ROUTE_LABELS = [['plan', 'Shot planning'], ['castAndSets', 'Cast & Sets direction']];
+const ROUTE_LABELS = [
+ ['brief', 'Creative brief'], ['lyrics', 'Lyrics draft'], ['lyricsReview', 'Lyrics review'],
+ ['plan', 'Shot planning'], ['castAndSets', 'Cast & Sets direction'],
+];
const initialPool = (project) => {
const fromBrief = (project?.automation?.tools || []).filter((id) => POOL_TOOL_IDS.has(id));
@@ -279,7 +282,7 @@ function BriefSection({ project, onSave, onKickoff, kickoffBusy, kickoffStep, ki
const save = () => {
setSaving(true);
- const payload = automationFromDraft(draft);
+ const payload = automationFromDraft(draft, automation);
// Back to Auto clears the saved pin explicitly: an absent key keeps it server-side.
if (!payload.llm && automation?.llm) payload.llm = null;
onSave(payload)
@@ -340,6 +343,12 @@ function BriefSection({ project, onSave, onKickoff, kickoffBusy, kickoffStep, ki
<p className="text-xs text-port-text-muted break-words">
Direction LLM: {automation.llm?.providerId ? llmRouteLabel(automation.llm) : 'Auto — a TUI provider when one is eligible'}
</p>
+ {MUSIC_VIDEO_LLM_STAGES.some((stage) => automation.llmStages?.[stage]) && (
+ <p className="text-xs text-port-text-muted break-words">
+ Per stage: {MUSIC_VIDEO_LLM_STAGES.filter((stage) => automation.llmStages?.[stage])
+ .map((stage) => `${MUSIC_VIDEO_LLM_STAGE_LABELS[stage]} → ${llmRouteLabel(automation.llmStages[stage])}`).join(' · ')}
+ </p>
+ )}
{ROUTE_LABELS.map(([stage, label]) => automation.routes?.[stage] && (
<p key={stage} className="text-xs text-port-text-muted break-words">
{label} ran on {llmRouteLabel(automation.routes[stage])}
diff --git a/client/src/components/musicVideo/MusicVideoLlmPicker.jsx b/client/src/components/musicVideo/MusicVideoLlmPicker.jsx
index 05733f71f7..61ed3c4398 100644
--- a/client/src/components/musicVideo/MusicVideoLlmPicker.jsx
+++ b/client/src/components/musicVideo/MusicVideoLlmPicker.jsx
@@ -14,8 +14,18 @@ import { EMPTY_LLM_DRAFT } from '../../lib/musicVideoAutomation.js';
* saved pin is restored into the hook once the catalog loads, and a pin whose
* provider is gone is cleared back to Auto with a visible note rather than
* silently kept.
+ *
+ * `emptyProviderOption` / `fallbackName` / `hint` let a per-stage row
+ * (MusicVideoLlmStagesPicker) name its blank choice "Default" and drop the
+ * direction picker's help text.
*/
-export default function MusicVideoLlmPicker({ idPrefix, value, onChange, disabled = false, label = 'Direction & planning LLM' }) {
+const AUTO_OPTION = 'Auto — a TUI provider when one is eligible';
+const AUTO_HINT = 'Auto prefers an enabled TUI provider so the work shows up as an attachable Shell session; pick an API provider to run without one. Applies to shot planning, the Cast & Sets direction and code authoring.';
+
+export default function MusicVideoLlmPicker({
+ idPrefix, value, onChange, disabled = false, label = 'Direction & planning LLM',
+ emptyProviderOption = AUTO_OPTION, fallbackName = 'Auto', hint = AUTO_HINT,
+}) {
const llm = useProviderModels({ allowDefault: true, silent: true, withEffort: true });
const { providers, loading, setSelectedProviderId, setSelectedModel } = llm;
const [seeded, setSeeded] = useState(false);
@@ -57,7 +67,7 @@ export default function MusicVideoLlmPicker({ idPrefix, value, onChange, disable
effort={current.effort}
onEffortChange={(effort) => onChange({ ...current, effort })}
label={label}
- emptyProviderOption="Auto — a TUI provider when one is eligible"
+ emptyProviderOption={emptyProviderOption}
emptyModelOption="Provider default"
disabled={disabled}
loading={loading}
@@ -65,11 +75,8 @@ export default function MusicVideoLlmPicker({ idPrefix, value, onChange, disable
layout="stacked"
compact
/>
- {missingId && <p className="text-[11px] text-port-warning mt-1" role="status">The saved provider “{missingId}” is no longer available — Auto will be used unless you pick another.</p>}
- <p className="text-[11px] text-port-text-muted mt-1">
- Auto prefers an enabled TUI provider so the work shows up as an attachable Shell session; pick an API provider to run without one.
- Applies to shot planning, the Cast &amp; Sets direction and code authoring.
- </p>
+ {missingId && <p className="text-[11px] text-port-warning mt-1" role="status">The saved provider “{missingId}” is no longer available — {fallbackName} will be used unless you pick another.</p>}
+ {hint && <p className="text-[11px] text-port-text-muted mt-1">{hint}</p>}
</div>
);
}
diff --git a/client/src/components/musicVideo/MusicVideoLlmStagesPicker.jsx b/client/src/components/musicVideo/MusicVideoLlmStagesPicker.jsx
new file mode 100644
index 0000000000..109db2614d
--- /dev/null
+++ b/client/src/components/musicVideo/MusicVideoLlmStagesPicker.jsx
@@ -0,0 +1,86 @@
+import { useRef, useState } from 'react';
+import { ChevronDown, ChevronRight } from 'lucide-react';
+import ToggleChip from '../ui/ToggleChip.jsx';
+import MusicVideoLlmPicker from './MusicVideoLlmPicker.jsx';
+import { MUSIC_VIDEO_LLM_STAGES, MUSIC_VIDEO_LLM_STAGE_LABELS } from '../../lib/musicVideoAutomation.js';
+
+/**
+ * "Models per stage" — a collapsible list of the Music Video LLM stages, each
+ * with its own provider / model / effort (MusicVideoLlmPicker). A stage left on
+ * "Default" runs on the direction LLM; the server resolves the order (request
+ * pin → stage pin → direction pin → an eligible TUI → the active provider, see
+ * services/musicVideo/llmRoute.js).
+ *
+ * `value` is the draft map `{ [stage]: { providerId, model, effort } }` (only
+ * pinned stages); `onChange` receives the next map. `stages` narrows the list
+ * to the stages a surface can actually run. When `onLyricsReviewChange` is
+ * given, a "Review lyrics with a second model" toggle is shown too. Pickers
+ * mount only while the section is open, so a collapsed section loads nothing.
+ */
+export default function MusicVideoLlmStagesPicker({
+ idPrefix, value, onChange, stages = MUSIC_VIDEO_LLM_STAGES, lyricsReview = false, onLyricsReviewChange = null, disabled = false,
+}) {
+ const current = value || {};
+ const pinned = stages.filter((stage) => current[stage]?.providerId);
+ const [open, setOpen] = useState(pinned.length > 0);
+ const bodyId = `${idPrefix}-llm-stages`;
+ const reviewPinned = !!current.lyricsReview?.providerId;
+
+ // Several rows can clear a vanished provider in the same commit; each builds on
+ // the map the previous one produced rather than on this render's stale copy.
+ const latest = useRef(current);
+ latest.current = current;
+ const setStage = (stage, llm) => {
+ const { [stage]: _previous, ...rest } = latest.current;
+ latest.current = llm?.providerId ? { ...rest, [stage]: llm } : rest;
+ onChange(latest.current);
+ };
+ const Chevron = open ? ChevronDown : ChevronRight;
+
+ return (
+ <div className="min-w-0 border border-port-border rounded p-2" data-testid={`${idPrefix}-llm-stages`}>
+ <button
+ type="button"
+ onClick={() => setOpen((o) => !o)}
+ aria-expanded={open}
+ aria-controls={bodyId}
+ className="flex items-center gap-1 text-xs text-port-text-muted min-h-[44px] sm:min-h-0"
+ >
+ <Chevron size={14} aria-hidden="true" />
+ Models per stage
+ <span className="text-[11px]">{pinned.length ? `· ${pinned.length} pinned` : '· all use the direction LLM'}</span>
+ </button>
+ {open && (
+ <div id={bodyId} className="mt-2 space-y-3 min-w-0">
+ <p className="text-[11px] text-port-text-muted">
+ A stage on Default runs on the direction LLM. Pin a cheap model to draft and a stronger one to review, plan or author code.
+ </p>
+ {onLyricsReviewChange && (
+ <ToggleChip
+ id={`${idPrefix}-lyrics-review`}
+ label={reviewPinned ? 'Review lyrics with a second model (on: review stage pinned)' : 'Review lyrics with a second model'}
+ hint="After the draft, a second pass revises the lyrics for scansion and punch, keeping the title, sections and length"
+ checked={lyricsReview || reviewPinned}
+ onToggle={() => { if (!disabled && !reviewPinned) onLyricsReviewChange(!lyricsReview); }}
+ />
+ )}
+ <div className="grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3">
+ {stages.map((stage) => (
+ <MusicVideoLlmPicker
+ key={stage}
+ idPrefix={`${idPrefix}-stage-${stage}`}
+ label={MUSIC_VIDEO_LLM_STAGE_LABELS[stage]}
+ value={current[stage]}
+ onChange={(llm) => setStage(stage, llm)}
+ emptyProviderOption="Default (use direction LLM)"
+ fallbackName="Default"
+ hint={null}
+ disabled={disabled}
+ />
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/lib/musicVideoAutomation.js b/client/src/lib/musicVideoAutomation.js
index 402e01e65a..5c20afc51e 100644
--- a/client/src/lib/musicVideoAutomation.js
+++ b/client/src/lib/musicVideoAutomation.js
@@ -1,9 +1,11 @@
// Music Video automation brief — client half. Re-exports the server's tool
// catalog (a dependency-free leaf) and owns the form draft ↔ wire mapping.
-import { MUSIC_VIDEO_AUTOMATION_TOOLS, MUSIC_VIDEO_AUTOMATION_TOOL_IDS, musicVideoLlmRouteLabel } from '../../../server/lib/musicVideoAutomation.js';
+import {
+ MUSIC_VIDEO_AUTOMATION_TOOLS, MUSIC_VIDEO_AUTOMATION_TOOL_IDS, MUSIC_VIDEO_LLM_STAGES, MUSIC_VIDEO_LLM_STAGE_LABELS, musicVideoLlmRouteLabel,
+} from '../../../server/lib/musicVideoAutomation.js';
-export { MUSIC_VIDEO_AUTOMATION_TOOLS, MUSIC_VIDEO_AUTOMATION_TOOL_IDS };
+export { MUSIC_VIDEO_AUTOMATION_TOOLS, MUSIC_VIDEO_AUTOMATION_TOOL_IDS, MUSIC_VIDEO_LLM_STAGES, MUSIC_VIDEO_LLM_STAGE_LABELS };
// `claude-tui · opus · high (TUI)` — one line naming the route a stage ran on.
export const llmRouteLabel = musicVideoLlmRouteLabel;
@@ -15,6 +17,32 @@ export const DEFAULT_AUTOMATION_TOOLS = MUSIC_VIDEO_AUTOMATION_TOOLS.filter((t)
// TUI provider, else the active one — resolved server-side, see llmRoute.js).
export const EMPTY_LLM_DRAFT = Object.freeze({ providerId: '', model: '', effort: '' });
+const llmDraftFrom = (pin) => (pin?.providerId
+ ? { providerId: pin.providerId, model: pin.model || '', effort: pin.effort || '' }
+ : { ...EMPTY_LLM_DRAFT });
+const llmFromDraft = (draft) => ({ providerId: draft.providerId, model: draft.model || null, effort: draft.effort || null });
+
+// The stored per-stage pins as form drafts: `{ [stage]: llmDraft }`, only for pinned stages.
+export const llmStagesDraftFrom = (llmStages) => Object.fromEntries(MUSIC_VIDEO_LLM_STAGES
+ .filter((stage) => llmStages?.[stage]?.providerId)
+ .map((stage) => [stage, llmDraftFrom(llmStages[stage])]));
+
+/**
+ * The per-stage pins a draft sends, or undefined when there is nothing to send.
+ * Pinned stages carry their pin; with `saved` (the stored map), a stage the
+ * director set back to Default is sent as `null` so the server clears it — an
+ * absent stage keeps its stored pin.
+ */
+export function llmStagesFromDraft(draftStages, saved = null) {
+ const out = {};
+ for (const stage of MUSIC_VIDEO_LLM_STAGES) {
+ const draft = draftStages?.[stage];
+ if (draft?.providerId) out[stage] = llmFromDraft(draft);
+ else if (saved?.[stage]) out[stage] = null;
+ }
+ return Object.keys(out).length ? out : undefined;
+}
+
// The draft keeps budget as the raw input string so an empty field reads as
// "no cap" rather than 0.
export const automationDraftFrom = (automation) => ({
@@ -23,13 +51,14 @@ export const automationDraftFrom = (automation) => ({
budget: automation?.budgetUsd != null ? String(automation.budgetUsd) : '',
// The Cast & Sets check-in stops the autopilot for review unless auto-approved.
castAndSetsCheckin: automation?.checkins?.castAndSets === 'auto' ? 'auto' : 'review',
- llm: automation?.llm?.providerId
- ? { providerId: automation.llm.providerId, model: automation.llm.model || '', effort: automation.llm.effort || '' }
- : { ...EMPTY_LLM_DRAFT },
+ llm: llmDraftFrom(automation?.llm),
+ llmStages: llmStagesDraftFrom(automation?.llmStages),
});
-export const automationFromDraft = (draft) => {
+// `saved` (the stored brief) lets a stage set back to Default clear its stored pin.
+export const automationFromDraft = (draft, saved = null) => {
const budget = Number.parseFloat(draft.budget);
+ const llmStages = llmStagesFromDraft(draft.llmStages, saved?.llmStages);
return {
tools: draft.tools,
guidance: draft.guidance.trim(),
@@ -37,9 +66,8 @@ export const automationFromDraft = (draft) => {
checkins: { castAndSets: draft.castAndSetsCheckin === 'auto' ? 'auto' : 'review' },
// Absent when Auto. Clearing a SAVED pin back to Auto is the caller's `llm: null` (the
// server keeps a stored pin when the key is absent), so a create payload stays unchanged.
- ...(draft.llm?.providerId
- ? { llm: { providerId: draft.llm.providerId, model: draft.llm.model || null, effort: draft.llm.effort || null } }
- : {}),
+ ...(draft.llm?.providerId ? { llm: llmFromDraft(draft.llm) } : {}),
+ ...(llmStages ? { llmStages } : {}),
};
};
diff --git a/client/src/lib/musicVideoAutomation.test.js b/client/src/lib/musicVideoAutomation.test.js
index bd849ea8a3..030785e8a5 100644
--- a/client/src/lib/musicVideoAutomation.test.js
+++ b/client/src/lib/musicVideoAutomation.test.js
@@ -1,6 +1,6 @@
import { describe, it, expect } from 'vitest';
import { automationDraftFrom, automationFromDraft, llmRouteLabel } from './musicVideoAutomation.js';
-import { autonomousRequestFromDraft, autopilotParamsFromDraft, emptyAutonomousDraft } from './musicVideoAutonomous.js';
+import { autonomousRequestFromDraft, autopilotDraftFromParams, autopilotParamsFromDraft, emptyAutonomousDraft } from './musicVideoAutonomous.js';
describe('brief draft ↔ wire mapping for the direction LLM (#9545)', () => {
it('round-trips a saved pin, and leaves Auto (and a pre-pin record) out of the payload', () => {
@@ -36,3 +36,30 @@ describe('autonomous entry and scheduled params carry effort (#9545)', () => {
expect(autopilotParamsFromDraft(draft, null, { providerId: 'claude-tui' }).llm).toEqual({ providerId: 'claude-tui', model: null });
});
});
+
+describe('per-stage LLM pins in the draft ↔ wire mapping', () => {
+ const plan = { providerId: 'claude-tui', model: 'opus', effort: 'high' };
+
+ it('round-trips a stage pin, clears a saved stage set back to Default with null, and sends nothing when no stage is pinned', () => {
+ const saved = { tools: [], guidance: '', budgetUsd: null, llmStages: { plan, castAndSets: { providerId: 'cloud', model: null, effort: null } } };
+ const draft = automationDraftFrom(saved);
+ expect(draft.llmStages.plan).toEqual({ providerId: 'claude-tui', model: 'opus', effort: 'high' });
+ expect(automationFromDraft(draft, saved).llmStages).toEqual(saved.llmStages);
+
+ const { castAndSets: _cleared, ...kept } = draft.llmStages;
+ expect(automationFromDraft({ ...draft, llmStages: kept }, saved).llmStages).toEqual({ plan, castAndSets: null });
+ expect('llmStages' in automationFromDraft(automationDraftFrom({ tools: [], guidance: '', budgetUsd: null }))).toBe(false);
+ });
+
+ it('carries stage pins and the lyric review toggle on a start request and the scheduled params', () => {
+ const draft = { ...emptyAutonomousDraft(), prompt: 'p', llmStages: { lyricsReview: { providerId: 'cloud', model: '', effort: '' } }, lyricsReview: true };
+ expect(autonomousRequestFromDraft(draft)).toMatchObject({ llmStages: { lyricsReview: { providerId: 'cloud', model: null, effort: null } }, lyricsReview: true });
+ expect(autonomousRequestFromDraft({ ...emptyAutonomousDraft(), prompt: 'p' })).not.toHaveProperty('llmStages');
+
+ const params = autopilotParamsFromDraft(draft, null);
+ expect(params).toMatchObject({ llmStages: { lyricsReview: { providerId: 'cloud' } }, lyricsReview: true });
+ expect(autopilotDraftFromParams(params)).toMatchObject({ llmStages: { lyricsReview: { providerId: 'cloud', model: '', effort: '' } }, lyricsReview: true });
+ // Params are replaced whole, so clearing every stage saves an explicit null.
+ expect(autopilotParamsFromDraft({ ...draft, llmStages: {}, lyricsReview: false }, params)).toMatchObject({ llmStages: null, lyricsReview: false });
+ });
+});
diff --git a/client/src/lib/musicVideoAutonomous.js b/client/src/lib/musicVideoAutonomous.js
index 6ca30a490a..1042a074cb 100644
--- a/client/src/lib/musicVideoAutonomous.js
+++ b/client/src/lib/musicVideoAutonomous.js
@@ -3,6 +3,7 @@
// form's draft ↔ wire mapping and the run's display helpers.
import { musicVideoMediaMode } from '../../../server/lib/musicVideoMediaPolicy.js';
+import { llmStagesDraftFrom, llmStagesFromDraft } from './musicVideoAutomation.js';
import {
AUTONOMOUS_DEFAULT_LIMITS, AUTONOMOUS_DEFAULT_TOOLS, AUTONOMOUS_LIVE_STATUSES, AUTONOMOUS_SONG_SOURCES, AUTONOMOUS_STAGES,
@@ -42,6 +43,10 @@ export const emptyAutonomousDraft = () => ({
moodBoardId: '',
// Suno's Advanced-form options; blank leaves that control as Suno has it.
suno: { excludeStyles: '', vocalGender: '', model: '', maxMode: '' },
+ // A provider/model/effort per LLM stage (`{ [stage]: llmDraft }`; absent = the direction LLM).
+ llmStages: {},
+ // Review & revise the lyric draft with a second pass.
+ lyricsReview: false,
});
/** A blank model is fine (Suno's current one); anything else must name a version such as v6. */
@@ -70,6 +75,7 @@ export function autonomousRequestFromDraft(draft, { providerId, model, effort }
const budget = Number.parseFloat(draft.budget);
const maxGenerations = optionalInt(draft.maxGenerations);
const suno = draft.songSource === 'suno' ? sunoRequestFromDraft(draft.suno) : null;
+ const llmStages = llmStagesFromDraft(draft.llmStages);
const models = Object.fromEntries(Object.entries(draft.models || {})
.filter(([id, value]) => draft.tools.includes(id) && typeof value === 'string' && value.trim())
.map(([id, value]) => [id, value.trim()]));
@@ -91,6 +97,8 @@ export function autonomousRequestFromDraft(draft, { providerId, model, effort }
...(maxGenerations ? { limits: { maxGenerations } } : {}),
checkpoints: draft.checkpoints,
...(draft.moodBoardId ? { moodBoardId: draft.moodBoardId } : {}),
+ ...(llmStages ? { llmStages } : {}),
+ ...(draft.lyricsReview === true ? { lyricsReview: true } : {}),
...(providerId ? { providerId, ...(model ? { model } : {}), ...(effort ? { effort } : {}) } : {}),
};
}
@@ -108,6 +116,12 @@ export function autonomousStageRows(run) {
/** 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 Lyrics stage is doing right now when it reviews its draft (`stages.lyrics.step`). */
+export const AUTONOMOUS_LYRICS_STEP_LABELS = Object.freeze({
+ draft: 'Writing the lyric draft',
+ review: 'Reviewing and revising the lyrics',
+});
+
/** 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',
@@ -133,7 +147,9 @@ export function autonomousStageOutput(run, stageId) {
add('musicalDescription', 'Musical description', out.musicalDescription);
add('concept', 'Visual concept', out.concept?.prompt);
} else if (stageId === 'lyrics') {
- add('lyrics', 'Lyrics', out.lyrics, { multiline: true });
+ add('lyrics', out.lyricsDraft ? 'Lyrics (revised)' : 'Lyrics', out.lyrics, { multiline: true });
+ add('lyricsReviewNotes', 'Review notes', out.lyricsReviewNotes);
+ add('lyricsDraft', 'First draft', out.lyricsDraft, { multiline: true });
} else if (stageId === 'style') {
add('sunoStyle', 'Suno style prompt', out.sunoStyle);
add('conceptStyle', 'Visual style', out.concept?.style);
@@ -167,6 +183,8 @@ export function autopilotDraftFromParams(params) {
maxGenerations: String(p.limits?.maxGenerations ?? AUTONOMOUS_DEFAULT_LIMITS.maxGenerations),
checkpoints: Array.isArray(p.checkpoints) ? [...p.checkpoints] : [],
moodBoardId: p.moodBoardId || '',
+ llmStages: llmStagesDraftFrom(p.llmStages),
+ lyricsReview: p.lyricsReview === true,
ideaTags: (p.ideaTags || []).join(', '),
};
}
@@ -183,6 +201,9 @@ export function autopilotParamsFromDraft(draft, saved, { providerId, model, effo
...request,
models: request.models || {},
authoring: request.authoring || null,
+ // The params are replaced whole on save, so an unpinned map and an off toggle are explicit.
+ llmStages: request.llmStages || null,
+ lyricsReview: request.lyricsReview === true,
limits: { ...(kept.limits || {}), ...(request.limits || {}) },
moodBoardId: draft.moodBoardId || null,
ideaTags: String(draft.ideaTags || '').split(',').map((t) => t.trim()).filter(Boolean),
diff --git a/docs/features/music-video-autonomous.md b/docs/features/music-video-autonomous.md
index df1b83a323..7573f36d3d 100644
--- a/docs/features/music-video-autonomous.md
+++ b/docs/features/music-video-autonomous.md
@@ -11,7 +11,7 @@ brief → lyrics → style → song → analyze → produce
| Stage | What happens | Costs |
|---|---|---|
| `brief` | One LLM call turns the prompt into a title, a musical description, a compact Suno style line, a visual concept and a mood-board spec. The project is renamed to the title. | one provider call |
-| `lyrics` | Original lyrics written against the musical description (skipped for an instrumental). | one provider call |
+| `lyrics` | Original lyrics written against the musical description (skipped for an instrumental). With the lyric review on, a second pass then reviews and revises the draft (see [Models per stage](#models-per-stage)). | one provider call (two with the review) |
| `style` | A **Mood Board** (text notes + a composite look prompt and an avoid list) is created and linked as the project's mood board; the concept is set from the brief. No images are generated. | free |
| `song` | The PortOS Browser drives the Suno web UI (custom mode: lyrics, style, title), only M4A is selected in Suno's Download UI and the completed audio is validated and imported directly into the music library, a Track is created, the take is recorded with `source: 'suno'`, and the project is linked to it. | Suno credits |
| `song` (local) | `songSource: 'local'` renders the song with the on-device Music Designer engines instead (see [Local song source](#local-song-source)). | free (GPU time) |
@@ -33,6 +33,33 @@ Approving can carry edits (`POST /api/music-video/:id/autonomous/resume` with `{
**Retake song.** At the `song` checkpoint the run panel also offers **Retake song** (`{ retakeSong: true }` on resume, combinable with the lyrics, style and `suno` edits). It discards the song from the run — its track link, Suno song ids, source and any local render — resets the `song` stage, makes a new song (a new Suno generation spends credits again) and parks at the `song` checkpoint once more. The rejected track stays in the music library; only the project's link to it is cleared, which keeps the lyric cues' text and clears their timings until the new song re-seeds them. A retake anywhere else is refused with 409 `NOT_AT_SONG_CHECKPOINT`.
+## Models per stage
+
+By default every LLM step runs on the one **direction LLM** (`providerId`/`model`/`effort` on the start request, stored as the brief's `llm`). A start request may instead route each step to its own provider, model and effort with `llmStages`:
+
+| Stage | Runs |
+|---|---|
+| `brief` | the creative brief |
+| `lyrics` | the lyric draft |
+| `lyricsReview` | the lyric review & revise pass |
+| `castAndSets` | the Cast & Sets direction call (production) |
+| `plan` | the shot plan's scene prompts (production) |
+| `authoring` | code authoring of a code-rendered video |
+
+For example, a cheap local model drafts the lyrics and a stronger one reviews them; one model plans the cast and scenes and a stronger one authors the animation code. Each step resolves its provider in a fixed order (`server/services/musicVideo/llmRoute.js`):
+
+1. a pin on the request itself (an explicit pick in a hand-driven panel);
+2. the stage's pin (`llmStages[stage]`) — the route records `source: 'stage'`;
+3. for `authoring` only, the run's separate code-authoring pin (`authoring`);
+4. the direction LLM (`llm`);
+5. an eligible TUI provider, then the install's active provider.
+
+A pin whose provider no longer exists gives way to the next one, and the route names it (`requestedProviderId`). `llmStages` is stored on the run's brief and copied into the project's automation brief, so the production stages started later (Cast & Sets, shot planning, code authoring) follow it too; each stage's last route is kept in the brief's `routes` (the autonomous text stages also keep theirs on the run output: `briefRoute`, `lyricsRoute`, `lyricsReviewRoute`). Code authoring is the exception: it runs inside production, whose creative basis includes the brief, so its route is not written back.
+
+**Lyric review.** Set `lyricsReview: true` (or pin `llmStages.lyricsReview`, which turns it on by itself) and the `lyrics` stage runs two steps — `draft` then `review`, shown as `stages.lyrics.step` — on the stage list's single `lyrics` entry. The review keeps the title, the section tags and roughly the same length, improves scansion, punch and argument, and adds no new topics. The run keeps the first draft (`output.lyricsDraft`), the revision (`output.lyrics`, what the `lyrics` checkpoint shows and Suno receives) and the reviewer's short critique (`output.lyricsReviewNotes`). The draft is stored before the review runs, so a failed review retries only the review.
+
+The start drawer and the scheduled task's settings show a collapsible **Models per stage** section with the lyric-review toggle; each stage offers *Default (use direction LLM)*. On an automation-first project, the autopilot brief (Produce tab → Edit brief, and the create drawer) offers the same section for the stages a saved project runs — Cast & Sets direction, shot plan and code authoring — next to the direction LLM picker; a patch merges per stage, and a stage set back to Default is sent as `null` to clear its pin.
+
## Suno form options
A start request (and the scheduled task's settings) may carry an optional `suno` object for Suno's Advanced form, stored on the run's brief:
@@ -102,7 +129,7 @@ The Suno adapter fills the form through `placeholder` / role selectors and reads
| Method | Path | |
|---|---|---|
-| `POST` | `/api/music-video/autonomous` | Start (202 `{ project, run }`). Body: `prompt` plus optional `songSource` (`suno` default, or `local`), `localFallback`, `suno` (Suno form options), `tools`, `models` (per-tool model pin), `budgetUsd`, `limits`, `checkpoints`, `instrumental`, `guidance`, `providerId`/`model` (brief + lyrics LLM), `authoring` (code-rendered video). |
+| `POST` | `/api/music-video/autonomous` | Start (202 `{ project, run }`). Body: `prompt` plus optional `songSource` (`suno` default, or `local`), `localFallback`, `suno` (Suno form options), `tools`, `models` (per-tool model pin), `budgetUsd`, `limits`, `checkpoints`, `instrumental`, `guidance`, `providerId`/`model`/`effort` (the direction LLM), `llmStages` (per-stage LLM pins), `lyricsReview`, `authoring` (code-rendered video). |
| `GET` | `/api/music-video/:id/autonomous` | The run. |
| `POST` | `/api/music-video/:id/autonomous/resume` | Approve the checkpoint, retry the stage that stopped, or resume an interrupted run. Optional `lyrics`, `style`, `suno` edits; `retakeSong: true` at the song checkpoint. |
| `POST` | `/api/music-video/:id/autonomous/stop` / `cancel` | Pause / cancel (also stops/cancels its production run). |
@@ -111,7 +138,7 @@ Progress is pushed over the `music-video:autonomous` socket event (`{ projectId,
## Scheduled task: `music-video-autopilot`
-A programmatic scheduled task (no agent). Each run picks the **oldest active Brain idea no earlier run used** (optionally only ideas carrying one of `ideaTags`), turns it into the prompt and starts an autonomous run with the task's saved settings (`taskMetadata.musicVideoAutopilot`: `songSource`, `localFallback`, `suno`, `tools`, `models`, `budgetUsd`, `limits`, `checkpoints`, `instrumental`, `guidance`, `providerId`/`model`, `authoring`, `ideaTags`). Set a cadence on its Schedule card; Run Now fires it once.
+A programmatic scheduled task (no agent). Each run picks the **oldest active Brain idea no earlier run used** (optionally only ideas carrying one of `ideaTags`), turns it into the prompt and starts an autonomous run with the task's saved settings (`taskMetadata.musicVideoAutopilot`: `songSource`, `localFallback`, `suno`, `tools`, `models`, `budgetUsd`, `limits`, `checkpoints`, `instrumental`, `guidance`, `llm`, `llmStages`, `lyricsReview`, `authoring`, `ideaTags`). Set a cadence on its Schedule card; Run Now fires it once.
- It declines while a previous scheduled run is still live, so videos never pile up behind a slow Suno login or a long production.
- An idea counts as used once its run is live or finished; a failed or canceled run leaves the idea available for the next fire.
diff --git a/server/lib/README.md b/server/lib/README.md
index 3d4d9e5511..0122ded3d6 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -807,7 +807,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `musicVideoCreativeContext.js` | `musicVideoDirectionContext(direction)` bounds the authoritative Cast & Sets bible; `musicVideoCodeDirectionContext(direction)` renders the approved procedural direction (rules + reusable character definitions) for code-authoring requests; `musicVideoCreativeContext(concept)` composes the selected universe style and authored cast/place/object bible for planning and generation. |
| `moodBoardStyleContext.js` | `collectBoardStyleContext(board)` bounds a board's notes, captions, analyzed prompts, and composite style for creative prompts. `moodBoardImageCandidates(board, resolveItem)` lists the poster first, then pinned local images. |
| `musicVideoAutonomous.js` | Fully-autonomous Music Video vocabulary: `AUTONOMOUS_STAGES` (brief → lyrics → style → song → analyze → produce), optional `AUTONOMOUS_CHECKPOINT_IDS`, `normalizeAutonomousSettings` / `normalizeAutonomousBrief` / `normalizeAutopilotParams` (the shared run settings, a run's stored brief, and the scheduled task's params), `autonomousMedium` / `autonomousPool` (tool picks → footage vs code, production route pool), `sunoSongFields` + Suno limits/URL helpers, `normalizeSunoOptions` (the brief's optional `suno` form options: exclude styles, vocal gender, model version), and `pickBrainIdea` / `ideaToPrompt` for the scheduled task. Pure; the client drawer and the run service import it. |
-| `musicVideoAutomation.js` | Music Video automation brief: `MUSIC_VIDEO_AUTOMATION_TOOLS` (image/video backends derived from `generationModes.js` plus `code:render`, each flagged `metered`), `MUSIC_VIDEO_AUTOMATION_TOOL_IDS`, and `normalizeMusicVideoAutomation(patch, current)` (per-sub-field merge, catalog-ordered tools, `budgetUsd: null` = no cap, `llm: null` clears the direction-LLM pin, server-written `routes` survive but are never patch-settable). Also `normalizeMusicVideoLlm` / `normalizeMusicVideoEffort` / `musicVideoLlmRouteLabel` for that pin and the effective route a stage ran on (#9545). Dependency-light; the client create drawer imports it. |
+| `musicVideoAutomation.js` | Music Video automation brief: `MUSIC_VIDEO_AUTOMATION_TOOLS` (image/video backends derived from `generationModes.js` plus `code:render`, each flagged `metered`), `MUSIC_VIDEO_AUTOMATION_TOOL_IDS`, and `normalizeMusicVideoAutomation(patch, current)` (per-sub-field merge, catalog-ordered tools, `budgetUsd: null` = no cap, `llm: null` clears the direction-LLM pin, `llmStages` merges per stage with `null` clearing one, server-written `routes` survive but are never patch-settable). Also `normalizeMusicVideoLlm` / `normalizeMusicVideoEffort` / `musicVideoLlmRouteLabel` for that pin and the effective route a stage ran on (#9545), and `MUSIC_VIDEO_LLM_STAGES` / `MUSIC_VIDEO_LLM_STAGE_LABELS` / `normalizeMusicVideoLlmStages` for the per-stage pins. Dependency-light; the client create drawer imports it. |
| `albumLimits.js` | Album record length/count caps shared by the albums sanitizer and client editors. |
| `artistLimits.js` | Artist record length caps shared by the artists sanitizer and client editors. |
| `authorLimits.js` | Author record length caps shared by the authors sanitizer and client editors. |
diff --git a/server/lib/musicVideoAutomation.js b/server/lib/musicVideoAutomation.js
index a770d643e0..b9e1ebdfae 100644
--- a/server/lib/musicVideoAutomation.js
+++ b/server/lib/musicVideoAutomation.js
@@ -52,13 +52,27 @@ export const MUSIC_VIDEO_AUTOMATION_GUIDANCE_MAX = 8000;
// director; `auto` approves the step and continues.
export const MUSIC_VIDEO_CHECKIN_MODES = Object.freeze(['review', 'auto']);
export const MUSIC_VIDEO_AUTOMATION_BUDGET_MAX_USD = 100000;
-// Stages that record the effective LLM route they last ran on (#9545).
-export const MUSIC_VIDEO_AUTOMATION_ROUTE_STAGES = Object.freeze(['plan', 'castAndSets']);
+// The LLM text stages a director may route to their own provider/model/effort
+// (`automation.llmStages`). An unpinned stage uses the direction pin (`llm`).
+// `brief` / `lyrics` / `lyricsReview` run inside an autonomous run; `castAndSets`,
+// `plan` and `authoring` run for every automation-first project.
+export const MUSIC_VIDEO_LLM_STAGES = Object.freeze(['brief', 'lyrics', 'lyricsReview', 'castAndSets', 'plan', 'authoring']);
+export const MUSIC_VIDEO_LLM_STAGE_LABELS = Object.freeze({
+ brief: 'Creative brief',
+ lyrics: 'Lyrics draft',
+ lyricsReview: 'Lyrics review & revise',
+ castAndSets: 'Cast & sets direction',
+ plan: 'Shot plan',
+ authoring: 'Code authoring',
+});
+// Stages that record the effective LLM route they last ran on (#9545): every LLM stage.
+export const MUSIC_VIDEO_AUTOMATION_ROUTE_STAGES = MUSIC_VIDEO_LLM_STAGES;
export const MUSIC_VIDEO_LLM_TRANSPORTS = Object.freeze(['tui', 'cli', 'api']);
-// pinned = the request named it; brief = the saved brief did; tui-preferred =
-// nothing was pinned so an eligible TUI provider was chosen; active = the
-// install's active provider (no eligible TUI).
-export const MUSIC_VIDEO_LLM_ROUTE_SOURCES = Object.freeze(['pinned', 'brief', 'tui-preferred', 'active']);
+// pinned = the request named it; stage = the brief's pin for that stage did;
+// brief = the saved brief's direction pin did; tui-preferred = nothing was
+// pinned so an eligible TUI provider was chosen; active = the install's active
+// provider (no eligible TUI).
+export const MUSIC_VIDEO_LLM_ROUTE_SOURCES = Object.freeze(['pinned', 'stage', 'brief', 'tui-preferred', 'active']);
/** A reasoning-effort level the runner accepts, else null (the runner clamps it per provider). */
export const normalizeMusicVideoEffort = (value) => (EFFORT_LEVELS.includes(value) ? value : null);
@@ -80,6 +94,20 @@ export function normalizeMusicVideoLlm(raw) {
};
}
+/**
+ * Per-stage LLM pins: `{ [stage]: { providerId, model, effort } }`, keeping
+ * only known stages whose pin normalizes. Null when no stage is pinned.
+ */
+export function normalizeMusicVideoLlmStages(raw) {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const stages = {};
+ for (const stage of MUSIC_VIDEO_LLM_STAGES) {
+ const pin = normalizeMusicVideoLlm(raw[stage]);
+ if (pin) stages[stage] = pin;
+ }
+ return Object.keys(stages).length ? stages : null;
+}
+
/** The effective LLM route a stage last ran on, as stored for the project summary. */
function normalizeMusicVideoLlmRoute(raw) {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
@@ -108,7 +136,10 @@ export const musicVideoLlmRouteLabel = (route) => (route?.providerId
* (a guidance edit cannot drop the tool list); `tools` replaces its list whole,
* de-duplicated in catalog order. `budgetUsd: null` means "no cap".
* `checkins` merges per gate; an unknown or absent gate is `review`.
- * `llm` (#9545): absent keeps the stored pin, `null` clears it. `routes` (the
+ * `llm` (#9545): absent keeps the stored pin, `null` clears it. `llmStages`
+ * merges per stage: an absent stage keeps its stored pin, a stage set to `null`
+ * clears it (back to the direction pin), and `llmStages: null` clears them all.
+ * `routes` (the
* effective route each stage last ran on) is server-written: only the stored
* record's value survives — a patch can never set it.
*/
@@ -122,6 +153,10 @@ export function normalizeMusicVideoAutomation(patch, current = null) {
if (route) routes[stage] = route;
}
const llm = normalizeMusicVideoLlm(merged.llm);
+ const llmStages = normalizeMusicVideoLlmStages(patch?.llmStages === null ? null : {
+ ...(current?.llmStages && typeof current.llmStages === 'object' ? current.llmStages : {}),
+ ...(patch?.llmStages && typeof patch.llmStages === 'object' ? patch.llmStages : {}),
+ });
return {
tools: MUSIC_VIDEO_AUTOMATION_TOOL_IDS.filter((id) => picked.has(id)),
guidance: typeof merged.guidance === 'string' ? merged.guidance.slice(0, MUSIC_VIDEO_AUTOMATION_GUIDANCE_MAX) : '',
@@ -131,6 +166,7 @@ export function normalizeMusicVideoAutomation(patch, current = null) {
castAndSets: ({ ...(current?.checkins || {}), ...(patch?.checkins || {}) }).castAndSets === 'auto' ? 'auto' : 'review',
},
...(llm ? { llm } : {}),
+ ...(llmStages ? { llmStages } : {}),
...(Object.keys(routes).length ? { routes } : {}),
};
}
diff --git a/server/lib/musicVideoAutonomous.js b/server/lib/musicVideoAutonomous.js
index d68b283a33..3667d33eb9 100644
--- a/server/lib/musicVideoAutonomous.js
+++ b/server/lib/musicVideoAutonomous.js
@@ -27,7 +27,7 @@ import { MUSIC_VIDEO_MEDIA_MODES, musicVideoMediaMode } from './musicVideoMediaP
* the run is fully unattended.
*/
-import { MUSIC_VIDEO_AUTOMATION_TOOL_IDS, normalizeMusicVideoEffort, normalizeMusicVideoLlm } from './musicVideoAutomation.js';
+import { MUSIC_VIDEO_AUTOMATION_TOOL_IDS, normalizeMusicVideoEffort, normalizeMusicVideoLlm, normalizeMusicVideoLlmStages } from './musicVideoAutomation.js';
import { isStr, trimTo } from './textUtils.js';
export const AUTONOMOUS_STAGES = Object.freeze([
@@ -157,9 +157,17 @@ function normalizeAutonomousSettings(raw = {}) {
authoring: authoringProvider && authoringModel
? { providerId: authoringProvider, model: authoringModel, ...(authoringEffort ? { effort: authoringEffort } : {}) } : null,
suno: normalizeSunoOptions(raw.suno),
+ // A provider/model/effort per LLM stage (null = every stage uses `llm`).
+ llmStages: normalizeMusicVideoLlmStages(raw.llmStages),
+ // Review and revise the lyric draft in a second pass. A `llmStages.lyricsReview`
+ // pin turns the pass on by itself; this asks for it on the direction LLM.
+ lyricsReview: raw.lyricsReview === true,
};
}
+/** True when a run brief asks for the lyric review & revise pass. */
+export const autonomousLyricsReviewEnabled = (brief) => brief?.lyricsReview === true || !!brief?.llmStages?.lyricsReview;
+
/** Normalize a start request into the brief a run stores: the settings plus prompt, name and origin. */
export function normalizeAutonomousBrief(raw = {}) {
const origin = raw.origin && typeof raw.origin === 'object' ? raw.origin : {};
diff --git a/server/lib/musicVideoAutonomous.test.js b/server/lib/musicVideoAutonomous.test.js
index 2d6c0b6571..18342b0a9a 100644
--- a/server/lib/musicVideoAutonomous.test.js
+++ b/server/lib/musicVideoAutonomous.test.js
@@ -49,6 +49,19 @@ describe('normalizeAutonomousBrief', () => {
expect(normalizeAutonomousBrief({ prompt: 'p', providerId: 'prov', effort: 'turbo' }).llm).toEqual({ providerId: 'prov', model: null });
});
+ it('carries per-stage LLM pins and the lyric review opt-in on a start request and the scheduled params', () => {
+ const llmStages = { lyrics: { providerId: 'local-llm', model: 'small' }, lyricsReview: { providerId: 'cloud', model: null, effort: 'high' } };
+ const body = musicVideoAutonomousStartSchema.parse({ prompt: 'p', llmStages, lyricsReview: true });
+ expect(normalizeAutonomousBrief(body)).toMatchObject({
+ llmStages: { lyrics: { providerId: 'local-llm', model: 'small', effort: null }, lyricsReview: { providerId: 'cloud', model: null, effort: 'high' } },
+ lyricsReview: true,
+ });
+ expect(() => musicVideoAutonomousStartSchema.parse({ prompt: 'p', llmStages: { mastering: { providerId: 'x' } } })).toThrow();
+ expect(normalizeAutonomousBrief({ prompt: 'p' })).toMatchObject({ llmStages: null, lyricsReview: false });
+ // The scheduled task's saved params re-normalize to the same shape.
+ expect(normalizeAutopilotParams({ llmStages, lyricsReview: true })).toMatchObject({ llmStages: { lyrics: { providerId: 'local-llm' } }, lyricsReview: true });
+ });
+
it('keeps Suno the default song source, accepts local, and only honors the fallback opt-in as a boolean', () => {
expect(normalizeAutonomousBrief({ prompt: 'p' })).toMatchObject({ songSource: 'suno', localFallback: false });
expect(normalizeAutonomousBrief({ prompt: 'p', songSource: 'local', localFallback: true })).toMatchObject({ songSource: 'local', localFallback: true });
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index 0c8412debc..5eb29c9d5b 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -28,6 +28,7 @@ import {
MUSIC_VIDEO_AUTOMATION_BUDGET_MAX_USD,
MUSIC_VIDEO_AUTOMATION_GUIDANCE_MAX,
MUSIC_VIDEO_AUTOMATION_TOOL_IDS,
+ MUSIC_VIDEO_LLM_STAGES,
MUSIC_VIDEO_CHECKIN_MODES,
} from './musicVideoAutomation.js';
import {
@@ -771,6 +772,20 @@ const musicVideoSunoOptionsSchema = z.object({
maxMode: z.boolean().nullable().optional(),
}).strict();
+// A provider/model/effort pin for a Music Video text stage. Effort is the union
+// of every accepted level; the runner clamps it to the chosen provider's ladder.
+export const musicVideoLlmSchema = z.object({
+ providerId: z.string().trim().min(1).max(200),
+ model: z.string().trim().min(1).max(200).nullable().optional(),
+ effort: z.enum(EFFORT_LEVELS).nullable().optional(),
+}).strict();
+
+// Per-stage pins (MUSIC_VIDEO_LLM_STAGES): an absent stage keeps its stored pin
+// (or, on a start request, uses the direction pin); null clears that stage.
+export const musicVideoLlmStagesSchema = z.object(Object.fromEntries(
+ MUSIC_VIDEO_LLM_STAGES.map((stage) => [stage, musicVideoLlmSchema.nullable().optional()]),
+)).strict();
+
// The alternate entry point: no track, style or board is picked up front. Tool
// ids are the same catalog the autopilot brief uses; `checkpoints` names the
// stages that park for approval (none = fully unattended).
@@ -800,6 +815,11 @@ export const musicVideoAutonomousStartSchema = z.object({
effort: z.enum(EFFORT_LEVELS).nullable().optional(),
// The separate code-authoring provider a code-rendered video needs.
authoring: musicVideoAuthoringSchema.optional(),
+ // A provider/model/effort per LLM stage; an unpinned stage uses the direction LLM above.
+ llmStages: musicVideoLlmStagesSchema.nullable().optional(),
+ // Review and revise the lyric draft with a second pass (the `lyricsReview` stage
+ // pin when set, else the direction LLM). Pinning `llmStages.lyricsReview` implies it.
+ lyricsReview: z.boolean().optional(),
origin: z.object({
kind: z.enum(AUTONOMOUS_ORIGINS).optional(),
ideaId: z.string().max(80).nullable().optional(),
@@ -834,14 +854,6 @@ export const musicVideoSoundBedSchema = z.object({
volume: z.number().min(0.05).max(1).optional(),
}).strict();
-// A provider/model/effort pin for a Music Video text stage. Effort is the union
-// of every accepted level; the runner clamps it to the chosen provider's ladder.
-export const musicVideoLlmSchema = z.object({
- providerId: z.string().trim().min(1).max(200),
- model: z.string().trim().min(1).max(200).nullable().optional(),
- effort: z.enum(EFFORT_LEVELS).nullable().optional(),
-}).strict();
-
// Automation-first brief: which render tools the agent may use, the director's
// free-text guidance, and a spend cap (null = no cap). A patch merges per
// sub-field; `tools` replaces its list whole. See musicVideoAutomation.js.
@@ -857,6 +869,8 @@ export const musicVideoAutomationSchema = z.object({
// The direction/planning LLM (#9545): absent keeps the stored pin, null clears
// it back to Auto (an eligible TUI provider, else the active provider).
llm: musicVideoLlmSchema.nullable().optional(),
+ // Per-stage LLM pins: merged per stage, a stage set to null clears it.
+ llmStages: musicVideoLlmStagesSchema.nullable().optional(),
}).strict();
// ---- Development artifacts ("ingredients") ----------------------------------
diff --git a/server/routes/musicVideoAutonomous.test.js b/server/routes/musicVideoAutonomous.test.js
index 331ecd00db..1feb18e734 100644
--- a/server/routes/musicVideoAutonomous.test.js
+++ b/server/routes/musicVideoAutonomous.test.js
@@ -71,27 +71,28 @@ afterEach(async () => {
await Promise.allSettled(projectIds.splice(0).map((id) => service.cancelAutonomousVideo(id)));
await settle();
});
+const stageDoubles = () => ({
+ draftCreativeBrief: async () => ({ brief: BRIEF }),
+ writeLyrics: async () => {
+ await heldStage?.promise;
+ return { lyrics: '[verse]\nrain on glass' };
+ },
+ createMoodBoard: async () => ({ id: 'board-1' }),
+ generateSunoSong: async (_fields, opts) => {
+ await opts.onSubmitted(['song-a']);
+ return { songId: 'song-a', songIds: ['song-a'], filename: 'music-song-a.mp3' };
+ },
+ createTrack: async () => ({ id: 'track-1' }),
+ attachAudio: async () => ({}),
+ probeDuration: async () => 120,
+ // The real updateProject would validate the track link against the track store.
+ updateProject: async (id, patch) => (patch.trackId ? projects.getProject(id) : projects.updateProject(id, patch)),
+ analyzeSong: async () => ({}),
+ startProduction,
+});
beforeEach(() => {
startProduction.mockClear();
- service.__setAutonomousDepsForTests({
- draftCreativeBrief: async () => ({ brief: BRIEF }),
- writeLyrics: async () => {
- await heldStage?.promise;
- return { lyrics: '[verse]\nrain on glass' };
- },
- createMoodBoard: async () => ({ id: 'board-1' }),
- generateSunoSong: async (_fields, opts) => {
- await opts.onSubmitted(['song-a']);
- return { songId: 'song-a', songIds: ['song-a'], filename: 'music-song-a.mp3' };
- },
- createTrack: async () => ({ id: 'track-1' }),
- attachAudio: async () => ({}),
- probeDuration: async () => 120,
- // The real updateProject would validate the track link against the track store.
- updateProject: async (id, patch) => (patch.trackId ? projects.getProject(id) : projects.updateProject(id, patch)),
- analyzeSong: async () => ({}),
- startProduction,
- });
+ service.__setAutonomousDepsForTests(stageDoubles());
});
const get = async (id) => (await request(app).get(`/api/music-video/${id}/autonomous`)).body.run;
@@ -171,6 +172,27 @@ describe('POST /api/music-video/autonomous', () => {
expect(startProduction).not.toHaveBeenCalled();
});
+ it('accepts per-stage LLM pins, stores them on the run and the project brief, and parks on the reviewed lyrics', async () => {
+ expect((await request(app).post('/api/music-video/autonomous').send({ prompt: 'p', llmStages: { mastering: { providerId: 'x' } } })).status).toBe(400);
+ expect((await request(app).post('/api/music-video/autonomous').send({ prompt: 'p', llmStages: { plan: { model: 'no-provider' } } })).status).toBe(400);
+
+ const reviewLyrics = vi.fn(async () => ({ lyrics: '[verse]\nrain against the glass', notes: 'Sharper verse.' }));
+ service.__setAutonomousDepsForTests({ ...stageDoubles(), reviewLyrics });
+ const llmStages = { lyricsReview: { providerId: 'example-review', model: 'example-large', effort: 'high' }, plan: { providerId: 'example-plan' } };
+ const res = await begin({ prompt: 'p', checkpoints: ['lyrics'], llmStages });
+ expect(res.status).toBe(202);
+ const id = res.body.project.id;
+ expect(res.body.project.automation.llmStages).toEqual({ ...llmStages, plan: { providerId: 'example-plan', model: null, effort: null } });
+ await settle();
+
+ const run = await get(id);
+ expect(run).toMatchObject({ status: 'awaiting-approval', awaiting: 'lyrics', brief: { llmStages: { lyricsReview: llmStages.lyricsReview }, lyricsReview: false } });
+ expect(run.output).toMatchObject({ lyricsDraft: '[verse]\nrain on glass', lyrics: '[verse]\nrain against the glass', lyricsReviewNotes: 'Sharper verse.' });
+ expect(reviewLyrics).toHaveBeenCalledOnce();
+ // The stored brief still carries the pins after the real store's read/write path.
+ expect((await projects.getProject(id)).automation.llmStages.plan).toMatchObject({ providerId: 'example-plan' });
+ });
+
it('stores the Suno form options, and retakes the song over HTTP only at the song checkpoint', async () => {
expect((await request(app).post('/api/music-video/autonomous').send({ prompt: 'p', suno: { model: 'latest' } })).status).toBe(400);
const res = await begin({ prompt: 'p', checkpoints: ['lyrics', 'song'], suno: { excludeStyles: 'metal', vocalGender: 'female' } });
diff --git a/server/services/musicDesigner.js b/server/services/musicDesigner.js
index fc9283d010..96aceaaa6e 100644
--- a/server/services/musicDesigner.js
+++ b/server/services/musicDesigner.js
@@ -7,8 +7,11 @@
* writeLyrics() that description (+ the user's extra guidance) → original
* lyrics in the `[verse]` / `[chorus]` section syntax the
* lyric-aware engines expect.
+ * reviewLyrics() a lyric draft → the revised sheet plus a short critique,
+ * so a second (often stronger) model can tighten a draft a
+ * cheaper one wrote (the autonomous run's lyric review).
*
- * Both are plain-text generators — no JSON contract — and both return an `llm`
+ * All are plain-text generators — no JSON contract — and all return an `llm`
* attribution block alongside the text, matching `roundsAI.js`'s shape.
*
* Meta-prompts ship as module constants and are overridable per call via
@@ -106,6 +109,47 @@ export function buildLyricsPrompt({ description, guidance, template, targetSecon
].join('');
}
+// The review pass is not user-overridable (no `template`): it edits a draft in
+// place, so its constraints are the contract rather than a creative brief.
+export const LYRICS_REVIEW_SEPARATOR = '---';
+const LYRICS_REVIEW_INSTRUCTIONS = [
+ 'You are a lyric editor. Review the draft song lyrics below against the musical description, then revise them.',
+ 'Keep the title and the song\'s subject. Keep every bracketed section tag and the section order; each tag stays alone on its own line.',
+ 'Keep the length roughly equal to the draft: about the same number of sung lines per section.',
+ 'Improve scansion and singability, sharpen weak or generic lines, give the chorus more punch, and make the argument of the song land more clearly.',
+ 'Never add new topics, characters or story beats the draft does not already contain. Keep the lyrics original.',
+].join(' ');
+const LYRICS_REVIEW_OUTPUT_CONTRACT = [
+ 'Return the complete revised lyric sheet first, with its section tags.',
+ `Then a line containing only ${LYRICS_REVIEW_SEPARATOR}`,
+ 'Then two to four short sentences of notes: what was weak in the draft and what you changed.',
+ 'No preamble, no other commentary, no markdown fence.',
+].join('\n');
+
+export function buildLyricsReviewPrompt({ lyrics, description, guidance } = {}) {
+ return [
+ LYRICS_REVIEW_INSTRUCTIONS,
+ section('MUSICAL DESCRIPTION', trimTo(description, MAX_DESCRIPTION) || '(none given)'),
+ section('ADDITIONAL GUIDANCE FROM THE USER', trimTo(guidance, MAX_GUIDANCE)),
+ section('DRAFT LYRICS', trimTo(lyrics, MAX_LYRICS)),
+ `\n\n${LYRICS_REVIEW_OUTPUT_CONTRACT}`,
+ ].join('');
+}
+
+/**
+ * Split a review response into the revised sheet and the notes: everything
+ * before the last line that is only `---` is the lyrics, everything after it
+ * the notes. No separator → the whole text is the lyrics and the notes are
+ * empty (a model that skipped the critique still revised the song).
+ */
+export function parseLyricsReview(text) {
+ const body = unfence(text).replace(/\r\n?/g, '\n');
+ const lines = body.split('\n');
+ const cut = lines.findLastIndex((line) => line.trim() === LYRICS_REVIEW_SEPARATOR);
+ if (cut < 0) return { lyrics: body.trim(), notes: '' };
+ return { lyrics: unfence(lines.slice(0, cut).join('\n')).trim(), notes: lines.slice(cut + 1).join('\n').trim() };
+}
+
// Providers habitually wrap prose in a ``` fence despite the instruction above.
// Unwrap a response that is ENTIRELY one fence; leave anything else untouched
// so a lyric line that merely contains backticks survives.
@@ -172,3 +216,37 @@ export async function writeLyrics({ description, guidance, template, targetSecon
console.log(`🎤 Wrote lyrics via ${provider.id}/${ranModel || 'default'} (${lyrics.length} chars)`);
return { lyrics, llm: { provider: provider.id, model: ranModel || null } };
}
+
+/**
+ * Review a lyric draft and return the revised sheet plus a short critique.
+ *
+ * @param {object} args
+ * @param {string} args.lyrics — the draft to revise
+ * @param {string} [args.description] — the musical description it was written against
+ * @param {string} [args.guidance]
+ * @param {string} [args.providerId]
+ * @param {string} [args.model]
+ * @param {string} [args.effort]
+ * @returns {Promise<{ lyrics: string, notes: string, llm: { provider: string, model: string|null } }>}
+ */
+export async function reviewLyrics({ lyrics, description, guidance, providerId, model, effort } = {}) {
+ if (!trimTo(lyrics, MAX_LYRICS)) {
+ throw new ServerError('There are no lyrics to review.', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });
+ assertProvider(provider, { message: 'No AI provider available to review lyrics', code: 'NO_PROVIDER' });
+
+ const prompt = buildLyricsReviewPrompt({ lyrics, description, guidance });
+ const { text, model: ranModel } = await runPromptThroughProvider({
+ provider, model: selectedModel, effort, prompt, source: 'music-lyrics-review',
+ });
+
+ const parsed = parseLyricsReview(text);
+ const revised = trimTo(parsed.lyrics, MAX_LYRICS);
+ if (!revised) {
+ throw new ServerError('The AI returned empty revised lyrics. Try rerunning or picking a stronger model.', { status: 502, code: 'LLM_EMPTY' });
+ }
+ const notes = trimTo(parsed.notes, MAX_GUIDANCE);
+ console.log(`🎤 Reviewed lyrics via ${provider.id}/${ranModel || 'default'} (${revised.length} chars${notes ? ', with notes' : ''})`);
+ return { lyrics: revised, notes, llm: { provider: provider.id, model: ranModel || null } };
+}
diff --git a/server/services/musicDesigner.test.js b/server/services/musicDesigner.test.js
index a81d5b787c..fdec83105a 100644
--- a/server/services/musicDesigner.test.js
+++ b/server/services/musicDesigner.test.js
@@ -17,7 +17,7 @@ vi.mock('./promptRunner.js', async () => ({
import { resolveProviderAndModel } from './promptRunner.js';
import {
DEFAULT_DESCRIBE_TEMPLATE, DEFAULT_LYRICS_TEMPLATE,
- buildDescribePrompt, buildLyricsPrompt, describeMusic, writeLyrics,
+ buildDescribePrompt, buildLyricsPrompt, describeMusic, reviewLyrics, writeLyrics,
} from './musicDesigner.js';
const lastRunArgs = () => ai.runPromptThroughProvider.mock.calls.at(-1)[0];
@@ -161,3 +161,37 @@ describe('writeLyrics', () => {
await expect(writeLyrics({ description: 'x' })).rejects.toMatchObject({ code: 'LLM_EMPTY', status: 502 });
});
});
+
+describe('reviewLyrics', () => {
+ const DRAFT = '[verse]\nrain on the glass\n[chorus]\nhold on';
+
+ it('sends the draft with its editing constraints and splits the answer into revised lyrics and notes', async () => {
+ ai.runPromptThroughProvider.mockResolvedValue({ text: '[verse]\nrain against the glass\n[chorus]\nhold on, hold on\n---\nThe chorus was flat; doubled the hook.', model: 'ran-model' });
+ const out = await reviewLyrics({ lyrics: DRAFT, description: 'melancholic synthwave', guidance: 'keep it hopeful', providerId: 'p', model: 'm', effort: 'high' });
+ expect(out).toEqual({
+ lyrics: '[verse]\nrain against the glass\n[chorus]\nhold on, hold on',
+ notes: 'The chorus was flat; doubled the hook.',
+ llm: { provider: 'fake-provider', model: 'ran-model' },
+ });
+ const { prompt, source, effort } = lastRunArgs();
+ expect(source).toBe('music-lyrics-review');
+ expect(effort).toBe('high');
+ expect(prompt).toContain(DRAFT);
+ expect(prompt).toContain('melancholic synthwave');
+ expect(prompt).toMatch(/Keep the title/);
+ expect(prompt).toMatch(/section tag/);
+ expect(prompt).toMatch(/Never add new topics/);
+ });
+
+ it('treats an answer with no separator as all lyrics (empty notes), unwrapping a fence', async () => {
+ ai.runPromptThroughProvider.mockResolvedValue({ text: '```\n[verse]\nrain against the glass\n```', model: 'ran-model' });
+ expect(await reviewLyrics({ lyrics: DRAFT })).toMatchObject({ lyrics: '[verse]\nrain against the glass', notes: '' });
+ });
+
+ it('refuses an empty draft before calling a provider, and an empty revision after', async () => {
+ await expect(reviewLyrics({ lyrics: ' ' })).rejects.toMatchObject({ code: 'VALIDATION_ERROR' });
+ expect(ai.runPromptThroughProvider).not.toHaveBeenCalled();
+ ai.runPromptThroughProvider.mockResolvedValue({ text: '---\nonly notes', model: 'ran-model' });
+ await expect(reviewLyrics({ lyrics: DRAFT })).rejects.toMatchObject({ code: 'LLM_EMPTY' });
+ });
+});
diff --git a/server/services/musicVideo/autonomousService.js b/server/services/musicVideo/autonomousService.js
index 2416f2c4fb..9a3692643c 100644
--- a/server/services/musicVideo/autonomousService.js
+++ b/server/services/musicVideo/autonomousService.js
@@ -43,6 +43,7 @@ import { trimTo } from '../../lib/textUtils.js';
import {
AUTONOMOUS_LIVE_STATUSES,
AUTONOMOUS_STAGE_IDS,
+ autonomousLyricsReviewEnabled,
autonomousMedium,
autonomousPool,
nextAutonomousStage,
@@ -65,8 +66,10 @@ const defaults = {
createProject: async (input) => (await import('./projects.js')).createProject(input),
updateProject: async (id, patch) => (await import('./projects.js')).updateProject(id, patch),
resolveLlm: async (pin) => (await import('./llmRoute.js')).resolveMusicVideoLlm(pin),
+ recordRoute: async (projectId, stage, route) => (await import('./llmRoute.js')).recordLlmRoute(projectId, stage, route),
draftCreativeBrief: async (args) => (await import('./autonomousBrief.js')).draftCreativeBrief(args),
writeLyrics: async (args) => (await import('../musicDesigner.js')).writeLyrics(args),
+ reviewLyrics: async (args) => (await import('../musicDesigner.js')).reviewLyrics(args),
createMoodBoard: async (spec) => (await import('./autonomousBoard.js')).createAutonomousMoodBoard(spec),
generateSunoSong: async (fields, opts) => (await import('./autonomousSuno.js')).generateSunoSong(fields, opts),
generateLocalSong: async (args) => (await import('./autonomousLocalSong.js')).generateLocalSong(args),
@@ -133,14 +136,22 @@ const stagePatch = (run, stage, patch) => ({ stages: { [stage]: { ...run.stages[
// when the stage's completion arrives later (production).
/**
- * The direction LLM for a run's text stages, resolved once per stage: the run's
- * pin, else an eligible TUI provider, else the active one (llmRoute.js). The
- * resolved route rides along (`route`) so the stage can record it on the run;
- * a failed registry read degrades to the plain pin rather than failing the stage.
+ * The LLM for one of a run's stages, resolved each time the stage runs: the
+ * run's pin for that stage (`brief.llmStages[stage]`), else — for `authoring` —
+ * its code-authoring pin, else its direction pin (`brief.llm`), else an
+ * eligible TUI provider, else the active one (llmRoute.js). The resolved route
+ * rides along (`route`) so the stage can record it on the run; a failed
+ * registry read degrades to the plain pin rather than failing the stage.
*/
-async function llmOf(run) {
- const pin = { providerId: run.brief.llm?.providerId, model: run.brief.llm?.model || undefined, effort: run.brief.llm?.effort || undefined };
- const resolved = await deps.resolveLlm(pin).catch((err) => {
+async function llmOf(run, stage) {
+ const { llm, llmStages, authoring } = run.brief;
+ const own = llmStages?.[stage] || (stage === 'authoring' && authoring) || llm;
+ const pin = { providerId: own?.providerId, model: own?.model || undefined, effort: own?.effort || undefined };
+ const resolved = await deps.resolveLlm({
+ stage,
+ automation: { llm: llm || null, llmStages: llmStages || null },
+ ...(stage === 'authoring' && authoring ? { authoring } : {}),
+ }).catch((err) => {
console.warn(`⚠️ Autonomous music video: LLM route resolution failed: ${err.message}`);
return null;
});
@@ -149,6 +160,9 @@ async function llmOf(run) {
return { providerId: route.providerId, model: route.model || undefined, effort: route.effort || undefined, route };
}
+/** Keep the route a text stage ran on in the project's brief too (best-effort, never fails the stage). */
+const recordRoute = (project, stage, route) => (route ? deps.recordRoute(project.id, stage, route).catch(() => null) : null);
+
/**
* The local song source: the track is created first (its id is stored at once),
* the render is queued onto it, and the stage settles once the audio has landed.
@@ -184,22 +198,49 @@ async function localSong({ project, run, save }) {
const STAGES = {
async brief({ project, run }) {
- const { route, ...llm } = await llmOf(run);
+ const { route, ...llm } = await llmOf(run, 'brief');
const { brief } = await deps.draftCreativeBrief({
prompt: run.brief.prompt, guidance: run.brief.guidance, instrumental: run.brief.instrumental, ...llm,
});
// A blank project name from the prompt gives way to the song title.
if (!run.brief.name) await deps.updateProject(project.id, { name: trimTo(brief.title, 200) });
+ await recordRoute(project, 'brief', route);
return { output: { ...brief, ...(route ? { briefRoute: route } : {}) } };
},
- async lyrics({ run }) {
+ // Draft, then — when the brief asks for it — review & revise on the
+ // `lyricsReview` stage's LLM. The review is a step inside this stage (the
+ // stage list is wire/UI contract), reported through `stages.lyrics.step`.
+ // The draft is stored before the review runs, so a failed review retries
+ // only the review.
+ async lyrics({ project, run, save }) {
if (run.brief.instrumental) return { output: { lyrics: '' } };
- const { route, ...llm } = await llmOf(run);
- const { lyrics } = await deps.writeLyrics({
- description: run.output.musicalDescription, guidance: run.brief.guidance || undefined, ...llm,
- });
- return { output: { lyrics, ...(route ? { lyricsRoute: route } : {}) } };
+ const review = autonomousLyricsReviewEnabled(run.brief);
+ const description = run.output.musicalDescription;
+ const guidance = run.brief.guidance || undefined;
+ const step = (name) => patchRun(project.id, (r) => stagePatch(r, 'lyrics', { step: name }));
+ let draft = review ? run.output.lyricsDraft : null;
+ let draftRoute = review ? run.output.lyricsRoute : null;
+ if (!draft) {
+ if (review) await step('draft');
+ const { route, ...llm } = await llmOf(run, 'lyrics');
+ ({ lyrics: draft } = await deps.writeLyrics({ description, guidance, ...llm }));
+ draftRoute = route;
+ await recordRoute(project, 'lyrics', route);
+ if (!review) return { output: { lyrics: draft, ...(route ? { lyricsRoute: route } : {}) } };
+ await save({ output: { lyricsDraft: draft, ...(route ? { lyricsRoute: route } : {}) } });
+ }
+ await step('review');
+ const { route, ...llm } = await llmOf(run, 'lyricsReview');
+ const revised = await deps.reviewLyrics({ lyrics: draft, description, guidance, ...llm });
+ await recordRoute(project, 'lyricsReview', route);
+ return { output: {
+ lyricsDraft: draft,
+ lyrics: revised.lyrics,
+ lyricsReviewNotes: revised.notes || '',
+ ...(draftRoute ? { lyricsRoute: draftRoute } : {}),
+ ...(route ? { lyricsReviewRoute: route } : {}),
+ } };
},
async style({ project, run }) {
@@ -276,7 +317,9 @@ const STAGES = {
await prepareProductionReview(project.id);
project = await getProject(project.id);
assertProductionApproval(project, 'storyboard');
- const authoring = run.brief.authoring || await llmOf(run);
+ // The authoring stage's pin, else the run's code-authoring pin taken as
+ // given (production checks it exactly), else the direction LLM.
+ const authoring = !run.brief.llmStages?.authoring && run.brief.authoring ? run.brief.authoring : await llmOf(run, 'authoring');
const input = { providerId: authoring.providerId, model: authoring.model || undefined, ...(authoring.effort ? { effort: authoring.effort } : {}) };
if (medium === 'code') {
if (project.composition?.mode === 'code') {
@@ -395,8 +438,9 @@ export async function startAutonomousVideo(input) {
guidance: brief.guidance,
budgetUsd: brief.budgetUsd,
checkins: { castAndSets: brief.checkpoints.includes('cast') ? 'review' : 'auto' },
- // The run's LLM pin also steers the stages production starts later (Cast & Sets, shot planning).
+ // The run's LLM pins also steer the stages production starts later (Cast & Sets, shot planning, authoring).
...(brief.llm ? { llm: brief.llm } : {}),
+ ...(brief.llmStages ? { llmStages: brief.llmStages } : {}),
},
});
const run = {
diff --git a/server/services/musicVideo/autonomousService.test.js b/server/services/musicVideo/autonomousService.test.js
index 5b3cea1d0e..de27ee898d 100644
--- a/server/services/musicVideo/autonomousService.test.js
+++ b/server/services/musicVideo/autonomousService.test.js
@@ -206,13 +206,89 @@ describe('startAutonomousVideo', () => {
expect(project.automation.llm).toEqual({ providerId: 'cloud', model: 'big', effort: 'low' });
await vi.waitFor(() => expect(calls).toContain('production'));
- // The run's pin is what gets resolved; what the resolver returns is what runs.
- expect(doubles.resolveLlm).toHaveBeenCalledWith({ providerId: 'cloud', model: 'big', effort: 'low' });
+ // The run's pin is what gets resolved, per stage; what the resolver returns is what runs.
+ const runPins = { llm: { providerId: 'cloud', model: 'big', effort: 'low' }, llmStages: null };
+ expect(doubles.resolveLlm).toHaveBeenCalledWith({ stage: 'brief', automation: runPins });
+ expect(doubles.resolveLlm).toHaveBeenCalledWith({ stage: 'lyrics', automation: runPins });
expect(doubles.draftCreativeBrief).toHaveBeenCalledWith(expect.objectContaining({ providerId: 'claude-tui', model: 'opus', effort: 'high' }));
expect(doubles.writeLyrics).toHaveBeenCalledWith(expect.objectContaining({ providerId: 'claude-tui', model: 'opus', effort: 'high' }));
expect(runOf().output).toMatchObject({ briefRoute: route, lyricsRoute: route });
});
+ it('drafts lyrics on the lyrics stage\'s model, then reviews and revises them on the review stage\'s model, and the checkpoint shows the revision', async () => {
+ const llmStages = { lyrics: { providerId: 'local-llm', model: 'small' }, lyricsReview: { providerId: 'cloud', model: 'big', effort: 'high' } };
+ const routeOf = (pin, source) => ({ providerId: pin.providerId, model: pin.model, effort: pin.effort || null, transport: 'api', source });
+ // A resolver double honoring the stage pin, like llmRoute.js does.
+ doubles.resolveLlm.mockImplementation(async ({ stage, automation }) => {
+ const pin = automation.llmStages?.[stage];
+ return pin ? { provider: { id: pin.providerId }, selectedModel: pin.model, route: routeOf(pin, 'stage') } : { provider: null, route: null };
+ });
+ doubles.reviewLyrics = stub('review', async () => ({ lyrics: '[verse]\nrain against the glass', notes: 'Tightened the verse.' }));
+ service.__setAutonomousDepsForTests(doubles);
+ const steps = [];
+ const onEvent = ({ run }) => { if (run.stages.lyrics.step) steps.push(run.stages.lyrics.step); };
+ musicVideoEvents.on('autonomous', onEvent);
+ try {
+ const { project } = await service.startAutonomousVideo({ prompt: 'p', llmStages, checkpoints: ['lyrics'] });
+ // The stage pins also reach the project's brief for the stages production runs later.
+ expect(project.automation.llmStages).toEqual({ lyrics: { ...llmStages.lyrics, effort: null }, lyricsReview: llmStages.lyricsReview });
+ await settled('awaiting-approval');
+ } finally {
+ musicVideoEvents.off('autonomous', onEvent);
+ }
+ expect(calls).toEqual(['createProject', 'brief', 'updateProject', 'lyrics', 'review']);
+ expect(doubles.writeLyrics).toHaveBeenCalledWith(expect.objectContaining({ providerId: 'local-llm', model: 'small' }));
+ expect(doubles.reviewLyrics).toHaveBeenCalledWith(expect.objectContaining({
+ lyrics: '[verse]\nrain on glass', description: BRIEF.musicalDescription, providerId: 'cloud', model: 'big', effort: 'high',
+ }));
+ expect(steps).toEqual(expect.arrayContaining(['draft', 'review']));
+ // The checkpoint parks on the revision, keeping the draft and the critique beside it.
+ expect(runOf()).toMatchObject({ awaiting: 'lyrics', stages: { lyrics: { status: 'done', step: null } } });
+ expect(runOf().output).toMatchObject({
+ lyricsDraft: '[verse]\nrain on glass', lyrics: '[verse]\nrain against the glass', lyricsReviewNotes: 'Tightened the verse.',
+ lyricsRoute: routeOf(llmStages.lyrics, 'stage'), lyricsReviewRoute: routeOf(llmStages.lyricsReview, 'stage'),
+ });
+ // Each stage's route is kept on the project brief too.
+ expect(store.get('mv-auto').automation.routes).toMatchObject({ lyrics: { providerId: 'local-llm' }, lyricsReview: { providerId: 'cloud' } });
+
+ // Approving sends the revised lyrics to Suno.
+ await service.resumeAutonomousVideo('mv-auto');
+ await vi.waitFor(() => expect(calls).toContain('production'));
+ expect(doubles.generateSunoSong.mock.calls[0][0].lyrics).toBe('[verse]\nrain against the glass');
+ });
+
+ it('skips the lyric review unless the brief asks for it, and reviews on the direction LLM when only the toggle is set', async () => {
+ doubles.reviewLyrics = stub('review', async () => ({ lyrics: '[verse]\nrevised', notes: '' }));
+ service.__setAutonomousDepsForTests(doubles);
+ await service.startAutonomousVideo({ prompt: 'p', providerId: 'cloud', model: 'big' });
+ await vi.waitFor(() => expect(calls).toContain('production'));
+ expect(calls).not.toContain('review');
+ expect(runOf().output).not.toHaveProperty('lyricsDraft');
+ expect(runOf().output.lyrics).toBe('[verse]\nrain on glass');
+
+ store.clear();
+ calls.length = 0;
+ await service.startAutonomousVideo({ prompt: 'p', providerId: 'cloud', model: 'big', lyricsReview: true });
+ await vi.waitFor(() => expect(calls).toContain('production'));
+ // No registry route resolves here, so both passes run on the run's own direction pin.
+ expect(doubles.reviewLyrics).toHaveBeenCalledWith(expect.objectContaining({ providerId: 'cloud', model: 'big' }));
+ expect(runOf().output).toMatchObject({ lyricsDraft: '[verse]\nrain on glass', lyrics: '[verse]\nrevised', lyricsReviewNotes: '' });
+ });
+
+ it('retries only the review when the review fails after the draft was stored', async () => {
+ doubles.reviewLyrics = vi.fn()
+ .mockRejectedValueOnce(new Error('review provider down'))
+ .mockResolvedValueOnce({ lyrics: '[verse]\nrevised', notes: 'ok' });
+ service.__setAutonomousDepsForTests(doubles);
+ await service.startAutonomousVideo({ prompt: 'p', lyricsReview: true });
+ await settled('failed');
+ expect(runOf().output.lyricsDraft).toBe('[verse]\nrain on glass');
+ await service.resumeAutonomousVideo('mv-auto');
+ await vi.waitFor(() => expect(calls).toContain('production'));
+ expect(doubles.writeLyrics).toHaveBeenCalledTimes(1);
+ expect(runOf().output.lyrics).toBe('[verse]\nrevised');
+ });
+
it('falls back to the run\'s own pin when the provider registry cannot be read', async () => {
doubles.resolveLlm.mockRejectedValue(new Error('registry down'));
await service.startAutonomousVideo({ prompt: 'p', providerId: 'cloud', model: 'big' });
diff --git a/server/services/musicVideo/castAndSetsService.js b/server/services/musicVideo/castAndSetsService.js
index 006e238bcf..c8ed15dac2 100644
--- a/server/services/musicVideo/castAndSetsService.js
+++ b/server/services/musicVideo/castAndSetsService.js
@@ -170,8 +170,8 @@ async function runDirection(projectId, { providerId, model, effort, notes = [],
const project = await requireProject(projectId);
const stage = project.castAndSets;
const { board, moodImages, track } = await loadContext(project);
- // Request pin > the brief's saved LLM > an eligible TUI provider > the active one (llmRoute.js).
- const { provider, selectedModel, route } = await deps.resolveProvider({ providerId, model, effort, automation: project.automation }).catch(() => ({ provider: null }));
+ // Request pin > the brief's Cast & Sets pin > its direction LLM > an eligible TUI provider > the active one (llmRoute.js).
+ const { provider, selectedModel, route } = await deps.resolveProvider({ providerId, model, effort, automation: project.automation, stage: 'castAndSets' }).catch(() => ({ provider: null }));
if (!provider) return fail(projectId, 'No AI provider is available for the creative direction');
if (provider.enabled === false) return fail(projectId, `The ${provider.name || provider.id} provider is disabled`);
const previous = stage?.direction || null;
diff --git a/server/services/musicVideo/codeGeneration.js b/server/services/musicVideo/codeGeneration.js
index bebc21a3a0..e41fd82be7 100644
--- a/server/services/musicVideo/codeGeneration.js
+++ b/server/services/musicVideo/codeGeneration.js
@@ -55,13 +55,16 @@ function acceptSources(parsed, ids) {
}
/**
- * Run one code-authoring prompt. The provider resolves through llmRoute.js —
- * request pin > the brief's saved LLM (`automation`) > an eligible TUI provider
- * > the active one — and `effort` rides the run when the provider has one.
+ * Run one code-authoring prompt. The provider resolves through llmRoute.js as
+ * the `authoring` stage — request pin > the brief's authoring-stage pin > its
+ * direction LLM (`automation`) > an eligible TUI provider > the active one —
+ * and `effort` rides the run when the provider has one. The route rides back on
+ * the result; it is not written to `automation.routes` here, because authoring
+ * runs inside production and the brief is part of production's creative basis.
*/
export async function runModel({ providerId, model, effort, automation = null, prompt, source = 'music-video-code', beforeSubmit = null }) {
const { assertProvider, runPromptThroughProvider } = await import('../promptRunner.js');
- const { provider, selectedModel, route } = await resolveMusicVideoLlm({ providerId, model, effort, automation });
+ const { provider, selectedModel, route } = await resolveMusicVideoLlm({ providerId, model, effort, automation, stage: 'authoring' });
assertProvider(provider, { message: 'No AI provider available to write the code video', code: 'PROVIDER_UNAVAILABLE', status: 400 });
console.log(`🎬 Music-video code generation on ${musicVideoLlmRouteLabel(route)}`);
const { text } = await runPromptThroughProvider({
diff --git a/server/services/musicVideo/llmRoute.js b/server/services/musicVideo/llmRoute.js
index 726ef6a58e..1038d47bda 100644
--- a/server/services/musicVideo/llmRoute.js
+++ b/server/services/musicVideo/llmRoute.js
@@ -6,15 +6,20 @@
*
* 1. a pin on the request (`providerId`/`model`/`effort`) — authoritative,
* API or TUI alike;
- * 2. the pin saved on the project's automation brief (`automation.llm`);
- * 3. nothing pinned: an enabled, launchable, hardware-compatible TUI provider
+ * 2. the brief's pin for this stage (`automation.llmStages[stage]`), when the
+ * caller names its `stage`;
+ * 3. for `authoring` only, the separate code-authoring pin a caller passes
+ * (`authoring`, e.g. an autonomous run's `brief.authoring`);
+ * 4. the brief's direction pin (`automation.llm`);
+ * 5. nothing pinned: an enabled, launchable, hardware-compatible TUI provider
* (the active provider when it is one), so the work shows up as an
* attachable Shell session instead of an invisible API call;
- * 4. the install's active provider (no eligible TUI) — a usable route, never
+ * 6. the install's active provider (no eligible TUI) — a usable route, never
* an error just because no TUI is configured.
*
- * A pin whose provider no longer resolves is not honored silently: the route
- * carries `requestedProviderId` so the summary shows what it replaced.
+ * Pins are tried in that order; one whose provider no longer resolves gives way
+ * to the next, and is not dropped silently: the route carries the first such
+ * `requestedProviderId` so the summary shows what it replaced.
*
* Image-reading stages (plate review, auto-review) deliberately do NOT resolve
* here: they take an explicit reviewer and already refuse, before dispatch, a
@@ -77,28 +82,34 @@ function describe({ provider, selectedModel, effort, source, requestedProviderId
* @param {string} [input.providerId] request pin
* @param {string} [input.model]
* @param {string} [input.effort]
- * @param {object|null} [input.automation] the project's automation brief; its `llm` pin applies when the request pins nothing
+ * @param {object|null} [input.automation] the project's automation brief; its `llmStages[stage]` and then `llm` pins apply when the request pins nothing
+ * @param {string} [input.stage] the stage being run (one of MUSIC_VIDEO_LLM_STAGES); selects the stage pin
+ * @param {object|null} [input.authoring] the code-authoring pin, consulted for the `authoring` stage after its stage pin
* @returns {Promise<{ provider: object|null, selectedModel: string|null, route: object|null }>}
* `route` carries the effective providerId/model/effort (clamped)/transport/source.
* `provider: null` when nothing resolves, so the caller throws its own typed error.
*/
-export async function resolveMusicVideoLlm({ providerId, model, effort, automation = null } = {}) {
+export async function resolveMusicVideoLlm({ providerId, model, effort, automation = null, stage = null, authoring = null } = {}) {
// Lazy: promptRunner drags the whole provider runtime, and callers that import this file for
// its pure helpers (or whose suites mock it) shouldn't pay for it at load.
const { resolveProviderAndModel } = await import('../promptRunner.js');
- const saved = normalizeMusicVideoLlm(automation?.llm);
- const pin = providerId
- ? { providerId, model, effort, source: 'pinned' }
- : saved ? { ...saved, source: 'brief' } : null;
+ const tagged = (pin, source) => (pin ? { ...pin, source } : null);
+ const pins = [
+ providerId ? { providerId, model, effort, source: 'pinned' } : null,
+ stage ? tagged(normalizeMusicVideoLlm(automation?.llmStages?.[stage]), 'stage') : null,
+ stage === 'authoring' ? tagged(normalizeMusicVideoLlm(authoring), 'brief') : null,
+ tagged(normalizeMusicVideoLlm(automation?.llm), 'brief'),
+ ].filter(Boolean);
let requestedProviderId = null;
- if (pin) {
+ for (const pin of pins) {
const { provider, selectedModel } = await resolveProviderAndModel({ providerId: pin.providerId, model: pin.model || undefined });
if (provider?.id === pin.providerId) {
- return { provider, selectedModel, route: describe({ provider, selectedModel, effort: pin.effort, source: pin.source }) };
+ return { provider, selectedModel, route: describe({ provider, selectedModel, effort: pin.effort, source: pin.source, requestedProviderId }) };
}
- requestedProviderId = pin.providerId;
+ requestedProviderId ||= pin.providerId;
}
+ const pin = pins[0] || null;
const tui = await preferredTuiProvider();
if (tui) {
diff --git a/server/services/musicVideo/llmRoute.test.js b/server/services/musicVideo/llmRoute.test.js
index 50a4999843..27e8c3f6d9 100644
--- a/server/services/musicVideo/llmRoute.test.js
+++ b/server/services/musicVideo/llmRoute.test.js
@@ -87,6 +87,35 @@ describe('resolveMusicVideoLlm', () => {
expect(route).toMatchObject({ providerId: 'tui-1', source: 'tui-preferred', requestedProviderId: 'deleted-provider' });
});
+ it('routes a stage to its own pin over the direction pin, and falls back to the direction pin for an unpinned stage', async () => {
+ registry.providers = [api('cloud'), tui('tui-1'), api('local-llm')];
+ registry.active = registry.providers[0];
+ const automation = {
+ llm: { providerId: 'cloud', model: 'big' },
+ llmStages: { lyrics: { providerId: 'local-llm', model: 'small', effort: null }, lyricsReview: { providerId: 'tui-1', model: 'opus', effort: 'high' } },
+ };
+ expect((await resolveMusicVideoLlm({ automation, stage: 'lyrics' })).route).toEqual({ providerId: 'local-llm', model: 'small', effort: null, transport: 'api', source: 'stage' });
+ expect((await resolveMusicVideoLlm({ automation, stage: 'lyricsReview' })).route).toMatchObject({ providerId: 'tui-1', model: 'opus', effort: 'high', source: 'stage' });
+ // No pin for `plan`, and a caller that names no stage, both run on the direction pin.
+ expect((await resolveMusicVideoLlm({ automation, stage: 'plan' })).route).toMatchObject({ providerId: 'cloud', model: 'big', source: 'brief' });
+ expect((await resolveMusicVideoLlm({ automation })).route).toMatchObject({ providerId: 'cloud', source: 'brief' });
+ // A request pin still beats the stage pin.
+ expect((await resolveMusicVideoLlm({ automation, stage: 'lyrics', providerId: 'tui-1' })).route).toMatchObject({ providerId: 'tui-1', source: 'pinned' });
+ });
+
+ it('gives a vanished stage pin way to the next pin, naming what it replaced; authoring consults its own pin before the direction pin', async () => {
+ registry.providers = [api('cloud'), tui('tui-1'), api('author')];
+ registry.active = registry.providers[0];
+ const automation = { llm: { providerId: 'cloud' }, llmStages: { plan: { providerId: 'deleted-provider' } } };
+ expect((await resolveMusicVideoLlm({ automation, stage: 'plan' })).route).toMatchObject({ providerId: 'cloud', source: 'brief', requestedProviderId: 'deleted-provider' });
+
+ const authoring = { providerId: 'author', model: 'code-model' };
+ expect((await resolveMusicVideoLlm({ automation, stage: 'authoring', authoring })).route).toMatchObject({ providerId: 'author', model: 'code-model', source: 'brief' });
+ // The authoring stage's own pin outranks the authoring pin; other stages never read it.
+ expect((await resolveMusicVideoLlm({ automation: { ...automation, llmStages: { authoring: { providerId: 'tui-1' } } }, stage: 'authoring', authoring })).route).toMatchObject({ providerId: 'tui-1', source: 'stage' });
+ expect((await resolveMusicVideoLlm({ automation, stage: 'castAndSets', authoring })).route).toMatchObject({ providerId: 'cloud' });
+ });
+
it('survives a registry with no providers at all', async () => {
expect(await resolveMusicVideoLlm()).toEqual({ provider: null, selectedModel: null, route: null });
});
diff --git a/server/services/musicVideo/planner.js b/server/services/musicVideo/planner.js
index 5f16ea18e2..86f1dcf94d 100644
--- a/server/services/musicVideo/planner.js
+++ b/server/services/musicVideo/planner.js
@@ -241,8 +241,8 @@ async function tryProposeScenePrompts(project, shots, { providerId, model, effor
return { seeded: null, reason: 'too-many-shots' };
}
- // Request pin > the brief's saved LLM > an eligible TUI provider > the active one (llmRoute.js).
- const { provider, selectedModel, route } = await resolveMusicVideoLlm({ providerId, model, effort, automation: project.automation }).catch((err) => {
+ // Request pin > the brief's shot-plan pin > its direction LLM > an eligible TUI provider > the active one (llmRoute.js).
+ const { provider, selectedModel, route } = await resolveMusicVideoLlm({ providerId, model, effort, automation: project.automation, stage: 'plan' }).catch((err) => {
console.warn(`⚠️ Music Video plan: provider resolution failed for ${project.id}: ${err.message}`);
return { provider: null, selectedModel: null, route: null };
});
diff --git a/server/services/musicVideo/productionService.js b/server/services/musicVideo/productionService.js
index 294a1f1e2c..39ae14576e 100644
--- a/server/services/musicVideo/productionService.js
+++ b/server/services/musicVideo/productionService.js
@@ -453,8 +453,10 @@ async function takeSteps(projectId, runId) {
// Marked first, like the plan: a failed start halts instead of looping.
await mutateProjectRecord(projectId, (current) => markProductionCastAndSets(current, runId));
// The reviewer pick steers the direction call only when the brief pins no LLM of its
- // own — a saved brief pin is the deliberate choice (castAndSetsService resolves it).
- const reviewerPin = !project.automation?.llm?.providerId && run.reviewer?.providerId;
+ // own — a saved brief pin (direction or Cast & Sets stage) is the deliberate choice
+ // (castAndSetsService resolves it).
+ const briefPinned = project.automation?.llm?.providerId || project.automation?.llmStages?.castAndSets?.providerId;
+ const reviewerPin = !briefPinned && run.reviewer?.providerId;
const started = await deps.startCastAndSets(projectId, {
productionRunId: runId,
...(reviewerPin ? { providerId: run.reviewer.providerId } : {}),
diff --git a/server/services/musicVideo/projectsLogic.test.js b/server/services/musicVideo/projectsLogic.test.js
index dc43abba04..e1c51e9a03 100644
--- a/server/services/musicVideo/projectsLogic.test.js
+++ b/server/services/musicVideo/projectsLogic.test.js
@@ -354,6 +354,24 @@ describe('applyProjectPatch', () => {
expect(legacy.automation).toEqual({ tools: ['image:codex'], guidance: 'h', budgetUsd: null, checkins: { castAndSets: 'review' } });
});
+ it('merges per-stage LLM pins stage by stage: absent keeps, null clears one stage, null for the whole map clears them all', () => {
+ const lyrics = { providerId: 'local-llm', model: 'small', effort: null };
+ const plan = { providerId: 'claude-tui', model: 'opus', effort: 'high' };
+ const created = buildProjectRecord({ name: 'Auto', mode: 'autonomous', automation: { tools: ['image:codex'], llmStages: { lyrics, bogus: plan, plan: { model: 'orphan' } } } }, { id: 'mv-a', now: 'n' });
+ // Unknown stages and a pin with no provider are dropped.
+ expect(created.automation.llmStages).toEqual({ lyrics });
+
+ const added = applyProjectPatch(created, { automation: { llmStages: { plan } } });
+ expect(added.automation.llmStages).toEqual({ lyrics, plan });
+ // An unrelated brief edit keeps every stage pin.
+ expect(applyProjectPatch(added, { automation: { guidance: 'darker' } }).automation.llmStages).toEqual({ lyrics, plan });
+
+ expect(applyProjectPatch(added, { automation: { llmStages: { lyrics: null } } }).automation.llmStages).toEqual({ plan });
+ // Clearing the last stage drops the field rather than storing an empty map.
+ expect('llmStages' in applyProjectPatch(created, { automation: { llmStages: { lyrics: null } } }).automation).toBe(false);
+ expect('llmStages' in applyProjectPatch(added, { automation: { llmStages: null } }).automation).toBe(false);
+ });
+
it('persists explicit renderer settings and merges later partial changes', () => {
const project = buildProjectRecord({
name: 'A',