mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
fix(tts): key the audio cache by provider and add a settings clear action
- Hash text, voice, model, speed, normalized endpoint and API key into one SHA-256 key shared by the disk cache and in-flight synthesis, so different providers cannot reuse each other's audio and old keys are not read as fallback. - Add DELETE /api/tts/cache to remove completed cached audio files, keep temporary files, tolerate missing files and report real failures. - Add a Clear audio cache action to TTS settings, available even when TTS is disabled or the builtin provider is selected, with pending, success and retryable error states.
This commit is contained in:
1 parent
1eba33c6f1
commit
169ee25a8a
5 files changed
+511
-35
No files matched your search
+57
-21
@@ -24,9 +24,25 @@ const TTSRequestSchema = z.object({
|
||||
text: z.string().min(1).max(4096),
|
||||
})
|
||||
|
||||
function generateCacheKey(text: string, voice: string, model: string, speed: number): string {
|
||||
interface SynthesisParams {
|
||||
text: string
|
||||
endpoint: string
|
||||
apiKey: string
|
||||
voice: string
|
||||
model: string
|
||||
speed: number
|
||||
}
|
||||
|
||||
function generateCacheKey(params: SynthesisParams): string {
|
||||
const hash = createHash('sha256')
|
||||
hash.update(`${text}|${voice}|${model}|${speed}`)
|
||||
hash.update(JSON.stringify([
|
||||
params.text,
|
||||
params.voice,
|
||||
params.model,
|
||||
params.speed,
|
||||
normalizeToBaseUrl(params.endpoint),
|
||||
params.apiKey,
|
||||
]))
|
||||
return hash.digest('hex')
|
||||
}
|
||||
|
||||
@@ -119,15 +135,6 @@ async function cacheAudio(cacheKey: string, audioData: Buffer): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
interface SynthesisParams {
|
||||
text: string
|
||||
endpoint: string
|
||||
apiKey: string
|
||||
voice: string
|
||||
model: string
|
||||
speed: number
|
||||
}
|
||||
|
||||
class TTSUpstreamError extends Error {
|
||||
readonly status: 400 | 500
|
||||
readonly details: string
|
||||
@@ -322,7 +329,32 @@ export async function getCacheStats(): Promise<{ count: number; sizeBytes: numbe
|
||||
}
|
||||
}
|
||||
|
||||
export { generateCacheKey, ensureCacheDir, getCachedAudio, cacheAudio, getCacheSize, cleanupOldestFiles }
|
||||
async function clearCache(): Promise<number> {
|
||||
let files: string[]
|
||||
try {
|
||||
files = await readdir(TTS_CACHE_DIR)
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return 0
|
||||
throw error
|
||||
}
|
||||
|
||||
let cleared = 0
|
||||
for (const file of files) {
|
||||
if (!file.endsWith('.mp3')) continue
|
||||
|
||||
try {
|
||||
await unlink(join(TTS_CACHE_DIR, file))
|
||||
cleared++
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
return cleared
|
||||
}
|
||||
|
||||
export { generateCacheKey, ensureCacheDir, getCachedAudio, cacheAudio, getCacheSize, cleanupOldestFiles, clearCache }
|
||||
|
||||
export function createTTSRoutes(db: Database) {
|
||||
const app = new Hono()
|
||||
@@ -353,7 +385,8 @@ export function createTTSRoutes(db: Database) {
|
||||
}
|
||||
|
||||
const { endpoint, apiKey, voice, model, speed } = ttsConfig
|
||||
const cacheKey = generateCacheKey(text, voice, model, speed)
|
||||
const synthesisParams: SynthesisParams = { text, endpoint, apiKey, voice, model, speed }
|
||||
const cacheKey = generateCacheKey(synthesisParams)
|
||||
|
||||
await ensureCacheDir()
|
||||
|
||||
@@ -376,14 +409,7 @@ export function createTTSRoutes(db: Database) {
|
||||
|
||||
let audioBuffer: Buffer
|
||||
try {
|
||||
audioBuffer = await getOrStartSynthesis(cacheKey, {
|
||||
text,
|
||||
endpoint,
|
||||
apiKey,
|
||||
voice,
|
||||
model,
|
||||
speed,
|
||||
})
|
||||
audioBuffer = await getOrStartSynthesis(cacheKey, synthesisParams)
|
||||
} catch (error) {
|
||||
if (error instanceof TTSUpstreamError) {
|
||||
return c.json({
|
||||
@@ -511,5 +537,15 @@ export function createTTSRoutes(db: Database) {
|
||||
})
|
||||
})
|
||||
|
||||
app.delete('/cache', async (c) => {
|
||||
try {
|
||||
const cleared = await clearCache()
|
||||
return c.json({ cleared })
|
||||
} catch (error) {
|
||||
logger.error('TTS cache clear failed:', error)
|
||||
return c.json({ error: 'Failed to clear TTS cache' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
+207
-13
@@ -55,7 +55,7 @@ const mockReaddir = fs.readdir as any
|
||||
const mockStat = fs.stat as any
|
||||
const mockUnlink = fs.unlink as any
|
||||
|
||||
import { createTTSRoutes, cleanupExpiredCache, getCacheStats, generateCacheKey, ensureCacheDir, getCachedAudio, getCacheSize, cleanupOldestFiles, cacheAudio } from '../../src/routes/tts'
|
||||
import { createTTSRoutes, cleanupExpiredCache, getCacheStats, generateCacheKey, ensureCacheDir, getCachedAudio, getCacheSize, cleanupOldestFiles, cacheAudio, clearCache } from '../../src/routes/tts'
|
||||
|
||||
const mockWriteFile = fs.writeFile as any
|
||||
const mockRename = (fs as any).rename as any
|
||||
@@ -91,27 +91,112 @@ describe('TTS Routes', () => {
|
||||
})
|
||||
|
||||
describe('generateCacheKey', () => {
|
||||
const params = {
|
||||
text: 'Hello world',
|
||||
endpoint: 'https://tts.example.com',
|
||||
apiKey: 'test-api-key',
|
||||
voice: 'alloy',
|
||||
model: 'tts-1',
|
||||
speed: 1.0,
|
||||
}
|
||||
|
||||
it('should generate consistent cache keys for identical inputs', () => {
|
||||
const text = 'Hello world'
|
||||
const voice = 'alloy'
|
||||
const model = 'tts-1'
|
||||
const speed = 1.0
|
||||
|
||||
const key1 = generateCacheKey(text, voice, model, speed)
|
||||
const key2 = generateCacheKey(text, voice, model, speed)
|
||||
|
||||
const key1 = generateCacheKey(params)
|
||||
const key2 = generateCacheKey({ ...params })
|
||||
|
||||
expect(key1).toBe(key2)
|
||||
expect(key1).toMatch(/^[a-f0-9]{64}$/)
|
||||
})
|
||||
|
||||
it('should generate different cache keys for different inputs', () => {
|
||||
const key1 = generateCacheKey('Hello', 'alloy', 'tts-1', 1.0)
|
||||
const key2 = generateCacheKey('World', 'alloy', 'tts-1', 1.0)
|
||||
|
||||
it('should generate different cache keys for different text', () => {
|
||||
expect(generateCacheKey(params)).not.toBe(generateCacheKey({ ...params, text: 'Other' }))
|
||||
})
|
||||
|
||||
it('should generate different cache keys for different voices', () => {
|
||||
expect(generateCacheKey(params)).not.toBe(generateCacheKey({ ...params, voice: 'echo' }))
|
||||
})
|
||||
|
||||
it('should generate different cache keys for different models', () => {
|
||||
expect(generateCacheKey(params)).not.toBe(generateCacheKey({ ...params, model: 'tts-1-hd' }))
|
||||
})
|
||||
|
||||
it('should generate different cache keys for different speeds', () => {
|
||||
expect(generateCacheKey(params)).not.toBe(generateCacheKey({ ...params, speed: 1.5 }))
|
||||
})
|
||||
|
||||
it('should generate different cache keys for different api keys', () => {
|
||||
expect(generateCacheKey(params)).not.toBe(generateCacheKey({ ...params, apiKey: 'other-api-key' }))
|
||||
})
|
||||
|
||||
it('should generate different cache keys for different endpoints', () => {
|
||||
expect(generateCacheKey(params)).not.toBe(generateCacheKey({ ...params, endpoint: 'https://other.example.com' }))
|
||||
})
|
||||
|
||||
it('should normalize endpoints so trailing slashes share a key', () => {
|
||||
expect(generateCacheKey(params)).toBe(generateCacheKey({ ...params, endpoint: 'https://tts.example.com/' }))
|
||||
})
|
||||
|
||||
it('should avoid delimiter ambiguity between concatenated fields', () => {
|
||||
const key1 = generateCacheKey({ ...params, text: 'a', voice: 'b|c' })
|
||||
const key2 = generateCacheKey({ ...params, text: 'a|b', voice: 'c' })
|
||||
|
||||
expect(key1).not.toBe(key2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('clearCache', () => {
|
||||
it('should delete every .mp3 file and count them', async () => {
|
||||
mockReaddir.mockResolvedValue(['a.mp3', 'b.mp3'] as any)
|
||||
mockUnlink.mockResolvedValue(undefined)
|
||||
|
||||
const cleared = await clearCache()
|
||||
|
||||
expect(cleared).toBe(2)
|
||||
expect(mockUnlink).toHaveBeenCalledTimes(2)
|
||||
expect(mockUnlink).toHaveBeenCalledWith(expect.stringContaining('a.mp3'))
|
||||
expect(mockUnlink).toHaveBeenCalledWith(expect.stringContaining('b.mp3'))
|
||||
})
|
||||
|
||||
it('should tolerate a missing cache directory', async () => {
|
||||
mockReaddir.mockRejectedValue(Object.assign(new Error('missing'), { code: 'ENOENT' }))
|
||||
|
||||
const cleared = await clearCache()
|
||||
|
||||
expect(cleared).toBe(0)
|
||||
expect(mockUnlink).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should tolerate a file removed by a race and keep clearing the rest', async () => {
|
||||
mockReaddir.mockResolvedValue(['gone.mp3', 'present.mp3'] as any)
|
||||
mockUnlink
|
||||
.mockRejectedValueOnce(Object.assign(new Error('gone'), { code: 'ENOENT' }))
|
||||
.mockResolvedValueOnce(undefined)
|
||||
|
||||
const cleared = await clearCache()
|
||||
|
||||
expect(cleared).toBe(1)
|
||||
expect(mockUnlink).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('should throw unexpected filesystem errors', async () => {
|
||||
mockReaddir.mockResolvedValue(['a.mp3'] as any)
|
||||
mockUnlink.mockRejectedValue(Object.assign(new Error('denied'), { code: 'EACCES' }))
|
||||
|
||||
await expect(clearCache()).rejects.toThrow('denied')
|
||||
})
|
||||
|
||||
it('should leave .tmp and unrelated files untouched', async () => {
|
||||
mockReaddir.mockResolvedValue(['a.mp3', 'pending.tmp', 'notes.txt'] as any)
|
||||
mockUnlink.mockResolvedValue(undefined)
|
||||
|
||||
const cleared = await clearCache()
|
||||
|
||||
expect(cleared).toBe(1)
|
||||
expect(mockUnlink).toHaveBeenCalledTimes(1)
|
||||
expect(mockUnlink).toHaveBeenCalledWith(expect.stringContaining('a.mp3'))
|
||||
})
|
||||
})
|
||||
|
||||
describe('ensureCacheDir', () => {
|
||||
it('should create cache directory when it does not exist', async () => {
|
||||
await expect(ensureCacheDir()).resolves.toBeUndefined()
|
||||
@@ -416,6 +501,85 @@ describe('TTS route handlers', () => {
|
||||
expect(Buffer.from(await secondRes.arrayBuffer()).toString()).toBe('shared-audio')
|
||||
})
|
||||
|
||||
it('does not share an in-flight synthesis across different endpoints or API keys', async () => {
|
||||
mockStat.mockRejectedValue(new Error('not found'))
|
||||
mockReaddir.mockResolvedValue([] as any)
|
||||
mockWriteFile.mockResolvedValue(undefined)
|
||||
mockRename.mockResolvedValue(undefined)
|
||||
mockGetSettings.mockImplementation((userId: string) => ({
|
||||
preferences: {
|
||||
tts: createTtsConfig(
|
||||
userId === 'first'
|
||||
? { endpoint: 'https://first.example.com', apiKey: 'first-key' }
|
||||
: { endpoint: 'https://second.example.com', apiKey: 'second-key' },
|
||||
),
|
||||
},
|
||||
}))
|
||||
|
||||
const resolvers: Array<(value: { ok: boolean; arrayBuffer: () => Promise<Buffer> }) => void> = []
|
||||
const fetchMock = vi.fn().mockImplementation(
|
||||
() => new Promise((resolve) => {
|
||||
resolvers.push(resolve)
|
||||
}),
|
||||
)
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const request = (userId: string) => app.request('/synthesize?userId=' + userId, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ text: 'Isolated text' }),
|
||||
})
|
||||
|
||||
const first = request('first')
|
||||
const second = request('second')
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 0))
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||
|
||||
resolvers[0]!({ ok: true, arrayBuffer: async () => Buffer.from('first-audio') })
|
||||
resolvers[1]!({ ok: true, arrayBuffer: async () => Buffer.from('second-audio') })
|
||||
|
||||
const [firstRes, secondRes] = await Promise.all([first, second])
|
||||
|
||||
expect(firstRes.status).toBe(200)
|
||||
expect(secondRes.status).toBe(200)
|
||||
expect(Buffer.from(await firstRes.arrayBuffer()).toString()).toBe('first-audio')
|
||||
expect(Buffer.from(await secondRes.arrayBuffer()).toString()).toBe('second-audio')
|
||||
})
|
||||
|
||||
it('isolates the disk cache across providers for identical text', async () => {
|
||||
mockStat.mockRejectedValue(new Error('not found'))
|
||||
mockReaddir.mockResolvedValue([] as any)
|
||||
mockWriteFile.mockResolvedValue(undefined)
|
||||
mockRename.mockResolvedValue(undefined)
|
||||
mockGetSettings.mockImplementation((userId: string) => ({
|
||||
preferences: {
|
||||
tts: createTtsConfig(
|
||||
userId === 'first'
|
||||
? { endpoint: 'https://first.example.com', apiKey: 'first-key' }
|
||||
: { endpoint: 'https://second.example.com', apiKey: 'second-key' },
|
||||
),
|
||||
},
|
||||
}))
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
arrayBuffer: async () => Buffer.from('audio'),
|
||||
}))
|
||||
|
||||
const request = (userId: string) => app.request('/synthesize?userId=' + userId, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ text: 'Shared text' }),
|
||||
})
|
||||
|
||||
await request('first')
|
||||
await request('second')
|
||||
|
||||
const statPaths = mockStat.mock.calls.map((call: unknown[]) => call[0] as string)
|
||||
expect(statPaths).toHaveLength(2)
|
||||
expect(statPaths[0]).not.toBe(statPaths[1])
|
||||
})
|
||||
|
||||
it('returns the upstream error details when synthesis fails', async () => {
|
||||
mockStat.mockRejectedValue(new Error('not found'))
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
||||
@@ -542,6 +706,36 @@ describe('TTS route handlers', () => {
|
||||
cache: { count: 1, sizeBytes: 1024, sizeMB: 0, maxSizeMB: 200, ttlHours: 24 },
|
||||
})
|
||||
})
|
||||
|
||||
it('clears the cache through the DELETE /cache route', async () => {
|
||||
mockReaddir.mockResolvedValue(['a.mp3', 'b.mp3', 'pending.tmp'] as any)
|
||||
mockUnlink.mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request('/cache', { method: 'DELETE' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ cleared: 2 })
|
||||
expect(mockUnlink).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('returns zero when the cache directory is missing', async () => {
|
||||
mockReaddir.mockRejectedValue(Object.assign(new Error('missing'), { code: 'ENOENT' }))
|
||||
|
||||
const res = await app.request('/cache', { method: 'DELETE' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ cleared: 0 })
|
||||
})
|
||||
|
||||
it('returns 500 when clearing the cache fails unexpectedly', async () => {
|
||||
mockReaddir.mockResolvedValue(['a.mp3'] as any)
|
||||
mockUnlink.mockRejectedValue(Object.assign(new Error('denied'), { code: 'EACCES' }))
|
||||
|
||||
const res = await app.request('/cache', { method: 'DELETE' })
|
||||
|
||||
expect(res.status).toBe(500)
|
||||
expect(await res.json()).toEqual({ error: 'Failed to clear TTS cache' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('cacheAudio', () => {
|
||||
|
||||
@@ -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>
|
||||
|
||||
Reference in new issue
Block a user