Skip to content

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.

Add a local web UI: --web PORT serves /mcp, the page and /api (GAME-223)

Kanaff52e7a9503a
diff --git a/src/audio_studio_mcp/server.py b/src/audio_studio_mcp/server.py
index 7a02f93..8170a96 100644
--- a/src/audio_studio_mcp/server.py
+++ b/src/audio_studio_mcp/server.py
@@ -12,6 +12,7 @@ process forever is not an option on a 16 GB Mac).
Run: audio-studio-mcp (stdio, what MCP clients launch)
audio-studio-mcp --http 8765 (one shared streamable-HTTP server on 127.0.0.1)
+ audio-studio-mcp --web 8765 (the same /mcp plus the web UI at http://127.0.0.1:8765/; see web.py)
"""
from __future__ import annotations
@@ -404,8 +405,13 @@ async def unload_models() -> dict:
def main(argv: list[str] | None = None) -> None:
global _preload_when_ready
ap = argparse.ArgumentParser(prog="audio-studio-mcp", description=__doc__.split("\n")[0])
- ap.add_argument("--http", type=int, metavar="PORT",
- help="serve streamable HTTP on 127.0.0.1:PORT instead of stdio (local only)")
+ 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",
+ 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")
ap.add_argument("--preload", action="store_true", help="load models at startup")
args = ap.parse_args(argv)
@@ -416,12 +422,15 @@ def main(argv: list[str] | None = None) -> None:
sys.exit(1)
backend.start_idle_reaper(IDLE_UNLOAD_MIN)
if args.preload:
- if args.http:
+ if args.http or args.web:
backend.preload()
else:
_preload_when_ready = True
- if args.http:
+ if args.web:
+ from . import web
+ web.serve(args.web, open_browser=not args.no_browser)
+ elif args.http:
server.run("streamable-http", host="127.0.0.1", port=args.http)
else:
server.run()
diff --git a/src/audio_studio_mcp/static/app.css b/src/audio_studio_mcp/static/app.css
new file mode 100644
index 0000000..d02f684
--- /dev/null
+++ b/src/audio_studio_mcp/static/app.css
@@ -0,0 +1,179 @@
+/* Audio Studio web UI. Neutral greys + one blue accent; status colours only
+ for status. Every text colour is >= 4.5:1 on the surface it sits on. */
+:root {
+ --bg: #f4f5f7;
+ --surface: #ffffff;
+ --surface-2: #f0f2f4;
+ --border: #d5d9de;
+ --border-strong: #b8bec6;
+ --text: #1b1f24;
+ --muted: #555e68;
+ --accent: #1d5fd6; /* links, focus, selected */
+ --accent-bg: #1d5fd6; /* primary button */
+ --accent-text: #ffffff;
+ --accent-soft: #e6eefc;
+ --ok: #1a7f37;
+ --warn: #8a5a00;
+ --danger: #b42318;
+ --danger-soft: #fdecea;
+ --shadow: 0 1px 2px rgba(16, 24, 40, .06);
+ --radius: 8px;
+ color-scheme: light;
+}
+@media (prefers-color-scheme: dark) {
+ :root:not([data-theme="light"]) {
+ --bg: #131518; --surface: #1c1f23; --surface-2: #24282d; --border: #343a41; --border-strong: #4a525b;
+ --text: #e7e9ec; --muted: #a4acb5; --accent: #79a8ff; --accent-bg: #2563eb; --accent-text: #ffffff;
+ --accent-soft: #1d2a42; --ok: #5cc37a; --warn: #e0b04f; --danger: #ff8f84; --danger-soft: #3a1f1d;
+ --shadow: none; color-scheme: dark;
+ }
+}
+:root[data-theme="dark"] {
+ --bg: #131518; --surface: #1c1f23; --surface-2: #24282d; --border: #343a41; --border-strong: #4a525b;
+ --text: #e7e9ec; --muted: #a4acb5; --accent: #79a8ff; --accent-bg: #2563eb; --accent-text: #ffffff;
+ --accent-soft: #1d2a42; --ok: #5cc37a; --warn: #e0b04f; --danger: #ff8f84; --danger-soft: #3a1f1d;
+ --shadow: none; color-scheme: dark;
+}
+
+* { box-sizing: border-box; }
+[hidden] { display: none !important; }
+html, body { margin: 0; }
+body {
+ background: var(--bg); color: var(--text);
+ font: 14px/1.5 system-ui, -apple-system, "Segoe UI", "Hiragino Sans", "Noto Sans JP", "Noto Sans SC", "Microsoft YaHei", sans-serif;
+ -webkit-font-smoothing: antialiased;
+}
+:lang(ja) body, body:lang(ja) { font-family: system-ui, -apple-system, "Hiragino Sans", "Yu Gothic UI", "Noto Sans JP", sans-serif; }
+:lang(zh) body, body:lang(zh) { font-family: system-ui, -apple-system, "PingFang SC", "Microsoft YaHei", "Noto Sans SC", sans-serif; }
+h1, h2 { margin: 0; font-weight: 600; }
+.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
+.muted { color: var(--muted); }
+.small { font-size: 12.5px; }
+:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+
+/* top bar */
+.topbar {
+ position: sticky; top: 0; z-index: 10;
+ display: flex; align-items: center; gap: 20px; flex-wrap: wrap;
+ padding: 10px 20px; background: var(--surface); border-bottom: 1px solid var(--border);
+}
+.brand { display: flex; align-items: center; gap: 8px; }
+.logo { width: 24px; height: 24px; }
+.logo rect { fill: var(--accent-bg); }
+.logo path { stroke: #fff; stroke-width: 2.4; stroke-linecap: round; fill: none; }
+.brand-name { font-weight: 650; font-size: 15px; }
+.version { color: var(--muted); font-size: 12px; }
+.tabs { display: flex; gap: 2px; }
+.tabs button {
+ appearance: none; border: 0; background: none; color: var(--muted); font: inherit; font-weight: 550;
+ padding: 7px 12px; border-radius: 6px; cursor: pointer;
+}
+.tabs button:hover { color: var(--text); background: var(--surface-2); }
+.tabs button[aria-selected="true"] { color: var(--accent); background: var(--accent-soft); }
+.status { margin-left: auto; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
+.model-state { display: inline-flex; align-items: center; gap: 6px; color: var(--muted); font-size: 12.5px; padding-right: 4px; }
+.model-state .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--border-strong); }
+.model-state[data-state="loaded"] .dot { background: var(--ok); }
+.model-state[data-state="busy"] .dot { background: var(--warn); }
+.model-state[data-state="error"] .dot { background: var(--danger); }
+
+/* controls */
+input[type="text"], input[type="number"], input[type="search"], textarea, select {
+ width: 100%; font: inherit; color: var(--text); background: var(--surface);
+ border: 1px solid var(--border-strong); border-radius: 6px; padding: 7px 9px;
+}
+textarea { resize: vertical; min-height: 64px; }
+input::placeholder, textarea::placeholder { color: var(--muted); opacity: 1; }
+input:focus, textarea:focus, select:focus { outline: 2px solid var(--accent); outline-offset: -1px; border-color: transparent; }
+[aria-invalid="true"] { border-color: var(--danger) !important; }
+.select-sm { width: auto; padding: 4px 6px; font-size: 12.5px; }
+.btn {
+ appearance: none; font: inherit; font-weight: 550; border-radius: 6px; padding: 7px 14px; cursor: pointer;
+ border: 1px solid var(--border-strong); background: var(--surface); color: var(--text);
+ display: inline-flex; align-items: center; gap: 6px; text-decoration: none; white-space: nowrap;
+}
+.btn:hover { background: var(--surface-2); }
+.btn:disabled { opacity: .55; cursor: not-allowed; }
+.btn-primary { background: var(--accent-bg); border-color: var(--accent-bg); color: var(--accent-text); }
+.btn-primary:hover { background: var(--accent-bg); filter: brightness(1.08); }
+.btn-quiet { background: transparent; }
+.btn-sm { padding: 4px 9px; font-size: 12.5px; }
+.link-btn { appearance: none; text-decoration: none; border: 0; background: none; color: var(--accent); font: inherit; font-size: 12.5px; padding: 2px 0; cursor: pointer; }
+.link-btn:hover { text-decoration: underline; }
+.link-btn:disabled { color: var(--muted); cursor: not-allowed; text-decoration: none; }
+
+/* layout */
+main { max-width: 1280px; margin: 0 auto; padding: 20px; }
+#page-generate { display: grid; grid-template-columns: minmax(340px, 460px) 1fr; gap: 20px; align-items: start; }
+@media (max-width: 900px) { #page-generate { grid-template-columns: 1fr; } }
+.panel { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow); }
+.form { padding: 18px; display: flex; flex-direction: column; gap: 14px; position: sticky; top: 72px; }
+.panel-title { font-size: 16px; }
+.field { display: flex; flex-direction: column; gap: 5px; min-width: 0; border: 0; padding: 0; margin: 0; }
+.field > label, .field > legend { font-weight: 550; font-size: 13px; padding: 0; }
+.hint { margin: 0; color: var(--muted); font-size: 12.5px; }
+.row { display: grid; grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)); gap: 10px; align-items: start; }
+.sfx-fields { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
+.segmented { display: flex; border: 1px solid var(--border-strong); border-radius: 6px; overflow: hidden; }
+.segmented label { flex: 1; position: relative; }
+.segmented input { position: absolute; opacity: 0; inset: 0; margin: 0; cursor: pointer; }
+.segmented span { display: block; text-align: center; padding: 6px 8px; font-weight: 550; color: var(--muted); border-left: 1px solid var(--border); white-space: nowrap; }
+.segmented label:first-child span { border-left: 0; }
+.segmented input:checked + span { background: var(--accent-soft); color: var(--accent); }
+.segmented input:focus-visible + span { outline: 2px solid var(--accent); outline-offset: -2px; }
+.segmented.compact span { padding: 6px 0; min-width: 30px; }
+.advanced { border-top: 1px solid var(--border); padding-top: 10px; }
+.advanced summary { cursor: pointer; font-weight: 550; color: var(--muted); }
+.advanced[open] summary { margin-bottom: 10px; color: var(--text); }
+.advanced > .field { margin-top: 10px; }
+.form-error { margin: 0; padding: 8px 10px; border-radius: 6px; background: var(--danger-soft); color: var(--danger); white-space: pre-wrap; word-break: break-word; }
+.actions { display: flex; gap: 8px; }
+
+/* results */
+.results-head { display: flex; align-items: baseline; gap: 12px; margin-bottom: 10px; }
+.results-head h2 { font-size: 15px; }
+.jobs { display: flex; flex-direction: column; gap: 12px; }
+.empty { color: var(--muted); padding: 28px; text-align: center; border: 1px dashed var(--border-strong); border-radius: var(--radius); margin: 0; }
+.job { padding: 14px; display: flex; flex-direction: column; gap: 10px; }
+.job-head { display: flex; gap: 10px; align-items: flex-start; }
+.job-prompt { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
+.job-state { font-size: 12.5px; color: var(--muted); white-space: nowrap; display: inline-flex; align-items: center; gap: 6px; }
+.job[data-status="error"] .job-state { color: var(--danger); }
+.job[data-status="done"] .job-state { color: var(--ok); }
+.spinner { width: 12px; height: 12px; border: 2px solid var(--border-strong); border-top-color: var(--accent); border-radius: 50%; animation: spin .9s linear infinite; }
+@keyframes spin { to { transform: rotate(360deg); } }
+@media (prefers-reduced-motion: reduce) { .spinner { animation: none; } }
+.progress { height: 3px; background: var(--surface-2); border-radius: 2px; overflow: hidden; }
+.progress > div { height: 100%; width: 30%; background: var(--accent); animation: slide 1.4s ease-in-out infinite; }
+@keyframes slide { from { transform: translateX(-100%); } to { transform: translateX(340%); } }
+.job-error { margin: 0; color: var(--danger); background: var(--danger-soft); padding: 8px 10px; border-radius: 6px; white-space: pre-wrap; word-break: break-word; font-size: 13px; }
+.candidates { display: grid; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); gap: 10px; }
+.cand { border: 1px solid var(--border); border-radius: 6px; padding: 10px; display: flex; flex-direction: column; gap: 8px; background: var(--surface-2); }
+.cand-head { display: flex; justify-content: space-between; gap: 8px; font-size: 12.5px; }
+.cand-head strong { font-weight: 600; }
+audio { width: 100%; height: 36px; }
+.cand-actions, .item-actions { display: flex; gap: 2px 12px; flex-wrap: wrap; }
+.badge { display: inline-block; font-size: 11.5px; font-weight: 600; padding: 1px 7px; border-radius: 10px; background: var(--surface-2); color: var(--muted); border: 1px solid var(--border); white-space: nowrap; }
+
+/* library */
+.library-bar { display: flex; gap: 10px; align-items: center; }
+.library-bar input { max-width: 440px; }
+.folder { margin: 8px 0 14px; word-break: break-all; }
+.library { display: flex; flex-direction: column; gap: 8px; }
+.item { padding: 12px 14px; display: grid; grid-template-columns: minmax(0, 1fr) minmax(220px, 320px); gap: 6px 16px; align-items: center; }
+@media (max-width: 760px) { .item { grid-template-columns: 1fr; } }
+.item-main { min-width: 0; display: flex; flex-direction: column; gap: 3px; }
+.item-title { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.item-meta { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; font-size: 12.5px; color: var(--muted); }
+.item-prompt { font-size: 13px; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.item-side { display: flex; flex-direction: column; gap: 6px; }
+.item-details { grid-column: 1 / -1; margin: 6px 0 0; display: grid; grid-template-columns: max-content 1fr; gap: 4px 14px; font-size: 12.5px; border-top: 1px solid var(--border); padding-top: 10px; }
+.item-details dt { color: var(--muted); }
+.item-details dd { margin: 0; word-break: break-word; }
+.more { text-align: center; margin-top: 14px; }
+mark { background: var(--accent-soft); color: inherit; border-radius: 2px; }
+
+.toast {
+ position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);
+ background: var(--text); color: var(--bg); padding: 8px 14px; border-radius: 6px; font-size: 13px; box-shadow: 0 4px 14px rgba(0,0,0,.2);
+}
diff --git a/src/audio_studio_mcp/static/app.js b/src/audio_studio_mcp/static/app.js
new file mode 100644
index 0000000..a18c111
--- /dev/null
+++ b/src/audio_studio_mcp/static/app.js
@@ -0,0 +1,461 @@
+// Audio Studio web UI. Plain JS, no build step. Talks to /api (see web.py).
+"use strict";
+
+const $ = (sel, root = document) => root.querySelector(sel);
+const state = {
+ lang: "en",
+ status: null,
+ jobs: new Map(), // id -> job view from the server
+ polling: false,
+ lib: { items: [], total: 0, offset: 0, query: "" },
+};
+const PAGE = 50;
+
+// ── i18n ───────────────────────────────────────────────────────────────────
+function pickLang(pref) {
+ if (pref && pref !== "auto" && I18N[pref]) return pref;
+ for (const l of navigator.languages || [navigator.language || "en"]) {
+ const base = l.toLowerCase().split("-")[0];
+ if (I18N[base]) return base;
+ }
+ return "en";
+}
+function t(key, vars) {
+ let s = (I18N[state.lang] && I18N[state.lang][key]) ?? I18N.en[key] ?? key;
+ if (vars) s = s.replace(/\{(\w+)\}/g, (_, k) => (k in vars ? vars[k] : `{${k}}`));
+ return s;
+}
+function applyI18n() {
+ document.documentElement.lang = state.lang === "zh" ? "zh-CN" : state.lang;
+ document.querySelectorAll("[data-i18n]").forEach((n) => { n.textContent = t(n.dataset.i18n); });
+ document.querySelectorAll("[data-i18n-placeholder]").forEach((n) => { n.placeholder = t(n.dataset.i18nPlaceholder); });
+ document.querySelectorAll("[data-i18n-title]").forEach((n) => { n.title = t(n.dataset.i18nTitle); });
+ updateTypeUI();
+ renderStatus();
+ renderJobs();
+ renderLibrary();
+}
+
+// ── helpers ────────────────────────────────────────────────────────────────
+function el(tag, attrs = {}, ...children) {
+ const n = document.createElement(tag);
+ for (const [k, v] of Object.entries(attrs)) {
+ if (v == null || v === false) continue;
+ if (k === "class") n.className = v;
+ else if (k === "text") n.textContent = v;
+ else if (k.startsWith("on")) n.addEventListener(k.slice(2), v);
+ else if (k === "dataset") Object.assign(n.dataset, v);
+ else n.setAttribute(k, v === true ? "" : v);
+ }
+ for (const c of children.flat()) if (c != null) n.append(c);
+ return n;
+}
+function fmtTime(sec) {
+ sec = Math.max(0, Math.round(sec || 0));
+ const m = Math.floor(sec / 60), s = sec % 60;
+ return `${m}:${String(s).padStart(2, "0")}`;
+}
+function fmtLen(sec) {
+ if (typeof sec !== "number") return "";
+ return sec < 60 ? `${sec.toFixed(sec < 10 ? 1 : 0)} s` : fmtTime(sec);
+}
+function fmtDate(epoch) {
+ const loc = state.lang === "zh" ? "zh-CN" : state.lang;
+ return new Date(epoch * 1000).toLocaleString(loc, { year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" });
+}
+function audioUrl(file, download) {
+ return `/api/audio/${encodeURIComponent(file)}${download ? "?download=1" : ""}`;
+}
+function baseName(p) { return String(p).split(/[\\/]/).pop(); }
+
+let toastTimer;
+function toast(msg) {
+ const n = $("#toast");
+ n.textContent = msg; n.hidden = false;
+ clearTimeout(toastTimer);
+ toastTimer = setTimeout(() => { n.hidden = true; }, 2200);
+}
+async function copyText(text) {
+ try { await navigator.clipboard.writeText(text); toast(t("toast.copied")); }
+ catch { toast(t("toast.copyFailed")); }
+}
+
+async function api(path, opts = {}) {
+ const init = { ...opts, headers: { ...(opts.headers || {}) } };
+ if (opts.json !== undefined) {
+ init.method = init.method || "POST";
+ init.headers["Content-Type"] = "application/json";
+ init.body = JSON.stringify(opts.json);
+ }
+ let res;
+ try { res = await fetch(path, init); }
+ catch { const e = new Error(t("err.network")); e.network = true; throw e; }
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) { const e = new Error(body.error || res.statusText); e.body = body; e.status = res.status; throw e; }
+ return body;
+}
+
+// ── theme / language settings ────────────────────────────────────────────────
+function initSettings() {
+ const theme = localStorage.getItem("as.theme") || "system";
+ $("#theme").value = theme;
+ $("#theme").addEventListener("change", (e) => {
+ const v = e.target.value;
+ if (v === "system") { delete document.documentElement.dataset.theme; localStorage.removeItem("as.theme"); }
+ else { document.documentElement.dataset.theme = v; localStorage.setItem("as.theme", v); }
+ });
+ const lang = localStorage.getItem("as.lang") || "auto";
+ $("#lang").value = lang;
+ state.lang = pickLang(lang);
+ $("#lang").addEventListener("change", (e) => {
+ const v = e.target.value;
+ if (v === "auto") localStorage.removeItem("as.lang"); else localStorage.setItem("as.lang", v);
+ state.lang = pickLang(v);
+ applyI18n();
+ });
+}
+
+// ── tabs ─────────────────────────────────────────────────────────────────────
+function showPage(name, push = true) {
+ document.querySelectorAll(".tabs [role=tab]").forEach((b) => b.setAttribute("aria-selected", String(b.dataset.page === name)));
+ document.querySelectorAll(".page").forEach((p) => { p.hidden = p.id !== `page-${name}`; });
+ if (push && location.hash !== `#${name}`) history.replaceState(null, "", `#${name}`);
+ if (name === "library") loadLibrary(true);
+}
+function initTabs() {
+ document.querySelectorAll(".tabs [role=tab]").forEach((b) => b.addEventListener("click", () => showPage(b.dataset.page)));
+ showPage(location.hash === "#library" ? "library" : "generate", false);
+}
+
+// ── 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; }
+ 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}`;
+ box.title = `${s.backend} — ${s.model}`;
+ $("#version").textContent = `v${s.version}`;
+ $("#unload").disabled = !s.loaded || busy;
+ $("#queue-info").textContent = (s.jobs.running || s.jobs.queued) ? t("jobs.queueInfo", s.jobs) : "";
+ $("#lib-folder").textContent = t("lib.folder", { dir: s.output_dir });
+ updateDurationPlaceholder();
+}
+async function refreshStatus() {
+ try { state.status = await api("/api/status"); }
+ catch { state.status = null; }
+ renderStatus();
+}
+async function unloadModel() {
+ $("#unload").disabled = true;
+ try {
+ const r = await api("/api/unload", { json: {} });
+ toast(r.unloaded ? t("status.unloaded") : t("status.nothingToUnload"));
+ } catch (e) { toast(e.message); }
+ refreshStatus();
+}
+
+// ── generate form ────────────────────────────────────────────────────────────
+const form = () => $("#gen-form");
+function currentType() { return form().audio_type.value; }
+function updateDurationPlaceholder() {
+ const d = state.status && state.status.default_seconds;
+ $("#duration_seconds").placeholder = d ? String(d[currentType()]) : "";
+ if (state.status) $("#duration_seconds").max = String(state.status.max_seconds);
+}
+function updateTypeUI() {
+ const type = currentType(), sfx = type === "sfx";
+ $("#sfx-fields").hidden = !sfx;
+ $("#bpm-field").hidden = sfx;
+ $("#prompt-label").textContent = t(`gen.prompt.${type}`);
+ $("#prompt-hint").textContent = t(`gen.promptHint.${type}`);
+ $("#prompt").placeholder = t(`gen.promptPh.${type}`);
+ updateDurationPlaceholder();
+}
+
+const NUMBER_FIELDS = { duration_seconds: parseFloat, bpm: parseInt, seed: parseInt, cfg: parseFloat, steps: parseInt, peak_ceiling_db: parseFloat };
+function readForm() {
+ const f = form(), type = currentType();
+ const args = { audio_type: type, prompt: f.prompt.value.trim(), variations: parseInt(f.variations.value, 10) };
+ if (type === "sfx") {
+ for (const k of ["sound_source", "sound_action", "sound_material", "sound_space"]) {
+ const v = f[k].value.trim();
+ if (v) args[k] = v;
+ }
+ }
+ for (const [k, parse] of Object.entries(NUMBER_FIELDS)) {
+ if (k === "bpm" && type === "sfx") continue;
+ const raw = f[k].value.trim();
+ if (raw !== "") args[k] = parse(raw, 10);
+ }
+ const title = f.title.value.trim();
+ if (title) args.title = title;
+ const neg = f.negative_prompt.value.trim();
+ if (neg) args.negative_prompt = neg;
+ return args;
+}
+function fillForm(meta) {
+ const f = form();
+ f.reset();
+ const type = ["music", "instrument", "sfx"].includes(meta.audio_type) ? meta.audio_type : "music";
+ f.audio_type.value = type;
+ f.prompt.value = meta.prompt || "";
+ const sf = meta.sound_fields || {};
+ f.sound_source.value = sf.source || ""; f.sound_action.value = sf.action || "";
+ f.sound_material.value = sf.material || ""; f.sound_space.value = sf.space || "";
+ f.duration_seconds.value = meta.seconds ?? "";
+ f.bpm.value = meta.bpm ?? "";
+ f.seed.value = meta.seed ?? "";
+ f.cfg.value = meta.cfg != null && meta.cfg !== 1 ? meta.cfg : "";
+ f.steps.value = meta.steps != null && meta.steps !== 8 ? meta.steps : "";
+ f.negative_prompt.value = meta.negative_prompt || "";
+ if (f.cfg.value || f.steps.value || f.negative_prompt.value) $("#advanced").open = true;
+ updateTypeUI();
+}
+function clearErrors() {
+ $("#form-error").hidden = true;
+ form().querySelectorAll("[aria-invalid]").forEach((n) => n.removeAttribute("aria-invalid"));
+}
+function showFormError(msg, fields) {
+ const box = $("#form-error");
+ box.textContent = msg; box.hidden = false;
+ for (const f of fields || []) {
+ const input = form().elements[f.field];
+ if (input && input.setAttribute) {
+ input.setAttribute("aria-invalid", "true");
+ if (["seed", "cfg", "steps", "peak_ceiling_db", "negative_prompt"].includes(f.field)) $("#advanced").open = true;
+ }
+ }
+}
+async function submitJob(args) {
+ clearErrors();
+ const hasText = args.prompt || args.sound_source || args.sound_action || args.sound_material || args.sound_space;
+ if (!hasText) { showFormError(t("err.emptyPrompt")); $("#prompt").setAttribute("aria-invalid", "true"); return null; }
+ $("#gen-submit").disabled = true;
+ try {
+ const job = await api("/api/jobs", { json: { tool: "generate_audio", arguments: args } });
+ state.jobs.set(job.id, job);
+ renderJobs();
+ pollJobs();
+ refreshStatus();
+ return job;
+ } catch (e) {
+ showFormError(e.message, e.body && e.body.fields);
+ return null;
+ } finally {
+ $("#gen-submit").disabled = false;
+ }
+}
+function initForm() {
+ form().addEventListener("change", (e) => { if (e.target.name === "audio_type") updateTypeUI(); });
+ form().addEventListener("input", (e) => e.target.removeAttribute && e.target.removeAttribute("aria-invalid"));
+ form().addEventListener("submit", (e) => { e.preventDefault(); submitJob(readForm()); });
+ form().addEventListener("keydown", (e) => {
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); form().requestSubmit(); }
+ });
+ $("#gen-reset").addEventListener("click", () => { form().reset(); clearErrors(); updateTypeUI(); });
+ $("#unload").addEventListener("click", unloadModel);
+}
+
+// ── jobs ─────────────────────────────────────────────────────────────────────
+function jobStateText(job) {
+ if (job.status === "queued") return t("jobs.queued", { n: job.position ?? 1 });
+ if (job.status === "running") return t("jobs.running", { t: fmtTime(job.elapsed) });
+ if (job.status === "done") return t("jobs.done", { t: fmtTime(job.elapsed) });
+ return t("jobs.error");
+}
+function promptLabel(a) {
+ const parts = [a.prompt, a.sound_source, a.sound_action, a.sound_material, a.sound_space].filter(Boolean);
+ return parts.join(", ") || "—";
+}
+function candidateCard(c, i) {
+ const file = baseName(c.path);
+ return el("div", { class: "cand" },
+ el("div", { class: "cand-head" },
+ el("strong", { text: t("cand.label", { n: i + 1 }) }),
+ el("span", { class: "muted", text: t("cand.seed", { seed: c.seed }) })),
+ el("audio", { controls: true, preload: "metadata", src: audioUrl(file) }),
+ el("div", { class: "cand-actions" },
+ el("a", { class: "link-btn", href: audioUrl(file, true), download: file, text: t("act.download") }),
+ el("button", { class: "link-btn", type: "button", text: t("act.copyPath"), onclick: () => copyText(c.path) }),
+ el("button", { class: "link-btn", type: "button", text: t("act.useSeed"),
+ onclick: () => { form().seed.value = c.seed; $("#advanced").open = true; toast(t("toast.seedSet", { seed: c.seed })); } })));
+}
+function jobCard(job) {
+ const a = job.arguments || {};
+ const active = job.status === "queued" || job.status === "running";
+ const card = el("article", { class: "panel job", dataset: { status: job.status, id: job.id } },
+ el("div", { class: "job-head" },
+ el("span", { class: "badge", text: t(`type.${a.audio_type || "music"}`) }),
+ el("span", { class: "job-prompt", title: promptLabel(a), text: promptLabel(a) }),
+ el("span", { class: "job-state" }, active ? el("span", { class: "spinner", "aria-hidden": "true" }) : null,
+ el("span", { class: "job-state-text", text: jobStateText(job) }))));
+ if (job.status === "running") card.append(el("div", { class: "progress", "aria-hidden": "true" }, el("div")));
+ if (job.status === "error") card.append(el("p", { class: "job-error", text: job.error || "" }));
+ if (job.status === "done" && job.result && Array.isArray(job.result.candidates)) {
+ card.append(el("div", { class: "candidates" }, job.result.candidates.map(candidateCard)));
+ }
+ return card;
+}
+function renderJobs() {
+ const box = $("#jobs");
+ const list = [...state.jobs.values()].sort((x, y) => y.created - x.created);
+ $("#jobs-empty").hidden = list.length > 0;
+ // Keep finished cards (their <audio> may be playing); rebuild only cards whose status changed.
+ const existing = new Map([...box.children].map((n) => [n.dataset.id, n]));
+ const nodes = list.map((job) => {
+ const old = existing.get(job.id);
+ if (old && old.dataset.status === job.status && old.dataset.lang === state.lang) {
+ const st = old.querySelector(".job-state-text");
+ if (st) st.textContent = jobStateText(job);
+ return old;
+ }
+ const card = jobCard(job);
+ card.dataset.lang = state.lang;
+ return card;
+ });
+ nodes.forEach((n, i) => { if (box.children[i] !== n) box.insertBefore(n, box.children[i] || null); });
+ while (box.children.length > nodes.length) box.lastChild.remove();
+}
+async function pollJobs() {
+ if (state.polling) return;
+ state.polling = true;
+ try {
+ while ([...state.jobs.values()].some((j) => j.status === "queued" || j.status === "running")) {
+ let finished = false;
+ try {
+ const r = await api("/api/jobs");
+ 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);
+ }
+ renderJobs();
+ } catch { /* server restarting: keep trying */ }
+ if (finished) { refreshStatus(); if (!$("#page-library").hidden) loadLibrary(true); }
+ await new Promise((r) => setTimeout(r, 800));
+ }
+ } finally {
+ state.polling = false;
+ refreshStatus();
+ }
+}
+async function restoreJobs() {
+ try {
+ const r = await api("/api/jobs");
+ for (const j of r.items) state.jobs.set(j.id, j);
+ renderJobs();
+ pollJobs();
+ } catch { /* offline */ }
+}
+
+// ── library ──────────────────────────────────────────────────────────────────
+function metaRows(item) {
+ const m = item.meta;
+ if (!m) return [[t("meta.path"), item.path], ["", t("meta.noSidecar")]];
+ const sf = m.sound_fields && Object.values(m.sound_fields).filter(Boolean).join(" / ");
+ const kind = String(m.kind || "");
+ const rows = [
+ [t("meta.kind"), kind.startsWith("edit") ? `${t("kind.edit")} (${kind.split(":")[1] || ""})` : (I18N.en[`kind.${kind}`] ? t(`kind.${kind}`) : kind)],
+ [t("meta.type"), m.audio_type && t(`type.${m.audio_type}`)],
+ [t("meta.prompt"), m.prompt], [t("meta.sound"), sf], [t("meta.promptUsed"), m.prompt_used],
+ [t("meta.idea"), m.original_idea],
+ [t("meta.seconds"), fmtLen(typeof m.seconds === "number" ? m.seconds : item.seconds)],
+ [t("meta.bpm"), m.bpm], [t("meta.seed"), m.seed], [t("meta.cfg"), m.cfg], [t("meta.steps"), m.steps],
+ [t("meta.negative"), m.negative_prompt],
+ [t("meta.peak"), m.peak_dbfs != null ? `${m.peak_dbfs} dBFS` : null],
+ [t("meta.model"), m.model ? `${m.model} (${m.backend})` : null],
+ [t("meta.input"), m.input_audio], [t("meta.created"), m.created], [t("meta.path"), item.path],
+ ];
+ return rows.filter(([, v]) => v !== null && v !== undefined && v !== "");
+}
+function regenerate(item) {
+ const m = item.meta;
+ fillForm(m);
+ showPage("generate");
+ const args = readForm();
+ args.variations = 1;
+ args.seed = m.seed;
+ if (m.title) args.title = m.title;
+ submitJob(args).then((job) => { if (job) toast(t("toast.regenQueued")); });
+}
+function libraryItem(item) {
+ const m = item.meta || {};
+ const title = m.title || item.file;
+ const canRegen = m.kind === "generate" && m.seed != null;
+ 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") });
+ toggle.addEventListener("click", () => {
+ details.hidden = !details.hidden;
+ toggle.setAttribute("aria-expanded", String(!details.hidden));
+ toggle.textContent = details.hidden ? t("act.details") : t("act.hideDetails");
+ });
+ const kind = String(m.kind || "");
+ const badge = m.audio_type ? t(`type.${m.audio_type}`) : kind === "process" ? t("kind.process") : item.format.toUpperCase();
+ return el("article", { class: "panel item" },
+ el("div", { class: "item-main" },
+ el("div", { class: "item-title", title: item.file, text: title }),
+ el("div", { class: "item-meta" },
+ el("span", { class: "badge", text: badge }),
+ kind.startsWith("edit") ? el("span", { class: "badge", text: t("kind.edit") }) : null,
+ el("span", { text: fmtLen(item.seconds) }),
+ el("span", { text: fmtDate(item.mtime) }),
+ m.seed != null ? el("span", { text: t("cand.seed", { seed: m.seed }) }) : null),
+ m.prompt || m.sound_fields ? el("div", { class: "item-prompt", text: promptLabel({ prompt: m.prompt, ...prefixSound(m.sound_fields) }) }) : null),
+ el("div", { class: "item-side" },
+ el("audio", { controls: true, preload: "none", src: audioUrl(item.file) }),
+ el("div", { class: "item-actions" },
+ toggle,
+ el("button", { class: "link-btn", type: "button", disabled: !canRegen, text: t("act.regen"), onclick: () => regenerate(item) }),
+ el("button", { class: "link-btn", type: "button", text: t("act.copyPath"), onclick: () => copyText(item.path) }),
+ el("a", { class: "link-btn", href: audioUrl(item.file, true), download: item.file, text: t("act.download") }))),
+ details);
+}
+function prefixSound(sf) {
+ sf = sf || {};
+ return { sound_source: sf.source, sound_action: sf.action, sound_material: sf.material, sound_space: sf.space };
+}
+function renderLibrary() {
+ const box = $("#library"), L = state.lib;
+ box.replaceChildren(...L.items.map(libraryItem));
+ $("#lib-count").textContent = t("lib.count", { n: L.total });
+ $("#lib-empty").hidden = L.items.length > 0;
+ $("#lib-empty").textContent = L.query ? t("lib.noMatch") : t("lib.empty");
+ $("#lib-more").hidden = L.items.length >= L.total;
+}
+let libSeq = 0;
+async function loadLibrary(reset) {
+ const L = state.lib, seq = ++libSeq;
+ const offset = reset ? 0 : L.items.length;
+ try {
+ const r = await api(`/api/library?q=${encodeURIComponent(L.query)}&offset=${offset}&limit=${PAGE}`);
+ if (seq !== libSeq) return; // a newer search finished first
+ L.items = reset ? r.items : L.items.concat(r.items);
+ L.total = r.total;
+ } catch (e) {
+ if (seq !== libSeq) return;
+ L.items = []; L.total = 0;
+ toast(e.message);
+ }
+ renderLibrary();
+}
+function initLibrary() {
+ let timer;
+ $("#lib-search").addEventListener("input", (e) => {
+ clearTimeout(timer);
+ timer = setTimeout(() => { state.lib.query = e.target.value.trim(); loadLibrary(true); }, 200);
+ });
+ $("#lib-refresh").addEventListener("click", () => loadLibrary(true));
+ $("#lib-more").addEventListener("click", () => loadLibrary(false));
+}
+
+// ── boot ─────────────────────────────────────────────────────────────────────
+initSettings();
+initForm();
+initLibrary();
+applyI18n();
+initTabs();
+refreshStatus();
+restoreJobs();
+setInterval(refreshStatus, 5000);
diff --git a/src/audio_studio_mcp/static/i18n.js b/src/audio_studio_mcp/static/i18n.js
new file mode 100644
index 0000000..d21b52a
--- /dev/null
+++ b/src/audio_studio_mcp/static/i18n.js
@@ -0,0 +1,144 @@
+// UI strings: English, Japanese, Simplified Chinese. {name} = placeholder.
+window.I18N = {
+ en: {
+ "nav.generate": "Generate", "nav.library": "Library",
+ "status.unload": "Free memory", "status.unloadHint": "Unload the model now (it reloads on the next generation)",
+ "status.loaded": "Model loaded", "status.notLoaded": "Model not loaded", "status.working": "Generating",
+ "status.offline": "Server unreachable", "status.unloaded": "Model unloaded, memory freed",
+ "status.nothingToUnload": "The model was not loaded",
+ "settings.language": "Language", "settings.auto": "Auto", "settings.theme": "Theme",
+ "settings.system": "System", "settings.light": "Light", "settings.dark": "Dark",
+ "gen.title": "New sound", "gen.type": "Type",
+ "type.music": "Music", "type.instrument": "Instrument", "type.sfx": "Sound effect", "type.raw": "Raw",
+ "gen.prompt.music": "Description (English)", "gen.prompt.instrument": "Description (English)",
+ "gen.prompt.sfx": "Overall description (optional, English)",
+ "gen.promptHint.music": "Genre, main instruments, rhythm and mood in one or two sentences. Vocals and lyrics are not supported.",
+ "gen.promptHint.instrument": "Instrument, playing technique, timbre and style. Loops work best at 6–20 s.",
+ "gen.promptHint.sfx": "Describe the sound with the four fields below; they are joined in this order.",
+ "gen.promptPh.music": "Lo-fi hip-hop track with mellow electric piano, soft vinyl crackle and relaxed drums",
+ "gen.promptPh.instrument": "Fingerpicked nylon guitar loop, warm and intimate, close-mic recording",
+ "gen.promptPh.sfx": "A glass bottle breaking",
+ "sfx.source": "Source", "sfx.action": "Action", "sfx.material": "Material", "sfx.space": "Space",
+ "sfx.sourcePh": "glass bottle", "sfx.actionPh": "shattering on impact, fragments scattering",
+ "sfx.materialPh": "thick glass, sharp bright transient", "sfx.spacePh": "concrete floor, close-up, dry",
+ "gen.duration": "Duration (s)", "gen.bpm": "BPM", "gen.optional": "Optional", "gen.variations": "Candidates",
+ "gen.name": "File name", "gen.namePh": "Automatic if empty",
+ "gen.advanced": "Advanced", "adv.seed": "Seed", "adv.seedPh": "Random", "adv.cfg": "CFG", "adv.steps": "Steps",
+ "adv.ceiling": "Peak ceiling (dBFS)", "adv.negative": "Negative prompt", "adv.negativePh": "Qualities to avoid",
+ "adv.hint": "The negative prompt only applies when CFG is not 1. CFG 3–7 follows the prompt more closely but takes about twice as long.",
+ "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",
+ "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",
+ "toast.copied": "Path copied", "toast.copyFailed": "Could not copy; select the path in Details", "toast.seedSet": "Seed {seed} set",
+ "toast.regenQueued": "Queued with the same settings",
+ "lib.search": "Search", "lib.searchPh": "Search by name, prompt, seed…", "lib.refresh": "Refresh",
+ "lib.count": "{n} files", "lib.empty": "No audio files yet. Generated sounds are saved here.",
+ "lib.noMatch": "No files match.", "lib.more": "Show more", "lib.folder": "Folder: {dir}",
+ "meta.kind": "Kind", "meta.type": "Type", "meta.prompt": "Prompt", "meta.promptUsed": "Prompt sent to the model",
+ "meta.idea": "Original idea", "meta.sound": "Sound fields", "meta.bpm": "BPM", "meta.seconds": "Length",
+ "meta.seed": "Seed", "meta.cfg": "CFG", "meta.steps": "Steps", "meta.negative": "Negative prompt",
+ "meta.peak": "Peak", "meta.model": "Model", "meta.created": "Created", "meta.path": "Path", "meta.input": "Input",
+ "meta.noSidecar": "No parameter record (.json) for this file.",
+ "kind.generate": "Generated", "kind.edit": "Edit", "kind.process": "Processed",
+ "err.network": "Cannot reach the server. Is audio-studio-mcp --web still running?",
+ "err.emptyPrompt": "Enter a description or fill in at least one sound field.",
+ },
+ ja: {
+ "nav.generate": "生成", "nav.library": "ライブラリ",
+ "status.unload": "メモリを解放", "status.unloadHint": "モデルを今すぐアンロードします(次の生成で再読み込み)",
+ "status.loaded": "モデル読み込み済み", "status.notLoaded": "モデル未読み込み", "status.working": "生成中",
+ "status.offline": "サーバーに接続できません", "status.unloaded": "モデルをアンロードしてメモリを解放しました",
+ "status.nothingToUnload": "モデルは読み込まれていません",
+ "settings.language": "言語", "settings.auto": "自動", "settings.theme": "テーマ",
+ "settings.system": "システム", "settings.light": "ライト", "settings.dark": "ダーク",
+ "gen.title": "新規作成", "gen.type": "種類",
+ "type.music": "音楽", "type.instrument": "楽器", "type.sfx": "効果音", "type.raw": "Raw",
+ "gen.prompt.music": "説明(英語)", "gen.prompt.instrument": "説明(英語)",
+ "gen.prompt.sfx": "全体の説明(任意・英語)",
+ "gen.promptHint.music": "ジャンル・主な楽器・リズム・雰囲気を 1〜2 文で。ボーカルや歌詞は生成できません。",
+ "gen.promptHint.instrument": "楽器・奏法・音色・スタイルを書きます。ループは 6〜20 秒が最適です。",
+ "gen.promptHint.sfx": "下の 4 項目で音を説明します。この順につなげてモデルに渡します。",
+ "gen.promptPh.music": "Lo-fi hip-hop track with mellow electric piano, soft vinyl crackle and relaxed drums",
+ "gen.promptPh.instrument": "Fingerpicked nylon guitar loop, warm and intimate, close-mic recording",
+ "gen.promptPh.sfx": "A glass bottle breaking",
+ "sfx.source": "音源", "sfx.action": "動作", "sfx.material": "素材・質感", "sfx.space": "空間",
+ "sfx.sourcePh": "glass bottle", "sfx.actionPh": "shattering on impact, fragments scattering",
+ "sfx.materialPh": "thick glass, sharp bright transient", "sfx.spacePh": "concrete floor, close-up, dry",
+ "gen.duration": "長さ(秒)", "gen.bpm": "BPM", "gen.optional": "任意", "gen.variations": "候補数",
+ "gen.name": "ファイル名", "gen.namePh": "空欄なら自動",
+ "gen.advanced": "詳細設定", "adv.seed": "シード", "adv.seedPh": "ランダム", "adv.cfg": "CFG", "adv.steps": "ステップ数",
+ "adv.ceiling": "ピーク上限(dBFS)", "adv.negative": "ネガティブプロンプト", "adv.negativePh": "避けたい要素",
+ "adv.hint": "ネガティブプロンプトは CFG が 1 以外のときだけ効きます。CFG 3〜7 はプロンプトに忠実になりますが、時間は約 2 倍かかります。",
+ "gen.submit": "生成", "gen.reset": "リセット",
+ "jobs.title": "結果", "jobs.empty": "生成した音はここに表示されます。",
+ "jobs.queued": "待機中・{n} 番目", "jobs.running": "生成中… {t}", "jobs.done": "完了({t})",
+ "jobs.error": "失敗", "jobs.queueInfo": "生成中 {running} 件・待機 {queued} 件",
+ "cand.label": "候補 {n}", "cand.seed": "シード {seed}",
+ "act.download": "ダウンロード", "act.copyPath": "パスをコピー", "act.useSeed": "このシードを使う",
+ "act.regen": "同じシードで再生成", "act.details": "詳細", "act.hideDetails": "詳細を閉じる",
+ "toast.copied": "パスをコピーしました", "toast.copyFailed": "コピーできませんでした。詳細からパスを選択してください", "toast.seedSet": "シード {seed} を設定しました",
+ "toast.regenQueued": "同じ設定でキューに追加しました",
+ "lib.search": "検索", "lib.searchPh": "名前・プロンプト・シードで検索…", "lib.refresh": "更新",
+ "lib.count": "{n} 件", "lib.empty": "まだ音声ファイルがありません。生成した音はここに保存されます。",
+ "lib.noMatch": "一致するファイルはありません。", "lib.more": "さらに表示", "lib.folder": "フォルダ: {dir}",
+ "meta.kind": "種別", "meta.type": "種類", "meta.prompt": "プロンプト", "meta.promptUsed": "モデルに渡したプロンプト",
+ "meta.idea": "元のアイデア", "meta.sound": "効果音の項目", "meta.bpm": "BPM", "meta.seconds": "長さ",
+ "meta.seed": "シード", "meta.cfg": "CFG", "meta.steps": "ステップ数", "meta.negative": "ネガティブプロンプト",
+ "meta.peak": "ピーク", "meta.model": "モデル", "meta.created": "作成日時", "meta.path": "パス", "meta.input": "入力",
+ "meta.noSidecar": "このファイルにはパラメータ記録(.json)がありません。",
+ "kind.generate": "生成", "kind.edit": "編集", "kind.process": "加工",
+ "err.network": "サーバーに接続できません。audio-studio-mcp --web が起動しているか確認してください。",
+ "err.emptyPrompt": "説明を入力するか、効果音の項目を 1 つ以上入力してください。",
+ },
+ zh: {
+ "nav.generate": "生成", "nav.library": "作品库",
+ "status.unload": "释放内存", "status.unloadHint": "立即卸载模型(下次生成时会重新加载)",
+ "status.loaded": "模型已加载", "status.notLoaded": "模型未加载", "status.working": "生成中",
+ "status.offline": "无法连接服务器", "status.unloaded": "已卸载模型并释放内存",
+ "status.nothingToUnload": "模型尚未加载",
+ "settings.language": "语言", "settings.auto": "自动", "settings.theme": "主题",
+ "settings.system": "跟随系统", "settings.light": "浅色", "settings.dark": "深色",
+ "gen.title": "新建", "gen.type": "类型",
+ "type.music": "音乐", "type.instrument": "单乐器", "type.sfx": "音效", "type.raw": "Raw",
+ "gen.prompt.music": "描述(英文)", "gen.prompt.instrument": "描述(英文)",
+ "gen.prompt.sfx": "整体描述(可选,英文)",
+ "gen.promptHint.music": "用一两句话写出风格、主要乐器、节奏和氛围。不能生成人声和歌词。",
+ "gen.promptHint.instrument": "写出乐器、演奏方式、音色和风格。循环素材 6–20 秒效果最好。",
+ "gen.promptHint.sfx": "用下面 4 个输入框描述声音,会按这个顺序拼接后交给模型。",
+ "gen.promptPh.music": "Lo-fi hip-hop track with mellow electric piano, soft vinyl crackle and relaxed drums",
+ "gen.promptPh.instrument": "Fingerpicked nylon guitar loop, warm and intimate, close-mic recording",
+ "gen.promptPh.sfx": "A glass bottle breaking",
+ "sfx.source": "发声物", "sfx.action": "动作", "sfx.material": "材质", "sfx.space": "空间",
+ "sfx.sourcePh": "glass bottle", "sfx.actionPh": "shattering on impact, fragments scattering",
+ "sfx.materialPh": "thick glass, sharp bright transient", "sfx.spacePh": "concrete floor, close-up, dry",
+ "gen.duration": "时长(秒)", "gen.bpm": "BPM", "gen.optional": "可选", "gen.variations": "候选数",
+ "gen.name": "文件名", "gen.namePh": "留空则自动命名",
+ "gen.advanced": "高级参数", "adv.seed": "种子", "adv.seedPh": "随机", "adv.cfg": "CFG", "adv.steps": "步数",
+ "adv.ceiling": "峰值上限(dBFS)", "adv.negative": "反向提示词", "adv.negativePh": "想避免的元素",
+ "adv.hint": "反向提示词只在 CFG 不等于 1 时生效。CFG 3–7 更贴合提示词,但耗时约为 2 倍。",
+ "gen.submit": "生成", "gen.reset": "重置",
+ "jobs.title": "结果", "jobs.empty": "生成的声音会显示在这里。",
+ "jobs.queued": "排队中 · 第 {n} 位", "jobs.running": "生成中… {t}", "jobs.done": "完成({t})",
+ "jobs.error": "失败", "jobs.queueInfo": "生成中 {running} 个 · 排队 {queued} 个",
+ "cand.label": "候选 {n}", "cand.seed": "种子 {seed}",
+ "act.download": "下载", "act.copyPath": "复制路径", "act.useSeed": "使用此种子",
+ "act.regen": "用同一种子重新生成", "act.details": "详情", "act.hideDetails": "收起详情",
+ "toast.copied": "已复制路径", "toast.copyFailed": "无法复制,请在详情中选中路径", "toast.seedSet": "已设置种子 {seed}",
+ "toast.regenQueued": "已用相同设置加入队列",
+ "lib.search": "搜索", "lib.searchPh": "按名称、提示词、种子搜索…", "lib.refresh": "刷新",
+ "lib.count": "{n} 个文件", "lib.empty": "还没有音频文件。生成的声音会保存在这里。",
+ "lib.noMatch": "没有匹配的文件。", "lib.more": "显示更多", "lib.folder": "文件夹:{dir}",
+ "meta.kind": "类别", "meta.type": "类型", "meta.prompt": "提示词", "meta.promptUsed": "实际发给模型的提示词",
+ "meta.idea": "原始想法", "meta.sound": "音效字段", "meta.bpm": "BPM", "meta.seconds": "时长",
+ "meta.seed": "种子", "meta.cfg": "CFG", "meta.steps": "步数", "meta.negative": "反向提示词",
+ "meta.peak": "峰值", "meta.model": "模型", "meta.created": "创建时间", "meta.path": "路径", "meta.input": "输入",
+ "meta.noSidecar": "此文件没有参数记录(.json)。",
+ "kind.generate": "生成", "kind.edit": "编辑", "kind.process": "后处理",
+ "err.network": "无法连接服务器。请确认 audio-studio-mcp --web 仍在运行。",
+ "err.emptyPrompt": "请填写描述,或至少填写一个音效字段。",
+ },
+};
diff --git a/src/audio_studio_mcp/static/index.html b/src/audio_studio_mcp/static/index.html
new file mode 100644
index 0000000..8727ae6
--- /dev/null
+++ b/src/audio_studio_mcp/static/index.html
@@ -0,0 +1,151 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<meta name="color-scheme" content="light dark">
+<title>Audio Studio</title>
+<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='7' fill='%232563eb'/%3E%3Cpath d='M7 16v0M11 11v10M15 7v18M19 12v8M23 9v14M25 16v0' stroke='white' stroke-width='2.4' stroke-linecap='round'/%3E%3C/svg%3E">
+<link rel="stylesheet" href="/static/app.css">
+<script>
+ // Apply the saved theme before first paint (no flash).
+ (function () { var t = localStorage.getItem("as.theme"); if (t === "light" || t === "dark") document.documentElement.dataset.theme = t; })();
+</script>
+</head>
+<body>
+<header class="topbar">
+ <div class="brand">
+ <svg class="logo" viewBox="0 0 32 32" aria-hidden="true"><rect width="32" height="32" rx="7"/><path d="M11 11v10M15 7v18M19 12v8M23 9v14" /></svg>
+ <span class="brand-name">Audio Studio</span>
+ <span class="version" id="version"></span>
+ </div>
+ <nav class="tabs" role="tablist">
+ <button role="tab" id="tab-generate" aria-controls="page-generate" aria-selected="true" data-page="generate" data-i18n="nav.generate">Generate</button>
+ <button role="tab" id="tab-library" aria-controls="page-library" aria-selected="false" data-page="library" data-i18n="nav.library">Library</button>
+ </nav>
+ <div class="status" id="statusbar">
+ <span class="model-state" id="model-state" role="status" aria-live="polite">
+ <span class="dot"></span><span id="model-text">…</span>
+ </span>
+ <button class="btn btn-quiet btn-sm" id="unload" data-i18n="status.unload" data-i18n-title="status.unloadHint">Free memory</button>
+ <label class="sr-only" for="lang" data-i18n="settings.language">Language</label>
+ <select id="lang" class="select-sm">
+ <option value="auto" data-i18n="settings.auto">Auto</option>
+ <option value="ja">日本語</option>
+ <option value="en">English</option>
+ <option value="zh">简体中文</option>
+ </select>
+ <label class="sr-only" for="theme" data-i18n="settings.theme">Theme</label>
+ <select id="theme" class="select-sm">
+ <option value="system" data-i18n="settings.system">System</option>
+ <option value="light" data-i18n="settings.light">Light</option>
+ <option value="dark" data-i18n="settings.dark">Dark</option>
+ </select>
+ </div>
+</header>
+
+<main>
+ <!-- Generate -->
+ <section id="page-generate" class="page" role="tabpanel" aria-labelledby="tab-generate">
+ <form id="gen-form" class="panel form" novalidate>
+ <h1 class="panel-title" data-i18n="gen.title">New sound</h1>
+
+ <fieldset class="field">
+ <legend data-i18n="gen.type">Type</legend>
+ <div class="segmented" id="type-seg">
+ <label><input type="radio" name="audio_type" value="music" checked><span data-i18n="type.music">Music</span></label>
+ <label><input type="radio" name="audio_type" value="instrument"><span data-i18n="type.instrument">Instrument</span></label>
+ <label><input type="radio" name="audio_type" value="sfx"><span data-i18n="type.sfx">Sound effect</span></label>
+ </div>
+ </fieldset>
+
+ <div class="field">
+ <label for="prompt" id="prompt-label" data-i18n="gen.prompt.music">Description (English)</label>
+ <textarea id="prompt" name="prompt" rows="3" spellcheck="false"></textarea>
+ <p class="hint" id="prompt-hint" data-i18n="gen.promptHint.music"></p>
+ </div>
+
+ <div class="sfx-fields" id="sfx-fields" hidden>
+ <div class="field"><label for="sound_source" data-i18n="sfx.source">Source</label><input id="sound_source" name="sound_source" type="text" data-i18n-placeholder="sfx.sourcePh"></div>
+ <div class="field"><label for="sound_action" data-i18n="sfx.action">Action</label><input id="sound_action" name="sound_action" type="text" data-i18n-placeholder="sfx.actionPh"></div>
+ <div class="field"><label for="sound_material" data-i18n="sfx.material">Material</label><input id="sound_material" name="sound_material" type="text" data-i18n-placeholder="sfx.materialPh"></div>
+ <div class="field"><label for="sound_space" data-i18n="sfx.space">Space</label><input id="sound_space" name="sound_space" type="text" data-i18n-placeholder="sfx.spacePh"></div>
+ </div>
+
+ <div class="row">
+ <div class="field">
+ <label for="duration_seconds" data-i18n="gen.duration">Duration (s)</label>
+ <input id="duration_seconds" name="duration_seconds" type="number" min="0.5" max="380" step="0.5" inputmode="decimal">
+ </div>
+ <div class="field" id="bpm-field">
+ <label for="bpm" data-i18n="gen.bpm">BPM</label>
+ <input id="bpm" name="bpm" type="number" min="30" max="300" step="1" inputmode="numeric" data-i18n-placeholder="gen.optional">
+ </div>
+ <fieldset class="field">
+ <legend data-i18n="gen.variations">Candidates</legend>
+ <div class="segmented compact">
+ <label><input type="radio" name="variations" value="1" checked><span>1</span></label>
+ <label><input type="radio" name="variations" value="2"><span>2</span></label>
+ <label><input type="radio" name="variations" value="3"><span>3</span></label>
+ <label><input type="radio" name="variations" value="4"><span>4</span></label>
+ </div>
+ </fieldset>
+ </div>
+
+ <div class="field">
+ <label for="title" data-i18n="gen.name">File name</label>
+ <input id="title" name="title" type="text" data-i18n-placeholder="gen.namePh">
+ </div>
+
+ <details class="advanced" id="advanced">
+ <summary data-i18n="gen.advanced">Advanced</summary>
+ <div class="row">
+ <div class="field"><label for="seed" data-i18n="adv.seed">Seed</label><input id="seed" name="seed" type="number" min="-1" step="1" inputmode="numeric" data-i18n-placeholder="adv.seedPh"></div>
+ <div class="field"><label for="cfg" data-i18n="adv.cfg">CFG</label><input id="cfg" name="cfg" type="number" min="0" max="15" step="0.5" placeholder="1.0"></div>
+ <div class="field"><label for="steps" data-i18n="adv.steps">Steps</label><input id="steps" name="steps" type="number" min="1" max="50" step="1" placeholder="8"></div>
+ <div class="field"><label for="peak_ceiling_db" data-i18n="adv.ceiling">Peak ceiling (dBFS)</label><input id="peak_ceiling_db" name="peak_ceiling_db" type="number" min="-24" max="0" step="0.5" placeholder="-1.0"></div>
+ </div>
+ <div class="field">
+ <label for="negative_prompt" data-i18n="adv.negative">Negative prompt</label>
+ <input id="negative_prompt" name="negative_prompt" type="text" data-i18n-placeholder="adv.negativePh">
+ <p class="hint" data-i18n="adv.hint"></p>
+ </div>
+ </details>
+
+ <p class="form-error" id="form-error" role="alert" hidden></p>
+ <div class="actions">
+ <button type="submit" class="btn btn-primary" id="gen-submit" data-i18n="gen.submit">Generate</button>
+ <button type="button" class="btn btn-quiet" id="gen-reset" data-i18n="gen.reset">Reset</button>
+ </div>
+ </form>
+
+ <div class="results">
+ <div class="results-head">
+ <h2 data-i18n="jobs.title">Results</h2>
+ <span class="muted small" id="queue-info"></span>
+ </div>
+ <div id="jobs" class="jobs"></div>
+ <p class="empty" id="jobs-empty" data-i18n="jobs.empty">Generated sounds appear here.</p>
+ </div>
+ </section>
+
+ <!-- Library -->
+ <section id="page-library" class="page" role="tabpanel" aria-labelledby="tab-library" hidden>
+ <div class="library-bar">
+ <label class="sr-only" for="lib-search" data-i18n="lib.search">Search</label>
+ <input id="lib-search" type="search" data-i18n-placeholder="lib.searchPh" autocomplete="off">
+ <button class="btn btn-quiet" id="lib-refresh" data-i18n="lib.refresh">Refresh</button>
+ <span class="muted small" id="lib-count"></span>
+ </div>
+ <p class="muted small folder" id="lib-folder"></p>
+ <div id="library" class="library"></div>
+ <p class="empty" id="lib-empty" hidden data-i18n="lib.empty">No audio files yet.</p>
+ <div class="more"><button class="btn btn-quiet" id="lib-more" hidden data-i18n="lib.more">Show more</button></div>
+ </section>
+</main>
+
+<div class="toast" id="toast" role="status" aria-live="polite" hidden></div>
+<script src="/static/i18n.js"></script>
+<script src="/static/app.js"></script>
+</body>
+</html>
diff --git a/src/audio_studio_mcp/web.py b/src/audio_studio_mcp/web.py
new file mode 100644
index 0000000..3c29289
--- /dev/null
+++ b/src/audio_studio_mcp/web.py
@@ -0,0 +1,397 @@
+"""Local web UI: `audio-studio-mcp --web PORT`.
+
+One process serves, on 127.0.0.1:PORT,
+ /mcp the MCP server (streamable HTTP), for agents
+ / the web UI (static/, plain HTML/JS/CSS, no build step)
+ /api/* a small JSON API the page uses
+so the page and MCP clients share one loaded model.
+
+The API runs tools in-process through `server.server.call_tool()`, so argument
+validation and error messages are exactly what an MCP client gets. Generation
+requests become jobs in a FIFO queue that one worker runs in order; the page
+polls a job for its queue position, elapsed time, result or error.
+
+Local only: the server binds 127.0.0.1 and /api rejects requests whose Host is
+not this loopback address (DNS rebinding) and writes from other origins (CSRF).
+"""
+from __future__ import annotations
+
+import asyncio
+import itertools
+import json
+import secrets
+import time
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+from urllib.parse import urlsplit
+
+from mcp.server.mcpserver.exceptions import ToolError
+from pydantic import ValidationError
+from starlette.applications import Starlette
+from starlette.requests import Request
+from starlette.responses import FileResponse, JSONResponse, Response
+from starlette.routing import Mount, Route
+from starlette.staticfiles import StaticFiles
+
+from . import __version__, server
+from .prompts import DEFAULT_SECONDS
+
+STATIC_DIR = Path(__file__).with_name("static")
+AUDIO_EXTS = {".wav": "audio/wav", ".ogg": "audio/ogg", ".flac": "audio/flac", ".mp3": "audio/mpeg"}
+# Tools the page may queue. edit/process take arbitrary input paths; they come
+# with the editing page (W2) and an input check limited to OUTPUT_DIR.
+JOB_TOOLS = {"generate_audio"}
+MAX_FINISHED_JOBS = 200
+
+
+# ── jobs ─────────────────────────────────────────────────────────────────────
+@dataclass
+class Job:
+ id: str
+ tool: str
+ arguments: dict
+ seq: int
+ status: str = "queued" # queued | running | done | error
+ created: float = field(default_factory=time.time)
+ started: float | None = None
+ finished: float | None = None
+ result: Any = None
+ error: str | None = None
+
+ def view(self, position: int | None) -> dict:
+ end = self.finished or time.time()
+ return {
+ "id": self.id, "tool": self.tool, "arguments": self.arguments,
+ "status": self.status, "position": position,
+ "created": self.created, "started": self.started, "finished": self.finished,
+ "elapsed": round(end - self.started, 1) if self.started else 0.0,
+ "waited": round((self.started or end) - self.created, 1),
+ "result": self.result, "error": self.error,
+ }
+
+
+def _tool_result(r) -> Any:
+ """CallToolResult → the tool's return value (raises ToolError on an error result)."""
+ text = "".join(getattr(c, "text", "") for c in r.content)
+ if r.is_error:
+ raise ToolError(text)
+ if r.structured_content is not None:
+ return r.structured_content
+ try:
+ return json.loads(text)
+ except ValueError:
+ return text
+
+
+class JobQueue:
+ """FIFO of tool calls run one at a time on the server's event loop.
+
+ The backend serializes model calls anyway; running web jobs one by one on
+ top of that keeps the queue position the page shows meaningful."""
+
+ def __init__(self) -> None:
+ self.jobs: dict[str, Job] = {}
+ self._seq = itertools.count(1)
+ self._queue: asyncio.Queue[Job] | None = None
+ self._worker: asyncio.Task | None = None
+
+ def submit(self, tool: str, arguments: dict) -> Job:
+ if self._queue is None:
+ self._queue = asyncio.Queue()
+ if self._worker is None or self._worker.done():
+ self._worker = asyncio.get_running_loop().create_task(self._run())
+ job = Job(id=secrets.token_hex(6), tool=tool, arguments=arguments, seq=next(self._seq))
+ self.jobs[job.id] = job
+ self._queue.put_nowait(job)
+ self._prune()
+ return job
+
+ def position(self, job: Job) -> int | None:
+ """1-based place among queued jobs, None once it has started."""
+ if job.status != "queued":
+ return None
+ return 1 + sum(1 for j in self.jobs.values() if j.status == "queued" and j.seq < job.seq)
+
+ def view(self, job: Job) -> dict:
+ return job.view(self.position(job))
+
+ def counts(self) -> dict:
+ st = [j.status for j in self.jobs.values()]
+ return {"queued": st.count("queued"), "running": st.count("running")}
+
+ def _prune(self) -> None:
+ done = [j for j in self.jobs.values() if j.status in ("done", "error")]
+ for j in sorted(done, key=lambda j: j.seq)[:max(0, len(done) - MAX_FINISHED_JOBS)]:
+ del self.jobs[j.id]
+
+ async def _run(self) -> None:
+ assert self._queue is not None
+ while True:
+ job = await self._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 see
+ job.error, job.status = str(e), "error"
+ finally:
+ job.finished = time.time()
+ self._queue.task_done()
+
+
+jobs = JobQueue()
+
+
+def validate_arguments(tool: str, arguments: dict) -> list[dict]:
+ """Check arguments against the tool's schema before queueing, so a typo is
+ reported now instead of after the jobs ahead of it. Returns field errors."""
+ t = server.server._tool_manager.get_tool(tool)
+ try:
+ t.fn_metadata.validate_arguments(arguments)
+ except ValidationError as e:
+ return [{"field": ".".join(str(p) for p in err["loc"]), "message": err["msg"]}
+ for err in e.errors()]
+ except AttributeError: # SDK internals moved; the tool call validates anyway
+ pass
+ return []
+
+
+# ── library ──────────────────────────────────────────────────────────────────
+def _output_dir() -> Path:
+ return server.OUTPUT_DIR # read at call time (tests and env may change it)
+
+
+def _safe_audio_path(name: str) -> Path | None:
+ """An audio file directly inside OUTPUT_DIR, or None (no traversal, no symlink escape)."""
+ if not name or "/" in name or "\\" in name or name in (".", "..") or "\0" in name:
+ return None
+ root = _output_dir().resolve()
+ path = (root / name)
+ if path.suffix.lower() not in AUDIO_EXTS:
+ return None
+ try:
+ resolved = path.resolve(strict=True)
+ except (OSError, RuntimeError):
+ return None
+ if resolved.parent != root or not resolved.is_file():
+ return None
+ return resolved
+
+
+def _entry(path: Path) -> dict:
+ st = path.stat()
+ meta = None
+ 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
+ seconds = (meta or {}).get("seconds")
+ if not isinstance(seconds, (int, float)):
+ try:
+ import soundfile as sf
+ 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}
+
+
+def _search_text(e: dict) -> str:
+ m = e["meta"] or {}
+ sf = m.get("sound_fields") or {}
+ 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", "")),
+ *(sf.values() if isinstance(sf, dict) else [])]
+ return " ".join(str(p) for p in parts if 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]
+ 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]}
+
+
+# ── HTTP ─────────────────────────────────────────────────────────────────────
+def _err(status: int, message: str, **extra) -> JSONResponse:
+ return JSONResponse({"error": message, **extra}, status_code=status)
+
+
+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)."""
+
+ LOOPBACK = ("127.0.0.1", "localhost", "::1")
+
+ def __init__(self, app, port: int | None) -> None:
+ self.app, self.port = app, port
+
+ def _host_ok(self, host: str) -> bool:
+ try:
+ u = urlsplit("//" + host)
+ port = u.port
+ except ValueError:
+ return False
+ if u.hostname not in self.LOOPBACK or u.username or u.path:
+ return False
+ return 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)
+ headers = {k.decode("latin-1"): v.decode("latin-1") for k, v in scope["headers"]}
+ problem = None
+ if not self._host_ok(headers.get("host", "")):
+ problem = "host not allowed"
+ elif 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)
+
+
+async def api_status(_: Request) -> Response:
+ b = server.get_backend()
+ return JSONResponse({
+ "version": __version__, "backend": b.name, "model": b.model_label,
+ "loaded": bool(b.loaded()), "max_seconds": b.max_seconds, "sample_rate": b.sample_rate,
+ "output_dir": str(_output_dir()), "default_seconds": DEFAULT_SECONDS,
+ "jobs": jobs.counts(),
+ })
+
+
+async def api_unload(_: Request) -> Response:
+ try:
+ r = _tool_result(await server.server.call_tool("unload_models", {}))
+ except ToolError as e:
+ return _err(500, str(e))
+ return JSONResponse(r)
+
+
+async def _json_body(request: Request) -> dict:
+ try:
+ body = await request.json()
+ except ValueError:
+ raise ValueError("invalid JSON body")
+ if not isinstance(body, dict):
+ raise ValueError("JSON body must be an object")
+ return body
+
+
+async def api_jobs_create(request: Request) -> Response:
+ try:
+ body = await _json_body(request)
+ except ValueError as e:
+ return _err(400, str(e))
+ tool, arguments = body.get("tool", "generate_audio"), body.get("arguments", {})
+ if tool not in JOB_TOOLS:
+ return _err(400, f"tool not available from the web UI: {tool!r}")
+ if not isinstance(arguments, dict):
+ return _err(400, "arguments must be an object")
+ errors = validate_arguments(tool, arguments)
+ if errors:
+ msg = "; ".join(f"{e['field']}: {e['message']}" for e in errors)
+ return _err(422, f"invalid arguments: {msg}", fields=errors)
+ job = jobs.submit(tool, arguments)
+ return JSONResponse(jobs.view(job), status_code=202)
+
+
+async def api_jobs_list(_: Request) -> Response:
+ items = sorted(jobs.jobs.values(), key=lambda j: j.seq, reverse=True)
+ return JSONResponse({"items": [jobs.view(j) for j in items], **jobs.counts()})
+
+
+async def api_job(request: Request) -> Response:
+ job = jobs.jobs.get(request.path_params["job_id"])
+ if job is None:
+ return _err(404, "no such job")
+ return JSONResponse(jobs.view(job))
+
+
+async def api_library(request: Request) -> Response:
+ q = request.query_params
+ try:
+ offset = max(0, int(q.get("offset", 0)))
+ limit = min(500, max(1, int(q.get("limit", 100))))
+ except ValueError:
+ return _err(400, "offset/limit must be integers")
+ return JSONResponse(await asyncio.to_thread(list_library, q.get("q", ""), offset, limit))
+
+
+async def api_audio(request: Request) -> Response:
+ path = _safe_audio_path(request.path_params["name"])
+ if path is None:
+ return _err(404, "not found")
+ download = request.query_params.get("download") in ("1", "true")
+ return FileResponse(path, media_type=AUDIO_EXTS[path.suffix.lower()],
+ filename=path.name if download else None,
+ content_disposition_type="attachment" if download else "inline",
+ headers={"Cache-Control": "no-cache"})
+
+
+async def index(_: Request) -> Response:
+ return FileResponse(STATIC_DIR / "index.html", headers={"Cache-Control": "no-cache"})
+
+
+API_ROUTES = [
+ Route("/api/status", api_status, methods=["GET"]),
+ Route("/api/unload", api_unload, methods=["POST"]),
+ Route("/api/jobs", api_jobs_create, methods=["POST"]),
+ Route("/api/jobs", api_jobs_list, methods=["GET"]),
+ Route("/api/jobs/{job_id}", api_job, methods=["GET"]),
+ Route("/api/library", api_library, methods=["GET"]),
+ Route("/api/audio/{name:path}", api_audio, methods=["GET", "HEAD"]),
+]
+
+
+def create_app(port: int | None = None) -> Starlette:
+ """The MCP streamable-HTTP app plus the web UI and API on the same routes table.
+
+ `port` pins the Host / Origin check to 127.0.0.1:port (None = any port, tests)."""
+ app = server.server.streamable_http_app(host="127.0.0.1")
+ app.router.routes.extend([
+ *API_ROUTES,
+ Route("/", index, methods=["GET"]),
+ Mount("/static", StaticFiles(directory=STATIC_DIR), name="static"),
+ ])
+ app.add_middleware(LocalOnly, port=port)
+ return app
+
+
+def serve(port: int, open_browser: bool = True) -> None:
+ import threading
+ import webbrowser
+
+ import uvicorn
+
+ url = f"http://127.0.0.1:{port}/"
+ config = uvicorn.Config(create_app(port), host="127.0.0.1", port=port, log_level="info")
+ srv = uvicorn.Server(config)
+
+ def announce():
+ while not srv.started:
+ if srv.should_exit:
+ return
+ time.sleep(0.1)
+ print(f"[audio-studio] web UI: {url} MCP: {url}mcp", flush=True)
+ if open_browser:
+ webbrowser.open(url)
+
+ threading.Thread(target=announce, daemon=True, name="open-browser").start()
+ srv.run()
diff --git a/tests/fake_web_server.py b/tests/fake_web_server.py
new file mode 100644
index 0000000..11a5598
--- /dev/null
+++ b/tests/fake_web_server.py
@@ -0,0 +1,23 @@
+"""Run `audio-studio-mcp` with the fake backend (tests and UI screenshots).
+
+ python tests/fake_web_server.py --web 8799 --no-browser
+FAKE_DELAY=seconds makes each generation take that long (to see the queue)."""
+import os
+import sys
+import time
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).parent))
+from conftest import FakeBackend # noqa: E402
+
+from audio_studio_mcp import server # noqa: E402
+
+
+class SlowFake(FakeBackend):
+ def _generate(self, seeds, req):
+ time.sleep(float(os.environ.get("FAKE_DELAY", "0")))
+ return super()._generate(seeds, req)
+
+
+server.set_backend(SlowFake())
+server.main(sys.argv[1:])
diff --git a/tests/test_web.py b/tests/test_web.py
new file mode 100644
index 0000000..2df1d20
--- /dev/null
+++ b/tests/test_web.py
@@ -0,0 +1,324 @@
+"""Web UI API tests (`--web`), with the fake backend."""
+from __future__ import annotations
+
+import functools
+import os
+import socket
+import subprocess
+import sys
+import threading
+import time
+from pathlib import Path
+
+import anyio
+import pytest
+from mcp import Client
+from starlette.testclient import TestClient
+
+from audio_studio_mcp import post, server, web
+from conftest import sine
+
+TESTS = Path(__file__).parent
+
+
+def client(fake, monkeypatch):
+ monkeypatch.setattr(web, "jobs", web.JobQueue())
+ with TestClient(web.create_app(), base_url="http://127.0.0.1") as c:
+ c.headers.update({"Origin": "http://127.0.0.1"})
+ yield c
+
+
+def wait_job(client, job_id, timeout=10):
+ end = time.time() + timeout
+ while time.time() < end:
+ j = client.get(f"/api/jobs/{job_id}").json()
+ if j["status"] in ("done", "error"):
+ return j
+ time.sleep(0.02)
+ raise AssertionError("job did not finish")
+
+
+def test_index_and_static_are_served(client):
+ r = client.get("/")
+ assert r.status_code == 200 and "<title>Audio Studio</title>" in r.text
+ for f in ("app.js", "app.css", "i18n.js"):
+ assert client.get(f"/static/{f}").status_code == 200
+
+
+def test_static_files_ship_in_the_package():
+ for f in ("index.html", "app.js", "app.css", "i18n.js"):
+ assert (web.STATIC_DIR / f).is_file()
+
+
+def test_status(client, fake):
+ s = client.get("/api/status").json()
+ assert s["backend"] == "fake" and s["loaded"] is False
+ assert s["max_seconds"] == fake.max_seconds
+ assert s["default_seconds"]["sfx"] == 5.0
+ assert s["output_dir"] == str(server.OUTPUT_DIR)
+ assert s["jobs"] == {"queued": 0, "running": 0}
+
+
+def test_generate_job_matches_the_mcp_tool(client, fake):
+ r = client.post("/api/jobs", json={"tool": "generate_audio", "arguments": {
+ "audio_type": "sfx", "sound_source": "door", "sound_action": "slam",
+ "duration_seconds": 1, "variations": 2, "seed": 7}})
+ assert r.status_code == 202
+ job = wait_job(client, r.json()["id"])
+ assert job["status"] == "done", job
+ res = job["result"]
+ assert res["prompt_used"] == "TrackType: SFX, door, slam."
+ assert [c["seed"] for c in res["candidates"]] == [7, 8]
+ for c in res["candidates"]:
+ assert Path(c["path"]).parent == server.OUTPUT_DIR and Path(c["metadata"]).is_file()
+ assert job["elapsed"] >= 0 and job["position"] is None
+ assert client.get("/api/status").json()["loaded"] is True
+
+
+def test_invalid_arguments_rejected_before_queueing(client, fake):
+ r = client.post("/api/jobs", json={"arguments": {"prompt": "x", "variations": 9, "steps": 0}})
+ assert r.status_code == 422
+ fields = {f["field"] for f in r.json()["fields"]}
+ assert fields == {"variations", "steps"}
+ assert client.get("/api/jobs").json()["items"] == []
+ assert fake.requests == []
+
+
+def test_tool_error_reaches_the_job_with_the_mcp_message(client, fake):
+ # passes schema validation, fails inside the tool: same text an MCP client gets
+ r = client.post("/api/jobs", json={"arguments": {"audio_type": "sfx"}})
+ job = wait_job(client, r.json()["id"])
+ assert job["status"] == "error"
+ assert "empty prompt" in job["error"]
+
+
+async def _mcp_error_text(args):
+ async with Client(server.server) as c:
+ r = await c.call_tool("generate_audio", args)
+ assert r.is_error
+ return r.content[0].text
+
+
+def test_error_text_identical_to_mcp(client, fake):
+ r = client.post("/api/jobs", json={"arguments": {"audio_type": "sfx"}})
+ job = wait_job(client, r.json()["id"])
+ assert job["error"] == anyio.run(_mcp_error_text, {"audio_type": "sfx"})
+
+
+def test_only_whitelisted_tools(client, tmp_path):
+ for tool in ("process_audio", "edit_audio", "unload_models", "nope"):
+ r = client.post("/api/jobs", json={"tool": tool, "arguments": {"input_audio": str(tmp_path)}})
+ assert r.status_code == 400, tool
+ assert client.post("/api/jobs", json={"arguments": []}).status_code == 400
+ assert client.post("/api/jobs", content=b"{", headers={"Content-Type": "application/json"}).status_code == 400
+
+
+def test_queue_runs_in_order_with_positions(client, fake):
+ gate = threading.Event()
+ orig = fake._generate
+
+ def slow(seeds, req):
+ gate.wait(10)
+ return orig(seeds, req)
+
+ fake._generate = slow
+ ids = [client.post("/api/jobs", json={"arguments": {"prompt": f"p{i}", "duration_seconds": 1, "seed": i}}).json()["id"]
+ for i in range(3)]
+ end = time.time() + 5
+ while client.get(f"/api/jobs/{ids[0]}").json()["status"] != "running" and time.time() < end:
+ time.sleep(0.02)
+ views = [client.get(f"/api/jobs/{i}").json() for i in ids]
+ assert [v["status"] for v in views] == ["running", "queued", "queued"]
+ assert [v["position"] for v in views] == [None, 1, 2]
+ assert client.get("/api/status").json()["jobs"] == {"queued": 2, "running": 1}
+ gate.set()
+ done = [wait_job(client, i) for i in ids]
+ assert all(d["status"] == "done" for d in done)
+ # FIFO: each job started after the previous one finished
+ for a, b in zip(done, done[1:]):
+ assert b["started"] >= a["finished"]
+ assert [r[1].prompt for r in fake.requests] == [f"TrackType: Music, VocalType: Instrumental, p{i}." for i in range(3)]
+ listed = client.get("/api/jobs").json()["items"]
+ assert [j["id"] for j in listed] == ids[::-1]
+
+
+def test_unload(client, fake):
+ assert client.post("/api/unload", json={}).json() == {"unloaded": False}
+ fake._loaded = True
+ assert client.post("/api/unload", json={}).json() == {"unloaded": True}
+ assert fake.loaded() is False
+
+
+def _make_library(fake):
+ out = server.OUTPUT_DIR
+ out.mkdir(parents=True, exist_ok=True)
+ 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
+ (out / "notes.txt").write_text("x")
+ (out / "reserved.wav").touch() # name reserved by a running generation
+ return out
+
+
+def test_library_lists_audio_with_sidecars(client, fake):
+ out = _make_library(fake)
+ lib = client.get("/api/library").json()
+ assert lib["output_dir"] == str(out) and lib["total"] == 2
+ files = [i["file"] for i in lib["items"]]
+ assert files == ["b.flac", "a.wav"] # newest first
+ a = lib["items"][1]
+ assert a["meta"]["seed"] == 42 and a["seconds"] == 1.0 and a["path"] == str(out / "a.wav")
+ b = lib["items"][0]
+ assert b["meta"] is None and b["seconds"] == pytest.approx(0.5, abs=0.01)
+
+
+def test_library_search_and_paging(client, fake):
+ _make_library(fake)
+ assert [i["file"] for i in client.get("/api/library?q=RAIN").json()["items"]] == ["a.wav"]
+ assert client.get("/api/library?q=rain 42").json()["total"] == 1
+ assert client.get("/api/library?q=rain 43").json()["total"] == 0
+ page = client.get("/api/library?limit=1&offset=1").json()
+ assert page["total"] == 2 and [i["file"] for i in page["items"]] == ["a.wav"]
+ assert client.get("/api/library?limit=x").status_code == 400
+
+
+def test_library_without_output_dir(client, fake):
+ assert client.get("/api/library").json()["total"] == 0
+
+
+def test_audio_served_with_range_and_download(client, fake):
+ _make_library(fake)
+ r = client.get("/api/audio/a.wav")
+ assert r.status_code == 200 and r.headers["content-type"] == "audio/wav"
+ assert r.content == (server.OUTPUT_DIR / "a.wav").read_bytes()
+ part = client.get("/api/audio/a.wav", headers={"Range": "bytes=0-99"})
+ assert part.status_code == 206 and len(part.content) == 100
+ d = client.get("/api/audio/a.wav?download=1")
+ assert d.headers["content-disposition"].startswith("attachment")
+
+
+ "../secret.wav", "..%2Fsecret.wav", "%2e%2e/secret.wav", "sub/x.wav", "..\\secret.wav",
+ "notes.txt", "a.wav.json", "missing.wav", "/etc/passwd", "%2Fetc%2Fpasswd", "link.wav",
+])
+def test_audio_path_traversal_blocked(client, fake, name):
+ out = _make_library(fake)
+ secret = out.parent / "secret.wav"
+ post.write(secret, sine(0.1), 44100, "wav")
+ (out / "sub").mkdir()
+ post.write(out / "sub" / "x.wav", sine(0.1), 44100, "wav")
+ if name == "link.wav":
+ try:
+ (out / "link.wav").symlink_to(secret)
+ except OSError: # Windows without symlink privilege
+ pytest.skip("symlinks not available")
+ r = client.get(f"/api/audio/{name}")
+ assert r.status_code == 404, (name, r.status_code)
+
+
+def test_rejects_foreign_host_and_cross_origin_writes(fake, monkeypatch):
+ monkeypatch.setattr(web, "jobs", web.JobQueue())
+ app = web.create_app(port=8765)
+ good = "http://127.0.0.1:8765"
+ with TestClient(app, base_url=good) as c:
+ assert c.get("/api/status").status_code == 200
+ assert c.get("/api/status", headers={"Host": "localhost:8765"}).status_code == 200
+ # DNS rebinding: attacker's name resolving to 127.0.0.1
+ assert c.get("/api/status", headers={"Host": "evil.example:8765"}).status_code == 403
+ assert c.get("/api/library", headers={"Host": "127.0.0.1:9999"}).status_code == 403
+ body = {"arguments": {"prompt": "x", "duration_seconds": 1}}
+ assert c.post("/api/jobs", json=body).status_code == 403 # no Origin
+ assert c.post("/api/jobs", json=body, headers={"Origin": "https://evil.example"}).status_code == 403
+ assert c.post("/api/jobs", json=body, headers={"Origin": "null"}).status_code == 403
+ assert c.post("/api/unload", json={}, headers={"Origin": "http://127.0.0.1:1234"}).status_code == 403
+ # a cross-site HTML form can only send form/text bodies
+ assert c.post("/api/jobs", content=b'{"arguments":{"prompt":"x"}}',
+ headers={"Origin": good, "Content-Type": "text/plain"}).status_code == 403
+ assert 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
+
+
+# ── real process: `audio-studio-mcp --web PORT` ──────────────────────────────
+def _free_port() -> int:
+ with socket.socket() as s:
+ s.bind(("127.0.0.1", 0))
+ return s.getsockname()[1]
+
+
+def _http(base, path, body=None):
+ """Tiny urllib client (the test env has no httpx)."""
+ import json
+ import urllib.request
+ req = urllib.request.Request(base + path, data=None if body is None else json.dumps(body).encode(),
+ headers={"Origin": base, "Content-Type": "application/json"})
+ with urllib.request.urlopen(req, timeout=10) as r:
+ data = r.read().decode()
+ return json.loads(data) if r.headers.get_content_type() == "application/json" else data
+
+
+async def test_web_flag_serves_ui_api_and_mcp_on_one_port(tmp_path):
+ port = _free_port()
+ base = f"http://127.0.0.1:{port}"
+ env = {**os.environ, "AUDIO_STUDIO_OUTPUT_DIR": str(tmp_path), "PYTHONUNBUFFERED": "1"}
+ proc = subprocess.Popen([sys.executable, str(TESTS / "fake_web_server.py"), "--web", str(port), "--no-browser"],
+ env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
+ http = functools.partial(anyio.to_thread.run_sync, _http, base)
+ try:
+ with anyio.fail_after(20):
+ while True:
+ try:
+ await http("/api/status")
+ break
+ except OSError:
+ await anyio.sleep(0.1)
+ assert "Audio Studio" in await http("/")
+ job = await http("/api/jobs", {"arguments": {"prompt": "x", "duration_seconds": 1, "seed": 3}})
+ # an MCP client on /mcp of the same process shares the backend
+ async with Client(f"{base}/mcp") as c:
+ r = await c.call_tool("generate_audio", {"prompt": "y", "duration_seconds": 1, "seed": 4})
+ assert not r.is_error, r.content
+ with anyio.fail_after(10):
+ while (j := await http(f"/api/jobs/{job['id']}"))["status"] not in ("done", "error"):
+ await anyio.sleep(0.05)
+ assert j["status"] == "done"
+ assert (await http("/api/library"))["total"] == 2 # both the web job and the MCP call
+ finally:
+ proc.terminate()
+ out = proc.communicate(timeout=10)[0].decode(errors="replace")
+ assert f"web UI: {base}/" in out, out
+
+
+def test_web_and_http_are_exclusive(capsys):
+ with pytest.raises(SystemExit):
+ server.main(["--web", "8000", "--http", "8001"])
+ assert "not allowed with" in capsys.readouterr().err
+
+
+def test_web_opens_browser_once_started(monkeypatch):
+ opened = []
+ started = threading.Event()
+
+ class FakeServer:
+ def __init__(self, config):
+ self.started, self.should_exit = False, False
+ assert config.host == "127.0.0.1" and config.port == 8123
+
+ def run(self):
+ self.started = True
+ started.set()
+ time.sleep(0.5)
+
+ import uvicorn
+ import webbrowser
+ monkeypatch.setattr(uvicorn, "Server", FakeServer)
+ monkeypatch.setattr(webbrowser, "open", opened.append)
+ web.serve(8123, open_browser=True)
+ assert opened == ["http://127.0.0.1:8123/"]
+ opened.clear()
+ web.serve(8123, open_browser=False)
+ assert opened == []
diff --git a/tests/test_webui_browser.py b/tests/test_webui_browser.py
new file mode 100644
index 0000000..d08cd2d
--- /dev/null
+++ b/tests/test_webui_browser.py
@@ -0,0 +1,224 @@
+"""Browser checks of the web UI (fake backend): every language × theme renders
+without untranslated keys, console errors or text below 4.5:1 contrast, and
+generate → result → library → regenerate works by clicking.
+
+Needs Playwright and a Chrome/Chromium; skipped otherwise (CI does not install
+them). Run locally:
+ uv run --with playwright pytest tests/test_webui_browser.py
+Screenshots go to $WEBUI_SCREENSHOTS (default: pytest's tmp dir).
+"""
+from __future__ import annotations
+
+import json
+import os
+import socket
+import subprocess
+import sys
+import time
+import urllib.request
+from pathlib import Path
+
+import pytest
+
+playwright = pytest.importorskip("playwright.sync_api")
+
+TESTS = Path(__file__).parent
+LANGS = ("en", "ja", "zh")
+THEMES = ("light", "dark")
+
+# Walks every visible text node's element, finds its effective background by
+# going up until an opaque background, and returns WCAG contrast failures.
+CONTRAST_JS = r"""
+() => {
+ const parse = (c) => { const m = c.match(/rgba?\(([^)]+)\)/); if (!m) return null;
+ const p = m[1].split(/[ ,/]+/).filter(Boolean).map(Number); return [p[0], p[1], p[2], p.length > 3 ? p[3] : 1]; };
+ const lum = ([r, g, b]) => { const f = (v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; };
+ return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b); };
+ const bgOf = (el) => { for (let n = el; n; n = n.parentElement) { const c = parse(getComputedStyle(n).backgroundColor);
+ if (c && c[3] >= 0.99) return c; } return parse(getComputedStyle(document.body).backgroundColor); };
+ const out = []; const seen = new Set();
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
+ while (walker.nextNode()) {
+ const node = walker.currentNode; const el = node.parentElement;
+ if (!node.textContent.trim() || !el || seen.has(el)) continue; seen.add(el);
+ const r = el.getBoundingClientRect(); const cs = getComputedStyle(el);
+ if (!r.width || !r.height || cs.visibility === "hidden" || el.closest("[hidden]") || el.closest("option")) continue;
+ if (el.closest("button:disabled, [aria-disabled=true]")) continue; // WCAG exempts disabled controls
+ const fg = parse(cs.color), bg = bgOf(el); if (!fg || !bg) continue;
+ const a = fg[3]; const mix = [0, 1, 2].map((i) => fg[i] * a + bg[i] * (1 - a));
+ const l1 = lum(mix), l2 = lum(bg); const ratio = (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
+ if (ratio < 4.5) out.push({ text: node.textContent.trim().slice(0, 40), ratio: Math.round(ratio * 100) / 100, cls: el.className });
+ }
+ return out;
+}
+"""
+# Any element still showing an i18n key ("gen.title") means a missing string.
+KEYS_JS = r"""() => [...document.querySelectorAll("body *")].filter((n) => n.children.length === 0
+ && /^[a-z]+\.[a-zA-Z.]+$/.test(n.textContent.trim()) && !n.closest("[hidden]")).map((n) => n.textContent.trim())"""
+
+
+def _free_port() -> int:
+ with socket.socket() as s:
+ s.bind(("127.0.0.1", 0))
+ return s.getsockname()[1]
+
+
[email protected](scope="module")
+def web(tmp_path_factory):
+ out = tmp_path_factory.mktemp("web-out")
+ port = _free_port()
+ env = {**os.environ, "AUDIO_STUDIO_OUTPUT_DIR": str(out), "FAKE_DELAY": "1.5", "PYTHONUNBUFFERED": "1"}
+ proc = subprocess.Popen([sys.executable, str(TESTS / "fake_web_server.py"), "--web", str(port), "--no-browser"],
+ env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
+ base = f"http://127.0.0.1:{port}"
+ for _ in range(100):
+ try:
+ urllib.request.urlopen(base + "/api/status", timeout=1)
+ break
+ except OSError:
+ time.sleep(0.1)
+ else:
+ proc.kill()
+ pytest.fail(proc.stdout.read().decode(errors="replace"))
+ yield base
+ proc.terminate()
+ proc.wait(10)
+
+
[email protected](scope="module")
+def browser():
+ with playwright.sync_playwright() as p:
+ b = None
+ for kw in ({"channel": "chrome"}, {}):
+ try:
+ b = p.chromium.launch(**kw)
+ break
+ except Exception:
+ continue
+ if b is None:
+ pytest.skip("no Chrome/Chromium for Playwright")
+ yield b
+ b.close()
+
+
[email protected](scope="module")
+def shots(tmp_path_factory):
+ d = os.environ.get("WEBUI_SCREENSHOTS")
+ p = Path(d) if d else tmp_path_factory.mktemp("shots")
+ p.mkdir(parents=True, exist_ok=True)
+ return p
+
+
+def _page(browser, base, lang, theme, errors):
+ ctx = browser.new_context(locale={"en": "en-US", "ja": "ja-JP", "zh": "zh-CN"}[lang],
+ color_scheme=theme, viewport={"width": 1360, "height": 900})
+ page = ctx.new_page()
+ # The browser logs every non-2xx fetch; a 422 is the expected answer to a bad form.
+ page.on("console", lambda m: m.type == "error" and "(Unprocessable" not in m.text and errors.append(m.text))
+ page.on("pageerror", lambda e: errors.append(str(e)))
+ page.goto(base + "/")
+ return page
+
+
+def _check(page, where):
+ keys = page.evaluate(KEYS_JS)
+ assert not keys, f"{where}: untranslated keys {keys}"
+ bad = page.evaluate(CONTRAST_JS)
+ assert not bad, f"{where}: contrast below 4.5:1: {json.dumps(bad, ensure_ascii=False)}"
+
+
+def test_generate_and_library_flow(web, browser, shots):
+ """Click through: sfx form → queue of two jobs → candidates → library → regenerate."""
+ errors: list[str] = []
+ page = _page(browser, web, "en", "light", errors)
+ page.click("label:has(input[name=audio_type][value=sfx])")
+ assert page.is_visible("#sound_source") and not page.is_visible("#bpm")
+ page.fill("#sound_source", "glass bottle")
+ page.fill("#sound_action", "shattering on impact")
+ page.fill("#duration_seconds", "2")
+ page.click("label:has(input[name=variations][value='3'])")
+ page.click("#gen-submit")
+ page.click("label:has(input[name=audio_type][value=music])")
+ page.fill("#prompt", "calm piano")
+ page.fill("#duration_seconds", "2")
+ page.click("label:has(input[name=variations][value='1'])")
+ page.click("#gen-submit")
+ # second job waits behind the first
+ page.wait_for_selector(".job[data-status=queued] >> text=#1 in queue", timeout=5000)
+ page.wait_for_selector(".job[data-status=running]", timeout=5000)
+ page.wait_for_function("document.querySelectorAll('.job[data-status=done]').length === 2", timeout=15000)
+ assert page.locator(".job").first.locator(".cand").count() == 1
+ assert page.locator(".job").nth(1).locator(".cand").count() == 3
+ # audio is served
+ src = page.locator(".cand audio").first.get_attribute("src")
+ assert page.request.get(web + src).status == 200
+
+ # validation error is shown on the field, nothing queued
+ page.click("#advanced summary")
+ page.fill("#steps", "99")
+ page.click("#gen-submit")
+ page.wait_for_selector("#form-error:not([hidden])")
+ assert page.get_attribute("#steps", "aria-invalid") == "true"
+ page.click("#gen-reset")
+
+ page.click("#tab-library")
+ page.wait_for_selector(".item")
+ assert page.locator(".item").count() == 4
+ page.fill("#lib-search", "glass")
+ page.wait_for_function("document.querySelectorAll('.item').length === 3")
+ page.locator(".item").first.locator("text=Details").click()
+ assert page.locator(".item-details").first.is_visible()
+ assert "glass bottle" in page.locator(".item-details").first.text_content()
+ page.locator(".item").first.locator("text=Regenerate (same seed)").click()
+ page.wait_for_selector("#page-generate:not([hidden])")
+ page.wait_for_function("document.querySelectorAll('.job').length === 3", timeout=5000)
+ page.wait_for_function("document.querySelectorAll('.job[data-status=done]').length === 3", timeout=15000)
+ assert page.input_value("#sound_source") == "glass bottle"
+ assert not errors, errors
+
+
[email protected]("theme", THEMES)
[email protected]("lang", LANGS)
+def test_languages_and_themes(web, browser, shots, lang, theme):
+ errors: list[str] = []
+ page = _page(browser, web, lang, theme, errors)
+ # language follows the browser, theme follows the system
+ assert page.evaluate("document.documentElement.lang").startswith(lang)
+ page.wait_for_selector("#model-state[data-state]")
+ page.wait_for_load_state("networkidle")
+ if not page.locator(".job").count():
+ page.fill("#prompt", "lo-fi piano loop")
+ page.fill("#duration_seconds", "2")
+ page.click("label:has(input[name=variations][value='2'])")
+ page.click("#gen-submit")
+ page.wait_for_selector(".job[data-status=done]", timeout=15000)
+ page.click("label:has(input[name=audio_type][value=sfx])")
+ page.click("#advanced summary")
+ _check(page, f"{lang}/{theme}/generate")
+ page.screenshot(path=str(shots / f"generate-{lang}-{theme}.png"), full_page=True)
+
+ page.click("#tab-library")
+ page.wait_for_selector(".item")
+ page.locator(".item").first.locator(".item-actions button").first.click()
+ _check(page, f"{lang}/{theme}/library")
+ page.screenshot(path=str(shots / f"library-{lang}-{theme}.png"), full_page=True)
+ assert not errors, errors
+
+
+def test_manual_theme_and_language_switch(web, browser):
+ errors: list[str] = []
+ page = _page(browser, web, "en", "light", errors)
+ page.select_option("#theme", "dark")
+ assert page.evaluate("document.documentElement.dataset.theme") == "dark"
+ bg = page.evaluate("getComputedStyle(document.body).backgroundColor")
+ page.select_option("#lang", "ja")
+ assert page.text_content("#tab-library") == "ライブラリ"
+ page.reload() # both choices persist
+ assert page.evaluate("document.documentElement.dataset.theme") == "dark"
+ assert page.evaluate("getComputedStyle(document.body).backgroundColor") == bg
+ assert page.text_content("#tab-library") == "ライブラリ"
+ page.select_option("#theme", "system")
+ page.select_option("#lang", "auto")
+ assert page.evaluate("document.documentElement.dataset.theme") is None
+ assert page.text_content("#tab-library") == "Library"
+ assert not errors, errors