Skip to content

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.

fix(voice): STT transcribe arg-name bug (the 'no text') + Piper voice picker

purpled3aa30092754
diff --git a/src-tauri/src/commands/tts.rs b/src-tauri/src/commands/tts.rs
index 154b9482..d939d476 100644
--- a/src-tauri/src/commands/tts.rs
+++ b/src-tauri/src/commands/tts.rs
@@ -5,8 +5,8 @@
//! 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.
+//! avoids a long-lived process + version-specific Python API. Voice models are
+//! downloaded on demand into `<app_data>/piper_voices/`.
use std::io::Write;
use std::path::PathBuf;
@@ -24,24 +24,38 @@ use crate::state::AppState;
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/`.
+/// ~63 MB. 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> {
+/// Reject voice names that aren't a plain Piper voice id (defence-in-depth — the
+/// name is interpolated into a download URL + a file path). Real ids look like
+/// `en_US-lessac-medium` / `en_GB-alba-medium`.
+fn is_valid_voice(voice: &str) -> bool {
+ !voice.is_empty()
+ && voice.len() < 64
+ && voice.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
+}
+
+fn piper_voices_dir(app: &tauri::AppHandle) -> Result<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))
+ Ok(dir)
}
-/// Whether neural TTS is usable: `import piper` succeeds AND the voice model is
-/// present. The Settings badge + the chat SpeakerButton gate on this.
+/// `(model.onnx, model.onnx.json)` for a voice id under the piper_voices dir.
+pub fn piper_voice_paths(app: &tauri::AppHandle, voice: &str) -> Result<(PathBuf, PathBuf), String> {
+ let dir = piper_voices_dir(app)?;
+ Ok((
+ dir.join(format!("{}.onnx", voice)),
+ dir.join(format!("{}.onnx.json", voice)),
+ ))
+}
+
+/// Whether neural TTS is usable: `import piper` succeeds AND the DEFAULT 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());
@@ -55,7 +69,7 @@ pub fn tts_status(state: State<'_, AppState>, app: tauri::AppHandle) -> Result<s
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);
+ let voice_ready = piper_voice_paths(&app, PIPER_VOICE).map(|(onnx, _)| onnx.exists()).unwrap_or(false);
Ok(serde_json::json!({
"available": piper_importable && voice_ready,
@@ -64,11 +78,76 @@ pub fn tts_status(state: State<'_, AppState>, app: tauri::AppHandle) -> Result<s
}))
}
-/// 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.
+/// Voice ids already downloaded under the piper_voices dir (file stems of the
+/// `*.onnx` models). The Settings picker marks these as installed.
+#[tauri::command]
+pub fn installed_piper_voices(app: tauri::AppHandle) -> Result<Vec<String>, String> {
+ let dir = match piper_voices_dir(&app) {
+ Ok(d) => d,
+ Err(_) => return Ok(vec![]),
+ };
+ let mut out = vec![];
+ if let Ok(entries) = std::fs::read_dir(&dir) {
+ for e in entries.flatten() {
+ let name = e.file_name().to_string_lossy().to_string();
+ if let Some(stem) = name.strip_suffix(".onnx") {
+ out.push(stem.to_string());
+ }
+ }
+ }
+ Ok(out)
+}
+
+/// Download a specific Piper voice model into the piper_voices dir. Blocking —
+/// the frontend awaits it with a spinner (no separate progress channel; a voice
+/// is ~63 MB). Idempotent: re-downloading an existing voice just no-ops fast.
+#[tauri::command]
+pub fn download_voice(
+ voice: String,
+ state: State<'_, AppState>,
+ app: tauri::AppHandle,
+) -> Result<serde_json::Value, String> {
+ if !is_valid_voice(&voice) {
+ return Err(format!("invalid voice id: {}", voice));
+ }
+ 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 dir = piper_voices_dir(&app)?;
+ let _ = std::fs::create_dir_all(&dir);
+
+ let mut cmd = Command::new(&python);
+ cmd.args([
+ "-m",
+ "piper.download_voices",
+ &voice,
+ "--download-dir",
+ &dir.to_string_lossy(),
+ ])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+ #[cfg(target_os = "windows")]
+ cmd.creation_flags(CREATE_NO_WINDOW);
+
+ let output = cmd.output().map_err(|e| format!("could not start voice download: {}", e))?;
+ if !output.status.success() {
+ return Err(format!("voice download failed: {}", String::from_utf8_lossy(&output.stderr)));
+ }
+ let (onnx, _) = piper_voice_paths(&app, &voice)?;
+ if !onnx.exists() {
+ return Err("voice download reported success but the model is missing".to_string());
+ }
+ Ok(serde_json::json!({ "ok": true, "voice": voice }))
+}
+
+/// Synthesize `text` to a WAV and return it base64-encoded for the frontend to
+/// play. `voice` is an optional Piper voice id (defaults to PIPER_VOICE). Runs
+/// the Piper CLI one-shot.
#[tauri::command]
pub fn synthesize(
text: String,
+ voice: Option<String>,
state: State<'_, AppState>,
app: tauri::AppHandle,
) -> Result<serde_json::Value, String> {
@@ -77,14 +156,22 @@ pub fn synthesize(
return Err("empty text".to_string());
}
+ let voice = match voice {
+ Some(v) if is_valid_voice(&v) => v,
+ _ => PIPER_VOICE.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)?;
+ let (onnx, config) = piper_voice_paths(&app, &voice)?;
if !onnx.exists() || !config.exists() {
- return Err("no_voice: neural TTS not installed — install it in Settings → Voice & Remote.".to_string());
+ return Err(format!(
+ "no_voice: the '{}' voice isn't downloaded — pick/install it in Settings → Voice & Remote.",
+ voice
+ ));
}
let stamp = std::time::SystemTime::now()
@@ -111,10 +198,9 @@ pub fn synthesize(
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
+ // dropped at end of block → stdin closed so piper proceeds
}
let output = child
.wait_with_output()
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index f87723f2..b9bcd7fe 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -131,6 +131,8 @@ fn main() {
// Piper neural TTS
commands::tts::tts_status,
commands::tts::synthesize,
+ commands::tts::download_voice,
+ commands::tts::installed_piper_voices,
// Agent tools (legacy)
commands::agent::execute_code,
commands::agent::file_read,
diff --git a/src/api/voice.ts b/src/api/voice.ts
index 5e7de0d7..737098e7 100644
--- a/src/api/voice.ts
+++ b/src/api/voice.ts
@@ -189,9 +189,13 @@ export async function transcribeAudio(audioBlob: Blob): Promise<string> {
binary += String.fromCharCode(bytes[i]);
}
const audioBase64 = btoa(binary);
+ // Tauri maps the Rust snake_case params (audio_base64, content_type) to
+ // camelCase invoke keys — passing snake_case silently fails the command
+ // ("missing required key audioBase64") → every transcription returned
+ // nothing. THIS was the "mic records but no text" bug.
const data = await backendCall("transcribe", {
- audio_base64: audioBase64,
- content_type: audioBlob.type || "audio/webm",
+ audioBase64,
+ contentType: audioBlob.type || "audio/wav",
});
if (data.error) throw new Error(data.error);
return data.transcript || "";
@@ -242,13 +246,28 @@ export async function recheckTtsAvailable(): Promise<boolean> {
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 });
+/** Synthesize text to a playable WAV data URL via a local Piper voice. */
+export async function synthesizeNeural(text: string, voice?: string): Promise<string> {
+ const data = await backendCall<{ audio_base64?: string; mime?: string }>("synthesize", { text, voice });
if (!data?.audio_base64) throw new Error("neural 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 });
+}
+
+/** Voice ids already present on disk — used to mark the Settings picker. */
+export async function listInstalledPiperVoices(): Promise<string[]> {
+ try {
+ if (isTauri()) return (await backendCall<string[]>("installed_piper_voices")) || [];
+ return [];
+ } catch {
+ return [];
+ }
+}
+
let neuralAudio: HTMLAudioElement | null = null;
/** Play a WAV data URL; resolves when playback ends. Replaces any current clip. */
@@ -392,6 +411,12 @@ export function createAudioRecorder(): AudioRecorder {
source.connect(processor);
processor.connect(mute);
mute.connect(audioCtx.destination);
+ // getUserMedia is awaited just above, which can drop the user-gesture
+ // activation → the AudioContext may start "suspended" and never fire
+ // onaudioprocess (= silent capture, empty WAV). Resume explicitly.
+ if (audioCtx.state === "suspended") {
+ try { await audioCtx.resume(); } catch { /* noop */ }
+ }
recording = true;
},
diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsx
index 812965af..6a32226e 100644
--- a/src/components/settings/SettingsPage.tsx
+++ b/src/components/settings/SettingsPage.tsx
@@ -6,7 +6,18 @@ import { useUIStore } from '../../stores/uiStore'
import { SliderControl } from './SliderControl'
import { PersonaPanel } from '../personas/PersonaPanel'
import { useVoiceStore } from '../../stores/voiceStore'
-import { checkWhisperAvailable, checkTtsAvailable } from '../../api/voice'
+import { checkWhisperAvailable, checkTtsAvailable, downloadPiperVoice, listInstalledPiperVoices } from '../../api/voice'
+
+// Curated local neural (Piper) voices the user can pick. Selecting one not yet
+// on disk downloads it (~63 MB). Ids match rhasspy/piper-voices.
+const PIPER_VOICES: { id: string; label: string }[] = [
+ { id: 'en_US-lessac-medium', label: 'Lessac — US, neutral' },
+ { id: 'en_US-amy-medium', label: 'Amy — US, female' },
+ { id: 'en_US-ryan-high', label: 'Ryan — US, male (high)' },
+ { id: 'en_US-hfc_female-medium', label: 'HFC — US, female' },
+ { id: 'en_GB-alba-medium', label: 'Alba — UK, female' },
+ { id: 'en_GB-northern_english_male-medium', label: 'Northern — UK, male' },
+]
import { useAgentModeStore } from '../../stores/agentModeStore'
import { FEATURE_FLAGS } from '../../lib/constants'
import { getRecommendedAgentModels } from '../../lib/model-compatibility'
@@ -667,7 +678,6 @@ export function SettingsPage() {
const { settings, updateSettings, resetSettings } = useSettingsStore()
const { setView } = useUIStore()
const voiceSettings = useVoiceStore()
- const [voices, setVoices] = useState<SpeechSynthesisVoice[]>([])
const [whisperStatus, setWhisperStatus] = useState<{ available: boolean; backend: string | null; error?: string } | null>(null)
const [whisperLoading, setWhisperLoading] = useState(true)
// §24.9 — in-app faster-whisper install. `installing` drives the spinner;
@@ -679,6 +689,10 @@ export function SettingsPage() {
const [ttsLoading, setTtsLoading] = useState(true)
const [ttsInstalling, setTtsInstalling] = useState(false)
const [ttsInstallError, setTtsInstallError] = useState<string | null>(null)
+ // Piper voice picker state.
+ const [installedVoices, setInstalledVoices] = useState<string[]>([])
+ const [voiceBusy, setVoiceBusy] = useState(false)
+ const [voiceError, setVoiceError] = useState<string | null>(null)
const [tab, setTab] = useState<SettingsTab>(() => {
if (typeof window === 'undefined') return 'general'
const stored = window.localStorage.getItem(SETTINGS_TAB_KEY)
@@ -692,18 +706,6 @@ export function SettingsPage() {
}
}, [tab])
- const ttsSupported = typeof window !== 'undefined' && 'speechSynthesis' in window
-
- useEffect(() => {
- if (!ttsSupported) return
- const loadVoices = () => {
- const v = speechSynthesis.getVoices()
- if (v.length > 0) setVoices(v)
- }
- loadVoices()
- speechSynthesis.addEventListener('voiceschanged', loadVoices)
- return () => speechSynthesis.removeEventListener('voiceschanged', loadVoices)
- }, [ttsSupported])
const refreshWhisper = () => {
setWhisperLoading(true)
@@ -729,9 +731,12 @@ export function SettingsPage() {
.finally(() => setTtsLoading(false))
}
+ const refreshVoices = () => listInstalledPiperVoices().then(setInstalledVoices).catch(() => {})
+
useEffect(() => {
void refreshWhisper()
void refreshTts()
+ void refreshVoices()
}, [])
// §24.9 — kick off the faster-whisper install, poll its status, then
@@ -804,6 +809,24 @@ 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.
+ const handlePickVoice = async (id: string) => {
+ voiceSettings.setPiperVoice(id)
+ setVoiceError(null)
+ if (installedVoices.includes(id)) return
+ setVoiceBusy(true)
+ try {
+ await downloadPiperVoice(id)
+ await refreshVoices()
+ await refreshTts()
+ } catch (e) {
+ setVoiceError(e instanceof Error ? e.message : String(e))
+ } finally {
+ setVoiceBusy(false)
+ }
+ }
+
return (
<div className="h-full overflow-y-auto scrollbar-thin">
<div className="max-w-lg mx-auto px-4 py-4">
@@ -1163,19 +1186,29 @@ export function SettingsPage() {
)}
<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">Fallback voice</span>
+ {/* Neural voice picker (Piper) — replaces the old Microsoft/browser
+ voices (David 2026-06-06). Picking one not yet on disk downloads
+ it (~63 MB). Browser-only rate/pitch knobs dropped — they didn't
+ apply to Piper. */}
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-[0.7rem] text-gray-500 flex items-center gap-1">
+ Voice {voiceBusy && <Loader2 size={10} className="animate-spin text-gray-500" />}
+ </span>
<select
- value={voiceSettings.ttsVoice}
- onChange={(e) => voiceSettings.updateVoiceSettings({ ttsVoice: e.target.value })}
- className="max-w-[180px] px-1.5 py-0.5 rounded bg-transparent border border-white/8 text-[0.65rem] text-gray-300 focus:outline-none"
+ value={voiceSettings.piperVoice}
+ onChange={(e) => void handlePickVoice(e.target.value)}
+ disabled={voiceBusy}
+ className="max-w-[210px] px-1.5 py-0.5 rounded bg-transparent border border-white/8 text-[0.65rem] text-gray-300 focus:outline-none disabled:opacity-50"
>
- <option value="">Default</option>
- {voices.map((v) => <option key={v.name} value={v.name}>{v.name}</option>)}
+ {PIPER_VOICES.map((v) => (
+ <option key={v.id} value={v.id}>
+ {v.label}{installedVoices.includes(v.id) ? '' : ' — download'}
+ </option>
+ ))}
</select>
</div>
- <SliderControl label="Rate" value={voiceSettings.ttsRate} min={0.5} max={2} step={0.1} onChange={(v) => voiceSettings.updateVoiceSettings({ ttsRate: v })} />
- <SliderControl label="Pitch" value={voiceSettings.ttsPitch} min={0.5} max={2} step={0.1} onChange={(v) => voiceSettings.updateVoiceSettings({ ttsPitch: v })} />
+ {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>}
</Section>
<Section title="Remote Access">
diff --git a/src/hooks/useVoice.ts b/src/hooks/useVoice.ts
index aef8ce15..56cf0a8a 100644
--- a/src/hooks/useVoice.ts
+++ b/src/hooks/useVoice.ts
@@ -146,7 +146,7 @@ export function useVoice() {
try {
if (store.ttsAvailable) {
try {
- const url = await synthesizeNeural(text);
+ const url = await synthesizeNeural(text, store.piperVoice);
await playNeuralAudio(url);
return;
} catch (err) {
diff --git a/src/stores/voiceStore.ts b/src/stores/voiceStore.ts
index ddcf2967..127ed3a5 100644
--- a/src/stores/voiceStore.ts
+++ b/src/stores/voiceStore.ts
@@ -19,6 +19,9 @@ interface VoiceState {
// Persisted settings
sttEnabled: boolean;
ttsEnabled: boolean;
+ /** Selected Piper neural voice id (e.g. "en_US-lessac-medium"). */
+ piperVoice: string;
+ /** Browser SpeechSynthesis voice — only the fallback when neural is off. */
ttsVoice: string;
ttsRate: number;
ttsPitch: number;
@@ -30,6 +33,7 @@ interface VoiceState {
setTranscript: (transcript: string) => void;
setSttAvailable: (available: boolean) => void;
setTtsAvailable: (available: boolean) => void;
+ setPiperVoice: (voice: string) => void;
updateVoiceSettings: (
settings: Partial<{
sttEnabled: boolean;
@@ -59,6 +63,7 @@ export const useVoiceStore = create<VoiceState>()(
// aktivieren". There is no auto-speak; this just shows/enables the
// per-message read-aloud Speaker button when TTS is usable.
ttsEnabled: true,
+ piperVoice: "en_US-lessac-medium",
ttsVoice: "",
ttsRate: 1.0,
ttsPitch: 1.0,
@@ -70,6 +75,7 @@ export const useVoiceStore = create<VoiceState>()(
setTranscript: (transcript) => set({ transcript }),
setSttAvailable: (available) => set({ sttAvailable: available }),
setTtsAvailable: (available) => set({ ttsAvailable: available }),
+ setPiperVoice: (voice) => set({ piperVoice: voice }),
updateVoiceSettings: (settings) => set((state) => ({ ...state, ...settings })),
@@ -86,6 +92,7 @@ export const useVoiceStore = create<VoiceState>()(
partialize: (state) => ({
sttEnabled: state.sttEnabled,
ttsEnabled: state.ttsEnabled,
+ piperVoice: state.piperVoice,
ttsVoice: state.ttsVoice,
ttsRate: state.ttsRate,
ttsPitch: state.ttsPitch,