Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add AI describe + lyrics endpoints behind the music designer (#4305)
[._.]/ Adam Eivy03207d569723
diff --git a/client/src/components/music/QuickMusicGenerator.jsx b/client/src/components/music/QuickMusicGenerator.jsxdeleted file mode 100644index 7d5a5cc4ca..0000000000--- a/client/src/components/music/QuickMusicGenerator.jsx+++ /dev/null@@ -1,60 +0,0 @@-import { useState } from 'react';-import { useNavigate } from 'react-router';-import MusicGenPanel from './MusicGenPanel';--export default function QuickMusicGenerator() {- const navigate = useNavigate();- const [title, setTitle] = useState('');- const [prompt, setPrompt] = useState('');- const [lyrics, setLyrics] = useState('');-- return (- <section className="max-w-4xl space-y-4">- <div>- <h2 className="text-lg font-semibold text-white">Generate a tune</h2>- <p className="text-sm text-gray-400">Start with an idea. Artist and album are optional and can be added later.</p>- </div>- <label htmlFor="quick-music-title" className="block">- <span className="mb-1 block text-xs uppercase tracking-wider text-gray-500">Title (optional)</span>- <input- id="quick-music-title"- value={title}- onChange={(event) => setTitle(event.target.value)}- maxLength={200}- placeholder="Derived from the prompt if left blank"- className="w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white"- />- </label>- <label htmlFor="quick-music-prompt" className="block">- <span className="mb-1 block text-xs uppercase tracking-wider text-gray-500">Music description</span>- <textarea- id="quick-music-prompt"- value={prompt}- onChange={(event) => setPrompt(event.target.value)}- rows={3}- maxLength={8000}- placeholder="Warm instrumental soul, relaxed pocket, Rhodes piano, 92 BPM…"- className="w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white"- />- </label>- <label htmlFor="quick-music-lyrics" className="block">- <span className="mb-1 block text-xs uppercase tracking-wider text-gray-500">Lyrics (optional)</span>- <textarea- id="quick-music-lyrics"- value={lyrics}- onChange={(event) => setLyrics(event.target.value)}- rows={6}- maxLength={20000}- placeholder={'[verse]\n…\n[chorus]\n…'}- className="w-full rounded border border-port-border bg-port-bg px-3 py-2 font-mono text-sm text-white"- />- </label>- <MusicGenPanel- title={title}- prompt={prompt}- lyrics={lyrics}- onGenerated={(track) => navigate(`/music/tracks/${encodeURIComponent(track.id)}`)}- />- </section>- );-}diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex a943f9131e..e8e3d96b13 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -53,6 +53,7 @@ export const NAV_COMMANDS = [{ id: 'nav.create.rounds', path: '/rounds', label: 'Rounds', section: 'Create', aliases: ['rounds', 'round', 'songs', 'song', 'a-cappella', 'acappella', 'sing'], keywords: ['round', 'song', 'lyrics', 'melody', 'harmony', 'dirge', 'ballad', 'a cappella', 'vocal', 'choir', 'singing', 'arrangement', 'quodlibet', '500 miles'] },{ id: 'nav.create.rounds-guide', path: '/rounds/guide', label: 'Rounds Guide', section: 'Create', aliases: ['rounds-guide', 'round-guide', 'songs-guide', 'song-guide', 'singing-guide', 'round-learning'], keywords: ['rhythm shapes', 'dirge', 'voice layers', 'harmony', 'notation', 'lead sheet', 'solfege', 'learn round', 'learn song', 'a cappella', 'singing help'] },{ id: 'nav.create.music', path: '/music', label: 'Music', section: 'Create', aliases: ['music', 'music-studio', 'generate-music'], keywords: ['music generation', 'ace-step', 'acestep', 'musicgen', 'audioldm', 'album', 'track', 'single', 'album art', 'artist', 'song generation', 'audio', 'beat', 'producer'] },+ { id: 'nav.create.music-generate', path: '/music/generate', label: 'Music Designer', section: 'Create', aliases: ['music-generate', 'music-designer', 'design-music', 'write-a-song', 'make-music'], keywords: ['generate music', 'music designer', 'describe music', 'enrich prompt', 'write lyrics', 'lyrics', 'ace-step', 'reference track', 'vibe', 'step by step', 'wizard'] },{ id: 'nav.create.music-artists', path: '/music/artists', label: 'Music Artists', section: 'Create', aliases: ['music-artists', 'artists', 'artist', 'artist-persona', 'musician', 'band'], keywords: ['artist persona', 'musician', 'band', 'byline', 'portrait', 'genre', 'musical style', 'stage name'] },{ id: 'nav.create.music-albums', path: '/music/albums', label: 'Music Albums', section: 'Create', aliases: ['albums', 'album', 'music-albums', 'discography', 'lp', 'ep'], keywords: ['album', 'cover art', 'tracklist', 'release', 'discography', 'record'] },{ id: 'nav.create.music-tracks', path: '/music/tracks', label: 'Music Tracks', section: 'Create', aliases: ['tracks', 'track', 'music-tracks', 'singles', 'songs-audio'], keywords: ['track', 'single', 'audio', 'recording', 'lyrics', 'mp3', 'wav', 'generate track'] },diff --git a/server/lib/validation.js b/server/lib/validation.jsindex d0341e0702..0d71fb1045 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -681,13 +681,23 @@ export const autofixerSettingsSchema = featureProviderConfigSchema.extend({// Music settings slice (#2911). `chiptune` remembers the Track editor's last// chiptune generation provider/model pin plus the publish preferences (target-// managed app + subdir inside its repo). Reuses the shared feature-provider-// shape so an empty-string picker value normalizes to unset.+// managed app + subdir inside its repo). `designer` (#4305) is the Generate+// tab's stepped music designer: its provider/model/effort pin plus optional+// meta-prompt overrides for the describe + lyrics steps (a blank override falls+// back to the shipped default server-side, in services/musicDesigner.js).+// Reuses the shared feature-provider shape so an empty-string picker value+// normalizes to unset. Every key stays optional so an older client PUTting only+// `{ chiptune }` — or only `{ designer }` — still validates.export const musicSettingsSchema = z.object({chiptune: featureProviderConfigSchema.extend({publishAppId: z.preprocess(emptyToUndefined, z.string().max(120).optional()),publishSubdir: z.preprocess(emptyToUndefined, z.string().max(200).optional()),}).partial().optional(),+ designer: featureProviderConfigSchema.extend({+ effort: z.preprocess(emptyToUndefined, z.string().max(64).optional()),+ describeTemplate: z.preprocess(emptyToUndefined, z.string().max(8000).optional()),+ lyricsTemplate: z.preprocess(emptyToUndefined, z.string().max(8000).optional()),+ }).partial().optional(),});// Creative Director settings slice. Each LLM-backed stage can pin its owndiff --git a/server/routes/music.js b/server/routes/music.jsindex 49e350639e..82548fe322 100644--- a/server/routes/music.js+++ b/server/routes/music.js@@ -2,8 +2,15 @@* Music generation routes (the Music studio's on-device generator surface).** GET /api/music/engines → { engines, defaultEngine }+ * POST /api/music/describe → { description, llm }+ * POST /api/music/lyrics → { lyrics, llm }* POST /api/music/generate → { track, filename, durationSec, engine, modelId }*+ * `describe`/`lyrics` are the Generate tab's stepped designer (#4305): an LLM+ * expands a short reference/vibe into a rich conditioning prompt, then writes+ * lyrics from it. Both are one-shot, user-triggered calls — the studio never+ * fires them on its own (AI Provider Usage Policy).+ ** Generation runs the engine-agnostic `generateMusic` (server/services/pipeline/* musicGen.js) — MusicGen / AudioLDM2 / ACE-Step behind one contract — lands the* WAV in the shared music library (data/music/), then creates a new Track (or@@ -28,6 +35,7 @@ import {enginePlatformLabel, generateMusic,} from '../services/pipeline/musicGen.js';import { listEngineModels, addAudioModel, removeAudioModel, isValidRepoId } from '../services/audioModels.js';+import { describeMusic, writeLyrics } from '../services/musicDesigner.js';import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';import { createInstallLogger } from '../lib/installLogger.js';import { inspectModelCache } from '../lib/hfCache.js';@@ -279,6 +287,70 @@ router.delete('/models/:engine/*id', asyncHandler(async (req, res) => {res.json({ removed });}));+// --- Stepped designer (#4305) ----------------------------------------------+// Empty/whitespace picker values normalize to undefined so a blank <select>+// means "use the install's active provider / the provider's default model"+// instead of reaching the runner as a whitespace string (same preprocessing as+// `refinePromptSchema` in routes/mediaJobs.js).+const blankToUndefined = (s) => {+ const v = (s ?? '').trim();+ return v.length > 0 ? v : undefined;+};+// Shared picker + meta-prompt-override fields for both designer routes. The+// template cap matches the description cap — an override is an instruction+// block, not a document.+const designerPickerShape = {+ guidance: z.string().trim().max(4000).optional(),+ template: z.string().trim().max(8000).optional(),+ providerId: z.string().max(128).optional().transform(blankToUndefined),+ model: z.string().max(256).optional().transform(blankToUndefined),+ effort: z.string().max(64).optional().transform(blankToUndefined),+};++// Caps mirror the Generate form's own limits: a concept/description feeds the+// prompt field (≤8000), lyrics feed the lyrics field (≤20000).+const describeSchema = z.object({+ concept: z.string().trim().min(1, 'concept is required').max(8000),+ ...designerPickerShape,+});++const lyricsSchema = z.object({+ description: z.string().trim().min(1, 'description is required').max(8000),+ ...designerPickerShape,+});++// POST /api/music/describe — expand a short reference/vibe into a rich musical+// description the audio engine can condition on. One explicit user action per+// call; nothing here runs unprompted.+router.post('/describe', asyncHandler(async (req, res) => {+ const body = validateRequest(describeSchema, req.body ?? {});+ const { description, llm } = await describeMusic({+ concept: body.concept,+ guidance: body.guidance,+ template: body.template,+ providerId: body.providerId,+ model: body.model,+ effort: body.effort,+ });+ res.json({ description, llm });+}));++// POST /api/music/lyrics — write original lyrics from that description plus the+// user's extra guidance, in the `[verse]`/`[chorus]` syntax the lyric-aware+// engines expect.+router.post('/lyrics', asyncHandler(async (req, res) => {+ const body = validateRequest(lyricsSchema, req.body ?? {});+ const { lyrics, llm } = await writeLyrics({+ description: body.description,+ guidance: body.guidance,+ template: body.template,+ providerId: body.providerId,+ model: body.model,+ effort: body.effort,+ });+ res.json({ lyrics, llm });+}));+const generateSchema = z.object({prompt: z.string().trim().min(1, 'prompt is required').max(8000),// No default: distinguish ABSENT (don't touch the track's lyrics) from adiff --git a/server/routes/music.test.js b/server/routes/music.test.jsindex f22a060d13..68ff6f3ce6 100644--- a/server/routes/music.test.js+++ b/server/routes/music.test.js@@ -110,8 +110,16 @@ vi.mock('../services/albums/index.js', () => ({updateAlbum: vi.fn(async (id, patch) => ({ id, ...patch })),}));+// The stepped designer's two LLM steps (#4305) — stubbed so the route tests pin+// validation + the exact service call args, not a provider round trip.+vi.mock('../services/musicDesigner.js', () => ({+ describeMusic: vi.fn(),+ writeLyrics: vi.fn(),+}));+import * as tracks from '../services/tracks/index.js';import * as albums from '../services/albums/index.js';+import * as designer from '../services/musicDesigner.js';import { errorMiddleware } from '../lib/errorHandler.js';import musicRoutes from './music.js';@@ -152,6 +160,103 @@ describe('music routes', () => {cache.cached = true;cuda.status = 'available';models.list.mockResolvedValue([{ id: 'm', name: 'M', userAdded: false }]);+ designer.describeMusic.mockReset().mockResolvedValue({ description: 'Lush pads over a broken beat.', llm: { provider: 'fake-provider', model: 'fake-model' } });+ designer.writeLyrics.mockReset().mockResolvedValue({ lyrics: '[verse]\nrain on the window', llm: { provider: 'fake-provider', model: 'fake-model' } });+ });++ describe('POST /describe', () => {+ it('passes every designer field through to describeMusic and returns text + attribution', async () => {+ const r = await request(app).post('/api/music/describe').send({+ concept: 'a rainy downtempo loop',+ guidance: 'under 100 BPM',+ template: 'Be terse.',+ providerId: 'fake-provider',+ model: 'fake-model',+ effort: 'high',+ });+ expect(r.status).toBe(200);+ expect(r.body).toEqual({ description: 'Lush pads over a broken beat.', llm: { provider: 'fake-provider', model: 'fake-model' } });+ expect(designer.describeMusic).toHaveBeenCalledWith({+ concept: 'a rainy downtempo loop',+ guidance: 'under 100 BPM',+ template: 'Be terse.',+ providerId: 'fake-provider',+ model: 'fake-model',+ effort: 'high',+ });+ });++ it('normalizes empty picker values to undefined so the service falls back to its defaults', async () => {+ const r = await request(app).post('/api/music/describe').send({+ concept: 'a rainy downtempo loop', providerId: '', model: ' ', effort: '',+ });+ expect(r.status).toBe(200);+ expect(designer.describeMusic).toHaveBeenCalledWith({+ concept: 'a rainy downtempo loop',+ guidance: undefined,+ template: undefined,+ providerId: undefined,+ model: undefined,+ effort: undefined,+ });+ });++ it('rejects a missing/blank concept', async () => {+ const missing = await request(app).post('/api/music/describe').send({});+ expect(missing.status).toBe(400);+ const blank = await request(app).post('/api/music/describe').send({ concept: ' ' });+ expect(blank.status).toBe(400);+ expect(designer.describeMusic).not.toHaveBeenCalled();+ });++ it('rejects a concept past the prompt-field cap', async () => {+ const r = await request(app).post('/api/music/describe').send({ concept: 'x'.repeat(8001) });+ expect(r.status).toBe(400);+ expect(designer.describeMusic).not.toHaveBeenCalled();+ });++ it('surfaces the service NO_PROVIDER error through the error middleware', async () => {+ designer.describeMusic.mockRejectedValue(new ServerError('No AI provider available to describe the music', { status: 503, code: 'NO_PROVIDER' }));+ const r = await request(app).post('/api/music/describe').send({ concept: 'x' });+ expect(r.status).toBe(503);+ expect(r.body.code).toBe('NO_PROVIDER');+ });+ });++ describe('POST /lyrics', () => {+ it('passes every designer field through to writeLyrics and returns lyrics + attribution', async () => {+ const r = await request(app).post('/api/music/lyrics').send({+ description: 'warm rhodes soul',+ guidance: 'about leaving at dawn',+ template: 'Two verses only.',+ providerId: 'fake-provider',+ model: 'fake-model',+ effort: 'low',+ });+ expect(r.status).toBe(200);+ expect(r.body).toEqual({ lyrics: '[verse]\nrain on the window', llm: { provider: 'fake-provider', model: 'fake-model' } });+ expect(designer.writeLyrics).toHaveBeenCalledWith({+ description: 'warm rhodes soul',+ guidance: 'about leaving at dawn',+ template: 'Two verses only.',+ providerId: 'fake-provider',+ model: 'fake-model',+ effort: 'low',+ });+ });++ it('rejects a missing description', async () => {+ const r = await request(app).post('/api/music/lyrics').send({ guidance: 'about leaving at dawn' });+ expect(r.status).toBe(400);+ expect(designer.writeLyrics).not.toHaveBeenCalled();+ });++ it('surfaces the service LLM_EMPTY error through the error middleware', async () => {+ designer.writeLyrics.mockRejectedValue(new ServerError('The AI returned empty lyrics.', { status: 502, code: 'LLM_EMPTY' }));+ const r = await request(app).post('/api/music/lyrics').send({ description: 'warm rhodes soul' });+ expect(r.status).toBe(502);+ expect(r.body.code).toBe('LLM_EMPTY');+ });});it('GET /engines lists engines with readiness + lyric capability + merged models', async () => {diff --git a/server/services/musicDesigner.js b/server/services/musicDesigner.jsnew file mode 100644index 0000000000..36cb831d37--- /dev/null+++ b/server/services/musicDesigner.js@@ -0,0 +1,134 @@+/**+ * Music designer — the two LLM steps behind the Music studio's stepped+ * Generate tab (#4305).+ *+ * describeMusic() short reference/vibe → a rich, genre-dense musical+ * description suitable as an ACE-Step conditioning prompt.+ * writeLyrics() that description (+ the user's extra guidance) → original+ * lyrics in the `[verse]` / `[chorus]` section syntax the+ * lyric-aware engines expect.+ *+ * Both are plain-text generators — no JSON contract — and both return an `llm`+ * attribution block alongside the text, matching `roundsAI.js`'s shape.+ *+ * Meta-prompts ship as module constants and are overridable per call via+ * `template`. The override is stored in **settings** (`settings.music.designer`)+ * rather than `data/prompts/`, which deliberately keeps these off the+ * prompt-template migration path — a blank/whitespace override falls back to+ * the shipped constant here, server-side, so a cleared field can never send an+ * instruction-less prompt to a provider.+ *+ * Nothing here runs on its own: every call is driven by an explicit button+ * press in the same request (AI Provider Usage Policy — no cold bootstrap).+ */++import { ServerError } from '../lib/errorHandler.js';+import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from '../lib/promptRunner.js';++// Caps mirror the Generate form's own field limits so a designer round-trip+// can't produce text the generate route would then reject.+const MAX_CONCEPT = 8000;+const MAX_GUIDANCE = 4000;+const MAX_TEMPLATE = 8000;+const MAX_DESCRIPTION = 8000;+const MAX_LYRICS = 20000;++export const DEFAULT_DESCRIBE_TEMPLATE = 'Describe the given musical reference and description in richer detail in English, focusing primarily on the sound, instruments, feel, and the overall atmosphere. Also briefly describe the composition, instrumentation, beats, lyrical or instrumental style (maybe it doesn\'t have lyrics), and aesthetic. Keep it concise and genre-focused rather than overly technical.';++export const DEFAULT_LYRICS_TEMPLATE = 'Write original song lyrics that fit the musical description below. Use the section syntax the audio engine expects: a bracketed section tag alone on its line ([verse], [chorus], [bridge], [outro]) with that section\'s lines beneath it. Match the mood, genre, energy, and vocal style implied by the description, and keep the phrasing singable. Keep the lyrics original (do not reproduce copyrighted lyrics verbatim).';++const clean = (value, max) => (typeof value === 'string' ? value.trim().slice(0, max) : '');++// A blank/whitespace override means "use the shipped default" — the UI clears+// the field to reset, and an empty instruction block would otherwise leave the+// provider with nothing but the raw concept text.+const pickTemplate = (template, fallback) => clean(template, MAX_TEMPLATE) || fallback;++// The output instruction lives OUTSIDE the overridable template on purpose: a+// user editing the meta-prompt is tuning the creative brief, not the wire+// format, and a fenced/preambled response would land verbatim in the textarea.+const section = (label, body) => (body ? `\n\n${label}:\n${body}` : '');++export function buildDescribePrompt({ concept, guidance, template } = {}) {+ return [+ pickTemplate(template, DEFAULT_DESCRIBE_TEMPLATE),+ section('MUSICAL REFERENCE / VIBE', clean(concept, MAX_CONCEPT) || '(none given)'),+ section('ADDITIONAL GUIDANCE FROM THE USER', clean(guidance, MAX_GUIDANCE)),+ '\n\nReturn ONLY the description as plain prose. No preamble, no headings, no bullet list, no markdown fence.',+ ].join('');+}++export function buildLyricsPrompt({ description, guidance, template } = {}) {+ return [+ pickTemplate(template, DEFAULT_LYRICS_TEMPLATE),+ section('MUSICAL DESCRIPTION', clean(description, MAX_DESCRIPTION) || '(none given)'),+ section('ADDITIONAL GUIDANCE FROM THE USER', clean(guidance, MAX_GUIDANCE)),+ '\n\nReturn ONLY the lyrics with their section tags. No preamble, no commentary, no markdown fence.',+ ].join('');+}++// Providers habitually wrap prose in a ``` fence despite the instruction above.+// Unwrap a response that is ENTIRELY one fence; leave anything else untouched+// so a lyric line that merely contains backticks survives.+function unfence(text) {+ const match = /^\s*```[a-zA-Z]*\s*\n([\s\S]*?)\n?```\s*$/.exec(text || '');+ return match ? match[1] : (text || '');+}++/**+ * Expand a short reference/vibe into a rich musical description.+ *+ * @param {object} args+ * @param {string} args.concept — the user's short "what do you want?" text+ * @param {string} [args.guidance] — extra free-text direction+ * @param {string} [args.template] — meta-prompt override; blank → the default+ * @param {string} [args.providerId] — blank → the install's active provider+ * @param {string} [args.model]+ * @param {string} [args.effort] — reasoning effort; dropped by providers without one+ * @returns {Promise<{ description: string, llm: { provider: string, model: string|null } }>}+ */+export async function describeMusic({ concept, guidance, template, providerId, model, effort } = {}) {+ const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });+ assertProvider(provider, { message: 'No AI provider available to describe the music', code: 'NO_PROVIDER' });++ const prompt = buildDescribePrompt({ concept, guidance, template });+ const { text, model: ranModel } = await runPromptThroughProvider({+ provider, model: selectedModel, effort, prompt, source: 'music-describe',+ });++ const description = clean(unfence(text), MAX_DESCRIPTION);+ if (!description) {+ throw new ServerError('The AI returned an empty description. Try rerunning or picking a stronger model.', { status: 502, code: 'LLM_EMPTY' });+ }+ console.log(`🎼 Described music via ${provider.id}/${ranModel || 'default'} (${description.length} chars)`);+ return { description, llm: { provider: provider.id, model: ranModel || null } };+}++/**+ * Write original lyrics grounded in an (already enriched) musical description.+ *+ * @param {object} args+ * @param {string} args.description — the enriched musical description+ * @param {string} [args.guidance] — "make the chorus about X", etc.+ * @param {string} [args.template] — meta-prompt override; blank → the default+ * @param {string} [args.providerId]+ * @param {string} [args.model]+ * @param {string} [args.effort]+ * @returns {Promise<{ lyrics: string, llm: { provider: string, model: string|null } }>}+ */+export async function writeLyrics({ description, guidance, template, providerId, model, effort } = {}) {+ const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });+ assertProvider(provider, { message: 'No AI provider available to write lyrics', code: 'NO_PROVIDER' });++ const prompt = buildLyricsPrompt({ description, guidance, template });+ const { text, model: ranModel } = await runPromptThroughProvider({+ provider, model: selectedModel, effort, prompt, source: 'music-lyrics',+ });++ const lyrics = clean(unfence(text), MAX_LYRICS);+ if (!lyrics) {+ throw new ServerError('The AI returned empty lyrics. Try rerunning or picking a stronger model.', { status: 502, code: 'LLM_EMPTY' });+ }+ console.log(`🎤 Wrote lyrics via ${provider.id}/${ranModel || 'default'} (${lyrics.length} chars)`);+ return { lyrics, llm: { provider: provider.id, model: ranModel || null } };+}diff --git a/server/services/musicDesigner.test.js b/server/services/musicDesigner.test.jsnew file mode 100644index 0000000000..76e7ebeae8--- /dev/null+++ b/server/services/musicDesigner.test.js@@ -0,0 +1,127 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Mock the AI runner so both designer steps run end to end against a canned+// response — no provider spawn. `resolve` lets a case return "no provider" so+// the NO_PROVIDER guard is exercised against the REAL assertProvider.+const ai = vi.hoisted(() => ({+ provider: { id: 'fake-provider', type: 'api' },+ selectedModel: 'fake-model',+ runPromptThroughProvider: vi.fn(),+}));+vi.mock('../lib/promptRunner.js', async () => ({+ ...(await vi.importActual('../lib/promptRunner.js')),+ resolveProviderAndModel: vi.fn(async () => ({ provider: ai.provider, selectedModel: ai.selectedModel })),+ runPromptThroughProvider: ai.runPromptThroughProvider,+}));++import { resolveProviderAndModel } from '../lib/promptRunner.js';+import {+ DEFAULT_DESCRIBE_TEMPLATE, DEFAULT_LYRICS_TEMPLATE,+ buildDescribePrompt, buildLyricsPrompt, describeMusic, writeLyrics,+} from './musicDesigner.js';++const lastRunArgs = () => ai.runPromptThroughProvider.mock.calls.at(-1)[0];++beforeEach(() => {+ ai.provider = { id: 'fake-provider', type: 'api' };+ ai.selectedModel = 'fake-model';+ ai.runPromptThroughProvider.mockReset().mockResolvedValue({ text: 'canned output', model: 'ran-model', runId: 'run-1' });+ resolveProviderAndModel.mockClear();+});++describe('prompt builders', () => {+ it('uses the shipped default when no template is given', () => {+ expect(buildDescribePrompt({ concept: 'a rainy downtempo loop' })).toContain(DEFAULT_DESCRIBE_TEMPLATE);+ expect(buildLyricsPrompt({ description: 'warm rhodes soul' })).toContain(DEFAULT_LYRICS_TEMPLATE);+ });++ it('uses an override template instead of the default', () => {+ const prompt = buildDescribePrompt({ concept: 'a rainy downtempo loop', template: 'Be terse.' });+ expect(prompt).toContain('Be terse.');+ expect(prompt).not.toContain(DEFAULT_DESCRIBE_TEMPLATE);+ });++ it('falls back to the default for a blank/whitespace override', () => {+ expect(buildDescribePrompt({ concept: 'x', template: ' ' })).toContain(DEFAULT_DESCRIBE_TEMPLATE);+ expect(buildLyricsPrompt({ description: 'x', template: '\n\t ' })).toContain(DEFAULT_LYRICS_TEMPLATE);+ });++ it('includes the user guidance section only when guidance is given', () => {+ expect(buildDescribePrompt({ concept: 'x', guidance: 'under 100 BPM' })).toContain('under 100 BPM');+ expect(buildDescribePrompt({ concept: 'x' })).not.toContain('ADDITIONAL GUIDANCE');+ });++ it('keeps the output-format instruction outside the overridable template', () => {+ // An override tunes the creative brief, not the wire format — a fenced or+ // preambled response would land verbatim in the user's textarea.+ expect(buildLyricsPrompt({ description: 'x', template: 'Whatever.' })).toContain('no markdown fence');+ });+});++describe('describeMusic', () => {+ it('runs the prompt through the resolved provider and returns text + attribution', async () => {+ ai.runPromptThroughProvider.mockResolvedValue({ text: ' Lush analog pads over a broken beat. ', model: 'ran-model' });++ const result = await describeMusic({ concept: 'a rainy downtempo loop', providerId: 'fake-provider', model: 'fake-model' });++ expect(result).toEqual({+ description: 'Lush analog pads over a broken beat.',+ llm: { provider: 'fake-provider', model: 'ran-model' },+ });+ expect(resolveProviderAndModel).toHaveBeenCalledWith({ providerId: 'fake-provider', model: 'fake-model' });+ expect(lastRunArgs()).toMatchObject({ provider: ai.provider, model: 'fake-model', source: 'music-describe' });+ });++ it('passes effort through to the runner', async () => {+ await describeMusic({ concept: 'x', effort: 'high' });+ expect(lastRunArgs().effort).toBe('high');+ });++ it('unwraps a fully fenced response', async () => {+ ai.runPromptThroughProvider.mockResolvedValue({ text: '```\nA slow, dusty boom-bap groove.\n```', model: null });+ const { description } = await describeMusic({ concept: 'x' });+ expect(description).toBe('A slow, dusty boom-bap groove.');+ });++ it('throws NO_PROVIDER when nothing resolves', async () => {+ ai.provider = null;+ ai.selectedModel = null;+ await expect(describeMusic({ concept: 'x' })).rejects.toMatchObject({ code: 'NO_PROVIDER', status: 503 });+ expect(ai.runPromptThroughProvider).not.toHaveBeenCalled();+ });++ it('throws LLM_EMPTY on a blank response instead of returning an empty description', async () => {+ ai.runPromptThroughProvider.mockResolvedValue({ text: ' ', model: null });+ await expect(describeMusic({ concept: 'x' })).rejects.toMatchObject({ code: 'LLM_EMPTY', status: 502 });+ });+});++describe('writeLyrics', () => {+ it('returns lyrics + attribution and tags the run source', async () => {+ ai.runPromptThroughProvider.mockResolvedValue({ text: '[verse]\nrain on the window\n', model: 'ran-model' });++ const result = await writeLyrics({ description: 'warm rhodes soul', guidance: 'about leaving at dawn' });++ expect(result).toEqual({+ lyrics: '[verse]\nrain on the window',+ llm: { provider: 'fake-provider', model: 'ran-model' },+ });+ expect(lastRunArgs()).toMatchObject({ source: 'music-lyrics' });+ expect(lastRunArgs().prompt).toContain('about leaving at dawn');+ });++ it('passes effort through to the runner', async () => {+ await writeLyrics({ description: 'x', effort: 'low' });+ expect(lastRunArgs().effort).toBe('low');+ });++ it('throws NO_PROVIDER when nothing resolves', async () => {+ ai.provider = null;+ await expect(writeLyrics({ description: 'x' })).rejects.toMatchObject({ code: 'NO_PROVIDER', status: 503 });+ });++ it('throws LLM_EMPTY on a blank response', async () => {+ ai.runPromptThroughProvider.mockResolvedValue({ text: '', model: null });+ await expect(writeLyrics({ description: 'x' })).rejects.toMatchObject({ code: 'LLM_EMPTY', status: 502 });+ });+});