Skip to content

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

Live calls (ElevenLabs): end the agent's turn at agent_response_complete

Bugfixer 274af1f006d9e
diff --git a/server/live-elevenlabs.test.ts b/server/live-elevenlabs.test.ts
index 4ddb701fbc..e1d846e7de 100644
--- a/server/live-elevenlabs.test.ts
+++ b/server/live-elevenlabs.test.ts
@@ -55,7 +55,8 @@ describe("an ElevenLabs agent for Live calls", () => {
conversation_config: { agent: { prompt: { tool_ids: ["tool_1"] } }, asr: { user_input_audio_format: "pcm_16000" }, tts: { agent_output_audio_format: "pcm_16000" } },
platform_settings: { overrides: { conversation_config_override: { agent: { prompt: { prompt: true } } } }, auth: { enable_auth: true } },
});
- expect(agent.conversation_config.conversation.client_events).toEqual(expect.arrayContaining(["client_tool_call", "audio", "interruption", "user_transcript", "agent_response", "ping"]));
+ expect(agent.conversation_config.conversation.client_events).toEqual(expect.arrayContaining(["client_tool_call", "audio", "interruption", "user_transcript", "agent_response", "agent_response_complete", "ping"]));
+ expect(agent.conversation_config.conversation.max_duration_seconds).toBe(3600);
});
it("fails with words for the person, never ElevenLabs' body, when ElevenLabs refuses or answers oddly", async () => {
diff --git a/server/live-elevenlabs.ts b/server/live-elevenlabs.ts
index 0170ba9a1a..63e533f6cd 100644
--- a/server/live-elevenlabs.ts
+++ b/server/live-elevenlabs.ts
@@ -17,7 +17,11 @@ const AUDIO_FORMAT = "pcm_16000";
const UNEXPECTED = "ElevenLabs returned an unexpected answer. Try the call again.";
/** What ElevenLabs sends the client. A list replaces ElevenLabs' defaults, so it names every event the client reads, with
* `client_tool_call` so `delegate` reaches the client. */
-const CLIENT_EVENTS = ["conversation_initiation_metadata", "ping", "audio", "interruption", "user_transcript", "agent_response", "agent_response_correction", "client_tool_call"];
+const CLIENT_EVENTS = [
+ "conversation_initiation_metadata", "ping", "audio", "interruption", "user_transcript", "agent_response", "agent_response_correction", "agent_response_complete", "client_tool_call",
+];
+/** ElevenLabs ends a conversation after 10 minutes unless the agent allows longer; a Live call may last an hour, as with Gemini. */
+const CALL_AT_MOST_SECONDS = 60 * 60;
/** `model` is the agent id, "" while no usable one is saved. The API root is the one ElevenLabs voices use (OMB_ELEVENLABS_API). */
export function elevenLabsLiveEndpoint(agentId: string | null | undefined, env: NodeJS.ProcessEnv = process.env): LiveEndpoint {
@@ -75,7 +79,7 @@ export async function setUpElevenLabsAgent(key: string, endpoint: LiveEndpoint,
agent: { first_message: "", language: "en", prompt: { prompt: `You are ${product} on a live voice call.`, tool_ids: [toolId] } },
asr: { user_input_audio_format: AUDIO_FORMAT },
tts: { agent_output_audio_format: AUDIO_FORMAT },
- conversation: { client_events: CLIENT_EVENTS },
+ conversation: { client_events: CLIENT_EVENTS, max_duration_seconds: CALL_AT_MOST_SECONDS },
},
// Without the override ElevenLabs refuses the prompt each conversation sends. With auth on, a conversation needs a
// signed URL, which only the harness can get with the key: knowing the agent id is not enough to spend the person's credits.
diff --git a/src/components/keys/KeyRow.analytics.test.ts b/src/components/keys/KeyRow.analytics.test.ts
index 1968520d57..fd2dbc76c2 100644
--- a/src/components/keys/KeyRow.analytics.test.ts
+++ b/src/components/keys/KeyRow.analytics.test.ts
@@ -19,6 +19,7 @@ vi.mock("react", async (original) => ({
}];
},
useEffect: () => {},
+ useLayoutEffect: () => {},
useId: () => "row",
useRef: (current: unknown) => {
const index = fixture.refIndex++;
diff --git a/src/components/keys/KeyRow.tsx b/src/components/keys/KeyRow.tsx
index 0c32f429a5..cff3f97a56 100644
--- a/src/components/keys/KeyRow.tsx
+++ b/src/components/keys/KeyRow.tsx
@@ -1,4 +1,4 @@
-import { useContext, useEffect, useId, useRef, useState, type ReactNode } from "react";
+import { useContext, useEffect, useId, useLayoutEffect, useRef, useState, type ReactNode } from "react";
import { Check, CircleAlert, ExternalLink, Eye, EyeOff, Loader2, TriangleAlert } from "lucide-react";
import { useStore } from "@/state/store";
import { installCommandFor } from "@/state/engine-install";
@@ -141,8 +141,9 @@ export function KeyRow({
setVerdict(null);
setWorks(false);
}
- // A check or save still running for the previous service must not show its result on this one.
- useEffect(() => () => { generation.current += 1; }, [entry.name]);
+ // A check or save still running for the previous service must not show its result on this one. A layout effect's
+ // cleanup runs while the new service commits, before any later answer can land, where a passive effect's may run after.
+ useLayoutEffect(() => () => { generation.current += 1; }, [entry.name]);
const target = entry.target;
if (!target) throw new Error(`${id} is not saved by a key row`);
const pointer = row.id !== entry.id;
diff --git a/src/components/keys/key-catalog.test.ts b/src/components/keys/key-catalog.test.ts
index 3606505609..8ef55f7463 100644
--- a/src/components/keys/key-catalog.test.ts
+++ b/src/components/keys/key-catalog.test.ts
@@ -4,7 +4,7 @@ import { setLocale, t } from "@/lib/i18n";
import type { ConfigStatus } from "@/state/store";
import { WORKSPACE_CREDENTIAL_ENV } from "../../../server/credential-env.ts";
import { CREDENTIAL_TARGETS, credentialConfigPatch, desktopCredentialSlot, isConfigCredentialTarget } from "../../../shared/credential-request";
-import { KEY_CATALOG, KEY_SECTIONS, keyEntry, keyForInstance, keyHidden, keyMatches, looksLikeOtherKey, savedState, type KeyId } from "./key-catalog";
+import { KEY_CATALOG, KEY_SECTIONS, keyEntry, keyForInstance, keyHidden, keyMatches, looksLikeOtherKey, savedState, shownKeyEntry, type KeyId } from "./key-catalog";
const NOT_A_PERSONS_KEY: Record<string, string> = {
OMB_ANTHROPIC_API_URL: "the address the Anthropic key goes to, set by a hosted install",
@@ -96,6 +96,12 @@ describe("every credential has one home on the keys page", () => {
expect(t(live.labelKey)).toBe("OpenAI key");
expect(t(keyEntry("openai").labelKey)).toBe("OpenAI API key");
});
+
+ it("never shows Cloud's included voices on the ElevenLabs Live key row: Live calls need the person's own key", () => {
+ const config = { live: { provider: "elevenlabs" }, tts: { provider: "elevenlabs", configured: true, included: true } } as ConfigStatus;
+ expect(savedState(shownKeyEntry("liveKey", config), config)).toEqual({ configured: false });
+ expect(savedState(keyEntry("elevenlabs"), config)).toEqual({ configured: false, included: true });
+ });
});
describe("searching the keys", () => {
diff --git a/src/components/keys/key-catalog.ts b/src/components/keys/key-catalog.ts
index 8a8285f89d..db13a50891 100644
--- a/src/components/keys/key-catalog.ts
+++ b/src/components/keys/key-catalog.ts
@@ -234,7 +234,13 @@ export function shownKeyEntry(id: KeyId, config: ConfigStatus | null | undefined
return { ...entry, name: "Gemini", labelKey: "keys.label.geminiTts", purposeKey: "keys.purpose.liveKeyGemini", target: keyEntry("geminiTts").target };
}
if (provider === "elevenlabs") {
- return { ...entry, name: "ElevenLabs", labelKey: "keys.label.elevenlabs", purposeKey: "keys.purpose.liveKeyElevenLabs", target: keyEntry("elevenlabs").target };
+ // Cloud's included voices cannot place Live calls, so this row asks for the person's own key even then.
+ const voices = keyEntry("elevenlabs").target!;
+ const saved = (config: ConfigStatus): SavedState => {
+ const { included: _included, ...own } = voices.saved(config);
+ return own;
+ };
+ return { ...entry, name: "ElevenLabs", labelKey: "keys.label.elevenlabs", purposeKey: "keys.purpose.liveKeyElevenLabs", target: { ...voices, saved } };
}
return { ...entry, name: "Azure OpenAI", labelKey: "call.live.azureKeyField", purposeKey: "keys.purpose.liveKeyAzure", target: { ...target, placeholder: "…", href: "https://portal.azure.com" } };
}
diff --git a/src/lib/live-call-elevenlabs.test.ts b/src/lib/live-call-elevenlabs.test.ts
index 7ffd072e11..830d6239f4 100644
--- a/src/lib/live-call-elevenlabs.test.ts
+++ b/src/lib/live-call-elevenlabs.test.ts
@@ -34,6 +34,7 @@ class FakeAudio implements GeminiAudio {
played: number[] = [];
playing = 0;
flushed = 0;
+ micDropped = 0;
closed = false;
mic: ((pcm: ArrayBuffer) => void) | null = null;
/** Set while the microphone permission prompt is still open; calling it answers the prompt. */
@@ -47,6 +48,7 @@ class FakeAudio implements GeminiAudio {
play(pcm: ArrayBuffer) { this.played.push(pcm.byteLength); this.playing += 1; }
flush() { this.flushed += 1; this.playing = 0; }
idle() { return this.playing === 0; }
+ dropMic() { this.micDropped += 1; }
finish() { this.playing = 0; this.onIdle?.(); }
close() { this.closed = true; }
}
@@ -177,6 +179,39 @@ describe("an ElevenLabs Live session", () => {
expect(t.socket().sent.at(-1)).toEqual({ type: "user_message", text: "[OpenMausBot] You have two new emails." });
});
+ it("ends the agent's turn at agent_response_complete once ElevenLabs sends it, not at a long gap in its audio", async () => {
+ const t = harness();
+ const session = await t.connect();
+ vi.useFakeTimers();
+ try {
+ const audio = (event_id: number) => t.socket().receive({ type: "audio", audio_event: { audio_base_64: AUDIO, event_id } });
+ audio(1);
+ t.socket().receive({ type: "agent_response_complete" });
+ t.audio().finish();
+ expect(t.callbacks.onModeChange).toHaveBeenLastCalledWith("listening");
+ audio(2);
+ session.sendUserMessage("[OpenMausBot] You have two new emails.");
+ t.audio().finish();
+ vi.advanceTimersByTime(2_000);
+ expect(t.callbacks.onModeChange).toHaveBeenLastCalledWith("speaking");
+ expect(t.socket().sent.map((m) => m.type)).not.toContain("user_message");
+ audio(3);
+ t.audio().finish();
+ t.socket().receive({ type: "agent_response_complete" });
+ expect(t.callbacks.onModeChange).toHaveBeenLastCalledWith("listening");
+ expect(t.socket().sent.at(-1)).toEqual({ type: "user_message", text: "[OpenMausBot] You have two new emails." });
+ // A turn whose end never comes still ends once its audio has long stopped.
+ audio(4);
+ t.audio().finish();
+ vi.advanceTimersByTime(2_999);
+ expect(t.callbacks.onModeChange).toHaveBeenLastCalledWith("speaking");
+ vi.advanceTimersByTime(1);
+ expect(t.callbacks.onModeChange).toHaveBeenLastCalledWith("listening");
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it("answers the delegate tool call with the harness's words", async () => {
const t = harness();
await t.connect();
@@ -216,7 +251,9 @@ describe("an ElevenLabs Live session", () => {
const sent = t.socket().sent.length;
t.audio().mic!(new Int16Array([1]).buffer);
expect(t.socket().sent).toHaveLength(sent);
+ expect(t.audio().micDropped).toBe(0);
await session.setMicMuted(false);
+ expect(t.audio().micDropped).toBe(1);
t.audio().mic!(new Int16Array([1]).buffer);
expect(t.socket().sent).toHaveLength(sent + 1);
});
diff --git a/src/lib/live-call-elevenlabs.ts b/src/lib/live-call-elevenlabs.ts
index a44365500f..46df9b1ead 100644
--- a/src/lib/live-call-elevenlabs.ts
+++ b/src/lib/live-call-elevenlabs.ts
@@ -8,8 +8,10 @@ import { decodeBase64, encodeBase64, type GeminiSocket } from "./live-call-gemin
/** The agent is set up to answer with 16 kHz PCM; the first message names the format. */
const DEFAULT_RATE = 16_000;
-/** ElevenLabs sends no end of the agent's turn, so a pause in its audio this long ends it, not a late chunk. */
+/** An agent set up before `agent_response_complete` was sent ends its turn with a pause in its audio this long. */
const IDLE_GRACE_MS = 300;
+/** Ends the agent's turn when its audio has stopped this long but no `agent_response_complete` came after it. */
+const TURN_END_WAIT_MS = 3_000;
export interface ElevenLabsSessionDeps {
openSocket(url: string): GeminiSocket;
@@ -61,6 +63,10 @@ class ElevenLabsLiveSession implements FishAgentSession {
private segment = 0;
private speaking = false;
private idleTimer: ReturnType<typeof setTimeout> | null = null;
+ /** Audio came after the last `agent_response_complete`. */
+ private answering = false;
+ /** ElevenLabs sends `agent_response_complete`, so a pause in the audio no longer ends the agent's turn. */
+ private turnEnds = false;
/** Audio of an interrupted answer still on its way is not played. */
private interruptedAt = -1;
@@ -131,6 +137,8 @@ class ElevenLabsLiveSession implements FishAgentSession {
}
async setMicMuted(muted: boolean): Promise<void> {
+ // What the microphone held while muted is not sent once it is on again.
+ if (!muted && this.muted) this.audio?.dropMic();
this.muted = muted;
}
@@ -178,6 +186,7 @@ class ElevenLabsLiveSession implements FishAgentSession {
const id = message.audio_event?.event_id;
if (!data || !this.audio || (id !== undefined && id <= this.interruptedAt)) return;
this.clearIdleTimer();
+ this.answering = true;
this.audio.play(decodeBase64(data));
if (!this.speaking) {
this.speaking = true;
@@ -197,8 +206,14 @@ class ElevenLabsLiveSession implements FishAgentSession {
if (text) this.options.callbacks.onAgentResponseDelta({ segmentId: `a${this.segment}`, text });
return;
}
+ case "agent_response_complete":
+ this.turnEnds = true;
+ this.answering = false;
+ if (this.audio?.idle() !== false) this.playbackPaused();
+ return;
case "interruption":
this.interruptedAt = message.interruption_event?.event_id ?? this.interruptedAt;
+ this.answering = false;
this.clearIdleTimer();
this.audio?.flush();
return this.playbackIdle();
@@ -209,10 +224,11 @@ class ElevenLabsLiveSession implements FishAgentSession {
private playbackPaused(): void {
this.clearIdleTimer();
+ if (this.turnEnds && !this.answering) return this.playbackIdle();
this.idleTimer = setTimeout(() => {
this.idleTimer = null;
this.playbackIdle();
- }, IDLE_GRACE_MS);
+ }, this.turnEnds ? TURN_END_WAIT_MS : IDLE_GRACE_MS);
}
private clearIdleTimer(): void {