fix: keep voice diagnostics scoped to current media

This commit is contained in:
illusia committed 2026-10-01 15:03:58 +08:00
1 parent 5855d0ba67
commit c16d1d4cfb
10 files changed
+532 -220

No files matched your search

+30 -175
View File
@@ -7,13 +7,15 @@ import { createAccompaniment, type AccompanimentErrorCode } from "../voice/accom
import { createWebRtcTransport } from "../voice/webrtc-transport.js";
import { createVoiceConnection } from "../voice/connection.js";
import { createVoiceCommands } from "../voice/commands.js";
import { createAudioDiagnostics, type AudioPermission, type VoiceAudioStatusSample } from "../voice/audio-diagnostics.js";
export type { AudioPermission, BrowserVoiceAudioStats, VoiceAudioStatusSample } from "../voice/audio-diagnostics.js";
import type { SinkAudioElement } from "../voice/webrtc-playback.js";
import { createScreenShareController } from "../voice/screen-share.js";
export type { ScreenShareOutputSettings, ScreenShareCaptureStats, ScreenSharePeerStats, ScreenShareWebRtcStats } from "../voice/screen-share.js";
import { parseServerMessage } from "../../../src/shared/server-messages.js";
import type { ClientCommandPayloads, ClientCommandType } from "../../../src/shared/client-commands.js";
export type { ScreenShareStreamDescription as ScreenShareStream, ScreenShareViewerDescription as ScreenShareViewer, ScreenSharePeerSignal as ScreenShareSignal } from "../../../src/shared/screen-share.js";
import type { ChannelMember, ChannelInfo, ChatMessage, ServerEvent, VoiceAudioBridgeStats } from "../../../src/shared/voice-models.js";
import type { ChannelMember, ChannelInfo, ChatMessage, ServerEvent } from "../../../src/shared/voice-models.js";
export type { ChannelMember, ChannelInfo, ChatMessage, ServerEvent, VoiceAudioBridgeStats } from "../../../src/shared/voice-models.js";
import { reactive, ref, shallowRef } from "vue";
import { loadLocalPreferences, saveLocalPreferences } from "../services/local-persistence.js";
@@ -51,39 +53,10 @@ export interface AudioOutputDevice {
groupId: string;
}
export type AudioPermission = "unknown" | "granted" | "denied";
type SinkAudioContext = AudioContext & {
setSinkId?: (sinkId: string) => Promise<void>;
};
export interface BrowserVoiceAudioStats {
outboundBytes: number | null;
outboundPackets: number | null;
outboundPacketsLost: number | null;
outboundLossPercent: number | null;
outboundRttMs: number | null;
inboundBytes: number | null;
inboundPackets: number | null;
inboundPacketsLost: number | null;
inboundLossPercent: number | null;
inboundJitterMs: number | null;
concealedSamples: number | null;
}
export interface VoiceAudioStatusSample {
sampledAt: number;
transport: "webrtc" | "websocket" | "negotiating" | "disconnected";
connectionState: string | null;
microphoneMuted: boolean;
microphoneReady: boolean;
microphonePermission: AudioPermission;
playbackState: "playing" | "paused" | "unavailable" | null;
bridge: VoiceAudioBridgeStats;
browser: BrowserVoiceAudioStats | null;
fallbackPlayback: { framesReceived: number; framesDropped: number; decodeErrors: number };
}
const MAX_VISIBLE_ERROR_CODE_LENGTH = 64;
const CLIENT_ERROR_CODE_ALIASES: Record<string, string> = {
PASSWORD_REQUIRED: "SERVER_PASSWORD_REQUIRED",
@@ -245,11 +218,6 @@ export function useVoiceWebSocket() {
});
const commands = createVoiceCommands({ socket: () => ws.value, generation: () => voiceConnection.generation });
let lastConnection: { target: string; channel: string; nickname: string; serverPassword: string; identity?: string; rememberIdentity: boolean; accelerated: boolean; accelerationRelayId: string } | null = null;
let audioStatusProbeSequence = 0;
const pendingAudioStatusProbes = new Map<string, { resolve: (stats: VoiceAudioBridgeStats | null) => void; timer: ReturnType<typeof setTimeout> }>();
let fallbackAudioFramesReceived = 0;
let fallbackAudioFramesDropped = 0;
let fallbackAudioDecodeErrors = 0;
const identityMaterial = ref("");
const storedVolumesByUid = reactive<Record<string, number>>({});
let microphoneStartPromise: Promise<void> | null = null;
@@ -341,8 +309,8 @@ export function useVoiceWebSocket() {
const remotePlayback = createRemotePlayback({
getContext: getAudioCtx,
getVolume: clientId => (volumes[clientId] ?? 1) * effectiveOutputVolume(),
onDecodeError: () => { fallbackAudioDecodeErrors++; },
onDrop: () => { fallbackAudioFramesDropped++; },
onDecodeError: () => audioDiagnostics.count("decodeErrors"),
onDrop: () => audioDiagnostics.count("framesDropped"),
});
const webrtc = createWebRtcTransport({
prepareMicrophone: async () => {
@@ -384,6 +352,26 @@ export function useVoiceWebSocket() {
onPlaying: syncAudioContextNotice,
},
});
const audioDiagnostics = createAudioDiagnostics({
source() {
const socket = ws.value;
if (!socket || socket.readyState !== WebSocket.OPEN || !state.connected) return null;
const peer = webrtc.peer;
return { socket, connection: voiceConnection.generation, transportGeneration: webrtc.generation, peer,
transport: webrtc.active ? "webrtc" : peer ? "negotiating" : "websocket" };
},
presentation({ peer }) {
return {
microphoneMuted: microphoneMuted.value,
microphoneReady: Boolean(micStream?.getAudioTracks().some(track => track.readyState === "live")),
microphonePermission: audioPermission.value,
playbackState: peer
? webrtc.output ? webrtc.output.paused ? "paused" : "playing" : "unavailable"
: audioCtx ? audioCtx.state === "running" ? "playing" : "paused" : null,
};
},
send: (source, sequence) => source.socket.send(JSON.stringify({ type: "audioStatsProbe", payload: { sequence } })),
});
async function saveAudioPreferences(): Promise<void> {
await saveLocalPreferences({
@@ -1021,7 +1009,7 @@ export function useVoiceWebSocket() {
selectedOutputDeviceId.value = committedOutputDeviceId;
noiseSuppressionEnabled.value = committedNoiseSuppressionEnabled;
microphoneTest.dispose();
clearAudioStatusProbes();
audioDiagnostics.reset();
commands.clear(new Error("语音连接已关闭"));
screenShare.stopTransport(sendScreenStop);
webrtc.stop();
@@ -1032,14 +1020,6 @@ export function useVoiceWebSocket() {
whisperActive.value = false;
}
function clearAudioStatusProbes(): void {
for (const [sequence, pending] of pendingAudioStatusProbes) {
clearTimeout(pending.timer);
pendingAudioStatusProbes.delete(sequence);
pending.resolve(null);
}
}
function handleMessage(raw: unknown): void {
const msg = parseServerMessage(raw);
if (!msg || screenShare.handleMessage(msg)) return;
@@ -1161,9 +1141,7 @@ export function useVoiceWebSocket() {
break;
case "audioStats": {
const sequence = typeof msg.sequence === "string" ? msg.sequence : "";
const pending = pendingAudioStatusProbes.get(sequence);
if (!pending) break;
pending.resolve(msg.stats);
audioDiagnostics.receive(sequence, msg.stats);
break;
}
case "disconnected":
@@ -1252,12 +1230,12 @@ export function useVoiceWebSocket() {
// produce duplicate or delayed playback.
if (webrtc.active) return;
if (data.length < 4) {
fallbackAudioFramesDropped++;
audioDiagnostics.count("framesDropped");
return;
}
const clientId = (data[1] << 8) | data[2];
if (clientId === state.tsClientId) return;
fallbackAudioFramesReceived++;
audioDiagnostics.count("framesReceived");
markSpeaking(clientId);
remotePlayback.play(clientId, data.slice(3));
}
@@ -1281,131 +1259,8 @@ export function useVoiceWebSocket() {
return sendCommandAndWait("moveClient", { clientId, channelId, ...(password ? { password } : {}) });
}
async function collectBrowserVoiceAudioStats(): Promise<BrowserVoiceAudioStats | null> {
const peer = webrtc.peer;
if (!peer) return null;
try {
const report = await peer.getStats();
let outbound: Record<string, unknown> | undefined;
let remoteInbound: Record<string, unknown> | undefined;
let inbound: Record<string, unknown> | undefined;
let candidatePair: Record<string, unknown> | undefined;
report.forEach((raw) => {
const stats = raw as unknown as Record<string, unknown>;
const type = typeof stats.type === "string" ? stats.type : "";
const kind = typeof stats.kind === "string" ? stats.kind : typeof stats.mediaType === "string" ? stats.mediaType : "";
if (kind === "audio") {
if (type === "outbound-rtp") outbound = stats;
else if (type === "remote-inbound-rtp") remoteInbound = stats;
else if (type === "inbound-rtp") inbound = stats;
}
if (type === "candidate-pair" && (stats.selected === true || stats.nominated === true) && stats.state === "succeeded") candidatePair = stats;
});
const readNumber = (stats: Record<string, unknown> | undefined, key: string): number | null => {
const value = stats?.[key];
return typeof value === "number" && Number.isFinite(value) ? value : null;
};
const outboundLost = readNumber(remoteInbound, "packetsLost");
const outboundPackets = readNumber(outbound, "packetsSent");
const fractionLost = readNumber(remoteInbound, "fractionLost");
const outboundLossPercent = fractionLost !== null
? Math.min(100, Math.max(0, fractionLost * 100))
: outboundLost !== null && outboundPackets !== null && outboundPackets + Math.max(0, outboundLost) > 0
? (Math.max(0, outboundLost) / (outboundPackets + Math.max(0, outboundLost))) * 100
: null;
const inboundPackets = readNumber(inbound, "packetsReceived");
const inboundPacketsLost = readNumber(inbound, "packetsLost");
const inboundLossTotal = inboundPackets !== null && inboundPacketsLost !== null
? inboundPackets + Math.max(0, inboundPacketsLost)
: null;
const outboundRttSeconds = readNumber(remoteInbound, "roundTripTime") ?? readNumber(candidatePair, "currentRoundTripTime");
const inboundJitterSeconds = readNumber(inbound, "jitter");
return {
outboundBytes: readNumber(outbound, "bytesSent"),
outboundPackets,
outboundPacketsLost: outboundLost,
outboundLossPercent,
outboundRttMs: outboundRttSeconds === null ? null : outboundRttSeconds * 1_000,
inboundBytes: readNumber(inbound, "bytesReceived"),
inboundPackets,
inboundPacketsLost,
inboundLossPercent: inboundLossTotal && inboundLossTotal > 0 && inboundPacketsLost !== null
? (Math.max(0, inboundPacketsLost) / inboundLossTotal) * 100
: null,
inboundJitterMs: inboundJitterSeconds === null ? null : inboundJitterSeconds * 1_000,
concealedSamples: readNumber(inbound, "concealedSamples"),
};
} catch {
return null;
}
}
function measureVoiceAudioStatus(timeoutMs = 1_800): Promise<VoiceAudioStatusSample | null> {
const socket = ws.value;
if (!socket || socket.readyState !== WebSocket.OPEN || !state.connected) return Promise.resolve(null);
const connection = voiceConnection.generation;
const peer = webrtc.peer;
const isCurrent = () => connection === voiceConnection.generation && ws.value === socket
&& socket.readyState === WebSocket.OPEN && state.connected && webrtc.peer === peer;
const sequence = `audio-${Date.now().toString(36)}-${(audioStatusProbeSequence++).toString(36)}`;
const browserStatsPromise = collectBrowserVoiceAudioStats();
return new Promise<VoiceAudioStatusSample | null>((resolve) => {
let settled = false;
let receivedBridge = false;
const finish = (sample: VoiceAudioStatusSample | null): void => {
if (settled) return;
settled = true;
clearTimeout(timer);
pendingAudioStatusProbes.delete(sequence);
resolve(sample);
};
// Keep the deadline and cancellation entry until both sources finish.
// A gateway reply must not leave an unbounded browser getStats wait.
const timer = setTimeout(() => finish(null), timeoutMs);
pendingAudioStatusProbes.set(sequence, {
resolve: (bridge) => {
if (!bridge) {
finish(null);
return;
}
if (settled || receivedBridge) return;
receivedBridge = true;
void browserStatsPromise.then((browser) => {
if (settled) return;
if (!isCurrent()) { finish(null); return; }
const transport = !state.connected
? "disconnected"
: webrtc.active
? "webrtc"
: peer
? "negotiating"
: "websocket";
const playbackState = peer
? webrtc.output ? webrtc.output.paused ? "paused" : "playing" : "unavailable"
: audioCtx ? audioCtx.state === "running" ? "playing" : "paused" : null;
finish({
sampledAt: performance.now(),
transport,
connectionState: peer?.connectionState ?? null,
microphoneMuted: microphoneMuted.value,
microphoneReady: Boolean(micStream?.getAudioTracks().some((track) => track.readyState === "live")),
microphonePermission: audioPermission.value,
playbackState,
bridge,
browser,
fallbackPlayback: {
framesReceived: fallbackAudioFramesReceived,
framesDropped: fallbackAudioFramesDropped,
decodeErrors: fallbackAudioDecodeErrors,
},
});
});
},
timer,
});
try { sendCmd("audioStatsProbe", { sequence }); }
catch { finish(null); }
});
return audioDiagnostics.measure(timeoutMs);
}
function sendTextMessage(message: string, targetId = ""): void {
+28 -26
View File
@@ -1,5 +1,5 @@
import { computed, onUnmounted, ref, watch, type Ref } from "vue";
import type { VoiceAudioStatusSample } from "./useVoiceWebSocket.js";
import type { VoiceAudioStatusSample } from "../voice/audio-diagnostics.js";
const SAMPLE_INTERVAL_MS = 2_000;
@@ -27,13 +27,21 @@ function intervalLossPercent(
currentLost: number | null | undefined,
previousLost: number | null | undefined,
fallback: number | null,
packetsIncludeLost = false,
): number | null {
if (currentReceived == null || previousReceived == null || currentLost == null || previousLost == null) return fallback;
const receivedDelta = counterDelta(currentReceived, previousReceived);
const lostDelta = counterDelta(Math.max(0, currentLost), Math.max(0, previousLost));
if (receivedDelta === null || lostDelta === null) return fallback;
const total = receivedDelta + lostDelta;
return total > 0 ? (lostDelta / total) * 100 : fallback;
const total = receivedDelta + (packetsIncludeLost ? 0 : lostDelta);
return total > 0 ? Math.min(100, (lostDelta / total) * 100) : fallback;
}
function downlinkCounter(sample: VoiceAudioStatusSample | null) {
if (!sample) return null;
if (sample.transport === "websocket") return { source: "pcm", value: sample.fallbackPlayback.framesReceived };
if (sample.transport === "webrtc" && sample.browser?.inboundPackets != null) return { source: "rtp", value: sample.browser.inboundPackets };
return { source: "bridge", value: sample.bridge.egressFrames };
}
export function useWebClientPerformance(
@@ -46,10 +54,12 @@ export function useWebClientPerformance(
const previousSample = ref<VoiceAudioStatusSample | null>(null);
let timer: number | null = null;
let generation = 0;
let disposed = false;
const stats = computed(() => {
const current = latestSample.value;
const previous = previousSample.value;
const prior = previousSample.value;
const previous = current && prior && current.scopeId === prior.scopeId && current.transport === prior.transport ? prior : null;
const elapsedMs = current && previous ? current.sampledAt - previous.sampledAt : 0;
const bridge = current?.bridge;
const previousBridge = previous?.bridge;
@@ -58,25 +68,12 @@ export function useWebClientPerformance(
const uplinkFramesPerSecond = bridge
? ratePerSecond(bridge.tsSendFrames, previousBridge?.tsSendFrames, elapsedMs)
: null;
const downlinkCounter = current
? current.transport === "websocket"
? current.fallbackPlayback.framesReceived
: current.transport === "webrtc" && browser?.inboundPackets !== null && browser?.inboundPackets !== undefined
? browser.inboundPackets
: bridge?.egressFrames ?? null
: null;
const previousDownlinkCounter = previous
? previous.transport === "websocket"
? previous.fallbackPlayback.framesReceived
: previous.transport === "webrtc" && previousBrowser?.inboundPackets !== null && previousBrowser?.inboundPackets !== undefined
? previousBrowser.inboundPackets
: previousBridge?.egressFrames ?? null
: null;
const downlinkFramesPerSecond = downlinkCounter === null
? null
: ratePerSecond(downlinkCounter, previousDownlinkCounter ?? undefined, elapsedMs);
const downlink = downlinkCounter(current);
const priorDownlink = downlinkCounter(previous);
const downlinkFramesPerSecond = downlink && priorDownlink && downlink.source === priorDownlink.source
? ratePerSecond(downlink.value, priorDownlink.value, elapsedMs) : null;
const uplinkLossPercent = browser
? intervalLossPercent(browser.outboundPackets, previousBrowser?.outboundPackets, browser.outboundPacketsLost, previousBrowser?.outboundPacketsLost, browser.outboundLossPercent)
? intervalLossPercent(browser.outboundPackets, previousBrowser?.outboundPackets, browser.outboundPacketsLost, previousBrowser?.outboundPacketsLost, browser.outboundLossPercent, true)
: null;
const downlinkLossPercent = browser
? intervalLossPercent(browser.inboundPackets, previousBrowser?.inboundPackets, browser.inboundPacketsLost, previousBrowser?.inboundPacketsLost, browser.inboundLossPercent)
@@ -138,13 +135,18 @@ export function useWebClientPerformance(
});
async function runProbe(expectedGeneration = generation): Promise<void> {
if (running.value || !connected.value) return;
if (disposed || expectedGeneration !== generation || running.value || !connected.value) return;
running.value = true;
try {
const sample = await measureAudioStatus();
if (expectedGeneration !== generation || !connected.value || !sample) return;
previousSample.value = latestSample.value;
if (expectedGeneration !== generation || !connected.value) return;
previousSample.value = sample ? latestSample.value : null;
latestSample.value = sample;
} catch {
if (expectedGeneration === generation) {
latestSample.value = null;
previousSample.value = null;
}
} finally {
if (expectedGeneration === generation) running.value = false;
}
@@ -181,7 +183,7 @@ export function useWebClientPerformance(
else stop();
}, { immediate: true });
onUnmounted(stop);
onUnmounted(() => { disposed = true; stop(); });
return { panelOpen, running, stats, togglePanel, refresh };
}
+168
View File
@@ -0,0 +1,168 @@
import type { VoiceAudioBridgeStats } from "../../../src/shared/voice-models.js";
export type AudioPermission = "unknown" | "granted" | "denied";
export interface BrowserVoiceAudioStats {
outboundBytes: number | null;
outboundPackets: number | null;
outboundPacketsLost: number | null;
outboundLossPercent: number | null;
outboundRttMs: number | null;
inboundBytes: number | null;
inboundPackets: number | null;
inboundPacketsLost: number | null;
inboundLossPercent: number | null;
inboundJitterMs: number | null;
concealedSamples: number | null;
}
export interface VoiceAudioStatusSample {
/** Browser-local counter scope; changes when the connection or transport does. */
scopeId: number;
sampledAt: number;
transport: "webrtc" | "websocket" | "negotiating" | "disconnected";
connectionState: string | null;
microphoneMuted: boolean;
microphoneReady: boolean;
microphonePermission: AudioPermission;
playbackState: "playing" | "paused" | "unavailable" | null;
bridge: VoiceAudioBridgeStats;
browser: BrowserVoiceAudioStats | null;
fallbackPlayback: { framesReceived: number; framesDropped: number; decodeErrors: number };
}
interface DiagnosticSource {
socket: WebSocket;
connection: number;
transportGeneration: number;
peer: RTCPeerConnection | null;
transport: VoiceAudioStatusSample["transport"];
}
interface DiagnosticOptions {
source(): DiagnosticSource | null;
presentation(source: DiagnosticSource): Pick<VoiceAudioStatusSample,
"microphoneMuted" | "microphoneReady" | "microphonePermission" | "playbackState">;
send(source: DiagnosticSource, sequence: string): void;
}
async function browserStats(peer: RTCPeerConnection | null): Promise<BrowserVoiceAudioStats | null> {
if (!peer) return null;
try {
const report = await peer.getStats();
let outbound: Record<string, unknown> | undefined;
let remoteInbound: Record<string, unknown> | undefined;
let inbound: Record<string, unknown> | undefined;
let candidatePair: Record<string, unknown> | undefined;
report.forEach(raw => {
const stats = raw as unknown as Record<string, unknown>;
const kind = stats.kind ?? stats.mediaType;
if (kind === "audio") {
if (stats.type === "outbound-rtp") outbound = stats;
else if (stats.type === "remote-inbound-rtp") remoteInbound = stats;
else if (stats.type === "inbound-rtp") inbound = stats;
}
if (stats.type === "candidate-pair" && (stats.selected === true || stats.nominated === true) && stats.state === "succeeded") candidatePair = stats;
});
const number = (stats: Record<string, unknown> | undefined, key: string): number | null => {
const value = stats?.[key];
return typeof value === "number" && Number.isFinite(value) ? value : null;
};
const outboundLost = number(remoteInbound, "packetsLost");
const outboundPackets = number(outbound, "packetsSent");
const fractionLost = number(remoteInbound, "fractionLost");
// packetsSent already counts all sent packets; adding lost packets again
// underestimates loss. Prefer the remote RTCP report when supplied.
// https://www.w3.org/TR/webrtc-stats/#dom-rtcsentrtpstreamstats-packetssent
const outboundLossPercent = fractionLost !== null
? Math.min(100, Math.max(0, fractionLost * 100))
: outboundLost !== null && outboundPackets !== null && outboundPackets > 0
? Math.min(100, (Math.max(0, outboundLost) / outboundPackets) * 100)
: null;
const inboundPackets = number(inbound, "packetsReceived");
const inboundPacketsLost = number(inbound, "packetsLost");
const inboundTotal = inboundPackets !== null && inboundPacketsLost !== null
? inboundPackets + Math.max(0, inboundPacketsLost) : null;
const rtt = number(remoteInbound, "roundTripTime") ?? number(candidatePair, "currentRoundTripTime");
const jitter = number(inbound, "jitter");
return {
outboundBytes: number(outbound, "bytesSent"), outboundPackets, outboundPacketsLost: outboundLost,
outboundLossPercent, outboundRttMs: rtt === null ? null : rtt * 1_000,
inboundBytes: number(inbound, "bytesReceived"), inboundPackets, inboundPacketsLost,
inboundLossPercent: inboundTotal && inboundTotal > 0 && inboundPacketsLost !== null
? (Math.max(0, inboundPacketsLost) / inboundTotal) * 100 : null,
inboundJitterMs: jitter === null ? null : jitter * 1_000,
concealedSamples: number(inbound, "concealedSamples"),
};
} catch { return null; }
}
function sameSource(left: DiagnosticSource | null, right: DiagnosticSource | null): boolean {
return Boolean(left && right && left.socket === right.socket && left.connection === right.connection
&& left.transportGeneration === right.transportGeneration && left.peer === right.peer && left.transport === right.transport);
}
export function createAudioDiagnostics(options: DiagnosticOptions) {
const pending = new Map<string, { receive(bridge: VoiceAudioBridgeStats): void; finish(sample: VoiceAudioStatusSample | null): void }>();
const fallback = { framesReceived: 0, framesDropped: 0, decodeErrors: 0 };
let sequence = 0;
let scopeId = 0;
let previousSource: DiagnosticSource | null = null;
function measure(timeoutMs = 1_800): Promise<VoiceAudioStatusSample | null> {
const source = options.source();
if (!source) return Promise.resolve(null);
if (!sameSource(previousSource, source)) {
previousSource = source;
scopeId++;
}
const scope = scopeId;
const requestId = `audio-${Date.now().toString(36)}-${(sequence++).toString(36)}`;
const browser = browserStats(source.peer);
return new Promise(resolve => {
let settled = false;
let receivedBridge = false;
const finish = (sample: VoiceAudioStatusSample | null): void => {
if (settled) return;
settled = true;
clearTimeout(timer);
pending.delete(requestId);
resolve(sample);
};
// Keep cancellation and the deadline until both sources finish.
const timer = setTimeout(() => finish(null), timeoutMs);
pending.set(requestId, {
finish,
receive(bridge) {
if (settled || receivedBridge) return;
receivedBridge = true;
void browser.then(stats => {
if (settled) return;
if (scope !== scopeId || !sameSource(source, options.source())) { finish(null); return; }
finish({
scopeId: scope, sampledAt: performance.now(), transport: source.transport,
connectionState: source.peer?.connectionState ?? null,
...options.presentation(source), bridge, browser: stats, fallbackPlayback: { ...fallback },
});
});
},
});
try { options.send(source, requestId); }
catch { finish(null); }
});
}
return {
measure,
receive(sequence: string, bridge: VoiceAudioBridgeStats): void { pending.get(sequence)?.receive(bridge); },
count(counter: keyof typeof fallback): void { fallback[counter]++; },
reset(): void {
scopeId++;
previousSource = null;
for (const probe of pending.values()) probe.finish(null);
fallback.framesReceived = 0;
fallback.framesDropped = 0;
fallback.decodeErrors = 0;
},
};
}
+1
View File
@@ -182,6 +182,7 @@ export function createWebRtcTransport(options: TransportOptions) {
return {
start, stop, applyAnswer,
get generation(): number { return generation; },
releaseInput(): void { releaseInput(); },
async fallback(reason: string): Promise<void> { if (current) await fail(current, reason); },
get peer(): RTCPeerConnection | null { return current?.peer ?? null; },
+1 -1
View File
@@ -44,7 +44,7 @@ const defaults = path => ({
before(async () => {
vite = await createServer({ configFile: false, root: fileURLToPath(new URL("../", import.meta.url)),
plugins: [vuePlugin()], server: { middlewareMode: true, hmr: false, watch: null },
plugins: [vuePlugin()], server: { middlewareMode: true, hmr: false, ws: false, watch: null },
optimizeDeps: { noDiscovery: true, include: [] }, appType: "custom" });
({ createRenderer, ssrContextKey } = await import("vue"));
({ createRouter, createMemoryHistory } = await import("vue-router"));
+201
View File
@@ -0,0 +1,201 @@
import assert from "node:assert/strict";
import { before, after, beforeEach, afterEach, test } from "node:test";
import { setImmediate as nextTurn } from "node:timers/promises";
import { fileURLToPath } from "node:url";
import { createServer } from "vite";
import { createRenderer, ref, nextTick } from "vue";
let vite, useWebClientPerformance, app, monitor, connected, measure;
const intervals = new Map();
const originalWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
const renderer = createRenderer({
createComment: text => ({ text }), createText: text => ({ text }), createElement: () => ({}),
insert() {}, remove() {}, setText() {}, setElementText() {}, patchProp() {}, parentNode: () => null, nextSibling: () => null,
});
const deferred = () => {
let resolve;
const promise = new Promise(done => { resolve = done; });
return { promise, resolve };
};
function sample(extra = {}, bridge = {}, browser = {}) {
return {
scopeId: 1, sampledAt: 1_000, transport: "webrtc", connectionState: "connected",
microphoneMuted: false, microphoneReady: true, microphonePermission: "granted", playbackState: "playing",
bridge: { transport: "webrtc", tsSendFrames: 0, tsSendErrors: 0, egressFrames: 0,
ingressDroppedFrames: 0, egressDroppedFrames: 0, webrtcIngressDecodeErrors: 0,
webrtcDownlinkDecodeErrors: 0, webrtcQueueDroppedFrames: 0, webrtcQueueUnderrunTicks: 0,
ingressMaxGapMs: 0, egressMaxGapMs: 0, ...bridge },
browser: { outboundBytes: 0, outboundPackets: 0, outboundPacketsLost: 0, outboundLossPercent: 0,
outboundRttMs: 20, inboundBytes: 0, inboundPackets: 0, inboundPacketsLost: 0, inboundLossPercent: 0,
inboundJitterMs: 5, concealedSamples: 0, ...browser },
fallbackPlayback: { framesReceived: 0, framesDropped: 0, decodeErrors: 0 },
...extra,
};
}
before(async () => {
vite = await createServer({ configFile: false, root: fileURLToPath(new URL("../", import.meta.url)),
server: { middlewareMode: true, hmr: false, ws: false, watch: null }, optimizeDeps: { noDiscovery: true, include: [] }, appType: "custom" });
({ useWebClientPerformance } = await vite.ssrLoadModule("/src/composables/useWebClientPerformance.ts"));
});
beforeEach(t => {
intervals.clear();
Object.defineProperty(globalThis, "window", { configurable: true, value: {
setInterval(callback, delay) { assert.equal(delay, 2_000); const timer = {}; intervals.set(timer, callback); return timer; },
} });
const clear = globalThis.clearInterval;
t.mock.method(globalThis, "clearInterval", timer => { if (!intervals.delete(timer)) clear(timer); });
connected = ref(true);
measure = async () => sample();
});
afterEach(() => { app?.unmount(); app = null; });
after(async () => {
await vite?.close();
if (originalWindow) Object.defineProperty(globalThis, "window", originalWindow);
else delete globalThis.window;
});
async function mount() {
app = renderer.createApp({ setup() { monitor = useWebClientPerformance(connected, () => measure()); return () => null; } });
app.mount({});
await nextTurn();
}
async function refresh(value) {
measure = async () => value;
monitor.refresh();
await nextTurn();
}
test("transport changes do not subtract RTP packets from compatibility frames", async () => {
measure = async () => sample({}, {}, { inboundPackets: 20 });
await mount();
await refresh(sample({ transport: "websocket", sampledAt: 3_000,
fallbackPlayback: { framesReceived: 200, framesDropped: 0, decodeErrors: 0 } }));
assert.equal(monitor.stats.value.downlinkFramesPerSecond, null);
assert.equal(monitor.stats.value.health, "quiet");
});
test("replacement peers and reconnects start a fresh counter baseline", async () => {
await mount();
await refresh(sample({ scopeId: 2, sampledAt: 3_000 }, { tsSendFrames: 500, tsSendErrors: 10 },
{ outboundBytes: 50_000, inboundBytes: 40_000, inboundPackets: 200 }));
assert.equal(monitor.stats.value.uplinkFramesPerSecond, null);
assert.equal(monitor.stats.value.uplinkBitrateKbps, null);
assert.equal(monitor.stats.value.downlinkFramesPerSecond, null);
assert.equal(monitor.stats.value.sendErrors, null);
assert.equal(monitor.stats.value.health, "quiet");
await refresh(sample({ scopeId: 2, sampledAt: 5_000 }, { tsSendFrames: 600, tsSendErrors: 10 },
{ outboundBytes: 58_000, inboundBytes: 44_000, inboundPackets: 300 }));
assert.equal(monitor.stats.value.uplinkFramesPerSecond, 50);
assert.equal(monitor.stats.value.downlinkFramesPerSecond, 50);
assert.equal(monitor.stats.value.uplinkBitrateKbps, 32);
assert.equal(monitor.stats.value.health, "active");
});
test("temporarily missing RTP stats do not turn bridge counters into packet deltas", async () => {
measure = async () => sample({}, { egressFrames: 1_000 }, { inboundPackets: 20 });
await mount();
await refresh(sample({ sampledAt: 3_000, browser: null }, { egressFrames: 1_100 }));
assert.equal(monitor.stats.value.downlinkFramesPerSecond, null);
await refresh(sample({ sampledAt: 5_000, browser: null }, { egressFrames: 1_200 }));
assert.equal(monitor.stats.value.downlinkFramesPerSecond, 50);
});
test("a missing sample clears stale activity and a later sample starts a new baseline", async () => {
await mount();
await refresh(sample({ sampledAt: 3_000 }, { tsSendFrames: 100 }));
assert.equal(monitor.stats.value.health, "active");
await refresh(null);
assert.equal(monitor.stats.value.ready, false);
assert.equal(monitor.stats.value.health, "sampling");
assert.equal(monitor.running.value, false);
await refresh(sample({ sampledAt: 7_000 }, { tsSendFrames: 300 }));
assert.equal(monitor.stats.value.uplinkFramesPerSecond, null);
});
test("a rejected probe is contained and the next refresh can recover", async () => {
await mount();
measure = async () => { throw new Error("Stats unavailable"); };
monitor.refresh();
await nextTurn();
assert.equal(monitor.stats.value.ready, false);
assert.equal(monitor.running.value, false);
await refresh(sample());
assert.equal(monitor.stats.value.ready, true);
});
test("a queued old polling callback cannot start work or wedge a replacement connection", async () => {
let calls = 0;
measure = async () => { calls++; return sample(); };
await mount();
const oldTick = [...intervals.values()][0];
connected.value = false;
await nextTick();
assert.equal(intervals.size, 0);
connected.value = true;
await nextTurn();
const callsBefore = calls;
oldTick();
await nextTurn();
assert.equal(calls, callsBefore);
assert.equal(monitor.running.value, false);
monitor.refresh();
await nextTurn();
assert.equal(calls, callsBefore + 1);
});
test("unmount retires pending results, queued timers and manual refresh", async () => {
const pending = deferred();
let calls = 0;
measure = () => { calls++; return pending.promise; };
await mount();
const oldTick = [...intervals.values()][0];
app.unmount();
app = null;
assert.equal(intervals.size, 0);
oldTick();
monitor.refresh();
pending.resolve(sample());
await nextTurn();
assert.equal(calls, 1);
assert.equal(monitor.running.value, false);
assert.equal(monitor.stats.value.ready, false);
});
test("late samples from an old connection cannot replace current diagnostics", async () => {
const pending = deferred();
measure = () => pending.promise;
await mount();
connected.value = false;
await nextTick();
measure = async () => sample({ scopeId: 2, transport: "websocket" });
connected.value = true;
await nextTurn();
pending.resolve(sample({ scopeId: 1, connectionState: "failed" }));
await nextTurn();
assert.equal(monitor.stats.value.transport, "websocket");
assert.equal(monitor.stats.value.health, "quiet");
assert.equal(monitor.running.value, false);
});
test("uplink loss uses sent packets while downlink loss includes missing packets", async () => {
await mount();
await refresh(sample({ sampledAt: 3_000 }, {}, {
outboundPackets: 100, outboundPacketsLost: 20, inboundPackets: 80, inboundPacketsLost: 20,
}));
assert.equal(monitor.stats.value.uplinkLossPercent, 20);
assert.equal(monitor.stats.value.downlinkLossPercent, 20);
});
test("normal counters preserve activity, warning and playback diagnostics", async () => {
await mount();
await refresh(sample({ sampledAt: 3_000, playbackState: "paused" }, { tsSendFrames: 100 }, { inboundPackets: 100 }));
assert.equal(monitor.stats.value.uplinkFramesPerSecond, 50);
assert.equal(monitor.stats.value.downlinkFramesPerSecond, 50);
assert.equal(monitor.stats.value.health, "warning");
assert.equal(monitor.stats.value.uplinkRttMs, 20);
assert.equal(monitor.stats.value.downlinkJitterMs, 5);
connected.value = false;
await nextTick();
assert.equal(monitor.stats.value.health, "disconnected");
assert.equal(monitor.stats.value.ready, false);
});
+56 -1
View File
@@ -166,7 +166,7 @@ before(async () => {
vite = await createServer({
configFile: false,
root: fileURLToPath(new URL("../", import.meta.url)),
server: { middlewareMode: true, hmr: false, watch: null },
server: { middlewareMode: true, hmr: false, ws: false, watch: null },
optimizeDeps: { noDiscovery: true, include: [] },
appType: "custom",
});
@@ -1220,6 +1220,7 @@ test("a current audio probe retains browser metrics and accepts missing browser
assert.equal(sample.browser.outboundPackets, 10);
assert.equal(sample.browser.outboundBytes, 100);
assert.equal(sample.browser.outboundRttMs, 50);
assert.equal(sample.browser.outboundLossPercent, 20);
peer.getStats = async () => { throw new Error("Stats unavailable"); };
const missing = voice.measureVoiceAudioStatus();
const nextRequest = socket.messages.filter(message => message.type === "audioStatsProbe").at(-1);
@@ -1227,6 +1228,60 @@ test("a current audio probe retains browser metrics and accepts missing browser
assert.equal((await missing).browser, null);
});
async function audioSample(socket, bridge = {}) {
const pending = voice.measureVoiceAudioStatus();
const request = socket.messages.filter(message => message.type === "audioStatsProbe").at(-1);
socket.receive({ type: "audioStats", sequence: request.payload.sequence, stats: { transport: "websocket", ...bridge } });
return pending;
}
test("diagnostic sample scopes follow peer replacement and fallback on one socket", async () => {
const { socket } = await connectWebRtc();
const first = await audioSample(socket);
const next = await audioSample(socket);
assert.equal(typeof first.scopeId, "number");
assert.equal(next.scopeId, first.scopeId);
await voice.setInputDevice("replacement");
const replaced = await audioSample(socket);
assert.notEqual(replaced.scopeId, first.scopeId);
socket.receive({ type: "webrtcError", code: "WEBRTC_UNAVAILABLE" });
await nextTurn();
const fallback = await audioSample(socket);
assert.notEqual(fallback.scopeId, replaced.scopeId);
assert.equal(fallback.transport, "websocket");
});
test("session recovery resets compatibility diagnostics without mutating old snapshots", async () => {
const socket = await connect();
socket.receive({ type: "connected", tsClientId: 1 });
await nextTurn();
receiveAudio(socket);
receiveAudio(socket);
socket.onmessage({ data: new Uint8Array([1, 2]).buffer });
const previous = await audioSample(socket);
assert.equal(previous.fallbackPlayback.framesReceived, 2);
assert.equal(previous.fallbackPlayback.framesDropped, 1);
socket.receive({ type: "disconnected", recoverable: true });
socket.receive({ type: "connected", tsClientId: 2 });
await nextTurn();
const current = await audioSample(socket);
assert.notEqual(current.scopeId, previous.scopeId);
assert.deepEqual(current.fallbackPlayback, { framesReceived: 0, framesDropped: 0, decodeErrors: 0 });
assert.equal(previous.fallbackPlayback.framesReceived, 2);
});
test("a probe started before peer allocation cannot survive a failed transport attempt", async t => {
t.mock.method(TestPeer.prototype, "createOffer", async () => { throw new Error("Offer unavailable"); });
const socket = await connect();
socket.receive({ type: "connected", tsClientId: 1, webrtcAvailable: true });
const pending = voice.measureVoiceAudioStatus();
const request = socket.messages.filter(message => message.type === "audioStatsProbe").at(-1);
await nextTurn();
assert.equal(TestPeer.instances.at(-1).connectionState, "closed");
socket.receive({ type: "audioStats", sequence: request.payload.sequence, stats: { transport: "websocket" } });
assert.equal(await pending, null);
});
test("disconnect clears the WebRTC answer deadline immediately", async () => {
await connectWebRtc();
assert.ok(browserTimers.size > 0);