Skip to main content

agentmux_srv/server/
voice.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! Voice speech-to-text endpoint — `POST /api/v1/voice/transcribe`, and `GET /api/v1/voice/status`, which
5//! says whether the chosen engine has what it needs, so the mic can say so before it records.
6//!
7//! The renderer captures mic audio (getUserMedia, gated by the CEF permission
8//! handler #1602) and POSTs each silence-bounded utterance here; we forward it
9//! to the configured Whisper backend and return the transcript. Keys/paths stay
10//! server-side — the renderer never sees them.
11//!
12//! Web Speech API can't transcribe in CEF (closed-source Google service), so
13//! this capture-and-send path is the real engine. See
14//! docs/specs/SPEC_VOICE_STT_ENGINE_2026_06_20.md and #1591.
15//!
16//! Backends (selected by the `voice:engine` setting):
17//!   * "groq" (default) — hosted whisper-large-v3-turbo; renderer sends webm.
18//!   * "whisper-local"  — offline whisper.cpp via a local `whisper-cli`
19//!                        subprocess; renderer sends 16 kHz mono WAV. Opt-in,
20//!                        configured via settings/env; needs a model file.
21
22#[cfg(windows)]
23use agentmux_common::win32::NoWindow;
24use axum::{
25    body::Bytes,
26    extract::{Query, State},
27    http::StatusCode,
28    response::{IntoResponse, Json},
29};
30use serde_json::json;
31
32use super::AppState;
33use crate::backend::vault;
34
35const GROQ_TRANSCRIBE_URL: &str = "https://api.groq.com/openai/v1/audio/transcriptions";
36const GROQ_MODEL: &str = "whisper-large-v3-turbo";
37/// The setting that holds the Groq key, or the `vault:<entry id>` that names it.
38const GROQ_SETTING: &str = "voice:groqApiKey";
39
40#[derive(serde::Deserialize)]
41pub(super) struct TranscribeQuery {
42    /// MIME type of the posted audio (e.g. "audio/webm"). Defaults to webm.
43    mime: Option<String>,
44    /// Optional BCP-47 language hint (e.g. "en"); improves accuracy + latency.
45    lang: Option<String>,
46}
47
48/// `POST /api/v1/voice/transcribe?mime=audio/webm&lang=en` — body is raw audio.
49/// → 200 `{ "text": "..." }` · 400 empty body · 501 no backend configured ·
50///   502 upstream/subprocess error.
51pub(super) async fn handle_voice_transcribe(
52    State(state): State<AppState>,
53    Query(q): Query<TranscribeQuery>,
54    body: Bytes,
55) -> impl IntoResponse {
56    if body.is_empty() {
57        return (StatusCode::BAD_REQUEST, Json(json!({ "error": "empty audio body" })))
58            .into_response();
59    }
60
61    let mime = q.mime.unwrap_or_else(|| "audio/webm".to_string());
62    let lang = q.lang.filter(|l| !l.trim().is_empty());
63    let settings = read_settings_json();
64    // Switched off, nothing is transcribed, whoever posts the audio: it goes to no engine and is dropped here.
65    if voice_off(&settings) {
66        return (StatusCode::NOT_IMPLEMENTED, Json(json!({ "error": VOICE_OFF }))).into_response();
67    }
68    let engine = resolve_engine(&settings);
69
70    let result = if engine == "whisper-local" {
71        transcribe_local_whisper(body, lang.as_deref(), &settings).await
72    } else {
73        // The key may be a Vault entry, opened here for this one request and sent nowhere else.
74        let (keyed, store) = (settings.clone(), state.identity_store.clone());
75        let key = tokio::task::spawn_blocking(move || groq_key(&keyed, Some(&store))).await.unwrap_or(GroqKey::Gone);
76        match key {
77            GroqKey::Found(key) => transcribe_groq(&key, body, &mime, lang.as_deref()).await,
78            GroqKey::Gone => Err(NotConfigured(GROQ_GONE.to_string())),
79            GroqKey::Unset => Err(NotConfigured(GROQ_NOT_CONFIGURED.to_string())),
80        }
81    };
82
83    match result {
84        Ok(text) => Json(json!({ "text": text })).into_response(),
85        Err(NotConfigured(msg)) => {
86            // Mirrors the frontend's `service-not-allowed` UX (#1603): voice
87            // isn't usable in this build/config yet.
88            log_not_configured(&msg);
89            (StatusCode::NOT_IMPLEMENTED, Json(json!({ "error": msg }))).into_response()
90        }
91        Err(Upstream(msg)) => {
92            tracing::warn!(target: "voice", "transcription failed: {msg}");
93            (StatusCode::BAD_GATEWAY, Json(json!({ "error": msg }))).into_response()
94        }
95    }
96}
97
98const VOICE_OFF: &str = "Voice input is turned off: turn it on in Settings > Recording";
99
100/// Voice input is switched off: `voice:enabled` is `false` in settings.json (Settings > Recording). Absent, it is on.
101fn voice_off(settings: &Option<serde_json::Value>) -> bool {
102    settings.as_ref().and_then(|s| s.get("voice:enabled")).and_then(serde_json::Value::as_bool) == Some(false)
103}
104
105const GROQ_NOT_CONFIGURED: &str = "Groq backend not configured — choose a Vault key for it in Settings > Recording \
106     (add one to the Vault there), or set the AGENTMUX_GROQ_API_KEY environment variable";
107const GROQ_GONE: &str = "The Vault key chosen for voice input is not there, is not an API key, or was not allowed for voice input — choose it again in \
108     Settings > Recording, or set the AGENTMUX_GROQ_API_KEY environment variable";
109
110/// `GET /api/v1/voice/status` → `{ "engine": "groq", "ready": false, "missing": "groq-key", "error": "..." }`.
111/// Whether the chosen engine has what it needs to transcribe, read from the settings and the environment
112/// alone: nothing is sent anywhere, no program is run and no model is fetched. The mic asks this before it
113/// records, so a person with no engine set up is told at the click, not after speaking into nothing.
114pub(super) async fn handle_voice_status(State(state): State<AppState>) -> impl IntoResponse {
115    let settings = read_settings_json();
116    let engine = resolve_engine(&settings);
117    let gap = setup_gap(&settings, &engine, Some(&state.identity_store));
118    if let Some(gap) = &gap {
119        log_not_configured(&gap.error);
120    }
121    Json(json!({
122        "engine": engine,
123        "ready": gap.is_none(),
124        "missing": gap.as_ref().map(|g| g.missing),
125        "error": gap.map(|g| g.error),
126    }))
127}
128
129/// What an engine still needs before it can transcribe.
130#[derive(Debug, PartialEq)]
131struct SetupGap {
132    /// `off`, `groq-key`, `whisper-cli` or `whisper-model`: what the pane's own wording is chosen by.
133    missing: &'static str,
134    /// The same sentence a transcription refused for it answers with.
135    error: String,
136}
137
138/// The first thing `engine` still needs, or `None` when a transcription can be tried. For local whisper a
139/// model that is fetched on first use is not a gap: only a model path that was given and is not there.
140fn setup_gap(settings: &Option<serde_json::Value>, engine: &str, store: Option<&crate::backend::storage::store::Store>) -> Option<SetupGap> {
141    setup_gap_with(env_groq_key(), settings, engine, store)
142}
143
144fn setup_gap_with(groq_env: Option<String>, settings: &Option<serde_json::Value>, engine: &str, store: Option<&crate::backend::storage::store::Store>) -> Option<SetupGap> {
145    let gap = |missing, error: SttError| {
146        let (NotConfigured(error) | Upstream(error)) = error;
147        Some(SetupGap { missing, error })
148    };
149    if voice_off(settings) {
150        return gap("off", NotConfigured(VOICE_OFF.to_string()));
151    }
152    if engine != "whisper-local" {
153        // The Vault entry is looked for, never opened: the status runs whenever the mic is clicked.
154        return match groq_key_state_with(groq_env, settings, store) {
155            GroqKeyState::Ready => None,
156            GroqKeyState::Gone => gap("groq-key", NotConfigured(GROQ_GONE.to_string())),
157            GroqKeyState::Unset => gap("groq-key", NotConfigured(GROQ_NOT_CONFIGURED.to_string())),
158        };
159    }
160    if let Err(e) = resolve_whisper_cli(settings) {
161        return gap("whisper-cli", e);
162    }
163    match explicit_model_path(settings) {
164        Some(Err(e)) => gap("whisper-model", e),
165        Some(Ok(_)) => None,
166        None => model_name(settings).err().and_then(|e| gap("whisper-model", e)),
167    }
168}
169
170/// One line in the log per run for a voice request that found no engine set up. The answer goes to the
171/// window, which is not in any log: without this line a report of "the mic does nothing" could not be read
172/// from the logs at all.
173fn log_not_configured(msg: &str) {
174    static LOGGED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
175    if !LOGGED.swap(true, std::sync::atomic::Ordering::Relaxed) {
176        tracing::warn!(
177            target: "voice",
178            "voice input was asked for, but its transcription engine is not set up: {msg} (logged once per run)"
179        );
180    }
181}
182
183/// Transcription failure: distinguishes "not configured" (→ 501, surfaced as the
184/// frontend's "unavailable" guidance) from a real upstream/runtime error (→ 502).
185enum SttError {
186    NotConfigured(String),
187    Upstream(String),
188}
189use SttError::{NotConfigured, Upstream};
190
191// ── Config resolution (server-side only) ────────────────────────────────────
192
193/// Read settings.json once; `None` if absent/unparseable. The file the config
194/// watcher loads, not `<config dir>/settings.json`: on a shared channel those
195/// differ (#1903).
196fn read_settings_json() -> Option<serde_json::Value> {
197    let path = crate::backend::config_watcher_fs::resolve_settings_dir().join("settings.json");
198    let content = std::fs::read_to_string(path).ok()?;
199    agentmux_common::settings_jsonc::parse_jsonc(&content)
200}
201
202fn settings_str(settings: &Option<serde_json::Value>, key: &str) -> Option<String> {
203    settings
204        .as_ref()?
205        .get(key)
206        .and_then(|x| x.as_str())
207        .map(|s| s.trim().to_string())
208        .filter(|s| !s.is_empty())
209}
210
211/// `voice:engine` — "groq" (default) or "whisper-local". Env override:
212/// `AGENTMUX_VOICE_ENGINE`.
213fn resolve_engine(settings: &Option<serde_json::Value>) -> String {
214    std::env::var("AGENTMUX_VOICE_ENGINE")
215        .ok()
216        .map(|s| s.trim().to_string())
217        .filter(|s| !s.is_empty())
218        .or_else(|| settings_str(settings, "voice:engine"))
219        .unwrap_or_else(|| "groq".to_string())
220}
221
222/// What the Groq key setting comes to.
223enum GroqKey {
224    Found(zeroize::Zeroizing<String>),
225    /// The setting names a Vault entry that is not there (or is not an API key).
226    Gone,
227    Unset,
228}
229
230/// Groq key: `AGENTMUX_GROQ_API_KEY` env (it wins, for CI and scripts), else settings.json `voice:groqApiKey`:
231/// a `vault:<entry id>` reference, read from the Vault here, or a plain key from before it was moved.
232fn groq_key(settings: &Option<serde_json::Value>, store: Option<&crate::backend::storage::store::Store>) -> GroqKey {
233    groq_key_with(env_groq_key(), settings, store)
234}
235
236fn groq_key_with(env: Option<String>, settings: &Option<serde_json::Value>, store: Option<&crate::backend::storage::store::Store>) -> GroqKey {
237    if let Some(k) = env {
238        return GroqKey::Found(zeroize::Zeroizing::new(k));
239    }
240    let Some(set) = settings_str(settings, "voice:groqApiKey") else { return GroqKey::Unset };
241    match (vault::setting_key::entry_of(&set), store) {
242        (Some(id), Some(store)) => match vault::setting_key::read(store, GROQ_SETTING, id, "AgentMux voice input", "voice input") {
243            Ok(v) => GroqKey::Found(v),
244            Err(_) => GroqKey::Gone,
245        },
246        (Some(_), None) => GroqKey::Gone,
247        (None, _) => GroqKey::Found(zeroize::Zeroizing::new(set)),
248    }
249}
250
251fn env_groq_key() -> Option<String> {
252    let k = std::env::var("AGENTMUX_GROQ_API_KEY").ok()?.trim().to_string();
253    (!k.is_empty()).then_some(k)
254}
255
256enum GroqKeyState {
257    Ready,
258    Gone,
259    Unset,
260}
261
262/// Whether there is a Groq key to use, without opening a Vault entry.
263fn groq_key_state_with(env: Option<String>, settings: &Option<serde_json::Value>, store: Option<&crate::backend::storage::store::Store>) -> GroqKeyState {
264    if env.is_some() {
265        return GroqKeyState::Ready;
266    }
267    let Some(set) = settings_str(settings, "voice:groqApiKey") else { return GroqKeyState::Unset };
268    match vault::setting_key::entry_of(&set) {
269        Some(id) if store.is_some_and(|s| vault::setting_key::present(s, GROQ_SETTING, id)) => GroqKeyState::Ready,
270        Some(_) => GroqKeyState::Gone,
271        None => GroqKeyState::Ready,
272    }
273}
274
275/// Env-first, then settings.json, for a path-valued config key.
276fn resolve_path(settings: &Option<serde_json::Value>, env: &str, key: &str) -> Option<String> {
277    std::env::var(env)
278        .ok()
279        .map(|s| s.trim().to_string())
280        .filter(|s| !s.is_empty())
281        .or_else(|| settings_str(settings, key))
282}
283
284// ── Groq backend (hosted) ───────────────────────────────────────────────────
285
286/// File extension matching the posted MIME, so Groq's content sniffing accepts
287/// the multipart `file` part.
288fn mime_ext(mime: &str) -> &'static str {
289    let m = mime.to_ascii_lowercase();
290    if m.contains("webm") {
291        "webm"
292    } else if m.contains("ogg") {
293        "ogg"
294    } else if m.contains("wav") {
295        "wav"
296    } else if m.contains("mp4") || m.contains("m4a") {
297        "m4a"
298    } else if m.contains("mpeg") || m.contains("mp3") {
299        "mp3"
300    } else if m.contains("flac") {
301        "flac"
302    } else {
303        "webm"
304    }
305}
306
307/// POST the audio to Groq's OpenAI-compatible transcription endpoint.
308async fn transcribe_groq(
309    key: &str,
310    audio: Bytes,
311    mime: &str,
312    lang: Option<&str>,
313) -> Result<String, SttError> {
314    let part = reqwest::multipart::Part::bytes(audio.to_vec())
315        .file_name(format!("audio.{}", mime_ext(mime)))
316        .mime_str(mime)
317        .map_err(|e| Upstream(format!("invalid mime: {e}")))?;
318
319    let mut form = reqwest::multipart::Form::new()
320        .text("model", GROQ_MODEL)
321        .text("response_format", "json")
322        .part("file", part);
323    if let Some(l) = lang {
324        form = form.text("language", l.to_string());
325    }
326
327    let resp = crate::http_client::client()
328        .post(GROQ_TRANSCRIBE_URL)
329        .bearer_auth(key)
330        .multipart(form)
331        .send()
332        .await
333        .map_err(|e| Upstream(format!("request failed: {e}")))?;
334
335    let status = resp.status();
336    let text_body = resp
337        .text()
338        .await
339        .map_err(|e| Upstream(format!("reading response: {e}")))?;
340
341    if !status.is_success() {
342        let snippet: String = text_body.chars().take(300).collect();
343        return Err(Upstream(format!("groq {}: {}", status.as_u16(), snippet)));
344    }
345
346    let v: serde_json::Value =
347        serde_json::from_str(&text_body).map_err(|e| Upstream(format!("parsing response: {e}")))?;
348    Ok(v.get("text")
349        .and_then(|t| t.as_str())
350        .unwrap_or_default()
351        .trim()
352        .to_string())
353}
354
355// ── Local whisper.cpp backend (offline, opt-in) ─────────────────────────────
356
357/// Transcribe via a local `whisper-cli` (whisper.cpp) subprocess. The renderer
358/// sends 16 kHz mono WAV for this engine, so we write the body to a temp `.wav`
359/// and run the CLI. Fully offline; nothing leaves the machine.
360///
361/// Config (env-first):
362///   * binary — `AGENTMUX_WHISPER_CLI` / settings `voice:whisperCliPath`
363///              (user-provided; auto-bundling is a follow-up — per-platform
364///              binary fetch is fragile)
365///   * model  — auto-downloaded on first use (default `base.en`, configurable
366///              via `voice:whisperModel`); override with an explicit
367///              `voice:whisperModelPath` / `AGENTMUX_WHISPER_MODEL`.
368///
369/// Missing binary → NotConfigured (501).
370/// Default GGML model name when none is configured. base.en (~142 MB) is a good
371/// accuracy/size balance for English; configurable via `voice:whisperModel`.
372const DEFAULT_WHISPER_MODEL: &str = "base.en";
373/// Cap the one-time model download so a stuck transfer can't wedge a request.
374const MODEL_DOWNLOAD_TIMEOUT_SECS: u64 = 600;
375
376/// Resolve the GGML model path, downloading an auto-managed model on first use.
377///
378///   * Explicit `voice:whisperModelPath` / `AGENTMUX_WHISPER_MODEL` → used as-is
379///     (no download; error if missing).
380///   * Otherwise → `<config>/whisper-models/ggml-<name>.bin`, where `name` comes
381///     from `voice:whisperModel` (default `base.en`), fetched once from the
382///     whisper.cpp model repo. A global lock serializes concurrent first-uses.
383async fn ensure_local_model(
384    settings: &Option<serde_json::Value>,
385) -> Result<std::path::PathBuf, SttError> {
386    if let Some(explicit) = explicit_model_path(settings) {
387        return explicit;
388    }
389    let name = model_name(settings)?;
390
391    let dir = crate::backend::base::get_mux_config_dir().join("whisper-models");
392    let path = dir.join(format!("ggml-{name}.bin"));
393    if path.exists() {
394        return Ok(path);
395    }
396
397    // Single global lock: serializes ALL first-use model downloads (not
398    // per-model), so one model's download blocks any other model's first-use
399    // for up to the 600s cap. Acceptable — first-use downloads are rare and
400    // models are typically not switched mid-session.
401    static DL_LOCK: std::sync::OnceLock<tokio::sync::Mutex<()>> = std::sync::OnceLock::new();
402    let _guard = DL_LOCK.get_or_init(|| tokio::sync::Mutex::new(())).lock().await;
403    if path.exists() {
404        return Ok(path); // another request finished the download while we waited
405    }
406
407    std::fs::create_dir_all(&dir).map_err(|e| Upstream(format!("create models dir: {e}")))?;
408    let url =
409        format!("https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-{name}.bin");
410    tracing::info!(target: "voice", "downloading whisper model '{name}' from {url}");
411
412    let bytes = tokio::time::timeout(
413        std::time::Duration::from_secs(MODEL_DOWNLOAD_TIMEOUT_SECS),
414        async {
415            let resp = crate::http_client::client()
416                .get(&url)
417                .send()
418                .await
419                .map_err(|e| Upstream(format!("model download request: {e}")))?;
420            if !resp.status().is_success() {
421                return Err(Upstream(format!(
422                    "model download {} for '{name}'",
423                    resp.status().as_u16()
424                )));
425            }
426            resp.bytes()
427                .await
428                .map_err(|e| Upstream(format!("model download body: {e}")))
429        },
430    )
431    .await
432    .map_err(|_| Upstream(format!("model download timed out after {MODEL_DOWNLOAD_TIMEOUT_SECS}s")))??;
433
434    // Write to a temp file then rename so a partial download never looks valid.
435    let tmp = dir.join(format!("ggml-{name}.bin.part"));
436    std::fs::write(&tmp, &bytes).map_err(|e| Upstream(format!("model write: {e}")))?;
437    std::fs::rename(&tmp, &path).map_err(|e| Upstream(format!("model finalize: {e}")))?;
438    tracing::info!(target: "voice", "whisper model '{name}' ready ({} bytes)", bytes.len());
439    Ok(path)
440}
441
442/// The model file the settings or the environment name outright, if they name one: there, or an error.
443fn explicit_model_path(
444    settings: &Option<serde_json::Value>,
445) -> Option<Result<std::path::PathBuf, SttError>> {
446    let p = resolve_path(settings, "AGENTMUX_WHISPER_MODEL", "voice:whisperModelPath")?;
447    let pb = std::path::PathBuf::from(&p);
448    Some(if pb.exists() {
449        Ok(pb)
450    } else {
451        Err(NotConfigured(format!("whisper model not found at {p}")))
452    })
453}
454
455/// The name of the auto-managed model (`voice:whisperModel`, default `base.en`).
456fn model_name(settings: &Option<serde_json::Value>) -> Result<String, SttError> {
457    let name = settings_str(settings, "voice:whisperModel")
458        .unwrap_or_else(|| DEFAULT_WHISPER_MODEL.to_string());
459    // Sanitize: model names are simple tokens — reject anything that could be a
460    // path or URL component (defends the format!-built path and URL it is put in).
461    if !name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_')) {
462        return Err(NotConfigured(format!("invalid voice:whisperModel name: {name}")));
463    }
464    Ok(name)
465}
466
467/// The `whisper-cli` program the local engine runs: its path, when one is set and is there.
468fn resolve_whisper_cli(settings: &Option<serde_json::Value>) -> Result<String, SttError> {
469    let cli = resolve_path(settings, "AGENTMUX_WHISPER_CLI", "voice:whisperCliPath").ok_or_else(
470        || {
471            NotConfigured(
472                "local whisper not configured — set voice:whisperCliPath (path to whisper-cli) \
473                 in settings.json or AGENTMUX_WHISPER_CLI"
474                    .to_string(),
475            )
476        },
477    )?;
478    if !std::path::Path::new(&cli).exists() {
479        return Err(NotConfigured(format!("whisper-cli not found at {cli}")));
480    }
481    Ok(cli)
482}
483
484async fn transcribe_local_whisper(
485    audio: Bytes,
486    lang: Option<&str>,
487    settings: &Option<serde_json::Value>,
488) -> Result<String, SttError> {
489    let cli = resolve_whisper_cli(settings)?;
490    // Resolve the model: an explicit path wins, otherwise an auto-managed model
491    // is downloaded once to the config dir (zero-config for the model file).
492    let model = ensure_local_model(settings).await?;
493
494    // Write the WAV body to a unique temp file. Timestamp alone can collide
495    // under concurrent requests (coarse Windows SystemTime granularity), so add
496    // a process-global atomic counter to guarantee uniqueness.
497    static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
498    let ts = std::time::SystemTime::now()
499        .duration_since(std::time::UNIX_EPOCH)
500        .map(|d| d.as_nanos())
501        .unwrap_or(0);
502    let seq = TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
503    let wav_path = std::env::temp_dir().join(format!("agentmux-voice-{ts}-{seq}.wav"));
504    std::fs::write(&wav_path, &audio).map_err(|e| Upstream(format!("temp write: {e}")))?;
505
506    // whisper-cli: -nt no timestamps, -np no progress prints → transcript on
507    // stdout; logs go to stderr.
508    let mut cmd = tokio::process::Command::new(&cli);
509    // Third-party transcription CLI (whisper.cpp).
510    crate::backend::pane_env::sanitize_external_command(&mut cmd);
511    cmd.arg("-m").arg(&model).arg("-f").arg(&wav_path).arg("-nt").arg("-np");
512    if let Some(l) = lang {
513        cmd.arg("-l").arg(l);
514    }
515    // Bound the run: a wedged CLI (corrupt model, pathological input) must not
516    // block the HTTP handler forever. kill_on_drop ensures the timed-out child
517    // is reaped when the timeout future drops it.
518    cmd.kill_on_drop(true);
519    // CREATE_NO_WINDOW: console-flash suppression, see crates/common/src/cli.rs
520    #[cfg(windows)]
521    {
522        cmd.no_window();
523    }
524    const WHISPER_TIMEOUT_SECS: u64 = 120;
525
526    let output = tokio::time::timeout(
527        std::time::Duration::from_secs(WHISPER_TIMEOUT_SECS),
528        cmd.output(),
529    )
530    .await;
531    let _ = std::fs::remove_file(&wav_path); // best-effort cleanup
532
533    let output = match output {
534        Err(_) => {
535            return Err(Upstream(format!(
536                "whisper-cli timed out after {WHISPER_TIMEOUT_SECS}s"
537            )))
538        }
539        Ok(r) => r.map_err(|e| Upstream(format!("spawn whisper-cli: {e}")))?,
540    };
541    if !output.status.success() {
542        let err: String = String::from_utf8_lossy(&output.stderr).chars().take(300).collect();
543        return Err(Upstream(format!(
544            "whisper-cli exited {}: {}",
545            output.status.code().unwrap_or(-1),
546            err
547        )));
548    }
549    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
550}
551
552#[cfg(test)]
553mod tests {
554    use super::*;
555
556    #[test]
557    fn mime_ext_maps_common_types() {
558        assert_eq!(mime_ext("audio/webm;codecs=opus"), "webm");
559        assert_eq!(mime_ext("audio/ogg"), "ogg");
560        assert_eq!(mime_ext("audio/wav"), "wav");
561        assert_eq!(mime_ext("audio/mp4"), "m4a");
562        assert_eq!(mime_ext("audio/mpeg"), "mp3");
563        assert_eq!(mime_ext("application/octet-stream"), "webm"); // fallback
564    }
565
566    /// These read the settings alone; a machine with the engine's own environment variables set would
567    /// answer for those instead, so such a run is skipped.
568    fn env_is_clean() -> bool {
569        ["AGENTMUX_GROQ_API_KEY", "AGENTMUX_WHISPER_CLI", "AGENTMUX_WHISPER_MODEL"]
570            .iter()
571            .all(|k| std::env::var(k).is_err())
572    }
573
574    fn vault_with_key(value: &str) -> (crate::backend::storage::store::Store, String) {
575        crate::backend::vault::seal::use_test_key();
576        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
577        store.apply_identity_schema_for_tests().unwrap();
578        let id = vault::setting_key::keep(&store, "Groq key (voice input)", "gsk_from_the_vault").unwrap();
579        // The setting is allowed to read it, as the Settings picker makes it.
580        vault::setting_key::allow(&store, &id, GROQ_SETTING, vault::PERSON).unwrap();
581        (store, id)
582    }
583
584    #[test]
585    fn a_file_that_names_an_entry_the_setting_was_not_allowed_to_read_gets_nothing() {
586        let (store, _mine) = vault_with_key("x");
587        let payment = vault::setting_key::keep(&store, "A payment key", "sk_live_payment_0123").unwrap();
588        // settings.json says so, but the Vault never allowed it: not read, and the mic says the key is gone.
589        let set = setting(&format!("vault:{payment}"));
590        assert!(matches!(groq_key_with(None, &set, Some(&store)), GroqKey::Gone));
591        assert!(matches!(groq_key_state_with(None, &set, Some(&store)), GroqKeyState::Gone));
592        let gap = setup_gap_with(None, &set, "groq", Some(&store)).expect("not allowed is a gap");
593        assert!(gap.error.contains("not there") && !gap.error.contains(&payment), "{}", gap.error);
594    }
595
596    fn setting(v: &str) -> Option<serde_json::Value> {
597        Some(serde_json::json!({ "voice:groqApiKey": v }))
598    }
599
600    #[test]
601    fn a_vault_reference_is_read_from_the_vault_and_a_gone_one_says_so() {
602        let (store, id) = vault_with_key("x");
603        let GroqKey::Found(k) = groq_key_with(None, &setting(&format!("vault:{id}")), Some(&store)) else { panic!("not found") };
604        assert_eq!(k.as_str(), "gsk_from_the_vault");
605        assert!(matches!(groq_key_state_with(None, &setting(&format!("vault:{id}")), Some(&store)), GroqKeyState::Ready));
606        assert!(matches!(groq_key_with(None, &setting("vault:nope"), Some(&store)), GroqKey::Gone));
607        assert!(matches!(groq_key_with(None, &setting(&format!("vault:{id}")), None), GroqKey::Gone), "no Vault to open");
608        let gap = setup_gap_with(None, &setting("vault:nope"), "groq", Some(&store)).expect("a dangling reference is a gap");
609        assert_eq!((gap.missing, gap.error.contains("not there")), ("groq-key", true), "{}", gap.error);
610        assert!(!gap.error.contains("nope"), "the answer names no entry: {}", gap.error);
611    }
612
613    #[test]
614    fn the_environment_variable_still_wins_over_the_setting_and_the_vault() {
615        let (store, id) = vault_with_key("x");
616        let GroqKey::Found(k) = groq_key_with(Some("gsk_from_env".into()), &setting(&format!("vault:{id}")), Some(&store)) else { panic!("not found") };
617        assert_eq!(k.as_str(), "gsk_from_env");
618        // Even a dangling reference is not a gap when the environment has the key.
619        assert!(matches!(groq_key_state_with(Some("gsk_from_env".into()), &setting("vault:nope"), Some(&store)), GroqKeyState::Ready));
620        assert!(matches!(groq_key_with(None, &None, Some(&store)), GroqKey::Unset));
621    }
622
623    #[test]
624    fn a_plain_key_left_in_the_settings_still_works_until_it_is_moved() {
625        let GroqKey::Found(k) = groq_key_with(None, &setting("gsk_plain"), None) else { panic!("not found") };
626        assert_eq!(k.as_str(), "gsk_plain");
627    }
628
629    #[test]
630    fn voice_switched_off_is_a_gap_whatever_else_is_set_up() {
631        let key = || Some("gsk_from_the_environment".to_string());
632        let off = Some(serde_json::json!({ "voice:enabled": false }));
633        assert!(voice_off(&off));
634        for engine in ["groq", "whisper-local"] {
635            let gap = setup_gap_with(key(), &off, engine, None).expect("off is a gap");
636            assert_eq!((gap.missing, gap.error.as_str()), ("off", VOICE_OFF));
637        }
638        // On, or never set, it is not: only an explicit false switches it off.
639        for on in [Some(serde_json::json!({ "voice:enabled": true })), Some(serde_json::json!({})), Some(serde_json::json!({ "voice:enabled": "false" })), None] {
640            assert!(!voice_off(&on), "{on:?}");
641            assert_eq!(setup_gap_with(key(), &on, "groq", None), None, "{on:?}");
642        }
643    }
644
645    #[test]
646    fn groq_with_no_key_is_a_gap_and_with_one_is_ready() {
647        if !env_is_clean() {
648            return;
649        }
650        let gap = setup_gap(&None, "groq", None).expect("no settings, no key");
651        assert_eq!(gap.missing, "groq-key");
652        assert!(gap.error.contains("Vault"), "{}", gap.error);
653        // A blank key is no key.
654        let blank = Some(serde_json::json!({ "voice:groqApiKey": "  " }));
655        assert_eq!(setup_gap(&blank, "groq", None).map(|g| g.missing), Some("groq-key"));
656        let keyed = Some(serde_json::json!({ "voice:groqApiKey": "gsk_x" }));
657        assert_eq!(setup_gap(&keyed, "groq", None), None);
658    }
659
660    #[test]
661    fn local_whisper_needs_its_program_and_a_named_model_file() {
662        if !env_is_clean() {
663            return;
664        }
665        assert_eq!(setup_gap(&None, "whisper-local", None).map(|g| g.missing), Some("whisper-cli"));
666        let gone = Some(serde_json::json!({ "voice:whisperCliPath": "/no/such/whisper-cli" }));
667        let gap = setup_gap(&gone, "whisper-local", None).expect("the program is not there");
668        assert_eq!(gap.missing, "whisper-cli");
669        assert!(gap.error.contains("/no/such/whisper-cli"), "{}", gap.error);
670
671        // Any file that is there stands for the program: the status does not run it.
672        let here = std::env::current_exe().unwrap().to_string_lossy().to_string();
673        // The default model is fetched on first use, so it is not a gap.
674        let ready = Some(serde_json::json!({ "voice:whisperCliPath": here }));
675        assert_eq!(setup_gap(&ready, "whisper-local", None), None);
676        let model_gone = Some(serde_json::json!({
677            "voice:whisperCliPath": here, "voice:whisperModelPath": "/no/such/model.bin",
678        }));
679        assert_eq!(setup_gap(&model_gone, "whisper-local", None).map(|g| g.missing), Some("whisper-model"));
680        let bad_name = Some(serde_json::json!({
681            "voice:whisperCliPath": here, "voice:whisperModel": "../etc/passwd",
682        }));
683        assert_eq!(setup_gap(&bad_name, "whisper-local", None).map(|g| g.missing), Some("whisper-model"));
684    }
685
686    #[test]
687    fn engine_defaults_to_groq() {
688        assert_eq!(resolve_engine(&None), "groq");
689        let s = serde_json::json!({ "voice:engine": "whisper-local" });
690        assert_eq!(resolve_engine(&Some(s)), "whisper-local");
691    }
692}