diff --git a/frontend/src/components/settings/TTSSettings.tsx b/frontend/src/components/settings/TTSSettings.tsx index 4b278809..2e73c1ab 100644 --- a/frontend/src/components/settings/TTSSettings.tsx +++ b/frontend/src/components/settings/TTSSettings.tsx @@ -1,11 +1,12 @@ -import { useEffect, useState } from 'react' +import { useEffect, useState, useRef } 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 { useTTSModels, useTTSVoices, useTTSDiscovery } from '@/hooks/useTTSDiscovery' -import { Loader2, Volume2, Square, XCircle, RefreshCw } from 'lucide-react' +import { getAvailableVoiceNames, isWebSpeechSupported } from '@/lib/webSpeechSynthesizer' +import { Loader2, Volume2, Square, XCircle, RefreshCw, MonitorSpeaker, Globe, CheckCircle2 } from 'lucide-react' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Switch } from '@/components/ui/switch' @@ -28,58 +29,121 @@ function isKokoroStyleVoice(voice: string): boolean { 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'), + 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), -}).refine((data) => { - if (data.enabled && !data.apiKey) { - return false +}).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', + }) + } } - return true -}, { - message: 'API key is required when TTS is enabled', - path: ['apiKey'], }) type TTSFormValues = z.infer export function TTSSettings() { - const { preferences, isLoading, updateSettings, isUpdating } = useSettings() - const { speak, stop, isPlaying, isLoading: isTTSLoading, error: ttsError } = useTTS() + 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([]) + const [isCheckingBuiltin, setIsCheckingBuiltin] = useState(false) + + // Auto-save state + const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle') + const saveTimeoutRef = useRef | null>(null) + const lastSavedDataRef = useRef(null) const form = useForm({ resolver: zodResolver(ttsFormSchema), defaultValues: DEFAULT_TTS_CONFIG, }) - const { reset, formState: { isDirty, isValid } } = form - // Fetch available models and voices when TTS is configured + const { reset, formState: { isDirty, isValid }, getValues } = form + + // Fetch available models and voices for external provider const { data: modelsData, isLoading: isLoadingModels, refetch: refetchModels } = useTTSModels( - undefined, // Let the hook use default user - true // Always fetch if endpoint is available + undefined, + true ) const { data: voicesData, isLoading: isLoadingVoices, refetch: refetchVoices } = useTTSVoices( - undefined, // Let the hook use default user - true // Always fetch if endpoint is available + undefined, + true ) - // Use data from API discovery first, fallback to stored preferences 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') - const canTest = watchEnabled && watchApiKey && !isDirty && watchVoice && availableVoices.length > 0 + // 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) @@ -94,73 +158,114 @@ export function TTSSettings() { } } + 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-fetch models and voices when endpoint or API key changes + // Auto-save on change with debouncing useEffect(() => { - if (watchEnabled && watchApiKey && watchEndpoint) { - const timer = setTimeout(() => { - refetchModels() - refetchVoices() - }, 1000) // Debounce by 1 second to avoid rapid calls - - return () => clearTimeout(timer) + if (saveTimeoutRef.current) { + clearTimeout(saveTimeoutRef.current) } - }, [watchEndpoint, watchApiKey, watchEnabled, refetchModels, refetchVoices]) - - const onSubmit = (data: TTSFormValues) => { - updateSettings({ tts: data }) - } + + 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 = () => { - speak(TEST_PHRASE) + const formData = getValues() + speakWithConfig(TEST_PHRASE, formData) } const handleStopTest = () => { stop() } - - if (isLoading) { - return ( -
- -
- ) - } - + return (

Text-to-Speech

- + {saveStatus === 'saved' && ( + <> + + Saved + + )} + {saveStatus === 'idle' && isDirty && isValid && ( + Unsaved changes + )} + {saveStatus === 'idle' && !isDirty && ( + All changes saved + )} +
- + - ( - - TTS Server URL - - - - - Base URL of your TTS service (e.g., https://x.x.x.x:Port) - - - - )} - /> +
+ + +
+
+ Choose how you want to generate speech. Built-in works offline with no setup required. +
- ( - - API Key - - - - - API key for the TTS service - - - - )} - /> + {/* External Provider Settings */} + {watchProvider === 'external' && ( + <> + ( + + TTS Server URL + + { + field.onChange(e) + // Auto-save will handle debounced save + }} + /> + + + Base URL of your TTS service (e.g., https://x.x.x.x:Port) + + + + )} + /> - { - 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 ( - - Voice - - - - - {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'} - - - - ) - }} - /> + ( + + API Key + + { + field.onChange(e) + // Auto-save will handle debounced save + }} + /> + + + API key for the TTS service + + + + )} + /> - ( - - Model - - ({ - value: model, - label: model - }))} - placeholder="Select a model or type custom name..." - disabled={!watchEnabled || isLoadingModels} - allowCustomValue={true} - /> - - - {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'} - - - - )} - /> + { + 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 ( + + Voice + + + + + {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'} + + + + ) + }} + /> + ( + + Model + + ({ + value: model, + label: model + }))} + placeholder="Select a model or type custom name..." + disabled={!watchEnabled || isLoadingModels} + allowCustomValue={true} + /> + + + {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'} + + + + )} + /> + +
+
+
Refresh Discovery Data
+

+ Force refresh available models and voices from the endpoint +

+
+ +
+ + )} + + {/* Builtin Provider Settings */} + {watchProvider === 'builtin' && ( + <> + { + const voiceOptions = browserVoices.map((voice: string) => ({ + value: voice, + label: voice + })) + + return ( + + Browser Voice + + + + + {isCheckingBuiltin ? ( + + + Checking for voices... + + ) : browserVoices.length > 0 ? ( + `${browserVoices.length} voices available in your browser` + ) : !hasWebSpeechSupport ? ( + Web Speech API not supported in this browser + ) : ( + 'No voices found - try refreshing' + )} + + + + ) + }} + /> + + {!hasWebSpeechSupport && ( +
+
+ Browser Not Supported: Your browser doesn't support Web Speech API. + Please use Chrome, Safari, Firefox, or Edge, or switch to an external API provider. +
+
+ )} + + {hasWebSpeechSupport && browserVoices.length === 0 && ( +
+
+
Check for Voices
+

+ Your browser may need permission to access voices +

+
+ +
+ )} + + )} + + {/* Common Settings for both providers */} field.onChange(value)} + onValueChange={(values) => field.onChange(values[0])} className="w-full" /> - Playback speed (0.25x to 4.0x) + Playback speed (0.25x to 4.0x). Note: Web Speech API has limited speed control. )} /> -
-
-
Refresh Discovery Data
-

- Force refresh available models and voices from the endpoint -

-
- -
-
Test TTS

- {isDirty - ? 'Save changes before testing' - : 'Verify your TTS configuration works'} + Verify your TTS configuration works

{ttsError && (

{ttsError} - {ttsError.includes("not found") && availableVoices.length > 0 && ( - - Try selecting from: {availableVoices.slice(0, 5).join(", ")} - {availableVoices.length > 5 && ` +${availableVoices.length - 5} more`} - - )}

)} - {!ttsError && watchEnabled && watchApiKey && watchEndpoint && availableVoices.length === 0 && !isLoadingVoices && ( -

- Click "Refresh" to discover available voices, or check your API key and endpoint URL. + {watchProvider === 'builtin' && !hasWebSpeechSupport && ( +

+ + Web Speech API is not available

)}
diff --git a/frontend/src/contexts/TTSContext.tsx b/frontend/src/contexts/TTSContext.tsx index 2791f41e..12ddde7a 100644 --- a/frontend/src/contexts/TTSContext.tsx +++ b/frontend/src/contexts/TTSContext.tsx @@ -1,10 +1,11 @@ import { useState, useRef, useCallback, useEffect, type ReactNode } from 'react' import { useSettings } from '@/hooks/useSettings' import { API_BASE_URL } from '@/config' -import { TTSContext, type TTSState } from './tts-context' +import { TTSContext, type TTSState, type TTSConfig } from './tts-context' import { sanitizeForTTS } from '@/lib/utils' +import { getWebSpeechSynthesizer, isWebSpeechSupported } from '@/lib/webSpeechSynthesizer' -export { TTSContext, type TTSContextValue, type TTSState } from './tts-context' +export { TTSContext, type TTSContextValue, type TTSState, type TTSConfig } from './tts-context' const SENTENCE_REGEX = /(?<=[.!?])\s+/ const SENTENCES_PER_CHUNK = 2 @@ -40,16 +41,43 @@ export function TTSProvider({ children }: TTSProviderProps) { const chunkIndexRef = useRef(0) const prefetchedBlobsRef = useRef>(new Map()) const fetchingIndexRef = useRef(-1) + + // Web Speech API reference + const webSpeechSynthRef = useRef | null>(null) const ttsConfig = preferences?.tts - const isEnabled = !!(ttsConfig?.enabled && ttsConfig?.apiKey) + const isBuiltin = ttsConfig?.provider === 'builtin' + const isEnabled = (() => { + if (!ttsConfig?.enabled) return false + if (isBuiltin) { + return isWebSpeechSupported() + } + // External requires apiKey + return !!ttsConfig?.apiKey + })() + + // Initialize Web Speech synthesizer on demand + const getSynthesizer = useCallback(() => { + if (!webSpeechSynthRef.current) { + webSpeechSynthRef.current = getWebSpeechSynthesizer(); + } + return webSpeechSynthRef.current; + }, []); const cleanup = useCallback(() => { + // Stop external audio if (audioRef.current) { audioRef.current.pause() audioRef.current.src = '' audioRef.current = null } + + // Stop Web Speech API + if (webSpeechSynthRef.current && isBuiltin) { + webSpeechSynthRef.current.stop() + webSpeechSynthRef.current.clearCallbacks() + } + if (abortControllerRef.current) { abortControllerRef.current.abort() abortControllerRef.current = null @@ -61,7 +89,7 @@ export function TTSProvider({ children }: TTSProviderProps) { chunksRef.current = [] chunkIndexRef.current = 0 fetchingIndexRef.current = -1 - }, []) + }, [isBuiltin]) const stop = useCallback(() => { stoppedRef.current = true @@ -79,7 +107,8 @@ export function TTSProvider({ children }: TTSProviderProps) { } }, [cleanup]) - const synthesize = useCallback(async (text: string, signal?: AbortSignal): Promise => { + // External API synthesis + const synthesizeExternal = useCallback(async (text: string, signal?: AbortSignal): Promise => { if (stoppedRef.current) return null try { @@ -135,7 +164,7 @@ export function TTSProvider({ children }: TTSProviderProps) { fetchingIndexRef.current = index try { - const blob = await synthesize(chunksRef.current[index], abortControllerRef.current?.signal) + const blob = await synthesizeExternal(chunksRef.current[index], abortControllerRef.current?.signal) if (blob && !stoppedRef.current) { prefetchedBlobsRef.current.set(index, blob) fetchNextChunk(index + 1) @@ -145,7 +174,7 @@ export function TTSProvider({ children }: TTSProviderProps) { } fetchingIndexRef.current = -1 - }, [synthesize]) + }, [synthesizeExternal]) const playChunk = useCallback(async (index: number) => { if (stoppedRef.current || index >= chunksRef.current.length) { @@ -163,7 +192,7 @@ export function TTSProvider({ children }: TTSProviderProps) { if (!blob) { setState('loading') - const fetched = await synthesize(chunksRef.current[index], abortControllerRef.current?.signal) + const fetched = await synthesizeExternal(chunksRef.current[index], abortControllerRef.current?.signal) if (fetched && !stoppedRef.current) { blob = fetched } @@ -202,17 +231,12 @@ export function TTSProvider({ children }: TTSProviderProps) { setError(err instanceof Error ? err.message : 'TTS failed') setState('error') } - }, [synthesize, fetchNextChunk]) + }, [synthesizeExternal, fetchNextChunk]) - const speak = useCallback(async (text: string): Promise => { - if (!ttsConfig?.enabled) { - setError('TTS is not enabled') - setState('error') - return false - } - - if (!ttsConfig?.apiKey) { - setError('API key not configured') + // Builtin Web Speech synthesis - takes explicit config + const speakBuiltinWithConfig = useCallback(async (text: string, config: TTSConfig): Promise => { + if (!isWebSpeechSupported()) { + setError('Web Speech API not supported in this browser') setState('error') return false } @@ -223,13 +247,6 @@ export function TTSProvider({ children }: TTSProviderProps) { return false } - if (!ttsConfig.voice || !ttsConfig.model) { - setError('Voice or model not configured') - setState('error') - return false - } - - // Sanitize markdown for clean TTS playback const sanitizedText = sanitizeForTTS(text) if (!sanitizedText?.trim()) { @@ -244,17 +261,126 @@ export function TTSProvider({ children }: TTSProviderProps) { setOriginalText(text) setCurrentText(sanitizedText) + setState('loading') - abortControllerRef.current = new AbortController() - chunksRef.current = splitIntoChunks(sanitizedText) + const synth = getSynthesizer() + await synth.waitForVoices() + + const voiceName = config.voice || '' - playChunk(0) + synth.clearCallbacks() - return true - }, [ttsConfig, stop, playChunk]) + synth.onEnd(() => { + if (!stoppedRef.current) { + setState('idle') + setCurrentText(null) + } + }) + + synth.onError((err) => { + if (!stoppedRef.current) { + setError(err) + setState('error') + } + }) + + try { + setState('playing') + + const rate = config.speed || 1.0 + + await synth.speakChunked(sanitizedText, 200, { + voice: voiceName || undefined, + rate: rate, + }) + + return true + } catch (err) { + if (stoppedRef.current) return false + setError(err instanceof Error ? err.message : 'TTS failed') + setState('error') + return false + } + }, [stop, getSynthesizer]) + + // Config-aware speak function - takes explicit config + const speakWithConfig = useCallback(async (text: string, config: TTSConfig): Promise => { + if (!config.enabled) { + setError('TTS is not enabled') + setState('error') + return false + } + + const configIsBuiltin = config.provider === 'builtin' + + if (configIsBuiltin) { + if (!isWebSpeechSupported()) { + setError('Web Speech API not supported in this browser') + setState('error') + return false + } + return speakBuiltinWithConfig(text, config) + } else { + if (!config.apiKey) { + setError('API key not configured') + setState('error') + return false + } + + if (!config.voice || !config.model) { + setError('Voice or model not configured') + setState('error') + return false + } + + const sanitizedText = sanitizeForTTS(text) + + if (!sanitizedText?.trim()) { + setError('No readable content after sanitization') + setState('error') + return false + } + + stop() + stoppedRef.current = false + setError(null) + + setOriginalText(text) + setCurrentText(sanitizedText) + + abortControllerRef.current = new AbortController() + chunksRef.current = splitIntoChunks(sanitizedText) + + playChunk(0) + + return true + } + }, [speakBuiltinWithConfig, stop, playChunk]) + + // Main speak function - uses stored preferences + const speak = useCallback(async (text: string): Promise => { + if (!ttsConfig) { + setError('TTS is not configured') + setState('error') + return false + } + + const config: TTSConfig = { + enabled: ttsConfig.enabled ?? false, + provider: ttsConfig.provider ?? 'external', + endpoint: ttsConfig.endpoint ?? '', + apiKey: ttsConfig.apiKey ?? '', + voice: ttsConfig.voice ?? '', + model: ttsConfig.model ?? '', + speed: ttsConfig.speed ?? 1.0, + } + + return speakWithConfig(text, config) + }, [ttsConfig, speakWithConfig]) const value = { speak, + speakWithConfig, stop, state, error, diff --git a/frontend/src/contexts/tts-context.ts b/frontend/src/contexts/tts-context.ts index 9889f70b..e9a76bf0 100644 --- a/frontend/src/contexts/tts-context.ts +++ b/frontend/src/contexts/tts-context.ts @@ -2,8 +2,19 @@ import { createContext } from 'react' export type TTSState = 'idle' | 'loading' | 'playing' | 'error' +export interface TTSConfig { + enabled: boolean + provider: 'external' | 'builtin' + endpoint: string + apiKey: string + voice: string + model: string + speed: number +} + export interface TTSContextValue { speak: (text: string) => Promise + speakWithConfig: (text: string, config: TTSConfig) => Promise stop: () => void state: TTSState error: string | null diff --git a/frontend/src/hooks/useSettings.ts b/frontend/src/hooks/useSettings.ts index bc8b2dc7..61628d19 100644 --- a/frontend/src/hooks/useSettings.ts +++ b/frontend/src/hooks/useSettings.ts @@ -14,8 +14,37 @@ export function useSettings(userId = 'default') { const updateMutation = useMutation({ mutationFn: (updates: Partial) => settingsApi.updateSettings({ preferences: updates }, userId), - onSuccess: (newData) => { - queryClient.setQueryData(['settings', userId], newData) + onMutate: async (updates) => { + // Cancel outgoing refetches + await queryClient.cancelQueries({ queryKey: ['settings', userId] }) + + // Snapshot current value + const previousData = queryClient.getQueryData(['settings', userId]) + + // Optimistically update cache immediately + queryClient.setQueryData(['settings', userId], (old: typeof data) => { + if (!old) return old + return { + ...old, + preferences: { + ...old.preferences, + ...updates, + }, + updatedAt: Date.now(), + } + }) + + return { previousData } + }, + onError: (_err, _updates, context) => { + // Rollback on error + if (context?.previousData) { + queryClient.setQueryData(['settings', userId], context.previousData) + } + }, + onSettled: () => { + // Refetch to ensure server state + queryClient.invalidateQueries({ queryKey: ['settings', userId] }) }, }) diff --git a/shared/src/schemas/settings.ts b/shared/src/schemas/settings.ts index 85335128..46e0f7c9 100644 --- a/shared/src/schemas/settings.ts +++ b/shared/src/schemas/settings.ts @@ -8,6 +8,7 @@ export const CustomCommandSchema = z.object({ export const TTSConfigSchema = z.object({ enabled: z.boolean(), + provider: z.enum(['external', 'builtin']).default('external'), endpoint: z.string(), apiKey: z.string(), voice: z.string(), @@ -27,6 +28,7 @@ export const CustomAgentSchema = z.object({ export type TTSConfig = { enabled: boolean; + provider: 'external' | 'builtin'; endpoint: string; apiKey: string; voice: string; @@ -75,6 +77,7 @@ export const UserPreferencesSchema = z.object({ export const DEFAULT_TTS_CONFIG: TTSConfig = { enabled: false, + provider: 'external', endpoint: "https://api.openai.com", apiKey: "", voice: "alloy",