Suno-style web UI for a self-hosted MiniMax-Music3 inference server
TypeScript ai-musicdiffusersdockerexpressminimaxminimax-musicmusic-generationreactself-hostedsgl-omnisunotailwindcsstext-to-musictypescriptvite
feat(server): live progress and growing audio file for streamed renders
Adam Benhassen10f9bb183e93
diff --git a/server/src/app.ts b/server/src/app.tsindex eb5c137..b8b91c0 100644--- a/server/src/app.ts+++ b/server/src/app.ts@@ -31,9 +31,9 @@ export function createApp(deps: AppDeps) {app.get('/api/health', async (_req, res) => {try {const h = await upstream.health();- res.json({ upstreamReachable: true, ready: h.ready, models: h.models, busy: queue.busy, queued: queue.queued, formats: FORMATS });+ res.json({ upstreamReachable: true, ready: h.ready, models: h.models, capabilities: h.capabilities, busy: queue.busy, queued: queue.queued, formats: FORMATS });} catch (err) {- res.json({ upstreamReachable: false, ready: false, busy: queue.busy, queued: queue.queued, formats: FORMATS, error: (err as Error).message });+ res.json({ upstreamReachable: false, ready: false, capabilities: [], busy: queue.busy, queued: queue.queued, formats: FORMATS, error: (err as Error).message });}});@@ -62,6 +62,7 @@ export function createApp(deps: AppDeps) {progress: 0,stage: 'queued',eta: null,+ renderedSeconds: null,error: null,file: null,createdAt: new Date().toISOString(),diff --git a/server/src/types.ts b/server/src/types.tsindex 593c56f..a81a867 100644--- a/server/src/types.ts+++ b/server/src/types.ts@@ -11,13 +11,16 @@ export interface Track {seed: number | null;format: string;status: TrackStatus;- /** 0..1 — estimated while rendering (the API is blocking and reports no progress) */+ /** 0..1 — real when the upstream streams progress, else estimated from elapsed time */progress: number;+ /** 'queued' | 'rendering' (estimated) | 'semantic' | 'denoise' (real) | 'done' | 'error' */stage: string;/** estimated seconds remaining */eta: number | null;/** seconds since the render started */elapsed?: number | null;+ /** seconds of audio already on disk while streaming; null when the server can't stream */+ renderedSeconds: number | null;error: string | null;file: string | null;createdAt: string;diff --git a/server/src/upstream.ts b/server/src/upstream.tsindex 6c4b5a5..53f9308 100644--- a/server/src/upstream.ts+++ b/server/src/upstream.ts@@ -52,6 +52,7 @@ export type StreamEvent =export class UpstreamClient {private modelId: string | null = null;private capabilities: string[] = [];+ private probed = false;constructor(private baseUrl: string, private apiKey: string | null = null) {}@@ -60,6 +61,12 @@ export class UpstreamClient {this.apiKey = apiKey;this.modelId = null;this.capabilities = [];+ this.probed = false;+ }++ /** Probe once (model id + capabilities) unless a health() call already did since configure(). */+ async ensureProbed(): Promise<void> {+ if (!this.probed) await this.health().catch(() => undefined);}/** true iff the last health probe advertised the optional `stream` extension (SSE progress + PCM windows). */@@ -105,6 +112,7 @@ export class UpstreamClient {}const h = await this.probeHealth();this.capabilities = h.capabilities;+ this.probed = true;return { ready: h.ready, models, capabilities: h.capabilities };}@@ -122,7 +130,7 @@ export class UpstreamClient {}private async post(body: SpeechBody, stream: boolean, signal?: AbortSignal): Promise<Response> {- if (!this.modelId) await this.health().catch(() => undefined);+ await this.ensureProbed();const payload = {model: this.model,input: body.lyrics,@@ -210,7 +218,8 @@ export class UpstreamClient {/*** 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.+ * from elapsed time — unless the upstream advertises `stream`, in which case progress and+ * audio windows arrive live and the track's file grows on disk while it renders.*/export class RenderQueue {private queue: string[] = [];@@ -260,27 +269,51 @@ export class RenderQueue {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 });+ await this.client.ensureProbed();+ const streaming = this.client.canStream;+ await this.library.update(id, { status: 'running', stage: streaming ? 'semantic' : 'rendering', progress: 0, eta: est, elapsed: 0, renderedSeconds: streaming ? 0 : null });++ const rel = `${id}.${extFor(track.format)}`;+ const dest = path.join(this.tracksDir, rel);+ const elapsedS = () => (Date.now() - startedAt) / 1000;++ // real progress state (streaming only)+ let frac = 0, stage: 'semantic' | 'denoise' = 'semantic', rendered = 0, fileKnown = false, lastWrite = 0;+ const onEvent = (e: StreamEvent) => {+ if (e.type === 'progress') {+ const part = e.total > 0 ? Math.min(1, e.done / e.total) : 0;+ stage = e.stage;+ frac = stage === 'semantic' ? 0.35 * part : 0.35 + 0.65 * part;+ if (Date.now() - lastWrite < 250) return; // throttle store writes; audio events always write+ } else {+ rendered = e.secondsRendered;+ }+ lastWrite = Date.now();+ const elapsed = elapsedS();+ const eta = frac > 0.02 ? Math.max(0, elapsed / frac - elapsed) : Math.max(0, est - elapsed);+ const patch: Partial<Track> = { stage, progress: Math.min(0.99, frac), eta, elapsed, renderedSeconds: rendered };+ if (rendered > 0 && !fileKnown) { fileKnown = true; patch.file = rel; }+ void this.library.update(id, patch);+ };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) });+ const elapsed = elapsedS();+ if (streaming) void this.library.update(id, { elapsed });+ else 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,- );+ const body = { prompt: track.prompt, lyrics: track.lyrics, duration: track.duration, seed: track.seed, format: track.format };+ const { seed } = streaming+ ? await this.client.speechStream(body, dest, onEvent, ac.signal)+ : await this.client.speechToFile(body, dest, ac.signal);clearInterval(timer);await this.library.update(id, {status: 'done', stage: 'done', progress: 1, eta: 0,- elapsed: (Date.now() - startedAt) / 1000,+ elapsed: elapsedS(),seed: seed ?? track.seed,file: rel,+ renderedSeconds: streaming ? rendered : null,finishedAt: new Date().toISOString(),});} catch (err) {@@ -291,7 +324,8 @@ export class RenderQueue {await this.library.update(id, {status: 'error', stage: 'error',error: aborted ? 'cancelled' : (err as Error).message,- elapsed: (Date.now() - startedAt) / 1000,+ elapsed: elapsedS(),+ file: null, renderedSeconds: null,finishedAt: new Date().toISOString(),});}diff --git a/server/test/app.test.ts b/server/test/app.test.tsindex b787345..0a46d60 100644--- a/server/test/app.test.ts+++ b/server/test/app.test.ts@@ -41,7 +41,7 @@ describe('app', () => {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, busy: false, queued: 0, formats: ['wav'], models: ['minimax_ttm'] });+ expect(res.body).toMatchObject({ upstreamReachable: true, ready: true, busy: false, queued: 0, formats: ['wav'], models: ['minimax_ttm'], capabilities: [] });expect(fake!.requests.map((r) => r.path)).toEqual(['/v1/models']);await fake!.close(); fake = null;const down = await request(app).get('/api/health');@@ -222,4 +222,44 @@ describe('app', () => {expect(bad.body.ok).toBe(false);expect((await request(app).get('/api/settings')).body.musicApi).toBe('http://127.0.0.1:7862');});++ it('streams when advertised: real stage/progress/renderedSeconds, file appears early, valid WAV at the end', async () => {+ const { app, lib, tracksDir } = await setup({ stream: { windows: 4, secondsPerWindow: 0.1, windowMs: 40 } });+ const h = await request(app).get('/api/health');+ expect(h.body.capabilities).toEqual(['stream']);+ const res = await request(app).post('/api/generate').send({ prompt: 'x', duration: 10 });+ const id = res.body[0].id as string;+ await until(() => lib.get(id)?.stage === 'semantic');+ await until(() => (lib.get(id)?.renderedSeconds ?? 0) > 0);+ const mid = lib.get(id)!;+ expect(mid.status).toBe('running');+ expect(mid.stage).toBe('denoise');+ expect(mid.file).toBe(`${id}.wav`);+ expect(mid.progress).toBeGreaterThan(0.35);+ await until(() => lib.get(id)?.status === 'done');+ const t = lib.get(id)!;+ expect(t.renderedSeconds).toBeCloseTo(0.4, 1);+ expect(t.progress).toBe(1);+ const wav = await fs.readFile(path.join(tracksDir, t.file!));+ expect(wav.readUInt32LE(40)).toBe(wav.length - 44);+ expect(fake!.requests.find((r) => r.path === '/v1/audio/speech')?.body).toMatchObject({ stream: true });+ });++ it('never sends stream:true to servers that do not advertise it', async () => {+ const { app, lib } = await setup({ loading: false });+ const res = await request(app).post('/api/generate').send({ prompt: 'x' });+ await until(() => lib.get(res.body[0].id)?.status === 'done');+ expect(fake!.requests.find((r) => r.path === '/v1/audio/speech')?.body).toMatchObject({ stream: false });+ expect(lib.get(res.body[0].id)?.renderedSeconds).toBeNull();+ });++ it('cancel mid-stream aborts upstream and marks cancelled', async () => {+ const { app, lib } = await setup({ stream: { windows: 50, windowMs: 40 } });+ const res = await request(app).post('/api/generate').send({ prompt: 'x' });+ const id = res.body[0].id as string;+ await until(() => (lib.get(id)?.renderedSeconds ?? 0) > 0);+ await request(app).delete(`/api/tracks/${id}`);+ await until(() => fake!.requests.find((r) => r.path === '/v1/audio/speech')?.aborted === true);+ expect(lib.get(id)).toBeUndefined();+ });});