Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(voice): add realtime voice session support

Steven Enamakeleb2631053f88
diff --git a/Cargo.lock b/Cargo.lock
index f0b3887c8d..5620439dd9 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4048,6 +4048,7 @@ dependencies = [
"tinyagents-definition",
"tinyagents-graph",
"tinyagents-harness",
+ "tinyagents-live",
"tinyagents-orchestration",
"tinyagents-registry",
"tinyagents-runtime",
@@ -6482,6 +6483,17 @@ dependencies = [
"zip",
]
+[[package]]
+name = "tinyagents-live"
+version = "2.1.3"
+dependencies = [
+ "serde_json",
+ "tinyagents-harness",
+ "tinyliveagents",
+ "tokio",
+ "tracing",
+]
+
[[package]]
name = "tinyagents-orchestration"
version = "2.1.3"
@@ -7042,6 +7054,24 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "tinyliveagents"
+version = "0.1.0"
+dependencies = [
+ "async-trait",
+ "base64 0.22.1",
+ "bytes",
+ "futures-util",
+ "reqwest",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.20",
+ "tokio",
+ "tokio-tungstenite 0.29.0",
+ "tracing",
+ "url",
+]
+
[[package]]
name = "tinymcp"
version = "0.3.7"
diff --git a/app/src/features/human/HumanPage.tsx b/app/src/features/human/HumanPage.tsx
index 4826008227..c636c1687a 100644
--- a/app/src/features/human/HumanPage.tsx
+++ b/app/src/features/human/HumanPage.tsx
@@ -21,7 +21,7 @@ import {
RiveMascot,
} from './Mascot';
import { useMascotManifest } from './Mascot/manifest/useMascotManifest';
-import LiveVoiceControls from './LiveVoiceControls';
+import LiveVoiceControls, { type LiveVoicePhase } from './LiveVoiceControls';
import { useHumanMascot } from './useHumanMascot';
import { IDLE_REALTIME_VOICE_AUDIO, type RealtimeVoiceAudio } from './voice/amplitudeLipsync';
import { useAmplitudeLipsync } from './voice/useAmplitudeLipsync';
@@ -37,7 +37,13 @@ const HumanPage = () => {
// same setting — and would silently drop whatever the user had chosen before.
const speakReplies = useAppSelector(selectSpeakReplies);
- const { face, visemeCode } = useHumanMascot({ speakReplies });
+ // While a live voice session runs it owns the audio: the transcript turns it
+ // persists into the thread must not also be read out by speak-replies TTS.
+ const [livePhase, setLivePhase] = useState<LiveVoicePhase>('off');
+ const { face, visemeCode } = useHumanMascot({
+ speakReplies: speakReplies && livePhase === 'off',
+ listening: livePhase === 'listening',
+ });
// Lip-sync for the live voice session. The session lives inside
// LiveVoiceControls, so it publishes its output-loudness accessor into this
@@ -150,6 +156,7 @@ const HumanPage = () => {
threadId={selectedThreadId}
audioRef={realtimeAudioRef}
onSpeakingChange={setRealtimeSpeaking}
+ onPhaseChange={setLivePhase}
/>
</div>
)}
diff --git a/app/src/features/human/RealtimeVoiceControls.test.tsx b/app/src/features/human/RealtimeVoiceControls.test.tsx
deleted file mode 100644
index 2e399e7f00..0000000000
--- a/app/src/features/human/RealtimeVoiceControls.test.tsx
+++ /dev/null
@@ -1,233 +0,0 @@
-/**
- * Unit tests for RealtimeVoiceControls (#5399) — the flag-gated realtime
- * voice-chat controls on the Human tab. The session hook is mocked so these
- * tests pin the presentational contract only: label per state, the
- * listening/speaking status line, the error alert, and the start/stop wiring.
- */
-import { configureStore } from '@reduxjs/toolkit';
-import { fireEvent, render, screen } from '@testing-library/react';
-import type { ReactNode, RefObject } from 'react';
-import { Provider } from 'react-redux';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import mascotReducer from '../../store/mascotSlice';
-import RealtimeVoiceControls from './RealtimeVoiceControls';
-import type { RealtimeVoiceAudio } from './voice/amplitudeLipsync';
-import type { RealtimeVoiceSession } from './voice/useRealtimeVoiceSession';
-
-// `@elevenlabs/react`'s ConversationProvider is only a context shell here — pass
-// children through so we exercise the real component tree without the SDK.
-vi.mock('@elevenlabs/react', () => ({
- ConversationProvider: ({ children }: { children: ReactNode }) => <>{children}</>,
-}));
-
-const start = vi.fn();
-const stop = vi.fn();
-let session: RealtimeVoiceSession;
-
-vi.mock('./voice/useRealtimeVoiceSession', () => ({ useRealtimeVoiceSession: () => session }));
-
-function makeSession(overrides: Partial<RealtimeVoiceSession> = {}): RealtimeVoiceSession {
- return {
- state: 'idle',
- isSpeaking: false,
- mode: 'listening',
- getOutputVolume: () => 0,
- error: null,
- start,
- stop,
- ...overrides,
- };
-}
-
-// `useT()` resolves against the bundled `en` map when no provider is mounted,
-// so the accessible names below are the real English labels (en.ts).
-const LABEL = {
- start: 'Start voice chat',
- stop: 'End voice chat',
- connecting: 'Connecting…',
- listening: 'Listening',
- speaking: 'Speaking',
-} as const;
-
-function renderControls(
- onSpeakingChange?: (speaking: boolean) => void,
- audioRef?: RefObject<RealtimeVoiceAudio>
-) {
- const store = configureStore({ reducer: { mascot: mascotReducer } });
- return render(
- <Provider store={store}>
- <RealtimeVoiceControls onSpeakingChange={onSpeakingChange} audioRef={audioRef} />
- </Provider>
- );
-}
-
-describe('RealtimeVoiceControls', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- session = makeSession();
- });
-
- it('shows the start label and no status while idle', () => {
- renderControls();
- const button = screen.getByRole('button', { name: LABEL.start });
- expect(button).toBeEnabled();
- expect(screen.queryByText(LABEL.listening)).not.toBeInTheDocument();
- expect(screen.queryByText(LABEL.speaking)).not.toBeInTheDocument();
- expect(screen.queryByRole('alert')).not.toBeInTheDocument();
- });
-
- it('disables the button and shows the connecting label while connecting', () => {
- session = makeSession({ state: 'connecting' });
- renderControls();
- expect(screen.getByRole('button', { name: LABEL.connecting })).toBeDisabled();
- });
-
- it('shows the stop label and the listening status when active and not speaking', () => {
- session = makeSession({ state: 'active', isSpeaking: false });
- renderControls();
- expect(screen.getByRole('button', { name: LABEL.stop })).toBeEnabled();
- expect(screen.getByText(LABEL.listening)).toBeInTheDocument();
- });
-
- it('shows the speaking status when the agent is speaking', () => {
- session = makeSession({ state: 'active', isSpeaking: true });
- renderControls();
- expect(screen.getByText(LABEL.speaking)).toBeInTheDocument();
- expect(screen.queryByText(LABEL.listening)).not.toBeInTheDocument();
- });
-
- it('surfaces the session error in an alert', () => {
- session = makeSession({ state: 'error', error: 'microphone blocked' });
- renderControls();
- expect(screen.getByRole('alert')).toHaveTextContent('microphone blocked');
- });
-
- it('starts a session when clicked while idle', () => {
- renderControls();
- fireEvent.click(screen.getByRole('button', { name: LABEL.start }));
- expect(start).toHaveBeenCalledTimes(1);
- expect(stop).not.toHaveBeenCalled();
- });
-
- it('stops the session when clicked while active', () => {
- session = makeSession({ state: 'active' });
- renderControls();
- fireEvent.click(screen.getByRole('button', { name: LABEL.stop }));
- expect(stop).toHaveBeenCalledTimes(1);
- expect(start).not.toHaveBeenCalled();
- });
-
- // The speaking edge gates the mascot's lip-sync loop on the page
- // (useAmplitudeLipsync's `enabled`), so it must reflect `active && isSpeaking`,
- // not either half alone.
- it('reports not-speaking to onSpeakingChange while idle', () => {
- const onSpeakingChange = vi.fn();
- renderControls(onSpeakingChange);
- expect(onSpeakingChange).toHaveBeenLastCalledWith(false);
- });
-
- it('reports speaking only when the session is active and the agent speaks', () => {
- const onSpeakingChange = vi.fn();
- session = makeSession({ state: 'active', isSpeaking: true });
- renderControls(onSpeakingChange);
- expect(onSpeakingChange).toHaveBeenLastCalledWith(true);
- });
-
- it('reports not-speaking when active but the agent is silent', () => {
- const onSpeakingChange = vi.fn();
- session = makeSession({ state: 'active', isSpeaking: false });
- renderControls(onSpeakingChange);
- expect(onSpeakingChange).toHaveBeenLastCalledWith(false);
- });
-
- // The lip-sync loop reads the SDK accessor and speaking flag straight out of
- // this ref (see useAmplitudeLipsync); a regression that stopped publishing
- // them would freeze the mascot's mouth mid-turn without failing any of the
- // presentational tests above, so pin the wiring directly.
- it('publishes the loudness accessor and speaking flag into audioRef', () => {
- const getOutputVolume = () => 0.5;
- session = makeSession({ state: 'active', isSpeaking: true, getOutputVolume });
- const audioRef: RefObject<RealtimeVoiceAudio> = {
- current: { getOutputVolume: null, speaking: false },
- };
- renderControls(undefined, audioRef);
- expect(audioRef.current?.getOutputVolume).toBe(getOutputVolume);
- expect(audioRef.current?.speaking).toBe(true);
- });
-
- it('clears the audioRef on unmount cleanup', () => {
- session = makeSession({ state: 'active', isSpeaking: true, getOutputVolume: () => 0.5 });
- const audioRef: RefObject<RealtimeVoiceAudio> = {
- current: { getOutputVolume: null, speaking: false },
- };
- const { unmount } = renderControls(undefined, audioRef);
- expect(audioRef.current?.speaking).toBe(true);
-
- unmount();
- expect(audioRef.current?.getOutputVolume).toBeNull();
- expect(audioRef.current?.speaking).toBe(false);
- });
-
- // Ending a session doesn't unmount the control — the card stays on screen and
- // the session hook just returns to 'idle'. The live effect (not the unmount
- // cleanup) has to clear the ref on that transition, or the mascot would keep
- // reading a stale accessor after the agent has gone.
- it('clears the audioRef when the session goes idle while still mounted', () => {
- const store = configureStore({ reducer: { mascot: mascotReducer } });
- const audioRef: RefObject<RealtimeVoiceAudio> = {
- current: { getOutputVolume: null, speaking: false },
- };
- session = makeSession({ state: 'active', isSpeaking: true, getOutputVolume: () => 0.5 });
- const { rerender } = render(
- <Provider store={store}>
- <RealtimeVoiceControls audioRef={audioRef} />
- </Provider>
- );
- expect(audioRef.current?.speaking).toBe(true);
-
- session = makeSession({ state: 'idle', isSpeaking: false });
- rerender(
- <Provider store={store}>
- <RealtimeVoiceControls audioRef={audioRef} />
- </Provider>
- );
- expect(audioRef.current?.getOutputVolume).toBeNull();
- expect(audioRef.current?.speaking).toBe(false);
- });
-
- // The agent falling silent mid-session flips only `isSpeaking` — the session
- // stays 'active'. The publication effect must re-run on that edge alone, or a
- // stale `speaking: true` would sit in the ref and freeze the mascot's mouth
- // open. Keeping `active` true here (unlike the goes-idle case above, where the
- // active→idle change would re-run the effect regardless) pins `speaking` in
- // the effect's dependency array specifically.
- it('publishes the speaking edge while the session stays active', () => {
- const store = configureStore({ reducer: { mascot: mascotReducer } });
- const onSpeakingChange = vi.fn();
- const getOutputVolume = () => 0.5;
- const audioRef: RefObject<RealtimeVoiceAudio> = {
- current: { getOutputVolume: null, speaking: false },
- };
- session = makeSession({ state: 'active', isSpeaking: true, getOutputVolume });
- const { rerender } = render(
- <Provider store={store}>
- <RealtimeVoiceControls audioRef={audioRef} onSpeakingChange={onSpeakingChange} />
- </Provider>
- );
- expect(onSpeakingChange).toHaveBeenLastCalledWith(true);
- expect(audioRef.current?.speaking).toBe(true);
-
- session = makeSession({ state: 'active', isSpeaking: false, getOutputVolume });
- rerender(
- <Provider store={store}>
- <RealtimeVoiceControls audioRef={audioRef} onSpeakingChange={onSpeakingChange} />
- </Provider>
- );
- expect(onSpeakingChange).toHaveBeenLastCalledWith(false);
- expect(audioRef.current?.speaking).toBe(false);
- // The session never closed, so the accessor stays published — only the
- // speaking flag dropped.
- expect(audioRef.current?.getOutputVolume).toBe(getOutputVolume);
- });
-});
diff --git a/app/src/features/human/RealtimeVoiceControls.tsx b/app/src/features/human/RealtimeVoiceControls.tsx
deleted file mode 100644
index 4d8e1cf928..0000000000
--- a/app/src/features/human/RealtimeVoiceControls.tsx
+++ /dev/null
@@ -1,151 +0,0 @@
-import { ConversationProvider } from '@elevenlabs/react';
-import { type RefObject, useEffect } from 'react';
-import { LuMic, LuSquare } from 'react-icons/lu';
-
-import Button from '../../components/ui/Button';
-import { useT } from '../../lib/i18n/I18nContext';
-import { useAppSelector } from '../../store/hooks';
-import { selectEffectiveMascotVoiceId } from '../../store/mascotSlice';
-import type { RealtimeVoiceAudio } from './voice/amplitudeLipsync';
-import { useRealtimeVoiceSession } from './voice/useRealtimeVoiceSession';
-
-/**
- * Realtime voice-chat controls for the Human tab (#5399). Rendered only when the
- * realtime voice mode is enabled and selected; the classic path is untouched.
- * Wraps its own `ConversationProvider` (required by `@elevenlabs/react`) so it
- * stays self-contained and adds no context to the rest of the app.
- */
-function RealtimeVoiceControlsInner({
- audioRef,
- onSpeakingChange,
- appearance = 'button',
-}: {
- audioRef?: RefObject<RealtimeVoiceAudio>;
- onSpeakingChange?: (speaking: boolean) => void;
- appearance?: RealtimeVoiceAppearance;
-}) {
- const { t } = useT();
- const voiceId = useAppSelector(selectEffectiveMascotVoiceId);
- const session = useRealtimeVoiceSession({ voiceId });
-
- const active = session.state === 'active';
- const connecting = session.state === 'connecting';
-
- // Publish the output-loudness accessor for the mascot's lip-sync. Written into
- // a ref rather than lifted into state because the mascot samples it once per
- // animation frame; see `useAmplitudeLipsync`. The session lives under this
- // component's own ConversationProvider, so this is the only place that can
- // reach it.
- const { getOutputVolume, isSpeaking } = session;
- const speaking = active && isSpeaking;
- useEffect(() => {
- if (audioRef?.current) {
- audioRef.current.getOutputVolume = active ? getOutputVolume : null;
- audioRef.current.speaking = speaking;
- }
- // Surface the speaking edge so the page can gate the mascot's lip-sync rAF
- // loop (`useAmplitudeLipsync`'s `enabled`) — an idle or classic Human tab
- // then schedules no frames. Unlike the 60fps amplitude above, this flips a
- // couple of times per turn, so it is cheap to lift into React state.
- onSpeakingChange?.(speaking);
- }, [audioRef, active, speaking, getOutputVolume, onSpeakingChange]);
-
- // A session that ends mid-speech would otherwise leave `speaking` true and the
- // mouth frozen open — reset both the ref the mascot samples and the speaking
- // edge the page gates its loop on.
- useEffect(
- () => () => {
- if (audioRef?.current) {
- audioRef.current.getOutputVolume = null;
- audioRef.current.speaking = false;
- }
- onSpeakingChange?.(false);
- },
- [audioRef, onSpeakingChange]
- );
-
- const label = connecting
- ? t('voice.mode.connecting')
- : active
- ? t('voice.mode.stop')
- : t('voice.mode.start');
-
- const status = active
- ? session.isSpeaking
- ? t('voice.mode.speaking')
- : t('voice.mode.listening')
- : null;
-
- const toggle = () => (active ? session.stop() : void session.start());
-
- return (
- <div className="flex flex-col items-center gap-2" data-testid="realtime-voice-controls">
- {appearance === 'icon' ? (
- // The Human stage's single affordance: one circular mic that starts the
- // session and becomes a stop square while it runs. Same handler and
- // same `label` as the text button, so the accessible name still says
- // which of start/stop/connecting this press does.
- <Button
- iconOnly
- variant={active ? 'secondary' : 'primary'}
- analyticsId="human-realtime-voice-toggle"
- data-testid="human-voice-toggle"
- disabled={connecting}
- aria-pressed={active}
- aria-label={label}
- title={label}
- className="size-14 rounded-full shadow-float"
- onClick={toggle}>
- {active ? <LuSquare className="size-5 fill-current" /> : <LuMic className="size-6" />}
- </Button>
- ) : (
- <Button
- analyticsId="human-realtime-voice-toggle"
- disabled={connecting}
- aria-label={label}
- onClick={toggle}>
- {label}
- </Button>
- )}
- {status && <span className="text-xs text-content-muted">{status}</span>}
- {session.error && (
- <span className="text-xs text-red-600 dark:text-red-300" role="alert">
- {session.error}
- </span>
- )}
- </div>
- );
-}
-
-/**
- * How the toggle presents itself.
- *
- * - `button` — the labelled text button, for surfaces that sit in a row of
- * other controls.
- * - `icon` — a circular mic (stop square while running), for the Human stage
- * where it is the only control on the page.
- */
-export type RealtimeVoiceAppearance = 'button' | 'icon';
-
-export default function RealtimeVoiceControls({
- audioRef,
- onSpeakingChange,
- appearance,
-}: {
- /** Optional sink for the mascot's lip-sync signal (see RealtimeVoiceAudio). */
- audioRef?: RefObject<RealtimeVoiceAudio>;
- /** Notified with the agent's speaking edge so the page can gate the loop. */
- onSpeakingChange?: (speaking: boolean) => void;
- /** Presentation of the start/stop toggle. Defaults to the labelled button. */
- appearance?: RealtimeVoiceAppearance;
-}) {
- return (
- <ConversationProvider>
- <RealtimeVoiceControlsInner
- audioRef={audioRef}
- onSpeakingChange={onSpeakingChange}
- appearance={appearance}
- />
- </ConversationProvider>
- );
-}
diff --git a/app/src/features/human/voice/useRealtimeVoiceSession.test.ts b/app/src/features/human/voice/useRealtimeVoiceSession.test.ts
deleted file mode 100644
index 2c12e775ca..0000000000
--- a/app/src/features/human/voice/useRealtimeVoiceSession.test.ts
+++ /dev/null
@@ -1,245 +0,0 @@
-import { act, renderHook } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import {
- clearAllProactiveThreadPins,
- PROACTIVE_VOICE_THREAD_ID,
- proactiveThreadPins,
-} from '../../../providers/proactiveThreadPins';
-import { fetchVoiceAgentSignedUrl } from '../../../services/api/voiceAgentApi';
-import { useRealtimeVoiceSession } from './useRealtimeVoiceSession';
-
-interface CapturedProps {
- onConnect: () => void;
- onDisconnect: () => void;
- onError: (message: string) => void;
-}
-let captured: CapturedProps | null = null;
-const startSession = vi.fn();
-const endSession = vi.fn();
-const sendUserMessage = vi.fn();
-
-vi.mock('@elevenlabs/react', () => ({
- useConversation: (props: CapturedProps) => {
- captured = props;
- return {
- startSession,
- endSession,
- sendUserMessage,
- isSpeaking: false,
- mode: 'listening' as const,
- };
- },
-}));
-
-// Capture the `voice_speak` subscription so a test can drive the speak-back path.
-const socketHandlers: Record<string, (payload: unknown) => void> = {};
-vi.mock('../../../services/socketService', () => ({
- socketService: {
- on: vi.fn((event: string, handler: (payload: unknown) => void) => {
- socketHandlers[event] = handler;
- }),
- off: vi.fn((event: string) => {
- delete socketHandlers[event];
- }),
- },
-}));
-
-vi.mock('../../../services/api/voiceAgentApi', () => ({ fetchVoiceAgentSignedUrl: vi.fn() }));
-vi.mock('../../../utils/config', () => ({ MASCOT_VOICE_ID: 'default-voice' }));
-
-const mockFetch = vi.mocked(fetchVoiceAgentSignedUrl);
-
-describe('useRealtimeVoiceSession', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- captured = null;
- Object.keys(socketHandlers).forEach(k => delete socketHandlers[k]);
- clearAllProactiveThreadPins();
- });
-
- it('fetches a signed URL and opens a WebSocket session with the voice override', async () => {
- mockFetch.mockResolvedValueOnce({ signedUrl: 'wss://x', agentId: 'a1', userToken: 'tok-1' });
- const { result } = renderHook(() => useRealtimeVoiceSession({ voiceId: 'v9' }));
- expect(result.current.state).toBe('idle');
-
- await act(async () => {
- await result.current.start();
- });
-
- expect(mockFetch).toHaveBeenCalledTimes(1);
- expect(startSession).toHaveBeenCalledWith({
- signedUrl: 'wss://x',
- connectionType: 'websocket',
- userId: 'tok-1',
- customLlmExtraBody: { user: 'tok-1' },
- overrides: { tts: { voiceId: 'v9' } },
- });
-
- act(() => captured?.onConnect());
- expect(result.current.state).toBe('active');
- });
-
- // `userId` alone never reaches the Custom-LLM request the backend relay
- // serves, so the relay cannot identify the caller and rejects the turn.
- // `customLlmExtraBody` is the field that carries it there.
- it('carries the relay token in customLlmExtraBody, not only in userId', async () => {
- mockFetch.mockResolvedValueOnce({ signedUrl: 'wss://x', agentId: 'a1', userToken: 'tok-9' });
- const { result } = renderHook(() => useRealtimeVoiceSession());
- await act(async () => {
- await result.current.start();
- });
- expect(startSession).toHaveBeenCalledWith(
- expect.objectContaining({ customLlmExtraBody: { user: 'tok-9' } })
- );
- });
-
- it('falls back to the default mascot voice id', async () => {
- mockFetch.mockResolvedValueOnce({ signedUrl: 'wss://x', agentId: 'a1', userToken: 'tok-1' });
- const { result } = renderHook(() => useRealtimeVoiceSession());
- await act(async () => {
- await result.current.start();
- });
- expect(startSession).toHaveBeenCalledWith(
- expect.objectContaining({ overrides: { tts: { voiceId: 'default-voice' } } })
- );
- });
-
- it('enters the error state when the signed-URL fetch fails (no session started)', async () => {
- mockFetch.mockRejectedValueOnce(new Error('no backend session token'));
- const { result } = renderHook(() => useRealtimeVoiceSession());
- await act(async () => {
- await result.current.start();
- });
- expect(result.current.state).toBe('error');
- expect(result.current.error).toContain('no backend session token');
- expect(startSession).not.toHaveBeenCalled();
- });
-
- it('stop() ends the session and returns to idle', async () => {
- mockFetch.mockResolvedValueOnce({ signedUrl: 'wss://x', agentId: 'a1', userToken: 'tok-1' });
- const { result } = renderHook(() => useRealtimeVoiceSession());
- await act(async () => {
- await result.current.start();
- });
- act(() => captured?.onConnect());
- act(() => result.current.stop());
- expect(endSession).toHaveBeenCalledTimes(1);
- expect(result.current.state).toBe('idle');
- });
-
- it('clears the voice thread pin when a new session begins', async () => {
- // A prior session pinned proactive:voice to some thread. Starting a new
- // session must drop that pin so this session's deferred answers resolve to a
- // fresh/current thread rather than appending to the previous (now off-screen)
- // one. See resolveVisibleThreadForProactive in ChatRuntimeProvider.
- proactiveThreadPins.set(PROACTIVE_VOICE_THREAD_ID, 'previous-session-thread');
- mockFetch.mockResolvedValueOnce({ signedUrl: 'wss://x', agentId: 'a1', userToken: 'tok-1' });
- const { result } = renderHook(() => useRealtimeVoiceSession());
- await act(async () => {
- await result.current.start();
- });
- expect(proactiveThreadPins.get(PROACTIVE_VOICE_THREAD_ID)).toBeUndefined();
- });
-
- it('surfaces an SDK onError', () => {
- const { result } = renderHook(() => useRealtimeVoiceSession());
- act(() => captured?.onError('microphone blocked'));
- expect(result.current.state).toBe('error');
- expect(result.current.error).toBe('microphone blocked');
- });
-
- it('returns to idle when the SDK disconnects', async () => {
- mockFetch.mockResolvedValueOnce({ signedUrl: 'wss://x', agentId: 'a1', userToken: 'tok-1' });
- const { result } = renderHook(() => useRealtimeVoiceSession());
- await act(async () => {
- await result.current.start();
- });
- act(() => captured?.onConnect());
- expect(result.current.state).toBe('active');
-
- act(() => captured?.onDisconnect());
- expect(result.current.state).toBe('idle');
- });
-
- it('tears down a live session on unmount', async () => {
- mockFetch.mockResolvedValueOnce({ signedUrl: 'wss://x', agentId: 'a1', userToken: 'tok-1' });
- const { result, unmount } = renderHook(() => useRealtimeVoiceSession());
- await act(async () => {
- await result.current.start();
- });
- act(() => captured?.onConnect());
- unmount();
- expect(endSession).toHaveBeenCalledTimes(1);
- });
-
- it('does not call endSession on unmount when no session is live', () => {
- const { unmount } = renderHook(() => useRealtimeVoiceSession());
- unmount();
- expect(endSession).not.toHaveBeenCalled();
- });
-
- it('reads a deferred result aloud when voice_speak arrives during a live call', async () => {
- mockFetch.mockResolvedValueOnce({ signedUrl: 'wss://x', agentId: 'a1', userToken: 'tok-1' });
- const { result } = renderHook(() => useRealtimeVoiceSession());
- await act(async () => {
- await result.current.start();
- });
- act(() => captured?.onConnect()); // liveRef becomes true
- act(() => socketHandlers['voice_speak']?.({ full_response: 'Your inbox summary.' }));
- expect(sendUserMessage).toHaveBeenCalledTimes(1);
- // Wrapped in the verbatim read-back prefix so the agent reads it aloud.
- expect(sendUserMessage.mock.calls[0][0]).toContain('Your inbox summary.');
- expect(sendUserMessage.mock.calls[0][0]).toContain('Please read the following');
- });
-
- // Each read-back is a real agent turn, so a repeat queues behind the first and
- // pushes the call towards the provider's per-turn ceiling.
- it('reads a redelivered answer aloud only once per call', async () => {
- mockFetch.mockResolvedValue({ signedUrl: 'wss://x', agentId: 'a1', userToken: 'tok-1' });
- const { result } = renderHook(() => useRealtimeVoiceSession());
- await act(async () => {
- await result.current.start();
- });
- act(() => captured?.onConnect());
- act(() => socketHandlers['voice_speak']?.({ full_response: 'Your inbox summary.' }));
- act(() => socketHandlers['voice_speak']?.({ full_response: 'Your inbox summary.' }));
- act(() => socketHandlers['voice_speak']?.({ full_response: 'A different answer.' }));
- expect(sendUserMessage).toHaveBeenCalledTimes(2);
-
- // A later call is a fresh conversation: the same answer may legitimately be
- // asked for and spoken again.
- act(() => captured?.onDisconnect());
- await act(async () => {
- await result.current.start();
- });
- act(() => captured?.onConnect());
- act(() => socketHandlers['voice_speak']?.({ full_response: 'Your inbox summary.' }));
- expect(sendUserMessage).toHaveBeenCalledTimes(3);
- });
-
- it('ignores voice_speak when no call is live', () => {
- renderHook(() => useRealtimeVoiceSession()); // never connected → liveRef stays false
- act(() => socketHandlers['voice_speak']?.({ full_response: 'ignored' }));
- expect(sendUserMessage).not.toHaveBeenCalled();
- });
-
- it('ignores an empty or missing voice_speak payload', async () => {
- mockFetch.mockResolvedValueOnce({ signedUrl: 'wss://x', agentId: 'a1', userToken: 'tok-1' });
- const { result } = renderHook(() => useRealtimeVoiceSession());
- await act(async () => {
- await result.current.start();
- });
- act(() => captured?.onConnect());
- act(() => socketHandlers['voice_speak']?.({ full_response: ' ' }));
- act(() => socketHandlers['voice_speak']?.(undefined));
- expect(sendUserMessage).not.toHaveBeenCalled();
- });
-
- it('unsubscribes from voice_speak on unmount', () => {
- const { unmount } = renderHook(() => useRealtimeVoiceSession());
- expect(socketHandlers['voice_speak']).toBeDefined();
- unmount();
- expect(socketHandlers['voice_speak']).toBeUndefined();
- });
-});
diff --git a/app/src/features/human/voice/useRealtimeVoiceSession.ts b/app/src/features/human/voice/useRealtimeVoiceSession.ts
deleted file mode 100644
index f551e9d174..0000000000
--- a/app/src/features/human/voice/useRealtimeVoiceSession.ts
+++ /dev/null
@@ -1,199 +0,0 @@
-import { useConversation } from '@elevenlabs/react';
-import createDebug from 'debug';
-import { useCallback, useEffect, useRef, useState } from 'react';
-
-import {
- PROACTIVE_VOICE_THREAD_ID,
- proactiveThreadPins,
-} from '../../../providers/proactiveThreadPins';
-import { fetchVoiceAgentSignedUrl } from '../../../services/api/voiceAgentApi';
-import { socketService } from '../../../services/socketService';
-import { MASCOT_VOICE_ID } from '../../../utils/config';
-
-const log = createDebug('app:human:realtime-voice');
-
-/**
- * Instruction prefix for "speak-back". A slow voice turn (e.g. an email summary)
- * is acknowledged aloud, finishes in the background, and its result is delivered
- * to chat AND pushed here as a `voice_speak` event. We send it back into the live
- * ElevenLabs session as a user message wrapped with this prefix so the agent reads
- * it verbatim. MUST match `VOICE_READBACK_PREFIX` in `voice/realtime_harness.rs`,
- * which uses it to avoid re-arming speak-back on the read-back turn (loop guard).
- */
-export const READBACK_PREFIX =
- 'Please read the following to me, word for word, and say nothing else:';
-
-/**
- * Lifecycle of a realtime ElevenLabs Agents voice session (#5399).
- * `idle → connecting → active → idle`, or `→ error`.
- */
-export type RealtimeSessionState = 'idle' | 'connecting' | 'active' | 'error';
-
-export interface RealtimeVoiceSession {
- state: RealtimeSessionState;
- /** True while the agent is speaking (drives the mascot's speaking pose). */
- isSpeaking: boolean;
- /** ElevenLabs turn mode; `listening` while the user speaks. */
- mode: 'speaking' | 'listening';
- /**
- * Output loudness (0..1) of the agent's voice, sampled from the SDK's
- * analyser. Drives the mascot's amplitude lip-sync — the realtime SDK owns
- * playback, so this is the only signal available to animate the mouth against.
- */
- getOutputVolume: () => number;
- error: string | null;
- /** Fetch a signed URL and open the WebSocket session. Idempotent while busy. */
- start: () => Promise<void>;
- stop: () => void;
-}
-
-/**
- * Drives a realtime voice-agent session with `@elevenlabs/react`. Must be used
- * inside a `ConversationProvider` (see `RealtimeVoiceControls`). Uses the
- * WebSocket connection type so the per-audio-event character `alignment` is
- * available for mascot lip-sync.
- */
-export function useRealtimeVoiceSession(opts?: { voiceId?: string }): RealtimeVoiceSession {
- const [state, setState] = useState<RealtimeSessionState>('idle');
- const [error, setError] = useState<string | null>(null);
- const startingRef = useRef(false);
- // Tracks whether a session is live so the unmount teardown only ends a real
- // session, and so the cleanup closure isn't tied to a stale `state`.
- const liveRef = useRef(false);
- // Answers already read aloud in THIS call, so a redelivered result is not
- // spoken twice. Scoped per call: asking the same question again in a later
- // session should of course be answered again.
- const spokenRef = useRef<Set<string>>(new Set());
-
- const conversation = useConversation({
- onConnect: () => {
- liveRef.current = true;
- log('connected');
- setState('active');
- },
- onDisconnect: () => {
- liveRef.current = false;
- log('disconnected');
- setState('idle');
- },
- // Errors from the SDK (mic denied, invalid/expired signed URL, WS handshake)
- // arrive here — startSession itself returns void — so this is the single
- // failure sink. Surface the message to the user (their own error) but log
- // only a stable category, never the raw provider text.
- onError: (message: string) => {
- liveRef.current = false;
- log('session error');
- setError(message);
- setState('error');
- },
- });
-
- // Keep a ref to the live conversation controls so the unmount effect can tear
- // the session down without re-running on every render.
- const conversationRef = useRef(conversation);
- conversationRef.current = conversation;
-
- const start = useCallback(async () => {
- if (startingRef.current || state === 'active' || state === 'connecting') return;
- startingRef.current = true;
- setError(null);
- setState('connecting');
- spokenRef.current.clear();
- // Each session is its own conversation: drop any pin from a prior session so
- // this session's deferred answers resolve to a fresh/current thread rather
- // than appending to the previous session's thread (which the Human page may
- // no longer have selected — the answer would land off-screen). The pin is
- // re-established on this session's first delivery. See
- // `resolveVisibleThreadForProactive` in ChatRuntimeProvider.
- proactiveThreadPins.delete(PROACTIVE_VOICE_THREAD_ID);
- log('start: requesting signed url');
- try {
- const { signedUrl, userToken } = await fetchVoiceAgentSignedUrl();
- log('start: signed url acquired, opening session');
- // `userId` is the identity binding the backend relay verifies (#5399).
- //
- // It rides the conversation-init event as `user_id`, but the provider does
- // not put it on the Custom-LLM request body: a live capture of
- // `POST /voice-agent/chat/completions` carried only
- // [messages, model, max_tokens, stream, stream_options, temperature, tools],
- // so every relayed turn was rejected for having no identity.
- //
- // `customLlmExtraBody` does reach that request — forwarded under an
- // `elevenlabs_extra_body` key rather than merged into the top level, which
- // is where the relay looks for it. `userId` stays for provider-side
- // attribution.
- conversation.startSession({
- signedUrl,
- connectionType: 'websocket',
- userId: userToken,
- customLlmExtraBody: { user: userToken },
- overrides: { tts: { voiceId: opts?.voiceId ?? MASCOT_VOICE_ID } },
- });
- } catch (err) {
- // Only the signed-url fetch rejects here; classify without leaking text.
- log('start failed: signed url request rejected');
- setError(err instanceof Error ? err.message : 'failed to start voice session');
- setState('error');
- } finally {
- startingRef.current = false;
- }
- }, [conversation, opts?.voiceId, state]);
-
- const stop = useCallback(() => {
- log('stop requested');
- conversation.endSession();
- liveRef.current = false;
- setState('idle');
- }, [conversation]);
-
- // Tear the session down if the component unmounts mid-call (e.g. the user
- // navigates away or switches voice mode) so the WebSocket and mic are released.
- useEffect(
- () => () => {
- if (liveRef.current) {
- log('unmount teardown: ending live session');
- conversationRef.current.endSession();
- liveRef.current = false;
- }
- },
- []
- );
-
- // Speak-back: a slow voice turn (email/calendar summary) is acknowledged aloud,
- // finishes in the background, and the core emits its result as a `voice_speak`
- // event. While the call is still open, read it aloud by sending it back into the
- // live ElevenLabs session wrapped in the verbatim prefix (a fast read-back turn).
- // The result also lands in chat regardless (delivered core-side) — this is the
- // spoken copy. Refs keep the subscription set up once while always seeing the
- // live conversation and liveness.
- useEffect(() => {
- const handler = (payload: unknown) => {
- if (!liveRef.current) return; // call already ended — the chat copy stands alone
- const text = (payload as { full_response?: string } | undefined)?.full_response?.trim();
- if (!text) return;
- // Each read-back is a real turn the agent has to speak, so a repeat is not
- // merely redundant: it queues behind the first and pushes the session
- // towards the provider's per-turn ceiling. Redelivery of the same answer
- // (a retried turn, a reconnect) must therefore be spoken once.
- if (spokenRef.current.has(text)) {
- log('speak-back: already read this answer aloud — skipping');
- return;
- }
- spokenRef.current.add(text);
- log('speak-back: reading deferred result aloud (%d chars)', text.length);
- conversationRef.current.sendUserMessage(`${READBACK_PREFIX}\n\n${text}`);
- };
- socketService.on('voice_speak', handler);
- return () => socketService.off('voice_speak', handler);
- }, []);
-
- return {
- state,
- isSpeaking: conversation.isSpeaking,
- mode: conversation.mode,
- getOutputVolume: conversation.getOutputVolume,
- error,
- start,
- stop,
- };
-}
diff --git a/app/src/services/api/voiceAgentApi.test.ts b/app/src/services/api/voiceAgentApi.test.ts
deleted file mode 100644
index ef0913f7be..0000000000
--- a/app/src/services/api/voiceAgentApi.test.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { callCoreRpc } from '../coreRpcClient';
-import { fetchVoiceAgentSignedUrl } from './voiceAgentApi';
-
-vi.mock('../coreRpcClient', () => ({ callCoreRpc: vi.fn() }));
-
-const mockCall = vi.mocked(callCoreRpc);
-
-describe('voiceAgentApi', () => {
- beforeEach(() => vi.clearAllMocks());
-
- it('calls the core RPC and maps the snake_case wire shape to camelCase', async () => {
- mockCall.mockResolvedValueOnce({ signed_url: 'wss://x', agent_id: 'a1', user_token: 'tok' });
- const res = await fetchVoiceAgentSignedUrl();
- expect(mockCall).toHaveBeenCalledWith({ method: 'openhuman.voice_agent_signed_url' });
- expect(res).toEqual({ signedUrl: 'wss://x', agentId: 'a1', userToken: 'tok' });
- });
-
- it('defaults userToken to empty against a backend that predates the binding', async () => {
- mockCall.mockResolvedValueOnce({ signed_url: 'wss://x', agent_id: 'a1' });
- const res = await fetchVoiceAgentSignedUrl();
- expect(res).toEqual({ signedUrl: 'wss://x', agentId: 'a1', userToken: '' });
- });
-
- it('propagates the core RPC error (e.g. signed out)', async () => {
- mockCall.mockRejectedValueOnce(new Error('no backend session token; sign in first'));
- await expect(fetchVoiceAgentSignedUrl()).rejects.toThrow('no backend session token');
- });
-});
diff --git a/app/src/services/api/voiceAgentApi.ts b/app/src/services/api/voiceAgentApi.ts
deleted file mode 100644
index 7d2a2c6bc4..0000000000
--- a/app/src/services/api/voiceAgentApi.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-/**
- * Realtime voice-agent session bootstrap (#5399).
- *
- * Mints a short-lived signed WebSocket URL for an ElevenLabs Agents
- * (Conversational AI) session via the core RPC `openhuman.voice_agent_signed_url`,
- * which proxies the backend `/voice-agent/get-signed-url`. The renderer never
- * sees the provider API key — only the short-lived signed URL — so the realtime
- * session client opens the connection with it directly.
- */
-import { callCoreRpc } from '../coreRpcClient';
-
-/** Camel-cased result the renderer consumes. */
-export interface VoiceAgentSignedUrl {
- signedUrl: string;
- agentId: string;
- /**
- * Short-lived token binding this session to the signed-in user. Passed back as
- * the ElevenLabs `userId` so the backend relay verifies it instead of trusting
- * a raw id (#5399). Empty only against a backend that predates the binding.
- */
- userToken: string;
-}
-
-/** Snake-cased wire shape returned by the core RPC. */
-interface VoiceAgentSignedUrlRpc {
- signed_url: string;
- agent_id: string;
- user_token?: string;
-}
-
-/**
- * Fetch a fresh signed URL for a realtime voice-agent session. Throws the core
- * RPC error (e.g. "no backend session token" when signed out, or a backend 400
- * when the agent is not configured) so callers can surface it.
- */
-export async function fetchVoiceAgentSignedUrl(): Promise<VoiceAgentSignedUrl> {
- const result = await callCoreRpc<VoiceAgentSignedUrlRpc>({
- method: 'openhuman.voice_agent_signed_url',
- });
- return {
- signedUrl: result.signed_url,
- agentId: result.agent_id,
- userToken: result.user_token ?? '',
- };
-}
diff --git a/crates/openhuman-core/src/voice/stub.rs b/crates/openhuman-core/src/voice/stub.rs
index cb2b515b68..209b3547ba 100644
--- a/crates/openhuman-core/src/voice/stub.rs
+++ b/crates/openhuman-core/src/voice/stub.rs
@@ -208,6 +208,22 @@ pub mod streaming {
pub async fn handle_dictation_ws(_socket: WebSocket, _config: Arc<Config>) {}
}
+// `live::ws::handle_live_voice_ws`: with voice off there are no live
+// providers, so the upgraded socket is dropped immediately.
+#[cfg(feature = "http-server")]
+pub mod live {
+ pub mod ws {
+ use std::sync::Arc;
+
+ use axum::extract::ws::WebSocket;
+
+ use crate::config::Config;
+
+ /// Drop the upgraded socket immediately — live voice is compiled out.
+ pub async fn handle_live_voice_ws(_socket: WebSocket, _config: Arc<Config>) {}
+ }
+}
+
// ---------------------------------------------------------------------------
// reply_speech::{synthesize_reply, ReplySpeechOptions, ReplySpeechResult, ...}
// ---------------------------------------------------------------------------
diff --git a/crates/openhuman-rpc/src/server/auth.rs b/crates/openhuman-rpc/src/server/auth.rs
index 5b091256f8..35395ac565 100644
--- a/crates/openhuman-rpc/src/server/auth.rs
+++ b/crates/openhuman-rpc/src/server/auth.rs
@@ -97,7 +97,7 @@ fn is_public_path(path: &str) -> bool {
/// Add new entries here only for SSE / WebSocket routes whose clients cannot
/// send headers and that carry per-user data. The follow-up approvals stream
/// (#1339) is the next planned addition.
-const QUERY_TOKEN_PATHS: &[&str] = &["/events/webhooks", "/ws/dictation"];
+const QUERY_TOKEN_PATHS: &[&str] = &["/events/webhooks", "/ws/dictation", "/ws/live-voice"];
/// Axum middleware: enforce `Authorization: Bearer <token>` on all protected
/// endpoints.
diff --git a/crates/openhuman-rpc/src/server/http/dictation.rs b/crates/openhuman-rpc/src/server/http/dictation.rs
index ff07459f06..493903cc99 100644
--- a/crates/openhuman-rpc/src/server/http/dictation.rs
+++ b/crates/openhuman-rpc/src/server/http/dictation.rs
@@ -94,7 +94,7 @@ pub(super) fn authorize_dictation_request(
}
#[derive(Clone, Copy, Debug)]
-enum DictationAuthError {
+pub(super) enum DictationAuthError {
Forbidden,
Unauthorized,
}
diff --git a/crates/openhuman-rpc/src/server/http/live_voice.rs b/crates/openhuman-rpc/src/server/http/live_voice.rs
new file mode 100644
index 0000000000..d2d98e7b5f
--- /dev/null
+++ b/crates/openhuman-rpc/src/server/http/live_voice.rs
@@ -0,0 +1,36 @@
+//! `GET /ws/live-voice`: the authenticated live voice agent WebSocket.
+//!
+//! Same upgrade guard as `/ws/dictation` (origin allowlist plus the core bearer
+//! from the `Authorization` header or `?token=`); the session itself is
+//! `openhuman_core::voice::live::ws::handle_live_voice_ws`.
+
+use std::sync::Arc;
+
+use axum::extract::{Query, WebSocketUpgrade};
+use axum::response::{IntoResponse, Response};
+
+use super::dictation::{authorize_dictation_request, DictationQuery};
+
+/// WebSocket upgrade handler for live voice sessions.
+pub(super) async fn live_voice_ws_handler(
+ headers: axum::http::HeaderMap,
+ Query(query): Query<DictationQuery>,
+ ws: WebSocketUpgrade,
+) -> Response {
+ log::info!("[ws] live voice WebSocket upgrade requested");
+ if let Err(error) = authorize_dictation_request(&headers, &query) {
+ return error.into_response();
+ }
+ // Agent audio arrives in ~40 ms chunks; keep frames small and unbounded
+ // in count rather than buffering.
+ ws.on_upgrade(|socket| async move {
+ let config = match openhuman_core::config::rpc::load_config_with_timeout().await {
+ Ok(c) => Arc::new(c),
+ Err(e) => {
+ log::error!("[ws] failed to load config for live voice: {e}");
+ return;
+ }
+ };
+ openhuman_core::voice::live::ws::handle_live_voice_ws(socket, config).await;
+ })
+}
diff --git a/crates/openhuman-rpc/src/server/http/mod.rs b/crates/openhuman-rpc/src/server/http/mod.rs
index 75cedca509..a51815d5ca 100644
--- a/crates/openhuman-rpc/src/server/http/mod.rs
+++ b/crates/openhuman-rpc/src/server/http/mod.rs
@@ -16,6 +16,7 @@ use openhuman_core::core::types::AppState;
pub(crate) mod cors;
mod dictation;
+mod live_voice;
mod events;
mod health;
mod oauth_mcp;
@@ -65,6 +66,7 @@ pub fn build_core_http_router(socketio_enabled: bool) -> Router {
post(rpc_handler::rpc_handler).route_layer(DefaultBodyLimit::max(MAX_RPC_BODY_BYTES)),
)
.route("/ws/dictation", get(dictation::dictation_ws_handler))
+ .route("/ws/live-voice", get(live_voice::live_voice_ws_handler))
.route(
"/oauth/mcp/callback",
get(oauth_mcp::oauth_mcp_callback_handler),