返回 CodeWhale
core_navigation_voice_host.rs
根目录 / crates / tui / src / commands / core_navigation_voice_host.rs
1 //! Host-owned voice capture and builtin shortcut transport.
2
3 use crate::commands::CommandResult;
4 use crate::commands::groups::core::navigation::voice::VOICE_INFO;
5 use crate::tui::app::{App, StatusToastKind};
6 use codewhale_engine::voice::{
7 is_available, record_audio, resolve_asr_choice, split_send_suffix, transcribe_selected,
8 };
9 use codewhale_localization::{MessageId, tr};
10 use codewhale_runtime::config::Config;
11 use std::time::Duration;
12
13 pub fn voice(app: &mut App) -> CommandResult {
14 super::core_navigation_host::dispatch(app, VOICE_INFO.name, None)
15 }
16
17 // --- Capture orchestration (UI event loop) ---------------------------------
18
19 /// What the UI should do with a finished capture.
20 #[derive(Debug, Clone, PartialEq, Eq)]
21 pub enum VoiceCaptureOutcome {
22 /// Insert the transcribed text into the composer at the cursor.
23 Insert(String),
24 /// Submit this text as a message (auto-send).
25 Send(String),
26 }
27
28 /// Status line while recording: the localized recording label, the latest
29 /// interim transcript once one exists, and how to stop. The capture is awaited
30 /// on the UI loop, so no key can end it — `record_audio` stops after a second
31 /// of silence (or `MAX_RECORD_SECS`), and the cue says exactly that.
32 fn recording_status(locale: codewhale_localization::Locale, interim: Option<&str>) -> String {
33 let label = tr(locale, MessageId::VoiceRecording);
34 let stop = tr(locale, MessageId::VoiceRecordingStopHint);
35 match interim.map(str::trim).filter(|text| !text.is_empty()) {
36 Some(text) => format!("{label} \u{2014} \u{201c}{text}\u{201d} \u{00b7} {stop}"),
37 None => format!("{label} \u{00b7} {stop}"),
38 }
39 }
40
41 /// Perform a complete record + transcribe cycle with live interim display.
42 ///
43 /// Runs in the UI event loop (see [`crate::tui::app::AppAction::VoiceCapture`]) so provider
44 /// credentials come from the live [`Config`] rather than state cached on
45 /// [`App`]. Recording happens on a blocking thread; transcription uses the
46 /// shared async HTTP client. Every failure path returns a localized message
47 /// so callers can surface it as a status line.
48 pub async fn capture_and_transcribe(
49 app: &mut App,
50 config: &Config,
51 ) -> Result<VoiceCaptureOutcome, String> {
52 let locale = app.ui_locale;
53
54 if !is_available() {
55 return Err(tr(locale, MessageId::VoiceErrNoRecorder).to_string());
56 }
57 // C01-10: the credential check follows the ASR backend that will run,
58 // not the chat provider. Local Whisper and Groq need no provider key, so
59 // resolve it lazily — the same contract as `codewhale_engine::voice::dictate_once`
60 // — and only refuse before recording when provider ASR is the backend.
61 let provider_key = || {
62 config
63 .active_route_api_key()
64 .map_err(|_| tr(locale, MessageId::VoiceErrNoAuth).to_string())
65 };
66 let (asr_kind, _asr_model) = resolve_asr_choice(config);
67 if asr_kind == "provider" {
68 provider_key()?;
69 } else if asr_kind == "deepseek"
70 && codewhale_engine::deepseek_media::resolve_deepseek_config_auth(config).is_none()
71 {
72 return Err(tr(locale, MessageId::VoiceErrNoAuth).to_string());
73 }
74 // Show the localized recording status plus the live interim in the composer.
75 let original_input = app.composer.input.clone();
76 let original_cursor = app.composer.cursor_position;
77 app.replace_progress_notice(
78 StatusToastKind::VoiceCapture,
79 recording_status(locale, None),
80 );
81
82 // Streaming interim: poll every 700ms and show partial transcript like Grok Build's
83 // VoiceEvent::Interim → VoiceState::Recording{interim}. We re-transcribe the
84 // growing buffer (local-whisper is cheap; Groq is ~300ms; provider falls back).
85 let interim_enabled = true; // always show partials — feels alive like Spark
86
87 // Spawn recorder on blocking thread with a shared buffer for interim polling.
88 let shared_buf: std::sync::Arc<parking_lot::Mutex<Vec<i16>>> =
89 std::sync::Arc::new(parking_lot::Mutex::new(Vec::new()));
90 let shared_done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
91 let shared_buf_clone = std::sync::Arc::clone(&shared_buf);
92 let shared_done_clone = std::sync::Arc::clone(&shared_done);
93 let recorder_handle = tokio::task::spawn_blocking(move || {
94 // Bridge to existing record_audio but copy into shared buffer incrementally.
95 // For now we reuse the blocking recorder and then publish; interim will
96 // poll the final buffer. A true streaming recorder (cpal/pw-record) is
97 // the next step — see grokbuild's xai-grok-voice::audio for the subprocess
98 // isolation pattern we should mirror.
99 let result = record_audio();
100 if let Some((samples, dur)) = result {
101 *shared_buf_clone.lock() = samples.clone();
102 shared_done_clone.store(true, std::sync::atomic::Ordering::SeqCst);
103 Some((samples, dur))
104 } else {
105 shared_done_clone.store(true, std::sync::atomic::Ordering::SeqCst);
106 None
107 }
108 });
109
110 // Interim polling loop — updates composer with "original + interim ▍" so text
111 // appears as you talk, just like Spark's live transcript.
112 let mut last_interim = String::new();
113 let mut ticks: u32 = 0;
114 loop {
115 tokio::time::sleep(Duration::from_millis(700)).await;
116 ticks += 1;
117 if shared_done.load(std::sync::atomic::Ordering::SeqCst) {
118 break;
119 }
120 if !interim_enabled || ticks < 2 {
121 continue; // let a little audio accumulate before first interim
122 }
123 let snapshot = { shared_buf.lock().clone() };
124 if snapshot.len() < 8000 {
125 // <0.5s of audio — not enough for meaningful ASR
126 continue;
127 }
128 // Try cheapest free ASR for interim; don't fail the whole capture on interim error.
129 let interim = transcribe_selected(config, &asr_kind, &snapshot, None)
130 .await
131 .unwrap_or_default();
132 let trimmed = interim.trim();
133 if !trimmed.is_empty() && trimmed != last_interim {
134 last_interim = trimmed.to_string();
135 // Show interim inline — preserve cursor at original position, append interim with a block cursor
136 let display = if original_input.trim().is_empty() {
137 format!("{trimmed} ▍")
138 } else {
139 format!("{} {} ▍", original_input.trim_end(), trimmed)
140 };
141 app.composer.input = display;
142 app.composer.cursor_position = original_cursor;
143 app.replace_progress_notice(
144 StatusToastKind::VoiceCapture,
145 recording_status(locale, Some(trimmed)),
146 );
147 }
148 if ticks > 40 {
149 break; // safety: ~28s max interim polling
150 }
151 }
152
153 let (samples, _duration) = recorder_handle
154 .await
155 .ok()
156 .flatten()
157 .ok_or_else(|| tr(locale, MessageId::VoiceErrTooShort).to_string())?;
158
159 // Restore composer to original before final insert (interim was preview only)
160 app.composer.input = original_input.clone();
161 app.composer.cursor_position = original_cursor;
162 app.replace_progress_notice(
163 StatusToastKind::VoiceCapture,
164 tr(locale, MessageId::VoiceProcessing).to_string(),
165 );
166
167 let text = transcribe_selected(
168 config,
169 &asr_kind,
170 &samples,
171 app.voice_control_enabled.then_some(original_input.as_str()),
172 )
173 .await
174 .map_err(|error| format!("{}: {error}", tr(locale, MessageId::VoiceErrNetwork)))?;
175
176 let clean = text.trim();
177 if app.voice_send_enabled {
178 let (remainder, wants_send) = split_send_suffix(clean);
179 if wants_send {
180 // A bare "send it" submits whatever is already in the composer.
181 let outgoing = if remainder.is_empty() {
182 let existing = app.composer.input.trim().to_string();
183 if !existing.is_empty() {
184 app.clear_input();
185 }
186 existing
187 } else {
188 remainder.to_string()
189 };
190 if outgoing.is_empty() {
191 return Err(tr(locale, MessageId::VoiceErrEmptySend).to_string());
192 }
193 return Ok(VoiceCaptureOutcome::Send(outgoing));
194 }
195 }
196 if clean.is_empty() {
197 return Err(tr(locale, MessageId::VoiceErrEmptySend).to_string());
198 }
199 Ok(VoiceCaptureOutcome::Insert(clean.to_string()))
200 }
201
202 #[cfg(test)]
203 mod tests {
204 use super::*;
205
206 #[test]
207 fn recording_status_is_localized_and_keeps_the_interim() {
208 use codewhale_localization::Locale;
209
210 for locale in [Locale::En, Locale::De, Locale::Ja] {
211 let label = tr(locale, MessageId::VoiceRecording).to_string();
212 let stop = tr(locale, MessageId::VoiceRecordingStopHint).to_string();
213 let idle = format!("{label} \u{00b7} {stop}");
214 assert_eq!(recording_status(locale, None), idle);
215 assert_eq!(recording_status(locale, Some(" ")), idle);
216
217 let with_interim = recording_status(locale, Some(" hello there "));
218 assert!(with_interim.starts_with(&label), "{with_interim}");
219 assert!(with_interim.contains("\u{201c}hello there\u{201d}"));
220 assert!(
221 with_interim.ends_with(&stop),
222 "the stop cue survives the interim: {with_interim}"
223 );
224 assert!(!with_interim.contains("\u{2325}V"), "no hardcoded key hint");
225 if locale != Locale::En {
226 assert!(!with_interim.contains("to finish"), "no English hint");
227 }
228 }
229 assert_ne!(
230 recording_status(Locale::En, None),
231 recording_status(Locale::De, None)
232 );
233 }
234 }
235
235 lines RUST