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(voice): streaming local STT (WAV) + neural TTS (Piper) with in-app install
purple441a094e0624
diff --git a/src-tauri/src/commands/install.rs b/src-tauri/src/commands/install.rsindex 0f599630..f8c3486c 100644--- a/src-tauri/src/commands/install.rs+++ b/src-tauri/src/commands/install.rs@@ -9,7 +9,7 @@ use std::time::Instant;#[cfg(target_os = "windows")]use std::os::windows::process::CommandExt;-use tauri::State;+use tauri::{Manager, State};use tracing::{error, info};use crate::python::venv_python_path;@@ -2383,6 +2383,147 @@ pub fn install_whisper_status(state: State<'_, AppState>) -> Result<serde_json::}))}+// ── Piper neural TTS installer (David 2026-06-06 — local neural TTS) ──────────++/// Resolve the Python LU's tooling uses: the ComfyUI venv when present, else+/// the resolved system Python. Shared by the faster-whisper + Piper-TTS+/// installers and the TTS synthesizer so they all target the same interpreter.+pub fn resolve_lu_python(state: &AppState) -> String {+ let comfy_dir: Option<PathBuf> = {+ let p = state.comfy_path.lock().unwrap().clone();+ p.map(PathBuf::from)+ .or_else(|| crate::commands::process::find_comfyui_path().map(PathBuf::from))+ };+ let venv_python = comfy_dir+ .as_deref()+ .and_then(crate::python::resolve_comfyui_venv_python);+ venv_python.unwrap_or_else(|| state.python_bin.lock().unwrap().clone())+}++/// pip args to install Piper TTS. `piper-tts` ships the `piper` CLI + the+/// `piper.download_voices` helper. Same flags as the whisper installer.+fn build_tts_pip_args() -> Vec<&'static str> {+ vec![+ "-m", "pip", "install",+ "--progress-bar", "off",+ "--no-input",+ "piper-tts",+ ]+}++/// Install Piper (neural TTS) into LU's Python, then download the default voice+/// model into `<app_data>/piper_voices/`. Mirrors `install_whisper`. Progress+/// is polled via `install_tts_status`; `tts_status` reports usability.+#[tauri::command]+pub fn install_tts(+ app: tauri::AppHandle,+ state: State<'_, AppState>,+) -> Result<serde_json::Value, String> {+ {+ let mut install = state.tts_install.lock().unwrap();+ if install.status == "installing" {+ return Ok(serde_json::json!({"status": "already_installing"}));+ }+ install.status = "installing".to_string();+ install.logs.clear();+ install.logs.push("Starting neural TTS (Piper) installation...".to_string());+ }++ info!("tts install start");++ let target_python = resolve_lu_python(state.inner());+ if target_python.is_empty() || !crate::python::is_real_python(&target_python) {+ let mut install = state.tts_install.lock().unwrap();+ install.status = "error".to_string();+ install.logs.push(+ "No Python found. Install Python first (Settings → ComfyUI → Install Python), \+ then retry the neural TTS install."+ .to_string(),+ );+ error!("tts install aborted: no usable python");+ return Err("no_python: Python must be installed before Piper TTS.".to_string());+ }++ let voices_dir = app+ .path()+ .app_data_dir()+ .map_err(|e| format!("no app data dir: {}", e))?+ .join("piper_voices");++ let install_state = state.tts_install.clone();++ std::thread::spawn(move || {+ let update = |status: &str, msg: &str| {+ if let Ok(mut s) = install_state.lock() {+ s.status = status.to_string();+ s.logs.push(msg.to_string());+ }+ };++ update(+ "installing",+ &format!("Installing piper-tts via {} (this can take a few minutes)…", target_python),+ );++ let args = build_tts_pip_args();+ match pip_install_streaming_with_retry_cancellable(&args, &target_python, 3, &install_state, None) {+ Ok(()) => {+ update(+ "installing",+ &format!(+ "piper-tts installed. Downloading the {} voice (~63 MB)…",+ crate::commands::tts::PIPER_VOICE+ ),+ );+ let _ = std::fs::create_dir_all(&voices_dir);+ let mut cmd = Command::new(&target_python);+ cmd.args([+ "-m",+ "piper.download_voices",+ crate::commands::tts::PIPER_VOICE,+ "--download-dir",+ &voices_dir.to_string_lossy(),+ ])+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);+ match cmd.output() {+ Ok(o) if o.status.success() => {+ update("complete", "Neural TTS is ready.");+ }+ Ok(o) => {+ update(+ "error",+ &format!("Voice download failed:\n{}", String::from_utf8_lossy(&o.stderr)),+ );+ }+ Err(e) => {+ update("error", &format!("Voice download could not start: {}", e));+ }+ }+ }+ Err(diagnosis) => {+ let err = format!("piper-tts installation failed.\n\n{}", diagnosis);+ println!("[TTS Install] {}", err);+ update("error", &err);+ }+ }+ });++ Ok(serde_json::json!({"status": "installing"}))+}++/// Poll the Piper-TTS install progress (mirrors `install_whisper_status`).+#[tauri::command]+pub fn install_tts_status(state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ let install = state.tts_install.lock().unwrap();+ Ok(serde_json::json!({+ "status": install.status,+ "logs": install.logs,+ }))+}+// ──────────────────────────────────────────────────────────────────────────────#[allow(non_snake_case)]diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rsindex 0f1f7e09..465bfe3c 100644--- a/src-tauri/src/commands/mod.rs+++ b/src-tauri/src/commands/mod.rs@@ -13,6 +13,7 @@ pub mod remote;pub mod search;pub mod shell;pub mod system;+pub mod tts;pub mod whisper;// ── uselu-compat error helpers ────────────────────────────────────────diff --git a/src-tauri/src/commands/tts.rs b/src-tauri/src/commands/tts.rsnew file mode 100644index 00000000..154b9482--- /dev/null+++ b/src-tauri/src/commands/tts.rs@@ -0,0 +1,139 @@+//! Local neural Text-to-Speech via Piper (rhasspy/piper, `piper-tts` on PyPI).+//!+//! 100% local — no cloud. We shell out to the same Python LU installs+//! faster-whisper into (ComfyUI venv → system Python) running the Piper CLI+//! one-shot per utterance: `python -m piper -m voice.onnx -c voice.onnx.json+//! -f out.wav` with the text on stdin. One-shot (vs a persistent server) costs+//! ~1-2 s of ONNX model load per "speak", which is acceptable for chat TTS and+//! avoids a long-lived process + version-specific Python API. The voice model+//! is downloaded by `install_tts` (commands/install.rs) into the app-data dir.++use std::io::Write;+use std::path::PathBuf;+use std::process::{Command, Stdio};++#[cfg(target_os = "windows")]+use std::os::windows::process::CommandExt;++use base64::Engine;+use tauri::{Manager, State};++use crate::state::AppState;++#[cfg(target_os = "windows")]+const CREATE_NO_WINDOW: u32 = 0x08000000;++/// The default Piper voice LU downloads + speaks with. Medium-quality English,+/// ~63 MB. The two files land in `<app_data>/piper_voices/`.+pub const PIPER_VOICE: &str = "en_US-lessac-medium";++/// Resolve `(model.onnx, model.onnx.json)` paths for the bundled voice under+/// the app-data piper_voices dir.+pub fn piper_voice_paths(app: &tauri::AppHandle) -> Result<(PathBuf, PathBuf), String> {+ let dir = app+ .path()+ .app_data_dir()+ .map_err(|e| format!("no app data dir: {}", e))?+ .join("piper_voices");+ let onnx = dir.join(format!("{}.onnx", PIPER_VOICE));+ let config = dir.join(format!("{}.onnx.json", PIPER_VOICE));+ Ok((onnx, config))+}++/// Whether neural TTS is usable: `import piper` succeeds AND the voice model is+/// present. The Settings badge + the chat SpeakerButton gate on this.+#[tauri::command]+pub fn tts_status(state: State<'_, AppState>, app: tauri::AppHandle) -> Result<serde_json::Value, String> {+ let python = crate::commands::install::resolve_lu_python(state.inner());++ let mut piper_importable = false;+ if !python.is_empty() && crate::python::is_real_python(&python) {+ let mut cmd = Command::new(&python);+ cmd.args(["-c", "import piper"]).stdout(Stdio::null()).stderr(Stdio::null());+ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);+ piper_importable = cmd.output().map(|o| o.status.success()).unwrap_or(false);+ }++ let voice_ready = piper_voice_paths(&app).map(|(onnx, _)| onnx.exists()).unwrap_or(false);++ Ok(serde_json::json!({+ "available": piper_importable && voice_ready,+ "piper": piper_importable,+ "voice": voice_ready,+ }))+}++/// Synthesize `text` to a 22.05 kHz mono WAV and return it base64-encoded for+/// the frontend to play. Runs the Piper CLI one-shot.+#[tauri::command]+pub fn synthesize(+ text: String,+ state: State<'_, AppState>,+ app: tauri::AppHandle,+) -> Result<serde_json::Value, String> {+ let text = text.trim().to_string();+ if text.is_empty() {+ return Err("empty text".to_string());+ }++ let python = crate::commands::install::resolve_lu_python(state.inner());+ if python.is_empty() || !crate::python::is_real_python(&python) {+ return Err("no_python: install Python first.".to_string());+ }++ let (onnx, config) = piper_voice_paths(&app)?;+ if !onnx.exists() || !config.exists() {+ return Err("no_voice: neural TTS not installed — install it in Settings → Voice & Remote.".to_string());+ }++ let stamp = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_millis())+ .unwrap_or(0);+ let out_wav = std::env::temp_dir().join(format!("lu-tts-{}.wav", stamp));++ let mut cmd = Command::new(&python);+ cmd.args([+ "-m",+ "piper",+ "-m",+ &onnx.to_string_lossy(),+ "-c",+ &config.to_string_lossy(),+ "-f",+ &out_wav.to_string_lossy(),+ ])+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);++ let mut child = cmd.spawn().map_err(|e| format!("Failed to start piper: {}", e))?;+ // Feed the text on stdin, then close it so piper proceeds.+ if let Some(mut stdin) = child.stdin.take() {+ let _ = stdin.write_all(text.as_bytes());+ // dropped at end of block → stdin closed+ }+ let output = child+ .wait_with_output()+ .map_err(|e| format!("piper wait failed: {}", e))?;++ if !output.status.success() {+ let _ = std::fs::remove_file(&out_wav);+ return Err(format!(+ "piper synthesis failed: {}",+ String::from_utf8_lossy(&output.stderr)+ ));+ }++ let bytes = std::fs::read(&out_wav).map_err(|e| format!("read wav: {}", e))?;+ let _ = std::fs::remove_file(&out_wav);+ if bytes.is_empty() {+ return Err("piper produced an empty WAV".to_string());+ }++ let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes);+ Ok(serde_json::json!({ "audio_base64": b64, "mime": "audio/wav" }))+}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex a858b39e..f87723f2 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -122,10 +122,15 @@ fn main() {commands::install::install_custom_node,commands::install::install_whisper,commands::install::install_whisper_status,+ commands::install::install_tts,+ commands::install::install_tts_status,commands::install::check_git_installed,// Whisper STTcommands::whisper::whisper_status,commands::whisper::transcribe,+ // Piper neural TTS+ commands::tts::tts_status,+ commands::tts::synthesize,// Agent tools (legacy)commands::agent::execute_code,commands::agent::file_read,diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rsindex 7aa2742d..cc5aa033 100644--- a/src-tauri/src/state.rs+++ b/src-tauri/src/state.rs@@ -158,6 +158,9 @@ pub struct AppState {/// (the STT badge had no way to fix a ✗). Mirrors the other per-installer/// states; `install_whisper` writes it, `install_whisper_status` reads it.pub whisper_install: Arc<Mutex<InstallState>>,+ /// Progress/log state for the in-app Piper neural-TTS installer (mirrors+ /// `whisper_install`); `install_tts` writes it, `install_tts_status` reads it.+ pub tts_install: Arc<Mutex<InstallState>>,pub searxng_install: Mutex<InstallState>,pub searxng_available: AtomicBool,/// Resolved Python binary path. Empty string means "no real Python on@@ -233,6 +236,7 @@ impl AppState {lmstudio_install: Arc::new(Mutex::new(InstallState::default())),python_install: Arc::new(Mutex::new(InstallState::default())),whisper_install: Arc::new(Mutex::new(InstallState::default())),+ tts_install: Arc::new(Mutex::new(InstallState::default())),searxng_install: Mutex::new(InstallState::default()),searxng_available: AtomicBool::new(false),python_bin: Arc::new(Mutex::new(python_bin)),diff --git a/src/App.tsx b/src/App.tsxindex 347a3f2b..b026b2c2 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -17,10 +17,15 @@ function App() {// previously never called anywhere → isSpeechRecognitionSupported() stayed// false forever → the mic was permanently disabled even with faster-whisper// installed and running. Fire-and-forget; never blocks first render.- import('./api/voice').then(({ initWhisperCheck }) => {+ import('./api/voice').then(({ initWhisperCheck, initTtsCheck }) => {initWhisperCheck().then((ok) => useVoiceStore.getState().setSttAvailable(ok)).catch(() => {})+ // Same one-shot probe for local neural TTS (Piper) so the speaker+ // buttons reflect real availability and light up after the install.+ initTtsCheck()+ .then((ok) => useVoiceStore.getState().setTtsAvailable(ok))+ .catch(() => {})})// Bug BB v2.5.0 — push persisted GPU selection from localStorage intodiff --git a/src/api/voice.ts b/src/api/voice.tsindex 46a5ffdd..5e7de0d7 100644--- a/src/api/voice.ts+++ b/src/api/voice.ts@@ -207,63 +207,210 @@ export async function transcribeAudio(audioBlob: Blob): Promise<string> {return data.transcript || "";}-// --- Audio Recorder (MediaRecorder only, NO SpeechRecognition) ---+// --- Local neural TTS (Piper) ---+// Synthesizes via the bundled Piper voice through the Rust `synthesize` command+// (100% local, no cloud). The browser SpeechSynthesis path in useVoice handles+// the case where neural TTS isn't installed.++let ttsChecked = false;+let ttsAvailableFlag = false;++export async function checkTtsAvailable(): Promise<{ available: boolean; piper?: boolean; voice?: boolean }> {+ try {+ if (isTauri()) return await backendCall("tts_status");+ return { available: false };+ } catch {+ return { available: false };+ }+}++export async function initTtsCheck(): Promise<boolean> {+ if (ttsChecked) return ttsAvailableFlag;+ try {+ ttsAvailableFlag = (await checkTtsAvailable()).available;+ } catch {+ ttsAvailableFlag = false;+ }+ ttsChecked = true;+ return ttsAvailableFlag;+}++// Force a fresh probe (after the in-app install, or when a Speaker button mounts+// while neural TTS still shows unavailable).+export async function recheckTtsAvailable(): Promise<boolean> {+ ttsChecked = false;+ return initTtsCheck();+}++/** Synthesize text to a playable WAV data URL via the local Piper voice. */+export async function synthesizeNeural(text: string): Promise<string> {+ const data = await backendCall<{ audio_base64?: string; mime?: string }>("synthesize", { text });+ if (!data?.audio_base64) throw new Error("neural TTS returned no audio");+ return `data:${data.mime || "audio/wav"};base64,${data.audio_base64}`;+}++let neuralAudio: HTMLAudioElement | null = null;++/** Play a WAV data URL; resolves when playback ends. Replaces any current clip. */+export function playNeuralAudio(dataUrl: string): Promise<void> {+ return new Promise((resolve, reject) => {+ stopNeuralAudio();+ const audio = new Audio(dataUrl);+ neuralAudio = audio;+ audio.onended = () => {+ if (neuralAudio === audio) neuralAudio = null;+ resolve();+ };+ audio.onerror = () => {+ if (neuralAudio === audio) neuralAudio = null;+ reject(new Error("neural audio playback failed"));+ };+ audio.play().catch(reject);+ });+}++export function stopNeuralAudio(): void {+ if (neuralAudio) {+ try { neuralAudio.pause(); } catch { /* noop */ }+ neuralAudio = null;+ }+}++// --- Audio Recorder (Web Audio PCM → 16 kHz mono WAV) ---+//+// We deliberately do NOT use MediaRecorder here. MediaRecorder with a timeslice+// emits *fragmented* webm/opus chunks; concatenating them yields a blob whose+// header/cues are incomplete, which faster-whisper (PyAV/ffmpeg) often fails to+// decode → empty transcript (the "mic on but no text" bug). Capturing raw PCM+// via Web Audio and encoding a clean 16 kHz mono WAV is what faster-whisper+// expects natively, and it lets us take mid-recording WAV snapshots for live+// streaming transcription.export interface AudioRecorder {start: () => Promise<void>;+ /** Final 16 kHz mono WAV of the whole take. */stop: () => Promise<Blob>;+ /** 16 kHz mono WAV of everything captured so far (for streaming interim STT). */+ snapshot: () => Blob | null;isRecording: () => boolean;}+const STT_TARGET_RATE = 16000;++function floatTo16BitPCM(samples: Float32Array): Int16Array {+ const out = new Int16Array(samples.length);+ for (let i = 0; i < samples.length; i++) {+ const s = Math.max(-1, Math.min(1, samples[i]));+ out[i] = s < 0 ? s * 0x8000 : s * 0x7fff;+ }+ return out;+}++// Box-filter downsample to the target rate (Whisper wants 16 kHz). Averaging+// the source window is a cheap anti-alias that beats naive decimation.+function downsampleTo(input: Float32Array, inRate: number, outRate: number): Float32Array {+ if (outRate >= inRate || input.length === 0) return input;+ const ratio = inRate / outRate;+ const outLen = Math.floor(input.length / ratio);+ const out = new Float32Array(outLen);+ for (let i = 0; i < outLen; i++) {+ const start = Math.floor(i * ratio);+ const end = Math.min(input.length, Math.floor((i + 1) * ratio));+ let sum = 0, n = 0;+ for (let j = start; j < end; j++) { sum += input[j]; n++; }+ out[i] = n ? sum / n : input[start] || 0;+ }+ return out;+}++function encodeWav(samples: Int16Array, sampleRate: number): Blob {+ const buffer = new ArrayBuffer(44 + samples.length * 2);+ const view = new DataView(buffer);+ const writeStr = (off: number, s: string) => {+ for (let i = 0; i < s.length; i++) view.setUint8(off + i, s.charCodeAt(i));+ };+ writeStr(0, "RIFF");+ view.setUint32(4, 36 + samples.length * 2, true);+ writeStr(8, "WAVE");+ writeStr(12, "fmt ");+ view.setUint32(16, 16, true); // PCM fmt chunk size+ view.setUint16(20, 1, true); // format = PCM+ view.setUint16(22, 1, true); // channels = mono+ view.setUint32(24, sampleRate, true);+ view.setUint32(28, sampleRate * 2, true); // byte rate (mono, 16-bit)+ view.setUint16(32, 2, true); // block align+ view.setUint16(34, 16, true); // bits per sample+ writeStr(36, "data");+ view.setUint32(40, samples.length * 2, true);+ let off = 44;+ for (let i = 0; i < samples.length; i++, off += 2) view.setInt16(off, samples[i], true);+ return new Blob([view], { type: "audio/wav" });+}+export function createAudioRecorder(): AudioRecorder {- let mediaRecorder: MediaRecorder | null = null;- let audioChunks: Blob[] = [];+ let audioCtx: AudioContext | null = null;+ let source: MediaStreamAudioSourceNode | null = null;+ let processor: ScriptProcessorNode | null = null;+ let mute: GainNode | null = null;+ let stream: MediaStream | null = null;+ let pcmChunks: Float32Array[] = [];+ let inputRate = 48000;let recording = false;+ const buildWav = (): Blob | null => {+ if (!pcmChunks.length) return null;+ let total = 0;+ for (const c of pcmChunks) total += c.length;+ if (total === 0) return null;+ const merged = new Float32Array(total);+ let o = 0;+ for (const c of pcmChunks) { merged.set(c, o); o += c.length; }+ const ds = downsampleTo(merged, inputRate, STT_TARGET_RATE);+ return encodeWav(floatTo16BitPCM(ds), STT_TARGET_RATE);+ };+return {start: async () => {- audioChunks = [];- const stream = await navigator.mediaDevices.getUserMedia({ audio: true });- mediaRecorder = new MediaRecorder(stream, {- mimeType: MediaRecorder.isTypeSupported("audio/webm;codecs=opus")- ? "audio/webm;codecs=opus"- : "audio/webm",- });-- mediaRecorder.ondataavailable = (event) => {- if (event.data.size > 0) {- audioChunks.push(event.data);- }+ pcmChunks = [];+ stream = await navigator.mediaDevices.getUserMedia({ audio: true });+ const Ctx = window.AudioContext || (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext;+ audioCtx = new Ctx();+ inputRate = audioCtx.sampleRate;+ source = audioCtx.createMediaStreamSource(stream);+ // ScriptProcessor is deprecated but works reliably in WebView2 without the+ // AudioWorklet module-loading dance. 4096-frame buffer ≈ 85 ms at 48 kHz.+ processor = audioCtx.createScriptProcessor(4096, 1, 1);+ processor.onaudioprocess = (e) => {+ if (!recording) return;+ // Copy — the underlying buffer is reused by the audio thread.+ pcmChunks.push(new Float32Array(e.inputBuffer.getChannelData(0)));};-- mediaRecorder.start(250); // Collect data every 250ms+ // Route through a zero-gain node so onaudioprocess fires WITHOUT echoing+ // the mic to the speakers.+ mute = audioCtx.createGain();+ mute.gain.value = 0;+ source.connect(processor);+ processor.connect(mute);+ mute.connect(audioCtx.destination);recording = true;},stop: () => {return new Promise<Blob>((resolve) => {recording = false;-- if (mediaRecorder && mediaRecorder.state !== "inactive") {- mediaRecorder.onstop = () => {- const blob = new Blob(audioChunks, {- type: mediaRecorder?.mimeType || "audio/webm",- });-- // Stop all tracks on the stream- mediaRecorder?.stream.getTracks().forEach((track) => track.stop());- mediaRecorder = null;-- resolve(blob);- };-- mediaRecorder.stop();- } else {- resolve(new Blob([], { type: "audio/webm" }));- }+ const wav = buildWav() || new Blob([], { type: "audio/wav" });+ try { processor?.disconnect(); } catch { /* noop */ }+ try { source?.disconnect(); } catch { /* noop */ }+ try { mute?.disconnect(); } catch { /* noop */ }+ try { stream?.getTracks().forEach((t) => t.stop()); } catch { /* noop */ }+ try { void audioCtx?.close(); } catch { /* noop */ }+ processor = null; source = null; mute = null; audioCtx = null; stream = null;+ resolve(wav);});},+ snapshot: () => buildWav(),+isRecording: () => recording,};}diff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsxindex e54a94fd..14004e08 100644--- a/src/components/chat/ChatInput.tsx+++ b/src/components/chat/ChatInput.tsx@@ -39,6 +39,10 @@ export function ChatInput({ onSend, onStop, isGenerating, pendingApproval, onAppconst [isVoiceRecording, setIsVoiceRecording] = useState(false)const textareaRef = useRef<HTMLTextAreaElement>(null)const fileInputRef = useRef<HTMLInputElement>(null)+ // Text already in the box when dictation started. Interim + final transcripts+ // are written as base + transcript, so streaming chunks REPLACE (not stack)+ // and pre-typed text is never wiped.+ const dictationBaseRef = useRef('')const isTranscribing = useVoiceStore((s) => s.isTranscribing)const thinkingEnabled = useSettingsStore((s) => s.settings.thinkingEnabled)const updateSettings = useSettingsStore((s) => s.updateSettings)@@ -63,6 +67,21 @@ export function ChatInput({ onSend, onStop, isGenerating, pendingApproval, onAppsetImages(prev => prev.filter((_, i) => i !== index))}+ // Write a dictation transcript (interim or final) into the input as+ // base + transcript, then resize the textarea. NEVER sends — the user+ // reviews and presses Send (David 2026-06-06).+ const applyDictation = (text: string) => {+ const base = dictationBaseRef.current+ const sep = base && !/\s$/.test(base) ? ' ' : ''+ setInput(base + sep + text)+ requestAnimationFrame(() => {+ if (textareaRef.current) {+ textareaRef.current.style.height = 'auto'+ textareaRef.current.style.height = Math.min(textareaRef.current.scrollHeight, 200) + 'px'+ }+ })+ }+const handleSend = () => {const trimmed = input.trim()if ((!trimmed && images.length === 0) || isGenerating || disabled) return@@ -176,11 +195,15 @@ export function ChatInput({ onSend, onStop, isGenerating, pendingApproval, onApp/><VoiceButton- // Dictation fills the input and NEVER auto-sends — the user reviews- // and presses Send (David 2026-06-06). Append to any text already- // typed instead of replacing it, so a transcript can't wipe input.- onTranscript={(text) => { setInput((prev) => (prev.trim() ? prev.replace(/\s+$/, '') + ' ' + text : text)); requestAnimationFrame(() => { if (textareaRef.current) { textareaRef.current.style.height = 'auto'; textareaRef.current.style.height = Math.min(textareaRef.current.scrollHeight, 200) + 'px' } }) }}- onRecordingChange={(r) => setIsVoiceRecording(r)}+ // Streaming dictation: interim chunks arrive while talking, the final+ // transcript replaces them on stop — both via applyDictation, which+ // writes base + transcript and NEVER sends (user presses Send).+ onInterim={applyDictation}+ onTranscript={applyDictation}+ onRecordingChange={(r) => {+ if (r) dictationBaseRef.current = input+ setIsVoiceRecording(r)+ }}disabled={isGenerating}/>diff --git a/src/components/chat/SpeakerButton.tsx b/src/components/chat/SpeakerButton.tsxindex 7cea1f91..8e12c50b 100644--- a/src/components/chat/SpeakerButton.tsx+++ b/src/components/chat/SpeakerButton.tsx@@ -6,9 +6,13 @@ interface Props {}export function SpeakerButton({ text }: Props) {- const { isSpeaking, ttsSupported, speakTextStreaming, stopSpeaking } = useVoice()+ const { isSpeaking, ttsSupported, ttsAvailable, ttsEnabled, speakTextStreaming, stopSpeaking } = useVoice()- if (!ttsSupported) return null+ // 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 nullconst handleClick = () => {if (isSpeaking) {@@ -21,7 +25,12 @@ export function SpeakerButton({ text }: Props) {return (<buttononClick={handleClick}- className="p-0.5 rounded opacity-0 group-hover:opacity-100 hover:bg-gray-200 dark:hover:bg-white/10 text-gray-400 hover:text-gray-700 dark:hover:text-white transition-all"+ className={+ "p-1 rounded-md transition-colors " ++ (isSpeaking+ ? "text-blue-500 dark:text-blue-400 bg-blue-500/10"+ : "text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/10")+ }title={isSpeaking ? "Stop speaking" : "Read aloud"}aria-label={isSpeaking ? "Stop speaking" : "Read aloud"}>diff --git a/src/components/chat/VoiceButton.tsx b/src/components/chat/VoiceButton.tsxindex bdfb86a1..202df972 100644--- a/src/components/chat/VoiceButton.tsx+++ b/src/components/chat/VoiceButton.tsx@@ -5,11 +5,13 @@ import { useVoice } from "../../hooks/useVoice"interface Props {onTranscript: (text: string) => void+ /** Live interim transcript while recording (streaming dictation). */+ onInterim?: (text: string) => voidonRecordingChange?: (isRecording: boolean) => voiddisabled?: boolean}-export function VoiceButton({ onTranscript, onRecordingChange, disabled }: Props) {+export function VoiceButton({ onTranscript, onInterim, onRecordingChange, disabled }: Props) {const { isRecording, isTranscribing, sttSupported, startRecording, stopRecording, recheckStt } = useVoice()useEffect(() => {@@ -31,7 +33,7 @@ export function VoiceButton({ onTranscript, onRecordingChange, disabled }: Props}} else {onRecordingChange?.(true)- await startRecording()+ await startRecording((interim) => onInterim?.(interim))}}diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsxindex 067429d7..812965af 100644--- a/src/components/settings/SettingsPage.tsx+++ b/src/components/settings/SettingsPage.tsx@@ -1,12 +1,12 @@import { useState, useEffect, useRef, type ReactNode, type ChangeEvent } from 'react'-import { ArrowLeft, RotateCcw, Sun, Moon, Volume2, Check, X, Loader2, Shield, ChevronRight, GraduationCap, Lock, Sliders, Plug, Bot, Phone, User } from 'lucide-react'+import { ArrowLeft, RotateCcw, Sun, Moon, Volume2, Check, X, Loader2, Shield, ChevronRight, GraduationCap, Lock, Sliders, Plug, Bot, Phone, User, Download, Mic } from 'lucide-react'import { motion, AnimatePresence } from 'framer-motion'import { useSettingsStore } from '../../stores/settingsStore'import { useUIStore } from '../../stores/uiStore'import { SliderControl } from './SliderControl'import { PersonaPanel } from '../personas/PersonaPanel'import { useVoiceStore } from '../../stores/voiceStore'-import { checkWhisperAvailable } from '../../api/voice'+import { checkWhisperAvailable, checkTtsAvailable } from '../../api/voice'import { useAgentModeStore } from '../../stores/agentModeStore'import { FEATURE_FLAGS } from '../../lib/constants'import { getRecommendedAgentModels } from '../../lib/model-compatibility'@@ -674,6 +674,11 @@ export function SettingsPage() {// `whisperInstallError` shows the last failure under the badge.const [whisperInstalling, setWhisperInstalling] = useState(false)const [whisperInstallError, setWhisperInstallError] = useState<string | null>(null)+ // Neural TTS (Piper) install state — mirrors the whisper installer.+ const [ttsStatus, setTtsStatus] = useState<{ available: boolean } | null>(null)+ const [ttsLoading, setTtsLoading] = useState(true)+ const [ttsInstalling, setTtsInstalling] = useState(false)+ const [ttsInstallError, setTtsInstallError] = useState<string | null>(null)const [tab, setTab] = useState<SettingsTab>(() => {if (typeof window === 'undefined') return 'general'const stored = window.localStorage.getItem(SETTINGS_TAB_KEY)@@ -712,8 +717,21 @@ export function SettingsPage() {.finally(() => setWhisperLoading(false))}+ const refreshTts = () => {+ setTtsLoading(true)+ return checkTtsAvailable()+ .then((s) => {+ setTtsStatus(s)+ // Same as STT: drive the read-aloud button availability from this probe+ // so it lights up right after the in-app install.+ voiceSettings.setTtsAvailable(!!s.available)+ })+ .finally(() => setTtsLoading(false))+ }+useEffect(() => {void refreshWhisper()+ void refreshTts()}, [])// §24.9 — kick off the faster-whisper install, poll its status, then@@ -752,6 +770,40 @@ export function SettingsPage() {}}+ // Install Piper neural TTS (pip + voice download) the same end-user way as+ // whisper, polling install_tts_status until done, then re-checking the badge.+ const handleInstallTts = async () => {+ if (ttsInstalling) return+ setTtsInstallError(null)+ setTtsInstalling(true)+ try {+ await backendCall('install_tts')+ const start = Date.now()+ // eslint-disable-next-line no-constant-condition+ while (true) {+ await new Promise((r) => setTimeout(r, 2000))+ let s: { status?: string; error?: string } = {}+ try {+ s = await backendCall<{ status?: string; error?: string }>('install_tts_status')+ } catch { /* transient — keep polling */ }+ if (s.status === 'complete') break+ if (s.status === 'error') {+ setTtsInstallError(s.error || 'Install failed.')+ break+ }+ if (Date.now() - start > 600_000) {+ setTtsInstallError('Install is taking unusually long — check the logs / try again.')+ break+ }+ }+ } catch (e) {+ setTtsInstallError(e instanceof Error ? e.message : String(e))+ } finally {+ setTtsInstalling(false)+ await refreshTts()+ }+ }+return (<div className="h-full overflow-y-auto scrollbar-thin"><div className="max-w-lg mx-auto px-4 py-4">@@ -1044,27 +1096,29 @@ export function SettingsPage() {{/* ── Voice & Remote tab ────────────────────────── */}{tab === 'voice-remote' && (<><Section title="Speech" defaultOpen>- <div className="flex items-center gap-3 text-[0.65rem]">- <span className="flex items-center gap-1">- {whisperLoading ? <Loader2 size={10} className="animate-spin text-gray-500" /> : whisperStatus?.available ? <Check size={10} className="text-green-500" /> : <X size={10} className="text-red-500" />}- <span className="text-gray-500">STT</span>+ <p className="text-[0.55rem] text-gray-500 leading-snug">+ Voice runs 100% locally — no cloud. Each engine is a one-time local install.+ </p>++ {/* Speech-to-Text — faster-whisper (powers the microphone / dictation) */}+ <div className="flex items-center gap-2 text-[0.65rem]">+ <span className="flex items-center gap-1.5">+ {whisperLoading+ ? <Loader2 size={11} className="animate-spin text-gray-500" />+ : whisperStatus?.available ? <Check size={11} className="text-green-500" /> : <X size={11} className="text-red-500" />}+ <Mic size={11} className="text-gray-400" />+ <span className="text-gray-700 dark:text-gray-200 font-medium">Speech-to-Text</span>+ <span className="text-gray-500">faster-whisper</span></span>- <span className="flex items-center gap-1">- {ttsSupported ? <Check size={10} className="text-green-500" /> : <X size={10} className="text-red-500" />}- <span className="text-gray-500">TTS</span>- </span>- {/* §24.9 — Install affordance: the STT badge used to just show ✗- with no fix. This installs faster-whisper into LU's Python- and starts the STT server, then re-checks the badge. */}{!whisperLoading && whisperStatus && !whisperStatus.available && (<buttononClick={() => void handleInstallWhisper()}disabled={whisperInstalling}className="ml-auto inline-flex items-center gap-1 px-2 py-0.5 rounded text-[0.6rem] font-medium bg-blue-500/15 text-blue-400 border border-blue-500/30 hover:bg-blue-500/25 transition-colors disabled:opacity-50"- title="Install faster-whisper so speech-to-text works"+ title="Download + install faster-whisper so the microphone works">- {whisperInstalling ? <Loader2 size={9} className="animate-spin" /> : null}- {whisperInstalling ? 'Installing…' : 'Install'}+ {whisperInstalling ? <Loader2 size={9} className="animate-spin" /> : <Download size={9} />}+ {whisperInstalling ? 'Installing…' : 'Download & Install'}</button>)}</div>@@ -1073,12 +1127,44 @@ export function SettingsPage() {)}{!whisperLoading && whisperStatus && !whisperStatus.available && !whisperInstalling && !whisperInstallError && (<p className="text-[0.55rem] text-gray-500 leading-snug">- Speech-to-text needs faster-whisper. Click Install to set it up locally (uses LU's Python; first run also downloads a small model).+ Required for the microphone. Installs faster-whisper into LU's Python; first run also downloads a small model.</p>)}- <InlineToggle label="TTS Enabled" enabled={voiceSettings.ttsEnabled} onChange={() => voiceSettings.updateVoiceSettings({ ttsEnabled: !voiceSettings.ttsEnabled })} icon={<Volume2 size={11} className="text-gray-500" />} />++ {/* Text-to-Speech — Piper neural (read responses aloud) */}+ <div className="flex items-center gap-2 text-[0.65rem] pt-1">+ <span className="flex items-center gap-1.5">+ {ttsLoading+ ? <Loader2 size={11} className="animate-spin text-gray-500" />+ : ttsStatus?.available ? <Check size={11} className="text-green-500" /> : <X size={11} className="text-red-500" />}+ <Volume2 size={11} className="text-gray-400" />+ <span className="text-gray-700 dark:text-gray-200 font-medium">Text-to-Speech</span>+ <span className="text-gray-500">Piper neural</span>+ </span>+ {!ttsLoading && ttsStatus && !ttsStatus.available && (+ <button+ onClick={() => void handleInstallTts()}+ disabled={ttsInstalling}+ className="ml-auto inline-flex items-center gap-1 px-2 py-0.5 rounded text-[0.6rem] font-medium bg-blue-500/15 text-blue-400 border border-blue-500/30 hover:bg-blue-500/25 transition-colors disabled:opacity-50"+ title="Download + install Piper neural TTS + a voice (~63 MB)"+ >+ {ttsInstalling ? <Loader2 size={9} className="animate-spin" /> : <Download size={9} />}+ {ttsInstalling ? 'Installing…' : 'Download & Install'}+ </button>+ )}+ </div>+ {ttsInstallError && (+ <p className="text-[0.55rem] text-red-400/90 leading-snug">{ttsInstallError}</p>+ )}+ {!ttsLoading && ttsStatus && !ttsStatus.available && !ttsInstalling && !ttsInstallError && (+ <p className="text-[0.55rem] text-gray-500 leading-snug">+ Required for read-aloud. Installs Piper + a neural voice locally (~63 MB).+ </p>+ )}++ <InlineToggle label="Read responses aloud" enabled={voiceSettings.ttsEnabled} onChange={() => voiceSettings.updateVoiceSettings({ ttsEnabled: !voiceSettings.ttsEnabled })} icon={<Volume2 size={11} className="text-gray-500" />} /><div className="flex items-center justify-between">- <span className="text-[0.7rem] text-gray-500">Voice</span>+ <span className="text-[0.7rem] text-gray-500">Fallback voice</span><selectvalue={voiceSettings.ttsVoice}onChange={(e) => voiceSettings.updateVoiceSettings({ ttsVoice: e.target.value })}diff --git a/src/hooks/useVoice.ts b/src/hooks/useVoice.tsindex 7e7d616d..aef8ce15 100644--- a/src/hooks/useVoice.ts+++ b/src/hooks/useVoice.ts@@ -2,6 +2,10 @@ import { useCallback, useRef } from "react";import { useVoiceStore } from "../stores/voiceStore";import {recheckWhisperAvailable,+ recheckTtsAvailable,+ synthesizeNeural,+ playNeuralAudio,+ stopNeuralAudio,isSpeechSynthesisSupported,speak,speakStreaming,@@ -16,6 +20,11 @@ import { log } from "../lib/logger";export function useVoice() {const store = useVoiceStore();const recorderRef = useRef<AudioRecorder | null>(null);+ // Streaming-dictation plumbing: a polling timer that transcribes the+ // audio-so-far while recording, and a single-in-flight guard so slow+ // (CPU Whisper) transcriptions never pile up.+ const streamTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);+ const interimBusyRef = useRef(false);// Reactive: the source of truth is the store flag set by the startup probe// (App.tsx) and the in-app install (Settings). Reading a module-level boolean@@ -23,6 +32,9 @@ export function useVoice() {const sttSupported = store.sttAvailable;const ttsSupported = isSpeechSynthesisSupported();+ // Reactive neural-TTS availability (Piper), same model as sttAvailable.+ const ttsAvailable = store.ttsAvailable;+// Re-probe Whisper on demand (mic mount / after install) and sync the store.const recheckStt = useCallback(async (): Promise<boolean> => {const ok = await recheckWhisperAvailable();@@ -30,34 +42,77 @@ export function useVoice() {return ok;}, [store]);- const startRecording = useCallback(async () => {- if (recorderRef.current?.isRecording()) return;+ // Re-probe neural TTS on demand (after install) and sync the store.+ const recheckTts = useCallback(async (): Promise<boolean> => {+ const ok = await recheckTtsAvailable();+ store.setTtsAvailable(ok);+ return ok;+ }, [store]);- const recorder = createAudioRecorder();- recorderRef.current = recorder;+ /**+ * Start dictation. If `onInterim` is supplied, the audio captured so far is+ * transcribed on a ~1.4 s cadence and streamed back so the input grows live+ * (Whisper isn't truly real-time, so this is chunked, not word-by-word). A+ * single-in-flight guard skips ticks while a transcription is still running,+ * so slow CPU transcriptions never queue up.+ */+ const startRecording = useCallback(+ async (onInterim?: (text: string) => void) => {+ if (recorderRef.current?.isRecording()) return;- try {- await recorder.start();- store.setRecording(true);- store.setTranscript("");- } catch (err) {- log.error("Failed to start recording", { err });- recorderRef.current = null;- }- }, [store]);+ const recorder = createAudioRecorder();+ recorderRef.current = recorder;++ try {+ await recorder.start();+ store.setRecording(true);+ store.setTranscript("");++ if (onInterim) {+ streamTimerRef.current = setInterval(async () => {+ const rec = recorderRef.current;+ if (!rec?.isRecording() || interimBusyRef.current) return;+ const snap = rec.snapshot();+ // ~0.4 s of 16 kHz / 16-bit mono ≈ 12.8 KB — wait for a little audio.+ if (!snap || snap.size < 12000) return;+ interimBusyRef.current = true;+ try {+ const partial = await transcribeAudio(snap);+ if (recorderRef.current?.isRecording() && partial.trim()) {+ store.setTranscript(partial.trim());+ onInterim(partial.trim());+ }+ } catch {+ /* interim failures are non-fatal — the final transcribe still runs */+ } finally {+ interimBusyRef.current = false;+ }+ }, 1400);+ }+ } catch (err) {+ log.error("Failed to start recording", { err });+ if (streamTimerRef.current) { clearInterval(streamTimerRef.current); streamTimerRef.current = null; }+ interimBusyRef.current = false;+ recorderRef.current = null;+ }+ },+ [store],+ );const stopRecording = useCallback(async (): Promise<string> => {+ if (streamTimerRef.current) { clearInterval(streamTimerRef.current); streamTimerRef.current = null; }+ interimBusyRef.current = false;if (!recorderRef.current) return "";try {- // Stop recording and get the audio blob+ // Stop recording and get the final WAV of the whole take.const blob = await recorderRef.current.stop();store.setRecording(false);recorderRef.current = null;if (blob.size === 0) return "";- // Transcribe locally via Whisper+ // Final full-take transcription — more accurate than the interim chunks.store.setTranscribing(true);try {const transcript = await transcribeAudio(blob);@@ -78,20 +133,37 @@ export function useVoice() {}}, [store]);- const speakText = useCallback(- async (text: string) => {- if (!ttsSupported || !store.ttsEnabled) return;+ // Speak `text`. Prefers local neural TTS (Piper) when installed; otherwise+ // falls back to the browser's SpeechSynthesis voices. `streaming` only+ // affects the browser path (sentence-by-sentence so it starts sooner) —+ // neural always synthesizes the whole utterance in one local call.+ const speakInternal = useCallback(+ async (text: string, streaming: boolean) => {+ if (!store.ttsEnabled) return;+ if (!store.ttsAvailable && !ttsSupported) return;store.setSpeaking(true);-try {+ if (store.ttsAvailable) {+ try {+ const url = await synthesizeNeural(text);+ await playNeuralAudio(url);+ return;+ } catch (err) {+ log.error("Neural TTS failed, falling back to browser voices", { err });+ }+ }+ if (!ttsSupported) return;let voice: SpeechSynthesisVoice | undefined;if (store.ttsVoice) {const voices = await getVoicesAsync();voice = voices.find((v) => v.name === store.ttsVoice);}-- await speak(text, voice, store.ttsRate, store.ttsPitch);+ if (streaming) {+ await speakStreaming(text, voice, store.ttsRate, store.ttsPitch);+ } else {+ await speak(text, voice, store.ttsRate, store.ttsPitch);+ }} catch (err) {log.error("Speech synthesis error", { err });} finally {@@ -101,30 +173,11 @@ export function useVoice() {[store, ttsSupported]);- const speakTextStreaming = useCallback(- async (text: string) => {- if (!ttsSupported || !store.ttsEnabled) return;-- store.setSpeaking(true);-- try {- let voice: SpeechSynthesisVoice | undefined;- if (store.ttsVoice) {- const voices = await getVoicesAsync();- voice = voices.find((v) => v.name === store.ttsVoice);- }-- await speakStreaming(text, voice, store.ttsRate, store.ttsPitch);- } catch (err) {- log.error("Speech synthesis streaming error", { err });- } finally {- store.setSpeaking(false);- }- },- [store, ttsSupported]- );+ const speakText = useCallback((text: string) => speakInternal(text, false), [speakInternal]);+ const speakTextStreaming = useCallback((text: string) => speakInternal(text, true), [speakInternal]);const stopSpeaking = useCallback(() => {+ stopNeuralAudio();stopSpeakingApi();store.setSpeaking(false);}, [store]);@@ -136,9 +189,12 @@ export function useVoice() {transcript: store.transcript,sttSupported,ttsSupported,+ ttsAvailable,+ ttsEnabled: store.ttsEnabled,startRecording,stopRecording,recheckStt,+ recheckTts,speakText,speakTextStreaming,stopSpeaking,diff --git a/src/stores/voiceStore.ts b/src/stores/voiceStore.tsindex f7fbcfc6..ddcf2967 100644--- a/src/stores/voiceStore.ts+++ b/src/stores/voiceStore.ts@@ -12,6 +12,9 @@ interface VoiceState {// "available" can never light up the mic on a machine where Whisper is gone,// and a fresh install lights it up without a restart.sttAvailable: boolean;+ // Whether local neural TTS (Piper) is installed + a voice model is present.+ // Same transient/probe model as sttAvailable.+ ttsAvailable: boolean;// Persisted settingssttEnabled: boolean;@@ -26,6 +29,7 @@ interface VoiceState {setSpeaking: (speaking: boolean) => void;setTranscript: (transcript: string) => void;setSttAvailable: (available: boolean) => void;+ setTtsAvailable: (available: boolean) => void;updateVoiceSettings: (settings: Partial<{sttEnabled: boolean;@@ -47,10 +51,14 @@ export const useVoiceStore = create<VoiceState>()(isSpeaking: false,transcript: "",sttAvailable: false,+ ttsAvailable: false,// Persisted settingssttEnabled: true,- ttsEnabled: false,+ // TTS (read-aloud) on by default — David 2026-06-06 "texttospeech+ // aktivieren". There is no auto-speak; this just shows/enables the+ // per-message read-aloud Speaker button when TTS is usable.+ ttsEnabled: true,ttsVoice: "",ttsRate: 1.0,ttsPitch: 1.0,@@ -61,6 +69,7 @@ export const useVoiceStore = create<VoiceState>()(setSpeaking: (speaking) => set({ isSpeaking: speaking }),setTranscript: (transcript) => set({ transcript }),setSttAvailable: (available) => set({ sttAvailable: available }),+ setTtsAvailable: (available) => set({ ttsAvailable: available }),updateVoiceSettings: (settings) => set((state) => ({ ...state, ...settings })),