From 67cfd862b1863005e62dd790911fc835bfb90a3c Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:08:33 -0400 Subject: [PATCH] fix(tts): let voice mode read replies aloud on iOS iOS rejects play() outside a user gesture unless the same media element was already played inside one. Each chunk used a new Audio element, so replies in voice mode failed with "Reading the reply failed". - reuse one audio element for all external TTS playback - add tts.unlock(), which plays a short silent clip on that element, and call it from the voice mode start and orb taps - route every playback failure through failPlayback(message) and pass the message to onEnd so voice mode shows the underlying reason - report a blocked play() as "Audio playback was blocked by the browser" --- .../components/message/MessageThread.test.tsx | 1 + .../schedules/RunDetailPanel.test.tsx | 1 + .../components/settings/TTSSettings.test.tsx | 1 + frontend/src/contexts/TTSContext.test.tsx | 330 ++++++++++++------ frontend/src/contexts/TTSContext.tsx | 157 +++++---- frontend/src/contexts/tts-context.ts | 10 +- .../src/hooks/useVoiceConversation.test.tsx | 34 +- frontend/src/hooks/useVoiceConversation.ts | 10 +- 8 files changed, 354 insertions(+), 190 deletions(-) diff --git a/frontend/src/components/message/MessageThread.test.tsx b/frontend/src/components/message/MessageThread.test.tsx index 677ef6d4..4ad2d85b 100644 --- a/frontend/src/components/message/MessageThread.test.tsx +++ b/frontend/src/components/message/MessageThread.test.tsx @@ -48,6 +48,7 @@ vi.mock('@/hooks/useTTS', () => ({ useTTS: () => ({ speakMessage: vi.fn(), stop: vi.fn(), + unlock: vi.fn(), isEnabled: false, isPlaying: false, isLoading: false, diff --git a/frontend/src/components/schedules/RunDetailPanel.test.tsx b/frontend/src/components/schedules/RunDetailPanel.test.tsx index 9f8fe562..9f59b503 100644 --- a/frontend/src/components/schedules/RunDetailPanel.test.tsx +++ b/frontend/src/components/schedules/RunDetailPanel.test.tsx @@ -15,6 +15,7 @@ const mocks = vi.hoisted(() => ({ const tts = { speakMessage: vi.fn(), stop: vi.fn(), + unlock: vi.fn(), isEnabled: true, isPlaying: false, isLoading: false, diff --git a/frontend/src/components/settings/TTSSettings.test.tsx b/frontend/src/components/settings/TTSSettings.test.tsx index 76863975..f3cef577 100644 --- a/frontend/src/components/settings/TTSSettings.test.tsx +++ b/frontend/src/components/settings/TTSSettings.test.tsx @@ -76,6 +76,7 @@ function mockHooks(preferences: UserPreferences = buildPreferences()) { stop: vi.fn(), pause: vi.fn(), resume: vi.fn(), + unlock: vi.fn(), state: 'idle', error: null, currentText: null, diff --git a/frontend/src/contexts/TTSContext.test.tsx b/frontend/src/contexts/TTSContext.test.tsx index 9a7b95a3..bd26b061 100644 --- a/frontend/src/contexts/TTSContext.test.tsx +++ b/frontend/src/contexts/TTSContext.test.tsx @@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { render, act, waitFor } from '@testing-library/react' import { TTSProvider } from './TTSContext' import { useTTS } from '@/hooks/useTTS' -import type { TTSConfig, TTSContextValue } from './tts-context' +import type { SpeakMessageOptions, TTSConfig, TTSContextValue } from './tts-context' import type { WebSpeechSynthesizer } from '@/lib/webSpeechSynthesizer' const mocks = vi.hoisted(() => ({ @@ -35,18 +35,22 @@ vi.mock('@/lib/webSpeechSynthesizer', () => ({ class FakeAudio { static instances: FakeAudio[] = [] + static nextPlayRejection: unknown = null src: string paused = true onended: (() => void) | null = null onerror: (() => void) | null = null - constructor(src: string) { + constructor(src = '') { this.src = src FakeAudio.instances.push(this) } - play = vi.fn(() => { + play = vi.fn((): Promise => { + const rejection = FakeAudio.nextPlayRejection + FakeAudio.nextPlayRejection = null + if (rejection) return Promise.reject(rejection) this.paused = false return Promise.resolve() }) @@ -86,6 +90,24 @@ async function flushPlayback() { }) } +function player(): FakeAudio { + const instance = FakeAudio.instances[0] + if (!instance) throw new Error('expected the shared audio player to exist') + return instance +} + +async function startPlayback( + messageId: string, + text: string, + options?: SpeakMessageOptions, +): Promise { + await act(async () => { + await ttsRef.current!.speakMessage(messageId, text, options) + }) + await waitFor(() => expect(player().paused).toBe(false)) + return player() +} + function setPreferences(overrides: Partial = {}) { mocks.useSettings.mockReturnValue({ preferences: { @@ -136,6 +158,7 @@ function renderProvider() { beforeEach(() => { vi.clearAllMocks() FakeAudio.instances = [] + FakeAudio.nextPlayRejection = null fetchBodies = [] objectUrlCounter = 0 ttsRef.current = null @@ -170,59 +193,46 @@ describe('TTSProvider playback isolation', () => { setPreferences() renderProvider() - await act(async () => { - await ttsRef.current!.speakMessage('A', textA) - }) - - await waitFor(() => expect(FakeAudio.instances.length).toBeGreaterThanOrEqual(1)) - const firstAudio = FakeAudio.instances[0] - await waitFor(() => expect(firstAudio.paused).toBe(false)) - const staleOnended = firstAudio.onended + const audio = await startPlayback('A', textA) + const firstSrc = audio.src + expect(firstSrc).toMatch(/^blob:/) + const staleOnended = audio.onended expect(staleOnended).toBeTypeOf('function') await act(async () => { await ttsRef.current!.speakMessage('B', textB) }) - await waitFor(() => expect(FakeAudio.instances.length).toBeGreaterThanOrEqual(2)) - const secondAudio = FakeAudio.instances[1] - await waitFor(() => expect(secondAudio.paused).toBe(false)) await waitFor(() => expect(fetchBodies).toContain('Bravo three. Bravo four.')) - - expect(firstAudio.paused).toBe(true) + await waitFor(() => expect(audio.src).not.toBe(firstSrc)) + const activeSrc = audio.src + expect(audio.paused).toBe(false) await act(async () => { staleOnended!() await new Promise((resolve) => setTimeout(resolve, 0)) }) - const playing = FakeAudio.instances.filter((audio) => !audio.paused) - expect(playing).toHaveLength(1) - expect(playing[0]).toBe(secondAudio) - expect(FakeAudio.instances).toHaveLength(2) + expect(FakeAudio.instances).toHaveLength(1) + expect(audio.src).toBe(activeSrc) + expect(audio.paused).toBe(false) }) it('ignores a stale onerror after cleanup without orphaning the new audio or corrupting state', async () => { setPreferences() renderProvider() - await act(async () => { - await ttsRef.current!.speakMessage('A', textA) - }) - - await waitFor(() => expect(FakeAudio.instances.length).toBeGreaterThanOrEqual(1)) - const firstAudio = FakeAudio.instances[0] - await waitFor(() => expect(firstAudio.paused).toBe(false)) - const staleOnerror = firstAudio.onerror + const audio = await startPlayback('A', textA) + const staleOnerror = audio.onerror expect(staleOnerror).toBeTypeOf('function') await act(async () => { await ttsRef.current!.speakMessage('B', textB) }) - await waitFor(() => expect(FakeAudio.instances.length).toBeGreaterThanOrEqual(2)) - const secondAudio = FakeAudio.instances[1] - await waitFor(() => expect(secondAudio.paused).toBe(false)) + await waitFor(() => expect(fetchBodies).toContain('Bravo three. Bravo four.')) + const activeSrc = audio.src + const playCalls = audio.play.mock.calls.length await act(async () => { staleOnerror!() @@ -230,7 +240,10 @@ describe('TTSProvider playback isolation', () => { expect(ttsRef.current!.state).toBe('playing') expect(ttsRef.current!.error).toBeNull() - expect(secondAudio.paused).toBe(false) + expect(audio.paused).toBe(false) + expect(audio.src).toBe(activeSrc) + expect(audio.play.mock.calls.length).toBe(playCalls) + expect(FakeAudio.instances).toHaveLength(1) }) it('cancels active Web Speech playback when an external playback starts', async () => { @@ -273,18 +286,13 @@ describe('TTSProvider playback isolation', () => { }), ) - await act(async () => { - await ttsRef.current!.speakMessage('A', textA) - }) - - await waitFor(() => expect(FakeAudio.instances.length).toBeGreaterThanOrEqual(1)) - const firstAudio = FakeAudio.instances[0] - await waitFor(() => expect(firstAudio.paused).toBe(false)) + const audio = await startPlayback('A', textA) await waitFor(() => expect(fetchBodies).toContain('Alpha one. Alpha two.')) expect(fetchBodies).not.toContain(slowChunkText) + const firstSrc = audio.src await act(async () => { - firstAudio.onended!() + audio.onended!() await new Promise((resolve) => setTimeout(resolve, 0)) }) @@ -293,9 +301,9 @@ describe('TTSProvider playback isolation', () => { await new Promise((resolve) => setTimeout(resolve, 0)) }) - await waitFor(() => expect(FakeAudio.instances.length).toBeGreaterThanOrEqual(2)) - const secondAudio = FakeAudio.instances[1] - await waitFor(() => expect(secondAudio.paused).toBe(false)) + await waitFor(() => expect(audio.src).not.toBe(firstSrc)) + await waitFor(() => expect(audio.play).toHaveBeenCalledTimes(2)) + expect(audio.paused).toBe(false) expect(fetchBodies.filter((text) => text === slowChunkText)).toHaveLength(1) @@ -319,10 +327,11 @@ describe('TTSProvider message completion', () => { await ttsRef.current!.speakMessage('A', textA, { onEnd }) }) + await waitFor(() => expect(FakeAudio.instances).toHaveLength(1)) + const audio = player() + for (let index = 0; index < 3; index += 1) { - await waitFor(() => expect(FakeAudio.instances.length).toBeGreaterThan(index)) - const audio = FakeAudio.instances[index] - await waitFor(() => expect(audio.paused).toBe(false)) + await waitFor(() => expect(audio.play).toHaveBeenCalledTimes(index + 1)) expect(onEnd).not.toHaveBeenCalled() await act(async () => { audio.onended!() @@ -330,7 +339,7 @@ describe('TTSProvider message completion', () => { } await waitFor(() => expect(onEnd).toHaveBeenCalledTimes(1)) - expect(onEnd).toHaveBeenCalledWith('completed') + expect(onEnd).toHaveBeenCalledWith('completed', undefined) expect(ttsRef.current!.state).toBe('idle') }) @@ -339,21 +348,15 @@ describe('TTSProvider message completion', () => { renderProvider() const onEnd = vi.fn() - await act(async () => { - await ttsRef.current!.speakMessage('A', textA, { onEnd }) - }) - - await waitFor(() => expect(FakeAudio.instances.length).toBeGreaterThanOrEqual(1)) - const firstAudio = FakeAudio.instances[0] - await waitFor(() => expect(firstAudio.paused).toBe(false)) - const staleOnended = firstAudio.onended + const audio = await startPlayback('A', textA, { onEnd }) + const staleOnended = audio.onended await act(async () => { ttsRef.current!.stop() }) expect(onEnd).toHaveBeenCalledTimes(1) - expect(onEnd).toHaveBeenCalledWith('stopped') + expect(onEnd).toHaveBeenCalledWith('stopped', undefined) await act(async () => { staleOnended!() @@ -369,21 +372,15 @@ describe('TTSProvider message completion', () => { const onEndA = vi.fn() const onEndB = vi.fn() - await act(async () => { - await ttsRef.current!.speakMessage('A', textA, { onEnd: onEndA }) - }) - - await waitFor(() => expect(FakeAudio.instances.length).toBeGreaterThanOrEqual(1)) - const firstAudio = FakeAudio.instances[0] - await waitFor(() => expect(firstAudio.paused).toBe(false)) - const staleOnended = firstAudio.onended + const audio = await startPlayback('A', textA, { onEnd: onEndA }) + const staleOnended = audio.onended await act(async () => { await ttsRef.current!.speakMessage('B', textB, { onEnd: onEndB }) }) expect(onEndA).toHaveBeenCalledTimes(1) - expect(onEndA).toHaveBeenCalledWith('stopped') + expect(onEndA).toHaveBeenCalledWith('stopped', undefined) expect(onEndB).not.toHaveBeenCalled() await act(async () => { @@ -400,13 +397,7 @@ describe('TTSProvider message completion', () => { renderProvider() const onEnd = vi.fn() - await act(async () => { - await ttsRef.current!.speakMessage('A', textA, { onEnd }) - }) - - await waitFor(() => expect(FakeAudio.instances.length).toBeGreaterThanOrEqual(1)) - const firstAudio = FakeAudio.instances[0] - await waitFor(() => expect(firstAudio.paused).toBe(false)) + await startPlayback('A', textA, { onEnd }) await act(async () => { ttsRef.current!.pause() @@ -420,7 +411,7 @@ describe('TTSProvider message completion', () => { expect(ttsRef.current!.isPaused).toBe(false) expect(onEnd).toHaveBeenCalledTimes(1) - expect(onEnd).toHaveBeenCalledWith('stopped') + expect(onEnd).toHaveBeenCalledWith('stopped', undefined) }) }) @@ -429,14 +420,8 @@ describe('TTSProvider pause and resume', () => { setPreferences() renderProvider() - await act(async () => { - await ttsRef.current!.speakMessage('A', textA) - }) - - await waitFor(() => expect(FakeAudio.instances.length).toBeGreaterThanOrEqual(1)) - const firstAudio = FakeAudio.instances[0] - await waitFor(() => expect(firstAudio.paused).toBe(false)) - const instanceCount = FakeAudio.instances.length + const audio = await startPlayback('A', textA) + const firstSrc = audio.src await act(async () => { ttsRef.current!.pause() @@ -444,19 +429,20 @@ describe('TTSProvider pause and resume', () => { expect(ttsRef.current!.isPaused).toBe(true) expect(ttsRef.current!.isPlaying).toBe(true) - expect(firstAudio.pause).toHaveBeenCalled() - expect(firstAudio.paused).toBe(true) + expect(audio.pause).toHaveBeenCalled() + expect(audio.paused).toBe(true) - const playCallsWhilePaused = firstAudio.play.mock.calls.length + const playCallsWhilePaused = audio.play.mock.calls.length await act(async () => { ttsRef.current!.resume() }) expect(ttsRef.current!.isPaused).toBe(false) - expect(firstAudio.play.mock.calls.length).toBe(playCallsWhilePaused + 1) - expect(firstAudio.paused).toBe(false) - expect(FakeAudio.instances).toHaveLength(instanceCount) + expect(audio.play.mock.calls.length).toBe(playCallsWhilePaused + 1) + expect(audio.paused).toBe(false) + expect(audio.src).toBe(firstSrc) + expect(FakeAudio.instances).toHaveLength(1) expect(fetchBodies.filter((text) => text === 'Alpha one. Alpha two.')).toHaveLength(1) }) @@ -464,27 +450,23 @@ describe('TTSProvider pause and resume', () => { setPreferences() renderProvider() - await act(async () => { - await ttsRef.current!.speakMessage('A', textA) - }) - - await waitFor(() => expect(FakeAudio.instances.length).toBeGreaterThanOrEqual(1)) - const firstAudio = FakeAudio.instances[0] - await waitFor(() => expect(firstAudio.paused).toBe(false)) + const audio = await startPlayback('A', textA) + const firstSrc = audio.src await act(async () => { ttsRef.current!.pause() }) + const playCallsWhilePaused = audio.play.mock.calls.length + await act(async () => { - firstAudio.onended!() + audio.onended!() }) - await waitFor(() => expect(FakeAudio.instances.length).toBeGreaterThanOrEqual(2)) - const secondAudio = FakeAudio.instances[1] + await waitFor(() => expect(audio.src).not.toBe(firstSrc)) - expect(secondAudio.play).not.toHaveBeenCalled() - expect(secondAudio.paused).toBe(true) + expect(audio.play.mock.calls.length).toBe(playCallsWhilePaused) + expect(audio.paused).toBe(true) expect(ttsRef.current!.isPaused).toBe(true) expect(ttsRef.current!.activeMessageId).toBe('A') @@ -492,8 +474,8 @@ describe('TTSProvider pause and resume', () => { ttsRef.current!.resume() }) - expect(secondAudio.play).toHaveBeenCalledTimes(1) - expect(secondAudio.paused).toBe(false) + expect(audio.play.mock.calls.length).toBe(playCallsWhilePaused + 1) + expect(audio.paused).toBe(false) expect(ttsRef.current!.isPaused).toBe(false) }) @@ -537,6 +519,115 @@ describe('TTSProvider pause and resume', () => { }) }) +describe('TTSProvider playback failures', () => { + it('reports the browser blocking playback with its own message', async () => { + setPreferences() + renderProvider() + const onEnd = vi.fn() + FakeAudio.nextPlayRejection = Object.assign(new Error('play blocked'), { + name: 'NotAllowedError', + }) + + await act(async () => { + await ttsRef.current!.speakMessage('A', textA, { onEnd }) + }) + await flushPlayback() + + expect(onEnd).toHaveBeenCalledTimes(1) + expect(onEnd).toHaveBeenCalledWith('error', 'Audio playback was blocked by the browser') + expect(ttsRef.current!.state).toBe('error') + expect(ttsRef.current!.error).toBe('Audio playback was blocked by the browser') + + act(() => ttsRef.current!.unlock()) + + expect(player().src.startsWith('data:audio/wav;base64,')).toBe(true) + expect(player().play).toHaveBeenCalledTimes(2) + }) + + it('reports the rejection message for a playback failure that is not a gesture block', async () => { + setPreferences() + renderProvider() + const onEnd = vi.fn() + FakeAudio.nextPlayRejection = new Error('decoder gave up') + + await act(async () => { + await ttsRef.current!.speakMessage('A', textA, { onEnd }) + }) + await flushPlayback() + + expect(onEnd).toHaveBeenCalledWith('error', 'decoder gave up') + expect(ttsRef.current!.error).toBe('decoder gave up') + }) +}) + +describe('TTSProvider unlock', () => { + it('primes the shared element with a silent clip and reuses it for chunk playback', async () => { + setPreferences() + renderProvider() + + act(() => ttsRef.current!.unlock()) + + expect(FakeAudio.instances).toHaveLength(1) + const audio = player() + expect(audio.src.startsWith('data:audio/wav;base64,')).toBe(true) + expect(audio.play).toHaveBeenCalledTimes(1) + + await flushPlayback() + + expect(audio.src).toBe('') + expect(audio.paused).toBe(true) + + await act(async () => { + await ttsRef.current!.speakMessage('A', textA) + }) + await flushPlayback() + + expect(FakeAudio.instances).toHaveLength(1) + expect(audio.src).toMatch(/^blob:/) + expect(audio.play).toHaveBeenCalledTimes(2) + expect(audio.paused).toBe(false) + }) + + it('does nothing on a repeat call once the element is primed', async () => { + setPreferences() + renderProvider() + + act(() => ttsRef.current!.unlock()) + await flushPlayback() + const playCalls = player().play.mock.calls.length + + act(() => ttsRef.current!.unlock()) + + expect(player().play).toHaveBeenCalledTimes(playCalls) + expect(FakeAudio.instances).toHaveLength(1) + }) + + it('does not interrupt a message that is already playing', async () => { + setPreferences() + renderProvider() + + const audio = await startPlayback('A', textA) + const src = audio.src + + act(() => ttsRef.current!.unlock()) + + expect(audio.src).toBe(src) + expect(audio.play).toHaveBeenCalledTimes(1) + expect(audio.pause).not.toHaveBeenCalled() + expect(audio.paused).toBe(false) + expect(ttsRef.current!.isPlaying).toBe(true) + }) + + it('does not touch the shared element for builtin playback', async () => { + setPreferences({ provider: 'builtin' }) + renderProvider() + + act(() => ttsRef.current!.unlock()) + + expect(FakeAudio.instances).toHaveLength(0) + }) +}) + describe('TTSProvider message queue', () => { const QUEUE_PAUSE_MS = 600 const firstText = 'Alpha plays first.' @@ -561,8 +652,9 @@ describe('TTSProvider message queue', () => { await flushPlayback() expect(FakeAudio.instances).toHaveLength(1) - const firstAudio = FakeAudio.instances[0] - expect(firstAudio.paused).toBe(false) + const audio = player() + const firstSrc = audio.src + expect(audio.paused).toBe(false) expect(ttsRef.current!.activeMessageId).toBe('A') await act(async () => { @@ -570,17 +662,17 @@ describe('TTSProvider message queue', () => { }) await flushPlayback() - expect(FakeAudio.instances).toHaveLength(1) - expect(firstAudio.paused).toBe(false) + expect(audio.play).toHaveBeenCalledTimes(1) + expect(audio.src).toBe(firstSrc) + expect(audio.paused).toBe(false) expect(ttsRef.current!.activeMessageId).toBe('A') expect(ttsRef.current!.isPlaying).toBe(true) await act(async () => { - firstAudio.onended!() + audio.onended!() }) await flushPlayback() - expect(FakeAudio.instances).toHaveLength(1) expect(ttsRef.current!.isIdle).toBe(true) expect(ttsRef.current!.activeMessageId).toBeNull() @@ -589,15 +681,16 @@ describe('TTSProvider message queue', () => { }) await flushPlayback() - expect(FakeAudio.instances).toHaveLength(1) + expect(audio.play).toHaveBeenCalledTimes(1) await act(async () => { vi.advanceTimersByTime(1) }) await flushPlayback() - expect(FakeAudio.instances).toHaveLength(2) - expect(FakeAudio.instances[1].paused).toBe(false) + expect(audio.play).toHaveBeenCalledTimes(2) + expect(audio.paused).toBe(false) + expect(fetchBodies).toContain(queuedText) expect(ttsRef.current!.activeMessageId).toBe('B') expect(ttsRef.current!.isPlaying).toBe(true) }) @@ -611,13 +704,15 @@ describe('TTSProvider message queue', () => { }) await flushPlayback() + const audio = player() + await act(async () => { ttsRef.current!.queueMessage('B', queuedText) }) await flushPlayback() await act(async () => { - FakeAudio.instances[0].onended!() + audio.onended!() }) await flushPlayback() @@ -630,6 +725,7 @@ describe('TTSProvider message queue', () => { }) await flushPlayback() + expect(audio.play).toHaveBeenCalledTimes(1) expect(FakeAudio.instances).toHaveLength(1) expect(fetchBodies).not.toContain(queuedText) expect(ttsRef.current!.state).toBe('idle') @@ -645,6 +741,8 @@ describe('TTSProvider message queue', () => { }) await flushPlayback() + const audio = player() + await act(async () => { ttsRef.current!.queueMessage('B', queuedText) }) @@ -655,20 +753,20 @@ describe('TTSProvider message queue', () => { }) await flushPlayback() - expect(FakeAudio.instances).toHaveLength(2) - expect(FakeAudio.instances[0].paused).toBe(true) + expect(audio.play).toHaveBeenCalledTimes(2) expect(ttsRef.current!.activeMessageId).toBe('C') + expect(ttsRef.current!.isPlaying).toBe(true) await act(async () => { vi.advanceTimersByTime(1000) }) await flushPlayback() - expect(FakeAudio.instances).toHaveLength(2) + expect(audio.play).toHaveBeenCalledTimes(2) expect(fetchBodies).not.toContain(queuedText) await act(async () => { - FakeAudio.instances[1].onended!() + audio.onended!() }) await flushPlayback() @@ -677,7 +775,7 @@ describe('TTSProvider message queue', () => { }) await flushPlayback() - expect(FakeAudio.instances).toHaveLength(2) + expect(audio.play).toHaveBeenCalledTimes(2) expect(ttsRef.current!.state).toBe('idle') }) }) diff --git a/frontend/src/contexts/TTSContext.tsx b/frontend/src/contexts/TTSContext.tsx index fabc5d7d..03f0aa02 100644 --- a/frontend/src/contexts/TTSContext.tsx +++ b/frontend/src/contexts/TTSContext.tsx @@ -18,6 +18,9 @@ export { const SENTENCE_REGEX = /(?<=[.!?])\s+/ const SENTENCES_PER_CHUNK = 2 const QUEUE_PAUSE_MS = 600 +const PLAYBACK_BLOCKED_MESSAGE = 'Audio playback was blocked by the browser' +const SILENT_WAV_DATA_URI = + 'data:audio/wav;base64,UklGRsQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YaAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA' interface QueuedMessage { messageId: string @@ -25,7 +28,30 @@ interface QueuedMessage { } interface SpeechRequest { - onEnd?: (reason: TTSEndReason) => void + onEnd?: (reason: TTSEndReason, error?: string) => void +} + +/** + * Returns whether a rejection is the browser refusing playback outside a user gesture. + * + * @param error The rejection value from play(). + * @returns True for a NotAllowedError. + */ +function isNotAllowedError(error: unknown): boolean { + if (typeof error !== 'object' || error === null) return false + return (error as { name?: unknown }).name === 'NotAllowedError' +} + +/** + * Picks the message shown for a failed playback. + * + * @param error The rejection value from play(). + * @param fallback The message to use when the rejection carries none. + * @returns The message to surface to the user. + */ +function playbackErrorMessage(error: unknown, fallback: string): string { + if (isNotAllowedError(error)) return PLAYBACK_BLOCKED_MESSAGE + return error instanceof Error && error.message ? error.message : fallback } function splitIntoChunks(text: string): string[] { @@ -56,6 +82,8 @@ export function TTSProvider({ children }: TTSProviderProps) { const [isPaused, setIsPaused] = useState(false) const abortControllerRef = useRef(null) + const playerRef = useRef(null) + const unlockedRef = useRef(false) const audioRef = useRef(null) const playbackIdRef = useRef(0) const currentObjectUrlRef = useRef(null) @@ -92,6 +120,13 @@ export function TTSProvider({ children }: TTSProviderProps) { return webSpeechSynthRef.current; }, []); + const getPlayer = useCallback((): HTMLAudioElement => { + if (!playerRef.current) { + playerRef.current = new Audio() + } + return playerRef.current + }, []) + const cleanup = useCallback(() => { if (audioRef.current) { audioRef.current.onended = null @@ -121,16 +156,16 @@ export function TTSProvider({ children }: TTSProviderProps) { chunkIndexRef.current = 0 }, []) - const settleSpeechRequest = useCallback((reason: TTSEndReason) => { + const settleSpeechRequest = useCallback((reason: TTSEndReason, error?: string) => { const request = speechRequestRef.current speechRequestRef.current = null - request?.onEnd?.(reason) + request?.onEnd?.(reason, error) }, []) - const beginSpeechRequest = useCallback((onEnd?: (reason: TTSEndReason) => void) => { + const beginSpeechRequest = useCallback((onEnd?: (reason: TTSEndReason, error?: string) => void) => { const previous = speechRequestRef.current speechRequestRef.current = { onEnd } - previous?.onEnd?.('stopped') + previous?.onEnd?.('stopped', undefined) }, []) const clearAdvanceTimer = useCallback(() => { @@ -166,15 +201,18 @@ export function TTSProvider({ children }: TTSProviderProps) { resetPlayback() }, [clearQueue, resetPlayback, settleSpeechRequest]) - const failPlayback = useCallback(() => { + const failPlayback = useCallback((message: string) => { + cleanup() clearQueue() busyRef.current = false activeProviderRef.current = null pausedRef.current = false setIsPaused(false) setActiveMessageId(null) - settleSpeechRequest('error') - }, [clearQueue, settleSpeechRequest]) + setError(message) + setState('error') + settleSpeechRequest('error', message) + }, [cleanup, clearQueue, settleSpeechRequest]) const advanceQueue = useCallback((playbackId: number) => { if (playbackIdRef.current !== playbackId) return @@ -304,69 +342,53 @@ export function TTSProvider({ children }: TTSProviderProps) { const url = URL.createObjectURL(blob) currentObjectUrlRef.current = url - const audio = new Audio(url) - audioRef.current = audio + const player = getPlayer() + audioRef.current = player - audio.onended = () => { + player.onended = () => { if (playbackIdRef.current !== playbackId) return if (currentObjectUrlRef.current === url) { URL.revokeObjectURL(url) currentObjectUrlRef.current = null } - if (audioRef.current === audio) { + if (audioRef.current === player) { audioRef.current = null } playChunk(index + 1, playbackId) } - audio.onerror = () => { + player.onerror = () => { if (playbackIdRef.current !== playbackId) return - if (currentObjectUrlRef.current === url) { - URL.revokeObjectURL(url) - currentObjectUrlRef.current = null - } - if (audioRef.current === audio) { - audioRef.current = null - } - failPlayback() - setError('Audio playback failed') - setState('error') + failPlayback('Audio playback failed') } + player.src = url setState('playing') if (!pausedRef.current) { - await audio.play() + await player.play() } } catch (err) { if (playbackIdRef.current !== playbackId) return - failPlayback() - setError(err instanceof Error ? err.message : 'TTS failed') - setState('error') + failPlayback(playbackErrorMessage(err, 'TTS failed')) } - }, [getChunkAudio, prefetchChunk, advanceQueue, failPlayback, settleSpeechRequest]) + }, [getPlayer, getChunkAudio, prefetchChunk, advanceQueue, failPlayback, settleSpeechRequest]) // Builtin Web Speech synthesis - takes explicit config and optional messageId const speakBuiltinWithConfig = useCallback(async (text: string, config: TTSConfig, messageId: string | null = null): Promise => { if (!isWebSpeechSupported()) { - failPlayback() - setError('Web Speech API not supported in this browser') - setState('error') + failPlayback('Web Speech API not supported in this browser') return false } if (!text?.trim()) { - failPlayback() - setError('No text provided') - setState('error') + failPlayback('No text provided') return false } const sanitizedText = sanitizeForTTS(text) if (!sanitizedText?.trim()) { - failPlayback() - setError('No readable content after sanitization') - setState('error') + failPlayback('No readable content after sanitization') return false } @@ -396,9 +418,7 @@ export function TTSProvider({ children }: TTSProviderProps) { synth.onError((err) => { if (playbackIdRef.current !== playbackId) return - failPlayback() - setError(err) - setState('error') + failPlayback(err) }) try { @@ -418,9 +438,7 @@ export function TTSProvider({ children }: TTSProviderProps) { return true } catch (err) { if (playbackIdRef.current !== playbackId) return false - failPlayback() - setError(err instanceof Error ? err.message : 'TTS failed') - setState('error') + failPlayback(err instanceof Error && err.message ? err.message : 'TTS failed') return false } }, [resetPlayback, advanceQueue, failPlayback, getSynthesizer, settleSpeechRequest]) @@ -451,9 +469,7 @@ export function TTSProvider({ children }: TTSProviderProps) { const playWithConfig = useCallback(async (text: string, config: TTSConfig, messageId: string | null = null): Promise => { if (!config.enabled) { - failPlayback() - setError('TTS is not enabled') - setState('error') + failPlayback('TTS is not enabled') return false } @@ -461,34 +477,26 @@ export function TTSProvider({ children }: TTSProviderProps) { if (configIsBuiltin) { if (!isWebSpeechSupported()) { - failPlayback() - setError('Web Speech API not supported in this browser') - setState('error') + failPlayback('Web Speech API not supported in this browser') return false } return speakBuiltinWithConfig(text, config, messageId) } if (!config.apiKey) { - failPlayback() - setError('API key not configured') - setState('error') + failPlayback('API key not configured') return false } if (!config.voice || !config.model) { - failPlayback() - setError('Voice or model not configured') - setState('error') + failPlayback('Voice or model not configured') return false } const sanitizedText = sanitizeForTTS(text) if (!sanitizedText?.trim()) { - failPlayback() - setError('No readable content after sanitization') - setState('error') + failPlayback('No readable content after sanitization') return false } @@ -513,9 +521,7 @@ export function TTSProvider({ children }: TTSProviderProps) { const config = buildStoredConfig() if (!config) { - failPlayback() - setError('TTS is not configured') - setState('error') + failPlayback('TTS is not configured') return false } @@ -549,9 +555,7 @@ export function TTSProvider({ children }: TTSProviderProps) { const config = buildStoredConfig() if (!config) { - failPlayback() - setError('TTS is not configured') - setState('error') + failPlayback('TTS is not configured') return false } @@ -589,12 +593,30 @@ export function TTSProvider({ children }: TTSProviderProps) { if (!audio) return void audio.play().catch((err: unknown) => { - failPlayback() - setError(err instanceof Error ? err.message : 'TTS failed') - setState('error') + failPlayback(playbackErrorMessage(err, 'TTS failed')) }) }, [getSynthesizer, failPlayback]) + const unlock = useCallback(() => { + if (isBuiltin) return + if (unlockedRef.current) return + if (audioRef.current || busyRef.current) return + + const player = getPlayer() + player.onended = null + player.onerror = null + player.src = SILENT_WAV_DATA_URI + + void player.play().then(() => { + unlockedRef.current = true + if (audioRef.current !== null) return + if (player.src !== SILENT_WAV_DATA_URI) return + player.pause() + player.removeAttribute('src') + player.load() + }).catch(() => {}) + }, [isBuiltin, getPlayer]) + const queueMessage = useCallback((messageId: string, text: string) => { if (messageId === activeMessageId || queueRef.current.some((item) => item.messageId === messageId)) { return @@ -616,6 +638,7 @@ export function TTSProvider({ children }: TTSProviderProps) { stop, pause, resume, + unlock, state, error, currentText, diff --git a/frontend/src/contexts/tts-context.ts b/frontend/src/contexts/tts-context.ts index dd90f134..6921c030 100644 --- a/frontend/src/contexts/tts-context.ts +++ b/frontend/src/contexts/tts-context.ts @@ -5,7 +5,7 @@ export type TTSState = 'idle' | 'loading' | 'playing' | 'error' export type TTSEndReason = 'completed' | 'stopped' | 'error' export interface SpeakMessageOptions { - onEnd?: (reason: TTSEndReason) => void + onEnd?: (reason: TTSEndReason, error?: string) => void } export interface TTSConfig { @@ -23,6 +23,14 @@ export interface TTSContextValue { speakWithConfig: (text: string, config: TTSConfig) => Promise speakMessage: (messageId: string, text: string, options?: SpeakMessageOptions) => Promise queueMessage: (messageId: string, text: string) => void + /** + * Primes the shared audio element inside a user gesture so a reply that + * arrives later is allowed to start playing. Must be called synchronously from + * the gesture handler. Does nothing while audio is already in use or once the + * element is primed, and does nothing for the builtin Web Speech provider, + * which keeps its own gesture requirement. + */ + unlock: () => void stop: () => void pause: () => void resume: () => void diff --git a/frontend/src/hooks/useVoiceConversation.test.tsx b/frontend/src/hooks/useVoiceConversation.test.tsx index 7aa35ea8..f4c8c1fa 100644 --- a/frontend/src/hooks/useVoiceConversation.test.tsx +++ b/frontend/src/hooks/useVoiceConversation.test.tsx @@ -39,6 +39,7 @@ const harness = vi.hoisted(() => ({ abortRecording: vi.fn(), speakMessage: vi.fn(), ttsStop: vi.fn(), + ttsUnlock: vi.fn(), ttsPause: vi.fn(), ttsResume: vi.fn(), sendTurn: vi.fn(), @@ -80,6 +81,7 @@ const ttsValue = { error: null as string | null, speakMessage: harness.speakMessage, stop: harness.ttsStop, + unlock: harness.ttsUnlock, pause: harness.ttsPause, resume: harness.ttsResume, } @@ -118,9 +120,9 @@ async function endOfSpeech(reason: SttEndOfSpeechReason, finalText: string) { }) } -function speechEndHandler(callIndex = 0): (reason: TTSEndReason) => void { +function speechEndHandler(callIndex = 0): (reason: TTSEndReason, error?: string) => void { const options = harness.speakMessage.mock.calls[callIndex]?.[2] as - | { onEnd?: (reason: TTSEndReason) => void } + | { onEnd?: (reason: TTSEndReason, error?: string) => void } | undefined if (!options?.onEnd) throw new Error('speakMessage was not called with an onEnd handler') return options.onEnd @@ -202,6 +204,7 @@ describe('useVoiceConversation', () => { await waitFor(() => expect(result.current.phase).toBe('listening')) expect(result.current.isActive).toBe(true) + expect(harness.ttsUnlock).toHaveBeenCalledTimes(1) expect(result.current.label).toBe('Listening') expect(harness.startRecording).toHaveBeenCalledTimes(1) expect(lastStartOptions().endpointing).toEqual({ pauseMs: 1200, noSpeechTimeoutMs: 10_000 }) @@ -283,6 +286,7 @@ describe('useVoiceConversation', () => { act(() => result.current.tapOrb()) await waitFor(() => expect(result.current.phase).toBe('recording')) + expect(harness.ttsUnlock).toHaveBeenCalledTimes(2) expect(harness.startRecording).toHaveBeenCalledTimes(1) expect(result.current.label).toBe('Adding to queue') @@ -546,12 +550,34 @@ describe('useVoiceConversation', () => { rerender(createProps({ messages: [assistantMessage('msg_1', 'Done')] })) await waitFor(() => expect(result.current.phase).toBe('speaking')) + act(() => speechEndHandler(0)('error', 'Audio playback was blocked by the browser')) + + expect(result.current.phase).toBe('paused') + expect(result.current.label).toBe( + 'Reading the reply failed: Audio playback was blocked by the browser', + ) + expect(result.current.hint).toBe('Tap to retry') + expect(harness.startRecording).toHaveBeenCalledTimes(1) + }) + + it('keeps the failure label plain when the player reports no detail', async () => { + const { result, rerender } = renderHook( + (props: UseVoiceConversationInput) => useVoiceConversation(props), + { initialProps: createProps() }, + ) + + act(() => result.current.start()) + await waitFor(() => expect(result.current.phase).toBe('listening')) + await endOfSpeech('pause', 'hello there') + await waitFor(() => expect(result.current.phase).toBe('working')) + + rerender(createProps({ messages: [assistantMessage('msg_1', 'Done')] })) + await waitFor(() => expect(result.current.phase).toBe('speaking')) + act(() => speechEndHandler(0)('error')) expect(result.current.phase).toBe('paused') expect(result.current.label).toBe('Reading the reply failed') - expect(result.current.hint).toBe('Tap to retry') - expect(harness.startRecording).toHaveBeenCalledTimes(1) }) it('marks a reply with nothing to read as heard and listens again', async () => { diff --git a/frontend/src/hooks/useVoiceConversation.ts b/frontend/src/hooks/useVoiceConversation.ts index 13ea4c8e..8abfde98 100644 --- a/frontend/src/hooks/useVoiceConversation.ts +++ b/frontend/src/hooks/useVoiceConversation.ts @@ -543,12 +543,16 @@ export function useVoiceConversation( speakingIdRef.current = message.id spokenIdsRef.current.add(message.id) void latestRef.current.tts.speakMessage(message.id, message.text, { - onEnd: (reason) => { + onEnd: (reason, error) => { if (speakTokenRef.current !== token) return if (reason === 'error') { speakTokenRef.current += 1 speakingIdRef.current = null - dispatch({ type: 'error', message: REPLY_READ_FAILED_MESSAGE, source: 'playback' }) + dispatch({ + type: 'error', + message: error ? `${REPLY_READ_FAILED_MESSAGE}: ${error}` : REPLY_READ_FAILED_MESSAGE, + source: 'playback', + }) return } speakingIdRef.current = null @@ -706,6 +710,7 @@ export function useVoiceConversation( } const latest = latestRef.current if (latest.tts.isPlaying) latest.tts.stop() + latest.tts.unlock() fireImpactHaptic() invalidateTurn() instructionEpochRef.current += 1 @@ -851,6 +856,7 @@ export function useVoiceConversation( const tapOrb = useCallback(() => { const phase = phaseRef.current const latest = latestRef.current + latest.tts.unlock() switch (phase) { case 'listening': void endTurnRef.current?.()