diff --git a/docs/SKIN_DEVELOPMENT.md b/docs/SKIN_DEVELOPMENT.md index c043674..a11aa48 100644 --- a/docs/SKIN_DEVELOPMENT.md +++ b/docs/SKIN_DEVELOPMENT.md @@ -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` | diff --git a/src/plugins/registry.ts b/src/plugins/registry.ts index 37b630c..1de84c6 100644 --- a/src/plugins/registry.ts +++ b/src/plugins/registry.ts @@ -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{return this.mutate(async()=>{ diff --git a/src/plugins/runtime.ts b/src/plugins/runtime.ts index e0ea0f5..06e3026 100644 --- a/src/plugins/runtime.ts +++ b/src/plugins/runtime.ts @@ -105,7 +105,7 @@ export class PluginRuntime { async restart(id:string):Promise{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"); diff --git a/src/server/webrtc-audio.test.ts b/src/server/webrtc-audio.test.ts index 67ad6a1..89a5de9 100644 --- a/src/server/webrtc-audio.test.ts +++ b/src/server/webrtc-audio.test.ts @@ -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"); } }], diff --git a/src/server/webrtc-audio.ts b/src/server/webrtc-audio.ts index c460911..c702e3e 100644 --- a/src/server/webrtc-audio.ts +++ b/src/server/webrtc-audio.ts @@ -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(); + private readonly decoderCodecByClient = new Map(); private readonly partialPcmByClient = new Map(); private readonly pendingFrames = new Map(); private readonly memberVolumes = new Map(); @@ -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 */ } } diff --git a/src/shared/opus-sdp.ts b/src/shared/opus-sdp.ts new file mode 100644 index 0000000..e0950eb --- /dev/null +++ b/src/shared/opus-sdp.ts @@ -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(";")}`; + } +} diff --git a/src/shared/plugins.ts b/src/shared/plugins.ts index 2fc97dc..a6bc41f 100644 --- a/src/shared/plugins.ts +++ b/src/shared/plugins.ts @@ -15,9 +15,9 @@ export interface PluginManifest { } export interface PluginFile { encoding: "utf8" | "base64"; data: string } export interface PluginPackage { manifest: PluginManifest; files: Record } -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; } diff --git a/src/shared/skin-layout.ts b/src/shared/skin-layout.ts index 39ca295..ee0d091 100644 --- a/src/shared/skin-layout.ts +++ b/src/shared/skin-layout.ts @@ -278,6 +278,7 @@ const PUBLIC_PART_IDS = new Set([ "voice.favorite-servers.tooltip", "voice.header", "voice.header-actions", + "voice.plugin-toolbar", "voice.member", "voice.member-panel", "voice.member-panel.channels", diff --git a/web/src/components/PluginPanel.vue b/web/src/components/PluginPanel.vue index 604709a..29705fe 100644 --- a/web/src/components/PluginPanel.vue +++ b/web/src/components/PluginPanel.vue @@ -1,10 +1,14 @@