diff --git a/README.md b/README.md index 75d98e7..f340227 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ WebSpeak 是一个自托管的 TeamSpeak 浏览器客户端与访客接入网关 - TeamSpeak 3 / TeamSpeak 6 自动探测,无需选择协议。 - 每个浏览器 Session 独立连接,硬上限固定为 100。 - Session 生命周期统一管理:连接状态机、WebSocket 心跳、幂等清理和优雅关闭。 +- TeamSpeak 临时断线自动重连,固定退避策略最长持续 5 分钟;认证失败不会无限重试,并尽量恢复原频道。 - 完整频道/成员树、频道切换、频道文字聊天和成员实时移动。 - PCM/Opus 语音桥接、自由麦、按键说话、麦克风选择与音量控制。 - 发言成员头像显示绿色动态边框。 @@ -156,7 +157,7 @@ npm run dev # 前端开发服务;/api 和 /ws 代理到 3040 npm run web:dev -# 自动测试(覆盖 M000、M001、M002) +# 自动测试(覆盖 M000–M003) npm test # 后端类型检查与构建 @@ -195,6 +196,7 @@ WebSpeak is a self-hosted TeamSpeak web client and guest gateway. Every browser - Automatic TeamSpeak 3 / TeamSpeak 6 detection. - Independent browser sessions with a fixed hard limit of 100. - Managed session lifecycle with a connection state machine, WebSocket heartbeat, idempotent teardown, and graceful shutdown. +- Temporary TeamSpeak failures recover with bounded jittered backoff for up to five minutes; authentication failures are not retried forever, and the previous channel is restored when possible. - Channel/member directory, channel switching, channel text chat, and live member movement. - PCM/Opus voice bridge, VOX, push-to-talk, microphone selection, and volume controls. - Bilingual guest UI and bilingual admin console. diff --git a/src/server/reconnect-policy.ts b/src/server/reconnect-policy.ts new file mode 100644 index 0000000..18f67a0 --- /dev/null +++ b/src/server/reconnect-policy.ts @@ -0,0 +1,19 @@ +import type { WebSpeakError } from "../errors.js"; + +export const RECONNECT_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 15_000, 30_000, 30_000] as const; +export const RECONNECT_WINDOW_MS = 5 * 60_000; + +export function reconnectDelayMs(attempt: number, random = Math.random): number { + const safeAttempt = Math.max(1, Math.floor(attempt)); + const base = RECONNECT_DELAYS_MS[Math.min(safeAttempt, RECONNECT_DELAYS_MS.length) - 1] ?? RECONNECT_DELAYS_MS.at(-1)!; + const jitter = Math.round(base * ((random() * 0.2) - 0.1)); + return Math.max(250, base + jitter); +} + +export function reconnectWindowOpen(startedAt: number, now = Date.now()): boolean { + return now - startedAt < RECONNECT_WINDOW_MS; +} + +export function isRecoverable(error: WebSpeakError | null): boolean { + return error?.retryable ?? true; +} diff --git a/src/server/session-manager.ts b/src/server/session-manager.ts index 32f41ab..db6f8bb 100644 --- a/src/server/session-manager.ts +++ b/src/server/session-manager.ts @@ -23,9 +23,9 @@ export type SessionTeardownReason = const ALLOWED_TRANSITIONS: Record = { idle: ["connecting", "disconnecting"], - connecting: ["authenticating", "failed", "disconnecting"], - authenticating: ["syncing", "failed", "disconnecting"], - syncing: ["connected", "failed", "disconnecting"], + connecting: ["authenticating", "reconnecting", "failed", "disconnecting"], + authenticating: ["syncing", "reconnecting", "failed", "disconnecting"], + syncing: ["connected", "reconnecting", "failed", "disconnecting"], connected: ["interrupted", "failed", "disconnecting"], interrupted: ["reconnecting", "failed", "disconnecting"], reconnecting: ["connecting", "failed", "disconnecting"], diff --git a/src/server/teamspeak-adapter.ts b/src/server/teamspeak-adapter.ts index 2514607..ca27aac 100644 --- a/src/server/teamspeak-adapter.ts +++ b/src/server/teamspeak-adapter.ts @@ -73,6 +73,7 @@ export interface TeamSpeakAdapterOptions { */ export class TeamSpeakAdapter { readonly client: TeamSpeakClient; + readonly identity: Identity; private detectedProtocol: TeamSpeakProtocol | null = null; constructor( @@ -80,6 +81,7 @@ export class TeamSpeakAdapter { private readonly logger: Logger, private readonly protocolCache: EndpointProtocolCache = endpointProtocolCache, ) { + this.identity = options.identity ?? generateIdentity(8); const clientOptions: ClientOptions = { serverPassword: options.serverPassword, defaultChannel: options.defaultChannel, @@ -92,7 +94,7 @@ export class TeamSpeakAdapter { }, }; this.client = new TeamSpeakClient( - options.identity ?? generateIdentity(8), + this.identity, formatTeamSpeakTarget(options.target), options.nickname, clientOptions, diff --git a/src/server/ts-client.ts b/src/server/ts-client.ts index 8442682..fdbe7f3 100644 --- a/src/server/ts-client.ts +++ b/src/server/ts-client.ts @@ -2,6 +2,8 @@ import { EventEmitter } from "node:events"; import { Client as TS3FullClient, clientMove as tsClientMove, + generateIdentity, + type Identity, type VoiceData, type ChannelInfo, type ClientInfo, @@ -16,6 +18,7 @@ export interface TSClientOptions { serverPassword?: string; defaultChannel?: string; channelPassword?: string; + identity?: Identity; } export interface TSVoiceData { @@ -33,79 +36,42 @@ export class TSClient extends EventEmitter { private client: TS3FullClient | null = null; private adapter: TeamSpeakAdapter | null = null; private logger: Logger; + private readonly identity: Identity; private clientId = 0; private connected = false; + private preferredChannelId = 0n; constructor(private options: TSClientOptions, logger: Logger) { super(); this.logger = logger.child({ nickname: options.nickname }); + this.identity = options.identity ?? generateIdentity(8); } async connect(): Promise { - this.adapter = new TeamSpeakAdapter({ - target: this.options.target, - nickname: this.options.nickname, - serverPassword: this.options.serverPassword, - defaultChannel: this.options.defaultChannel, - channelPassword: this.options.channelPassword, - }, this.logger); - this.client = this.adapter.client; + if (!this.adapter || !this.client) { + this.adapter = new TeamSpeakAdapter({ + target: this.options.target, + nickname: this.options.nickname, + identity: this.identity, + serverPassword: this.options.serverPassword, + defaultChannel: this.options.defaultChannel, + channelPassword: this.options.channelPassword, + }, this.logger); + this.client = this.adapter.client; + this.attachClientListeners(this.client); + } + const adapter = this.adapter; + const client = this.client; - this.client.on("voiceData", (data: VoiceData) => { - this.emit("voiceData", { - clientId: data.clientId, - codec: data.codec, - data: Buffer.from(data.data), - } as TSVoiceData); - }); + await adapter.connect(); - // The SDK patch exposes the directory that TeamSpeak sends during the - // normal client welcome sequence. This is the same data a native client - // receives and does not require channellist/clientlist permissions. - (this.client as unknown as { - on(event: "directorySnapshot", handler: (snapshot: TSDirectorySnapshot) => void): unknown; - }).on("directorySnapshot", (snapshot) => { - this.emit("directorySnapshot", snapshot); - }); - - this.client.on("textMessage", (msg) => { - this.emit("textMessage", { - invokerName: msg.invokerName, - invokerId: msg.invokerID, - invokerUid: msg.invokerUID, - message: msg.message, - targetMode: msg.targetMode, - }); - }); - - this.client.on("disconnected", (err) => { - this.logger.warn({ err: err?.message }, "Disconnected from TS"); - this.connected = false; - this.clientId = 0; - this.emit("disconnected"); - }); - - this.client.on("clientEnter", (info) => { - this.emit("clientEnter", info); - }); - - this.client.on("clientLeave", (info) => { - this.emit("clientLeave", info); - }); - - this.client.on("clientMoved", (info) => { - this.emit("clientMoved", info); - }); - - await this.adapter.connect(); - - this.clientId = this.client.clientID(); + this.clientId = client.clientID(); try { // A native TeamSpeak client subscribes to the complete channel tree // after the welcome sequence. Without this command the server only // exposes members in the current channel, so users disappear as soon as // they move elsewhere even though both clients are on the same server. - await this.client.execCommand("channelsubscribeall", 5000); + await client.execCommand("channelsubscribeall", 5000); } catch (error: unknown) { this.logger.warn({ err: error instanceof Error ? error.message : String(error), @@ -116,12 +82,79 @@ export class TSClient extends EventEmitter { // contains members from every subscribed channel. await new Promise((resolve) => setImmediate(resolve)); await new Promise((resolve) => setImmediate(resolve)); + + const connectedChannelId = client.channelID(); + if (this.preferredChannelId === 0n) { + this.preferredChannelId = connectedChannelId; + } else if (connectedChannelId !== this.preferredChannelId) { + try { + await tsClientMove(client, this.clientId, this.preferredChannelId); + } catch (error: unknown) { + // The old channel may have been deleted or become inaccessible. The + // SDK has already left us in the server/default channel, which is the + // safe fallback required by the reconnect contract. + this.logger.info({ + channelId: this.preferredChannelId.toString(), + err: error instanceof Error ? error.message : String(error), + }, "Previous TeamSpeak channel could not be restored"); + this.preferredChannelId = client.channelID(); + } + } this.connected = true; this.logger.info({ clientId: this.clientId }, "Connected to TeamSpeak"); this.emit("connected", this.clientId); } + private attachClientListeners(client: TS3FullClient): void { + client.on("voiceData", (data: VoiceData) => { + this.emit("voiceData", { + clientId: data.clientId, + codec: data.codec, + data: Buffer.from(data.data), + } as TSVoiceData); + }); + + // The SDK patch exposes the directory that TeamSpeak sends during the + // normal client welcome sequence. This is the same data a native client + // receives and does not require channellist/clientlist permissions. + (client as unknown as { + on(event: "directorySnapshot", handler: (snapshot: TSDirectorySnapshot) => void): unknown; + }).on("directorySnapshot", (snapshot) => { + this.emit("directorySnapshot", snapshot); + }); + + client.on("textMessage", (msg) => { + this.emit("textMessage", { + invokerName: msg.invokerName, + invokerId: msg.invokerID, + invokerUid: msg.invokerUID, + message: msg.message, + targetMode: msg.targetMode, + }); + }); + + client.on("disconnected", (err) => { + this.logger.warn({ err: err?.message }, "Disconnected from TS"); + this.connected = false; + this.clientId = 0; + this.emit("disconnected", err); + }); + + client.on("clientEnter", (info) => { + this.emit("clientEnter", info); + }); + + client.on("clientLeave", (info) => { + this.emit("clientLeave", info); + }); + + client.on("clientMoved", (info) => { + if (info.id === this.clientId && info.targetChannelID !== 0n) this.preferredChannelId = info.targetChannelID; + this.emit("clientMoved", info); + }); + } + sendVoice(data: Buffer, codec: number = 4): void { if (!this.client || !this.connected) return; this.client.sendVoice(data, codec); @@ -139,8 +172,9 @@ export class TSClient extends EventEmitter { } async switchChannel(channelId: bigint, password?: string): Promise { - if (!this.client) return; + if (!this.client || !this.connected) return; await tsClientMove(this.client, this.clientId, channelId, password); + this.preferredChannelId = channelId; } getClientId(): number { @@ -154,6 +188,10 @@ export class TSClient extends EventEmitter { return this.adapter?.protocol ?? null; } + getIdentityString(): string { + return this.identity.toString(); + } + getChannelId(): bigint { if (!this.client) return 0n; const sdkClient = this.client as unknown as { channelID?: () => bigint }; diff --git a/src/server/voice-bridge.ts b/src/server/voice-bridge.ts index 2c4e532..04befa9 100644 --- a/src/server/voice-bridge.ts +++ b/src/server/voice-bridge.ts @@ -9,6 +9,7 @@ import { formatTeamSpeakTarget, type TeamSpeakTarget } from "../domain/teamspeak import { JoinTicketStore, type JoinTicketPayload } from "./join-ticket.js"; import { SessionManager, type ManagedSession, type SessionTeardownReason } from "./session-manager.js"; import { parseClientCommand, type ClientCommand } from "./voice-protocol.js"; +import { isRecoverable, reconnectDelayMs, reconnectWindowOpen } from "./reconnect-policy.js"; const require = createRequire(import.meta.url); const { OpusEncoder } = require("@discordjs/opus") as { @@ -38,6 +39,7 @@ interface WebClientEntry { members: Map; opusEncoder: { encode(pcm: Buffer): Buffer } | null; isAlive: boolean; + reconnectTimer: ReturnType | null; } export class VoiceBridge { @@ -100,6 +102,7 @@ export class VoiceBridge { members: new Map(), opusEncoder: null, isAlive: true, + reconnectTimer: null, }; this.entries.set(entryId, entry); try { @@ -116,6 +119,9 @@ export class VoiceBridge { let initialStateSent = false; let audioReady = true; let realtimeReady = false; + let hasConnectedOnce = false; + let reconnectStartedAt = 0; + let reconnectAttempt = 0; const directory = new DirectorySynchronizer(); const sendJson = (message: Record) => { @@ -137,9 +143,106 @@ export class VoiceBridge { const sendInitialState = () => { if (initialStateSent || !tsReady || !directory.ready || !realtimeReady || !audioReady || session.state !== "syncing") return; initialStateSent = true; + const wasReconnecting = hasConnectedOnce; + hasConnectedOnce = true; + reconnectAttempt = 0; + reconnectStartedAt = 0; session.transition("connected"); sendJson({ type: "connected", tsClientId: selfId, members: Array.from(entry!.members.values()) }); sendJson({ type: "channelList", channels: entry!.channelTree }); + if (wasReconnecting) sendJson({ type: "reconnected" }); + }; + + const resetDirectoryForReconnect = () => { + tsReady = false; + initialStateSent = false; + selfId = 0; + selfChannelId = 0n; + directory.clear(); + entry!.channelTree = []; + entry!.members.clear(); + }; + + const failReconnect = (normalized: ReturnType) => { + if (entry!.reconnectTimer) { + clearTimeout(entry!.reconnectTimer); + entry!.reconnectTimer = null; + } + try { + if (session.state !== "disconnecting" && session.state !== "idle") session.transition("failed"); + } catch { /* teardown below remains authoritative */ } + sendJson({ type: "reconnectFailed", code: normalized.code }); + void this.teardown(entryId, "teamSpeak-connect-failed"); + }; + + const scheduleReconnect = (normalized: ReturnType | null) => { + if (session.state === "disconnecting" || session.state === "idle" || session.state === "failed") return; + if (!isRecoverable(normalized)) { + failReconnect(normalized ?? normalizeTeamSpeakError(new Error("TeamSpeak connection failed"))); + return; + } + const now = Date.now(); + if (!reconnectStartedAt) reconnectStartedAt = now; + reconnectAttempt += 1; + if (!reconnectWindowOpen(reconnectStartedAt, now)) { + failReconnect(normalized ?? normalizeTeamSpeakError(new Error("Reconnect window expired"))); + return; + } + if (session.state === "connected") session.transition("interrupted"); + if (session.state === "interrupted") session.transition("reconnecting"); + if (entry!.reconnectTimer) return; + const delayMs = reconnectDelayMs(reconnectAttempt); + sendJson({ type: "reconnecting", attempt: reconnectAttempt, delayMs }); + entry!.reconnectTimer = setTimeout(() => { + entry!.reconnectTimer = null; + if (session.state !== "reconnecting") return; + try { + session.transition("connecting"); + session.transition("authenticating"); + } catch { + failReconnect(normalizeTeamSpeakError(new Error("Reconnect state initialization failed"))); + return; + } + void connectTeamSpeak(true); + }, delayMs); + entry!.reconnectTimer.unref?.(); + }; + + const connectTeamSpeak = async (isReconnect: boolean): Promise => { + try { + await tsClient.connect(); + if (session.state !== "authenticating") return; + session.transition("syncing"); + tsReady = true; + selfId = tsClient.getClientId(); + const sdkChannelId = tsClient.getChannelId(); + if (sdkChannelId !== 0n) selfChannelId = sdkChannelId; + refreshDirectory(); + if (selfId > 0 && !entry!.members.has(selfId)) { + directory.applyClientEnter({ id: selfId, nickname, channelID: selfChannelId, uid: "", type: 1, serverGroups: [] }); + refreshDirectory(); + } + sendInitialState(); + } catch (error: unknown) { + const normalized = normalizeTeamSpeakError(error); + this.logger.error({ code: normalized.code, entryId, reconnect: isReconnect, attempt: reconnectAttempt }, "TS connect failed"); + if (!isReconnect) { + try { + if (session.state !== "disconnecting" && session.state !== "idle") session.transition("failed"); + } catch { /* teardown below remains authoritative */ } + if (ws.readyState === WebSocket.OPEN) ws.close(4003, normalized.code); + void this.teardown(entryId, "teamSpeak-connect-failed"); + return; + } + if (isReconnect && isRecoverable(normalized)) { + try { + if (session.state !== "disconnecting" && session.state !== "idle") session.transition("reconnecting"); + } catch { /* teardown below remains authoritative */ } + scheduleReconnect(normalized); + return; + } + failReconnect(normalized); + } }; // Register every directory listener before connect(). Events emitted by @@ -204,12 +307,12 @@ export class VoiceBridge { }); }); - tsClient.on("disconnected", () => { - if (session.state !== "disconnecting" && session.state !== "idle") { - try { session.transition("interrupted"); } catch { /* teardown below is authoritative */ } - sendJson({ type: "disconnected" }); - void this.teardown(entryId, "teamSpeak-disconnect"); - } + tsClient.on("disconnected", (error?: Error) => { + if (!hasConnectedOnce || session.state !== "connected") return; + resetDirectoryForReconnect(); + const normalized = error ? normalizeTeamSpeakError(error) : null; + sendJson({ type: "disconnected", recoverable: isRecoverable(normalized) }); + scheduleReconnect(normalized); }); ws.on("pong", () => { if (entry) entry.isAlive = true; }); @@ -259,28 +362,7 @@ export class VoiceBridge { return; } - tsClient.connect() - .then(() => { - if (session.state !== "authenticating") return; - session.transition("syncing"); - tsReady = true; - selfId = tsClient.getClientId(); - const sdkChannelId = tsClient.getChannelId(); - if (sdkChannelId !== 0n) selfChannelId = sdkChannelId; - refreshDirectory(); - if (selfId > 0 && !entry!.members.has(selfId)) { - directory.applyClientEnter({ id: selfId, nickname, channelID: selfChannelId, uid: "", type: 1, serverGroups: [] }); - refreshDirectory(); - } - sendInitialState(); - }) - .catch((error: Error) => { - const normalized = normalizeTeamSpeakError(error); - this.logger.error({ code: normalized.code, entryId }, "TS connect failed"); - try { if (session.state !== "disconnecting" && session.state !== "idle") session.transition("failed"); } catch { /* cleanup below */ } - if (ws.readyState === WebSocket.OPEN) ws.close(4003, normalized.code); - void this.teardown(entryId, "teamSpeak-connect-failed"); - }); + void connectTeamSpeak(false); }); this.wss.on("error", (error) => { @@ -321,6 +403,10 @@ export class VoiceBridge { private async cleanupEntry(entry: WebClientEntry, reason: SessionTeardownReason): Promise { if (this.entries.get(entry.id) === entry) this.entries.delete(entry.id); + if (entry.reconnectTimer) { + clearTimeout(entry.reconnectTimer); + entry.reconnectTimer = null; + } entry.opusEncoder = null; entry.channelTree = []; entry.members.clear(); diff --git a/test/reconnect-policy.test.ts b/test/reconnect-policy.test.ts new file mode 100644 index 0000000..6cdd4f9 --- /dev/null +++ b/test/reconnect-policy.test.ts @@ -0,0 +1,19 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { WebSpeakError } from "../src/errors.js"; +import { RECONNECT_WINDOW_MS, isRecoverable, reconnectDelayMs, reconnectWindowOpen } from "../src/server/reconnect-policy.js"; + +test("reconnect backoff follows the bounded policy and applies deterministic jitter", () => { + assert.deepEqual([1, 2, 3, 4, 5, 6, 8].map((attempt) => reconnectDelayMs(attempt, () => 0.5)), [1000, 2000, 4000, 8000, 15000, 30000, 30000]); + assert.equal(reconnectDelayMs(1, () => 0), 900); + assert.equal(reconnectDelayMs(1, () => 1), 1100); + assert.equal(reconnectDelayMs(0, () => 0.5), 1000); +}); + +test("reconnect eligibility distinguishes transient failures from authentication failures", () => { + assert.equal(isRecoverable(new WebSpeakError("unreachable", "offline", true)), true); + assert.equal(isRecoverable(new WebSpeakError("authentication_failed", "bad password", false)), false); + assert.equal(isRecoverable(null), true); + assert.equal(reconnectWindowOpen(10_000, 10_000 + RECONNECT_WINDOW_MS - 1), true); + assert.equal(reconnectWindowOpen(10_000, 10_000 + RECONNECT_WINDOW_MS), false); +}); diff --git a/test/session-manager.test.ts b/test/session-manager.test.ts index 74ec5d1..15831ea 100644 --- a/test/session-manager.test.ts +++ b/test/session-manager.test.ts @@ -14,6 +14,18 @@ test("connection state machine accepts the normal lifecycle and rejects illegal assert.throws(() => machine.transition("connected"), /Illegal connection state transition/); }); +test("connection state machine can retry a transient authentication phase", () => { + const machine = new ConnectionStateMachine(); + machine.transition("connecting"); + machine.transition("authenticating"); + machine.transition("reconnecting"); + machine.transition("connecting"); + machine.transition("authenticating"); + machine.transition("syncing"); + machine.transition("connected"); + assert.equal(machine.state, "connected"); +}); + test("managed session teardown is idempotent and reaches idle even when cleanup fails", async () => { const manager = new SessionManager(); let cleanupCalls = 0; diff --git a/web/src/composables/useVoiceWebSocket.ts b/web/src/composables/useVoiceWebSocket.ts index c0e6e81..cc0fa0a 100644 --- a/web/src/composables/useVoiceWebSocket.ts +++ b/web/src/composables/useVoiceWebSocket.ts @@ -3,6 +3,9 @@ import { reactive, ref } from "vue"; export interface VoiceState { connected: boolean; connecting: boolean; + reconnecting: boolean; + reconnectAttempt: number; + reconnectFailed: boolean; tsClientId: number; error: string; } @@ -37,11 +40,13 @@ export interface ChatMessage { export function useVoiceWebSocket() { const ws = ref(null); - const state = reactive({ connected: false, connecting: false, tsClientId: 0, error: "" }); + const state = reactive({ connected: false, connecting: false, reconnecting: false, reconnectAttempt: 0, reconnectFailed: false, tsClientId: 0, error: "" }); const members = reactive([]); const channels = reactive([]); const chatMessages = reactive([]); let connectionSequence = 0; + let lastConnection: { target: string; channel: string; nickname: string; serverPassword: string } | null = null; + let microphoneStartPromise: Promise | null = null; // Audio capture. The ScriptProcessor path remains the most compatible option // for the current browser support matrix, but the graph now has an explicit @@ -199,6 +204,16 @@ export function useVoiceWebSocket() { await refreshInputDevices(); } + async function ensureMicrophone(): Promise { + if (micStream) return; + if (!microphoneStartPromise) { + microphoneStartPromise = startMicrophone().finally(() => { + microphoneStartPromise = null; + }); + } + await microphoneStartPromise; + } + function voxGate(samples: Float32Array): boolean { let sum = 0; const count = Math.min(256, samples.length); @@ -313,10 +328,14 @@ export function useVoiceWebSocket() { } function connect(target: string, channel: string, nickname: string, serverPassword = ""): void { - disconnect(); + disconnect(true); + lastConnection = { target, channel, nickname, serverPassword }; const sequence = ++connectionSequence; state.error = ""; state.connecting = true; + state.reconnecting = false; + state.reconnectAttempt = 0; + state.reconnectFailed = false; void openTicketedConnection(sequence, target, channel, nickname, serverPassword); } @@ -350,7 +369,7 @@ export function useVoiceWebSocket() { socket.close(1000); return; } - startMicrophone().catch((error: unknown) => { + ensureMicrophone().catch((error: unknown) => { state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`; }); }; @@ -369,7 +388,8 @@ export function useVoiceWebSocket() { if (sequence !== connectionSequence) return; state.connected = false; state.connecting = false; - if (event.code !== 1000 && !state.error) state.error = closeReason(event.code); + state.reconnecting = false; + if (event.code !== 1000 && !state.error && !state.reconnectFailed) state.error = closeReason(event.code); stopMicrophone(); }; socket.onerror = () => { @@ -392,14 +412,18 @@ export function useVoiceWebSocket() { return "连接已断开"; } - function disconnect(): void { + function disconnect(preserveConnection = false): void { connectionSequence++; + if (!preserveConnection) lastConnection = null; stopMicrophone(); const socket = ws.value; ws.value = null; if (socket && socket.readyState < WebSocket.CLOSING) socket.close(1000); state.connected = false; state.connecting = false; + state.reconnecting = false; + state.reconnectAttempt = 0; + state.reconnectFailed = false; state.tsClientId = 0; members.length = 0; channels.length = 0; @@ -417,8 +441,13 @@ export function useVoiceWebSocket() { function handleMessage(msg: any): void { switch (msg.type) { case "connected": + const wasReconnecting = state.reconnecting; state.connected = true; state.connecting = false; + state.reconnecting = false; + state.reconnectAttempt = 0; + state.reconnectFailed = false; + state.error = ""; state.tsClientId = Number(msg.tsClientId) || 0; if (Array.isArray(msg.members)) { members.length = 0; @@ -426,6 +455,11 @@ export function useVoiceWebSocket() { members.push({ ...member, isSelf: Number(member.id) === state.tsClientId }); } } + if (wasReconnecting) { + ensureMicrophone().catch((error: unknown) => { + state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`; + }); + } break; case "memberEnter": if (!members.some((member) => member.id === msg.id)) { @@ -458,7 +492,29 @@ export function useVoiceWebSocket() { case "disconnected": state.connected = false; state.connecting = false; - state.error = "TeamSpeak 连接已断开"; + state.reconnecting = Boolean(msg.recoverable !== false); + state.reconnectFailed = false; + if (!state.reconnecting) state.error = "TeamSpeak 连接已断开"; + stopMicrophone(); + break; + case "reconnecting": + state.connected = false; + state.connecting = false; + state.reconnecting = true; + state.reconnectFailed = false; + state.reconnectAttempt = Number(msg.attempt) || state.reconnectAttempt + 1; + stopMicrophone(); + break; + case "reconnected": + state.reconnecting = false; + state.reconnectFailed = false; + break; + case "reconnectFailed": + state.connected = false; + state.connecting = false; + state.reconnecting = false; + state.reconnectFailed = true; + state.error = "连接已中断,无法自动恢复"; break; case "error": state.error = protocolErrorMessage(String(msg.error?.code || ""), String(msg.error?.message || msg.message || "操作失败")); @@ -495,6 +551,11 @@ export function useVoiceWebSocket() { }); } + function reconnectNow(): void { + if (!lastConnection || state.connecting) return; + connect(lastConnection.target, lastConnection.channel, lastConnection.nickname, lastConnection.serverPassword); + } + function setMicMode(mode: "vox" | "ptt"): void { micMode.value = mode; if (mode === "vox") pttPressed = false; @@ -564,6 +625,7 @@ export function useVoiceWebSocket() { startMicrophoneTest, stopMicrophoneTest, connect, + reconnectNow, disconnect, switchChannel, sendTextMessage, diff --git a/web/src/views/WebClient.vue b/web/src/views/WebClient.vue index 652ebc0..82d058c 100644 --- a/web/src/views/WebClient.vue +++ b/web/src/views/WebClient.vue @@ -1,7 +1,7 @@