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
fix(voice): state detection, venv python, PEP 668 installs, opt-in auto-read (#77, #78)
purplecc7451fe3dae
diff --git a/src-tauri/src/commands/install.rs b/src-tauri/src/commands/install.rsindex 15b9366e..f7cbc1b7 100644--- a/src-tauri/src/commands/install.rs+++ b/src-tauri/src/commands/install.rs@@ -2398,7 +2398,16 @@ pub fn install_whisper(update("installing", &format!("Installing faster-whisper via {} (this can take a few minutes)…", target_python));- let args = build_whisper_pip_args();+ let mut args = build_whisper_pip_args();+ // Arch / Debian 12+ / Fedora 38+ system Python is PEP 668 protected, so a+ // bare `pip install` dies with externally-managed-environment. When that's+ // the target (no ComfyUI venv absorbed it), install into the user site+ // with the escape hatch so STT installs there too (joerack, Arch). No-op+ // on Windows/macOS/venv Pythons (not PEP 668 protected).+ if is_pep668_protected(&target_python) {+ args.push("--break-system-packages");+ args.push("--user");+ }// No cancel flag — this single pip install is short relative to the// ComfyUI PyTorch download, so we run it to completion like install_python.match pip_install_streaming_with_retry_cancellable(&args, &target_python, 3, &install_state, None) {@@ -2550,7 +2559,13 @@ pub fn install_tts(&format!("Installing piper-tts via {} (this can take a few minutes)…", target_python),);- let args = build_tts_pip_args();+ let mut args = build_tts_pip_args();+ // PEP 668 escape hatch (Arch / Debian 12+ / Fedora 38+) — see+ // install_whisper. No-op on Windows/macOS/venv Pythons.+ if is_pep668_protected(&target_python) {+ args.push("--break-system-packages");+ args.push("--user");+ }match pip_install_streaming_with_retry_cancellable(&args, &target_python, 3, &install_state, None) {Ok(()) => {update(diff --git a/src-tauri/src/commands/tts.rs b/src-tauri/src/commands/tts.rsindex eb5e916b..14c69e2d 100644--- a/src-tauri/src/commands/tts.rs+++ b/src-tauri/src/commands/tts.rs@@ -69,7 +69,19 @@ pub fn tts_status(state: State<'_, AppState>, app: tauri::AppHandle) -> Result<spiper_importable = cmd.output().map(|o| o.status.success()).unwrap_or(false);}- let voice_ready = piper_voice_paths(&app, PIPER_VOICE).map(|(onnx, _)| onnx.exists()).unwrap_or(false);+ // Ready if ANY voice model is present, not just the hardcoded default+ // (#77, ElBiggus): a user who downloaded a different voice than+ // en_US-lessac-medium had the badge read "not installed" and every read+ // fell back to the Windows SAPI voice.+ let voice_ready = piper_voices_dir(&app)+ .ok()+ .and_then(|dir| std::fs::read_dir(&dir).ok())+ .map(|entries| {+ entries+ .flatten()+ .any(|e| e.file_name().to_string_lossy().ends_with(".onnx"))+ })+ .unwrap_or(false);Ok(serde_json::json!({"available": piper_importable && voice_ready,diff --git a/src-tauri/src/commands/whisper.rs b/src-tauri/src/commands/whisper.rsindex c358d4ad..a0df601a 100644--- a/src-tauri/src/commands/whisper.rs+++ b/src-tauri/src/commands/whisper.rs@@ -155,14 +155,57 @@ impl WhisperServer {#[tauri::command]pub fn whisper_status(state: State<'_, AppState>) -> Result<serde_json::Value, String> {- let whisper = state.whisper.lock().unwrap();+ let (running, ready, backend) = {+ let whisper = state.whisper.lock().unwrap();+ (whisper.process.is_some(), whisper.ready, whisper.backend.clone())+ };+ // Report INSTALLED-on-disk, not merely "server process running". The whisper+ // server lazy-starts on first mic use and is killed on quit, so keying the+ // badge on process.is_some() made STT read as uninstalled after every+ // relaunch — the "reinstall every launch" report (#78, ElBiggus). If the+ // server is up it's obviously installed; otherwise probe the resolved+ // interpreter for the faster_whisper package.+ let available = running || whisper_package_installed(state.inner());Ok(serde_json::json!({- "available": whisper.process.is_some(),- "backend": whisper.backend,- "loading": whisper.process.is_some() && !whisper.ready,+ "available": available,+ "backend": backend,+ "loading": running && !ready,}))}+/// Is `faster_whisper` importable in the interpreter install_whisper targets+/// (resolve_lu_python: ComfyUI venv if present, else system Python)? Cheap+/// best-effort probe so the badge reflects a prior install across relaunches+/// without the server running. Any spawn/timeout failure → "not installed".+fn whisper_package_installed(state: &AppState) -> bool {+ let python = crate::commands::install::resolve_lu_python(state);+ if python.is_empty() {+ return false;+ }+ let mut cmd = Command::new(&python);+ cmd.args(["-c", "import faster_whisper"])+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null());+ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);+ let mut child = match cmd.spawn() {+ Ok(c) => c,+ Err(_) => return false,+ };+ // An ABSENT package fails in well under a second; a present one loads+ // ctranslate2 (a few seconds cold). 10 s cap so status never hangs.+ for _ in 0..100 {+ match child.try_wait() {+ Ok(Some(status)) => return status.success(),+ Ok(None) => std::thread::sleep(std::time::Duration::from_millis(100)),+ Err(_) => return false,+ }+ }+ let _ = child.kill();+ false+}+#[tauri::command]pub fn transcribe(app: AppHandle, audio_base64: String, content_type: String, state: State<'_, AppState>) -> Result<serde_json::Value, String> {let audio_bytes = base64::engine::general_purpose::STANDARD@@ -199,7 +242,11 @@ pub fn transcribe(app: AppHandle, audio_base64: String, content_type: String, st{let needs_start = state.whisper.lock().map(|w| w.process.is_none()).unwrap_or(true);if needs_start {- let python_bin = state.python_bin.lock().unwrap().clone();+ // Resolve the SAME interpreter install_whisper used (ComfyUI venv if+ // present, else system Python). Using state.python_bin here meant a+ // venv install was invisible at runtime → STT silently dead after+ // relaunch on boxes with a ComfyUI venv (#78).+ let python_bin = crate::commands::install::resolve_lu_python(state.inner());if python_bin.is_empty() {return Err("Whisper unavailable: no Python runtime detected. Install Python in the setup step, then retry.".to_string());}diff --git a/src/api/voice.ts b/src/api/voice.tsindex 66a78636..f6f51241 100644--- a/src/api/voice.ts+++ b/src/api/voice.ts@@ -114,9 +114,16 @@ export function speak(}/**- * Speak text sentence by sentence for streaming-style playback.- * Each sentence is spoken sequentially, allowing early interruption- * via stopSpeaking() between sentences.+ * Speak `text` via the browser SpeechSynthesis fallback.+ *+ * Speaks the whole text as ONE utterance. It used to split into per-sentence+ * utterances and chain them, which hit the well-known Chromium/WebView2 bug+ * where speak() issued right after cancel() silently no-ops — so onend for the+ * 2nd sentence never fired and playback died after the FIRST sentence (#77c,+ * ElBiggus: only "What do you call a fake noodle?" was read, never the punch+ * line). One utterance removes the chaining entirely; stopSpeaking() (cancel)+ * still interrupts instantly. A periodic resume() counters Chromium pausing the+ * synthesizer after ~15 s on a long answer.*/export async function speakStreaming(text: string,@@ -127,34 +134,34 @@ export async function speakStreaming(if (!isSpeechSynthesisSupported()) return;stopSpeaking();- // Split into sentences (keeping the punctuation)- const sentences = text.match(/[^.!?]+[.!?]+/g) || [text];-- for (const sentence of sentences) {- const trimmed = sentence.trim();- if (!trimmed) continue;-- // Check if speech was cancelled between sentences- if (!window.speechSynthesis) return;-- await new Promise<void>((resolve, reject) => {- const utterance = new SpeechSynthesisUtterance(trimmed);- if (voice) utterance.voice = voice;- if (rate !== undefined) utterance.rate = rate;- if (pitch !== undefined) utterance.pitch = pitch;-- utterance.onend = () => resolve();- utterance.onerror = (event) => {- if (event.error === "canceled" || event.error === "interrupted") {- resolve();- } else {- reject(new Error(`Speech synthesis error: ${event.error}`));- }- };+ const synth = window.speechSynthesis;+ const trimmed = text.trim();+ if (!trimmed || !synth) return;- window.speechSynthesis.speak(utterance);- });- }+ await new Promise<void>((resolve, reject) => {+ const utterance = new SpeechSynthesisUtterance(trimmed);+ if (voice) utterance.voice = voice;+ if (rate !== undefined) utterance.rate = rate;+ if (pitch !== undefined) utterance.pitch = pitch;++ const keepAlive = setInterval(() => {+ try { synth.resume(); } catch { /* engine gone — onend/onerror will settle */ }+ }, 10000);+ let settled = false;+ const cleanup = () => { if (settled) return; settled = true; clearInterval(keepAlive); };++ utterance.onend = () => { cleanup(); resolve(); };+ utterance.onerror = (event) => {+ cleanup();+ if (event.error === "canceled" || event.error === "interrupted") {+ resolve();+ } else {+ reject(new Error(`Speech synthesis error: ${event.error}`));+ }+ };++ synth.speak(utterance);+ });}export function stopSpeaking(): void {diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsxindex 8b4bf88f..5ec4e3d7 100644--- a/src/components/settings/SettingsPage.tsx+++ b/src/components/settings/SettingsPage.tsx@@ -915,11 +915,15 @@ export function SettingsPage() {}}- // Pick a Piper voice. If it isn't on disk yet, download it (~63 MB) first,- // then re-check the installed list + TTS availability.+ // Pick a Piper voice. If it isn't on disk yet, download it (~63 MB), then+ // re-check the installed list + TTS availability. The selection is applied+ // optimistically (so the dropdown reflects the pick) but REVERTED if the+ // download fails — otherwise piperVoice pointed at a missing model and every+ // read fell back to the Windows SAPI voice (#77, ElBiggus).const handlePickVoice = async (id: string) => {- voiceSettings.setPiperVoice(id)setVoiceError(null)+ const prev = voiceSettings.piperVoice+ voiceSettings.setPiperVoice(id)if (installedVoices.includes(id)) returnsetVoiceBusy(true)try {@@ -927,6 +931,7 @@ export function SettingsPage() {await refreshVoices()await refreshTts()} catch (e) {+ voiceSettings.setPiperVoice(prev)setVoiceError(e instanceof Error ? e.message : String(e))} finally {setVoiceBusy(false)@@ -1268,7 +1273,10 @@ export function SettingsPage() {<p className="text-[0.55rem] text-gray-500 leading-snug">Cloud mode: dictation and read-aloud run on lu-labs.ai (hosted Whisper speech-to-text + MiniMax text-to-speech) and are metered against your credits. No local installs needed.</p>- <InlineToggle label="Read responses aloud" enabled={voiceSettings.ttsEnabled} onChange={() => voiceSettings.updateVoiceSettings({ ttsEnabled: !voiceSettings.ttsEnabled })} icon={<Volume2 size={11} className="text-gray-500" />} />+ <InlineToggle label="Enable read-aloud" enabled={voiceSettings.ttsEnabled} onChange={() => voiceSettings.updateVoiceSettings({ ttsEnabled: !voiceSettings.ttsEnabled })} icon={<Volume2 size={11} className="text-gray-500" />} />+ {voiceSettings.ttsEnabled && (+ <InlineToggle label="Auto-read new responses" enabled={voiceSettings.autoReadAloud} onChange={() => voiceSettings.updateVoiceSettings({ autoReadAloud: !voiceSettings.autoReadAloud })} icon={<Volume2 size={11} className="text-gray-500" />} />+ )}<div className="flex items-center justify-between gap-2"><span className="text-[0.7rem] text-gray-500">Voice</span><select@@ -1348,7 +1356,14 @@ export function SettingsPage() {</p>)}- <InlineToggle label="Read responses aloud" enabled={voiceSettings.ttsEnabled} onChange={() => voiceSettings.updateVoiceSettings({ ttsEnabled: !voiceSettings.ttsEnabled })} icon={<Volume2 size={11} className="text-gray-500" />} />+ <InlineToggle label="Enable read-aloud" enabled={voiceSettings.ttsEnabled} onChange={() => voiceSettings.updateVoiceSettings({ ttsEnabled: !voiceSettings.ttsEnabled })} icon={<Volume2 size={11} className="text-gray-500" />} />+ {/* Auto-read is a SEPARATE opt-in (default OFF). The toggle above only+ surfaces the per-message Speaker button; this one also reads each+ finished response aloud (#77, ElBiggus — the old single toggle was+ labelled "Read responses aloud" but never auto-read). */}+ {voiceSettings.ttsEnabled && (+ <InlineToggle label="Auto-read new responses" enabled={voiceSettings.autoReadAloud} onChange={() => voiceSettings.updateVoiceSettings({ autoReadAloud: !voiceSettings.autoReadAloud })} icon={<Volume2 size={11} className="text-gray-500" />} />+ )}{/* Neural voice picker (Piper) — replaces the old Microsoft/browservoices (David 2026-06-06). Picking one not yet on disk downloadsit (~63 MB). Browser-only rate/pitch knobs dropped — they didn'tdiff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex f50eb739..75549e09 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -27,6 +27,8 @@ import { compactMessages, getModelMaxTokens, estimateTokens } from '../lib/conteimport { getModelContextCached } from '../api/ollama'import { effectiveContextWindow } from '../lib/context-window'import { useMemoryStore } from '../stores/memoryStore'+import { useVoiceStore } from '../stores/voiceStore'+import { autoSpeak } from '../lib/ttsBridge'import { getProviderForModel, getProviderIdFromModel } from '../api/providers'import { buildExtractionPrompt, parseExtractionResponse } from '../lib/memory-extraction'import { useAgentWorkflowStore } from '../stores/agentWorkflowStore'@@ -1433,9 +1435,15 @@ export function useAgentChat() {approvalQueueRef.current = []setPendingApproval(null)- // No auto-speak. Reading a response aloud is manual-only via the- // per-message Speaker button (David 2026-06-07: "nicht immer automatisch- // vorlesen"). Enabling TTS only surfaces that button; it never auto-reads.+ // Auto-read the finished response when the user opted in (#77). Default+ // OFF, additionally gated on ttsEnabled; getState() so this callback never+ // subscribes to the voice store's isSpeaking churn during playback.+ {+ const voice = useVoiceStore.getState()+ if (voice.ttsEnabled && voice.autoReadAloud && contentRef.current.trim()) {+ autoSpeak(contentRef.current)+ }+ }// Auto-extract memories (fire-and-forget, agent mode always qualifies)const memSettings = useMemoryStore.getState().settingsdiff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex 703db14b..9dd0c17f 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -5,6 +5,8 @@ import { useModelStore } from "../stores/modelStore"import { useSettingsStore } from "../stores/settingsStore"import { useRAGStore } from "../stores/ragStore"import { useMemoryStore } from "../stores/memoryStore"+import { useVoiceStore } from "../stores/voiceStore"+import { autoSpeak } from "../lib/ttsBridge"import { retrieveContext } from "../api/rag"import { getModelMaxTokens } from "../lib/context-compaction"import { getModelContextCached } from "../api/ollama"@@ -555,9 +557,16 @@ export function useChat() {useModelStore.getState().setIsModelLoading(false)abortRef.current = null- // No auto-speak. Reading a response aloud is manual-only via the- // per-message Speaker button (David 2026-06-07: "nicht immer automatisch- // vorlesen"). Enabling TTS only surfaces that button; it never auto-reads.+ // Auto-read the finished response when the user opted in (#77, ElBiggus).+ // Default OFF and additionally gated on ttsEnabled; getState() (not the+ // hook) so this callback never subscribes to the voice store's isSpeaking+ // churn during playback.+ {+ const voice = useVoiceStore.getState()+ if (voice.ttsEnabled && voice.autoReadAloud && contentRef.current.trim()) {+ autoSpeak(contentRef.current)+ }+ }// Auto-extract memories (fire-and-forget)const memSettings = useMemoryStore.getState().settingsdiff --git a/src/hooks/useVoice.ts b/src/hooks/useVoice.tsindex c56a4554..5c018537 100644--- a/src/hooks/useVoice.ts+++ b/src/hooks/useVoice.ts@@ -24,6 +24,7 @@ import {import { CloudJobError } from "../api/cloud/client";import { isTauri } from "../api/backend";import { log } from "../lib/logger";+import { registerAutoSpeak } from "../lib/ttsBridge";// Honest, actionable copy for dictation failures. The cloud route's own error// strings (403 "your plan does not include cloud voice", 429 "monthly credit@@ -357,6 +358,13 @@ export function useVoice() {const speakText = useCallback((text: string) => speakInternal(text, false), [speakInternal]);const speakTextStreaming = useCallback((text: string) => speakInternal(text, true), [speakInternal]);+ // Publish the current streaming-speak fn so useChat/useAgentChat can auto-read+ // finished responses (#77) without subscribing to this store. Re-runs whenever+ // the fn is re-memoized (i.e. voice settings changed), keeping it fresh.+ useEffect(() => {+ registerAutoSpeak(speakTextStreaming);+ }, [speakTextStreaming]);+// Module-scoped singleton — any instance's Stop halts the global playback.const stopSpeaking = useCallback(() => stopSpeechPlayback(), []);diff --git a/src/lib/ttsBridge.ts b/src/lib/ttsBridge.tsnew file mode 100644index 00000000..a90d0134--- /dev/null+++ b/src/lib/ttsBridge.ts@@ -0,0 +1,18 @@+// Auto-read bridge (#77). Lets non-voice hooks (useChat / useAgentChat, on turn+// completion) trigger the SAME TTS ladder the Speaker button uses, WITHOUT+// calling useVoice() themselves — useVoice subscribes to the voice store whose+// `isSpeaking` flips during playback, and a chat hook must not re-render on that.+//+// useVoice registers its current streaming-speak fn; the always-mounted mic+// VoiceButton keeps it refreshed on every voice-state change, so `current`+// tracks the live voice settings. Callers gate on `ttsEnabled && autoReadAloud`+// (read via getState(), non-reactive) before invoking.+let current: ((text: string) => void) | null = null++export function registerAutoSpeak(fn: (text: string) => void): void {+ current = fn+}++export function autoSpeak(text: string): void {+ current?.(text)+}diff --git a/src/stores/voiceStore.ts b/src/stores/voiceStore.tsindex 07e6b485..aca9b26b 100644--- a/src/stores/voiceStore.ts+++ b/src/stores/voiceStore.ts@@ -23,6 +23,10 @@ interface VoiceState {// Persisted settingssttEnabled: boolean;ttsEnabled: boolean;+ /** Read each finished response aloud automatically (#77, ElBiggus). Opt-in,+ * default OFF — TTS on only surfaces the manual per-message Speaker button;+ * this additionally auto-reads when the turn completes. */+ autoReadAloud: boolean;/** Selected Piper neural voice id (e.g. "en_US-lessac-medium"). */piperVoice: string;/** Browser SpeechSynthesis voice — only the fallback when neural is off. */@@ -52,6 +56,7 @@ interface VoiceState {settings: Partial<{sttEnabled: boolean;ttsEnabled: boolean;+ autoReadAloud: boolean;ttsVoice: string;ttsRate: number;ttsPitch: number;@@ -82,12 +87,12 @@ export const useVoiceStore = create<VoiceState>()(// Persisted settings — voice OFF by default (David 2026-06-07:// "tts und stt standardmäßig AUS und nicht immer automatisch vorlesen").- // STT and TTS are opt-in; nothing reads responses aloud automatically- // (the auto-speak on turn-completion was removed in useChat/useAgentChat).- // When the user turns TTS on, it only enables the per-message read-aloud- // Speaker button — reading happens on click, never automatically.+ // STT and TTS are opt-in. TTS on surfaces the per-message read-aloud+ // Speaker button; auto-reading is a SEPARATE opt-in (autoReadAloud, default+ // OFF) so "always read aloud" stays off unless the user asks for it (#77).sttEnabled: false,ttsEnabled: false,+ autoReadAloud: false,piperVoice: "en_US-lessac-medium",ttsVoice: "",ttsRate: 1.0,@@ -122,6 +127,7 @@ export const useVoiceStore = create<VoiceState>()(set({sttEnabled: false,ttsEnabled: false,+ autoReadAloud: false,piperVoice: "en_US-lessac-medium",ttsVoice: "",ttsRate: 1.0,@@ -137,6 +143,7 @@ export const useVoiceStore = create<VoiceState>()(partialize: (state) => ({sttEnabled: state.sttEnabled,ttsEnabled: state.ttsEnabled,+ autoReadAloud: state.autoReadAloud,piperVoice: state.piperVoice,ttsVoice: state.ttsVoice,ttsRate: state.ttsRate,