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 { useSTT } from '@/hooks/useSTT' import { isWebRecognitionSupported, getAvailableLanguages } from '@/lib/webSpeechRecognizer' import { sttApi } from '@/api/stt' import { Mic, Loader2, XCircle, CheckCircle2, RefreshCw, Eye, EyeOff, MicOff } from 'lucide-react' import { Switch } from '@/components/ui/switch' import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form' import { Combobox } from '@/components/ui/combobox' import { DEFAULT_STT_CONFIG } from '@/api/types/settings' const sttFormSchema = z.object({ enabled: z.boolean(), provider: z.enum(['external', 'builtin']), endpoint: z.string(), apiKey: z.string(), model: z.string(), language: z.string(), }).superRefine((data, ctx) => { if (!data.enabled) return if (data.provider === 'external') { if (!data.endpoint || data.endpoint.trim().length === 0) { ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['endpoint'], message: 'Endpoint is required for external provider', }) } } }) type STTFormValues = z.infer export function STTSettings() { const { preferences, updateSettings } = useSettings() const { startRecording, stopRecording, abortRecording, isRecording, isProcessing, transcript, interimTranscript, error: sttError, isExternalProvider } = useSTT() const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle') const [isTesting, setIsTesting] = useState(false) const [testTranscript, setTestTranscript] = useState('') const [testResult, setTestResult] = useState<'idle' | 'success' | 'failed'>('idle') const [showApiKey, setShowApiKey] = useState(false) const [availableModels, setAvailableModels] = useState(['whisper-1']) const [isLoadingModels, setIsLoadingModels] = useState(false) const isWebSpeechAvailable = isWebRecognitionSupported() const form = useForm({ resolver: zodResolver(sttFormSchema), defaultValues: { ...DEFAULT_STT_CONFIG, model: DEFAULT_STT_CONFIG.model || 'whisper-1', }, }) const { reset, formState: { isDirty, isValid }, getValues, setValue } = form const availableLanguages = getAvailableLanguages() const watchEnabled = form.watch('enabled') const watchProvider = form.watch('provider') const watchLanguage = form.watch('language') const watchEndpoint = form.watch('endpoint') const watchApiKey = form.watch('apiKey') const watchModel = form.watch('model') const fetchModels = async (forceRefresh = false) => { if (!watchEndpoint) return setIsLoadingModels(true) try { const response = await sttApi.getModels('default', forceRefresh) setAvailableModels(response.models.length > 0 ? response.models : ['whisper-1']) if (!watchModel && response.models.length > 0) { setValue('model', response.models[0]) } } catch { setAvailableModels(['whisper-1']) } finally { setIsLoadingModels(false) } } useEffect(() => { if (watchProvider === 'external' && watchEndpoint) { const timer = setTimeout(() => { fetchModels() }, 500) return () => clearTimeout(timer) } // eslint-disable-next-line react-hooks/exhaustive-deps }, [watchProvider, watchEndpoint]) const handleTest = async () => { if (isTesting || isRecording) { if (isExternalProvider) { stopRecording() } else { abortRecording() setIsTesting(false) if (testTranscript) { setTestResult('success') } } return } setTestTranscript('') setTestResult('idle') setIsTesting(true) await startRecording() } useEffect(() => { if (isTesting && !isRecording && !isProcessing) { if (transcript) { setTestTranscript(transcript) setTestResult('success') setTimeout(() => { setIsTesting(false) }, 1000) } else if (sttError) { setTestResult('failed') setIsTesting(false) } } }, [isTesting, isRecording, isProcessing, transcript, sttError]) useEffect(() => { if (isTesting && interimTranscript && interimTranscript !== 'Processing...' && interimTranscript !== 'Recording...') { setTestTranscript(interimTranscript) } }, [isTesting, interimTranscript]) useEffect(() => { if (preferences?.stt) { const sttPrefs = preferences.stt as typeof preferences.stt & { model?: string; availableModels?: string[] } reset({ enabled: sttPrefs.enabled ?? DEFAULT_STT_CONFIG.enabled, provider: sttPrefs.provider ?? DEFAULT_STT_CONFIG.provider, endpoint: sttPrefs.endpoint ?? DEFAULT_STT_CONFIG.endpoint, apiKey: sttPrefs.apiKey ?? DEFAULT_STT_CONFIG.apiKey, model: sttPrefs.model ?? 'whisper-1', language: sttPrefs.language ?? DEFAULT_STT_CONFIG.language, }) if (sttPrefs.availableModels && sttPrefs.availableModels.length > 0) { setAvailableModels(sttPrefs.availableModels) } } // eslint-disable-next-line react-hooks/exhaustive-deps }, [preferences?.stt]) useEffect(() => { const timer = setTimeout(() => { if (isDirty && isValid) { const formData = getValues() updateSettings({ stt: formData }) setSaveStatus('saved') setTimeout(() => setSaveStatus('idle'), 1500) } }, 800) return () => clearTimeout(timer) }, [watchEnabled, watchProvider, watchLanguage, watchEndpoint, watchApiKey, watchModel, isDirty, isValid, getValues, updateSettings]) const canTestBuiltin = watchEnabled && watchProvider === 'builtin' && isWebSpeechAvailable const canTestExternal = watchEnabled && watchProvider === 'external' && watchEndpoint const canTest = canTestBuiltin || canTestExternal return (

Speech-to-Text

{saveStatus === 'saved' && ( <> Saved )} {saveStatus === 'idle' && isDirty && isValid && ( Unsaved changes )} {saveStatus === 'idle' && !isDirty && ( All changes saved )}
(
Enable STT Allow speech-to-text input for voice messages
)} /> {watchEnabled && ( <> ( Provider {watchProvider === 'builtin' ? "Uses browser's built-in speech recognition (free, requires Chrome/Safari/Edge)" : "Uses OpenAI Whisper API or compatible endpoint (requires API key)" } )} /> {watchProvider === 'external' && ( <> ( API Endpoint Base URL for the Whisper-compatible API (e.g., OpenAI, local Whisper server) )} /> ( API Key
Your API key for the speech-to-text service (optional for some servers)
)} /> (
Model
({ value: model, label: model, }))} placeholder="Select model..." disabled={isLoadingModels} allowCustomValue={true} /> The speech-to-text model to use (e.g., whisper-1)
)} /> )} {watchProvider === 'builtin' && ( <> ( Language ({ value: lang, label: lang.replace('-', ' - ') }))} placeholder="Select language..." disabled={!isWebSpeechAvailable} allowCustomValue={false} /> Select the language for speech recognition )} /> )} {sttError && (
{sttError}
)}
Test STT

{watchProvider === 'external' ? 'Record audio, then click Stop to transcribe' : 'Verify your speech recognition is working' }

{(isTesting || isProcessing) && (

{testTranscript || (isProcessing ? 'Processing...' : 'Listening...')}

{isRecording && (
Recording...
)} {isProcessing && !isRecording && (
Transcribing...
)}
)} {!isTesting && !isProcessing && testResult === 'success' && testTranscript && (
Test successful

{testTranscript}

)} {!isTesting && !isProcessing && testResult === 'failed' && (
Test failed - {sttError || 'no speech detected'}
)}
)}
) }