diff --git a/frontend/src/contexts/TTSContext.test.tsx b/frontend/src/contexts/TTSContext.test.tsx new file mode 100644 index 00000000..8c3a78d5 --- /dev/null +++ b/frontend/src/contexts/TTSContext.test.tsx @@ -0,0 +1,296 @@ +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 { WebSpeechSynthesizer } from '@/lib/webSpeechSynthesizer' + +const mocks = vi.hoisted(() => ({ + useSettings: vi.fn(), +})) + +const webSpeech = vi.hoisted(() => ({ + stop: vi.fn(), + clearCallbacks: vi.fn(), + waitForVoices: vi.fn(() => Promise.resolve()), + onEnd: vi.fn(), + onError: vi.fn(), + speakChunked: vi.fn(() => Promise.resolve()), +})) + +vi.mock('@/hooks/useSettings', () => ({ + useSettings: mocks.useSettings, +})) + +vi.mock('@/lib/webSpeechSynthesizer', () => ({ + getWebSpeechSynthesizer: () => webSpeech as unknown as WebSpeechSynthesizer, + isWebSpeechSupported: () => true, +})) + +class FakeAudio { + static instances: FakeAudio[] = [] + + src: string + paused = true + onended: (() => void) | null = null + onerror: (() => void) | null = null + + constructor(src: string) { + this.src = src + FakeAudio.instances.push(this) + } + + play = vi.fn(() => { + this.paused = false + return Promise.resolve() + }) + + pause = vi.fn(() => { + this.paused = true + }) + + load = vi.fn() + + removeAttribute = vi.fn((name: string) => { + if (name === 'src') this.src = '' + }) +} + +const ttsRef: { current: TTSContextValue | null } = { current: null } + +function Consumer() { + ttsRef.current = useTTS() + return null +} + +let fetchBodies: string[] = [] +let objectUrlCounter = 0 + +const createObjectURL = vi.fn(() => `blob:fake-${++objectUrlCounter}`) +const revokeObjectURL = vi.fn() + +const textA = 'Alpha one. Alpha two. Alpha three. Alpha four. Alpha five.' +const textB = 'Bravo one. Bravo two. Bravo three. Bravo four. Bravo five.' + +function setPreferences(overrides: Partial = {}) { + mocks.useSettings.mockReturnValue({ + preferences: { + tts: { + enabled: true, + autoPlay: false, + provider: 'external', + endpoint: 'https://api.openai.com', + apiKey: 'test-key', + voice: 'alloy', + model: 'tts-1', + speed: 1.0, + ...overrides, + }, + }, + updateSettings: vi.fn(), + }) +} + +const externalConfig: TTSConfig = { + enabled: true, + provider: 'external', + endpoint: 'https://api.openai.com', + apiKey: 'test-key', + voice: 'alloy', + model: 'tts-1', + speed: 1.0, +} + +const builtinConfig: TTSConfig = { + enabled: true, + provider: 'builtin', + endpoint: '', + apiKey: '', + voice: '', + model: '', + speed: 1.0, +} + +function renderProvider() { + return render( + + + , + ) +} + +beforeEach(() => { + vi.clearAllMocks() + FakeAudio.instances = [] + fetchBodies = [] + objectUrlCounter = 0 + ttsRef.current = null + + const fetchMock = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => { + const body = JSON.parse(String(init?.body ?? '{}')) as { text: string } + fetchBodies.push(body.text) + const blob = new Blob([`audio:${body.text}`], { type: 'audio/mpeg' }) + return { + ok: true, + status: 200, + headers: { + get: (name: string) => (name.toLowerCase() === 'content-type' ? 'audio/mpeg' : null), + }, + blob: async () => blob, + json: async () => ({}), + } as unknown as Response + }) + + vi.stubGlobal('Audio', FakeAudio) + vi.stubGlobal('fetch', fetchMock) + URL.createObjectURL = createObjectURL + URL.revokeObjectURL = revokeObjectURL +}) + +afterEach(() => { + vi.unstubAllGlobals() +}) + +describe('TTSProvider playback isolation', () => { + it('does not start a concurrent chain when a stale onended fires after a new playback begins', 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 staleOnended = firstAudio.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 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) + }) + + 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 + 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 act(async () => { + staleOnerror!() + }) + + expect(ttsRef.current!.state).toBe('playing') + expect(ttsRef.current!.error).toBeNull() + expect(secondAudio.paused).toBe(false) + }) + + it('cancels active Web Speech playback when an external playback starts', async () => { + setPreferences({ provider: 'external' }) + renderProvider() + + await act(async () => { + await ttsRef.current!.speakWithConfig('Hello from web speech.', builtinConfig) + }) + + expect(webSpeech.speakChunked).toHaveBeenCalled() + webSpeech.stop.mockClear() + + await act(async () => { + await ttsRef.current!.speakWithConfig('Now external audio.', externalConfig) + }) + + expect(webSpeech.stop).toHaveBeenCalled() + }) + + it('fetches each chunk at most once when playback outruns an in-flight prefetch', async () => { + setPreferences() + renderProvider() + + const slowChunkText = 'Alpha three. Alpha four.' + let releaseSlowChunk: () => void = () => {} + const slowChunkGate = new Promise((resolve) => { + releaseSlowChunk = resolve + }) + + const baseFetch = globalThis.fetch + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const body = JSON.parse(String(init?.body ?? '{}')) as { text: string } + if (body.text === slowChunkText) { + await slowChunkGate + } + return baseFetch(input, init) + }), + ) + + 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)) + await waitFor(() => expect(fetchBodies).toContain('Alpha one. Alpha two.')) + expect(fetchBodies).not.toContain(slowChunkText) + + await act(async () => { + firstAudio.onended!() + await new Promise((resolve) => setTimeout(resolve, 0)) + }) + + await act(async () => { + releaseSlowChunk() + 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)) + + expect(fetchBodies.filter((text) => text === slowChunkText)).toHaveLength(1) + + const fetchCounts = new Map() + for (const text of fetchBodies) { + fetchCounts.set(text, (fetchCounts.get(text) ?? 0) + 1) + } + for (const count of fetchCounts.values()) { + expect(count).toBe(1) + } + }) +}) diff --git a/frontend/src/contexts/TTSContext.tsx b/frontend/src/contexts/TTSContext.tsx index d5d814fd..31dd42a9 100644 --- a/frontend/src/contexts/TTSContext.tsx +++ b/frontend/src/contexts/TTSContext.tsx @@ -37,11 +37,11 @@ export function TTSProvider({ children }: TTSProviderProps) { const abortControllerRef = useRef(null) const audioRef = useRef(null) - const stoppedRef = useRef(false) + const playbackIdRef = useRef(0) + const currentObjectUrlRef = useRef(null) const chunksRef = useRef([]) const chunkIndexRef = useRef(0) - const prefetchedBlobsRef = useRef>(new Map()) - const fetchingIndexRef = useRef(-1) + const chunkAudioRef = useRef>>(new Map()) // Web Speech API reference const webSpeechSynthRef = useRef | null>(null) @@ -66,34 +66,36 @@ export function TTSProvider({ children }: TTSProviderProps) { }, []); const cleanup = useCallback(() => { - // Stop external audio if (audioRef.current) { + audioRef.current.onended = null + audioRef.current.onerror = null audioRef.current.pause() - audioRef.current.src = '' + audioRef.current.removeAttribute('src') + audioRef.current.load() audioRef.current = null } - - // Stop Web Speech API - if (webSpeechSynthRef.current && isBuiltin) { + + if (currentObjectUrlRef.current) { + URL.revokeObjectURL(currentObjectUrlRef.current) + currentObjectUrlRef.current = null + } + + if (webSpeechSynthRef.current) { webSpeechSynthRef.current.stop() webSpeechSynthRef.current.clearCallbacks() } - + if (abortControllerRef.current) { abortControllerRef.current.abort() abortControllerRef.current = null } - prefetchedBlobsRef.current.forEach((_, key) => { - prefetchedBlobsRef.current.delete(key) - }) - prefetchedBlobsRef.current.clear() + chunkAudioRef.current.clear() chunksRef.current = [] chunkIndexRef.current = 0 - fetchingIndexRef.current = -1 - }, [isBuiltin]) + }, []) const stop = useCallback(() => { - stoppedRef.current = true + playbackIdRef.current += 1 cleanup() setState('idle') setCurrentText(null) @@ -104,14 +106,14 @@ export function TTSProvider({ children }: TTSProviderProps) { useEffect(() => { return () => { - stoppedRef.current = true + playbackIdRef.current += 1 cleanup() } }, [cleanup]) // External API synthesis - const synthesizeExternal = useCallback(async (text: string, signal?: AbortSignal): Promise => { - if (stoppedRef.current) return null + const synthesizeExternal = useCallback(async (text: string, signal: AbortSignal | undefined, playbackId: number): Promise => { + if (playbackIdRef.current !== playbackId) return null try { const response = await fetch(`${API_BASE_URL}/api/tts/synthesize`, { @@ -121,7 +123,7 @@ export function TTSProvider({ children }: TTSProviderProps) { signal, }) - if (stoppedRef.current) return null + if (playbackIdRef.current !== playbackId) return null if (!response.ok) { let errorMessage = 'TTS request failed' @@ -155,32 +157,31 @@ export function TTSProvider({ children }: TTSProviderProps) { } }, []) - const fetchNextChunk = useCallback(async (index: number) => { - if (stoppedRef.current) return - if (index >= chunksRef.current.length) return - if (prefetchedBlobsRef.current.has(index)) { - fetchNextChunk(index + 1) - return - } - - fetchingIndexRef.current = index - - try { - const blob = await synthesizeExternal(chunksRef.current[index], abortControllerRef.current?.signal) - if (blob && !stoppedRef.current) { - prefetchedBlobsRef.current.set(index, blob) - fetchNextChunk(index + 1) - } - } catch { - if (stoppedRef.current) return - } - - fetchingIndexRef.current = -1 + const getChunkAudio = useCallback((index: number, playbackId: number): Promise => { + const existing = chunkAudioRef.current.get(index) + if (existing) return existing + + const promise = synthesizeExternal(chunksRef.current[index], abortControllerRef.current?.signal, playbackId) + chunkAudioRef.current.set(index, promise) + return promise }, [synthesizeExternal]) - const playChunk = useCallback(async (index: number) => { - if (stoppedRef.current || index >= chunksRef.current.length) { - if (!stoppedRef.current) { + const prefetchChunk = useCallback((index: number, playbackId: number) => { + if (playbackIdRef.current !== playbackId) return + if (index >= chunksRef.current.length) return + if (chunkAudioRef.current.has(index)) return + + getChunkAudio(index, playbackId) + .then((blob) => { + if (!blob || playbackIdRef.current !== playbackId) return + prefetchChunk(index + 1, playbackId) + }) + .catch(() => {}) + }, [getChunkAudio]) + + const playChunk = useCallback(async (index: number, playbackId: number) => { + if (playbackIdRef.current !== playbackId || index >= chunksRef.current.length) { + if (playbackIdRef.current === playbackId) { setState('idle') setCurrentText(null) setActiveMessageId(null) @@ -191,50 +192,54 @@ export function TTSProvider({ children }: TTSProviderProps) { chunkIndexRef.current = index try { - let blob: Blob | undefined = prefetchedBlobsRef.current.get(index) - - if (!blob) { + if (!chunkAudioRef.current.has(index)) { setState('loading') - const fetched = await synthesizeExternal(chunksRef.current[index], abortControllerRef.current?.signal) - if (fetched && !stoppedRef.current) { - blob = fetched - } - fetchNextChunk(index + 1) } - - if (!blob || stoppedRef.current) return - prefetchedBlobsRef.current.delete(index) - + const blob = await getChunkAudio(index, playbackId) + if (!blob || playbackIdRef.current !== playbackId) return + + chunkAudioRef.current.delete(index) + prefetchChunk(index + 1, playbackId) + const url = URL.createObjectURL(blob) + currentObjectUrlRef.current = url const audio = new Audio(url) audioRef.current = audio audio.onended = () => { - URL.revokeObjectURL(url) - audioRef.current = null - if (!stoppedRef.current) { - playChunk(index + 1) + if (playbackIdRef.current !== playbackId) return + if (currentObjectUrlRef.current === url) { + URL.revokeObjectURL(url) + currentObjectUrlRef.current = null } + if (audioRef.current === audio) { + audioRef.current = null + } + playChunk(index + 1, playbackId) } audio.onerror = () => { - URL.revokeObjectURL(url) - audioRef.current = null - if (!stoppedRef.current) { - setError('Audio playback failed') - setState('error') + if (playbackIdRef.current !== playbackId) return + if (currentObjectUrlRef.current === url) { + URL.revokeObjectURL(url) + currentObjectUrlRef.current = null } + if (audioRef.current === audio) { + audioRef.current = null + } + setError('Audio playback failed') + setState('error') } setState('playing') await audio.play() } catch (err) { - if (stoppedRef.current) return + if (playbackIdRef.current !== playbackId) return setError(err instanceof Error ? err.message : 'TTS failed') setState('error') } - }, [synthesizeExternal, fetchNextChunk]) + }, [getChunkAudio, prefetchChunk]) // Builtin Web Speech synthesis - takes explicit config and optional messageId const speakBuiltinWithConfig = useCallback(async (text: string, config: TTSConfig, messageId: string | null = null): Promise => { @@ -259,7 +264,7 @@ export function TTSProvider({ children }: TTSProviderProps) { } stop() - stoppedRef.current = false + const playbackId = playbackIdRef.current setError(null) setOriginalText(text) @@ -274,38 +279,38 @@ export function TTSProvider({ children }: TTSProviderProps) { const synth = getSynthesizer() await synth.waitForVoices() + if (playbackIdRef.current !== playbackId) return false + const voiceName = config.voice || '' - + synth.clearCallbacks() - + synth.onEnd(() => { - if (!stoppedRef.current) { - setState('idle') - setCurrentText(null) - setActiveMessageId(null) - } + if (playbackIdRef.current !== playbackId) return + setState('idle') + setCurrentText(null) + setActiveMessageId(null) }) synth.onError((err) => { - if (!stoppedRef.current) { - setError(err) - setState('error') - } + if (playbackIdRef.current !== playbackId) return + setError(err) + setState('error') }) try { setState('playing') - + const rate = config.speed || 1.0 - + await synth.speakChunked(sanitizedText, 200, { voice: voiceName || undefined, rate: rate, }) - + return true } catch (err) { - if (stoppedRef.current) return false + if (playbackIdRef.current !== playbackId) return false setError(err instanceof Error ? err.message : 'TTS failed') setState('error') return false @@ -315,7 +320,7 @@ export function TTSProvider({ children }: TTSProviderProps) { // Internal helper to start external TTS playback const startExternalPlayback = useCallback((sanitizedText: string, original: string, messageId: string | null): boolean => { stop() - stoppedRef.current = false + const playbackId = playbackIdRef.current setError(null) setOriginalText(original) @@ -328,9 +333,9 @@ export function TTSProvider({ children }: TTSProviderProps) { abortControllerRef.current = new AbortController() chunksRef.current = splitIntoChunks(sanitizedText) - - playChunk(0) - + + playChunk(0, playbackId) + return true }, [stop, playChunk])