browser audio detection phase 4

This commit is contained in:
Joren de Graaf
2026-10-02 21:45:24 +02:00
parent 20bdabdd8f
commit 037797aa89
20 changed files with 903 additions and 31 deletions
+84
View File
@@ -0,0 +1,84 @@
import assert from "node:assert/strict";
import test from "node:test";
import { JSDOM } from "jsdom";
function fixture() {
const dom = new JSDOM(`<!doctype html><html><body>
<script id="boomcast-browser-config" type="application/json">{"browserProcessingBeta":true,"policyUrl":"/policy","policyVersion":1}</script>
<form class="upload-form" action="/classify">
<label id="drop-zone"><input id="audio-file" name="audio" type="file" accept="audio/*,.wav" required><span id="upload-progress-circle"><span id="upload-icon-content"></span></span><span id="file-name"></span></label>
<input id="browser-processing-toggle" type="checkbox">
<button type="submit">Submit</button><button class="upload-cancel" type="button" hidden>Cancel</button>
<section id="browser-gate" hidden><strong id="browser-gate-title"></strong><p id="browser-gate-message"></p><button id="browser-gate-choose" type="button"></button><button id="browser-gate-override" type="button"></button></section>
<section id="classification-results"></section>
</form><p id="upload-status"></p></body></html>`, { url: "https://example.test/" });
const { window } = dom;
window.matchMedia = () => ({ matches: false });
window.BOOMCAST_I18N = {};
const requests = [];
class MockXHR {
upload = { addEventListener() {} };
addEventListener() {}
open() {}
send(data) { requests.push(data); }
}
const originals = Object.fromEntries(["window", "document", "FormData", "XMLHttpRequest", "DOMParser", "fetch"].map((name) => [name, globalThis[name]]));
Object.assign(globalThis, { window, document: window.document, FormData: window.FormData, XMLHttpRequest: MockXHR, DOMParser: window.DOMParser });
const form = window.document.querySelector("form");
form.reportValidity = () => true;
const input = window.document.querySelector("#audio-file");
const audio = new window.File(["audio"], "clip.wav", { type: "audio/wav" });
Object.defineProperty(input, "files", { configurable: true, value: [audio] });
const toggle = window.document.querySelector("#browser-processing-toggle");
return { window, form, input, audio, toggle, requests, restore: () => {
for (const [name, value] of Object.entries(originals)) {
if (value === undefined) delete globalThis[name];
else globalThis[name] = value;
}
dom.window.close();
} };
}
test("admin ON with user toggle OFF uploads the original audio without policy fetch", async () => {
const ui = fixture();
let fetches = 0;
globalThis.fetch = () => { fetches += 1; throw new Error("browser policy must not load"); };
try {
await import("../src/scripts/audio-upload.js?mode=server");
assert.equal(ui.toggle.checked, false);
ui.input.dispatchEvent(new ui.window.Event("change", { bubbles: true }));
assert.equal(ui.form.querySelector('button[type="submit"]').disabled, false);
ui.form.dispatchEvent(new ui.window.Event("submit", { bubbles: true, cancelable: true }));
assert.equal(fetches, 0);
assert.equal(ui.requests.length, 1);
assert.equal(ui.requests[0].get("audio").name, "clip.wav");
assert.equal(ui.requests[0].has("browser_processing_metadata"), false);
} finally { ui.restore(); }
});
test("switching browser mode off invalidates a policy job and restores server submission", async () => {
const ui = fixture();
let resolveFetch;
let fetches = 0;
globalThis.fetch = () => { fetches += 1; return new Promise((resolve) => { resolveFetch = resolve; }); };
try {
await import("../src/scripts/audio-upload.js?mode=switch");
ui.input.dispatchEvent(new ui.window.Event("change", { bubbles: true }));
ui.toggle.checked = true;
ui.toggle.dispatchEvent(new ui.window.Event("change", { bubbles: true }));
for (let i = 0; i < 30 && !resolveFetch; i += 1) await new Promise((resolve) => setTimeout(resolve, 5));
assert.equal(fetches, 1);
assert.equal(ui.form.querySelector('button[type="submit"]').disabled, true);
ui.toggle.checked = false;
ui.toggle.dispatchEvent(new ui.window.Event("change", { bubbles: true }));
resolveFetch({ ok: true, json: async () => ({ browser_processing_beta_enabled: true, version: 1 }) });
await new Promise((resolve) => setTimeout(resolve, 0));
assert.equal(ui.input.accept, "audio/*,.wav");
assert.equal(ui.form.querySelector('button[type="submit"]').disabled, false);
assert.equal(ui.window.document.querySelector("#browser-gate").hidden, true);
ui.form.dispatchEvent(new ui.window.Event("submit", { bubbles: true, cancelable: true }));
assert.equal(ui.requests.length, 1);
assert.equal(ui.requests[0].get("audio").name, "clip.wav");
assert.equal(ui.requests[0].has("browser_processing_metadata"), false);
} finally { ui.restore(); }
});
@@ -26,6 +26,7 @@ test("audio and video-derived WAV use the same gate; audio never calls FFmpeg",
async () => { extractionCalls += 1; return new File(["wav"], "clip.wav", { type: "audio/wav" }); },
{ prepareAudio: async () => new Float32Array(16000), classify: async () => { classificationCalls += 1; return [{ class: "Speech", score: .9 }]; } },
);
processor.setEnabled(true);
try {
assert.equal((await processor.prepare(new File(["audio"], "audio.wav", { type: "audio/wav" }))).gate, "speech_only");
assert.equal(extractionCalls, 0);
@@ -43,6 +44,7 @@ test("local classifier failure restores ordinary server upload", async () => {
{ prepareAudio: async () => new Float32Array(16000), classify: async () => { throw new Error("offline"); } },
);
const audio = new File(["audio"], "audio.wav", { type: "audio/wav" });
processor.setEnabled(true);
try {
const result = await processor.prepare(audio);
assert.equal(result.file, audio);
@@ -58,7 +60,40 @@ test("aborted classification never yields a gate decision", async () => {
{ browserProcessingBeta: true, policyUrl: "/policy", policyVersion: 1 }, null,
{ prepareAudio: async () => new Float32Array(16000), classify: async () => { controller.abort(); return [{ class: "Fireworks", score: .9 }]; } },
);
processor.setEnabled(true);
try {
await assert.rejects(processor.prepare(new File(["audio"], "audio.wav", { type: "audio/wav" }), { signal: controller.signal }));
} finally { globalThis.fetch = originalFetch; }
});
test("replacing a classification cancels the old result and keeps the new file", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = async () => ({ ok: true, json: async () => ({ ...policy, browser_processing_beta_enabled: true, version: 1 }) });
let firstStarted;
const started = new Promise((resolve) => { firstStarted = resolve; });
let finishFirst;
let calls = 0;
const processor = new BrowserSubmissionProcessor(
{ browserProcessingBeta: true, policyUrl: "/policy", policyVersion: 1 }, null,
{ prepareAudio: async () => new Float32Array(16000), classify: async () => {
calls += 1;
if (calls === 1) {
firstStarted();
return new Promise((resolve) => { finishFirst = resolve; });
}
return [{ class: "Fireworks", score: .9 }];
} },
);
processor.setEnabled(true);
const firstFile = new File(["a"], "first.wav", { type: "audio/wav" });
const secondFile = new File(["b"], "second.wav", { type: "audio/wav" });
try {
const first = processor.process(firstFile);
await started;
const second = await processor.process(secondFile);
assert.equal(second.file, secondFile);
assert.equal(second.gate, "whitelist_match");
finishFirst([{ class: "Speech", score: .9 }]);
await assert.rejects(first);
} finally { globalThis.fetch = originalFetch; }
});
@@ -10,6 +10,7 @@ test("disabled beta returns the original file without loading policy", async ()
globalThis.fetch = () => { throw new Error("fetch must not run"); };
try {
const processor = new BrowserSubmissionProcessor({ browserProcessingBeta: false });
processor.setEnabled(true);
assert.equal(processor.isEnabled(), false);
assert.equal(processor.canProcess(file), false);
assert.deepEqual(await processor.prepare(file), { file, metadata: null, gate: "unavailable" });
@@ -23,6 +24,7 @@ test("enabled shell checks current server policy and never claims processing occ
globalThis.fetch = async () => ({ ok: true, json: async () => ({ browser_processing_beta_enabled: true, version: 1 }) });
try {
const processor = new BrowserSubmissionProcessor({ browserProcessingBeta: true, policyUrl: "/browser-policy/", policyVersion: 1 });
processor.setEnabled(true);
const result = await processor.prepare(file);
assert.equal(result.file, file);
assert.equal(result.metadata.browser_processing_used, false);
@@ -35,6 +37,7 @@ test("enabled shell checks current server policy and never claims processing occ
test("admin-disabled policy and fetch failure both fall back to the original file", async () => {
const originalFetch = globalThis.fetch;
const processor = new BrowserSubmissionProcessor({ browserProcessingBeta: true, policyUrl: "/browser-policy/", policyVersion: 1 });
processor.setEnabled(true);
try {
globalThis.fetch = async () => ({ ok: true, json: async () => ({ browser_processing_beta_enabled: false, version: 1 }) });
assert.deepEqual(await processor.prepare(file), { file, metadata: null, gate: "unavailable" });
@@ -55,6 +58,7 @@ test("video routing is gated and audio never invokes FFmpeg", async () => {
async () => { calls += 1; return new File(["wav"], "clip.wav", { type: "audio/wav" }); },
{ prepareAudio: async () => new Float32Array(16000), classify: async () => [{ class: "Fireworks", score: .9 }] },
);
processor.setEnabled(true);
await processor.prepare(file);
assert.equal(calls, 0);
const video = { type: "video/mp4", size: 123, name: "clip.mp4" };
@@ -77,8 +81,32 @@ test("video conversion failure rejects instead of falling back to original video
{ browserProcessingBeta: true, policyUrl: "/browser-policy/", policyVersion: 1 },
async () => { throw new Error("decode failed"); },
);
processor.setEnabled(true);
await assert.rejects(processor.prepare({ type: "video/mp4", name: "bad.mp4" }), /decode failed/);
} finally {
globalThis.fetch = originalFetch;
}
});
test("admin ON and user toggle OFF bypasses policy, FFmpeg and TensorFlow", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = () => { throw new Error("policy must not load"); };
const audio = new File(["audio"], "clip.wav", { type: "audio/wav" });
const processor = new BrowserSubmissionProcessor(
{ browserProcessingBeta: true, policyUrl: "/policy", policyVersion: 1 },
async () => { throw new Error("FFmpeg must not load"); },
{ prepareAudio: async () => { throw new Error("audio preparation must not run"); },
classify: async () => { throw new Error("TensorFlow must not load"); } },
);
try {
assert.equal(processor.isAvailable(), true);
assert.equal(processor.isEnabled(), false);
assert.deepEqual(await processor.process(audio), { file: audio, metadata: null, gate: "unavailable" });
processor.setEnabled(true);
assert.equal(processor.isEnabled(), true);
processor.setEnabled(false);
assert.equal(processor.isEnabled(), false);
assert.deepEqual(await processor.process(audio), { file: audio, metadata: null, gate: "unavailable" });
} finally { globalThis.fetch = originalFetch; }
});