Skip to content

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

feat(chat): read a message aloud, over the TTS the app already has

M3gA-Minda572debc25b2
diff --git a/app/src/components/assistant-ui/__tests__/thread.readAloud.test.tsx b/app/src/components/assistant-ui/__tests__/thread.readAloud.test.tsx
new file mode 100644
index 0000000000..6bd53de42e
--- /dev/null
+++ b/app/src/components/assistant-ui/__tests__/thread.readAloud.test.tsx
@@ -0,0 +1,113 @@
+/**
+ * Read-aloud, proven from the component `/chat` actually mounts.
+ *
+ * `ActionBarPrimitive.Speak` has the same trap as Reload: its disabled
+ * predicate checks only the message's role and running status, NOT
+ * `capabilities.speech`. So a Speak button rendered against a runtime with no
+ * `adapters.speech` is enabled, clickable, and throws. Both halves have to be
+ * present for the control to mean anything, which is what these tests assert —
+ * the button appears only when the runtime can actually speak.
+ */
+import {
+ AssistantRuntimeProvider,
+ type SpeechSynthesisAdapter,
+ type ThreadMessageLike,
+ useExternalStoreRuntime,
+} from '@assistant-ui/react';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { Thread } from '../thread';
+
+const messages: ThreadMessageLike[] = [
+ { role: 'user', content: [{ type: 'text', text: 'explain mitochondria' }] },
+ {
+ role: 'assistant',
+ content: [{ type: 'text', text: 'The mitochondria is the powerhouse of the cell.' }],
+ },
+];
+
+/** A speech adapter whose utterance this test drives by hand. */
+function controllableSpeech() {
+ const cancel = vi.fn();
+ const speak = vi.fn((_text: string) => {
+ const listeners = new Set<() => void>();
+ const utterance = {
+ status: { type: 'running' } as SpeechSynthesisAdapter.Utterance['status'],
+ cancel: () => {
+ cancel();
+ utterance.status = { type: 'ended', reason: 'cancelled' };
+ for (const l of listeners) l();
+ },
+ subscribe: (cb: () => void) => {
+ listeners.add(cb);
+ return () => listeners.delete(cb);
+ },
+ };
+ return utterance;
+ });
+ return { adapter: { speak } as unknown as SpeechSynthesisAdapter, speak, cancel };
+}
+
+function Harness({ speech }: { speech?: SpeechSynthesisAdapter }) {
+ const runtime = useExternalStoreRuntime({
+ messages,
+ isRunning: false,
+ convertMessage: (m: ThreadMessageLike) => m,
+ onNew: async () => {},
+ ...(speech ? { adapters: { speech } } : {}),
+ });
+ return (
+ <AssistantRuntimeProvider runtime={runtime}>
+ <Thread model={null} onModelChange={() => {}} />
+ </AssistantRuntimeProvider>
+ );
+}
+
+describe('read-aloud on the live Thread', () => {
+ it('offers Read aloud when the runtime can speak', async () => {
+ const { adapter } = controllableSpeech();
+ render(<Harness speech={adapter} />);
+
+ await screen.findByText('The mitochondria is the powerhouse of the cell.');
+ expect(await screen.findByRole('button', { name: /read aloud/i })).toBeInTheDocument();
+ });
+
+ it('offers NO Read aloud button when the runtime cannot speak', async () => {
+ // The guard against the Reload defect: without an adapter the control must
+ // be absent, not present-and-throwing. `capabilities.speech` is false here
+ // because no `adapters.speech` was supplied.
+ render(<Harness />);
+
+ await screen.findByText('The mitochondria is the powerhouse of the cell.');
+ expect(screen.queryByRole('button', { name: /read aloud/i })).toBeNull();
+ });
+
+ it('speaks the message text and swaps to Stop reading', async () => {
+ const { adapter, speak } = controllableSpeech();
+ render(<Harness speech={adapter} />);
+ await screen.findByText('The mitochondria is the powerhouse of the cell.');
+
+ fireEvent.click(await screen.findByRole('button', { name: /read aloud/i }));
+
+ await waitFor(() => expect(speak).toHaveBeenCalled());
+ // The message's own text, not a placeholder — an adapter handed the wrong
+ // string would read the wrong message aloud.
+ expect(speak.mock.calls[0]?.[0]).toContain('powerhouse of the cell');
+ // While it is speaking the affordance must become Stop, or there is no way
+ // to silence it.
+ expect(await screen.findByRole('button', { name: /stop reading/i })).toBeInTheDocument();
+ });
+
+ it('stops the utterance when Stop reading is pressed', async () => {
+ const { adapter, cancel } = controllableSpeech();
+ render(<Harness speech={adapter} />);
+ await screen.findByText('The mitochondria is the powerhouse of the cell.');
+ fireEvent.click(await screen.findByRole('button', { name: /read aloud/i }));
+
+ fireEvent.click(await screen.findByRole('button', { name: /stop reading/i }));
+
+ await waitFor(() => expect(cancel).toHaveBeenCalled());
+ await waitFor(() => expect(screen.queryByRole('button', { name: /stop reading/i })).toBeNull());
+ });
+});
diff --git a/app/src/components/assistant-ui/thread.tsx b/app/src/components/assistant-ui/thread.tsx
index 7d73cc2694..cb4c8990ad 100644
--- a/app/src/components/assistant-ui/thread.tsx
+++ b/app/src/components/assistant-ui/thread.tsx
@@ -73,6 +73,8 @@ import {
SquareIcon,
ThumbsDownIcon,
ThumbsUpIcon,
+ Volume2Icon,
+ VolumeXIcon,
} from 'lucide-react';
import {
type ComponentType,
@@ -1227,6 +1229,31 @@ const AssistantActionBar: FC = () => {
<ThumbsDownIcon />
</TooltipIconButton>
</ActionBarPrimitive.FeedbackNegative>
+ {/*
+ * Read aloud, through the same TTS the chat mascot uses. Gated on the
+ * capability rather than rendered unconditionally: `actionBarSpeakDisabled`
+ * checks only the message's role and running status, NOT
+ * `capabilities.speech`, so an ungated Speak button on a runtime with no
+ * `adapters.speech` is enabled, clickable, and throws. The gate makes the
+ * control appear exactly when it can work — the same rule `UserActionBar`
+ * applies to Edit (#5897).
+ */}
+ <AuiIf condition={s => s.thread.capabilities.speech}>
+ <AuiIf condition={s => s.message.speech == null}>
+ <ActionBarPrimitive.Speak asChild>
+ <TooltipIconButton tooltip="Read aloud">
+ <Volume2Icon />
+ </TooltipIconButton>
+ </ActionBarPrimitive.Speak>
+ </AuiIf>
+ <AuiIf condition={s => s.message.speech != null}>
+ <ActionBarPrimitive.StopSpeaking asChild>
+ <TooltipIconButton tooltip="Stop reading">
+ <VolumeXIcon className="text-destructive" />
+ </TooltipIconButton>
+ </ActionBarPrimitive.StopSpeaking>
+ </AuiIf>
+ </AuiIf>
<ActionBarMorePrimitive.Root>
<ActionBarMorePrimitive.Trigger asChild>
<TooltipIconButton tooltip="More" className="data-[state=open]:bg-accent">
diff --git a/app/src/providers/__tests__/speechAdapter.test.ts b/app/src/providers/__tests__/speechAdapter.test.ts
new file mode 100644
index 0000000000..c6ce7ba526
--- /dev/null
+++ b/app/src/providers/__tests__/speechAdapter.test.ts
@@ -0,0 +1,154 @@
+/**
+ * The read-aloud bridge.
+ *
+ * assistant-ui drives this through a small contract — `speak(text)` returns an
+ * utterance whose `status` moves `starting` → `running` → `ended` and whose
+ * `subscribe` fires on each transition. Getting the TERMINAL states right is
+ * what matters: the Stop button renders while `status` is not `ended`, so an
+ * utterance that never reaches `ended` leaves a Stop button on a message that
+ * is silent, and one that reports `error` for an ordinary cancel flashes a
+ * failure at a user who simply pressed Stop.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AudioStoppedError, playBase64Audio } from '../../features/human/voice/audioPlayer';
+import { synthesizeSpeech } from '../../features/human/voice/ttsClient';
+import { openHumanSpeechAdapter } from '../speechAdapter';
+
+vi.mock('../../features/human/voice/ttsClient', async importOriginal => {
+ const actual = await importOriginal<typeof import('../../features/human/voice/ttsClient')>();
+ return { ...actual, synthesizeSpeech: vi.fn() };
+});
+vi.mock('../../features/human/voice/audioPlayer', async importOriginal => {
+ const actual = await importOriginal<typeof import('../../features/human/voice/audioPlayer')>();
+ return { ...actual, playBase64Audio: vi.fn() };
+});
+
+/** A playback handle whose `ended` this test resolves or rejects by hand. */
+function fakeHandle() {
+ let resolveEnded!: () => void;
+ let rejectEnded!: (err: Error) => void;
+ const ended = new Promise<void>((res, rej) => {
+ resolveEnded = res;
+ rejectEnded = rej;
+ });
+ const stop = vi.fn(() => rejectEnded(new AudioStoppedError()));
+ return {
+ handle: {
+ currentMs: () => 0,
+ durationMs: () => 0,
+ metadataReady: Promise.resolve(),
+ stop,
+ ended,
+ },
+ finish: resolveEnded,
+ stop,
+ };
+}
+
+/** Let the adapter's internal promise chain advance. */
+const tick = () => new Promise(resolve => setTimeout(resolve, 0));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(synthesizeSpeech).mockResolvedValue({
+ audio_base64: 'AAAA',
+ audio_mime: 'audio/mpeg',
+ visemes: [],
+ } as never);
+});
+
+describe('openHumanSpeechAdapter', () => {
+ it('synthesises the prose and plays it, ending as finished', async () => {
+ const { handle, finish } = fakeHandle();
+ vi.mocked(playBase64Audio).mockResolvedValue(handle as never);
+
+ const utterance = openHumanSpeechAdapter.speak('Hello **there**.');
+ expect(utterance.status.type).toBe('starting');
+
+ await tick();
+ expect(utterance.status.type).toBe('running');
+ // Markdown is stripped before synthesis, so the reading does not say
+ // "asterisk asterisk there asterisk asterisk".
+ expect(vi.mocked(synthesizeSpeech).mock.calls[0]?.[0]).not.toContain('**');
+ expect(vi.mocked(synthesizeSpeech).mock.calls[0]?.[0]).toContain('there');
+
+ finish();
+ await tick();
+ expect(utterance.status).toEqual({ type: 'ended', reason: 'finished' });
+ });
+
+ it('notifies subscribers on every transition', async () => {
+ const { handle, finish } = fakeHandle();
+ vi.mocked(playBase64Audio).mockResolvedValue(handle as never);
+ const utterance = openHumanSpeechAdapter.speak('Hello.');
+ const onChange = vi.fn();
+ utterance.subscribe(onChange);
+
+ await tick();
+ finish();
+ await tick();
+
+ // Without this the Stop button never appears and never goes away: the
+ // button is rendered from state assistant-ui only re-reads when told to.
+ expect(onChange.mock.calls.length).toBeGreaterThanOrEqual(2);
+ });
+
+ it('ends as cancelled — not error — when the reader presses Stop', async () => {
+ // `PlaybackHandle.stop()` rejects `ended` by design, so a cancel arrives on
+ // the error path and must not be reported as a failure.
+ const { handle, stop } = fakeHandle();
+ vi.mocked(playBase64Audio).mockResolvedValue(handle as never);
+ const utterance = openHumanSpeechAdapter.speak('Hello.');
+ await tick();
+
+ utterance.cancel();
+ await tick();
+
+ expect(stop).toHaveBeenCalled();
+ expect(utterance.status).toEqual({ type: 'ended', reason: 'cancelled' });
+ });
+
+ it('stops audio that only started after the cancel landed', async () => {
+ // The race: cancel() between `synthesizeSpeech` resolving and the handle
+ // existing. Without the post-await check the reader presses Stop and the
+ // audio starts playing anyway, with no handle left to stop it.
+ const { handle, stop } = fakeHandle();
+ let releasePlayback!: (h: unknown) => void;
+ vi.mocked(playBase64Audio).mockReturnValue(
+ new Promise(resolve => {
+ releasePlayback = resolve;
+ }) as never
+ );
+
+ const utterance = openHumanSpeechAdapter.speak('Hello.');
+ await tick();
+ utterance.cancel();
+ releasePlayback(handle);
+ await tick();
+
+ expect(stop).toHaveBeenCalled();
+ expect(utterance.status).toEqual({ type: 'ended', reason: 'cancelled' });
+ });
+
+ it('reports a synthesis failure as an error', async () => {
+ vi.mocked(synthesizeSpeech).mockRejectedValue(new Error('tts provider unreachable'));
+
+ const utterance = openHumanSpeechAdapter.speak('Hello.');
+ await tick();
+
+ expect(utterance.status.type).toBe('ended');
+ expect(utterance.status).toMatchObject({ reason: 'error' });
+ });
+
+ it('finishes quietly for a message with no prose to read', async () => {
+ // A tool-only or code-only answer. Ending as `finished` rather than
+ // `error` keeps the button from flashing a failure at a message that
+ // simply has nothing sayable in it.
+ const utterance = openHumanSpeechAdapter.speak('```ts\nconst x = 1;\n```');
+ await tick();
+
+ expect(utterance.status).toEqual({ type: 'ended', reason: 'finished' });
+ expect(vi.mocked(synthesizeSpeech)).not.toHaveBeenCalled();
+ });
+});
diff --git a/app/src/providers/__tests__/useOpenHumanExternalStore.speech.test.tsx b/app/src/providers/__tests__/useOpenHumanExternalStore.speech.test.tsx
new file mode 100644
index 0000000000..7062999408
--- /dev/null
+++ b/app/src/providers/__tests__/useOpenHumanExternalStore.speech.test.tsx
@@ -0,0 +1,52 @@
+/**
+ * The runtime must actually offer speech, or the Read aloud button never
+ * renders in the real app.
+ *
+ * `thread.readAloud.test.tsx` proves the buttons appear when a runtime CAN
+ * speak, using its own adapter. This is the other half: that OpenHuman's own
+ * adapter supplies one. Without it `capabilities.speech` is false, the gate in
+ * `AssistantActionBar` hides the control, and the feature is invisible on
+ * `/chat` while every component-level test still passes — the stranded-surface
+ * shape this whole change exists to avoid.
+ */
+import { configureStore } from '@reduxjs/toolkit';
+import { renderHook } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { Provider } from 'react-redux';
+import { describe, expect, it, vi } from 'vitest';
+
+import chatRuntimeReducer from '../../store/chatRuntimeSlice';
+import threadReducer from '../../store/threadSlice';
+import { useOpenHumanExternalStore } from '../useOpenHumanExternalStore';
+
+vi.mock('../../services/api/threadApi', () => ({
+ threadApi: {
+ getDerivedTranscript: vi
+ .fn()
+ .mockResolvedValue({
+ threadId: 't-speech',
+ items: [],
+ total: 0,
+ hasMore: false,
+ hasTranscript: false,
+ }),
+ },
+}));
+
+function mount() {
+ const store = configureStore({
+ reducer: { thread: threadReducer, chatRuntime: chatRuntimeReducer },
+ });
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <Provider store={store}>{children}</Provider>
+ );
+ return renderHook(() => useOpenHumanExternalStore('t-speech'), { wrapper });
+}
+
+describe('the external-store adapter', () => {
+ it('supplies a speech adapter, which is what makes capabilities.speech true', () => {
+ const { result } = mount();
+
+ expect(typeof result.current.adapters?.speech?.speak).toBe('function');
+ });
+});
diff --git a/app/src/providers/speechAdapter.ts b/app/src/providers/speechAdapter.ts
new file mode 100644
index 0000000000..8fd9260bbe
--- /dev/null
+++ b/app/src/providers/speechAdapter.ts
@@ -0,0 +1,137 @@
+/**
+ * Read-aloud for the assistant-ui surface, over OpenHuman's existing TTS.
+ *
+ * `ActionBarPrimitive.Speak` / `.StopSpeaking` are exported by our pinned
+ * assistant-ui and were rendered nowhere, because the capability derives from
+ * `adapters.speech` and the external-store adapter supplied none.
+ *
+ * ## Why this is a bridge and not a new feature
+ *
+ * The app already speaks. `openhuman.voice_reply_synthesize` dispatches through
+ * the user's configured `tts_provider` (cloud / piper / …), and the chat mascot
+ * already calls it on this very route — `ChatMascotOverlay` speaks replies when
+ * the voice stage is expanded and the "speak replies" switch is on. So this
+ * adapter adds no backend, no provider, and no new configuration: it calls the
+ * same RPC through the same client.
+ *
+ * What it adds is the affordance that surface does NOT have. The mascot's
+ * speech is automatic, applies to every reply, and only runs while the voice
+ * stage is open. A text-chat reader who wants ONE answer read aloud currently
+ * has to open the voice stage and enable speak-replies — which then speaks
+ * everything from that point and never reads the message they were looking at.
+ * This is per-message, on demand, in ordinary text chat.
+ *
+ * ## Deliberately not the browser's speech synthesis
+ *
+ * assistant-ui ships `WebSpeechSynthesisAdapter`. Using it would put a second,
+ * different-sounding voice in an app that already has one, with none of the
+ * provider routing the settings screen offers. It would also repeat the
+ * dictation finding (#6489): a Web Speech API that is present but does not
+ * behave in this app's webview.
+ *
+ * Nothing here touches the mascot, Rive, or the lipsync pipeline — those are
+ * the visual layer over the same audio, and a text-chat reader wants none of it.
+ */
+import type { SpeechSynthesisAdapter } from '@assistant-ui/react';
+
+import {
+ isAudioStopped,
+ type PlaybackHandle,
+ playBase64Audio,
+} from '../features/human/voice/audioPlayer';
+import { prepareForSpeech, synthesizeSpeech } from '../features/human/voice/ttsClient';
+
+/**
+ * Safety bound on a single utterance, mirroring the voice path's own guard: a
+ * provider that returns a runaway file should not be able to hold the audio
+ * element open indefinitely. Ten minutes is far beyond any real answer.
+ */
+const MAX_UTTERANCE_MS = 10 * 60 * 1000;
+
+type Status = SpeechSynthesisAdapter.Utterance['status'];
+
+/**
+ * Speak one message.
+ *
+ * The returned utterance is live: `status` moves `starting` → `running` →
+ * `ended`, and `subscribe` fires on each transition so assistant-ui can swap
+ * the Speak button for Stop and back again.
+ */
+function speak(text: string): SpeechSynthesisAdapter.Utterance {
+ const listeners = new Set<() => void>();
+ let status: Status = { type: 'starting' };
+ let handle: PlaybackHandle | null = null;
+ let cancelled = false;
+
+ const setStatus = (next: Status) => {
+ if (status.type === 'ended') return;
+ status = next;
+ for (const listener of listeners) listener();
+ };
+
+ void (async () => {
+ try {
+ // Strip markdown, code fences and link syntax before synthesis — the
+ // same preparation the spoken-reply path uses, so a read-aloud sounds
+ // like the mascot rather than like someone reading punctuation.
+ const spoken = prepareForSpeech(text);
+ if (spoken.trim().length === 0) {
+ // Nothing sayable (a tool-only or code-only answer). Ending as
+ // `finished` rather than `error` keeps the button from flashing a
+ // failure at the user for a message that simply has no prose.
+ setStatus({ type: 'ended', reason: 'finished' });
+ return;
+ }
+
+ const reply = await synthesizeSpeech(spoken);
+ if (cancelled) return;
+
+ handle = await playBase64Audio(reply.audio_base64, reply.audio_mime, {
+ maxDurationMs: MAX_UTTERANCE_MS,
+ });
+ // `cancel()` can land between the await above and this line, when the
+ // handle did not yet exist for it to stop.
+ if (cancelled) {
+ handle.stop();
+ // `stop()` rejects `ended` by design. Every other path reaches the
+ // `await` below and lets the `catch` absorb it; this one returns
+ // first, so the rejection would have no handler attached and surface
+ // as an unhandled promise rejection.
+ void handle.ended.catch(() => {});
+ return;
+ }
+
+ setStatus({ type: 'running' });
+ await handle.ended;
+ setStatus({ type: 'ended', reason: 'finished' });
+ } catch (error) {
+ // `stop()` rejects `ended` by design, so a cancellation arrives here as
+ // an error and must not be reported as one.
+ if (cancelled || isAudioStopped(error)) {
+ setStatus({ type: 'ended', reason: 'cancelled' });
+ return;
+ }
+ setStatus({ type: 'ended', reason: 'error', error });
+ }
+ })();
+
+ return {
+ get status() {
+ return status;
+ },
+ cancel() {
+ cancelled = true;
+ handle?.stop();
+ setStatus({ type: 'ended', reason: 'cancelled' });
+ },
+ subscribe(callback: () => void) {
+ listeners.add(callback);
+ return () => {
+ listeners.delete(callback);
+ };
+ },
+ };
+}
+
+/** The `adapters.speech` entry for {@link useOpenHumanExternalStore}. */
+export const openHumanSpeechAdapter: SpeechSynthesisAdapter = { speak };
diff --git a/app/src/providers/useOpenHumanExternalStore.ts b/app/src/providers/useOpenHumanExternalStore.ts
index cc203467e3..dac07346db 100644
--- a/app/src/providers/useOpenHumanExternalStore.ts
+++ b/app/src/providers/useOpenHumanExternalStore.ts
@@ -22,6 +22,7 @@ import type { DerivedDisplayItem } from '../types/derivedTranscript';
import type { ThreadMessage } from '../types/thread';
import { buildRuntimeMessages, STREAMING_TAIL_ID } from './assistantUiMessages';
import { getChatSurface } from './chatSurfaceHandlers';
+import { openHumanSpeechAdapter } from './speechAdapter';
const EMPTY_MESSAGES: ThreadMessage[] = [];
const EMPTY_SUGGESTIONS: readonly ThreadSuggestion[] = [];
@@ -433,7 +434,8 @@ export function useOpenHumanExternalStore(threadId: string | null) {
[dispatch, threadId]
);
- // DO NOT add `adapters: { dictation: new WebSpeechDictationAdapter() }` here.
+ // DO NOT add `dictation: new WebSpeechDictationAdapter()` to the `adapters`
+ // key below.
//
// It is exported by `@assistant-ui/react` at our pinned 0.15.16 and looks like
// a one-line win: the transcript already renders Dictate / StopDictation
@@ -479,10 +481,19 @@ export function useOpenHumanExternalStore(threadId: string | null) {
suggestions,
// Already `ThreadMessageLike`; the runtime's converter is the identity.
convertMessage: (m: (typeof runtimeMessages)[number]) => m,
- adapters: { feedback: feedbackAdapter },
onNew,
onCancel,
onRespondToToolApproval,
+ // Read-aloud for a single message. Supplying this is what makes
+ // `capabilities.speech` true and the Speak / StopSpeaking controls
+ // usable — and it must ship WITH the buttons, never before or after
+ // them: `actionBarSpeakDisabled` does not consult the capability (it
+ // checks only role and running status), so a Speak button rendered
+ // without an adapter is enabled, clickable, and throws "Runtime does not
+ // support speech." That is the #5897 defect shape, and Reload already
+ // sits in the same trap today.
+ // No `dictation` key here — see the Web Speech note above this object.
+ adapters: { feedback: feedbackAdapter, speech: openHumanSpeechAdapter },
}),
[
runtimeMessages,