Suno-style web UI for a self-hosted MiniMax-Music3 inference server
TypeScript ai-musicdiffusersdockerexpressminimaxminimax-musicmusic-generationreactself-hostedsgl-omnisunotailwindcsstext-to-musictypescriptvite
fix(server): disable undici timeouts for long upstream renders
Adam Benhasseneb371c072f91
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6b77567..76dfd9a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,7 @@## Unreleased+- Fix renders longer than 5 minutes failing with "upstream unreachable: fetch failed": the HTTP client's 300 s header/body timeouts are off for `/v1/audio/speech` (optional `UPSTREAM_TIMEOUT_MS`), and a timeout is reported as "upstream timed out after Ns".- Prompt enhancement: magic-wand button on the prompt field runs MiniMax's `music-caption-rewriter` skill on an OpenAI-compatible LLM (Settings or `LLM_API` / `LLM_API_KEY` / `LLM_MODEL`); undo restores the original text. Disabled in the demo.## v0.1.0 — 2026-08-19diff --git a/README.md b/README.mdindex d469894..ac448f2 100644--- a/README.md+++ b/README.md@@ -123,6 +123,7 @@ The inference server address is resolved in this order:| `LLM_API` | – | OpenAI-compatible base URL incl. `/v1` for prompt enhancement, e.g. `https://api.openai.com/v1`, `http://localhost:11434/v1` (overrides Settings) || `LLM_API_KEY` | – | Bearer key for `LLM_API`, if it needs one (overrides Settings) || `LLM_MODEL` | – | Chat model with tool calling, e.g. `gpt-4.1-mini` (overrides Settings) |+| `UPSTREAM_TIMEOUT_MS` | `0` | Max wait for a render's response (and between its chunks); `0` = no limit. The official route sends nothing until the song is done, so long songs need minutes || `PORT` | `8787` | Port for the UI server || `DATA_DIR` | `./data` | Where `library.json`, `templates.json`, `settings.json` and `tracks/` live || `STATIC_DIR` | `web/dist` (if built) | Directory of the built SPA to serve |diff --git a/package-lock.json b/package-lock.jsonindex 58c4432..821a093 100644--- a/package-lock.json+++ b/package-lock.json@@ -4261,7 +4261,8 @@"name": "@minimax-music-ui/server","version": "0.1.0","dependencies": {- "express": "^5.2.1"+ "express": "^5.2.1",+ "undici": "^7.30.0"},"devDependencies": {"@types/express": "^5.0.6",@@ -4273,6 +4274,15 @@"vitest": "^5.0.2"}},+ "server/node_modules/undici": {+ "version": "7.30.0",+ "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.0.tgz",+ "integrity": "sha512-dkrQXeHSaoamnItlYbmzG0wFYrM0ZwDxCIg0A7aKjTyyhh9svRzCNFEzV+Vm05/yehjCzjDZ31KXfGEjYSztDQ==",+ "license": "MIT",+ "engines": {+ "node": ">=20.18.1"+ }+ },"web": {"name": "@minimax-music-ui/web","version": "0.1.0",diff --git a/server/package.json b/server/package.jsonindex 0ac5390..2c242e6 100644--- a/server/package.json+++ b/server/package.json@@ -12,7 +12,8 @@"typecheck": "tsc -p tsconfig.json --noEmit"},"dependencies": {- "express": "^5.2.1"+ "express": "^5.2.1",+ "undici": "^7.30.0"},"devDependencies": {"@types/express": "^5.0.6",diff --git a/server/src/config.ts b/server/src/config.tsindex 2a3cf78..502213d 100644--- a/server/src/config.ts+++ b/server/src/config.ts@@ -12,6 +12,8 @@ export interface Config {llmApiEnv: string | null;llmApiKeyEnv: string | null;llmModelEnv: string | null;+ /** UPSTREAM_TIMEOUT_MS: max wait for a render's response (and between its chunks); 0 = no limit */+ upstreamTimeoutMs: number;/** DEMO=1: read-only public demo (see demo.ts) */demo: boolean;}@@ -19,12 +21,15 @@ export interface Config {export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {const port = Number(env.PORT ?? 8787);if (!Number.isInteger(port) || port <= 0) throw new Error(`Invalid PORT: ${env.PORT}`);+ const upstreamTimeoutMs = Number(env.UPSTREAM_TIMEOUT_MS ?? 0);+ if (!Number.isInteger(upstreamTimeoutMs) || upstreamTimeoutMs < 0) throw new Error(`Invalid UPSTREAM_TIMEOUT_MS: ${env.UPSTREAM_TIMEOUT_MS}`);return {musicApiEnv: env.MUSIC_API?.trim() ? env.MUSIC_API.trim().replace(/\/+$/, '') : null,apiKeyEnv: env.MUSIC_API_KEY?.trim() || null,llmApiEnv: env.LLM_API?.trim() ? env.LLM_API.trim().replace(/\/+$/, '') : null,llmApiKeyEnv: env.LLM_API_KEY?.trim() || null,llmModelEnv: env.LLM_MODEL?.trim() || null,+ upstreamTimeoutMs,port,dataDir: path.resolve(env.DATA_DIR ?? './data'),staticDir: env.STATIC_DIR ? path.resolve(env.STATIC_DIR) : null,diff --git a/server/src/index.ts b/server/src/index.tsindex d779f07..ad0dfd9 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -22,7 +22,7 @@ const settings = new SettingsStore(path.join(config.dataDir, 'settings.json'), {await settings.load();const effective = settings.effective();-const upstream = new UpstreamClient(effective.musicApi, effective.apiKey, effective.compat);+const upstream = new UpstreamClient(effective.musicApi, effective.apiKey, effective.compat, config.upstreamTimeoutMs);const queue = new RenderQueue(library, upstream, tracksDir);const recovered = await queue.recover();diff --git a/server/src/upstream.ts b/server/src/upstream.tsindex 64d877e..de0e242 100644--- a/server/src/upstream.ts+++ b/server/src/upstream.ts@@ -3,6 +3,7 @@ import fsp from 'node:fs/promises';import path from 'node:path';import { pipeline } from 'node:stream/promises';import { Readable } from 'node:stream';+import { Agent, fetch as undiciFetch, type Response as UndiciResponse } from 'undici';import type { Library } from './library.js';import type { Track } from './types.js';import { parseSse } from './sse.js';@@ -54,8 +55,18 @@ export class UpstreamClient {private capabilities: string[] = [];private probed = false;- /** `compat`: pretend the server is stock sgl-omni — skip GET /health, so no loading state and no extras. */- constructor(private baseUrl: string, private apiKey: string | null = null, private compat = false) {}+ /**+ * `compat`: pretend the server is stock sgl-omni — skip GET /health, so no loading state and no extras.+ * `timeoutMs`: limit on waiting for /v1/audio/speech headers and between body chunks; 0 = none. The route+ * sends nothing until the whole song is rendered, so undici's 300 s defaults would cut long renders off.+ */+ constructor(private baseUrl: string, private apiKey: string | null = null, private compat = false, private readonly timeoutMs = 0) {}++ private _speechAgent: Agent | null = null;+ /** Lazy: callers that only ever probe health() (e.g. the settings "test connection" route) shouldn't pay for a connection pool they never use. */+ private get speechAgent(): Agent {+ return (this._speechAgent ??= new Agent({ headersTimeout: this.timeoutMs, bodyTimeout: this.timeoutMs }));+ }configure(baseUrl: string, apiKey: string | null, compat = false): void {this.baseUrl = baseUrl.replace(/\/+$/, '');@@ -131,7 +142,15 @@ export class UpstreamClient {}}- private async post(body: SpeechBody, stream: boolean, signal?: AbortSignal, extra: Record<string, unknown> = {}): Promise<Response> {+ /** undici's headers/body timeout (only when `timeoutMs` is set): the server is reachable, just slower than the limit. */+ private timedOut(err: unknown): UpstreamError | null {+ const e = err as { code?: string; cause?: { code?: string } };+ const code = e.cause?.code ?? e.code;+ if (code !== 'UND_ERR_HEADERS_TIMEOUT' && code !== 'UND_ERR_BODY_TIMEOUT') return null;+ return new UpstreamError(`upstream timed out after ${this.timeoutMs / 1000}s waiting for the render`);+ }++ private async post(body: SpeechBody, stream: boolean, signal?: AbortSignal, extra: Record<string, unknown> = {}): Promise<UndiciResponse> {await this.ensureProbed();const payload = {model: this.model,@@ -143,17 +162,18 @@ export class UpstreamClient {...(body.seed !== null ? { seed: body.seed } : {}),...extra,};- let res: Response;+ let res: UndiciResponse;try {- res = await fetch(`${this.baseUrl}/v1/audio/speech`, {+ res = await undiciFetch(`${this.baseUrl}/v1/audio/speech`, {method: 'POST',headers: this.headers({ 'Content-Type': 'application/json' }),body: JSON.stringify(payload),signal,+ dispatcher: this.speechAgent,});} catch (err) {if ((err as Error).name === 'AbortError') throw err;- throw new UpstreamError(`upstream unreachable: ${(err as Error).message}`);+ throw this.timedOut(err) ?? new UpstreamError(`upstream unreachable: ${(err as Error).message}`);}if (!res.ok) {const text = await res.text().catch(() => '');@@ -162,7 +182,7 @@ export class UpstreamClient {return res;}- private static seedOf(res: Response): number | null {+ private static seedOf(res: UndiciResponse): number | null {const h = res.headers.get('x-seed');return h !== null && h !== '' && Number.isFinite(Number(h)) ? Number(h) : null;}@@ -172,7 +192,11 @@ export class UpstreamClient {const res = await this.post(body, false, signal);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 });+ try {+ await pipeline(Readable.fromWeb(res.body), fs.createWriteStream(dest), { signal });+ } catch (err) {+ throw this.timedOut(err) ?? err;+ }return { seed: UpstreamClient.seedOf(res) };}@@ -214,6 +238,8 @@ export class UpstreamClient {if (!finished) throw new UpstreamError('upstream stream ended before done');if (!header) throw new UpstreamError('upstream stream carried no audio');await fd.write(patchWavSizes(header, WAV_HEADER_BYTES + dataBytes), 0, WAV_HEADER_BYTES, 0);+ } catch (err) {+ throw this.timedOut(err) ?? err;} finally {await fd.close();}diff --git a/server/test/upstream.test.ts b/server/test/upstream.test.tsindex 09abcf0..ab527eb 100644--- a/server/test/upstream.test.ts+++ b/server/test/upstream.test.ts@@ -41,3 +41,29 @@ describe('UpstreamClient streaming', () => {await expect(c.speechStream(body, path.join(os.tmpdir(), 'x.wav'), () => {})).rejects.toThrow(/400/);});});++describe('UpstreamClient render timeout', () => {+ const dest = async () => path.join(await fs.mkdtemp(path.join(os.tmpdir(), 'up-')), 'a.wav');++ it('a render slower than UPSTREAM_TIMEOUT_MS fails as a timeout, not as unreachable', async () => {+ fake = await startFakeUpstream({ renderMs: 2500 }); // undici checks timeouts on a ~1 s tick, so leave headroom+ const c = new UpstreamClient(fake.url, null, false, 200);+ await expect(c.speechToFile(body, await dest())).rejects.toThrow('upstream timed out after 0.2s waiting for the render');+ });++ it('no timeout (0): waits for a render however long it takes', async () => {+ fake = await startFakeUpstream({ renderMs: 400 });+ const c = new UpstreamClient(fake.url, null, false, 0);+ const out = await dest();+ await c.speechToFile(body, out);+ expect((await fs.readFile(out)).toString()).toBe('RIFF-fake-audio');+ });++ it('user cancel still aborts a render with no timeout', async () => {+ fake = await startFakeUpstream({ renderMs: 2000 });+ const c = new UpstreamClient(fake.url);+ const ac = new AbortController();+ setTimeout(() => ac.abort(), 100);+ await expect(c.speechToFile(body, await dest(), ac.signal)).rejects.toMatchObject({ name: 'AbortError' });+ });+});