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>
This commit is contained in:
javis-bot
2026-11-11 11:14:25 +09:00
parent 5838f9edd8
commit 8479112ddd
31 changed files with 5169 additions and 1 deletions

67
app/test/chat.test.ts Normal file
View File

@@ -0,0 +1,67 @@
import { describe, expect, it } from "vitest";
import { ChatAccessError, ChatChannels, hasMessageContentIntent, MESSAGE_LIMIT, splitMessage } from "../src/core/chat.js";
describe("splitMessage", () => {
it("leaves short text alone", () => {
expect(splitMessage("안녕하세요")).toEqual(["안녕하세요"]);
});
it("breaks at the last newline, then space, within the limit and loses only the break", () => {
const text = "aaaa bbbb\ncccc dddd";
const parts = splitMessage(text, 12);
expect(parts).toEqual(["aaaa bbbb", "cccc dddd"]);
expect(splitMessage("aaaa bbbb cccc", 10)).toEqual(["aaaa bbbb", "cccc"]);
});
it("cuts hard when there is no break, keeping emoji whole", () => {
const text = "x".repeat(MESSAGE_LIMIT - 1) + "😀" + "y";
const parts = splitMessage(text);
expect(parts.every((p) => p.length <= MESSAGE_LIMIT)).toBe(true);
expect(parts.join("")).toBe(text);
expect(parts[1]!.startsWith("😀")).toBe(true);
});
it("every part fits for long mixed text", () => {
const text = Array.from({ length: 900 }, (_, i) => `줄 ${i} 내용입니다`).join("\n");
const parts = splitMessage(text);
expect(parts.length).toBeGreaterThan(1);
expect(parts.every((p) => p.length > 0 && p.length <= MESSAGE_LIMIT)).toBe(true);
expect(parts.join("\n")).toBe(text);
});
});
describe("ChatChannels", () => {
const ch = new ChatChannels([
{ id: "111111111111111111", name: "일정", description: "", read: true, send: false },
{ id: "222222222222222222", name: "공지", description: "", read: false, send: true },
]);
it("follows each channel's read and send switches", () => {
expect(ch.canRead("111111111111111111")).toBe(true);
expect(ch.canSend("111111111111111111")).toBe(false);
expect(ch.canRead("222222222222222222")).toBe(false);
expect(ch.canSend("222222222222222222")).toBe(true);
expect(() => ch.assertSend("111111111111111111")).toThrow(ChatAccessError);
expect(() => ch.assertRead("222222222222222222")).toThrow(ChatAccessError);
});
it("refuses channels that are not registered", () => {
expect(ch.canRead("333333333333333333")).toBe(false);
expect(() => ch.assertRead("333333333333333333")).toThrow(/not a registered/);
expect(() => ch.assertSend("333333333333333333")).toThrow(/not a registered/);
});
it("needs the message intents only when some channel is readable", () => {
expect(ch.anyReadable).toBe(true);
expect(new ChatChannels([{ id: "1".repeat(18), name: "", description: "", read: false, send: true }]).anyReadable)
.toBe(false);
});
});
describe("hasMessageContentIntent", () => {
it("accepts the full and the limited intent flag", () => {
expect(hasMessageContentIntent(1 << 18)).toBe(true);
expect(hasMessageContentIntent(1 << 19)).toBe(true);
expect(hasMessageContentIntent((1 << 15) | (1 << 13))).toBe(false);
});
});

40
app/test/fixtures/fake_engine_worker.py vendored Normal file
View File

@@ -0,0 +1,40 @@
"""The real voice worker server with fake engines, for the app's protocol tests (no GPU, no models).
The fake VAD reads speech probability off the amplitude; the fake transcriber names a clip by its
pitch ("level 0.9" for a 900 Hz tone); the fake TTS makes 10 samples per character.
Run with the repo's src/ on PYTHONPATH: python fake_engine_worker.py <port>
"""
import asyncio
import os
import sys
import numpy as np
from voice_worker.server import VoiceWorker
class AmplitudeVad:
def prob(self, window):
return float(np.max(np.abs(window)))
class LevelTranscriber:
def transcribe(self, clips, opts):
return [f"level {np.argmax(np.abs(np.fft.rfft(c))) * 16000 / len(c) / 1000:.1f}" for c in clips]
class FakeTts:
def synthesize(self, text, rate):
return np.full(len(text) * 10, 1000, dtype=np.int16)
async def main(port: int) -> None:
worker = VoiceWorker(os.environ["JARVIS_VOICE_TOKEN"], LevelTranscriber(), AmplitudeVad, FakeTts())
server = await worker.serve("127.0.0.1", port)
print(f"READY 127.0.0.1:{port}", flush=True)
await server.serve_forever()
if __name__ == "__main__":
asyncio.run(main(int(sys.argv[1])))

26
app/test/frames.test.ts Normal file
View File

@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import { decodeTtsFrame, encodeAudioFrame, KIND_AUDIO, KIND_TTS } from "../src/core/frames.js";
describe("binary frames (voice_worker/protocol.py layout)", () => {
it("audio frame is kind, id length, UTF-8 id, then PCM", () => {
const pcm = Buffer.from([1, 0, 2, 0]);
const f = encodeAudioFrame("유저", pcm);
const id = Buffer.from("유저", "utf8");
expect([...f]).toEqual([KIND_AUDIO, id.length, ...id, 1, 0, 2, 0]);
});
it("rejects ids that do not fit in a byte", () => {
expect(() => encodeAudioFrame("", Buffer.alloc(2))).toThrow();
expect(() => encodeAudioFrame("x".repeat(256), Buffer.alloc(2))).toThrow();
});
it("decodes a TTS frame and refuses truncated ones", () => {
const id = Buffer.from("r1");
const seq = Buffer.alloc(4);
seq.writeUInt32LE(7);
const frame = Buffer.concat([Buffer.from([KIND_TTS, id.length]), id, seq, Buffer.from([9, 9])]);
expect(decodeTtsFrame(frame)).toEqual({ id: "r1", seq: 7, pcm: Buffer.from([9, 9]) });
expect(decodeTtsFrame(frame.subarray(0, 5))).toBeNull();
expect(decodeTtsFrame(Buffer.from([KIND_AUDIO, 1, 65, 0, 0, 0, 0]))).toBeNull();
});
});

View File

@@ -0,0 +1,317 @@
/**
* 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);
});

121
app/test/playback.test.ts Normal file
View File

@@ -0,0 +1,121 @@
import { describe, expect, it } from "vitest";
import { Playback, type PlaybackEnd } from "../src/core/playback.js";
/** A fake worker and speaker: records what was asked of them and what was played. */
function setup() {
const sent: { id: string; text: string; more: boolean }[] = [];
const cancelled: string[] = [];
const played: string[] = [];
let stops = 0;
const pb = new Playback(
{ tts: (id, text, more = false) => (sent.push({ id, text, more }), true), ttsCancel: (id) => void cancelled.push(id) },
{ play: (pcm) => void played.push(pcm.toString()), stop: () => void stops++ },
);
const ends: PlaybackEnd[] = [];
const starts: string[] = [];
pb.on("end", (e) => ends.push(e));
pb.on("start", (id) => starts.push(id));
return { pb, sent, cancelled, played, ends, starts, stops: () => stops };
}
const pcm = (s: string) => Buffer.from(s);
describe("Playback", () => {
it("plays the first sentence as soon as it arrives, then the next when the clip ends", () => {
const t = setup();
const id = t.pb.say("하나. 둘.");
expect(t.sent).toEqual([{ id, text: "하나. 둘.", more: false }]);
t.pb.audio(id, 0, pcm("s0"));
expect(t.played).toEqual(["s0"]);
expect(t.starts).toEqual([id]);
t.pb.audio(id, 1, pcm("s1"));
expect(t.played).toEqual(["s0"]); // still playing s0
t.pb.clipEnded();
expect(t.played).toEqual(["s0", "s1"]);
t.pb.done({ id, chunks: 2, cancelled: false, failed: false });
expect(t.ends).toEqual([]); // s1 is still playing
t.pb.clipEnded();
expect(t.ends).toEqual([{ id, played: 2, cancelled: false, failed: false }]);
expect(t.pb.busy).toBe(false);
});
it("plays requests in the order they were made", () => {
const t = setup();
const a = t.pb.say("a");
const b = t.pb.say("b");
t.pb.audio(b, 0, pcm("b0")); // b's audio arrives first
expect(t.played).toEqual([]);
t.pb.audio(a, 0, pcm("a0"));
t.pb.done({ id: a, chunks: 1, cancelled: false, failed: false });
t.pb.done({ id: b, chunks: 1, cancelled: false, failed: false });
t.pb.clipEnded();
t.pb.clipEnded();
expect(t.played).toEqual(["a0", "b0"]);
expect(t.ends.map((e) => e.id)).toEqual([a, b]);
});
it("keeps sentences in order even when they arrive out of order", () => {
const t = setup();
const id = t.pb.say("x", true);
t.pb.audio(id, 1, pcm("s1"));
expect(t.played).toEqual([]);
t.pb.audio(id, 0, pcm("s0"));
t.pb.clipEnded();
expect(t.played).toEqual(["s0", "s1"]);
});
it("skips a sentence that failed and still plays the rest", () => {
const t = setup();
const id = t.pb.say("a. b. c.");
t.pb.audio(id, 0, pcm("s0"));
t.pb.audio(id, 2, pcm("s2"));
t.pb.done({ id, chunks: 2, cancelled: false, failed: true });
t.pb.clipEnded();
t.pb.clipEnded();
expect(t.played).toEqual(["s0", "s2"]);
expect(t.ends).toEqual([{ id, played: 2, cancelled: false, failed: true }]);
});
it("stop silences the clip, cancels unfinished requests and drops the queue", () => {
const t = setup();
const a = t.pb.say("a", true);
const b = t.pb.say("b");
t.pb.audio(a, 0, pcm("a0"));
t.pb.done({ id: b, chunks: 0, cancelled: false, failed: false });
expect(t.pb.stop()).toBe(2);
expect(t.stops()).toBe(1);
expect(t.cancelled).toEqual([a]); // b was already done at the worker
expect(t.ends).toEqual([
{ id: a, played: 1, cancelled: true, failed: false },
{ id: b, played: 0, cancelled: true, failed: false },
]);
// Late audio for a stopped request is ignored.
t.pb.audio(a, 1, pcm("a1"));
t.pb.clipEnded();
expect(t.played).toEqual(["a0"]);
expect(t.pb.busy).toBe(false);
});
it("stop with nothing to say reports zero and touches nothing", () => {
const t = setup();
expect(t.pb.stop()).toBe(0);
expect(t.stops()).toBe(0);
});
it("text can be added to an open request", () => {
const t = setup();
const id = t.pb.say("첫 문장.", true);
t.pb.continueText(id, " 둘째 문장.", false);
expect(t.sent.map((s) => [s.text, s.more])).toEqual([["첫 문장.", true], [" 둘째 문장.", false]]);
});
it("a request the worker never accepted ends as failed without blocking the next", () => {
const t = setup();
const a = t.pb.say("a");
const b = t.pb.say("b");
t.pb.done({ id: a, chunks: 0, cancelled: false, failed: true });
t.pb.audio(b, 0, pcm("b0"));
expect(t.played).toEqual(["b0"]);
expect(t.ends[0]).toEqual({ id: a, played: 0, cancelled: false, failed: true });
});
});

61
app/test/settings.test.ts Normal file
View File

@@ -0,0 +1,61 @@
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { defaultSettings, loadSettings, parseSettings, SettingsError } from "../src/core/settings.js";
const ID = "123456789012345678";
describe("settings", () => {
it("an empty file gives the defaults", () => {
expect(parseSettings({})).toEqual(defaultSettings());
});
it("a missing file gives the defaults", () => {
const dir = mkdtempSync(join(process.env.TMPDIR ?? tmpdir(), "jarvis-settings-"));
expect(loadSettings(join(dir, "nope.json"))).toEqual(defaultSettings());
});
it("reads a full file, BOM included", () => {
const dir = mkdtempSync(join(process.env.TMPDIR ?? tmpdir(), "jarvis-settings-"));
const path = join(dir, "settings.json");
writeFileSync(path, "" + JSON.stringify({
discord: { guildId: ID, voiceChannelId: ID, commandName: "jarvis", ephemeralReplies: false },
voice: { maxSpeakers: 3, listenToBots: true, joinNotice: "알림", wakeWords: [" 자비스 ", "", "javis"],
stt: { end_silence_ms: 250 } },
chatChannels: [{ id: ID, name: "일정", description: "일정 올리는 곳", send: false }],
voiceWorker: { python: "/venv/bin/python", cwd: "/repo/src", args: ["--melo-python", "/m/python"] },
somethingNew: 1,
}));
const s = loadSettings(path);
expect(s.discord).toEqual({ guildId: ID, voiceChannelId: ID, commandName: "jarvis", ephemeralReplies: false });
expect(s.voice).toEqual({ maxSpeakers: 3, listenToBots: true, joinNotice: "알림", wakeWords: ["자비스", "javis"],
stt: { end_silence_ms: 250 } });
expect(s.chatChannels).toEqual([{ id: ID, name: "일정", description: "일정 올리는 곳", read: true, send: false }]);
expect(s.voiceWorker.args).toEqual(["--melo-python", "/m/python"]);
});
it.each([
[{ discord: { guildId: "abc" } }, /discord.guildId/],
[{ discord: { commandName: "Jarvis" } }, /commandName/],
[{ discord: { commandName: "두 단어" } }, /commandName/],
[{ voice: { maxSpeakers: 11 } }, /maxSpeakers/],
[{ voice: { maxSpeakers: 0 } }, /maxSpeakers/],
[{ voice: { joinNotice: " " } }, /joinNotice/],
[{ chatChannels: [{ id: ID }, { id: ID }] }, /twice/],
[{ chatChannels: [{ id: "1" }] }, /chatChannels\[0\].id/],
[{ chatChannels: {} }, /chatChannels/],
[{ voice: [] }, /voice/],
[[], /object/],
])("refuses %j", (raw, message) => {
expect(() => parseSettings(raw)).toThrow(SettingsError);
expect(() => parseSettings(raw)).toThrow(message);
});
it("reports invalid JSON with the path", () => {
const dir = mkdtempSync(join(process.env.TMPDIR ?? tmpdir(), "jarvis-settings-"));
const path = join(dir, "settings.json");
writeFileSync(path, "{ nope");
expect(() => loadSettings(path)).toThrow(/not valid JSON/);
});
});

24
app/test/speakers.test.ts Normal file
View File

@@ -0,0 +1,24 @@
import { describe, expect, it } from "vitest";
import { SpeakerGate } from "../src/core/speakers.js";
describe("SpeakerGate", () => {
it("hears up to the limit and lets the next person in once someone stops", () => {
const g = new SpeakerGate(2);
expect(g.start("a")).toBe(true);
expect(g.start("b")).toBe(true);
expect(g.start("c")).toBe(false);
expect(g.isActive("c")).toBe(false);
expect(g.end("a")).toBe(true);
expect(g.start("c")).toBe(true);
expect(g.count).toBe(2);
});
it("a speaker already heard stays heard; ending someone not heard is a no-op", () => {
const g = new SpeakerGate(1);
expect(g.start("a")).toBe(true);
expect(g.start("a")).toBe(true);
expect(g.end("z")).toBe(false);
expect(g.end("a")).toBe(true);
expect(g.end("a")).toBe(false);
});
});

5
app/test/tsconfig.json Normal file
View File

@@ -0,0 +1,5 @@
{
"extends": "../tsconfig.json",
"compilerOptions": { "noEmit": true, "rootDir": ".." },
"include": ["../src", "."]
}

View File

@@ -0,0 +1,171 @@
import { once } from "node:events";
import { afterEach, describe, expect, it } from "vitest";
import { WebSocketServer, type WebSocket } from "ws";
import { decodeTtsFrame, encodeAudioFrame, KIND_TTS } from "../src/core/frames.js";
import { VoiceWorkerClient, type TtsDone } from "../src/core/workerClient.js";
const TOKEN = "t0ken";
const FMT = { rate: 48000, channels: 2 } as const;
/** A stand-in voice worker: checks the hello and records what the client sends. */
async function fakeWorker(port = 0) {
const wss = new WebSocketServer({ host: "127.0.0.1", port });
await once(wss, "listening");
const received: (Record<string, unknown> | Buffer)[] = [];
const sockets: WebSocket[] = [];
wss.on("connection", (ws) => {
sockets.push(ws);
ws.on("message", (data, isBinary) => {
if (isBinary) return void received.push(data as Buffer);
const msg = JSON.parse(String(data));
received.push(msg);
if (msg.type === "hello") {
if (msg.token !== TOKEN) return ws.close(4401, "bad token");
ws.send(JSON.stringify({ type: "hello_ok", stt_ready: true, tts_ready: true, stt: msg.stt }));
}
});
});
const addr = wss.address() as { port: number };
return { wss, received, sockets, url: `ws://127.0.0.1:${addr.port}`, port: addr.port };
}
const cleanups: (() => void | Promise<void>)[] = [];
afterEach(async () => {
for (const c of cleanups.splice(0)) await c();
});
function client(url: string, extra: Partial<ConstructorParameters<typeof VoiceWorkerClient>[0]> = {}) {
const c = new VoiceWorkerClient({ url, token: TOKEN, audio: FMT, tts: FMT, backoffMs: 20, maxBackoffMs: 50, ...extra });
cleanups.push(() => c.close());
return c;
}
const until = async (pred: () => boolean, ms = 3000) => {
const end = Date.now() + ms;
while (!pred()) {
if (Date.now() > end) throw new Error("timed out");
await new Promise((r) => setTimeout(r, 10));
}
};
describe("VoiceWorkerClient", () => {
it("says hello with the token, formats and STT settings, then streams audio frames", async () => {
const w = await fakeWorker();
cleanups.push(() => void w.wss.close());
const c = client(w.url, { stt: { hotwords: ["자비스"] } });
c.start();
const ok = await c.waitReady(2000);
expect(ok.stt).toEqual({ hotwords: ["자비스"] });
expect(w.received[0]).toEqual({ type: "hello", token: TOKEN, audio: FMT, tts: FMT, stt: { hotwords: ["자비스"] } });
const pcm = Buffer.alloc(3840, 1);
c.sendAudio("123", pcm);
c.speakingEnd("123");
c.speakerLeave("123");
await until(() => w.received.length >= 4);
expect(w.received[1]).toEqual(encodeAudioFrame("123", pcm));
expect(w.received.slice(2)).toEqual([{ type: "speaking_end", speaker: "123" }, { type: "speaker_leave", speaker: "123" }]);
});
it("passes worker events on and only TTS audio of requests it opened", async () => {
const w = await fakeWorker();
cleanups.push(() => void w.wss.close());
const c = client(w.url);
c.start();
await c.waitReady(2000);
const finals: unknown[] = [];
const audio: { id: string; seq: number }[] = [];
const done: TtsDone[] = [];
c.on("final", (f) => finals.push(f));
c.on("tts_audio", (a) => audio.push({ id: a.id, seq: a.seq }));
c.on("tts_done", (d) => done.push(d));
expect(c.tts("r1", "안녕하세요.")).toBe(true);
await until(() => w.received.some((m) => !Buffer.isBuffer(m) && m.type === "tts"));
const ws = w.sockets[0]!;
const frame = (id: string, seq: number) => {
const s = Buffer.alloc(4);
s.writeUInt32LE(seq);
return Buffer.concat([Buffer.from([KIND_TTS, id.length]), Buffer.from(id), s, Buffer.alloc(8)]);
};
ws.send(frame("r1", 0));
ws.send(frame("zz", 0)); // not ours
ws.send(JSON.stringify({ type: "final", speaker: "1", utt: 1, text: "네", end_reason: "silence", audio_ms: 900,
wait_ms: 100, stt_ms: 80 }));
ws.send(JSON.stringify({ type: "tts_done", id: "r1", chunks: 1, cancelled: false, failed: false }));
await until(() => done.length === 1 && finals.length === 1);
expect(audio).toEqual([{ id: "r1", seq: 0 }]);
expect(decodeTtsFrame(frame("r1", 0))?.pcm.length).toBe(8);
expect(done[0]).toEqual({ id: "r1", chunks: 1, cancelled: false, failed: false });
});
it("a refused TTS request (no engine) ends as failed", async () => {
const w = await fakeWorker();
cleanups.push(() => void w.wss.close());
const c = client(w.url);
c.start();
await c.waitReady(2000);
const done: TtsDone[] = [];
c.on("tts_done", (d) => done.push(d));
c.tts("r9", "x");
await until(() => w.received.length >= 2);
w.sockets[0]!.send(JSON.stringify({ type: "error", code: "tts_unavailable", message: "no", id: "r9" }));
await until(() => done.length === 1);
expect(done[0]).toMatchObject({ id: "r9", failed: true });
});
it("reconnects after the worker restarts and fails the TTS that was in flight", async () => {
let w = await fakeWorker();
const port = w.port;
const c = client(w.url);
let readies = 0;
let disconnects = 0;
c.on("ready", () => readies++);
c.on("disconnected", () => disconnects++);
const done: TtsDone[] = [];
c.on("tts_done", (d) => done.push(d));
c.start();
await c.waitReady(2000);
c.tts("r1", "길게 말하는 중");
await until(() => w.received.length >= 2);
// The worker dies...
for (const s of w.sockets) s.terminate();
await new Promise<void>((r) => w.wss.close(() => r()));
await until(() => disconnects === 1);
expect(done).toEqual([{ id: "r1", chunks: 0, cancelled: false, failed: true }]);
expect(c.isReady).toBe(false);
// Audio while it is down is dropped, not queued.
c.sendAudio("1", Buffer.alloc(4));
// ...and comes back on the same port.
w = await fakeWorker(port);
cleanups.push(() => void w.wss.close());
await until(() => readies === 2);
expect(w.received[0]).toMatchObject({ type: "hello", token: TOKEN });
expect(w.received.filter(Buffer.isBuffer)).toEqual([]);
});
it("settings changed with configure() are sent now and in every later hello", async () => {
let w = await fakeWorker();
const port = w.port;
const c = client(w.url, { stt: { language: "ko" } });
c.start();
await c.waitReady(2000);
c.configure({ partials: false });
await until(() => w.received.length >= 2);
expect(w.received[1]).toEqual({ type: "config", partials: false });
for (const s of w.sockets) s.terminate();
await new Promise<void>((r) => w.wss.close(() => r()));
await until(() => !c.isReady);
w = await fakeWorker(port);
cleanups.push(() => void w.wss.close());
await until(() => c.isReady);
expect(w.received[0]).toMatchObject({ stt: { language: "ko", partials: false } });
});
it("tts while disconnected fails at once instead of waiting forever", async () => {
const c = client("ws://127.0.0.1:1");
const done: TtsDone[] = [];
c.on("tts_done", (d) => done.push(d));
expect(c.tts("r1", "x")).toBe(false);
await until(() => done.length === 1);
expect(done[0]).toMatchObject({ id: "r1", failed: true });
});
});

View File

@@ -0,0 +1,85 @@
import { mkdtempSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { once } from "node:events";
import { afterEach, describe, expect, it } from "vitest";
import { VoiceWorkerProcess } from "../src/core/workerProcess.js";
// A stand-in `voice_worker` package run by a real Python, so the spawn line is the one the app uses.
const PYTHON = process.env.JARVIS_TEST_PYTHON ?? (process.platform === "win32" ? "python" : "python3");
const FAKE_MAIN = `
import json, os, sys, time
out = os.environ["FAKE_OUT"]
runs = len(os.listdir(out))
with open(os.path.join(out, f"run{runs}.json"), "w") as f:
json.dump({"argv": sys.argv[1:], "token": os.environ.get("JARVIS_VOICE_TOKEN")}, f)
if os.environ.get("FAKE_CRASH_FIRST") == "1" and runs == 0:
sys.exit(3)
print("loading models...", flush=True)
print("READY 127.0.0.1:" + sys.argv[sys.argv.index("--port") + 1], flush=True)
time.sleep(60)
`;
function fakeWorkerDir() {
const root = mkdtempSync(join(process.env.TMPDIR ?? tmpdir(), "jarvis-fake-worker-"));
mkdirSync(join(root, "voice_worker"));
writeFileSync(join(root, "voice_worker", "__init__.py"), "");
writeFileSync(join(root, "voice_worker", "__main__.py"), FAKE_MAIN);
const out = join(root, "out");
mkdirSync(out);
return { root, out, run: (n: number) => JSON.parse(readFileSync(join(out, `run${n}.json`), "utf8")) };
}
const procs: VoiceWorkerProcess[] = [];
afterEach(async () => {
for (const p of procs.splice(0)) await p.stop(1000);
});
describe("VoiceWorkerProcess", () => {
it("runs python -m voice_worker on loopback with the token only in the environment", async () => {
const d = fakeWorkerDir();
const p = new VoiceWorkerProcess({ python: PYTHON, cwd: d.root, args: ["--melo-python", "/x/python"],
env: { FAKE_OUT: d.out } });
procs.push(p);
const ready = once(p, "ready");
await p.start();
await ready;
const run = d.run(0);
const port = new URL(p.url).port;
expect(run.argv).toEqual(["--host", "127.0.0.1", "--port", port, "--melo-python", "/x/python"]);
expect(run.token).toBe(p.token);
expect(p.token.length).toBeGreaterThanOrEqual(40);
expect(run.argv.join(" ")).not.toContain(p.token);
expect(new URL(p.url).hostname).toBe("127.0.0.1");
});
it("restarts a worker that dies, on the same port with the same token", async () => {
const d = fakeWorkerDir();
const p = new VoiceWorkerProcess({ python: PYTHON, cwd: d.root, args: [], restartDelayMs: 50,
env: { FAKE_OUT: d.out, FAKE_CRASH_FIRST: "1" } });
procs.push(p);
const exited = once(p, "exit");
const ready = once(p, "ready");
await p.start();
expect((await exited)[0]).toMatchObject({ code: 3 });
await ready;
expect(p.restarts).toBe(1);
expect(d.run(1).argv).toEqual(d.run(0).argv);
expect(d.run(1).token).toBe(d.run(0).token);
});
it("stop ends the worker for good", async () => {
const d = fakeWorkerDir();
const p = new VoiceWorkerProcess({ python: PYTHON, cwd: d.root, args: [], restartDelayMs: 20,
env: { FAKE_OUT: d.out } });
const ready = once(p, "ready");
await p.start();
await ready;
let exits = 0;
p.on("exit", () => exits++);
await p.stop(2000);
await new Promise((r) => setTimeout(r, 200));
expect(exits).toBe(1);
expect(p.restarts).toBe(0);
});
});

View File

@@ -0,0 +1,89 @@
/**
* The app's worker client against the real Python voice worker server (with fake engines), so both
* sides of the protocol are checked together. Needs a Python with the worker's requirements:
* JARVIS_VOICE_PYTHON=<venv python> npm test
*/
import { spawn, type ChildProcess } from "node:child_process";
import { createInterface } from "node:readline";
import { fileURLToPath } from "node:url";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { Playback } from "../src/core/playback.js";
import { VoiceWorkerClient, type Final, type TtsDone } from "../src/core/workerClient.js";
import { freePort } from "../src/core/workerProcess.js";
const PYTHON = process.env.JARVIS_VOICE_PYTHON;
const SRC = fileURLToPath(new URL("../../src", import.meta.url));
const FIXTURE = fileURLToPath(new URL("./fixtures/fake_engine_worker.py", import.meta.url));
const TOKEN = "protocol-test-token";
const FMT = { rate: 48000, channels: 2 } as const;
/** 20 ms of a 48 kHz stereo tone whose amplitude and pitch (x1000 Hz) are `level`. */
function frame(level: number): Buffer {
const n = 960;
const buf = Buffer.alloc(n * 4);
for (let i = 0; i < n; i++) {
const v = Math.round(level * Math.sin((2 * Math.PI * level * 1000 * i) / 48000) * 32767);
buf.writeInt16LE(v, i * 4);
buf.writeInt16LE(v, i * 4 + 2);
}
return buf;
}
describe.skipIf(!PYTHON)("worker protocol against the Python server", () => {
let child: ChildProcess;
let client: VoiceWorkerClient;
beforeAll(async () => {
const port = await freePort();
child = spawn(PYTHON!, [FIXTURE, String(port)], {
env: { ...process.env, PYTHONPATH: SRC, JARVIS_VOICE_TOKEN: TOKEN },
stdio: ["ignore", "pipe", "inherit"],
});
await new Promise<void>((resolve, reject) => {
child.once("exit", (c) => reject(new Error(`fake worker exited ${c}`)));
createInterface({ input: child.stdout! }).on("line", (l) => l.startsWith("READY") && resolve());
});
client = new VoiceWorkerClient({ url: `ws://127.0.0.1:${port}`, token: TOKEN, audio: FMT, tts: FMT,
stt: { partials: false, hotwords: ["자비스"] } });
client.start();
const ok = await client.waitReady(5000);
expect(ok).toMatchObject({ stt_ready: true, tts_ready: true });
expect(ok.stt).toMatchObject({ partials: false, hotwords: ["자비스"] });
});
afterAll(() => {
client?.close();
child?.kill();
});
it("Discord-format audio from two speakers comes back as each speaker's final", async () => {
const finals: Final[] = [];
client.on("final", (f) => finals.push(f));
for (let i = 0; i < 30; i++) {
client.sendAudio("111111111111111111", frame(0.9));
client.sendAudio("222222222222222222", frame(0.6));
}
client.speakingEnd("111111111111111111");
// The second speaker leaves mid-utterance: the final still comes.
client.speakerLeave("222222222222222222");
const end = Date.now() + 5000;
while (finals.length < 2 && Date.now() < end) await new Promise((r) => setTimeout(r, 20));
const bySpeaker = Object.fromEntries(finals.map((f) => [f.speaker, f]));
expect(bySpeaker["111111111111111111"]).toMatchObject({ text: "level 0.9", end_reason: "speaking_end", utt: 1 });
expect(bySpeaker["222222222222222222"]).toMatchObject({ text: "level 0.6", end_reason: "speaking_end", utt: 1 });
});
it("TTS sentences play in order through Playback and the request ends cleanly", async () => {
const played: Buffer[] = [];
const playback = new Playback(client, { play: (pcm) => { played.push(pcm); setTimeout(() => playback.clipEnded(), 5); }, stop: () => {} });
client.on("tts_audio", (f) => playback.audio(f.id, f.seq, f.pcm));
client.on("tts_done", (d: TtsDone) => playback.done(d));
const ended = new Promise((resolve) => playback.once("end", resolve));
const text = "첫 번째 문장입니다. 두 번째 문장은 조금 더 깁니다.";
playback.say(text);
expect(await ended).toMatchObject({ played: 2, cancelled: false, failed: false });
// 10 samples per character at 48 kHz, mono duplicated to stereo, 2 bytes each.
const sentences = ["첫 번째 문장입니다.", "두 번째 문장은 조금 더 깁니다."];
expect(played.map((p) => p.length)).toEqual(sentences.map((s) => s.length * 10 * 2 * 2));
});
});