Suno-style web UI for a self-hosted MiniMax-Music3 inference server
TypeScript ai-musicdiffusersdockerexpressminimaxminimax-musicmusic-generationreactself-hostedsgl-omnisunotailwindcsstext-to-musictypescriptvite
refactor: target the standard MiniMax-Music3 API (POST /v1/audio/speech)
Adam Benhassen356377960e91
diff --git a/README.md b/README.mdindex 4f1d961..f543a21 100644--- a/README.md+++ b/README.md@@ -3,8 +3,9 @@</p><p align="center">- A Suno-style web interface for a self-hosted <a href="https://huggingface.co/MiniMaxAI/MiniMax-Music3">MiniMax-Music3</a> inference server.<br>- Write a style prompt and lyrics, queue takes, watch them render, and keep a local library with a waveform player.+ A Suno-style web interface for any self-hosted <a href="https://huggingface.co/MiniMaxAI/MiniMax-Music3">MiniMax-Music3</a> server.<br>+ Write a style prompt and lyrics, queue takes, watch them render, and keep a local library with a waveform player.<br>+ Talks the standard <code>POST /v1/audio/speech</code> route, so it works with <code>sgl-omni serve</code> out of the box.</p><p align="center">@@ -21,22 +22,21 @@## Features-- **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 / steps / output format.-- **Templates** — a built-in default plus your own saved templates (style, lyrics, duration, steps, format), stored server-side.-- **Live queue** — cards show stage, progress bar and ETA straight from the inference server; cancel while queued, retry on error.-- **Library** — every finished render is downloaded into `data/tracks/` with its metadata (prompt, lyrics, seed, peak level…) so it survives the inference box pruning its own job list. Search, download, delete, "reuse settings".+- **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 format (wav · flac · mp3).+- **Templates** — a built-in default plus your own saved templates (style, lyrics, duration, format), stored server-side.+- **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 API reports no progress). Cancel while queued or rendering, retry on error.+- **Library** — every finished render is saved into `data/tracks/` with its metadata (prompt, lyrics, seed, format). Search, download, delete, "reuse settings".- **Player** — sticky bottom bar with waveform (decoded client-side), seek, prev/next, keyboard space to play/pause.-- **Health pill** — offline / loading model / idle / rendering · N queued.+- **Health pill** — offline / idle / rendering · N queued (probes `GET /v1/models`).- **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.- Responsive down to phone width. No external services; everything runs on your machine or tailnet.## Architecture```-browser ──/api/*──▶ server/ (Express 5) ──HTTP──▶ MiniMax-Music3 inference server (:7862)- │ polls /jobs/{id} every 1 s- │ downloads /jobs/{id}/audio when done- └─▶ data/library.json · data/templates.json · data/tracks/*.flac|wav|mp3+browser ──/api/*──▶ server/ (Express 5) ──POST /v1/audio/speech──▶ MiniMax-Music3 server (sgl-omni, :8000)+ │ one render at a time; streams the audio response to disk+ └─▶ data/library.json · data/templates.json · data/settings.json · data/tracks/*.wav|flac|mp3```| Package | What |@@ -47,7 +47,7 @@ browser ──/api/*──▶ server/ (Express 5) ──HTTP──▶ MiniMax-## Requirements- Node.js 20 or newer-- A running MiniMax-Music3 inference server exposing `POST /generate`, `GET /jobs/{id}`, `GET /jobs/{id}/audio`, `DELETE /jobs/{id}`, `GET /health` (see [Upstream API](#upstream-api))+- A running MiniMax-Music3 server exposing `POST /v1/audio/speech` and `GET /v1/models` — e.g. MiniMax's own `sgl-omni serve --model-path MiniMaxAI/MiniMax-Music3 --port 8000` (see [Upstream API](#upstream-api))## Quick start@@ -56,7 +56,7 @@ git clone https://github.com/adambenhassen/minimax-music-ui.gitcd minimax-music-uinpm installnpm run build-MUSIC_API=http://<inference-host>:8080/upstream/music3 npm start+MUSIC_API=http://<inference-host>:8000 npm start# → http://localhost:8787```@@ -83,7 +83,7 @@ The inference server address is resolved in this order:| Variable | Default | Description ||---|---|---|-| `MUSIC_API` | – | Base URL of the inference server, path prefix allowed, e.g. `http://host:8080/upstream/music3` (overrides Settings) |+| `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) || `PORT` | `8787` | Port for the UI server || `DATA_DIR` | `./data` | Where `library.json`, `templates.json`, `settings.json` and `tracks/` live |@@ -98,10 +98,10 @@ npm test # server tests (vitest) against the fake upstreamnpm run typecheck # both packages```-The fake upstream (`server/test/fakeUpstream.ts`) walks each job through `queued → running → done`. Options for the standalone runner:+The fake upstream (`server/test/fakeUpstream.ts`) implements `GET /v1/models` and a blocking `POST /v1/audio/speech`. Options for the standalone runner:```bash-FAKE_AUDIO=/path/to/real.wav FAKE_ADVANCE_MS=1500 npm run fake -w server+FAKE_AUDIO=/path/to/real.wav FAKE_RENDER_MS=8000 npm run fake -w server```## UI server API@@ -110,29 +110,26 @@ FAKE_AUDIO=/path/to/real.wav FAKE_ADVANCE_MS=1500 npm run fake -w server|---|---|---|| `GET` | `/api/health` | Upstream `/health` plus `upstreamReachable` || `GET` | `/api/library` | Tracks, newest first |-| `POST` | `/api/generate` | `{title?, prompt, lyrics?, duration, seed?, steps?, format, takes}` → created tracks |+| `POST` | `/api/generate` | `{title?, prompt, lyrics?, duration, seed?, format, takes}` → created tracks (queued) || `GET` | `/api/tracks/:id/audio` | Stream audio (`?download` for an attachment) |-| `DELETE` | `/api/tracks/:id` | Cancel upstream if in flight, delete file and entry |+| `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?, steps?, format?}` — same name overwrites |+| `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, and which fields are env-locked (the key itself is never returned) || `PUT` | `/api/settings` | `{musicApi?, apiKey?}` — `apiKey: ""` clears it; env-locked fields are rejected |-| `POST` | `/api/settings/test` | Probe a candidate `{musicApi?, apiKey?}` against `/health` without saving |+| `POST` | `/api/settings/test` | Probe a candidate `{musicApi?, apiKey?}` against `/v1/models` without saving |## Upstream API-The server expects the inference box to speak this contract, relative to `MUSIC_API` (which may include a path prefix such as `/upstream/music3`):+The server speaks the standard MiniMax-Music3 contract (the same one `sgl-omni serve` exposes), relative to `MUSIC_API`:| Method | Path | ||---|---|---|-| `POST` | `/generate` | `{prompt, lyrics="[Instrumental]", duration=60 (5–360), seed?, steps? (10–100), format="wav"\|wav16\|wav32f\|flac\|mp3, wait=false}` → `{job_id}` |-| `GET` | `/jobs/{id}` | `{status: queued\|running\|done\|error, progress, stage, eta, seed, error?, audio_url?, sampling_rate?, peak_dbfs?, clipped?}` |-| `GET` | `/jobs/{id}/audio` | Finished render |-| `DELETE` | `/jobs/{id}` | Cancel if queued / delete file |-| `GET` | `/health` | `{ready, busy, queued, formats[], sampling_rate}` |+| `GET` | `/v1/models` | Reachability probe; expected to list `minimax_ttm` |+| `POST` | `/v1/audio/speech` | `{model: "minimax_ttm", input: <lyrics>, instructions: <style>, response_format: wav\|flac\|mp3, seed?, max_new_tokens: duration×25 (≤ 9000), stream: false}` → audio bytes; `X-Seed` header (if present) is stored |-Only one job renders at a time upstream; additional submissions queue. Rendering is roughly 2.5–3× slower than realtime.+The call blocks for the whole render (roughly 2.5–3× the audio length), so the UI server queues renders one at a time and shows an estimated bar. Optional `Authorization: Bearer <key>` is sent when an API key is configured.## Contributingdiff --git a/docs/assets/screenshot.png b/docs/assets/screenshot.pngindex 2436437..deadb34 100644Binary files a/docs/assets/screenshot.png and b/docs/assets/screenshot.png differdiff --git a/server/src/app.ts b/server/src/app.tsindex 2b55aec..4bf7b85 100644--- a/server/src/app.ts+++ b/server/src/app.ts@@ -3,20 +3,18 @@ import fs from 'node:fs/promises';import path from 'node:path';import { randomUUID } from 'node:crypto';import type { JsonStore, Library } from './library.js';-import type { Poller } from './poller.js';-import { UpstreamClient, UpstreamError } from './upstream.js';+import { extFor, RenderQueue, UpstreamClient, UpstreamError } from './upstream.js';import { normalizeGenerate, ValidationError } from './validate.js';import { normalizeMusicApi, SettingsStore } from './settings.js';-import { DEFAULT_FORMATS, type Template, type Track, type UpstreamHealth } from './types.js';-import { extFor } from './poller.js';import { randomTitle } from './names.js';+import { FORMATS, type Template, type Track } from './types.js';export interface AppDeps {library: Library;templates: JsonStore<Template>;settings: SettingsStore;upstream: UpstreamClient;- poller: Poller;+ queue: RenderQueue;tracksDir: string;staticDir?: string | null;log?: (msg: string) => void;@@ -25,21 +23,17 @@ export interface AppDeps {const MIME: Record<string, string> = { wav: 'audio/wav', flac: 'audio/flac', mp3: 'audio/mpeg' };export function createApp(deps: AppDeps) {- const { library, templates, settings, upstream, poller, tracksDir } = deps;+ const { library, templates, settings, upstream, queue, tracksDir } = deps;const log = deps.log ?? ((m: string) => console.log(`[app] ${m}`));const app = express();app.use(express.json({ limit: '1mb' }));- let lastHealth: UpstreamHealth | null = null;-app.get('/api/health', async (_req, res) => {try {- lastHealth = await upstream.health();- poller.upstreamReachable = true;- res.json({ upstreamReachable: true, ...lastHealth });+ const h = await upstream.health();+ res.json({ upstreamReachable: true, ready: h.ready, models: h.models, busy: queue.busy, queued: queue.queued, formats: FORMATS });} catch (err) {- poller.upstreamReachable = false;- res.json({ upstreamReachable: false, ready: false, busy: false, queued: 0, formats: lastHealth?.formats ?? DEFAULT_FORMATS, error: (err as Error).message });+ res.json({ upstreamReachable: false, ready: false, busy: queue.busy, queued: queue.queued, formats: FORMATS, error: (err as Error).message });}});@@ -49,48 +43,34 @@ export function createApp(deps: AppDeps) {app.post('/api/generate', async (req, res, next) => {try {- const formats = lastHealth?.formats?.length ? lastHealth.formats : DEFAULT_FORMATS;- const g = normalizeGenerate(req.body, formats);+ const g = normalizeGenerate(req.body);const groupId = randomUUID();const title = g.title || randomTitle();const created: Track[] = [];for (let i = 0; i < g.takes; i++) {- const seed = g.seed === null ? null : g.seed + i;const track: Track = {id: randomUUID(),groupId,takeIndex: i,- jobId: null,title,prompt: g.prompt,lyrics: g.lyrics,duration: g.duration,- seed,- steps: g.steps,+ seed: g.seed === null ? null : g.seed + i,format: g.format,status: 'queued',progress: 0,- stage: 'submitting',+ stage: 'queued',eta: null,error: null,file: null,createdAt: new Date().toISOString(),finishedAt: null,};- try {- const { job_id } = await upstream.generate({ prompt: g.prompt, lyrics: g.lyrics, duration: g.duration, seed, steps: g.steps, format: g.format });- track.jobId = job_id;- track.stage = 'queued';- } catch (err) {- track.status = 'error';- track.stage = 'error';- track.error = (err as Error).message;- log(`generate failed: ${track.error}`);- }await library.add(track);+ queue.enqueue(track.id);created.push(track);}- void poller.tick();res.status(201).json(created);} catch (err) {next(err);@@ -100,16 +80,8 @@ export function createApp(deps: AppDeps) {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' });- if (track.jobId && (track.status === 'queued' || track.status === 'running')) {- try {- await upstream.cancel(track.jobId);- } catch (err) {- log(`cancel ${track.jobId} failed: ${(err as Error).message}`);- }- }- if (track.file) {- await fs.rm(path.join(tracksDir, track.file), { force: true });- }+ if (track.status === 'queued' || track.status === 'running') queue.cancel(track.id);+ if (track.file) await fs.rm(path.join(tracksDir, track.file), { force: true });await library.remove(track.id);res.json({ ok: true });});@@ -140,7 +112,6 @@ export function createApp(deps: AppDeps) {await settings.update({ musicApi: b.musicApi, apiKey: b.apiKey });const e = settings.effective();upstream.configure(e.musicApi, e.apiKey);- lastHealth = null;log(`upstream reconfigured → ${e.musicApi}${e.apiKey ? ' (bearer set)' : ''}`);res.json(settings.publicView());} catch (err) {@@ -151,18 +122,18 @@ export function createApp(deps: AppDeps) {app.post('/api/settings/test', async (req, res) => {const b = (req.body ?? {}) as Record<string, unknown>;const e = settings.effective();+ const locked = settings.publicView().locked;let url = e.musicApi;let key = e.apiKey;try {- if (typeof b.musicApi === 'string' && !settings.publicView().locked.musicApi) url = normalizeMusicApi(b.musicApi);- if (typeof b.apiKey === 'string' && !settings.publicView().locked.apiKey) key = b.apiKey.trim() || null;+ if (typeof b.musicApi === 'string' && !locked.musicApi) url = normalizeMusicApi(b.musicApi);+ if (typeof b.apiKey === 'string' && !locked.apiKey) key = b.apiKey.trim() || null;} catch (err) {return res.status(400).json({ ok: false, error: (err as Error).message });}- const probe = new UpstreamClient(url, key);try {- const h = await probe.health();- res.json({ ok: true, musicApi: url, health: h });+ const h = await new UpstreamClient(url, key).health();+ res.json({ ok: true, musicApi: url, health: { ...h, formats: FORMATS } });} catch (err) {res.json({ ok: false, musicApi: url, error: (err as Error).message });}@@ -177,7 +148,7 @@ export function createApp(deps: AppDeps) {const b = (req.body ?? {}) as Record<string, unknown>;const name = typeof b.name === 'string' ? b.name.trim().slice(0, 80) : '';if (!name) throw new ValidationError('name is required');- const g = normalizeGenerate({ ...b, prompt: b.prompt, takes: 1 }, lastHealth?.formats?.length ? lastHealth.formats : DEFAULT_FORMATS);+ const g = normalizeGenerate({ ...b, prompt: b.prompt, takes: 1 });const existing = templates.all().find((t) => t.name.toLowerCase() === name.toLowerCase());const tpl: Template = {id: existing?.id ?? randomUUID(),@@ -185,7 +156,6 @@ export function createApp(deps: AppDeps) {prompt: g.prompt,lyrics: g.lyrics,duration: g.duration,- steps: g.steps,format: g.format,createdAt: new Date().toISOString(),};diff --git a/server/src/index.ts b/server/src/index.tsindex 2aa6cef..f28eac3 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -4,9 +4,8 @@ import { fileURLToPath } from 'node:url';import { loadConfig } from './config.js';import { JsonStore, Library } from './library.js';import type { Template } from './types.js';-import { UpstreamClient } from './upstream.js';+import { RenderQueue, UpstreamClient } from './upstream.js';import { SettingsStore } from './settings.js';-import { Poller } from './poller.js';import { createApp } from './app.js';const config = loadConfig();@@ -15,29 +14,28 @@ 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 });await settings.load();const effective = settings.effective();+const upstream = new UpstreamClient(effective.musicApi, effective.apiKey);-const poller = new Poller(library, upstream, tracksDir);+const queue = new RenderQueue(library, upstream, tracksDir);+const orphaned = await queue.failOrphans();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, poller, tracksDir, staticDir });-poller.start();+const app = createApp({ library, templates, settings, upstream, queue, tracksDir, staticDir });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}])` : ''}`);console.log(` data: ${config.dataDir}`);console.log(` static: ${staticDir ?? '(none — run web dev server)'}`);- const inflight = library.all().filter((t) => t.status === 'queued' || t.status === 'running').length;- if (inflight) console.log(` resuming ${inflight} in-flight track(s)`);+ if (orphaned) console.log(` marked ${orphaned} interrupted render(s) as error`);});for (const sig of ['SIGINT', 'SIGTERM'] as const) {- process.on(sig, () => { poller.stop(); process.exit(0); });+ process.on(sig, () => process.exit(0));}diff --git a/server/src/poller.ts b/server/src/poller.tsdeleted file mode 100644index b116681..0000000--- a/server/src/poller.ts+++ /dev/null@@ -1,111 +0,0 @@-import fs from 'node:fs/promises';-import path from 'node:path';-import type { Library } from './library.js';-import { UpstreamClient, UpstreamError } from './upstream.js';-import type { Track, UpstreamJob } from './types.js';--const EXT: Record<string, string> = { wav: 'wav', wav16: 'wav', wav32f: 'wav', flac: 'flac', mp3: 'mp3' };-export const extFor = (format: string) => EXT[format] ?? format;--export class Poller {- private timer: NodeJS.Timeout | null = null;- private inflightTick: Promise<void> | null = null;- upstreamReachable = true;-- constructor(- private readonly library: Library,- private readonly upstream: UpstreamClient,- private readonly tracksDir: string,- private readonly intervalMs = 1000,- private readonly log: (msg: string) => void = (m) => console.log(`[poller] ${m}`),- ) {}-- start(): void {- if (this.timer) return;- this.timer = setInterval(() => void this.tick(), this.intervalMs);- }-- stop(): void {- if (this.timer) clearInterval(this.timer);- this.timer = null;- }-- /** One pass over all in-flight tracks. Concurrent callers share the in-progress pass. */- tick(): Promise<void> {- if (this.inflightTick) return this.inflightTick;- this.inflightTick = this.pass().finally(() => { this.inflightTick = null; });- return this.inflightTick;- }-- private async pass(): Promise<void> {- const inflight = this.library.all().filter((t) => t.status === 'queued' || t.status === 'running');- for (const track of inflight) await this.poll(track);- }-- private async poll(track: Track): Promise<void> {- if (!track.jobId) {- await this.library.update(track.id, { status: 'error', error: 'no upstream job id', stage: 'error' });- return;- }- let job: UpstreamJob;- try {- job = await this.upstream.job(track.jobId);- this.upstreamReachable = true;- } catch (err) {- if (err instanceof UpstreamError && err.status === 404) {- await this.library.update(track.id, { status: 'error', error: 'job vanished upstream', stage: 'error' });- return;- }- this.upstreamReachable = false;- this.log(`poll ${track.jobId} failed: ${(err as Error).message}`);- return;- }-- const base: Partial<Track> = {- progress: typeof job.progress === 'number' ? job.progress : track.progress,- stage: job.stage ?? track.stage,- eta: typeof job.eta === 'number' ? job.eta : null,- elapsed: typeof job.elapsed === 'number' ? job.elapsed : track.elapsed ?? null,- seed: typeof job.seed === 'number' ? job.seed : track.seed,- };-- switch (job.status) {- case 'queued':- case 'running':- await this.library.update(track.id, { ...base, status: job.status });- return;- case 'error':- await this.library.update(track.id, { ...base, status: 'error', error: job.error ?? 'upstream error', stage: 'error', finishedAt: new Date().toISOString() });- return;- case 'done': {- await this.library.update(track.id, { ...base, status: 'running', stage: 'downloading', progress: 1 });- const rel = `${track.id}.${extFor(track.format)}`;- const dest = path.join(this.tracksDir, rel);- try {- await fs.mkdir(this.tracksDir, { recursive: true });- await this.upstream.downloadAudio(track.jobId, dest);- } catch (err) {- this.log(`download ${track.jobId} failed: ${(err as Error).message}`);- await this.library.update(track.id, { status: 'error', error: `download failed: ${(err as Error).message}`, stage: 'error' });- return;- }- await this.library.update(track.id, {- status: 'done',- stage: 'done',- progress: 1,- eta: 0,- file: rel,- finishedAt: new Date().toISOString(),- sampleRate: job.sampling_rate,- channels: job.channels,- encoding: job.encoding,- peakDbfs: job.peak_dbfs,- clipped: job.clipped,- });- return;- }- default:- this.log(`unknown status ${(job as { status: string }).status} for ${track.jobId}`);- }- }-}diff --git a/server/src/settings.ts b/server/src/settings.tsindex e46a081..e1cf46f 100644--- a/server/src/settings.ts+++ b/server/src/settings.ts@@ -28,7 +28,7 @@ export function normalizeMusicApi(v: unknown): string {try {url = new URL(v.trim());} catch {- throw new ValidationError('musicApi must be a valid URL, e.g. http://100.105.185.107:8080/upstream/music3');+ throw new ValidationError('musicApi must be a valid URL, e.g. http://100.105.185.107:8000');}if (url.protocol !== 'http:' && url.protocol !== 'https:') throw new ValidationError('musicApi must be http or https');return url.toString().replace(/\/+$/, '');diff --git a/server/src/types.ts b/server/src/types.tsindex a5724fd..ab413c9 100644--- a/server/src/types.ts+++ b/server/src/types.ts@@ -4,29 +4,24 @@ export interface Track {id: string;groupId: string;takeIndex: number;- jobId: string | null;title: string;prompt: string;lyrics: string;duration: number;seed: number | null;- steps: number | null;format: string;status: TrackStatus;+ /** 0..1 — estimated while rendering (the API is blocking and reports no progress) */progress: number;stage: string;+ /** estimated seconds remaining */eta: number | null;- /** seconds the upstream job has been running (from /jobs/{id}) */+ /** seconds since the render started */elapsed?: number | null;error: string | null;file: string | null;createdAt: string;finishedAt: string | null;- sampleRate?: number;- channels?: number;- encoding?: string;- peakDbfs?: number;- clipped?: boolean;}export interface GenerateRequest {@@ -35,47 +30,19 @@ export interface GenerateRequest {lyrics: string;duration: number;seed: number | null;- steps: number | null;format: string;takes: number;}-export interface UpstreamHealth {- ready: boolean;- busy: boolean;- queued: number;- sampling_rate?: number;- formats?: string[];-}--export interface UpstreamJob {- job_id: string;- status: TrackStatus;- progress?: number;- stage?: string;- elapsed?: number;- eta?: number | null;- seed?: number | null;- duration?: number;- format?: string;- error?: string;- audio_url?: string;- sampling_rate?: number;- channels?: number;- encoding?: string;- peak_dbfs?: number;- clipped?: boolean;-}--export const DEFAULT_FORMATS = ['wav', 'wav16', 'wav32f', 'flac', 'mp3'];-export interface Template {id: string;name: string;prompt: string;lyrics: string;duration: number;- steps: number | null;format: string;createdAt: string;}++/** Output formats accepted by POST /v1/audio/speech. */+export const FORMATS = ['wav', 'flac', 'mp3'];diff --git a/server/src/upstream.ts b/server/src/upstream.tsindex 301d410..c4a81a4 100644--- a/server/src/upstream.ts+++ b/server/src/upstream.ts@@ -1,27 +1,46 @@import fs from 'node:fs';+import fsp from 'node:fs/promises';+import path from 'node:path';import { pipeline } from 'node:stream/promises';import { Readable } from 'node:stream';-import type { UpstreamHealth, UpstreamJob } from './types.js';+import type { Library } from './library.js';+import type { Track } from './types.js';-export interface UpstreamGenerateBody {+/** MiniMax-Music3 renders ~2.5–3× slower than realtime; drives the estimated progress bar. */+export const REALTIME_FACTOR = 3;+const FRAMES_PER_SECOND = 25;+const MAX_FRAMES = 9000;++const EXT: Record<string, string> = { wav: 'wav', flac: 'flac', mp3: 'mp3' };+export const extFor = (format: string) => EXT[format] ?? format;++export class UpstreamError extends Error {+ constructor(message: string, readonly status: number | null = null) {+ super(message);+ }+}++export interface SpeechBody {prompt: string;lyrics: string;duration: number;seed: number | null;- steps: number | null;format: string;}-export class UpstreamError extends Error {- constructor(message: string, readonly status: number | null = null) {- super(message);- }+export interface UpstreamHealth {+ ready: boolean;+ models: string[];}+/**+ * Client for the MiniMax-Music3 server contract (same shape as `sgl-omni serve`):+ * GET /v1/models → {data:[{id:"minimax_ttm"}]}+ * POST /v1/audio/speech → audio bytes (blocking for the whole render)+ */export class UpstreamClient {constructor(private baseUrl: string, private apiKey: string | null = null) {}- /** Re-point the client (used when settings change at runtime). */configure(baseUrl: string, apiKey: string | null): void {this.baseUrl = baseUrl.replace(/\/+$/, '');this.apiKey = apiKey;@@ -37,46 +56,148 @@ export class UpstreamClient {return h;}- private async req(path: string, init: RequestInit = {}): Promise<Response> {+ /** Reachability probe: the server is up when /v1/models answers. */+ async health(): Promise<UpstreamHealth> {+ let res: Response;+ try {+ res = await fetch(`${this.baseUrl}/v1/models`, { headers: this.headers() });+ } catch (err) {+ throw new UpstreamError(`upstream unreachable: ${(err as Error).message}`);+ }+ if (!res.ok) throw new UpstreamError(`upstream ${res.status} on /v1/models`, res.status);+ const json = (await res.json().catch(() => ({}))) as { data?: { id?: string }[] };+ const models = (json.data ?? []).map((m) => m.id ?? '').filter(Boolean);+ return { ready: true, models };+ }++ /** POST /v1/audio/speech, streaming the audio into `dest`. Returns the seed the server reports (X-Seed), if any. */+ async speechToFile(body: SpeechBody, dest: string, signal?: AbortSignal): Promise<{ seed: number | null }> {+ const payload = {+ model: 'minimax_ttm',+ input: body.lyrics,+ instructions: body.prompt,+ response_format: body.format,+ max_new_tokens: Math.min(MAX_FRAMES, Math.max(1, Math.round(body.duration * FRAMES_PER_SECOND))),+ stream: false,+ ...(body.seed !== null ? { seed: body.seed } : {}),+ };let res: Response;try {- res = await fetch(`${this.baseUrl}${path}`, { ...init, headers: this.headers(init.headers as Record<string, string>) });+ res = await fetch(`${this.baseUrl}/v1/audio/speech`, {+ method: 'POST',+ headers: this.headers({ 'Content-Type': 'application/json' }),+ body: JSON.stringify(payload),+ signal,+ });} catch (err) {+ if ((err as Error).name === 'AbortError') throw err;throw new UpstreamError(`upstream unreachable: ${(err as Error).message}`);}if (!res.ok) {const text = await res.text().catch(() => '');- throw new UpstreamError(`upstream ${res.status} on ${path}: ${text.slice(0, 300)}`, res.status);+ throw new UpstreamError(`upstream ${res.status} on /v1/audio/speech: ${text.slice(0, 300)}`, res.status);}- return res;+ if (!res.body) throw new UpstreamError('empty audio body');+ await fsp.mkdir(path.dirname(dest), { recursive: true });+ await pipeline(Readable.fromWeb(res.body as import('node:stream/web').ReadableStream), fs.createWriteStream(dest), { signal });+ const seedHeader = res.headers.get('x-seed');+ const seed = seedHeader !== null && seedHeader !== '' && Number.isFinite(Number(seedHeader)) ? Number(seedHeader) : null;+ return { seed };}+}- async health(): Promise<UpstreamHealth> {- return (await this.req('/health')).json() as Promise<UpstreamHealth>;- }+/**+ * One-at-a-time render queue. The upstream call blocks for the whole render and reports no+ * progress, so we keep our own queue (for "queued" state + cancel) and estimate progress+ * from elapsed time.+ */+export class RenderQueue {+ private queue: string[] = [];+ private current: { id: string; ac: AbortController } | null = null;++ constructor(+ private readonly library: Library,+ private readonly client: UpstreamClient,+ private readonly tracksDir: string,+ private readonly log: (msg: string) => void = (m) => console.log(`[render] ${m}`),+ private readonly tickMs = 1000,+ ) {}++ get busy(): boolean { return this.current !== null; }+ get queued(): number { return this.queue.length; }- async generate(body: UpstreamGenerateBody): Promise<{ job_id: string }> {- const res = await this.req('/generate', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ ...body, wait: false }),- });- const json = (await res.json()) as { job_id?: string };- if (!json.job_id) throw new UpstreamError('upstream /generate returned no job_id');- return { job_id: json.job_id };+ enqueue(id: string): void {+ this.queue.push(id);+ void this.pump();}- async job(id: string): Promise<UpstreamJob> {- return (await this.req(`/jobs/${encodeURIComponent(id)}`)).json() as Promise<UpstreamJob>;+ /** Remove from queue or abort the running render. Returns true if it was ours. */+ cancel(id: string): boolean {+ const i = this.queue.indexOf(id);+ if (i !== -1) { this.queue.splice(i, 1); return true; }+ if (this.current?.id === id) { this.current.ac.abort(); return true; }+ return false;}- async downloadAudio(id: string, dest: string): Promise<void> {- const res = await this.req(`/jobs/${encodeURIComponent(id)}/audio`);- if (!res.body) throw new UpstreamError('empty audio body');- await pipeline(Readable.fromWeb(res.body as import('node:stream/web').ReadableStream), fs.createWriteStream(dest));+ /** On boot: anything left queued/running by a previous process can't be resumed. */+ async failOrphans(): Promise<number> {+ const orphans = this.library.all().filter((t) => t.status === 'queued' || t.status === 'running');+ for (const t of orphans) {+ await this.library.update(t.id, { status: 'error', stage: 'error', error: 'interrupted by UI server restart', finishedAt: new Date().toISOString() });+ }+ return orphans.length;}- async cancel(id: string): Promise<void> {- await this.req(`/jobs/${encodeURIComponent(id)}`, { method: 'DELETE' });+ private async pump(): Promise<void> {+ if (this.current) return;+ const id = this.queue.shift();+ if (!id) return;+ const track = this.library.get(id);+ if (!track) return void this.pump();++ const ac = new AbortController();+ this.current = { id, ac };+ const startedAt = Date.now();+ const est = Math.max(5, track.duration * REALTIME_FACTOR);+ await this.library.update(id, { status: 'running', stage: 'rendering', progress: 0, eta: est, elapsed: 0 });++ const timer = setInterval(() => {+ const elapsed = (Date.now() - startedAt) / 1000;+ void this.library.update(id, { elapsed, progress: Math.min(0.95, elapsed / est), eta: Math.max(0, est - elapsed) });+ }, this.tickMs);++ const rel = `${id}.${extFor(track.format)}`;+ const dest = path.join(this.tracksDir, rel);+ try {+ const { seed } = await this.client.speechToFile(+ { prompt: track.prompt, lyrics: track.lyrics, duration: track.duration, seed: track.seed, format: track.format },+ dest,+ ac.signal,+ );+ clearInterval(timer);+ await this.library.update(id, {+ status: 'done', stage: 'done', progress: 1, eta: 0,+ elapsed: (Date.now() - startedAt) / 1000,+ seed: seed ?? track.seed,+ file: rel,+ finishedAt: new Date().toISOString(),+ });+ } catch (err) {+ clearInterval(timer);+ await fsp.rm(dest, { force: true }).catch(() => {});+ const aborted = (err as Error).name === 'AbortError' || ac.signal.aborted;+ if (this.library.get(id)) {+ await this.library.update(id, {+ status: 'error', stage: 'error',+ error: aborted ? 'cancelled' : (err as Error).message,+ elapsed: (Date.now() - startedAt) / 1000,+ finishedAt: new Date().toISOString(),+ });+ }+ if (!aborted) this.log(`render ${id} failed: ${(err as Error).message}`);+ } finally {+ this.current = null;+ void this.pump();+ }}}diff --git a/server/src/validate.ts b/server/src/validate.tsindex a8e9ff8..7f403d5 100644--- a/server/src/validate.ts+++ b/server/src/validate.ts@@ -1,4 +1,4 @@-import { DEFAULT_FORMATS, type GenerateRequest } from './types.js';+import { FORMATS, type GenerateRequest } from './types.js';export class ValidationError extends Error {status = 400;@@ -13,7 +13,7 @@ function optInt(v: unknown, name: string): number | null {return n;}-export function normalizeGenerate(body: unknown, formats: string[] = DEFAULT_FORMATS): GenerateRequest {+export function normalizeGenerate(body: unknown): GenerateRequest {if (!body || typeof body !== 'object') throw new ValidationError('body must be an object');const b = body as Record<string, unknown>;@@ -28,12 +28,9 @@ export function normalizeGenerate(body: unknown, formats: string[] = DEFAULT_FORconst duration = clamp(Math.round(durationRaw), 5, 360);const seed = optInt(b.seed, 'seed');- const steps = optInt(b.steps, 'steps');- if (steps !== null && (steps < 10 || steps > 100)) throw new ValidationError('steps must be 10–100');const format = typeof b.format === 'string' && b.format ? b.format : 'wav';- const allowed = formats.length ? formats : DEFAULT_FORMATS;- if (!allowed.includes(format)) throw new ValidationError(`format must be one of ${allowed.join(', ')}`);+ if (!FORMATS.includes(format)) throw new ValidationError(`format must be one of ${FORMATS.join(', ')}`);const takesRaw = b.takes === undefined ? 1 : Number(b.takes);if (!Number.isFinite(takesRaw)) throw new ValidationError('takes must be a number');@@ -41,5 +38,5 @@ export function normalizeGenerate(body: unknown, formats: string[] = DEFAULT_FORconst title = typeof b.title === 'string' ? b.title.trim().slice(0, 120) : '';- return { title, prompt, lyrics, duration, seed, steps, format, takes };+ return { title, prompt, lyrics, duration, seed, format, takes };}diff --git a/server/test/app.test.ts b/server/test/app.test.tsindex a84fc2d..02609d3 100644--- a/server/test/app.test.ts+++ b/server/test/app.test.ts@@ -4,9 +4,8 @@ import fs from 'node:fs/promises';import os from 'node:os';import path from 'node:path';import { JsonStore, Library } from '../src/library.js';-import type { Template } from '../src/types.js';-import { UpstreamClient } from '../src/upstream.js';-import { Poller } from '../src/poller.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 { startFakeUpstream, type FakeUpstream } from './fakeUpstream.js';@@ -23,165 +22,177 @@ async function setup(opts: Parameters<typeof startFakeUpstream>[0] = {}, apiKey:await settings.load();const upstream = new UpstreamClient(fake.url, apiKey);const tracksDir = path.join(dir, 'tracks');- const poller = new Poller(lib, upstream, tracksDir, 1000, () => {});const templates = new JsonStore<Template>(path.join(dir, 'templates.json'));await templates.load();- const app = createApp({ library: lib, templates, settings, upstream, poller, tracksDir, log: () => {} });- return { app, lib, poller, tracksDir, dir, upstream };+ const queue = new RenderQueue(lib, upstream, tracksDir, () => {}, 20);+ const app = createApp({ library: lib, templates, settings, upstream, queue, tracksDir, log: () => {} });+ return { app, lib, tracksDir, dir, upstream, queue };}+const until = async (cond: () => boolean, ms = 4000) => {+ const t0 = Date.now();+ while (!cond()) {+ if (Date.now() - t0 > ms) throw new Error('timeout');+ await new Promise((r) => setTimeout(r, 10));+ }+};+describe('app', () => {- it('health proxies upstream and reports reachability', async () => {- const { app } = await setup({ formats: ['flac'] });+ it('health probes /v1/models and reports queue state', async () => {+ const { app } = await setup();const res = await request(app).get('/api/health');- expect(res.body).toMatchObject({ upstreamReachable: true, ready: true, formats: ['flac'] });+ expect(res.body).toMatchObject({ upstreamReachable: true, ready: true, busy: false, queued: 0, formats: ['wav', 'flac', 'mp3'], models: ['minimax_ttm'] });+ expect(fake!.requests.map((r) => r.path)).toEqual(['/v1/models']);await fake!.close(); fake = null;const down = await request(app).get('/api/health');expect(down.body.upstreamReachable).toBe(false);- expect(down.body.formats).toEqual(['flac']);+ expect(down.body.error).toMatch(/unreachable/);+ expect(down.body.formats).toEqual(['wav', 'flac', 'mp3']);});- it('generate creates N takes with incrementing seeds and forwards bearer', async () => {- const { app, lib } = await setup({}, 'sekrit');- const res = await request(app).post('/api/generate').send({ prompt: 'lo-fi hip hop, 80 BPM', takes: 3, seed: 100, format: 'flac', duration: 20 });+ it('generate → queue → speech → file: maps fields, serialises takes, forwards bearer', async () => {+ const { app, lib } = await setup({ renderMs: 120 }, 'sekrit');+ const res = await request(app).post('/api/generate').send({ prompt: 'ambient', lyrics: '', duration: 10, format: 'flac', takes: 2, seed: 5 });expect(res.status).toBe(201);- expect(res.body).toHaveLength(3);- expect(res.body.map((t: { seed: number }) => t.seed)).toEqual([100, 101, 102]);- expect(res.body[0].groupId).toBe(res.body[2].groupId);- expect(res.body[0].title).toMatch(/^[A-Z][A-Za-z&' ]+$/);- expect(new Set(res.body.map((t: { title: string }) => t.title)).size).toBe(1); // all takes share the name- expect(res.body.every((t: { jobId: string }) => t.jobId)).toBe(true);- expect(lib.all()).toHaveLength(3);- const gen = fake!.requests.filter((r) => r.path === '/generate');- expect(gen).toHaveLength(3);- expect(gen[0].auth).toBe('Bearer sekrit');- expect(gen[0].body).toMatchObject({ prompt: 'lo-fi hip hop, 80 BPM', lyrics: '[Instrumental]', duration: 20, format: 'flac', wait: false });+ expect(res.body).toHaveLength(2);+ expect(res.body[0]).toMatchObject({ status: 'queued', seed: 5, lyrics: '[Instrumental]' });+ expect(res.body[1].seed).toBe(6);+ expect(res.body[0].groupId).toBe(res.body[1].groupId);+ expect(res.body[0].title).toBe(res.body[1].title);+ const [a, b] = res.body as Track[];+ await until(() => lib.get(a.id)?.status === 'running');+ expect(lib.get(b.id)?.status).toBe('queued'); // one render at a time+ await until(() => (lib.get(a.id)?.elapsed ?? 0) > 0);+ expect(lib.get(a.id)?.progress).toBeGreaterThan(0);+ expect(lib.get(a.id)?.progress).toBeLessThan(1);+ await until(() => lib.get(b.id)?.status === 'done');+ expect(lib.get(a.id)).toMatchObject({ status: 'done', file: `${a.id}.flac`, seed: 5, progress: 1, eta: 0 });+ const speech = fake!.requests.filter((r) => r.path === '/v1/audio/speech');+ expect(speech).toHaveLength(2);+ expect(speech[0].auth).toBe('Bearer sekrit');+ expect(speech[0].body).toEqual({ model: 'minimax_ttm', input: '[Instrumental]', instructions: 'ambient', response_format: 'flac', max_new_tokens: 250, stream: false, seed: 5 });+ expect(speech[1].body).toMatchObject({ seed: 6 });+ const audio = await request(app).get(`/api/tracks/${a.id}/audio`);+ expect(audio.status).toBe(200);+ expect(audio.headers['content-type']).toBe('audio/flac');+ expect(Buffer.from(audio.body).toString()).toBe('RIFF-fake-audio');+ const dl = await request(app).get(`/api/tracks/${a.id}/audio?download`);+ expect(dl.headers['content-disposition']).toMatch(/^attachment; filename=".+\.flac"$/);+ });++ it('random seed → seed reported by the server (X-Seed) is stored', async () => {+ const { app, lib } = await setup();+ const res = await request(app).post('/api/generate').send({ prompt: 'x' });+ expect(res.body[0].seed).toBeNull();+ await until(() => lib.get(res.body[0].id)?.status === 'done');+ expect(lib.get(res.body[0].id)?.seed).toBe(4242);+ expect(fake!.requests.at(-1)?.body).not.toHaveProperty('seed');});it('rejects bad input', async () => {const { app } = await setup();expect((await request(app).post('/api/generate').send({})).status).toBe(400);- expect((await request(app).post('/api/generate').send({ prompt: 'x', steps: 3 })).status).toBe(400);+ expect((await request(app).post('/api/generate').send({ prompt: 'x', format: 'wav16' })).status).toBe(400);+ expect((await request(app).post('/api/generate').send({ prompt: 'x', seed: 1.5 })).status).toBe(400);});- it('marks track error when upstream is down at submit', async () => {- const { app } = await setup();+ it('records upstream failures on the track', async () => {+ const { app, lib } = await setup();await fake!.close(); fake = null;const res = await request(app).post('/api/generate').send({ prompt: 'x' });expect(res.status).toBe(201);- expect(res.body[0]).toMatchObject({ status: 'error' });- expect(res.body[0].error).toMatch(/unreachable/);+ await until(() => lib.get(res.body[0].id)?.status === 'error');+ expect(lib.get(res.body[0].id)?.error).toMatch(/unreachable/);+ expect(lib.get(res.body[0].id)?.file).toBeNull();});- it('full cycle: generate → poll → audio → delete', async () => {- const { app, poller, tracksDir } = await setup();- const { body } = await request(app).post('/api/generate').send({ prompt: 'ambient piano', title: 'ambient piano', format: 'mp3' });- const id = body[0].id;- for (let i = 0; i < 8; i++) await poller.tick();- const lib = await request(app).get('/api/library');- expect(lib.body[0]).toMatchObject({ id, status: 'done', file: `${id}.mp3` });- const audio = await request(app).get(`/api/tracks/${id}/audio`);- expect(audio.status).toBe(200);- expect(audio.headers['content-type']).toBe('audio/mpeg');- const dl = await request(app).get(`/api/tracks/${id}/audio?download`);- expect(dl.headers['content-disposition']).toMatch(/attachment; filename="ambient piano.mp3"/);- const del = await request(app).delete(`/api/tracks/${id}`);- expect(del.status).toBe(200);+ it('delete: removes queued, aborts running, deletes finished files', async () => {+ const { app, lib, queue, tracksDir } = await setup({ renderMs: 500 });+ const res = await request(app).post('/api/generate').send({ prompt: 'x', takes: 2 });+ const [a, b] = res.body as Track[];+ await until(() => lib.get(a.id)?.status === 'running');+ expect((await request(app).delete(`/api/tracks/${b.id}`)).status).toBe(200);+ expect(queue.queued).toBe(0);+ expect((await request(app).delete(`/api/tracks/${a.id}`)).status).toBe(200);+ await until(() => !queue.busy);+ await until(() => fake!.requests.some((r) => r.aborted));+ expect(lib.all()).toEqual([]);+ expect((await request(app).delete(`/api/tracks/${a.id}`)).status).toBe(404);++ const done = await request(app).post('/api/generate').send({ prompt: 'y', format: 'mp3', title: 'ambient piano' });+ const id = done.body[0].id;+ await until(() => lib.get(id)?.status === 'done');+ await fs.access(path.join(tracksDir, `${id}.mp3`));+ expect((await request(app).delete(`/api/tracks/${id}`)).status).toBe(200);await expect(fs.access(path.join(tracksDir, `${id}.mp3`))).rejects.toThrow();- expect((await request(app).get('/api/library')).body).toEqual([]);- expect((await request(app).delete(`/api/tracks/${id}`)).status).toBe(404);});- it('delete cancels in-flight jobs upstream', async () => {+ it('failOrphans marks leftover renders after a restart', async () => {+ const { lib, queue } = await setup();+ await lib.add({ id: 'o1', groupId: 'g', takeIndex: 0, title: 'T', prompt: 'p', lyrics: '[Instrumental]', duration: 10, seed: null, format: 'wav', status: 'running', progress: 0.3, stage: 'rendering', eta: null, error: null, file: null, createdAt: new Date().toISOString(), finishedAt: null });+ expect(await queue.failOrphans()).toBe(1);+ expect(lib.get('o1')).toMatchObject({ status: 'error', error: /restart/ });+ });++ it('uses the given title when present, random otherwise', async () => {const { app } = await setup();- const { body } = await request(app).post('/api/generate').send({ prompt: 'x' });- await request(app).delete(`/api/tracks/${body[0].id}`);- expect(fake!.requests.some((r) => r.method === 'DELETE' && r.path === `/jobs/${body[0].jobId}`)).toBe(true);+ expect((await request(app).post('/api/generate').send({ prompt: 'x', title: ' Pine Morning ' })).body[0].title).toBe('Pine Morning');+ expect((await request(app).post('/api/generate').send({ prompt: 'x' })).body[0].title).toMatch(/^[A-Z][A-Za-z&' ]+$/);+ });++ it('works with a path-prefixed upstream base URL and trailing slash', async () => {+ const { app, lib } = await setup({ prefix: '/upstream/music3' }, null, { musicApi: null, apiKey: null });+ const put = await request(app).put('/api/settings').send({ musicApi: `${fake!.url}/` });+ expect(put.status).toBe(200);+ expect(put.body.musicApi).toBe(fake!.url);+ expect((await request(app).get('/api/health')).body.upstreamReachable).toBe(true);+ const res = await request(app).post('/api/generate').send({ prompt: 'x' });+ await until(() => lib.get(res.body[0].id)?.status === 'done');+ expect(fake!.requests.map((r) => r.path)).toEqual(expect.arrayContaining(['/v1/models', '/v1/audio/speech']));});it('templates: create, upsert by name, list, delete', async () => {const { app } = await setup();expect((await request(app).post('/api/templates').send({ prompt: 'x' })).status).toBe(400);expect((await request(app).post('/api/templates').send({ name: 'Lo-fi' })).status).toBe(400);- const c = await request(app).post('/api/templates').send({ name: 'Lo-fi', prompt: 'lo-fi hip hop', lyrics: '', duration: 90, format: 'mp3', steps: 40 });+ const c = await request(app).post('/api/templates').send({ name: 'Lo-fi', prompt: 'lo-fi hip hop', lyrics: '', duration: 90, format: 'mp3' });expect(c.status).toBe(201);- expect(c.body).toMatchObject({ name: 'Lo-fi', prompt: 'lo-fi hip hop', lyrics: '[Instrumental]', duration: 90, format: 'mp3', steps: 40 });+ expect(c.body).toMatchObject({ name: 'Lo-fi', prompt: 'lo-fi hip hop', lyrics: '[Instrumental]', duration: 90, format: 'mp3' });const u = await request(app).post('/api/templates').send({ name: 'lo-fi', prompt: 'lo-fi v2' });expect(u.status).toBe(200);expect(u.body.id).toBe(c.body.id);- const list = await request(app).get('/api/templates');- expect(list.body).toHaveLength(1);- expect(list.body[0].prompt).toBe('lo-fi v2');+ expect((await request(app).get('/api/templates')).body).toHaveLength(1);expect((await request(app).delete(`/api/templates/${c.body.id}`)).status).toBe(200);expect((await request(app).delete(`/api/templates/${c.body.id}`)).status).toBe(404);- expect((await request(app).get('/api/templates')).body).toEqual([]);});- it('settings: env-locked values cannot be changed', async () => {+ it('settings: env-locked values cannot be changed and the key is never returned', async () => {const { app } = await setup({}, 'k');const s = await request(app).get('/api/settings');expect(s.body).toMatchObject({ apiKeySet: true, locked: { musicApi: true, apiKey: true }, source: { musicApi: 'env', apiKey: 'env' } });- expect(s.body.musicApi).toBe(fake!.url);expect(JSON.stringify(s.body)).not.toContain('"k"');expect((await request(app).put('/api/settings').send({ musicApi: 'http://x:1' })).status).toBe(400);});it('settings: stored values apply, persist, and re-point the upstream client', async () => {const { app, dir, upstream } = await setup({}, null, { musicApi: null, apiKey: null });- const before = await request(app).get('/api/settings');- expect(before.body).toMatchObject({ musicApi: 'http://127.0.0.1:7862', apiKeySet: false, locked: { musicApi: false, apiKey: false }, source: { musicApi: 'default', apiKey: 'none' } });+ expect((await request(app).get('/api/settings')).body).toMatchObject({ musicApi: 'http://127.0.0.1:7862', apiKeySet: false, source: { musicApi: 'default', apiKey: 'none' } });expect((await request(app).put('/api/settings').send({ musicApi: 'not a url' })).status).toBe(400);- expect((await request(app).put('/api/settings').send({ musicApi: 'ftp://x' })).status).toBe(400);const put = await request(app).put('/api/settings').send({ musicApi: `${fake!.url}/`, apiKey: 'sekrit' });- expect(put.status).toBe(200);expect(put.body).toMatchObject({ musicApi: fake!.url, apiKeySet: true, source: { musicApi: 'settings', apiKey: 'settings' } });expect(upstream.url).toBe(fake!.url);- const stored = JSON.parse(await fs.readFile(path.join(dir, 'settings.json'), 'utf8'));- expect(stored).toEqual({ musicApi: fake!.url, apiKey: 'sekrit' });- // requests now carry the bearer from settings+ expect(JSON.parse(await fs.readFile(path.join(dir, 'settings.json'), 'utf8'))).toEqual({ musicApi: fake!.url, apiKey: 'sekrit' });await request(app).get('/api/health');expect(fake!.requests.at(-1)?.auth).toBe('Bearer sekrit');- // clearing the key- const cleared = await request(app).put('/api/settings').send({ apiKey: '' });- expect(cleared.body.apiKeySet).toBe(false);- // reload from disk- const again = new SettingsStore(path.join(dir, 'settings.json'), { musicApi: null, apiKey: null });- await again.load();- expect(again.effective()).toMatchObject({ musicApi: fake!.url, apiKey: null });- });-- it('works with a path-prefixed upstream base URL', async () => {- const { app, poller } = await setup({ prefix: '/upstream/music3' });- expect(fake!.url).toMatch(/\/upstream\/music3$/);- expect((await request(app).get('/api/health')).body.upstreamReachable).toBe(true);- const { body } = await request(app).post('/api/generate').send({ prompt: 'x', format: 'flac' });- for (let i = 0; i < 8; i++) await poller.tick();- expect((await request(app).get('/api/library')).body[0]).toMatchObject({ id: body[0].id, status: 'done' });- expect(fake!.requests.map((r) => r.path)).toEqual(expect.arrayContaining(['/health', '/generate', `/jobs/${body[0].jobId}`, `/jobs/${body[0].jobId}/audio`]));- });-- it('settings keep a path prefix and drop trailing slashes', async () => {- const { app } = await setup({ prefix: '/upstream/music3' }, null, { musicApi: null, apiKey: null });- const put = await request(app).put('/api/settings').send({ musicApi: `${fake!.url}/` });- expect(put.status).toBe(200);- expect(put.body.musicApi).toBe(fake!.url);- expect((await request(app).get('/api/health')).body.upstreamReachable).toBe(true);- expect(fake!.requests.at(-1)?.path).toBe('/health');+ expect((await request(app).put('/api/settings').send({ apiKey: '' })).body.apiKeySet).toBe(false);});it('settings/test probes a candidate URL without saving', async () => {const { app } = await setup({}, null, { musicApi: null, apiKey: null });const ok = await request(app).post('/api/settings/test').send({ musicApi: fake!.url });- expect(ok.body).toMatchObject({ ok: true, musicApi: fake!.url, health: { ready: true } });+ expect(ok.body).toMatchObject({ ok: true, musicApi: fake!.url, health: { ready: true, models: ['minimax_ttm'] } });const bad = await request(app).post('/api/settings/test').send({ musicApi: 'http://127.0.0.1:1' });expect(bad.body.ok).toBe(false);- expect(bad.body.error).toMatch(/unreachable/);expect((await request(app).get('/api/settings')).body.musicApi).toBe('http://127.0.0.1:7862');});-- it('uses the given title when present', async () => {- const { app } = await setup();- const res = await request(app).post('/api/generate').send({ prompt: 'x', title: ' Pine Morning ' });- expect(res.body[0].title).toBe('Pine Morning');- });});diff --git a/server/test/fakeUpstream.ts b/server/test/fakeUpstream.tsindex 46834b7..b41d825 100644--- a/server/test/fakeUpstream.ts+++ b/server/test/fakeUpstream.ts@@ -1,47 +1,21 @@import express from 'express';import type { Server } from 'node:http';-import type { UpstreamJob } from '../src/types.js';/**- * Fake of the MiniMax-Music3 inference API. Each POST /generate creates a job whose- * GET /jobs/:id responses walk a scripted list of states (last state repeats).+ * Fake MiniMax-Music3 server (same shape as `sgl-omni serve`):+ * GET /v1/models + blocking POST /v1/audio/speech that returns audio bytes after `renderMs`.*/export interface FakeUpstreamOptions {- formats?: string[];- ready?: boolean;- /** states per job in order; default queued → running → done */- script?: (jobId: string, body: Record<string, unknown>) => UpstreamJob[];+ renderMs?: number;audioBytes?: Buffer;- /** milliseconds between auto-advances; 0 = advance on every poll */- autoAdvanceMs?: number;- /** mount the API under a path prefix, e.g. '/upstream/music3' */prefix?: string;+ port?: number;}export interface FakeUpstream {url: string;- app: express.Express;+ requests: { method: string; path: string; body?: unknown; auth?: string; aborted?: boolean }[];close(): Promise<void>;- requests: { method: string; path: string; body?: unknown; auth?: string }[];- jobs: Map<string, { states: UpstreamJob[]; idx: number; body: Record<string, unknown>; last: number }>;-}--let counter = 0;--export function defaultScript(jobId: string, body: Record<string, unknown>): UpstreamJob[] {- const duration = Number(body.duration ?? 60);- const format = String(body.format ?? 'wav');- const seed = typeof body.seed === 'number' ? body.seed : 424242;- return [- { job_id: jobId, status: 'queued', progress: 0, stage: 'queued', eta: null, seed, duration, format },- { job_id: jobId, status: 'running', progress: 0.1, stage: 'generating audio tokens', eta: duration * 2.7, elapsed: 4.2, seed, duration, format },- { job_id: jobId, status: 'running', progress: 0.5, stage: 'step 210/420', eta: duration * 1.3, elapsed: duration * 1.4, seed, duration, format },- { job_id: jobId, status: 'running', progress: 0.95, stage: 'decoding audio', eta: 5, elapsed: duration * 2.6, seed, duration, format },- {- job_id: jobId, status: 'done', progress: 1, stage: 'done', eta: 0, seed, duration, format,- audio_url: `/jobs/${jobId}/audio`, sampling_rate: 44100, channels: 2, encoding: 'PCM_24', peak_dbfs: -1.2, clipped: false,- },- ];}export async function startFakeUpstream(opts: FakeUpstreamOptions = {}): Promise<FakeUpstream> {@@ -50,66 +24,34 @@ export async function startFakeUpstream(opts: FakeUpstreamOptions = {}): Promiseroot.use(opts.prefix ?? '/', app);app.use(express.json());const requests: FakeUpstream['requests'] = [];- const jobs: FakeUpstream['jobs'] = new Map();const audio = opts.audioBytes ?? Buffer.from('RIFF-fake-audio');- const autoAdvanceMs = opts.autoAdvanceMs ?? 0;-- app.use((req, _res, next) => {- requests.push({ method: req.method, path: req.path, body: req.body, auth: req.header('authorization') ?? undefined });- next();- });-- app.get('/health', (_req, res) => {- const busy = [...jobs.values()].some((j) => j.states[j.idx].status === 'running');- const queued = [...jobs.values()].filter((j) => j.states[j.idx].status === 'queued').length;- res.json({ ready: opts.ready ?? true, busy, queued, sampling_rate: 44100, formats: opts.formats ?? ['wav', 'wav16', 'wav32f', 'flac', 'mp3'] });- });+ const renderMs = opts.renderMs ?? 30;- app.post('/generate', (req, res) => {- if (!req.body?.prompt) return res.status(422).json({ detail: 'prompt required' });- const jobId = `job${(++counter).toString(16).padStart(4, '0')}`;- const states = (opts.script ?? defaultScript)(jobId, req.body);- jobs.set(jobId, { states, idx: 0, body: req.body, last: Date.now() });- res.json({ job_id: jobId, status: 'queued' });+ app.get('/v1/models', (req, res) => {+ requests.push({ method: 'GET', path: req.path, auth: req.header('authorization') ?? undefined });+ res.json({ object: 'list', data: [{ id: 'minimax_ttm', object: 'model' }] });});- app.get('/jobs', (_req, res) => {- res.json([...jobs.entries()].reverse().map(([, j]) => j.states[j.idx]));+ app.post('/v1/audio/speech', (req, res) => {+ const entry = { method: 'POST', path: req.path, body: req.body, auth: req.header('authorization') ?? undefined, aborted: false };+ requests.push(entry);+ const b = req.body ?? {};+ if (b.stream === true) return res.status(400).json({ error: 'stream: true is not supported' });+ if (!b.instructions) return res.status(422).json({ detail: 'instructions required' });+ if (!['wav', 'flac', 'mp3'].includes(b.response_format ?? 'wav')) return res.status(422).json({ detail: 'response_format must be wav, flac or mp3' });+ const timer = setTimeout(() => {+ res.setHeader('Content-Type', b.response_format === 'mp3' ? 'audio/mpeg' : b.response_format === 'flac' ? 'audio/flac' : 'audio/wav');+ res.setHeader('X-Seed', String(b.seed ?? 4242));+ res.send(audio);+ }, renderMs);+ res.on('close', () => { if (!res.headersSent) { entry.aborted = true; clearTimeout(timer); } });});- app.get('/jobs/:id', (req, res) => {- const j = jobs.get(req.params.id);- if (!j) return res.status(404).json({ detail: 'not found' });- const state = j.states[j.idx];- const now = Date.now();- if (j.idx < j.states.length - 1 && now - j.last >= autoAdvanceMs) {- j.idx++;- j.last = now;- }- res.json(state);- });-- app.get('/jobs/:id/audio', (req, res) => {- const j = jobs.get(req.params.id);- if (!j || j.states[j.idx].status !== 'done') return res.status(404).json({ detail: 'not ready' });- res.setHeader('Content-Type', 'audio/wav');- res.send(audio);- });-- app.delete('/jobs/:id', (req, res) => {- if (!jobs.delete(req.params.id)) return res.status(404).json({ detail: 'not found' });- res.json({ ok: true });- });-- const server: Server = await new Promise((resolve) => {- const s = root.listen(opts.autoAdvanceMs !== undefined && process.env.FAKE_PORT ? Number(process.env.FAKE_PORT) : 0, '127.0.0.1', () => resolve(s));- });+ const server: Server = await new Promise((resolve) => { const s = root.listen(opts.port ?? 0, '127.0.0.1', () => resolve(s)); });const addr = server.address() as { port: number };return {url: `http://127.0.0.1:${addr.port}${opts.prefix ?? ''}`,- app,requests,- jobs,- close: () => new Promise((resolve, reject) => server.close((e) => (e ? reject(e) : resolve()))),+ close: () => new Promise((resolve) => server.close(() => resolve())),};}diff --git a/server/test/fakeUpstreamServer.ts b/server/test/fakeUpstreamServer.tsindex c427017..70e99d7 100644--- a/server/test/fakeUpstreamServer.ts+++ b/server/test/fakeUpstreamServer.ts@@ -1,9 +1,9 @@import fs from 'node:fs';import { startFakeUpstream } from './fakeUpstream.js';-// Standalone fake for `npm run dev:fake`: jobs advance one state every ~2.5 s.-// FAKE_AUDIO=path/to/file.wav makes it serve a real, playable file.-process.env.FAKE_PORT ??= '7999';+// Standalone fake for `npm run dev:fake` — no GPU needed.+// FAKE_AUDIO=path/to/file.wav serves a real, playable file; FAKE_RENDER_MS sets the blocking render time.+const port = Number(process.env.FAKE_PORT ?? 7999);const audioBytes = process.env.FAKE_AUDIO ? fs.readFileSync(process.env.FAKE_AUDIO) : undefined;-const fake = await startFakeUpstream({ autoAdvanceMs: Number(process.env.FAKE_ADVANCE_MS ?? 2500), audioBytes });-console.log(`fake upstream listening on ${fake.url}${audioBytes ? ` (audio: ${process.env.FAKE_AUDIO})` : ''}`);+const fake = await startFakeUpstream({ renderMs: Number(process.env.FAKE_RENDER_MS ?? 8000), audioBytes, port });+console.log(`fake MiniMax-Music3 server (POST /v1/audio/speech) listening on ${fake.url}${audioBytes ? ` (audio: ${process.env.FAKE_AUDIO})` : ''}`);diff --git a/server/test/library.test.ts b/server/test/library.test.tsindex b03aab3..1965ca2 100644--- a/server/test/library.test.ts+++ b/server/test/library.test.ts@@ -6,8 +6,8 @@ import { Library } from '../src/library.js';import type { Track } from '../src/types.js';const mk = (id: string): Track => ({- id, groupId: 'g', takeIndex: 0, jobId: null, title: id, prompt: 'p', lyrics: '[Instrumental]',- duration: 60, seed: null, steps: null, format: 'wav', status: 'queued', progress: 0, stage: 'queued',+ id, groupId: 'g', takeIndex: 0, title: id, prompt: 'p', lyrics: '[Instrumental]',+ duration: 60, seed: null, format: 'wav', status: 'queued', progress: 0, stage: 'queued',eta: null, error: null, file: null, createdAt: new Date().toISOString(), finishedAt: null,});diff --git a/server/test/poller.test.ts b/server/test/poller.test.tsdeleted file mode 100644index b13e652..0000000--- a/server/test/poller.test.ts+++ /dev/null@@ -1,74 +0,0 @@-import { describe, it, expect, afterEach } from 'vitest';-import fs from 'node:fs/promises';-import os from 'node:os';-import path from 'node:path';-import { Library } from '../src/library.js';-import { UpstreamClient } from '../src/upstream.js';-import { Poller } from '../src/poller.js';-import { startFakeUpstream, type FakeUpstream } from './fakeUpstream.js';-import type { Track } from '../src/types.js';--let fake: FakeUpstream | null = null;-afterEach(async () => { await fake?.close(); fake = null; });--async function setup(opts: Parameters<typeof startFakeUpstream>[0] = {}) {- fake = await startFakeUpstream(opts);- const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'poller-'));- const lib = new Library(path.join(dir, 'library.json'));- await lib.load();- const upstream = new UpstreamClient(fake.url);- const poller = new Poller(lib, upstream, path.join(dir, 'tracks'), 1000, () => {});- return { dir, lib, upstream, poller };-}--const track = (jobId: string, format = 'flac'): Track => ({- id: 't1', groupId: 'g', takeIndex: 0, jobId, title: 'T', prompt: 'p', lyrics: '[Instrumental]', duration: 30,- seed: null, steps: null, format, status: 'queued', progress: 0, stage: 'queued', eta: null, error: null,- file: null, createdAt: new Date().toISOString(), finishedAt: null,-});--describe('Poller', () => {- it('walks queued → running → done and downloads the file', async () => {- const { dir, lib, upstream, poller } = await setup();- const { job_id } = await upstream.generate({ prompt: 'p', lyrics: '[Instrumental]', duration: 30, seed: null, steps: null, format: 'flac' });- await lib.add(track(job_id));- await poller.tick(); // queued- expect(lib.get('t1')?.status).toBe('queued');- await poller.tick(); // running 0.1- expect(lib.get('t1')).toMatchObject({ status: 'running', progress: 0.1, stage: 'generating audio tokens', seed: 424242, elapsed: 4.2 });- await poller.tick(); await poller.tick(); // 0.5, 0.95- await poller.tick(); // done → download- const t = lib.get('t1')!;- expect(t.status).toBe('done');- expect(t.file).toBe('t1.flac');- expect(t.sampleRate).toBe(44100);- expect(t.peakDbfs).toBe(-1.2);- const bytes = await fs.readFile(path.join(dir, 'tracks', 't1.flac'));- expect(bytes.toString()).toBe('RIFF-fake-audio');- await poller.tick(); // no-op once done- expect(fake!.requests.filter((r) => r.path.endsWith('/audio')).length).toBe(1);- });-- it('records upstream error', async () => {- const { lib, upstream, poller } = await setup({- script: (id) => [{ job_id: id, status: 'error', error: 'CUDA OOM' }],- });- const { job_id } = await upstream.generate({ prompt: 'p', lyrics: '[Instrumental]', duration: 30, seed: null, steps: null, format: 'wav' });- await lib.add(track(job_id, 'wav'));- await poller.tick();- expect(lib.get('t1')).toMatchObject({ status: 'error', error: 'CUDA OOM' });- });-- it('marks vanished jobs as error and survives unreachable upstream', async () => {- const { lib, poller } = await setup();- await lib.add(track('nope'));- await poller.tick();- expect(lib.get('t1')?.status).toBe('error');- await lib.update('t1', { status: 'queued', error: null });- await fake!.close();- fake = null;- await poller.tick();- expect(lib.get('t1')?.status).toBe('queued');- expect(poller.upstreamReachable).toBe(false);- });-});diff --git a/server/test/validate.test.ts b/server/test/validate.test.tsindex 66d46b6..abae54c 100644--- a/server/test/validate.test.ts+++ b/server/test/validate.test.ts@@ -17,16 +17,15 @@ describe('normalizeGenerate', () => {expect(normalizeGenerate({ prompt: 'x', takes: 0 }).takes).toBe(1);expect(normalizeGenerate({ prompt: 'x', takes: 9 }).takes).toBe(4);});- it('validates steps and seed', () => {- expect(() => normalizeGenerate({ prompt: 'x', steps: 5 })).toThrow(/steps/);- expect(normalizeGenerate({ prompt: 'x', steps: null }).steps).toBeNull();- expect(normalizeGenerate({ prompt: 'x', steps: '40' }).steps).toBe(40);+ it('validates seed', () => {expect(() => normalizeGenerate({ prompt: 'x', seed: 1.5 })).toThrow(/seed/);expect(normalizeGenerate({ prompt: 'x', seed: '' }).seed).toBeNull();+ expect(normalizeGenerate({ prompt: 'x', seed: '42' }).seed).toBe(42);});- it('validates format against upstream list', () => {+ it('validates format against the speech route list', () => {expect(() => normalizeGenerate({ prompt: 'x', format: 'ogg' })).toThrow(/format/);- expect(normalizeGenerate({ prompt: 'x', format: 'flac' }, ['flac']).format).toBe('flac');- expect(() => normalizeGenerate({ prompt: 'x', format: 'wav' }, ['flac'])).toThrow(/format/);+ expect(() => normalizeGenerate({ prompt: 'x', format: 'wav16' })).toThrow(/format/);+ expect(normalizeGenerate({ prompt: 'x', format: 'flac' }).format).toBe('flac');+ expect(normalizeGenerate({ prompt: 'x' }).format).toBe('wav');});});diff --git a/web/src/App.tsx b/web/src/App.tsxindex 615c496..5ab3ff9 100644--- a/web/src/App.tsx+++ b/web/src/App.tsx@@ -71,7 +71,7 @@ export default function App() {const reuse = (t: Track) => { setForm(formFromTrack(t)); setView('create'); };const retry = (t: Track) => {- void submit({ title: t.title, prompt: t.prompt, lyrics: t.lyrics, duration: t.duration, seed: t.seed, steps: t.steps, format: t.format, takes: 1 }).catch((e) => alert((e as Error).message));+ void submit({ title: t.title, prompt: t.prompt, lyrics: t.lyrics, duration: t.duration, seed: t.seed, format: t.format, takes: 1 }).catch((e) => alert((e as Error).message));};const feed = (diff --git a/web/src/components/CreatePanel.tsx b/web/src/components/CreatePanel.tsxindex 2433842..ce8e6cf 100644--- a/web/src/components/CreatePanel.tsx+++ b/web/src/components/CreatePanel.tsx@@ -22,12 +22,11 @@ export interface FormState {duration: number;takes: number;seed: string;- steps: string;format: string;}export const DEFAULT_FORM: FormState = {- mode: 'simple', title: '', prompt: TEMPLATE_PROMPT, lyrics: TEMPLATE_LYRICS, instrumental: false, duration: 60, takes: 1, seed: '', steps: '', format: 'flac',+ mode: 'simple', title: '', prompt: TEMPLATE_PROMPT, lyrics: TEMPLATE_LYRICS, instrumental: false, duration: 60, takes: 1, seed: '', format: 'flac',};export function formFromTrack(t: Track): FormState {@@ -40,7 +39,6 @@ export function formFromTrack(t: Track): FormState {duration: t.duration,takes: 1,seed: t.seed === null ? '' : String(t.seed),- steps: t.steps === null ? '' : String(t.steps),format: t.format,};}@@ -58,7 +56,7 @@ export function CreatePanel({ health, form, onFormChange, onSubmit }: Props) {const [error, setError] = useState<string | null>(null);const set = <K extends keyof FormState>(k: K, v: FormState[K]) => onFormChange({ ...form, [k]: v });- const formats = health?.formats?.length ? health.formats : ['wav', 'wav16', 'wav32f', 'flac', 'mp3'];+ const formats = health?.formats?.length ? health.formats : ['wav', 'flac', 'mp3'];useEffect(() => {if (!formats.includes(form.format)) onFormChange({ ...form, format: formats.includes('flac') ? 'flac' : formats[0] });// eslint-disable-next-line react-hooks/exhaustive-deps@@ -71,9 +69,7 @@ export function CreatePanel({ health, form, onFormChange, onSubmit }: Props) {const submit = async () => {setError(null);const seed = form.seed.trim() === '' ? null : Number(form.seed);- const steps = form.steps.trim() === '' ? null : Number(form.steps);if (seed !== null && !Number.isInteger(seed)) return setError('Seed must be an integer');- if (steps !== null && (!Number.isInteger(steps) || steps < 10 || steps > 100)) return setError('Steps must be 10–100');setSubmitting(true);try {await onSubmit({@@ -82,7 +78,6 @@ export function CreatePanel({ health, form, onFormChange, onSubmit }: Props) {lyrics: form.instrumental ? '[Instrumental]' : form.lyrics.trim(),duration: form.duration,seed,- steps,format: form.format,takes: form.takes,});@@ -133,12 +128,11 @@ export function CreatePanel({ health, form, onFormChange, onSubmit }: Props) {<div className="flex items-center justify-between mb-1"><div className="label">{form.mode === 'simple' ? 'Song description' : 'Style of music'}</div><TemplatesMenu- builtin={{ prompt: TEMPLATE_PROMPT, lyrics: TEMPLATE_LYRICS, duration: 60, steps: null, format: 'flac' }}+ builtin={{ prompt: TEMPLATE_PROMPT, lyrics: TEMPLATE_LYRICS, duration: 60, format: 'flac' }}current={{prompt: form.prompt.trim(),lyrics: form.instrumental ? '[Instrumental]' : form.lyrics.trim(),duration: form.duration,- steps: form.steps.trim() === '' ? null : Number(form.steps),format: form.format,}}onLoad={(t: TemplateValues) => onFormChange({@@ -147,7 +141,6 @@ export function CreatePanel({ health, form, onFormChange, onSubmit }: Props) {lyrics: t.lyrics === '[Instrumental]' ? '' : t.lyrics,instrumental: t.lyrics === '[Instrumental]',duration: t.duration,- steps: t.steps === null ? '' : String(t.steps),format: t.format,})}/>@@ -196,15 +189,11 @@ export function CreatePanel({ health, form, onFormChange, onSubmit }: Props) {<Chevron width={14} height={14} className={`transition-transform ${advanced ? 'rotate-90' : ''}`} /> Advanced</button>{advanced && (- <div className="grid grid-cols-3 gap-3 mt-2">+ <div className="grid grid-cols-2 gap-3 mt-2"><div><div className="label mb-1">Seed</div><input className="field font-mono" inputMode="numeric" value={form.seed} onChange={(e) => set('seed', e.target.value)} placeholder="random" /></div>- <div>- <div className="label mb-1">Steps</div>- <input className="field font-mono" inputMode="numeric" value={form.steps} onChange={(e) => set('steps', e.target.value)} placeholder="30" />- </div><div><div className="label mb-1">Format</div><select className="field" value={form.format} onChange={(e) => set('format', e.target.value)}>diff --git a/web/src/components/ProgressDetail.tsx b/web/src/components/ProgressDetail.tsxindex dd874be..a0b784f 100644--- a/web/src/components/ProgressDetail.tsx+++ b/web/src/components/ProgressDetail.tsx@@ -6,23 +6,17 @@ export function ProgressDetail({ track: t }: { track: Track }) {const info = parseStage(t.stage, t.status === 'queued' ? 'queued' : 'running');const cur = phaseIndex(info.phase);const pct = Math.round(t.progress * 100);- const indeterminate = t.progress <= 0 && info.phase !== 'download';+ const indeterminate = t.status === 'queued';return (<div className="mt-2 space-y-1.5">- {/* phase stepper */}<ol className="flex items-center gap-1 text-[10px]">{PHASES.map((p, i) => {const state = i < cur ? 'done' : i === cur ? 'active' : 'todo';return (<li key={p.id} className="flex items-center gap-1 min-w-0">- <span- className={`px-1.5 py-0.5 rounded-md whitespace-nowrap transition ${- state === 'active' ? 'bg-accent-soft text-white ring-1 ring-accent/60' : state === 'done' ? 'text-zinc-400' : 'text-zinc-600'- }`}- >+ <span className={`px-1.5 py-0.5 rounded-md whitespace-nowrap transition ${state === 'active' ? 'bg-accent-soft text-white ring-1 ring-accent/60' : state === 'done' ? 'text-zinc-400' : 'text-zinc-600'}`}>{state === 'done' ? '✓ ' : ''}{p.label}- {state === 'active' && info.step ? <span className="tabular-nums text-zinc-300"> {info.step.n}/{info.step.total}</span> : null}</span>{i < PHASES.length - 1 && <span className={`w-3 h-px ${i < cur ? 'bg-zinc-500' : 'bg-ink-600'}`} />}</li>@@ -30,26 +24,19 @@ export function ProgressDetail({ track: t }: { track: Track }) {})}</ol>- {/* bar */}- <div className="h-1.5 rounded-full bg-ink-700 overflow-hidden relative">+ <div className="h-1.5 rounded-full bg-ink-700 overflow-hidden"><divclassName={`h-full rounded-full bg-gradient-to-r from-accent to-purple-400 transition-[width] duration-700 ease-out ${indeterminate ? 'animate-pulseBar w-1/12' : ''}`}style={indeterminate ? undefined : { width: `${Math.max(2, pct)}%` }}/>- {info.step && (- <div className="absolute inset-0 pointer-events-none">- {[0.25, 0.5, 0.75].map((f) => <span key={f} className="absolute top-0 h-full w-px bg-ink-900/60" style={{ left: `${f * 100}%` }} />)}- </div>- )}</div>- {/* numbers */}<div className="flex items-center justify-between text-[11px] text-zinc-400 tabular-nums"><span className="truncate">{info.label}</span><span className="shrink-0 flex items-center gap-2">- <span className="text-zinc-300">{indeterminate ? '' : `${pct}%`}</span>+ {!indeterminate && <span className="text-zinc-300">~{pct}%</span>}{typeof t.elapsed === 'number' && t.elapsed > 0 && <span title="elapsed">{fmtTime(t.elapsed)} elapsed</span>}- {t.eta !== null && t.eta > 0 && <span title="estimated remaining" className="text-zinc-300">{fmtEta(t.eta)}</span>}+ {t.eta !== null && t.eta > 0 && !indeterminate && <span title="estimated remaining" className="text-zinc-300">≈ {fmtEta(t.eta)}</span>}</span></div></div>diff --git a/web/src/components/SettingsPanel.tsx b/web/src/components/SettingsPanel.tsxindex 9758c5e..86656af 100644--- a/web/src/components/SettingsPanel.tsx+++ b/web/src/components/SettingsPanel.tsx@@ -67,7 +67,7 @@ export function SettingsPanel({ onSaved }: { onSaved: () => void }) {<div><h2 className="text-sm font-semibold">Inference server</h2><p className="text-xs text-zinc-500 mt-1">- Base URL of the MiniMax-Music3 API — a path prefix is fine (e.g. <code className="text-zinc-300">http://host:8080/upstream/music3</code>); <code className="text-zinc-300">/generate</code>, <code className="text-zinc-300">/jobs/…</code> and <code className="text-zinc-300">/health</code> are appended. Values set via <code className="text-zinc-300">MUSIC_API</code> / <code className="text-zinc-300">MUSIC_API_KEY</code> environment variables always win and are shown locked here.+ Base URL of your MiniMax-Music3 server — anything that speaks the standard <code className="text-zinc-300">POST /v1/audio/speech</code> route (e.g. <code className="text-zinc-300">sgl-omni serve --model-path MiniMaxAI/MiniMax-Music3 --port 8000</code> → <code className="text-zinc-300">http://host:8000</code>). A path prefix is fine; <code className="text-zinc-300">/v1/models</code> and <code className="text-zinc-300">/v1/audio/speech</code> are appended. Values set via <code className="text-zinc-300">MUSIC_API</code> / <code className="text-zinc-300">MUSIC_API_KEY</code> environment variables always win and are shown locked here.</p></div>@@ -85,7 +85,7 @@ export function SettingsPanel({ onSaved }: { onSaved: () => void }) {value={musicApi}disabled={settings.locked.musicApi}onChange={(e) => setMusicApi(e.target.value)}- placeholder="http://100.105.185.107:8080/upstream/music3"+ placeholder="http://100.105.185.107:8000"spellCheck={false}/></div>@@ -127,7 +127,7 @@ export function SettingsPanel({ onSaved }: { onSaved: () => void }) {{test && (<div className={`text-xs rounded-lg px-3 py-2 border ${test.ok ? 'text-emerald-300 bg-emerald-500/10 border-emerald-500/30' : 'text-red-300 bg-red-500/10 border-red-500/30'}`}>{test.ok- ? <>Reachable at <span className="font-mono">{test.musicApi}</span> — {test.health?.ready ? 'model ready' : 'model still loading'}{test.health?.formats?.length ? ` · formats: ${test.health.formats.join(', ')}` : ''}</>+ ? <>Reachable at <span className="font-mono">{test.musicApi}</span>{test.health?.models?.length ? ` · models: ${test.health.models.join(', ')}` : ''}{test.health?.formats?.length ? ` · formats: ${test.health.formats.join(', ')}` : ''}</>: <>Could not reach <span className="font-mono">{test.musicApi}</span>: {test.error}</>}</div>)}diff --git a/web/src/components/TemplatesMenu.tsx b/web/src/components/TemplatesMenu.tsxindex 263a20b..64056e4 100644--- a/web/src/components/TemplatesMenu.tsx+++ b/web/src/components/TemplatesMenu.tsx@@ -7,7 +7,6 @@ export interface TemplateValues {prompt: string;lyrics: string;duration: number;- steps: number | null;format: string;}@@ -86,7 +85,7 @@ export function TemplatesMenu({ builtin, current, onLoad }: Props) {<input className="field !py-1 text-xs" placeholder="Template name" value={name} onChange={(e) => setName(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') void save(); }} /><button type="button" className="btn-primary !px-3 !py-1 text-xs" disabled={!name.trim() || saving} onClick={save}>Save</button></div>- <div className="text-[10px] text-zinc-500 px-2 pb-1">Saves style, lyrics, duration, steps and format. Same name overwrites.</div>+ <div className="text-[10px] text-zinc-500 px-2 pb-1">Saves style, lyrics, duration and format. Same name overwrites.</div>{error && <div className="text-[11px] text-red-400 px-2 pb-1">{error}</div>}</div>)}diff --git a/web/src/components/TrackCard.tsx b/web/src/components/TrackCard.tsxindex 64953df..e1757d2 100644--- a/web/src/components/TrackCard.tsx+++ b/web/src/components/TrackCard.tsx@@ -68,10 +68,8 @@ export function TrackCard({ track: t, groupSize, active, playing, onPlay, onDele<span>·</span><span>{FORMAT_LABEL[t.format] ?? t.format}</span>{t.seed !== null && (<><span>·</span><span className="font-mono">seed {t.seed}</span></>)}- {t.steps !== null && (<><span>·</span><span>{t.steps} steps</span></>)}<span>·</span><span>{fmtAgo(t.createdAt)}</span>- {done && t.clipped && <span className="text-amber-400" title={`peak ${t.peakDbfs?.toFixed(1)} dBFS`}>clipped</span>}{t.lyrics !== '[Instrumental]' && (<button className="ml-auto text-zinc-400 hover:text-white" onClick={() => setOpen((o) => !o)}>{open ? 'hide lyrics' : 'lyrics'}</button>)}diff --git a/web/src/hooks/usePolling.ts b/web/src/hooks/usePolling.tsindex 797ac19..91ca4cb 100644--- a/web/src/hooks/usePolling.ts+++ b/web/src/hooks/usePolling.ts@@ -2,7 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';import { api } from '../api';import { isInflight, type Health, type Track } from '../types';-const OFFLINE_HEALTH: Health = { upstreamReachable: false, ready: false, busy: false, queued: 0, formats: ['wav', 'wav16', 'wav32f', 'flac', 'mp3'], error: 'ui server unreachable' };+const OFFLINE_HEALTH: Health = { upstreamReachable: false, ready: false, busy: false, queued: 0, formats: ['wav', 'flac', 'mp3'], error: 'ui server unreachable' };export function useHealth(intervalMs = 5000) {const [health, setHealth] = useState<Health | null>(null);diff --git a/web/src/lib/format.ts b/web/src/lib/format.tsindex 424a357..17ddc46 100644--- a/web/src/lib/format.ts+++ b/web/src/lib/format.ts@@ -19,6 +19,4 @@ export function fmtAgo(iso: string): string {return new Date(iso).toLocaleDateString();}-export const FORMAT_LABEL: Record<string, string> = {- wav: 'WAV 24-bit', wav16: 'WAV 16-bit', wav32f: 'WAV 32-bit float', flac: 'FLAC', mp3: 'MP3 320k',-};+export const FORMAT_LABEL: Record<string, string> = { wav: 'WAV', flac: 'FLAC', mp3: 'MP3' };diff --git a/web/src/lib/stage.ts b/web/src/lib/stage.tsindex f0c8219..6a1dd66 100644--- a/web/src/lib/stage.ts+++ b/web/src/lib/stage.ts@@ -1,34 +1,21 @@-export type PhaseId = 'queued' | 'tokens' | 'diffusion' | 'decode' | 'download';+export type PhaseId = 'queued' | 'rendering' | 'download';export const PHASES: { id: PhaseId; label: string }[] = [{ id: 'queued', label: 'Queued' },- { id: 'tokens', label: 'Audio tokens' },- { id: 'diffusion', label: 'Diffusion' },- { id: 'decode', label: 'Decode' },+ { id: 'rendering', label: 'Rendering' },{ id: 'download', label: 'Download' },];export interface StageInfo {phase: PhaseId;- /** human label for the current stage, e.g. "Diffusion step 176 / 420" */label: string;- step?: { n: number; total: number };}-/** Map the upstream `stage` string (+ status) onto a coarse phase. */export function parseStage(stage: string, status: 'queued' | 'running'): StageInfo {const s = (stage || '').toLowerCase().trim();- const m = /step\s+(\d+)\s*\/\s*(\d+)/.exec(s);- if (m) {- const n = Number(m[1]);- const total = Number(m[2]);- return { phase: 'diffusion', label: `Diffusion · step ${n} / ${total}`, step: { n, total } };- }- if (s.includes('token')) return { phase: 'tokens', label: 'Generating audio tokens' };- if (s.includes('decod')) return { phase: 'decode', label: 'Decoding audio' };- if (s.includes('download')) return { phase: 'download', label: 'Downloading render' };- if (status === 'queued' || s === 'queued' || s === 'submitting' || s === '') return { phase: 'queued', label: s === 'submitting' ? 'Submitting to inference server' : 'Waiting in queue' };- return { phase: 'tokens', label: stage };+ if (status === 'queued') return { phase: 'queued', label: 'Waiting for the GPU — one render at a time' };+ if (s.includes('download')) return { phase: 'download', label: 'Saving render' };+ return { phase: 'rendering', label: 'Rendering — progress is estimated (~3× realtime); the server reports none' };}export const phaseIndex = (p: PhaseId) => PHASES.findIndex((x) => x.id === p);diff --git a/web/src/types.ts b/web/src/types.tsindex 148837e..46d0ec8 100644--- a/web/src/types.ts+++ b/web/src/types.ts@@ -4,29 +4,22 @@ export interface Track {id: string;groupId: string;takeIndex: number;- jobId: string | null;title: string;prompt: string;lyrics: string;duration: number;seed: number | null;- steps: number | null;format: string;status: TrackStatus;+ /** 0..1 — estimated while rendering (the API is blocking and reports no progress) */progress: number;stage: string;eta: number | null;- /** seconds the upstream job has been running (from /jobs/{id}) */elapsed?: number | null;error: string | null;file: string | null;createdAt: string;finishedAt: string | null;- sampleRate?: number;- channels?: number;- encoding?: string;- peakDbfs?: number;- clipped?: boolean;}export interface Health {@@ -34,8 +27,8 @@ export interface Health {ready: boolean;busy: boolean;queued: number;- sampling_rate?: number;formats: string[];+ models?: string[];error?: string;}@@ -45,20 +38,16 @@ export interface GenerateInput {lyrics: string;duration: number;seed: number | null;- steps: number | null;format: string;takes: number;}-export const isInflight = (t: Track) => t.status === 'queued' || t.status === 'running';-export interface Template {id: string;name: string;prompt: string;lyrics: string;duration: number;- steps: number | null;format: string;createdAt: string;}@@ -76,3 +65,5 @@ export interface SettingsTestResult {health?: Health;error?: string;}++export const isInflight = (t: Track) => t.status === 'queued' || t.status === 'running';