'use client' import { useEffect, useId, useRef, useState } from 'react' import { Loader2, Volume2 } from 'lucide-react' import { useTranslation } from 'react-i18next' import { useSettings } from '@/features/settings/store/SettingsStore' import { apiFetch, apiUrl } from '@/lib/api' import { modelTestFingerprint } from '@/lib/model-settings' import { speechRequestTimeout, SPEECH_TIMEOUT_MESSAGE } from '@/lib/voice-settings' import { inputClass, subPanelClass } from './shared' import { registryButton } from './RegistryControls' export function VoicePreviewPanel({ profileId, modelId, maxChars = 500, }: { profileId: string modelId: string maxChars?: number }) { const { draft } = useSettings() // A different model, voice, language, parameter or credential invalidates the // clip and aborts any request, including late completions from old selections. return ( ) } function PreviewRequest({ profileId, modelId, maxChars, }: { profileId: string modelId: string maxChars: number }) { const { t, i18n } = useTranslation() const { draft } = useSettings() const [text, setText] = useState(() => i18n?.language?.startsWith('zh') ? '你好,我是你的学习伙伴。让我们一起探索新的知识。' : 'Hello, I am your learning companion. Let us explore something new together.' ) const [pending, setPending] = useState(false) const [url, setUrl] = useState(null) const [error, setError] = useState('') const controller = useRef(null) const textId = useId() useEffect(() => () => controller.current?.abort(), []) useEffect( () => () => { if (url) URL.revokeObjectURL(url) }, [url] ) const clear = () => { controller.current?.abort() setPending(false) setUrl(null) setError('') } const preview = async () => { clear() const request = new AbortController() controller.current = request setPending(true) const model = draft.services.tts.profiles.find(p => p.id === profileId)?.models.find(m => m.id === modelId) // Allow the configured backend deadline plus time to return its error. const timeout = setTimeout(() => request.abort(), (speechRequestTimeout(model) + 5) * 1000) try { const response = await apiFetch(apiUrl('/api/settings/voice/preview'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, signal: request.signal, body: JSON.stringify({ catalog: draft, profile_id: profileId, model_id: modelId, text }), }) if (!response.ok) { // A reverse proxy can replace the backend's JSON error with an HTML // page; parse defensively and surface the status instead of the // resulting JSON syntax error. const payload = (await response.json().catch(() => ({}))) as { detail?: unknown } throw new Error( typeof payload.detail === 'string' && payload.detail.trim() ? payload.detail : t('Voice preview failed (HTTP {{status}}).', { status: response.status }) ) } const audio = await response.blob() if (request.signal.aborted) return if (!audio.size || !audio.type.startsWith('audio/')) throw new Error('The provider returned no playable audio.') setUrl(URL.createObjectURL(audio)) } catch (err) { if (!request.signal.aborted) setError(err instanceof Error ? err.message : 'Voice preview failed.') else if (controller.current === request) setError(SPEECH_TIMEOUT_MESSAGE) } finally { clearTimeout(timeout) if (controller.current === request) setPending(false) } } return ( {t('Voice preview')} void preview()} disabled={pending || !text.trim() || text.length > maxChars} > {pending ? : } {t(pending ? 'Generating preview…' : 'Preview voice')} {t('Preview text')} { clear() controller.current = null setText(e.target.value) }} /> {t( "Uses the current form without saving. Choose text in the voice's language. The provider may charge for this synthesis." )} {pending && ( { clear() controller.current = null }} > {t('Cancel')} )} {error && ( {t(error)} )} {url && ( )} ) }
{t( "Uses the current form without saving. Choose text in the voice's language. The provider may charge for this synthesis." )}
{t(error)}