fix: improve voice playback, diagnostics and workspace controls

This commit is contained in:
illusia committed 2026-11-13 19:49:31 +08:00
1 parent 72d7e6e013
commit e82116239a
34 files changed
+502 -147

No files matched your search

+1 -1
View File
@@ -388,7 +388,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
| --- | --- |
| 通用 | `app`、`app.toast`、`control`、`skin.trigger`、`skin.menu`、`skin.option`、`language.trigger`、`language.menu`、`language.option` |
| 首页 | `home`、`home.header`、`home.brand`、`home.header-tools`、`home.gateway-status`、`home.content`、`home.hero`、`home.hero.eyebrow`、`home.hero.title`、`home.hero.description`、`home.features`、`home.feature`、`home.visitors`、`home.visitors.orbit`、`home.visitors.icon`、`home.visitors.label`、`home.visitors.divider`、`home.visitors.total`、`home.visitors.spark`、`home.join-card`、`home.join-card.waveform`、`home.join-card.sonar`、`home.join-title`、`home.join-description`、`home.notice`、`home.form`、`home.server-target`、`home.field-label`、`home.field`、`home.relay-choice`、`home.relay-choice.copy`、`home.server-history`、`home.server-history.group`、`home.server-history.item`、`home.server-history.select`、`home.server-history.favorite-toggle`、`home.favorite-toggle`、`home.identity`、`home.identity-actions`、`home.identity-provider.button`、`home.identity-provider.label`、`home.identity-import.open`、`home.identity-export.button`、`home.identity-import-dialog`、`home.identity-import.header`、`home.identity-import.close`、`home.identity-import.textarea`、`home.identity-import.drop-zone`、`home.identity-import.file-button`、`home.identity-import.error`、`home.identity-import.security`、`home.identity-import.footer`、`home.identity-import.cancel`、`home.identity-import.submit`、`home.server-announcement`、`home.server-announcement.title`、`home.server-announcement.body`、`home.social-links`、`home.connection-status`、`home.connect`、`home.security-note`、`home.footer`、`home.community-dialog` |
| 语音工作区 | `voice.shell`、`voice.workspace`、`voice.header`、`voice.header-actions`、`voice.breadcrumbs`、`voice.performance`、`voice.performance.panel`、`voice.performance.route`、`voice.performance.metrics`、`voice.performance.status`、`voice.performance.webrtc-stats`、`voice.connection-status`、`voice.audio-status`、`voice.poke`、`voice.scroll`、`voice.content`、`voice.activity`、`voice.activity.artwork`、`voice.activity-heading`、`voice.screen-share-error`、`voice.members`、`voice.members.empty`、`voice.member`、`voice.member.action-trigger`、`voice.member.avatar-wrap`、`voice.member.avatar`、`voice.member.mic-status`、`voice.member.name`、`voice.member.status`、`voice.member.live-indicator`、`voice.member.stop-share`、`voice.member.share-actions`、`voice.member-panel`、`voice.member-panel.heading`、`voice.member-panel.search`、`voice.member-panel.channels`、`voice.channel-group`、`voice.channel-group.heading`、`voice.channel-group.members`、`voice.member-row`、`voice.member-row.avatar`、`voice.member-row.copy`、`voice.member-row.flags`、`voice.member-row.volume`、`voice.whisper-strip`、`voice.audio-dock`、`voice.audio-dock.microphone`、`voice.audio-dock.microphone-panel`、`voice.audio-dock.output`、`voice.audio-dock.output-panel`、`voice.audio-settings`、`voice.audio-settings.device-select`、`voice.audio-settings.device-select-trigger`、`voice.audio-settings.device-select-chevron`、`voice.audio-settings.device-select-menu`、`voice.audio-settings.device-select-option`、`voice.mobile-more`、`voice.mobile-nav` |
| 语音工作区 | `voice.shell`、`voice.workspace`、`voice.header`、`voice.header-actions`、`voice.plugin-toolbar`、`voice.breadcrumbs`、`voice.performance`、`voice.performance.panel`、`voice.performance.route`、`voice.performance.metrics`、`voice.performance.status`、`voice.performance.webrtc-stats`、`voice.connection-status`、`voice.audio-status`、`voice.poke`、`voice.scroll`、`voice.content`、`voice.activity`、`voice.activity.artwork`、`voice.activity-heading`、`voice.screen-share-error`、`voice.members`、`voice.members.empty`、`voice.member`、`voice.member.action-trigger`、`voice.member.avatar-wrap`、`voice.member.avatar`、`voice.member.mic-status`、`voice.member.name`、`voice.member.status`、`voice.member.live-indicator`、`voice.member.stop-share`、`voice.member.share-actions`、`voice.member-panel`、`voice.member-panel.heading`、`voice.member-panel.search`、`voice.member-panel.channels`、`voice.channel-group`、`voice.channel-group.heading`、`voice.channel-group.members`、`voice.member-row`、`voice.member-row.avatar`、`voice.member-row.copy`、`voice.member-row.flags`、`voice.member-row.volume`、`voice.whisper-strip`、`voice.audio-dock`、`voice.audio-dock.microphone`、`voice.audio-dock.microphone-panel`、`voice.audio-dock.output`、`voice.audio-dock.output-panel`、`voice.audio-settings`、`voice.audio-settings.device-select`、`voice.audio-settings.device-select-trigger`、`voice.audio-settings.device-select-chevron`、`voice.audio-settings.device-select-menu`、`voice.audio-settings.device-select-option`、`voice.mobile-more`、`voice.mobile-nav` |
| KOOK 频道树与服务器切换 | `voice.server-switcher`、`voice.server-switcher.trigger`、`voice.server-switcher.menu`、`voice.server-switcher.item`、`voice.server-switcher.icon`、`voice.server-switcher.label`、`voice.server-switcher.current`、`voice.server-switcher.empty`、`voice.channel-tree.list`、`voice.channel-tree.empty`、`voice.channel-tree.node`、`voice.channel-tree.line`、`voice.channel-tree.expander`、`voice.channel-tree.row`、`voice.channel-tree.icon`、`voice.channel-tree.join-hint`、`voice.channel-tree.name`、`voice.channel-tree.count`、`voice.channel-tree.branch`、`voice.channel-tree.member`、`voice.channel-tree.avatar`、`voice.channel-tree.member-name`、`voice.channel-tree.member-muted`、`voice.channel-tree.member-screen-share`、`voice.channel-tree.member-speaking`、`voice.channel-tree.member-away` |
| 快速服务器 | `voice.favorite-servers.rail`、`voice.favorite-servers.rail.list`、`voice.favorite-servers.rail.item`、`voice.favorite-servers.server`、`voice.favorite-servers.avatar`、`voice.favorite-servers.tooltip`、`voice.favorite-servers.favorite-toggle`、`voice.favorite-servers.add`、`voice.favorite-servers.strip`、`voice.favorite-servers.strip.item`、`voice.favorite-servers.strip.server`、`voice.favorite-servers.strip.favorite-toggle`、`voice.favorite-servers.strip.add`、`voice.favorite-servers.switch-status`、`voice.favorite-servers.current-toggle`、`voice.favorite-servers.dialog-backdrop`、`voice.favorite-servers.dialog`、`voice.favorite-servers.dialog.header`、`voice.favorite-servers.dialog.close`、`voice.favorite-servers.dialog.form`、`voice.favorite-servers.dialog.field`、`voice.favorite-servers.dialog.input`、`voice.favorite-servers.dialog.target`、`voice.favorite-servers.dialog.hint`、`voice.favorite-servers.dialog.actions`、`voice.favorite-servers.dialog.cancel`、`voice.favorite-servers.dialog.submit` |
| 聊天与菜单 | `voice.chat`、`voice.chat.tabs`、`voice.chat.tab`、`voice.chat.heading`、`voice.chat.messages`、`voice.chat.event`、`voice.chat.message`、`voice.chat.message-avatar`、`voice.chat.message-body`、`voice.chat.message-bubble`、`voice.chat.empty`、`voice.chat.composer`、`voice.chat.status`、`voice.context-menu-backdrop`、`voice.context-menu`、`voice.context-menu.header`、`voice.context-menu.move-submenu` |
+14 -4
View File
@@ -28,7 +28,17 @@ export class PluginRegistry {
const manifest=parsePluginManifest(v.manifest);pluginAssert(file===`${manifest.id}.json`&&typeof v.packageDigest==='string'&&/^[a-f0-9]{64}$/.test(v.packageDigest)&&typeof v.serverConfigCiphertext==='string'&&typeof v.installedAt==='number'&&Number.isFinite(v.installedAt));
const settings=this.settings(v.settings,manifest,!!v.serverConfigCiphertext);
const record={schemaVersion:2 as const,manifest,settings,packageDigest:v.packageDigest,serverConfigCiphertext:v.serverConfigCiphertext,installedAt:v.installedAt,revision:''};
this.readSecret(record);record.revision=this.hash(record);pluginAssert(record.revision===v.revision);this.records.set(manifest.id,record);
this.readSecret(record);
if (pluginRecord(v.settings) && v.settings.toolbarPinned === undefined) {
const legacyHash=createHash("sha256").update(JSON.stringify({manifest,settings:v.settings,packageDigest:v.packageDigest,serverConfigCiphertext:v.serverConfigCiphertext,installedAt:v.installedAt})).digest("hex");
pluginAssert(legacyHash===v.revision);
record.revision="";
this.records.set(manifest.id,record);
try { await this.commit(record); }
catch { /* keep the migrated record usable in memory if disk replacement fails */ }
} else {
record.revision=this.hash(record);pluginAssert(record.revision===v.revision);this.records.set(manifest.id,record);
}
} catch { /* Invalid or obsolete packages are never executed. */ }
}
}
@@ -41,12 +51,12 @@ export class PluginRegistry {
return createHash('sha256').update(JSON.stringify({manifest:record.manifest,settings:record.settings,packageDigest:record.packageDigest,serverConfigCiphertext:record.serverConfigCiphertext,installedAt:record.installedAt})).digest('hex');
}
private settings(value: unknown, manifest: StoredPlugin['manifest'], hasServerConfig: boolean): PluginSettings {
pluginAssert(pluginRecord(value)&&typeof value.enabled==='boolean'&&typeof value.trusted==='boolean'&&manifest.scopes.includes(value.scope as never));
pluginAssert(pluginRecord(value)&&typeof value.enabled==='boolean'&&typeof value.trusted==='boolean'&&(value.toolbarPinned===undefined||typeof value.toolbarPinned==='boolean')&&manifest.scopes.includes(value.scope as never));
pluginAssert(Array.isArray(value.targets)&&value.targets.length<=50&&value.targets.every(t=>typeof t==='string'&&t.length<=300));
let targets:string[];try{targets=[...new Set(value.targets.map(t=>teamSpeakTargetKey(parseTeamSpeakTarget(t))))];}catch{throw new PluginError('PLUGIN_TARGET_INVALID');}
pluginAssert(!value.enabled||value.trusted,'PLUGIN_TRUST_REQUIRED');
pluginAssert(value.scope!=='server'||!value.enabled||targets.length>0,'PLUGIN_TARGET_REQUIRED');
return {enabled:value.enabled,trusted:value.trusted,scope:value.scope as PluginSettings['scope'],targets,config:parsePluginJson(value.config),hasServerConfig};
return {enabled:value.enabled,trusted:value.trusted,toolbarPinned:value.toolbarPinned===true,scope:value.scope as PluginSettings['scope'],targets,config:parsePluginJson(value.config),hasServerConfig};
}
private readSecret(record: StoredPlugin): JsonValue {
const text=decryptSecret(record.serverConfigCiphertext,this.masterKey,`webspeak:plugin-config:v2:${record.manifest.id}`);
@@ -66,7 +76,7 @@ export class PluginRegistry {
await mkdir(directory,{recursive:true});const file=path.join(directory,`${digest}.wplugin`);
try{await writeFile(file,bytes,{flag:'wx',mode:0o600});}catch(error){if(!(error&&typeof error==='object'&&'code'in error&&error.code==='EEXIST'))throw error;}
const old=previous?.settings;
const settings={enabled:false,trusted:false,scope:old&&pack.manifest.scopes.includes(old.scope)?old.scope:pack.manifest.scopes[0],targets:old?.targets??[],config:old?.config??{},hasServerConfig:!!previous?.serverConfigCiphertext};
const settings={enabled:false,trusted:false,toolbarPinned:old?.toolbarPinned??false,scope:old&&pack.manifest.scopes.includes(old.scope)?old.scope:pack.manifest.scopes[0],targets:old?.targets??[],config:old?.config??{},hasServerConfig:!!previous?.serverConfigCiphertext};
return this.commit({schemaVersion:2,manifest:pack.manifest,settings,packageDigest:digest,serverConfigCiphertext:previous?.serverConfigCiphertext??'',installedAt:previous?.installedAt??Date.now(),revision:''});
});}
configure(id:string,input:unknown,revision:string):Promise<InstalledPlugin>{return this.mutate(async()=>{
+1 -1
View File
@@ -105,7 +105,7 @@ export class PluginRuntime {
async restart(id:string):Promise<void>{this.revokePlugin(id,"PLUGIN_RESTARTED");const entry=this.entries.get(id);if(entry)entry.stale=true;await this.synchronize(id);}
directory(voiceToken:string) {
const participant=this.options.participant(voiceToken);pluginAssert(participant,"PLUGIN_NOT_CONNECTED");
return this.options.registry.list().filter(policy=>{try{this.scopeKey(policy,participant);return true;}catch{return false;}}).map(policy=>({manifest:policy.manifest,scope:policy.settings.scope,runtime:this.status(policy.manifest.id)}));
return this.options.registry.list().filter(policy=>{try{this.scopeKey(policy,participant);return true;}catch{return false;}}).map(policy=>({manifest:policy.manifest,scope:policy.settings.scope,toolbarPinned:policy.settings.toolbarPinned,runtime:this.status(policy.manifest.id)}));
}
private scopeKey(policy:InstalledPlugin,participant:PluginParticipant):string{
pluginAssert(policy.settings.enabled&&policy.settings.trusted,"PLUGIN_DISABLED");
+1
View File
@@ -116,6 +116,7 @@ function fixture() {
closed: false, closePromise: null, audioTimer: null, activityTimer: undefined,
pendingFrames: new Map([[1, []]]), memberVolumes: new Map([[1, 1]]),
partialPcmByClient: new Map([[1, Buffer.alloc(2)]]), activeSpeakerIds: new Set([1]),
decoderCodecByClient: new Map([[1, 4], [2, 5]]),
decoderByClient: new Map([
[1, { dispose() { released.push("decoder-1"); throw new Error("Decoder failed"); } }],
[2, { dispose() { released.push("decoder-2"); } }],
+40 -10
View File
@@ -11,13 +11,15 @@ import type { TSVoiceData } from "./ts-client.js";
import { WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
import { OpusEncoder } from "./opus-codec.js";
import type { WebRtcSessionDescription } from "../shared/webrtc.js";
import { addOpusFmtpParameters } from "../shared/opus-sdp.js";
export type { WebRtcSessionDescription } from "../shared/webrtc.js";
export { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
const AUDIO_SAMPLE_RATE = 48_000;
const AUDIO_FRAME_SAMPLES = 960;
const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * 2;
const AUDIO_CHANNELS = 2;
const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * AUDIO_CHANNELS * 2;
const DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE = 111;
const AUDIO_CLOCK_INTERVAL_MS = 20;
const SPEAKER_ACTIVITY_INTERVAL_MS = 100;
@@ -102,6 +104,7 @@ export class WebRtcAudioSession {
private readonly onVoiceActivity: (clientIds: number[]) => void;
private readonly outgoingTrack: MediaStreamTrack;
private readonly decoderByClient = new Map<number, OpusEncoder>();
private readonly decoderCodecByClient = new Map<number, 4 | 5>();
private readonly partialPcmByClient = new Map<number, Buffer>();
private readonly pendingFrames = new Map<number, PendingAudioFrame[]>();
private readonly memberVolumes = new Map<number, number>();
@@ -198,7 +201,7 @@ export class WebRtcAudioSession {
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not prepare WebRTC output track");
});
const createEncoder = options.createEncoder ?? (() => new OpusEncoder(AUDIO_SAMPLE_RATE, 1));
const createEncoder = options.createEncoder ?? (() => new OpusEncoder(AUDIO_SAMPLE_RATE, AUDIO_CHANNELS));
try {
this.encoder = createEncoder();
} catch (error: unknown) {
@@ -240,22 +243,37 @@ export class WebRtcAudioSession {
this.outgoingPayloadType = opus[0]!.payloadType;
await transceiver.sender.replaceTrack(this.outgoingTrack);
const answer = await this.peer.createAnswer();
await this.peer.setLocalDescription(answer);
await this.peer.setLocalDescription({
...answer,
sdp: addOpusFmtpParameters(answer.sdp ?? "", ["stereo=1", "sprop-stereo=1"]),
});
const description = this.peer.localDescription;
if (!description) throw new Error("WebRTC answer was not created");
if (description.type !== "answer" && description.type !== "offer") throw new Error("Unexpected WebRTC answer type");
return { type: description.type, sdp: description.sdp };
return {
type: description.type,
sdp: addOpusFmtpParameters(description.sdp, ["stereo=1", "sprop-stereo=1"]),
};
}
pushTeamSpeakVoice(data: TSVoiceData): void {
if (this.closed || (data.codec !== 4 && data.codec !== 5)) return;
let decoder = this.decoderByClient.get(data.clientId);
if (decoder && this.decoderCodecByClient.get(data.clientId) !== data.codec) {
try { decoder.dispose(); } catch { /* a codec transition must still reset queued PCM */ }
this.decoderByClient.delete(data.clientId);
this.decoderCodecByClient.delete(data.clientId);
this.partialPcmByClient.delete(data.clientId);
this.pendingFrames.delete(data.clientId);
decoder = undefined;
}
if (!decoder) {
try {
// @discordjs/opus exposes decoding on OpusEncoder instances too;
// there is no separate OpusDecoder constructor in that package.
decoder = new OpusEncoder(AUDIO_SAMPLE_RATE, 1);
decoder = new OpusEncoder(AUDIO_SAMPLE_RATE, data.codec === 4 ? 1 : 2);
this.decoderByClient.set(data.clientId, decoder);
this.decoderCodecByClient.set(data.clientId, data.codec);
} catch (error: unknown) {
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not create WebRTC mixer decoder");
return;
@@ -264,16 +282,26 @@ export class WebRtcAudioSession {
try {
const pcm = decoder.decode(data.data);
this.stats.webrtcDownlinkDecodedFrames++;
if (pcm.length < 2) {
const inputChannels = data.codec === 4 ? 1 : 2;
if (pcm.length < inputChannels * 2 || pcm.length % (inputChannels * 2) !== 0) {
this.stats.webrtcDownlinkShortFrames++;
return;
}
let stereoPcm = pcm;
if (inputChannels === 1) {
stereoPcm = Buffer.allocUnsafe(pcm.length * AUDIO_CHANNELS);
for (let inputOffset = 0, outputOffset = 0; inputOffset < pcm.length; inputOffset += 2, outputOffset += 4) {
const sample = pcm.readInt16LE(inputOffset);
stereoPcm.writeInt16LE(sample, outputOffset);
stereoPcm.writeInt16LE(sample, outputOffset + 2);
}
}
// TeamSpeak may deliver 10/20/40/60 ms Opus frames. Keep a partial
// decoded frame per speaker and split every decoded buffer into the
// fixed 20 ms cadence used by the WebRTC mixer instead of discarding
// anything after the first 20 ms.
const pendingPcm = this.partialPcmByClient.get(data.clientId);
const combined = pendingPcm ? Buffer.concat([pendingPcm, pcm]) : pcm;
const combined = pendingPcm ? Buffer.concat([pendingPcm, stereoPcm]) : stereoPcm;
const rms = this.calculateRms(pcm);
// RMS is used only for the UI speaking indicator. Every decoded frame,
// including quiet/comfort-noise frames, continues into the queue so the
@@ -326,6 +354,7 @@ export class WebRtcAudioSession {
this.closePromise = Promise.resolve().then(async () => {
const decoders = [...this.decoderByClient.values()];
this.decoderByClient.clear();
this.decoderCodecByClient.clear();
for (const decoder of decoders) {
try { decoder.dispose(); } catch { /* continue releasing other resources */ }
}
@@ -368,13 +397,13 @@ export class WebRtcAudioSession {
this.stats.webrtcQueueUnderrunTicks++;
}
}
const mixed = new Int32Array(AUDIO_FRAME_SAMPLES);
const mixed = new Int32Array(AUDIO_FRAME_SAMPLES * AUDIO_CHANNELS);
for (const [clientId, queue] of this.pendingFrames) {
const frame = queue.shift();
if (queue.length === 0) this.pendingFrames.delete(clientId);
if (!frame) continue;
const volume = this.memberVolumes.get(clientId) ?? 1;
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) {
for (let index = 0; index < AUDIO_FRAME_SAMPLES * AUDIO_CHANNELS; index++) {
mixed[index] += Math.round(frame.pcm.readInt16LE(index * 2) * volume);
}
}
@@ -383,7 +412,7 @@ export class WebRtcAudioSession {
// source packets with our encoded silence/mixes corrupts decoder history
// and can suppress otherwise valid speech without any packet loss.
const pcm = Buffer.allocUnsafe(AUDIO_FRAME_BYTES);
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) {
for (let index = 0; index < AUDIO_FRAME_SAMPLES * AUDIO_CHANNELS; index++) {
// Keep a fixed gain for the mixed path. Per-sample soft limiting changes
// the waveform's apparent loudness as the source level changes, which
// is especially noticeable on music. Only clip actual overflow caused
@@ -450,6 +479,7 @@ export class WebRtcAudioSession {
const decoder = this.decoderByClient.get(clientId);
if (!decoder) return;
this.decoderByClient.delete(clientId);
this.decoderCodecByClient.delete(clientId);
try { decoder.dispose(); } catch { /* continue after codec cleanup failures */ }
}
+45
View File
@@ -0,0 +1,45 @@
/** Add Opus channel negotiation parameters to audio payloads in an SDP document. */
export function addOpusFmtpParameters(sdp: string, parameters: readonly string[]): string {
if (!sdp || parameters.length === 0) return sdp;
const lines = sdp.split(/\r?\n/);
const output: string[] = [];
let section: string[] = [];
const flush = () => {
if (section[0]?.startsWith("m=audio ")) patchAudioSection(section, parameters);
output.push(...section);
section = [];
};
for (const line of lines) {
if (line.startsWith("m=")) {
if (section.length) flush();
}
section.push(line);
}
if (section.length) flush();
return output.join("\r\n");
}
function patchAudioSection(section: string[], parameters: readonly string[]): void {
const payloads = new Set(section[0]!.trim().split(/\s+/).slice(3));
const opusPayloads = section.flatMap(line => {
const match = /^a=rtpmap:(\d+)\s+opus\/48000(?:\/\d+)?\s*$/i.exec(line);
return match && payloads.has(match[1]!) ? [match[1]!] : [];
});
for (const payload of opusPayloads) {
const prefix = `a=fmtp:${payload}`;
const index = section.findIndex(line => new RegExp(`^${prefix}(?:\\s|$)`).test(line));
if (index < 0) {
const rtpmap = section.findIndex(line => line.startsWith(`a=rtpmap:${payload} `));
if (rtpmap >= 0) section.splice(rtpmap + 1, 0, `${prefix} ${parameters.join(";")}`);
continue;
}
const parts = section[index]!.slice(prefix.length).trim().split(";").filter(Boolean);
for (const parameter of parameters) {
const name = parameter.split("=", 1)[0]!.trim().toLowerCase();
const existing = parts.findIndex(part => part.split("=", 1)[0]!.trim().toLowerCase() === name);
if (existing < 0) parts.push(parameter);
else parts[existing] = parameter;
}
section[index] = `${prefix} ${parts.join(";")}`;
}
}
+4 -4
View File
@@ -15,9 +15,9 @@ export interface PluginManifest {
}
export interface PluginFile { encoding: "utf8" | "base64"; data: string }
export interface PluginPackage { manifest: PluginManifest; files: Record<string, PluginFile> }
export interface PluginSettings { enabled: boolean; trusted: boolean; scope: PluginScope; targets: string[]; config: JsonValue; hasServerConfig: boolean }
export interface PluginSettings { enabled: boolean; trusted: boolean; toolbarPinned: boolean; scope: PluginScope; targets: string[]; config: JsonValue; hasServerConfig: boolean }
export interface PluginSettingsInput {
enabled: boolean; trusted: boolean; scope: PluginScope; targets: string[]; config: JsonValue;
enabled: boolean; trusted: boolean; toolbarPinned?: boolean; scope: PluginScope; targets: string[]; config: JsonValue;
serverConfigAction?: "keep" | "replace" | "remove"; serverConfig?: JsonValue;
}
export interface PluginRuntimeStatus { state: "disabled" | "client" | "stopped" | "starting" | "running" | "failed"; error?: string }
@@ -95,8 +95,8 @@ export function parsePluginJson(v: unknown, maxBytes = 64 * 1024): JsonValue {
export function readInstalledPlugin(v: unknown): InstalledPlugin {
pluginAssert(pluginRecord(v) && pluginRecord(v.settings) && typeof v.revision === "string" && /^[a-f0-9]{64}$/.test(v.revision) && typeof v.installedAt === "number" && Number.isFinite(v.installedAt));
const manifest=parsePluginManifest(v.manifest),s=v.settings;
pluginAssert(typeof s.enabled === "boolean" && typeof s.trusted === "boolean" && typeof s.hasServerConfig === "boolean" && manifest.scopes.includes(s.scope as PluginScope) && Array.isArray(s.targets) && s.targets.length <= 50 && s.targets.every(t=>typeof t === "string" && t.length <= 300));
const result: InstalledPlugin={manifest,revision:v.revision,installedAt:v.installedAt,settings:{enabled:s.enabled,trusted:s.trusted,scope:s.scope as PluginScope,targets:[...s.targets],config:parsePluginJson(s.config),hasServerConfig:s.hasServerConfig}};
pluginAssert(typeof s.enabled === "boolean" && typeof s.trusted === "boolean" && (s.toolbarPinned === undefined || typeof s.toolbarPinned === "boolean") && typeof s.hasServerConfig === "boolean" && manifest.scopes.includes(s.scope as PluginScope) && Array.isArray(s.targets) && s.targets.length <= 50 && s.targets.every(t=>typeof t === "string" && t.length <= 300));
const result: InstalledPlugin={manifest,revision:v.revision,installedAt:v.installedAt,settings:{enabled:s.enabled,trusted:s.trusted,toolbarPinned:s.toolbarPinned===true,scope:s.scope as PluginScope,targets:[...s.targets],config:parsePluginJson(s.config),hasServerConfig:s.hasServerConfig}};
if(v.runtime!==undefined){pluginAssert(pluginRecord(v.runtime) && ["disabled","client","stopped","starting","running","failed"].includes(String(v.runtime.state)) && (v.runtime.error===undefined||typeof v.runtime.error==="string"));result.runtime={state:v.runtime.state as PluginRuntimeStatus["state"],...(v.runtime.error?{error:v.runtime.error as string}:{})};}
return result;
}
+1
View File
@@ -278,6 +278,7 @@ const PUBLIC_PART_IDS = new Set<string>([
"voice.favorite-servers.tooltip",
"voice.header",
"voice.header-actions",
"voice.plugin-toolbar",
"voice.member",
"voice.member-panel",
"voice.member-panel.channels",
+24 -24
View File
@@ -1,10 +1,14 @@
<template>
<Teleport to="#webspeak-plugin-toolbar">
<div v-if="thirdPartyAllowed && connected && sessionToken" class="ws-plugin-toolbar">
<button ref="launcher" class="header-action ws-plugin-toolbar-trigger" type="button" :title="tr('title')" :aria-label="tr('title')" :aria-expanded="visible" @click="toggle">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4zM14 14h6v6h-6z" /></svg>
</button>
<button v-for="entry in pinnedApps" :key="entry.manifest.id" class="header-action ws-plugin-toolbar-shortcut" type="button" :title="entry.manifest.name" :aria-label="entry.manifest.name" :disabled="busy || entry.runtime.state === 'failed'" @click="launch(entry.manifest.id)">{{ entry.manifest.name.slice(0, 1).toUpperCase() }}</button>
</div>
</Teleport>
<Teleport to="body">
<div v-if="thirdPartyAllowed && connected && sessionToken" class="ws-plugin-overlay" :data-plugin-theme="theme">
<button ref="launcher" class="ws-plugin-launcher" :style="launcherPosition" type="button" :title="tr('title')" :aria-label="tr('title')" :aria-expanded="visible" @pointerdown="startLauncherDrag" @lostpointercapture="endDrag" @click="toggle">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4zM14 14h6v6h-6z" /></svg>
<span>{{ tr('title') }}</span><i v-if="current" />
</button>
<section v-show="visible" ref="windowElement" class="ws-plugin-window" :class="{ 'is-maximized': maximized, 'is-dragging': dragging }" :style="position" role="dialog" :aria-label="current && appView ? current.manifest.name : tr('title')" tabindex="-1" @keydown.esc.stop="minimize">
<header class="ws-plugin-titlebar" @pointerdown="startDrag" @lostpointercapture="endDrag" @dblclick="toggleMaximize">
<span class="ws-plugin-mark" aria-hidden="true">◈</span>
@@ -55,14 +59,14 @@ const tr = (key: PluginTextKey) => pluginTranslations[props.language][key];
const ui = computed(() => pluginWindowTranslations[props.language]);
const windowElement = ref<HTMLElement | null>(null), launcher = ref<HTMLButtonElement | null>(null), frame = ref<HTMLIFrameElement | null>(null);
const available = shallowRef<AvailablePluginApp[]>([]), current = shallowRef<PluginAppLaunch | null>(null);
const pinnedApps = computed(() => available.value.filter(entry => entry.toolbarPinned));
const busy = ref(false), error = ref(''), theme = ref<'light' | 'dark'>('light');
const visible = ref(false), maximized = ref(false), appView = ref(false), dragging = ref(false), search = ref('');
const position = ref<Record<string, string>>({});
const launcherPosition = ref<Record<string, string>>({});
const filtered = computed(() => available.value.filter(entry => `${entry.manifest.name} ${entry.manifest.description}`.toLocaleLowerCase().includes(search.value.trim().toLocaleLowerCase())));
let epoch = 0, pending: AbortController | undefined, opening: { client: PluginAppClient; key: string } | undefined, observer: MutationObserver | undefined;
let drag: { id: number; x: number; y: number; left: number; top: number; handle: HTMLElement; kind: 'window' | 'launcher'; moved: boolean } | undefined;
let suppressLauncherClick = false, resizeObserver: ResizeObserver | undefined;
let drag: { id: number; x: number; y: number; left: number; top: number; handle: HTMLElement; moved: boolean } | undefined;
let resizeObserver: ResizeObserver | undefined;
const browserFeatures = computed(() => {
const policy = (document as Document & { featurePolicy?: { features(): string[] } }).featurePolicy;
const features = policy?.features() ?? ['fullscreen', 'autoplay', 'camera', 'microphone', 'display-capture', 'clipboard-read', 'clipboard-write', 'geolocation', 'screen-wake-lock'];
@@ -84,7 +88,6 @@ async function refresh() {
finally { if (owner === epoch) { busy.value = false; pending = undefined; } }
}
function toggle() {
if (suppressLauncherClick) { suppressLauncherClick = false; return; }
if (visible.value) { minimize(); return; }
detectTheme(); visible.value = true;
if (!current.value) { appView.value = false; void refresh(); }
@@ -98,6 +101,7 @@ function stop() {
}
async function launch(id: string) {
if (!thirdPartyAllowed.value) return;
detectTheme(); visible.value = true;
if (current.value?.manifest.id === id) { appView.value = true; return; }
stop(); const owner = ++epoch, controller = new AbortController(), service = client(), key = crypto.randomUUID(); pending = controller; opening = { client: service, key }; busy.value = true; error.value = '';
try {
@@ -115,10 +119,6 @@ function message(event: MessageEvent) {
}
function appearance() { if (current.value && opening) void opening.client.appearance(current.value.id, theme.value, props.language).catch(() => undefined); }
function fitWindow() {
if (launcher.value && launcherPosition.value.left) {
const box = launcher.value.getBoundingClientRect();
launcherPosition.value = { left: `${Math.max(8, Math.min(box.left, innerWidth - box.width - 8))}px`, top: `${Math.max(8, Math.min(box.top, innerHeight - box.height - 8))}px`, right: 'auto', bottom: 'auto' };
}
if (!visible.value || maximized.value || !windowElement.value) return;
const box = windowElement.value.getBoundingClientRect();
position.value = { left: `${Math.max(8, Math.min(box.left, innerWidth - box.width - 8))}px`, top: `${Math.max(8, Math.min(box.top, innerHeight - box.height - 8))}px`, transform: 'none' };
@@ -128,34 +128,34 @@ function startDrag(event: PointerEvent) {
if (event.button !== 0 || maximized.value || (event.target as HTMLElement).closest('button')) return;
const box = windowElement.value?.getBoundingClientRect(); if (!box) return;
event.preventDefault(); const handle = event.currentTarget as HTMLElement;
drag = { id: event.pointerId, x: event.clientX, y: event.clientY, left: box.left, top: box.top, handle, kind: 'window', moved: false }; dragging.value = true;
drag = { id: event.pointerId, x: event.clientX, y: event.clientY, left: box.left, top: box.top, handle, moved: false }; dragging.value = true;
handle.setPointerCapture(event.pointerId);
}
function startLauncherDrag(event: PointerEvent) {
if (event.button !== 0 || !launcher.value) return;
const box = launcher.value.getBoundingClientRect(); suppressLauncherClick = false;
drag = { id: event.pointerId, x: event.clientX, y: event.clientY, left: box.left, top: box.top, handle: launcher.value, kind: 'launcher', moved: false };
launcher.value.setPointerCapture(event.pointerId);
}
function moveDrag(event: PointerEvent) {
if (!drag || drag.id !== event.pointerId) return;
const target = drag.kind === 'launcher' ? launcher.value : windowElement.value; if (!target) return;
const target = windowElement.value; if (!target) return;
if (Math.hypot(event.clientX - drag.x, event.clientY - drag.y) < 5 && !drag.moved) return;
drag.moved = true; const box = target.getBoundingClientRect();
const next = { left: `${Math.max(8, Math.min(drag.left + event.clientX - drag.x, innerWidth - box.width - 8))}px`, top: `${Math.max(8, Math.min(drag.top + event.clientY - drag.y, innerHeight - box.height - 8))}px`, transform: 'none' };
if (drag.kind === 'launcher') launcherPosition.value = { ...next, right: 'auto', bottom: 'auto' }; else position.value = next;
position.value = next;
}
function endDrag() {
const old = drag; drag = undefined; dragging.value = false;
if (old?.kind === 'launcher' && old.moved) suppressLauncherClick = true;
if (old?.handle.hasPointerCapture(old.id)) old.handle.releasePointerCapture(old.id);
}
watch(windowElement, element => { resizeObserver?.disconnect(); if (element) { resizeObserver = new ResizeObserver(fitWindow); resizeObserver.observe(element); } });
watch(() => [props.sessionToken, props.gatewayUrl, props.connected] as const, close);
watch(thirdPartyAllowed, allowed => { if (!allowed) close(); }, { flush: 'sync' });
watch(() => [props.sessionToken, props.gatewayUrl, props.connected] as const, () => {
close();
if (props.connected && thirdPartyAllowed.value) void refresh();
});
watch(thirdPartyAllowed, allowed => {
if (!allowed) close();
else if (props.connected) void refresh();
}, { flush: 'sync' });
watch(() => props.language, appearance); watch(theme, appearance);
onMounted(() => {
detectTheme(); window.addEventListener('message', message); window.addEventListener('resize', fitWindow); window.addEventListener('pointermove', moveDrag); window.addEventListener('pointerup', endDrag); window.addEventListener('pointercancel', endDrag); window.addEventListener('blur', endDrag);
if (props.connected && thirdPartyAllowed.value) void refresh();
observer = new MutationObserver(detectTheme); observer.observe(document.documentElement, { attributes: true, subtree: true, attributeFilter: ['data-ws-skin', 'data-theme'] });
});
onBeforeUnmount(() => { stop(); endDrag(); observer?.disconnect(); resizeObserver?.disconnect(); window.removeEventListener('message', message); window.removeEventListener('resize', fitWindow); window.removeEventListener('pointermove', moveDrag); window.removeEventListener('pointerup', endDrag); window.removeEventListener('pointercancel', endDrag); window.removeEventListener('blur', endDrag); });
@@ -29,6 +29,7 @@
<details :open="expanded===plugin.manifest.id" @toggle="onToggle($event,plugin.manifest.id)"><summary><Icon name="settings" :size="16" />{{ text('configure') }}<Icon class="plugin-chevron" name="chevron-down" :size="15" /></summary><fieldset :disabled="model.busy.value">
<div class="plugin-enable-row"><div><strong>{{ tr('enabled') }}</strong><p>{{ text('review') }}</p></div><label class="plugin-switch"><input v-model="model.drafts[plugin.manifest.id].enabled" type="checkbox" :aria-label="tr('enabled')" /><span></span></label></div>
<label class="plugin-trust"><input v-model="model.drafts[plugin.manifest.id].trusted" type="checkbox" />{{ tr('trust') }}</label><p class="plugin-trust-note">{{ tr('enableNote') }}</p>
<label class="plugin-trust"><input v-model="model.drafts[plugin.manifest.id].toolbarPinned" type="checkbox" />{{ tr('toolbarPin') }}</label>
<label>{{ tr('scope') }}<select v-model="model.drafts[plugin.manifest.id].scope"><option v-for="scope in plugin.manifest.scopes" :key="scope" :value="scope">{{ tr(scope) }}</option></select></label>
<label v-if="model.drafts[plugin.manifest.id].scope==='server'">{{ tr('targets') }}<textarea v-model="model.drafts[plugin.manifest.id].targets" rows="3" maxlength="15000" placeholder="voice.example.com:9987"></textarea></label>
<details class="plugin-advanced"><summary>{{ text('advanced') }}<Icon name="chevron-down" :size="14" /></summary><label>{{ tr('config') }}<textarea v-model="model.drafts[plugin.manifest.id].config" rows="5" maxlength="65536" spellcheck="false"></textarea></label><template v-if="plugin.manifest.server"><label>{{ tr('privateConfig') }}<small>{{ tr(plugin.settings.hasServerConfig?'secretSaved':'secretEmpty') }}</small><select v-model="model.drafts[plugin.manifest.id].serverConfigAction"><option value="keep">{{ tr('keep') }}</option><option value="replace">{{ tr('replace') }}</option><option value="remove">{{ tr('erase') }}</option></select><textarea v-if="model.drafts[plugin.manifest.id].serverConfigAction==='replace'" v-model="model.drafts[plugin.manifest.id].serverConfig" rows="5" maxlength="65536" spellcheck="false" autocomplete="off" autocapitalize="off" autocorrect="off"></textarea></label></template></details>
+12 -13
View File
@@ -50,15 +50,14 @@
@input="onInputVolume"
/>
<div class="dock-panel-divider"></div>
<label class="dock-switch-row"
><span
><strong>{{ t("noiseSuppression") }}</strong></span
><input
type="checkbox"
:checked="noiseSuppressionEnabled"
:aria-label="t('noiseSuppression')"
@change="onNoiseSuppressionToggle"
/></label>
<label class="dock-switch-row">
<span><strong>{{ t("noiseSuppression") }}</strong></span>
<select class="noise-suppression-level" :value="noiseSuppressionLevel" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
<option value="off">{{ t("noiseSuppressionOff") }}</option>
<option value="standard">{{ t("noiseSuppressionStandard") }}</option>
<option value="strong">{{ t("noiseSuppressionStrong") }}</option>
</select>
</label>
</div>
</div>
<div
@@ -132,12 +131,12 @@ import type { useVoiceWebSocket } from "../../composables/useVoiceWebSocket.js";
import type { useWebClientAudioControls } from "../../composables/useWebClientAudioControls.js";
const props = defineProps<{
model: Pick<ReturnType<typeof useVoiceWebSocket>, "microphoneMuted" | "inputVolume" | "outputVolume" | "outputMuted" | "noiseSuppressionEnabled" | "accompanimentActive">;
controls: Pick<ReturnType<typeof useWebClientAudioControls>, "toggleMicrophone" | "toggleNoiseSuppression" | "onInputVolume" | "onOutputVolume" | "onNoiseSuppressionToggle" | "toggleAccompaniment">;
model: Pick<ReturnType<typeof useVoiceWebSocket>, "microphoneMuted" | "inputVolume" | "outputVolume" | "outputMuted" | "noiseSuppressionLevel" | "accompanimentActive">;
controls: Pick<ReturnType<typeof useWebClientAudioControls>, "toggleMicrophone" | "toggleNoiseSuppression" | "onInputVolume" | "onOutputVolume" | "onNoiseSuppressionChange" | "toggleAccompaniment">;
t: (key: string) => string;
rangeStyle: (value: number, max: number) => Record<string, string>;
}>();
const { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionEnabled, accompanimentActive } = props.model;
const { toggleMicrophone, onInputVolume, onOutputVolume, onNoiseSuppressionToggle, toggleAccompaniment } = props.controls;
const { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionLevel, accompanimentActive } = props.model;
const { toggleMicrophone, onInputVolume, onOutputVolume, onNoiseSuppressionChange, toggleAccompaniment } = props.controls;
const emit = defineEmits<{ settings: []; outputMute: [] }>();
</script>
@@ -76,16 +76,14 @@
/>
{{ microphoneMuted ? t("unmuteMic") : t("muteMic") }}</button
></div
><label
class="noise-suppression-toggle settings-form-row"
><span
><strong>{{ t("noiseSuppression") }}</strong
><small>{{ t("noiseSuppressionHint") }}</small></span
><input
type="checkbox"
:checked="noiseSuppressionEnabled"
:aria-label="t('noiseSuppression')"
@change="onNoiseSuppressionToggle" /></label
><label class="settings-form-row">
<span><strong>{{ t("noiseSuppression") }}</strong><small>{{ t("noiseSuppressionHint") }}</small></span>
<select class="noise-suppression-level" :value="noiseSuppressionLevel" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
<option value="off">{{ t("noiseSuppressionOff") }}</option>
<option value="standard">{{ t("noiseSuppressionStandard") }}</option>
<option value="strong">{{ t("noiseSuppressionStrong") }}</option>
</select>
</label
><div class="settings-form-row settings-range-form-row"
><label class="settings-label">{{ t("inputVolume") }}</label
><div class="settings-form-control"
@@ -265,7 +263,7 @@ type AudioSettingsState = Pick<ReturnType<typeof useVoiceWebSocket>,
| "audioPermission"
| "audioContextState"
| "microphoneMuted"
| "noiseSuppressionEnabled"
| "noiseSuppressionLevel"
| "inputVolume"
| "outputVolume"
| "voxThreshold"
@@ -277,7 +275,7 @@ type AudioSettingsState = Pick<ReturnType<typeof useVoiceWebSocket>,
type AudioSettingsControls = Pick<ReturnType<typeof useWebClientAudioControls>,
| "settingsError"
| "onInputVolume"
| "onNoiseSuppressionToggle"
| "onNoiseSuppressionChange"
| "onOutputVolume"
| "onVoxThreshold"
| "onNotificationVolume"
@@ -310,7 +308,7 @@ const {
audioPermission,
audioContextState,
microphoneMuted,
noiseSuppressionEnabled,
noiseSuppressionLevel,
inputVolume,
outputVolume,
voxThreshold,
@@ -322,7 +320,7 @@ const {
const {
settingsError: audioSettingsError,
onInputVolume,
onNoiseSuppressionToggle,
onNoiseSuppressionChange,
onOutputVolume,
onVoxThreshold,
onNotificationVolume,
@@ -33,15 +33,21 @@
><div
><strong>{{ t("voiceStatus") }}</strong
><small>{{ t("voiceStatusHint") }}</small></div
><button
><div class="performance-panel-tools"><button
type="button"
class="performance-refresh"
:title="t('exportAudioTrace')"
:aria-label="t('exportAudioTrace')"
:disabled="!traceEvents.length"
@click="exportTrace"
><Icon name="download" :size="15" /></button><button
type="button"
class="performance-refresh"
:title="t('measureNow')"
:aria-label="t('measureNow')"
:disabled="performanceRunning"
@click="refreshPerformanceProbe"
><Icon
name="refresh"
:size="15" /></button
><Icon name="refresh" :size="15" /></button></div
></header>
<div
class="voice-status-summary"
@@ -147,6 +153,7 @@
: t("voiceStatusWaiting")
}}</p
>
<p class="performance-status">{{ t("backgroundVoiceHint") }} · {{ t("audioTraceHint") }}</p>
<section
v-if="showScreenShare && screenShareWebRtcStats.peers.length"
class="webrtc-stats"
@@ -224,7 +231,7 @@ import type { useWebClientPerformance } from "../../composables/useWebClientPerf
import type { ScreenShareWebRtcStats } from "../../composables/useVoiceWebSocket.js";
const props = defineProps<{ model: ReturnType<typeof useWebClientPerformance>; screenShareWebRtcStats: ScreenShareWebRtcStats; showScreenShare?: boolean; t: (key: string) => string }>();
const showScreenShare = props.showScreenShare !== false;
const { panelOpen: performancePanelOpen, running: performanceRunning, stats: performanceStats, togglePanel: togglePerformancePanel, refresh: refreshPerformanceProbe } = props.model;
const { panelOpen: performancePanelOpen, running: performanceRunning, stats: performanceStats, traceEvents, togglePanel: togglePerformancePanel, refresh: refreshPerformanceProbe, exportTrace } = props.model;
const root = ref<HTMLElement | null>(null);
const trigger = ref<HTMLButtonElement | null>(null);
const t = props.t;
+3 -3
View File
@@ -6,10 +6,10 @@ import { parsePluginPackage, PLUGIN_LIMIT_BYTES, type InstalledPlugin, type Plug
export function useAdminPlugins(api: AdminApi) {
const installed=shallowRef<InstalledPlugin[]>([]),catalog=shallowRef<PluginCatalog|null>(null),runtime=shallowRef<PluginRuntimeSettings|null>(null);
const origin=ref(''),busy=ref(false),error=ref(''),catalogError=ref(''),requests=createAdminRequests();
const drafts=reactive<Record<string,{enabled:boolean;trusted:boolean;scope:'server'|'instance';targets:string;config:string;serverConfigAction:'keep'|'replace'|'remove';serverConfig:string}>>({});
const drafts=reactive<Record<string,{enabled:boolean;trusted:boolean;toolbarPinned:boolean;scope:'server'|'instance';targets:string;config:string;serverConfigAction:'keep'|'replace'|'remove';serverConfig:string}>>({});
function apply(records:InstalledPlugin[]){
installed.value=records;
for(const record of records)if(!drafts[record.manifest.id])drafts[record.manifest.id]={enabled:record.settings.enabled,trusted:record.settings.trusted,scope:record.settings.scope,targets:record.settings.targets.join('\n'),config:JSON.stringify(record.settings.config,null,2),serverConfigAction:'keep',serverConfig:''};
for(const record of records)if(!drafts[record.manifest.id])drafts[record.manifest.id]={enabled:record.settings.enabled,trusted:record.settings.trusted,toolbarPinned:record.settings.toolbarPinned,scope:record.settings.scope,targets:record.settings.targets.join('\n'),config:JSON.stringify(record.settings.config,null,2),serverConfigAction:'keep',serverConfig:''};
for(const id of Object.keys(drafts))if(!records.some(r=>r.manifest.id===id))delete drafts[id];
}
async function work(run:(signal:AbortSignal,current:()=>boolean)=>Promise<void>){
@@ -29,7 +29,7 @@ export function useAdminPlugins(api: AdminApi) {
});}
function save(record:InstalledPlugin){return work(async(signal,current)=>{
const draft=drafts[record.manifest.id],captured=JSON.stringify(draft);
const settings:PluginSettingsInput={enabled:draft.enabled,trusted:draft.trusted,scope:draft.scope,targets:draft.targets.split(/\r?\n/).map(t=>t.trim()).filter(Boolean),config:JSON.parse(draft.config),serverConfigAction:draft.serverConfigAction,...(draft.serverConfigAction==='replace'?{serverConfig:JSON.parse(draft.serverConfig)}:{})};
const settings:PluginSettingsInput={enabled:draft.enabled,trusted:draft.trusted,toolbarPinned:draft.toolbarPinned,scope:draft.scope,targets:draft.targets.split(/\r?\n/).map(t=>t.trim()).filter(Boolean),config:JSON.parse(draft.config),serverConfigAction:draft.serverConfigAction,...(draft.serverConfigAction==='replace'?{serverConfig:JSON.parse(draft.serverConfig)}:{})};
const result=await api.configurePlugin(record.manifest.id,record.revision,settings,signal);
if(current()){if(JSON.stringify(drafts[record.manifest.id])===captured)delete drafts[record.manifest.id];apply(installed.value.map(p=>p.manifest.id===record.manifest.id?result.plugin:p));}
});}
+5 -4
View File
@@ -31,9 +31,9 @@ export function usePublicSkin(options: PublicSkinOptions = {}) {
let disposed = false;
const owns = (operation: ReturnType<typeof createSkinOperation>) => !disposed && current === operation;
function cancel() { current?.cancel(); current = undefined; }
function begin() {
function begin(timeoutMs = options.timeoutMs) {
cancel();
return current = createSkinOperation({ timeoutMs: options.timeoutMs });
return current = createSkinOperation({ timeoutMs });
}
onScopeDispose(() => { disposed = true; cancel(); });
@@ -41,7 +41,7 @@ export function usePublicSkin(options: PublicSkinOptions = {}) {
operation.check();
if (!canUseSkin(id)) id = fallbackId();
const entry = catalogSkins.value.find(skin => skin.id === id);
const skin = await operation.wait(activateSkin(id, entry?.version, options.appVersion?.(), { signal: operation.signal }));
const skin = await operation.wait(activateSkin(id, entry?.version, options.appVersion?.(), { signal: operation.signal, timeoutMs: operation.timeoutMs }));
if (!owns(operation)) return;
if (!builtin(id) && !skin) throw new Error("The selected skin could not be activated.");
activeSkin.value = skin;
@@ -89,7 +89,8 @@ export function usePublicSkin(options: PublicSkinOptions = {}) {
}
async function select(id: string) {
if (disposed) return;
const operation = begin();
// A user-selected package can take longer to download on a cold cache.
const operation = begin(options.timeoutMs ?? (builtin(id) ? undefined : 25_000));
try {
try { localStorage.setItem("webspeak:skin-choice", id); } catch { /* Optional storage. */ }
await apply(id, operation, true, true);
+73 -20
View File
@@ -10,6 +10,7 @@ import { createVoiceCommands } from "../voice/commands.js";
import { createVoiceSessionState } from "../voice/session-state.js";
import { applySavedMemberVolumes } from "../voice/member-volume-preferences.js";
import { createAudioDiagnostics, type AudioPermission, type VoiceAudioStatusSample } from "../voice/audio-diagnostics.js";
import { createVoiceSessionTrace } from "../voice/session-trace.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";
@@ -20,7 +21,7 @@ import type { ChatMessage } from "../../../src/shared/voice-models.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";
export type { ChannelMember, ChannelInfo, ChatMessage, ServerEvent, VoiceAudioBridgeStats } from "../../../src/shared/voice-models.js";
import { reactive, ref, shallowRef } from "vue";
import { computed, onBeforeUnmount, reactive, ref, shallowRef } from "vue";
import { loadLocalPreferences, saveLocalPreferences } from "../services/local-persistence.js";
export interface VoiceState {
@@ -197,6 +198,7 @@ class CancelledMediaOperation extends Error {
}
export function useVoiceWebSocket() {
const sessionTrace = createVoiceSessionTrace();
const ws = shallowRef<WebSocket | null>(null);
const serverInfo = shallowRef<VoiceServerInfo | null>(null);
const state = reactive<VoiceState>({ connected: false, connecting: false, reconnecting: false, reconnectAttempt: 0, reconnectFailed: false, tsClientId: 0, error: "", errorCode: "", microphoneError: "", microphoneErrorCode: "", audioNotice: "", audioNoticeCode: "", channelSwitchedChannelId: "" });
@@ -215,10 +217,12 @@ export function useVoiceWebSocket() {
const { members, channels, chatMessages, serverEvents, pokeNotifications } = sessionState;
let chatGeneration = 0;
const voiceConnection = createVoiceConnection({
onSocket: socket => { ws.value = socket; },
onSocket: socket => { ws.value = socket; sessionTrace.record("gateway.socket", { state: socket ? "connecting" : "closed" }); },
onSocketOpen: () => sessionTrace.record("gateway.socket", { state: "open" }),
onMessage: handleMessage,
onAudio: handleAudioFrame,
onClose(event) {
sessionTrace.record("gateway.socket.closed", { code: event.code, clean: event.wasClean });
releaseSessionResources();
state.connected = false;
state.connecting = false;
@@ -235,6 +239,7 @@ export function useVoiceWebSocket() {
onFailure({ code, detail, cause }) {
state.connecting = false;
state.errorCode = normalizedClientErrorCode(code, "REQUEST_FAILED");
sessionTrace.record("gateway.connection.failed", { code: state.errorCode });
state.error = cause instanceof Error ? cause.message : joinTicketReason(state.errorCode, detail);
},
});
@@ -302,9 +307,10 @@ export function useVoiceWebSocket() {
onError: error => { setMicrophoneError(error); },
});
const microphoneMuted = ref(false);
const noiseSuppressionEnabled = ref(true);
const noiseSuppressionLevel = ref<"off" | "standard" | "strong">("strong");
const noiseSuppressionEnabled = computed(() => noiseSuppressionLevel.value !== "off");
let noiseSuppressionTouched = false;
let committedNoiseSuppressionEnabled = noiseSuppressionEnabled.value;
let committedNoiseSuppressionLevel = noiseSuppressionLevel.value;
const inputVolume = ref(1);
const outputVolume = ref(1);
const outputMuted = ref(false);
@@ -352,9 +358,14 @@ export function useVoiceWebSocket() {
if (rms !== null && !microphoneMuted.value && track.enabled && rms >= voxThreshold.value) markSpeaking(state.tsClientId);
else if (state.tsClientId) clearSpeaking(state.tsClientId);
},
onReady: syncWebRtcMemberVolumes,
onReady() {
sessionTrace.record("webrtc.media", { state: "active" });
syncWebRtcMemberVolumes();
},
onConnectionState(stateName) { sessionTrace.record("webrtc.connection", { state: stateName }); },
async onFallback(reason, isCurrent) {
if (!isCurrent()) return;
sessionTrace.record("webrtc.fallback", { code: safeClientErrorCode(reason) || "WEBRTC_UNAVAILABLE" });
setAudioNotice("WEBRTC_FALLBACK", `实时语音(WebRTC)不可用(错误代码:${safeClientErrorCode(reason) || "WEBRTC_UNAVAILABLE"}),已切换为兼容传输:延迟与音质可能下降`);
try { await startMicrophone(); }
catch (error) { if (isCurrent()) setMicrophoneError(error); }
@@ -403,7 +414,8 @@ export function useVoiceWebSocket() {
preferredInputDeviceId: committedInputDeviceId,
inputDeviceId: committedInputDeviceId,
microphoneMuted: microphoneMuted.value,
noiseSuppressionEnabled: committedNoiseSuppressionEnabled,
noiseSuppressionEnabled: committedNoiseSuppressionLevel !== "off",
noiseSuppressionLevel: committedNoiseSuppressionLevel,
voxThreshold: voxThreshold.value,
inputGain: inputVolume.value,
outputVolume: outputVolume.value,
@@ -426,9 +438,15 @@ export function useVoiceWebSocket() {
committedInputDeviceId = selectedInputDeviceId.value;
}
if (typeof preferences.microphoneMuted === "boolean") microphoneMuted.value = preferences.microphoneMuted;
if (!noiseSuppressionTouched && typeof preferences.noiseSuppressionEnabled === "boolean") {
noiseSuppressionEnabled.value = preferences.noiseSuppressionEnabled;
committedNoiseSuppressionEnabled = preferences.noiseSuppressionEnabled;
if (!noiseSuppressionTouched) {
const storedLevel = preferences.noiseSuppressionLevel;
if (storedLevel === "off" || storedLevel === "standard" || storedLevel === "strong") {
noiseSuppressionLevel.value = storedLevel;
committedNoiseSuppressionLevel = storedLevel;
} else if (typeof preferences.noiseSuppressionEnabled === "boolean") {
noiseSuppressionLevel.value = preferences.noiseSuppressionEnabled ? "strong" : "off";
committedNoiseSuppressionLevel = noiseSuppressionLevel.value;
}
}
if (typeof preferences.voxThreshold === "number") voxThreshold.value = clamp(preferences.voxThreshold, 0.001, 0.08);
if (typeof preferences.inputGain === "number") inputVolume.value = Math.max(0, Math.min(1, preferences.inputGain));
@@ -482,7 +500,10 @@ export function useVoiceWebSocket() {
audioCtx = new AudioContext({ sampleRate: 48000 }) as SinkAudioContext;
audioContextState.value = audioCtx.state;
audioCtx.addEventListener("statechange", () => {
if (audioCtx) audioContextState.value = audioCtx.state;
if (audioCtx) {
audioContextState.value = audioCtx.state;
sessionTrace.record("audio.context", { state: audioCtx.state });
}
});
outputDeviceSupported.value = typeof audioCtx.setSinkId === "function"
|| typeof (HTMLMediaElement.prototype as SinkAudioElement).setSinkId === "function";
@@ -573,7 +594,7 @@ export function useVoiceWebSocket() {
sampleRate: { ideal: 48000 },
channelCount: { ideal: 1 },
echoCancellation: true,
noiseSuppression: noiseSuppressionEnabled.value,
noiseSuppression: noiseSuppressionLevel.value !== "off",
// Keep the microphone's natural dynamics. Browser AGC can make speech
// pump in volume, especially while background noise changes.
autoGainControl: false,
@@ -698,7 +719,7 @@ export function useVoiceWebSocket() {
factoryOwnsStream = true;
nextCapture = await microphoneCaptureFactory.prepare({
context: ctx, stream: nextStream, signal: controller.signal, assertCurrent,
noiseSuppression: noiseSuppressionEnabled.value, volume: inputVolume.value, onSamples: handleCaptureChunk,
rnnoiseEnabled: noiseSuppressionLevel.value === "strong", volume: inputVolume.value, onSamples: handleCaptureChunk,
});
assertCurrent();
// Commit only a complete graph. Permission and node failures leave the
@@ -706,13 +727,21 @@ export function useVoiceWebSocket() {
stopMicrophone(false);
micStream = nextStream;
microphoneCapture = nextCapture;
const microphoneTrack = nextStream.getAudioTracks()[0];
if (microphoneTrack) {
const recordTrack = (stateName: string) => sessionTrace.record("microphone.track", { state: stateName, muted: microphoneTrack.muted });
recordTrack(microphoneTrack.readyState);
microphoneTrack.addEventListener("mute", () => recordTrack("mute"));
microphoneTrack.addEventListener("unmute", () => recordTrack("unmute"));
microphoneTrack.addEventListener("ended", () => recordTrack("ended"));
}
Object.assign(microphoneProcessing, nextCapture.processing);
nextCapture.setVolume(inputVolume.value);
nextCapture.activate();
// The fallback for a later failed change is this actual live graph, even
// if device enumeration or WebRTC negotiation is still in progress.
committedInputDeviceId = selectedInputDeviceId.value;
committedNoiseSuppressionEnabled = noiseSuppressionEnabled.value;
committedNoiseSuppressionLevel = noiseSuppressionLevel.value;
clearMicrophoneError();
} catch (error) {
nextCapture?.dispose();
@@ -795,6 +824,7 @@ export function useVoiceWebSocket() {
pendingMicrophoneCapture = null;
}
stopCaptureGraph();
if (micStream) sessionTrace.record("microphone.track", { state: "released" });
microphoneCapture?.dispose();
microphoneCapture = null;
webrtc.releaseInput();
@@ -834,13 +864,13 @@ export function useVoiceWebSocket() {
await refreshAudioDevices();
if (!isCurrent()) return;
committedInputDeviceId = selectedInputDeviceId.value;
committedNoiseSuppressionEnabled = noiseSuppressionEnabled.value;
committedNoiseSuppressionLevel = noiseSuppressionLevel.value;
localStorage.setItem("webspeak:input-device", committedInputDeviceId);
await saveAudioPreferences();
} catch (error) {
if (!isCurrent() || error instanceof CancelledMediaOperation) return;
selectedInputDeviceId.value = committedInputDeviceId;
noiseSuppressionEnabled.value = committedNoiseSuppressionEnabled;
noiseSuppressionLevel.value = committedNoiseSuppressionLevel;
localStorage.setItem("webspeak:input-device", committedInputDeviceId);
throw error;
}
@@ -1031,7 +1061,7 @@ export function useVoiceWebSocket() {
deviceListGeneration++;
selectedInputDeviceId.value = committedInputDeviceId;
selectedOutputDeviceId.value = committedOutputDeviceId;
noiseSuppressionEnabled.value = committedNoiseSuppressionEnabled;
noiseSuppressionLevel.value = committedNoiseSuppressionLevel;
microphoneTest.dispose();
audioDiagnostics.reset();
commands.clear(new Error("语音连接已关闭"));
@@ -1057,6 +1087,7 @@ export function useVoiceWebSocket() {
};
break;
case "connected":
sessionTrace.record("teamspeak.session", { state: "connected" });
const wasReconnecting = state.reconnecting;
state.connected = true;
state.connecting = false;
@@ -1106,6 +1137,7 @@ export function useVoiceWebSocket() {
break;
}
case "disconnected":
sessionTrace.record("teamspeak.session", { state: "disconnected", recoverable: msg.recoverable !== false });
state.connected = false;
state.connecting = false;
state.reconnecting = Boolean(msg.recoverable !== false);
@@ -1114,6 +1146,7 @@ export function useVoiceWebSocket() {
releaseSessionResources();
break;
case "reconnecting":
sessionTrace.record("teamspeak.reconnect", { state: "retrying", attempt: Number(msg.attempt) || 0 });
state.connected = false;
state.connecting = false;
state.reconnecting = true;
@@ -1122,10 +1155,12 @@ export function useVoiceWebSocket() {
releaseSessionResources();
break;
case "reconnected":
sessionTrace.record("teamspeak.reconnect", { state: "restored" });
state.reconnecting = false;
state.reconnectFailed = false;
break;
case "reconnectFailed":
sessionTrace.record("teamspeak.reconnect", { state: "failed", code: normalizedClientErrorCode(msg.code) });
state.connected = false;
state.connecting = false;
state.reconnecting = false;
@@ -1135,6 +1170,7 @@ export function useVoiceWebSocket() {
releaseSessionResources();
break;
case "connectionFailed":
sessionTrace.record("teamspeak.session", { state: "connection-failed", code: normalizedClientErrorCode(msg.code) });
state.connected = false;
state.connecting = false;
state.reconnecting = false;
@@ -1180,6 +1216,7 @@ export function useVoiceWebSocket() {
}
case "error":
state.errorCode = normalizedClientErrorCode(msg.error?.code, "OPERATION_FAILED");
sessionTrace.record("teamspeak.session.error", { code: state.errorCode });
state.error = protocolErrorMessage(state.errorCode, String(msg.error?.message || msg.message || "操作失败"));
{
const requestId = typeof msg.requestId === "string" ? msg.requestId : "";
@@ -1200,10 +1237,15 @@ export function useVoiceWebSocket() {
return;
}
const clientId = (data[1] << 8) | data[2];
const codec = data[0];
if (clientId === state.tsClientId) return;
if (codec !== 4 && codec !== 5) {
audioDiagnostics.count("framesDropped");
return;
}
audioDiagnostics.count("framesReceived");
markSpeaking(clientId);
remotePlayback.play(clientId, data.slice(3));
remotePlayback.play(clientId, codec, data.slice(3));
}
function sendCmd<K extends ClientCommandType>(type: K, payload: ClientCommandPayloads[K]): void {
@@ -1399,17 +1441,23 @@ export function useVoiceWebSocket() {
void saveAudioPreferences();
}
async function setNoiseSuppressionEnabled(enabled: boolean): Promise<void> {
if (noiseSuppressionEnabled.value === enabled) return;
async function setNoiseSuppressionLevel(level: "off" | "standard" | "strong"): Promise<void> {
if (noiseSuppressionLevel.value === level) return;
noiseSuppressionTouched = true;
noiseSuppressionEnabled.value = enabled;
const previousLevel = noiseSuppressionLevel.value;
noiseSuppressionLevel.value = level;
try {
await reconfigureMicrophone();
} catch (error) {
noiseSuppressionLevel.value = previousLevel;
setMicrophoneError(error);
}
}
function setNoiseSuppressionEnabled(enabled: boolean): Promise<void> {
return setNoiseSuppressionLevel(enabled ? (noiseSuppressionLevel.value === "off" ? "strong" : noiseSuppressionLevel.value) : "off");
}
function setOutputVolume(volume: number): void {
outputVolume.value = Math.max(0, Math.min(1, volume));
applyOutputVolume();
@@ -1431,6 +1479,8 @@ export function useVoiceWebSocket() {
void saveAudioPreferences();
}
onBeforeUnmount(() => sessionTrace.dispose());
return {
pluginSession,
...screenShare.api,
@@ -1446,6 +1496,7 @@ export function useVoiceWebSocket() {
pokeNotifications,
microphoneMuted,
noiseSuppressionEnabled,
noiseSuppressionLevel,
inputVolume,
outputVolume,
outputMuted,
@@ -1472,6 +1523,7 @@ export function useVoiceWebSocket() {
accompanimentErrorCode,
setVolume,
setInputVolume,
setNoiseSuppressionLevel,
setNoiseSuppressionEnabled,
setOutputVolume,
toggleOutputMute,
@@ -1504,5 +1556,6 @@ export function useVoiceWebSocket() {
checkSupport,
clearError,
measureVoiceAudioStatus,
sessionTrace,
};
}
@@ -1,9 +1,11 @@
import { computed, onScopeDispose, ref, watch, type Ref } from "vue";
import type { LocalPreferences } from "../services/local-persistence.js";
type NoiseSuppressionLevel = NonNullable<LocalPreferences["noiseSuppressionLevel"]>;
interface UseWebClientAudioControlsOptions {
settingsOpen: Ref<boolean>;
microphoneMuted: Readonly<Ref<boolean>>;
noiseSuppressionEnabled: Readonly<Ref<boolean>>;
noiseSuppressionLevel: Readonly<Ref<NoiseSuppressionLevel>>;
inputVolume: Readonly<Ref<number>>;
voxThreshold: Readonly<Ref<number>>;
notificationVolume: Readonly<Ref<number>>;
@@ -14,7 +16,7 @@ interface UseWebClientAudioControlsOptions {
whisperTargetIds: Set<number>;
prepareInputDevices: () => Promise<void>;
setInputVolume: (value: number) => void;
setNoiseSuppressionEnabled: (enabled: boolean) => Promise<void>;
setNoiseSuppressionLevel: (level: NoiseSuppressionLevel) => Promise<void>;
setOutputVolume: (value: number) => void;
setVoxThreshold: (value: number) => void;
setNotificationVolume: (value: number) => void;
@@ -34,7 +36,7 @@ interface UseWebClientAudioControlsOptions {
export function useWebClientAudioControls({
settingsOpen,
microphoneMuted,
noiseSuppressionEnabled,
noiseSuppressionLevel,
inputVolume,
voxThreshold,
notificationVolume,
@@ -45,7 +47,7 @@ export function useWebClientAudioControls({
whisperTargetIds,
prepareInputDevices,
setInputVolume,
setNoiseSuppressionEnabled,
setNoiseSuppressionLevel,
setOutputVolume,
setVoxThreshold,
setNotificationVolume,
@@ -92,12 +94,13 @@ export function useWebClientAudioControls({
setInputVolume(Number((event.target as HTMLInputElement).value) / 100);
}
function onNoiseSuppressionToggle(event: Event): void {
void setNoiseSuppressionEnabled((event.target as HTMLInputElement).checked);
function onNoiseSuppressionChange(event: Event): void {
const level = (event.target as HTMLSelectElement).value;
if (level === "off" || level === "standard" || level === "strong") void setNoiseSuppressionLevel(level);
}
function toggleNoiseSuppression(): void {
void setNoiseSuppressionEnabled(!noiseSuppressionEnabled.value);
void setNoiseSuppressionLevel(noiseSuppressionLevel.value === "off" ? "strong" : "off");
}
function onOutputVolume(event: Event): void {
@@ -244,7 +247,7 @@ export function useWebClientAudioControls({
whisperPttActive,
micMeterBars,
onInputVolume,
onNoiseSuppressionToggle,
onNoiseSuppressionChange,
toggleNoiseSuppression,
onOutputVolume,
onVoxThreshold,
+50 -1
View File
@@ -1,5 +1,6 @@
import { computed, onUnmounted, ref, watch, type Ref } from "vue";
import type { VoiceAudioStatusSample } from "../voice/audio-diagnostics.js";
import type { VoiceSessionTrace } from "../voice/session-trace.js";
const SAMPLE_INTERVAL_MS = 2_000;
@@ -21,6 +22,21 @@ function bitrateKbps(current: number | null, previous: number | null | undefined
return Math.round(((current - previous) * 8) / elapsedMs);
}
function browserLabel(userAgent: string): string {
const candidates: Array<[RegExp, string]> = [
[/\bEdg(?:A|iOS)?\/([\d.]+)/, "Edge"],
[/\bOPR\/([\d.]+)/, "Opera"],
[/\b(?:CriOS|Chrome)\/([\d.]+)/, "Chrome"],
[/\b(?:FxiOS|Firefox)\/([\d.]+)/, "Firefox"],
];
for (const [pattern, name] of candidates) {
const version = userAgent.match(pattern)?.[1];
if (version) return `${name}/${version}`;
}
const safariVersion = userAgent.match(/\bVersion\/([\d.]+)/)?.[1];
return safariVersion && /\bSafari\//.test(userAgent) ? `Safari/${safariVersion}` : "Other";
}
function intervalLossPercent(
currentReceived: number | null | undefined,
previousReceived: number | null | undefined,
@@ -47,11 +63,13 @@ function downlinkCounter(sample: VoiceAudioStatusSample | null) {
export function useWebClientPerformance(
connected: Readonly<Ref<boolean>>,
measureAudioStatus: () => Promise<VoiceAudioStatusSample | null>,
sessionTrace: VoiceSessionTrace,
) {
const panelOpen = ref(false);
const running = ref(false);
const latestSample = ref<VoiceAudioStatusSample | null>(null);
const previousSample = ref<VoiceAudioStatusSample | null>(null);
const traceEvents = sessionTrace.events;
let timer: number | null = null;
let generation = 0;
let disposed = false;
@@ -142,6 +160,22 @@ export function useWebClientPerformance(
if (expectedGeneration !== generation || !connected.value) return;
previousSample.value = sample ? latestSample.value : null;
latestSample.value = sample;
if (sample) sessionTrace.record("audio.sample", {
transport: sample.transport,
connection: sample.connectionState ?? "unknown",
microphone: sample.microphoneReady ? "ready" : sample.microphonePermission,
playback: sample.playbackState ?? "unknown",
sentFrames: sample.bridge.tsSendFrames,
receivedFrames: sample.transport === "webrtc" ? sample.browser?.inboundPackets ?? 0 : sample.fallbackPlayback.framesReceived,
sendErrors: sample.bridge.tsSendErrors,
droppedFrames: sample.bridge.ingressDroppedFrames + sample.bridge.egressDroppedFrames + sample.bridge.webrtcQueueDroppedFrames + sample.fallbackPlayback.framesDropped,
uplinkPackets: sample.browser?.outboundPackets ?? null,
uplinkLost: sample.browser?.outboundPacketsLost ?? null,
downlinkPackets: sample.browser?.inboundPackets ?? null,
downlinkLost: sample.browser?.inboundPacketsLost ?? null,
rttMs: sample.browser?.outboundRttMs ?? null,
jitterMs: sample.browser?.inboundJitterMs ?? null,
});
} catch {
if (expectedGeneration === generation) {
latestSample.value = null;
@@ -174,6 +208,21 @@ export function useWebClientPerformance(
void runProbe();
}
function exportTrace(): void {
const payload = {
schemaVersion: 1,
exportedAt: new Date().toISOString(),
browser: browserLabel(navigator.userAgent),
events: sessionTrace.snapshot(),
};
const url = URL.createObjectURL(new Blob([JSON.stringify(payload, null, 2)], { type: "application/json" }));
const link = document.createElement("a");
link.href = url;
link.download = `webspeak-audio-trace-${new Date().toISOString().replace(/[:.]/g, "-")}.json`;
link.click();
window.setTimeout(() => URL.revokeObjectURL(url), 1_000);
}
function togglePanel(): void {
panelOpen.value = !panelOpen.value;
}
@@ -185,5 +234,5 @@ export function useWebClientPerformance(
onUnmounted(() => { disposed = true; stop(); });
return { panelOpen, running, stats, togglePanel, refresh };
return { panelOpen, running, stats, traceEvents, togglePanel, refresh, exportTrace };
}
+5
View File
@@ -32,6 +32,7 @@ const en = {
"origin": "Public runtime origin",
"originHelp": "Use a separate HTTPS origin, such as https://apps.example.com, proxying to the runtime port. Blank enables local automatic addressing only.",
"trust": "I have reviewed and trust this application and its dependencies",
"toolbarPin": "Pin this app in the voice toolbar",
"privateConfig": "Private backend configuration (JSON; encrypted at rest)",
"keep": "Keep existing secret configuration",
"replace": "Replace secret configuration",
@@ -83,6 +84,7 @@ zh:{
"origin": "运行时公开源地址",
"originHelp": "配置独立的 HTTPS 源,如 https://apps.example.com,并反向代理到运行时端口。留空仅支持本地自动地址。",
"trust": "我已审核并信任此应用及其依赖",
"toolbarPin": "在语音工具栏中固定此应用",
"privateConfig": "后端私密配置(JSON;加密存储)",
"keep": "保留现有私密配置",
"replace": "替换私密配置",
@@ -131,6 +133,7 @@ de:{
"origin": "Öffentliche Runtime-Origin",
"originHelp": "Separate HTTPS-Origin, z. B. https://apps.example.com, auf den Runtime-Port weiterleiten. Leer nur für lokale automatische Adressen.",
"trust": "Ich habe diese Anwendung und ihre Abhängigkeiten geprüft und vertraue ihnen",
"toolbarPin": "Diese App in der Sprachsymbolleiste anheften",
"privateConfig": "Private Backend-Konfiguration (JSON; verschlüsselt gespeichert)",
"keep": "Vorhandene private Konfiguration behalten",
"replace": "Private Konfiguration ersetzen",
@@ -179,6 +182,7 @@ ru:{
"origin": "Публичный источник среды",
"originHelp": "Отдельный HTTPS-источник, например https://apps.example.com, с проксированием на порт среды. Пустое поле — только для локальных адресов.",
"trust": "Я проверил приложение и зависимости и доверяю им",
"toolbarPin": "Закрепить приложение на панели голосовой комнаты",
"privateConfig": "Приватные настройки сервиса (JSON; хранятся зашифрованными)",
"keep": "Сохранить текущие приватные настройки",
"replace": "Заменить приватные настройки",
@@ -227,6 +231,7 @@ ja:{
"origin": "公開ランタイムオリジン",
"originHelp": "https://apps.example.com のような別 HTTPS オリジンを実行ポートへ転送します。空欄はローカル自動アドレス専用です。",
"trust": "アプリと依存関係を審査し、信頼します",
"toolbarPin": "このアプリをボイスツールバーに固定",
"privateConfig": "バックエンドの秘密設定(JSON、暗号化して保存)",
"keep": "現在の秘密設定を保持",
"replace": "秘密設定を置換",
+35 -5
View File
@@ -340,7 +340,13 @@ export const webClientTranslations: Record<string, Record<string, string>> = {
audioStatus: "音频状态",
audioReady: "音频已就绪",
noiseSuppression: "浏览器降噪",
noiseSuppressionHint: "在浏览器采集端处理",
noiseSuppressionHint: "标准使用浏览器降噪;强效模式会叠加 RNNoise(设备支持时)。",
noiseSuppressionOff: "关闭",
noiseSuppressionStandard: "标准(浏览器)",
noiseSuppressionStrong: "强效(RNNoise)",
exportAudioTrace: "导出最近两分钟的音频诊断",
audioTraceHint: "可导出不含语音内容、昵称或服务器地址的本地诊断记录。",
backgroundVoiceHint: "浏览器后台麦克风受浏览器和系统策略限制;锁屏或切后台后可能暂停。",
rnnoise: "RNNoise 降噪",
echoCancellation: "回声消除",
autoGainControl: "自动增益",
@@ -766,7 +772,13 @@ export const webClientTranslations: Record<string, Record<string, string>> = {
audioStatus: "Audio status",
audioReady: "Audio ready",
noiseSuppression: "Browser noise suppression",
noiseSuppressionHint: "Process audio in the browser",
noiseSuppressionHint: "Standard uses browser filtering; strong also enables RNNoise when supported.",
noiseSuppressionOff: "Off",
noiseSuppressionStandard: "Standard (browser)",
noiseSuppressionStrong: "Strong (RNNoise)",
exportAudioTrace: "Export the last two minutes of audio diagnostics",
audioTraceHint: "The local trace excludes audio content, nicknames, and server addresses.",
backgroundVoiceHint: "Background microphone capture depends on browser and OS policy and may pause when hidden or locked.",
rnnoise: "RNNoise suppression",
echoCancellation: "Echo cancellation",
autoGainControl: "Automatic gain control",
@@ -1185,7 +1197,13 @@ webClientTranslations.de = {
audioStatus: "Audiostatus",
audioReady: "Audio bereit",
noiseSuppression: "Browser-Geräuschunterdrückung",
noiseSuppressionHint: "Verarbeitung bei der Aufnahme im Browser",
noiseSuppressionHint: "Standard nutzt die Browserfilterung; Stark aktiviert zusätzlich RNNoise, sofern unterstützt.",
noiseSuppressionOff: "Aus",
noiseSuppressionStandard: "Standard (Browser)",
noiseSuppressionStrong: "Stark (RNNoise)",
exportAudioTrace: "Letzte zwei Minuten der Audiodiagnose exportieren",
audioTraceHint: "Der lokale Verlauf enthält keine Audioinhalte, Namen oder Serveradressen.",
backgroundVoiceHint: "Die Mikrofonaufnahme im Hintergrund hängt von Browser und Betriebssystem ab und kann pausieren.",
rnnoise: "RNNoise-Geräuschunterdrückung",
echoCancellation: "Echounterdrückung",
autoGainControl: "Automatische Verstärkungsregelung",
@@ -1354,7 +1372,13 @@ webClientTranslations.ru = {
screenShareBitrate12M: "12 Мбит/с",
screenShareSettingsNote: "Настройки применятся при следующем запуске трансляции",
noiseSuppression: "Шумоподавление",
noiseSuppressionHint: "Обработка звука при захвате в браузере",
noiseSuppressionHint: "Стандартный режим использует фильтр браузера; усиленный также включает RNNoise, если он поддерживается.",
noiseSuppressionOff: "Выкл.",
noiseSuppressionStandard: "Стандартный (браузер)",
noiseSuppressionStrong: "Усиленный (RNNoise)",
exportAudioTrace: "Экспортировать диагностику звука за последние две минуты",
audioTraceHint: "Локальная запись не содержит аудио, имён или адресов серверов.",
backgroundVoiceHint: "Фоновая запись с микрофона зависит от браузера и ОС и может приостанавливаться.",
highQuality: "Качественный звук",
opusAudio: "Передача Opus с низкой задержкой",
secureJoin: "Безопасное подключение",
@@ -1567,7 +1591,13 @@ webClientTranslations.ja = {
screenShareBitrate12M: "12 Mbps",
screenShareSettingsNote: "次回の共有開始時に適用されます",
noiseSuppression: "ノイズ抑制",
noiseSuppressionHint: "ブラウザ側で音声を処理",
noiseSuppressionHint: "標準はブラウザーのフィルターを使用し、強力は対応環境で RNNoise も有効にします。",
noiseSuppressionOff: "オフ",
noiseSuppressionStandard: "標準(ブラウザー)",
noiseSuppressionStrong: "強力(RNNoise)",
exportAudioTrace: "直近 2 分間の音声診断をエクスポート",
audioTraceHint: "音声、ニックネーム、サーバーアドレスを含まないローカル診断です。",
backgroundVoiceHint: "バックグラウンドでのマイク利用はブラウザーと OS の制御を受け、停止する場合があります。",
highQuality: "高品質な音声",
opusAudio: "低遅延 Opus 転送",
secureJoin: "安全に参加",
+1
View File
@@ -146,6 +146,7 @@ export interface LocalPreferences {
skinId?: string;
microphoneMuted?: boolean;
noiseSuppressionEnabled?: boolean;
noiseSuppressionLevel?: "off" | "standard" | "strong";
voxThreshold?: number;
language?: "zh" | "en" | "de" | "ru" | "ja";
preferredInputDeviceId?: string;
+2 -2
View File
@@ -1,6 +1,6 @@
import { parsePluginManifest, pluginAssert, pluginRecord, type PluginManifest, type PluginAppLaunch, type PluginScope, type PluginRuntimeStatus } from '../../../src/shared/plugins.js';
export interface AvailablePluginApp { manifest: PluginManifest; scope: PluginScope; runtime: PluginRuntimeStatus }
export interface AvailablePluginApp { manifest: PluginManifest; scope: PluginScope; toolbarPinned: boolean; runtime: PluginRuntimeStatus }
export function createPluginAppClient(gatewayUrl:string,token:string,fetcher:typeof fetch=fetch,timeoutMs=15000){
pluginAssert(/^[A-Za-z0-9_-]{43}$/.test(token),'PLUGIN_NOT_CONNECTED');
const gateway=new URL(gatewayUrl);pluginAssert(['ws:','wss:','http:','https:'].includes(gateway.protocol)&&!gateway.username&&!gateway.password);
@@ -23,7 +23,7 @@ export function createPluginAppClient(gatewayUrl:string,token:string,fetcher:typ
const value=await request('','GET',undefined,signal);pluginAssert(pluginRecord(value)&&Array.isArray(value.plugins)&&value.plugins.length<=50,'PLUGIN_INVALID_RESPONSE');
return value.plugins.map(entry=>{
pluginAssert(pluginRecord(entry)&&(entry.scope==='server'||entry.scope==='instance')&&pluginRecord(entry.runtime)&&['disabled','client','stopped','starting','running','failed'].includes(String(entry.runtime.state)),'PLUGIN_INVALID_RESPONSE');
return {manifest:parsePluginManifest(entry.manifest),scope:entry.scope,runtime:{state:entry.runtime.state as PluginRuntimeStatus['state'],...(typeof entry.runtime.error==='string'?{error:entry.runtime.error}:{})}};
return {manifest:parsePluginManifest(entry.manifest),scope:entry.scope,toolbarPinned:entry.toolbarPinned===true,runtime:{state:entry.runtime.state as PluginRuntimeStatus['state'],...(typeof entry.runtime.error==='string'?{error:entry.runtime.error}:{})}};
});
},
async open(id:string,options:{openId:string;theme:'light'|'dark';language:string},signal?:AbortSignal):Promise<PluginAppLaunch>{
+1 -1
View File
@@ -34,5 +34,5 @@ export function createSkinOperation({ signal: parent, timeoutMs = SKIN_LOAD_TIME
if (signal.aborted) { done(); aborted(); }
});
}
return { signal, check, wait, cancel, finish };
return { signal, timeoutMs, check, wait, cancel, finish };
}
+8 -6
View File
@@ -6,9 +6,13 @@
.ws-plugin-overlay button:disabled{opacity:.5;cursor:wait}
.ws-plugin-overlay button:focus-visible,.ws-plugin-search:focus-visible{outline:2px solid var(--po-accent);outline-offset:3px}
.ws-plugin-overlay svg{display:block;width:19px;height:19px;flex:none;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}
.ws-plugin-overlay .ws-plugin-launcher{position:absolute;pointer-events:auto;right:max(20px,env(safe-area-inset-right));bottom:calc(22px + env(safe-area-inset-bottom));padding:13px 18px;border:1px solid #ffffff35;border-radius:18px;background:#303f78;color:#fff;box-shadow:0 8px 30px #101a4240;font-weight:650;transition:background .15s,box-shadow .15s}
.ws-plugin-overlay .ws-plugin-launcher:hover{background:#405496;box-shadow:0 10px 35px #101a4260}
.ws-plugin-launcher i{width:7px;height:7px;border-radius:50%;background:#9ee7b5}
.webspeak-plugin-toolbar-host{display:flex;align-items:center;flex:none;min-width:0;max-width:min(38vw,240px)}
.ws-plugin-toolbar{display:flex;align-items:center;gap:4px;max-width:100%;overflow-x:auto;overscroll-behavior-inline:contain;scrollbar-width:none}
.ws-plugin-toolbar::-webkit-scrollbar{display:none}
.ws-plugin-toolbar .ws-plugin-toolbar-trigger,.ws-plugin-toolbar .ws-plugin-toolbar-shortcut{display:inline-flex;align-items:center;justify-content:center;flex:none;width:34px;height:34px;padding:7px;border-radius:10px;cursor:pointer}
.ws-plugin-toolbar .ws-plugin-toolbar-trigger svg{width:17px;height:17px;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}
.ws-plugin-toolbar .ws-plugin-toolbar-shortcut{font-size:12px;font-weight:700}
.ws-plugin-toolbar button:focus-visible{outline:2px solid currentColor;outline-offset:2px}
.ws-plugin-window{position:absolute;pointer-events:auto;left:50%;top:10dvh;transform:translateX(-50%);display:flex;flex-direction:column;width:min(1080px,calc(100vw - 32px));height:min(760px,80dvh);min-width:320px;min-height:240px;max-width:calc(100vw - 16px);max-height:calc(100dvh - 16px);overflow:hidden;resize:both;border:1px solid var(--po-line);border-radius:17px;background:var(--po-bg);box-shadow:0 30px 100px #080e3540,0 4px 20px #080e3520;isolation:isolate}
.ws-plugin-window:focus{outline:none}
.ws-plugin-window.is-maximized{inset:8px!important;width:calc(100vw - 16px)!important;height:calc(100dvh - 16px)!important;transform:none!important;resize:none}
@@ -45,6 +49,4 @@
.ws-plugin-browser{flex:1;min-height:0;display:flex;background:var(--po-surface)}
.ws-plugin-browser iframe{display:block;flex:1;width:100%;height:100%;min-height:0;border:0;border-radius:0;background:var(--po-surface)}
.ws-plugin-drag-shield{position:absolute;inset:62px 0 0;z-index:1;cursor:grabbing}
@media(max-width:600px){.ws-plugin-window{left:8px!important;top:8px!important;transform:none!important;width:calc(100vw - 16px)!important;height:calc(100dvh - 92px);min-width:0;resize:none;border-radius:13px}.ws-plugin-titlebar{padding-left:12px;gap:8px}.ws-plugin-window-title small{display:none}.ws-plugin-library{padding:18px}.ws-plugin-overlay .ws-plugin-launcher{bottom:calc(16px + env(safe-area-inset-bottom));right:12px;padding:12px 14px}.ws-plugin-library-heading h2{font-size:21px}.ws-plugin-entry{padding:16px}.ws-plugin-navigation{padding-inline:10px}}
@media(prefers-reduced-motion:reduce){.ws-plugin-overlay .ws-plugin-launcher{transition:none}}
.ws-plugin-launcher{touch-action:none;user-select:none}
@media(max-width:600px){.ws-plugin-window{left:8px!important;top:8px!important;transform:none!important;width:calc(100vw - 16px)!important;height:calc(100dvh - 92px);min-width:0;resize:none;border-radius:13px}.ws-plugin-titlebar{padding-left:12px;gap:8px}.ws-plugin-window-title small{display:none}.ws-plugin-library{padding:18px}.webspeak-plugin-toolbar-host{max-width:30vw}.ws-plugin-toolbar .ws-plugin-toolbar-shortcut{width:30px;height:30px}.ws-plugin-library-heading h2{font-size:21px}.ws-plugin-entry{padding:16px}.ws-plugin-navigation{padding-inline:10px}}
+29
View File
@@ -6113,6 +6113,12 @@
gap: 12px;
}
:deep(.performance-panel-tools) {
display: flex;
gap: 6px;
flex: none;
}
:deep(.performance-panel header strong),
:deep(.performance-panel header small) {
display: block;
@@ -6748,6 +6754,29 @@
font-size: 11px;
}
:deep(.noise-suppression-level) {
min-width: 0;
max-width: 100%;
padding: 8px 28px 8px 10px;
color: var(--text-primary);
background: var(--surface-1);
border: 1px solid var(--border);
border-radius: 8px;
font: inherit;
font-size: 11px;
}
:deep(.noise-suppression-level:focus-visible) {
outline: 3px solid color-mix(in srgb, var(--accent) 45%, transparent);
outline-offset: 2px;
}
:deep(.dock-switch-row .noise-suppression-level) {
min-width: 138px;
max-width: 168px;
font-size: 10px;
}
:deep(.noise-suppression-toggle) {
margin-bottom: 18px;
padding: 12px;
+1 -1
View File
@@ -178,7 +178,7 @@ const skinPluginActions = {
.demo-page.skin-initializing { visibility: hidden; }
.demo-page { min-height: 100dvh; padding: 0 28px 38px; font-family: Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: radial-gradient(circle at 72% 12%, rgba(126, 213, 205, .18), transparent 26rem), #f7f9f8; color: #1c2b28; }
.demo-page button, .demo-page input { font: inherit; }
.demo-header { display: flex; align-items: center; justify-content: space-between; width: min(1380px, 100%); min-height: 82px; margin: 0 auto; }
.demo-header { position: relative; z-index: 2; display: flex; align-items: center; justify-content: space-between; width: min(1380px, 100%); min-height: 82px; margin: 0 auto; }
.demo-brand, .demo-tools, .demo-brand > div, .demo-tools { display: flex; align-items: center; }.demo-brand { gap: 10px; }.demo-brand > span { display: grid; place-items: center; width: 39px; height: 39px; color: #fff; background: #006a64; border-radius: 12px; }.demo-brand strong, .demo-brand small { display: block; }.demo-brand strong { color: #006a64; font-size: 18px; }.demo-brand small { margin-top: 2px; color: #84938e; font-size: 10px; }.demo-tools { gap: 15px; color: #68807a; font-size: 12px; }.demo-tools button, .demo-tools a { padding: 7px 10px; color: #006a64; background: #e1f2ee; border: 1px solid #cbe6e0; border-radius: 7px; font-size: 11px; font-weight: 700; text-decoration: none; cursor: pointer; }.demo-badge { color: #2d7d50; font-weight: 700; }
.demo-reconnect { display: flex; align-items: center; gap: 9px; width: min(1380px, 100%); margin: 0 auto 14px; padding: 11px 14px; color: #8b6537; background: #fff8e9; border: 1px solid #efd9aa; border-radius: 10px; }.demo-reconnect span { flex: 1; }.demo-reconnect button { padding: 6px 10px; color: #7d5d35; background: #fff; border: 1px solid #ead0a0; border-radius: 6px; cursor: pointer; }
.demo-shell { display: grid; grid-template-columns: 240px minmax(0, 1fr) 235px; gap: 18px; width: min(1380px, 100%); min-height: 720px; margin: 0 auto; }.demo-channel-panel, .demo-actions-panel, .demo-main { min-width: 0; padding: 20px; border: 1px solid #e0ebe7; border-radius: 16px; background: rgba(255,255,255,.9); box-shadow: 0 12px 30px rgba(26,66,59,.05); }.demo-panel-title { display: grid; gap: 5px; margin-bottom: 20px; }.demo-panel-title span, .demo-section-heading span, .demo-chat-head span { color: #79918c; font-size: 10px; font-weight: 800; letter-spacing: .12em; text-transform: uppercase; }.demo-panel-title strong { color: #263a35; font-size: 18px; }.demo-channel { margin: 4px -8px 12px; padding: 3px 8px 9px; border-radius: 10px; }.demo-channel.active { background: #e2f3ef; }.demo-channel > button { display: flex; align-items: center; gap: 7px; width: 100%; padding: 8px 0; color: #45635b; background: transparent; border: 0; text-align: left; cursor: pointer; }.demo-channel.active > button { color: #006a64; font-weight: 800; }.demo-channel button span { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.demo-channel button small { color: #84a19a; }.demo-channel-members { display: grid; gap: 7px; padding-left: 22px; color: #7b8e88; font-size: 11px; }.demo-channel-members span { display: flex; align-items: center; gap: 7px; }.demo-channel-members i, .demo-user > i, .demo-voice-card > i, .demo-message > i { display: grid; place-items: center; flex: 0 0 auto; color: #fff; border-radius: 50%; font-style: normal; font-weight: 800; }.demo-channel-members i { width: 20px; height: 20px; font-size: 9px; }.demo-channel-members span.speaking i { box-shadow: 0 0 0 2px #83e88d, 0 0 10px rgba(83,214,105,.45); }
+9 -6
View File
@@ -469,6 +469,7 @@
:screen-share-web-rtc-stats="screenShareWebRtcStats"
:t="t"
/>
<div id="webspeak-plugin-toolbar" class="webspeak-plugin-toolbar-host" data-ws-part="voice.plugin-toolbar"></div>
<button
class="header-action"
:title="t('copyInvite')"
@@ -1042,6 +1043,7 @@ const {
pokeNotifications,
microphoneMuted,
noiseSuppressionEnabled,
noiseSuppressionLevel,
inputVolume,
outputVolume,
outputMuted,
@@ -1064,7 +1066,7 @@ const {
whisperActive,
setVolume,
setInputVolume,
setNoiseSuppressionEnabled,
setNoiseSuppressionLevel,
setOutputVolume,
toggleOutputMute,
setVoxThreshold,
@@ -1113,8 +1115,9 @@ const {
ws: pluginVoiceSocket,
createInvite,
measureVoiceAudioStatus,
sessionTrace,
} = useVoiceWebSocket();
const performance = useWebClientPerformance(computed(() => voiceState.connected), measureVoiceAudioStatus);
const performance = useWebClientPerformance(computed(() => voiceState.connected), measureVoiceAudioStatus, sessionTrace);
const { panelOpen: performancePanelOpen } = performance;
const query = new URLSearchParams(location.search);
@@ -1256,7 +1259,7 @@ const skinHomeFeatures = computed(() => {
const audioControls = useWebClientAudioControls({
settingsOpen,
microphoneMuted,
noiseSuppressionEnabled,
noiseSuppressionLevel,
inputVolume,
voxThreshold,
notificationVolume,
@@ -1267,7 +1270,7 @@ const audioControls = useWebClientAudioControls({
whisperTargetIds,
prepareInputDevices,
setInputVolume,
setNoiseSuppressionEnabled,
setNoiseSuppressionLevel,
setOutputVolume,
setVoxThreshold,
setNotificationVolume,
@@ -1291,7 +1294,7 @@ function reconnectMobile(): void {
reconnectNow();
}
const { toggleMicrophone, stopWhisperTalk } = audioControls;
const audioDockState = { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionEnabled, accompanimentActive };
const audioDockState = { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionLevel, accompanimentActive };
const audioSettingsState = {
inputDevices,
outputDevices,
@@ -1301,7 +1304,7 @@ const audioSettingsState = {
audioPermission,
audioContextState,
microphoneMuted,
noiseSuppressionEnabled,
noiseSuppressionLevel,
inputVolume,
outputVolume,
voxThreshold,
+2
View File
@@ -6,6 +6,7 @@ export interface ConnectionFailure {
interface ConnectionOptions {
onSocket(socket: WebSocket | null): void;
onSocketOpen?(): void;
onMessage(message: unknown): void;
onAudio(frame: Uint8Array): void;
onClose(event: CloseEvent): void;
@@ -72,6 +73,7 @@ export function createVoiceConnection(options: ConnectionOptions) {
options.onSocket(socket);
socket.onopen = () => {
if (!isCurrent(record)) clean(() => socket.close(1000));
else options.onSocketOpen?.();
};
socket.onmessage = event => {
if (!isCurrent(record) || record.socket !== socket || socket.readyState !== WebSocket.OPEN) return;
+2 -2
View File
@@ -22,7 +22,7 @@ export interface MicrophoneCapture {
interface CaptureOptions {
context: AudioContext;
stream: MediaStream;
noiseSuppression: boolean;
rnnoiseEnabled: boolean;
volume: number;
signal: AbortSignal;
assertCurrent(): void;
@@ -92,7 +92,7 @@ export function createMicrophoneCaptureFactory() {
const settings = track.getSettings();
source = ctx.createMediaStreamSource(stream);
const supportsWorklet = typeof AudioWorkletNode !== "undefined" && Boolean(ctx.audioWorklet);
if (options.noiseSuppression && supportsWorklet) {
if (options.rnnoiseEnabled && supportsWorklet) {
try {
if (!wasmPromise) wasmPromise = loadRnnoise({ url: rnnoiseWasmUrl, simdUrl: rnnoiseSimdWasmUrl }).catch(error => {
wasmPromise = null;
+21
View File
@@ -0,0 +1,21 @@
/** Return an Opus packet's decoded duration in microseconds, or null if malformed. */
export function opusPacketDurationUs(packet: Uint8Array): number | null {
if (packet.length < 1) return null;
const toc = packet[0]!;
const config = toc >>> 3;
const frameDurationUs = config < 12
? [10_000, 20_000, 40_000, 60_000][config & 3]!
: config < 16
? [10_000, 20_000][config & 1]!
: [2_500, 5_000, 10_000, 20_000][config & 3]!;
const code = toc & 3;
let frameCount = 1;
if (code === 1 || code === 2) frameCount = 2;
else if (code === 3) {
if (packet.length < 2) return null;
frameCount = packet[1]! & 0x3f;
if (frameCount < 1 || frameCount > 48) return null;
}
const duration = frameDurationUs * frameCount;
return duration <= 120_000 ? duration : null;
}
+13 -9
View File
@@ -1,3 +1,5 @@
import { opusPacketDurationUs } from "./opus-packet.js";
interface RemotePlaybackOptions {
getContext(): AudioContext;
getVolume(clientId: number): number;
@@ -6,6 +8,7 @@ interface RemotePlaybackOptions {
}
interface SpeakerPlayback {
codec: 4 | 5;
context: AudioContext;
decoder: AudioDecoder | null;
gain: GainNode;
@@ -73,9 +76,9 @@ export function createRemotePlayback(options: RemotePlaybackOptions) {
}
}
function create(clientId: number, context: AudioContext): SpeakerPlayback {
function create(clientId: number, context: AudioContext, codec: 4 | 5): SpeakerPlayback {
const stream: SpeakerPlayback = {
context, decoder: null, gain: context.createGain(), sources: new Set(),
codec, context, decoder: null, gain: context.createGain(), sources: new Set(),
playTime: context.currentTime, timestamp: 0,
};
speakers.set(clientId, stream);
@@ -89,23 +92,24 @@ export function createRemotePlayback(options: RemotePlaybackOptions) {
clear(clientId);
},
});
stream.decoder.configure({ codec: "opus", sampleRate: 48000, numberOfChannels: 1 });
stream.decoder.configure({ codec: "opus", sampleRate: 48000, numberOfChannels: codec === 4 ? 1 : 2 });
return stream;
}
function play(clientId: number, opusData: Uint8Array): void {
if (opusData.length < 3) { options.onDrop(); return; }
function play(clientId: number, codec: 4 | 5, opusData: Uint8Array): void {
const duration = opusPacketDurationUs(opusData);
if (!duration || opusData.length < 3) { options.onDrop(); return; }
try {
const context = options.getContext();
let stream = speakers.get(clientId);
if (stream && (stream.context !== context || stream.playTime > context.currentTime + MAX_PLAY_AHEAD_SECONDS || (stream.decoder?.decodeQueueSize ?? 0) >= MAX_DECODE_QUEUE_FRAMES)) {
if (stream && (stream.codec !== codec || stream.context !== context || stream.playTime > context.currentTime + MAX_PLAY_AHEAD_SECONDS || (stream.decoder?.decodeQueueSize ?? 0) >= MAX_DECODE_QUEUE_FRAMES)) {
clear(clientId);
stream = undefined;
}
stream ??= create(clientId, context);
stream ??= create(clientId, context, codec);
if (speakers.get(clientId) !== stream) return;
stream.decoder?.decode(new EncodedAudioChunk({ type: "key", timestamp: stream.timestamp, duration: 20_000, data: opusData }));
stream.timestamp += 20_000;
stream.decoder?.decode(new EncodedAudioChunk({ type: "key", timestamp: stream.timestamp, duration, data: opusData }));
stream.timestamp += duration;
} catch {
options.onDecodeError();
clear(clientId);
+55
View File
@@ -0,0 +1,55 @@
import { shallowRef } from "vue";
export interface VoiceTraceEvent {
at: string;
event: string;
data: Record<string, string | number | boolean | null>;
}
const TRACE_WINDOW_MS = 120_000;
const TRACE_MAX_EVENTS = 240;
/** Keeps a short, local-only trace. Callers must pass state and counters, never user content. */
export function createVoiceSessionTrace() {
const events = shallowRef<VoiceTraceEvent[]>([]);
function record(event: string, data: Record<string, string | number | boolean | null> = {}): void {
const safeEvent = event.replace(/[^A-Za-z0-9_.-]/g, "_").slice(0, 64);
if (!safeEvent) return;
const safeData: VoiceTraceEvent["data"] = {};
for (const [key, value] of Object.entries(data)) {
if (!/^[A-Za-z][A-Za-z0-9_]{0,40}$/.test(key)) continue;
if (value === null) safeData[key] = null;
else if (typeof value === "boolean") safeData[key] = value;
else if (typeof value === "number" && Number.isFinite(value)) safeData[key] = Math.round(value * 100) / 100;
else if (typeof value === "string") safeData[key] = value.replace(/[^A-Za-z0-9_.:-]/g, "_").slice(0, 80);
}
const now = Date.now();
events.value = [...events.value.filter(item => now - Date.parse(item.at) <= TRACE_WINDOW_MS), {
at: new Date(now).toISOString(), event: safeEvent, data: safeData,
}].slice(-TRACE_MAX_EVENTS);
}
const visibility = () => record("page.visibility", { state: document.visibilityState });
const pageHide = () => record("page.lifecycle", { state: "pagehide" });
const pageShow = () => record("page.lifecycle", { state: "pageshow" });
document.addEventListener("visibilitychange", visibility);
window.addEventListener("pagehide", pageHide);
window.addEventListener("pageshow", pageShow);
record("page.lifecycle", { state: "loaded" });
visibility();
return {
events,
record,
snapshot: () => events.value
.filter(item => Date.now() - Date.parse(item.at) <= TRACE_WINDOW_MS)
.map(item => ({ ...item, data: { ...item.data } })),
dispose() {
document.removeEventListener("visibilitychange", visibility);
window.removeEventListener("pagehide", pageHide);
window.removeEventListener("pageshow", pageShow);
},
};
}
export type VoiceSessionTrace = ReturnType<typeof createVoiceSessionTrace>;
+6 -2
View File
@@ -2,6 +2,7 @@ import { isSessionDescription, type WebRtcClientMessage } from "../../../src/sha
import { createWebRtcInput, type WebRtcInput } from "./webrtc-input.js";
import { createMicrophoneMeter, type MicrophoneMeter } from "./microphone-meter.js";
import { createWebRtcPlayback, type WebRtcPlaybackOptions } from "./webrtc-playback.js";
import { addOpusFmtpParameters } from "../../../src/shared/opus-sdp.js";
interface Microphone {
context: AudioContext;
@@ -24,6 +25,7 @@ interface TransportOptions {
releaseAccompaniment(): void;
onLevel(rms: number | null, track: MediaStreamTrack): void;
onReady(): void;
onConnectionState?(state: RTCPeerConnectionState): void;
onFallback(reason: string, isCurrent: () => boolean): Promise<void>;
playback: WebRtcPlaybackOptions;
}
@@ -142,20 +144,22 @@ export function createWebRtcTransport(options: TransportOptions) {
};
record.meter = createMicrophoneMeter(context, stream, rms => options.onLevel(rms, track));
peer.onconnectionstatechange = () => {
options.onConnectionState?.(peer.connectionState);
if (isCurrent(record) && peer.connectionState === "failed") void fail(record, "WEBRTC_CONNECTION_FAILED");
};
options.onConnectionState?.(peer.connectionState);
record.active = true;
const offer = await peer.createOffer();
if (!isCurrent(record)) return;
await peer.setLocalDescription(offer);
await peer.setLocalDescription({ ...offer, sdp: addOpusFmtpParameters(offer.sdp ?? "", ["stereo=1"]) });
if (!isCurrent(record)) return;
await waitForIce(record, peer);
if (!isCurrent(record)) return;
const description = peer.localDescription;
if (!description || description.type !== "offer") throw new Error("WebRTC offer was not created");
connection.send({ type: "webrtcOffer", payload: {
sdp: { type: "offer", sdp: description.sdp },
sdp: { type: "offer", sdp: addOpusFmtpParameters(description.sdp, ["stereo=1"]) },
muted: options.muted(), accompanimentActive: options.accompanimentActive(),
} });
record.answerTimer = window.setTimeout(() => {
+2 -1
View File
@@ -55,7 +55,8 @@ after(async () => {
else delete globalThis.window;
});
async function mount() {
app = renderer.createApp({ setup() { monitor = useWebClientPerformance(connected, () => measure()); return () => null; } });
const trace = { events: ref([]), record() {}, snapshot: () => [] };
app = renderer.createApp({ setup() { monitor = useWebClientPerformance(connected, () => measure(), trace); return () => null; } });
app.mount({});
await nextTurn();
}