Add TTS support with OpenAI-compatible endpoint configuration

- Add TTS settings schema and configuration UI with validation
- Create backend TTS proxy with 24hr file-based caching
- Add frontend useTTS hook with Cache API caching
- Add TTS playback button on assistant messages (step-finish)
- Include test button to verify TTS configuration
This commit is contained in:
Chris Scott committed 2025-11-28 19:52:35 -05:00
1 parent 283348b64f
commit fb91b4d3a3
12 files changed
+859 -5

No files matched your search

+4 -1
View File
@@ -6,7 +6,7 @@ import { initializeDatabase } from './db/schema'
import { createRepoRoutes } from './routes/repos'
import { createSettingsRoutes } from './routes/settings'
import { createHealthRoutes } from './routes/health'
import { createTTSRoutes, cleanupExpiredCache } from './routes/tts'
import { createFileRoutes } from './routes/files'
import { createProvidersRoutes } from './routes/providers'
import { ensureDirectoryExists, writeFileContent } from './services/file-operations'
@@ -130,6 +130,8 @@ try {
await cleanupOrphanedDirectories(db)
logger.info('Orphaned directory cleanup completed')
await cleanupExpiredCache()
await ensureDefaultConfigExists()
await syncDefaultConfigToDisk()
@@ -144,6 +146,7 @@ app.route('/api/settings', createSettingsRoutes(db))
app.route('/api/health', createHealthRoutes(db))
app.route('/api/files', createFileRoutes(db))
app.route('/api/providers', createProvidersRoutes())
app.route('/api/tts', createTTSRoutes(db))
app.all('/api/opencode/*', async (c) => {
const request = c.req.raw
+175
View File
@@ -0,0 +1,175 @@
import { Hono } from 'hono'
import { z } from 'zod'
import { Database } from 'bun:sqlite'
import { createHash } from 'crypto'
import { mkdir, readFile, writeFile, readdir, stat, unlink } from 'fs/promises'
import { join } from 'path'
import { SettingsService } from '../services/settings'
import { logger } from '../utils/logger'
import { getWorkspacePath } from '@opencode-webui/shared'
const TTS_CACHE_DIR = join(getWorkspacePath(), 'cache', 'tts')
const CACHE_TTL_MS = 24 * 60 * 60 * 1000
const TTSRequestSchema = z.object({
text: z.string().min(1).max(4096),
})
function generateCacheKey(text: string, voice: string, model: string, speed: number): string {
const hash = createHash('sha256')
hash.update(`${text}|${voice}|${model}|${speed}`)
return hash.digest('hex')
}
async function ensureCacheDir(): Promise<void> {
await mkdir(TTS_CACHE_DIR, { recursive: true })
}
async function getCachedAudio(cacheKey: string): Promise<Buffer | null> {
try {
const filePath = join(TTS_CACHE_DIR, `${cacheKey}.mp3`)
const fileStat = await stat(filePath)
if (Date.now() - fileStat.mtimeMs > CACHE_TTL_MS) {
await unlink(filePath)
return null
}
return await readFile(filePath)
} catch {
return null
}
}
async function cacheAudio(cacheKey: string, audioData: Buffer): Promise<void> {
const filePath = join(TTS_CACHE_DIR, `${cacheKey}.mp3`)
await writeFile(filePath, audioData)
}
export async function cleanupExpiredCache(): Promise<number> {
try {
await ensureCacheDir()
const files = await readdir(TTS_CACHE_DIR)
let cleanedCount = 0
for (const file of files) {
if (!file.endsWith('.mp3')) continue
const filePath = join(TTS_CACHE_DIR, file)
try {
const fileStat = await stat(filePath)
if (Date.now() - fileStat.mtimeMs > CACHE_TTL_MS) {
await unlink(filePath)
cleanedCount++
}
} catch {
continue
}
}
if (cleanedCount > 0) {
logger.info(`TTS cache cleanup: removed ${cleanedCount} expired files`)
}
return cleanedCount
} catch (error) {
logger.error('TTS cache cleanup failed:', error)
return 0
}
}
export function createTTSRoutes(db: Database) {
const app = new Hono()
app.post('/synthesize', async (c) => {
try {
const body = await c.req.json()
const { text } = TTSRequestSchema.parse(body)
const userId = c.req.query('userId') || 'default'
const settingsService = new SettingsService(db)
const settings = settingsService.getSettings(userId)
const ttsConfig = settings.preferences.tts
if (!ttsConfig?.enabled) {
return c.json({ error: 'TTS is not enabled' }, 400)
}
if (!ttsConfig.apiKey) {
return c.json({ error: 'TTS API key is not configured' }, 400)
}
const { endpoint, apiKey, voice, model, speed } = ttsConfig
const cacheKey = generateCacheKey(text, voice, model, speed)
await ensureCacheDir()
const cachedAudio = await getCachedAudio(cacheKey)
if (cachedAudio) {
logger.info(`TTS cache hit: ${cacheKey.substring(0, 8)}...`)
return new Response(cachedAudio, {
headers: {
'Content-Type': 'audio/mpeg',
'X-Cache': 'HIT',
},
})
}
logger.info(`TTS cache miss, calling API: ${cacheKey.substring(0, 8)}...`)
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model,
voice,
input: text,
speed,
response_format: 'mp3',
}),
})
if (!response.ok) {
const errorText = await response.text()
logger.error(`TTS API error: ${response.status} - ${errorText}`)
const status = response.status >= 400 && response.status < 600 ? response.status as 400 | 500 : 500
return c.json({ error: 'TTS API request failed', details: errorText }, status)
}
const audioBuffer = Buffer.from(await response.arrayBuffer())
await cacheAudio(cacheKey, audioBuffer)
logger.info(`TTS audio cached: ${cacheKey.substring(0, 8)}...`)
return new Response(audioBuffer, {
headers: {
'Content-Type': 'audio/mpeg',
'X-Cache': 'MISS',
},
})
} catch (error) {
logger.error('TTS synthesis failed:', error)
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid request', details: error.issues }, 400)
}
return c.json({ error: 'TTS synthesis failed' }, 500)
}
})
app.get('/status', async (c) => {
const userId = c.req.query('userId') || 'default'
const settingsService = new SettingsService(db)
const settings = settingsService.getSettings(userId)
const ttsConfig = settings.preferences.tts
return c.json({
enabled: ttsConfig?.enabled || false,
configured: !!(ttsConfig?.apiKey),
})
})
return app
}
+1
View File
@@ -15,6 +15,7 @@
"@radix-ui/react-dropdown-menu": "^2.1.16",
"@radix-ui/react-label": "^2.1.7",
"@radix-ui/react-select": "^2.2.6",
"@radix-ui/react-slider": "^1.3.6",
"@radix-ui/react-slot": "^1.2.3",
"@radix-ui/react-switch": "^1.2.6",
"@radix-ui/react-tabs": "^1.1.13",
+20
View File
@@ -4,6 +4,24 @@ export interface CustomCommand {
promptTemplate: string
}
export interface TTSConfig {
enabled: boolean
endpoint: string
apiKey: string
voice: string
model: string
speed: number
}
export const DEFAULT_TTS_CONFIG: TTSConfig = {
enabled: false,
endpoint: 'https://api.openai.com/v1/audio/speech',
apiKey: '',
voice: 'alloy',
model: 'tts-1',
speed: 1.0,
}
export interface CustomAgent {
name: string
description: string
@@ -22,6 +40,7 @@ export interface UserPreferences {
customCommands: CustomCommand[]
customAgents: CustomAgent[]
gitToken?: string
tts?: TTSConfig
}
export interface SettingsResponse {
@@ -87,4 +106,5 @@ export const DEFAULT_USER_PREFERENCES: UserPreferences = {
customCommands: [],
customAgents: [],
gitToken: undefined,
tts: DEFAULT_TTS_CONFIG,
}
@@ -1,9 +1,10 @@
import { memo } from 'react'
import type { components } from '@/api/opencode-types'
import { Copy } from 'lucide-react'
import { Copy, Volume2, Square, Loader2 } from 'lucide-react'
import { TextPart } from './TextPart'
import { PatchPart } from './PatchPart'
import { ToolCallPart } from './ToolCallPart'
import { useTTS } from '@/hooks/useTTS'
type Part = components['schemas']['Part']
@@ -13,6 +14,7 @@ interface MessagePartProps {
allParts?: Part[]
partIndex?: number
onFileClick?: (filePath: string, lineNumber?: number) => void
messageTextContent?: string
}
function getCopyableContent(part: Part, allParts?: Part[]): string {
@@ -74,9 +76,49 @@ function CopyButton({ content, title, className = "" }: { content: string; title
)
}
interface TTSButtonProps {
content: string
className?: string
}
export function TTSButton({ content, className = "" }: TTSButtonProps) {
const { speak, stop, isEnabled, isPlaying, isLoading, currentText } = useTTS()
if (!isEnabled || !content.trim()) {
return null
}
const isThisPlaying = (isPlaying || isLoading) && currentText === content
const handleClick = () => {
if (isThisPlaying) {
stop()
} else {
speak(content)
}
}
return (
<button
onClick={handleClick}
className={`p-1.5 rounded ${isThisPlaying ? 'bg-red-500/20 text-red-500 hover:bg-red-500/30' : 'bg-card hover:bg-card-hover text-muted-foreground hover:text-foreground'} ${className}`}
title={isThisPlaying ? "Stop playback" : "Read aloud"}
disabled={isLoading && currentText !== content}
>
{isLoading && isThisPlaying ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : isThisPlaying ? (
<Square className="w-4 h-4" />
) : (
<Volume2 className="w-4 h-4" />
)}
</button>
)
}
export const MessagePart = memo(function MessagePart({ part, role, allParts, partIndex, onFileClick }: MessagePartProps) {
export const MessagePart = memo(function MessagePart({ part, role, allParts, partIndex, onFileClick, messageTextContent }: MessagePartProps) {
const copyableContent = getCopyableContent(part, allParts)
switch (part.type) {
@@ -120,6 +162,7 @@ export const MessagePart = memo(function MessagePart({ part, role, allParts, par
<div className="text-xs text-muted-foreground my-1 flex items-center gap-2">
<span>${part.cost.toFixed(4)} • {part.tokens.input + part.tokens.output} tokens</span>
<CopyButton content={copyableContent} title="Copy step complete" />
{messageTextContent && <TTSButton content={messageTextContent} />}
</div>
)
case 'file':
@@ -4,6 +4,14 @@ import { useSettings } from '@/hooks/useSettings'
import { MessagePart } from './MessagePart'
import type { MessageWithParts } from '@/api/types'
function getMessageTextContent(msg: MessageWithParts): string {
return msg.parts
.filter(p => p.type === 'text')
.map(p => p.text || '')
.join('\n\n')
.trim()
}
interface MessageThreadProps {
opcodeUrl: string
sessionID: string
@@ -189,6 +197,7 @@ export const MessageThread = memo(function MessageThread({ opcodeUrl, sessionID,
allParts={msg.parts}
partIndex={index}
onFileClick={onFileClick}
messageTextContent={msg.info.role === 'assistant' ? getMessageTextContent(msg) : undefined}
/>
</div>
))}
@@ -1,12 +1,22 @@
import { useState, useEffect } from 'react'
import { useSettings } from '@/hooks/useSettings'
import { Loader2 } from 'lucide-react'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Switch } from '@/components/ui/switch'
import { Input } from '@/components/ui/input'
import { TTSSettings } from './TTSSettings'
export function GeneralSettings() {
const { preferences, isLoading, updateSettings, isUpdating } = useSettings()
const [gitToken, setGitToken] = useState('')
useEffect(() => {
if (preferences) {
setGitToken(preferences.gitToken || '')
}
}, [preferences])
if (isLoading) {
return (
@@ -108,8 +118,9 @@ export function GeneralSettings() {
id="gitToken"
type="password"
placeholder="ghp_..."
value={preferences?.gitToken || ''}
onChange={(e) => updateSettings({ gitToken: e.target.value })}
value={gitToken}
onChange={(e) => setGitToken(e.target.value)}
onBlur={() => updateSettings({ gitToken })}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
<p className="text-sm text-muted-foreground">
@@ -124,6 +135,10 @@ export function GeneralSettings() {
</div>
)}
</div>
<div className="mt-6">
<TTSSettings />
</div>
</div>
)
}
@@ -0,0 +1,317 @@
import { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
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 { 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 { DEFAULT_TTS_CONFIG } from '@/api/types/settings'
const TEST_PHRASE = 'Text to speech is working correctly.'
const ttsFormSchema = z.object({
enabled: z.boolean(),
endpoint: z.string().url('Must be a valid URL').min(1, 'Endpoint is required'),
apiKey: z.string().min(1, 'API key is required when TTS is enabled').or(z.literal('')),
voice: z.string().min(1, 'Voice is required'),
model: z.string().min(1, 'Model is required'),
speed: z.number().min(0.25).max(4.0),
}).refine((data) => {
if (data.enabled && !data.apiKey) {
return false
}
return true
}, {
message: 'API key is required when TTS is enabled',
path: ['apiKey'],
})
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 [testStatus, setTestStatus] = useState<'idle' | 'success' | 'error'>('idle')
const form = useForm<TTSFormValues>({
resolver: zodResolver(ttsFormSchema),
defaultValues: DEFAULT_TTS_CONFIG,
})
const { reset, formState: { isDirty, isValid } } = form
const watchEnabled = form.watch('enabled')
const watchApiKey = form.watch('apiKey')
const canTest = watchEnabled && watchApiKey && !isDirty
useEffect(() => {
if (preferences?.tts) {
reset({
enabled: preferences.tts.enabled ?? DEFAULT_TTS_CONFIG.enabled,
endpoint: preferences.tts.endpoint ?? DEFAULT_TTS_CONFIG.endpoint,
apiKey: preferences.tts.apiKey ?? DEFAULT_TTS_CONFIG.apiKey,
voice: preferences.tts.voice ?? DEFAULT_TTS_CONFIG.voice,
model: preferences.tts.model ?? DEFAULT_TTS_CONFIG.model,
speed: preferences.tts.speed ?? DEFAULT_TTS_CONFIG.speed,
})
}
}, [preferences?.tts, reset])
const onSubmit = (data: TTSFormValues) => {
updateSettings({ tts: data })
}
const handleTest = async () => {
setTestStatus('idle')
try {
await speak(TEST_PHRASE)
setTestStatus('success')
setTimeout(() => setTestStatus('idle'), 3000)
} catch {
setTestStatus('error')
}
}
const handleStopTest = () => {
stop()
setTestStatus('idle')
}
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
)
}
return (
<div className="bg-card border border-border rounded-lg p-6">
<div className="flex items-center justify-between mb-6">
<h2 className="text-lg font-semibold text-foreground">Text-to-Speech</h2>
<Button
onClick={form.handleSubmit(onSubmit)}
disabled={!isDirty || !isValid || isUpdating}
size="sm"
>
{isUpdating ? (
<>
<Loader2 className="h-4 w-4 animate-spin mr-2" />
Saving...
</>
) : (
'Save'
)}
</Button>
</div>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<FormField
control={form.control}
name="enabled"
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<FormLabel className="text-base">Enable TTS</FormLabel>
<FormDescription>
Allow text-to-speech playback for messages
</FormDescription>
</div>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
{watchEnabled && (
<>
<FormField
control={form.control}
name="endpoint"
render={({ field }) => (
<FormItem>
<FormLabel>TTS Endpoint</FormLabel>
<FormControl>
<Input
placeholder="https://api.openai.com/v1/audio/speech"
className="bg-background"
{...field}
/>
</FormControl>
<FormDescription>
OpenAI-compatible TTS API endpoint
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="apiKey"
render={({ field }) => (
<FormItem>
<FormLabel>API Key</FormLabel>
<FormControl>
<Input
type="password"
placeholder="sk-..."
className="bg-background"
{...field}
/>
</FormControl>
<FormDescription>
API key for the TTS service
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<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>
<FormDescription>
Voice for text-to-speech output
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="model"
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>
<FormDescription>
TTS model quality
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="speed"
render={({ field }) => (
<FormItem>
<div className="flex justify-between">
<FormLabel>Speed</FormLabel>
<span className="text-sm text-muted-foreground">
{field.value.toFixed(2)}x
</span>
</div>
<FormControl>
<Slider
min={0.25}
max={4.0}
step={0.25}
value={[field.value]}
onValueChange={([value]) => field.onChange(value)}
className="w-full"
/>
</FormControl>
<FormDescription>
Playback speed (0.25x to 4.0x)
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<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>
<p className="text-sm text-muted-foreground">
{isDirty
? 'Save changes before testing'
: 'Verify your TTS configuration works'}
</p>
{ttsError && (
<p className="text-sm text-destructive flex items-center gap-1">
<XCircle className="h-4 w-4" />
{ttsError}
</p>
)}
{testStatus === 'success' && (
<p className="text-sm text-green-500 flex items-center gap-1">
<CheckCircle className="h-4 w-4" />
TTS is working
</p>
)}
</div>
<Button
type="button"
variant="outline"
size="sm"
onClick={isPlaying || isTTSLoading ? handleStopTest : handleTest}
disabled={!canTest}
>
{isTTSLoading ? (
<>
<Loader2 className="h-4 w-4 animate-spin mr-2" />
Testing...
</>
) : isPlaying ? (
<>
<Square className="h-4 w-4 mr-2" />
Stop
</>
) : (
<>
<Volume2 className="h-4 w-4 mr-2" />
Test
</>
)}
</Button>
</div>
</>
)}
</form>
</Form>
</div>
)
}
+26
View File
@@ -0,0 +1,26 @@
import * as React from "react"
import * as SliderPrimitive from "@radix-ui/react-slider"
import { cn } from "@/lib/utils"
const Slider = React.forwardRef<
React.ComponentRef<typeof SliderPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>
>(({ className, ...props }, ref) => (
<SliderPrimitive.Root
ref={ref}
className={cn(
"relative flex w-full touch-none select-none items-center",
className
)}
{...props}
>
<SliderPrimitive.Track className="relative h-2 w-full grow overflow-hidden rounded-full bg-secondary">
<SliderPrimitive.Range className="absolute h-full bg-primary" />
</SliderPrimitive.Track>
<SliderPrimitive.Thumb className="block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50" />
</SliderPrimitive.Root>
))
Slider.displayName = SliderPrimitive.Root.displayName
export { Slider }
+192
View File
@@ -0,0 +1,192 @@
import { useState, useRef, useCallback, useEffect } from 'react'
import { useSettings } from './useSettings'
import { API_BASE_URL } from '@/config'
const TTS_CACHE_NAME = 'tts-audio-cache'
const CACHE_TTL_MS = 24 * 60 * 60 * 1000
async function generateCacheKey(text: string, voice: string, model: string, speed: number): Promise<string> {
const data = `${text}|${voice}|${model}|${speed}`
const encoder = new TextEncoder()
const dataBuffer = encoder.encode(data)
const hashBuffer = await crypto.subtle.digest('SHA-256', dataBuffer)
const hashArray = Array.from(new Uint8Array(hashBuffer))
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('')
}
async function getCachedAudio(cacheKey: string): Promise<Blob | null> {
try {
const cache = await caches.open(TTS_CACHE_NAME)
const response = await cache.match(cacheKey)
if (!response) return null
const cachedAt = response.headers.get('x-cached-at')
if (cachedAt && Date.now() - parseInt(cachedAt) > CACHE_TTL_MS) {
await cache.delete(cacheKey)
return null
}
return await response.blob()
} catch {
return null
}
}
async function cacheAudio(cacheKey: string, blob: Blob): Promise<void> {
try {
const cache = await caches.open(TTS_CACHE_NAME)
const headers = new Headers({
'Content-Type': 'audio/mpeg',
'x-cached-at': Date.now().toString(),
})
const response = new Response(blob, { headers })
await cache.put(cacheKey, response)
} catch {
// Cache API not available, continue without caching
}
}
export type TTSState = 'idle' | 'loading' | 'playing' | 'paused' | 'error'
export function useTTS() {
const { preferences } = useSettings()
const [state, setState] = useState<TTSState>('idle')
const [error, setError] = useState<string | null>(null)
const [currentText, setCurrentText] = useState<string | null>(null)
const audioRef = useRef<HTMLAudioElement | null>(null)
const abortControllerRef = useRef<AbortController | null>(null)
const ttsConfig = preferences?.tts
const isEnabled = ttsConfig?.enabled && ttsConfig?.apiKey
const cleanup = useCallback(() => {
if (audioRef.current) {
audioRef.current.pause()
audioRef.current.src = ''
audioRef.current = null
}
if (abortControllerRef.current) {
abortControllerRef.current.abort()
abortControllerRef.current = null
}
}, [])
useEffect(() => {
return () => cleanup()
}, [cleanup])
const speak = useCallback(async (text: string) => {
if (!isEnabled || !ttsConfig) {
setError('TTS is not configured')
setState('error')
return
}
cleanup()
setError(null)
setCurrentText(text)
setState('loading')
try {
const { voice, model, speed } = ttsConfig
const cacheKey = await generateCacheKey(text, voice, model, speed)
let audioBlob = await getCachedAudio(cacheKey)
if (!audioBlob) {
abortControllerRef.current = new AbortController()
const response = await fetch(`${API_BASE_URL}/api/tts/synthesize`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ text }),
signal: abortControllerRef.current.signal,
})
if (!response.ok) {
const errorData = await response.json().catch(() => ({}))
throw new Error(errorData.error || 'TTS request failed')
}
audioBlob = await response.blob()
await cacheAudio(cacheKey, audioBlob)
}
const audioUrl = URL.createObjectURL(audioBlob)
const audio = new Audio(audioUrl)
audioRef.current = audio
audio.onplay = () => setState('playing')
audio.onpause = () => {
if (audio.currentTime < audio.duration) {
setState('paused')
}
}
audio.onended = () => {
setState('idle')
setCurrentText(null)
URL.revokeObjectURL(audioUrl)
}
audio.onerror = () => {
setError('Audio playback failed')
setState('error')
URL.revokeObjectURL(audioUrl)
}
await audio.play()
} catch (err) {
if (err instanceof Error && err.name === 'AbortError') {
setState('idle')
return
}
setError(err instanceof Error ? err.message : 'TTS failed')
setState('error')
}
}, [isEnabled, ttsConfig, cleanup])
const stop = useCallback(() => {
cleanup()
setState('idle')
setCurrentText(null)
setError(null)
}, [cleanup])
const pause = useCallback(() => {
if (audioRef.current && state === 'playing') {
audioRef.current.pause()
}
}, [state])
const resume = useCallback(() => {
if (audioRef.current && state === 'paused') {
audioRef.current.play()
}
}, [state])
const toggle = useCallback(() => {
if (state === 'playing') {
pause()
} else if (state === 'paused') {
resume()
}
}, [state, pause, resume])
return {
speak,
stop,
pause,
resume,
toggle,
state,
error,
currentText,
isEnabled,
isPlaying: state === 'playing',
isLoading: state === 'loading',
isPaused: state === 'paused',
isIdle: state === 'idle',
}
}
+33
View File
@@ -73,6 +73,9 @@ importers:
'@radix-ui/react-select':
specifier: ^2.2.6
version: 2.2.6(@types/react-dom@19.2.3)(@types/react@19.2.7)(react-dom@19.2.0)(react@19.2.0)
'@radix-ui/react-slider':
specifier: ^1.3.6
version: 1.3.6(@types/react-dom@19.2.3)(@types/react@19.2.7)(react-dom@19.2.0)(react@19.2.0)
'@radix-ui/react-slot':
specifier: ^1.2.3
version: 1.2.4(@types/react@19.2.7)(react@19.2.0)
@@ -1248,6 +1251,36 @@ packages:
react-remove-scroll: 2.7.1(@types/react@19.2.7)(react@19.2.0)
dev: false
/@radix-ui/react-slider@1.3.6(@types/react-dom@19.2.3)(@types/react@19.2.7)(react-dom@19.2.0)(react@19.2.0):
resolution: {integrity: sha512-JPYb1GuM1bxfjMRlNLE+BcmBC8onfCi60Blk7OBqi2MLTFdS+8401U4uFjnwkOr49BLmXxLC6JHkvAsx5OJvHw==}
peerDependencies:
'@types/react': '*'
'@types/react-dom': '*'
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@types/react-dom':
optional: true
dependencies:
'@radix-ui/number': 1.1.1
'@radix-ui/primitive': 1.1.3
'@radix-ui/react-collection': 1.1.7(@types/react-dom@19.2.3)(@types/react@19.2.7)(react-dom@19.2.0)(react@19.2.0)
'@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.7)(react@19.2.0)
'@radix-ui/react-context': 1.1.2(@types/react@19.2.7)(react@19.2.0)
'@radix-ui/react-direction': 1.1.1(@types/react@19.2.7)(react@19.2.0)
'@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3)(@types/react@19.2.7)(react-dom@19.2.0)(react@19.2.0)
'@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.7)(react@19.2.0)
'@radix-ui/react-use-layout-effect': 1.1.1(@types/react@19.2.7)(react@19.2.0)
'@radix-ui/react-use-previous': 1.1.1(@types/react@19.2.7)(react@19.2.0)
'@radix-ui/react-use-size': 1.1.1(@types/react@19.2.7)(react@19.2.0)
'@types/react': 19.2.7
'@types/react-dom': 19.2.3(@types/react@19.2.7)
react: 19.2.0
react-dom: 19.2.0(react@19.2.0)
dev: false
/@radix-ui/react-slot@1.2.3(@types/react@19.2.7)(react@19.2.0):
resolution: {integrity: sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A==}
peerDependencies:
+20
View File
@@ -6,6 +6,15 @@ export const CustomCommandSchema = z.object({
promptTemplate: z.string(),
});
export const TTSConfigSchema = z.object({
enabled: z.boolean(),
endpoint: z.string(),
apiKey: z.string(),
voice: z.string(),
model: z.string(),
speed: z.number().min(0.25).max(4.0),
});
export const CustomAgentSchema = z.object({
name: z.string(),
description: z.string(),
@@ -35,8 +44,18 @@ export const UserPreferencesSchema = z.object({
customCommands: z.array(CustomCommandSchema),
customAgents: z.array(CustomAgentSchema),
gitToken: z.string().optional(),
tts: TTSConfigSchema.optional(),
});
export const DEFAULT_TTS_CONFIG = {
enabled: false,
endpoint: "https://api.openai.com/v1/audio/speech",
apiKey: "",
voice: "alloy",
model: "tts-1",
speed: 1.0,
};
export const DEFAULT_USER_PREFERENCES = {
theme: "dark" as const,
mode: "build" as const,
@@ -47,6 +66,7 @@ export const DEFAULT_USER_PREFERENCES = {
customCommands: [],
customAgents: [],
gitToken: undefined,
tts: DEFAULT_TTS_CONFIG,
};
export const SettingsResponseSchema = z.object({