Files
javis_bot/app/test/live/discord.live.test.ts
javis-bot 8479112ddd feat(app): M2 Discord voice core in the Electron app
- app/ (Electron 45 + TypeScript): the core joins one voice channel, decodes each speaker's Opus to
  48 kHz stereo and streams it to the voice worker, sends speaking_end and speaker_leave, and emits
  speech_start/partial/final with the speaker's display name.
- Sentence playback from the worker's TTS, first come first served, with stop that silences the clip
  at once and cancels unfinished requests; slash command join/leave/stop (create-or-update by name).
- Transcription notice posted on every join; other bots ignored by default; at most maxSpeakers
  people transcribed at once.
- Registered chat channels: live message events, history reads, sends split at 2,000 characters with
  mentions disabled; Message Content intent checked before login.
- The app starts the Python voice worker with a fresh token in the environment, restarts it with
  backoff, and the worker client reconnects and fails in-flight TTS on a lost connection.
- Spec in app/src/core/discord_core.spec.md; Vitest unit tests, a protocol test against the real
  Python worker server with fake engines, and an opt-in live test with two bots on real Discord.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:14:25 +09:00

318 lines
15 KiB
TypeScript

/**
* The Discord voice core end to end on real Discord, with the real voice worker on the GPU.
*
* Two bots in one voice channel: the "Jarvis" bot runs the core; the "speaker" bot plays recorded
* Korean speech into the channel, records what Jarvis says, and writes in the channel's chat.
* Opt-in; it refuses to run if a person is in the channel.
*
* JARVIS_LIVE_DISCORD=1 JARVIS_LIVE_BOT_TOKEN=... JARVIS_LIVE_SPEAKER_TOKEN=... \
* JARVIS_LIVE_GUILD=<server id> JARVIS_LIVE_VOICE_CHANNEL=<voice channel id> \
* JARVIS_VOICE_PYTHON=<worker venv python> JARVIS_MELO_PYTHON=<MeloTTS venv python> \
* npx vitest run test/live
*
* On Linux, put the pip CUDA libraries on LD_LIBRARY_PATH (nvidia/cublas/lib, nvidia/cudnn/lib).
*/
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { Client, Events, GatewayIntentBits, REST, Routes, type Message, type VoiceBasedChannel } from "discord.js";
import {
AudioPlayerStatus,
createAudioPlayer,
createAudioResource,
EndBehaviorType,
entersState,
joinVoiceChannel,
StreamType,
VoiceConnectionStatus,
type VoiceConnection,
} from "@discordjs/voice";
import OpusScript from "opusscript";
import { Readable } from "node:stream";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { DISCORD_PCM, DiscordCore, type HeardFinal } from "../../src/core/discordCore.js";
import { parseSettings } from "../../src/core/settings.js";
import { VoiceWorkerClient, type Final } from "../../src/core/workerClient.js";
import { VoiceWorkerProcess } from "../../src/core/workerProcess.js";
import type { PlaybackEnd } from "../../src/core/playback.js";
import type { ChatMessage } from "../../src/core/chat.js";
const env = process.env;
const LIVE = env.JARVIS_LIVE_DISCORD === "1";
const GUILD = env.JARVIS_LIVE_GUILD!;
const VOICE = env.JARVIS_LIVE_VOICE_CHANNEL!;
const COMMAND = "jarvis-live-test";
const SAMPLES = fileURLToPath(new URL("../../../scripts/m0/assets/ko_samples/", import.meta.url));
const SRC = fileURLToPath(new URL("../../../src", import.meta.url));
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
async function until(pred: () => boolean, ms: number, what: string) {
const end = Date.now() + ms;
while (!pred()) {
if (Date.now() > end) throw new Error(`timed out waiting for ${what}`);
await sleep(25);
}
}
function cer(ref: string, hyp: string): number {
const norm = (s: string) => [...s.replace(/[^\p{L}\p{N}]+/gu, "")];
const a = norm(ref);
const b = norm(hyp);
let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
for (let i = 1; i <= a.length; i++) {
const cur = [i];
for (let j = 1; j <= b.length; j++) {
cur.push(Math.min(prev[j]! + 1, cur[j - 1]! + 1, prev[j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1)));
}
prev = cur;
}
return prev[b.length]! / Math.max(1, a.length);
}
/** Seconds into 48 kHz stereo PCM where the last sound above -34 dBFS ends (the end of speech). */
function speechEndSeconds(pcm: Buffer): number {
for (let k = pcm.length / 4 - 1; k >= 0; k--) if (Math.abs(pcm.readInt16LE(k * 4)) > 655) return (k + 1) / 48000;
return 0;
}
/** A 16 kHz mono PCM16 WAV as 48 kHz stereo PCM16 (Discord's format). */
function wavTo48kStereo(path: string): Buffer {
const wav = readFileSync(path);
let off = 12;
let data: Buffer | null = null;
while (off + 8 <= wav.length) {
const id = wav.toString("ascii", off, off + 4);
const size = wav.readUInt32LE(off + 4);
if (id === "data") data = wav.subarray(off + 8, off + 8 + size);
off += 8 + size + (size % 2);
}
if (!data) throw new Error(`no data chunk in ${path}`);
const n = data.length / 2;
const out = Buffer.alloc(n * 3 * 4);
for (let k = 0; k < n * 3; k++) {
const pos = k / 3;
const i = Math.floor(pos);
const a = data.readInt16LE(i * 2);
const b = i + 1 < n ? data.readInt16LE((i + 1) * 2) : a;
const v = Math.round(a + (b - a) * (pos - i));
out.writeInt16LE(v, k * 4);
out.writeInt16LE(v, k * 4 + 2);
}
return out;
}
describe.skipIf(!LIVE)("Discord voice core on real Discord", () => {
let workerProcess: VoiceWorkerProcess;
let worker: VoiceWorkerClient;
let core: DiscordCore;
let speaker: Client;
let speakerVoice: VoiceConnection;
let jarvisId = "";
const finals: HeardFinal[] = [];
const speakEnds: PlaybackEnd[] = [];
const chats: ChatMessage[] = [];
/** Jarvis's voice as the speaker bot hears it: decoded PCM and packet times. */
const heard = { pcm: [] as Buffer[], lastPacketAt: 0, packets: 0 };
beforeAll(async () => {
// The speaker bot first: it checks the channel is free of people before anything joins.
speaker = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });
await speaker.login(env.JARVIS_LIVE_SPEAKER_TOKEN);
await new Promise<void>((r) => (speaker.isReady() ? r() : speaker.once(Events.ClientReady, () => r())));
const guild = await speaker.guilds.fetch(GUILD);
const people = guild.voiceStates.cache.filter((v) => v.channelId === VOICE && !v.member?.user.bot);
if (people.size) throw new Error(`refusing to test: ${people.size} people are in the voice channel`);
// Either bot already in a voice channel of this server is in use elsewhere; joining would move it.
const jarvisApp = (await new REST({ version: "10" }).setToken(env.JARVIS_LIVE_BOT_TOKEN!)
.get(Routes.currentApplication())) as { id: string };
for (const id of [speaker.user!.id, jarvisApp.id]) {
if (guild.voiceStates.cache.get(id)?.channelId) throw new Error(`refusing to test: bot ${id} is in a voice channel`);
}
workerProcess = new VoiceWorkerProcess({ python: env.JARVIS_VOICE_PYTHON!, cwd: SRC,
args: env.JARVIS_MELO_PYTHON ? ["--melo-python", env.JARVIS_MELO_PYTHON] : [] });
const workerReady = new Promise<void>((r) => workerProcess.once("ready", () => r()));
await workerProcess.start();
await workerReady;
worker = new VoiceWorkerClient({ url: workerProcess.url, token: workerProcess.token, audio: DISCORD_PCM,
tts: DISCORD_PCM, stt: { hotwords: ["자비스"] } });
worker.start();
await worker.waitReady(10_000);
const settings = parseSettings({
discord: { guildId: GUILD, voiceChannelId: VOICE, commandName: COMMAND },
// The "person" here is a bot, so bots must be heard.
voice: { listenToBots: true },
// The voice channel's own chat stands in for a registered chat channel.
chatChannels: [{ id: VOICE, name: "테스트", description: "라이브 테스트", read: true, send: true }],
});
core = new DiscordCore(settings, env.JARVIS_LIVE_BOT_TOKEN!, worker);
core.on("final", (f) => finals.push(f));
core.on("speak_end", (e) => speakEnds.push(e));
core.on("chat", (c) => chats.push(c));
core.on("ready", (r) => (jarvisId = r.userId));
await core.start(); // logs in, registers the command, auto-joins VOICE, posts the notice
expect(core.voiceChannelId).toBe(VOICE);
const channel = (await speaker.channels.fetch(VOICE)) as VoiceBasedChannel;
speakerVoice = joinVoiceChannel({ channelId: VOICE, guildId: GUILD, adapterCreator: channel.guild.voiceAdapterCreator,
selfDeaf: false, group: "speaker" });
await entersState(speakerVoice, VoiceConnectionStatus.Ready, 20_000);
speakerVoice.receiver.speaking.on("start", (userId) => {
if (userId !== jarvisId) return;
const stream = speakerVoice.receiver.subscribe(userId, { end: { behavior: EndBehaviorType.Manual } });
if (stream.listenerCount("data")) return;
const dec = new OpusScript(48000, 2, OpusScript.Application.VOIP);
stream.on("data", (p: Buffer) => {
heard.packets++;
heard.lastPacketAt = Date.now();
try {
heard.pcm.push(Buffer.from(dec.decode(p)));
} catch { /* corrupt packet */ }
});
});
}, 240_000);
afterAll(async () => {
try {
const rest = new REST({ version: "10" }).setToken(env.JARVIS_LIVE_BOT_TOKEN!);
const app = (await rest.get(Routes.currentApplication())) as { id: string };
const cmds = (await rest.get(Routes.applicationGuildCommands(app.id, GUILD))) as { id: string; name: string }[];
for (const c of cmds.filter((c) => c.name === COMMAND)) {
await rest.delete(Routes.applicationGuildCommand(app.id, GUILD, c.id));
}
} catch { /* best effort */ }
speakerVoice?.destroy();
await core?.close();
await speaker?.destroy();
worker?.close();
await workerProcess?.stop();
}, 60_000);
it("registered the slash command in the server", async () => {
const rest = new REST({ version: "10" }).setToken(env.JARVIS_LIVE_BOT_TOKEN!);
const app = (await rest.get(Routes.currentApplication())) as { id: string };
const cmds = (await rest.get(Routes.applicationGuildCommands(app.id, GUILD))) as
{ name: string; options: { name: string }[] }[];
const cmd = cmds.find((c) => c.name === COMMAND);
expect(cmd?.options.map((o) => o.name).sort()).toEqual(["join", "leave", "stop"]);
});
it("hears each recorded sentence played into the channel as a final transcript", async () => {
const refs = JSON.parse(readFileSync(`${SAMPLES}refs.json`, "utf8")).samples as { file: string; text: string }[];
const player = createAudioPlayer();
speakerVoice.subscribe(player);
const speakerId = speaker.user!.id;
const results: { ref: string; hyp: string; cer: number; speechEndToFinalMs: number; endReason: string }[] = [];
for (const ref of refs.slice(0, 5)) {
const before = finals.length;
const pcm = wavTo48kStereo(SAMPLES + ref.file);
player.play(createAudioResource(Readable.from([pcm]), { inputType: StreamType.Raw }));
await entersState(player, AudioPlayerStatus.Playing, 5000);
const speechEndsAt = Date.now() + speechEndSeconds(pcm) * 1000;
let finalAt = 0;
await until(() => {
const ok = finals.slice(before).some((f) => f.speakerId === speakerId);
if (ok && !finalAt) finalAt = Date.now();
return ok;
}, 20_000, `final for ${ref.file}`);
await entersState(player, AudioPlayerStatus.Idle, 20_000);
await sleep(800);
const mine = finals.slice(before).filter((f) => f.speakerId === speakerId);
const hyp = mine.map((f) => f.text).join(" ");
results.push({ ref: ref.text, hyp, cer: cer(ref.text, hyp), speechEndToFinalMs: finalAt - speechEndsAt,
endReason: mine.map((f) => f.endReason).join(",") });
expect(mine[0]!.speakerName.length).toBeGreaterThan(0);
}
console.log("live STT results", JSON.stringify(results, null, 1));
const mean = results.reduce((s, r) => s + r.cer, 0) / results.length;
expect(results.every((r) => r.hyp.length > 0)).toBe(true);
expect(mean).toBeLessThan(0.15);
}, 180_000);
it("speaks a reply the other side hears, and the STT reads it back", async () => {
const text = "안녕하세요, 저는 자비스입니다. 디스코드 음성 연결을 확인하고 있어요.";
heard.pcm.length = 0;
const before = speakEnds.length;
const id = core.say(text);
expect(id).not.toBeNull();
await until(() => speakEnds.length > before, 30_000, "speech to end");
expect(speakEnds.at(-1)).toMatchObject({ id, cancelled: false, failed: false });
await sleep(500);
const pcm = Buffer.concat(heard.pcm);
const seconds = pcm.length / (48000 * 4);
expect(seconds).toBeGreaterThan(2);
// Read Jarvis's voice back through the STT on a second worker session.
const echo = new VoiceWorkerClient({ url: workerProcess.url, token: workerProcess.token, audio: DISCORD_PCM,
tts: DISCORD_PCM, stt: { partials: false } });
echo.start();
await echo.waitReady(5000);
const got: Final[] = [];
echo.on("final", (f) => got.push(f));
const frame = 3840;
for (let k = 0; k < pcm.length; k += frame) echo.sendAudio("echo", pcm.subarray(k, k + frame));
for (let k = 0; k < 25; k++) echo.sendAudio("echo", Buffer.alloc(frame)); // 0.5 s of silence
echo.speakingEnd("echo");
await sleep(3000);
echo.close();
const hyp = got.map((f) => f.text).join(" ");
console.log("live TTS read back", JSON.stringify({ seconds, hyp, cer: cer(text, hyp) }));
expect(cer(text, hyp)).toBeLessThan(0.2);
}, 90_000);
it("stop silences it within a few frames and cancels the rest", async () => {
const text = "이 문장은 정지 명령을 시험하려고 길게 말하는 첫 번째 문장입니다. "
+ "두 번째 문장도 꽤 길게 이어집니다. 세 번째 문장까지 들리면 정지가 안 된 것입니다. "
+ "네 번째 문장은 절대 들리면 안 됩니다.";
const before = speakEnds.length;
let started = false;
core.once("speak_start", () => (started = true));
const id = core.say(text);
await until(() => started, 30_000, "speech to start");
await sleep(1500);
const stopAt = Date.now();
expect(core.stop()).toBe(1);
await sleep(1500);
expect(speakEnds.slice(before)).toEqual([expect.objectContaining({ id, cancelled: true })]);
const tail = heard.lastPacketAt - stopAt;
console.log("live stop", JSON.stringify({ lastPacketAfterStopMs: tail }));
// The player sends no padding after a forced stop; allow for network delivery.
expect(tail).toBeLessThan(400);
expect(core.speaking).toBe(false);
}, 60_000);
it("reads the registered chat channel live and in history, and sends to it without pings", async () => {
const channel = (await speaker.channels.fetch(VOICE)) as VoiceBasedChannel;
const marker = `라이브 테스트 메시지 ${Date.now()}`;
await channel.send(marker);
await until(() => chats.some((c) => c.content === marker), 10_000, "chat event");
expect(chats.find((c) => c.content === marker)).toMatchObject({ channelId: VOICE, authorId: speaker.user!.id,
authorIsBot: true, fromSelf: false });
const history = await core.readChat(VOICE, 20);
expect(history.some((m) => m.content === marker && !m.fromSelf)).toBe(true);
// The transcription notice from joining is there, written by Jarvis.
expect(history.some((m) => m.fromSelf && m.content.includes("받아 적습니다"))).toBe(true);
const seen: Message[] = [];
speaker.on(Events.MessageCreate, (m) => void (m.author.id === jarvisId && seen.push(m)));
const reply = `자비스 답장 @everyone ${Date.now()}`;
const ids = await core.sendChat(VOICE, reply);
await until(() => seen.some((m) => ids.includes(m.id)), 10_000, "sent message");
const sent = seen.find((m) => ids.includes(m.id))!;
expect(sent.content).toBe(reply);
expect(sent.mentions.everyone).toBe(false);
// Our own message does not come back as a chat event.
await sleep(500);
expect(chats.some((c) => c.content === reply)).toBe(false);
}, 60_000);
it("leaves the voice channel", async () => {
const guild = await speaker.guilds.fetch(GUILD);
expect(core.leave()).toBe(true);
await until(() => guild.voiceStates.cache.get(jarvisId)?.channelId == null, 10_000, "Jarvis to leave");
expect(core.voiceChannelId).toBeNull();
expect(core.say("아무도 못 듣는 말")).toBeNull();
}, 30_000);
});