Suno-style web UI for a self-hosted MiniMax-Music3 inference server
TypeScript ai-musicdiffusersdockerexpressminimaxminimax-musicmusic-generationreactself-hostedsgl-omnisunotailwindcsstext-to-musictypescriptvite
feat: prompt enhancement via MiniMax's music-caption-rewriter skill
Adam Benhassenb1d655897137
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 86b66fc..6b77567 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,9 @@# Changelog+## Unreleased++- Prompt enhancement: magic-wand button on the prompt field runs MiniMax's `music-caption-rewriter` skill on an OpenAI-compatible LLM (Settings or `LLM_API` / `LLM_API_KEY` / `LLM_MODEL`); undo restores the original text. Disabled in the demo.+## v0.1.0 — 2026-08-19First release. Live demo: https://demo-minimax-music.adambh.devdiff --git a/README.md b/README.mdindex 0b3b6bd..d469894 100644--- a/README.md+++ b/README.md@@ -31,6 +31,7 @@- **Create panel** — Simple or Custom mode, song title (random name like “Velvet Horizon” if left empty), style description, lyrics editor with `[Verse]` / `[Chorus]` / … tag chips, instrumental toggle, duration 5–360 s, 1–4 takes per submit (each take gets `seed + i`), advanced seed. Output is WAV, as the official route documents (FLAC/MP3 appear in the selector but disabled).- **Templates** — a built-in default plus your own saved templates (style, lyrics, duration), stored server-side.+- **Prompt enhancement** — the magic wand at the top right of the prompt field rewrites your description into a structured MiniMax Music 3 caption (Global Metadata / Vocal Details / Arrangement) using MiniMax's own [`music-caption-rewriter`](https://github.com/MiniMax-AI/MiniMax-Music3/tree/main/skills/music-caption-rewriter) skill. It runs on any OpenAI-compatible chat model with tool calling that you configure in Settings (or `LLM_API` / `LLM_MODEL`); the music server is not involved. Skill files are fetched from GitHub on first use and cached in `data/skill-cache/`. Undo restores your original text.- **Render queue** — the UI server renders one track at a time against the blocking `/v1/audio/speech` route and shows queued / rendering / done with elapsed time and an estimated bar (~3× realtime — the official API reports no progress). Cancel while queued or rendering, retry on error. Queued tracks survive a UI-server restart (they are re-queued in order); a render that was in flight is marked as interrupted.- **Live progress + play while rendering** — when the server is the bundled `inference/server.py` (it advertises `capabilities: ["stream"]` on `/health`), progress is real for every render (Generating → Rendering, ETA from the measured rate). Tick *Play while rendering* under Advanced and the audio is streamed as it's rendered too: press play on a track that is still rendering, the waveform grows as windows arrive, the player buffers when it catches up with the renderer and swaps to the final file seamlessly. Stock `sgl-omni` keeps the estimated bar.- **Library** — every finished render is saved into `data/tracks/` with its metadata (prompt, lyrics, seed, format). Cards show duration, seed and how long the render took. Search, download, delete, "reuse settings".@@ -38,7 +39,7 @@- **Player** — sticky bottom bar with waveform (decoded client-side), seek, prev/next, keyboard space to play/pause.- **Health pill** — offline / loading model / idle (· live progress) / rendering · N queued (probes `GET /v1/models` and the optional `GET /health`).- **Settings page** — point the app at your inference server (URL + optional API key) from the UI, with a "Test connection" button. Environment variables, when set, take precedence and lock those fields. A *Compatibility mode* debug switch makes the UI treat any server as stock `sgl-omni` (no `/health`, no streaming) to check the plain contract still works.-- Responsive down to phone width. No external services; everything runs on your machine or tailnet.+- Responsive down to phone width. No external services required; everything runs on your machine or tailnet (prompt enhancement is optional and uses the LLM you configure, plus a one-time fetch of the skill from GitHub).## Architecture@@ -119,6 +120,9 @@ The inference server address is resolved in this order:|---|---|---|| `MUSIC_API` | – | Base URL of the inference server, path prefix allowed, e.g. `http://host:8000` (overrides Settings) || `MUSIC_API_KEY` | – | Sent as `Authorization: Bearer …` if the inference server was started with `--api-key` (overrides Settings) |+| `LLM_API` | – | OpenAI-compatible base URL incl. `/v1` for prompt enhancement, e.g. `https://api.openai.com/v1`, `http://localhost:11434/v1` (overrides Settings) |+| `LLM_API_KEY` | – | Bearer key for `LLM_API`, if it needs one (overrides Settings) |+| `LLM_MODEL` | – | Chat model with tool calling, e.g. `gpt-4.1-mini` (overrides Settings) || `PORT` | `8787` | Port for the UI server || `DATA_DIR` | `./data` | Where `library.json`, `templates.json`, `settings.json` and `tracks/` live || `STATIC_DIR` | `web/dist` (if built) | Directory of the built SPA to serve |@@ -156,16 +160,17 @@ docker run --read-only -p 8787:8787 minimax-music-ui-demo| Method | Path | Description ||---|---|---|-| `GET` | `/api/health` | `demo` (read-only demo, see above), `upstreamReachable` (via `/v1/models`), `ready` (false only if an optional upstream `/health` answers 503), `capabilities` from that `/health`, queue state |+| `GET` | `/api/health` | `demo` (read-only demo, see above), `upstreamReachable` (via `/v1/models`), `ready` (false only if an optional upstream `/health` answers 503), `capabilities` from that `/health`, `enhance` (an LLM is configured), queue state || `GET` | `/api/library` | Tracks, newest first || `POST` | `/api/generate` | `{title?, prompt, lyrics?, duration, seed?, format, takes}` → created tracks (queued) |+| `POST` | `/api/enhance` | `{prompt, lyrics?, instrumental?}` → `{prompt}` rewritten by the caption-rewriter skill; 409 until an LLM is configured, 502/504 on LLM failure or timeout || `GET` | `/api/tracks/:id/audio` | Stream audio (`?download` for an attachment); for a track still rendering, the audio so far with a valid header (Range supported) || `DELETE` | `/api/tracks/:id` | Cancel (dequeue or abort the render), delete file and entry || `GET` | `/api/templates` | Saved templates || `POST` | `/api/templates` | `{name, prompt, lyrics?, duration?, format?}` — same name overwrites || `DELETE` | `/api/templates/:id` | Remove a template |-| `GET` | `/api/settings` | Effective inference URL, whether a key is set, `compat` flag, and which fields are env-locked (the key itself is never returned) |-| `PUT` | `/api/settings` | `{musicApi?, apiKey?, compat?}` — `apiKey: ""` clears it; env-locked fields are rejected; `compat: true` skips `/health` and never streams |+| `GET` | `/api/settings` | Effective inference URL, whether a key is set, `compat` flag, LLM URL/model and whether its key is set, and which fields are env-locked (keys are never returned) |+| `PUT` | `/api/settings` | `{musicApi?, apiKey?, compat?, llmApi?, llmApiKey?, llmModel?}` — `""` clears a key or LLM field; env-locked fields are rejected; `compat: true` skips `/health` and never streams || `POST` | `/api/settings/test` | Probe a candidate `{musicApi?, apiKey?}` against `/v1/models` without saving |## Upstream APIdiff --git a/server/src/app.ts b/server/src/app.tsindex e9e4725..3073636 100644--- a/server/src/app.ts+++ b/server/src/app.ts@@ -5,7 +5,8 @@ import path from 'node:path';import { randomUUID } from 'node:crypto';import type { JsonStore, Library } from './library.js';import { extFor, RenderQueue, UpstreamClient, UpstreamError } from './upstream.js';-import { normalizeGenerate, ValidationError } from './validate.js';+import { normalizeEnhance, normalizeGenerate, ValidationError } from './validate.js';+import { EnhanceError, enhancePrompt, type SkillFiles } from './enhance.js';import { normalizeMusicApi, SettingsStore } from './settings.js';import { randomTitle } from './names.js';import { FORMATS, type Template, type Track } from './types.js';@@ -20,6 +21,8 @@ export interface AppDeps {queue: RenderQueue;tracksDir: string;staticDir?: string | null;+ /** MiniMax's caption-rewriter skill files, for POST /api/enhance */+ skill: SkillFiles;log?: (msg: string) => void;/** read-only public demo: showcase library, simulated per-visitor renders, no upstream, no writes */demo?: DemoOptions | null;@@ -64,9 +67,9 @@ export function createApp(deps: AppDeps) {app.get('/api/health', async (_req, res) => {try {const h = await upstream.health();- res.json({ upstreamReachable: true, ready: h.ready, models: h.models, capabilities: h.capabilities, busy: queue.busy, queued: queue.queued, formats: FORMATS });+ res.json({ upstreamReachable: true, ready: h.ready, models: h.models, capabilities: h.capabilities, busy: queue.busy, queued: queue.queued, formats: FORMATS, enhance: settings.llm() !== null });} catch (err) {- res.json({ upstreamReachable: false, ready: false, capabilities: [], busy: queue.busy, queued: queue.queued, formats: FORMATS, error: (err as Error).message });+ res.json({ upstreamReachable: false, ready: false, capabilities: [], busy: queue.busy, queued: queue.queued, formats: FORMATS, enhance: settings.llm() !== null, error: (err as Error).message });}});@@ -112,6 +115,17 @@ export function createApp(deps: AppDeps) {}});+ app.post('/api/enhance', async (req, res, next) => {+ try {+ const input = normalizeEnhance(req.body);+ const llm = settings.llm();+ if (!llm) return res.status(409).json({ error: 'Prompt enhancement is not configured — set an LLM in Settings' });+ res.json({ prompt: await enhancePrompt(input, llm, deps.skill) });+ } catch (err) {+ next(err);+ }+ });+app.delete('/api/tracks/:id', async (req, res) => {const track = library.get(req.params.id);if (!track) return res.status(404).json({ error: 'not found' });@@ -145,7 +159,7 @@ export function createApp(deps: AppDeps) {app.put('/api/settings', async (req, res, next) => {try {const b = (req.body ?? {}) as Record<string, unknown>;- await settings.update({ musicApi: b.musicApi, apiKey: b.apiKey, compat: b.compat });+ await settings.update({ musicApi: b.musicApi, apiKey: b.apiKey, compat: b.compat, llmApi: b.llmApi, llmApiKey: b.llmApiKey, llmModel: b.llmModel });const e = settings.effective();upstream.configure(e.musicApi, e.apiKey, e.compat);log(`upstream reconfigured → ${e.musicApi}${e.apiKey ? ' (bearer set)' : ''}${e.compat ? ' (compat mode)' : ''}`);@@ -217,6 +231,7 @@ export function createApp(deps: AppDeps) {app.use((err: unknown, _req: Request, res: Response, _next: NextFunction) => {if (err instanceof ValidationError) return res.status(400).json({ error: err.message });if (err instanceof UpstreamError) return res.status(502).json({ error: err.message });+ if (err instanceof EnhanceError) return res.status(err.status).json({ error: err.message });if (err && typeof err === 'object' && 'type' in err && (err as { type: string }).type === 'entity.parse.failed') {return res.status(400).json({ error: 'invalid JSON' });}diff --git a/server/src/config.ts b/server/src/config.tsindex 030d14e..2a3cf78 100644--- a/server/src/config.ts+++ b/server/src/config.ts@@ -8,6 +8,10 @@ export interface Config {port: number;dataDir: string;staticDir: string | null;+ /** LLM_API / LLM_API_KEY / LLM_MODEL from env (prompt enhancement), or null when not set */+ llmApiEnv: string | null;+ llmApiKeyEnv: string | null;+ llmModelEnv: string | null;/** DEMO=1: read-only public demo (see demo.ts) */demo: boolean;}@@ -18,6 +22,9 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {return {musicApiEnv: env.MUSIC_API?.trim() ? env.MUSIC_API.trim().replace(/\/+$/, '') : null,apiKeyEnv: env.MUSIC_API_KEY?.trim() || null,+ llmApiEnv: env.LLM_API?.trim() ? env.LLM_API.trim().replace(/\/+$/, '') : null,+ llmApiKeyEnv: env.LLM_API_KEY?.trim() || null,+ llmModelEnv: env.LLM_MODEL?.trim() || null,port,dataDir: path.resolve(env.DATA_DIR ?? './data'),staticDir: env.STATIC_DIR ? path.resolve(env.STATIC_DIR) : null,diff --git a/server/src/demo.ts b/server/src/demo.tsindex 28288fd..c5812f8 100644--- a/server/src/demo.ts+++ b/server/src/demo.ts@@ -97,7 +97,7 @@ export function demoRouter(library: Library, tracksDir: string, opts: DemoOptionconst r = Router();r.get('/api/health', (_req, res) => {- res.json({ demo: true, upstreamReachable: true, ready: true, busy: false, queued: 0, formats: FORMATS, capabilities: [], models: [] });+ res.json({ demo: true, upstreamReachable: true, ready: true, busy: false, queued: 0, formats: FORMATS, capabilities: [], models: [], enhance: false });});r.get('/api/library', (req, res) => {@@ -153,6 +153,7 @@ export function demoRouter(library: Library, tracksDir: string, opts: DemoOptionr.put('/api/settings', readOnly);r.post('/api/settings/test', readOnly);r.post('/api/templates', readOnly);+ r.post('/api/enhance', readOnly);r.delete('/api/templates/:id', readOnly);return r;diff --git a/server/src/enhance.ts b/server/src/enhance.tsnew file mode 100644index 0000000..668ec04--- /dev/null+++ b/server/src/enhance.ts@@ -0,0 +1,167 @@+import fs from 'node:fs/promises';+import path from 'node:path';+import { randomUUID } from 'node:crypto';+import type { EnhanceRequest, LlmConfig } from './types.js';++/** MiniMax's music-caption-rewriter skill at a pinned commit. It ships without a license, so files are fetched on demand, not vendored. */+export const SKILL_BASE = 'https://raw.githubusercontent.com/MiniMax-AI/MiniMax-Music3/945655064d59b98004dd70002e7eb5c8c6e11373/skills/music-caption-rewriter';++const SKILL_PATH = /^(SKILL\.md|references\/[a-z0-9][a-z0-9_-]*\.md|templates\/[a-z0-9][a-z0-9_-]*\.txt)$/;++export class EnhanceError extends Error {+ constructor(message: string, readonly status: number) {+ super(message);+ }+}++/** Skill files from the local cache; a missing one is fetched once from `base` and cached. */+export class SkillFiles {+ constructor(private readonly cacheDir: string, private readonly base = SKILL_BASE) {}++ static isValidPath(p: string): boolean {+ return SKILL_PATH.test(p);+ }++ /** File text, or null when the skill has no such file. Throws when the fetch itself fails. */+ async read(rel: string, signal?: AbortSignal): Promise<string | null> {+ if (!SkillFiles.isValidPath(rel)) throw new Error(`invalid skill path: ${rel}`);+ const local = path.join(this.cacheDir, rel);+ try {+ return await fs.readFile(local, 'utf8');+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;+ }+ const res = await fetch(`${this.base}/${rel}`, { signal });+ if (res.status === 404) return null;+ if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);+ const text = await res.text();+ await fs.mkdir(path.dirname(local), { recursive: true });+ const tmp = `${local}.${randomUUID()}.tmp`;+ await fs.writeFile(tmp, text, 'utf8');+ await fs.rename(tmp, local);+ return text;+ }+}++interface ToolCall {+ id: string;+ type: 'function';+ function: { name: string; arguments: string };+}++interface ChatMessage {+ role: 'system' | 'user' | 'assistant' | 'tool';+ content: string | null;+ tool_calls?: ToolCall[];+ tool_call_id?: string;+}++const HARNESS_NOTE = `++## Harness++You are running inside a music-generation UI. Read skill files with the read_file tool, using paths relative to the skill root (for example references/genre-router.md or templates/<id>.txt). No other tools or scripts are available. Reply with only the final caption: the three headings and their content, no preamble.`;++const TOOLS = [{+ type: 'function',+ function: {+ name: 'read_file',+ description: 'Read a file of the music-caption-rewriter skill. Paths are relative to the skill root, e.g. references/genre-router.md or templates/<id>.txt.',+ parameters: { type: 'object', properties: { path: { type: 'string' } }, required: ['path'] },+ },+}];++function userMessage(input: EnhanceRequest): string {+ const parts = [`Caption: ${input.prompt}`];+ if (input.instrumental) parts.push('Constraints: instrumental — no vocals.');+ else if (input.lyrics) parts.push(`Lyrics:\n${input.lyrics}`);+ return parts.join('\n\n');+}++/** Tool failures go back to the model as text so it can recover; they never fail the request. */+async function runTool(call: ToolCall, skill: SkillFiles, signal: AbortSignal): Promise<string> {+ if (call.function.name !== 'read_file') return `error: unknown tool ${call.function.name}`;+ let p: unknown;+ try {+ p = (JSON.parse(call.function.arguments || '{}') as { path?: unknown }).path;+ } catch {+ return 'error: arguments must be JSON like {"path": "references/genre-router.md"}';+ }+ if (typeof p !== 'string') return 'error: path is required';+ const rel = p.replace(/^\.\//, '');+ if (!SkillFiles.isValidPath(rel)) return `error: ${p} is not a readable skill file (SKILL.md, references/*.md, templates/*.txt)`;+ try {+ return (await skill.read(rel, signal)) ?? `error: file not found: ${rel}`;+ } catch (err) {+ return `error: fetch failed for ${rel}: ${(err as Error).message}`;+ }+}++async function complete(llm: LlmConfig, messages: ChatMessage[], signal: AbortSignal): Promise<ChatMessage> {+ const failed = (err: unknown, what: string) =>+ signal.aborted ? new EnhanceError('enhancement timed out', 504) : new EnhanceError(`${what}: ${(err as Error).message}`, 502);+ let res: Response;+ try {+ res = await fetch(`${llm.url}/chat/completions`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...(llm.apiKey ? { Authorization: `Bearer ${llm.apiKey}` } : {}) },+ body: JSON.stringify({ model: llm.model, messages, tools: TOOLS }),+ signal,+ });+ } catch (err) {+ throw failed(err, `LLM unreachable at ${llm.url}`);+ }+ let text: string;+ try {+ text = await res.text();+ } catch (err) {+ throw failed(err, 'LLM response was cut off');+ }+ if (!res.ok) {+ let detail = text.slice(0, 300) || res.statusText;+ try {+ const m = (JSON.parse(text) as { error?: { message?: unknown } }).error?.message;+ if (typeof m === 'string') detail = m;+ } catch { /* not JSON: keep the raw text */ }+ throw new EnhanceError(`LLM error ${res.status}: ${detail}`, 502);+ }+ let body: { choices?: { message?: ChatMessage }[] };+ try {+ body = JSON.parse(text);+ } catch {+ throw new EnhanceError('LLM returned invalid JSON', 502);+ }+ const msg = body.choices?.[0]?.message;+ if (!msg) throw new EnhanceError('LLM response had no message', 502);+ return msg;+}++/** Rewrite a song description with MiniMax's music-caption-rewriter skill, run as a tool-calling agent on `llm`. */+export async function enhancePrompt(input: EnhanceRequest, llm: LlmConfig, skill: SkillFiles, opts: { maxRounds?: number; timeoutMs?: number } = {}): Promise<string> {+ const maxRounds = opts.maxRounds ?? 12;+ const signal = AbortSignal.timeout(opts.timeoutMs ?? 180_000);+ let skillMd: string | null;+ try {+ skillMd = await skill.read('SKILL.md', signal);+ } catch (err) {+ if (signal.aborted) throw new EnhanceError('enhancement timed out', 504);+ throw new EnhanceError(`could not load the caption-rewriter skill: ${(err as Error).message}`, 502);+ }+ if (skillMd === null) throw new EnhanceError('could not load the caption-rewriter skill: SKILL.md not found', 502);++ const messages: ChatMessage[] = [+ { role: 'system', content: skillMd + HARNESS_NOTE },+ { role: 'user', content: userMessage(input) },+ ];+ for (let round = 0; ; round++) {+ const msg = await complete(llm, messages, signal);+ if (!msg.tool_calls?.length) {+ const caption = (msg.content ?? '').trim();+ if (!caption) throw new EnhanceError('the LLM returned an empty caption', 502);+ return caption;+ }+ if (round === maxRounds) throw new EnhanceError(`enhancement did not finish within ${maxRounds} tool rounds`, 502);+ messages.push(msg);+ for (const call of msg.tool_calls) messages.push({ role: 'tool', tool_call_id: call.id, content: await runTool(call, skill, signal) });+ }+}diff --git a/server/src/index.ts b/server/src/index.tsindex 6c78fd6..d779f07 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -7,6 +7,7 @@ import type { Template } from './types.js';import { RenderQueue, UpstreamClient } from './upstream.js';import { SettingsStore } from './settings.js';import { createApp } from './app.js';+import { SkillFiles } from './enhance.js';const config = loadConfig();const tracksDir = path.join(config.dataDir, 'tracks');@@ -14,7 +15,10 @@ const library = new Library(path.join(config.dataDir, 'library.json'));await library.load();const templates = new JsonStore<Template>(path.join(config.dataDir, 'templates.json'));await templates.load();-const settings = new SettingsStore(path.join(config.dataDir, 'settings.json'), { musicApi: config.musicApiEnv, apiKey: config.apiKeyEnv });+const settings = new SettingsStore(path.join(config.dataDir, 'settings.json'), {+ musicApi: config.musicApiEnv, apiKey: config.apiKeyEnv,+ llmApi: config.llmApiEnv, llmApiKey: config.llmApiKeyEnv, llmModel: config.llmModelEnv,+});await settings.load();const effective = settings.effective();@@ -26,11 +30,14 @@ const here = path.dirname(fileURLToPath(import.meta.url));const defaultStatic = path.resolve(here, '../../web/dist');const staticDir = config.staticDir ?? (fs.existsSync(defaultStatic) ? defaultStatic : null);-const app = createApp({ library, templates, settings, upstream, queue, tracksDir, staticDir, demo: config.demo ? {} : null });+const skill = new SkillFiles(path.join(config.dataDir, 'skill-cache'));+const app = createApp({ library, templates, settings, upstream, queue, tracksDir, staticDir, skill, demo: config.demo ? {} : null });app.listen(config.port, () => {console.log(`minimax-music-ui server on http://localhost:${config.port}`);console.log(` upstream: ${effective.musicApi} [${effective.source.musicApi}]${effective.apiKey ? ` (bearer set [${effective.source.apiKey}])` : ''}`);+ const llm = settings.llm();+ console.log(` enhance: ${llm ? `${llm.model} @ ${llm.url}` : '(no LLM configured)'}`);console.log(` data: ${config.dataDir}`);console.log(` static: ${staticDir ?? '(none — run web dev server)'}`);if (config.demo) console.log(' DEMO mode: read-only showcase, renders are simulated');diff --git a/server/src/settings.ts b/server/src/settings.tsindex b496f48..b0c6230 100644--- a/server/src/settings.ts+++ b/server/src/settings.ts@@ -1,17 +1,25 @@import fs from 'node:fs/promises';import path from 'node:path';import { ValidationError } from './validate.js';+import type { LlmConfig } from './types.js';export interface StoredSettings {musicApi: string | null;apiKey: string | null;/** debug/testing: behave as if the upstream were stock sgl-omni — skip /health, never stream */compat: boolean;+ /** OpenAI-compatible LLM for prompt enhancement */+ llmApi: string | null;+ llmApiKey: string | null;+ llmModel: string | null;}export interface EnvOverrides {musicApi: string | null;apiKey: string | null;+ llmApi?: string | null;+ llmApiKey?: string | null;+ llmModel?: string | null;}export interface EffectiveUpstream {@@ -37,9 +45,25 @@ export function normalizeMusicApi(v: unknown): string {return url.toString().replace(/\/+$/, '');}+/** `""` clears the stored LLM URL. */+export function normalizeLlmApi(v: unknown): string | null {+ if (typeof v !== 'string') throw new ValidationError('llmApi must be a string');+ if (!v.trim()) return null;+ let url: URL;+ try {+ url = new URL(v.trim());+ } catch {+ throw new ValidationError('llmApi must be a valid URL, e.g. https://api.openai.com/v1');+ }+ if (url.protocol !== 'http:' && url.protocol !== 'https:') throw new ValidationError('llmApi must be http or https');+ return url.toString().replace(/\/+$/, '');+}++const llmSource = (env: string | null | undefined, stored: string | null) => (env ? 'env' : stored ? 'settings' : 'none') as 'env' | 'settings' | 'none';+/** Persists user-editable upstream settings; env vars always win over stored values. */export class SettingsStore {- private stored: StoredSettings = { musicApi: null, apiKey: null, compat: false };+ private stored: StoredSettings = { musicApi: null, apiKey: null, compat: false, llmApi: null, llmApiKey: null, llmModel: null };private writing: Promise<void> = Promise.resolve();constructor(private readonly file: string, private readonly env: EnvOverrides) {}@@ -51,6 +75,9 @@ export class SettingsStore {musicApi: typeof raw.musicApi === 'string' && raw.musicApi ? raw.musicApi : null,apiKey: typeof raw.apiKey === 'string' && raw.apiKey ? raw.apiKey : null,compat: raw.compat === true,+ llmApi: typeof raw.llmApi === 'string' && raw.llmApi ? raw.llmApi : null,+ llmApiKey: typeof raw.llmApiKey === 'string' && raw.llmApiKey ? raw.llmApiKey : null,+ llmModel: typeof raw.llmModel === 'string' && raw.llmModel ? raw.llmModel : null,};} catch (err) {if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;@@ -71,6 +98,14 @@ export class SettingsStore {};}+ /** The LLM used for prompt enhancement, or null until both its URL and model are set. */+ llm(): LlmConfig | null {+ const url = this.env.llmApi ?? this.stored.llmApi;+ const model = this.env.llmModel ?? this.stored.llmModel;+ if (!url || !model) return null;+ return { url, model, apiKey: this.env.llmApiKey ?? this.stored.llmApiKey };+ }+/** What the UI may see: never the key itself. */publicView() {const e = this.effective();@@ -78,26 +113,56 @@ export class SettingsStore {musicApi: e.musicApi,apiKeySet: !!e.apiKey,compat: e.compat,- source: e.source,- locked: { musicApi: this.env.musicApi !== null, apiKey: this.env.apiKey !== null },+ llmApi: this.env.llmApi ?? this.stored.llmApi,+ llmModel: this.env.llmModel ?? this.stored.llmModel,+ llmKeySet: !!(this.env.llmApiKey ?? this.stored.llmApiKey),+ source: {+ ...e.source,+ llmApi: llmSource(this.env.llmApi, this.stored.llmApi),+ llmApiKey: llmSource(this.env.llmApiKey, this.stored.llmApiKey),+ llmModel: llmSource(this.env.llmModel, this.stored.llmModel),+ },+ locked: {+ musicApi: this.env.musicApi !== null,+ apiKey: this.env.apiKey !== null,+ llmApi: this.env.llmApi != null,+ llmApiKey: this.env.llmApiKey != null,+ llmModel: this.env.llmModel != null,+ },};}- /** Update stored values. `apiKey: ""` clears it; `undefined` leaves it alone. */- async update(patch: { musicApi?: unknown; apiKey?: unknown; compat?: unknown }): Promise<void> {+ /** Update stored values. `apiKey`/`llm*: ""` clears it; `undefined` leaves it alone. */+ async update(patch: { musicApi?: unknown; apiKey?: unknown; compat?: unknown; llmApi?: unknown; llmApiKey?: unknown; llmModel?: unknown }): Promise<void> {+ const next = { ...this.stored }; // applied only if every field validatesif (patch.musicApi !== undefined) {if (this.env.musicApi !== null) throw new ValidationError('MUSIC_API is set in the environment and cannot be changed here');- this.stored.musicApi = normalizeMusicApi(patch.musicApi);+ next.musicApi = normalizeMusicApi(patch.musicApi);}if (patch.apiKey !== undefined) {if (this.env.apiKey !== null) throw new ValidationError('MUSIC_API_KEY is set in the environment and cannot be changed here');if (typeof patch.apiKey !== 'string') throw new ValidationError('apiKey must be a string');- this.stored.apiKey = patch.apiKey.trim() || null;+ next.apiKey = patch.apiKey.trim() || null;}if (patch.compat !== undefined) {if (typeof patch.compat !== 'boolean') throw new ValidationError('compat must be a boolean');- this.stored.compat = patch.compat;+ next.compat = patch.compat;+ }+ if (patch.llmApi !== undefined) {+ if (this.env.llmApi != null) throw new ValidationError('LLM_API is set in the environment and cannot be changed here');+ next.llmApi = normalizeLlmApi(patch.llmApi);+ }+ if (patch.llmApiKey !== undefined) {+ if (this.env.llmApiKey != null) throw new ValidationError('LLM_API_KEY is set in the environment and cannot be changed here');+ if (typeof patch.llmApiKey !== 'string') throw new ValidationError('llmApiKey must be a string');+ next.llmApiKey = patch.llmApiKey.trim() || null;+ }+ if (patch.llmModel !== undefined) {+ if (this.env.llmModel != null) throw new ValidationError('LLM_MODEL is set in the environment and cannot be changed here');+ if (typeof patch.llmModel !== 'string') throw new ValidationError('llmModel must be a string');+ next.llmModel = patch.llmModel.trim() || null;}+ this.stored = next;await this.persist();}diff --git a/server/src/types.ts b/server/src/types.tsindex 3129e18..7d0e7fa 100644--- a/server/src/types.ts+++ b/server/src/types.ts@@ -52,3 +52,16 @@ export interface Template {/** Output formats — the official /v1/audio/speech route documents wav only. */export const FORMATS = ['wav'];++/** OpenAI-compatible chat endpoint used for prompt enhancement; `url` includes `/v1`. */+export interface LlmConfig {+ url: string;+ apiKey: string | null;+ model: string;+}++export interface EnhanceRequest {+ prompt: string;+ lyrics: string;+ instrumental: boolean;+}diff --git a/server/src/validate.ts b/server/src/validate.tsindex 1bd508e..ab2a548 100644--- a/server/src/validate.ts+++ b/server/src/validate.ts@@ -1,4 +1,4 @@-import { FORMATS, type GenerateRequest } from './types.js';+import { FORMATS, type EnhanceRequest, type GenerateRequest } from './types.js';export class ValidationError extends Error {status = 400;@@ -42,3 +42,12 @@ export function normalizeGenerate(body: unknown): GenerateRequest {return { title, prompt, lyrics, duration, seed, format, takes, stream };}++export function normalizeEnhance(body: unknown): EnhanceRequest {+ if (!body || typeof body !== 'object') throw new ValidationError('body must be an object');+ const b = body as Record<string, unknown>;+ const prompt = typeof b.prompt === 'string' ? b.prompt.trim() : '';+ if (!prompt) throw new ValidationError('prompt is required');+ const lyrics = typeof b.lyrics === 'string' ? b.lyrics.trim() : '';+ return { prompt, lyrics, instrumental: b.instrumental === true };+}diff --git a/server/test/app.test.ts b/server/test/app.test.tsindex 0d7e407..067fe35 100644--- a/server/test/app.test.ts+++ b/server/test/app.test.ts@@ -7,13 +7,17 @@ import { JsonStore, Library } from '../src/library.js';import type { Template, Track } from '../src/types.js';import { RenderQueue, UpstreamClient } from '../src/upstream.js';import { createApp } from '../src/app.js';-import { SettingsStore } from '../src/settings.js';+import { SettingsStore, type EnvOverrides } from '../src/settings.js';import { startFakeUpstream, type FakeUpstream } from './fakeUpstream.js';+import { SkillFiles } from '../src/enhance.js';+import { startFakeLlm, type FakeLlm } from './fakeLlm.js';let fake: FakeUpstream | null = null;afterEach(async () => { await fake?.close(); fake = null; });+let llm: FakeLlm | null = null;+afterEach(async () => { await llm?.close(); llm = null; });-async function setup(opts: Parameters<typeof startFakeUpstream>[0] = {}, apiKey: string | null = null, env: { musicApi: string | null; apiKey: string | null } | null = null) {+async function setup(opts: Parameters<typeof startFakeUpstream>[0] = {}, apiKey: string | null = null, env: EnvOverrides | null = null) {fake = await startFakeUpstream(opts);const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'app-'));const lib = new Library(path.join(dir, 'library.json'));@@ -25,10 +29,17 @@ async function setup(opts: Parameters<typeof startFakeUpstream>[0] = {}, apiKey:const templates = new JsonStore<Template>(path.join(dir, 'templates.json'));await templates.load();const queue = new RenderQueue(lib, upstream, tracksDir, () => {}, 20);- const app = createApp({ library: lib, templates, settings, upstream, queue, tracksDir, log: () => {} });+ // unreachable base: tests never hit GitHub; they seed the cache instead+ const skill = new SkillFiles(path.join(dir, 'skill-cache'), 'http://127.0.0.1:1');+ const app = createApp({ library: lib, templates, settings, upstream, queue, tracksDir, skill, log: () => {} });return { app, lib, tracksDir, dir, upstream, queue };}+const seedSkill = async (dir: string) => {+ await fs.mkdir(path.join(dir, 'skill-cache'), { recursive: true });+ await fs.writeFile(path.join(dir, 'skill-cache', 'SKILL.md'), '# skill');+};+const until = async (cond: () => boolean, ms = 4000) => {const t0 = Date.now();while (!cond()) {@@ -213,7 +224,7 @@ describe('app', () => {const put = await request(app).put('/api/settings').send({ musicApi: `${fake!.url}/`, apiKey: 'sekrit' });expect(put.body).toMatchObject({ musicApi: fake!.url, apiKeySet: true, source: { musicApi: 'settings', apiKey: 'settings' } });expect(upstream.url).toBe(fake!.url);- expect(JSON.parse(await fs.readFile(path.join(dir, 'settings.json'), 'utf8'))).toEqual({ musicApi: fake!.url, apiKey: 'sekrit', compat: false });+ expect(JSON.parse(await fs.readFile(path.join(dir, 'settings.json'), 'utf8'))).toEqual({ musicApi: fake!.url, apiKey: 'sekrit', compat: false, llmApi: null, llmApiKey: null, llmModel: null });await request(app).get('/api/health');expect(fake!.requests.at(-1)?.auth).toBe('Bearer sekrit');expect((await request(app).put('/api/settings').send({ apiKey: '' })).body.apiKeySet).toBe(false);@@ -228,6 +239,69 @@ describe('app', () => {expect((await request(app).get('/api/settings')).body.musicApi).toBe('http://127.0.0.1:7862');});+ it('settings: LLM fields persist, gate health.enhance, and never return the key', async () => {+ const { app, dir } = await setup();+ expect((await request(app).get('/api/health')).body.enhance).toBe(false);+ expect((await request(app).put('/api/settings').send({ llmApi: 'ftp://x' })).status).toBe(400);+ const put = await request(app).put('/api/settings').send({ llmApi: 'http://llm.test/v1/', llmApiKey: 'llm-sekrit', llmModel: 'gpt-x' });+ expect(put.body).toMatchObject({+ llmApi: 'http://llm.test/v1', llmModel: 'gpt-x', llmKeySet: true,+ source: { llmApi: 'settings', llmApiKey: 'settings', llmModel: 'settings' },+ locked: { llmApi: false, llmApiKey: false, llmModel: false },+ });+ expect(JSON.stringify(put.body)).not.toContain('llm-sekrit');+ expect((await request(app).get('/api/health')).body.enhance).toBe(true);+ expect(JSON.parse(await fs.readFile(path.join(dir, 'settings.json'), 'utf8'))).toMatchObject({ llmApi: 'http://llm.test/v1', llmApiKey: 'llm-sekrit', llmModel: 'gpt-x' });+ expect((await request(app).put('/api/settings').send({ llmModel: '' })).body.llmModel).toBeNull();+ expect((await request(app).get('/api/health')).body.enhance).toBe(false);+ await fake!.close(); fake = null;+ await request(app).put('/api/settings').send({ llmModel: 'gpt-x' });+ expect((await request(app).get('/api/health')).body).toMatchObject({ upstreamReachable: false, enhance: true });+ });++ it('enhance: 400 without a prompt, 409 until an LLM is configured, then returns the caption', async () => {+ const { app, dir } = await setup();+ expect((await request(app).post('/api/enhance').send({ prompt: ' ' })).status).toBe(400);+ const off = await request(app).post('/api/enhance').send({ prompt: 'sad piano' });+ expect(off.status).toBe(409);+ expect(off.body.error).toMatch(/not configured/);+ await seedSkill(dir);+ llm = await startFakeLlm([{ content: '### Global Metadata\nslow piano' }]);+ await request(app).put('/api/settings').send({ llmApi: llm.url, llmModel: 'm' });+ const on = await request(app).post('/api/enhance').send({ prompt: 'sad piano', lyrics: '[Verse]\nx', instrumental: false });+ expect(on.status).toBe(200);+ expect(on.body).toEqual({ prompt: '### Global Metadata\nslow piano' });+ expect(llm.requests[0].body.messages[1].content).toBe('Caption: sad piano\n\nLyrics:\n[Verse]\nx');+ expect(fake!.requests.some((r) => r.path.includes('speech'))).toBe(false);+ });++ it('enhance: LLM failure maps to 502 with the reason', async () => {+ const { app, dir } = await setup();+ await seedSkill(dir);+ llm = await startFakeLlm([{ status: 500 }]);+ await request(app).put('/api/settings').send({ llmApi: llm.url, llmModel: 'm' });+ const res = await request(app).post('/api/enhance').send({ prompt: 'sad piano' });+ expect(res.status).toBe(502);+ expect(res.body.error).toMatch(/LLM error 500/);+ });++ it('settings: a rejected PUT changes nothing, even fields that validated', async () => {+ const { app, dir } = await setup();+ expect((await request(app).put('/api/settings').send({ llmApi: 'http://ok.test/v1', llmModel: 5 })).status).toBe(400);+ expect((await request(app).get('/api/settings')).body.llmApi).toBeNull();+ await request(app).put('/api/settings').send({ compat: true });+ expect(JSON.parse(await fs.readFile(path.join(dir, 'settings.json'), 'utf8'))).toMatchObject({ compat: true, llmApi: null });+ });++ it('settings: env-locked LLM fields cannot be changed and the key is never returned', async () => {+ const { app } = await setup({}, null, { musicApi: null, apiKey: null, llmApi: 'http://env-llm/v1', llmApiKey: 'envk', llmModel: 'm' });+ const s = await request(app).get('/api/settings');+ expect(s.body).toMatchObject({ llmApi: 'http://env-llm/v1', llmModel: 'm', llmKeySet: true, locked: { llmApi: true, llmApiKey: true, llmModel: true }, source: { llmApi: 'env', llmApiKey: 'env', llmModel: 'env' } });+ expect(JSON.stringify(s.body)).not.toContain('envk');+ expect((await request(app).put('/api/settings').send({ llmModel: 'other' })).status).toBe(400);+ expect((await request(app).put('/api/settings').send({ llmApiKey: 'x' })).status).toBe(400);+ });+it('streams when advertised: real stage/progress/renderedSeconds, file appears early, valid WAV at the end', async () => {const { app, lib, tracksDir } = await setup({ stream: { windows: 4, secondsPerWindow: 0.1, windowMs: 40 } });const h = await request(app).get('/api/health');diff --git a/server/test/demo.test.ts b/server/test/demo.test.tsindex e8f34e9..45abe4a 100644--- a/server/test/demo.test.ts+++ b/server/test/demo.test.ts@@ -8,6 +8,7 @@ import type { Template, Track } from '../src/types.js';import { RenderQueue, UpstreamClient } from '../src/upstream.js';import { createApp } from '../src/app.js';import { SettingsStore } from '../src/settings.js';+import { SkillFiles } from '../src/enhance.js';const seedTrack = (id: string, file: string): Track => ({id, groupId: id, takeIndex: 0, title: `Seed ${id}`, prompt: 'seed', lyrics: '[Instrumental]', duration: 10, seed: 1, format: 'wav',@@ -29,7 +30,7 @@ async function setup() {const templates = new JsonStore<Template>(path.join(dir, 'templates.json'));await templates.load();const queue = new RenderQueue(lib, upstream, tracksDir, () => {}, 20);- const app = createApp({ library: lib, templates, settings, upstream, queue, tracksDir, log: () => {}, demo: { renderMs: 120, tickMs: 20 } });+ const app = createApp({ library: lib, templates, settings, upstream, queue, tracksDir, skill: new SkillFiles(path.join(dir, 'skill-cache'), 'http://127.0.0.1:1'), log: () => {}, demo: { renderMs: 120, tickMs: 20 } });return { app, lib };}@@ -45,7 +46,7 @@ describe('demo mode', () => {it('reports demo health without touching any upstream', async () => {const { app } = await setup();const h = await request(app).get('/api/health');- expect(h.body).toMatchObject({ demo: true, upstreamReachable: true, ready: true, capabilities: [] });+ expect(h.body).toMatchObject({ demo: true, upstreamReachable: true, ready: true, capabilities: [], enhance: false });});it('refuses writes to seed tracks, settings and templates', async () => {@@ -53,6 +54,7 @@ describe('demo mode', () => {expect((await request(app).delete('/api/tracks/s1')).status).toBe(403);expect(lib.get('s1')).toBeDefined();expect((await request(app).put('/api/settings').send({ musicApi: 'http://x:1' })).status).toBe(403);+ expect((await request(app).post('/api/enhance').send({ prompt: 'x' })).status).toBe(403);expect((await request(app).post('/api/settings/test').send({})).status).toBe(403);expect((await request(app).post('/api/templates').send({ name: 'n', prompt: 'p' })).status).toBe(403);expect((await request(app).delete('/api/templates/x')).status).toBe(403);diff --git a/server/test/enhance.test.ts b/server/test/enhance.test.tsnew file mode 100644index 0000000..6cef6db--- /dev/null+++ b/server/test/enhance.test.ts@@ -0,0 +1,127 @@+import { describe, it, expect, afterEach } from 'vitest';+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { enhancePrompt, SkillFiles } from '../src/enhance.js';+import type { LlmConfig } from '../src/types.js';+import { startFakeLlm, type FakeLlm, type FakeLlmReply } from './fakeLlm.js';++const SKILL = { 'SKILL.md': '# skill body', 'references/genre-router.md': 'ROUTER', 'templates/pop_0001.txt': 'TEMPLATE' };+const read = (p: string) => ({ name: 'read_file', args: { path: p } });+const input = { prompt: 'sad piano', lyrics: '[Verse]\nla la', instrumental: false };++let fake: FakeLlm | null = null;+afterEach(async () => { await fake?.close(); fake = null; });++async function setup(replies: FakeLlmReply[], files: Record<string, string> = SKILL, apiKey: string | null = null) {+ fake = await startFakeLlm(replies, files);+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'enhance-'));+ const skill = new SkillFiles(path.join(dir, 'skill-cache'), fake.skillUrl);+ const llm: LlmConfig = { url: fake.url, apiKey, model: 'test-model' };+ return { skill, llm, dir };+}++const toolResults = (i: number) => fake!.requests[i].body.messages.filter((m) => m.role === 'tool').map((m) => m.content);++describe('enhancePrompt', () => {+ it('runs SKILL.md as the system prompt, serves read_file, returns the final caption', async () => {+ const { skill, llm } = await setup([{ toolCalls: [read('references/genre-router.md')] }, { content: ' ### Global Metadata\nslow ' }]);+ expect(await enhancePrompt(input, llm, skill)).toBe('### Global Metadata\nslow');+ const [first, second] = fake!.requests;+ expect(first.body.model).toBe('test-model');+ expect(first.body.messages[0].role).toBe('system');+ expect(first.body.messages[0].content).toMatch(/^# skill body/);+ expect(first.body.messages[1]).toEqual({ role: 'user', content: 'Caption: sad piano\n\nLyrics:\n[Verse]\nla la' });+ expect(first.body.tools.map((t) => t.function.name)).toEqual(['read_file']);+ expect(first.auth).toBeUndefined();+ expect(second.body.messages.at(-1)).toMatchObject({ role: 'tool', tool_call_id: 'call_0_0', content: 'ROUTER' });+ });++ it('sends the bearer when a key is set', async () => {+ const { skill, llm } = await setup([{ content: 'ok' }], SKILL, 'k1');+ await enhancePrompt(input, llm, skill);+ expect(fake!.requests[0].auth).toBe('Bearer k1');+ });++ it('instrumental: states the constraint and leaves lyrics out', async () => {+ const { skill, llm } = await setup([{ content: 'ok' }]);+ await enhancePrompt({ ...input, instrumental: true }, llm, skill);+ expect(fake!.requests[0].body.messages[1].content).toBe('Caption: sad piano\n\nConstraints: instrumental — no vocals.');+ });++ it('refuses paths outside the skill without fetching them', async () => {+ const { skill, llm } = await setup([+ { toolCalls: [read('../secrets.md'), read('/etc/passwd'), read('templates/a.md'), read('scripts/x.txt'), { name: 'read_file', args: 'not json' }, { name: 'shell', args: {} }] },+ { content: 'ok' },+ ]);+ await enhancePrompt(input, llm, skill);+ const results = toolResults(1);+ expect(results).toHaveLength(6);+ for (const r of results.slice(0, 4)) expect(r).toMatch(/^error: .* is not a readable skill file/);+ expect(results[4]).toMatch(/^error: arguments must be JSON/);+ expect(results[5]).toBe('error: unknown tool shell');+ expect(fake!.skillRequests).toEqual(['SKILL.md']);+ });++ it('a missing skill file is a tool error, not a failure', async () => {+ const { skill, llm } = await setup([{ toolCalls: [read('./templates/nope_0001.txt')] }, { content: 'ok' }]);+ expect(await enhancePrompt(input, llm, skill)).toBe('ok');+ expect(toolResults(1)).toEqual(['error: file not found: templates/nope_0001.txt']);+ });++ it('caches skill files across runs', async () => {+ const { skill, llm, dir } = await setup([{ toolCalls: [read('templates/pop_0001.txt')] }, { content: 'ok' }, { toolCalls: [read('templates/pop_0001.txt')] }, { content: 'ok' }]);+ await enhancePrompt(input, llm, skill);+ await enhancePrompt(input, llm, skill);+ expect(fake!.skillRequests).toEqual(['SKILL.md', 'templates/pop_0001.txt']);+ expect(toolResults(3)).toEqual(['TEMPLATE']);+ expect(await fs.readFile(path.join(dir, 'skill-cache', 'templates', 'pop_0001.txt'), 'utf8')).toBe('TEMPLATE');+ });++ it('gives up after maxRounds tool rounds', async () => {+ const { skill, llm } = await setup([{ toolCalls: [read('references/genre-router.md')] }]);+ await expect(enhancePrompt(input, llm, skill, { maxRounds: 3 })).rejects.toMatchObject({ status: 502, message: expect.stringMatching(/did not finish within 3/) });+ expect(fake!.requests).toHaveLength(4);+ });++ it('LLM HTTP error → 502 with the upstream detail', async () => {+ const { skill, llm } = await setup([{ status: 500 }]);+ await expect(enhancePrompt(input, llm, skill)).rejects.toMatchObject({ status: 502, message: 'LLM error 500: fake llm failure' });+ });++ it('empty final answer → 502', async () => {+ const { skill, llm } = await setup([{ content: ' ' }]);+ await expect(enhancePrompt(input, llm, skill)).rejects.toMatchObject({ status: 502, message: expect.stringMatching(/empty/) });+ });++ it('timeout → 504', async () => {+ const { skill, llm } = await setup([{ content: 'late', delayMs: 500 }]);+ await expect(enhancePrompt(input, llm, skill, { timeoutMs: 50 })).rejects.toMatchObject({ status: 504 });+ });++ it('the timeout also covers skill file fetches', async () => {+ fake = await startFakeLlm([{ content: 'ok' }], SKILL, { skillDelayMs: 500 });+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'enhance-'));+ const skill = new SkillFiles(path.join(dir, 'skill-cache'), fake.skillUrl);+ await expect(enhancePrompt(input, { url: fake.url, apiKey: null, model: 'm' }, skill, { timeoutMs: 50 })).rejects.toMatchObject({ status: 504 });+ expect(fake.requests).toHaveLength(0);+ });++ it('unreachable LLM → 502', async () => {+ const { skill } = await setup([{ content: 'ok' }]);+ await expect(enhancePrompt(input, { url: 'http://127.0.0.1:1/v1', apiKey: null, model: 'm' }, skill)).rejects.toMatchObject({ status: 502, message: expect.stringMatching(/unreachable/) });+ });++ it('SKILL.md unavailable → 502 before calling the LLM', async () => {+ const { skill, llm } = await setup([{ content: 'ok' }], {});+ await expect(enhancePrompt(input, llm, skill)).rejects.toMatchObject({ status: 502, message: expect.stringMatching(/could not load the caption-rewriter skill/) });+ expect(fake!.requests).toHaveLength(0);+ });+});++describe('SkillFiles.isValidPath', () => {+ it('accepts only SKILL.md, references/*.md, templates/*.txt', () => {+ for (const ok of ['SKILL.md', 'references/genre-router.md', 'references/index-hip-hop-rap.md', 'templates/a-cappella-choral-pop_0001.txt']) expect(SkillFiles.isValidPath(ok)).toBe(true);+ for (const bad of ['../SKILL.md', 'README.md', 'references/../SKILL.md', 'references/x.txt', 'templates/X.txt', 'templates/sub/a.txt', 'agents/openai.yaml', '']) expect(SkillFiles.isValidPath(bad)).toBe(false);+ });+});diff --git a/server/test/fakeLlm.ts b/server/test/fakeLlm.tsnew file mode 100644index 0000000..cec3a6a--- /dev/null+++ b/server/test/fakeLlm.ts@@ -0,0 +1,77 @@+import express from 'express';+import type { Server } from 'node:http';++/** One scripted /v1/chat/completions answer. The last one repeats once the script runs out. */+export interface FakeLlmReply {+ content?: string | null;+ /** `args` is JSON-encoded unless already a string (lets tests send malformed arguments) */+ toolCalls?: { name: string; args: unknown }[];+ /** answer with this HTTP status and an error body instead */+ status?: number;+ delayMs?: number;+}++export interface FakeLlmRequest {+ auth?: string;+ body: {+ model: string;+ messages: { role: string; content: string | null; tool_call_id?: string }[];+ tools: { function: { name: string } }[];+ };+}++/**+ * Fake OpenAI-compatible chat endpoint plus a fake skill source:+ * `POST {url}/chat/completions` and `GET {skillUrl}/<path>` served from `files` (404 otherwise).+ */+export interface FakeLlm {+ url: string;+ skillUrl: string;+ requests: FakeLlmRequest[];+ skillRequests: string[];+ close(): Promise<void>;+}++export async function startFakeLlm(replies: FakeLlmReply[], files: Record<string, string> = {}, opts: { skillDelayMs?: number } = {}): Promise<FakeLlm> {+ const app = express();+ app.use(express.json({ limit: '10mb' }));+ const requests: FakeLlmRequest[] = [];+ const skillRequests: string[] = [];+ let n = 0;++ app.post('/v1/chat/completions', (req, res) => {+ requests.push({ auth: req.headers.authorization, body: req.body });+ const r = replies[Math.min(n, replies.length - 1)];+ const id = n++;+ const send = () => {+ if (r.status) return void res.status(r.status).json({ error: { message: 'fake llm failure' } });+ const toolCalls = r.toolCalls?.map((t, i) => ({+ id: `call_${id}_${i}`, type: 'function',+ function: { name: t.name, arguments: typeof t.args === 'string' ? t.args : JSON.stringify(t.args) },+ }));+ res.json({ choices: [{ index: 0, finish_reason: toolCalls ? 'tool_calls' : 'stop', message: { role: 'assistant', content: r.content ?? null, ...(toolCalls ? { tool_calls: toolCalls } : {}) } }] });+ };+ if (r.delayMs) setTimeout(send, r.delayMs); else send();+ });++ app.use('/skill', (req, res) => {+ const rel = req.path.slice(1);+ skillRequests.push(rel);+ const send = () => {+ if (Object.hasOwn(files, rel)) res.type('text/plain').send(files[rel]);+ else res.status(404).send('Not Found');+ };+ if (opts.skillDelayMs) setTimeout(send, opts.skillDelayMs); else send();+ });++ const server: Server = await new Promise((resolve) => { const s = app.listen(0, '127.0.0.1', () => resolve(s)); });+ const { port } = server.address() as { port: number };+ const base = `http://127.0.0.1:${port}`;+ return {+ url: `${base}/v1`,+ skillUrl: `${base}/skill`,+ requests,+ skillRequests,+ close: () => new Promise((resolve) => { server.closeAllConnections(); server.close(() => resolve()); }),+ };+}diff --git a/server/test/settings.test.ts b/server/test/settings.test.tsindex b5c6ce4..9e193dd 100644--- a/server/test/settings.test.ts+++ b/server/test/settings.test.ts@@ -20,6 +20,6 @@ describe('SettingsStore', () => {expect(error).toHaveBeenCalled();expect(writeFile).toHaveBeenCalledTimes(2);- expect(JSON.parse(await fs.readFile(file, 'utf8'))).toEqual({ musicApi: 'http://127.0.0.1:7862', apiKey: null, compat: true });+ expect(JSON.parse(await fs.readFile(file, 'utf8'))).toEqual({ musicApi: 'http://127.0.0.1:7862', apiKey: null, compat: true, llmApi: null, llmApiKey: null, llmModel: null });});});diff --git a/server/test/validate.test.ts b/server/test/validate.test.tsindex 27a5749..4a4c124 100644--- a/server/test/validate.test.ts+++ b/server/test/validate.test.ts@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest';-import { normalizeGenerate, ValidationError } from '../src/validate.js';+import { normalizeEnhance, normalizeGenerate, ValidationError } from '../src/validate.js';describe('normalizeGenerate', () => {it('rejects empty prompt', () => {@@ -32,3 +32,12 @@ describe('normalizeGenerate', () => {expect(normalizeGenerate({ prompt: 'x' }).format).toBe('wav');});});++describe('normalizeEnhance', () => {+ it('requires a prompt, trims, defaults lyrics and instrumental', () => {+ expect(() => normalizeEnhance({ prompt: ' ' })).toThrow(/prompt is required/);+ expect(() => normalizeEnhance(null)).toThrow(/object/);+ expect(normalizeEnhance({ prompt: ' a ', lyrics: ' [Verse] ', instrumental: true })).toEqual({ prompt: 'a', lyrics: '[Verse]', instrumental: true });+ expect(normalizeEnhance({ prompt: 'a', instrumental: 'yes' })).toEqual({ prompt: 'a', lyrics: '', instrumental: false });+ });+});diff --git a/web/src/api.ts b/web/src/api.tsindex 3123764..aa39b07 100644--- a/web/src/api.ts+++ b/web/src/api.ts@@ -17,13 +17,15 @@ export const api = {library: () => fetch('/api/library').then((r) => json<Track[]>(r)),generate: (input: GenerateInput) =>fetch('/api/generate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input) }).then((r) => json<Track[]>(r)),+ enhance: (input: { prompt: string; lyrics: string; instrumental: boolean }) =>+ fetch('/api/enhance', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input) }).then((r) => json<{ prompt: string }>(r)),deleteTrack: (id: string) => fetch(`/api/tracks/${id}`, { method: 'DELETE' }).then((r) => json<{ ok: true }>(r)),templates: () => fetch('/api/templates').then((r) => json<Template[]>(r)),saveTemplate: (t: Omit<Template, 'id' | 'createdAt'>) =>fetch('/api/templates', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(t) }).then((r) => json<Template>(r)),deleteTemplate: (id: string) => fetch(`/api/templates/${id}`, { method: 'DELETE' }).then((r) => json<{ ok: true }>(r)),settings: () => fetch('/api/settings').then((r) => json<Settings>(r)),- saveSettings: (patch: { musicApi?: string; apiKey?: string; compat?: boolean }) =>+ saveSettings: (patch: { musicApi?: string; apiKey?: string; compat?: boolean; llmApi?: string; llmApiKey?: string; llmModel?: string }) =>fetch('/api/settings', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(patch) }).then((r) => json<Settings>(r)),testSettings: (candidate: { musicApi?: string; apiKey?: string }) =>fetch('/api/settings/test', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(candidate) }).then((r) => json<SettingsTestResult>(r)),diff --git a/web/src/components/CreatePanel.tsx b/web/src/components/CreatePanel.tsxindex 6f43cec..6f35e48 100644--- a/web/src/components/CreatePanel.tsx+++ b/web/src/components/CreatePanel.tsx@@ -1,8 +1,9 @@-import { useMemo, useState } from 'react';+import { useMemo, useState, type Dispatch, type SetStateAction } from 'react';+import { api } from '../api';import type { GenerateInput, Health, Track } from '../types';import { LyricsEditor } from './LyricsEditor';import { TemplatesMenu, type TemplateValues } from './TemplatesMenu';-import { Chevron, Sparkle } from './Icons';+import { Chevron, Sparkle, Spinner, Wand } from './Icons';export const TEMPLATE_PROMPT = 'Genre: acoustic pop. BPM: 96. Key: C major. Warm and intimate, building gently into the chorus. Vocals: soft female lead, close and breathy, light stacked harmonies in the chorus. Arrangement: fingerpicked guitar and soft piano; brushed drums and upright bass enter in the chorus.';@@ -55,7 +56,7 @@ export function formFromTrack(t: Track): FormState {interface Props {health: Health | null;form: FormState;- onFormChange: (f: FormState) => void;+ onFormChange: Dispatch<SetStateAction<FormState>>;onSubmit: (input: GenerateInput) => Promise<void>;}@@ -63,6 +64,10 @@ export function CreatePanel({ health, form, onFormChange, onSubmit }: Props) {const [advanced, setAdvanced] = useState(false);const [submitting, setSubmitting] = useState(false);const [error, setError] = useState<string | null>(null);+ const [enhancing, setEnhancing] = useState(false);+ const [enhanceError, setEnhanceError] = useState<string | null>(null);+ /** prompt before the last enhance; offered as undo while the enhanced text is untouched */+ const [undo, setUndo] = useState<{ before: string; after: string } | null>(null);const set = <K extends keyof FormState>(k: K, v: FormState[K]) => onFormChange({ ...form, [k]: v });@@ -70,6 +75,8 @@ export function CreatePanel({ health, form, onFormChange, onSubmit }: Props) {const loading = online && !health!.ready;const canSubmit = online && !loading && form.prompt.trim().length > 0 && !submitting;const canStream = !!health?.capabilities?.includes('stream');+ const canEnhance = !!health?.enhance && form.prompt.trim().length > 0 && !enhancing;+ const enhanceTitle = health?.demo ? 'Not available in the demo' : !health?.enhance ? 'Set an LLM in Settings to enhance prompts' : 'Enhance prompt with MiniMax’s caption rewriter';const estMin = useMemo(() => Math.round((form.duration * 3 * form.takes) / 60 * 10) / 10, [form.duration, form.takes]);const submit = async () => {@@ -95,6 +102,21 @@ export function CreatePanel({ health, form, onFormChange, onSubmit }: Props) {}};+ const enhance = async () => {+ setEnhanceError(null);+ setEnhancing(true);+ try {+ const before = form.prompt;+ const { prompt } = await api.enhance({ prompt: before.trim(), lyrics: form.lyrics.trim(), instrumental: form.instrumental });+ setUndo({ before, after: prompt });+ onFormChange((f) => ({ ...f, prompt }));+ } catch (err) {+ setEnhanceError((err as Error).message);+ } finally {+ setEnhancing(false);+ }+ };+const modeBtn = (m: FormState['mode'], label: string, disabled = false) => (<buttontype="button"@@ -154,13 +176,33 @@ export function CreatePanel({ health, form, onFormChange, onSubmit }: Props) {})}/></div>- <textarea- rows={form.mode === 'simple' ? 6 : 5}- value={form.prompt}- onChange={(e) => set('prompt', e.target.value)}- className="field resize-y leading-relaxed"- placeholder={TEMPLATE_PROMPT}- />+ <div className="relative">+ <textarea+ rows={form.mode === 'simple' ? 6 : 5}+ value={form.prompt}+ readOnly={enhancing}+ onChange={(e) => set('prompt', e.target.value)}+ className={`field resize-y leading-relaxed pr-10 ${enhancing ? 'opacity-60' : ''}`}+ placeholder={TEMPLATE_PROMPT}+ />+ <button+ type="button"+ aria-label="Enhance prompt"+ title={enhanceTitle}+ disabled={!canEnhance}+ onClick={() => void enhance()}+ className="absolute top-2 right-2 p-1.5 rounded-md text-zinc-400 hover:text-accent hover:bg-ink-700 transition disabled:opacity-40 disabled:hover:bg-transparent disabled:hover:text-zinc-400"+ >+ {enhancing ? <Spinner width={16} height={16} /> : <Wand width={16} height={16} />}+ </button>+ </div>+ {enhanceError && <div className="text-xs text-red-400 mt-1">Enhance failed: {enhanceError}</div>}+ {enhancing && <div className="text-[11px] text-zinc-500 mt-1">Rewriting with MiniMax’s caption rewriter… this can take a minute.</div>}+ {undo && !enhancing && form.prompt === undo.after && (+ <button type="button" className="text-[11px] text-zinc-400 hover:text-white mt-1" onClick={() => { onFormChange((f) => ({ ...f, prompt: undo.before })); setUndo(null); }}>+ Undo enhance+ </button>+ )}</div>{!form.instrumental && (diff --git a/web/src/components/Icons.tsx b/web/src/components/Icons.tsxindex cc60d96..68001a8 100644--- a/web/src/components/Icons.tsx+++ b/web/src/components/Icons.tsx@@ -13,6 +13,7 @@ export const Trash = (p: SVGProps<SVGSVGElement>) => <svg {...base(p)}><path d="export const Refresh = (p: SVGProps<SVGSVGElement>) => <svg {...base(p)}><path d="M20 12a8 8 0 1 1-2.3-5.7M20 4v5h-5" /></svg>;export const Reuse = (p: SVGProps<SVGSVGElement>) => <svg {...base(p)}><path d="M4 12V8a2 2 0 0 1 2-2h12M4 12l3-3M4 12l3 3M20 12v4a2 2 0 0 1-2 2H6m14-6l-3-3m3 3l-3 3" /></svg>;export const Sparkle = (p: SVGProps<SVGSVGElement>) => <svg {...base(p)}><path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8zM19 16l.8 2.2L22 19l-2.2.8L19 22l-.8-2.2L16 19l2.2-.8z" /></svg>;+export const Wand = (p: SVGProps<SVGSVGElement>) => <svg {...base(p)}><path d="M15 4V2M15 16v-2M8 9h2M20 9h2M17.8 11.8L19 13M15 9h.01M17.8 6.2L19 5M3 21l9-9M12.2 6.2L11 5" /></svg>;export const Music = (p: SVGProps<SVGSVGElement>) => <svg {...base(p)}><path d="M9 18V6l10-2v12M9 18a3 3 0 1 1-6 0 3 3 0 0 1 6 0zm10-2a3 3 0 1 1-6 0 3 3 0 0 1 6 0z" /></svg>;export const Library = (p: SVGProps<SVGSVGElement>) => <svg {...base(p)}><path d="M4 4h4v16H4zM10 4h4v16h-4zM16 5l4-1v16l-4 1z" /></svg>;export const X = (p: SVGProps<SVGSVGElement>) => <svg {...base(p)}><path d="M6 6l12 12M18 6L6 18" /></svg>;diff --git a/web/src/components/SettingsPanel.tsx b/web/src/components/SettingsPanel.tsxindex 8eed31f..f7cc8fb 100644--- a/web/src/components/SettingsPanel.tsx+++ b/web/src/components/SettingsPanel.tsx@@ -8,10 +8,15 @@ export function SettingsPanel({ onSaved, demo = false }: { onSaved: () => void;const [musicApi, setMusicApi] = useState('');const [apiKey, setApiKey] = useState('');const [clearKey, setClearKey] = useState(false);- const [busy, setBusy] = useState<'save' | 'test' | null>(null);+ const [busy, setBusy] = useState<'save' | 'test' | 'llm' | null>(null);const [test, setTest] = useState<SettingsTestResult | null>(null);const [msg, setMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null);const [compatMsg, setCompatMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null);+ const [llmApi, setLlmApi] = useState('');+ const [llmModel, setLlmModel] = useState('');+ const [llmKey, setLlmKey] = useState('');+ const [clearLlmKey, setClearLlmKey] = useState(false);+ const [llmMsg, setLlmMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null);const load = async () => {const s = await api.settings();@@ -19,6 +24,10 @@ export function SettingsPanel({ onSaved, demo = false }: { onSaved: () => void;setMusicApi(s.musicApi);setApiKey('');setClearKey(false);+ setLlmApi(s.llmApi ?? '');+ setLlmModel(s.llmModel ?? '');+ setLlmKey('');+ setClearLlmKey(false);};useEffect(() => { load().catch((e) => setMsg({ kind: 'err', text: (e as Error).message })); }, []);@@ -26,6 +35,26 @@ export function SettingsPanel({ onSaved, demo = false }: { onSaved: () => void;const dirty = musicApi.trim() !== settings.musicApi || apiKey !== '' || clearKey;const keyPatch = () => (clearKey ? '' : apiKey.trim() ? apiKey.trim() : undefined);+ const llmDirty = llmApi.trim() !== (settings.llmApi ?? '') || llmModel.trim() !== (settings.llmModel ?? '') || llmKey !== '' || clearLlmKey;++ const saveLlm = async () => {+ setBusy('llm'); setLlmMsg(null);+ try {+ const patch: { llmApi?: string; llmApiKey?: string; llmModel?: string } = {};+ if (!settings.locked.llmApi && llmApi.trim() !== (settings.llmApi ?? '')) patch.llmApi = llmApi.trim();+ if (!settings.locked.llmModel && llmModel.trim() !== (settings.llmModel ?? '')) patch.llmModel = llmModel.trim();+ const k = clearLlmKey ? '' : llmKey.trim() ? llmKey.trim() : undefined;+ if (!settings.locked.llmApiKey && k !== undefined) patch.llmApiKey = k;+ const s = await api.saveSettings(patch);+ setSettings(s); setLlmApi(s.llmApi ?? ''); setLlmModel(s.llmModel ?? ''); setLlmKey(''); setClearLlmKey(false);+ setLlmMsg({ kind: 'ok', text: s.llmApi && s.llmModel ? 'Saved. The magic wand on the prompt field is ready.' : 'Saved. Set both URL and model to enable the magic wand.' });+ onSaved();+ } catch (e) {+ setLlmMsg({ kind: 'err', text: (e as Error).message });+ } finally {+ setBusy(null);+ }+ };const doTest = async () => {setBusy('test'); setTest(null); setMsg(null);@@ -157,6 +186,69 @@ export function SettingsPanel({ onSaved, demo = false }: { onSaved: () => void;{msg && <div className={`text-xs ${msg.kind === 'ok' ? 'text-emerald-300' : 'text-red-400'}`}>{msg.text}</div>}</section>+ <section className="space-y-4">+ <div>+ <h2 className="text-sm font-semibold">Prompt enhancement</h2>+ <p className="text-xs text-zinc-500 mt-1">+ The magic wand on the prompt field rewrites your description with MiniMax's <code className="text-zinc-300">music-caption-rewriter</code> skill, run on any OpenAI-compatible chat model with tool calling (OpenAI, OpenRouter, Ollama, vLLM, LM Studio…). Skill files are fetched from MiniMax's GitHub on first use and cached in <code className="text-zinc-300">data/skill-cache/</code>. <code className="text-zinc-300">LLM_API</code> / <code className="text-zinc-300">LLM_API_KEY</code> / <code className="text-zinc-300">LLM_MODEL</code> from the environment override and lock these fields.+ </p>+ </div>++ <div>+ <div className="flex items-center justify-between mb-1">+ <label className="label" htmlFor="llmApi">LLM base URL</label>+ <span className="text-[10px] text-zinc-500 flex items-center gap-1">+ {settings.locked.llmApi && <Lock width={11} height={11} />}+ {sourceLabel(settings.source.llmApi)}+ </span>+ </div>+ <input id="llmApi" className="field font-mono disabled:opacity-60" value={llmApi} disabled={settings.locked.llmApi} onChange={(e) => setLlmApi(e.target.value)} placeholder="https://api.openai.com/v1 · http://localhost:11434/v1" spellCheck={false} />+ </div>++ <div>+ <div className="flex items-center justify-between mb-1">+ <label className="label" htmlFor="llmModel">Model</label>+ <span className="text-[10px] text-zinc-500 flex items-center gap-1">+ {settings.locked.llmModel && <Lock width={11} height={11} />}+ {sourceLabel(settings.source.llmModel)}+ </span>+ </div>+ <input id="llmModel" className="field font-mono disabled:opacity-60" value={llmModel} disabled={settings.locked.llmModel} onChange={(e) => setLlmModel(e.target.value)} placeholder="gpt-4.1-mini · qwen3:14b" spellCheck={false} />+ </div>++ <div>+ <div className="flex items-center justify-between mb-1">+ <label className="label" htmlFor="llmKey">API key <span className="text-zinc-600 normal-case tracking-normal">(optional)</span></label>+ <span className="text-[10px] text-zinc-500 flex items-center gap-1">+ {settings.locked.llmApiKey && <Lock width={11} height={11} />}+ {sourceLabel(settings.source.llmApiKey)}+ </span>+ </div>+ <div className="flex gap-2">+ <input+ id="llmKey"+ type="password"+ className="field font-mono disabled:opacity-60"+ value={llmKey}+ disabled={settings.locked.llmApiKey || clearLlmKey}+ onChange={(e) => setLlmKey(e.target.value)}+ placeholder={settings.locked.llmApiKey ? '•••••••• (from environment)' : settings.llmKeySet ? '•••••••• (saved — enter a new key to replace)' : 'Not needed for local servers like Ollama'}+ autoComplete="off"+ />+ {settings.llmKeySet && !settings.locked.llmApiKey && (+ <button type="button" className={`btn-ghost text-xs shrink-0 ${clearLlmKey ? 'bg-ink-700 text-white' : ''}`} onClick={() => { setClearLlmKey((c) => !c); setLlmKey(''); }}>+ {clearLlmKey ? 'Will clear' : 'Clear key'}+ </button>+ )}+ </div>+ </div>++ <div className="flex items-center gap-2 pt-1">+ <button type="button" className="btn-primary" disabled={busy !== null || !llmDirty} onClick={() => void saveLlm()}>{busy === 'llm' ? 'Saving…' : 'Save'}</button>+ </div>+ {llmMsg && <div className={`text-xs ${llmMsg.kind === 'ok' ? 'text-emerald-300' : 'text-red-400'}`}>{llmMsg.text}</div>}+ </section>+<section className="space-y-3"><h2 className="text-sm font-semibold">Debugging</h2><label className="flex items-start gap-3 text-xs text-zinc-400 cursor-pointer">diff --git a/web/src/types.ts b/web/src/types.tsindex a8b8e06..54397d6 100644--- a/web/src/types.ts+++ b/web/src/types.ts@@ -37,6 +37,8 @@ export interface Health {models?: string[];/** optional upstream extras, e.g. "stream" (live progress + play-while-rendering) */capabilities?: string[];+ /** an LLM is configured, so the prompt can be rewritten with MiniMax's caption-rewriter skill */+ enhance?: boolean;error?: string;}@@ -66,8 +68,15 @@ export interface Settings {apiKeySet: boolean;/** debug/testing: treat the server as stock sgl-omni (no /health, no streaming) */compat: boolean;- source: { musicApi: 'env' | 'settings' | 'default'; apiKey: 'env' | 'settings' | 'none' };- locked: { musicApi: boolean; apiKey: boolean };+ /** OpenAI-compatible LLM for prompt enhancement */+ llmApi: string | null;+ llmModel: string | null;+ llmKeySet: boolean;+ source: {+ musicApi: 'env' | 'settings' | 'default'; apiKey: 'env' | 'settings' | 'none';+ llmApi: 'env' | 'settings' | 'none'; llmApiKey: 'env' | 'settings' | 'none'; llmModel: 'env' | 'settings' | 'none';+ };+ locked: { musicApi: boolean; apiKey: boolean; llmApi: boolean; llmApiKey: boolean; llmModel: boolean };}export interface SettingsTestResult {