fix(open-protocol): restore prefix-only command parsing and declare command_prefix in list_ack

This commit is contained in:
Dr1mH4X committed 2026-11-15 12:14:05 +08:00
1 parent 263c1ba6da
commit 69b311283a
6 files changed
+26 -92

No files matched your search

-29
View File
@@ -1,7 +1,6 @@
import { describe, it, expect } from "vitest";
import {
parseCommand,
parseCommandWithFallback,
canRunCommand,
isAdminCommand,
} from "./commands.js";
@@ -98,31 +97,3 @@ describe("canRunCommand", () => {
expect(canRunCommand("clear", [], [6])).toBe(false);
});
});
describe("parseCommandWithFallback", () => {
it("accepts both the configured primary prefix and slash fallback", () => {
expect(parseCommandWithFallback("!play 晴天", "!")).toEqual({
name: "play",
args: "晴天",
rawArgs: ["晴天"],
flags: new Set(),
});
expect(parseCommandWithFallback("/play 晴天", "!")).toEqual({
name: "play",
args: "晴天",
rawArgs: ["晴天"],
flags: new Set(),
});
});
it("applies aliases on slash fallback and ignores bare slash", () => {
expect(parseCommandWithFallback("/p 稻香", "!", { p: "play" })).toEqual({
name: "play",
args: "稻香",
rawArgs: ["稻香"],
flags: new Set(),
});
expect(parseCommandWithFallback("/", "!")).toBeNull();
expect(parseCommandWithFallback("plain chat", "!")).toBeNull();
});
});
-17
View File
@@ -55,23 +55,6 @@ export function parseCommand(
};
}
export function parseCommandWithFallback(
message: string,
primaryPrefix: string,
aliases: Record<string, string> = {},
fallbackPrefixes: readonly string[] = ["/"],
): ParsedCommand | null {
const direct = parseCommand(message, primaryPrefix, aliases);
if (direct) return direct;
for (const fallback of fallbackPrefixes) {
if (!fallback || fallback === primaryPrefix) continue;
const parsed = parseCommand(message, fallback, aliases);
if (parsed) return parsed;
}
return null;
}
export function isAdminCommand(commandName: string): boolean {
return ADMIN_COMMANDS.has(commandName);
}
+9 -6
View File
@@ -1949,18 +1949,21 @@ describe("BotInstance trackEnd — stale playback sessions", () => {
});
});
describe("BotInstance — OpenProtocol & slash command routing", () => {
it("accepts / commands when commandPrefix is '!' and routes private replies to invokerId", async () => {
describe("BotInstance — OpenProtocol & command routing", () => {
it("ignores / commands when commandPrefix is '!' and routes private replies to invokerId", async () => {
const ctx = makeGateCtx({ adminGroups: [] });
ctx.executeCommand = vi.fn(async (parsed: { name: string; args: string }) =>
`ok:${parsed.name}:${parsed.args}`,
);
await handleTextMessage.call(ctx, makeMsg("/play 晴天"));
expect(ctx.executeCommand).not.toHaveBeenCalled();
const dm: TS3TextMessage = {
invokerName: "FlSpeakUser",
invokerId: "12",
invokerUid: "uid-fl",
message: "/play 晴天",
message: "!play 晴天",
targetMode: 1,
invokerGroups: [],
};
@@ -1971,7 +1974,7 @@ describe("BotInstance — OpenProtocol & slash command routing", () => {
expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledWith("ok:play:晴天", 1, 12);
ctx.tsClient.sendTextMessage.mockClear();
await handleTextMessage.call(ctx, makeMsg("/now"));
await handleTextMessage.call(ctx, makeMsg("!now"));
expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledWith("ok:now:");
});
@@ -1981,7 +1984,7 @@ describe("BotInstance — OpenProtocol & slash command routing", () => {
invokerName: "Guest",
invokerId: "22",
invokerUid: "uid-guest",
message: "/stop",
message: "!stop",
targetMode: 1,
invokerGroups: [],
};
@@ -1993,7 +1996,7 @@ describe("BotInstance — OpenProtocol & slash command routing", () => {
okCtx.executeCommand = vi.fn(async () => {
throw new Error("boom");
});
await handleTextMessage.call(okCtx, { ...dmStop, message: "/play x" });
await handleTextMessage.call(okCtx, { ...dmStop, message: "!play x" });
expect(okCtx.tsClient.sendTextMessage).toHaveBeenCalledWith("Error: boom", 1, 22);
});
+2 -2
View File
@@ -12,7 +12,7 @@ import { AudioPlayer } from "../audio/player.js";
import { PlayQueue, PlayMode, type QueuedSong } from "../audio/queue.js";
import type { MusicProvider, Platform, Song } from "../music/provider.js";
import {
parseCommandWithFallback,
parseCommand,
canRunCommand,
type ParsedCommand,
} from "./commands.js";
@@ -823,7 +823,7 @@ export class BotInstance extends EventEmitter {
}
private async handleTextMessage(msg: TS3TextMessage): Promise<void> {
const parsed = parseCommandWithFallback(
const parsed = parseCommand(
msg.message,
this.config.commandPrefix,
this.config.commandAliases,
+7 -14
View File
@@ -39,8 +39,8 @@ function makeCmd(overrides: Partial<TS3PluginCommand> = {}): TS3PluginCommand {
}
describe("OpenProtocol payload builders", () => {
it("builds valid v1 identity payloads with package version and command_prefix under 1024 bytes", () => {
const raw = buildIdentityPayloadJson("announce", "!");
it("builds valid v1 identity payloads with package version under 1024 bytes", () => {
const raw = buildIdentityPayloadJson("announce");
expect(Buffer.byteLength(raw, "utf8")).toBeLessThan(MAX_PAYLOAD_BYTES);
expect(JSON.parse(raw)).toEqual({
v: OPEN_PROTOCOL_VERSION,
@@ -49,18 +49,11 @@ describe("OpenProtocol payload builders", () => {
app_name: APP_NAME,
app_version: APP_VERSION,
capabilities: [...BOT_CAPABILITIES],
command_prefix: "!",
});
const ack = JSON.parse(buildIdentityPayloadJson("announce_ack", "?"));
const ack = JSON.parse(buildIdentityPayloadJson("announce_ack"));
expect(ack.action).toBe("announce_ack");
expect(ack.command_prefix).toBe("?");
});
it("drops command_prefix if an oversized value would exceed 1024 bytes", () => {
const raw = buildIdentityPayloadJson("announce", "p".repeat(1200));
expect(Buffer.byteLength(raw, "utf8")).toBeLessThan(MAX_PAYLOAD_BYTES);
expect(JSON.parse(raw).app_name).toBe(APP_NAME);
expect(ack.command_prefix).toBeUndefined();
});
it("builds localized command lists adhering to field caps and <1024 byte UTF-8 limit", () => {
@@ -82,12 +75,12 @@ describe("OpenProtocol payload builders", () => {
const parsed = JSON.parse(raw) as {
v: number;
action: string;
prefix: string;
command_prefix: string;
commands: unknown[];
};
expect(parsed.v).toBe(OPEN_PROTOCOL_VERSION);
expect(parsed.action).toBe("list_ack");
expect(parsed.prefix).toBe("!");
expect(parsed.command_prefix).toBe("!");
expect(parsed.commands.length).toBe(cmds.length);
}
});
@@ -184,7 +177,7 @@ describe("OpenProtocolManager", () => {
const payload = JSON.parse(sendPluginCommand.mock.calls[0][1] as string);
expect(payload.v).toBe(1);
expect(payload.action).toBe("list_ack");
expect(payload.prefix).toBe("?");
expect(payload.command_prefix).toBe("?");
expect(payload.commands[0]).toEqual({ name: "play", args: "<query>", desc: "Play song" });
// Cooldown falls back to invokerId when invokerUid is empty
+8 -24
View File
@@ -21,6 +21,7 @@ export const ACK_GLOBAL_BURST = 4;
export const ACK_GLOBAL_RATE_PER_SEC = 2;
export const MAX_COMMANDS = 16;
export const MAX_CMD_PREFIX_CHARS = 8;
export const MAX_CMD_NAME_CHARS = 24;
export const MAX_CMD_ARGS_CHARS = 32;
export const MAX_CMD_DESC_CHARS = 64;
@@ -40,13 +41,12 @@ export interface OpenProtocolIdentityPayload {
app_name: string;
app_version: string;
capabilities: string[];
command_prefix?: string;
}
export interface OpenProtocolCommandsListAckPayload {
v: 1;
action: "list_ack";
prefix?: string;
command_prefix?: string;
commands: OpenProtocolCommandSpec[];
}
@@ -124,14 +124,8 @@ function truncateChars(value: string, maxChars: number): string {
export function buildIdentityPayloadJson(
action: "announce" | "announce_ack",
commandPrefix?: string,
appVersion: string = APP_VERSION,
): string {
const normalizedPrefix =
typeof commandPrefix === "string" && commandPrefix.trim().length > 0
? truncateChars(commandPrefix.trim(), MAX_CMD_NAME_CHARS)
: undefined;
const payload: OpenProtocolIdentityPayload = {
v: OPEN_PROTOCOL_VERSION,
action,
@@ -139,15 +133,8 @@ export function buildIdentityPayloadJson(
app_name: truncateChars(APP_NAME, MAX_APP_META_CHARS),
app_version: truncateChars(appVersion, MAX_APP_META_CHARS),
capabilities: [...BOT_CAPABILITIES],
...(normalizedPrefix ? { command_prefix: normalizedPrefix } : {}),
};
const json = JSON.stringify(payload);
if (Buffer.byteLength(json, "utf8") < MAX_PAYLOAD_BYTES) {
return json;
}
delete payload.command_prefix;
return JSON.stringify(payload);
}
@@ -172,7 +159,7 @@ export function buildCommandsListAckJson(
): string {
const normalizedPrefix =
typeof commandPrefix === "string" && commandPrefix.trim().length > 0
? truncateChars(commandPrefix.trim(), MAX_CMD_NAME_CHARS)
? truncateChars(commandPrefix.trim(), MAX_CMD_PREFIX_CHARS)
: undefined;
const commands = buildOpenProtocolCommands(locale);
@@ -180,7 +167,7 @@ export function buildCommandsListAckJson(
const payload: OpenProtocolCommandsListAckPayload = {
v: OPEN_PROTOCOL_VERSION,
action: "list_ack",
...(normalizedPrefix ? { prefix: normalizedPrefix } : {}),
...(normalizedPrefix ? { command_prefix: normalizedPrefix } : {}),
commands,
};
const json = JSON.stringify(payload);
@@ -193,7 +180,7 @@ export function buildCommandsListAckJson(
return JSON.stringify({
v: OPEN_PROTOCOL_VERSION,
action: "list_ack",
...(normalizedPrefix ? { prefix: normalizedPrefix } : {}),
...(normalizedPrefix ? { command_prefix: normalizedPrefix } : {}),
commands: [],
} satisfies OpenProtocolCommandsListAckPayload);
}
@@ -402,8 +389,7 @@ export class OpenProtocolManager {
);
if (!token) return;
const { commandPrefix } = this.getConfig();
const payload = buildIdentityPayloadJson("announce_ack", commandPrefix);
const payload = buildIdentityPayloadJson("announce_ack");
await this.sendAck(IDENTITY_PLUGIN, payload, invokerId, token);
}
@@ -460,8 +446,7 @@ export class OpenProtocolManager {
this.lastAnnounceAttemptMs = this.now();
const seq = ++this.announceSeq;
const { commandPrefix } = this.getConfig();
const payload = buildIdentityPayloadJson("announce", commandPrefix);
const payload = buildIdentityPayloadJson("announce");
if (Buffer.byteLength(payload, "utf8") >= MAX_PAYLOAD_BYTES) {
this.logger.debug("OpenProtocol announce payload exceeded size limit");
@@ -497,8 +482,7 @@ export class OpenProtocolManager {
return;
}
const retrySeq = ++this.announceSeq;
const { commandPrefix } = this.getConfig();
const payload = buildIdentityPayloadJson("announce", commandPrefix);
const payload = buildIdentityPayloadJson("announce");
this.lastAnnounceAttemptMs = this.now();
this.transport
.sendPluginCommand(IDENTITY_PLUGIN, payload, "channel")