Local AI BGM and sound effects for Claude Code and any MCP client. Stable Audio 3 on Apple Silicon (MLX) and Windows NVIDIA GPUs (PyTorch). No cloud, no API key.
Python apple-siliconaudio-generationclaude-codecudagame-audiomcpmcp-servermlxmusic-generationpytorchsound-effectsstable-audiowindows
Web UI: fixes from the full code review (GAME-223)
Kana1e76388771f0
diff --git a/src/audio_studio_mcp/server.py b/src/audio_studio_mcp/server.pyindex 8170a96..24c2c15 100644--- a/src/audio_studio_mcp/server.py+++ b/src/audio_studio_mcp/server.py@@ -402,13 +402,20 @@ async def unload_models() -> dict:return {"unloaded": await _backend.unload()}+def _port(text: str) -> int:+ port = int(text)+ if not 1 <= port <= 65535:+ raise argparse.ArgumentTypeError(f"port must be 1-65535, got {port}")+ return port++def main(argv: list[str] | None = None) -> None:global _preload_when_readyap = argparse.ArgumentParser(prog="audio-studio-mcp", description=__doc__.split("\n")[0])mode = ap.add_mutually_exclusive_group()mode.add_argument("--http", type=int, metavar="PORT",help="serve streamable HTTP on 127.0.0.1:PORT instead of stdio (local only)")- mode.add_argument("--web", type=int, metavar="PORT",+ mode.add_argument("--web", type=_port, metavar="PORT",help="serve the web UI at http://127.0.0.1:PORT/ and MCP at /mcp on the same ""port, sharing one loaded model (local only)")ap.add_argument("--no-browser", action="store_true", help="with --web: do not open a browser")@@ -422,12 +429,12 @@ def main(argv: list[str] | None = None) -> None:sys.exit(1)backend.start_idle_reaper(IDLE_UNLOAD_MIN)if args.preload:- if args.http or args.web:+ if args.http or args.web is not None:backend.preload()else:_preload_when_ready = True- if args.web:+ if args.web is not None:from . import webweb.serve(args.web, open_browser=not args.no_browser)elif args.http:diff --git a/src/audio_studio_mcp/static/app.js b/src/audio_studio_mcp/static/app.jsindex a18c111..a48d79b 100644--- a/src/audio_studio_mcp/static/app.js+++ b/src/audio_studio_mcp/static/app.js@@ -10,6 +10,7 @@ const state = {lib: { items: [], total: 0, offset: 0, query: "" },};const PAGE = 50;+const RESTORE_JOBS = 8;// ── i18n ───────────────────────────────────────────────────────────────────function pickLang(pref) {@@ -130,7 +131,7 @@ function initTabs() {// ── status bar ───────────────────────────────────────────────────────────────function renderStatus() {const box = $("#model-state"), text = $("#model-text"), s = state.status;- if (!s) { box.dataset.state = "error"; text.textContent = t("status.offline"); return; }+ if (!s) { box.dataset.state = "error"; text.textContent = t("status.offline"); $("#unload").disabled = true; return; }const busy = s.jobs.running > 0;box.dataset.state = busy ? "busy" : s.loaded ? "loaded" : "idle";text.textContent = `${busy ? t("status.working") : s.loaded ? t("status.loaded") : t("status.notLoaded")} · ${s.backend}`;@@ -173,7 +174,8 @@ function updateTypeUI() {updateDurationPlaceholder();}-const NUMBER_FIELDS = { duration_seconds: parseFloat, bpm: parseInt, seed: parseInt, cfg: parseFloat, steps: parseInt, peak_ceiling_db: parseFloat };+// Sent as typed; the server validates (a seed of 1.5 is an error, not 1).+const NUMBER_FIELDS = ["duration_seconds", "bpm", "seed", "cfg", "steps", "peak_ceiling_db"];function readForm() {const f = form(), type = currentType();const args = { audio_type: type, prompt: f.prompt.value.trim(), variations: parseInt(f.variations.value, 10) };@@ -183,10 +185,10 @@ function readForm() {if (v) args[k] = v;}}- for (const [k, parse] of Object.entries(NUMBER_FIELDS)) {+ for (const k of NUMBER_FIELDS) {if (k === "bpm" && type === "sfx") continue;const raw = f[k].value.trim();- if (raw !== "") args[k] = parse(raw, 10);+ if (raw !== "") args[k] = Number(raw);}const title = f.title.value.trim();if (title) args.title = title;@@ -325,14 +327,22 @@ async function pollJobs() {let finished = false;try {const r = await api("/api/jobs");+ const seen = new Set();for (const j of r.items) {const prev = state.jobs.get(j.id);if (prev && prev.status !== j.status && (j.status === "done" || j.status === "error")) finished = true;state.jobs.set(j.id, j);+ seen.add(j.id);+ }+ // The server restarted and forgot these: stop waiting for them.+ for (const j of state.jobs.values()) {+ if (!seen.has(j.id) && (j.status === "queued" || j.status === "running")) {+ state.jobs.set(j.id, { ...j, status: "error", position: null, error: t("jobs.lost") });+ }}renderJobs();} catch { /* server restarting: keep trying */ }- if (finished) { refreshStatus(); if (!$("#page-library").hidden) loadLibrary(true); }+ if (finished) refreshStatus();await new Promise((r) => setTimeout(r, 800));}} finally {@@ -343,7 +353,8 @@ async function pollJobs() {async function restoreJobs() {try {const r = await api("/api/jobs");- for (const j of r.items) state.jobs.set(j.id, j);+ // After a reload show the latest few jobs plus anything still waiting.+ r.items.forEach((j, i) => { if (i < RESTORE_JOBS || j.status === "queued" || j.status === "running") state.jobs.set(j.id, j); });renderJobs();pollJobs();} catch { /* offline */ }@@ -382,7 +393,8 @@ function regenerate(item) {function libraryItem(item) {const m = item.meta || {};const title = m.title || item.file;- const canRegen = m.kind === "generate" && m.seed != null;+ // The form has no "raw" type, so only these can be regenerated faithfully.+ const canRegen = m.kind === "generate" && m.seed != null && ["music", "instrument", "sfx"].includes(m.audio_type);const details = el("dl", { class: "item-details", hidden: true },metaRows(item).flatMap(([k, v]) => [el("dt", { text: k }), el("dd", { text: String(v) })]));const toggle = el("button", { class: "link-btn", type: "button", "aria-expanded": "false", text: t("act.details") });diff --git a/src/audio_studio_mcp/static/i18n.js b/src/audio_studio_mcp/static/i18n.jsindex d21b52a..3357e04 100644--- a/src/audio_studio_mcp/static/i18n.js+++ b/src/audio_studio_mcp/static/i18n.js@@ -29,7 +29,7 @@ window.I18N = {"gen.submit": "Generate", "gen.reset": "Reset","jobs.title": "Results", "jobs.empty": "Generated sounds appear here.","jobs.queued": "Waiting · #{n} in queue", "jobs.running": "Generating… {t}", "jobs.done": "Done in {t}",- "jobs.error": "Failed", "jobs.queueInfo": "{running} generating · {queued} waiting",+ "jobs.error": "Failed", "jobs.lost": "The server restarted before this finished. Please generate again.", "jobs.queueInfo": "{running} generating · {queued} waiting","cand.label": "Candidate {n}", "cand.seed": "seed {seed}","act.download": "Download", "act.copyPath": "Copy path", "act.useSeed": "Use this seed","act.regen": "Regenerate (same seed)", "act.details": "Details", "act.hideDetails": "Hide details",@@ -76,7 +76,7 @@ window.I18N = {"gen.submit": "生成", "gen.reset": "リセット","jobs.title": "結果", "jobs.empty": "生成した音はここに表示されます。","jobs.queued": "待機中・{n} 番目", "jobs.running": "生成中… {t}", "jobs.done": "完了({t})",- "jobs.error": "失敗", "jobs.queueInfo": "生成中 {running} 件・待機 {queued} 件",+ "jobs.error": "失敗", "jobs.lost": "完了前にサーバーが再起動しました。もう一度生成してください。", "jobs.queueInfo": "生成中 {running} 件・待機 {queued} 件","cand.label": "候補 {n}", "cand.seed": "シード {seed}","act.download": "ダウンロード", "act.copyPath": "パスをコピー", "act.useSeed": "このシードを使う","act.regen": "同じシードで再生成", "act.details": "詳細", "act.hideDetails": "詳細を閉じる",@@ -123,7 +123,7 @@ window.I18N = {"gen.submit": "生成", "gen.reset": "重置","jobs.title": "结果", "jobs.empty": "生成的声音会显示在这里。","jobs.queued": "排队中 · 第 {n} 位", "jobs.running": "生成中… {t}", "jobs.done": "完成({t})",- "jobs.error": "失败", "jobs.queueInfo": "生成中 {running} 个 · 排队 {queued} 个",+ "jobs.error": "失败", "jobs.lost": "完成前服务器已重启,请重新生成。", "jobs.queueInfo": "生成中 {running} 个 · 排队 {queued} 个","cand.label": "候选 {n}", "cand.seed": "种子 {seed}","act.download": "下载", "act.copyPath": "复制路径", "act.useSeed": "使用此种子","act.regen": "用同一种子重新生成", "act.details": "详情", "act.hideDetails": "收起详情",diff --git a/src/audio_studio_mcp/web.py b/src/audio_studio_mcp/web.pyindex 3c29289..9cb3b51 100644--- a/src/audio_studio_mcp/web.py+++ b/src/audio_studio_mcp/web.py@@ -19,7 +19,9 @@ from __future__ import annotationsimport asyncioimport itertoolsimport json+import osimport secrets+import statimport timefrom dataclasses import dataclass, fieldfrom pathlib import Path@@ -95,12 +97,18 @@ class JobQueue:self._seq = itertools.count(1)self._queue: asyncio.Queue[Job] | None = Noneself._worker: asyncio.Task | None = None+ self._loop: asyncio.AbstractEventLoop | None = Nonedef submit(self, tool: str, arguments: dict) -> Job:- if self._queue is None:- self._queue = asyncio.Queue()+ loop = asyncio.get_running_loop()+ if self._loop is not loop: # first call, or the app was restarted on a new loop+ self._loop, self._queue = loop, asyncio.Queue()+ for j in self.jobs.values():+ if j.status in ("queued", "running"): # their worker died with the old loop+ j.status, j.error, j.finished = "error", "interrupted (server restarted)", time.time()+ self._worker = Noneif self._worker is None or self._worker.done():- self._worker = asyncio.get_running_loop().create_task(self._run())+ self._worker = loop.create_task(self._run())job = Job(id=secrets.token_hex(6), tool=tool, arguments=arguments, seq=next(self._seq))self.jobs[job.id] = jobself._queue.put_nowait(job)@@ -126,18 +134,22 @@ class JobQueue:del self.jobs[j.id]async def _run(self) -> None:- assert self._queue is not None+ queue = self._queue+ assert queue is not Nonewhile True:- job = await self._queue.get()+ job = await queue.get()job.status, job.started = "running", time.time()try:job.result = _tool_result(await server.server.call_tool(job.tool, job.arguments))job.status = "done"except Exception as e: # ToolError carries the same text MCP clients seejob.error, job.status = str(e), "error"+ except asyncio.CancelledError: # server shutting down+ job.error, job.status = "cancelled", "error"+ raisefinally:job.finished = time.time()- self._queue.task_done()+ queue.task_done()jobs = JobQueue()@@ -179,15 +191,29 @@ def _safe_audio_path(name: str) -> Path | None:return resolved-def _entry(path: Path) -> dict:- st = path.stat()- meta = None+def _read_meta(side: Path) -> dict | None:+ try:+ meta = json.loads(side.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return None+ return meta if isinstance(meta, dict) else None+++# file name → (stat key, entry); a library request re-reads only changed files+_entry_cache: dict[str, tuple[tuple, dict]] = {}+++def _entry(path: Path, st: os.stat_result) -> dict:side = path.with_suffix(path.suffix + ".json")- if side.is_file():- try:- meta = json.loads(side.read_text(encoding="utf-8"))- except (OSError, ValueError):- meta = None+ try:+ side_mtime = side.stat().st_mtime_ns+ except OSError:+ side_mtime = None+ key = (str(path), st.st_mtime_ns, st.st_size, side_mtime)+ hit = _entry_cache.get(path.name)+ if hit and hit[0] == key:+ return hit[1]+ meta = _read_meta(side) if side_mtime is not None else Noneseconds = (meta or {}).get("seconds")if not isinstance(seconds, (int, float)):try:@@ -195,33 +221,47 @@ def _entry(path: Path) -> dict:seconds = round(float(sf.info(str(path)).duration), 3)except Exception:seconds = None- return {"file": path.name, "path": str(path), "size": st.st_size, "mtime": st.st_mtime,- "seconds": seconds, "format": path.suffix.lower().lstrip("."), "meta": meta}+ entry = {"file": path.name, "path": str(path), "size": st.st_size, "mtime": st.st_mtime,+ "seconds": seconds, "format": path.suffix.lower().lstrip("."), "meta": meta}+ _entry_cache[path.name] = (key, entry)+ return entrydef _search_text(e: dict) -> str:m = e["meta"] or {}- sf = m.get("sound_fields") or {}+ sf = m.get("sound_fields")parts = [e["file"], m.get("title"), m.get("prompt"), m.get("prompt_used"),- m.get("original_idea"), m.get("audio_type"), m.get("kind"), str(m.get("seed", "")),+ m.get("original_idea"), m.get("audio_type"), m.get("kind"), m.get("seed"),*(sf.values() if isinstance(sf, dict) else [])]- return " ".join(str(p) for p in parts if p).lower()+ return " ".join(str(p) for p in parts if p is not None and p != "").lower()def list_library(query: str = "", offset: int = 0, limit: int = 100) -> dict:root = _output_dir()- files = []- if root.is_dir():- files = [p for p in root.iterdir()- if p.suffix.lower() in AUDIO_EXTS and p.is_file() and not p.name.startswith(".")- and p.stat().st_size > 0] # skip names reserved by a running generation- files.sort(key=lambda p: p.stat().st_mtime, reverse=True)- entries = [_entry(p) for p in files]+ files: list[tuple[Path, os.stat_result]] = []+ try:+ names = list(root.iterdir()) if root.is_dir() else []+ except OSError:+ names = []+ for p in names:+ if p.suffix.lower() not in AUDIO_EXTS or p.name.startswith("."):+ continue+ try:+ st = p.stat()+ except OSError: # deleted while we scan+ continue+ if stat.S_ISREG(st.st_mode) and st.st_size > 0: # empty = name reserved by a running generation+ files.append((p, st))+ files.sort(key=lambda f: (f[1].st_mtime, f[0].name), reverse=True)+ if len(_entry_cache) > 2 * len(files) + 100:+ _entry_cache.clear()words = query.lower().split()- if words:- entries = [e for e in entries if all(w in _search_text(e) for w in words)]- return {"output_dir": str(root), "total": len(entries),- "items": entries[offset:offset + limit]}+ if not words: # build entries for the requested page only+ return {"output_dir": str(root), "total": len(files),+ "items": [_entry(p, st) for p, st in files[offset:offset + limit]]}+ entries = [e for e in (_entry(p, st) for p, st in files)+ if all(w in _search_text(e) for w in words)]+ return {"output_dir": str(root), "total": len(entries), "items": entries[offset:offset + limit]}# ── HTTP ─────────────────────────────────────────────────────────────────────@@ -230,10 +270,13 @@ def _err(status: int, message: str, **extra) -> JSONResponse:class LocalOnly:- """ASGI middleware for /api: loopback Host only; writes need a same-origin- Origin and a JSON body (blocks DNS rebinding and cross-site form posts)."""+ """ASGI middleware. /api: loopback Host only (DNS rebinding), no requests+ from other sites (Sec-Fetch-Site), and writes need a same-origin Origin and+ a JSON body (cross-site form posts). Every response: no framing (clickjacking)."""LOOPBACK = ("127.0.0.1", "localhost", "::1")+ FRAME_HEADERS = [(b"x-frame-options", b"DENY"),+ (b"content-security-policy", b"frame-ancestors 'none'")]def __init__(self, app, port: int | None) -> None:self.app, self.port = app, port@@ -248,22 +291,34 @@ class LocalOnly:return Falsereturn self.port is None or port == self.port- async def __call__(self, scope, receive, send):- if scope["type"] != "http" or not scope["path"].startswith("/api/"):- return await self.app(scope, receive, send)+ def _problem(self, scope) -> str | None:headers = {k.decode("latin-1"): v.decode("latin-1") for k, v in scope["headers"]}- problem = Noneif not self._host_ok(headers.get("host", "")):- problem = "host not allowed"- elif scope["method"] not in ("GET", "HEAD"):+ return "host not allowed"+ if headers.get("sec-fetch-site", "same-origin") not in ("same-origin", "none"):+ return "cross-site request refused"+ if scope["method"] not in ("GET", "HEAD"):origin = headers.get("origin")if origin is None or not self._host_ok(origin.split("://", 1)[-1]):- problem = "cross-origin request refused"- elif not headers.get("content-type", "").startswith("application/json"):- problem = "expected application/json"- if problem:- return await _err(403, problem)(scope, receive, send)- return await self.app(scope, receive, send)+ return "cross-origin request refused"+ if not headers.get("content-type", "").startswith("application/json"):+ return "expected application/json"+ return None++ async def __call__(self, scope, receive, send):+ if scope["type"] != "http":+ return await self.app(scope, receive, send)++ async def send_with_headers(message):+ if message["type"] == "http.response.start":+ message = {**message, "headers": [*message.get("headers", []), *self.FRAME_HEADERS]}+ await send(message)++ if scope["path"].startswith("/api/"):+ problem = self._problem(scope)+ if problem:+ return await _err(403, problem)(scope, receive, send_with_headers)+ return await self.app(scope, receive, send_with_headers)async def api_status(_: Request) -> Response:@@ -381,7 +436,8 @@ def serve(port: int, open_browser: bool = True) -> None:import uvicornurl = f"http://127.0.0.1:{port}/"- config = uvicorn.Config(create_app(port), host="127.0.0.1", port=port, log_level="info")+ config = uvicorn.Config(create_app(port), host="127.0.0.1", port=port, log_level="info",+ access_log=False) # the page polls; keep the console readablesrv = uvicorn.Server(config)def announce():diff --git a/tests/test_web.py b/tests/test_web.pyindex 2df1d20..739e35c 100644--- a/tests/test_web.py+++ b/tests/test_web.py@@ -156,8 +156,9 @@ def _make_library(fake):post.write(out / "a.wav", sine(1.0), 44100, "wav")post.write_sidecar(out / "a.wav", {"kind": "generate", "title": "Rain loop", "prompt": "soft rain","audio_type": "sfx", "seed": 42, "seconds": 1.0})- time.sleep(0.01)post.write(out / "b.flac", sine(0.5), 44100, "flac") # no sidecar+ os.utime(out / "a.wav", (1_700_000_000, 1_700_000_000))+ os.utime(out / "b.flac", (1_700_000_100, 1_700_000_100))(out / "notes.txt").write_text("x")(out / "reserved.wav").touch() # name reserved by a running generationreturn out@@ -185,6 +186,19 @@ def test_library_search_and_paging(client, fake):assert client.get("/api/library?limit=x").status_code == 400+def test_library_survives_bad_sidecars_and_picks_up_new_ones(client, fake):+ out = _make_library(fake)+ (out / "b.flac.json").write_text("[1, 2]") # valid JSON, not an object+ post.write(out / "c.wav", sine(0.2), 44100, "wav")+ (out / "c.wav.json").write_text("{broken")+ lib = client.get("/api/library?q=wav").json()+ assert {i["file"] for i in lib["items"]} == {"a.wav", "c.wav"}+ assert client.get("/api/library").json()["total"] == 3+ # a sidecar written after the first listing (cached entry) shows up+ post.write_sidecar(out / "c.wav", {"kind": "generate", "title": "late", "seed": 1})+ assert [i["file"] for i in client.get("/api/library?q=late").json()["items"]] == ["c.wav"]++def test_library_without_output_dir(client, fake):assert client.get("/api/library").json()["total"] == 0@@ -238,8 +252,40 @@ def test_rejects_foreign_host_and_cross_origin_writes(fake, monkeypatch):assert c.post("/api/jobs", content=b'{"arguments":{"prompt":"x"}}',headers={"Origin": good, "Content-Type": "text/plain"}).status_code == 403assert c.post("/api/jobs", json=body, headers={"Origin": good}).status_code == 202- # the page itself is not restricted beyond what the MCP SDK does- assert c.get("/").status_code == 200+ # reads from another site's page (e.g. <audio src> or fetch) are refused too+ for site in ("cross-site", "same-site"):+ assert c.get("/api/library", headers={"Sec-Fetch-Site": site}).status_code == 403+ assert c.get("/api/library", headers={"Sec-Fetch-Site": "same-origin"}).status_code == 200+ assert c.get("/api/library", headers={"Sec-Fetch-Site": "none"}).status_code == 200+ # the page cannot be framed (clickjacking)+ r = c.get("/")+ assert r.status_code == 200 and r.headers["x-frame-options"] == "DENY"+ assert "frame-ancestors 'none'" in r.headers["content-security-policy"]+ assert c.get("/api/status", headers={"Host": "evil.example"}).headers["x-frame-options"] == "DENY"+++def test_jobs_interrupted_by_a_new_event_loop_are_reported(fake):+ q = web.JobQueue()+ gate = threading.Event()+ orig = fake._generate+ fake._generate = lambda seeds, req: (gate.wait(10), orig(seeds, req))[1]++ async def first():+ q.submit("generate_audio", {"prompt": "x", "duration_seconds": 1})+ q.submit("generate_audio", {"prompt": "y", "duration_seconds": 1})+ await anyio.sleep(0.2) # first one running, second queued; then the loop ends+ anyio.run(first)+ gate.set()+ running, queued = sorted(q.jobs.values(), key=lambda j: j.seq)+ assert (running.status, running.error) == ("error", "cancelled")+ assert queued.status == "queued"++ async def second():+ job = q.submit("unload_models", {})+ while job.status != "done":+ await anyio.sleep(0.01)+ anyio.run(second)+ assert queued.status == "error" and "interrupted" in queued.error# ── real process: `audio-studio-mcp --web PORT` ──────────────────────────────@@ -289,7 +335,11 @@ async def test_web_flag_serves_ui_api_and_mcp_on_one_port(tmp_path):assert (await http("/api/library"))["total"] == 2 # both the web job and the MCP callfinally:proc.terminate()- out = proc.communicate(timeout=10)[0].decode(errors="replace")+ try:+ out = proc.communicate(timeout=10)[0].decode(errors="replace")+ except subprocess.TimeoutExpired:+ proc.kill()+ out = proc.communicate()[0].decode(errors="replace")assert f"web UI: {base}/" in out, out@@ -299,6 +349,13 @@ def test_web_and_http_are_exclusive(capsys):assert "not allowed with" in capsys.readouterr().err[email protected]("port", ["0", "70000", "x"])+def test_web_port_is_validated(capsys, port):+ with pytest.raises(SystemExit):+ server.main(["--web", port])+ assert "--web" in capsys.readouterr().err++def test_web_opens_browser_once_started(monkeypatch):opened = []started = threading.Event()