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-224)
Kana2d3572067e75
diff --git a/src/audio_studio_mcp/server.py b/src/audio_studio_mcp/server.pyindex 24c2c15..107cb25 100644--- a/src/audio_studio_mcp/server.py+++ b/src/audio_studio_mcp/server.py@@ -44,6 +44,7 @@ IDLE_UNLOAD_MIN = float(os.environ.get("AUDIO_STUDIO_IDLE_UNLOAD_MIN", "10"))# The MLX backend chdirs into its runtime; resolve relative inputs against the# directory the server was started from instead._START_CWD = Path.cwd()+MAX_STEM_BYTES = 160 # UTF-8; Japanese names take 3 bytes a character_backend: Backend | None = None@@ -73,6 +74,11 @@ def _out_path(stem: str, ext: str = ".wav") -> Path:server processes sharing the folder never pick the same name."""OUTPUT_DIR.mkdir(parents=True, exist_ok=True)stem = re.sub(r'[\\/:*?"<>|\s]+', "_", stem).strip("_") or "audio"+ # chained edits append _inpaint, _proc, … to the input's name; keep room for+ # _vN_N.ext.json under the 255-byte file name limit (and Windows paths)+ base, suffix = re.fullmatch(r"(.*?)(_v\d+)?", stem).groups(default="") # keep the candidate number+ base = base.encode()[:MAX_STEM_BYTES - len(suffix)].decode(errors="ignore").strip("_") or "audio"+ stem = base + suffixn = 1while True:path = OUTPUT_DIR / (f"{stem}{ext}" if n == 1 else f"{stem}_{n}{ext}")diff --git a/src/audio_studio_mcp/static/app.css b/src/audio_studio_mcp/static/app.cssindex 280fe03..d2f7b74 100644--- a/src/audio_studio_mcp/static/app.css+++ b/src/audio_studio_mcp/static/app.css@@ -153,6 +153,7 @@ input.num { width: 96px; flex: none; }.sfx-fields { border: 1px solid var(--border); border-radius: 6px; padding: 8px 10px; }.sfx-fields summary { cursor: pointer; font-weight: 550; font-size: 13px; color: var(--muted); }.sfx-fields[open] summary { margin-bottom: 8px; color: var(--text); }+.row.top { align-items: start; }.sfx-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }.mod-dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: var(--accent); margin-left: 6px; vertical-align: middle; }.advanced .link-btn { margin-top: 8px; }diff --git a/src/audio_studio_mcp/static/app.js b/src/audio_studio_mcp/static/app.jsindex 38062ec..1b99420 100644--- a/src/audio_studio_mcp/static/app.js+++ b/src/audio_studio_mcp/static/app.js@@ -191,13 +191,25 @@ function openEditor(file) {}function route() {const h = location.hash;- if (h.startsWith("#edit/")) openEditor(decodeURIComponent(h.slice(6)));+ let file = null;+ if (h.startsWith("#edit/")) {+ try { file = decodeURIComponent(h.slice(6)); } catch { file = null; } // malformed link+ }+ if (file) openEditor(file);else showPage(h === "#library" ? "library" : h === "#edit" ? "edit" : "generate", false);}function initTabs() {document.querySelectorAll(".tabs [role=tab]").forEach((b) => b.addEventListener("click", () => showPage(b.dataset.page)));window.addEventListener("hashchange", route); // typed or pasted linksroute();+ // arrow keys move between tabs (WAI-ARIA tabs pattern)+ document.querySelectorAll("[role=tablist]").forEach((list) => list.addEventListener("keydown", (e) => {+ if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;+ const tabs = [...list.querySelectorAll("[role=tab]")], i = tabs.indexOf(document.activeElement);+ if (i < 0) return;+ const next = tabs[(i + (e.key === "ArrowRight" ? 1 : tabs.length - 1)) % tabs.length];+ next.focus(); next.click(); e.preventDefault();+ }));}// ── status bar ───────────────────────────────────────────────────────────────@@ -435,7 +447,7 @@ function jobBadge(job) {}const LETTERS = "ABCD";function candidateCard(c, i, job) {- const file = baseName(c.path), mini = new MiniWave(file, c.seconds);+ const file = baseName(c.path), mini = new MiniWave(file, c.seconds, Math.round(job.finished || 0));const many = job.result.candidates.length > 1;return el("div", { class: "cand", dataset: { index: i } },el("div", { class: "cand-head", title: c.seed != null ? t("cand.seed", { seed: c.seed }) : null },@@ -543,6 +555,8 @@ function renderJobList(box, list) {updateProgress(card, job);return card;});+ const keep = new Set(nodes);+ for (const old of existing.values()) if (!keep.has(old)) disposeMinis(old);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();}@@ -567,7 +581,8 @@ async function pollJobs() {while ([...state.jobs.values()].some((j) => j.status === "queued" || j.status === "running")) {let finished = false;try {- const r = await api("/api/jobs");+ const waiting = [...state.jobs.values()].filter((j) => j.status === "queued" || j.status === "running");+ const r = await api(`/api/jobs?ids=${waiting.map((j) => j.id).join(",")}`);state.loaded = r.loaded;const seen = new Set();for (const j of r.items) {@@ -622,7 +637,7 @@ function metaRows(item) {[t("meta.strength"), m.strength], [t("meta.region"), Array.isArray(m.region) ? m.region.map((x) => `${x}s`).join(" – ") : null],[t("meta.negative"), m.negative_prompt],[t("meta.stepsDone"), Array.isArray(m.steps) ? m.steps.join(" → ") : null],- [t("meta.format"), m.kind === "process" ? `${String(m.format || "").toUpperCase()} · ${m.sample_rate} Hz · ${m.channels === 1 ? "mono" : "stereo"}` : null],+ [t("meta.format"), m.kind === "process" ? `${String(m.format || "").toUpperCase()} · ${m.sample_rate} Hz · ${m.channels === 1 ? t("edit.mono") : t("edit.stereo")}` : null],[t("meta.loudness"), m.output_lufs != null ? `${m.output_lufs} LUFS` : null],[t("meta.peak"), m.peak_dbfs != null ? `${m.peak_dbfs} dBFS` : null],[t("meta.model"), m.model ? `${m.model} (${m.backend})` : null],@@ -664,7 +679,7 @@ function libraryItem(item) {const badges = [m.audio_type ? t(`type.${m.audio_type}`) : null,kind.startsWith("edit") ? t(`mode.${kind.split(":")[1]}`) : kind === "process" ? t("kind.process") : null,kind === "process" || !m.kind ? item.format.toUpperCase() : null].filter(Boolean);- const mini = new MiniWave(item.file, item.seconds);+ const mini = new MiniWave(item.file, item.seconds, Math.round(item.mtime));return el("article", { class: "panel item" },el("div", { class: "item-main" },el("div", { class: "item-title", title: title, text: title }),@@ -690,6 +705,7 @@ function prefixSound(sf) {}function renderLibrary() {const box = $("#library"), L = state.lib;+ disposeMinis(box);box.replaceChildren(...L.items.map(libraryItem));$("#lib-count").textContent = t("lib.count", { n: L.total });$("#lib-empty").hidden = L.items.length > 0;diff --git a/src/audio_studio_mcp/static/editor.js b/src/audio_studio_mcp/static/editor.jsindex c37ce8c..532dcf5 100644--- a/src/audio_studio_mcp/static/editor.js+++ b/src/audio_studio_mcp/static/editor.js@@ -8,6 +8,7 @@const OVERVIEW_N = 4000;const MIN_SPAN = 0.05; // seconds visible at the deepest zoomconst DRAG_PX = 4; // movement that turns a click into a selection+const MIN_SEL = 0.01; // shortest selection (seconds)// Export presets: what the user is making → process_audio settings.const PRESETS = {@@ -108,7 +109,7 @@ const Editor = {item = await api(`/api/library/${encodeURIComponent(file)}`); // 404 if it is not in the output folderif (seq !== this.openSeq) return;this.audio.src = audioUrl(file);- peaks = await Peaks.get(file, OVERVIEW_N);+ peaks = await Peaks.get(file, OVERVIEW_N, null, null, Math.round(item.mtime));} catch (e) {if (seq !== this.openSeq) return;this.file = null;@@ -154,6 +155,12 @@ const Editor = {el("span", { class: "muted small", text: `${fmtLen(it.seconds)} · ${fmtDate(it.mtime)}` }))));if (items.length) box.prepend(el("p", { class: "small muted recent-head", text: t("edit.recent") }));},+ // An input path can be opened here only if it is a file of the output folder.+ inOutputDir(path) {+ if (!path || !state.status) return false;+ const name = baseName(path), dir = String(path).slice(0, -name.length - 1);+ return dir === state.status.output_dir;+ },renderInfo() {if (!this.file) return;const m = (this.item && this.item.meta) || {};@@ -167,7 +174,7 @@ const Editor = {$("#edit-info").textContent = parts.join(" · ");const src = $("#edit-source");src.replaceChildren();- if (m.input_audio) {+ if (this.inOutputDir(m.input_audio)) {const name = baseName(m.input_audio);src.append(el("span", { class: "muted", text: t("edit.madeFrom") }), " ",el("button", { type: "button", class: "link-btn", text: name, onclick: () => openEditor(name) }));@@ -213,7 +220,7 @@ const Editor = {const n = Math.min(20000, Math.ceil(px * ((e - s) / span)));const file = this.file;try {- const p = await Peaks.get(file, n, s, e);+ const p = await Peaks.get(file, n, s, e, this.item && Math.round(this.item.mtime));if (file === this.file) { this.detail = p; this.draw(); }} catch { /* keep the overview */ }}, 120);@@ -298,11 +305,15 @@ const Editor = {},// ── selection ──────────────────────────────────────────────────────────- setSel(sel, { quiet } = {}) {+ // keep: an edge is being moved, so hold a minimal width instead of dropping the selection+ setSel(sel, { quiet, keep } = {}) {const had = !!this.sel;if (sel) {let a = this.clampT(Math.min(sel.a, sel.b)), b = this.clampT(Math.max(sel.a, sel.b));- sel = b - a >= 0.01 ? { a, b } : null;+ if (b - a < MIN_SEL && keep && this.seconds >= MIN_SEL) {+ if (a + MIN_SEL <= this.seconds) b = a + MIN_SEL; else a = b - MIN_SEL;+ }+ sel = b - a >= MIN_SEL ? { a, b } : null;}this.sel = sel;this.audio.loop = $("#w-loop").checked && !sel;@@ -344,7 +355,7 @@ const Editor = {if (e.shiftKey && this.sel) {const edge = Math.abs(tm - this.sel.a) < Math.abs(tm - this.sel.b) ? "a" : "b";this.drag = { mode: "edge", edge };- this.setSel({ ...this.sel, [edge]: tm });+ this.setSel({ ...this.sel, [edge]: tm }, { keep: true });} else {this.drag = { mode: "pending", x0: e.clientX, anchor: tm };}@@ -363,7 +374,7 @@ const Editor = {else if (d.mode === "edge" && this.sel) {const other = d.edge === "a" ? this.sel.b : this.sel.a;if ((d.edge === "a" && tm > other) || (d.edge === "b" && tm < other)) d.edge = d.edge === "a" ? "b" : "a";- this.setSel(d.edge === "a" ? { a: tm, b: other } : { a: other, b: tm });+ this.setSel(d.edge === "a" ? { a: tm, b: other } : { a: other, b: tm }, { keep: true });}},pointerUp(e) {@@ -399,12 +410,18 @@ const Editor = {},handleKey(e, edge) {if (!this.sel) return;- const step = e.shiftKey ? 0.1 : 0.01;- const d = e.key === "ArrowRight" || e.key === "ArrowUp" ? step : e.key === "ArrowLeft" || e.key === "ArrowDown" ? -step : 0;- if (!d) return;+ const step = e.shiftKey ? 0.1 : 0.01, { a, b } = this.sel;+ let v;+ if (e.key === "ArrowRight" || e.key === "ArrowUp") v = this.sel[edge] + step;+ else if (e.key === "ArrowLeft" || e.key === "ArrowDown") v = this.sel[edge] - step;+ else if (e.key === "Home") v = edge === "a" ? 0 : a + MIN_SEL;+ else if (e.key === "End") v = edge === "b" ? this.seconds : b - MIN_SEL;+ else return;e.preventDefault();e.stopPropagation();- this.setSel({ ...this.sel, [edge]: this.sel[edge] + d });+ // an edge stops at the other one (the selection never disappears from a key press)+ v = edge === "a" ? Math.min(v, b - MIN_SEL) : Math.max(v, a + MIN_SEL);+ this.setSel(edge === "a" ? { a: v, b } : { a, b: v }, { keep: true });},globalKey(e) {if (!this.visible || !this.file || typing(e) || e.altKey) return;@@ -440,7 +457,8 @@ const Editor = {if (this.sel && (start < this.sel.a || start >= this.sel.b - 0.01)) start = this.sel.a;else if (!this.sel && start >= this.seconds - 0.01) start = 0;this.playSel = !!this.sel;- if (a.readyState < 1) await new Promise((r) => a.addEventListener("loadedmetadata", r, { once: true }));+ const file = this.file;+ if (!(await whenReady(a)) || file !== this.file) return;a.currentTime = start;this.playhead = start;try { await a.play(); } catch { /* interrupted */ }@@ -515,7 +533,7 @@ const Editor = {outLen() {const trim = this.xField("trim_selection").checked && this.sel;let len = trim ? this.sel.b - this.sel.a : this.seconds;- if (this.xField("loop").checked) len -= Number(this.xField("loop_crossfade_ms").value) / 1000 || 0;+ if (this.xField("loop").checked) len -= (Number(this.xField("loop_crossfade_ms").value) || 200) / 1000;return Math.max(0, len);},// Fades never take more than a quarter of the output each (a 2 s fade on a 0.4 s clip silences it).@@ -547,8 +565,10 @@ const Editor = {"aria-pressed": String(Math.abs(target - Math.ceil(this.seconds + d)) < 0.01), text: `+${d} s`,onclick: () => { dur.value = Math.ceil(this.seconds + d); this.updateAiForm(); } })));// submit label states what will happen+ const atMax = this.seconds >= this.max() - 0.5; // nothing left to extend+ if (mode === "continue" && atMax) $("#extend-hint").textContent = t("edit.atMax", { max: this.max() });const btn = $("#ai-submit");- btn.disabled = !this.file || (mode === "inpaint" && !this.sel);+ btn.disabled = !this.file || (mode === "inpaint" && !this.sel) || (mode === "continue" && atMax);if (mode === "variation") btn.textContent = n > 1 ? t("edit.submitVariationN", { n }) : t("edit.submitVariation");else if (mode === "inpaint") btn.textContent = this.sel ? t("edit.submitInpaint", { range: this.selText() }) : t("mode.inpaint");else btn.textContent = t("edit.submitContinue", { len: target > 0 ? `${target} s` : "—" });@@ -556,7 +576,7 @@ const Editor = {// AI edits of an export (mono, resampled, normalized) are better done on its originalconst m = (this.item && this.item.meta) || {};const exp = $("#export-note");- exp.hidden = !(m.kind === "process" && m.input_audio);+ exp.hidden = !(m.kind === "process" && this.inOutputDir(m.input_audio));if (!exp.hidden) {const orig = baseName(m.input_audio);exp.replaceChildren(el("span", { text: t("edit.isExport") }), " ",@@ -657,9 +677,9 @@ const Editor = {if (trim.checked) parts.push(t("sum.trim", { range: this.selText() }));if (this.xField("trim_silence").checked) parts.push(t("sum.silence"));if (this.xField("mono").checked) parts.push(t("sum.mono"));- if (norm === "peak") parts.push(t("sum.peak", { db: this.xField("peak_ceiling_db").value }));- if (norm === "loudness") parts.push(t("sum.lufs", { lufs: this.xField("target_lufs").value }));- if (this.xField("loop").checked) parts.push(t("sum.loop", { ms: this.xField("loop_crossfade_ms").value }));+ if (norm === "peak") parts.push(t("sum.peak", { db: this.xField("peak_ceiling_db").value || "-1" }));+ if (norm === "loudness") parts.push(t("sum.lufs", { lufs: this.xField("target_lufs").value || "-16" }));+ if (this.xField("loop").checked) parts.push(t("sum.loop", { ms: this.xField("loop_crossfade_ms").value || "200" }));const { fi, fo, clamped } = this.fades();if (fi || fo) parts.push(t(clamped ? "sum.fadeShort" : "sum.fade", { a: fi, b: fo }));const fmt = String(this.xField("format").value).toUpperCase(), sr = Number(this.xField("sample_rate").value) / 1000;@@ -670,13 +690,16 @@ const Editor = {async submitExport() {const f = $("#export-form");clearErrors(f, $("#x-error"));- const num = (k) => Number(this.xField(k).value);+ const { fi, fo } = this.fades();const args = { input_audio: this.file, trim_silence: this.xField("trim_silence").checked, mono: this.xField("mono").checked,- normalize: this.xField("normalize").value, peak_ceiling_db: num("peak_ceiling_db"), loop: this.xField("loop").checked,- fade_in_ms: this.fades().fi, fade_out_ms: this.fades().fo, format: this.xField("format").value,- sample_rate: num("sample_rate") };- if (args.normalize === "loudness") args.target_lufs = num("target_lufs");- if (args.loop) args.loop_crossfade_ms = num("loop_crossfade_ms");+ normalize: this.xField("normalize").value, loop: this.xField("loop").checked,+ fade_in_ms: fi, fade_out_ms: fo, format: this.xField("format").value,+ sample_rate: Number(this.xField("sample_rate").value) };+ // an emptied field means "the tool's default", not 0+ const num = (k, name = k) => { const raw = this.xField(k).value.trim(); if (raw !== "") args[name] = Number(raw); };+ num("peak_ceiling_db");+ if (args.normalize === "loudness") num("target_lufs");+ if (args.loop) num("loop_crossfade_ms");if (this.xField("trim_selection").checked && this.sel) {args.start_seconds = +this.sel.a.toFixed(3);args.end_seconds = +this.sel.b.toFixed(3);diff --git a/src/audio_studio_mcp/static/i18n.js b/src/audio_studio_mcp/static/i18n.jsindex 296b2fb..8b64240 100644--- a/src/audio_studio_mcp/static/i18n.js+++ b/src/audio_studio_mcp/static/i18n.js@@ -85,6 +85,7 @@ window.I18N = {"edit.strength": "How different?", "edit.subtle": "Close to the original", "edit.loose": "Very different","edit.totalLength": "Total length after extending (seconds)","edit.extendHint": "Now {now}. Up to {max} s.",+ "edit.atMax": "This sound is already at the maximum length ({max} s).","edit.prompt": "Description (English)","edit.promptHint.variation": "Describe the result. Keep the original text for the same style, or change it (e.g. another instrument).","edit.promptHint.inpaint": "What should the selected part sound like? The audio around it matters more than the text.",@@ -230,6 +231,7 @@ window.I18N = {"edit.strength": "どれくらい変える?", "edit.subtle": "元に近い", "edit.loose": "大きく変える","edit.totalLength": "延長後の長さ(秒)","edit.extendHint": "現在 {now}。最大 {max} 秒。",+ "edit.atMax": "この音はすでに最大の長さ({max} 秒)です。","edit.prompt": "説明(英語)","edit.promptHint.variation": "結果を説明します。同じ雰囲気ならそのまま、変えたいなら書き換えます(例:別の楽器)。","edit.promptHint.inpaint": "選択部分をどんな音にするか。説明文より前後の音の影響が大きくなります。",@@ -375,6 +377,7 @@ window.I18N = {"edit.strength": "改变多少?", "edit.subtle": "接近原声", "edit.loose": "大幅改变","edit.totalLength": "延长后的总时长(秒)","edit.extendHint": "当前 {now},最长 {max} 秒。",+ "edit.atMax": "这个声音已经是最大时长({max} 秒)。","edit.prompt": "描述(英文)","edit.promptHint.variation": "描述想要的结果。保持原文则风格不变,改写则会变化(例如换一种乐器)。","edit.promptHint.inpaint": "选中的部分应该是什么声音?前后的音频比文字影响更大。",diff --git a/src/audio_studio_mcp/static/index.html b/src/audio_studio_mcp/static/index.htmlindex c0c5b59..d666a81 100644--- a/src/audio_studio_mcp/static/index.html+++ b/src/audio_studio_mcp/static/index.html@@ -247,7 +247,7 @@<p class="hint" id="ai-prompt-hint"></p></div>- <div class="row">+ <div class="row top"><div class="field"><label for="ai-type" data-i18n="edit.treatAs">Treat as</label><select id="ai-type" name="audio_type" aria-describedby="ai-type-hint">diff --git a/src/audio_studio_mcp/static/wave.js b/src/audio_studio_mcp/static/wave.jsindex 4c86907..6771a3e 100644--- a/src/audio_studio_mcp/static/wave.js+++ b/src/audio_studio_mcp/static/wave.js@@ -5,8 +5,8 @@const Peaks = {cache: new Map(), // key -> Promise of the /api/peaks answer- get(file, n, start, end) {- const q = `n=${n}` + (start != null ? `&start=${start.toFixed(4)}&end=${end.toFixed(4)}` : "");+ get(file, n, start, end, version) {+ const q = `n=${n}` + (start != null ? `&start=${start.toFixed(4)}&end=${end.toFixed(4)}` : "") + (version ? `&v=${version}` : "");const key = `${file}?${q}`;if (!this.cache.has(key)) {if (this.cache.size > 200) this.cache.clear();@@ -75,7 +75,7 @@ const Player = {},// all = every thumbnail (resize, theme); otherwise only the playing one and the previous oneemit(all) {- if (all) { for (const m of this.listeners) m.render(); return; }+ if (all) { for (const m of [...this.listeners]) m.render(); return; }for (const m of [this.owner, this.prev]) if (m) m.render();},async play(mini, at) {@@ -86,8 +86,8 @@ const Player = {}if (this.owner !== mini) { this.prev = this.owner; this.owner = mini; }if (at != null) {- if (a.readyState < 1) await new Promise((r) => a.addEventListener("loadedmetadata", r, { once: true }));- a.currentTime = Math.min(at, (a.duration || at) - 0.01);+ if (!(await whenReady(a)) || this.owner !== mini) return;+ a.currentTime = Math.max(0, Math.min(at, (a.duration || at) - 0.01));}try { await a.play(); } catch { /* interrupted by another play() */ }this.emit(false);@@ -99,8 +99,9 @@ const Player = {// Compact player: play button + waveform thumbnail (click / arrow keys seek) + time.class MiniWave {- constructor(file, seconds) {+ constructor(file, seconds, version) {this.file = file;+ this.version = version;this.seconds = seconds || 0;this.peaks = null;this.btn = el("button", { class: "play-btn", type: "button", "aria-label": t("player.play"), onclick: () => this.toggle() });@@ -117,11 +118,16 @@ class MiniWave {async load() {if (this.peaks) return;try {- this.peaks = await Peaks.get(this.file, 240);+ this.peaks = await Peaks.get(this.file, 240, null, null, this.version);this.seconds = this.peaks.seconds;} catch { this.peaks = { min: [], max: [] }; }this.render();}+ // Called when the card is removed or re-rendered.+ dispose() {+ Player.listeners.delete(this);+ MiniWave.observer.unobserve(this.node);+ }toggle() { Player.isPlaying(this) ? Player.pause() : Player.play(this, Player.owner === this ? null : 0); }seekTo(sec) { Player.play(this, Math.max(0, Math.min(this.seconds, sec))); }seekPointer(e) {@@ -140,7 +146,7 @@ class MiniWave {}render() {if (!this.node.isConnected) { // card removed from the page: forget it- if (this.attached) Player.listeners.delete(this);+ if (this.attached) this.dispose();return this.update();}this.attached = true;@@ -168,6 +174,22 @@ MiniWave.observer = new IntersectionObserver((entries) => {for (const e of entries) if (e.isIntersecting) { e.target.mini.load(); MiniWave.observer.unobserve(e.target); }}, { rootMargin: "200px" });+// Resolves true once the element knows its duration, false on an error or after 10 s.+function whenReady(a) {+ if (a.readyState >= 1) return Promise.resolve(true);+ return new Promise((resolve) => {+ const done = (ok) => { clearTimeout(timer); a.removeEventListener("loadedmetadata", yes); a.removeEventListener("error", no); resolve(ok); };+ const yes = () => done(true), no = () => done(false);+ const timer = setTimeout(no, 10000);+ a.addEventListener("loadedmetadata", yes);+ a.addEventListener("error", no);+ });+}+// Dispose the thumbnails inside nodes that are being removed or replaced.+function disposeMinis(root) {+ root.querySelectorAll(".mini-wave").forEach((n) => n.mini && n.mini.dispose());+}+// m:ss.t for waveform times, m:ss for card lengthsfunction fmtClock(sec, decimals = 0) {sec = Math.max(0, sec || 0);diff --git a/src/audio_studio_mcp/web.py b/src/audio_studio_mcp/web.pyindex 79e277d..370bbc4 100644--- a/src/audio_studio_mcp/web.py+++ b/src/audio_studio_mcp/web.py@@ -19,6 +19,7 @@ from __future__ import annotationsimport asyncioimport itertoolsimport json+import mathimport osimport secretsimport stat@@ -119,14 +120,13 @@ class JobQueue: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 positions(self) -> dict[str, int]:+ """1-based place of each queued job (started jobs have none)."""+ queued = sorted((j for j in self.jobs.values() if j.status == "queued"), key=lambda j: j.seq)+ return {j.id: i for i, j in enumerate(queued, 1)}- def view(self, job: Job) -> dict:- return job.view(self.position(job))+ def view(self, job: Job, positions: dict[str, int] | None = None) -> dict:+ return job.view((positions if positions is not None else self.positions()).get(job.id))def cancel(self, job: Job) -> bool:"""Drop a job that has not started yet (a running model call cannot stop)."""@@ -190,7 +190,7 @@ def _output_dir() -> Path: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:+ if not name or "/" in name or "\\" in name or name.startswith(".") or "\0" in name:return Noneroot = _output_dir().resolve()path = (root / name)@@ -200,7 +200,8 @@ def _safe_audio_path(name: str) -> Path | None:resolved = path.resolve(strict=True)except (OSError, RuntimeError):return None- if resolved.parent != root or not resolved.is_file():+ # a symlink must stay in the folder and point at audio as well+ if resolved.parent != root or resolved.suffix.lower() not in AUDIO_EXTS or not resolved.is_file():return Nonereturn resolved@@ -298,6 +299,8 @@ def list_library(query: str = "", offset: int = 0, limit: int = 100, kind: str =if p.suffix.lower() not in AUDIO_EXTS or p.name.startswith("."):continuetry:+ if p.is_symlink() and _safe_audio_path(p.name) is None:+ continue # points outside the folder or at something that is not audiost = p.stat()except OSError: # deleted while we scancontinue@@ -316,43 +319,64 @@ def list_library(query: str = "", offset: int = 0, limit: int = 100, kind: str =# ── waveform peaks ───────────────────────────────────────────────────────────-# Decoded on the server so every format the tools read draws in every browser-# (Safari cannot decode OGG Vorbis). A few decoded clips are kept for zooming.-_decoded: dict[tuple, tuple] = {}-_decoded_lock = threading.Lock()-_DECODED_KEEP = 4---def _decode(path: Path) -> tuple:+# Read on the server so every format the tools read draws in every browser+# (Safari cannot decode OGG Vorbis). Each file is summarized once, streaming,+# into min/max per PEAK_BLOCK frames (380 s stereo → ~0.5 MB instead of a+# 127 MB decode); windows finer than that read just their frames from the file.+PEAK_BLOCK = 256+_summaries: dict[tuple, tuple] = {} # (path, mtime, size) -> (sr, channels, frames, mins, maxs)+_summary_lock = threading.Lock() # one summary at a time; also dedupes parallel requests+_SUMMARY_KEEP = 64+++def _summary(path: Path) -> tuple:+ import soundfile as sfst = path.stat()key = (str(path), st.st_mtime_ns, st.st_size)- with _decoded_lock:- hit = _decoded.pop(key, None)- if hit is None:- hit = post.read(path)- with _decoded_lock:- _decoded[key] = hit # most recent last- while len(_decoded) > _DECODED_KEEP:- del _decoded[next(iter(_decoded))]+ with _summary_lock:+ hit = _summaries.pop(key, None)+ if hit is None:+ mins, maxs = [], []+ with sf.SoundFile(str(path)) as f:+ sr, channels = f.samplerate, f.channels+ for block in f.blocks(blocksize=PEAK_BLOCK * 4096, dtype="float32", always_2d=True):+ lo, hi = block.min(axis=1), block.max(axis=1)+ idx = np.arange(0, len(lo), PEAK_BLOCK)+ mins.append(np.minimum.reduceat(lo, idx))+ maxs.append(np.maximum.reduceat(hi, idx))+ frames = f.frames if f.frames > 0 else sum(len(m) for m in mins) * PEAK_BLOCK+ empty = np.zeros(0, dtype=np.float32)+ hit = (sr, channels, frames, np.concatenate(mins) if mins else empty,+ np.concatenate(maxs) if maxs else empty)+ _summaries[key] = hit # most recent last+ while len(_summaries) > _SUMMARY_KEEP:+ del _summaries[next(iter(_summaries))]return hit+def _buckets(lo: np.ndarray, hi: np.ndarray, n: int) -> tuple[np.ndarray, np.ndarray]:+ """Reduce per-frame (or per-block) min/max to n buckets. A bucket narrower+ than one input value (zoomed past sample level) repeats the value it starts on."""+ idx = (np.arange(n) * len(lo)) // n+ return np.minimum.reduceat(lo, idx), np.maximum.reduceat(hi, idx)++def peaks(path: Path, n: int, start: float | None = None, end: float | None = None) -> dict:"""Min/max of all channels in n equal buckets over [start, end] seconds."""- audio, sr = _decode(path)- total = audio.shape[-1]- seconds = total / sr+ sr, channels, total, bmin, bmax = _summary(path)s = 0 if start is None else min(total, max(0, int(start * sr)))e = total if end is None else min(total, max(s, int(end * sr)))- seg = audio[:, s:e]lo = hi = np.zeros(0, dtype=np.float32)- if seg.shape[-1] and n:- # reduceat over bucket starts; a bucket narrower than one sample- # (zoomed past sample level) repeats the sample it starts on- idx = (np.arange(n) * seg.shape[-1]) // n- lo = np.minimum.reduceat(seg.min(axis=0), idx)- hi = np.maximum.reduceat(seg.max(axis=0), idx)- return {"seconds": round(seconds, 4), "sample_rate": sr, "channels": int(audio.shape[0]),+ if e > s and n:+ if (e - s) >= n * PEAK_BLOCK: # coarse enough for the summary+ b0, b1 = s // PEAK_BLOCK, min(len(bmin), -(-e // PEAK_BLOCK))+ lo, hi = _buckets(bmin[b0:b1], bmax[b0:b1], n)+ else:+ import soundfile as sf+ seg = sf.read(str(path), start=s, stop=e, dtype="float32", always_2d=True)[0]+ if len(seg):+ lo, hi = _buckets(seg.min(axis=1), seg.max(axis=1), n)+ return {"seconds": round(total / sr, 4), "sample_rate": sr, "channels": channels,"start": round(s / sr, 4), "end": round(e / sr, 4),"min": [round(float(v), 4) for v in lo], "max": [round(float(v), 4) for v in hi]}@@ -466,10 +490,15 @@ async def api_jobs_create(request: Request) -> Response:return JSONResponse(jobs.view(job), status_code=202)-async def api_jobs_list(_: Request) -> Response:+async def api_jobs_list(request: Request) -> Response:items = sorted(jobs.jobs.values(), key=lambda j: j.seq, reverse=True)+ ids = request.query_params.get("ids")+ if ids is not None: # the page polls only the jobs it is waiting for+ wanted = set(ids.split(","))+ items = [j for j in items if j.id in wanted]+ pos = jobs.positions()# `loaded` lets the page tell "loading the model" from "generating"- return JSONResponse({"items": [jobs.view(j) for j in items], **jobs.counts(),+ return JSONResponse({"items": [jobs.view(j, pos) for j in items], **jobs.counts(),"loaded": bool(server.get_backend().loaded())})@@ -529,8 +558,10 @@ async def api_peaks(request: Request) -> Response:n = min(MAX_PEAKS, max(1, int(q.get("n", 2000))))start = float(q["start"]) if q.get("start") else Noneend = float(q["end"]) if q.get("end") else None+ if not all(math.isfinite(v) for v in (start, end) if v is not None):+ raise ValueErrorexcept ValueError:- return _err(400, "n/start/end must be numbers")+ return _err(400, "n/start/end must be finite numbers")try:return JSONResponse(await asyncio.to_thread(peaks, path, n, start, end))except Exception as e: # unreadable or truncated file@@ -577,16 +608,16 @@ def serve(port: int, open_browser: bool = True) -> None:url = f"http://127.0.0.1:{port}/"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 readable- 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()++ class Server(uvicorn.Server):+ # Announce from the startup itself: a watcher thread can be killed+ # before it prints when the server is stopped right away (uvicorn+ # re-raises SIGTERM after shutting down).+ async def startup(self, sockets=None):+ await super().startup(sockets=sockets)+ if self.started:+ print(f"[audio-studio] web UI: {url} MCP: {url}mcp", flush=True)+ if open_browser:+ threading.Thread(target=webbrowser.open, args=(url,), daemon=True, name="open-browser").start()++ Server(config).run()diff --git a/tests/test_server.py b/tests/test_server.pyindex b0e7a29..9985db0 100644--- a/tests/test_server.py+++ b/tests/test_server.py@@ -230,3 +230,13 @@ async def test_sidecars_are_utf8_whatever_the_locale(fake):p = await call("process_audio", {"input_audio": r["candidates"][0]["path"], "sample_rate": 48000})meta = json.loads(Path(p["metadata"]).read_bytes().decode("utf-8"))assert meta["source"]["original_idea"] == idea and any("→" in s for s in meta["steps"])+++def test_output_names_stay_short(fake):+ """Chained edits keep appending to the input name; it is capped (bytes)."""+ long = "あ" * 100 + "_" + "x" * 200+ p1, p2 = server._out_path(long + "_v1"), server._out_path(long + "_v2")+ for p in (p1, p2):+ assert len(p.name.encode()) <= server.MAX_STEM_BYTES + 4+ p.with_suffix(".wav.json").write_text("{}") # the sidecar name fits too+ assert p1.stem.endswith("_v1") and p2.stem.endswith("_v2")diff --git a/tests/test_web.py b/tests/test_web.pyindex a02905f..827bf9d 100644--- a/tests/test_web.py+++ b/tests/test_web.py@@ -203,6 +203,13 @@ def test_peaks(client, fake):e = client.get("/api/peaks/p.wav?n=10&start=5&end=9").json()assert e["min"] == [] and e["start"] == e["end"] == 1.0assert client.get("/api/peaks/p.wav?n=x").status_code == 400+ for bad in ("nan", "inf", "-inf"):+ assert client.get(f"/api/peaks/p.wav?n=10&start={bad}&end=1").status_code == 400+ # summary path (coarse) and exact path (fine) agree on a window+ coarse = client.get("/api/peaks/p.wav?n=4&start=0&end=1").json()+ fine = client.get("/api/peaks/p.wav?n=400&start=0&end=0.01").json()+ assert len(coarse["max"]) == 4 and len(fine["max"]) == 400+ assert max(coarse["max"]) == pytest.approx(0.5, abs=1e-3)assert client.get("/api/peaks/b.flac?n=10").json()["seconds"] == pytest.approx(0.5, abs=0.01)for bad in ("../secret.wav", "notes.txt", "missing.wav"):assert client.get(f"/api/peaks/{bad}").status_code == 404@@ -239,6 +246,16 @@ def test_queue_runs_in_order_with_positions(client, fake):assert [j["id"] for j in listed] == ids[::-1]+def test_jobs_list_filtered_by_ids(client, fake):+ ids = [client.post("/api/jobs", json={"arguments": {"prompt": f"p{i}", "duration_seconds": 1}}).json()["id"]+ for i in range(3)]+ for i in ids:+ wait_job(client, i)+ r = client.get(f"/api/jobs?ids={ids[0]},{ids[2]},nope").json()+ assert [j["id"] for j in r["items"]] == [ids[2], ids[0]]+ assert len(client.get("/api/jobs").json()["items"]) == 3++def test_cancel_waiting_job(client, fake):gate = threading.Event()orig = fake._generate@@ -325,6 +342,25 @@ def test_library_kind_filter(client, fake):assert client.get("/api/library?kind=video").status_code == 400+def test_symlinks_and_hidden_files(client, fake):+ out = _make_library(fake)+ secret = out.parent / "secret.wav"+ post.write(secret, sine(0.1), 44100, "wav")+ (out / ".hidden.wav").write_bytes((out / "a.wav").read_bytes())+ try:+ (out / "outside.wav").symlink_to(secret)+ (out / "alias.wav").symlink_to(out / "a.wav.json") # audio name, JSON target+ (out / "inside.wav").symlink_to(out / "a.wav")+ except OSError:+ pytest.skip("symlinks not available")+ listed = {i["file"] for i in client.get("/api/library").json()["items"]}+ assert listed == {"a.wav", "b.flac", "inside.wav"}+ for name in ("outside.wav", "alias.wav", ".hidden.wav"):+ for api in ("audio", "peaks", "library"):+ assert client.get(f"/api/{api}/{name}").status_code == 404, (api, name)+ assert client.get("/api/audio/inside.wav").status_code == 200++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@@ -495,19 +531,22 @@ def test_web_port_is_validated(capsys, port):assert "--web" in capsys.readouterr().err-def test_web_opens_browser_once_started(monkeypatch):+def test_web_opens_browser_once_started(monkeypatch, capsys):opened = []- started = threading.Event()- class FakeServer:+ class FakeServer: # stands in for uvicorn.Server: startup succeeds or fails (port in use)+ fail = False+def __init__(self, config):- self.started, self.should_exit = False, False+ self.started = Falseassert config.host == "127.0.0.1" and config.port == 8123+ async def startup(self, sockets=None):+ self.started = not self.fail+def run(self):- self.started = True- started.set()- time.sleep(0.5)+ anyio.run(self.startup)+ time.sleep(0.2) # the browser opens on a threadimport uvicornimport webbrowser@@ -515,6 +554,11 @@ def test_web_opens_browser_once_started(monkeypatch):monkeypatch.setattr(webbrowser, "open", opened.append)web.serve(8123, open_browser=True)assert opened == ["http://127.0.0.1:8123/"]+ assert "web UI: http://127.0.0.1:8123/" in capsys.readouterr().outopened.clear()web.serve(8123, open_browser=False)assert opened == []+ capsys.readouterr()+ FakeServer.fail = True+ web.serve(8123, open_browser=True)+ assert opened == [] and "web UI" not in capsys.readouterr().outdiff --git a/tests/test_webui_browser.py b/tests/test_webui_browser.pyindex 8eeb6d5..2309417 100644--- a/tests/test_webui_browser.py+++ b/tests/test_webui_browser.py@@ -224,6 +224,11 @@ def test_generate_and_library_flow(web, browser, shots):page.wait_for_selector("#lib-empty:not([hidden])")page.click("#lib-empty-btn") # clear searchpage.wait_for_function("document.querySelectorAll('.item').length === 5")+ # re-rendering the library does not keep old thumbnails alive+ for q in ("glass", "piano", "", "glass", ""):+ page.fill("#lib-search", q)+ page.wait_for_timeout(350)+ assert page.evaluate("Player.listeners.size") <= page.evaluate("document.querySelectorAll('.mini-wave').length")assert not errors, errors@@ -321,6 +326,27 @@ def test_editor_flow(web, browser, shots):page.click("#w-zoom-fit")assert page.evaluate("Editor.view") == {"s": 0, "e": page.evaluate("Editor.seconds")}+ # handles: arrow keys stop at the other edge instead of dropping the selection+ page.fill("#w-start", "1")+ page.press("#w-start", "Enter")+ page.fill("#w-end", "1.05")+ page.press("#w-end", "Enter")+ page.focus("#w-h-start")+ for _ in range(10):+ page.keyboard.press("ArrowRight")+ assert page.evaluate("Editor.sel") == {"a": pytest.approx(1.04), "b": pytest.approx(1.05)}+ page.keyboard.press("Home")+ assert page.evaluate("Editor.sel.a") == 0+ # an emptied number field means the tool's default, not 0+ page.click("#st-export")+ page.click("label.preset:has(input[value=game_sfx])")+ page.fill("#x-peak", "")+ page.click("#x-submit")+ page.wait_for_function("[...state.jobs.values()].filter(j => j.tool === 'process_audio' && j.status === 'done').length === 3", timeout=10000)+ last = page.evaluate("[...state.jobs.values()].filter(j => j.tool === 'process_audio').sort((a, b) => b.created - a.created)[0]")+ assert "peak_ceiling_db" not in last["arguments"] and last["result"]["peak_dbfs"] <= -0.99+ page.click("#st-ai")+# keys: Esc clears, click moves the playhead, Space plays and pausespage.click("#w-wave")page.keyboard.press("Escape")@@ -339,11 +365,14 @@ def test_editor_flow(web, browser, shots):# the library filters by typepage.click("#tab-library")page.click("#lib-kinds >> text=Exports")- page.wait_for_function("document.querySelectorAll('.item').length === 2")+ page.wait_for_function("document.querySelectorAll('.item').length === 3")assert all(f.endswith(".ogg") or f.endswith(".wav") for f in page.locator(".item-file").all_text_contents())page.click("#lib-kinds >> text=AI edits")page.wait_for_function("document.querySelectorAll('.item').length === 2")page.click("#lib-kinds >> text=All")+ page.evaluate("location.hash = '#edit/%E0%A4%A'") # malformed link: no exception+ page.wait_for_selector("#page-generate:not([hidden])")+ assert not errors, errorspage.goto(web + "/#edit/missing.wav")page.wait_for_selector("#edit-empty:not([hidden])")page.wait_for_selector("#toast >> text=missing.wav is not in the output folder")