-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathTTSSettings.tsx
More file actions
663 lines (614 loc) · 26 KB
/
TTSSettings.tsx
File metadata and controls
663 lines (614 loc) · 26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
import { useEffect, useState, useRef } from 'react'
import { useForm } from 'react-hook-form'
import { standardSchemaResolver } from '@hookform/resolvers/standard-schema'
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 { Button } from '@/components/ui/button'
import { SquareFill } from '@/components/ui/square-fill'
import { Input } from '@/components/ui/input'
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 { DEFAULT_TTS_CONFIG } from '@/api/types/settings'
const TEST_PHRASE = 'Text to speech is working correctly.'
const KOKORO_COMPOSITE_VOICE_SUGGESTIONS = [
{ value: "am_adam+am_echo", label: "Composite: am_adam+am_echo" },
{ value: "af_bella+af_nova", label: "Composite: af_bella+af_nova" },
{ value: "bm_daniel+bm_george", label: "Composite: bm_daniel+bm_george" },
]
function isKokoroStyleVoice(voice: string): boolean {
return /^[a-z]{2}_/.test(voice)
}
const ttsFormSchema = z.object({
enabled: z.boolean(),
provider: z.enum(['external', 'builtin']),
endpoint: z.string(),
apiKey: z.string(),
voice: z.string(),
model: z.string(),
speed: z.number().min(0.25).max(4.0),
}).superRefine((data, ctx) => {
if (!data.enabled) return
// External provider specific validation
if (data.provider === 'external') {
if (!data.apiKey || data.apiKey.trim().length === 0) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['apiKey'],
message: 'API key is required',
})
}
if (!data.endpoint || data.endpoint.trim().length === 0) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['endpoint'],
message: 'Endpoint is required',
})
}
}
// Voice requirement depends on provider
if (!data.voice || data.voice.trim().length === 0) {
if (data.provider === 'builtin') {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['voice'],
message: 'Please select a browser voice',
})
}
}
})
type TTSFormValues = z.infer<typeof ttsFormSchema>
export function TTSSettings() {
const { preferences, updateSettings } = useSettings()
const { speakWithConfig, stop, isPlaying, isLoading: isTTSLoading, error: ttsError } = useTTS()
const { refreshAll } = useTTSDiscovery()
const [isRefreshingDiscovery, setIsRefreshingDiscovery] = useState(false)
const [browserVoices, setBrowserVoices] = useState<string[]>([])
const [isCheckingBuiltin, setIsCheckingBuiltin] = useState(false)
// Auto-save state
const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle')
const saveTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const lastSavedDataRef = useRef<TTSFormValues | null>(null)
const form = useForm<TTSFormValues>({
resolver: standardSchemaResolver(ttsFormSchema),
defaultValues: DEFAULT_TTS_CONFIG,
})
const { reset, formState: { isDirty, isValid }, getValues } = form
// Fetch available models and voices for external provider
const { data: modelsData, isLoading: isLoadingModels, refetch: refetchModels } = useTTSModels(
undefined,
true
)
const { data: voicesData, isLoading: isLoadingVoices, refetch: refetchVoices } = useTTSVoices(
undefined,
true
)
const availableModels = modelsData?.models || preferences?.tts?.availableModels || []
const availableVoices = voicesData?.voices || preferences?.tts?.availableVoices || []
const modelsCached = modelsData?.cached || false
const voicesCached = voicesData?.cached || false
const watchEnabled = form.watch('enabled')
const watchProvider = form.watch('provider')
const watchApiKey = form.watch('apiKey')
const watchEndpoint = form.watch('endpoint')
const watchVoice = form.watch('voice')
const watchModel = form.watch('model')
const watchSpeed = form.watch('speed')
// Check builtin Web Speech API support
const hasWebSpeechSupport = isWebSpeechSupported()
// Determine if test button should be enabled
// With auto-save, we allow testing as long as settings are valid (no need to wait for save)
const canTest = (() => {
if (!watchEnabled) return false
if (watchProvider === 'builtin') {
return hasWebSpeechSupport && browserVoices.length > 0 && !!watchVoice && !isCheckingBuiltin
} else {
return !!watchApiKey && !!watchVoice && !isLoadingVoices
}
})()
// Load browser voices when provider is builtin
useEffect(() => {
if (watchProvider === 'builtin' && watchEnabled) {
setIsCheckingBuiltin(true)
getAvailableVoiceNames()
.then((voices) => {
setBrowserVoices(voices)
setIsCheckingBuiltin(false)
})
.catch(() => {
setBrowserVoices([])
setIsCheckingBuiltin(false)
})
}
}, [watchProvider, watchEnabled])
const handleRefreshDiscovery = async () => {
setIsRefreshingDiscovery(true)
try {
await refreshAll()
await Promise.all([
refetchModels(),
refetchVoices()
])
} finally {
setIsRefreshingDiscovery(false)
}
}
const handleCheckBuiltin = async () => {
setIsCheckingBuiltin(true)
try {
const voices = await getAvailableVoiceNames()
setBrowserVoices(voices)
} finally {
setIsCheckingBuiltin(false)
}
}
// Load preferences into form
useEffect(() => {
if (preferences?.tts) {
reset({
enabled: preferences.tts.enabled ?? DEFAULT_TTS_CONFIG.enabled,
provider: preferences.tts.provider ?? DEFAULT_TTS_CONFIG.provider,
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,
})
lastSavedDataRef.current = preferences.tts
setSaveStatus('idle')
}
}, [preferences?.tts, reset])
// Auto-save on change with debouncing
useEffect(() => {
if (saveTimeoutRef.current) {
clearTimeout(saveTimeoutRef.current)
}
if (!isDirty) {
setSaveStatus('idle')
return
}
if (!isValid) {
setSaveStatus('idle')
return
}
setSaveStatus('saving')
saveTimeoutRef.current = setTimeout(() => {
const formData = getValues()
if (lastSavedDataRef.current && JSON.stringify(formData) === JSON.stringify(lastSavedDataRef.current)) {
setSaveStatus('idle')
return
}
updateSettings({ tts: formData })
lastSavedDataRef.current = formData
setSaveStatus('saved')
setTimeout(() => {
setSaveStatus('idle')
}, 1500)
}, 800)
return () => {
if (saveTimeoutRef.current) {
clearTimeout(saveTimeoutRef.current)
}
}
}, [watchEnabled, watchProvider, watchApiKey, watchEndpoint, watchVoice, watchModel, watchSpeed, isValid, isDirty, getValues, updateSettings])
const handleTest = () => {
const formData = getValues()
speakWithConfig(TEST_PHRASE, formData)
}
const handleStopTest = () => {
stop()
}
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>
{/* Show auto-save status instead of save button */}
<div className="flex items-center gap-2 text-sm">
{saveStatus === 'saving' && (
<>
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
<span className="text-muted-foreground">Saving...</span>
</>
)}
{saveStatus === 'saved' && (
<>
<CheckCircle2 className="h-4 w-4 text-green-500" />
<span className="text-green-600">Saved</span>
</>
)}
{saveStatus === 'idle' && isDirty && isValid && (
<span className="text-amber-600">Unsaved changes</span>
)}
{saveStatus === 'idle' && !isDirty && (
<span className="text-muted-foreground">All changes saved</span>
)}
</div>
</div>
<Form {...form}>
<form 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 && (
<>
<div className="grid grid-cols-2 gap-3">
<button
type="button"
onClick={() => {
form.setValue('provider', 'builtin', { shouldDirty: true })
form.setValue('apiKey', '', { shouldDirty: true })
form.setValue('endpoint', '', { shouldDirty: true })
}}
className={`flex flex-col items-center justify-center gap-2 rounded-lg border-2 p-4 transition ${
watchProvider === 'builtin'
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
: 'border-border hover:border-blue-300'
}`}
>
<MonitorSpeaker className={`h-6 w-6 ${watchProvider === 'builtin' ? 'text-blue-600 dark:text-blue-400' : 'text-muted-foreground'}`} />
<span className={`font-medium ${watchProvider === 'builtin' ? 'text-blue-700 dark:text-blue-300' : ''}`}>
Built-in Browser
</span>
<span className="text-xs text-muted-foreground text-center">
No API key or URL needed
</span>
</button>
<button
type="button"
onClick={() => {
form.setValue('provider', 'external', { shouldDirty: true })
}}
className={`flex flex-col items-center justify-center gap-2 rounded-lg border-2 p-4 transition ${
watchProvider === 'external'
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
: 'border-border hover:border-blue-300'
}`}
>
<Globe className={`h-6 w-6 ${watchProvider === 'external' ? 'text-blue-600 dark:text-blue-400' : 'text-muted-foreground'}`} />
<span className={`font-medium ${watchProvider === 'external' ? 'text-blue-700 dark:text-blue-300' : ''}`}>
External API
</span>
<span className="text-xs text-muted-foreground text-center">
OpenAI, Kokoro, etc.
</span>
</button>
</div>
<div className="text-xs text-muted-foreground mt-1">
Choose how you want to generate speech. Built-in works offline with no setup required.
</div>
{/* External Provider Settings */}
{watchProvider === 'external' && (
<>
<FormField
control={form.control}
name="endpoint"
render={({ field }) => (
<FormItem>
<FormLabel>TTS Server URL</FormLabel>
<FormControl>
<Input
placeholder="https://api.openai.com"
className="bg-background"
{...field}
onChange={(e) => {
field.onChange(e)
// Auto-save will handle debounced save
}}
/>
</FormControl>
<FormDescription>
Base URL of your TTS service (e.g., https://x.x.x.x:Port)
</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}
onChange={(e) => {
field.onChange(e)
// Auto-save will handle debounced save
}}
/>
</FormControl>
<FormDescription>
API key for the TTS service
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="voice"
render={({ field }) => {
const hasKokoroVoices = availableVoices.some(isKokoroStyleVoice)
const voiceOptions = [
...availableVoices.slice(0, 10).map((voice: string) => ({
value: voice,
label: voice
})),
...(hasKokoroVoices ? KOKORO_COMPOSITE_VOICE_SUGGESTIONS : []),
...availableVoices.slice(10).map((voice: string) => ({
value: voice,
label: voice
}))
]
return (
<FormItem>
<FormLabel>Voice</FormLabel>
<FormControl>
<Combobox
value={field.value}
onChange={field.onChange}
options={voiceOptions}
placeholder={hasKokoroVoices ? "Select a voice or type custom name (e.g., am_adam+am_echo)..." : "Select a voice..."}
disabled={!watchEnabled || isLoadingVoices}
allowCustomValue={true}
/>
</FormControl>
<FormDescription>
{isLoadingVoices ? 'Loading available voices...' :
voicesCached ? `Available voices (${availableVoices.length}) - cached` :
availableVoices.length > 0 ? `Available voices (${availableVoices.length})${hasKokoroVoices ? ' - Support composite voices (e.g., am_adam+am_echo)' : ''}` :
watchEnabled && watchApiKey ? 'No voices available - check endpoint and API key' :
'Configure TTS to discover voices'}
</FormDescription>
<FormMessage />
</FormItem>
)
}}
/>
<FormField
control={form.control}
name="model"
render={({ field }) => (
<FormItem>
<FormLabel>Model</FormLabel>
<FormControl>
<Combobox
value={field.value}
onChange={field.onChange}
options={availableModels.map((model: string) => ({
value: model,
label: model
}))}
placeholder="Select a model or type custom name..."
disabled={!watchEnabled || isLoadingModels}
allowCustomValue={true}
/>
</FormControl>
<FormDescription>
{isLoadingModels ? 'Loading available models...' :
modelsCached ? `Available models (${availableModels.length}) - cached` :
availableModels.length > 0 ? `Available models (${availableModels.length})` :
watchEnabled && watchApiKey ? 'No models available - check endpoint and API key' :
'Configure TTS to discover models'}
</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">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>
</>
)}
{/* Builtin Provider Settings */}
{watchProvider === 'builtin' && (
<>
<FormField
control={form.control}
name="voice"
render={({ field }) => {
const voiceOptions = browserVoices.map((voice: string) => ({
value: voice,
label: voice
}))
return (
<FormItem>
<FormLabel>Browser Voice</FormLabel>
<FormControl>
<Combobox
value={field.value}
onChange={field.onChange}
options={voiceOptions}
placeholder={isCheckingBuiltin ? "Loading voices..." : "Select a voice..."}
disabled={!watchEnabled || isCheckingBuiltin || browserVoices.length === 0}
allowCustomValue={false}
/>
</FormControl>
<FormDescription>
{isCheckingBuiltin ? (
<span className="flex items-center gap-1">
<Loader2 className="h-3 w-3 animate-spin" />
Checking for voices...
</span>
) : browserVoices.length > 0 ? (
`${browserVoices.length} voices available in your browser`
) : !hasWebSpeechSupport ? (
<span className="text-destructive">Web Speech API not supported in this browser</span>
) : (
'No voices found - try refreshing'
)}
</FormDescription>
<FormMessage />
</FormItem>
)
}}
/>
{!hasWebSpeechSupport && (
<div className="rounded-lg bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 p-4">
<div className="text-sm text-yellow-800 dark:text-yellow-200">
<strong>Browser Not Supported</strong>: Your browser doesn't support Web Speech API.
Please use Chrome, Safari, Firefox, or Edge, or switch to an external API provider.
</div>
</div>
)}
{hasWebSpeechSupport && browserVoices.length === 0 && (
<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">Check for Voices</div>
<p className="text-sm text-muted-foreground">
Your browser may need permission to access voices
</p>
</div>
<Button
type="button"
variant="outline"
size="sm"
onClick={handleCheckBuiltin}
disabled={isCheckingBuiltin}
>
{isCheckingBuiltin ? (
<>
<Loader2 className="h-4 w-4 animate-spin mr-2" />
Checking...
</>
) : (
<>
<RefreshCw className="h-4 w-4 mr-2" />
Check for Voices
</>
)}
</Button>
</div>
)}
</>
)}
{/* Common Settings for both providers */}
<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={(values) => field.onChange(values[0])}
className="w-full"
/>
</FormControl>
<FormDescription>
Playback speed (0.25x to 4.0x). Note: Web Speech API has limited speed control.
</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">
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>
)}
{watchProvider === 'builtin' && !hasWebSpeechSupport && (
<p className="text-sm text-destructive flex items-center gap-1">
<XCircle className="h-4 w-4" />
Web Speech API is not available
</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 ? (
<>
<SquareFill className="h-4 w-4 mr-2" />
Stop
</>
) : (
<>
<Volume2 className="h-4 w-4 mr-2" />
Test
</>
)}
</Button>
</div>
</>
)}
</form>
</Form>
</div>
)
}