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.

Web UI: fixes from the pre-release QA (GAME-240)

Kana05de8c1c7613
diff --git a/src/audio_studio_mcp/server.py b/src/audio_studio_mcp/server.py
index 107cb25..f93ad12 100644
--- a/src/audio_studio_mcp/server.py
+++ b/src/audio_studio_mcp/server.py
@@ -67,32 +67,35 @@ def _slug(text: str, n: int = 48) -> str:
return re.sub(r"[^\w\-]+", "_", text)[:n].strip("_")
-def _out_path(stem: str, ext: str = ".wav") -> Path:
+def _out_path(stem: str, ext: str = ".wav", tail: str = "") -> Path:
"""Reserve a new file name in OUTPUT_DIR (stem.ext, stem_2.ext, …).
- The empty file is created atomically, so parallel tool calls and other
- server processes sharing the folder never pick the same name."""
+ `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."""
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
base = base.encode()[:MAX_STEM_BYTES - len(suffix)].decode(errors="ignore").strip("_") or "audio"
stem = base + suffix
n = 1
while True:
path = OUTPUT_DIR / (f"{stem}{ext}" if n == 1 else f"{stem}_{n}{ext}")
try:
- os.close(os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY))
+ os.close(os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644))
return path
except FileExistsError:
n += 1
-def _auto_stem(title: str | None, prompt: str, seed: int) -> str:
+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:
- return _slug(title, 80)
- return f"{datetime.now():%Y%m%d-%H%M%S}_{_slug(strip_prefix(prompt)) or 'audio'}_{seed}"
+ return _slug(title, 80), ""
+ return f"{datetime.now():%Y%m%d-%H%M%S}_{_slug(strip_prefix(prompt)) or 'audio'}", f"_{seed}"
def _input_path(p: str) -> Path:
@@ -237,10 +240,10 @@ async def generate_audio(
"sound_fields": dict(zip(("source", "action", "material", "space"), sfx_fields)),
"bpm": bpm, "seconds": seconds, "negative_prompt": negative_prompt,
"cfg": cfg, "steps": steps, "variations": variations}
- stem = _auto_stem(title, text, seeds[0])
+ stem, tail = _auto_stem(title, text, seeds[0])
candidates = []
for i, (sd, audio) in enumerate(zip(seeds, res.audios)):
- path = _out_path(stem if variations == 1 else f"{stem}_v{i + 1}")
+ path = _out_path(stem, tail=tail if variations == 1 else f"{tail}_v{i + 1}")
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,
@@ -315,10 +318,10 @@ async def edit_audio(
"bpm": bpm, "seconds": seconds, "negative_prompt": negative_prompt,
"cfg": cfg, "steps": steps, "variations": variations,
"input_audio": str(src), "source": _load_sidecar(src), **extra}
- stem = _slug(title, 80) if title else f"{src.stem}_{mode}"
+ 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 if variations == 1 else f"{stem}_v{i + 1}")
+ path = _out_path(stem, tail=tail if variations == 1 else f"{tail}_v{i + 1}")
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,
@@ -384,7 +387,7 @@ async def process_audio(
steps_done.append(f"peak ceiling {peak_ceiling_db} dBFS ({gain:+.2f} dB)")
ext = {"wav": ".wav", "ogg": ".ogg", "flac": ".flac"}[format]
- path = _out_path(_slug(title, 80) if title else f"{src.stem}_proc", ext)
+ path = _out_path(_slug(title, 80), ext) if title else _out_path(src.stem, ext, "_proc")
post.write(path, audio, sr, format, ogg_quality)
st = post.stats(audio)
result = {"path": str(path), "format": format, "sample_rate": sr,
diff --git a/src/audio_studio_mcp/static/app.js b/src/audio_studio_mcp/static/app.js
index b51b1e0..d0f4abf 100644
--- a/src/audio_studio_mcp/static/app.js
+++ b/src/audio_studio_mcp/static/app.js
@@ -89,6 +89,13 @@ function el(tag, attrs = {}, ...children) {
for (const c of children.flat()) if (c != null) n.append(c);
return n;
}
+// replaceChildren that keeps keyboard focus on the same position (chips and
+// radios are rebuilt on every change and status refresh)
+function replaceKeepFocus(box, ...children) {
+ const i = [...box.querySelectorAll("button, input")].indexOf(document.activeElement);
+ box.replaceChildren(...children);
+ if (i >= 0) { const n = box.querySelectorAll("button, input")[i]; if (n) n.focus({ preventScroll: true }); }
+}
function fmtTime(sec) {
sec = Math.max(0, Math.round(sec || 0));
const m = Math.floor(sec / 60), s = sec % 60;
@@ -280,7 +287,7 @@ function updateDurationUI() {
$("#duration-hint").textContent = t("gen.durationHint", { def: d ?? "—", max });
const empty = input.value.trim() === "", cur = Number(input.value), auto = empty || cur === d;
input.title = t("gen.durationHint", { def: d ?? "—", max });
- $("#durations").replaceChildren(
+ replaceKeepFocus($("#durations"),
el("button", { type: "button", class: "chip", "aria-pressed": String(auto), text: t("gen.durationAuto", { def: d ?? "—" }),
onclick: () => { input.value = ""; updateDurationUI(); } }),
...DURATIONS[type].filter((s) => s <= max && s !== d).map((s) =>
@@ -367,6 +374,8 @@ function clearErrors(f = form(), box = $("#form-error")) {
}
// Show an API error next to the form; mark the fields it names.
function showFormError(msg, fields, f = form(), box = $("#form-error"), adv = $("#advanced")) {
+ // the server's field messages are English; lead with a translated sentence
+ if (fields && fields.length) msg = `${t("err.invalidFields")} (${fields.map((fe) => `${fe.field}: ${fe.message}`).join("; ")})`;
box.textContent = msg; box.hidden = false;
for (const fe of fields || []) {
const input = f.elements.namedItem(fe.field);
@@ -492,7 +501,7 @@ function jobBadge(job) {
}
const LETTERS = "ABCD";
function candidateCard(c, i, job) {
- const file = baseName(c.path), mini = new MiniWave(file, c.seconds, Math.round(job.finished || 0));
+ const file = baseName(c.path), mini = new MiniWave(file, c.seconds ?? job.result.seconds, Math.round(job.finished || 0));
const many = job.result.candidates.length > 1 || job.tool === "edit_audio";
const exported = job.tool === "process_audio";
return el("div", { class: "cand", dataset: { index: i } },
@@ -661,7 +670,8 @@ async function pollJobs() {
let finished = false;
try {
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(",")}`);
+ const asked = new Set(waiting.map((j) => j.id));
+ const r = await api(`/api/jobs?ids=${[...asked].join(",")}`);
state.loaded = r.loaded;
const seen = new Set();
for (const j of r.items) {
@@ -674,9 +684,10 @@ async function pollJobs() {
if (prev || j.status === "queued" || j.status === "running") state.jobs.set(j.id, j);
seen.add(j.id);
}
- // The server restarted and forgot these: stop waiting for them.
+ // The server restarted and forgot these: stop waiting for them. Only jobs
+ // this request asked about (one queued meanwhile is not in the answer).
for (const j of state.jobs.values()) {
- if (!seen.has(j.id) && (j.status === "queued" || j.status === "running")) {
+ if (asked.has(j.id) && !seen.has(j.id) && (j.status === "queued" || j.status === "running")) {
state.jobs.set(j.id, { ...j, status: "error", position: null, error: t("jobs.lost") });
}
}
@@ -815,7 +826,7 @@ async function loadLibrary(reset) {
// Type filter chips above the library list.
const LIB_KINDS = ["", "music", "instrument", "sfx", "edit", "process"];
function renderKinds() {
- $("#lib-kinds").replaceChildren(...LIB_KINDS.map((k) => el("button", { type: "button", class: "chip",
+ replaceKeepFocus($("#lib-kinds"), ...LIB_KINDS.map((k) => el("button", { type: "button", class: "chip",
"aria-pressed": String(state.lib.kind === k), text: t(`lib.kind.${k || "all"}`),
onclick: () => { state.lib.kind = k; renderKinds(); loadLibrary(true); } })));
}
diff --git a/src/audio_studio_mcp/static/editor.js b/src/audio_studio_mcp/static/editor.js
index 15fecf8..4eaf768 100644
--- a/src/audio_studio_mcp/static/editor.js
+++ b/src/audio_studio_mcp/static/editor.js
@@ -120,7 +120,7 @@ const Editor = {
if (seq !== this.openSeq) return;
this.file = null;
this.audio.removeAttribute("src");
- toast(e.status === 404 ? t("edit.notFound", { file }) : e.message);
+ toast(e.status === 404 ? t("edit.notFound", { file }) : e.status === 422 ? t("edit.unreadable", { file }) : e.message);
this.showEmpty();
if (location.hash.startsWith("#edit/")) history.replaceState(null, "", "#edit");
return;
@@ -596,7 +596,7 @@ const Editor = {
const target = parseFloat(dur.value);
$("#extend-hint").textContent = t("edit.extendHint", { now: this.fmt(this.seconds), max: this.max() });
const adds = [5, 10, 30, 60].filter((d) => this.seconds + d <= this.max());
- $("#extend-chips").replaceChildren(...adds.map((d) => el("button", { type: "button", class: "chip",
+ replaceKeepFocus($("#extend-chips"), ...adds.map((d) => el("button", { type: "button", class: "chip",
"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
@@ -669,7 +669,7 @@ const Editor = {
const box = $("#presets");
if (!box) return;
const cur = this.preset || "original";
- box.replaceChildren(...PRESET_ORDER.map((p) => el("label", { class: `preset${p === cur ? " checked" : ""}` },
+ replaceKeepFocus(box, ...PRESET_ORDER.map((p) => el("label", { class: `preset${p === cur ? " checked" : ""}` },
el("input", { type: "radio", name: "preset", value: p, checked: p === cur }),
el("span", { class: "preset-name", text: t(`preset.${p}`) }))));
$("#preset-desc").textContent = t(`preset.${cur}Desc`);
diff --git a/src/audio_studio_mcp/static/i18n.js b/src/audio_studio_mcp/static/i18n.js
index 21d9e04..762d913 100644
--- a/src/audio_studio_mcp/static/i18n.js
+++ b/src/audio_studio_mcp/static/i18n.js
@@ -72,12 +72,14 @@ window.I18N = {
"kind.generate": "Generated", "kind.edit": "Edit", "kind.process": "Export",
"err.network": "Cannot reach the server. Is audio-studio-mcp --web still running?",
"err.emptyPrompt": "Describe the sound first (or click an example).",
+ "err.invalidFields": "Check the highlighted fields.",
"player.play": "Play", "player.pause": "Pause", "player.position": "Playback position",
"edit.emptyTitle": "Open a sound to edit it",
"edit.emptyHint": "Click “Edit” on a result or in the library. You can make variations, replace a part, extend it, or export it for a game or video.",
"edit.browse": "Browse the library", "edit.recent": "Recent sounds", "edit.notFound": "{file} is not in the output folder.",
+ "edit.unreadable": "{file} can't be read as audio (damaged or unsupported).",
"edit.mono": "mono", "edit.stereo": "stereo", "edit.madeFrom": "Made from",
"edit.aiTab": "Change with AI", "edit.exportTab": "Export", "edit.mode": "What to do",
"mode.variation": "Make a variation", "mode.variationDesc": "Same idea, new take on the whole sound",
@@ -157,7 +159,7 @@ window.I18N = {
"settings.language": "言語", "settings.auto": "自動",
"gen.title": "新しい音", "gen.type": "何を作りますか?",
- "type.music": "音楽", "type.instrument": "楽器ソロ/ループ", "type.sfx": "効果音", "type.raw": "Raw",
+ "type.music": "音楽", "type.instrument": "楽器ソロ/ループ", "type.sfx": "効果音", "type.raw": "指定なし",
"type.musicHint": "BGM:複数の楽器による 1 曲。",
"type.instrumentHint": "単一の楽器や短いループ(ドラムビート、ギターのフレーズなど)。",
"type.sfxHint": "足音、衝撃音、UI 音、環境音など。",
@@ -218,12 +220,14 @@ window.I18N = {
"kind.generate": "生成", "kind.edit": "編集", "kind.process": "書き出し",
"err.network": "サーバーに接続できません。audio-studio-mcp --web が起動しているか確認してください。",
"err.emptyPrompt": "まず音の説明を入力してください(例をクリックしても OK)。",
+ "err.invalidFields": "印の付いた項目を確認してください。",
"player.play": "再生", "player.pause": "一時停止", "player.position": "再生位置",
"edit.emptyTitle": "編集する音を開いてください",
"edit.emptyHint": "結果やライブラリの「編集」をクリックします。バリエーション作成、一部の差し替え、延長、ゲームや動画向けの書き出しができます。",
"edit.browse": "ライブラリを見る", "edit.recent": "最近の音", "edit.notFound": "{file} は出力フォルダにありません。",
+ "edit.unreadable": "{file} を音声として読み込めません(壊れているか未対応の形式です)。",
"edit.mono": "モノラル", "edit.stereo": "ステレオ", "edit.madeFrom": "元の音:",
"edit.aiTab": "AI で変える", "edit.exportTab": "書き出し", "edit.mode": "操作",
"mode.variation": "バリエーション", "mode.variationDesc": "同じアイデアで全体を作り直す",
@@ -303,7 +307,7 @@ window.I18N = {
"settings.language": "语言", "settings.auto": "自动",
"gen.title": "新建声音", "gen.type": "想做什么?",
- "type.music": "音乐", "type.instrument": "单乐器 / 循环", "type.sfx": "音效", "type.raw": "Raw",
+ "type.music": "音乐", "type.instrument": "单乐器 / 循环", "type.sfx": "音效", "type.raw": "未指定",
"type.musicHint": "背景音乐:多种乐器组成的完整曲子。",
"type.instrumentHint": "单一乐器或短循环,例如鼓点、吉他乐句。",
"type.sfxHint": "脚步声、撞击声、UI 音、环境音等。",
@@ -364,12 +368,14 @@ window.I18N = {
"kind.generate": "生成", "kind.edit": "编辑", "kind.process": "导出",
"err.network": "无法连接服务器。请确认 audio-studio-mcp --web 仍在运行。",
"err.emptyPrompt": "请先描述声音(也可以点一个示例)。",
+ "err.invalidFields": "请检查标出的项目。",
"player.play": "播放", "player.pause": "暂停", "player.position": "播放位置",
"edit.emptyTitle": "打开一个声音来编辑",
"edit.emptyHint": "在结果或作品库中点击“编辑”。可以生成变体、替换其中一段、延长,或导出给游戏和视频使用。",
"edit.browse": "浏览作品库", "edit.recent": "最近的声音", "edit.notFound": "输出文件夹中没有 {file}。",
+ "edit.unreadable": "无法读取 {file}(文件已损坏或格式不支持)。",
"edit.mono": "单声道", "edit.stereo": "立体声", "edit.madeFrom": "来源:",
"edit.aiTab": "用 AI 修改", "edit.exportTab": "导出", "edit.mode": "操作",
"mode.variation": "生成变体", "mode.variationDesc": "同样的想法,整体重新演绎",
diff --git a/src/audio_studio_mcp/static/wave.js b/src/audio_studio_mcp/static/wave.js
index 6771a3e..e085208 100644
--- a/src/audio_studio_mcp/static/wave.js
+++ b/src/audio_studio_mcp/static/wave.js
@@ -11,7 +11,7 @@ const Peaks = {
if (!this.cache.has(key)) {
if (this.cache.size > 200) this.cache.clear();
const p = fetch(`/api/peaks/${encodeURIComponent(file)}?${q}`).then((r) => {
- if (!r.ok) throw new Error(`peaks ${r.status}`);
+ if (!r.ok) { const e = new Error(`peaks ${r.status}`); e.status = r.status; throw e; }
return r.json();
});
p.catch(() => this.cache.delete(key));
diff --git a/src/audio_studio_mcp/web.py b/src/audio_studio_mcp/web.py
index 370bbc4..8ebc32f 100644
--- a/src/audio_studio_mcp/web.py
+++ b/src/audio_studio_mcp/web.py
@@ -50,6 +50,7 @@ JOB_TOOLS = {"generate_audio", "edit_audio", "process_audio"}
INPUT_TOOLS = {"edit_audio", "process_audio"}
MAX_FINISHED_JOBS = 200
MAX_PEAKS = 20000
+MAX_BODY = 1 << 20 # bytes; a job request is a few hundred
# ── jobs ─────────────────────────────────────────────────────────────────────
@@ -154,6 +155,9 @@ class JobQueue:
continue
job.status, job.started = "running", time.time()
try:
+ if job.tool in INPUT_TOOLS and resolve_input(job.arguments.get("input_audio")) is None:
+ # checked at submit time; the file may have been replaced since
+ raise ValueError("input_audio must be an audio file in the output folder")
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
@@ -333,6 +337,9 @@ def _summary(path: Path) -> tuple:
import soundfile as sf
st = path.stat()
key = (str(path), st.st_mtime_ns, st.st_size)
+ hit = _summaries.get(key)
+ if hit is not None: # cached: don't wait behind another file being summarized
+ return hit
with _summary_lock:
hit = _summaries.pop(key, None)
if hit is None:
@@ -393,7 +400,8 @@ class LocalOnly:
LOOPBACK = ("127.0.0.1", "localhost", "::1")
FRAME_HEADERS = [(b"x-frame-options", b"DENY"),
- (b"content-security-policy", b"frame-ancestors 'none'")]
+ (b"content-security-policy", b"frame-ancestors 'none'"),
+ (b"x-content-type-options", b"nosniff")]
def __init__(self, app, port: int | None) -> None:
self.app, self.port = app, port
@@ -415,10 +423,10 @@ class LocalOnly:
if headers.get("sec-fetch-site", "same-origin") not in ("same-origin", "none"):
return "cross-site request refused"
if scope["method"] not in ("GET", "HEAD"):
- origin = headers.get("origin")
- if origin is None or not self._host_ok(origin.split("://", 1)[-1]):
+ origin = headers.get("origin", "")
+ if not origin.startswith("http://") or not self._host_ok(origin[len("http://"):]):
return "cross-origin request refused"
- if not headers.get("content-type", "").startswith("application/json"):
+ if headers.get("content-type", "").split(";")[0].strip().lower() != "application/json":
return "expected application/json"
return None
@@ -457,9 +465,14 @@ async def api_unload(_: Request) -> Response:
async def _json_body(request: Request) -> dict:
+ raw = b""
+ async for chunk in request.stream():
+ raw += chunk
+ if len(raw) > MAX_BODY:
+ raise ValueError("request body too large")
try:
- body = await request.json()
- except ValueError:
+ body = json.loads(raw)
+ except (ValueError, RecursionError):
raise ValueError("invalid JSON body")
if not isinstance(body, dict):
raise ValueError("JSON body must be an object")
@@ -472,7 +485,7 @@ async def api_jobs_create(request: Request) -> Response:
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:
+ if not isinstance(tool, str) or 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")
@@ -560,6 +573,8 @@ async def api_peaks(request: Request) -> Response:
end = 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 ValueError
+ # keep int(seconds * rate) finite (a week is longer than any file here)
+ start, end = (None if v is None else min(max(v, 0.0), 604800.0) for v in (start, end))
except ValueError:
return _err(400, "n/start/end must be finite numbers")
try:
diff --git a/tests/test_server.py b/tests/test_server.py
index 9985db0..738668a 100644
--- a/tests/test_server.py
+++ b/tests/test_server.py
@@ -240,3 +240,22 @@ def test_output_names_stay_short(fake):
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")
+
+
+def test_cut_names_keep_their_tail(fake):
+ """A long name loses its middle, not the seed / edit mode / candidate number."""
+ long = "あ" * 100
+ p = server._out_path(long, tail="_inpaint_v2")
+ assert p.stem.endswith("_inpaint_v2") and len(p.stem.encode()) <= server.MAX_STEM_BYTES
+ q = server._out_path(p.stem, ".ogg", "_proc") # edit of a cut name: v2 and the new step stay
+ assert q.stem.endswith("_v2_proc") and len(q.stem.encode()) <= server.MAX_STEM_BYTES
+ stem, tail = server._auto_stem(None, "冷たい" * 40, 6)
+ assert server._out_path(stem, tail=tail).stem.endswith("_6")
+ assert oct(p.stat().st_mode & 0o777) == oct(0o644 & ~_umask())
+
+
+def _umask() -> int:
+ import os
+ m = os.umask(0)
+ os.umask(m)
+ return m
diff --git a/tests/test_web.py b/tests/test_web.py
index 827bf9d..5a9c2be 100644
--- a/tests/test_web.py
+++ b/tests/test_web.py
@@ -562,3 +562,53 @@ def test_web_opens_browser_once_started(monkeypatch, capsys):
FakeServer.fail = True
web.serve(8123, open_browser=True)
assert opened == [] and "web UI" not in capsys.readouterr().out
+
+
+def test_bad_job_requests_are_400_not_500(client):
+ assert client.post("/api/jobs", json={"tool": ["x"]}).status_code == 400
+ deep = '{"a":' * 100000
+ r = client.post("/api/jobs", content=deep, headers={"Content-Type": "application/json"})
+ assert r.status_code == 400
+ big = '{"tool": "generate_audio", "arguments": {"prompt": "' + "x" * (web.MAX_BODY + 1) + '"}}'
+ r = client.post("/api/jobs", content=big, headers={"Content-Type": "application/json"})
+ assert r.status_code == 400 and "too large" in r.json()["error"]
+
+
+def test_header_checks_are_exact(client):
+ ok = client.post("/api/jobs", content="{}", headers={"Content-Type": "Application/JSON; charset=utf-8"})
+ assert ok.status_code != 403
+ for origin in ("https://127.0.0.1", "evil://127.0.0.1"):
+ assert client.post("/api/jobs", json={}, headers={"Origin": origin}).status_code == 403
+ r = client.post("/api/jobs", content="{}", headers={"Content-Type": "application/jsonx"})
+ assert r.status_code == 403
+ assert client.get("/api/status").headers["x-content-type-options"] == "nosniff"
+
+
+def test_peaks_with_a_huge_end(client, fake):
+ sf_path = server.OUTPUT_DIR / "tone.wav"
+ server.OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
+ import soundfile as sf
+ sf.write(sf_path, sine(1.0).T, 44100)
+ r = client.get("/api/peaks/tone.wav?n=10&start=0&end=1e308")
+ assert r.status_code == 200 and r.json()["end"] == pytest.approx(1.0, abs=0.01)
+
+
+def test_input_checked_again_when_the_job_starts(client, fake, tmp_path):
+ """A file swapped for a link out of the folder after queueing is refused."""
+ import soundfile as sf
+ server.OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
+ src = server.OUTPUT_DIR / "swap.wav"
+ sf.write(src, sine(1.0).T, 44100)
+ outside = tmp_path / "outside.wav"
+ sf.write(outside, sine(1.0).T, 44100)
+ gate = threading.Event()
+ orig = fake._generate
+ fake._generate = lambda seeds, req: (gate.wait(10), orig(seeds, req))[1]
+ client.post("/api/jobs", json={"arguments": {"prompt": "slow", "duration_seconds": 1}})
+ r = client.post("/api/jobs", json={"tool": "process_audio", "arguments": {"input_audio": "swap.wav"}})
+ assert r.status_code == 202 # passed the submit check
+ src.unlink()
+ src.symlink_to(outside)
+ gate.set()
+ j = wait_job(client, r.json()["id"])
+ assert j["status"] == "error" and "output folder" in j["error"]
diff --git a/tests/test_webui_browser.py b/tests/test_webui_browser.py
index 18c80f8..9e141e6 100644
--- a/tests/test_webui_browser.py
+++ b/tests/test_webui_browser.py
@@ -462,3 +462,40 @@ def test_manual_theme_and_language_switch(web, browser):
pad = page.evaluate("parseFloat(getComputedStyle(document.querySelector('#lang')).paddingRight)")
assert pad >= 24
assert not errors, errors
+
+
+def test_keyboard_focus_survives_rerenders(web, browser):
+ errors: list[str] = []
+ page = _page(browser, web, "en", "light", errors)
+ page.wait_for_selector("#durations .chip")
+ page.focus("#durations .chip:nth-child(2)")
+ page.evaluate("refreshStatus()") # the status refresh rebuilds the chips
+ page.wait_for_timeout(300)
+ assert page.evaluate("document.activeElement.matches('#durations .chip:nth-child(2)')")
+ page.keyboard.press("Enter") # its own click rebuilds them too
+ assert page.evaluate("document.activeElement.matches('#durations .chip:nth-child(2)')")
+ assert not errors, errors
+
+
+def test_jobs_queued_while_polling_are_not_lost(web, browser):
+ """A job added while a poll is in flight is not in that poll's answer."""
+ errors: list[str] = []
+ page = _page(browser, web, "en", "light", errors)
+ page.wait_for_function("state.status !== undefined && state.status !== null")
+ page.evaluate("""async () => {
+ // slow polls, so the jobs below are queued while one is in flight
+ const orig = window.fetch;
+ window.fetch = async (url, init) => {
+ if (String(url).includes("/api/jobs?ids=")) await new Promise((r) => setTimeout(r, 500));
+ return orig(url, init);
+ };
+ for (let i = 0; i < 5; i++) {
+ await queueJob("generate_audio", { prompt: `race ${i}`, duration_seconds: 1, seed: i });
+ await new Promise((r) => setTimeout(r, 300));
+ }
+ }""")
+ page.wait_for_function("[...state.jobs.values()].every((j) => j.status !== 'queued' && j.status !== 'running')",
+ timeout=30000)
+ statuses = page.evaluate("[...state.jobs.values()].filter((j) => (j.arguments.prompt || '').startsWith('race')).map((j) => j.status)")
+ assert statuses == ["done"] * 5, statuses
+ assert not errors, errors