Add TTS model and voice discovery with caching

This commit is contained in:
OpenCode committed 2025-12-15 17:43:05 +00:00
1 parent 722c62f61e
commit 406ff8fd4a
5 files changed
+421 -31

No files matched your search

+205
View File
@@ -9,7 +9,9 @@ import { logger } from '../utils/logger'
import { getWorkspacePath } from '@opencode-manager/shared'
const TTS_CACHE_DIR = join(getWorkspacePath(), 'cache', 'tts')
const DISCOVERY_CACHE_DIR = join(getWorkspacePath(), 'cache', 'discovery')
const CACHE_TTL_MS = 24 * 60 * 60 * 1000
const DISCOVERY_CACHE_TTL_MS = 60 * 60 * 1000 // 1 hour for discovery cache
const TTSRequestSchema = z.object({
text: z.string().min(1).max(4096),
@@ -25,6 +27,10 @@ async function ensureCacheDir(): Promise<void> {
await mkdir(TTS_CACHE_DIR, { recursive: true })
}
async function ensureDiscoveryCacheDir(): Promise<void> {
await mkdir(DISCOVERY_CACHE_DIR, { recursive: true })
}
async function getCachedAudio(cacheKey: string): Promise<Buffer | null> {
try {
const filePath = join(TTS_CACHE_DIR, `${cacheKey}.mp3`)
@@ -46,6 +52,127 @@ async function cacheAudio(cacheKey: string, audioData: Buffer): Promise<void> {
await writeFile(filePath, audioData)
}
async function getCachedDiscovery(cacheKey: string): Promise<string[] | null> {
try {
const filePath = join(DISCOVERY_CACHE_DIR, `${cacheKey}.json`)
const fileStat = await stat(filePath)
if (Date.now() - fileStat.mtimeMs > DISCOVERY_CACHE_TTL_MS) {
await unlink(filePath)
return null
}
const content = await readFile(filePath, 'utf-8')
return JSON.parse(content)
} catch {
return null
}
}
async function cacheDiscovery(cacheKey: string, data: string[]): Promise<void> {
try {
const filePath = join(DISCOVERY_CACHE_DIR, `${cacheKey}.json`)
await writeFile(filePath, JSON.stringify(data))
} catch (error) {
logger.error(`Failed to cache discovery data for ${cacheKey}:`, error)
}
}
function generateDiscoveryCacheKey(endpoint: string, apiKey: string, type: 'models' | 'voices'): string {
const hash = createHash('sha256')
hash.update(`${endpoint}|${apiKey.substring(0, 8)}|${type}`)
return hash.digest('hex')
}
async function fetchAvailableModels(endpoint: string, apiKey: string): Promise<string[]> {
// Try different endpoint formats for models
const endpointVariations = [
`${endpoint.replace(/\/audio\/speech$/, '')}/v1/models`,
`${endpoint.replace(/\/audio\/speech$/, '')}/models`,
`${endpoint.replace(/\/v1\/audio\/speech$/, '')}/v1/models`,
]
for (const modelEndpoint of endpointVariations) {
try {
const response = await fetch(modelEndpoint, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
})
if (response.ok) {
const data = await response.json() as { data?: { id?: string }[] } | unknown[]
// Handle different response formats
if ('data' in data && Array.isArray(data.data)) {
// OpenAI format: { data: [{ id: "gpt-4" }, ...] }
return data.data
.filter((model) => model.id && typeof model.id === 'string')
.filter((model) =>
model.id!.toLowerCase().includes('tts') ||
model.id!.toLowerCase().includes('audio') ||
model.id!.toLowerCase().includes('speech')
)
.map((model) => model.id!)
} else if (Array.isArray(data)) {
return data.filter((item): item is string => typeof item === 'string')
}
}
} catch (error) {
logger.debug(`Failed to fetch models from ${modelEndpoint}:`, error)
continue
}
}
return ['tts-1', 'tts-1-hd']
}
async function fetchAvailableVoices(endpoint: string, apiKey: string): Promise<string[]> {
// Try different endpoint formats for voices
const endpointVariations = [
`${endpoint.replace(/\/audio\/speech$/, '')}/v1/audio/voices`,
`${endpoint.replace(/\/audio\/speech$/, '')}/voices`,
`${endpoint.replace(/\/v1\/audio\/speech$/, '')}/v1/audio/voices`,
`${endpoint.replace(/\/v1\/audio\/speech$/, '')}/audio/voices`,
]
for (const voiceEndpoint of endpointVariations) {
try {
const response = await fetch(voiceEndpoint, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
})
if (response.ok) {
type VoiceItem = { id?: string; name?: string; voice?: string }
const data = await response.json() as { data?: VoiceItem[] } | (string | VoiceItem)[]
// Handle different response formats
if ('data' in data && Array.isArray(data.data)) {
// OpenAI-style format: { data: [{ name: "alloy" }, ...] }
return data.data
.filter((voice) => voice.id || voice.name)
.map((voice) => (voice.id || voice.name)!)
} else if (Array.isArray(data)) {
// Simple array format: ["alloy", "echo", ...] or [{ voice: "alloy" }, ...]
return data.map((item) => {
if (typeof item === 'string') return item
return item.name || item.voice || item.id
}).filter((v): v is string => typeof v === 'string')
}
}
} catch (error) {
logger.debug(`Failed to fetch voices from ${voiceEndpoint}:`, error)
continue
}
}
return ['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer']
}
export async function cleanupExpiredCache(): Promise<number> {
try {
await ensureCacheDir()
@@ -159,6 +286,84 @@ export function createTTSRoutes(db: Database) {
}
})
app.get('/models', async (c) => {
try {
const userId = c.req.query('userId') || 'default'
const forceRefresh = c.req.query('refresh') === 'true'
const settingsService = new SettingsService(db)
const settings = settingsService.getSettings(userId)
const ttsConfig = settings.preferences.tts
if (!ttsConfig?.apiKey || !ttsConfig?.endpoint) {
return c.json({ error: 'TTS not configured' }, 400)
}
const cacheKey = generateDiscoveryCacheKey(ttsConfig.endpoint, ttsConfig.apiKey, 'models')
// Check cache first (unless force refresh)
if (!forceRefresh) {
const cachedModels = await getCachedDiscovery(cacheKey)
if (cachedModels) {
logger.info(`Models cache hit for user ${userId}`)
return c.json({ models: cachedModels, cached: true })
}
}
// Fetch from API
await ensureDiscoveryCacheDir()
logger.info(`Fetching TTS models for user ${userId}`)
const models = await fetchAvailableModels(ttsConfig.endpoint, ttsConfig.apiKey)
await cacheDiscovery(cacheKey, models)
logger.info(`Fetched ${models.length} TTS models`)
return c.json({ models, cached: false })
} catch (error) {
logger.error('Failed to fetch TTS models:', error)
return c.json({ error: 'Failed to fetch models' }, 500)
}
})
app.get('/voices', async (c) => {
try {
const userId = c.req.query('userId') || 'default'
const forceRefresh = c.req.query('refresh') === 'true'
const settingsService = new SettingsService(db)
const settings = settingsService.getSettings(userId)
const ttsConfig = settings.preferences.tts
if (!ttsConfig?.apiKey || !ttsConfig?.endpoint) {
return c.json({ error: 'TTS not configured' }, 400)
}
const cacheKey = generateDiscoveryCacheKey(ttsConfig.endpoint, ttsConfig.apiKey, 'voices')
// Check cache first (unless force refresh)
if (!forceRefresh) {
const cachedVoices = await getCachedDiscovery(cacheKey)
if (cachedVoices) {
logger.info(`Voices cache hit for user ${userId}`)
return c.json({ voices: cachedVoices, cached: true })
}
}
// Fetch from API
await ensureDiscoveryCacheDir()
logger.info(`Fetching TTS voices for user ${userId}`)
const voices = await fetchAvailableVoices(ttsConfig.endpoint, ttsConfig.apiKey)
await cacheDiscovery(cacheKey, voices)
logger.info(`Fetched ${voices.length} TTS voices`)
return c.json({ voices, cached: false })
} catch (error) {
logger.error('Failed to fetch TTS voices:', error)
return c.json({ error: 'Failed to fetch voices' }, 500)
}
})
app.get('/status', async (c) => {
const userId = c.req.query('userId') || 'default'
const settingsService = new SettingsService(db)
+104
View File
@@ -0,0 +1,104 @@
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { API_BASE_URL } from '@/config'
async function fetchTTSModels(userId?: string, forceRefresh = false): Promise<{ models: string[]; cached: boolean }> {
const url = new URL(`${API_BASE_URL}/api/tts/models`)
if (userId) url.searchParams.set('userId', userId)
if (forceRefresh) url.searchParams.set('refresh', 'true')
const response = await fetch(url.toString())
if (!response.ok) {
let errorMessage = 'Failed to fetch TTS models'
try {
const errorData = await response.json()
errorMessage = errorData.error || errorMessage
} catch {
if (response.status === 400) errorMessage = 'TTS not configured'
else if (response.status === 401) errorMessage = 'Invalid TTS API key'
else if (response.status === 500) errorMessage = 'TTS service unavailable'
}
throw new Error(errorMessage)
}
return response.json()
}
async function fetchTTSVoices(userId?: string, forceRefresh = false): Promise<{ voices: string[]; cached: boolean }> {
const url = new URL(`${API_BASE_URL}/api/tts/voices`)
if (userId) url.searchParams.set('userId', userId)
if (forceRefresh) url.searchParams.set('refresh', 'true')
const response = await fetch(url.toString())
if (!response.ok) {
let errorMessage = 'Failed to fetch TTS voices'
try {
const errorData = await response.json()
errorMessage = errorData.error || errorMessage
} catch {
if (response.status === 400) errorMessage = 'TTS not configured'
else if (response.status === 401) errorMessage = 'Invalid TTS API key'
else if (response.status === 500) errorMessage = 'TTS service unavailable'
}
throw new Error(errorMessage)
}
return response.json()
}
export function useTTSModels(userId?: string, enabled = true) {
return useQuery({
queryKey: ['tts-models', userId],
queryFn: () => fetchTTSModels(userId),
enabled,
staleTime: 60 * 60 * 1000, // 1 hour
gcTime: 2 * 60 * 60 * 1000, // 2 hours
})
}
export function useTTSVoices(userId?: string, enabled = true) {
return useQuery({
queryKey: ['tts-voices', userId],
queryFn: () => fetchTTSVoices(userId),
enabled,
staleTime: 60 * 60 * 1000, // 1 hour
gcTime: 2 * 60 * 60 * 1000, // 2 hours
})
}
export function useTTSDiscovery(userId?: string) {
const queryClient = useQueryClient()
const refreshModels = async () => {
const result = await fetchTTSModels(userId, true)
queryClient.setQueryData(['tts-models', userId], result)
return result
}
const refreshVoices = async () => {
const result = await fetchTTSVoices(userId, true)
queryClient.setQueryData(['tts-voices', userId], result)
return result
}
const refreshAll = async () => {
const [models, voices] = await Promise.all([
refreshModels(),
refreshVoices()
])
return { models, voices }
}
return {
refreshModels,
refreshVoices,
refreshAll,
invalidateModels: () => queryClient.invalidateQueries({ queryKey: ['tts-models', userId] }),
invalidateVoices: () => queryClient.invalidateQueries({ queryKey: ['tts-voices', userId] }),
invalidateAll: () => {
queryClient.invalidateQueries({ queryKey: ['tts-models', userId] })
queryClient.invalidateQueries({ queryKey: ['tts-voices', userId] })
}
}
}
+8
View File
@@ -11,6 +11,10 @@ export interface TTSConfig {
voice: string
model: string
speed: number
availableVoices?: string[]
availableModels?: string[]
lastVoicesFetch?: number
lastModelsFetch?: number
}
export const DEFAULT_TTS_CONFIG: TTSConfig = {
@@ -20,6 +24,10 @@ export const DEFAULT_TTS_CONFIG: TTSConfig = {
voice: 'alloy',
model: 'tts-1',
speed: 1.0,
availableVoices: [],
availableModels: [],
lastVoicesFetch: 0,
lastModelsFetch: 0,
}
export interface CustomAgent {
@@ -4,13 +4,14 @@ import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { useSettings } from '@/hooks/useSettings'
import { useTTS } from '@/hooks/useTTS'
import { Loader2, Volume2, Square, CheckCircle, XCircle } from 'lucide-react'
import { useTTSModels, useTTSVoices, useTTSDiscovery } from '@/api/tts'
import { Loader2, Volume2, Square, CheckCircle, XCircle, RefreshCw } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Switch } from '@/components/ui/switch'
import { Slider } from '@/components/ui/slider'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form'
import { Combobox } from '@/components/ui/combobox'
import { DEFAULT_TTS_CONFIG } from '@/api/types/settings'
const TEST_PHRASE = 'Text to speech is working correctly.'
@@ -37,7 +38,9 @@ type TTSFormValues = z.infer<typeof ttsFormSchema>
export function TTSSettings() {
const { preferences, isLoading, updateSettings, isUpdating } = useSettings()
const { speak, stop, isPlaying, isLoading: isTTSLoading, error: ttsError } = useTTS()
const { refreshModels, refreshVoices, refreshAll } = useTTSDiscovery()
const [testStatus, setTestStatus] = useState<'idle' | 'success' | 'error'>('idle')
const [isRefreshingDiscovery, setIsRefreshingDiscovery] = useState(false)
const form = useForm<TTSFormValues>({
resolver: zodResolver(ttsFormSchema),
@@ -47,9 +50,39 @@ export function TTSSettings() {
const { reset, formState: { isDirty, isValid } } = form
const watchEnabled = form.watch('enabled')
const watchApiKey = form.watch('apiKey')
const watchEndpoint = form.watch('endpoint')
const canTest = watchEnabled && watchApiKey && !isDirty
// Fetch available models and voices when TTS is configured
const { data: modelsData, isLoading: isLoadingModels, refetch: refetchModels } = useTTSModels(
preferences?.tts?.enabled && preferences?.tts?.apiKey ? undefined : 'default',
watchEnabled && !!watchApiKey && !!watchEndpoint
)
const { data: voicesData, isLoading: isLoadingVoices, refetch: refetchVoices } = useTTSVoices(
preferences?.tts?.enabled && preferences?.tts?.apiKey ? undefined : 'default',
watchEnabled && !!watchApiKey && !!watchEndpoint
)
const availableModels = modelsData?.models || []
const availableVoices = voicesData?.voices || []
const modelsCached = modelsData?.cached || false
const voicesCached = voicesData?.cached || false
const handleRefreshDiscovery = async () => {
setIsRefreshingDiscovery(true)
try {
await refreshAll()
await Promise.all([
refetchModels(),
refetchVoices()
])
} finally {
setIsRefreshingDiscovery(false)
}
}
useEffect(() => {
if (preferences?.tts) {
reset({
@@ -179,29 +212,29 @@ export function TTSSettings() {
)}
/>
<FormField
<FormField
control={form.control}
name="voice"
render={({ field }) => (
<FormItem>
<FormLabel>Voice</FormLabel>
<Select onValueChange={field.onChange} value={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select a voice" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="alloy">Alloy</SelectItem>
<SelectItem value="echo">Echo</SelectItem>
<SelectItem value="fable">Fable</SelectItem>
<SelectItem value="onyx">Onyx</SelectItem>
<SelectItem value="nova">Nova</SelectItem>
<SelectItem value="shimmer">Shimmer</SelectItem>
</SelectContent>
</Select>
<FormControl>
<Combobox
value={field.value}
onChange={field.onChange}
options={availableVoices.map(voice => ({
value: voice,
label: voice
}))}
placeholder="Select a voice or type custom name..."
disabled={!watchEnabled || isLoadingVoices}
allowCustomValue={true}
/>
</FormControl>
<FormDescription>
Voice for text-to-speech output
{isLoadingVoices ? 'Loading available voices...' :
voicesCached ? `Available voices (${availableVoices.length}) - cached` :
`Available voices (${availableVoices.length})`}
</FormDescription>
<FormMessage />
</FormItem>
@@ -214,19 +247,23 @@ export function TTSSettings() {
render={({ field }) => (
<FormItem>
<FormLabel>Model</FormLabel>
<Select onValueChange={field.onChange} value={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select a model" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="tts-1">TTS-1 (faster)</SelectItem>
<SelectItem value="tts-1-hd">TTS-1-HD (higher quality)</SelectItem>
</SelectContent>
</Select>
<FormControl>
<Combobox
value={field.value}
onChange={field.onChange}
options={availableModels.map(model => ({
value: model,
label: model
}))}
placeholder="Select a model or type custom name..."
disabled={!watchEnabled || isLoadingModels}
allowCustomValue={true}
/>
</FormControl>
<FormDescription>
TTS model quality
{isLoadingModels ? 'Loading available models...' :
modelsCached ? `Available models (${availableModels.length}) - cached` :
`Available models (${availableModels.length})`}
</FormDescription>
<FormMessage />
</FormItem>
@@ -262,6 +299,34 @@ export function TTSSettings() {
)}
/>
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<div className="text-base font-medium">Refresh Discovery Data</div>
<p className="text-sm text-muted-foreground">
Force refresh available models and voices from the endpoint
</p>
</div>
<Button
type="button"
variant="outline"
size="sm"
onClick={handleRefreshDiscovery}
disabled={!watchEnabled || !watchApiKey || isRefreshingDiscovery}
>
{isRefreshingDiscovery ? (
<>
<Loader2 className="h-4 w-4 animate-spin mr-2" />
Refreshing...
</>
) : (
<>
<RefreshCw className="h-4 w-4 mr-2" />
Refresh
</>
)}
</Button>
</div>
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<div className="text-base font-medium">Test TTS</div>
+8
View File
@@ -13,6 +13,10 @@ export const TTSConfigSchema = z.object({
voice: z.string(),
model: z.string(),
speed: z.number().min(0.25).max(4.0),
availableVoices: z.array(z.string()).optional(),
availableModels: z.array(z.string()).optional(),
lastVoicesFetch: z.number().optional(),
lastModelsFetch: z.number().optional(),
});
export const CustomAgentSchema = z.object({
@@ -54,6 +58,10 @@ export const DEFAULT_TTS_CONFIG = {
voice: "alloy",
model: "tts-1",
speed: 1.0,
availableVoices: [],
availableModels: [],
lastVoicesFetch: 0,
lastModelsFetch: 0,
};
export const DEFAULT_USER_PREFERENCES = {