Suno-style web UI for a self-hosted MiniMax-Music3 inference server
TypeScript ai-musicdiffusersdockerexpressminimaxminimax-musicmusic-generationreactself-hostedsgl-omnisunotailwindcsstext-to-musictypescriptvite
feat: configurable inference server via Settings page; add Dockerfile and compose
Adam Benhassen4728a47e3f7c
diff --git a/.dockerignore b/.dockerignorenew file mode 100644index 0000000..8e1730f--- /dev/null+++ b/.dockerignore@@ -0,0 +1,9 @@+node_modules+*/node_modules+*/dist+data+docs+.git+.playwright-cli+*.log+.DS_Storediff --git a/Dockerfile b/Dockerfilenew file mode 100644index 0000000..824b743--- /dev/null+++ b/Dockerfile@@ -0,0 +1,33 @@+# syntax=docker/dockerfile:1.7++# ---- build ---------------------------------------------------------------+FROM node:22-alpine AS build+WORKDIR /app+COPY package.json package-lock.json ./+COPY server/package.json server/+COPY web/package.json web/+RUN npm ci+COPY server server+COPY web web+RUN npm run build \+ && npm prune --omit=dev++# ---- runtime -------------------------------------------------------------+FROM node:22-alpine+ENV NODE_ENV=production \+ PORT=8787 \+ DATA_DIR=/data \+ STATIC_DIR=/app/web/dist+WORKDIR /app+COPY --from=build /app/package.json ./+COPY --from=build /app/node_modules ./node_modules+COPY --from=build /app/server/package.json ./server/+COPY --from=build /app/server/dist ./server/dist+COPY --from=build /app/web/dist ./web/dist+RUN mkdir -p /data && chown -R node:node /data /app+USER node+VOLUME ["/data"]+EXPOSE 8787+HEALTHCHECK --interval=30s --timeout=5s --start-period=10s \+ CMD wget -qO- http://127.0.0.1:8787/api/library >/dev/null || exit 1+CMD ["node", "server/dist/index.js"]diff --git a/README.md b/README.mdindex 40d46f9..e0463e2 100644--- a/README.md+++ b/README.md@@ -27,6 +27,7 @@- **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".- **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.+- **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@@ -59,16 +60,33 @@ MUSIC_API=http://<inference-host>:7862 npm start# → http://localhost:8787```+Then open **Settings** in the sidebar and enter the inference server URL — or set `MUSIC_API` in the environment (see below).++### Docker++```bash+docker compose up -d --build # → http://localhost:8787, library persisted in ./data+# or+docker build -t minimax-music-ui .+docker run -d -p 8787:8787 -v "$PWD/data:/data" minimax-music-ui+```++Set `MUSIC_API` / `MUSIC_API_KEY` in the environment (or a `.env` next to `docker-compose.yml`) to pin the inference server; leave them unset to configure it from the Settings page. When the inference server runs on the Docker host, use `http://host.docker.internal:7862`.+### Configuration-All configuration is via environment variables on the server process.+The inference server address is resolved in this order:++1. `MUSIC_API` / `MUSIC_API_KEY` environment variables — always win; the Settings page shows them locked+2. Values saved from the **Settings** page (`data/settings.json`, written with mode `0600`)+3. Default `http://127.0.0.1:7862`| Variable | Default | Description ||---|---|---|-| `MUSIC_API` | `http://127.0.0.1:7862` | Base URL of the inference server |-| `MUSIC_API_KEY` | – | Sent as `Authorization: Bearer …` if the inference server was started with `--api-key` |+| `MUSIC_API` | – | Base URL of the inference server (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` and `tracks/` live |+| `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 |## Development@@ -98,6 +116,9 @@ FAKE_AUDIO=/path/to/real.wav FAKE_ADVANCE_MS=1500 npm run fake -w server| `GET` | `/api/templates` | Saved templates || `POST` | `/api/templates` | `{name, prompt, lyrics?, duration?, steps?, 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 |## Upstream APIdiff --git a/docker-compose.yml b/docker-compose.ymlnew file mode 100644index 0000000..d4edcd8--- /dev/null+++ b/docker-compose.yml@@ -0,0 +1,15 @@+services:+ minimax-music-ui:+ build: .+ image: minimax-music-ui+ container_name: minimax-music-ui+ ports:+ - "8787:8787"+ volumes:+ - ./data:/data+ environment:+ # Optional. When set, these lock the corresponding fields in Settings.+ # Leave unset to configure the inference server from the UI instead.+ MUSIC_API: ${MUSIC_API:-}+ MUSIC_API_KEY: ${MUSIC_API_KEY:-}+ restart: unless-stoppeddiff --git a/server/src/app.ts b/server/src/app.tsindex 27fd6fd..8831272 100644--- a/server/src/app.ts+++ b/server/src/app.ts@@ -6,12 +6,14 @@ import type { JsonStore, Library } from './library.js';import type { Poller } from './poller.js';import { 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';export interface AppDeps {library: Library;templates: JsonStore<Template>;+ settings: SettingsStore;upstream: UpstreamClient;poller: Poller;tracksDir: string;@@ -22,7 +24,7 @@ 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, upstream, poller, tracksDir } = deps;+ const { library, templates, settings, upstream, poller, tracksDir } = deps;const log = deps.log ?? ((m: string) => console.log(`[app] ${m}`));const app = express();app.use(express.json({ limit: '1mb' }));@@ -126,6 +128,44 @@ export function createApp(deps: AppDeps) {});});+ app.get('/api/settings', (_req, res) => {+ res.json(settings.publicView());+ });++ app.put('/api/settings', async (req, res, next) => {+ try {+ const b = (req.body ?? {}) as Record<string, unknown>;+ await settings.update({ musicApi: b.musicApi, apiKey: b.apiKey });+ 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) {+ next(err);+ }+ });++ app.post('/api/settings/test', async (req, res) => {+ const b = (req.body ?? {}) as Record<string, unknown>;+ const e = settings.effective();+ 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;+ } 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 });+ } catch (err) {+ res.json({ ok: false, musicApi: url, error: (err as Error).message });+ }+ });+app.get('/api/templates', (_req, res) => {res.json(templates.all());});diff --git a/server/src/config.ts b/server/src/config.tsindex 95a8e86..c893bf5 100644--- a/server/src/config.ts+++ b/server/src/config.ts@@ -1,8 +1,10 @@import path from 'node:path';export interface Config {- musicApi: string;- apiKey: string | null;+ /** MUSIC_API from env, or null when not set (then settings.json / default apply) */+ musicApiEnv: string | null;+ /** MUSIC_API_KEY from env, or null when not set */+ apiKeyEnv: string | null;port: number;dataDir: string;staticDir: string | null;@@ -12,8 +14,8 @@ 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}`);return {- musicApi: (env.MUSIC_API ?? 'http://127.0.0.1:7862').replace(/\/+$/, ''),- apiKey: env.MUSIC_API_KEY?.trim() || null,+ musicApiEnv: env.MUSIC_API?.trim() ? env.MUSIC_API.trim().replace(/\/+$/, '') : null,+ apiKeyEnv: env.MUSIC_API_KEY?.trim() || null,port,dataDir: path.resolve(env.DATA_DIR ?? './data'),staticDir: env.STATIC_DIR ? path.resolve(env.STATIC_DIR) : null,diff --git a/server/src/index.ts b/server/src/index.tsindex ce09efd..2aa6cef 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -5,6 +5,7 @@ import { loadConfig } from './config.js';import { JsonStore, Library } from './library.js';import type { Template } from './types.js';import { UpstreamClient } from './upstream.js';+import { SettingsStore } from './settings.js';import { Poller } from './poller.js';import { createApp } from './app.js';@@ -15,19 +16,22 @@ await library.load();const templates = new JsonStore<Template>(path.join(config.dataDir, 'templates.json'));await templates.load();-const upstream = new UpstreamClient(config.musicApi, config.apiKey);+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 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, upstream, poller, tracksDir, staticDir });+const app = createApp({ library, templates, settings, upstream, poller, tracksDir, staticDir });poller.start();app.listen(config.port, () => {console.log(`minimax-music-ui server on http://localhost:${config.port}`);- console.log(` upstream: ${config.musicApi}${config.apiKey ? ' (bearer set)' : ''}`);+ 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;diff --git a/server/src/settings.ts b/server/src/settings.tsnew file mode 100644index 0000000..df10dff--- /dev/null+++ b/server/src/settings.ts@@ -0,0 +1,104 @@+import fs from 'node:fs/promises';+import path from 'node:path';+import { ValidationError } from './validate.js';++export interface StoredSettings {+ musicApi: string | null;+ apiKey: string | null;+}++export interface EnvOverrides {+ musicApi: string | null;+ apiKey: string | null;+}++export interface EffectiveUpstream {+ musicApi: string;+ apiKey: string | null;+ /** where each value came from */+ source: { musicApi: 'env' | 'settings' | 'default'; apiKey: 'env' | 'settings' | 'none' };+}++export const DEFAULT_MUSIC_API = 'http://127.0.0.1:7862';+++export function normalizeMusicApi(v: unknown): string {+ if (typeof v !== 'string' || !v.trim()) throw new ValidationError('musicApi is required');+ let url: URL;+ try {+ url = new URL(v.trim());+ } catch {+ throw new ValidationError('musicApi must be a valid URL, e.g. http://100.105.185.107:7862');+ }+ if (url.protocol !== 'http:' && url.protocol !== 'https:') throw new ValidationError('musicApi must be http or https');+ return url.toString().replace(/\/+$/, '');+}++/** Persists user-editable upstream settings; env vars always win over stored values. */+export class SettingsStore {+ private stored: StoredSettings = { musicApi: null, apiKey: null };+ private writing: Promise<void> = Promise.resolve();++ constructor(private readonly file: string, private readonly env: EnvOverrides) {}++ async load(): Promise<void> {+ try {+ const raw = JSON.parse(await fs.readFile(this.file, 'utf8')) as Partial<StoredSettings>;+ this.stored = {+ musicApi: typeof raw.musicApi === 'string' && raw.musicApi ? raw.musicApi : null,+ apiKey: typeof raw.apiKey === 'string' && raw.apiKey ? raw.apiKey : null,+ };+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;+ }+ }++ effective(): EffectiveUpstream {+ const musicApi = this.env.musicApi ?? this.stored.musicApi ?? DEFAULT_MUSIC_API;+ const apiKey = this.env.apiKey ?? this.stored.apiKey;+ return {+ musicApi,+ apiKey,+ source: {+ musicApi: this.env.musicApi ? 'env' : this.stored.musicApi ? 'settings' : 'default',+ apiKey: this.env.apiKey ? 'env' : this.stored.apiKey ? 'settings' : 'none',+ },+ };+ }++ /** What the UI may see: never the key itself. */+ publicView() {+ const e = this.effective();+ return {+ musicApi: e.musicApi,+ apiKeySet: !!e.apiKey,+ source: e.source,+ locked: { musicApi: this.env.musicApi !== null, apiKey: this.env.apiKey !== null },+ };+ }++ /** Update stored values. `apiKey: ""` clears it; `undefined` leaves it alone. */+ async update(patch: { musicApi?: unknown; apiKey?: unknown }): Promise<void> {+ if (patch.musicApi !== undefined) {+ if (this.env.musicApi !== null) throw new ValidationError('MUSIC_API is set in the environment and cannot be changed here');+ this.stored.musicApi = normalizeMusicApi(patch.musicApi);+ }+ if (patch.apiKey !== undefined) {+ if (this.env.apiKey !== null) throw new ValidationError('MUSIC_API_KEY is set in the environment and cannot be changed here');+ if (typeof patch.apiKey !== 'string') throw new ValidationError('apiKey must be a string');+ this.stored.apiKey = patch.apiKey.trim() || null;+ }+ await this.persist();+ }++ private persist(): Promise<void> {+ const snapshot = JSON.stringify(this.stored, null, 2);+ this.writing = this.writing.then(async () => {+ await fs.mkdir(path.dirname(this.file), { recursive: true });+ const tmp = `${this.file}.${process.pid}.tmp`;+ await fs.writeFile(tmp, snapshot, { encoding: 'utf8', mode: 0o600 });+ await fs.rename(tmp, this.file);+ });+ return this.writing;+ }+}diff --git a/server/src/upstream.ts b/server/src/upstream.tsindex c288ef1..301d410 100644--- a/server/src/upstream.ts+++ b/server/src/upstream.ts@@ -19,7 +19,17 @@ export class UpstreamError extends Error {}export class UpstreamClient {- constructor(private readonly baseUrl: string, private readonly apiKey: string | null = null) {}+ 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;+ }++ get url(): string {+ return this.baseUrl;+ }private headers(extra: Record<string, string> = {}): Record<string, string> {const h: Record<string, string> = { ...extra };diff --git a/server/test/app.test.ts b/server/test/app.test.tsindex fede2da..25555d1 100644--- a/server/test/app.test.ts+++ b/server/test/app.test.ts@@ -8,23 +8,26 @@ import type { Template } from '../src/types.js';import { UpstreamClient } from '../src/upstream.js';import { Poller } from '../src/poller.js';import { createApp, titleFromPrompt } from '../src/app.js';+import { SettingsStore } from '../src/settings.js';import { startFakeUpstream, type FakeUpstream } from './fakeUpstream.js';let fake: FakeUpstream | null = null;afterEach(async () => { await fake?.close(); fake = null; });-async function setup(opts: Parameters<typeof startFakeUpstream>[0] = {}, apiKey: string | null = null) {+async function setup(opts: Parameters<typeof startFakeUpstream>[0] = {}, apiKey: string | null = null, env: { musicApi: string | null; apiKey: string | null } | null = null) {fake = await startFakeUpstream(opts);const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'app-'));const lib = new Library(path.join(dir, 'library.json'));await lib.load();+ const settings = new SettingsStore(path.join(dir, 'settings.json'), env ?? { musicApi: fake.url, 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, upstream, poller, tracksDir, log: () => {} });- return { app, lib, poller, tracksDir };+ const app = createApp({ library: lib, templates, settings, upstream, poller, tracksDir, log: () => {} });+ return { app, lib, poller, tracksDir, dir, upstream };}describe('app', () => {@@ -113,6 +116,49 @@ describe('app', () => {expect((await request(app).get('/api/templates')).body).toEqual([]);});+ it('settings: env-locked values cannot be changed', 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).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+ 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('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 } });+ 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('titleFromPrompt strips structured prefix', () => {expect(titleFromPrompt('Global Metadata: genre dream pop, 92 BPM, D major, wistful')).toBe('genre dream pop, 92 BPM, D');expect(titleFromPrompt(' ')).toBe('Untitled');diff --git a/web/src/App.tsx b/web/src/App.tsxindex 6b2348c..615c496 100644--- a/web/src/App.tsx+++ b/web/src/App.tsx@@ -7,6 +7,7 @@ import { HealthPill } from './components/HealthPill';import { CreatePanel, DEFAULT_FORM, formFromTrack, type FormState } from './components/CreatePanel';import { TrackFeed } from './components/TrackFeed';import { Player } from './components/Player';+import { SettingsPanel } from './components/SettingsPanel';const FORM_KEY = 'minimax-music-ui.form';@@ -92,10 +93,12 @@ export default function App() {<Sidebar view={view} onChange={setView} counts={{ inflight, total: tracks.length }} /><main className="flex-1 flex flex-col min-w-0"><header className="h-14 shrink-0 flex items-center justify-between gap-3 px-4 md:px-6 border-b border-ink-700">- <h1 className="text-base font-semibold truncate">{view === 'create' ? 'Create' : 'Library'}</h1>+ <h1 className="text-base font-semibold truncate">{view === 'create' ? 'Create' : view === 'library' ? 'Library' : 'Settings'}</h1><div className="flex items-center gap-3 shrink-0">{libError && <span className="text-xs text-red-400">UI server: {libError}</span>}- {health && !health.upstreamReachable && <span className="text-xs text-red-400 hidden md:inline">Set MUSIC_API and make sure the inference box is reachable</span>}+ {health && !health.upstreamReachable && view !== 'settings' && (+ <button className="text-xs text-red-400 hover:text-red-300 hidden md:inline underline-offset-2 hover:underline" onClick={() => setView('settings')}>Point the app at your inference server in Settings</button>+ )}<HealthPill health={health} /></div></header>@@ -106,6 +109,8 @@ export default function App() {</section><section className="p-4 md:p-5 lg:overflow-y-auto lg:min-h-0">{feed}</section></div>+ ) : view === 'settings' ? (+ <div className="flex-1 min-h-0 overflow-y-auto"><SettingsPanel onSaved={() => void refresh()} /></div>) : (<div className="flex-1 min-h-0 flex flex-col"><div className="px-5 pt-4">diff --git a/web/src/api.ts b/web/src/api.tsindex 69ceb46..76cae41 100644--- a/web/src/api.ts+++ b/web/src/api.ts@@ -1,4 +1,4 @@-import type { GenerateInput, Health, Template, Track } from './types';+import type { GenerateInput, Health, Settings, SettingsTestResult, Template, Track } from './types';async function json<T>(res: Response): Promise<T> {if (!res.ok) {@@ -22,6 +22,11 @@ export const api = {saveTemplate: (t: Omit<Template, 'id' | 'createdAt'>) =>fetch('/api/templates', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(t) }).then((r) => json<Template>(r)),deleteTemplate: (id: string) => fetch(`/api/templates/${id}`, { method: 'DELETE' }).then((r) => json<{ ok: true }>(r)),+ settings: () => fetch('/api/settings').then((r) => json<Settings>(r)),+ saveSettings: (patch: { musicApi?: string; apiKey?: string }) =>+ fetch('/api/settings', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(patch) }).then((r) => json<Settings>(r)),+ testSettings: (candidate: { musicApi?: string; apiKey?: string }) =>+ fetch('/api/settings/test', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(candidate) }).then((r) => json<SettingsTestResult>(r)),audioUrl: (id: string) => `/api/tracks/${id}/audio`,downloadUrl: (id: string) => `/api/tracks/${id}/audio?download`,};diff --git a/web/src/components/Icons.tsx b/web/src/components/Icons.tsxindex 5a8cda6..2ec055c 100644--- a/web/src/components/Icons.tsx+++ b/web/src/components/Icons.tsx@@ -18,3 +18,5 @@ export const Library = (p: SVGProps<SVGSVGElement>) => <svg {...base(p)}><path dexport const X = (p: SVGProps<SVGSVGElement>) => <svg {...base(p)}><path d="M6 6l12 12M18 6L6 18" /></svg>;export const Chevron = (p: SVGProps<SVGSVGElement>) => <svg {...base(p)}><path d="M9 6l6 6-6 6" /></svg>;export const Alert = (p: SVGProps<SVGSVGElement>) => <svg {...base(p)}><path d="M12 9v4m0 4h.01M10.3 3.9L2.5 18a2 2 0 0 0 1.7 3h15.6a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z" /></svg>;+export const Gear = (p: SVGProps<SVGSVGElement>) => <svg {...base(p)}><circle cx="12" cy="12" r="3" /><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z" /></svg>;+export const Lock = (p: SVGProps<SVGSVGElement>) => <svg {...base(p)}><rect x="4" y="11" width="16" height="10" rx="2" /><path d="M8 11V7a4 4 0 0 1 8 0v4" /></svg>;diff --git a/web/src/components/SettingsPanel.tsx b/web/src/components/SettingsPanel.tsxnew file mode 100644index 0000000..77558b7--- /dev/null+++ b/web/src/components/SettingsPanel.tsx@@ -0,0 +1,147 @@+import { useEffect, useState } from 'react';+import { api } from '../api';+import type { Settings, SettingsTestResult } from '../types';+import { Lock } from './Icons';++export function SettingsPanel({ onSaved }: { onSaved: () => void }) {+ const [settings, setSettings] = useState<Settings | null>(null);+ const [musicApi, setMusicApi] = useState('');+ const [apiKey, setApiKey] = useState('');+ const [clearKey, setClearKey] = useState(false);+ const [busy, setBusy] = useState<'save' | 'test' | null>(null);+ const [test, setTest] = useState<SettingsTestResult | null>(null);+ const [msg, setMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null);++ const load = async () => {+ const s = await api.settings();+ setSettings(s);+ setMusicApi(s.musicApi);+ setApiKey('');+ setClearKey(false);+ };+ useEffect(() => { load().catch((e) => setMsg({ kind: 'err', text: (e as Error).message })); }, []);++ if (!settings) return <div className="p-6 text-sm text-zinc-500">Loading settings…</div>;++ const dirty = musicApi.trim() !== settings.musicApi || apiKey !== '' || clearKey;+ const keyPatch = () => (clearKey ? '' : apiKey.trim() ? apiKey.trim() : undefined);++ const doTest = async () => {+ setBusy('test'); setTest(null); setMsg(null);+ try {+ const patch: { musicApi?: string; apiKey?: string } = {};+ if (!settings.locked.musicApi) patch.musicApi = musicApi.trim();+ const k = keyPatch();+ if (!settings.locked.apiKey && k !== undefined) patch.apiKey = k;+ setTest(await api.testSettings(patch));+ } catch (e) {+ setMsg({ kind: 'err', text: (e as Error).message });+ } finally {+ setBusy(null);+ }+ };++ const save = async () => {+ setBusy('save'); setMsg(null);+ try {+ const patch: { musicApi?: string; apiKey?: string } = {};+ if (!settings.locked.musicApi && musicApi.trim() !== settings.musicApi) patch.musicApi = musicApi.trim();+ const k = keyPatch();+ if (!settings.locked.apiKey && k !== undefined) patch.apiKey = k;+ const s = await api.saveSettings(patch);+ setSettings(s); setMusicApi(s.musicApi); setApiKey(''); setClearKey(false); setTest(null);+ setMsg({ kind: 'ok', text: 'Saved. The server now talks to the new address.' });+ onSaved();+ } catch (e) {+ setMsg({ kind: 'err', text: (e as Error).message });+ } finally {+ setBusy(null);+ }+ };++ const sourceLabel = (s: string) => ({ env: 'from environment', settings: 'saved in settings', default: 'default', none: 'not set' }[s] ?? s);++ return (+ <div className="p-6 max-w-2xl space-y-8">+ <section className="space-y-4">+ <div>+ <h2 className="text-sm font-semibold">Inference server</h2>+ <p className="text-xs text-zinc-500 mt-1">+ Where the MiniMax-Music3 API lives. 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>++ <div>+ <div className="flex items-center justify-between mb-1">+ <label className="label" htmlFor="musicApi">Base URL</label>+ <span className="text-[10px] text-zinc-500 flex items-center gap-1">+ {settings.locked.musicApi && <Lock width={11} height={11} />}+ {sourceLabel(settings.source.musicApi)}+ </span>+ </div>+ <input+ id="musicApi"+ className="field font-mono disabled:opacity-60"+ value={musicApi}+ disabled={settings.locked.musicApi}+ onChange={(e) => setMusicApi(e.target.value)}+ placeholder="http://100.105.185.107:7862"+ spellCheck={false}+ />+ </div>++ <div>+ <div className="flex items-center justify-between mb-1">+ <label className="label" htmlFor="apiKey">API key <span className="text-zinc-600 normal-case tracking-normal">(optional)</span></label>+ <span className="text-[10px] text-zinc-500 flex items-center gap-1">+ {settings.locked.apiKey && <Lock width={11} height={11} />}+ {sourceLabel(settings.source.apiKey)}+ </span>+ </div>+ <div className="flex gap-2">+ <input+ id="apiKey"+ type="password"+ className="field font-mono disabled:opacity-60"+ value={apiKey}+ disabled={settings.locked.apiKey || clearKey}+ onChange={(e) => setApiKey(e.target.value)}+ placeholder={settings.locked.apiKey ? '•••••••• (from environment)' : settings.apiKeySet ? '•••••••• (saved — enter a new key to replace)' : 'Only if the server was started with --api-key'}+ autoComplete="off"+ />+ {settings.apiKeySet && !settings.locked.apiKey && (+ <button type="button" className={`btn-ghost text-xs shrink-0 ${clearKey ? 'bg-ink-700 text-white' : ''}`} onClick={() => { setClearKey((c) => !c); setApiKey(''); }}>+ {clearKey ? 'Will clear' : 'Clear key'}+ </button>+ )}+ </div>+ <p className="text-[10px] text-zinc-600 mt-1">Sent as <code>Authorization: Bearer …</code>. Stored in <code>data/settings.json</code>; never returned to the browser.</p>+ </div>++ <div className="flex items-center gap-2 pt-1">+ <button type="button" className="btn-primary" disabled={busy !== null || !dirty} onClick={save}>{busy === 'save' ? 'Saving…' : 'Save'}</button>+ <button type="button" className="btn-ghost border border-ink-600" disabled={busy !== null} onClick={doTest}>{busy === 'test' ? 'Testing…' : 'Test connection'}</button>+ {dirty && !settings.locked.musicApi && <button type="button" className="btn-ghost text-xs" onClick={() => void load()}>Reset</button>}+ </div>++ {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(', ')}` : ''}</>+ : <>Could not reach <span className="font-mono">{test.musicApi}</span>: {test.error}</>}+ </div>+ )}+ {msg && <div className={`text-xs ${msg.kind === 'ok' ? 'text-emerald-300' : 'text-red-400'}`}>{msg.text}</div>}+ </section>++ <section className="space-y-2">+ <h2 className="text-sm font-semibold">Precedence</h2>+ <ol className="text-xs text-zinc-400 list-decimal list-inside space-y-1">+ <li><code className="text-zinc-300">MUSIC_API</code> / <code className="text-zinc-300">MUSIC_API_KEY</code> environment variables (locked above)</li>+ <li>Values saved on this page (<code className="text-zinc-300">data/settings.json</code>)</li>+ <li>Default <code className="text-zinc-300">http://127.0.0.1:7862</code></li>+ </ol>+ </section>+ </div>+ );+}diff --git a/web/src/components/Sidebar.tsx b/web/src/components/Sidebar.tsxindex 4b2a313..71a925c 100644--- a/web/src/components/Sidebar.tsx+++ b/web/src/components/Sidebar.tsx@@ -1,6 +1,6 @@-import { Library, Music, Sparkle } from './Icons';+import { Gear, Library, Music, Sparkle } from './Icons';-export type View = 'create' | 'library';+export type View = 'create' | 'library' | 'settings';export function Sidebar({ view, onChange, counts }: { view: View; onChange: (v: View) => void; counts: { inflight: number; total: number } }) {const item = (v: View, label: string, Icon: typeof Sparkle, badge?: number) => (@@ -27,7 +27,9 @@ export function Sidebar({ view, onChange, counts }: { view: View; onChange: (v:</div>{item('create', 'Create', Sparkle, counts.inflight)}{item('library', 'Library', Library, undefined)}- <div className="mt-auto px-3 py-2 text-[11px] text-zinc-500 hidden md:block">{counts.total} track{counts.total === 1 ? '' : 's'}</div>+ <div className="mt-auto" />+ {item('settings', 'Settings', Gear, undefined)}+ <div className=" px-3 py-2 text-[11px] text-zinc-500 hidden md:block">{counts.total} track{counts.total === 1 ? '' : 's'}</div></aside>);}diff --git a/web/src/types.ts b/web/src/types.tsindex bdf317d..5e2308e 100644--- a/web/src/types.ts+++ b/web/src/types.ts@@ -60,3 +60,17 @@ export interface Template {format: string;createdAt: string;}++export interface Settings {+ musicApi: string;+ apiKeySet: boolean;+ source: { musicApi: 'env' | 'settings' | 'default'; apiKey: 'env' | 'settings' | 'none' };+ locked: { musicApi: boolean; apiKey: boolean };+}++export interface SettingsTestResult {+ ok: boolean;+ musicApi: string;+ health?: Health;+ error?: string;+}