fix: validate merged voice fallback and host toolbar features

This commit is contained in:
illusia committed 2026-11-27 08:53:26 +08:00
1 parent 02509ea551
commit 001457d004
32 files changed
+319 -102

No files matched your search

+1 -1
View File
@@ -24,7 +24,7 @@ test("schema 7 upgrades preserve the previously unused public host and initializ
const original = new WebSpeakDatabase(filename);
original.close();
const legacy = new DatabaseSync(filename);
legacy.exec("DROP TABLE ts_admin_settings; ALTER TABLE relay_nodes DROP COLUMN voice_endpoint; ALTER TABLE settings DROP COLUMN ts_target; ALTER TABLE managed_invites DROP COLUMN target_text; ALTER TABLE settings DROP COLUMN webrtc_ipv6_enabled; ALTER TABLE settings DROP COLUMN webrtc_stun_server; DROP TABLE workspace_invites; ALTER TABLE settings DROP COLUMN voice_profile; ALTER TABLE settings DROP COLUMN voice_turn_urls; ALTER TABLE settings DROP COLUMN voice_turn_secret_encrypted; ALTER TABLE settings DROP COLUMN voice_turn_ttl_seconds; ALTER TABLE settings DROP COLUMN voice_opus_ws; ALTER TABLE settings DROP COLUMN voice_jitter_max_ms; PRAGMA user_version = 7;");
legacy.exec("DROP TABLE ts_admin_settings; ALTER TABLE relay_nodes DROP COLUMN voice_endpoint; ALTER TABLE settings DROP COLUMN ts_target; ALTER TABLE managed_invites DROP COLUMN target_text; ALTER TABLE settings DROP COLUMN webrtc_ipv6_enabled; ALTER TABLE settings DROP COLUMN webrtc_stun_server; DROP TABLE workspace_invites; PRAGMA user_version = 7;");
legacy.prepare("UPDATE settings SET webrtc_public_host = ?").run("media.example.com");
legacy.close();
const migrated = new WebSpeakDatabase(filename);
+10 -1
View File
@@ -69,6 +69,13 @@ const rectOf = (element) => {
};
const withinViewport = (rect) => rect.left >= -0.5 && rect.top >= -0.5
&& rect.right <= innerWidth + 0.5 && rect.bottom <= innerHeight + 0.5;
// Controls may overflow a narrow anchor; they must remain clamped on screen.
const alignedWithAnchor = (inner, outer, align = "end") => {
const desiredLeft = align === "start" ? outer.left : outer.right - inner.width;
const left = Math.min(Math.max(4, desiredLeft), Math.max(4, innerWidth - 4 - inner.width));
const top = Math.min(Math.max(4, outer.top + (outer.height - inner.height) / 2), Math.max(4, innerHeight - 4 - inner.height));
return Math.abs(inner.left - left) <= 0.5 && Math.abs(inner.top - top) <= 0.5;
};
const withinRect = (inner, outer) => inner.left >= outer.left - 0.5 && inner.right <= outer.right + 0.5
&& inner.top >= outer.top - 0.5 && inner.bottom <= outer.bottom + 0.5;
const rectsOverlap = (a, b) => Math.min(a.right, b.right) - Math.max(a.left, b.left) > 1
@@ -257,7 +264,9 @@ try {
const voiceAnchorRect = rectOf(document.getElementById("voice-anchor"));
const afterSwitch = {
...snapshot(),
insideVoiceAnchor: openToolbars().every((bar) => withinRect(rectOf(bar), voiceAnchorRect)),
alignedWithVoiceAnchor: openToolbars().every((bar) => alignedWithAnchor(rectOf(bar), voiceAnchorRect,
mode === "split" && actions(bar).includes("built-in") ? "start" : "end")),
anchorRect: voiceAnchorRect,
resolvedVoice: resolveSkinAnchor(anchorList, document, "community.plugin-panel-fixture")?.id,
};
+12 -3
View File
@@ -62,6 +62,13 @@ const rectOf = (element) => {
};
const withinViewport = (rect) => rect.left >= -0.5 && rect.top >= -0.5
&& rect.right <= innerWidth + 0.5 && rect.bottom <= innerHeight + 0.5;
// Controls may overflow a narrow anchor; they must remain clamped on screen.
const alignedWithAnchor = (inner, outer, align = "end") => {
const desiredLeft = align === "start" ? outer.left : outer.right - inner.width;
const left = Math.min(Math.max(4, desiredLeft), Math.max(4, innerWidth - 4 - inner.width));
const top = Math.min(Math.max(4, outer.top + (outer.height - inner.height) / 2), Math.max(4, innerHeight - 4 - inner.height));
return Math.abs(inner.left - left) <= 0.5 && Math.abs(inner.top - top) <= 0.5;
};
const withinRect = (inner, outer) => inner.left >= outer.left - 0.5 && inner.right <= outer.right + 0.5
&& inner.top >= outer.top - 0.5 && inner.bottom <= outer.bottom + 0.5;
@@ -109,7 +116,8 @@ try {
const firstStyle = getComputedStyle(first);
const initialSnapshot = {
toolbarOpen: isOpen(initial),
insideAnchor: withinRect(initialRect, homeRect),
alignedWithAnchor: alignedWithAnchor(initialRect, homeRect),
anchorRect: homeRect,
insideViewport: withinViewport(initialRect),
labels: buttons().map((button) => button.textContent?.trim()),
actionCount: buttons().length,
@@ -163,7 +171,8 @@ try {
const voiceRect = rectOf(document.getElementById("voice-anchor"));
const afterSwitch = {
toolbarOpen: isOpen(toolbar()),
insideVoiceAnchor: withinRect(rectOf(toolbar()), voiceRect),
alignedWithVoiceAnchor: alignedWithAnchor(rectOf(toolbar()), voiceRect),
rect: rectOf(toolbar()), anchorRect: voiceRect,
insideViewport: withinViewport(rectOf(toolbar())),
resolvedVoice: resolveSkinAnchor(
["skin.home.topbar.part-host-actions", "skin.voice.topbar.part-host-actions"],
@@ -193,7 +202,7 @@ try {
await sleep(2200);
const redocked = {
toolbarOpen: isOpen(toolbar()),
insideVoiceAnchor: withinRect(rectOf(toolbar()), rectOf(document.getElementById("voice-anchor"))),
alignedWithVoiceAnchor: alignedWithAnchor(rectOf(toolbar()), rectOf(document.getElementById("voice-anchor"))),
capsuleOpen: isOpen(capsule()),
};
+27
View File
@@ -0,0 +1,27 @@
<!doctype html><meta charset="utf-8"><pre id="result">pending</pre>
<script type="module">
import { createOpusUplink } from "/src/voice/opus-uplink.ts";
const fallback = [];
const sent = [];
let encoder;
const uplink = createOpusUplink({
createEncoder(output, error) { encoder = new AudioEncoder({ output, error }); return encoder; },
send(frame) { sent.push(frame.length); return true; },
onDrop() {},
onFallback(reason) { fallback.push(reason); },
});
try {
const initialized = await uplink.init();
uplink.push(new Float32Array(960));
await encoder.flush();
const before = { active: uplink.active, frames: sent.length };
uplink.resetStream();
uplink.push(new Float32Array(960));
await encoder.flush();
document.querySelector("#result").textContent = JSON.stringify({
initialized, before, after: { active: uplink.active, frames: sent.length }, fallback,
});
} catch (error) {
document.querySelector("#result").textContent = JSON.stringify({ error: String(error) });
} finally { uplink.close(); }
</script>
+5 -5
View File
@@ -700,7 +700,7 @@ test("toolbar-mode recovery docks plain host buttons, de-duplicates the library
const initial = payload.initial;
assert.equal(initial.toolbarOpen, true, "the toolbar did not dock into the declared anchor");
assert.equal(initial.insideAnchor, true, "the toolbar is not placed inside the page anchor");
assert.equal(initial.alignedWithAnchor, true, JSON.stringify(initial));
assert.equal(initial.insideViewport, true);
assert.equal(initial.actionCount, 2, "the group slot must render both independent host buttons");
assert.deepEqual(initial.labels, ["Integrierten Skin verwenden", "Anwendungsbibliothek"]);
@@ -729,7 +729,7 @@ test("toolbar-mode recovery docks plain host buttons, de-duplicates the library
}
assert.equal(payload.afterSwitch.toolbarOpen, true, "the toolbar did not survive the home -> voice page switch");
assert.equal(payload.afterSwitch.insideVoiceAnchor, true, "the toolbar stayed on the previous page anchor");
assert.equal(payload.afterSwitch.alignedWithVoiceAnchor, true, "the toolbar stayed on the previous page anchor");
assert.equal(payload.afterSwitch.resolvedVoice, "voice-anchor", "the candidate list did not resolve the voice anchor");
assert.equal(payload.fallback.toolbarOpen, false, "the toolbar stayed visible with a broken anchor");
@@ -738,7 +738,7 @@ test("toolbar-mode recovery docks plain host buttons, de-duplicates the library
assert.equal(payload.fallback.launcherSuppressed, true, "the fallback capsule must keep exactly one library entry");
assert.equal(payload.redocked.toolbarOpen, true, "the toolbar did not re-dock after the anchor returned");
assert.equal(payload.redocked.insideVoiceAnchor, true);
assert.equal(payload.redocked.alignedWithVoiceAnchor, true);
assert.equal(payload.redocked.capsuleOpen, false);
assert.equal(payload.shortcut.capsuleOpen, true, "the shortcut did not summon the recovery capsule");
@@ -844,7 +844,7 @@ test("real PluginPanel launcher is de-duplicated by group and split toolbars on
assert.equal(group.clicks.builtIn, true);
assert.equal(group.clicks.library, true);
assert.equal(group.afterSwitch.toolbars[0].open, true, "the toolbar did not survive the page switch");
assert.equal(group.afterSwitch.insideVoiceAnchor, true);
assert.equal(group.afterSwitch.alignedWithVoiceAnchor, true);
assert.equal(group.afterSwitch.resolvedVoice, "voice-anchor");
assert.equal(group.fallback.toolbars[0].open, false, "the toolbar stayed docked with a broken anchor");
assert.equal(group.fallback.capsuleVisible, true);
@@ -873,7 +873,7 @@ test("real PluginPanel launcher is de-duplicated by group and split toolbars on
assert.equal(split.clicks.library, true, "the library split toolbar button was not clickable");
assert.equal(split.afterSwitch.toolbars[0].open, true);
assert.equal(split.afterSwitch.toolbars[1].open, true);
assert.equal(split.afterSwitch.insideVoiceAnchor, true);
assert.equal(split.afterSwitch.alignedWithVoiceAnchor, true);
for (const lang of ["de", "ru", "ja"]) {
observableButtons({ visibleActions: split.languages[lang] }, `${lang} split desktop`);
}
+37
View File
@@ -0,0 +1,37 @@
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { existsSync } from "node:fs";
import { fileURLToPath } from "node:url";
import test from "node:test";
import { createServer } from "vite";
const chrome = [process.env.WEBSPEAK_TEST_CHROME, "/usr/bin/google-chrome", "/usr/bin/google-chrome-stable"]
.find(candidate => candidate && existsSync(candidate));
test("real WebCodecs Opus encoding survives a VOX pause and reset", { skip: !chrome && "Chrome is not installed" }, async t => {
const server = await createServer({
root: fileURLToPath(new URL("../", import.meta.url)), logLevel: "silent",
server: { host: "127.0.0.1", port: 0, hmr: false, ws: false },
});
t.after(() => server.close());
await server.listen();
const port = server.httpServer.address().port;
const dom = await new Promise((resolve, reject) => {
const child = spawn(chrome, ["--headless=new", "--no-sandbox", "--disable-gpu", "--disable-dev-shm-usage",
"--virtual-time-budget=4000", "--dump-dom", `http://127.0.0.1:${port}/test/fixtures/opus-uplink-browser.html`]);
let output = "", error = "";
child.stdout.on("data", data => { output += data; });
child.stderr.on("data", data => { error += data; });
const timer = setTimeout(() => { child.kill(); reject(new Error("Browser timed out")); }, 30_000);
child.on("error", err => { clearTimeout(timer); reject(err); });
child.on("exit", () => { clearTimeout(timer); output.includes('id="result"') ? resolve(output) : reject(new Error(error)); });
});
const result = JSON.parse(dom.match(/<pre id="result"[^>]*>([\s\S]*?)<\/pre>/)[1].replaceAll("&quot;", '"').replaceAll("&amp;", "&"));
assert.equal(result.error, undefined);
assert.equal(result.initialized, true);
assert.equal(result.before.active, true);
assert.ok(result.before.frames > 0, JSON.stringify(result));
assert.equal(result.after.active, true);
assert.ok(result.after.frames > result.before.frames, JSON.stringify(result));
assert.deepEqual(result.fallback, []);
});
+14 -4
View File
@@ -9,15 +9,16 @@ function fakeUplink() {
let dropped = 0;
let configured = false;
const encoder = {
state: "configured" as const,
state: "unconfigured" as "unconfigured" | "configured" | "closed",
encodeQueueSize: 0,
configure() { configured = true; },
configure() { configured = true; this.state = "configured"; },
encode(data: AudioData) {
if (this.state !== "configured") throw new DOMException("Encoder is not configured", "InvalidStateError");
encoded.push(data);
output?.({ byteLength: 3, copyTo(target: Uint8Array) { target.set([1, 2, 3]); } });
},
reset() {},
close() {},
reset() { this.state = "unconfigured"; },
close() { this.state = "closed"; },
};
const uplink = createOpusUplink({
send(frame) { sent.push(frame); return true; },
@@ -41,12 +42,21 @@ test("Opus uplink accumulates 960 samples, emits tagged frames and resets on VOX
f.uplink.push(new Float32Array(480));
assert.equal(f.encoded.length, 2);
f.uplink.resetStream();
assert.equal(f.encoder.state, "configured");
f.uplink.push(new Float32Array(960));
assert.equal(f.encoded.length, 3);
f.uplink.disable();
assert.equal(f.uplink.active, false);
});
test("an encoder error partway through a large capture chunk exits the loop and falls back", async () => {
const f = fakeUplink();
await f.uplink.init();
f.encoder.encode = () => { throw new DOMException("Encoding failed", "EncodingError"); };
assert.equal(f.uplink.push(new Float32Array(4096)), false);
assert.equal(f.uplink.active, false);
});
test("Opus uplink cancels initialization when disabled during capability detection", async t => {
const previousEncoder = globalThis.AudioEncoder;
let resolveSupport!: (value: { supported: boolean }) => void;
+45 -4
View File
@@ -146,6 +146,7 @@ function deferred() {
class TestPeer extends EventTarget {
static instances = [];
static connectOnAnswer = true;
iceGatheringState = "complete";
connectionState = "new";
localDescription = null;
@@ -156,7 +157,13 @@ class TestPeer extends EventTarget {
getSenders() { return [this.sender]; }
async createOffer() { return { type: "offer", sdp: "test-offer" }; }
async setLocalDescription(description) { this.localDescription = description; }
async setRemoteDescription(description) { this.remoteDescription = description; }
async setRemoteDescription(description) {
this.remoteDescription = description;
if (TestPeer.connectOnAnswer) {
this.connectionState = "connected";
this.onconnectionstatechange?.();
}
}
close() { this.connectionState = "closed"; }
}
@@ -206,6 +213,7 @@ beforeEach(() => {
compatibilityAudioClientId = 7;
TestSocket.instances.length = 0;
TestPeer.instances.length = 0;
TestPeer.connectOnAnswer = true;
AudioContextStub.processors.length = 0;
AudioContextStub.instances.length = 0;
AudioContextStub.sources.length = 0;
@@ -748,11 +756,15 @@ test("channel traversal preserves sibling predecessors and handles a deep direct
assert.equal(deep.channelTree.value.at(-1).depth, 4_999);
});
async function connectWebRtc() {
async function connectWebRtc({ negotiateOnly = false } = {}) {
const socket = await connect();
socket.receive({ type: "connected", tsClientId: 1, webrtcAvailable: true });
await nextTurn();
assert.ok(socket.messages.some(message => message.type === "webrtcOffer"));
if (!negotiateOnly) {
socket.receive({ type: "webrtcAnswer", payload: { sdp: { type: "answer", sdp: "connected-answer" } } });
await nextTurn();
}
return { socket, peer: TestPeer.instances.at(-1) };
}
@@ -1539,6 +1551,28 @@ test("a successful old WebRTC answer cannot activate WebRTC for a replacement co
assert.ok(current.messages.some(message => message instanceof ArrayBuffer && message.byteLength === 1920));
});
test("an answer without connected media keeps compatibility audio and a retry can time out", async t => {
const deadlines = [];
const setTimer = window.setTimeout.bind(window);
t.mock.method(window, "setTimeout", (callback, ms) => {
if (ms === 15_000) deadlines.push(callback);
return setTimer(callback, ms);
});
TestPeer.connectOnAnswer = false;
const {socket,peer} = await connectWebRtc({ negotiateOnly: true });
peer.connectionState = "connecting";
socket.receive({type:"webrtcAnswer",payload:{sdp:{type:"answer",sdp:"no-media"}}});
await nextTurn();
assertCompatibilityAudio(socket);
assert.equal((await audioSample(socket)).transport, "negotiating");
assert.equal(deadlines.length, 1);
deadlines[0]();
await nextTurn();
assert.equal(peer.connectionState, "closed");
assert.match(voice.state.audioNotice, /WEBRTC_CONNECTION_TIMEOUT/);
assertCompatibilityAudio(socket);
});
test("reconnect WebRTC keeps compatibility audio until ready without reconnecting TeamSpeak", async () => {
const getUserMedia = navigator.mediaDevices.getUserMedia;
let microphoneRequests = 0;
@@ -1567,9 +1601,16 @@ test("reconnect WebRTC keeps compatibility audio until ready without reconnectin
assert.equal(voice.state.webrtcReconnecting, true);
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FAILED");
assertCompatibilityAudio(socket);
TestPeer.connectOnAnswer = false;
socket.receive({ type: "webrtcAnswer", payload: { sdp: { type: "answer", sdp: "reconnected-answer" } } });
await nextTurn();
assert.equal(current.remoteDescription.sdp, "reconnected-answer");
assert.equal(voice.state.webrtcReconnecting, true);
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FAILED");
assertCompatibilityAudio(socket);
current.connectionState = "connected";
current.onconnectionstatechange();
await nextTurn();
assert.equal(voice.state.webrtcReconnecting, false);
assert.equal(voice.state.audioNoticeCode, "");
assert.equal(voice.state.connected, true);
@@ -1969,7 +2010,7 @@ test("a probe started before peer allocation cannot survive a failed transport a
});
test("disconnect clears the WebRTC answer deadline immediately", async () => {
await connectWebRtc();
await connectWebRtc({ negotiateOnly: true });
assert.ok(browserTimers.size > 0);
voice.disconnect();
assert.equal(browserTimers.size, 0);
@@ -2019,7 +2060,7 @@ test("an answer timeout keeps the session and offers a WebRTC retry", async t =>
if (ms === 8_000) deadlines.push(callback);
return setTimer(callback, ms);
});
const { socket, peer } = await connectWebRtc();
const { socket, peer } = await connectWebRtc({ negotiateOnly: true });
assert.equal(deadlines.length, 1);
deadlines[0]();
await nextTurn();