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: choose the Music Video autopilot LLM and prefer visible TUI runs (#9545)

[._.]/ Adam Eivy6bc2703003eb
diff --git a/client/src/components/cos/tabs/schedule/MusicVideoAutopilotSettings.jsx b/client/src/components/cos/tabs/schedule/MusicVideoAutopilotSettings.jsx
index 1caf43db87..5a1dcd4f3d 100644
--- a/client/src/components/cos/tabs/schedule/MusicVideoAutopilotSettings.jsx
+++ b/client/src/components/cos/tabs/schedule/MusicVideoAutopilotSettings.jsx
@@ -21,7 +21,8 @@ const inputClass = 'w-full min-w-0 bg-port-bg border border-port-border rounded
export default function MusicVideoAutopilotSettings({ taskType, config, onUpdate, updating, setUpdating }) {
const saved = config.taskMetadata?.musicVideoAutopilot;
const [draft, setDraft] = useState(() => autopilotDraftFromParams(saved));
- const llm = useProviderModels({ allowDefault: true, silent: true });
+ const llm = useProviderModels({ allowDefault: true, silent: true, withEffort: true });
+ const [effort, setEffort] = useState(saved?.llm?.effort || '');
const [llmSeeded, setLlmSeeded] = useState(false);
const patch = (next) => setDraft((d) => ({ ...d, ...next }));
@@ -48,8 +49,8 @@ export default function MusicVideoAutopilotSettings({ taskType, config, onUpdate
// Until the catalog has seeded the picker, "no selection" means "not loaded
// yet", not "use the install default" — keep the saved pin untouched.
const pin = llmSeeded
- ? { providerId: llm.selectedProviderId || undefined, model: llm.selectedModel || undefined }
- : { providerId: saved?.llm?.providerId, model: saved?.llm?.model || undefined };
+ ? { providerId: llm.selectedProviderId || undefined, model: llm.selectedModel || undefined, effort: effort || undefined }
+ : { providerId: saved?.llm?.providerId, model: saved?.llm?.model || undefined, effort: saved?.llm?.effort || undefined };
const params = autopilotParamsFromDraft(draft, saved, pin);
await onUpdate(taskType, { taskMetadata: { ...config.taskMetadata, musicVideoAutopilot: params } }).catch(() => {});
setUpdating(false);
@@ -105,8 +106,12 @@ export default function MusicVideoAutopilotSettings({ taskType, config, onUpdate
selectedProviderId={llm.selectedProviderId}
selectedModel={llm.selectedModel}
availableModels={llm.availableModels}
- onProviderChange={llm.setSelectedProviderId}
+ onProviderChange={(id) => { llm.setSelectedProviderId(id); setEffort(''); }}
onModelChange={llm.setSelectedModel}
+ effort={effort}
+ onEffortChange={setEffort}
+ emptyProviderOption="Auto — a TUI provider when one is eligible"
+ emptyModelOption="Provider default"
label="Writes the brief and lyrics"
disabled={updating}
modelDisabled={llm.availableModels.length === 0}
diff --git a/client/src/components/musicVideo/AutomationBriefFields.jsx b/client/src/components/musicVideo/AutomationBriefFields.jsx
index a9bee95423..5f43a9f55b 100644
--- a/client/src/components/musicVideo/AutomationBriefFields.jsx
+++ b/client/src/components/musicVideo/AutomationBriefFields.jsx
@@ -1,10 +1,11 @@
import ToggleChip from '../ui/ToggleChip.jsx';
+import MusicVideoLlmPicker from './MusicVideoLlmPicker.jsx';
import { MUSIC_VIDEO_AUTOMATION_TOOLS, MUSIC_VIDEO_AUTOMATION_TOOL_IDS } from '../../lib/musicVideoAutomation.js';
const GROUPS = [['image', 'Image'], ['video', 'Video'], ['code', 'Code']];
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 + budget for an automation-first music video. */
+/** Tool picker + guidance + direction LLM + budget for an automation-first music video. */
export default function AutomationBriefFields({ idPrefix, draft, onChange }) {
const picked = new Set(draft.tools);
const allPicked = picked.size === MUSIC_VIDEO_AUTOMATION_TOOL_IDS.length;
@@ -57,6 +58,7 @@ export default function AutomationBriefFields({ idPrefix, draft, onChange }) {
className={inputClass}
/>
</div>
+ <MusicVideoLlmPicker idPrefix={idPrefix} value={draft.llm} onChange={(llm) => onChange({ llm })} />
<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/AutonomousStartDrawer.jsx b/client/src/components/musicVideo/AutonomousStartDrawer.jsx
index 40c4a3f8ea..9238f08971 100644
--- a/client/src/components/musicVideo/AutonomousStartDrawer.jsx
+++ b/client/src/components/musicVideo/AutonomousStartDrawer.jsx
@@ -25,7 +25,8 @@ const inputClass = 'w-full min-w-0 bg-port-bg border border-port-border rounded
export default function AutonomousStartDrawer({ open, onClose, onStarted }) {
const [draft, setDraft] = useState(emptyAutonomousDraft);
const [submitting, setSubmitting] = useState(false);
- const llm = useProviderModels({ allowDefault: true, silent: true });
+ const llm = useProviderModels({ allowDefault: true, silent: true, withEffort: true });
+ const [effort, setEffort] = useState('');
const patch = (next) => setDraft((d) => ({ ...d, ...next }));
const toggleCheckpoint = (id) => patch({
checkpoints: AUTONOMOUS_CHECKPOINT_IDS.filter((c) => (c === id ? !draft.checkpoints.includes(c) : draft.checkpoints.includes(c))),
@@ -37,7 +38,7 @@ export default function AutonomousStartDrawer({ open, onClose, onStarted }) {
if (!valid || submitting) return;
setSubmitting(true);
startAutonomousMusicVideo(
- autonomousRequestFromDraft(draft, { providerId: llm.selectedProviderId || undefined, model: llm.selectedModel || undefined }),
+ autonomousRequestFromDraft(draft, { providerId: llm.selectedProviderId || undefined, model: llm.selectedModel || undefined, effort: effort || undefined }),
{ silent: true },
)
.then(({ project }) => {
@@ -130,8 +131,12 @@ export default function AutonomousStartDrawer({ open, onClose, onStarted }) {
selectedProviderId={llm.selectedProviderId}
selectedModel={llm.selectedModel}
availableModels={llm.availableModels}
- onProviderChange={llm.setSelectedProviderId}
+ onProviderChange={(id) => { llm.setSelectedProviderId(id); setEffort(''); }}
onModelChange={llm.setSelectedModel}
+ effort={effort}
+ onEffortChange={setEffort}
+ emptyProviderOption="Auto — a TUI provider when one is eligible"
+ emptyModelOption="Provider default"
label="Writes the brief and lyrics"
disabled={submitting}
modelDisabled={llm.availableModels.length === 0}
diff --git a/client/src/components/musicVideo/AutopilotBriefLlm.test.jsx b/client/src/components/musicVideo/AutopilotBriefLlm.test.jsx
new file mode 100644
index 0000000000..386f766a34
--- /dev/null
+++ b/client/src/components/musicVideo/AutopilotBriefLlm.test.jsx
@@ -0,0 +1,130 @@
+/**
+ * The autopilot brief's direction/planning LLM (#9545), over the REAL provider
+ * hook and selector with only the provider list doubled: the picker is
+ * available before kickoff, a pick (provider + model + effort) is what Save
+ * sends, a reload restores it, a dirty selection cannot start the kickoff, and
+ * the route each stage last ran on is shown. Nothing here calls a provider.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { useState } from 'react';
+import { render, screen, fireEvent, waitFor, within, act } from '@testing-library/react';
+
+vi.mock('../../services/api', async (importOriginal) => ({
+ ...(await importOriginal()),
+ getProviders: vi.fn(),
+}));
+vi.mock('../../services/apiMusicVideo.js', () => ({
+ startMusicVideoProduction: vi.fn(), resumeMusicVideoProduction: vi.fn(), stopMusicVideoProduction: vi.fn(), cancelMusicVideoProduction: vi.fn(),
+}));
+vi.mock('../../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn() } }));
+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), info: vi.fn(), error: vi.fn() } }));
+
+import AutopilotPanel from './AutopilotPanel.jsx';
+import * as api from '../../services/api';
+
+const PROVIDERS = [
+ { id: 'claude-tui', name: 'Claude TUI', type: 'tui', enabled: true, command: 'claude', models: ['opus', 'sonnet'], defaultModel: 'opus' },
+ { id: 'cloud-api', name: 'Cloud API', type: 'api', enabled: true, models: ['big'], defaultModel: 'big' },
+];
+const IDLE_PRODUCTION = { busy: false, start: vi.fn(), resume: vi.fn(), stop: vi.fn(), cancel: vi.fn() };
+const BASE = { tools: ['image:local'], guidance: 'Moody neon', budgetUsd: null, checkins: { castAndSets: 'review' } };
+
+// The server merges a patch per sub-field and returns the stored brief; do the same here.
+function Harness({ initial, onSave }) {
+ const [project, setProject] = useState({ id: 'mv-1', trackId: 't1', automation: initial });
+ const save = (patch) => {
+ onSave(patch);
+ const { llm, ...rest } = { ...project.automation, ...patch };
+ setProject((p) => ({ ...p, automation: { ...rest, ...(llm ? { llm } : {}) } }));
+ return Promise.resolve();
+ };
+ return <AutopilotPanel project={project} production={IDLE_PRODUCTION} onSave={save} onKickoff={vi.fn()} kickoffBusy={false} />;
+}
+
+// The production form below also renders provider pickers; scope to the brief's.
+const picker = async () => within(await screen.findByTestId('mv-auto-mv-1-llm'));
+// The production form's provider hooks fetch on mount; settle them inside act.
+const renderBrief = async (initial, onSave = vi.fn()) => {
+ render(<Harness initial={initial} onSave={onSave} />);
+ await act(async () => {});
+};
+const providerSelect = async () => (await picker()).findByLabelText('Direction & planning LLM');
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ api.getProviders.mockResolvedValue({ activeProvider: 'cloud-api', providers: PROVIDERS });
+});
+
+describe('AutopilotPanel direction LLM (#9545)', () => {
+ it('offers Auto before kickoff, saves a provider + model + effort pick, and shows it with the kickoff available again', async () => {
+ const onSave = vi.fn();
+ await renderBrief(BASE, onSave);
+ // Before editing: the saved brief names Auto and the kickoff is available.
+ expect(screen.getByText(/Direction LLM: Auto/)).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /Analyze & plan/ })).toBeEnabled();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Edit brief' }));
+ const provider = await providerSelect();
+ await waitFor(() => expect(provider).toHaveValue(''));
+ expect(screen.getByRole('option', { name: /Auto — a TUI provider/ })).toBeInTheDocument();
+
+ fireEvent.change(provider, { target: { value: 'claude-tui' } });
+ fireEvent.change(await (await picker()).findByLabelText('Model'), { target: { value: 'sonnet' } });
+ fireEvent.change(await (await picker()).findByLabelText('Thinking effort'), { target: { value: 'high' } });
+
+ // A dirty selection cannot start the kickoff: the editor replaces the kickoff control until saved.
+ expect(screen.queryByRole('button', { name: /Analyze & plan/ })).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Save brief' }));
+ await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
+ expect(onSave.mock.calls[0][0]).toMatchObject({ llm: { providerId: 'claude-tui', model: 'sonnet', effort: 'high' } });
+
+ expect(await screen.findByText(/Direction LLM: claude-tui · sonnet · high/)).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /Analyze & plan/ })).toBeEnabled();
+ });
+
+ it('restores a saved pin on reload, and sends an explicit null when the director goes back to Auto', async () => {
+ const onSave = vi.fn();
+ await renderBrief({ ...BASE, llm: { providerId: 'claude-tui', model: 'sonnet', effort: 'low' } }, onSave);
+ fireEvent.click(screen.getByRole('button', { name: 'Edit brief' }));
+
+ const provider = await providerSelect();
+ await waitFor(() => expect(provider).toHaveValue('claude-tui'));
+ expect(await (await picker()).findByLabelText('Model')).toHaveValue('sonnet');
+ expect(await (await picker()).findByLabelText('Thinking effort')).toHaveValue('low');
+
+ fireEvent.change(provider, { target: { value: '' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save brief' }));
+ await waitFor(() => expect(onSave).toHaveBeenCalled());
+ expect(onSave.mock.calls[0][0].llm).toBeNull();
+ expect(await screen.findByText(/Direction LLM: Auto/)).toBeInTheDocument();
+ });
+
+ it('says so, instead of silently keeping the pin, when the saved provider is gone', async () => {
+ const onSave = vi.fn();
+ await renderBrief({ ...BASE, llm: { providerId: 'deleted-provider', model: null, effort: null } }, onSave);
+ fireEvent.click(screen.getByRole('button', { name: 'Edit brief' }));
+
+ expect(await (await picker()).findByRole('status')).toHaveTextContent(/“deleted-provider” is no longer available/);
+ fireEvent.click(screen.getByRole('button', { name: 'Save brief' }));
+ await waitFor(() => expect(onSave).toHaveBeenCalled());
+ // The unavailable pin is cleared, not re-sent.
+ expect(onSave.mock.calls[0][0].llm).toBeNull();
+ });
+
+ 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' },
+ castAndSets: { providerId: 'cloud-api', model: 'big', transport: 'api', source: 'active', requestedProviderId: 'deleted-provider' },
+ };
+ await renderBrief({ ...BASE, routes });
+ expect(screen.getByText('Shot planning ran on claude-tui · opus · high (TUI)')).toBeInTheDocument();
+ expect(screen.getByText(/Cast & Sets direction ran on cloud-api · big \(API\) — replaced the unavailable deleted-provider/)).toBeInTheDocument();
+ });
+
+ it('loads a brief saved before the pin existed with no pin and no route lines', async () => {
+ await renderBrief(BASE);
+ expect(screen.getByText(/Direction LLM: Auto/)).toBeInTheDocument();
+ expect(screen.queryByText(/ran on/)).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/musicVideo/AutopilotPanel.jsx b/client/src/components/musicVideo/AutopilotPanel.jsx
index c896cab756..136a8d55bb 100644
--- a/client/src/components/musicVideo/AutopilotPanel.jsx
+++ b/client/src/components/musicVideo/AutopilotPanel.jsx
@@ -8,7 +8,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,
+ DEFAULT_AUTOMATION_TOOLS, MUSIC_VIDEO_AUTOMATION_TOOLS, automationDraftFrom, automationFromDraft, llmRouteLabel,
} from '../../lib/musicVideoAutomation.js';
import { RESUMABLE_RUN_STATUSES, currentProductionRun } from '../../lib/musicVideoStages.js';
import { formatCount, formatUsd } from '../../utils/formatters.js';
@@ -34,6 +34,12 @@ 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}` : ''}`;
+// Code authoring runs one-shot and tool-free (server: isToolFreeOneShotProvider), which a
+// TUI provider never is — offering one here only sets up a refusal at Start.
+const AUTHORING_PROVIDERS = (provider) => provider.enabled !== false && provider.type !== 'tui';
+
+const ROUTE_LABELS = [['plan', 'Shot planning'], ['castAndSets', 'Cast & Sets direction']];
+
const initialPool = (project) => {
const fromBrief = (project?.automation?.tools || []).filter((id) => POOL_TOOL_IDS.has(id));
const assets = codeFirstProductionAssets(project);
@@ -75,7 +81,7 @@ function RunView({ run, production, codeFirst, project }) {
</span>
</div>
{run.directive && <p className="text-port-text-muted break-words">Directive: {run.directive}</p>}
- {run.authoring && <p className="text-port-text-muted">Authoring: {run.authoring.providerId} · {run.authoring.model} · {run.authoring.costUsd == null ? 'unknown dollar cost (generation count still bounded)' : 'no per-call dollar charge; local compute or quota may apply'}</p>}
+ {run.authoring && <p className="text-port-text-muted">Authoring: {run.authoring.providerId} · {run.authoring.model}{run.authoring.effort ? ` · ${run.authoring.effort}` : ''} · {run.authoring.costUsd == null ? 'unknown dollar cost (generation count still bounded)' : 'no per-call dollar charge; local compute or quota may apply'}</p>}
{steps.some((step) => step.kind === 'plate') && <p className="text-port-text-muted">Plate preflight calls consume the generation limit. {steps.some((step) => step.kind === 'plate' && step.costUsd == null) ? 'Their dollar cost is unpriced; use a free vision API reviewer for dollar-capped runs.' : 'Their reserved dollar cost is included in the run total.'}</p>}
{run.authoring && <p className="text-port-text-muted">{['author', 'frame', 'clip'].map((kind) => {
const used = steps.filter((step) => step.kind === kind && step.status !== 'refused');
@@ -152,7 +158,8 @@ function RunView({ run, production, codeFirst, project }) {
function StartForm({ project, production }) {
const assets = codeFirstProductionAssets(project);
- const author = useProviderModels({ allowDefault: false, silent: true });
+ const author = useProviderModels({ allowDefault: false, silent: true, withEffort: true, filter: AUTHORING_PROVIDERS });
+ const [authorEffort, setAuthorEffort] = useState('');
const [pool, setPool] = useState(() => initialPool(project));
const [directive, setDirective] = useState('');
const [maxGenerations, setMaxGenerations] = useState(12);
@@ -179,7 +186,7 @@ function StartForm({ project, production }) {
const [kind, mode] = t.id.split(':');
return { kind, mode };
}),
- ...(assets ? { authoring: { providerId: author.selectedProviderId, model: author.selectedModel } } : {}),
+ ...(assets ? { authoring: { providerId: author.selectedProviderId, model: author.selectedModel, ...(authorEffort ? { effort: authorEffort } : {}) } } : {}),
limits: { maxGenerations, maxReviewAttempts, ...(capValue != null ? { spendCapUsd: capValue } : {}) },
...(selectedProviderId ? { providerId: selectedProviderId } : {}),
...(selectedModel ? { model: selectedModel } : {}),
@@ -234,8 +241,10 @@ function StartForm({ project, production }) {
selectedProviderId={author.selectedProviderId}
selectedModel={author.selectedModel}
availableModels={author.availableModels}
- onProviderChange={author.setSelectedProviderId}
+ onProviderChange={(id) => { author.setSelectedProviderId(id); setAuthorEffort(''); }}
onModelChange={author.setSelectedModel}
+ effort={authorEffort}
+ onEffortChange={setAuthorEffort}
label="Code authoring"
disabled={production.busy}
modelDisabled={author.availableModels.length === 0}
@@ -273,7 +282,10 @@ function BriefSection({ project, onSave, onKickoff, kickoffBusy, kickoffStep, ki
const save = () => {
setSaving(true);
- onSave(automationFromDraft(draft))
+ const payload = automationFromDraft(draft);
+ // 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)
.then(() => setDraft(null))
// A failed save keeps the brief open for another try.
.catch(() => {})
@@ -328,6 +340,15 @@ function BriefSection({ project, onSave, onKickoff, kickoffBusy, kickoffStep, ki
<p className="text-xs text-port-text-muted break-words line-clamp-3">
{automation.guidance || 'No guidance yet — the agent plans from the song, universe and board alone.'}
</p>
+ <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>
+ {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])}
+ {automation.routes[stage].requestedProviderId ? ` — replaced the unavailable ${automation.routes[stage].requestedProviderId}` : ''}
+ </p>
+ ))}
{kickoffStep && <p className="text-xs text-port-accent" role="status">{kickoffStep}</p>}
{kickoffBlockedReason && <p className="text-xs text-port-warning">{kickoffBlockedReason}</p>}
</>
diff --git a/client/src/components/musicVideo/MusicVideoLlmPicker.jsx b/client/src/components/musicVideo/MusicVideoLlmPicker.jsx
new file mode 100644
index 0000000000..05733f71f7
--- /dev/null
+++ b/client/src/components/musicVideo/MusicVideoLlmPicker.jsx
@@ -0,0 +1,75 @@
+import { useEffect, useState } from 'react';
+import ProviderModelSelector from '../ProviderModelSelector.jsx';
+import useProviderModels from '../../hooks/useProviderModels.js';
+import { EMPTY_LLM_DRAFT } from '../../lib/musicVideoAutomation.js';
+
+/**
+ * Provider / model / effort for a Music Video text stage (#9545). `value` is the
+ * draft `{ providerId, model, effort }` (all strings); a blank provider is Auto,
+ * which the server resolves to an eligible TUI provider (visible as a Shell
+ * session) before falling back to the active provider — so Auto is named in the
+ * dropdown rather than left implicit.
+ *
+ * The hook only supplies the provider catalog; the parent owns the value. The
+ * 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.
+ */
+export default function MusicVideoLlmPicker({ idPrefix, value, onChange, disabled = false, label = 'Direction & planning LLM' }) {
+ const llm = useProviderModels({ allowDefault: true, silent: true, withEffort: true });
+ const { providers, loading, setSelectedProviderId, setSelectedModel } = llm;
+ const [seeded, setSeeded] = useState(false);
+ const [missingId, setMissingId] = useState('');
+ const current = value || EMPTY_LLM_DRAFT;
+
+ useEffect(() => {
+ if (seeded || loading) return;
+ setSeeded(true);
+ if (!current.providerId) return;
+ if (providers.some((p) => p.id === current.providerId)) {
+ setSelectedProviderId(current.providerId);
+ setSelectedModel(current.model || '');
+ } else if (providers.length) {
+ setMissingId(current.providerId);
+ onChange({ ...EMPTY_LLM_DRAFT });
+ }
+ }, [seeded, loading, providers, current.providerId, current.model, setSelectedProviderId, setSelectedModel, onChange]);
+
+ const pickProvider = (providerId) => {
+ setMissingId('');
+ setSelectedProviderId(providerId);
+ onChange({ providerId, model: '', effort: '' });
+ };
+ const pickModel = (model) => {
+ setSelectedModel(model);
+ onChange({ ...current, model });
+ };
+
+ return (
+ <div className="min-w-0" data-testid={`${idPrefix}-llm`}>
+ <ProviderModelSelector
+ providers={providers}
+ selectedProviderId={llm.selectedProviderId}
+ selectedModel={llm.selectedModel}
+ availableModels={llm.availableModels}
+ onProviderChange={pickProvider}
+ onModelChange={pickModel}
+ effort={current.effort}
+ onEffortChange={(effort) => onChange({ ...current, effort })}
+ label={label}
+ emptyProviderOption="Auto — a TUI provider when one is eligible"
+ emptyModelOption="Provider default"
+ disabled={disabled}
+ loading={loading}
+ modelDisabled={llm.availableModels.length === 0}
+ 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>
+ </div>
+ );
+}
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index a4037a1bbc..3ee7a5333c 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -67,7 +67,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `musicVideoStages.js` | Music Video page stage model: `MUSIC_VIDEO_STAGES` (setup → cast-sets → board → produce → compose → review), `resolveStageParam(value)` for the `:stage` route param, `deriveStages(project)` (per-stage `done`/`active`/`blocked`/`todo` + `current`, the first incomplete stage; a live production run pins Produce), `deriveNextAction(project, ctx)` (the one primary action the sticky header offers — approve Cast & Sets, stop/resume production, render final, …), `projectSpend(project)` (paid generation used vs. cap) and `currentProductionRun`. Used by `components/musicVideo/MusicVideoLayout.jsx` and `pages/MusicVideo.jsx`. |
| `musicVideoUniverseRefs.js` | `pullUniverseCanonReferences(universe, existingReferences)` (#8978) maps a linked universe's characters/places/objects to visual-spec references (character/set/prop roles), skipping images already present and capping at `MUSIC_VIDEO_MAX_REFERENCES` (24, mirrors the server schema). Returns `{ next, added, skipped }`; the caller persists `next` via the ordinary visualSpec PATCH. Used by `components/musicVideo/VisualSpecPanel.jsx`. (The style snapshots are derived server-side, #9105.) |
| `musicVideoAutonomous.js` | Fully-autonomous Music Video, client half: re-exports the server stage vocabulary (`AUTONOMOUS_STAGES`, checkpoint ids, default tools/limits, `autonomousMedium`), the status/checkpoint labels, and owns the start form's `emptyAutonomousDraft` / `autonomousRequestFromDraft` mapping plus `autonomousStageRows(run)` and `isAutonomousLive(run)` for the run panel, and `autopilotDraftFromParams` / `autopilotParamsFromDraft` for the music-video-autopilot Schedule settings form. |
-| `musicVideoAutomation.js` | Music Video automation brief, client half: re-exports the server tool catalog (`MUSIC_VIDEO_AUTOMATION_TOOLS` / `_TOOL_IDS`), `DEFAULT_AUTOMATION_TOOLS` (the unmetered tools), and the form mapping `automationDraftFrom(automation)` / `automationFromDraft(draft)` (empty budget = no cap). Used by the create drawer and `AutopilotPanel`. |
+| `musicVideoAutomation.js` | Music Video automation brief, client half: re-exports the server tool catalog (`MUSIC_VIDEO_AUTOMATION_TOOLS` / `_TOOL_IDS`), `DEFAULT_AUTOMATION_TOOLS` (the unmetered tools), and the form mapping `automationDraftFrom(automation)` / `automationFromDraft(draft)` (empty budget = no cap; the direction-LLM pin rides as `llm`, absent = Auto), plus `llmRouteLabel(route)` for the stage-route summary. Used by the create drawer and `AutopilotPanel`. |
| `bibleLimits.js` | `BIBLE_LIMITS` re-exported from the pure leaf `server/lib/bibleLimits.js`, plus the client-only `capImageRefs` / `appendImageRefById` for the optimistic imageRefs-append paths. |
| `characterEvolution.js` | The five-stage character evolution lens as the editors consume it. Re-exports `EVOLUTION_STAGES` / `EVOLUTION_OUTCOMES` / `EVOLUTION_STAGE_LABELS` / `EVOLUTION_STAGE_TEXT_FIELDS` / `EVOLUTION_EVIDENCE_FIELDS` / `EVOLUTION_EVIDENCE_STATUSES` / `CHARACTER_EVOLUTION_LIMITS` / `evolutionEvidenceStatus` / `isDeclaredEvolution` from the pure leaf `server/lib/characterEvolution.js` (a guard in `server/lib/characterEvolution.test.js` fails if this file ever restates a vocabulary instead of re-exporting it), adds the editor descriptors `EVOLUTION_STAGE_EDITOR_FIELDS` / `EVOLUTION_OUTCOME_HINTS` (#6440), and the draft-mutation helpers `evolutionStage` / `patchEvolution` / `patchEvolutionStage` / `patchEvolutionEvidence` that keep an editor's draft collapsing to the same shape the server sanitizer produces — so a present-but-empty field is a real clear (#6441). |
| `characterFramework.js` | The narrative-character framework as the editors consume it. Re-exports `CHARACTER_ARC_TYPES` / `CHARACTER_FRAMEWORK_FIELDS` / `CHARACTER_FRAMEWORK_TEXT_FIELDS` / `CHARACTER_FRAMEWORK_LIMITS` / `CHARACTER_PSYCHOLOGY_LIMITS` / `CHARACTER_SLIDER_AXES` / `PSYCHOLOGY_ASSESSMENTS` / `PSYCHOLOGY_DRIVE_AXES` / `RELATIONSHIP_LINK_TYPES` from the pure leaf `server/lib/characterFramework.js`, and adds the editor descriptors `CHARACTER_FRAMEWORK_EDITOR_FIELDS` (Ghost → Wound → Lie → Need → Want, with labels/placeholders/caps), `CHARACTER_MOTIVATIONS_FIELD`, `CHARACTER_SECRETS_FIELD`, `CHARACTER_PSYCHOLOGY_EDITOR_FIELDS` / `CHARACTER_PSYCHOLOGY_NOTE_FIELD` / `CHARACTER_PSYCHOLOGY_DRIVE_HINTS` (#6414), and `CHARACTER_SLIDER_MIN` / `CHARACTER_SLIDER_MAX`. Shared by the Universe cast editor and the Writers Room bible so the two never restate the same field copy (#6417). |
diff --git a/client/src/lib/musicVideoAutomation.js b/client/src/lib/musicVideoAutomation.js
index 9ec78e8ade..402e01e65a 100644
--- a/client/src/lib/musicVideoAutomation.js
+++ b/client/src/lib/musicVideoAutomation.js
@@ -1,14 +1,20 @@
// 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 } from '../../../server/lib/musicVideoAutomation.js';
+import { MUSIC_VIDEO_AUTOMATION_TOOLS, MUSIC_VIDEO_AUTOMATION_TOOL_IDS, musicVideoLlmRouteLabel } from '../../../server/lib/musicVideoAutomation.js';
export { MUSIC_VIDEO_AUTOMATION_TOOLS, MUSIC_VIDEO_AUTOMATION_TOOL_IDS };
+// `claude-tui · opus · high (TUI)` — one line naming the route a stage ran on.
+export const llmRouteLabel = musicVideoLlmRouteLabel;
// Free (local) tools — the default pick for a new autopilot brief, so nothing
// metered is spent until the director opts in.
export const DEFAULT_AUTOMATION_TOOLS = MUSIC_VIDEO_AUTOMATION_TOOLS.filter((t) => !t.metered).map((t) => t.id);
+// The direction/planning LLM pin as form strings: '' provider = Auto (an eligible
+// TUI provider, else the active one — resolved server-side, see llmRoute.js).
+export const EMPTY_LLM_DRAFT = Object.freeze({ providerId: '', model: '', effort: '' });
+
// The draft keeps budget as the raw input string so an empty field reads as
// "no cap" rather than 0.
export const automationDraftFrom = (automation) => ({
@@ -17,6 +23,9 @@ 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 },
});
export const automationFromDraft = (draft) => {
@@ -26,5 +35,11 @@ export const automationFromDraft = (draft) => {
guidance: draft.guidance.trim(),
budgetUsd: Number.isFinite(budget) && budget >= 0 ? budget : null,
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 } }
+ : {}),
};
};
+
diff --git a/client/src/lib/musicVideoAutomation.test.js b/client/src/lib/musicVideoAutomation.test.js
new file mode 100644
index 0000000000..bd849ea8a3
--- /dev/null
+++ b/client/src/lib/musicVideoAutomation.test.js
@@ -0,0 +1,38 @@
+import { describe, it, expect } from 'vitest';
+import { automationDraftFrom, automationFromDraft, llmRouteLabel } from './musicVideoAutomation.js';
+import { autonomousRequestFromDraft, 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', () => {
+ const saved = { tools: ['image:local'], guidance: 'g', budgetUsd: null, llm: { providerId: 'claude-tui', model: 'opus', effort: 'high' } };
+ const draft = automationDraftFrom(saved);
+ expect(draft.llm).toEqual({ providerId: 'claude-tui', model: 'opus', effort: 'high' });
+ expect(automationFromDraft(draft).llm).toEqual({ providerId: 'claude-tui', model: 'opus', effort: 'high' });
+
+ // Blank model/effort become null so the server stores "provider default / no effort".
+ expect(automationFromDraft({ ...draft, llm: { providerId: 'claude-tui', model: '', effort: '' } }).llm)
+ .toEqual({ providerId: 'claude-tui', model: null, effort: null });
+
+ const auto = automationDraftFrom({ tools: [], guidance: '', budgetUsd: null });
+ expect(auto.llm).toEqual({ providerId: '', model: '', effort: '' });
+ expect('llm' in automationFromDraft(auto)).toBe(false);
+ });
+
+ it('names a route on one line', () => {
+ expect(llmRouteLabel({ providerId: 'claude-tui', model: 'opus', effort: 'high', transport: 'tui' })).toBe('claude-tui · opus · high (TUI)');
+ expect(llmRouteLabel({ providerId: 'cloud', transport: 'api' })).toBe('cloud (API)');
+ });
+});
+
+describe('autonomous entry and scheduled params carry effort (#9545)', () => {
+ it('sends effort only with a provider, and stores it on the scheduled pin', () => {
+ const draft = emptyAutonomousDraft();
+ expect(autonomousRequestFromDraft({ ...draft, prompt: 'p' }, { providerId: 'claude-tui', model: 'opus', effort: 'high' }))
+ .toMatchObject({ providerId: 'claude-tui', model: 'opus', effort: 'high' });
+ expect(autonomousRequestFromDraft({ ...draft, prompt: 'p' }, { effort: 'high' })).not.toHaveProperty('effort');
+
+ expect(autopilotParamsFromDraft(draft, null, { providerId: 'claude-tui', model: 'opus', effort: 'low' }).llm)
+ .toEqual({ providerId: 'claude-tui', model: 'opus', effort: 'low' });
+ expect(autopilotParamsFromDraft(draft, null, { providerId: 'claude-tui' }).llm).toEqual({ providerId: 'claude-tui', model: null });
+ });
+});
diff --git a/client/src/lib/musicVideoAutonomous.js b/client/src/lib/musicVideoAutonomous.js
index c5bb0f3aa3..ada9f23b57 100644
--- a/client/src/lib/musicVideoAutonomous.js
+++ b/client/src/lib/musicVideoAutonomous.js
@@ -43,7 +43,7 @@ const optionalInt = (raw) => {
};
/** The start request for a draft: blank optional fields are omitted so the server defaults apply. */
-export function autonomousRequestFromDraft(draft, { providerId, model } = {}) {
+export function autonomousRequestFromDraft(draft, { providerId, model, effort } = {}) {
const budget = Number.parseFloat(draft.budget);
const maxGenerations = optionalInt(draft.maxGenerations);
const models = Object.fromEntries(Object.entries(draft.models || {})
@@ -61,7 +61,7 @@ export function autonomousRequestFromDraft(draft, { providerId, model } = {}) {
...(maxGenerations ? { limits: { maxGenerations } } : {}),
checkpoints: draft.checkpoints,
...(draft.moodBoardId ? { moodBoardId: draft.moodBoardId } : {}),
- ...(providerId ? { providerId, ...(model ? { model } : {}) } : {}),
+ ...(providerId ? { providerId, ...(model ? { model } : {}), ...(effort ? { effort } : {}) } : {}),
};
}
@@ -102,7 +102,7 @@ export function autopilotDraftFromParams(params) {
* The `musicVideoAutopilot` params a draft saves. Starts from the saved params
* so fields the form does not edit (review attempts, authoring provider) survive a save; the server re-normalizes it all on write.
*/
-export function autopilotParamsFromDraft(draft, saved, { providerId, model } = {}) {
+export function autopilotParamsFromDraft(draft, saved, { providerId, model, effort } = {}) {
const { prompt: _prompt, ...request } = autonomousRequestFromDraft({ ...draft, prompt: '' }, {});
const { llm: _llm, ...kept } = saved && typeof saved === 'object' ? saved : {};
return {
@@ -112,6 +112,6 @@ export function autopilotParamsFromDraft(draft, saved, { providerId, model } = {
limits: { ...(kept.limits || {}), ...(request.limits || {}) },
moodBoardId: draft.moodBoardId || null,
ideaTags: String(draft.ideaTags || '').split(',').map((t) => t.trim()).filter(Boolean),
- ...(providerId ? { llm: { providerId, model: model || null } } : {}),
+ ...(providerId ? { llm: { providerId, model: model || null, ...(effort ? { effort } : {}) } } : {}),
};
}
diff --git a/server/lib/README.md b/server/lib/README.md
index 3f047a69e3..fba0fa3766 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -800,7 +800,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; `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, 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). Dependency-free; 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, server-written `routes` survive but are never patch-settable). Also `normalizeMusicVideoLlm` / `normalizeMusicVideoLlmRoute` / `normalizeMusicVideoEffort` / `musicVideoLlmRouteLabel` for that pin and the effective route a stage ran on (#9545). 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 fa87958d0b..69f924cafd 100644
--- a/server/lib/musicVideoAutomation.js
+++ b/server/lib/musicVideoAutomation.js
@@ -11,6 +11,7 @@
* pass (typography, composition layers, procedural frames).
*/
+import { EFFORT_LEVELS } from './providerModels.js';
import {
CLOUD_IMAGE_GEN_MODES, CLOUD_VIDEO_GEN_MODES, IMAGE_GEN_MODE, IMAGE_GEN_MODES, VIDEO_GEN_MODE, VIDEO_GEN_MODES,
} from './generationModes.js';
@@ -50,17 +51,77 @@ 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']);
+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']);
+
+/** 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);
+
+/**
+ * The direction/planning LLM the brief pins (#9545): provider, optional model
+ * and optional reasoning effort. Returns null when no provider is pinned — the
+ * stages then prefer an eligible TUI provider (see services/musicVideo/llmRoute.js).
+ * A model or effort with no provider is dropped: neither is meaningful alone.
+ */
+export function normalizeMusicVideoLlm(raw) {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const text = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
+ const providerId = text(raw.providerId, 200);
+ if (!providerId) return null;
+ return {
+ providerId,
+ model: text(raw.model, 200) || null,
+ effort: normalizeMusicVideoEffort(raw.effort),
+ };
+}
+
+/** The effective LLM route a stage last ran on, as stored for the project summary. */
+export function normalizeMusicVideoLlmRoute(raw) {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const providerId = typeof raw.providerId === 'string' ? raw.providerId.trim().slice(0, 200) : '';
+ if (!providerId) return null;
+ const text = (v, max) => (typeof v === 'string' && v.trim() ? v.trim().slice(0, max) : null);
+ return {
+ providerId,
+ model: text(raw.model, 200),
+ effort: normalizeMusicVideoEffort(raw.effort),
+ transport: MUSIC_VIDEO_LLM_TRANSPORTS.includes(raw.transport) ? raw.transport : null,
+ source: MUSIC_VIDEO_LLM_ROUTE_SOURCES.includes(raw.source) ? raw.source : null,
+ // A saved pin whose provider no longer resolved: what the run replaced.
+ ...(text(raw.requestedProviderId, 200) ? { requestedProviderId: text(raw.requestedProviderId, 200) } : {}),
+ at: text(raw.at, 40),
+ };
+}
+
+/** One line naming the route a stage ran on: `claude-tui · opus · high (TUI)`. */
+export const musicVideoLlmRouteLabel = (route) => (route?.providerId
+ ? `${route.providerId}${route.model ? ` · ${route.model}` : ''}${route.effort ? ` · ${route.effort}` : ''}${route.transport ? ` (${route.transport.toUpperCase()})` : ''}`
+ : 'no provider');
/**
* Merge a validated automation patch onto the stored brief. Sub-fields merge
* (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
+ * effective route each stage last ran on) is server-written: only the stored
+ * record's value survives — a patch can never set it.
*/
export function normalizeMusicVideoAutomation(patch, current = null) {
const merged = { ...(current || {}), ...(patch || {}) };
const picked = new Set(Array.isArray(merged.tools) ? merged.tools : []);
const budget = Number(merged.budgetUsd);
+ const routes = {};
+ for (const stage of MUSIC_VIDEO_AUTOMATION_ROUTE_STAGES) {
+ const route = normalizeMusicVideoLlmRoute(current?.routes?.[stage]);
+ if (route) routes[stage] = route;
+ }
+ const llm = normalizeMusicVideoLlm(merged.llm);
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) : '',
@@ -69,5 +130,7 @@ export function normalizeMusicVideoAutomation(patch, current = null) {
checkins: {
castAndSets: ({ ...(current?.checkins || {}), ...(patch?.checkins || {}) }).castAndSets === 'auto' ? 'auto' : 'review',
},
+ ...(llm ? { llm } : {}),
+ ...(Object.keys(routes).length ? { routes } : {}),
};
}
diff --git a/server/lib/musicVideoAutonomous.js b/server/lib/musicVideoAutonomous.js
index 52d625e81f..ab9c2bdeba 100644
--- a/server/lib/musicVideoAutonomous.js
+++ b/server/lib/musicVideoAutonomous.js
@@ -26,7 +26,7 @@
* the run is fully unattended.
*/
-import { MUSIC_VIDEO_AUTOMATION_TOOL_IDS } from './musicVideoAutomation.js';
+import { MUSIC_VIDEO_AUTOMATION_TOOL_IDS, normalizeMusicVideoEffort, normalizeMusicVideoLlm } from './musicVideoAutomation.js';
import { isStr, trimTo } from './textUtils.js';
export const AUTONOMOUS_STAGES = Object.freeze([
@@ -108,10 +108,12 @@ function normalizeAutonomousSettings(raw = {}) {
}
const checkpoints = AUTONOMOUS_CHECKPOINT_IDS.filter((id) => Array.isArray(raw.checkpoints) && raw.checkpoints.includes(id));
const budget = Number(raw.budgetUsd);
- const llmProvider = clean(raw.providerId, 200);
- const llmModel = clean(raw.model, 200);
+ // The direction LLM is a top-level providerId/model/effort on a start request but a
+ // nested `llm` on a stored brief or the scheduled task's params (#9545 added effort).
+ const llm = normalizeMusicVideoLlm(raw.providerId ? raw : raw.llm);
const authoringProvider = clean(raw.authoring?.providerId, 200);
const authoringModel = clean(raw.authoring?.model, 200);
+ const authoringEffort = normalizeMusicVideoEffort(raw.authoring?.effort);
return {
songSource: AUTONOMOUS_SONG_SOURCES.includes(raw.songSource) ? raw.songSource : AUTONOMOUS_SONG_SOURCES[0],
// Suno only: when it cannot even take the request (signed out, no credits,
@@ -129,8 +131,9 @@ function normalizeAutonomousSettings(raw = {}) {
checkpoints,
// An existing mood board to reuse instead of generating one (blank = generate).
moodBoardId: clean(raw.moodBoardId, 64) || null,
- llm: llmProvider ? { providerId: llmProvider, model: llmModel || null } : null,
- authoring: authoringProvider && authoringModel ? { providerId: authoringProvider, model: authoringModel } : null,
+ llm: llm ? { providerId: llm.providerId, model: llm.model, ...(llm.effort ? { effort: llm.effort } : {}) } : null,
+ authoring: authoringProvider && authoringModel
+ ? { providerId: authoringProvider, model: authoringModel, ...(authoringEffort ? { effort: authoringEffort } : {}) } : null,
};
}
diff --git a/server/lib/musicVideoAutonomous.test.js b/server/lib/musicVideoAutonomous.test.js
index a1bb449477..b2bcbdbd48 100644
--- a/server/lib/musicVideoAutonomous.test.js
+++ b/server/lib/musicVideoAutonomous.test.js
@@ -38,6 +38,17 @@ describe('normalizeAutonomousBrief', () => {
expect(brief.llm).toEqual({ providerId: 'prov', model: 'm' });
});
+ it('carries effort on the direction LLM and the authoring pin, reads a nested saved `llm`, and drops an unknown effort (#9545)', () => {
+ const body = musicVideoAutonomousStartSchema.parse({ prompt: 'p', providerId: 'prov', model: 'm', effort: 'high', authoring: { providerId: 'a', model: 'b', effort: 'low' } });
+ expect(normalizeAutonomousBrief(body)).toMatchObject({ llm: { providerId: 'prov', model: 'm', effort: 'high' }, authoring: { providerId: 'a', model: 'b', effort: 'low' } });
+ expect(() => musicVideoAutonomousStartSchema.parse({ prompt: 'p', providerId: 'prov', effort: 'turbo' })).toThrow();
+ // The scheduled task stores the pin nested as `llm`; it must survive a re-normalize.
+ expect(normalizeAutopilotParams({ llm: { providerId: 'prov', model: 'm', effort: 'medium' } }).llm).toEqual({ providerId: 'prov', model: 'm', effort: 'medium' });
+ // No effort stays absent (older records and tests keep their exact shape).
+ expect(normalizeAutonomousBrief({ prompt: 'p', providerId: 'prov' }).llm).toEqual({ providerId: 'prov', model: null });
+ expect(normalizeAutonomousBrief({ prompt: 'p', providerId: 'prov', effort: 'turbo' }).llm).toEqual({ providerId: 'prov', model: null });
+ });
+
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 921beca719..0eac7f03e9 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -10,6 +10,7 @@ import { MUSIC_VIDEO_GRADE_PRESETS, MUSIC_VIDEO_GRADE_MAX_GRAIN } from './musicV
*/
import { z } from 'zod';
+import { EFFORT_LEVELS } from './providerModels.js';
import { shotActionContractProblem } from './musicVideoActionContract.js';
import { NARRATIVE_EVENT_KINDS } from './musicVideoNarrativeEvents.js';
import { MUSIC_VIDEO_MEDIA } from './musicVideoMediumPlan.js';
@@ -339,6 +340,7 @@ export const musicVideoCodeVideoSchema = z.object({
export const musicVideoCodeGenerateSchema = z.object({
providerId: z.string().max(120).optional(),
model: z.string().max(200).optional(),
+ effort: z.enum(EFFORT_LEVELS).optional(),
}).strict();
// Where the project's composition document lives. Set only by the import
@@ -715,11 +717,18 @@ export const musicVideoProductionLimitsSchema = z.object({
spendCapUsd: z.number().min(0).max(100000).nullable().optional(),
}).strict();
+// A code-authoring provider pin: both ids are required, effort is optional.
+const musicVideoAuthoringSchema = z.object({
+ providerId: z.string().min(1).max(200),
+ model: z.string().min(1).max(200),
+ effort: z.enum(EFFORT_LEVELS).nullable().optional(),
+}).strict();
+
export const musicVideoProductionStartSchema = z.object({
directive: z.string().max(4000).optional(),
pool: z.array(musicVideoProductionRouteSchema).max(12),
limits: musicVideoProductionLimitsSchema,
- authoring: z.object({ providerId: z.string().min(1).max(200), model: z.string().min(1).max(200) }).strict().optional(),
+ authoring: musicVideoAuthoringSchema.optional(),
providerId: z.string().min(1).max(200).nullable().optional(),
model: z.string().min(1).max(200).nullable().optional(),
}).strict();
@@ -752,11 +761,13 @@ export const musicVideoAutonomousStartSchema = z.object({
checkpoints: z.array(z.enum(AUTONOMOUS_CHECKPOINT_IDS)).max(AUTONOMOUS_CHECKPOINT_IDS.length).optional(),
// Reuse this existing mood board instead of generating one from the prompt.
moodBoardId: z.string().trim().min(1).max(64).nullable().optional(),
- // The LLM that writes the brief and lyrics (blank = the install's active provider).
+ // The LLM that writes the brief and lyrics (blank = an eligible TUI provider, else the
+ // install's active provider — see services/musicVideo/llmRoute.js).
providerId: z.string().trim().min(1).max(200).nullable().optional(),
model: z.string().trim().min(1).max(200).nullable().optional(),
+ effort: z.enum(EFFORT_LEVELS).nullable().optional(),
// The separate code-authoring provider a code-rendered video needs.
- authoring: z.object({ providerId: z.string().min(1).max(200), model: z.string().min(1).max(200) }).strict().optional(),
+ authoring: musicVideoAuthoringSchema.optional(),
origin: z.object({
kind: z.enum(AUTONOMOUS_ORIGINS).optional(),
ideaId: z.string().max(80).nullable().optional(),
@@ -786,6 +797,14 @@ 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.
@@ -798,6 +817,9 @@ export const musicVideoAutomationSchema = z.object({
checkins: z.object({
castAndSets: z.enum(MUSIC_VIDEO_CHECKIN_MODES).optional(),
}).strict().optional(),
+ // 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(),
}).strict();
// ---- Development artifacts ("ingredients") ----------------------------------
@@ -850,6 +872,7 @@ export const musicVideoDevArtifactFileQuerySchema = z.object({
export const musicVideoCastAndSetsStartSchema = z.object({
providerId: z.string().min(1).max(64).optional(),
model: z.string().min(1).max(200).optional(),
+ effort: z.enum(EFFORT_LEVELS).optional(),
}).strict();
// Regenerate with notes. Omitted notes = the open notes on the sheet. A
@@ -862,6 +885,7 @@ export const musicVideoCastAndSetsRegenerateSchema = z.object({
}).strict()).min(1).max(50).optional(),
providerId: z.string().min(1).max(64).optional(),
model: z.string().min(1).max(200).optional(),
+ effort: z.enum(EFFORT_LEVELS).optional(),
}).strict();
export const musicVideoProjectCreateSchema = z.object({
@@ -996,6 +1020,7 @@ export const musicVideoPlanRequestSchema = z.object({
seedPrompts: z.boolean().optional(),
providerId: z.string().max(64).optional(),
model: z.string().max(200).optional(),
+ effort: z.enum(EFFORT_LEVELS).optional(),
}).strict();
// Manual-tempo fallback (see services/musicVideo/audioAnalysis.js for why bpm
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index fe9fe98a3f..49f41741be 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -324,8 +324,8 @@ router.post('/:id/analyze/manual', asyncHandler(async (req, res) => {
// a missing provider or parse failure degrades to plain scenes rather than
// failing the request (see `promptsSeeded`/`promptsSkippedReason` in the body).
router.post('/:id/plan', asyncHandler(async (req, res) => {
- const { seedPrompts, providerId, model } = validateRequest(musicVideoPlanRequestSchema, req.body || {});
- const result = await planProject(req.params.id, { seedPrompts, providerId, model });
+ const { seedPrompts, providerId, model, effort } = validateRequest(musicVideoPlanRequestSchema, req.body || {});
+ const result = await planProject(req.params.id, { seedPrompts, providerId, model, effort });
res.json(result);
}));
diff --git a/server/services/musicVideo/autonomousBrief.js b/server/services/musicVideo/autonomousBrief.js
index b63b734406..2bfdb3fc48 100644
--- a/server/services/musicVideo/autonomousBrief.js
+++ b/server/services/musicVideo/autonomousBrief.js
@@ -76,12 +76,13 @@ function sanitizeBrief(parsed, { prompt }) {
};
}
-export async function draftCreativeBrief({ prompt, guidance = '', instrumental = false, providerId, model } = {}) {
+export async function draftCreativeBrief({ prompt, guidance = '', instrumental = false, providerId, model, effort } = {}) {
const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });
assertProvider(provider, { message: 'No AI provider available to draft the music video brief', code: 'NO_PROVIDER' });
const result = await runPromptThroughProvider({
provider,
model: selectedModel,
+ ...(effort ? { effort } : {}),
prompt: buildBriefPrompt({ prompt, guidance, instrumental }),
source: 'music-video-autonomous-brief',
});
diff --git a/server/services/musicVideo/autonomousService.js b/server/services/musicVideo/autonomousService.js
index 4ae1571117..317b99aeb8 100644
--- a/server/services/musicVideo/autonomousService.js
+++ b/server/services/musicVideo/autonomousService.js
@@ -57,6 +57,7 @@ const short = (id) => String(id).slice(0, 8);
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),
draftCreativeBrief: async (args) => (await import('./autonomousBrief.js')).draftCreativeBrief(args),
writeLyrics: async (args) => (await import('../musicDesigner.js')).writeLyrics(args),
createMoodBoard: async (spec) => (await import('./autonomousBoard.js')).createAutonomousMoodBoard(spec),
@@ -122,7 +123,22 @@ const stagePatch = (run, stage, patch) => ({ stages: { [stage]: { ...run.stages[
// Each returns `{ output }` (merged into run.output) or `{ output, wait: true }`
// when the stage's completion arrives later (production).
-const llmOf = (run) => ({ providerId: run.brief.llm?.providerId, model: run.brief.llm?.model || undefined });
+/**
+ * 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.
+ */
+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) => {
+ console.warn(`⚠️ Autonomous music video: LLM route resolution failed: ${err.message}`);
+ return null;
+ });
+ const route = resolved?.route;
+ if (!route) return { ...pin, route: null };
+ return { providerId: route.providerId, model: route.model || undefined, effort: route.effort || undefined, route };
+}
/**
* The local song source: the track is created first (its id is stored at once),
@@ -159,20 +175,22 @@ async function localSong({ project, run, save }) {
const STAGES = {
async brief({ project, run }) {
+ const { route, ...llm } = await llmOf(run);
const { brief } = await deps.draftCreativeBrief({
- prompt: run.brief.prompt, guidance: run.brief.guidance, instrumental: run.brief.instrumental, ...llmOf(run),
+ 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) });
- return { output: brief };
+ return { output: { ...brief, ...(route ? { briefRoute: route } : {}) } };
},
async lyrics({ run }) {
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, ...llmOf(run),
+ description: run.output.musicalDescription, guidance: run.brief.guidance || undefined, ...llm,
});
- return { output: { lyrics } };
+ return { output: { lyrics, ...(route ? { lyricsRoute: route } : {}) } };
},
async style({ project, run }) {
@@ -239,8 +257,10 @@ const STAGES = {
const medium = autonomousMedium(run.brief.tools);
if (medium === 'code') {
await deps.updateProject(project.id, { composition: { mode: 'code' } });
- const authoring = run.brief.authoring || (run.brief.llm ? { providerId: run.brief.llm.providerId, model: run.brief.llm.model } : {});
- await deps.generateCode(project.id, { providerId: authoring.providerId, model: authoring.model || undefined });
+ const authoring = run.brief.authoring || (run.brief.llm ? { providerId: run.brief.llm.providerId, model: run.brief.llm.model, effort: run.brief.llm.effort } : {});
+ await deps.generateCode(project.id, {
+ providerId: authoring.providerId, model: authoring.model || undefined, ...(authoring.effort ? { effort: authoring.effort } : {}),
+ });
const render = await deps.renderVideo(project.id);
return { output: { renderJobId: render?.jobId || null } };
}
@@ -341,6 +361,8 @@ 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).
+ ...(brief.llm ? { llm: brief.llm } : {}),
},
});
const run = {
diff --git a/server/services/musicVideo/autonomousService.test.js b/server/services/musicVideo/autonomousService.test.js
index cf316e018a..676cb699ea 100644
--- a/server/services/musicVideo/autonomousService.test.js
+++ b/server/services/musicVideo/autonomousService.test.js
@@ -54,6 +54,8 @@ beforeEach(() => {
store.set(id, clone(next));
return next;
}),
+ // Registry doubles: no provider configured → llmOf falls back to the run's own pin.
+ resolveLlm: vi.fn(async () => ({ provider: null, selectedModel: null, route: null })),
draftCreativeBrief: stub('brief', async () => ({ brief: BRIEF })),
writeLyrics: stub('lyrics', async () => ({ lyrics: '[verse]\nrain on glass' })),
createMoodBoard: stub('board', async () => ({ id: 'board-1' })),
@@ -130,6 +132,34 @@ describe('startAutonomousVideo', () => {
await settled('completed');
});
+ it('resolves the direction LLM once per text stage: brief and lyrics run on the resolved TUI route, effort included, and the route is recorded (#9545)', async () => {
+ const route = { providerId: 'claude-tui', model: 'opus', effort: 'high', transport: 'tui', source: 'tui-preferred' };
+ doubles.resolveLlm.mockResolvedValue({ provider: { id: 'claude-tui' }, selectedModel: 'opus', route });
+ const { project } = await service.startAutonomousVideo({ prompt: 'p', providerId: 'cloud', model: 'big', effort: 'low' });
+ 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' });
+ 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('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' });
+ await vi.waitFor(() => expect(calls).toContain('production'));
+ expect(doubles.draftCreativeBrief).toHaveBeenCalledWith(expect.objectContaining({ providerId: 'cloud', model: 'big' }));
+ expect(runOf().output.briefRoute).toBeUndefined();
+ });
+
+ it('threads the authoring effort into code generation for a code-only brief', async () => {
+ await service.startAutonomousVideo({ prompt: 'p', tools: ['code:render'], authoring: { providerId: 'prov', model: 'm', effort: 'medium' } });
+ await vi.waitFor(() => expect(calls).toContain('render'));
+ expect(doubles.generateCode).toHaveBeenCalledWith('mv-auto', { providerId: 'prov', model: 'm', effort: 'medium' });
+ });
+
it('sends the Cast & Sets check-in to review only when the cast checkpoint is chosen', async () => {
const { project } = await service.startAutonomousVideo({ prompt: 'p', checkpoints: ['cast'] });
expect(project.automation.checkins.castAndSets).toBe('review');
diff --git a/server/services/musicVideo/castAndSetsService.js b/server/services/musicVideo/castAndSetsService.js
index 35653bf367..1ea9862045 100644
--- a/server/services/musicVideo/castAndSetsService.js
+++ b/server/services/musicVideo/castAndSetsService.js
@@ -36,6 +36,7 @@ import { RENDER_TARGET } from '../../lib/renderTargets.js';
import { trimTo } from '../../lib/textUtils.js';
import { getProject, mutateProjectRecord } from './projects.js';
import { musicVideoEvents } from './events.js';
+import { effortArg, recordLlmRoute, resolveMusicVideoLlm } from './llmRoute.js';
import {
allCastAndSetsImagesDone,
assertCastAndSetsApprovable,
@@ -80,7 +81,7 @@ const MAX_SUBMITTED_REFERENCES = 16;
// Test seam: provider, queue, settings and mood-board access are swappable.
const defaults = {
- resolveProvider: async (opts) => (await import('../promptRunner.js')).resolveProviderAndModel(opts),
+ resolveProvider: async (opts) => resolveMusicVideoLlm(opts),
runPrompt: async (opts) => (await import('../promptRunner.js')).runPromptThroughProvider(opts),
getSettings: async () => (await import('../settings.js')).getSettings(),
enqueue: async (job) => (await import('../mediaJobQueue/index.js')).enqueueJob(job),
@@ -161,11 +162,12 @@ async function loadContext(project) {
* plan. `notes` (a revision) are sent with the current direction; `forceKeys`
* are image keys the director flagged directly.
*/
-async function runDirection(projectId, { providerId, model, notes = [], forceKeys = [] } = {}) {
+async function runDirection(projectId, { providerId, model, effort, notes = [], forceKeys = [] } = {}) {
const project = await requireProject(projectId);
const stage = project.castAndSets;
const { board, moodImages, track } = await loadContext(project);
- const { provider, selectedModel } = await deps.resolveProvider({ providerId, model }).catch(() => ({ provider: null }));
+ // 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 }));
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;
@@ -177,10 +179,11 @@ async function runDirection(projectId, { providerId, model, notes = [], forceKey
const prompt = buildCastAndSetsPrompt(project, { moodImages, board, track, previous: notes.length ? previous : null, notes, medium });
let text;
try {
- ({ text } = await deps.runPrompt({ provider, model: selectedModel, prompt, source: 'music-video-cast-sets' }));
+ ({ text } = await deps.runPrompt({ provider, model: selectedModel, ...effortArg(route), prompt, source: 'music-video-cast-sets' }));
} catch (err) {
return fail(projectId, 'The creative direction call failed', err.message);
}
+ await recordLlmRoute(projectId, 'castAndSets', route);
const parsed = parseCastAndSetsResponse(text);
if (!parsed) return fail(projectId, 'The creative direction answer had no usable JSON');
const sections = songSections(project);
@@ -556,7 +559,7 @@ export async function skipCastAndSets(projectId) {
// ---- director actions ------------------------------------------------------------------
/** Start the check-in (explicit request). The work continues in the background. */
-export async function startCastAndSets(projectId, { providerId, model, productionRunId = null } = {}) {
+export async function startCastAndSets(projectId, { providerId, model, effort, productionRunId = null } = {}) {
const project = await requireProject(projectId);
if (!Array.isArray(project.audioAnalysis?.sections) || !project.audioAnalysis.sections.length) {
throw new ServerError('Analyze the song before the Cast & Sets check-in', { status: 409, code: 'NOT_ANALYZED' });
@@ -564,7 +567,7 @@ export async function startCastAndSets(projectId, { providerId, model, productio
const out = await mutateProjectRecord(projectId, (current) => startCastAndSetsOnProject(current, { processId: PROCESS_ID, productionRunId }));
console.log(`🎭 Music Video Cast & Sets ${short(projectId)} started (r${out.stage.revision})`);
publish(projectId, out.project);
- inBackground('The creative direction', projectId, () => runDirection(projectId, { providerId, model }));
+ inBackground('The creative direction', projectId, () => runDirection(projectId, { providerId, model, effort }));
return { project: out.project, stage: presentCastAndSets(out.stage, PROCESS_ID) };
}
@@ -575,7 +578,7 @@ export async function startCastAndSets(projectId, { providerId, model, productio
* note revises the direction, and only images whose prompt changed re-render.
* The consumed notes are resolved on the sheet. Returns `{ project, stage }`.
*/
-export async function regenerateCastAndSets(projectId, { notes = null, providerId, model } = {}) {
+export async function regenerateCastAndSets(projectId, { notes = null, providerId, model, effort } = {}) {
const project = await requireProject(projectId);
const stage = project.castAndSets;
if (!stage?.direction) throw new ServerError('There is no Cast & Sets sheet to regenerate yet', { status: 409, code: 'CAST_SETS_NO_DIRECTION' });
@@ -603,18 +606,18 @@ export async function regenerateCastAndSets(projectId, { notes = null, providerI
publish(projectId, out.project);
const forceKeys = Object.keys(imageNotes);
inBackground('The regeneration', projectId, () => (redirect
- ? runDirection(projectId, { providerId, model, notes: directionNotes, forceKeys })
+ ? runDirection(projectId, { providerId, model, effort, notes: directionNotes, forceKeys })
: writePlan(projectId, { forceKeys })));
return { project: out.project, stage: presentCastAndSets(out.stage, PROCESS_ID) };
}
/** Resume an interrupted (restart) or failed stage in this process. */
-export async function resumeCastAndSets(projectId, { providerId, model } = {}) {
+export async function resumeCastAndSets(projectId, { providerId, model, effort } = {}) {
const out = await mutateProjectRecord(projectId, (current) => resumeCastAndSetsOnProject(current, { processId: PROCESS_ID }));
console.log(`▶️ Music Video Cast & Sets ${short(projectId)} resumed (${out.stage.status})`);
publish(projectId, out.project);
inBackground('The resume', projectId, () => {
- if (out.stage.status === 'directing') return runDirection(projectId, { providerId, model, notes: out.stage.notesApplied || [] });
+ if (out.stage.status === 'directing') return runDirection(projectId, { providerId, model, effort, notes: out.stage.notesApplied || [] });
if (out.stage.status === 'assembling') return assemble(projectId);
return advance(projectId);
});
diff --git a/server/services/musicVideo/castAndSetsService.test.js b/server/services/musicVideo/castAndSetsService.test.js
index d3885f558d..b9afcef348 100644
--- a/server/services/musicVideo/castAndSetsService.test.js
+++ b/server/services/musicVideo/castAndSetsService.test.js
@@ -147,17 +147,20 @@ beforeEach(() => {
imageParamsOverrides = {};
vi.clearAllMocks();
runPrompt.mockResolvedValue({ text: `Here you go:\n\`\`\`json\n${JSON.stringify(DIRECTION)}\n\`\`\`` });
- service.__setCastAndSetsDepsForTests({
- resolveProvider: async () => ({ provider: { id: 'example-provider', enabled: true }, selectedModel: 'example-model' }),
- runPrompt,
- getSettings: async () => ({}),
- enqueue,
- imageParams: async (_settings, route, common) => ({ mode: route.mode, ...common, ...imageParamsOverrides }),
- resolveRoute: async () => ({ mode: 'codex', model: null }),
- loadBoard: async () => board,
- boardItemImage: async () => (item) => (item.type === 'image' ? { kind: 'image', filename: item.file } : null),
- loadTrack: async () => null,
- });
+ service.__setCastAndSetsDepsForTests(testDeps());
+});
+
+const testDeps = (overrides = {}) => ({
+ resolveProvider: async () => ({ provider: { id: 'example-provider', enabled: true }, selectedModel: 'example-model' }),
+ runPrompt,
+ getSettings: async () => ({}),
+ enqueue,
+ imageParams: async (_settings, route, common) => ({ mode: route.mode, ...common, ...imageParamsOverrides }),
+ resolveRoute: async () => ({ mode: 'codex', model: null }),
+ loadBoard: async () => board,
+ boardItemImage: async () => (item) => (item.type === 'image' ? { kind: 'image', filename: item.file } : null),
+ loadTrack: async () => null,
+ ...overrides,
});
afterAll(cleanupTempDataRoots);
@@ -350,6 +353,22 @@ describe('Cast & Sets check-in', () => {
});
});
+it('directs on the resolved LLM route: the brief and request pins reach the resolver, effort reaches the run, and the route is recorded (#9545)', async () => {
+ const route = { providerId: 'claude-tui', model: 'opus', effort: 'high', transport: 'tui', source: 'brief' };
+ const resolveProvider = vi.fn(async () => ({ provider: { id: 'claude-tui', enabled: true }, selectedModel: 'opus', route }));
+ service.__setCastAndSetsDepsForTests(testDeps({ resolveProvider }));
+ const llm = { providerId: 'claude-tui', model: 'opus', effort: 'high' };
+ const project = await seed({ automation: { tools: ['image:codex'], llm } });
+
+ const started = await request(app).post(`/api/music-video/${project.id}/cast-and-sets`).send({ effort: 'low' });
+ expect(started.status).toBe(202);
+ await runTo(project.id, 'review');
+
+ expect(resolveProvider).toHaveBeenCalledWith(expect.objectContaining({ effort: 'low', automation: expect.objectContaining({ llm }) }));
+ expect(runPrompt).toHaveBeenCalledWith(expect.objectContaining({ source: 'music-video-cast-sets', model: 'opus', effort: 'high' }));
+ expect((await current(project.id)).automation.routes.castAndSets).toMatchObject({ providerId: 'claude-tui', transport: 'tui', effort: 'high' });
+});
+
it('uses project moodboard style images for Cast & Sets without a linked board', async () => {
const project = await seed({ visualSpec: null, styleReferences: [{ imageId: 'style.png', caption: 'silver grain' }] });
const snapshots = [];
diff --git a/server/services/musicVideo/codeGeneration.js b/server/services/musicVideo/codeGeneration.js
index aeb0b571d9..4eb8fb7698 100644
--- a/server/services/musicVideo/codeGeneration.js
+++ b/server/services/musicVideo/codeGeneration.js
@@ -14,6 +14,8 @@ import { universeStyleLines } from '../../lib/styleSourcePrompt.js';
import { buildMusicVideoCodePrompt, extractCodeSections } from '../codeAnimation/prompt.js';
import { normalizeComposition } from './composition.js';
import { getProject, mutateProjectRecord } from './projects.js';
+import { musicVideoLlmRouteLabel } from '../../lib/musicVideoAutomation.js';
+import { effortArg, resolveMusicVideoLlm } from './llmRoute.js';
import { buildCodeTimeline, buildSongDocument, paletteFromProject } from './codeTimeline.js';
export async function styleLinesFor(project) {
@@ -42,20 +44,26 @@ function acceptSources(parsed, ids) {
return accepted;
}
-export async function runModel({ providerId, model, prompt, source = 'music-video-code', beforeSubmit = null }) {
- const { assertProvider, resolveProviderAndModel, runPromptThroughProvider } = await import('../promptRunner.js');
- const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });
+/**
+ * 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.
+ */
+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 });
assertProvider(provider, { message: 'No AI provider available to write the code video', code: 'PROVIDER_UNAVAILABLE', status: 400 });
- console.log(`🎬 Music-video code generation on ${provider.id}/${selectedModel || 'default'}`);
+ console.log(`🎬 Music-video code generation on ${musicVideoLlmRouteLabel(route)}`);
const { text } = await runPromptThroughProvider({
provider,
model: selectedModel || undefined,
+ ...effortArg(route),
prompt,
source,
cwd: PATHS.data,
...(beforeSubmit ? { allowFallback: false, toolFree: true, beforeExecute: beforeSubmit } : {}),
});
- return { text, providerId: provider.id, model: selectedModel || null };
+ return { text, providerId: provider.id, model: selectedModel || null, route };
}
function storeCodeVideo(project, { providerId, model, sections, timelineIds }) {
@@ -87,7 +95,7 @@ async function writeComposition(projectId, run, sections, timelineIds) {
* Generate every section. Replaces stored functions for the sections the
* model returned; a section it omitted keeps its previous function.
*/
-export async function generateMusicVideoCode(projectId, { providerId, model } = {}) {
+export async function generateMusicVideoCode(projectId, { providerId, model, effort } = {}) {
const project = await getProject(projectId);
if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
const timeline = buildCodeTimeline(project);
@@ -102,7 +110,7 @@ export async function generateMusicVideoCode(projectId, { providerId, model } =
song,
styleLines: await styleLinesFor(project),
});
- const run = await runModel({ providerId, model, prompt });
+ const run = await runModel({ providerId, model, effort, automation: project.automation, prompt });
const parsed = extractCodeSections(run.text);
const sections = acceptSources(parsed, timeline.sections.map((section) => section.id));
if (!sections.length) {
@@ -114,7 +122,7 @@ export async function generateMusicVideoCode(projectId, { providerId, model } =
}
/** Replace one section function. Every other stored function stays. */
-export async function regenerateMusicVideoCodeSection(projectId, sectionId, { providerId, model } = {}) {
+export async function regenerateMusicVideoCodeSection(projectId, sectionId, { providerId, model, effort } = {}) {
const project = await getProject(projectId);
if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
const timeline = buildCodeTimeline(project);
@@ -129,7 +137,7 @@ export async function regenerateMusicVideoCodeSection(projectId, sectionId, { pr
styleLines: await styleLinesFor(project),
onlySectionId: sectionId,
});
- const run = await runModel({ providerId, model, prompt });
+ const run = await runModel({ providerId, model, effort, automation: project.automation, prompt });
const sections = acceptSources(extractCodeSections(run.text), [sectionId]);
if (!sections.length) {
throw new ServerError('The model did not return that section', { status: 422, code: 'NO_SECTION_SOURCE' });
diff --git a/server/services/musicVideo/documentGeneration.js b/server/services/musicVideo/documentGeneration.js
index 9525793122..9ae30581b3 100644
--- a/server/services/musicVideo/documentGeneration.js
+++ b/server/services/musicVideo/documentGeneration.js
@@ -164,7 +164,7 @@ async function priorManifest(project) {
return { pointer, manifest };
}
-async function runAuthoring(projectId, { providerId, model, sectionId = null, eventRevision = false, expectedDraft = null, feedback = '', beforeSubmit = null, verifyCurrent = () => {} } = {}) {
+async function runAuthoring(projectId, { providerId, model, effort, sectionId = null, eventRevision = false, expectedDraft = null, feedback = '', beforeSubmit = null, verifyCurrent = () => {} } = {}) {
const project = await getProject(projectId);
if (!project) throw fail('Project not found', 'NOT_FOUND', 404);
const context = await authoringContext(project);
@@ -194,7 +194,7 @@ async function runAuthoring(projectId, { providerId, model, sectionId = null, ev
onlySectionId: sectionId, sharedStyle,
});
const directedPrompt = feedback ? `${prompt}\n\nReview findings for this section (retain the approved medium and selected assets; never invent a footage fallback):\n${feedback.slice(0, 8000)}` : prompt;
- const run = await runModel({ providerId, model, prompt: directedPrompt, source: 'music-video-document', beforeSubmit });
+ const run = await runModel({ providerId, model, effort, automation: project.automation, prompt: directedPrompt, source: 'music-video-document', beforeSubmit });
const updated = acceptedSections(run.text, ids);
const merged = new Map((prior?.manifest.sections || []).map((section) => [section.id, section.source]));
for (const [id, source] of updated) merged.set(id, source);
diff --git a/server/services/musicVideo/documentGeneration.test.js b/server/services/musicVideo/documentGeneration.test.js
index 71a05538f5..d5f7ecf32c 100644
--- a/server/services/musicVideo/documentGeneration.test.js
+++ b/server/services/musicVideo/documentGeneration.test.js
@@ -3,14 +3,15 @@ import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';
-const h = vi.hoisted(() => ({ calls: 0, prompt: '', response: '', onSubmit: null }));
+const h = vi.hoisted(() => ({ calls: 0, prompt: '', response: '', onSubmit: null, provider: { id: 'stub-provider' }, args: null }));
vi.mock('../../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), {
dataRoot: () => lazyTempDataRoot('portos-mv-document-author-'),
}));
vi.mock('../promptRunner.js', () => ({
assertProvider: () => {},
- resolveProviderAndModel: async () => ({ provider: { id: 'stub-provider' }, selectedModel: 'fixture-model' }),
- runPromptThroughProvider: async ({ prompt, beforeExecute }) => {
+ resolveProviderAndModel: async () => ({ provider: h.provider, selectedModel: 'fixture-model' }),
+ runPromptThroughProvider: async ({ prompt, beforeExecute, ...args }) => {
+ h.args = args;
if (beforeExecute) await beforeExecute({ provider: { id: 'stub-provider' }, model: 'fixture-model' });
h.calls += 1; h.prompt = prompt;
if (h.onSubmit) await h.onSubmit();
@@ -28,7 +29,7 @@ const response = (colors) => JSON.stringify({ sections: Object.entries(colors).m
const manifestAt = async (document) => JSON.parse(await readFile(join(PATHS.data, document.directory, 'manifest.json'), 'utf8'));
afterAll(() => cleanupTempDataRoots());
-beforeEach(() => { h.onSubmit = null; h.calls = 0; h.prompt = ''; h.response = response({ intro: '#112233', still: '#445566', clip: '#778899' }); });
+beforeEach(() => { h.provider = { id: 'stub-provider' }; h.args = null; h.onSubmit = null; h.calls = 0; h.prompt = ''; h.response = response({ intro: '#112233', still: '#445566', clip: '#778899' }); });
async function fixture() {
await mkdir(PATHS.images, { recursive: true });
@@ -64,6 +65,17 @@ async function fixture() {
}
describe('treatment-driven mixed-media document authoring', () => {
+ it('runs authoring on the pinned provider with its effort, and drops effort for a provider that has none (#9545)', async () => {
+ const id = await fixture();
+ h.provider = { id: 'stub-provider', type: 'cli', command: 'claude' };
+ await generateMixedMediaDocument(id, { providerId: 'stub-provider', effort: 'high' });
+ expect(h.args).toMatchObject({ provider: { id: 'stub-provider' }, model: 'fixture-model', effort: 'high', source: 'music-video-document' });
+
+ h.provider = { id: 'stub-provider', type: 'api' };
+ await generateMixedMediaDocument(id, { providerId: 'stub-provider', effort: 'high' });
+ expect(h.args).not.toHaveProperty('effort');
+ });
+
it('accepts a legacy generated manifest and upgrades it through an event-only revision', async () => {
const id = await fixture();
const first = (await generateMixedMediaDocument(id)).document;
diff --git a/server/services/musicVideo/llmRoute.js b/server/services/musicVideo/llmRoute.js
new file mode 100644
index 0000000000..3f315eff9d
--- /dev/null
+++ b/server/services/musicVideo/llmRoute.js
@@ -0,0 +1,138 @@
+/**
+ * Music Video — which LLM runs a text stage (#9545).
+ *
+ * Direction, shot planning, the autonomous brief/lyrics and code authoring all
+ * resolve their provider here, in one fixed order:
+ *
+ * 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
+ * (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
+ * 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.
+ *
+ * Image-reading stages (plate review, auto-review) deliberately do NOT resolve
+ * here: they take an explicit reviewer and already refuse, before dispatch, a
+ * provider that cannot read images (a TUI other than Codex's, a tool-using CLI).
+ * Only text stages prefer a TUI.
+ *
+ * Nothing here calls a provider: it only reads the provider registry.
+ */
+
+import { isTuiProvider } from '../../lib/providerTypes.js';
+import { resolveCliEffort } from '../../lib/providerModels.js';
+import { captureSystemCapabilities, isHardwareCompatible, withProviderHardwareCompatibility } from '../../lib/systemCapabilities.js';
+import { normalizeMusicVideoLlm } from '../../lib/musicVideoAutomation.js';
+
+const transportOf = (provider) => (provider?.type === 'tui' ? 'tui' : provider?.type === 'cli' ? 'cli' : 'api');
+
+async function launchable(provider) {
+ const { buildTuiShellLaunch } = await import('../../lib/tuiShellLaunch.js');
+ return buildTuiShellLaunch(provider) !== null;
+}
+
+/**
+ * The TUI provider an unpinned text stage should use, or null. Never throws: a
+ * registry read failure just means "no preference".
+ */
+export async function preferredTuiProvider() {
+ // Lazy: the provider registry (and its toolkit) is only needed when nothing is pinned.
+ const { getActiveProvider, listProviders } = await import('../providers.js');
+ const providers = await listProviders().catch(() => []);
+ const capabilities = captureSystemCapabilities();
+ const eligible = [];
+ for (const provider of providers) {
+ if (!isTuiProvider(provider) || provider.enabled === false) continue;
+ if (!isHardwareCompatible(withProviderHardwareCompatibility(provider, capabilities).hardwareCompatibility)) continue;
+ if (!(await launchable(provider))) continue;
+ eligible.push(provider);
+ }
+ if (!eligible.length) return null;
+ const active = await getActiveProvider().catch(() => null);
+ return eligible.find((provider) => provider.id === active?.id) || eligible[0];
+}
+
+function describe({ provider, selectedModel, effort, source, requestedProviderId }) {
+ return {
+ providerId: provider.id,
+ model: selectedModel || null,
+ // The level the run will actually use: clamped to the provider's ladder, and
+ // none for a provider with no effort control (every API provider).
+ effort: provider.type === 'api' ? null : resolveCliEffort(effort, provider, selectedModel) || null,
+ transport: transportOf(provider),
+ source,
+ ...(requestedProviderId ? { requestedProviderId } : {}),
+ };
+}
+
+/**
+ * Resolve the provider, model and effort a Music Video stage runs on.
+ *
+ * @param {object} [input]
+ * @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
+ * @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 } = {}) {
+ // 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;
+
+ let requestedProviderId = null;
+ if (pin) {
+ 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 }) };
+ }
+ requestedProviderId = pin.providerId;
+ }
+
+ const tui = await preferredTuiProvider();
+ if (tui) {
+ const { provider, selectedModel } = await resolveProviderAndModel({ providerId: tui.id });
+ if (provider) {
+ return { provider, selectedModel, route: describe({ provider, selectedModel, effort: pin?.effort, source: 'tui-preferred', requestedProviderId }) };
+ }
+ }
+
+ const { provider, selectedModel } = await resolveProviderAndModel({});
+ if (!provider) return { provider: null, selectedModel: null, route: null };
+ return { provider, selectedModel, route: describe({ provider, selectedModel, effort: pin?.effort, source: 'active', requestedProviderId }) };
+}
+
+/** The `effort` argument for a run: only present when the route has one. */
+export const effortArg = (route) => (route?.effort ? { effort: route.effort } : {});
+
+/**
+ * Remember the route a stage ran on in the project's brief so the page can show
+ * it (and a reload still does). Only projects with an automation brief carry
+ * one; best-effort — a failed write never fails the stage it describes.
+ * Returns the persisted project, or null when nothing was written.
+ */
+export async function recordLlmRoute(projectId, stage, route) {
+ if (!route) return null;
+ try {
+ const { mutateProjectRecord } = await import('./projects.js');
+ const at = new Date().toISOString();
+ const written = await mutateProjectRecord(projectId, (current) => (current.automation
+ ? { project: { ...current, automation: { ...current.automation, routes: { ...(current.automation.routes || {}), [stage]: { ...route, at } } } }, written: true }
+ : { project: current, written: false }));
+ return written?.written ? written.project : null;
+ } catch (err) {
+ console.warn(`⚠️ Music Video ${stage}: could not record the LLM route for ${projectId}: ${err.message}`);
+ return null;
+ }
+}
diff --git a/server/services/musicVideo/llmRoute.test.js b/server/services/musicVideo/llmRoute.test.js
new file mode 100644
index 0000000000..50a4999843
--- /dev/null
+++ b/server/services/musicVideo/llmRoute.test.js
@@ -0,0 +1,111 @@
+/**
+ * Which LLM a Music Video text stage runs on (#9545): request pin > the brief's
+ * saved pin > an eligible TUI provider > the active provider. The registry and
+ * the runner's model resolution are doubled; nothing calls a real provider.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const registry = { providers: [], active: null };
+vi.mock('../providers.js', () => ({
+ listProviders: vi.fn(async () => registry.providers),
+ getActiveProvider: vi.fn(async () => registry.active),
+}));
+vi.mock('../promptRunner.js', () => ({
+ // Like the real helper: a known id resolves, anything else falls back to the active provider.
+ resolveProviderAndModel: vi.fn(async ({ providerId, model } = {}) => {
+ const provider = registry.providers.find((p) => p.id === providerId) || registry.active;
+ return { provider, selectedModel: model || provider?.defaultModel || null };
+ }),
+}));
+vi.mock('../../lib/tuiShellLaunch.js', () => ({
+ buildTuiShellLaunch: (provider) => (provider.unlaunchable ? null : { commandLine: provider.command, env: {} }),
+}));
+vi.mock('./projects.js', () => ({ mutateProjectRecord: vi.fn() }));
+
+const { resolveMusicVideoLlm, recordLlmRoute, effortArg } = await import('./llmRoute.js');
+const { mutateProjectRecord } = await import('./projects.js');
+
+const api = (id, extra = {}) => ({ id, type: 'api', enabled: true, defaultModel: 'api-model', ...extra });
+const tui = (id, extra = {}) => ({ id, type: 'tui', enabled: true, command: 'claude', defaultModel: 'tui-model', ...extra });
+
+beforeEach(() => {
+ registry.providers = [];
+ registry.active = null;
+ vi.clearAllMocks();
+});
+
+describe('resolveMusicVideoLlm', () => {
+ it('prefers an eligible TUI over the active API provider when nothing is pinned, and the active TUI over the first', async () => {
+ registry.providers = [api('cloud'), tui('first-tui'), tui('active-tui')];
+ registry.active = registry.providers[0];
+ expect((await resolveMusicVideoLlm()).route).toMatchObject({ providerId: 'first-tui', transport: 'tui', source: 'tui-preferred' });
+
+ registry.active = registry.providers[2];
+ expect((await resolveMusicVideoLlm()).route.providerId).toBe('active-tui');
+ });
+
+ it('skips a TUI that is disabled, cannot run on this hardware, or cannot be launched, then uses the active provider', async () => {
+ registry.providers = [
+ tui('off', { enabled: false }),
+ tui('wrong-os', { hardwareRequirements: { platforms: ['plan9'] } }),
+ tui('stub', { unlaunchable: true }),
+ api('cloud'),
+ ];
+ registry.active = registry.providers[3];
+ const { provider, route } = await resolveMusicVideoLlm();
+ expect(provider.id).toBe('cloud');
+ expect(route).toMatchObject({ providerId: 'cloud', transport: 'api', source: 'active', effort: null });
+ });
+
+ it('keeps a request pin authoritative — an API pin is not replaced by an available TUI', async () => {
+ registry.providers = [tui('tui-1'), api('cloud')];
+ registry.active = registry.providers[0];
+ const { provider, selectedModel, route } = await resolveMusicVideoLlm({ providerId: 'cloud', model: 'big', effort: 'high' });
+ expect([provider.id, selectedModel]).toEqual(['cloud', 'big']);
+ // API providers have no effort control, so the effective effort is none.
+ expect(route).toMatchObject({ source: 'pinned', transport: 'api', effort: null });
+ });
+
+ it('applies the brief pin when the request pins nothing, with effort clamped to the provider ladder', async () => {
+ registry.providers = [api('cloud'), tui('tui-1')];
+ registry.active = registry.providers[0];
+ const automation = { llm: { providerId: 'tui-1', model: 'opus', effort: 'ultra' } };
+ const { route } = await resolveMusicVideoLlm({ automation });
+ // `ultra` is not on the Claude ladder: it runs at the nearest level below.
+ expect(route).toEqual({ providerId: 'tui-1', model: 'opus', effort: 'max', transport: 'tui', source: 'brief' });
+ expect(effortArg(route)).toEqual({ effort: 'max' });
+
+ // A request pin beats the saved brief pin.
+ expect((await resolveMusicVideoLlm({ automation, providerId: 'cloud' })).route).toMatchObject({ providerId: 'cloud', source: 'pinned' });
+ });
+
+ it('reports the pin it replaced when the saved provider no longer exists', async () => {
+ registry.providers = [api('cloud'), tui('tui-1')];
+ registry.active = registry.providers[0];
+ const { route } = await resolveMusicVideoLlm({ automation: { llm: { providerId: 'deleted-provider' } } });
+ expect(route).toMatchObject({ providerId: 'tui-1', source: 'tui-preferred', requestedProviderId: 'deleted-provider' });
+ });
+
+ it('survives a registry with no providers at all', async () => {
+ expect(await resolveMusicVideoLlm()).toEqual({ provider: null, selectedModel: null, route: null });
+ });
+});
+
+describe('recordLlmRoute', () => {
+ const route = { providerId: 'tui-1', model: 'opus', effort: 'high', transport: 'tui', source: 'tui-preferred' };
+
+ it('stores the route on a project that has an automation brief, keeping the other stage', async () => {
+ mutateProjectRecord.mockImplementation(async (_id, transform) => transform({ automation: { tools: [], routes: { plan: { providerId: 'p' } } } }));
+ const project = await recordLlmRoute('mv-1', 'castAndSets', route);
+ expect(project.automation.routes.plan).toEqual({ providerId: 'p' });
+ expect(project.automation.routes.castAndSets).toMatchObject(route);
+ });
+
+ it('writes nothing for a manual project, and a failed write never fails the stage', async () => {
+ mutateProjectRecord.mockImplementationOnce(async (_id, transform) => transform({ name: 'manual' }));
+ expect(await recordLlmRoute('mv-1', 'plan', route)).toBeNull();
+ mutateProjectRecord.mockRejectedValueOnce(new Error('db down'));
+ expect(await recordLlmRoute('mv-1', 'plan', route)).toBeNull();
+ });
+});
diff --git a/server/services/musicVideo/planner.js b/server/services/musicVideo/planner.js
index 19a3823884..35067f337a 100644
--- a/server/services/musicVideo/planner.js
+++ b/server/services/musicVideo/planner.js
@@ -40,7 +40,8 @@ import { musicVideoCreativeContext, musicVideoDirectionContext } from '../../lib
import { ServerError } from '../../lib/errorHandler.js';
import { extractJson } from '../../lib/jsonExtract.js';
-import { resolveProviderAndModel, runPromptThroughProvider } from '../promptRunner.js';
+import { runPromptThroughProvider } from '../promptRunner.js';
+import { effortArg, recordLlmRoute, resolveMusicVideoLlm } from './llmRoute.js';
import { directShots, planShots, resolveClipCapacitySec, validSections } from './shotPlan.js';
import { getProject, addProjectScenes, mutateProjectRecord } from './projects.js';
@@ -223,14 +224,15 @@ function parseScenePlanResponse(text, count) {
* provider disabled, LLM call failed, response didn't parse) so the caller
* can fall back to plain scenes without the whole plan request failing.
*/
-async function tryProposeScenePrompts(project, shots, { providerId, model } = {}) {
+async function tryProposeScenePrompts(project, shots, { providerId, model, effort } = {}) {
if (shots.length > MAX_SHOTS_FOR_PROMPTS) {
return { seeded: null, reason: 'too-many-shots' };
}
- const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model }).catch((err) => {
+ // 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) => {
console.warn(`⚠️ Music Video plan: provider resolution failed for ${project.id}: ${err.message}`);
- return { provider: null, selectedModel: null };
+ return { provider: null, selectedModel: null, route: null };
});
if (!provider) return { seeded: null, reason: 'no-provider' };
if (provider.enabled === false) return { seeded: null, reason: 'provider-disabled' };
@@ -240,20 +242,21 @@ async function tryProposeScenePrompts(project, shots, { providerId, model } = {}
({ text } = await runPromptThroughProvider({
provider,
model: selectedModel,
+ ...effortArg(route),
prompt: buildScenePlanPrompt(project, shots),
source: 'music-video-plan',
}));
} catch (err) {
console.warn(`⚠️ Music Video plan: scene-prompt LLM call failed for ${project.id}: ${err.message}`);
- return { seeded: null, reason: 'llm-failed' };
+ return { seeded: null, reason: 'llm-failed', route };
}
const seeded = parseScenePlanResponse(text, shots.length);
if (!seeded) {
console.warn(`⚠️ Music Video plan: unparsable scene-prompt response for ${project.id}`);
- return { seeded: null, reason: 'unparsable-response' };
+ return { seeded: null, reason: 'unparsable-response', route };
}
- return { seeded, reason: null };
+ return { seeded, reason: null, route };
}
/**
@@ -266,11 +269,16 @@ async function tryProposeScenePrompts(project, shots, { providerId, model } = {}
* @param {string} [options.providerId] — pin a specific provider instead of
* the active one.
* @param {string} [options.model] — model override for the prompt-seeding call.
+ * @param {string} [options.effort] — reasoning-effort override for an
+ * effort-capable CLI/TUI provider (clamped by the runner).
* @param {string} [options.directive] — a production run's directive (#9066),
* added to the director guidance the first-pass prompts are written under.
- * @returns {Promise<{ project: object, scenesAdded: number, promptsSeeded: boolean, promptsSkippedReason: string|null, pacing: object }>}
+ * @returns {Promise<{ project: object, scenesAdded: number, promptsSeeded: boolean, promptsSkippedReason: string|null, pacing: object, llmRoute: object|null }>}
+ * `llmRoute` is the effective provider/model/effort/transport the prompt call
+ * used (null when none was made); a project with an automation brief also
+ * keeps it under `automation.routes.plan`.
*/
-export async function planProject(id, { seedPrompts = true, providerId, model, directive } = {}) {
+export async function planProject(id, { seedPrompts = true, providerId, model, effort, directive } = {}) {
const project = await getProject(id);
if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
@@ -297,10 +305,12 @@ export async function planProject(id, { seedPrompts = true, providerId, model, d
let promptsSeeded = false;
let promptsSkippedReason = seedPrompts ? null : 'not-requested';
+ let llmRoute = null;
if (seedPrompts) {
const guidance = [project.automation?.guidance?.trim(), directive?.trim()].filter(Boolean).join('\n');
const planning = directive?.trim() ? { ...project, automation: { ...project.automation, guidance } } : project;
- const { seeded, reason } = await tryProposeScenePrompts(planning, shots, { providerId, model });
+ const { seeded, reason, route } = await tryProposeScenePrompts(planning, shots, { providerId, model, effort });
+ llmRoute = route || null;
if (seeded) {
promptsSeeded = true;
for (const [idx, fields] of seeded) {
@@ -326,11 +336,13 @@ export async function planProject(id, { seedPrompts = true, providerId, model, d
const hasCards = sceneInputs.some((s) => s.visualLayer === 'card');
// Persist card scenes and the mode that renders them in the same transaction.
// Read the current composition under the lock so concurrent edits survive.
- const { project: updated, scenes } = hasCards
+ const { project: persisted, scenes } = hasCards
? await persistCardPlan(id, sceneInputs)
: await addProjectScenes(id, sceneInputs);
+ // Only a project with an automation brief keeps the route it planned on.
+ const updated = (persisted.automation && await recordLlmRoute(id, 'plan', llmRoute)) || persisted;
console.log(`🪄 Music Video plan: seeded ${scenes.length} scene${scenes.length === 1 ? '' : 's'} for ${id} (prompts ${promptsSeeded ? 'seeded' : `skipped: ${promptsSkippedReason || 'n/a'}`})`);
- return { project: updated, scenesAdded: scenes.length, promptsSeeded, promptsSkippedReason, pacing };
+ return { project: updated, scenesAdded: scenes.length, promptsSeeded, promptsSkippedReason, pacing, llmRoute };
}
async function persistCardPlan(id, sceneInputs) {
diff --git a/server/services/musicVideo/planner.test.js b/server/services/musicVideo/planner.test.js
index ec0fb4ef3d..ee30598cb0 100644
--- a/server/services/musicVideo/planner.test.js
+++ b/server/services/musicVideo/planner.test.js
@@ -417,6 +417,37 @@ Here is my answer:
expect(result.promptsSkippedReason).toBe('unparsable-response');
});
+ it('runs the saved brief LLM pin with its effort and records the effective route on the brief (#9545)', async () => {
+ const automation = { tools: [], guidance: '', budgetUsd: null, llm: { providerId: 'claude-tui', model: 'opus', effort: 'high' } };
+ getProject.mockResolvedValue(makeProject({ automation }));
+ addProjectScenes.mockResolvedValue(freshProjectResult({ automation }));
+ resolveProviderAndModel.mockResolvedValue({ provider: { id: 'claude-tui', type: 'tui', command: 'claude' }, selectedModel: 'opus' });
+ runPromptThroughProvider.mockResolvedValue({ text: '[]' });
+ mutateProjectRecord.mockImplementation(async (_id, transform) => transform({ automation }));
+
+ const result = await planProject('mv-1');
+
+ expect(resolveProviderAndModel).toHaveBeenCalledWith({ providerId: 'claude-tui', model: 'opus' });
+ expect(runPromptThroughProvider).toHaveBeenCalledWith(expect.objectContaining({
+ provider: expect.objectContaining({ id: 'claude-tui' }), model: 'opus', effort: 'high', source: 'music-video-plan',
+ }));
+ expect(result.llmRoute).toMatchObject({ providerId: 'claude-tui', model: 'opus', effort: 'high', transport: 'tui', source: 'brief' });
+ expect(result.project.automation.routes.plan).toMatchObject({ providerId: 'claude-tui', transport: 'tui', effort: 'high' });
+ });
+
+ it('lets a request pin outrank the brief pin, and sends no effort to an API provider', async () => {
+ const automation = { tools: [], guidance: '', budgetUsd: null, llm: { providerId: 'claude-tui', effort: 'high' } };
+ getProject.mockResolvedValue(makeProject({ automation }));
+ addProjectScenes.mockResolvedValue(freshProjectResult());
+ resolveProviderAndModel.mockResolvedValue({ provider: { id: 'cloud', type: 'api' }, selectedModel: 'gpt' });
+ runPromptThroughProvider.mockResolvedValue({ text: '[]' });
+
+ const result = await planProject('mv-1', { providerId: 'cloud', model: 'gpt', effort: 'low' });
+
+ expect(runPromptThroughProvider.mock.calls[0][0]).not.toHaveProperty('effort');
+ expect(result.llmRoute).toMatchObject({ providerId: 'cloud', transport: 'api', source: 'pinned', effort: null });
+ });
+
it('skips prompt-seeding when the resolved provider is disabled', async () => {
getProject.mockResolvedValue(makeProject());
addProjectScenes.mockResolvedValue(freshProjectResult());
diff --git a/server/services/musicVideo/productionService.js b/server/services/musicVideo/productionService.js
index fd223916b0..c8bfcac273 100644
--- a/server/services/musicVideo/productionService.js
+++ b/server/services/musicVideo/productionService.js
@@ -105,7 +105,7 @@ const defaults = {
const { provider, selectedModel } = await resolveProviderAndModel(input);
if (!provider || provider.id !== input?.providerId || provider.enabled === false || !selectedModel || selectedModel !== input?.model) throw new ServerError('The selected code-authoring provider/model is unavailable', { status: 409, code: 'PRODUCTION_AUTHORING_UNAVAILABLE' });
if (!isToolFreeOneShotProvider(provider)) throw new ServerError('Choose an API or a tool-free headless CLI for code authoring', { status: 422, code: 'PRODUCTION_AUTHORING_UNAVAILABLE' });
- return { providerId: provider.id, model: selectedModel, costUsd: isFreeProvider(provider) ? 0 : null };
+ return { providerId: provider.id, model: selectedModel, ...(input.effort ? { effort: input.effort } : {}), costUsd: isFreeProvider(provider) ? 0 : null };
},
releaseRevisionSection: async (...args) => (await import('./revisionService.js')).releaseRevisionSection(...args),
};
@@ -428,10 +428,13 @@ async function takeSteps(projectId, runId) {
if (step.type === 'cast-and-sets') {
// 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;
const started = await deps.startCastAndSets(projectId, {
productionRunId: runId,
- ...(run.reviewer?.providerId ? { providerId: run.reviewer.providerId } : {}),
- ...(run.reviewer?.model ? { model: run.reviewer.model } : {}),
+ ...(reviewerPin ? { providerId: run.reviewer.providerId } : {}),
+ ...(reviewerPin && run.reviewer?.model ? { model: run.reviewer.model } : {}),
}).catch((err) => ({ error: err }));
if (started.error) {
const out = await halt(projectId, runId, { status: 'blocked', reason: `The Cast & Sets check-in could not start: ${started.error.message}` });
diff --git a/server/services/musicVideo/projectsLogic.test.js b/server/services/musicVideo/projectsLogic.test.js
index bd355e3924..55bf005823 100644
--- a/server/services/musicVideo/projectsLogic.test.js
+++ b/server/services/musicVideo/projectsLogic.test.js
@@ -331,6 +331,29 @@ describe('applyProjectPatch', () => {
expect(applyProjectPatch(edited, { automation: null }).automation).toBeNull();
});
+ it('keeps the brief LLM pin through other edits, clears it with null, never takes a patch-written route, and loads a pre-#9545 record unchanged', () => {
+ const llm = { providerId: 'claude-tui', model: 'opus', effort: 'high' };
+ const created = buildProjectRecord({ name: 'Auto', mode: 'autonomous', automation: { tools: ['image:codex'], llm } }, { id: 'mv-a', now: 'n' });
+ expect(created.automation.llm).toEqual(llm);
+
+ // Another sub-field edit keeps it; a route a patch tries to smuggle in is dropped.
+ const edited = applyProjectPatch(created, { automation: { guidance: 'darker', routes: { plan: { providerId: 'forged' } } } });
+ expect(edited.automation.llm).toEqual(llm);
+ expect(edited.automation.routes).toBeUndefined();
+
+ // The server-written route survives later brief edits.
+ const withRoute = { ...edited, automation: { ...edited.automation, routes: { plan: { providerId: 'claude-tui', transport: 'tui', source: 'brief' } } } };
+ expect(applyProjectPatch(withRoute, { automation: { budgetUsd: 3 } }).automation.routes.plan).toMatchObject({ providerId: 'claude-tui', transport: 'tui' });
+
+ // null returns to Auto; a model/effort without a provider is dropped.
+ expect('llm' in applyProjectPatch(edited, { automation: { llm: null } }).automation).toBe(false);
+ expect('llm' in applyProjectPatch(edited, { automation: { llm: { model: 'orphan', effort: 'high' } } }).automation).toBe(false);
+
+ // A record saved before the pin existed carries neither field.
+ const legacy = applyProjectPatch({ ...created, automation: { tools: ['image:codex'], guidance: 'g', budgetUsd: null, checkins: { castAndSets: 'review' } } }, { automation: { guidance: 'h' } });
+ expect(legacy.automation).toEqual({ tools: ['image:codex'], guidance: 'h', budgetUsd: null, checkins: { castAndSets: 'review' } });
+ });
+
it('persists explicit renderer settings and merges later partial changes', () => {
const project = buildProjectRecord({
name: 'A',
diff --git a/server/services/scheduledHandlers/musicVideoAutopilot.js b/server/services/scheduledHandlers/musicVideoAutopilot.js
index dab33a7e3f..3df0d237a3 100644
--- a/server/services/scheduledHandlers/musicVideoAutopilot.js
+++ b/server/services/scheduledHandlers/musicVideoAutopilot.js
@@ -60,9 +60,10 @@ export async function run({ params } = {}) {
const { project } = await startAutonomousVideo({
...runSettings,
// The LLM pin is stored as `llm` on the normalized settings; the start
- // request takes it as providerId/model.
+ // request takes it as providerId/model/effort.
providerId: settings.llm?.providerId,
model: settings.llm?.model || undefined,
+ effort: settings.llm?.effort || undefined,
prompt: ideaToPrompt(idea),
origin: { kind: 'schedule', ideaId: idea.id, ideaTitle: idea.title },
});