1use std::sync::{Arc, Mutex};
13use std::time::{Duration, Instant};
14
15use chrono::Utc;
16use tokio::sync::{Notify, mpsc};
17use tokio::task::JoinHandle;
18
19use super::app::Update;
20use super::safe::safe_line;
21use crate::engine::SurfaceEngine;
22use crate::model::DecisionCard;
23use crate::origin::Caller;
24use crate::rules::{Answer, Risk};
25use crate::voice::{VoiceClientMessage, VoiceHub, VoiceInput, VoiceOutput, VoiceUpdate};
26use crate::words;
27
28const END_WAIT: Duration = Duration::from_secs(2);
30
31pub struct TerminalVoice {
52 hub: VoiceHub,
53 model: String,
54 microphone: mpsc::Receiver<Vec<u8>>,
55 speaker: mpsc::Sender<Vec<u8>>,
56 flush: Option<Arc<Notify>>,
57}
58
59impl std::fmt::Debug for TerminalVoice {
60 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61 f.debug_struct("TerminalVoice").field("model", &self.model).finish_non_exhaustive()
62 }
63}
64
65impl TerminalVoice {
66 pub fn new(
68 hub: VoiceHub,
69 model: impl Into<String>,
70 microphone: mpsc::Receiver<Vec<u8>>,
71 speaker: mpsc::Sender<Vec<u8>>,
72 ) -> Self {
73 Self { hub, model: model.into(), microphone, speaker, flush: None }
74 }
75
76 #[must_use]
95 pub fn with_flush(mut self, flush: Arc<Notify>) -> Self {
96 self.flush = Some(flush);
97 self
98 }
99}
100
101pub(crate) type VoiceSlot = Arc<Mutex<Option<TerminalVoice>>>;
103
104#[derive(Debug, Clone, Default, PartialEq, Eq)]
106pub(crate) struct VoiceLine {
107 pub speaking: bool,
109 pub heard: Option<String>,
111 pub pending: Option<(String, Instant)>,
113 pub pending_heading: Option<String>,
115 pub prompt: Option<String>,
117 pub needs_screen: Option<String>,
119 pub outcome: Option<String>,
121 pub problem: Option<String>,
123 pub ended: bool,
125}
126
127impl VoiceLine {
128 pub(crate) fn text(&self, now: Instant) -> String {
130 if self.ended {
131 return ENDED.to_string();
132 }
133 if let Some((_, until)) = &self.pending {
134 return countdown(*until, now, self.pending_heading.as_deref());
135 }
136 let said = [&self.outcome, &self.problem, &self.prompt, &self.needs_screen];
137 if let Some(text) = said.into_iter().flatten().next() {
138 return safe_line(text);
139 }
140 if let Some(heard) = &self.heard {
141 return words::heard(&safe_line(heard));
142 }
143 if self.speaking { words::SPEAKING } else { words::LISTENING }.to_string()
144 }
145
146 pub(crate) fn news(&self, before: &VoiceLine, now: Instant) -> Vec<String> {
151 let mut news = Vec::new();
152 if self.heard != before.heard
153 && let Some(heard) = &self.heard
154 {
155 news.push(words::heard(&safe_line(heard)));
156 }
157 if let Some((id, until)) = &self.pending
158 && before.pending.as_ref().is_none_or(|(was, _)| was != id)
159 {
160 news.push(countdown(*until, now, self.pending_heading.as_deref()));
161 }
162 let needs_screen =
164 if self.needs_screen == self.prompt { &None } else { &self.needs_screen };
165 for (now_said, before_said) in [
166 (&self.outcome, &before.outcome),
167 (&self.prompt, &before.prompt),
168 (needs_screen, &before.needs_screen),
169 (&self.problem, &before.problem),
170 ] {
171 if now_said != before_said
172 && let Some(text) = now_said
173 {
174 news.push(safe_line(text));
175 }
176 }
177 if self.ended && !before.ended {
178 news.push(ENDED.to_string());
179 }
180 news
181 }
182}
183
184const ENDED: &str = "The voice conversation ended.";
186
187fn countdown(until: Instant, now: Instant, heading: Option<&str>) -> String {
189 let seconds = until.saturating_duration_since(now).as_millis().div_ceil(1000);
190 let allowing = words::allowing_in(u64::try_from(seconds).unwrap_or(u64::MAX));
191 match heading {
192 Some(heading) => format!("{allowing}: {} — c to cancel", safe_line(heading)),
193 None => format!("{allowing} — c to cancel"),
194 }
195}
196
197fn cant_approve(card: &DecisionCard) -> String {
199 let why = if card.money || card.risk == Risk::High {
200 words::voice_cant_approve(&card.heading, card.money)
201 } else {
202 words::wants_to(&card.agent.display_name, &card.heading)
204 };
205 format!("{why} {}", words::SAY_DENY_OR_DECIDE_ON_SCREEN)
206}
207
208pub(crate) struct Running {
210 input: mpsc::Sender<VoiceInput>,
211 task: JoinHandle<()>,
212}
213
214impl Running {
215 pub(crate) async fn end(self) {
218 let _ = self.input.send(VoiceInput::Message(VoiceClientMessage::End)).await;
219 drop(self.input);
220 if tokio::time::timeout(END_WAIT, self.task).await.is_err() {
221 tracing::warn!("the voice conversation did not end in time");
222 }
223 }
224}
225
226pub(crate) async fn open(
228 slot: &VoiceSlot,
229 engine: &SurfaceEngine,
230 caller: &Caller,
231 updates: &mpsc::UnboundedSender<Update>,
232) -> std::io::Result<Option<(String, Running)>> {
233 let voice = slot.lock().unwrap_or_else(|e| e.into_inner()).take();
234 match voice {
235 Some(voice) => {
236 Ok(Some(start(voice, engine.clone(), caller.clone(), updates.clone()).await?))
237 }
238 None => Ok(None),
239 }
240}
241
242pub(crate) async fn start(
245 voice: TerminalVoice,
246 engine: SurfaceEngine,
247 caller: Caller,
248 updates: mpsc::UnboundedSender<Update>,
249) -> std::io::Result<(String, Running)> {
250 let TerminalVoice { hub, model, mut microphone, speaker, flush } = voice;
251 let link = hub.open_in_thread(&caller, &model).await.map_err(std::io::Error::other)?;
252 let session = link.session_id.clone();
253 let input = link.input.clone();
254 let task = tokio::spawn(async move {
255 let mut output = link.output;
256 let sender = link.input;
257 let mut line = VoiceLine::default();
258 let mut hearing = true;
259 loop {
260 tokio::select! {
261 pcm = microphone.recv(), if hearing => match pcm {
262 Some(pcm) => {
263 if sender.send(VoiceInput::Audio(pcm)).await.is_err() {
264 break;
265 }
266 }
267 None => hearing = false,
268 },
269 out = output.recv() => match out {
270 Some(VoiceOutput::Audio(pcm)) => {
271 let _ = speaker.try_send(pcm);
273 }
274 Some(VoiceOutput::Update(VoiceUpdate::BargeIn)) => {
277 if let Some(flush) = &flush {
278 flush.notify_one();
279 let ended = VoiceInput::Message(VoiceClientMessage::PlaybackEnded);
280 if sender.send(ended).await.is_err() {
281 break;
282 }
283 }
284 }
285 Some(VoiceOutput::Update(update)) => {
286 apply(&mut line, update, &engine, &caller).await;
287 if updates.send(Update::Voice(line.clone())).is_err() {
288 break;
289 }
290 }
291 None => break,
292 },
293 }
294 }
295 });
296 Ok((session, Running { input, task }))
297}
298
299async fn apply(line: &mut VoiceLine, update: VoiceUpdate, engine: &SurfaceEngine, caller: &Caller) {
301 match update {
302 VoiceUpdate::Ready { .. } | VoiceUpdate::Listening => line.speaking = false,
303 VoiceUpdate::Speaking => line.speaking = true,
304 VoiceUpdate::Heard { text } => {
305 line.heard = Some(text);
306 line.problem = None;
307 line.outcome = None;
308 }
309 VoiceUpdate::Pending { decision_id, cancel_until, .. } => {
310 let left = (cancel_until - Utc::now()).to_std().unwrap_or_default();
311 line.pending_heading =
312 engine.decision(caller, &decision_id).await.ok().map(|card| card.heading);
313 line.pending = Some((decision_id, Instant::now() + left));
314 line.outcome = None;
315 }
316 VoiceUpdate::Outcome { decision_id, text, .. } => {
317 if line.pending.as_ref().is_some_and(|(id, _)| *id == decision_id) {
318 line.pending = None;
319 line.pending_heading = None;
320 }
321 line.outcome = text;
322 }
323 VoiceUpdate::Prompted { decision_id, .. } => {
324 let card = match decision_id {
325 Some(id) => engine.decision(caller, &id).await.ok(),
326 None => None,
327 };
328 line.prompt = card.map(|card| {
329 let allows = card
330 .allowed
331 .option(Answer::AllowOnce)
332 .is_some_and(|option| !option.needs_expanded);
333 if allows {
334 let wants = words::wants_to(&card.agent.display_name, &card.heading);
335 format!("{wants} {}", words::SAY_ALLOW_ONCE_OR_DENY)
336 } else {
337 cant_approve(&card)
338 }
339 });
340 line.outcome = None;
341 }
342 VoiceUpdate::NeedsScreen { decision_ids } => {
343 line.needs_screen = match decision_ids.last() {
344 Some(id) => engine.decision(caller, id).await.ok().map(|card| cant_approve(&card)),
345 None => None,
346 };
347 }
348 VoiceUpdate::Ended => line.ended = true,
349 VoiceUpdate::Error { message, .. } => line.problem = Some(message),
350 VoiceUpdate::BargeIn => {}
351 VoiceUpdate::PendingAction { text, heading, .. } => {
353 line.outcome = Some(format!("{heading} · {text} — say cancel to cancel"));
354 }
355 VoiceUpdate::ActionOutcome { text, heading, .. } => {
356 line.outcome = Some(match heading {
357 Some(heading) => format!("{heading} · {text}"),
358 None => text,
359 });
360 }
361 }
362}
363
364#[cfg(test)]
365mod tests {
366 use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};
367 use proptest::prelude::*;
368 use ratatui::Terminal;
369 use ratatui::backend::TestBackend;
370
371 use super::*;
372 use crate::engine::Command;
373 use crate::tui::app::{App, Effect};
374 use crate::tui::inline::Printer;
375 use crate::tui::theme::{Appearance, Theme};
376 use crate::tui::view::Renderer;
377
378 fn key(code: KeyCode) -> KeyEvent {
379 KeyEvent {
380 code,
381 modifiers: KeyModifiers::NONE,
382 kind: KeyEventKind::Press,
383 state: KeyEventState::NONE,
384 }
385 }
386
387 fn counting_down(now: Instant) -> App {
389 let mut app = App::new("adk-rust", "voice-1".into());
390 let line = VoiceLine {
391 heard: Some("allow once".into()),
392 pending: Some(("apr_1".into(), now + Duration::from_secs(5))),
393 ..VoiceLine::default()
394 };
395 app.update(Update::Voice(line), now);
396 app
397 }
398
399 fn screen(app: &App, appearance: Appearance, now: Instant) -> String {
400 let mut terminal = Terminal::new(TestBackend::new(100, 24)).unwrap();
401 let mut renderer = Renderer::new(Theme::new(appearance, true));
402 terminal
403 .draw(|frame| {
404 renderer.draw(frame, app, now);
405 })
406 .unwrap();
407 let buffer = terminal.backend().buffer().clone();
408 (0..buffer.area.height)
409 .map(|y| (0..buffer.area.width).map(|x| buffer[(x, y)].symbol()).collect::<String>())
410 .collect::<Vec<_>>()
411 .join("\n")
412 }
413
414 #[test]
416 fn the_pending_line_renders() {
417 let now = Instant::now();
418 let app = counting_down(now);
419 for appearance in [Appearance::Light, Appearance::Dark] {
420 let screen = screen(&app, appearance, now);
421 assert!(screen.contains("Allowing once in 5 seconds — c to cancel"), "{screen}");
422 }
423 }
424
425 #[test]
427 fn c_cancels_only_from_an_empty_message_box() {
428 let now = Instant::now();
429 let mut app = counting_down(now);
430 let effects = app.key(key(KeyCode::Char('c')), now);
431 assert!(matches!(
432 effects.as_slice(),
433 [Effect::Execute(Command::CancelAnswer { decision_id })] if decision_id == "apr_1"
434 ));
435 let mut app = counting_down(now);
436 app.key(key(KeyCode::Char('o')), now);
437 let effects = app.key(key(KeyCode::Char('c')), now);
438 assert!(effects.is_empty());
439 assert_eq!(app.composer.text, "oc");
440 let mut app = App::new("adk-rust", "voice-1".into());
442 app.update(Update::Voice(VoiceLine::default()), now);
443 assert!(app.key(key(KeyCode::Char('c')), now).is_empty());
444 assert_eq!(app.composer.text, "c");
445 }
446
447 #[test]
448 fn esc_never_decides_or_cancels() {
449 let now = Instant::now();
450 let mut app = counting_down(now);
451 assert!(app.key(key(KeyCode::Esc), now).is_empty());
452 assert!(app.voice.as_ref().is_some_and(|voice| voice.pending.is_some()));
453 }
454
455 proptest! {
456 #![proptest_config(ProptestConfig::with_cases(128))]
457
458 #[test]
460 fn keys_never_decide_from_the_voice_line(keys in prop::collection::vec(prop_oneof![
461 Just(KeyCode::Char('c')), Just(KeyCode::Char('y')), Just(KeyCode::Char('n')),
462 Just(KeyCode::Char('a')), Just(KeyCode::Char('e')), Just(KeyCode::Esc),
463 Just(KeyCode::Enter), Just(KeyCode::Backspace),
464 ], 1..20)) {
465 let now = Instant::now();
466 let mut app = counting_down(now);
467 for (step, code) in keys.into_iter().enumerate() {
468 let at = now + Duration::from_millis(step as u64 * 50);
469 for effect in app.key(key(code), at) {
470 let decides = matches!(effect, Effect::Execute(Command::Decide { .. }));
471 prop_assert!(!decides, "a key decided from the voice line");
472 }
473 }
474 }
475 }
476
477 #[test]
481 fn the_inline_terminal_prints_each_piece_of_news_once() {
482 fn step(printer: &mut Printer<Vec<u8>>, app: &mut App, line: &VoiceLine, at: Instant) {
483 app.update(Update::Voice(line.clone()), at);
484 printer.sync(app, at).unwrap();
485 }
486 let now = Instant::now();
487 let mut printer =
488 Printer::new(Vec::new(), Theme::new(Appearance::Light, false), false, false)
489 .with_width(90);
490 let mut app = App::new("adk-rust", "voice-1".into());
491 let mut line = VoiceLine::default();
492 step(&mut printer, &mut app, &line, now);
493 line.speaking = true;
494 step(&mut printer, &mut app, &line, now);
495 line.speaking = false;
496 line.heard = Some("allow\u{1b}[2J once".into());
497 step(&mut printer, &mut app, &line, now);
498 line.pending = Some(("apr_1".into(), now + Duration::from_secs(5)));
499 line.pending_heading = Some("Send the invoice".into());
500 step(&mut printer, &mut app, &line, now);
501 step(&mut printer, &mut app, &line, now + Duration::from_secs(2));
502 line.pending = None;
503 line.outcome = Some(words::CHANGED_WHILE_YOU_SPOKE.into());
504 step(&mut printer, &mut app, &line, now + Duration::from_secs(5));
505 let release = "\"Publish the release\" is high risk, so voice can't approve it. Say \"deny\", or decide on screen.";
506 line.outcome = None;
507 line.prompt = Some(release.into());
508 line.needs_screen = Some(release.into());
509 step(&mut printer, &mut app, &line, now + Duration::from_secs(6));
510 line.ended = true;
511 step(&mut printer, &mut app, &line, now + Duration::from_secs(7));
512 let out = String::from_utf8(printer.into_inner()).unwrap();
513 let printed: Vec<&str> = out.lines().filter(|line| !line.trim().is_empty()).collect();
514 assert_eq!(
515 printed,
516 [
517 "Heard \"allow\\u{1b}[2J once\"",
518 "Allowing once in 5 seconds: Send the invoice — c to cancel",
519 words::CHANGED_WHILE_YOU_SPOKE,
520 release,
521 "The voice conversation ended.",
522 ]
523 );
524 }
525
526 #[test]
529 fn the_line_names_the_prompted_decision() {
530 let now = Instant::now();
531 let mut line = VoiceLine {
532 heard: Some("hello".into()),
533 prompt: Some(
534 "Finance wants to send email to [client email]. Say \"allow once\" or \"deny\"."
535 .into(),
536 ),
537 ..VoiceLine::default()
538 };
539 assert_eq!(
540 line.text(now),
541 "Finance wants to send email to [client email]. Say \"allow once\" or \"deny\"."
542 );
543 line.pending = Some(("apr_1".into(), now + Duration::from_secs(5)));
544 line.pending_heading = Some("Send email to [client email]".into());
545 assert_eq!(
546 line.text(now),
547 "Allowing once in 5 seconds: Send email to [client email] — c to cancel"
548 );
549 }
550
551 #[test]
553 fn the_line_says_how_a_spoken_answer_ended() {
554 let now = Instant::now();
555 let mut line = VoiceLine {
556 heard: Some("allow once".into()),
557 prompt: Some("Finance wants to send email. Say \"allow once\" or \"deny\".".into()),
558 ..VoiceLine::default()
559 };
560 line.outcome = Some(words::VOICE_CANT_APPROVE_THIS.into());
561 assert_eq!(line.text(now), words::VOICE_CANT_APPROVE_THIS);
562 let before = VoiceLine { outcome: None, ..line.clone() };
563 assert_eq!(line.news(&before, now), [words::VOICE_CANT_APPROVE_THIS]);
564 }
565
566 #[test]
569 fn a_call_voice_cant_approve_says_why() {
570 let mut money = crate::tui::tests::card("apr_1", "pay_invoice", serde_json::json!({}));
571 money.heading = "Pay the invoice".into();
572 money.risk = Risk::Low;
573 money.money = true;
574 assert_eq!(
575 cant_approve(&money),
576 "\"Pay the invoice\" spends money, so voice can't approve it. Say \"deny\", or decide on screen."
577 );
578 let mut high = money.clone();
579 high.money = false;
580 high.risk = Risk::High;
581 assert_eq!(
582 cant_approve(&high),
583 "\"Pay the invoice\" is high risk, so voice can't approve it. Say \"deny\", or decide on screen."
584 );
585 let mut cut = high.clone();
586 cut.risk = Risk::Low;
587 assert_eq!(
588 cant_approve(&cut),
589 "Finance wants to pay the invoice. Say \"deny\", or decide on screen."
590 );
591 }
592
593 #[test]
594 fn the_line_says_one_thing_and_escapes_what_was_said() {
595 let now = Instant::now();
596 let mut line = VoiceLine::default();
597 assert_eq!(line.text(now), "Listening");
598 line.heard = Some("allow\u{1b}[2J once".into());
599 assert_eq!(line.text(now), "Heard \"allow\\u{1b}[2J once\"");
600 line.needs_screen = Some("\"Publish\u{1b}[2J\" is high risk".into());
601 assert_eq!(line.text(now), "\"Publish\\u{1b}[2J\" is high risk");
602 line.pending = Some(("apr_1".into(), now + Duration::from_millis(4_200)));
603 assert_eq!(line.text(now), "Allowing once in 5 seconds — c to cancel");
604 }
605}