use std::collections::{HashMap, HashSet, VecDeque};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use adk_harness::VoiceSurface;
use adk_realtime::ServerEvent;
use adk_realtime::audio::{AudioChunk, AudioEncoding, AudioFormat};
use base64::Engine as _;
use futures::StreamExt;
use futures::stream::FuturesUnordered;
use tokio::sync::{Mutex as AsyncMutex, Notify, mpsc, oneshot};
use tokio::task::JoinSet;
use tokio::time::Instant;
use super::SpokenAnswer;
use super::source::Registration;
use super::spoken::{self, Spoken};
use super::visual::VisualInputs;
use super::wire::{InputSource, VisualSource, VoiceClientMessage, VoiceUpdate};
use crate::engine::{Command, CommandOutcome, SurfaceEngine};
use crate::error::{Result, SurfaceError};
use crate::model::DecisionCard;
use crate::origin::Caller;
use crate::rules::Answer;
use crate::words;
pub(crate) const PROMPT_DWELL: Duration = Duration::from_secs(1);
pub(crate) const ECHO_TAIL: Duration = Duration::from_millis(300);
const CHANNEL: usize = 256;
const UTTERANCES: usize = 8;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VoiceInput {
Audio(Vec<u8>),
Frame {
source: VisualSource,
jpeg: Vec<u8>,
},
Message(VoiceClientMessage),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VoiceOutput {
Audio(Vec<u8>),
Update(VoiceUpdate),
}
#[derive(Debug)]
pub struct VoiceLink {
pub session_id: String,
pub input_rate: u32,
pub output_rate: u32,
pub input: mpsc::Sender<VoiceInput>,
pub output: mpsc::Receiver<VoiceOutput>,
}
#[derive(Debug, Clone)]
struct Prompt {
id: String,
version: u64,
since: Instant,
}
#[derive(Debug, Clone)]
struct Utterance {
bound: Option<(String, u64)>,
echo: bool,
}
pub(crate) struct Conversation {
pub(crate) engine: SurfaceEngine,
pub(crate) surface: Arc<VoiceSurface>,
pub(crate) registration: Registration,
pub(crate) wake: Arc<Notify>,
pub(crate) speaker: Caller,
pub(crate) viewer: Caller,
pub(crate) session_id: String,
pub(crate) input_rate: u32,
pub(crate) output_rate: u32,
pub(crate) visual: VisualInputs,
pub(crate) poll: Duration,
pub(crate) own_only: bool,
#[cfg(feature = "verb-ui")]
pub(crate) verbs: Option<crate::verbs::VerbGate>,
}
pub(crate) fn start(conversation: Conversation) -> VoiceLink {
let (input, input_rx) = mpsc::channel(CHANNEL);
let (output_tx, output) = mpsc::channel(CHANNEL);
let link = VoiceLink {
session_id: conversation.session_id.clone(),
input_rate: conversation.input_rate,
output_rate: conversation.output_rate,
input,
output,
};
tokio::spawn(run(conversation, input_rx, output_tx));
link
}
type Settled = Pin<
Box<
dyn Future<
Output = (
String,
std::result::Result<Result<CommandOutcome>, oneshot::error::RecvError>,
),
> + Send,
>,
>;
type Acting = Pin<Box<dyn Future<Output = (String, VoiceUpdate)> + Send>>;
struct State {
engine: SurfaceEngine,
surface: Arc<VoiceSurface>,
speaker: Caller,
viewer: Caller,
session_id: String,
input_rate: u32,
output_rate: u32,
output: mpsc::Sender<VoiceOutput>,
visual: VisualInputs,
mic_on: bool,
speaking: bool,
playing_until: Option<Instant>,
barge_in: Option<Option<Instant>>,
prompt: Option<Prompt>,
utterances: VecDeque<Utterance>,
own_only: bool,
own: Vec<String>,
pending: HashSet<String>,
settled: FuturesUnordered<Settled>,
needs_screen: Vec<String>,
stopped: bool,
ended: bool,
resumes: JoinSet<()>,
resume_lock: Arc<AsyncMutex<()>>,
resume_again: bool,
poke: Arc<Notify>,
closing: Arc<AtomicBool>,
actions: HashMap<String, WindowedAction>,
acting: FuturesUnordered<Acting>,
#[cfg(feature = "verb-ui")]
verbs: Option<crate::verbs::VerbGate>,
}
async fn run(
conversation: Conversation,
mut input: mpsc::Receiver<VoiceInput>,
output: mpsc::Sender<VoiceOutput>,
) {
let Conversation {
engine,
surface,
registration,
wake,
speaker,
viewer,
session_id,
input_rate,
output_rate,
visual,
poll,
own_only,
#[cfg(feature = "verb-ui")]
verbs,
} = conversation;
let closing = Arc::new(AtomicBool::new(false));
let poke = Arc::new(Notify::new());
let (events_tx, mut events) = mpsc::channel(CHANNEL);
let pump = tokio::spawn(pump(surface.clone(), events_tx, poke.clone(), closing.clone()));
let mut state = State {
engine,
surface,
speaker,
viewer,
session_id,
input_rate,
output_rate,
output,
visual,
mic_on: true,
speaking: false,
playing_until: None,
barge_in: None,
prompt: None,
utterances: VecDeque::new(),
own_only,
own: Vec::new(),
pending: HashSet::new(),
settled: FuturesUnordered::new(),
needs_screen: Vec::new(),
stopped: false,
ended: false,
resumes: JoinSet::new(),
resume_lock: Arc::new(AsyncMutex::new(())),
resume_again: false,
poke,
closing,
actions: HashMap::new(),
acting: FuturesUnordered::new(),
#[cfg(feature = "verb-ui")]
verbs,
};
if state.engine.source().stopped().await.unwrap_or(false) {
state.stopped = true;
} else {
state
.send(VoiceUpdate::Ready {
session_id: state.session_id.clone(),
input_rate: state.input_rate,
output_rate: state.output_rate,
})
.await;
state.send(VoiceUpdate::Listening).await;
state.resume();
state.refresh().await;
}
let source = Arc::clone(state.engine.source());
let changes = move || -> Pin<Box<dyn Future<Output = ()> + Send>> {
let source = Arc::clone(&source);
Box::pin(async move { source.changed(poll).await })
};
let mut changed = changes();
while !state.stopped {
tokio::select! {
message = input.recv() => match message {
Some(message) => {
if state.on_input(message).await.is_break() {
break;
}
}
None => {
state.end().await;
break;
}
},
event = events.recv() => match event {
Some(Ok(event)) => state.on_event(event).await,
Some(Err(error)) => {
state
.send(VoiceUpdate::Error {
code: "surface.voice.provider".into(),
message: error.to_string(),
})
.await;
}
None => {
state.end().await;
break;
}
},
() = wake.notified() => state.resume(),
Some((id, settled)) = state.settled.next(), if !state.settled.is_empty() => {
state.on_settled(id, settled).await;
}
Some((id, update)) = state.acting.next(), if !state.acting.is_empty() => {
state.actions.remove(&id);
state.send(update).await;
}
() = &mut changed => {
changed = changes();
let holding = !state.own.is_empty();
state.refresh().await;
if holding {
state.resume();
}
}
Some(_) = state.resumes.join_next(), if !state.resumes.is_empty() => {
if std::mem::take(&mut state.resume_again) {
state.resume();
}
}
}
if state.output.is_closed() {
state.end().await;
break;
}
}
if state.stopped && !state.ended {
state
.send(VoiceUpdate::Error {
code: "surface.stopped".into(),
message: words::ALL_AGENTS_STOPPED.to_string(),
})
.await;
state.end().await;
}
drop(registration);
while state.resumes.join_next().await.is_some() {}
if let Err(error) = state.surface.resume_held_calls().await {
tracing::debug!(error = %error, "the decided calls could not be resumed at the end");
}
state.closing.store(true, Ordering::SeqCst);
state.poke.notify_one();
if let Err(error) = state.surface.runner().close().await {
tracing::debug!(error = %error, "closing the realtime session failed");
}
if tokio::time::timeout(Duration::from_secs(5), pump).await.is_err() {
tracing::warn!(session.id = %state.session_id, "the realtime session did not end in time");
}
}
async fn pump(
surface: Arc<VoiceSurface>,
events: mpsc::Sender<adk_realtime::Result<ServerEvent>>,
poke: Arc<Notify>,
closing: Arc<AtomicBool>,
) {
loop {
match surface.runner().next_event().await {
Some(event) => {
if events.send(event).await.is_err() {
return;
}
}
None => {
if closing.load(Ordering::SeqCst) {
return;
}
let _ = tokio::time::timeout(Duration::from_secs(1), poke.notified()).await;
}
}
}
}
enum Flow {
Continue,
Break,
}
#[cfg_attr(not(feature = "verb-ui"), allow(dead_code))]
struct WindowedAction {
task: tokio::task::AbortHandle,
claimed: Arc<AtomicBool>,
}
impl WindowedAction {
fn cancel(&self) -> bool {
if self.claimed.swap(true, Ordering::SeqCst) {
return false;
}
self.task.abort();
true
}
}
impl Flow {
fn is_break(&self) -> bool {
matches!(self, Self::Break)
}
}
impl State {
async fn send(&mut self, update: VoiceUpdate) {
let _ = self.output.send(VoiceOutput::Update(update)).await;
}
fn error(&self, error: &SurfaceError) -> VoiceUpdate {
VoiceUpdate::Error { code: error.code(), message: error.to_string() }
}
async fn on_input(&mut self, input: VoiceInput) -> Flow {
match input {
VoiceInput::Audio(pcm) => {
if !self.mic_on || pcm.is_empty() {
return Flow::Continue;
}
let chunk = AudioChunk::new(
pcm,
AudioFormat::new(self.input_rate, 1, 16, AudioEncoding::Pcm16),
);
if let Err(error) = self.surface.runner().send_audio_chunk(&chunk).await {
self.send(VoiceUpdate::Error {
code: "surface.voice.provider".into(),
message: error.to_string(),
})
.await;
self.end().await;
return Flow::Break;
}
self.poke.notify_one();
}
VoiceInput::Frame { source, jpeg } => {
if self.visual.offer(source, &jpeg, Instant::now()) {
let data = base64::engine::general_purpose::STANDARD.encode(&jpeg);
if let Err(error) =
self.surface.runner().send_video_frame("image/jpeg", &data).await
{
tracing::debug!(error = %error, "a frame could not be sent");
}
}
if source == VisualSource::Camera
&& let Some(cameras) = self.engine.camera_hub()
&& let Some(camera) = cameras.voice_camera()
{
cameras.ingest(&camera, jpeg, chrono::Utc::now()).await;
}
}
VoiceInput::Message(message) => match message {
VoiceClientMessage::Switch { source, on } => match source {
InputSource::Mic => self.mic_on = on,
InputSource::Camera => {
self.visual.switch(VisualSource::Camera, on);
if let Some(camera) =
self.engine.camera_hub().and_then(|cameras| cameras.voice_camera())
&& let Err(error) =
self.engine.switch_camera(&self.viewer, &camera, on).await
{
tracing::debug!(error = %error, camera.id = %camera, "the voice screen's camera switch did not reach its camera");
}
}
InputSource::Screen => self.visual.switch(VisualSource::Screen, on),
},
VoiceClientMessage::PlaybackEnded => {
let now = Instant::now();
self.playing_until = match self.barge_in.take() {
Some(since) => Some(since.map_or(now, |until| until.max(now))),
None => Some(self.playing_until.map_or(now, |until| until.max(now))),
};
}
VoiceClientMessage::End => {
self.end().await;
return Flow::Break;
}
VoiceClientMessage::Hello { .. } => {}
VoiceClientMessage::CancelAction { action_id } => {
if self.actions.get(&action_id).is_some_and(WindowedAction::cancel) {
self.actions.remove(&action_id);
}
}
},
}
Flow::Continue
}
fn over_playback(&self, now: Instant) -> bool {
self.playing_until.is_some_and(|until| now < until + ECHO_TAIL)
}
fn begin_utterance(&mut self, now: Instant) {
let bound = self
.prompt
.as_ref()
.filter(|prompt| now.saturating_duration_since(prompt.since) >= PROMPT_DWELL)
.map(|prompt| (prompt.id.clone(), prompt.version));
if self.utterances.len() == UTTERANCES {
self.utterances.pop_front();
}
self.utterances.push_back(Utterance { bound, echo: self.over_playback(now) });
}
async fn on_event(&mut self, event: ServerEvent) {
match event {
ServerEvent::SpeechStarted { .. } => {
let now = Instant::now();
if self.over_playback(now) {
self.send(VoiceUpdate::BargeIn).await;
self.barge_in = Some(None);
}
self.begin_utterance(now);
}
ServerEvent::InputTranscriptDelta { .. } if self.utterances.is_empty() => {
self.begin_utterance(Instant::now());
}
ServerEvent::InputTranscriptCompleted { transcript, .. } => {
let utterance =
self.utterances.pop_front().unwrap_or(Utterance { bound: None, echo: true });
self.send(VoiceUpdate::Heard { text: transcript.clone() }).await;
self.on_utterance(&transcript, utterance).await;
}
ServerEvent::AudioDelta { delta, .. } => {
let now = Instant::now();
let bytes_per_second = u64::from(self.output_rate.max(1)) * 2;
let length =
Duration::from_micros(delta.len() as u64 * 1_000_000 / bytes_per_second);
let from = self.playing_until.filter(|until| *until > now).unwrap_or(now);
self.playing_until = Some(from + length);
if let Some(since) = &mut self.barge_in {
let from = since.filter(|until| *until > now).unwrap_or(now);
*since = Some(from + length);
}
if !self.speaking {
self.speaking = true;
self.send(VoiceUpdate::Speaking).await;
}
let _ = self.output.send(VoiceOutput::Audio(delta)).await;
}
ServerEvent::ResponseDone { .. } if self.speaking => {
self.speaking = false;
self.send(VoiceUpdate::Listening).await;
}
ServerEvent::ToolConfirmationRequested { call_id, request } => {
if let Err(error) = self.surface.record_held(&call_id, &request).await {
tracing::warn!(error = %error, "the hold's audit record failed");
}
self.refresh().await;
}
ServerEvent::Error { error, .. } => {
self.send(VoiceUpdate::Error {
code: "surface.voice.provider".into(),
message: error.message,
})
.await;
}
_ => {}
}
}
async fn on_utterance(&mut self, transcript: &str, utterance: Utterance) {
let pending = !self.pending.is_empty() || !self.actions.is_empty();
let Some(said) = spoken::parse(transcript, pending) else {
if !utterance.echo {
self.spoken_action(transcript).await;
}
return;
};
if utterance.echo {
return;
}
match said {
Spoken::StopAll => {
let stop = Command::StopAll { reason: None };
if let Err(error) = self.engine.execute(&self.speaker, stop).await {
let update = match &error {
SurfaceError::OperatorOnly { .. } => VoiceUpdate::Error {
code: error.code(),
message: words::STOPPING_NEEDS_THE_OPERATOR.to_string(),
},
_ => self.error(&error),
};
self.send(update).await;
}
self.refresh().await;
}
Spoken::Cancel => {
let speaker = self.speaker.clone();
self.cancel_pending(&speaker).await;
self.cancel_actions();
}
Spoken::AllowOnce | Spoken::Deny => {
let answer =
if said == Spoken::AllowOnce { Answer::AllowOnce } else { Answer::Deny };
self.answer(answer, transcript, utterance.bound).await;
}
}
}
async fn answer(&mut self, answer: Answer, transcript: &str, bound: Option<(String, u64)>) {
let Some((id, version)) = bound else {
return;
};
let current = self.prompt.as_ref().map(|prompt| (prompt.id.as_str(), prompt.version));
if current != Some((id.as_str(), version)) {
self.send(VoiceUpdate::Outcome {
decision_id: id,
decided: false,
text: Some(words::CHANGED_WHILE_YOU_SPOKE.to_string()),
})
.await;
return;
}
match self.engine.decide_spoken(&self.speaker, &id, version, answer, transcript).await {
Ok(SpokenAnswer { outcome, settled }) => {
if let CommandOutcome::Pending { decision_id, cancel_until, text } = &outcome {
self.pending.insert(decision_id.clone());
if let Some(settled) = settled {
let id = decision_id.clone();
self.settled.push(Box::pin(async move { (id, settled.await) }));
}
self.send(VoiceUpdate::Pending {
decision_id: decision_id.clone(),
cancel_until: *cancel_until,
text: text.clone(),
})
.await;
} else {
self.send(outcome_update(&id, Ok(outcome))).await;
}
}
Err(error) => self.send(outcome_update(&id, Err(error))).await,
}
self.refresh().await;
}
async fn on_settled(
&mut self,
id: String,
settled: std::result::Result<Result<CommandOutcome>, oneshot::error::RecvError>,
) {
self.pending.remove(&id);
let update = match settled {
Ok(result) => outcome_update(&id, result),
Err(_) => VoiceUpdate::Outcome {
decision_id: id,
decided: false,
text: Some(words::SPOKEN_ANSWER_CANCELLED.to_string()),
},
};
self.send(update).await;
self.refresh().await;
}
async fn cancel_pending(&mut self, caller: &Caller) {
let pending: Vec<String> = self.pending.iter().cloned().collect();
for id in pending {
let cancel = Command::CancelAnswer { decision_id: id.clone() };
match self.engine.execute(caller, cancel).await {
Ok(_) => {}
Err(SurfaceError::NotFound { .. }) => {}
Err(error) => self.send(self.error(&error)).await,
}
}
}
async fn end(&mut self) {
if std::mem::replace(&mut self.ended, true) {
return;
}
let viewer = self.viewer.clone();
self.cancel_pending(&viewer).await;
self.cancel_actions();
while !self.settled.is_empty() {
match tokio::time::timeout(Duration::from_secs(1), self.settled.next()).await {
Ok(Some((id, settled))) => self.on_settled(id, settled).await,
Ok(None) | Err(_) => break,
}
}
self.send(VoiceUpdate::Ended).await;
}
fn cancel_actions(&mut self) {
self.actions.retain(|_, action| !action.cancel());
}
#[cfg(feature = "verb-ui")]
async fn spoken_action(&mut self, transcript: &str) {
use crate::verbs::spoken::{SpokenAction, parse};
use crate::verbs::{ObjectRef, VerbIntent, problem_line, words as verb_words};
let Some(gate) = self.verbs.clone() else {
return;
};
if !crate::verbs::spoken::may_be_action(transcript) {
return;
}
let Ok(items) = gate.coming_up(&self.speaker).await else {
return;
};
let (item, title, tomorrow) = match parse(transcript, &items) {
None => return,
Some(SpokenAction::Ambiguous { said, matches }) => {
let text = format!(
"{} — say the full name or use the screen",
verb_words::things_match(matches.len(), &said)
);
self.send(VoiceUpdate::ActionOutcome {
action_id: None,
done: false,
text,
heading: None,
})
.await;
return;
}
Some(SpokenAction::Snooze { item, title, tomorrow }) => (item, title, tomorrow),
};
let Some(found) = items.iter().find(|found| found.id == item) else {
return;
};
let choice = found.choices.iter().find(|choice| choice.tomorrow == tomorrow);
let Some(choice) = choice.filter(|_| found.why_not.is_none()) else {
let why = found.why_not.clone().unwrap_or_else(|| match found.ends {
Some(ends) => verb_words::ends_at(
&gate.registry().scope(self.speaker.user_id(), None).time_text(ends),
),
None => verb_words::NOT_ONE_TIME.to_string(),
});
let text = verb_words::cant_snooze(&why);
self.send(VoiceUpdate::ActionOutcome {
action_id: None,
done: false,
text,
heading: None,
})
.await;
return;
};
let heading = verb_words::move_to(&title, &choice.at_text);
let done = verb_words::moved_to(&title, &choice.at_text);
let said_done = format!("You snoozed {title} by voice");
let window = gate.voice_cancel_window();
let id = format!("act-{}", uuid::Uuid::new_v4());
let cancel_until = chrono::Utc::now()
+ chrono::Duration::from_std(window).unwrap_or_else(|_| chrono::Duration::seconds(5));
let intent = VerbIntent::new("snooze", serde_json::json!({ "to": choice.to }))
.on(ObjectRef::coming_up(&item));
let speaker = self.speaker.clone();
let said = transcript.to_string();
let (task_id, task_heading) = (id.clone(), heading.clone());
let cancelled = VoiceUpdate::ActionOutcome {
action_id: Some(id.clone()),
done: false,
text: verb_words::CANCELLED_NOTHING_CHANGED.to_string(),
heading: Some(heading.clone()),
};
let claimed = Arc::new(AtomicBool::new(false));
let mine = Arc::clone(&claimed);
let withdrawn = cancelled.clone();
let handle = tokio::spawn(async move {
tokio::time::sleep(window).await;
if mine.swap(true, Ordering::SeqCst) {
return withdrawn;
}
match gate.call_spoken(&speaker, intent, &said).await {
Ok(_) => VoiceUpdate::ActionOutcome {
action_id: Some(task_id),
done: true,
text: said_done,
heading: Some(done),
},
Err(error) => VoiceUpdate::ActionOutcome {
action_id: Some(task_id),
done: false,
text: problem_line(&error),
heading: Some(task_heading),
},
}
});
self.actions.insert(id.clone(), WindowedAction { task: handle.abort_handle(), claimed });
let ending = id.clone();
self.acting.push(Box::pin(async move {
match handle.await {
Ok(update) => (ending, update),
Err(_) => (ending, cancelled),
}
}));
let seconds = window.as_millis().div_ceil(1000) as u64;
self.send(VoiceUpdate::PendingAction {
action_id: id,
cancel_until,
text: verb_words::snoozing_in(seconds),
heading,
})
.await;
}
#[cfg(not(feature = "verb-ui"))]
async fn spoken_action(&mut self, _transcript: &str) {}
fn resume(&mut self) {
while self.resumes.try_join_next().is_some() {}
if self.resumes.len() >= 2 {
self.resume_again = true;
return;
}
let surface = Arc::clone(&self.surface);
let lock = Arc::clone(&self.resume_lock);
let output = self.output.clone();
self.resumes.spawn(async move {
let _one_at_a_time = lock.lock().await;
if let Err(error) = surface.resume_held_calls().await {
tracing::warn!(error = %error, "a decided call could not be resumed");
let _ = output
.send(VoiceOutput::Update(VoiceUpdate::Error {
code: "surface.voice.provider".into(),
message: error.to_string(),
}))
.await;
}
});
}
async fn refresh(&mut self) {
let stopped = self.engine.source().stopped().await.unwrap_or(false);
let cards = if stopped {
Vec::new()
} else {
match self.engine.decisions(&self.speaker).await {
Ok(cards) if self.own_only => {
cards.into_iter().filter(|card| card.session_id == self.session_id).collect()
}
Ok(cards) => cards,
Err(error) => {
tracing::warn!(error = %error, "the open decisions could not be read");
return;
}
}
};
self.stopped = stopped;
self.own = cards
.iter()
.filter(|card| card.session_id == self.session_id)
.map(|card| card.id.clone())
.collect();
let choice = choose(&cards, &self.own, &self.pending);
let now = Instant::now();
let changed = match (&self.prompt, choice) {
(Some(prompt), Some(card)) => prompt.id != card.id || prompt.version != card.version,
(None, None) => false,
_ => true,
};
if changed {
self.prompt = choice.map(|card| Prompt {
id: card.id.clone(),
version: card.version,
since: now,
});
self.send(VoiceUpdate::Prompted {
decision_id: choice.map(|card| card.id.clone()),
version: choice.map(|card| card.version),
})
.await;
}
let needs_screen: Vec<String> = cards
.iter()
.filter(|card| {
card.allowed.option(Answer::AllowOnce).is_none_or(|option| option.needs_expanded)
})
.map(|card| card.id.clone())
.collect();
if needs_screen != self.needs_screen {
self.needs_screen = needs_screen.clone();
self.send(VoiceUpdate::NeedsScreen { decision_ids: needs_screen }).await;
}
}
}
fn choose<'a>(
cards: &'a [DecisionCard],
own: &[String],
pending: &HashSet<String>,
) -> Option<&'a DecisionCard> {
let answerable = |card: &&DecisionCard| {
!pending.contains(&card.id)
&& card.allowed.options.iter().any(|option| {
matches!(option.answer, Answer::AllowOnce | Answer::Deny) && !option.needs_expanded
})
};
own.iter()
.rev()
.find_map(|id| cards.iter().filter(answerable).find(|card| &card.id == id))
.or_else(|| cards.iter().find(answerable))
}
fn outcome_update(id: &str, result: Result<CommandOutcome>) -> VoiceUpdate {
let (decided, text) = match result {
Ok(CommandOutcome::Answered { card }) => (card.decided.is_some(), None),
Ok(CommandOutcome::Changed { .. }) => {
(false, Some(words::CHANGED_WHILE_YOU_SPOKE.to_string()))
}
Ok(CommandOutcome::AlreadyDecided { decided, .. }) => (false, Some(decided.text)),
Ok(CommandOutcome::AnswerCancelled { .. }) => {
(false, Some(words::SPOKEN_ANSWER_CANCELLED.to_string()))
}
Ok(_) => (false, None),
Err(SurfaceError::Rule(_)) => (false, Some(words::VOICE_CANT_APPROVE_THIS.to_string())),
Err(error) => (false, Some(error.to_string())),
};
VoiceUpdate::Outcome { decision_id: id.to_string(), decided, text }
}