feat: 浏览器端报错翻译与提示改造

- 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 总表与网关关闭码映射
- 关键新增逻辑补充中文注释说明改动意图
This commit is contained in:
LainHE committed 2026-09-16 22:24:25 +08:00
1 parent 1ba8cd5ee1
commit 4ead174c04
8 files changed
+677 -74

No files matched your search

+8 -3
View File
@@ -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";
}
+1
View File
@@ -17,6 +17,7 @@ export type SessionTeardownReason =
| "websocket-error"
| "protocol-error"
| "teamSpeak-disconnect"
| "teamSpeak-kicked" // 会话被 TeamSpeak 服务器踢出/封禁时拆除
| "teamSpeak-connect-failed"
| "heartbeat-timeout"
| "admin-terminated"
+16
View File
@@ -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<WebSpeakErrorCode, ProbeErrorCode> = {
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",
+19 -1
View File
@@ -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);
+65 -5
View File
@@ -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<number, ChannelMember>;
eventLog: ServerEvent[];
opusEncoder: { encode(pcm: Buffer): Buffer } | null;
opusEncoderWarnedAt: number; // Opus 编码器不可用告警的时间戳,用于限流避免反复刷屏
whisperTargetIds: Set<number>;
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: "你已经在该频道中" };