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
Fixes from the Windows QA, README for the web UI (GAME-240)
Kanaa518755a2872
diff --git a/.github/release-notes/v0.3.0.md b/.github/release-notes/v0.3.0.mdindex f0c8202..27a3305 100644--- a/.github/release-notes/v0.3.0.md+++ b/.github/release-notes/v0.3.0.md@@ -26,10 +26,20 @@## Changes for MCP clients- The four tools (`generate_audio`, `edit_audio`, `process_audio`, `unload_models`) have the same parameters, results and sidecars as in v0.2.2, and give the same audio for the same seed.-- Output file names are now capped at 160 bytes. Long titles (especially Japanese ones) and long chains of edits used to grow past the 255-byte file name limit of most file systems. When a name is cut, the middle is dropped, so the seed, the edit step (`_inpaint`, `_proc`, …) and the version number (`_v2`) stay at the end.+- Output file names are now capped at 160 bytes. Long titles (especially Japanese ones) and long chains of edits used to grow past the 255-byte file name limit of most file systems. When a name is cut, the middle is dropped, so the seed, the edit step (`_inpaint`, `_proc`, …), the version number (`_v2`) and a `_2` counter stay at the end.+- When a name is already taken, all candidates of one call now move on together: a second run with the same title gives `title_2_v1`, `title_2_v2` instead of `title_v1_2`, `title_v2_2`.- New files are created with normal file permissions (`0644`) instead of being marked executable.- `--http` and `--web` can't be combined; `--web` checks that the port is valid.+## Install++- Windows: `install.ps1` now works when the folder path contains Japanese (or other non-ASCII) characters, for example under a Japanese user name. Python 3.11 could not start from such a `.venv`, and the installer wrongly reported that you were not logged in to Hugging Face. It now also checks that the `.venv` starts and says so clearly if it doesn't.+- Both installers end by showing how to start the web UI.++## Docs++- The READMEs (English, 简体中文, 日本語) have a new **Web UI** section, and the license section lists the bundled font.+## UpdateFrom an existing clone:diff --git a/README.ja.md b/README.ja.mdindex c7cbf72..e290f1a 100644--- a/README.ja.md+++ b/README.ja.md@@ -16,7 +16,7 @@[English](README.md) | [简体中文](README.zh-CN.md) | **日本語**-[🎧 サンプルを聴く](https://kanaworksai-hue.github.io/audio-studio-mcp/) · [クイックスタート](#-クイックスタート) · [ツール](#-ツール) · [FAQ](#-faq) · [⭐ Star で応援](#-star-で応援する)+[🎧 サンプルを聴く](https://kanaworksai-hue.github.io/audio-studio-mcp/) · [クイックスタート](#-クイックスタート) · [ツール](#-ツール) · [Web UI](#-web-ui) · [FAQ](#-faq) · [⭐ Star で応援](#-star-で応援する)</div>@@ -185,6 +185,28 @@ macOS ではダウンロードにログインは不要で、`hf auth login` で生成ファイルは 44.1 kHz 24-bit ステレオ WAV で、このフォルダの `outputs/` に保存され、それぞれ隣に `<ファイル名>.json` が付きます。後処理したファイルには、元の生成情報が `source` として残ります。</details>+## 🌐 Web UI++チャットよりクリックで操作したい場合は、同じサーバーに付属するローカルの Web ページが使えます。BGM や効果音の生成、候補の聴き比べ、編集(バリエーション、一部の差し替え、延長)、ゲームや動画向けの書き出し、これまで作った音を一覧できるライブラリまで、ブラウザで操作できます。++```bash+.venv/bin/audio-studio-mcp --web 8765+```++ブラウザで http://127.0.0.1:8765/ が開きます。ブラウザを開かずに起動するには `--no-browser`、起動時にモデルを読み込むには `--preload` を付けます。止めるときは Ctrl+C です。Windows では `.venv\Scripts\audio-studio-mcp.exe --web 8765` で起動します。++同じポートの `/mcp` で MCP も提供されるので、ページと MCP クライアントで 1 つのプロセスと読み込み済みのモデルを共有できます。一度登録すれば両方を同時に使えます。ページからのリクエストとエージェントからのリクエストは 1 つのキューで順番に処理されます。++```bash+claude mcp add --scope user --transport http audio-studio http://127.0.0.1:8765/mcp+```++- ファイルは出力フォルダ(`outputs/`、または `AUDIO_STUDIO_OUTPUT_DIR`)に書き出されます。ライブラリにはこのフォルダの中身が表示され、編集もこのフォルダ内のファイルが対象です。+- 表示言語は英語・日本語・中国語で、ブラウザの言語に合わせて切り替わります。設定から変更することもできます。++> [!WARNING]+> Web UI は自分のパソコンだけで使うためのものです。待ち受けは `127.0.0.1` のみで、ログイン機能はありません。ポート転送、リバースプロキシ、トンネルなどで他のマシンから開けるようにしないでください。開ける人は誰でも GPU を使い、出力フォルダにファイルを書き込めてしまいます。+## ⚙️ 設定<details>@@ -215,6 +237,8 @@ claude mcp add --scope user --transport http audio-studio http://127.0.0.1:8765/```Windows では `.venv\Scripts\audio-studio-mcp.exe --http 8765 --preload` で起動します。++`--web 8765` でも同じように動き、同じポートで [Web UI](#-web-ui) も使えます。</details>## ⚡ パフォーマンス@@ -304,6 +328,7 @@ Rosetta で動く x86_64 版の Python(たとえば `/usr/local` にある Int- [x] Apple Silicon バックエンド(Stable Audio 3、MLX)- [x] NVIDIA GPU 向けの Windows バックエンド(Stable Audio 3、PyTorch)+- [x] ローカル Web UI(`--web`)- [ ] LoRA 対応(上流のランタイムは対応済み)Issue やプルリクエストを歓迎します。@@ -334,6 +359,8 @@ src/audio_studio_mcp/backends/base.py バックエンドのインターフェースbackends/sa3_mlx.py Apple Silicon 上の Stable Audio 3(MLX)backends/sa3_torch.py NVIDIA GPU 上の Stable Audio 3(PyTorch)+ web.py Web UI のサーバー(--web)と JSON API+ static/ Web UI(HTML/JS/CSS、ビルド不要)```新しいプラットフォームは、`backends/` にバックエンドとして追加します。@@ -344,6 +371,7 @@ src/audio_studio_mcp/- **Stable Audio 3 ランタイム:** インストール時に `vendor/` へダウンロードされます。© Stability AI、MIT ライセンスです。- **モデルの重み:** [Stability AI Community License](https://huggingface.co/stabilityai/stable-audio-3-optimized) が適用されます。重みは Hugging Face からダウンロードされ(macOS:`stable-audio-3-optimized`、Windows:`stable-audio-3-medium` と小型モデル)、本プロジェクトでは配布していません。- **ブランド:** KanaWorks_AI の名称、ロゴ、Kana のキャラクターの権利は東京AI映像合同会社に帰属し、MIT ライセンスの対象**外**です。詳しくは [docs/brand](docs/brand/README.md) を参照してください。+- **フォント:** Web UI には IBM Plex Sans(© IBM Corp.、SIL Open Font License 1.1)を同梱しています([`OFL.txt`](src/audio_studio_mcp/static/fonts/OFL.txt))。Web UI の Kana の画像([`static/brand`](src/audio_studio_mcp/static/brand/README.md))には上記「ブランド」の項が適用されます。- **使用している技術:** [Stable Audio 3](https://github.com/Stability-AI/stable-audio-3)、[MLX](https://github.com/ml-explore/mlx)、[PyTorch](https://pytorch.org)、[Model Context Protocol](https://modelcontextprotocol.io)本プロジェクトは独立したプロジェクトであり、Stability AI、Apple、NVIDIA、Anthropic とは関係がなく、その承認も受けていません。diff --git a/README.md b/README.mdindex 1b07b9f..853159c 100644--- a/README.md+++ b/README.md@@ -16,7 +16,7 @@**English** | [简体中文](README.zh-CN.md) | [日本語](README.ja.md)-[🎧 Listen to samples](https://kanaworksai-hue.github.io/audio-studio-mcp/) · [Quick start](#-quick-start) · [Tools](#-tools) · [FAQ](#-faq) · [⭐ Star](#-like-it-star-it)+[🎧 Listen to samples](https://kanaworksai-hue.github.io/audio-studio-mcp/) · [Quick start](#-quick-start) · [Tools](#-tools) · [Web UI](#-web-ui) · [FAQ](#-faq) · [⭐ Star](#-like-it-star-it)</div>@@ -178,6 +178,28 @@ Then just ask:Generated files are 44.1 kHz 24-bit stereo WAV, written to `outputs/` in this folder. Each one has a `<name>.json` next to it. Processed files keep the original generation info under `source`.</details>+## 🌐 Web UI++Prefer clicking to chatting? The same server comes with a local web page. Generate BGM and sound effects, compare the candidates, edit them (make a variation, replace a part, extend), export them for your game or video, and browse everything you've made in the library.++```bash+.venv/bin/audio-studio-mcp --web 8765+```++Your browser opens http://127.0.0.1:8765/. Add `--no-browser` to start without opening it, or `--preload` to load the model at startup. Press Ctrl+C to stop it. On Windows: `.venv\Scripts\audio-studio-mcp.exe --web 8765`.++The page and your MCP clients can share one process and one loaded model: the same port also serves MCP at `/mcp`. Register it once and use both at the same time. Requests from the page and from agents wait in one queue.++```bash+claude mcp add --scope user --transport http audio-studio http://127.0.0.1:8765/mcp+```++- Files are written to the output folder (`outputs/`, or `AUDIO_STUDIO_OUTPUT_DIR`). The library shows that folder, and the editor works on the files in it.+- The page is in English, Japanese and Chinese and follows your browser's language. You can change it in the settings.++> [!WARNING]+> The web UI is for your own computer only. It listens on `127.0.0.1` only and has no login. Don't make it reachable from other machines (port forwarding, a reverse proxy or a tunnel): anyone who can open it can use your GPU and write files to your output folder.+## ⚙️ Configuration<details>@@ -208,6 +230,8 @@ claude mcp add --scope user --transport http audio-studio http://127.0.0.1:8765/```On Windows, start it with `.venv\Scripts\audio-studio-mcp.exe --http 8765 --preload`.++`--web 8765` does the same and adds the [web UI](#-web-ui) on the same port.</details>## ⚡ Performance@@ -297,6 +321,7 @@ Use WAV or OGG for loops. MP3 adds padding at the start and end, so it can't loo- [x] Apple Silicon backend (Stable Audio 3, MLX)- [x] Windows backend for NVIDIA GPUs (Stable Audio 3, PyTorch)+- [x] Local web UI (`--web`)- [ ] LoRA support (the upstream runtime already has it)Issues and pull requests are welcome.@@ -327,6 +352,8 @@ src/audio_studio_mcp/backends/base.py backend interfacebackends/sa3_mlx.py Stable Audio 3 on Apple Silicon (MLX)backends/sa3_torch.py Stable Audio 3 on NVIDIA GPUs (PyTorch)+ web.py web UI server (--web) and its JSON API+ static/ web UI (HTML/JS/CSS, no build step)```A new platform is added as another backend in `backends/`.@@ -337,6 +364,7 @@ A new platform is added as another backend in `backends/`.- **Stable Audio 3 runtime:** downloaded into `vendor/` at install time. It is © Stability AI and MIT-licensed.- **Model weights:** licensed under the [Stability AI Community License](https://huggingface.co/stabilityai/stable-audio-3-optimized). They are downloaded from Hugging Face (macOS: `stable-audio-3-optimized`; Windows: `stable-audio-3-medium` and the small models), not distributed here.- **Brand:** the KanaWorks_AI name, logo and the Kana character are © 東京AI映像合同会社 (Tokyo AI Visuals LLC) and are **not** covered by the MIT license. See [docs/brand](docs/brand/README.md).+- **Fonts:** the web UI ships IBM Plex Sans, © IBM Corp., under the SIL Open Font License 1.1 ([`OFL.txt`](src/audio_studio_mcp/static/fonts/OFL.txt)). The Kana images in the web UI ([`static/brand`](src/audio_studio_mcp/static/brand/README.md)) are covered by the Brand note above.- **Built on:** [Stable Audio 3](https://github.com/Stability-AI/stable-audio-3), [MLX](https://github.com/ml-explore/mlx), [PyTorch](https://pytorch.org) and the [Model Context Protocol](https://modelcontextprotocol.io).This is an independent project. It is not affiliated with or endorsed by Stability AI, Apple, NVIDIA or Anthropic.diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 9c0394f..417fe7f 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -16,7 +16,7 @@[English](README.md) | **简体中文** | [日本語](README.ja.md)-[🎧 试听样例](https://kanaworksai-hue.github.io/audio-studio-mcp/) · [快速开始](#-快速开始) · [工具](#-工具) · [常见问题](#-常见问题) · [⭐ 点个 Star](#-点个-star-支持一下)+[🎧 试听样例](https://kanaworksai-hue.github.io/audio-studio-mcp/) · [快速开始](#-快速开始) · [工具](#-工具) · [Web UI](#-web-ui) · [常见问题](#-常见问题) · [⭐ 点个 Star](#-点个-star-支持一下)</div>@@ -185,6 +185,28 @@ macOS 上下载不需要登录,用 `hf auth login` 登录后 Hugging Face 的生成的文件是 44.1 kHz 24-bit 立体声 WAV,写到本目录的 `outputs/`,旁边各有一个 `<文件名>.json`。处理后的文件会在 `source` 里保留原始生成信息。</details>+## 🌐 Web UI++比起聊天更想直接点按钮?同一个服务器还自带一个本地网页:生成 BGM 和音效、对比候选、编辑(生成变体、替换其中一段、延长)、导出给游戏或视频使用,还能在作品库里浏览做过的所有声音。++```bash+.venv/bin/audio-studio-mcp --web 8765+```++浏览器会打开 http://127.0.0.1:8765/。加 `--no-browser` 可以只启动不打开浏览器,加 `--preload` 会在启动时加载模型。按 Ctrl+C 停止。Windows 上用 `.venv\Scripts\audio-studio-mcp.exe --web 8765` 启动。++同一个端口的 `/mcp` 也提供 MCP 服务,所以网页和 MCP 客户端可以共用一个进程和已加载的模型。注册一次就能同时使用两者,网页和 agent 的请求在同一个队列里依次处理。++```bash+claude mcp add --scope user --transport http audio-studio http://127.0.0.1:8765/mcp+```++- 文件写入输出目录(`outputs/`,或 `AUDIO_STUDIO_OUTPUT_DIR`)。作品库显示的就是这个目录,编辑的也是其中的文件。+- 界面支持英文、日文和中文,默认跟随浏览器语言,也可以在设置里切换。++> [!WARNING]+> Web UI 只适合在自己的电脑上使用:它只监听 `127.0.0.1`,没有登录验证。不要通过端口转发、反向代理或隧道让其他机器访问它,否则任何能打开页面的人都能使用你的 GPU,并向你的输出目录写入文件。+## ⚙️ 配置<details>@@ -215,6 +237,8 @@ claude mcp add --scope user --transport http audio-studio http://127.0.0.1:8765/```Windows 上用 `.venv\Scripts\audio-studio-mcp.exe --http 8765 --preload` 启动。++`--web 8765` 的效果相同,并在同一端口提供 [Web UI](#-web-ui)。</details>## ⚡ 性能@@ -304,6 +328,7 @@ Windows + RTX 3060 12 GB,medium 模型:- [x] Apple Silicon 后端(Stable Audio 3、MLX)- [x] 面向 NVIDIA 显卡的 Windows 后端(Stable Audio 3、PyTorch)+- [x] 本地 Web UI(`--web`)- [ ] LoRA 支持(上游运行时已经支持)欢迎提 Issue 和 Pull Request。@@ -334,6 +359,8 @@ src/audio_studio_mcp/backends/base.py 后端接口backends/sa3_mlx.py Apple Silicon 上的 Stable Audio 3(MLX)backends/sa3_torch.py NVIDIA 显卡上的 Stable Audio 3(PyTorch)+ web.py Web UI 服务(--web)及其 JSON API+ static/ Web UI(HTML/JS/CSS,无需构建)```新平台以新后端的形式加到 `backends/` 里。@@ -344,6 +371,7 @@ src/audio_studio_mcp/- **Stable Audio 3 运行时:** 安装时下载到 `vendor/`,© Stability AI,MIT 协议。- **模型权重:** 适用 [Stability AI Community License](https://huggingface.co/stabilityai/stable-audio-3-optimized)。权重从 Hugging Face 下载(macOS:`stable-audio-3-optimized`;Windows:`stable-audio-3-medium` 及小模型),本项目不分发。- **品牌:** KanaWorks_AI 名称、logo 和 Kana 形象版权归东京AI映像合同会社所有,**不在** MIT 授权范围内。详见 [docs/brand](docs/brand/README.md)。+- **字体:** Web UI 附带 IBM Plex Sans 字体,© IBM Corp.,采用 SIL Open Font License 1.1([`OFL.txt`](src/audio_studio_mcp/static/fonts/OFL.txt))。Web UI 中的 Kana 图片([`static/brand`](src/audio_studio_mcp/static/brand/README.md))适用上面“品牌”一条。- **基于:** [Stable Audio 3](https://github.com/Stability-AI/stable-audio-3)、[MLX](https://github.com/ml-explore/mlx)、[PyTorch](https://pytorch.org) 和 [Model Context Protocol](https://modelcontextprotocol.io)。本项目是独立项目,与 Stability AI、Apple、NVIDIA、Anthropic 都没有关联,也未获其背书。diff --git a/install.ps1 b/install.ps1index 2c2e30f..23f2169 100644--- a/install.ps1+++ b/install.ps1@@ -141,6 +141,20 @@ Step "Installing Python dependencies into .venv (PyTorch + CUDA, ~3 GB)"Push-Location $RepoDirtry { uv sync --extra cuda; Check "uv sync" } finally { Pop-Location }$Py = Join-Path $RepoDir ".venv\Scripts\python.exe"+# uv writes the path of src\ into an editable-install .pth file as UTF-8, but+# Python 3.11 reads .pth files in the Windows code page (cp932 on Japanese+# Windows), so a folder name with Japanese characters stops Python from+# starting. A path relative to site-packages is plain ASCII and always works.+$Site = Join-Path $RepoDir ".venv\Lib\site-packages"+Get-ChildItem -LiteralPath $Site -Filter "_editable_impl_audio_studio_mcp*.pth" -ErrorAction SilentlyContinue | ForEach-Object {+ $line = [IO.File]::ReadAllText($_.FullName, [Text.Encoding]::UTF8).Trim()+ if ($line -match '[^\x00-\x7F]') { [IO.File]::WriteAllText($_.FullName, "..\..\..\src`r`n", [Text.Encoding]::ASCII) }+}+& $Py -c "import audio_studio_mcp" 2>$null+if ($LASTEXITCODE -ne 0) {+ & $Py -c "import audio_studio_mcp"+ Die "the Python in .venv cannot start or cannot import audio_studio_mcp (see the error above). If the folder path ($RepoDir) has non-English characters, try a folder such as C:\audio-studio-mcp."+}$cuda = (& $Py -c "import torch; print(torch.cuda.get_device_name(0) if torch.cuda.is_available() else '')" 2>$null) -join ""if ($cuda) { Ok ".venv ready (CUDA: $cuda)" } else { Ok ".venv ready"; Warn "PyTorch cannot see a CUDA GPU; generation will run on the CPU." }@@ -221,4 +235,5 @@ Write-Host ""Write-Host " claude mcp add --scope user audio-studio $EnvArg-- `"$Bin`""Write-Host ""Write-Host "Other MCP clients (Claude Desktop, Cursor, ...): command = $Bin"+Write-Host "Web UI: & `"$Bin`" --web 8765 (opens http://127.0.0.1:8765/ in your browser)"Write-Host "Test it: & `"$Py`" `"$(Join-Path $RepoDir 'scripts\smoke_test.py')`""diff --git a/install.sh b/install.shindex d815be1..3898ad3 100755--- a/install.sh+++ b/install.sh@@ -168,3 +168,4 @@ printf '\n%s%s✓ Installed.%s Register it with Claude Code:\n\n' "$B" "$G" "$N"printf ' claude mcp add --scope user audio-studio %s-- "%s"\n\n' "$ENV_ARG" "$BIN"printf 'Other MCP clients (Claude Desktop, Cursor, …): command = %s\n' "$BIN"printf 'Test it: "%s/.venv/bin/python" "%s/scripts/smoke_test.py"\n' "$REPO_DIR" "$REPO_DIR"+printf 'Web UI: "%s" --web 8765 (opens http://127.0.0.1:8765/ in your browser)\n' "$BIN"diff --git a/src/audio_studio_mcp/server.py b/src/audio_studio_mcp/server.pyindex f93ad12..62361e4 100644--- a/src/audio_studio_mcp/server.py+++ b/src/audio_studio_mcp/server.py@@ -67,30 +67,43 @@ def _slug(text: str, n: int = 48) -> str:return re.sub(r"[^\w\-]+", "_", text)[:n].strip("_")-def _out_path(stem: str, ext: str = ".wav", tail: str = "") -> Path:- """Reserve a new file name in OUTPUT_DIR (stem.ext, stem_2.ext, …).-- `tail` (ASCII: _seed, _inpaint, _v2, …) is never cut when a long stem is- shortened. The empty file is created atomically, so parallel tool calls and- other server processes sharing the folder never pick the same name."""+def _out_paths(stem: str, ext: str = ".wav", tail: str = "", count: int = 1) -> list[Path]:+ """Reserve `count` new file names in OUTPUT_DIR: stem+tail, or stem+tail_v1 …+ _vN for several candidates. When one is taken the whole set moves on to+ stem+tail_2(_vN), so the candidates of one call keep one name.++ `tail` (ASCII: _seed, _inpaint, …) and the input's own trailing numbers+ (_v2, _3, a seed) are never cut when a long stem is shortened. The empty+ files are created atomically, so parallel tool calls and other 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- suffix += tail+ # _N_vN.ext.json under the 255-byte file name limit (and Windows paths)+ base, keep = re.fullmatch(r"(.*?)((?:_v?\d{1,12}){0,3})", stem).groups()+ suffix = keep + tailbase = base.encode()[:MAX_STEM_BYTES - len(suffix)].decode(errors="ignore").strip("_") or "audio"stem = base + suffix+ variants = [f"_v{i}" for i in range(1, count + 1)] if count > 1 else [""]n = 1while True:- path = OUTPUT_DIR / (f"{stem}{ext}" if n == 1 else f"{stem}_{n}{ext}")+ paths = [OUTPUT_DIR / f"{stem}{'' if n == 1 else f'_{n}'}{v}{ext}" for v in variants]+ made = []try:- os.close(os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644))- return path+ for path in paths:+ os.close(os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644))+ made.append(path)+ return pathsexcept FileExistsError:+ for path in made:+ path.unlink(missing_ok=True)n += 1+def _out_path(stem: str, ext: str = ".wav", tail: str = "") -> Path:+ return _out_paths(stem, ext, tail)[0]++def _auto_stem(title: str | None, prompt: str, seed: int) -> tuple[str, str]:"""(stem, tail) for _out_path: the seed stays in the name when it is cut."""if title:@@ -242,8 +255,8 @@ async def generate_audio("cfg": cfg, "steps": steps, "variations": variations}stem, tail = _auto_stem(title, text, seeds[0])candidates = []- for i, (sd, audio) in enumerate(zip(seeds, res.audios)):- path = _out_path(stem, tail=tail if variations == 1 else f"{tail}_v{i + 1}")+ paths = _out_paths(stem, tail=tail, count=variations)+ for i, (sd, audio, path) in enumerate(zip(seeds, res.audios, paths)):candidates.append(_save_generated(backend, audio, path, peak_ceiling_db,{**meta, "seed": sd, "candidate": i + 1}))return {**_summary(backend, text, seconds, variations, res.wall_seconds,@@ -320,8 +333,8 @@ async def edit_audio("input_audio": str(src), "source": _load_sidecar(src), **extra}stem, tail = (_slug(title, 80), "") if title else (src.stem, f"_{mode}")candidates = []- for i, (sd, audio) in enumerate(zip(seeds, res.audios)):- path = _out_path(stem, tail=tail if variations == 1 else f"{tail}_v{i + 1}")+ paths = _out_paths(stem, tail=tail, count=variations)+ for i, (sd, audio, path) in enumerate(zip(seeds, res.audios, paths)):candidates.append(_save_generated(backend, audio, path, peak_ceiling_db,{**meta, "seed": sd, "candidate": i + 1}))return {**_summary(backend, text, seconds, variations, res.wall_seconds,diff --git a/src/audio_studio_mcp/web.py b/src/audio_studio_mcp/web.pyindex 8ebc32f..012aedd 100644--- a/src/audio_studio_mcp/web.py+++ b/src/audio_studio_mcp/web.py@@ -583,8 +583,27 @@ async def api_peaks(request: Request) -> Response:return _err(422, f"cannot read audio: {e}")+# Fixed types for the page's own files. mimetypes reads the Windows registry,+# where some programs set .js to text/plain; with nosniff the browser would+# then refuse to run the scripts.+STATIC_TYPES = {".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8",+ ".css": "text/css; charset=utf-8", ".woff2": "font/woff2", ".png": "image/png",+ ".md": "text/markdown; charset=utf-8", ".txt": "text/plain; charset=utf-8"}+++class _StaticFiles(StaticFiles):+ def file_response(self, full_path, stat_result, scope, status_code=200):+ response = super().file_response(full_path, stat_result, scope, status_code)+ media_type = STATIC_TYPES.get(Path(full_path).suffix.lower())+ if media_type:+ response.media_type = media_type+ response.headers["content-type"] = media_type+ return response++async def index(_: Request) -> Response:- return FileResponse(STATIC_DIR / "index.html", headers={"Cache-Control": "no-cache"})+ return FileResponse(STATIC_DIR / "index.html", media_type=STATIC_TYPES[".html"],+ headers={"Cache-Control": "no-cache"})API_ROUTES = [@@ -609,7 +628,7 @@ def create_app(port: int | None = None) -> Starlette:app.router.routes.extend([*API_ROUTES,Route("/", index, methods=["GET"]),- Mount("/static", StaticFiles(directory=STATIC_DIR), name="static"),+ Mount("/static", _StaticFiles(directory=STATIC_DIR), name="static"),])app.add_middleware(LocalOnly, port=port)return appdiff --git a/tests/test_server.py b/tests/test_server.pyindex da0bce4..7909d08 100644--- a/tests/test_server.py+++ b/tests/test_server.py@@ -260,3 +260,22 @@ def _umask() -> int:m = os.umask(0)os.umask(m)return m+++def test_candidates_of_one_call_share_a_name(fake):+ """Same title twice: X_v1, X_v2 then X_2_v1, X_2_v2 (not X_v1_2)."""+ first = server._out_paths("same", count=2)+ second = server._out_paths("same", count=2)+ assert [p.stem for p in first] == ["same_v1", "same_v2"]+ assert [p.stem for p in second] == ["same_2_v1", "same_2_v2"]+ (server.OUTPUT_DIR / "solo_v2.wav").touch() # one of the set is taken: the set moves on+ assert [p.stem for p in server._out_paths("solo", count=2)] == ["solo_2_v1", "solo_2_v2"]+ assert not (server.OUTPUT_DIR / "solo_v1.wav").exists()+++def test_cut_names_keep_the_inputs_counter(fake):+ """Exports of A and A_2 with long names stay apart (the _2 is not cut)."""+ long = "あ" * 100+ a = server._out_path(long, ".ogg", "_proc")+ b = server._out_path(long + "_2", ".ogg", "_proc")+ assert b.stem.endswith("_2_proc") and a.stem != b.stem and not b.stem.endswith("_proc_2")diff --git a/tests/test_web.py b/tests/test_web.pyindex 5a9c2be..04677de 100644--- a/tests/test_web.py+++ b/tests/test_web.py@@ -608,7 +608,29 @@ def test_input_checked_again_when_the_job_starts(client, fake, tmp_path):r = client.post("/api/jobs", json={"tool": "process_audio", "arguments": {"input_audio": "swap.wav"}})assert r.status_code == 202 # passed the submit checksrc.unlink()- src.symlink_to(outside)+ try:+ src.symlink_to(outside)+ except OSError: # Windows without developer mode or admin rights+ gate.set()+ pytest.skip("symlinks not available")gate.set()j = wait_job(client, r.json()["id"])assert j["status"] == "error" and "output folder" in j["error"]+++def test_static_types_do_not_depend_on_the_system(client):+ """Windows can map .js to text/plain in the registry; with nosniff the+ browser would refuse the scripts."""+ import mimetypes+ before = {ext: mimetypes.guess_type("x" + ext)[0] for ext in (".js", ".css", ".html")}+ for ext in before:+ mimetypes.add_type("text/plain", ext) # what such a registry gives+ try:+ for f, t in (("app.js", "text/javascript"), ("app.css", "text/css"),+ ("fonts/ibm-plex-sans-latin.woff2", "font/woff2"), ("brand/kana.png", "image/png")):+ r = client.get(f"/static/{f}")+ assert r.status_code == 200 and r.headers["content-type"].startswith(t), (f, r.headers["content-type"])+ assert client.get("/").headers["content-type"].startswith("text/html")+ finally:+ for ext, t in before.items():+ mimetypes.add_type(t, ext)