From 4ead174c047f22827ec58b5c22561b280d10c3ed Mon Sep 17 00:00:00 2001 From: LainHE <64828020+EchoSixHIYA@users.noreply.github.com> Date: Wed, 16 Sep 2026 22:24:25 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B5=8F=E8=A7=88=E5=99=A8=E7=AB=AF?= =?UTF-8?q?=E6=8A=A5=E9=94=99=E7=BF=BB=E8=AF=91=E4=B8=8E=E6=8F=90=E7=A4=BA?= =?UTF-8?q?=E6=94=B9=E9=80=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - errors: 新增 TeamSpeak 服务器错误 ID 映射表与不可重连错误码集合,归一化 normalizeTeamSpeakError 按 错误ID/关键词/异常类/传输层特征 分级收敛错误 - voice-bridge: 身份无效/客户端不可用时先发结构化 connectionFailed 帧再关闭, 新增 pendingKickReason 机制在 kicked 事件后优先回放踢出原因;Opus 编码器 不可用时限流上报 AUDIO_ENCODER_UNAVAILABLE - ts-client: 记录本端退出 reasonID,转发 kicked 事件并归一化踢出/封禁原因 - network-probe/teamspeak-probe: 收窄关键字匹配、拒绝原因收敛到既有探测码 - session-manager: 新增 teamSpeak-kicked 拆除原因 - WebClient: 麦克风失败不再假成功,音频状态避免自相矛盾,新增降级横幅与 中/英/德三语提示词表 - useVoiceWebSocket: 导出 ensureMicrophone 供开麦前预检,新增音频诊断状态、 CONNECTION_FAILURE_MESSAGES 总表与网关关闭码映射 - 关键新增逻辑补充中文注释说明改动意图 --- src/errors.ts | 271 +++++++++++++++++++-- src/server/network-probe.ts | 11 +- src/server/session-manager.ts | 1 + src/server/teamspeak-probe.ts | 16 ++ src/server/ts-client.ts | 20 +- src/server/voice-bridge.ts | 70 +++++- web/src/composables/useVoiceWebSocket.ts | 286 +++++++++++++++++++---- web/src/views/WebClient.vue | 76 +++++- 8 files changed, 677 insertions(+), 74 deletions(-) diff --git a/src/errors.ts b/src/errors.ts index 57cf65f..ae9b577 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -1,19 +1,31 @@ export type WebSpeakErrorCode = | "invalid_target" | "invalid_nickname" + | "nickname_in_use" | "host_not_found" | "unreachable" | "connection_refused" | "connection_reset" | "timeout" | "authentication_failed" - | "protocol_negotiation_failed" + | "channel_password_required" + | "identity_security_level_too_low" + | "identity_limit_reached" + | "client_version_outdated" + | "flooding" + | "banned" + | "kicked" + | "server_shutting_down" | "server_full" + | "invalid_parameter_size" + | "connection_initialisation_failed" + | "protocol_negotiation_failed" | "unknown"; export type ClientConnectionFailureCode = | "INVALID_TARGET" | "INVALID_NICKNAME" + | "NICKNAME_IN_USE" | "HOST_NOT_FOUND" | "UNREACHABLE" | "CONNECTION_REFUSED" @@ -21,8 +33,18 @@ export type ClientConnectionFailureCode = | "TIMEOUT" | "SERVER_PASSWORD_REQUIRED" | "INVALID_SERVER_PASSWORD" + | "CHANNEL_PASSWORD_REQUIRED" + | "IDENTITY_SECURITY_LEVEL_TOO_LOW" + | "IDENTITY_LIMIT_REACHED" + | "CLIENT_VERSION_OUTDATED" + | "FLOOD_PROTECTION" + | "BANNED" + | "KICKED" + | "SERVER_SHUTTING_DOWN" + | "SERVER_FULL" + | "INVALID_PARAMETER" | "PROTOCOL_NEGOTIATION_FAILED" - | "SERVER_REJECTED" + | "CONNECTION_INITIALISATION_FAILED" | "CONNECTION_FAILED"; export interface TeamSpeakErrorDiagnostics { @@ -53,37 +75,220 @@ export class WebSpeakError extends Error { } } +/** + * TeamSpeak server error ids (SDK `public_errors.h`, shared by TS3 and TS6) that + * the gateway can name precisely. Ids that are absent on purpose fall through to + * the text heuristics below and finally to `unknown`, which still carries the raw + * server detail to the browser. + */ +export const TEAMSPEAK_SERVER_ERROR_IDS: Readonly> = { + // Client (0x02xx): nickname, capacity, identity, password, version, flooding. + "513": "nickname_in_use", + "515": "server_full", + "519": "identity_security_level_too_low", + "520": "authentication_failed", + "521": "identity_limit_reached", + "522": "client_version_outdated", + "524": "flooding", + // Parameter (0x06xx). During the connect handshake the only size-checked value + // the gateway sends is the nickname, so 1541 is reported as a nickname problem + // instead of a generic parameter error. + "1536": "invalid_parameter_size", + "1537": "invalid_parameter_size", + "1538": "invalid_parameter_size", + "1539": "invalid_parameter_size", + "1540": "invalid_parameter_size", + "1541": "invalid_nickname", + "1542": "invalid_parameter_size", + "1543": "protocol_negotiation_failed", + // Connection (0x07xx). + "1792": "connection_reset", + "1794": "channel_password_required", + "1796": "connection_initialisation_failed", + "1797": "host_not_found", + "1804": "unreachable", + "1805": "protocol_negotiation_failed", + "1806": "protocol_negotiation_failed", + // Server (0x04xx). + "1041": "server_shutting_down", + // Accounting (0x0bxx): the slot and virtual-server limits both surface as a + // full server from the user's point of view. + "2816": "server_full", + "2817": "server_full", + "2825": "protocol_negotiation_failed", + // Ban (0x0dxx). + "3329": "banned", + "3330": "banned", + "3331": "flooding", +}; + +/** + * Default (English) message per normalized code. The browser translates these + * strings for zh/en/de, so keep them stable and never embed a raw server id here: + * the raw detail travels separately in `diagnostics`. + */ +export const WEBSPEAK_ERROR_MESSAGES: Readonly> = { + invalid_target: "The TeamSpeak server address is invalid", + invalid_nickname: "TeamSpeak refused the nickname: it must be 3-30 characters long", + nickname_in_use: "This nickname is already used by another user on the TeamSpeak server", + host_not_found: "TeamSpeak server hostname could not be resolved", + unreachable: "TeamSpeak server is unreachable", + connection_refused: "TeamSpeak server refused the connection", + connection_reset: "TeamSpeak connection was reset", + timeout: "TeamSpeak connection timed out", + authentication_failed: "TeamSpeak authentication failed", + channel_password_required: "The TeamSpeak channel requires a password", + identity_security_level_too_low: "This TeamSpeak identity's security level is below the server requirement", + identity_limit_reached: "This TeamSpeak identity already holds the maximum number of connections", + client_version_outdated: "The TeamSpeak server requires a newer client version", + flooding: "The TeamSpeak server's flood protection refused the connection", + banned: "You are banned from this TeamSpeak server", + kicked: "You were kicked from the TeamSpeak server", + server_shutting_down: "The TeamSpeak server is shutting down", + connection_initialisation_failed: "The TeamSpeak server refused the connection during initialisation", + server_full: "The TeamSpeak server is full", + invalid_parameter_size: "TeamSpeak refused a parameter because its length or value is out of range", + protocol_negotiation_failed: "TeamSpeak protocol negotiation failed", + unknown: "TeamSpeak connection failed", +}; + +// 不可重连的错误码集合:这些错误原样重连必然失败(如被封禁、昵称被占用等), +// 集合与消息表相邻存放便于审计重连决策;unknown 保持不可重连,防止未映射的 +// 服务器拒绝演变成无限重连循环。 +/** + * Codes for which reconnecting unchanged cannot succeed. Keeping the list next to + * the messages makes the retry decision auditable; `unknown` stays non-retryable + * so an unmapped server refusal can never turn into a reconnect loop. + */ +const NON_RETRYABLE_CODES: ReadonlySet = new Set([ + "invalid_target", + "invalid_nickname", + "nickname_in_use", + "authentication_failed", + "channel_password_required", + "identity_security_level_too_low", + "identity_limit_reached", + "client_version_outdated", + "banned", + "kicked", + "invalid_parameter_size", + "connection_initialisation_failed", + "unknown", +]); + +function createTeamSpeakError(code: WebSpeakErrorCode, cause: unknown, diagnostics: TeamSpeakErrorDiagnostics): WebSpeakError { + return new WebSpeakError(code, WEBSPEAK_ERROR_MESSAGES[code], !NON_RETRYABLE_CODES.has(code), cause, diagnostics); +} + +/** + * Resolve a raw TeamSpeak server error id to a normalized code. Accepts the + * decimal form the SDK forwards (`err.id`, `id=515`) and the hex form used by the + * official headers (`0x0203`), because both shapes show up in logs. + */ +export function teamSpeakServerErrorCode(id: unknown): WebSpeakErrorCode | null { + if (id === undefined || id === null) return null; + const text = String(id).trim().toLocaleLowerCase(); + if (/^\d{1,6}$/.test(text)) return TEAMSPEAK_SERVER_ERROR_IDS[String(Number(text))] ?? null; + const hexMatch = /^(?:0x)?([0-9a-f]{4,6})$/.exec(text); + if (hexMatch) return TEAMSPEAK_SERVER_ERROR_IDS[String(parseInt(hexMatch[1], 16))] ?? null; + return null; +} + +// 归一化入口:按「服务器错误ID → 关键词启发式 → 异常类名 → 传输层特征」的 +// 优先级,把 SDK/Node 抛出的原始错误收敛为带稳定错误码的 WebSpeakError。 export function normalizeTeamSpeakError(error: unknown): WebSpeakError { if (error instanceof WebSpeakError) return error; const diagnostics = collectDiagnostics(error); const text = diagnosticText(error).toLocaleLowerCase(); - if (/password|authenticate|authentication|not authorized|invalid.*(credential|password)/.test(text)) { - return new WebSpeakError("authentication_failed", "TeamSpeak authentication failed", false, error, diagnostics); + // 1) A TeamSpeak server error id names the exact reason, so it outranks every + // keyword heuristic below. Only 1541 used to be recognised, which pushed + // "banned", "server is full" and every other refusal into the generic + // fallback. The inline scan keeps the `id=515` shape working even when the + // SDK does not attach the id as a structured field. + const inlineId = /\bid[\s=:]*(\d{3,5})\b/.exec(text)?.[1]; + const serverErrorCode = + teamSpeakServerErrorCode(diagnostics.id) ?? teamSpeakServerErrorCode(diagnostics.code) ?? teamSpeakServerErrorCode(inlineId); + if (serverErrorCode) return createTeamSpeakError(serverErrorCode, error, diagnostics); + + // 2) Explicit refusals that arrive without a stable id. Every pattern stays + // narrow on purpose: bare words such as "password", "network", "socket", + // "crypto" or "denied" also appear in unrelated Teamspeak messages and used + // to steal the classification from the real cause. + if (/invalid[\s_-]*parameter[\s_-]*size|parameter.{0,20}(size|out of range)|nickname.{0,20}(length|size)/.test(text)) { + return createTeamSpeakError("invalid_nickname", error, diagnostics); } - if (/invalid parameter size|nickname.{0,20}(length|size)|(?:length|size).{0,20}nickname|id[=: ]1541/.test(text)) { - return new WebSpeakError("invalid_nickname", "TeamSpeak nickname length is invalid", false, error, diagnostics); + if (/nickname.{0,30}(in use|already (in )?use|taken|exists)|nickname_in_use/.test(text)) { + return createTeamSpeakError("nickname_in_use", error, diagnostics); } - if (/enotfound|eai_again|host not found|name or service not known|dns/.test(text)) { - return new WebSpeakError("host_not_found", "TeamSpeak server hostname could not be resolved", true, error, diagnostics); + if (/channel.{0,30}password|password.{0,30}channel|i_channel_password/.test(text)) { + return createTeamSpeakError("channel_password_required", error, diagnostics); + } + if (/security ?level|insufficient security|could not validate identity/.test(text)) { + return createTeamSpeakError("identity_security_level_too_low", error, diagnostics); + } + if (/too many clones|clone.{0,20}(limit|connected)|identity.{0,20}(limit|maximum|max).{0,20}connection/.test(text)) { + return createTeamSpeakError("identity_limit_reached", error, diagnostics); + } + if (/version.{0,25}(outdated|out of date|too old|not allowed|unsupported)|outdated.{0,25}version/.test(text)) { + return createTeamSpeakError("client_version_outdated", error, diagnostics); + } + if (/flood/.test(text)) { + return createTeamSpeakError("flooding", error, diagnostics); + } + if (/\bban(ned)?\b|blacklist|you may retry in/.test(text)) { + return createTeamSpeakError("banned", error, diagnostics); + } + if (/kicked/.test(text)) { + return createTeamSpeakError("kicked", error, diagnostics); + } + if (/server.{0,20}shut ?down|server_shutdown|server is shutting down/.test(text)) { + return createTeamSpeakError("server_shutting_down", error, diagnostics); + } + if (/failed[\s_-]*connection[\s_-]*initiali[sz]ation|connection initiali[sz]ation failed|failed to (initialise|initialize) the connection/.test(text)) { + return createTeamSpeakError("connection_initialisation_failed", error, diagnostics); + } + if (/server.{0,25}full|server is full|maximum (number of )?(clients|slots)|slot limit|client protocol limit/.test(text)) { + return createTeamSpeakError("server_full", error, diagnostics); + } + if (/invalid (server )?password|wrong (server )?password|password (is )?(invalid|incorrect|wrong)|password required|i_server_password|authentication failed|not authorized|invalid credential|login (failed|refused)/.test(text)) { + return createTeamSpeakError("authentication_failed", error, diagnostics); + } + + // 3) SDK handshake/crypto error classes carry no numeric id at all, so match + // the class name before falling back to the message text. + const errorName = (diagnostics.name ?? "").toLocaleLowerCase(); + if (/eaxtagmismatch|fakesignaturemismatch|cryptoinit|invalididentity|license/.test(errorName)) { + return createTeamSpeakError("protocol_negotiation_failed", error, diagnostics); + } + if (/alreadyconnected/.test(errorName)) { + return createTeamSpeakError("identity_limit_reached", error, diagnostics); + } + if (/timeout/.test(errorName)) { + return createTeamSpeakError("timeout", error, diagnostics); + } + + // 4) Transport level failures reported by Node or the TLS layer. + if (/enotfound|eai_again|host not found|name or service not known|getaddrinfo/.test(text)) { + return createTeamSpeakError("host_not_found", error, diagnostics); } if (/econnrefused|connection refused/.test(text)) { - return new WebSpeakError("connection_refused", "TeamSpeak server refused the connection", true, error, diagnostics); + return createTeamSpeakError("connection_refused", error, diagnostics); } - if (/econnreset|econnaborted|connection reset|connection aborted/.test(text)) { - return new WebSpeakError("connection_reset", "TeamSpeak connection was reset", true, error, diagnostics); + if (/econnreset|econnaborted|connection reset|connection aborted|socket hang up/.test(text)) { + return createTeamSpeakError("connection_reset", error, diagnostics); } if (/timeout|timed out|ack timeout|idle timeout|etimedout/.test(text)) { - return new WebSpeakError("timeout", "TeamSpeak connection timed out", true, error, diagnostics); + return createTeamSpeakError("timeout", error, diagnostics); } - if (/ehostunreach|enetunreach|network is unreachable|no route to host|network|socket/.test(text)) { - return new WebSpeakError("unreachable", "TeamSpeak server is unreachable", true, error, diagnostics); + if (/ehostunreach|enetunreach|network is unreachable|no route to host|unable to connect|transport error|unexpected eof/.test(text)) { + return createTeamSpeakError("unreachable", error, diagnostics); } - if (/protocol|handshake|crypto|init1/.test(text)) { - return new WebSpeakError("protocol_negotiation_failed", "TeamSpeak protocol negotiation failed", true, error, diagnostics); + if (/handshake|protocol|eax|crypto ?(init|handshake|setup)|init1|signature|license/.test(text)) { + return createTeamSpeakError("protocol_negotiation_failed", error, diagnostics); } - return new WebSpeakError("unknown", "TeamSpeak connection failed", false, error, diagnostics); + return createTeamSpeakError("unknown", error, diagnostics); } export function clientConnectionFailureCode(error: WebSpeakError, serverPassword = ""): ClientConnectionFailureCode { @@ -93,19 +298,49 @@ export function clientConnectionFailureCode(error: WebSpeakError, serverPassword const mapping: Record = { invalid_target: "INVALID_TARGET", invalid_nickname: "INVALID_NICKNAME", + nickname_in_use: "NICKNAME_IN_USE", host_not_found: "HOST_NOT_FOUND", unreachable: "UNREACHABLE", connection_refused: "CONNECTION_REFUSED", connection_reset: "CONNECTION_RESET", timeout: "TIMEOUT", authentication_failed: "SERVER_PASSWORD_REQUIRED", + channel_password_required: "CHANNEL_PASSWORD_REQUIRED", + identity_security_level_too_low: "IDENTITY_SECURITY_LEVEL_TOO_LOW", + identity_limit_reached: "IDENTITY_LIMIT_REACHED", + client_version_outdated: "CLIENT_VERSION_OUTDATED", + flooding: "FLOOD_PROTECTION", + banned: "BANNED", + kicked: "KICKED", + server_shutting_down: "SERVER_SHUTTING_DOWN", + connection_initialisation_failed: "CONNECTION_INITIALISATION_FAILED", + server_full: "SERVER_FULL", + invalid_parameter_size: "INVALID_PARAMETER", protocol_negotiation_failed: "PROTOCOL_NEGOTIATION_FAILED", - server_full: "SERVER_REJECTED", unknown: "CONNECTION_FAILED", }; return mapping[error.code]; } +/** + * Normalize the SDK `kicked` event. TeamSpeak reports a kick/ban as a + * `clientleftview` whose reason id is 4 (kicked) or 5 (kicked with ban) and whose + * `reasonMsg` is written by the admin, e.g. "Slow down!" or "you may retry in + * 300 seconds". Before this helper existed the reason text was dropped and the + * browser only showed a generic connection failure, which is exactly the + * experience this translation layer removes. The ban/kick split prefers the + * server text and falls back to reason id 5. + */ +export function normalizeTeamSpeakKickedReason(reasonMsg: unknown, reasonId?: unknown): WebSpeakError { + const text = typeof reasonMsg === "string" ? reasonMsg.trim() : ""; + const numericReasonId = typeof reasonId === "number" ? reasonId : Number(reasonId); + const isBan = /\bban(ned)?\b|blacklist|you may retry in/i.test(text) || numericReasonId === 5; + const diagnostics: TeamSpeakErrorDiagnostics = { name: isBan ? "TeamSpeakBan" : "TeamSpeakKick" }; + if (text) diagnostics.serverMessage = text; + if (Number.isFinite(numericReasonId)) diagnostics.id = String(numericReasonId); + return createTeamSpeakError(isBan ? "banned" : "kicked", reasonMsg, diagnostics); +} + /** Format useful SDK/Node details for a safe operational log field. */ export function describeTeamSpeakError(error: WebSpeakError): string { const details = error.diagnostics; diff --git a/src/server/network-probe.ts b/src/server/network-probe.ts index 1000860..5cae769 100644 --- a/src/server/network-probe.ts +++ b/src/server/network-probe.ts @@ -114,9 +114,14 @@ function classifyProbeError(error: unknown): TeamSpeakPingErrorCode { if (/enoent|spawn\s+(?:ping(?:\.exe)?|ping)\s+.*not found|command not found/.test(lower)) return "PING_UNAVAILABLE"; if (/enotfound|eai_again|getaddrinfo|host not found|unknown host|could not find host|name or service not known/.test(lower)) return "HOST_NOT_FOUND"; if (/timeout|timed out|packet ack timeout|idle timeout/.test(lower)) return "TIMEOUT"; - if (/password|authentication|invalid.*credential/.test(lower)) return "INVALID_PASSWORD"; - if (/protocol|version|handshake|negotiat/.test(lower)) return "PROTOCOL_NEGOTIATION_FAILED"; - if (/reject|full|denied/.test(lower)) return "SERVER_REJECTED"; + // 关键词刻意收窄:裸的 password/version/denied 会出现在大量无关的 ping/传输 + // 输出中,误判会把用户引向错误的排查方向,只把明确的短语视为证据。 + // Keep the keywords narrow: a bare "password", "version" or "denied" appears in + // plenty of unrelated ping/transport output, and guessing here used to send the + // user to the wrong remedy. Only explicit phrases are treated as evidence. + if (/invalid password|password (?:required|incorrect|wrong|rejected)|authentication failed|invalid credential/.test(lower)) return "INVALID_PASSWORD"; + if (/protocol (?:version )?(?:mismatch|not supported|error)|version (?:is )?(?:outdated|too old|not supported)|handshake (?:failed|error|timeout)|negotiation failed/.test(lower)) return "PROTOCOL_NEGOTIATION_FAILED"; + if (/server (?:is )?full|slot limit|client protocol limit|banned?|flooding|server rejected|connection (?:denied|refused) by (?:the )?server/.test(lower)) return "SERVER_REJECTED"; return "UNREACHABLE"; } diff --git a/src/server/session-manager.ts b/src/server/session-manager.ts index 421682c..d11d32e 100644 --- a/src/server/session-manager.ts +++ b/src/server/session-manager.ts @@ -17,6 +17,7 @@ export type SessionTeardownReason = | "websocket-error" | "protocol-error" | "teamSpeak-disconnect" + | "teamSpeak-kicked" // 会话被 TeamSpeak 服务器踢出/封禁时拆除 | "teamSpeak-connect-failed" | "heartbeat-timeout" | "admin-terminated" diff --git a/src/server/teamspeak-probe.ts b/src/server/teamspeak-probe.ts index 9740e8c..20810a6 100644 --- a/src/server/teamspeak-probe.ts +++ b/src/server/teamspeak-probe.ts @@ -103,15 +103,31 @@ export function toProbeError(error: unknown, password = ""): TeamSpeakProbeError if (/enotfound|eai_again|getaddrinfo|host not found/.test(raw)) { return new TeamSpeakProbeError("HOST_NOT_FOUND", "TeamSpeak host was not found", error); } + // 探测只回答「该地址是否可用」,因此把网关能细分的拒绝原因收敛到既有探测码, + // 具体原因由连接/重连路径向浏览器上报。 + // The probe only answers "can this address be used at all", so the richer + // rejection reasons the gateway can now name are bucketed into the existing + // probe codes; the exact reason is reported by the connect/reconnect path. const mapping: Record = { invalid_target: "INTERNAL_ERROR", invalid_nickname: "INVALID_NICKNAME", + nickname_in_use: "INVALID_NICKNAME", + invalid_parameter_size: "INVALID_NICKNAME", unreachable: "UNREACHABLE", host_not_found: "HOST_NOT_FOUND", connection_refused: "CONNECTION_REFUSED", connection_reset: "CONNECTION_RESET", timeout: "TIMEOUT", authentication_failed: password.trim() ? "INVALID_PASSWORD" : "PASSWORD_REQUIRED", + channel_password_required: "PASSWORD_REQUIRED", + identity_security_level_too_low: "SERVER_REJECTED", + identity_limit_reached: "SERVER_REJECTED", + client_version_outdated: "SERVER_REJECTED", + flooding: "SERVER_REJECTED", + banned: "SERVER_REJECTED", + kicked: "SERVER_REJECTED", + server_shutting_down: "SERVER_REJECTED", + connection_initialisation_failed: "SERVER_REJECTED", protocol_negotiation_failed: "PROTOCOL_NEGOTIATION_FAILED", server_full: "SERVER_REJECTED", unknown: "SERVER_REJECTED", diff --git a/src/server/ts-client.ts b/src/server/ts-client.ts index 106c629..9e55f79 100644 --- a/src/server/ts-client.ts +++ b/src/server/ts-client.ts @@ -14,7 +14,7 @@ import { type TextMessage, } from "@echosixhiya/teamspeak-client"; import type { Logger } from "../logger.js"; -import { describeTeamSpeakError, normalizeTeamSpeakError } from "../errors.js"; +import { describeTeamSpeakError, normalizeTeamSpeakError, normalizeTeamSpeakKickedReason } from "../errors.js"; import { TeamSpeakAdapter, type TeamSpeakProtocol } from "./teamspeak-adapter.js"; import type { TeamSpeakTarget } from "../domain/teamspeak-target.js"; import { createAccelerationRelayClient, type AccelerationRelayClient, type AccelerationRelayOptions } from "./acceleration-relay.js"; @@ -74,6 +74,10 @@ export class TSClient extends EventEmitter { private connected = false; private preferredChannelId = 0n; private accelerationClient: AccelerationRelayClient | null = null; + // Reason id of the most recent self leave, kept so the SDK `kicked` event can + // tell a plain kick (4) from a kick with ban (5). The SDK only forwards the + // reason message to its `kicked` handler, not the reason id. + private selfLeaveReasonId: number | null = null; constructor(private options: TSClientOptions, logger: Logger) { super(); @@ -214,9 +218,23 @@ export class TSClient extends EventEmitter { }); client.on("clientLeave", (info) => { + // 仅记录本客户端的踢出(4)/踢出并封禁(5)退出原因,供 kicked 事件区分普通踢出与封禁 + if (info.id === this.clientId && (info.reasonID === 4 || info.reasonID === 5)) this.selfLeaveReasonId = info.reasonID; this.emit("clientLeave", info); }); + // 转发 SDK 的 kicked 事件:不转发的话管理员填写的踢出原因会被丢弃,浏览器 + // 只能看到笼统的「连接失败」。这里把原因连同 reason id 一起归一化后向上抛。 + // The SDK emits `kicked` only for a self leave with reason 4 (kick) or 5 + // (kick with ban) and hands over the admin written reason message. Without + // this listener the reason was dropped, so the browser degraded to a generic + // "connection failed" right after the transport went away. + client.on("kicked", (reasonMsg) => { + const reasonId = this.selfLeaveReasonId; + this.selfLeaveReasonId = null; + this.emit("kicked", normalizeTeamSpeakKickedReason(reasonMsg, reasonId)); + }); + client.on("clientMoved", (info) => { if (info.id === this.clientId && info.targetChannelID !== 0n) this.preferredChannelId = info.targetChannelID; this.emit("clientMoved", info); diff --git a/src/server/voice-bridge.ts b/src/server/voice-bridge.ts index 395f144..8ed663e 100644 --- a/src/server/voice-bridge.ts +++ b/src/server/voice-bridge.ts @@ -6,7 +6,7 @@ import { identityFromString } from "@echosixhiya/teamspeak-client"; import { DirectorySynchronizer } from "./directory-sync.js"; import { TSClient, type TSDirectorySnapshot, type TSVoiceData } from "./ts-client.js"; import type { Logger as LoggerType } from "../logger.js"; -import { clientConnectionFailureCode, describeTeamSpeakError, normalizeTeamSpeakError } from "../errors.js"; +import { clientConnectionFailureCode, describeTeamSpeakError, normalizeTeamSpeakError, teamSpeakServerErrorCode, type WebSpeakError } from "../errors.js"; import { formatTeamSpeakTarget, teamSpeakTargetKey, type TeamSpeakTarget } from "../domain/teamspeak-target.js"; import { JoinTicketStore, type JoinTicketPayload } from "./join-ticket.js"; import { IdentityLeaseStore } from "./identity-lease.js"; @@ -141,6 +141,7 @@ interface WebClientEntry { members: Map; eventLog: ServerEvent[]; opusEncoder: { encode(pcm: Buffer): Buffer } | null; + opusEncoderWarnedAt: number; // Opus 编码器不可用告警的时间戳,用于限流避免反复刷屏 whisperTargetIds: Set; whisperActive: boolean; isAlive: boolean; @@ -191,7 +192,10 @@ export class VoiceBridge { try { identity = connection.identity ? identityFromString(connection.identity) : undefined; } catch { - ws.close(4003, "Invalid identity"); + // Send a structured failure before the close so the browser can tell + // an invalid remembered identity apart from a real connection failure. + if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: "connectionFailed", code: "IDENTITY_INVALID", detail: "Invalid identity" })); + ws.close(4003, "IDENTITY_INVALID"); return; } const entryId = `w-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`; @@ -229,8 +233,11 @@ export class VoiceBridge { } catch (error: unknown) { if (identityLeaseKey) this.identityLeases.release(identityLeaseKey, entryId); this.logger.error({ err: error, entryId }, "Could not create TeamSpeak client"); - void this.sessionManager.teardown(entryId, "teamSpeak-connect-failed"); - ws.close(4003, "TeamSpeak client unavailable"); + // A 4003 with a bare close used to be reported as "identity rejected". + // Send a structured failure so the browser says the TeamSpeak client + // could not be created (server down / unreachable) instead. + if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: "connectionFailed", code: "TEAM_SPEAK_CLIENT_UNAVAILABLE", detail: "TeamSpeak client unavailable" })); + ws.close(4003, "TEAM_SPEAK_CLIENT_UNAVAILABLE"); return; } entry = { @@ -250,6 +257,7 @@ export class VoiceBridge { members: new Map(), eventLog: [], opusEncoder: null, + opusEncoderWarnedAt: 0, whisperTargetIds: new Set(), whisperActive: false, isAlive: true, @@ -274,6 +282,10 @@ export class VoiceBridge { let audioReady = true; let realtimeReady = false; let hasConnectedOnce = false; + // Set when the server kicks or bans this client. The kick and the transport + // drop can arrive in either order, so the reason is parked here and consumed + // by whichever handler runs second. + let pendingKickReason: WebSpeakError | null = null; let reconnectStartedAt = 0; let reconnectAttempt = 0; const directory = new DirectorySynchronizer(); @@ -338,6 +350,8 @@ export class VoiceBridge { initialStateSent = true; const wasReconnecting = hasConnectedOnce; hasConnectedOnce = true; + // A previous kick reason never applies to a fresh, successful session. + pendingKickReason = null; reconnectAttempt = 0; reconnectStartedAt = 0; if (!wasReconnecting) { @@ -602,10 +616,30 @@ export class VoiceBridge { addServerEvent("poke", `${event.invokerName || "用户"} 戳了你一下`); }); + // 被踢/封禁对本会话是终态:把服务器给出的原因回放给浏览器并拆除会话, + // 而不是像以前那样因原因被丢弃而反复重连、再次撞上同一踢出。 + // A kick or ban is terminal for this session: replay the reason the server + // sent instead of reconnecting, which is what used to happen once the reason + // message was dropped (the browser kept retrying straight into the kick). + tsClient.on("kicked", (kick: WebSpeakError) => { + if (!hasConnectedOnce || session.state !== "connected") return; + pendingKickReason = kick; + resetDirectoryForReconnect(); + const failureCode = clientConnectionFailureCode(kick, serverPassword); + const failureDetail = publicFailureDetail(kick); + entry!.connectionFailureCode = failureCode; + this.logger.warn({ entryId, code: failureCode, normalizedCode: kick.code, failureDetail: describeTeamSpeakError(kick) }, "TeamSpeak session ended by kick/ban"); + sendJson({ type: "connectionFailed", code: failureCode, ...(failureDetail ? { detail: failureDetail } : {}) }); + void this.teardown(entryId, "teamSpeak-kicked"); + }); + tsClient.on("disconnected", (error?: Error) => { if (!hasConnectedOnce || session.state !== "connected") return; resetDirectoryForReconnect(); - const normalized = error ? normalizeTeamSpeakError(error) : null; + // Prefer a kick reason over the generic transport error that follows it, + // regardless of which of the two events arrives first. + const normalized = pendingKickReason ?? (error ? normalizeTeamSpeakError(error) : null); + pendingKickReason = null; sendJson({ type: "disconnected", recoverable: isRecoverable(normalized) }); scheduleReconnect(normalized); }); @@ -637,6 +671,16 @@ export class VoiceBridge { entry!.audio.tsSendFirstAt ??= sentAt; entry!.audio.tsSendLastAt = sentAt; entry!.audio.tsSendFrames++; + } else { + // Opus 编码器不可用(初始化失败或销毁后仍有帧在途):显式告知浏览器 + // 而不是静默丢帧,5 秒限流避免高频告警刷屏。 + // The Opus encoder is unavailable (init failed or torn down while + // frames are still in flight): say it instead of dropping silently. + const warnedAt = entry!.opusEncoderWarnedAt; + if (Date.now() - warnedAt > 5_000) { + entry!.opusEncoderWarnedAt = Date.now(); + sendJson({ type: "audioError", code: "AUDIO_ENCODER_UNAVAILABLE", detail: "Opus encoder unavailable" }); + } } } catch { // A frame arriving during shutdown is safe to discard. @@ -1059,6 +1103,22 @@ async function handleCommand( function classifyOperationError(error: unknown, fallbackCode: string, fallbackMessage: string): { code: string; message: string } { const text = error instanceof Error ? error.message : String(error); const normalized = text.toLocaleLowerCase(); + // A TeamSpeak server error id is authoritative when the SDK preserved it, so it + // is consulted before the keyword rules: 1794 (channel password), 2568 + // (permissions), 515/2817 (server or slot limit) and friends keep their exact + // meaning instead of being guessed from prose. + const serverCode = + teamSpeakServerErrorCode(isRecord(error) ? (error.id ?? error.code) : undefined) ?? + teamSpeakServerErrorCode(/\bid[\s=:]*(\d{3,5})\b/.exec(normalized)?.[1]); + if (serverCode) { + if (serverCode === "identity_security_level_too_low") return { code: "PERMISSION_DENIED", message: "你没有执行此操作的权限" }; + if (serverCode === "channel_password_required") return { code: "CHANNEL_PASSWORD_REQUIRED", message: "该频道需要密码" }; + if (serverCode === "server_full") return { code: "CHANNEL_FULL", message: "该频道已满" }; + if (serverCode === "client_version_outdated") return { code: "CLIENT_VERSION_OUTDATED", message: "客户端版本过旧,服务器拒绝了该操作" }; + if (serverCode === "flooding") return { code: "FLOOD_PROTECTION", message: "操作过于频繁,请稍后重试" }; + if (serverCode === "banned") return { code: "BANNED", message: "你已被该服务器封禁" }; + if (serverCode === "connection_initialisation_failed") return { code: "CONNECTION_INITIALISATION_FAILED", message: "TeamSpeak 服务器未能完成连接初始化,请稍后重试" }; + } if (/permission|not permitted|insufficient|i_permission|2568/.test(normalized)) return { code: "PERMISSION_DENIED", message: "你没有执行此操作的权限" }; if (/channel.*(password|password.*required)|invalid.*(channel|password)|i_channel_password|1794/.test(normalized)) return { code: "CHANNEL_PASSWORD_REQUIRED", message: "该频道需要密码" }; if (/already member/.test(normalized)) return { code: "ALREADY_IN_CHANNEL", message: "你已经在该频道中" }; diff --git a/web/src/composables/useVoiceWebSocket.ts b/web/src/composables/useVoiceWebSocket.ts index 98c2f37..daafe38 100644 --- a/web/src/composables/useVoiceWebSocket.ts +++ b/web/src/composables/useVoiceWebSocket.ts @@ -12,6 +12,15 @@ export interface VoiceState { tsClientId: number; error: string; errorCode: string; + /** + * Non-fatal audio diagnostics. Unlike error/errorCode these never take over + * the connect form: they explain a degraded microphone or playback path while + * the voice room itself stays joined and usable. + */ + microphoneError: string; + microphoneErrorCode: string; + audioNotice: string; + audioNoticeCode: string; channelSwitchedChannelId: string; } @@ -89,7 +98,6 @@ const CLIENT_ERROR_CODE_ALIASES: Record = { PASSWORD_REQUIRED: "SERVER_PASSWORD_REQUIRED", INVALID_PASSWORD: "INVALID_SERVER_PASSWORD", AUTHENTICATION_FAILED: "INVALID_SERVER_PASSWORD", - SERVER_FULL: "SERVER_REJECTED", GATEWAY_FULL: "SERVER_REJECTED", TS_CONNECT_FAILED: "CONNECTION_FAILED", TEAM_SPEAK_CONNECT_FAILED: "CONNECTION_FAILED", @@ -118,9 +126,101 @@ function safeClientErrorDetail(value: unknown): string { .slice(0, 160); } +// TeamSpeak 对非法昵称没有独立错误码:长度违规统一报 invalid parameter size +// (服务器错误 id 1541),该特征串是网关能转发的唯一机器可读线索,因此把匹配器 +// 与解释文案放在一起,保证两者同步演进。 +/** + * TeamSpeak has no dedicated error for a nickname it refuses: a nickname outside + * its length rules is answered with "invalid parameter size" and server error id + * 1541. That signature is the only machine-readable hint the gateway can forward, + * so keep the matcher next to the message builder that explains it to the user. + */ +const NICKNAME_LENGTH_SIGNATURE = /invalid[\s_-]*parameter[\s_-]*size|\bid[\s=:]*1541\b|nickname.{0,30}(?:length|size)/i; + +/** Shown whenever TeamSpeak refuses the nickname because of its length. */ +const NICKNAME_LENGTH_MESSAGE = "昵称长度不符合 TeamSpeak 服务器要求,至少 3 个字符,请修改后重试"; + +/** + * Browsers only hand out a DOMException name for getUserMedia failures (and an + * often-English message that used to reach the UI verbatim). Map every name the + * browsers actually raise to a sentence the user can act on, and keep the + * DOMException name as the stable failure code. + */ +const MICROPHONE_FAILURE_REASONS: Record = { + NOTALLOWEDERROR: "浏览器未授予麦克风权限", + PERMISSIONDENIEDERROR: "浏览器未授予麦克风权限", + PERMISSION_DISMISSED: "浏览器未授予麦克风权限", + SECURITYERROR: "浏览器阻止了麦克风访问", + NOTFOUNDERROR: "未找到可用的麦克风", + DEVICESNOTFOUNDERROR: "未找到可用的麦克风", + OVERCONSTRAINEDERROR: "所选麦克风当前不可用", + NOTREADABLEERROR: "麦克风可能正被其他程序占用", + TRACKSTARTERROR: "麦克风可能正被其他程序占用", + ABORTERROR: "麦克风启动被中断,请重试", + INVALIDSTATEERROR: "麦克风启动被中断,请重试", + TYPEFERROR: "麦克风访问参数被系统拒绝", +}; + +const MICROPHONE_FAILURE_FALLBACK = "麦克风不可用,请检查浏览器权限与音频设备"; + +const MICROPHONE_FAILURE_CODE_PREFIX = "MIC_"; + +/** Turn a getUserMedia / DOMException failure into a stable code plus a readable sentence. */ +export function normalizeMicrophoneFailure(error: unknown): { code: string; message: string } { + const rawName = error instanceof Error ? String(error.name || "") : ""; + const name = safeClientErrorCode(rawName).slice(0, 40); + const reason = MICROPHONE_FAILURE_REASONS[name] ?? MICROPHONE_FAILURE_FALLBACK; + return { code: `${MICROPHONE_FAILURE_CODE_PREFIX}${name || "UNAVAILABLE"}`, message: `麦克风访问失败:${reason}` }; +} + +/** + * Every code this client can render for a failed connection. A code is regarded + * as "explainable" only when it appears here, which is also what keeps the + * gateway close codes from being replaced by an unknown close reason. + */ +const CONNECTION_FAILURE_MESSAGES: Record = { + ORIGIN_REJECTED: "请求来源不受信任,请从正确的网站入口重新打开", + NOT_INITIALIZED: "WebSpeak 尚未完成配置,请联系管理员", + RATE_LIMITED: "请求过于频繁,请稍后重试", + INVALID_TARGET: "TeamSpeak 服务器地址无效", + INVALID_NICKNAME: NICKNAME_LENGTH_MESSAGE, + HOST_NOT_FOUND: "找不到 TeamSpeak 服务器主机名,请检查地址", + UNREACHABLE: "无法到达 TeamSpeak 服务器,请检查网络或地址", + CONNECTION_REFUSED: "TeamSpeak 服务器拒绝了连接,请检查端口和服务状态", + CONNECTION_RESET: "TeamSpeak 连接被服务器或网络重置,请稍后重试", + TIMEOUT: "连接 TeamSpeak 超时,请检查网络或服务器状态", + SERVER_PASSWORD_REQUIRED: "该服务器需要密码,请输入密码后重试", + INVALID_SERVER_PASSWORD: "服务器密码错误,请重新输入", + PROTOCOL_NEGOTIATION_FAILED: "TeamSpeak 协议协商失败", + SERVER_REJECTED: "TeamSpeak 服务器拒绝了连接", + CHANNEL_PASSWORD_REQUIRED: "该频道需要密码", + NICKNAME_IN_USE: "该昵称已被服务器上的其他用户占用,请更换昵称", + IDENTITY_SECURITY_LEVEL_TOO_LOW: "你的身份安全等级低于该服务器要求,请提升后重试", + IDENTITY_LIMIT_REACHED: "该身份建立的连接数已达上限,请关闭其他连接后重试", + CLIENT_VERSION_OUTDATED: "客户端版本过旧,服务器拒绝连接,请升级后重试", + FLOOD_PROTECTION: "操作过于频繁,已被服务器洪水防护暂时拒绝,请稍后重试", + BANNED: "你已被该服务器封禁,无法连接", + KICKED: "你已被服务器移出", + SERVER_SHUTTING_DOWN: "TeamSpeak 服务器正在关闭,暂时无法连接", + CONNECTION_INITIALISATION_FAILED: "TeamSpeak 服务器未能完成连接初始化,请检查地址、端口或稍后重试", + SERVER_FULL: "服务器当前已满,请稍后重试", + INVALID_PARAMETER: "TeamSpeak 服务器拒绝了参数,通常是昵称长度或格式不合规", + IDENTITY_IN_USE: "此 TeamSpeak 身份已在另一个浏览器页面使用,请关闭另一条连接或取消“保持身份”后重试", + CONNECTION_FAILED: "TeamSpeak 连接失败,请检查地址、网络或服务器状态", + // Gateway close codes: these replace the generic "connection failed" when the + // gateway drops the socket itself (see GATEWAY_CLOSE_CODE_CODES). + JOIN_TICKET_REQUIRED: "语音会话票据缺失或已过期,请返回列表重新进入语音空间", + IDENTITY_INVALID: "语音网关拒绝了本次连接:身份无效,请取消“保持身份”后重新进入", + IDENTITY_REJECTED: "语音网关拒绝了本次连接:身份无效或无法在此页面使用,请取消“保持身份”后重新进入", + ACCELERATION_UNAVAILABLE: "当前中继加速不可用,请关闭加速后重试或联系管理员", + GATEWAY_NETWORK_LOST: "与语音网关的网络连接异常中断(掉线或代理断开),并非 TeamSpeak 服务器拒绝连接,请检查网络后重新进入", + GATEWAY_SESSION_ENDED: "语音网关会话意外结束,请重新进入语音空间", + TEAM_SPEAK_CLIENT_UNAVAILABLE: "语音网关未能创建 TeamSpeak 客户端(服务器可能已关闭或地址不可达),请确认服务器地址或稍后重试", +}; + export function useVoiceWebSocket() { const ws = ref(null); - const state = reactive({ connected: false, connecting: false, reconnecting: false, reconnectAttempt: 0, reconnectFailed: false, tsClientId: 0, error: "", errorCode: "", channelSwitchedChannelId: "" }); + const state = reactive({ connected: false, connecting: false, reconnecting: false, reconnectAttempt: 0, reconnectFailed: false, tsClientId: 0, error: "", errorCode: "", microphoneError: "", microphoneErrorCode: "", audioNotice: "", audioNoticeCode: "", channelSwitchedChannelId: "" }); const members = reactive([]); const channels = reactive([]); const chatMessages = reactive([]); @@ -306,6 +406,51 @@ export function useVoiceWebSocket() { return Math.max(minimum, Math.min(maximum, value)); } + /** + * Microphone failures are a degraded state, not a connection failure: the room + * stays joined, so they get their own slot instead of taking over `error`. + */ + function setMicrophoneError(error: unknown): string { + const failure = normalizeMicrophoneFailure(error); + state.microphoneErrorCode = failure.code; + state.microphoneError = failure.message; + return failure.message; + } + + function clearMicrophoneError(): void { + state.microphoneError = ""; + state.microphoneErrorCode = ""; + } + + /** Non-fatal audio notice (WebRTC fallback, blocked autoplay, device list failure...). */ + function setAudioNotice(code: string, message: string): void { + state.audioNoticeCode = safeClientErrorCode(code) || "AUDIO_NOTICE"; + state.audioNotice = message; + } + + function clearAudioNotice(code?: string): void { + if (code && state.audioNoticeCode !== safeClientErrorCode(code)) return; + state.audioNotice = ""; + state.audioNoticeCode = ""; + } + + /** A suspended AudioContext silently swallows capture: say so instead of pretending. */ + function syncAudioContextNotice(): void { + if (audioCtx && audioCtx.state === "suspended") { + setAudioNotice("AUDIO_CONTEXT_SUSPENDED", "浏览器的音频处理被暂停(需要一次页面交互),麦克风与扬声器可能无声:请点击页面任意位置后重试"); + } else { + clearAudioNotice("AUDIO_CONTEXT_SUSPENDED"); + } + } + + function audioNoticeMessage(code: string, detail?: unknown): string { + const detailText = safeClientErrorDetail(detail); + if (code === "AUDIO_ENCODER_UNAVAILABLE") { + return `麦克风声音未能发送:语音网关的音频编码器不可用(错误代码:${code})${detailText ? `:${detailText}` : ""},请联系管理员`; + } + return `音频链路异常(错误代码:${code})${detailText ? `:${detailText}` : ""},麦克风声音可能没有发送给其他成员`; + } + async function setAudioSink(ctx: SinkAudioContext, deviceId: string): Promise { const mediaSinkSupported = typeof (HTMLMediaElement.prototype as SinkAudioElement).setSinkId === "function"; if (!ctx.setSinkId && !mediaSinkSupported) { @@ -339,12 +484,19 @@ export function useVoiceWebSocket() { // route: a running-but-silent graph could leave the UI reporting a live // speaker while the actual remote audio element remained muted. output.muted = false; + if (audioCtx && audioCtx.state === "suspended") { + try { await audioCtx.resume(); } catch { /* a user gesture is still required */ } + } try { await output.play(); webrtcPlaybackRetryCleanup?.(); + clearAudioNotice("PLAYBACK_BLOCKED"); + syncAudioContextNotice(); } catch { // Mobile and privacy-focused browsers can require a gesture even for a - // MediaStream. Keep retrying after the next real interaction. + // MediaStream. Keep retrying after the next real interaction, but tell the + // user why the remote audio is missing instead of staying silent. + setAudioNotice("PLAYBACK_BLOCKED", "浏览器阻止了音频自动播放,暂时听不到其他成员的声音:请点击页面任意位置,或在地址栏允许本站播放声音"); installWebRtcPlaybackRetry(); } } @@ -374,9 +526,21 @@ export function useVoiceWebSocket() { if (!navigator.mediaDevices?.enumerateDevices) { inputDevices.length = 0; outputDevices.length = 0; + setAudioNotice("DEVICE_LIST_UNAVAILABLE", "无法读取音频设备列表,将使用浏览器默认音频设备:请在系统或浏览器隐私设置中允许读取设备信息"); + return; + } + let devices: MediaDeviceInfo[]; + try { + devices = await navigator.mediaDevices.enumerateDevices(); + clearAudioNotice("DEVICE_LIST_UNAVAILABLE"); + } catch { + // enumerateDevices rejects when the device list is blocked (for example in a + // locked-down iframe). Use the browser defaults and explain the limitation. + inputDevices.length = 0; + outputDevices.length = 0; + setAudioNotice("DEVICE_LIST_UNAVAILABLE", "无法读取音频设备列表,将使用浏览器默认音频设备:请在系统或浏览器隐私设置中允许读取设备信息"); return; } - const devices = await navigator.mediaDevices.enumerateDevices(); const microphones = devices .filter((device) => device.kind === "audioinput") .map((device) => ({ deviceId: device.deviceId, label: device.label, groupId: device.groupId })); @@ -405,15 +569,21 @@ export function useVoiceWebSocket() { async function startMicrophone(): Promise { const ctx = getAudioCtx(); - if (ctx.state === "suspended") await ctx.resume(); + if (ctx.state === "suspended") { + try { await ctx.resume(); } catch { /* the audio context notice explains the silence */ } + } // Acquire the replacement stream before tearing down the current graph so // changing devices does not interrupt an active microphone on failure. let nextStream: MediaStream; try { nextStream = await navigator.mediaDevices.getUserMedia({ audio: microphoneConstraints() }); audioPermission.value = "granted"; + clearMicrophoneError(); } catch (error) { if (error instanceof DOMException && ["NotAllowedError", "SecurityError"].includes(error.name)) audioPermission.value = "denied"; + // Never let the raw DOMException (usually an English message) reach the UI: + // record a readable failure first, then let the caller decide how to show it. + setMicrophoneError(error); throw error; } stopMicrophone(false); @@ -508,8 +678,10 @@ export function useVoiceWebSocket() { captureNode.connect(silentGain); silentGain.connect(ctx.destination); await refreshAudioDevices(); + syncAudioContextNotice(); } + // 导出给 WebClient:开麦前先 await 此函数完成真实采集,避免出现“假成功” async function ensureMicrophone(): Promise { if (micStream) return; if (!microphoneStartPromise) { @@ -724,7 +896,7 @@ export function useVoiceWebSocket() { }; startWebRtcMicMonitor(getAudioCtx(), micStream, microphoneTrack); peer.onconnectionstatechange = () => { - if (peer.connectionState === "failed") void fallbackFromWebRtc(sequence, socket); + if (peer.connectionState === "failed") void fallbackFromWebRtc(sequence, socket, "WEBRTC_CONNECTION_FAILED"); }; const negotiation = (async () => { @@ -741,14 +913,14 @@ export function useVoiceWebSocket() { accompanimentActive: accompanimentActive.value, } })); window.setTimeout(() => { - if (webrtcPeer === peer && !peer.remoteDescription) void fallbackFromWebRtc(sequence, socket); + if (webrtcPeer === peer && !peer.remoteDescription) void fallbackFromWebRtc(sequence, socket, "WEBRTC_ANSWER_TIMEOUT"); }, 8_000); })(); webrtcNegotiationPromise = negotiation; try { await negotiation; } catch (error) { - if (webrtcPeer === peer) await fallbackFromWebRtc(sequence, socket); + if (webrtcPeer === peer) await fallbackFromWebRtc(sequence, socket, "WEBRTC_NEGOTIATION_FAILED"); throw error; } finally { if (webrtcNegotiationPromise === negotiation) webrtcNegotiationPromise = null; @@ -781,19 +953,22 @@ export function useVoiceWebSocket() { webrtcActive.value = true; syncWebRtcMemberVolumes(); } catch { - if (lastConnection && ws.value) await fallbackFromWebRtc(connectionSequence, ws.value); + if (lastConnection && ws.value) await fallbackFromWebRtc(connectionSequence, ws.value, "WEBRTC_ANSWER_REJECTED"); } } - async function fallbackFromWebRtc(sequence: number, socket: WebSocket): Promise { + async function fallbackFromWebRtc(sequence: number, socket: WebSocket, reasonCode = "WEBRTC_UNAVAILABLE"): Promise { if (sequence !== connectionSequence || webrtcFallbackStarted) return; webrtcFallbackStarted = true; webrtcActive.value = false; if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type: "webrtcStop" })); stopWebRtcTransport(); if (socket.readyState === WebSocket.OPEN && state.connected) { + // Degrading to the compatibility transport must be visible: the user is + // still connected, but with different latency and audio quality. + setAudioNotice("WEBRTC_FALLBACK", `实时语音(WebRTC)不可用(错误代码:${safeClientErrorCode(reasonCode) || "WEBRTC_UNAVAILABLE"}),已切换为兼容传输:延迟与音质可能下降`); try { await startMicrophone(); } catch (error: unknown) { - state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`; + setMicrophoneError(error); } } } @@ -1129,6 +1304,9 @@ export function useVoiceWebSocket() { const sequence = ++connectionSequence; state.error = ""; state.errorCode = ""; + // Audio diagnostics belong to the previous session, never to the new one. + clearMicrophoneError(); + clearAudioNotice(); state.connecting = true; state.reconnecting = false; state.reconnectAttempt = 0; @@ -1198,6 +1376,8 @@ export function useVoiceWebSocket() { } stopWebRtcTransport(); stopMicrophone(); + clearMicrophoneError(); + clearAudioNotice(); whisperTargetIds.clear(); whisperActive.value = false; }; @@ -1221,38 +1401,45 @@ export function useVoiceWebSocket() { return messages[normalized] ?? connectionFailureMessage(normalized, detail); } + // 网关关闭码 → 前端可解释错误码的映射:4000-4003 是网关/会话级,4004/4005 是 + // TeamSpeak 拒绝与身份冲突,4006 是中继加速,1006/1011 是传输级掉线,绝不能 + // 被误当成 TeamSpeak 服务器拒绝。 + /** + * Gateway close codes. 4000-4003 are gateway/session level, 4004/4005 are a + * TeamSpeak rejection and an identity conflict, 4006 is the acceleration relay, + * and 1006 is a transport-level drop that must not be blamed on TeamSpeak. + */ + const GATEWAY_CLOSE_CODE_CODES: Record = { + 4000: "CONNECTION_FAILED", + 4001: "JOIN_TICKET_REQUIRED", + 4002: "INVALID_TARGET", + 4003: "IDENTITY_REJECTED", + 4004: "SERVER_REJECTED", + 4005: "IDENTITY_IN_USE", + 4006: "ACCELERATION_UNAVAILABLE", + 1006: "GATEWAY_NETWORK_LOST", + 1011: "GATEWAY_SESSION_ENDED", + }; + function closeErrorCode(code: number, reason = ""): string { const closeCode = normalizedClientErrorCode(reason, ""); - if (closeCode) return closeCode; - if (code === 4002) return "INVALID_TARGET"; - if (code === 4004) return "SERVER_REJECTED"; - if (code === 4005) return "IDENTITY_IN_USE"; - return "CONNECTION_FAILED"; + // The gateway repeats the failure code in the close reason. Trust it when the + // browser can explain that code, otherwise fall back to the numeric close code + // so even a silent close maps to an actionable message. + if (closeCode && CONNECTION_FAILURE_MESSAGES[closeCode]) return closeCode; + return GATEWAY_CLOSE_CODE_CODES[code] ?? "CONNECTION_FAILED"; } function connectionFailureMessage(code: string, detail?: unknown): string { - const messages: Record = { - ORIGIN_REJECTED: "请求来源不受信任,请从正确的网站入口重新打开", - NOT_INITIALIZED: "WebSpeak 尚未完成配置,请联系管理员", - RATE_LIMITED: "请求过于频繁,请稍后重试", - INVALID_TARGET: "TeamSpeak 服务器地址无效", - INVALID_NICKNAME: "昵称长度不符合 TeamSpeak 服务器要求,请修改后重试", - HOST_NOT_FOUND: "找不到 TeamSpeak 服务器主机名,请检查地址", - UNREACHABLE: "无法到达 TeamSpeak 服务器,请检查网络或地址", - CONNECTION_REFUSED: "TeamSpeak 服务器拒绝了连接,请检查端口和服务状态", - CONNECTION_RESET: "TeamSpeak 连接被服务器或网络重置,请稍后重试", - TIMEOUT: "连接 TeamSpeak 超时,请检查网络或服务器状态", - SERVER_PASSWORD_REQUIRED: "该服务器需要密码,请输入密码后重试", - INVALID_SERVER_PASSWORD: "服务器密码错误,请重新输入", - PROTOCOL_NEGOTIATION_FAILED: "TeamSpeak 协议协商失败", - SERVER_REJECTED: "TeamSpeak 服务器拒绝了连接", - IDENTITY_IN_USE: "此 TeamSpeak 身份已在另一个浏览器页面使用,请关闭另一条连接或取消“保持身份”后重试", - CONNECTION_FAILED: "TeamSpeak 连接失败,请检查地址、网络或服务器状态", - }; + const messages = CONNECTION_FAILURE_MESSAGES; const normalized = normalizedClientErrorCode(code); if (messages[normalized]) return messages[normalized]; const safeCode = safeClientErrorCode(normalized); const safeDetail = safeClientErrorDetail(detail); + // The gateway classifies a refused nickname before it reaches the browser, + // but translate the raw TeamSpeak signature too: a nickname problem must + // never end up as the generic "check your network" fallback. + if (safeDetail && NICKNAME_LENGTH_SIGNATURE.test(safeDetail)) return NICKNAME_LENGTH_MESSAGE; return `TeamSpeak 连接失败(错误代码:${safeCode})${safeDetail ? `:${safeDetail}` : ""},请检查输入、网络或服务器状态`; } @@ -1268,6 +1455,8 @@ export function useVoiceWebSocket() { const keepRememberedIdentity = lastConnection?.rememberIdentity === true; if (!preserveConnection) lastConnection = null; stopMicrophone(); + clearMicrophoneError(); + clearAudioNotice(); const socket = ws.value; ws.value = null; stopWebRtcTransport(); @@ -1335,17 +1524,13 @@ export function useVoiceWebSocket() { const start = msg.webrtcAvailable === true && typeof RTCPeerConnection !== "undefined" ? (ws.value ? startWebRtcTransport(connectionSequence, ws.value) : Promise.resolve()) : ensureMicrophone(); - start.catch((error: unknown) => { - state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`; - }); + // A failed microphone must not look like a failed connection: record it + // as an audio diagnostic so the room stays visible with a clear reason. + start.catch((error: unknown) => { setMicrophoneError(error); }); } else if (msg.webrtcAvailable === true && typeof RTCPeerConnection !== "undefined" && ws.value) { - void startWebRtcTransport(connectionSequence, ws.value).catch((error: unknown) => { - state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`; - }); + void startWebRtcTransport(connectionSequence, ws.value).catch((error: unknown) => { setMicrophoneError(error); }); } else { - void ensureMicrophone().catch((error: unknown) => { - state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`; - }); + void ensureMicrophone().catch((error: unknown) => { setMicrophoneError(error); }); } break; case "memberEnter": @@ -1475,8 +1660,15 @@ export function useVoiceWebSocket() { void applyWebRtcAnswer(msg.payload?.sdp); break; case "webrtcError": - if (ws.value) void fallbackFromWebRtc(connectionSequence, ws.value); + if (ws.value) void fallbackFromWebRtc(connectionSequence, ws.value, safeClientErrorCode(msg.code) || "WEBRTC_NEGOTIATION_FAILED"); break; + case "audioError": { + // The gateway could not encode our microphone audio (for example its Opus + // encoder is unavailable): say it instead of dropping frames silently. + const audioCode = safeClientErrorCode(msg.code) || "AUDIO_ERROR"; + setAudioNotice(audioCode, audioNoticeMessage(audioCode, msg.detail)); + break; + } case "voiceActivity": if (Array.isArray(msg.clientIds)) { for (const clientId of msg.clientIds) { @@ -1634,6 +1826,11 @@ export function useVoiceWebSocket() { CHANNEL_SWITCH_FAILED: "频道切换失败", CHANNEL_PASSWORD_REQUIRED: "该频道需要密码", CHANNEL_FULL: "该频道已满", + NICKNAME_IN_USE: "该昵称已被占用,请更换昵称", + CLIENT_VERSION_OUTDATED: "客户端版本过旧,服务器拒绝了该操作", + FLOOD_PROTECTION: "操作过于频繁,请稍后重试", + BANNED: "你已被该服务器封禁", + KICKED: "你已被服务器移出", PERMISSION_DENIED: "你没有执行此操作的权限", CLIENT_NOT_FOUND: "成员已离线", OPERATION_FAILED: "操作失败", @@ -1752,6 +1949,7 @@ export function useVoiceWebSocket() { setWhisperTargets, setWhisperActive, setMicrophoneMuted, + ensureMicrophone, startAccompaniment, stopAccompaniment, checkSupport, diff --git a/web/src/views/WebClient.vue b/web/src/views/WebClient.vue index 72b2c30..a0c4d2a 100644 --- a/web/src/views/WebClient.vue +++ b/web/src/views/WebClient.vue @@ -293,7 +293,7 @@ @@ -674,6 +674,8 @@ const translations: Record> = { notificationVolume: "通知音量", audioStatus: "音频状态", audioReady: "音频已就绪", + audioUnavailable: "音频不可用(麦克风故障)", + microphoneUnavailable: "麦克风不可用,你暂时无法说话", audioSuspended: "音频被浏览器暂停", audioUnknown: "尚未初始化", audioPrivacy: "WebSpeak 会在浏览器安全上下文中处理音频,不会保存录音。", @@ -941,6 +943,8 @@ const translations: Record> = { notificationVolume: "Notification volume", audioStatus: "Audio status", audioReady: "Audio ready", + audioUnavailable: "Audio unavailable (microphone failure)", + microphoneUnavailable: "Microphone unavailable — others cannot hear you", audioSuspended: "Audio paused by the browser", audioUnknown: "Not initialized", audioPrivacy: "WebSpeak processes audio in the browser's secure context and does not save recordings.", @@ -1211,6 +1215,8 @@ translations.de = { notificationVolume: "Benachrichtigungslautstärke", audioStatus: "Audiostatus", audioReady: "Audio bereit", + audioUnavailable: "Audio nicht verfügbar (Mikrofonfehler)", + microphoneUnavailable: "Mikrofon nicht verfügbar – andere können dich nicht hören", audioSuspended: "Audio wurde vom Browser pausiert", audioUnknown: "Nicht initialisiert", audioPrivacy: "WebSpeak verarbeitet Audio im sicheren Browserkontext und speichert keine Aufnahmen.", @@ -1295,7 +1301,7 @@ function localizedMessage(message: string) { "连接已断开": "The connection was closed", "此 TeamSpeak 身份已在另一个浏览器页面使用,请关闭另一条连接或取消“保持身份”后重试": "This TeamSpeak identity is already used by another browser page. Close that connection or clear ‘Remember identity’ and try again", "TeamSpeak 服务器地址无效": "The TeamSpeak server address is invalid", - "昵称长度不符合 TeamSpeak 服务器要求,请修改后重试": "The nickname length does not meet the TeamSpeak server requirements. Change it and try again", + "昵称长度不符合 TeamSpeak 服务器要求,至少 3 个字符,请修改后重试": "The nickname length does not meet the TeamSpeak server requirements (at least 3 characters). Change it and try again", "TeamSpeak 服务器连接失败": "Could not connect to the TeamSpeak server", "找不到 TeamSpeak 服务器主机名,请检查地址": "The TeamSpeak server hostname could not be resolved. Check the address", "无法到达 TeamSpeak 服务器,请检查网络或地址": "The TeamSpeak server is unreachable. Check the network or address", @@ -1334,6 +1340,20 @@ function localizedMessage(message: string) { "你没有执行此操作的权限": "You do not have permission to perform this action", "成员已离线": "This member is offline", "操作失败": "The operation failed", + "该昵称已被服务器上的其他用户占用,请更换昵称": "This nickname is already in use on the server. Choose another one", + "该昵称已被占用,请更换昵称": "This nickname is already in use. Choose another one", + "你的身份安全等级低于该服务器要求,请提升后重试": "Your identity security level is below what this server requires. Raise it and try again", + "该身份建立的连接数已达上限,请关闭其他连接后重试": "This identity reached its connection limit. Close the other connections and try again", + "客户端版本过旧,服务器拒绝连接,请升级后重试": "Your client version is outdated and the server rejected the connection. Update and try again", + "客户端版本过旧,服务器拒绝了该操作": "Your client version is outdated, so the server rejected this action", + "操作过于频繁,已被服务器洪水防护暂时拒绝,请稍后重试": "Too many requests: the server flood protection rejected you temporarily. Try again shortly", + "操作过于频繁,请稍后重试": "Too many requests. Try again shortly", + "你已被该服务器封禁,无法连接": "You are banned from this server, so the connection is refused", + "你已被该服务器封禁": "You are banned from this server", + "你已被服务器移出": "You were removed from the server", + "TeamSpeak 服务器正在关闭,暂时无法连接": "The TeamSpeak server is shutting down and is unreachable right now", + "TeamSpeak 服务器未能完成连接初始化,请检查地址、端口或稍后重试": "The TeamSpeak server could not finish initialising the connection. Check the address and port, or try again shortly", + "TeamSpeak 服务器拒绝了参数,通常是昵称长度或格式不合规": "The TeamSpeak server rejected the parameters, usually because the nickname length or format is invalid", }; if (language.value !== "de" && exact[message]) return exact[message]; if (message.startsWith("麦克风访问失败:")) return `Microphone access failed: ${message.slice(8)}`; @@ -1352,7 +1372,8 @@ function localizedMessage(message: string) { "TeamSpeak 连接已断开": "Die TeamSpeak-Verbindung wurde getrennt", "连接已断开": "Die Verbindung wurde getrennt", "TeamSpeak 服务器地址无效": "Die TeamSpeak-Serveradresse ist ungültig", - "昵称长度不符合 TeamSpeak 服务器要求,请修改后重试": "Die Länge des Spitznamens entspricht nicht den Anforderungen des TeamSpeak-Servers. Ändere ihn und versuche es erneut", + "昵称长度不符合 TeamSpeak 服务器要求,至少 3 个字符,请修改后重试": "Die Länge des Spitznamens entspricht nicht den Anforderungen des TeamSpeak-Servers (mindestens 3 Zeichen). Ändere ihn und versuche es erneut", + "请输入有效的昵称": "Gib einen gültigen Nicknamen ein", "找不到 TeamSpeak 服务器主机名,请检查地址": "Der TeamSpeak-Servername konnte nicht aufgelöst werden. Prüfe die Adresse", "无法到达 TeamSpeak 服务器,请检查网络或地址": "Der TeamSpeak-Server ist nicht erreichbar. Prüfe Netzwerk und Adresse", "TeamSpeak 服务器拒绝了连接,请检查端口和服务状态": "Der TeamSpeak-Server hat die Verbindung abgelehnt. Prüfe Port und Serverstatus", @@ -1364,8 +1385,56 @@ function localizedMessage(message: string) { "TeamSpeak 服务器拒绝了连接": "Der TeamSpeak-Server hat die Verbindung abgelehnt", "TeamSpeak 连接失败,请检查地址、网络或服务器状态": "Die TeamSpeak-Verbindung ist fehlgeschlagen. Prüfe Adresse, Netzwerk und Serverstatus", "服务器当前已满或拒绝了连接,请稍后重试": "Der Server ist voll oder hat die Verbindung abgelehnt. Versuche es später erneut", + "服务器当前已满,请稍后重试": "Der Server ist derzeit voll. Versuche es später erneut", + "该昵称已被服务器上的其他用户占用,请更换昵称": "Dieser Spitzname wird auf dem Server bereits verwendet. Wähle einen anderen", + "该昵称已被占用,请更换昵称": "Dieser Spitzname wird bereits verwendet. Wähle einen anderen", + "你的身份安全等级低于该服务器要求,请提升后重试": "Deine Sicherheitsstufe liegt unter der Anforderung dieses Servers. Erhöhe sie und versuche es erneut", + "该身份建立的连接数已达上限,请关闭其他连接后重试": "Diese Identität hat ihr Verbindungslimit erreicht. Schließe die anderen Verbindungen und versuche es erneut", + "客户端版本过旧,服务器拒绝连接,请升级后重试": "Deine Client-Version ist veraltet und der Server hat die Verbindung abgelehnt. Aktualisiere und versuche es erneut", + "客户端版本过旧,服务器拒绝了该操作": "Deine Client-Version ist veraltet, daher hat der Server diese Aktion abgelehnt", + "操作过于频繁,已被服务器洪水防护暂时拒绝,请稍后重试": "Zu viele Anfragen: Der Flood-Schutz des Servers hat dich vorübergehend abgewiesen. Versuche es gleich erneut", + "操作过于频繁,请稍后重试": "Zu viele Anfragen. Versuche es gleich erneut", + "你已被该服务器封禁,无法连接": "Du wurdest von diesem Server gebannt und kannst nicht verbinden", + "你已被该服务器封禁": "Du wurdest von diesem Server gebannt", + "你已被服务器移出": "Du wurdest vom Server entfernt", + "TeamSpeak 服务器正在关闭,暂时无法连接": "Der TeamSpeak-Server wird heruntergefahren und ist derzeit nicht erreichbar", + "TeamSpeak 服务器未能完成连接初始化,请检查地址、端口或稍后重试": "Der TeamSpeak-Server konnte die Verbindungsinitialisierung nicht abschließen. Prüfe Adresse und Port oder versuche es später erneut", + "TeamSpeak 服务器拒绝了参数,通常是昵称长度或格式不合规": "Der TeamSpeak-Server hat die Parameter abgelehnt, meist wegen ungültiger Länge oder ungültigen Formats des Spitznamens", + "此 TeamSpeak 身份已在另一个浏览器页面使用,请关闭另一条连接或取消“保持身份”后重试": "Diese TeamSpeak-Identität wird bereits in einem anderen Browser-Tab verwendet. Schließe die andere Verbindung oder deaktiviere „Identität merken“ und versuche es erneut", + "语音会话票据缺失或已过期,请返回列表重新进入语音空间": "Der Sprachsitzungs-Token fehlt oder ist abgelaufen. Kehre zur Liste zurück und tritt dem Sprachraum erneut bei", + "语音网关拒绝了本次连接:身份无效,请取消“保持身份”后重新进入": "Das Sprach-Gateway hat die Verbindung abgelehnt: Die Identität ist ungültig. Deaktiviere „Identität merken“ und tritt erneut bei", + "语音网关拒绝了本次连接:身份无效或无法在此页面使用,请取消“保持身份”后重新进入": "Das Sprach-Gateway hat die Verbindung abgelehnt: Die Identität ist ungültig oder kann auf dieser Seite nicht verwendet werden. Deaktiviere „Identität merken“ und tritt erneut bei", + "当前中继加速不可用,请关闭加速后重试或联系管理员": "Der beschleunigte Relay-Modus ist nicht verfügbar. Deaktiviere ihn und versuche es erneut oder wende dich an den Administrator", + "与语音网关的网络连接异常中断(掉线或代理断开),并非 TeamSpeak 服务器拒绝连接,请检查网络后重新进入": "Die Verbindung zum Sprach-Gateway wurde unerwartet unterbrochen (Offline oder Proxy getrennt) – der TeamSpeak-Server hat die Verbindung nicht abgelehnt. Prüfe deine Netzwerkverbindung und tritt erneut bei", + "语音网关会话意外结束,请重新进入语音空间": "Die Sprach-Gateway-Sitzung wurde unerwartet beendet. Tritt dem Sprachraum erneut bei", + "语音网关未能创建 TeamSpeak 客户端(服务器可能已关闭或地址不可达),请确认服务器地址或稍后重试": "Das Sprach-Gateway konnte keinen TeamSpeak-Client erstellen (der Server ist möglicherweise aus oder nicht erreichbar). Prüfe die Serveradresse oder versuche es später erneut", + "消息格式无效": "Ungültiges Nachrichtenformat", + "请求标识无效": "Ungültige Anforderungs-ID", + "不支持的操作": "Nicht unterstützte Operation", + "操作参数无效": "Ungültige Operationsparameter", + "频道标识无效": "Ungültige Kanal-ID", + "频道密码无效": "Ungültiges Kanalpasswort", + "成员标识无效": "Ungültige Mitglieds-ID", + "文字消息无效": "Ungültige Textnachricht", + "戳一戳消息无效": "Ungültige Poke-Nachricht", + "离开状态无效": "Ungültiger Abwesenheitsstatus", + "音频帧格式无效": "Ungültiges Audio-Frame-Format", + "成员音量无效": "Ungültige Mitgliedslautstärke", + "私语目标无效": "Ungültige Flüsterziele", + "私语状态无效": "Ungültiger Flüsterstatus", + "请先选择私语目标": "Wähle zuerst ein Flüsterziel", + "TeamSpeak 会话尚未就绪": "Die TeamSpeak-Sitzung ist noch nicht bereit", + "频道切换失败": "Kanalwechsel fehlgeschlagen", + "该频道需要密码": "Dieser Kanal erfordert ein Passwort", + "该频道已满": "Dieser Kanal ist voll", + "你没有执行此操作的权限": "Du hast keine Berechtigung für diese Aktion", + "成员已离线": "Das Mitglied ist offline", + "操作失败": "Operation fehlgeschlagen", }; if (german[message]) return german[message]; + if (message.startsWith("麦克风访问失败:")) return `Mikrofonzugriff fehlgeschlagen: ${message.slice(8)}`; + if (message.startsWith("麦克风声音未能发送:")) return `Mikrofon-Audio konnte nicht gesendet werden: ${message.slice(10)}`; + if (message.startsWith("音频链路异常")) return message.replace("音频链路异常", "Audioverbindung fehlerhaft"); } return message; } @@ -2257,6 +2326,7 @@ function stopWhisperTalk(): void { .settings-footer { justify-content: flex-end; } .reconnect-banner { display: flex; align-items: center; justify-content: space-between; gap: 18px; margin: 14px auto 0; width: min(950px, calc(100% - 64px)); padding: 12px 16px; color: #6c5a2c; border: 1px solid #f0dfae; border-radius: 10px; background: #fff9e8; } .reconnect-banner.failed { color: #8f4540; border-color: #f2d1cd; background: #fff2f1; } +.reconnect-banner.degraded { color: #7a4d1d; border-color: #f3d9a9; background: #fff7ec; } /* 降级/告警级提示(如音频链路降级) */ .reconnect-copy { display: flex; align-items: baseline; gap: 10px; min-width: 0; } .reconnect-copy strong { font-size: 13px; } .reconnect-copy span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 11px; }