Merge the reviewed OpenProtocol changes into playback retry

This commit is contained in:
TIANYAO ZHANG committed 2026-11-18 17:02:45 +08:00
commit cb01cd3049
15 files changed
+1339 -182

No files matched your search

+147
View File
@@ -2013,3 +2013,150 @@ describe("BotInstance trackEnd — stale playback sessions", () => {
expect(ctx.advances).toEqual([]);
});
});
describe("BotInstance — OpenProtocol & command routing", () => {
it("routes private DM command replies to invokerId and channel replies to the channel", async () => {
const ctx = makeGateCtx({ adminGroups: [] });
ctx.executeCommand = vi.fn(async (parsed: { name: string; args: string }) =>
`ok:${parsed.name}:${parsed.args}`,
);
const dm: TS3TextMessage = {
invokerName: "FlSpeakUser",
invokerId: "12",
invokerUid: "uid-fl",
message: "!play 晴天",
targetMode: 1,
invokerGroups: [],
};
await handleTextMessage.call(ctx, dm);
expect(ctx.executeCommand).toHaveBeenCalledTimes(1);
expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledTimes(1);
expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledWith("ok:play:晴天", 1, 12);
ctx.tsClient.sendTextMessage.mockClear();
await handleTextMessage.call(ctx, makeMsg("!now"));
expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledWith("ok:now:");
});
it("drops a private command reply when the connection changed during execution", async () => {
const ctx = makeGateCtx({});
ctx.lifecycleGeneration = 1;
const executed = deferred();
const reply = deferred<string>();
ctx.executeCommand = vi.fn(() => {
executed.resolve();
return reply.promise;
});
const pending = handleTextMessage.call(ctx, { ...makeMsg("!now"), targetMode: 1 });
await executed.promise;
ctx.lifecycleGeneration++;
reply.resolve("Prior connection's queue");
await pending;
expect(ctx.tsClient.sendTextMessage).not.toHaveBeenCalled();
});
it("drops a command from a previous connection after the group check", async () => {
const ctx = makeGateCtx({ adminGroups: [6] });
ctx.lifecycleGeneration = 1;
const groups = deferred<string[]>();
ctx.tsClient.getClientServerGroups.mockReturnValue(groups.promise);
const pending = handleTextMessage.call(ctx, { ...makeMsg("!stop"), targetMode: 1 });
expect(ctx.tsClient.getClientServerGroups).toHaveBeenCalled();
ctx.lifecycleGeneration++;
groups.resolve(["6"]);
await pending;
expect(ctx.executeCommand).not.toHaveBeenCalled();
expect(ctx.tsClient.sendTextMessage).not.toHaveBeenCalled();
});
it("routes permission denied and execution errors privately when triggered via DM", async () => {
const ctx = makeGateCtx({ adminGroups: [6], lookupGroups: [] });
const dmStop: TS3TextMessage = {
invokerName: "Guest",
invokerId: "22",
invokerUid: "uid-guest",
message: "!stop",
targetMode: 1,
invokerGroups: [],
};
await handleTextMessage.call(ctx, dmStop);
expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledWith(COMMAND_DENIED_MESSAGE, 1, 22);
ctx.tsClient.sendTextMessage.mockClear();
const okCtx = makeGateCtx({ adminGroups: [] });
okCtx.executeCommand = vi.fn(async () => {
throw new Error("boom");
});
await handleTextMessage.call(okCtx, { ...dmStop, message: "!play x" });
expect(okCtx.tsClient.sendTextMessage).toHaveBeenCalledWith("Error: boom", 1, 22);
});
it("wires connected, clientMoved, pluginCommand, and disconnected to openProtocol", () => {
const tsClient = new EventEmitter() as EventEmitter & {
getClientId(): number;
};
tsClient.getClientId = () => 99;
const openProtocol = {
scheduleAnnounce: vi.fn(),
handlePluginCommand: vi.fn(async () => {}),
reset: vi.fn(),
};
const ctx = {
tsClient,
openProtocol,
connected: true,
lifecycleGeneration: 0,
autoPaused: false,
idleTimer: null,
idlePollTimer: null,
jellyfinPollTimer: null,
snapshotTimer: null,
currentSourceIsSpotify: false,
disconnectEmitted: false,
_cancelIdleTimer: vi.fn(),
_startIdlePoller: vi.fn(),
_startJellyfinReportPoller: vi.fn(),
unregisterManagedVoiceClient: vi.fn(),
voiceDucking: { reset: vi.fn(), removeSpeaker: vi.fn(), handleVoiceActivity: vi.fn() },
spotifyController: { stop: vi.fn() },
player: { stop: vi.fn() },
jellyfinReporter: undefined,
queue: { clear: vi.fn() },
sweepLocalAudio: vi.fn(),
emit: vi.fn(),
refreshOccupancy: vi.fn(async () => {}),
profileManager: { onChannelMoved: vi.fn(async () => {}) },
logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },
} as Record<string, any>;
(BotInstance.prototype as any).setupTsEvents.call(ctx);
tsClient.emit("connected");
expect(openProtocol.scheduleAnnounce).toHaveBeenCalledTimes(1);
tsClient.emit("clientMoved", { id: 5, targetChannelID: 10n });
expect(openProtocol.scheduleAnnounce).toHaveBeenCalledTimes(1);
tsClient.emit("clientMoved", { id: 99, targetChannelID: 10n });
expect(openProtocol.scheduleAnnounce).toHaveBeenCalledTimes(2);
const pluginCmd = {
name: "tsclient:commands",
data: JSON.stringify({ v: 1, action: "list_req" }),
invokerId: 5,
invokerName: "User",
invokerUid: "uid-user",
};
tsClient.emit("pluginCommand", pluginCmd);
expect(openProtocol.handlePluginCommand).toHaveBeenCalledWith(pluginCmd);
tsClient.emit("disconnected");
expect(openProtocol.reset).toHaveBeenCalledTimes(1);
});
});
+48 -6
View File
@@ -2,10 +2,12 @@ import { EventEmitter } from "node:events";
import {
TS3Client,
type TS3ClientOptions,
type TS3PluginCommand,
type TS3TextMessage,
type TS3VoiceActivity,
type TS3VoiceSendFailure,
} from "../ts-protocol/client.js";
import { OpenProtocolManager } from "../ts-protocol/open-protocol.js";
import { AudioPlayer } from "../audio/player.js";
import { resolveUrlWithRetry } from "./url-retry.js";
import { RISK_CONTROL_CODE, RiskControlError, toPlayFailure } from "../music/provider.js";
@@ -157,11 +159,27 @@ export interface BotStatus {
effectiveDuration?: number;
}
async function sendTextReply(
tsClient: Pick<TS3Client, "sendTextMessage">,
msg: TS3TextMessage,
text: string,
): Promise<void> {
if (msg.targetMode === 1) {
const targetClientId = Number(msg.invokerId);
if (Number.isInteger(targetClientId) && targetClientId > 0) {
await tsClient.sendTextMessage(text, 1, targetClientId);
}
return;
}
await tsClient.sendTextMessage(text);
}
export class BotInstance extends EventEmitter {
readonly id: string;
name: string;
private tsClient: TS3Client;
private openProtocol: OpenProtocolManager;
private player: AudioPlayer;
private voiceDucking: VoiceDuckingController;
private managedVoiceClients: ManagedVoiceClientRegistry;
@@ -235,6 +253,14 @@ export class BotInstance extends EventEmitter {
this.avatarStore = options.avatarStore;
this.tsClient = new TS3Client(options.tsOptions, this.logger);
this.openProtocol = new OpenProtocolManager({
transport: this.tsClient,
getConfig: () => ({
locale: this.config.locale,
commandPrefix: this.config.commandPrefix,
}),
logger: this.logger,
});
this.player = new AudioPlayer(this.logger);
this.voiceDucking = new VoiceDuckingController(
this.player,
@@ -451,6 +477,12 @@ export class BotInstance extends EventEmitter {
});
});
this.tsClient.on("pluginCommand", (cmd: TS3PluginCommand) => {
this.openProtocol?.handlePluginCommand(cmd).catch((err) => {
this.logger.debug({ err }, "OpenProtocol plugin command handler failed");
});
});
this.tsClient.on("disconnected", () => {
// Always reset local state — covers the case where connect() never
// completed (hanging handshake → 60s library idle timeout) and
@@ -458,6 +490,7 @@ export class BotInstance extends EventEmitter {
// short-circuited on !this.connected, leaving player stuck as "playing".
this.lifecycleGeneration++;
this.connected = false;
this.openProtocol?.reset();
this._cancelIdleTimer();
this.unregisterManagedVoiceClient(MANAGED_VOICE_CLIENT_RELEASE_GRACE_MS);
this.voiceDucking.reset(true);
@@ -492,6 +525,7 @@ export class BotInstance extends EventEmitter {
this.autoPaused = false;
this._startIdlePoller();
this._startJellyfinReportPoller();
this.openProtocol?.scheduleAnnounce();
});
this.tsClient.on("voiceActivity", (activity: TS3VoiceActivity) => {
@@ -530,6 +564,7 @@ export class BotInstance extends EventEmitter {
this.profileManager.onChannelMoved(event.targetChannelID).catch((err) => {
this.logger.warn({ err }, "Channel description move update failed");
});
this.openProtocol?.scheduleAnnounce();
} else {
this.voiceDucking.removeSpeaker(event.id);
}
@@ -672,6 +707,7 @@ export class BotInstance extends EventEmitter {
this.disconnectEmitted = true;
this.emit("disconnected");
}
this.openProtocol?.reset();
this.tsClient.disconnect();
// Stop outbound PCM and initiate the TeamSpeak disconnect before removing
// our id from the shared registry, minimizing the window in which another
@@ -799,13 +835,19 @@ export class BotInstance extends EventEmitter {
);
if (!parsed) return;
if (!(await this.isCommandAllowed(parsed.name, msg))) {
// A numeric invoker ID only belongs to this TeamSpeak connection.
const generation = this.lifecycleGeneration;
const isCurrent = () => this.lifecycleGeneration === generation;
const allowed = await this.isCommandAllowed(parsed.name, msg);
if (!isCurrent()) return;
if (!allowed) {
this.logger.info(
{ command: parsed.name, invoker: msg.invokerName },
"Command denied: invoker not in adminGroups"
);
try {
await this.tsClient.sendTextMessage(COMMAND_DENIED_MESSAGE);
await sendTextReply(this.tsClient, msg, COMMAND_DENIED_MESSAGE);
} catch (sendErr) {
this.logger.error({ err: sendErr }, "Failed to send permission-denied message to chat");
}
@@ -823,15 +865,15 @@ export class BotInstance extends EventEmitter {
// A single long reply (e.g. full lyrics) would exceed TeamSpeak's
// per-message byte cap, so split it and send the chunks in order.
for (const chunk of splitTextIntoChunks(response)) {
await this.tsClient.sendTextMessage(chunk);
if (!isCurrent()) return;
await sendTextReply(this.tsClient, msg, chunk);
}
}
} catch (err) {
if (!isCurrent()) return;
this.logger.error({ err, command: parsed.name }, "Command execution error");
try {
await this.tsClient.sendTextMessage(
`Error: ${(err as Error).message}`
);
await sendTextReply(this.tsClient, msg, `Error: ${(err as Error).message}`);
} catch (sendErr) {
this.logger.error({ err: sendErr }, "Failed to send error message to chat");
}
+3 -9
View File
@@ -1,5 +1,4 @@
import { describe, it, expect, beforeEach, vi } from "vitest";
import { Client, generateIdentity } from "@honeybbq/teamspeak-client";
import { BotProfileManager } from "./profile.js";
import { TS6HttpQuery } from "../ts-protocol/http-query.js";
import type { TS3Client } from "../ts-protocol/client.js";
@@ -419,20 +418,15 @@ describe("BotProfileManager checked TS6 profile lifecycle", () => {
it("checks self clientupdate permission responses and retries only after reconnect", async () => {
const { pm, ts, request, logger } = makeHttpProfile({ nicknameEnabled: true, awayStatusEnabled: true });
const client: any = new Client(generateIdentity(0), "127.0.0.1:9987", "Bot");
const commands: string[] = [];
client.handler.sendPacket = vi.fn((_type, data: Buffer) => {
const command = data.toString();
ts.execCommand.mockImplementation(async (command: string) => {
commands.push(command);
const returnCode = command.match(/return_code=(\d+)/)?.[1];
client.handler.onPacket({ typeFlagged: 2, data: Buffer.from(`error id=2568 msg=insufficient\\sclient\\spermissions${returnCode ? ` return_code=${returnCode}` : ""}`) });
throw new Error("insufficient client permissions (error id=2568)");
});
ts.sendCommandNoWait.mockImplementation((command: string) => client.sendCommandNoWait(command));
ts.execCommand.mockImplementation((command: string) => client.execCommand(command));
await pm.onSongChange(null);
await pm.onSongChange(null);
expect(commands).toHaveLength(1);
expect(commands[0]).toMatch(/^clientupdate client_nickname=Bot client_away=1 client_away_message=等待播放 return_code=\d+$/);
expect(commands[0]).toBe("clientupdate client_nickname=Bot client_away=1 client_away_message=等待播放");
expect(request).not.toHaveBeenCalled();
expect(logger.info.mock.calls.some((call: any[]) => call[1] === "Client properties updated (nickname + away)")).toBe(false);
pm.onConnect();