M003: add TeamSpeak reconnect recovery

This commit is contained in:
illusia committed 2026-09-01 16:59:48 +08:00
1 parent 8c7a940de5
commit 3cca211ae9
10 files changed
+362 -98

No files matched your search

+3 -1
View File
@@ -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.
+19
View File
@@ -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;
}
+3 -3
View File
@@ -23,9 +23,9 @@ export type SessionTeardownReason =
const ALLOWED_TRANSITIONS: Record<ConnectionState, readonly ConnectionState[]> = {
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"],
+3 -1
View File
@@ -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,
+96 -58
View File
@@ -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<void> {
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<void>((resolve) => setImmediate(resolve));
await new Promise<void>((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<void> {
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 };
+114 -28
View File
@@ -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<number, ChannelMember>;
opusEncoder: { encode(pcm: Buffer): Buffer } | null;
isAlive: boolean;
reconnectTimer: ReturnType<typeof setTimeout> | 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<string, unknown>) => {
@@ -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<typeof normalizeTeamSpeakError>) => {
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<typeof normalizeTeamSpeakError> | 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<void> => {
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<void> {
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();
+19
View File
@@ -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);
});
+12
View File
@@ -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;
+68 -6
View File
@@ -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<WebSocket | null>(null);
const state = reactive<VoiceState>({ connected: false, connecting: false, tsClientId: 0, error: "" });
const state = reactive<VoiceState>({ connected: false, connecting: false, reconnecting: false, reconnectAttempt: 0, reconnectFailed: false, tsClientId: 0, error: "" });
const members = reactive<ChannelMember[]>([]);
const channels = reactive<ChannelInfo[]>([]);
const chatMessages = reactive<ChatMessage[]>([]);
let connectionSequence = 0;
let lastConnection: { target: string; channel: string; nickname: string; serverPassword: string } | null = null;
let microphoneStartPromise: Promise<void> | 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<void> {
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,
+25 -1
View File
@@ -1,7 +1,7 @@
<template>
<div class="web-client" @keydown="onKeyDown" @keyup="onKeyUp" tabindex="0">
<!-- Connection / welcome screen -->
<section v-if="!voiceState.connected" class="join-page">
<section v-if="!voiceState.connected && !voiceState.reconnecting && !voiceState.reconnectFailed" class="join-page">
<header class="join-header">
<div class="brand-lockup">
<div class="brand-mark"><Icon name="waveform" :size="22" /></div>
@@ -92,6 +92,11 @@
</div>
</header>
<div v-if="voiceState.reconnecting || voiceState.reconnectFailed" :class="['reconnect-banner', { failed: voiceState.reconnectFailed }]" role="status">
<div class="reconnect-copy"><strong>{{ voiceState.reconnectFailed ? t('reconnectFailed') : t('connectionInterrupted') }}</strong><span v-if="voiceState.reconnecting">{{ t('reconnectingAttempt', { attempt: voiceState.reconnectAttempt }) }}</span><span v-else>{{ localizedMessage(voiceState.error) }}</span></div>
<div class="reconnect-actions"><button v-if="voiceState.reconnectFailed" type="button" class="secondary-button" @click="reconnectNow">{{ t('reconnectNow') }}</button><button type="button" class="text-button" @click="doDisconnect">{{ t('back') }}</button></div>
</div>
<div class="workspace-scroll">
<div class="workspace-content">
<section class="room-hero">
@@ -207,6 +212,7 @@ const {
startMicrophoneTest,
stopMicrophoneTest,
connect,
reconnectNow,
disconnect,
switchChannel,
sendTextMessage,
@@ -342,6 +348,11 @@ const translations: Record<Language, Record<string, string>> = {
volumeTip: "拖动成员右侧滑杆,单独调整听到的音量。",
moreMemberOptions: "更多成员选项",
connectedToast: "当前已连接到此服务器",
connectionInterrupted: "连接已中断,正在尝试恢复…",
reconnectingAttempt: "第 {{attempt}} 次重连",
reconnectFailed: "无法恢复连接",
reconnectNow: "立即重连",
back: "返回",
volumeToast: "成员音量可以在列表中单独调整",
copiedToast: "邀请链接已复制",
copyFailedToast: "复制失败,请手动复制浏览器地址",
@@ -478,6 +489,11 @@ const translations: Record<Language, Record<string, string>> = {
volumeTip: "Drag a member slider to adjust their volume just for you.",
moreMemberOptions: "More member options",
connectedToast: "You are connected to this server",
connectionInterrupted: "Connection interrupted",
reconnectingAttempt: "Reconnecting… Attempt {{attempt}}",
reconnectFailed: "Could not restore the connection",
reconnectNow: "Reconnect now",
back: "Back",
volumeToast: "Adjust each member's volume from the list",
copiedToast: "Invite link copied",
copyFailedToast: "Copy failed. Copy the browser address manually",
@@ -982,6 +998,14 @@ function stopPointerTalk() {
.settings-select:disabled { cursor: wait; opacity: .65; }
.settings-error { margin: -9px 0 15px; color: #b14e47; font-size: 10px; line-height: 1.5; }
.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-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; }
.reconnect-actions { display: flex; align-items: center; gap: 12px; flex: 0 0 auto; }
.reconnect-actions .secondary-button { min-height: 34px; padding-inline: 13px; }
@media (max-width: 740px) { .reconnect-banner { align-items: flex-start; flex-direction: column; gap: 10px; width: calc(100% - 30px); }.reconnect-copy { align-items: flex-start; flex-direction: column; gap: 4px; }.reconnect-actions { width: 100%; justify-content: flex-end; } }
.save-button { min-height: 38px; }
/* Increase connected-view typography by 25% while keeping the layout compact. */