Skip to content

Suno-style web UI for a self-hosted MiniMax-Music3 inference server

feat: lyrics wand writes lyrics from the song description

Adam Benhassena95f73331b83
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a3c445e..0dd27f2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,9 @@
# Changelog
+## Unreleased
+
+- Lyrics writing: a wand on the lyrics field writes original lyrics from the song description, sized to the duration, with the model's section tags; undo restores the previous lyrics. Uses the prompt-enhancement LLM; hidden for instrumentals, disabled in the demo.
+
## v0.1.2 — 2026-09-26
### Fixes
diff --git a/README.md b/README.md
index ac448f2..96fd813 100644
--- a/README.md
+++ b/README.md
@@ -32,6 +32,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.
+- **Lyrics writing** — a second wand on the lyrics field writes original lyrics from the song description with the same LLM, sized to the chosen duration and using the model's section tags (`[Verse]`, `[Chorus]`, …). It replaces the current lyrics; Undo restores them. Hidden for instrumentals.
- **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".
@@ -164,6 +165,7 @@ docker run --read-only -p 8787:8787 minimax-music-ui-demo
| `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/lyrics` | `{prompt, duration?}` → `{lyrics}` written from the description and sized to the duration; 409 until an LLM is configured, 502/504 on LLM failure or timeout |
| `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 |
diff --git a/server/src/app.ts b/server/src/app.ts
index 3073636..d49a37e 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 { normalizeEnhance, normalizeGenerate, ValidationError } from './validate.js';
+import { normalizeEnhance, normalizeGenerate, normalizeLyrics, ValidationError } from './validate.js';
+import { writeLyrics } from './lyrics.js';
import { EnhanceError, enhancePrompt, type SkillFiles } from './enhance.js';
import { normalizeMusicApi, SettingsStore } from './settings.js';
import { randomTitle } from './names.js';
@@ -126,6 +127,17 @@ export function createApp(deps: AppDeps) {
}
});
+ app.post('/api/lyrics', async (req, res, next) => {
+ try {
+ const input = normalizeLyrics(req.body);
+ const llm = settings.llm();
+ if (!llm) return res.status(409).json({ error: 'Lyrics writing is not configured — set an LLM in Settings' });
+ res.json({ lyrics: await writeLyrics(input, llm) });
+ } 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' });
diff --git a/server/src/demo.ts b/server/src/demo.ts
index c5812f8..2aab1f0 100644
--- a/server/src/demo.ts
+++ b/server/src/demo.ts
@@ -154,6 +154,7 @@ export function demoRouter(library: Library, tracksDir: string, opts: DemoOption
r.post('/api/settings/test', readOnly);
r.post('/api/templates', readOnly);
r.post('/api/enhance', readOnly);
+ r.post('/api/lyrics', readOnly);
r.delete('/api/templates/:id', readOnly);
return r;
diff --git a/server/src/enhance.ts b/server/src/enhance.ts
index 668ec04..6d14437 100644
--- a/server/src/enhance.ts
+++ b/server/src/enhance.ts
@@ -97,7 +97,8 @@ async function runTool(call: ToolCall, skill: SkillFiles, signal: AbortSignal):
}
}
-async function complete(llm: LlmConfig, messages: ChatMessage[], signal: AbortSignal): Promise<ChatMessage> {
+/** One OpenAI-compatible chat completion; failures map to EnhanceError (502, or 504 once `signal` times out). */
+export async function chatComplete(llm: LlmConfig, messages: ChatMessage[], signal: AbortSignal, tools?: unknown[]): 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;
@@ -105,7 +106,7 @@ async function complete(llm: LlmConfig, messages: ChatMessage[], signal: AbortSi
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 }),
+ body: JSON.stringify({ model: llm.model, messages, ...(tools ? { tools } : {}) }),
signal,
});
} catch (err) {
@@ -154,7 +155,7 @@ export async function enhancePrompt(input: EnhanceRequest, llm: LlmConfig, skill
{ role: 'user', content: userMessage(input) },
];
for (let round = 0; ; round++) {
- const msg = await complete(llm, messages, signal);
+ const msg = await chatComplete(llm, messages, signal, TOOLS);
if (!msg.tool_calls?.length) {
const caption = (msg.content ?? '').trim();
if (!caption) throw new EnhanceError('the LLM returned an empty caption', 502);
diff --git a/server/src/lyrics.ts b/server/src/lyrics.ts
new file mode 100644
index 0000000..0538a16
--- /dev/null
+++ b/server/src/lyrics.ts
@@ -0,0 +1,29 @@
+import { chatComplete, EnhanceError } from './enhance.js';
+import type { LlmConfig, LyricsRequest } from './types.js';
+
+const SYSTEM = `You write original song lyrics for MiniMax Music 3, a text-to-music model that sings them.
+
+Rules:
+- Reply with only the lyrics: section tags on their own lines, sung lines below each. No title, notes, markdown or code fences.
+- Use only these tags, spelled exactly: [Intro] [Verse] [Pre-Chorus] [Chorus] [Post-Chorus] [Bridge] [Instrumental] [Solo] [Outro]. [Intro], [Instrumental] and [Solo] may stand alone without sung lines.
+- Fit the target length: about the number of sung lines given, in a structure that suits it. A short song is one verse and one chorus; longer songs repeat the chorus and may add a pre-chorus, bridge and outro.
+- Match the description's genre, mood, story and vocal style. If it has an Arrangement section, follow its section order.
+- Write in the language the description asks for; otherwise English.
+- Be original: never reproduce or closely paraphrase existing lyrics, even if the description names an artist or song. Capture the style only.`;
+
+/** Sung-line budget for a song of `duration` seconds (~5 s per line, leaving room for instrumental parts). */
+export function lyricLines(duration: number): number {
+ return Math.max(4, Math.round(duration / 5));
+}
+
+/** Write original lyrics for a song description, sized to its duration: one plain chat call, no tools. */
+export async function writeLyrics(input: LyricsRequest, llm: LlmConfig, opts: { timeoutMs?: number } = {}): Promise<string> {
+ const signal = AbortSignal.timeout(opts.timeoutMs ?? 120_000);
+ const msg = await chatComplete(llm, [
+ { role: 'system', content: SYSTEM },
+ { role: 'user', content: `Song description:\n${input.prompt}\n\nTarget length: ${input.duration} s — about ${lyricLines(input.duration)} sung lines in total.` },
+ ], signal);
+ const lyrics = (msg.content ?? '').trim().replace(/^```[^\n]*\n([\s\S]*?)\n?```$/, '$1').trim();
+ if (!lyrics) throw new EnhanceError('the LLM returned no lyrics', 502);
+ return lyrics;
+}
diff --git a/server/src/types.ts b/server/src/types.ts
index 7d0e7fa..cc9a4b4 100644
--- a/server/src/types.ts
+++ b/server/src/types.ts
@@ -65,3 +65,9 @@ export interface EnhanceRequest {
lyrics: string;
instrumental: boolean;
}
+
+export interface LyricsRequest {
+ prompt: string;
+ /** seconds; sizes the lyrics */
+ duration: number;
+}
diff --git a/server/src/validate.ts b/server/src/validate.ts
index ab2a548..b708746 100644
--- a/server/src/validate.ts
+++ b/server/src/validate.ts
@@ -1,4 +1,4 @@
-import { FORMATS, type EnhanceRequest, type GenerateRequest } from './types.js';
+import { FORMATS, type EnhanceRequest, type GenerateRequest, type LyricsRequest } from './types.js';
export class ValidationError extends Error {
status = 400;
@@ -51,3 +51,13 @@ export function normalizeEnhance(body: unknown): EnhanceRequest {
const lyrics = typeof b.lyrics === 'string' ? b.lyrics.trim() : '';
return { prompt, lyrics, instrumental: b.instrumental === true };
}
+
+export function normalizeLyrics(body: unknown): LyricsRequest {
+ 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 durationRaw = b.duration === undefined ? 60 : Number(b.duration);
+ if (!Number.isFinite(durationRaw)) throw new ValidationError('duration must be a number');
+ return { prompt, duration: clamp(Math.round(durationRaw), 5, 360) };
+}
diff --git a/server/test/app.test.ts b/server/test/app.test.ts
index 067fe35..93b050d 100644
--- a/server/test/app.test.ts
+++ b/server/test/app.test.ts
@@ -275,6 +275,20 @@ describe('app', () => {
expect(fake!.requests.some((r) => r.path.includes('speech'))).toBe(false);
});
+ it('lyrics: 400 without a prompt, 409 until an LLM is configured, then returns lyrics', async () => {
+ const { app } = await setup();
+ expect((await request(app).post('/api/lyrics').send({ prompt: '' })).status).toBe(400);
+ const off = await request(app).post('/api/lyrics').send({ prompt: 'night drive', duration: 30 });
+ expect(off.status).toBe(409);
+ expect(off.body.error).toMatch(/not configured/);
+ llm = await startFakeLlm([{ content: '[Verse]\nNeon' }]);
+ await request(app).put('/api/settings').send({ llmApi: llm.url, llmModel: 'm' });
+ const on = await request(app).post('/api/lyrics').send({ prompt: 'night drive', duration: 30 });
+ expect(on.status).toBe(200);
+ expect(on.body).toEqual({ lyrics: '[Verse]\nNeon' });
+ expect(llm.requests[0].body.messages[1].content).toContain('Target length: 30 s');
+ });
+
it('enhance: LLM failure maps to 502 with the reason', async () => {
const { app, dir } = await setup();
await seedSkill(dir);
diff --git a/server/test/demo.test.ts b/server/test/demo.test.ts
index 45abe4a..8fb104f 100644
--- a/server/test/demo.test.ts
+++ b/server/test/demo.test.ts
@@ -55,6 +55,7 @@ describe('demo mode', () => {
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/lyrics').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.ts
index 6cef6db..22c2713 100644
--- a/server/test/enhance.test.ts
+++ b/server/test/enhance.test.ts
@@ -32,7 +32,7 @@ describe('enhancePrompt', () => {
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.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' });
});
diff --git a/server/test/fakeLlm.ts b/server/test/fakeLlm.ts
index cec3a6a..e8a798d 100644
--- a/server/test/fakeLlm.ts
+++ b/server/test/fakeLlm.ts
@@ -16,7 +16,7 @@ export interface FakeLlmRequest {
body: {
model: string;
messages: { role: string; content: string | null; tool_call_id?: string }[];
- tools: { function: { name: string } }[];
+ tools?: { function: { name: string } }[];
};
}
diff --git a/server/test/lyrics.test.ts b/server/test/lyrics.test.ts
new file mode 100644
index 0000000..e75df67
--- /dev/null
+++ b/server/test/lyrics.test.ts
@@ -0,0 +1,52 @@
+import { describe, it, expect, afterEach } from 'vitest';
+import { lyricLines, writeLyrics } from '../src/lyrics.js';
+import { startFakeLlm, type FakeLlm, type FakeLlmReply } from './fakeLlm.js';
+
+let fake: FakeLlm | null = null;
+afterEach(async () => { await fake?.close(); fake = null; });
+
+const input = { prompt: 'dreamy synth-pop about a night drive', duration: 60 };
+const setup = async (replies: FakeLlmReply[]) => {
+ fake = await startFakeLlm(replies);
+ return { url: fake.url, apiKey: null, model: 'test-model' };
+};
+
+describe('writeLyrics', () => {
+ it('sends one plain chat call (no tools) with the description and a line budget', async () => {
+ const llm = await setup([{ content: ' [Verse]\nNeon on the highway\n[Chorus]\nDrive ' }]);
+ expect(await writeLyrics(input, llm)).toBe('[Verse]\nNeon on the highway\n[Chorus]\nDrive');
+ const { body } = fake!.requests[0];
+ expect(body.model).toBe('test-model');
+ expect(body.tools).toBeUndefined();
+ expect(body.messages[0].role).toBe('system');
+ expect(body.messages[0].content).toContain('[Pre-Chorus]');
+ expect(body.messages[0].content).toMatch(/never reproduce/i);
+ expect(body.messages[1]).toEqual({ role: 'user', content: 'Song description:\ndreamy synth-pop about a night drive\n\nTarget length: 60 s — about 12 sung lines in total.' });
+ });
+
+ it('strips a code fence wrapped around the lyrics', async () => {
+ const llm = await setup([{ content: '```text\n[Verse]\nla\n```' }]);
+ expect(await writeLyrics(input, llm)).toBe('[Verse]\nla');
+ });
+
+ it('empty answer → 502', async () => {
+ const llm = await setup([{ content: ' ' }]);
+ await expect(writeLyrics(input, llm)).rejects.toMatchObject({ status: 502, message: 'the LLM returned no lyrics' });
+ });
+
+ it('LLM error → 502 with the reason', async () => {
+ const llm = await setup([{ status: 500 }]);
+ await expect(writeLyrics(input, llm)).rejects.toMatchObject({ status: 502, message: 'LLM error 500: fake llm failure' });
+ });
+
+ it('timeout → 504', async () => {
+ const llm = await setup([{ content: 'late', delayMs: 500 }]);
+ await expect(writeLyrics(input, llm, { timeoutMs: 50 })).rejects.toMatchObject({ status: 504 });
+ });
+});
+
+describe('lyricLines', () => {
+ it('scales with duration, never below 4', () => {
+ expect([5, 30, 60, 180, 360].map(lyricLines)).toEqual([4, 6, 12, 36, 72]);
+ });
+});
diff --git a/server/test/validate.test.ts b/server/test/validate.test.ts
index 4a4c124..5baa042 100644
--- a/server/test/validate.test.ts
+++ b/server/test/validate.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { normalizeEnhance, normalizeGenerate, ValidationError } from '../src/validate.js';
+import { normalizeEnhance, normalizeGenerate, normalizeLyrics, ValidationError } from '../src/validate.js';
describe('normalizeGenerate', () => {
it('rejects empty prompt', () => {
@@ -41,3 +41,13 @@ describe('normalizeEnhance', () => {
expect(normalizeEnhance({ prompt: 'a', instrumental: 'yes' })).toEqual({ prompt: 'a', lyrics: '', instrumental: false });
});
});
+
+describe('normalizeLyrics', () => {
+ it('requires a prompt; clamps and defaults the duration', () => {
+ expect(() => normalizeLyrics({ prompt: ' ' })).toThrow(/prompt is required/);
+ expect(() => normalizeLyrics({ prompt: 'a', duration: 'x' })).toThrow(/duration must be a number/);
+ expect(normalizeLyrics({ prompt: ' a ' })).toEqual({ prompt: 'a', duration: 60 });
+ expect(normalizeLyrics({ prompt: 'a', duration: 999 })).toEqual({ prompt: 'a', duration: 360 });
+ expect(normalizeLyrics({ prompt: 'a', duration: 1 })).toEqual({ prompt: 'a', duration: 5 });
+ });
+});
diff --git a/web/src/api.ts b/web/src/api.ts
index aa39b07..c0ec2a6 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -19,6 +19,8 @@ export const api = {
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)),
+ lyrics: (input: { prompt: string; duration: number }) =>
+ fetch('/api/lyrics', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input) }).then((r) => json<{ lyrics: 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'>) =>
diff --git a/web/src/components/CreatePanel.tsx b/web/src/components/CreatePanel.tsx
index 6f35e48..095890f 100644
--- a/web/src/components/CreatePanel.tsx
+++ b/web/src/components/CreatePanel.tsx
@@ -68,6 +68,10 @@ export function CreatePanel({ health, form, onFormChange, onSubmit }: Props) {
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 [writingLyrics, setWritingLyrics] = useState(false);
+ const [lyricsError, setLyricsError] = useState<string | null>(null);
+ /** lyrics before the last write; offered as undo while the written text is untouched */
+ const [lyricsUndo, setLyricsUndo] = useState<{ before: string; after: string } | null>(null);
const set = <K extends keyof FormState>(k: K, v: FormState[K]) => onFormChange({ ...form, [k]: v });
@@ -75,8 +79,11 @@ 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;
+ // the wands read each other's field, so they never run at once
+ const canEnhance = !!health?.enhance && form.prompt.trim().length > 0 && !enhancing && !writingLyrics;
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 canWriteLyrics = !!health?.enhance && form.prompt.trim().length > 0 && !writingLyrics && !enhancing;
+ const lyricsTitle = health?.demo ? 'Not available in the demo' : !health?.enhance ? 'Set an LLM in Settings to write lyrics' : !form.prompt.trim() ? 'Describe the song first' : 'Write lyrics from the song description';
const estMin = useMemo(() => Math.round((form.duration * 3 * form.takes) / 60 * 10) / 10, [form.duration, form.takes]);
const submit = async () => {
@@ -117,6 +124,21 @@ export function CreatePanel({ health, form, onFormChange, onSubmit }: Props) {
}
};
+ const writeLyrics = async () => {
+ setLyricsError(null);
+ setWritingLyrics(true);
+ try {
+ const before = form.lyrics;
+ const { lyrics } = await api.lyrics({ prompt: form.prompt.trim(), duration: form.duration });
+ setLyricsUndo({ before, after: lyrics });
+ onFormChange((f) => ({ ...f, lyrics }));
+ } catch (err) {
+ setLyricsError((err as Error).message);
+ } finally {
+ setWritingLyrics(false);
+ }
+ };
+
const modeBtn = (m: FormState['mode'], label: string, disabled = false) => (
<button
type="button"
@@ -185,16 +207,7 @@ export function CreatePanel({ health, form, onFormChange, onSubmit }: Props) {
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>
+ <WandButton label="Enhance prompt" title={enhanceTitle} busy={enhancing} disabled={!canEnhance} onClick={() => void enhance()} />
</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>}
@@ -208,7 +221,20 @@ export function CreatePanel({ health, form, onFormChange, onSubmit }: Props) {
{!form.instrumental && (
<div>
<div className="label mb-1">Lyrics</div>
- <LyricsEditor value={form.lyrics} onChange={(v) => set('lyrics', v)} rows={form.mode === 'simple' ? 6 : 10} />
+ <LyricsEditor
+ value={form.lyrics}
+ onChange={(v) => set('lyrics', v)}
+ rows={form.mode === 'simple' ? 6 : 10}
+ readOnly={writingLyrics}
+ action={<WandButton label="Write lyrics" title={lyricsTitle} busy={writingLyrics} disabled={!canWriteLyrics} onClick={() => void writeLyrics()} />}
+ />
+ {lyricsError && <div className="text-xs text-red-400 mt-1">Writing lyrics failed: {lyricsError}</div>}
+ {writingLyrics && <div className="text-[11px] text-zinc-500 mt-1">Writing lyrics for a {form.duration}s song…</div>}
+ {lyricsUndo && !writingLyrics && form.lyrics === lyricsUndo.after && (
+ <button type="button" className="text-[11px] text-zinc-400 hover:text-white mt-1" onClick={() => { onFormChange((f) => ({ ...f, lyrics: lyricsUndo.before })); setLyricsUndo(null); }}>
+ Undo lyrics
+ </button>
+ )}
</div>
)}
@@ -276,3 +302,18 @@ export function CreatePanel({ health, form, onFormChange, onSubmit }: Props) {
</div>
);
}
+
+function WandButton({ label, title, busy, disabled, onClick }: { label: string; title: string; busy: boolean; disabled: boolean; onClick: () => void }) {
+ return (
+ <button
+ type="button"
+ aria-label={label}
+ title={title}
+ disabled={disabled}
+ onClick={onClick}
+ 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"
+ >
+ {busy ? <Spinner width={16} height={16} /> : <Wand width={16} height={16} />}
+ </button>
+ );
+}
diff --git a/web/src/components/LyricsEditor.tsx b/web/src/components/LyricsEditor.tsx
index ee6ef09..cf2dcf3 100644
--- a/web/src/components/LyricsEditor.tsx
+++ b/web/src/components/LyricsEditor.tsx
@@ -1,8 +1,9 @@
-import { useRef } from 'react';
+import { useRef, type ReactNode } from 'react';
const TAGS = ['Intro', 'Verse', 'Pre-Chorus', 'Chorus', 'Bridge', 'Outro', 'Instrumental'];
-export function LyricsEditor({ value, onChange, rows = 10 }: { value: string; onChange: (v: string) => void; rows?: number }) {
+/** `action` renders at the textarea's top-right corner (e.g. a wand button); `readOnly` locks the text and the tag chips, and dims them. */
+export function LyricsEditor({ value, onChange, rows = 10, action, readOnly = false }: { value: string; onChange: (v: string) => void; rows?: number; action?: ReactNode; readOnly?: boolean }) {
const ref = useRef<HTMLTextAreaElement>(null);
const insertTag = (tag: string) => {
@@ -25,17 +26,21 @@ export function LyricsEditor({ value, onChange, rows = 10 }: { value: string; on
<div className="space-y-2">
<div className="flex flex-wrap gap-1.5">
{TAGS.map((t) => (
- <button key={t} type="button" className="chip" onClick={() => insertTag(t)}>[{t}]</button>
+ <button key={t} type="button" className="chip disabled:opacity-40" disabled={readOnly} onClick={() => insertTag(t)}>[{t}]</button>
))}
</div>
- <textarea
- ref={ref}
- rows={rows}
- value={value}
- onChange={(e) => onChange(e.target.value)}
- className="field font-mono text-[13px] leading-relaxed resize-y"
- placeholder={'[Verse]\nMorning light filtering through the pine\nEvery quiet street is yours and mine\n[Chorus]\nSoftly the world begins to breathe\n\nLeave empty for an instrumental.'}
- />
+ <div className="relative">
+ <textarea
+ ref={ref}
+ rows={rows}
+ value={value}
+ readOnly={readOnly}
+ onChange={(e) => onChange(e.target.value)}
+ className={`field font-mono text-[13px] leading-relaxed resize-y ${action ? 'pr-10' : ''} ${readOnly ? 'opacity-60' : ''}`}
+ placeholder={'[Verse]\nMorning light filtering through the pine\nEvery quiet street is yours and mine\n[Chorus]\nSoftly the world begins to breathe\n\nLeave empty for an instrumental.'}
+ />
+ {action}
+ </div>
</div>
);
}