The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
feat(tts): external OpenAI-compatible TTS engine over HTTP (GH #58)
purplefc3b1b870d3d
diff --git a/src-tauri/src/commands/tts.rs b/src-tauri/src/commands/tts.rsindex d939d476..eb5e916b 100644--- a/src-tauri/src/commands/tts.rs+++ b/src-tauri/src/commands/tts.rs@@ -223,3 +223,88 @@ pub fn synthesize(let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes);Ok(serde_json::json!({ "audio_base64": b64, "mime": "audio/wav" }))}++/// Synthesize `text` via a user-configured external HTTP TTS engine and return+/// it base64-encoded for the frontend to play (GitHub #58). The endpoint is an+/// OpenAI-compatible `/v1/audio/speech` URL — e.g. Kokoro-FastAPI on+/// `http://localhost:8880/v1/audio/speech`, or any OpenAI-compatible TTS server.+///+/// SSRF note: unlike `proxy::fetch_external`, this deliberately does NOT run the+/// localhost/private-IP block. The endpoint comes from the Settings UI (the+/// user's own voice config), never from model output or chat content, so there+/// is no attacker-controlled-URL vector — and pointing at a LOCAL engine+/// (localhost:8880) is the entire point, exactly like LU's local Ollama /+/// ComfyUI / LM Studio connections.+#[tauri::command]+pub async fn synthesize_external(+ text: String,+ url: String,+ voice: Option<String>,+) -> Result<serde_json::Value, String> {+ let text = text.trim().to_string();+ if text.is_empty() {+ return Err("empty text".to_string());+ }++ // Light validation only — must be a well-formed http(s) URL. Localhost/LAN+ // is allowed on purpose (see the SSRF note above).+ let parsed = url::Url::parse(url.trim()).map_err(|e| format!("invalid TTS endpoint URL: {}", e))?;+ match parsed.scheme() {+ "http" | "https" => {}+ other => return Err(format!("TTS endpoint must be http or https, got '{}'", other)),+ }++ // OpenAI-compatible engines require a voice. Default to OpenAI's "alloy";+ // Kokoro users set their own (e.g. "af_bella") in Settings.+ let voice = voice+ .map(|v| v.trim().to_string())+ .filter(|v| !v.is_empty())+ .unwrap_or_else(|| "alloy".to_string());++ let client = reqwest::Client::builder()+ .user_agent("LocallyUncensored/2.0")+ .timeout(std::time::Duration::from_secs(120))+ .build()+ .map_err(|e| e.to_string())?;++ // OpenAI-compatible TTS request body. Kokoro-FastAPI + OpenAI both accept it.+ let body = serde_json::json!({+ "model": "tts-1",+ "input": text,+ "voice": voice,+ "response_format": "wav",+ });++ let resp = client+ .post(parsed.as_str())+ .json(&body)+ .send()+ .await+ .map_err(|e| format!("external TTS request failed: {}", e))?;++ if !resp.status().is_success() {+ let code = resp.status().as_u16();+ let detail = resp.text().await.unwrap_or_default();+ let snippet: String = detail.chars().take(200).collect();+ return Err(format!("external TTS HTTP {}: {}", code, snippet));+ }++ // Honor whatever audio type the engine returns (wav/mp3/…). The browser+ // <audio> element plays both from a data URL, so pass the Content-Type+ // through as the mime instead of forcing a single format.+ let mime = resp+ .headers()+ .get(reqwest::header::CONTENT_TYPE)+ .and_then(|v| v.to_str().ok())+ .map(|s| s.split(';').next().unwrap_or(s).trim().to_string())+ .filter(|s| s.starts_with("audio/"))+ .unwrap_or_else(|| "audio/wav".to_string());++ let bytes = resp.bytes().await.map_err(|e| e.to_string())?;+ if bytes.is_empty() {+ return Err("external TTS returned no audio".to_string());+ }++ let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes);+ Ok(serde_json::json!({ "audio_base64": b64, "mime": mime }))+}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 9cbfc945..65778b56 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -132,6 +132,7 @@ fn main() {// Piper neural TTScommands::tts::tts_status,commands::tts::synthesize,+ commands::tts::synthesize_external,commands::tts::download_voice,commands::tts::installed_piper_voices,// Agent tools (legacy)diff --git a/src/api/voice.ts b/src/api/voice.tsindex 737098e7..021434d4 100644--- a/src/api/voice.ts+++ b/src/api/voice.ts@@ -253,6 +253,18 @@ export async function synthesizeNeural(text: string, voice?: string): Promise<streturn `data:${data.mime || "audio/wav"};base64,${data.audio_base64}`;}+/**+ * Synthesize text via a user-configured external HTTP TTS engine (GitHub #58).+ * `url` is an OpenAI-compatible endpoint (e.g. Kokoro-FastAPI at+ * http://localhost:8880/v1/audio/speech); `voice` is that engine's voice name.+ * Returns a playable data URL (the Rust side honors the returned audio type).+ */+export async function synthesizeExternal(text: string, url: string, voice?: string): Promise<string> {+ const data = await backendCall<{ audio_base64?: string; mime?: string }>("synthesize_external", { text, url, voice });+ if (!data?.audio_base64) throw new Error("external TTS returned no audio");+ return `data:${data.mime || "audio/wav"};base64,${data.audio_base64}`;+}+/** Download a Piper voice model on demand. Blocks until done (~63 MB). */export async function downloadPiperVoice(voice: string): Promise<void> {await backendCall("download_voice", { voice });diff --git a/src/components/chat/SpeakerButton.tsx b/src/components/chat/SpeakerButton.tsxindex 8e12c50b..016a9195 100644--- a/src/components/chat/SpeakerButton.tsx+++ b/src/components/chat/SpeakerButton.tsx@@ -6,13 +6,14 @@ interface Props {}export function SpeakerButton({ text }: Props) {- const { isSpeaking, ttsSupported, ttsAvailable, ttsEnabled, speakTextStreaming, stopSpeaking } = useVoice()+ const { isSpeaking, ttsSupported, ttsAvailable, ttsExternalReady, ttsEnabled, speakTextStreaming, stopSpeaking } = useVoice()// Show the read-aloud button only when the feature is on AND some TTS engine- // is usable (local neural Piper, or the browser's system voices as fallback).- // Availability is reactive: the boot probe (App.tsx) and the Settings install- // both push it into the store, so this lights up without a per-message probe.- if (!ttsEnabled || (!ttsAvailable && !ttsSupported)) return null+ // is usable: an external HTTP engine (#58), local neural Piper, or the+ // browser's system voices as fallback. Availability is reactive: the boot+ // probe (App.tsx) and the Settings install both push it into the store, so+ // this lights up without a per-message probe.+ if (!ttsEnabled || (!ttsExternalReady && !ttsAvailable && !ttsSupported)) return nullconst handleClick = () => {if (isSpeaking) {diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsxindex 3eab9405..e6502035 100644--- a/src/components/settings/SettingsPage.tsx+++ b/src/components/settings/SettingsPage.tsx@@ -1290,6 +1290,49 @@ export function SettingsPage() {</div>{voiceBusy && <p className="text-[0.55rem] text-gray-500 leading-snug">Downloading voice (~63 MB)…</p>}{voiceError && <p className="text-[0.55rem] text-red-400/90 leading-snug">{voiceError}</p>}++ {/* TTS engine — bundled Piper, or an external OpenAI-compatible HTTP+ endpoint like Kokoro-FastAPI (GitHub #58). */}+ <div className="flex items-center justify-between gap-2 pt-1">+ <span className="text-[0.7rem] text-gray-500">Engine</span>+ <div className="flex items-center gap-1 text-[0.6rem]">+ {(['piper', 'external'] as const).map((m) => (+ <button+ key={m}+ onClick={() => voiceSettings.updateVoiceSettings({ ttsMode: m })}+ className={+ 'px-2 py-0.5 rounded border transition-colors ' ++ (voiceSettings.ttsMode === m+ ? 'bg-gray-200 dark:bg-white/15 text-gray-900 dark:text-white border-gray-300 dark:border-white/20'+ : 'text-gray-500 border-white/8 hover:text-gray-300')+ }+ >+ {m === 'piper' ? 'Piper neural' : 'External HTTP'}+ </button>+ ))}+ </div>+ </div>+ {voiceSettings.ttsMode === 'external' && (+ <div className="space-y-1.5">+ <input+ value={voiceSettings.externalTtsUrl}+ onChange={(e) => voiceSettings.updateVoiceSettings({ externalTtsUrl: e.target.value })}+ placeholder="http://localhost:8880/v1/audio/speech"+ spellCheck={false}+ className="w-full px-2 py-1 rounded bg-transparent border border-white/8 text-[0.65rem] text-gray-300 placeholder-gray-600 focus:outline-none focus:border-white/20"+ />+ <input+ value={voiceSettings.externalTtsVoice}+ onChange={(e) => voiceSettings.updateVoiceSettings({ externalTtsVoice: e.target.value })}+ placeholder="voice name (e.g. af_bella, alloy)"+ spellCheck={false}+ className="w-full px-2 py-1 rounded bg-transparent border border-white/8 text-[0.65rem] text-gray-300 placeholder-gray-600 focus:outline-none focus:border-white/20"+ />+ <p className="text-[0.55rem] text-gray-500 leading-snug">+ Any OpenAI-compatible TTS endpoint (e.g. Kokoro-FastAPI). Used for read-aloud instead of Piper. Stays on your machine when the endpoint is local.+ </p>+ </div>+ )}</Section><Section title="Remote Access">diff --git a/src/hooks/useVoice.ts b/src/hooks/useVoice.tsindex 56cf0a8a..359bbaa7 100644--- a/src/hooks/useVoice.ts+++ b/src/hooks/useVoice.ts@@ -4,6 +4,7 @@ import {recheckWhisperAvailable,recheckTtsAvailable,synthesizeNeural,+ synthesizeExternal,playNeuralAudio,stopNeuralAudio,isSpeechSynthesisSupported,@@ -35,6 +36,10 @@ export function useVoice() {// Reactive neural-TTS availability (Piper), same model as sttAvailable.const ttsAvailable = store.ttsAvailable;+ // External HTTP TTS engine configured + selected (#58). Lets the read-aloud+ // button light up even on a machine without Piper or browser voices.+ const ttsExternalReady = store.ttsMode === "external" && !!store.externalTtsUrl.trim();+// Re-probe Whisper on demand (mic mount / after install) and sync the store.const recheckStt = useCallback(async (): Promise<boolean> => {const ok = await recheckWhisperAvailable();@@ -140,11 +145,24 @@ export function useVoice() {const speakInternal = useCallback(async (text: string, streaming: boolean) => {if (!store.ttsEnabled) return;- if (!store.ttsAvailable && !ttsSupported) return;+ // An external HTTP engine (#58) needs a configured URL; Piper needs to be+ // installed; the browser path needs SpeechSynthesis. Bail only if none of+ // the three can speak.+ const externalReady = store.ttsMode === "external" && !!store.externalTtsUrl.trim();+ if (!externalReady && !store.ttsAvailable && !ttsSupported) return;store.setSpeaking(true);try {- if (store.ttsAvailable) {+ // External HTTP TTS engine takes precedence when selected + configured.+ if (externalReady) {+ try {+ const url = await synthesizeExternal(text, store.externalTtsUrl.trim(), store.externalTtsVoice || undefined);+ await playNeuralAudio(url);+ return;+ } catch (err) {+ log.error("External TTS failed, falling back to browser voices", { err });+ }+ } else if (store.ttsAvailable) {try {const url = await synthesizeNeural(text, store.piperVoice);await playNeuralAudio(url);@@ -190,6 +208,7 @@ export function useVoice() {sttSupported,ttsSupported,ttsAvailable,+ ttsExternalReady,ttsEnabled: store.ttsEnabled,startRecording,stopRecording,diff --git a/src/stores/voiceStore.ts b/src/stores/voiceStore.tsindex f4d80b6d..c8907236 100644--- a/src/stores/voiceStore.ts+++ b/src/stores/voiceStore.ts@@ -25,6 +25,13 @@ interface VoiceState {ttsVoice: string;ttsRate: number;ttsPitch: number;+ /** TTS engine: bundled Piper (local) or a user-configured external HTTP+ * endpoint (OpenAI-compatible, e.g. Kokoro-FastAPI) — GitHub #58. */+ ttsMode: "piper" | "external";+ /** External TTS endpoint URL, e.g. http://localhost:8880/v1/audio/speech. */+ externalTtsUrl: string;+ /** Voice name passed to the external engine (e.g. "af_bella" / "alloy"). */+ externalTtsVoice: string;// ActionssetRecording: (recording: boolean) => void;@@ -41,6 +48,9 @@ interface VoiceState {ttsVoice: string;ttsRate: number;ttsPitch: number;+ ttsMode: "piper" | "external";+ externalTtsUrl: string;+ externalTtsVoice: string;}>) => void;resetTransient: () => void;@@ -73,6 +83,9 @@ export const useVoiceStore = create<VoiceState>()(ttsVoice: "",ttsRate: 1.0,ttsPitch: 1.0,+ ttsMode: "piper",+ externalTtsUrl: "",+ externalTtsVoice: "",// ActionssetRecording: (recording) => set({ isRecording: recording }),@@ -101,6 +114,9 @@ export const useVoiceStore = create<VoiceState>()(ttsVoice: "",ttsRate: 1.0,ttsPitch: 1.0,+ ttsMode: "piper",+ externalTtsUrl: "",+ externalTtsVoice: "",}),}),{