Merge pull request #416 from chriswritescode-dev/fix/tts-overlap-and-cache-race

fix(tts): prevent overlapping playback and corrupted audio cache
This commit is contained in:
Chris Scott authored and GitHub committed 2026-10-11 00:19:15 -04:00
commit 51e92d8cf2
9 files changed
+1145 -167

No files matched your search

+10
View File
@@ -11,6 +11,10 @@ export interface TTSVoicesResponse {
cached: boolean
}
export interface TTSClearCacheResponse {
cleared: number
}
export interface TTSStatusResponse {
enabled: boolean
configured: boolean
@@ -42,6 +46,12 @@ export const ttsApi = {
})
},
clearCache: async (): Promise<TTSClearCacheResponse> => {
return fetchWrapper(`${API_BASE_URL}/api/tts/cache`, {
method: 'DELETE',
})
},
synthesize: async (text: string, userId = 'default', signal?: AbortSignal): Promise<Blob> => {
return fetchWrapperBlob(`${API_BASE_URL}/api/tts/synthesize`, {
method: 'POST',
@@ -0,0 +1,181 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { ReactNode } from 'react'
import { TTSSettings } from './TTSSettings'
import { useSettings } from '@/hooks/useSettings'
import { useTTS } from '@/hooks/useTTS'
import { useTTSModels, useTTSVoices, useTTSDiscovery } from '@/hooks/useTTSDiscovery'
import { getAvailableVoiceNames, isWebSpeechSupported } from '@/lib/webSpeechSynthesizer'
import { createUseSettingsMock } from '@/test/test-utils'
import type { UserPreferences } from '@/api/types/settings'
vi.mock('@/hooks/useSettings')
vi.mock('@/hooks/useTTS')
vi.mock('@/hooks/useTTSDiscovery')
vi.mock('@/lib/webSpeechSynthesizer')
const fetchMock = vi.fn()
const baseTts: NonNullable<UserPreferences['tts']> = {
enabled: true,
provider: 'external',
autoPlay: false,
endpoint: 'https://api.openai.com',
apiKey: 'sk-test',
voice: 'alloy',
model: 'tts-1',
speed: 1,
availableVoices: [],
availableModels: [],
lastVoicesFetch: 0,
lastModelsFetch: 0,
}
function buildPreferences(overrides: Partial<UserPreferences> = {}): UserPreferences {
return {
theme: 'dark',
mode: 'build',
autoScroll: true,
expandDiffs: true,
expandToolCalls: false,
showReasoning: false,
simpleChatMode: false,
keyboardShortcuts: {},
customCommands: [],
tts: baseTts,
...overrides,
}
}
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
})
}
function renderTTSSettings() {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
})
function Wrapper({ children }: { children: ReactNode }) {
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
}
return render(<TTSSettings />, { wrapper: Wrapper })
}
function mockHooks(preferences: UserPreferences = buildPreferences()) {
vi.mocked(useSettings).mockReturnValue(createUseSettingsMock({ preferences }))
vi.mocked(useTTS).mockReturnValue({
speak: vi.fn(),
speakWithConfig: vi.fn(),
speakMessage: vi.fn(),
stop: vi.fn(),
state: 'idle',
error: null,
currentText: null,
originalText: null,
activeMessageId: null,
isEnabled: true,
isPlaying: false,
isLoading: false,
isIdle: true,
})
vi.mocked(useTTSDiscovery).mockReturnValue({
refreshModels: vi.fn(),
refreshVoices: vi.fn(),
refreshAll: vi.fn(),
invalidateModels: vi.fn(),
invalidateVoices: vi.fn(),
invalidateAll: vi.fn(),
})
vi.mocked(useTTSModels).mockReturnValue({
data: undefined,
isLoading: false,
refetch: vi.fn(),
} as unknown as ReturnType<typeof useTTSModels>)
vi.mocked(useTTSVoices).mockReturnValue({
data: undefined,
isLoading: false,
refetch: vi.fn(),
} as unknown as ReturnType<typeof useTTSVoices>)
vi.mocked(isWebSpeechSupported).mockReturnValue(true)
vi.mocked(getAvailableVoiceNames).mockResolvedValue(['Alex'])
}
describe('TTSSettings audio cache', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.stubGlobal('fetch', fetchMock)
mockHooks()
})
afterEach(() => {
vi.unstubAllGlobals()
})
it('clears the server cache via DELETE /api/tts/cache and reports the count', async () => {
const user = userEvent.setup()
fetchMock.mockResolvedValueOnce(jsonResponse({ cleared: 3 }))
renderTTSSettings()
await user.click(screen.getByRole('button', { name: 'Clear audio cache' }))
expect(await screen.findByRole('status')).toHaveTextContent('Cleared 3 cached audio file(s).')
const [url, options] = fetchMock.mock.calls[0] as [string, RequestInit]
expect(String(url)).toContain('/api/tts/cache')
expect(options).toMatchObject({ method: 'DELETE' })
})
it('disables the button and shows a pending label while clearing', async () => {
const user = userEvent.setup()
let resolveResponse: (response: Response) => void = () => {}
fetchMock.mockReturnValueOnce(
new Promise<Response>((resolve) => {
resolveResponse = resolve
}),
)
renderTTSSettings()
await user.click(screen.getByRole('button', { name: 'Clear audio cache' }))
const pendingButton = screen.getByRole('button', { name: /clearing/i })
expect(pendingButton).toBeDisabled()
resolveResponse(jsonResponse({ cleared: 1 }))
expect(await screen.findByRole('status')).toHaveTextContent('Cleared 1 cached audio file(s).')
})
it('shows an actionable error and allows retrying after a failure', async () => {
const user = userEvent.setup()
fetchMock
.mockResolvedValueOnce(jsonResponse({ error: 'cache unavailable' }, 500))
.mockResolvedValueOnce(jsonResponse({ cleared: 2 }))
renderTTSSettings()
await user.click(screen.getByRole('button', { name: 'Clear audio cache' }))
expect(await screen.findByRole('alert')).toHaveTextContent('cache unavailable')
const retryButton = screen.getByRole('button', { name: 'Clear audio cache' })
expect(retryButton).toBeEnabled()
await user.click(retryButton)
expect(await screen.findByRole('status')).toHaveTextContent('Cleared 2 cached audio file(s).')
expect(fetchMock).toHaveBeenCalledTimes(2)
})
it('stays available when TTS is disabled or the builtin provider is selected', async () => {
mockHooks(buildPreferences({ tts: { ...baseTts, enabled: false } }))
const disabledRender = renderTTSSettings()
expect(screen.getByRole('button', { name: 'Clear audio cache' })).toBeInTheDocument()
disabledRender.unmount()
mockHooks(buildPreferences({ tts: { ...baseTts, provider: 'builtin', voice: 'Alex' } }))
renderTTSSettings()
expect(screen.getByRole('button', { name: 'Clear audio cache' })).toBeInTheDocument()
expect(await screen.findByText('1 voices available in your browser')).toBeInTheDocument()
})
})
@@ -1,12 +1,13 @@
import { useEffect, useState, useRef } from 'react'
import { useForm } from 'react-hook-form'
import { useMutation } from '@tanstack/react-query'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { useSettings } from '@/hooks/useSettings'
import { useTTS } from '@/hooks/useTTS'
import { useTTSModels, useTTSVoices, useTTSDiscovery } from '@/hooks/useTTSDiscovery'
import { getAvailableVoiceNames, isWebSpeechSupported } from '@/lib/webSpeechSynthesizer'
import { Loader2, Volume2, XCircle, RefreshCw, MonitorSpeaker, Globe, CheckCircle2 } from 'lucide-react'
import { Loader2, Volume2, XCircle, RefreshCw, MonitorSpeaker, Globe, CheckCircle2, Trash2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { SquareFill } from '@/components/ui/square-fill'
import { Input } from '@/components/ui/input'
@@ -14,6 +15,7 @@ import { Switch } from '@/components/ui/switch'
import { Slider } from '@/components/ui/slider'
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form'
import { Combobox } from '@/components/ui/combobox'
import { ttsApi } from '@/api/tts'
import { DEFAULT_TTS_CONFIG } from '@/api/types/settings'
const TEST_PHRASE = 'Text to speech is working correctly.'
@@ -240,6 +242,15 @@ export function TTSSettings() {
stop()
}
const clearCacheMutation = useMutation({
mutationFn: () => ttsApi.clearCache(),
})
const clearCacheError =
clearCacheMutation.error instanceof Error
? clearCacheMutation.error.message
: 'Unable to clear the audio cache'
return (
<div className="bg-card border border-border rounded-lg p-6">
<div className="flex items-center justify-between mb-6">
@@ -681,6 +692,50 @@ export function TTSSettings() {
</div>
</>
)}
<div className="flex flex-col gap-3 rounded-lg border border-border p-4 sm:flex-row sm:items-center sm:justify-between">
<div className="space-y-0.5">
<div className="text-base font-medium">Clear audio cache</div>
<p className="text-sm text-muted-foreground">
Removes all cached server TTS audio. Audio is regenerated on next use, and active playback or synthesis may repopulate the cache.
</p>
<p className="text-xs text-muted-foreground">
Does not affect model or voice discovery.
</p>
{clearCacheMutation.isSuccess && (
<p role="status" className="text-sm text-success flex items-center gap-1">
<CheckCircle2 className="h-4 w-4" />
Cleared {clearCacheMutation.data?.cleared ?? 0} cached audio file(s).
</p>
)}
{clearCacheMutation.isError && (
<p role="alert" className="text-sm text-destructive flex items-center gap-1">
<XCircle className="h-4 w-4" />
Could not clear cached audio: {clearCacheError}. Try again.
</p>
)}
</div>
<Button
type="button"
variant="outline"
size="sm"
className="self-start sm:self-auto"
onClick={() => clearCacheMutation.mutate()}
disabled={clearCacheMutation.isPending}
>
{clearCacheMutation.isPending ? (
<>
<Loader2 className="h-4 w-4 animate-spin mr-2" />
Clearing...
</>
) : (
<>
<Trash2 className="h-4 w-4 mr-2" />
Clear audio cache
</>
)}
</Button>
</div>
</form>
</Form>
</div>
+296
View File
@@ -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<TTSConfig> = {}) {
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(
<TTSProvider>
<Consumer />
</TTSProvider>,
)
}
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<void>((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<string, number>()
for (const text of fetchBodies) {
fetchCounts.set(text, (fetchCounts.get(text) ?? 0) + 1)
}
for (const count of fetchCounts.values()) {
expect(count).toBe(1)
}
})
})
+92 -87
View File
@@ -37,11 +37,11 @@ export function TTSProvider({ children }: TTSProviderProps) {
const abortControllerRef = useRef<AbortController | null>(null)
const audioRef = useRef<HTMLAudioElement | null>(null)
const stoppedRef = useRef(false)
const playbackIdRef = useRef(0)
const currentObjectUrlRef = useRef<string | null>(null)
const chunksRef = useRef<string[]>([])
const chunkIndexRef = useRef(0)
const prefetchedBlobsRef = useRef<Map<number, Blob>>(new Map())
const fetchingIndexRef = useRef<number>(-1)
const chunkAudioRef = useRef<Map<number, Promise<Blob | null>>>(new Map())
// Web Speech API reference
const webSpeechSynthRef = useRef<ReturnType<typeof getWebSpeechSynthesizer> | 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<Blob | null> => {
if (stoppedRef.current) return null
const synthesizeExternal = useCallback(async (text: string, signal: AbortSignal | undefined, playbackId: number): Promise<Blob | null> => {
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<Blob | null> => {
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<boolean> => {
@@ -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])