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
fix: preserve authored Music Designer inputs and refuse oversized drafts (#11357)
[._.]/ Adam Eivy39ffc9536165
diff --git a/client/src/components/music/MusicDesigner.jsx b/client/src/components/music/MusicDesigner.jsxindex a607ef5751..54fa5c2ccf 100644--- a/client/src/components/music/MusicDesigner.jsx+++ b/client/src/components/music/MusicDesigner.jsx@@ -218,7 +218,7 @@ export default function MusicDesigner() {const music = musicSettingsRef.current;const next = { ...music, designer: { ...(music.designer || {}), ...patch } };musicSettingsRef.current = next;- updateSettings({ music: next }, { silent: true }).catch(() => {});+ updateSettings({ music: next }, { silent: true }).catch((err) => toast.error(err?.message || 'Could not save Music Designer preferences'));};const saveDraft = (patch) => {@@ -252,19 +252,19 @@ export default function MusicDesigner() {const runDescribe = async ({ advance }) => {if (!concept.trim()) { toast.error('Describe the vibe (or name a reference) first'); return; }- saveDraft({ concept: concept.trim() });+ saveDraft({ concept });setDescribing(true);const res = await describeMusic({- concept: concept.trim(),- guidance: conceptGuidance.trim() || undefined,- template: describeTemplate.trim() || undefined,+ concept,+ guidance: conceptGuidance || undefined,+ template: describeTemplate.trim() ? describeTemplate : undefined,providerId: selectedProviderId || undefined,model: selectedModel || undefined,effort: effort || undefined,}, { silent: true }).catch((err) => { toast.error(err?.message || 'Could not describe the music'); return null; });if (mountedRef.current) setDescribing(false);if (!res?.description) return;- saveDraft({ concept: concept.trim(), prompt: res.description });+ saveDraft({ concept, prompt: res.description });if (!mountedRef.current) return;setDescription(res.description);setDescribeSent(typeof res.sentPrompt === 'string' ? { sentPrompt: res.sentPrompt, additions: res.promptAdditions || [] } : null);@@ -274,12 +274,12 @@ export default function MusicDesigner() {const runLyrics = async () => {if (!description.trim()) { toast.error('Write the musical description first'); return; }- saveDraft({ prompt: description.trim() });+ saveDraft({ prompt: description });setWriting(true);const res = await generateLyrics({- description: description.trim(),- guidance: lyricsGuidance.trim() || undefined,- template: lyricsTemplate.trim() || undefined,+ description,+ guidance: lyricsGuidance || undefined,+ template: lyricsTemplate.trim() ? lyricsTemplate : undefined,providerId: selectedProviderId || undefined,model: selectedModel || undefined,effort: effort || undefined,@@ -344,10 +344,9 @@ export default function MusicDesigner() {id="music-designer-concept"value={concept}onChange={(event) => setConcept(event.target.value)}- onBlur={() => saveDraft({ concept: concept.trim() })}+ onBlur={() => saveDraft({ concept })}disabled={draftLoading}rows={3}- maxLength={8000}placeholder="A cross between a rain-soaked downtempo instrumental and a late-night synth ballad…"className={FIELD_CLASS}/>@@ -360,7 +359,6 @@ export default function MusicDesigner() {value={conceptGuidance}onChange={(event) => setConceptGuidance(event.target.value)}disabled={draftLoading}- maxLength={4000}placeholder="90–96 BPM, 6/8 meter, D minor, instrumental only with a cello lead…"className={FIELD_CLASS}/>@@ -402,9 +400,8 @@ export default function MusicDesigner() {id="music-designer-describe-template"value={describeTemplate}onChange={(event) => setDescribeTemplate(event.target.value)}- onBlur={() => persistDesignerPrefs({ describeTemplate: describeTemplate.trim() })}+ onBlur={() => persistDesignerPrefs({ describeTemplate })}rows={4}- maxLength={8000}placeholder={DESCRIBE_PLACEHOLDER}className={FIELD_CLASS}/>@@ -425,9 +422,8 @@ export default function MusicDesigner() {id="music-designer-lyrics-template"value={lyricsTemplate}onChange={(event) => setLyricsTemplate(event.target.value)}- onBlur={() => persistDesignerPrefs({ lyricsTemplate: lyricsTemplate.trim() })}+ onBlur={() => persistDesignerPrefs({ lyricsTemplate })}rows={4}- maxLength={8000}placeholder={LYRICS_PLACEHOLDER}className={FIELD_CLASS}/>@@ -463,10 +459,9 @@ export default function MusicDesigner() {id="music-designer-description"value={description}onChange={(event) => setDescription(event.target.value)}- onBlur={() => saveDraft({ prompt: description.trim() })}+ onBlur={() => saveDraft({ prompt: description })}disabled={draftLoading}rows={8}- maxLength={8000}placeholder={'Global Metadata\nBasic Attributes: 92 BPM, 6/8 meter, warm instrumental soul…\n\nVocal Details\nInstrumental only; the Rhodes carries the lead melody…\n\nArrangement\nIntro: sparse keys enter first…'}className={FIELD_CLASS}/>@@ -520,7 +515,6 @@ export default function MusicDesigner() {value={lyricsGuidance}onChange={(event) => setLyricsGuidance(event.target.value)}disabled={draftLoading}- maxLength={4000}placeholder="Make the chorus about leaving a city at dawn…"className={FIELD_CLASS}/>@@ -554,7 +548,6 @@ export default function MusicDesigner() {onBlur={() => saveDraft({ lyrics })}disabled={draftLoading}rows={10}- maxLength={20000}placeholder={'[verse]\n…\n[chorus]\n…'}className={`${FIELD_CLASS} font-mono`}/>@@ -565,7 +558,7 @@ export default function MusicDesigner() {<SentPromptPanel sentPrompt={lyricsSent.sentPrompt} additions={lyricsSent.additions} /></div>)}- <button type="button" onClick={() => { saveDraft({ prompt: description.trim(), lyrics }); goTo('render'); }} disabled={busy || !draftReady} className={PRIMARY_BTN}>+ <button type="button" onClick={() => { saveDraft({ prompt: description, lyrics }); goTo('render'); }} disabled={busy || !draftReady} className={PRIMARY_BTN}>{lyrics.trim() ? 'Next: render' : 'Continue without lyrics'}</button>{!lyrics.trim() && (@@ -606,10 +599,9 @@ export default function MusicDesigner() {id="music-designer-render-prompt"value={description}onChange={(event) => setDescription(event.target.value)}- onBlur={() => saveDraft({ prompt: description.trim() })}+ onBlur={() => saveDraft({ prompt: description })}disabled={draftLoading}rows={6}- maxLength={8000}placeholder={'Describe the sound, arrangement, vocals, instruments, mood, and production direction…'}aria-describedby="music-designer-render-prompt-hint"className={FIELD_CLASS}diff --git a/client/src/components/music/MusicDesigner.test.jsx b/client/src/components/music/MusicDesigner.test.jsxindex ef9b6b1c56..9fca822219 100644--- a/client/src/components/music/MusicDesigner.test.jsx+++ b/client/src/components/music/MusicDesigner.test.jsx@@ -241,6 +241,56 @@ describe('<MusicDesigner>', () => {});});+ // Uniquely catches whitespace loss in blur saves, either LLM submission,+ // template preferences, or the final description handoff to the renderer.+ it('preserves authored text across editor saves, AI requests and render handoff', async () => {+ const concept = ' Paper moons\n ';+ const description = ' \nSoft fictional piano\n ';+ const template = ' \nMy custom instruction\n ';+ const lyrics = ' [verse]\nPaper moons\n ';+ api.describeMusic.mockResolvedValue({ description, llm: {} });+ api.generateLyrics.mockResolvedValue({ lyrics, llm: {} });+ renderAt('/music/generate/concept');+ const conceptBox = await findEnabledByLabelText(/what do you want to hear/i);+ fireEvent.change(conceptBox, { target: { value: concept } });+ fireEvent.blur(conceptBox);+ fireEvent.change(screen.getByLabelText(/extra guidance/i), { target: { value: ' Soft pulse ' } });+ fireEvent.click(screen.getByRole('button', { name: /advanced — meta-prompts/i }));+ const templateBox = screen.getByLabelText(/description instruction/i);+ fireEvent.change(templateBox, { target: { value: template } });+ fireEvent.blur(templateBox);+ fireEvent.click(screen.getByRole('button', { name: /describe it/i }));+ await findEnabledByLabelText(/music description/i);+ expect(api.describeMusic).toHaveBeenCalledWith(expect.objectContaining({ concept, guidance: ' Soft pulse ', template }), { silent: true });+ expect(api.updateSettings).toHaveBeenCalledWith(expect.objectContaining({ music: expect.objectContaining({ designer: expect.objectContaining({ describeTemplate: template }) }) }), { silent: true });+ await waitFor(() => expect(api.updateTrack).toHaveBeenCalledWith('track-draft', { concept }, { silent: true }));+ const edited = description + 'Keep my ending. ';+ fireEvent.change(screen.getByLabelText(/music description/i), { target: { value: edited } });+ fireEvent.blur(screen.getByLabelText(/music description/i));+ fireEvent.click(screen.getByRole('button', { name: /next: lyrics/i }));+ fireEvent.change(screen.getByLabelText(/lyric guidance/i), { target: { value: ' Keep the hook ' } });+ fireEvent.click(screen.getByRole('button', { name: /generate lyrics/i }));+ await waitFor(() => expect(screen.getByLabelText('Lyrics')).toHaveValue(lyrics));+ expect(api.generateLyrics).toHaveBeenCalledWith(expect.objectContaining({ description: edited, guidance: ' Keep the hook ' }), { silent: true });+ fireEvent.click(screen.getByRole('button', { name: /next: render/i }));+ expect(await screen.findByTestId('gen-panel')).toHaveAttribute('data-prompt', edited);+ expect(screen.getByTestId('gen-panel')).toHaveAttribute('data-lyrics', lyrics);+ await waitFor(() => expect(api.updateTrack).toHaveBeenCalledWith('track-draft', { prompt: edited, lyrics }, { silent: true }));+ });++ it('keeps oversized authored text editable when its submission is refused', async () => {+ api.describeMusic.mockRejectedValue(new Error('concept has 8001 characters; limit is 8000'));+ renderAt('/music/generate/concept');+ const input = await findEnabledByLabelText(/what do you want to hear/i);+ expect(input).not.toHaveAttribute('maxlength');+ const concept = 'x'.repeat(8001);+ fireEvent.change(input, { target: { value: concept } });+ fireEvent.click(screen.getByRole('button', { name: /describe it/i }));+ await waitFor(() => expect(api.describeMusic).toHaveBeenCalledWith(expect.objectContaining({ concept }), { silent: true }));+ expect(input).toHaveValue(concept);+ expect(screen.getByTestId('location')).toHaveTextContent('/music/generate/concept');+ });+describe('the describe step', () => {it('fires no LLM call on mount — both provider calls need an explicit press', async () => {renderAt('/music/generate/concept');diff --git a/server/lib/README.md b/server/lib/README.mdindex 49cda9bb9e..71934b7bbe 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -900,3 +900,5 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `deepAudit.js` | Strict Deep audit checkpoint schema, scope invalidation, server-assigned passes and mechanical completion rules. |- `auditWorkflow.js`: versioned extended Deep execution and historical certification classification.++| `musicDesignerValidation.js` | Non-transforming authored input schemas and character limits for Music Designer composition and routes. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 5fd0a0d252..dce1e21aab 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -884,3 +884,5 @@ export * from './musicVideoTransitions.js';export * from './musicVideoImageEffects.js';export * from './securityScanEvidence.js';++export * from './musicDesignerValidation.js';diff --git a/server/lib/musicDesignerValidation.js b/server/lib/musicDesignerValidation.jsnew file mode 100644index 0000000000..f25a2e292d--- /dev/null+++ b/server/lib/musicDesignerValidation.js@@ -0,0 +1,31 @@+import { z } from 'zod';+import { CONCEPT_MAX, PROMPT_MAX, LYRICS_MAX } from './trackLimits.js';+import { isNonBlankStr } from './textUtils.js';++// Authored model inputs are validated without rewriting whitespace or cutting+// text. Count the original string, including whitespace, against its wire cap.+const authoredField = (field, limit) => z.string().superRefine((value, ctx) => {+ if (value.length > limit) ctx.addIssue({ code: 'custom', message: `${field} has ${value.length} characters; limit is ${limit}` });+});+const requiredField = (field, limit) => authoredField(field, limit).refine(isNonBlankStr, `${field} is required`);+export const MUSIC_DESIGNER_GUIDANCE_MAX = 4000;+export const musicDesignerFields = {+ guidance: authoredField('guidance', MUSIC_DESIGNER_GUIDANCE_MAX).optional(),+ template: authoredField('template', PROMPT_MAX).optional(),+};+export const musicDescribeInputSchema = z.object({+ concept: requiredField('concept', CONCEPT_MAX),+ ...musicDesignerFields,+});+export const musicLyricsInputSchema = z.object({+ description: requiredField('description', PROMPT_MAX),+ request: authoredField('request', MUSIC_DESIGNER_GUIDANCE_MAX).optional(),+ targetSeconds: z.number().min(30).max(600).optional(),+ ...musicDesignerFields,+});+export const musicLyricsReviewInputSchema = z.object({+ lyrics: requiredField('lyrics', LYRICS_MAX),+ description: authoredField('description', PROMPT_MAX).optional(),+ request: authoredField('request', MUSIC_DESIGNER_GUIDANCE_MAX).optional(),+ guidance: musicDesignerFields.guidance,+});diff --git a/server/routes/music.js b/server/routes/music.jsindex 9c428561d9..5b71d118e0 100644--- a/server/routes/music.js+++ b/server/routes/music.js@@ -33,7 +33,7 @@import { Router } from 'express';import { existsSync } from 'fs';import { z } from 'zod';-import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { failValidation, asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import { createLineReader } from '../lib/streamLines.js';import { SETUP_IMAGE_VIDEO_SCRIPT, spawnSetupScript, stopSetupScript } from '../lib/setupScriptRunner.js';@@ -56,6 +56,8 @@ import { getCudaCapability } from '../lib/cudaCapability.js';import { federatedMediaAudioProfileSchema } from '../lib/federatedMediaWire.js';import { composeMusicPrompt, queueMusicGeneration } from '../services/musicGeneration.js';+import { musicDescribeInputSchema, musicLyricsInputSchema, musicDesignerFields } from '../lib/musicDesignerValidation.js';+const router = Router();// GET /api/music/engines — every selectable backend with its models (shipped +@@ -302,8 +304,7 @@ const blankToUndefined = (s) => {// 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(),+ ...musicDesignerFields,providerId: z.string().max(128).optional().transform(blankToUndefined),model: z.string().max(256).optional().transform(blankToUndefined),effort: z.string().max(64).optional().transform(blankToUndefined),@@ -311,21 +312,16 @@ const designerPickerShape = {// 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,-});+const describeSchema = musicDescribeInputSchema.extend(designerPickerShape);+const lyricsSchema = musicLyricsInputSchema.extend(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 parsed = describeSchema.safeParse(req.body ?? {});+ if (!parsed.success) failValidation(parsed);+ const body = parsed.data;const { description, llm, sentPrompt, promptAdditions } = await describeMusic({concept: body.concept,guidance: body.guidance,@@ -341,9 +337,13 @@ router.post('/describe', asyncHandler(async (req, res) => {// 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 parsed = lyricsSchema.safeParse(req.body ?? {});+ if (!parsed.success) failValidation(parsed);+ const body = parsed.data;const { lyrics, llm, sentPrompt, promptAdditions } = await writeLyrics({description: body.description,+ request: body.request,+ targetSeconds: body.targetSeconds,guidance: body.guidance,template: body.template,providerId: body.providerId,diff --git a/server/routes/music.test.js b/server/routes/music.test.jsindex 1afb3ae31c..fc7a9cfeb1 100644--- a/server/routes/music.test.js+++ b/server/routes/music.test.js@@ -225,6 +225,62 @@ describe('music routes', () => {designer.writeLyrics.mockReset().mockResolvedValue({ lyrics: '[verse]\nrain on the window', llm: { provider: 'fake-provider', model: 'fake-model' } });});+ // Uniquely catches route/schema or composer rewrites of authored text, and+ // ensures generated overflow is refused by the real workflow at its HTTP boundary.+ it('preserves authored designer fields through routes and provider composition', async () => {+ const real = await vi.importActual('../services/musicDesigner.js');+ designer.describeMusic.mockImplementation(real.describeMusic);+ designer.writeLyrics.mockImplementation(real.writeLyrics);+ promptRunner.resolveProviderAndModel.mockResolvedValue({ provider: { id: 'p', type: 'api' }, selectedModel: 'm' });+ promptRunner.runPromptThroughProvider.mockResolvedValue({ text: 'Valid generated text', model: 'm' });+ const concept = ' A fictional twilight loop\n\t';+ const guidance = ' Keep the pulse soft\t ';+ const template = ' \nMy authored instruction.\n ';+ const described = await request(app).post('/api/music/describe').send({ concept, guidance, template });+ expect(described.status).toBe(200);+ expect(described.body.sentPrompt).toBe(promptRunner.runPromptThroughProvider.mock.calls.at(-1)[0].prompt);+ expect(described.body.sentPrompt).toContain(`${template}\n\nMUSICAL REFERENCE / VIBE:\n${concept}\n\nADDITIONAL GUIDANCE FROM THE USER:\n${guidance}`);+ const description = ' An airy fictional arrangement.\n ';+ const requestText = ' Chorus about paper moons\n ';+ const written = await request(app).post('/api/music/lyrics').send({ description, guidance, template, request: requestText });+ expect(written.status).toBe(200);+ expect(written.body.sentPrompt).toContain(`:\n${requestText}\n\nMUSICAL DESCRIPTION:\n${description}\n\nADDITIONAL GUIDANCE FROM THE USER:\n${guidance}`);+ expect(written.body.sentPrompt).toContain(template);+ const reset = await request(app).post('/api/music/describe').send({ concept, template: ' \n\t' });+ expect(reset.body.sentPrompt).toContain(real.DEFAULT_DESCRIBE_TEMPLATE);+ expect(reset.body.promptAdditions.map((item) => item.label)).toContain('Describe instructions');+ });++ it.each([+ ['/describe', { concept: 'x' }, 'description', 8000],+ ['/lyrics', { description: 'x' }, 'lyrics', 20000],+ ])('rejects oversized generated output from %s without another provider call', async (path, body, field, limit) => {+ const real = await vi.importActual('../services/musicDesigner.js');+ designer.describeMusic.mockImplementation(real.describeMusic);+ designer.writeLyrics.mockImplementation(real.writeLyrics);+ promptRunner.resolveProviderAndModel.mockResolvedValue({ provider: { id: 'p', type: 'api' }, selectedModel: 'm' });+ promptRunner.runPromptThroughProvider.mockReset().mockResolvedValue({ text: 'x'.repeat(limit + 1), model: 'm' });+ const response = await request(app).post(`/api/music${path}`).send(body);+ expect(response.status).toBe(502);+ expect(response.body.code).toBe('LLM_OUTPUT_TOO_LONG');+ expect(response.body.error).toContain(`${limit + 1} characters; limit is ${limit}`);+ expect(response.body).not.toHaveProperty(field);+ expect(promptRunner.runPromptThroughProvider).toHaveBeenCalledTimes(1);+ });++ it.each([+ ['/describe', { concept: 'x' + ' '.repeat(8000) }, 8001, 8000],+ ['/lyrics', { description: 'x', guidance: ' '.repeat(4001) }, 4001, 4000],+ ['/lyrics', { description: 'x', template: ' '.repeat(8001) }, 8001, 8000],+ ['/lyrics', { description: 'x', request: ' '.repeat(4001) }, 4001, 4000],+ ])('counts authored whitespace before rejecting %s', async (path, body, count, limit) => {+ const response = await request(app).post(`/api/music${path}`).send(body);+ expect(response.status).toBe(400);+ expect(response.body.error).toContain(`${count} characters; limit is ${limit}`);+ expect(designer.describeMusic).not.toHaveBeenCalled();+ expect(designer.writeLyrics).not.toHaveBeenCalled();+ });+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({@@ -288,6 +344,8 @@ describe('music routes', () => {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',+ request: undefined,+ targetSeconds: undefined,guidance: 'about leaving at dawn',template: 'Two verses only.',providerId: 'fake-provider',@@ -298,6 +356,8 @@ describe('music routes', () => {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',+ request: undefined,+ targetSeconds: undefined,guidance: 'about leaving at dawn',template: 'Two verses only.',providerId: 'fake-provider',diff --git a/server/routes/tracks.js b/server/routes/tracks.jsindex b6d456a95d..e95048dd93 100644--- a/server/routes/tracks.js+++ b/server/routes/tracks.js@@ -72,9 +72,9 @@ const titleField = z.string().trim().min(1).max(tracks.TITLE_MAX);const albumIdField = z.string().trim().max(tracks.ALBUM_ID_MAX);const artistIdField = z.string().trim().max(tracks.ARTIST_ID_MAX);const artistNameField = z.string().trim().max(tracks.ARTIST_NAME_MAX);-const conceptField = z.string().trim().max(tracks.CONCEPT_MAX);+const conceptField = z.string().max(tracks.CONCEPT_MAX);const lyricsField = z.string().max(tracks.LYRICS_MAX);-const promptField = z.string().trim().max(tracks.PROMPT_MAX);+const promptField = z.string().max(tracks.PROMPT_MAX);const engineField = z.string().trim().max(tracks.ENGINE_MAX);const modelIdField = z.string().trim().max(tracks.MODEL_ID_MAX);// On the generic save path, `audioFilename` must be a bare, safe music-librarydiff --git a/server/routes/tracks.test.js b/server/routes/tracks.test.jsindex fecfcb476b..9e1b868dbd 100644--- a/server/routes/tracks.test.js+++ b/server/routes/tracks.test.js@@ -315,6 +315,14 @@ describe('tracks routes', () => {expect(tracks.updateTrack).toHaveBeenCalledWith('track-1', { prompt: 'warm folk' });});+ it('PATCH /:id preserves authored designer text before persistence', async () => {+ tracks.getTrack.mockResolvedValue({ id: 'track-1', title: 'Fictional draft' });+ const patch = { concept: ' Paper moons\n ', prompt: ' \nSoft piano\t ', lyrics: ' [verse]\nPaper moons\n ' };+ const response = await request(app).patch('/api/tracks/track-1').send(patch);+ expect(response.status).toBe(200);+ expect(tracks.updateTrack).toHaveBeenCalledWith('track-1', patch);+ });+it('PATCH /:id accepts a saved music-designer concept', async () => {tracks.getTrack.mockResolvedValue({ id: 'track-1', title: 'Intro' });const r = await request(app).patch('/api/tracks/track-1').send({ concept: 'A dusk-time pulse' });diff --git a/server/services/musicDesigner.js b/server/services/musicDesigner.jsindex 1cee1543ea..10c055b6f2 100644--- a/server/services/musicDesigner.js+++ b/server/services/musicDesigner.js@@ -25,19 +25,25 @@* press in the same request (AI Provider Usage Policy — no cold bootstrap).*/-import { ServerError } from '../lib/errorHandler.js';+import { ServerError, failValidation } from '../lib/errorHandler.js';import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from './promptRunner.js';-import { trimTo } from '../lib/textUtils.js';+import { isNonBlankStr } from '../lib/textUtils.js';+import { musicDescribeInputSchema, musicLyricsInputSchema, musicLyricsReviewInputSchema, MUSIC_DESIGNER_GUIDANCE_MAX } from '../lib/musicDesignerValidation.js';+import { PROMPT_MAX, LYRICS_MAX } from '../lib/trackLimits.js';import { CREATIVE_LATITUDE_ADDITION, withCreativeLatitude } from '../lib/creativeLatitude.js';import { promptAddition } from '../lib/modelInput.js';+// Service callers also compose directly, so route validation alone is not enough.+const validateInput = (schema, input) => {+ const parsed = schema.safeParse(input);+ if (!parsed.success) failValidation(parsed);+ return parsed.data;+};+// 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;+const MAX_DESCRIPTION = PROMPT_MAX;+const MAX_LYRICS = LYRICS_MAX;// Caption shape follows MiniMax Music 3's official music-caption-rewriter// contract. Keep it model-neutral enough to remain useful for ACE-Step and the@@ -60,7 +66,7 @@ export const DEFAULT_LYRICS_TEMPLATE = [].join(' ');const DESCRIBE_OUTPUT_CONTRACT = [- 'Return ONLY the structured caption as plain text, normally 250–450 English words.',+ `Return ONLY the structured caption as plain text, normally 250–450 English words, never more than ${MAX_DESCRIPTION} characters including whitespace.`,'Use exactly these three top-level headings in this order, each alone on its own line and without markdown markers:','Global Metadata','Cover basic attributes (genre, tempo, meter/groove, and only deliberate key/scale details), the global emotional progression, application imagery, and the sonic/production profile.',@@ -74,18 +80,19 @@ const DESCRIBE_OUTPUT_CONTRACT = [// 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) => trimTo(template, MAX_TEMPLATE) || fallback;+const pickTemplate = (template, fallback) => isNonBlankStr(template) ? 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 } = {}) {+export function buildDescribePrompt(input = {}) {+ const { concept, guidance, template } = validateInput(musicDescribeInputSchema, input);return [pickTemplate(template, DEFAULT_DESCRIBE_TEMPLATE),- section('MUSICAL REFERENCE / VIBE', trimTo(concept, MAX_CONCEPT) || '(none given)'),- section('ADDITIONAL GUIDANCE FROM THE USER', trimTo(guidance, MAX_GUIDANCE)),+ section('MUSICAL REFERENCE / VIBE', concept),+ section('ADDITIONAL GUIDANCE FROM THE USER', guidance),`\n\n${DESCRIBE_OUTPUT_CONTRACT}`,].join('');}@@ -106,14 +113,15 @@ const lengthContract = (targetSeconds) => {// phrase, subject and imagery the user asked for never reach the lyricist.const SONG_REQUEST_LABEL = 'SONG REQUEST (what the lyrics must deliver: honour every hook phrase, subject and image it names; ignore its purely musical or production details such as genre, tempo, instruments or artist names, which the musical description owns and which never belong in a lyric line)';-const LYRICS_OUTPUT_CONTRACT = 'Return ONLY the lyrics with their section tags. No preamble, no commentary, no markdown fence.';+const LYRICS_OUTPUT_CONTRACT = `Return ONLY the lyrics with their section tags, never more than ${MAX_LYRICS} characters including whitespace. No preamble, no commentary, no markdown fence.`;-export function buildLyricsPrompt({ description, guidance, request, template, targetSeconds } = {}) {+export function buildLyricsPrompt(input = {}) {+ const { description, guidance, request, template, targetSeconds } = validateInput(musicLyricsInputSchema, input);return [pickTemplate(template, DEFAULT_LYRICS_TEMPLATE),- section(SONG_REQUEST_LABEL, trimTo(request, MAX_GUIDANCE)),- section('MUSICAL DESCRIPTION', trimTo(description, MAX_DESCRIPTION) || '(none given)'),- section('ADDITIONAL GUIDANCE FROM THE USER', trimTo(guidance, MAX_GUIDANCE)),+ section(SONG_REQUEST_LABEL, request),+ section('MUSICAL DESCRIPTION', description || '(none given)'),+ section('ADDITIONAL GUIDANCE FROM THE USER', guidance),lengthContract(targetSeconds),`\n\n${LYRICS_OUTPUT_CONTRACT}`,].join('');@@ -124,7 +132,7 @@ export function buildLyricsPrompt({ description, guidance, request, template, ta// default is listed as an addition.const designerAdditions = ({ template, defaultTemplate, instructionsLabel, extra }) => [CREATIVE_LATITUDE_ADDITION,- trimTo(template, MAX_TEMPLATE) ? null : promptAddition('designer-instructions', instructionsLabel, defaultTemplate),+ isNonBlankStr(template) ? null : promptAddition('designer-instructions', instructionsLabel, defaultTemplate),...extra,].filter(Boolean);@@ -141,20 +149,21 @@ const LYRICS_REVIEW_INSTRUCTIONS = [// Only with a request, so a review without one (Music Studio) keeps its original prompt.const LYRICS_REVIEW_REQUEST_CHECK = ' Exception: check the draft against the SONG REQUEST first. Any hook phrase, title phrase or required image it names that the draft lacks must appear in the revision (a named hook belongs in the chorus), and your notes must say what was missing.';const LYRICS_REVIEW_OUTPUT_CONTRACT = [- 'Return the complete revised lyric sheet first, with its section tags.',+ `Return the complete revised lyric sheet first, with its section tags, never more than ${MAX_LYRICS} characters including whitespace.`,`Then a line containing only ${LYRICS_REVIEW_SEPARATOR}`,- 'Then two to four short sentences of notes: what was weak in the draft and what you changed.',+ `Then two to four short sentences of notes: what was weak in the draft and what you changed. Keep notes within ${MUSIC_DESIGNER_GUIDANCE_MAX} characters.`,'No preamble, no other commentary, no markdown fence.',].join('\n');-function buildLyricsReviewPrompt({ lyrics, description, guidance, request } = {}) {+function buildLyricsReviewPrompt(input = {}) {+ const { lyrics, description, guidance, request } = validateInput(musicLyricsReviewInputSchema, input);return [LYRICS_REVIEW_INSTRUCTIONS,- trimTo(request, MAX_GUIDANCE) ? LYRICS_REVIEW_REQUEST_CHECK : '',- section(SONG_REQUEST_LABEL, trimTo(request, MAX_GUIDANCE)),- section('MUSICAL DESCRIPTION', trimTo(description, MAX_DESCRIPTION) || '(none given)'),- section('ADDITIONAL GUIDANCE FROM THE USER', trimTo(guidance, MAX_GUIDANCE)),- section('DRAFT LYRICS', trimTo(lyrics, MAX_LYRICS)),+ request ? LYRICS_REVIEW_REQUEST_CHECK : '',+ section(SONG_REQUEST_LABEL, request),+ section('MUSICAL DESCRIPTION', description || '(none given)'),+ section('ADDITIONAL GUIDANCE FROM THE USER', guidance),+ section('DRAFT LYRICS', lyrics),`\n\n${LYRICS_REVIEW_OUTPUT_CONTRACT}`,].join('');}@@ -181,6 +190,16 @@ function unfence(text) {return match ? match[1] : (text || '');}+// Never turn an invalid provider result into a shorter, apparently valid draft.+function validateGeneratedText(text, field, limit) {+ if (text.length > limit) {+ throw new ServerError(`The AI returned ${field} with ${text.length} characters; limit is ${limit}. Revise the instructions or choose another model.`, {+ status: 502, code: 'LLM_OUTPUT_TOO_LONG', context: { field, count: text.length, limit },+ });+ }+ return text;+}+/*** Expand a short reference/vibe into a rich musical description.*@@ -194,11 +213,10 @@ function unfence(text) {* @returns {Promise<{ description: string, llm: { provider: string, model: string|null } }>}*/export async function describeMusic({ concept, guidance, template, providerId, model, effort } = {}) {+ const prompt = withCreativeLatitude(buildDescribePrompt({ concept, guidance, template }));const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });assertProvider(provider, { message: 'No AI provider available to describe the music', code: 'NO_PROVIDER' });- // Stamped here (idempotent) so the response carries the exact text sent.- const prompt = withCreativeLatitude(buildDescribePrompt({ concept, guidance, template }));const promptAdditions = designerAdditions({template, defaultTemplate: DEFAULT_DESCRIBE_TEMPLATE, instructionsLabel: 'Describe instructions',extra: [promptAddition('caption-format', 'Caption format', DESCRIBE_OUTPUT_CONTRACT)],@@ -207,7 +225,7 @@ export async function describeMusic({ concept, guidance, template, providerId, mprovider, model: selectedModel, effort, prompt, source: 'music-describe',});- const description = trimTo(unfence(text), MAX_DESCRIPTION);+ const description = validateGeneratedText(unfence(text), 'description', MAX_DESCRIPTION).trim();if (!description) {throw new ServerError('The AI returned an empty description. Try rerunning or picking a stronger model.', { status: 502, code: 'LLM_EMPTY' });}@@ -230,14 +248,14 @@ export async function describeMusic({ concept, guidance, template, providerId, m* @returns {Promise<{ lyrics: string, llm: { provider: string, model: string|null } }>}*/export async function writeLyrics({ description, guidance, request, template, targetSeconds, providerId, model, effort } = {}) {+ const prompt = withCreativeLatitude(buildLyricsPrompt({ description, guidance, request, template, targetSeconds }));const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });assertProvider(provider, { message: 'No AI provider available to write lyrics', code: 'NO_PROVIDER' });- const prompt = withCreativeLatitude(buildLyricsPrompt({ description, guidance, request, template, targetSeconds }));const promptAdditions = designerAdditions({template, defaultTemplate: DEFAULT_LYRICS_TEMPLATE, instructionsLabel: 'Lyrics instructions',extra: [- promptAddition('song-request', 'Song request', trimTo(request, MAX_GUIDANCE) && `${SONG_REQUEST_LABEL}:\n${trimTo(request, MAX_GUIDANCE)}`),+ promptAddition('song-request', 'Song request', request && `${SONG_REQUEST_LABEL}:\n${request}`),promptAddition('target-length', 'Target length', lengthContract(targetSeconds)),promptAddition('lyrics-format', 'Lyrics format', LYRICS_OUTPUT_CONTRACT),],@@ -246,7 +264,7 @@ export async function writeLyrics({ description, guidance, request, template, taprovider, model: selectedModel, effort, prompt, source: 'music-lyrics',});- const lyrics = trimTo(unfence(text), MAX_LYRICS);+ const lyrics = validateGeneratedText(unfence(text), 'lyrics', MAX_LYRICS).trim();if (!lyrics) {throw new ServerError('The AI returned empty lyrics. Try rerunning or picking a stronger model.', { status: 502, code: 'LLM_EMPTY' });}@@ -268,23 +286,20 @@ export async function writeLyrics({ description, guidance, request, template, ta* @returns {Promise<{ lyrics: string, notes: string, llm: { provider: string, model: string|null } }>}*/export async function reviewLyrics({ lyrics, description, guidance, request, providerId, model, effort } = {}) {- if (!trimTo(lyrics, MAX_LYRICS)) {- throw new ServerError('There are no lyrics to review.', { status: 400, code: 'VALIDATION_ERROR' });- }+ const prompt = buildLyricsReviewPrompt({ lyrics, description, guidance, request });const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });assertProvider(provider, { message: 'No AI provider available to review lyrics', code: 'NO_PROVIDER' });- const prompt = buildLyricsReviewPrompt({ lyrics, description, guidance, request });const { text, model: ranModel } = await runPromptThroughProvider({provider, model: selectedModel, effort, prompt, source: 'music-lyrics-review',});const parsed = parseLyricsReview(text);- const revised = trimTo(parsed.lyrics, MAX_LYRICS);+ const revised = validateGeneratedText(parsed.lyrics, 'revised lyrics', MAX_LYRICS);if (!revised) {throw new ServerError('The AI returned empty revised lyrics. Try rerunning or picking a stronger model.', { status: 502, code: 'LLM_EMPTY' });}- const notes = trimTo(parsed.notes, MAX_GUIDANCE);+ const notes = validateGeneratedText(parsed.notes, 'review notes', MUSIC_DESIGNER_GUIDANCE_MAX);console.log(`🎤 Reviewed lyrics via ${provider.id}/${ranModel || 'default'} (${revised.length} chars${notes ? ', with notes' : ''})`);return { lyrics: revised, notes, llm: { provider: provider.id, model: ranModel || null } };}diff --git a/server/services/musicDesigner.test.js b/server/services/musicDesigner.test.jsindex 5fe475ca09..0ca51ef130 100644--- a/server/services/musicDesigner.test.js+++ b/server/services/musicDesigner.test.js@@ -185,6 +185,35 @@ describe('writeLyrics', () => {});});+// Service callers include autonomous media work: they must obey the same+// preservation and refusal contract without relying on an HTTP validator.+describe('designer service input boundaries', () => {+ it('refuses missing, blank, and oversized inputs before provider resolution', async () => {+ await expect(describeMusic({ concept: ' ' })).rejects.toMatchObject({ code: 'VALIDATION_ERROR' });+ await expect(writeLyrics({ description: 'x', request: 'x'.repeat(4001) })).rejects.toMatchObject({ code: 'VALIDATION_ERROR' });+ await expect(reviewLyrics({ lyrics: 'x'.repeat(20001) })).rejects.toMatchObject({ code: 'VALIDATION_ERROR' });+ expect(resolveProviderAndModel).not.toHaveBeenCalled();+ expect(ai.runPromptThroughProvider).not.toHaveBeenCalled();+ });++ it('preserves review draft, description, guidance and request in the sent blocks', async () => {+ const lyrics = ' [verse]\nPaper moons\n ';+ const description = ' Soft piano\n ';+ const guidance = ' Keep the ending\n ';+ const request = ' Sing of paper moons\n ';+ await reviewLyrics({ lyrics, description, guidance, request });+ expect(lastRunArgs().prompt).toContain(`:\n${request}\n\nMUSICAL DESCRIPTION:\n${description}\n\nADDITIONAL GUIDANCE FROM THE USER:\n${guidance}\n\nDRAFT LYRICS:\n${lyrics}`);+ });++ it('rejects an oversized revision or critique rather than cutting it', async () => {+ ai.runPromptThroughProvider.mockResolvedValueOnce({ text: 'x'.repeat(20001) + '\n---\nA note.' });+ await expect(reviewLyrics({ lyrics: '[verse]\nPaper moons' })).rejects.toMatchObject({ code: 'LLM_OUTPUT_TOO_LONG', context: { count: 20001, limit: 20000 } });+ ai.runPromptThroughProvider.mockResolvedValueOnce({ text: '[verse]\nPaper moons\n---\n' + 'x'.repeat(4001) });+ await expect(reviewLyrics({ lyrics: '[verse]\nPaper moons' })).rejects.toMatchObject({ code: 'LLM_OUTPUT_TOO_LONG', context: { count: 4001, limit: 4000 } });+ expect(ai.runPromptThroughProvider).toHaveBeenCalledTimes(2);+ });+});+describe('reviewLyrics', () => {const DRAFT = '[verse]\nrain on the glass\n[chorus]\nhold on';diff --git a/server/services/tracks/file.test.js b/server/services/tracks/file.test.jsindex 191f517b33..92dcaec983 100644--- a/server/services/tracks/file.test.js+++ b/server/services/tracks/file.test.js@@ -46,6 +46,15 @@ beforeEach(reset);afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));describe('tracks file backend — CRUD', () => {+ it('preserves authored concept, description and lyrics across draft save/read', async () => {+ const authored = { concept: ' Paper moons\n ', prompt: ' \nSoft piano\t ', lyrics: ' [verse]\nKeep the spaces\n ' };+ const created = await file.createTrack({ title: 'Fictional draft', ...authored });+ expect(await file.getTrack(created.id)).toMatchObject(authored);+ const edited = { concept: ' \nNew concept\t ', prompt: ' New arrangement\n ' };+ await file.updateTrack(created.id, edited);+ expect(await file.getTrack(created.id)).toMatchObject({ ...authored, ...edited });+ });+it('creates, reads, updates and soft-deletes a track', async () => {const created = await file.createTrack({ title: 'Intro', audioFilename: 'music-1.mp3' });expect(created.id).toMatch(/^track-/);diff --git a/server/services/tracks/logic.js b/server/services/tracks/logic.jsindex 1461f85fa8..bf1108cd90 100644--- a/server/services/tracks/logic.js+++ b/server/services/tracks/logic.js@@ -195,7 +195,7 @@ export function sanitizeTrack(raw) {const updatedAt = isStr(raw.updatedAt) ? raw.updatedAt : createdAt;const deleted = raw.deleted === true;const lyrics = isStr(raw.lyrics) ? raw.lyrics.slice(0, LYRICS_MAX) : '';- const prompt = trimTo(raw.prompt, PROMPT_MAX);+ const prompt = isStr(raw.prompt) ? raw.prompt.slice(0, PROMPT_MAX) : '';const engine = trimTo(raw.engine, ENGINE_MAX);const modelId = trimTo(raw.modelId, MODEL_ID_MAX);const durationSec = sanitizeDuration(raw.durationSec);@@ -233,7 +233,7 @@ export function sanitizeTrack(raw) {albumId: trimTo(raw.albumId, ALBUM_ID_MAX),artistId: trimTo(raw.artistId, ARTIST_ID_MAX),artist: trimTo(raw.artist, ARTIST_NAME_MAX),- concept: trimTo(raw.concept, CONCEPT_MAX),+ concept: isStr(raw.concept) ? raw.concept.slice(0, CONCEPT_MAX) : '',lyrics,prompt,engine,