Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(tts): cancel HTTP synthesis when playback stops

Afloatfd62c06d0928
diff --git a/server/tts/cancellation.test.ts b/server/tts/cancellation.test.ts
new file mode 100644
index 0000000000..a772214009
--- /dev/null
+++ b/server/tts/cancellation.test.ts
@@ -0,0 +1,83 @@
+import { once } from "node:events";
+import { createServer, type Server, type ServerResponse } from "node:http";
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+
+import type { AppConfig } from "../config.ts";
+import { json, readBody } from "../harness/http.ts";
+
+let provider: Server;
+let api: Server;
+let providerUrl = "";
+let apiUrl = "";
+let config: AppConfig = {};
+let entered: (response: ServerResponse) => void;
+
+async function listen(server: Server): Promise<string> {
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const address = server.address();
+ if (!address || typeof address === "string") throw new Error("Expected TCP fixture");
+ return `http://127.0.0.1:${address.port}`;
+}
+
+beforeAll(async () => {
+ provider = createServer((req, res) => {
+ req.resume();
+ const gemini = req.url === "/interactions";
+ res.writeHead(200, { "content-type": gemini ? "application/json" : "audio/mpeg" });
+ res.write(gemini
+ ? '{"steps":[{"type":"model_output","content":[{"type":"audio","mime_type":"audio/wav","data":"'
+ : Buffer.from([0xff, 0xfb, 0x90, 0x00]));
+ entered(res);
+ });
+ providerUrl = await listen(provider);
+ vi.stubEnv("OMB_ELEVENLABS_API", `${providerUrl}/v1`);
+ vi.stubEnv("OMB_FISH_AUDIO_API", providerUrl);
+ vi.stubEnv("OMB_XAI_TTS_API", `${providerUrl}/v1`);
+ vi.stubEnv("OMB_GEMINI_TTS_API", providerUrl);
+ const { createTtsRoutes } = await import("../routes/tts.ts");
+ const route = createTtsRoutes({ config: () => config });
+ api = createServer(async (req, res) => {
+ const url = new URL(req.url ?? "/", "http://localhost");
+ await route({
+ req, res, url, path: url.pathname, method: req.method ?? "GET", json, readBody,
+ auth: { kind: "loopback", scopes: ["admin", "client"] },
+ });
+ });
+ apiUrl = await listen(api);
+});
+
+afterEach(() => {
+ api.closeAllConnections();
+ provider.closeAllConnections();
+});
+
+afterAll(async () => {
+ await Promise.all([api, provider].map((server) => new Promise<void>((resolve) => server.close(() => resolve()))));
+ vi.unstubAllEnvs();
+});
+
+describe("stopping read aloud", () => {
+ it.each(["elevenlabs", "fish", "gemini", "xai", "chatterbox"] as const)(
+ "closes the in-flight %s request when the reader disconnects", async (kind) => {
+ config = {
+ xai: { key: "local-fixture-only" },
+ tts: {
+ provider: kind, voice: kind === "gemini" ? "Kore" : "test-voice", baseUrl: providerUrl,
+ key: "local-fixture-only", fishKey: "local-fixture-only", geminiKey: "local-fixture-only",
+ },
+ };
+ const receiving = new Promise<ServerResponse>((resolve) => { entered = resolve; });
+ const controller = new AbortController();
+ const response = fetch(`${apiUrl}/api/tts/speak`, {
+ method: "POST", headers: { "content-type": "application/json" },
+ body: JSON.stringify({ text: "A reply the person stopped reading aloud." }), signal: controller.signal,
+ }).catch((error: unknown) => error);
+ const streaming = await receiving;
+ const closed = once(streaming, "close", { signal: AbortSignal.timeout(2_000) });
+ controller.abort();
+ expect(await response).toBeInstanceOf(Error);
+ await closed;
+ expect(streaming.writableEnded).toBe(false);
+ },
+ );
+});
diff --git a/server/tts/chatterbox.ts b/server/tts/chatterbox.ts
index 1ef5884700..6a9a09c85b 100644
--- a/server/tts/chatterbox.ts
+++ b/server/tts/chatterbox.ts
@@ -89,6 +89,7 @@ export async function synthesizeChatterbox(
voiceId: string,
baseUrl: string,
model?: string,
+ signal?: AbortSignal,
): Promise<Audio> {
const res = await request(
`${apiRoot(baseUrl)}/audio/speech`,
@@ -96,7 +97,7 @@ export async function synthesizeChatterbox(
method: "POST",
headers: { "content-type": "application/json", accept: "audio/wav" },
body: JSON.stringify({ model: model?.trim() || DEFAULT_MODEL, input: text, voice: voiceId, response_format: "wav" }),
- signal: AbortSignal.timeout(60_000),
+ signal: AbortSignal.any([AbortSignal.timeout(60_000), ...(signal ? [signal] : [])]),
},
"speaking",
baseUrl,
diff --git a/server/tts/elevenlabs.ts b/server/tts/elevenlabs.ts
index dc3bc2db68..a440c45793 100644
--- a/server/tts/elevenlabs.ts
+++ b/server/tts/elevenlabs.ts
@@ -156,7 +156,7 @@ export interface Synthesis {
audio: Promise<Audio>;
}
-export function synthesize(text: string, voiceId: string, key: string, api: string, included = false): Synthesis {
+export function synthesize(text: string, voiceId: string, key: string, api: string, included = false, signal?: AbortSignal): Synthesis {
const firstAudio = withResolvers<Audio>();
const audio = withResolvers<Audio>();
// Callers may consume only `audio`: a failure before the first chunk must not become an unhandled rejection.
@@ -168,7 +168,7 @@ export function synthesize(text: string, voiceId: string, key: string, api: stri
headers: { "xi-api-key": key, "content-type": "application/json", accept: "audio/mpeg" },
body: JSON.stringify({ text, model_id: speechModel(text, included) }),
redirect: "error",
- signal: AbortSignal.timeout(60_000),
+ signal: AbortSignal.any([AbortSignal.timeout(60_000), ...(signal ? [signal] : [])]),
});
if (!res.ok) throw new Error(message(res.status, "speaking", await safeJson(res)));
if (!res.body) throw new Error("speaking failed: no audio came back");
diff --git a/server/tts/fish.ts b/server/tts/fish.ts
index 1192d9f752..b167aae961 100644
--- a/server/tts/fish.ts
+++ b/server/tts/fish.ts
@@ -180,6 +180,7 @@ export async function synthesize(
voiceId: string,
key: string,
model: FishTtsModel = DEFAULT_FISH_MODEL,
+ signal?: AbortSignal,
): Promise<Audio> {
let res: Response;
try {
@@ -200,7 +201,7 @@ export async function synthesize(
latency: "normal",
}),
redirect: "error",
- signal: AbortSignal.timeout(60_000),
+ signal: AbortSignal.any([AbortSignal.timeout(60_000), ...(signal ? [signal] : [])]),
});
} catch {
throw new Error("Couldn't reach Fish Audio to generate speech — check your connection.");
diff --git a/server/tts/gemini.ts b/server/tts/gemini.ts
index bf40d00308..b6876133f9 100644
--- a/server/tts/gemini.ts
+++ b/server/tts/gemini.ts
@@ -61,7 +61,7 @@ export async function verifyKey(key: string): Promise<VerifyResult> {
* @param model Gemini model identifier.
* @returns Synthesized Audio object containing bytes and MIME type.
*/
-export async function synthesize(text: string, voiceId: string, key: string, model = DEFAULT_GEMINI_MODEL): Promise<Audio> {
+export async function synthesize(text: string, voiceId: string, key: string, model = DEFAULT_GEMINI_MODEL, signal?: AbortSignal): Promise<Audio> {
if (!isSupportedVoice(voiceId)) throw new Error("Pick a Gemini voice from the voice list.");
let response: Response;
try {
@@ -72,7 +72,7 @@ export async function synthesize(text: string, voiceId: string, key: string, mod
input: [{ type: "user_input", content: [{ type: "text", text }] }],
response_format: { type: "audio" }, generation_config: { speech_config: [{ voice: voiceId }] },
}),
- signal: AbortSignal.timeout(60_000),
+ signal: AbortSignal.any([AbortSignal.timeout(60_000), ...(signal ? [signal] : [])]),
});
} catch {
throw new Error("Could not reach Gemini speech generation. Check your connection and try again.");
diff --git a/server/tts/grok.ts b/server/tts/grok.ts
index 2b0402113d..8e9618898c 100644
--- a/server/tts/grok.ts
+++ b/server/tts/grok.ts
@@ -48,12 +48,12 @@ export async function listVoices(key: string): Promise<Voice[]> {
}));
}
-export async function synthesize(text: string, voiceId: string, key: string): Promise<Audio> {
+export async function synthesize(text: string, voiceId: string, key: string, signal?: AbortSignal): Promise<Audio> {
const response = await request("/tts", {
method: "POST",
headers: { authorization: `Bearer ${key}`, "content-type": "application/json", accept: "audio/mpeg" },
body: JSON.stringify({ text, voice_id: voiceId, language: "auto", output_format: { codec: "mp3" } }),
- signal: AbortSignal.timeout(60_000),
+ signal: AbortSignal.any([AbortSignal.timeout(60_000), ...(signal ? [signal] : [])]),
});
const mime = (response.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
if (mime !== "audio/mpeg" && mime !== "audio/mp3") {
diff --git a/server/tts/index.ts b/server/tts/index.ts
index 9e90c82ed5..34ead441f2 100644
--- a/server/tts/index.ts
+++ b/server/tts/index.ts
@@ -173,6 +173,7 @@ export async function addSharedVoice(cfg: AppConfig, publicOwnerId: string, voic
* @param text The plain text to synthesize into spoken audio.
* @param voiceId Optional override voice ID.
* @param run Optional runner for system voices.
+ * @param signal Cancels network speech requests when the listener stops playback.
* @returns Synthesized audio buffer or stream promise.
*/
export function speak(cfg: AppConfig, text: string, voiceId?: string, run?: systemVoices.Runner, signal?: AbortSignal) {
@@ -182,7 +183,7 @@ export function speak(cfg: AppConfig, text: string, voiceId?: string, run?: syst
if (!key) throw new NoVoiceConfigured("key", "Add a Gemini API key in Settings to use Gemini voice.");
const voice = voiceId || cfg.tts?.voice;
if (!voice) throw new NoVoiceConfigured("voice");
- return gemini.synthesize(text, voice, key, cfg.tts?.model);
+ return gemini.synthesize(text, voice, key, cfg.tts?.model, signal);
}
if (provider === "openai") return openai.synthesize(text, voiceId || cfg.tts?.voice || "", cfg.openai?.key || "", signal);
if (provider === "xai") {
@@ -190,7 +191,7 @@ export function speak(cfg: AppConfig, text: string, voiceId?: string, run?: syst
if (!key) throw new NoVoiceConfigured("key", "Add an xAI key in Settings to use Grok voice.");
const voice = voiceId || cfg.tts?.voice;
if (!voice) throw new NoVoiceConfigured("voice");
- return grok.synthesize(text, voice, key);
+ return grok.synthesize(text, voice, key, signal);
}
if (provider === "system") {
const voice = voiceId || cfg.tts?.voice;
@@ -208,7 +209,7 @@ export function speak(cfg: AppConfig, text: string, voiceId?: string, run?: syst
}
const voice = voiceId || cfg.tts?.voice;
if (!voice) throw new NoVoiceConfigured("voice");
- return chatterbox.synthesizeChatterbox(text, voice, baseUrl, cfg.tts?.model);
+ return chatterbox.synthesizeChatterbox(text, voice, baseUrl, cfg.tts?.model, signal);
}
if (provider === "fish") {
const key = cfg.tts?.fishKey;
@@ -220,13 +221,13 @@ export function speak(cfg: AppConfig, text: string, voiceId?: string, run?: syst
}
const voice = voiceId || cfg.tts?.voice;
if (!voice) throw new NoVoiceConfigured("voice");
- return fish.synthesize(text, voice, key, cfg.tts?.fishModel);
+ return fish.synthesize(text, voice, key, cfg.tts?.fishModel, signal);
}
const credential = elevenLabs(cfg);
if (!credential) throw new NoVoiceConfigured("key");
const voice = voiceId || cfg.tts?.voice;
if (!voice) throw new NoVoiceConfigured("voice");
- return elevenlabs.synthesize(text, voice, credential.token, credential.api, credential.included).audio;
+ return elevenlabs.synthesize(text, voice, credential.token, credential.api, credential.included, signal).audio;
}
export type { Voice } from "./elevenlabs.ts";