perf(bridge): stream TTS per sentence to cut voice reply latency

The /converse turn synthesised the entire reply before any audio played, so
time-to-first-audio grew with reply length. Add a streaming /converse_stream
endpoint that emits the transcript/reply first, then one audio clip per
sentence as each finishes synthesising. The Discord voice layer enqueues each
clip on arrival via the existing FIFO playQueue, so the first sentence starts
speaking while the rest are still being synthesised.

STT and the reply engine still run to completion before the first clip; only
TTS is pipelined. The non-streaming /converse and /text endpoints are
unchanged.

- bridge: language-agnostic sentence splitter (bridge/text_utils.py) + NDJSON
  streaming route
- bot: ndjson() reader + converseStream() client; voice.ts plays clips
  progressively
- tests: splitter unit tests + bot ndjson/converseStream tests

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-06-13 01:09:39 +09:00
parent 989a4f3e98
commit 5c295420ea
6 changed files with 363 additions and 18 deletions

87
bot/src/bridge.test.ts Normal file
View File

@@ -0,0 +1,87 @@
import { test, expect } from "bun:test";
// bridge.ts imports the runtime `config`, which requires DISCORD_GUILD_ID.
// Set it before the dynamic import so the module loads without a real .env.
process.env.DISCORD_GUILD_ID ||= "test-guild";
const { ndjson, converseStream } = await import("./bridge.ts");
const enc = (s: string) => new TextEncoder().encode(s);
async function* chunked(...cs: string[]): AsyncGenerator<Uint8Array> {
for (const c of cs) yield enc(c);
}
test("ndjson yields one object per line even when chunks split mid-line", async () => {
const out: any[] = [];
for await (const o of ndjson(chunked('{"a":1}\n{"b":', '2}\n{"c":3}'))) out.push(o);
expect(out).toEqual([{ a: 1 }, { b: 2 }, { c: 3 }]);
});
test("ndjson skips blank lines and a trailing newline", async () => {
const out: any[] = [];
for await (const o of ndjson(chunked('{"a":1}\n\n{"b":2}\n'))) out.push(o);
expect(out).toEqual([{ a: 1 }, { b: 2 }]);
});
test("converseStream surfaces meta first, then plays each sentence clip in order", async () => {
const clipA = Buffer.from("clipA");
const clipB = Buffer.from("clipB");
const body =
[
JSON.stringify({
type: "meta",
transcript: "안녕",
reply: "안녕하세요. 반갑습니다!",
broadcast_action: "start",
}),
JSON.stringify({ type: "audio", seq: 0, audio_b64: clipA.toString("base64") }),
JSON.stringify({ type: "audio", seq: 1, audio_b64: clipB.toString("base64") }),
JSON.stringify({ type: "end" }),
].join("\n") + "\n";
const orig = globalThis.fetch;
globalThis.fetch = (async () => ({
ok: true,
body: chunked(body),
text: async () => "",
})) as any;
try {
const events: string[] = [];
const clips: Buffer[] = [];
let meta: any;
await converseStream(Buffer.from("wav"), true, {
onMeta: (m) => {
meta = m;
events.push("meta");
},
onAudio: (c) => {
clips.push(c);
events.push("audio");
},
});
expect(meta.transcript).toBe("안녕");
expect(meta.broadcast_action).toBe("start");
// Meta must arrive before any audio, and clips must stay in order.
expect(events).toEqual(["meta", "audio", "audio"]);
expect(clips.map((c) => c.toString())).toEqual(["clipA", "clipB"]);
} finally {
globalThis.fetch = orig;
}
});
test("converseStream throws on a non-ok bridge response", async () => {
const orig = globalThis.fetch;
globalThis.fetch = (async () => ({
ok: false,
status: 500,
body: null,
text: async () => "boom",
})) as any;
try {
await expect(converseStream(Buffer.from("wav"), undefined, {})).rejects.toThrow("500");
} finally {
globalThis.fetch = orig;
}
});