Skip to main content

adk_surface/voice/
session.rs

1//! One voice conversation (spec 3.3 §5.6): the realtime session of the harness, the prompted
2//! decision, spoken answers through the engine, and the camera and screen gate.
3
4use std::collections::{HashMap, HashSet, VecDeque};
5use std::future::Future;
6use std::pin::Pin;
7use std::sync::Arc;
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::time::Duration;
10
11use adk_harness::VoiceSurface;
12use adk_realtime::ServerEvent;
13use adk_realtime::audio::{AudioChunk, AudioEncoding, AudioFormat};
14use base64::Engine as _;
15use futures::StreamExt;
16use futures::stream::FuturesUnordered;
17use tokio::sync::{Mutex as AsyncMutex, Notify, mpsc, oneshot};
18use tokio::task::JoinSet;
19use tokio::time::Instant;
20
21use super::SpokenAnswer;
22use super::source::Registration;
23use super::spoken::{self, Spoken};
24use super::visual::VisualInputs;
25use super::wire::{InputSource, VisualSource, VoiceClientMessage, VoiceUpdate};
26use crate::engine::{Command, CommandOutcome, SurfaceEngine};
27use crate::error::{Result, SurfaceError};
28use crate::model::DecisionCard;
29use crate::origin::Caller;
30use crate::rules::Answer;
31use crate::words;
32
33/// How long a prompt is on screen before speech counts as an answer to it (spec 3.3 §5.6).
34pub(crate) const PROMPT_DWELL: Duration = Duration::from_secs(1);
35
36/// How long after the model's audio ends speech is still taken for its echo (spec 3.3 §5.6).
37pub(crate) const ECHO_TAIL: Duration = Duration::from_millis(300);
38
39/// How many messages wait between the conversation and its transport.
40const CHANNEL: usize = 256;
41
42/// How many utterances may wait for their transcripts; an older one is dropped.
43const UTTERANCES: usize = 8;
44
45/// What a transport sends a voice conversation (spec 3.3 §5.6).
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum VoiceInput {
48    /// PCM16 mono at the model's input rate, from the microphone.
49    Audio(Vec<u8>),
50    /// A camera or screen JPEG.
51    Frame {
52        /// Which.
53        source: VisualSource,
54        /// The JPEG.
55        jpeg: Vec<u8>,
56    },
57    /// A text message of the view.
58    Message(VoiceClientMessage),
59}
60
61/// What a voice conversation sends its transport (spec 3.3 §5.6).
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub enum VoiceOutput {
64    /// PCM16 mono at the model's output rate, to play.
65    Audio(Vec<u8>),
66    /// Transient voice state.
67    Update(VoiceUpdate),
68}
69
70/// An open voice conversation, from its transport's side (spec 3.3 §5.6): send it
71/// [`VoiceInput`]s, read its [`VoiceOutput`]s. Dropping `input` ends the conversation, as
72/// [`VoiceClientMessage::End`] does.
73#[derive(Debug)]
74pub struct VoiceLink {
75    /// The conversation's own session.
76    pub session_id: String,
77    /// The sample rate of the audio to send.
78    pub input_rate: u32,
79    /// The sample rate of the audio to play.
80    pub output_rate: u32,
81    /// Where the transport sends.
82    pub input: mpsc::Sender<VoiceInput>,
83    /// What the transport receives.
84    pub output: mpsc::Receiver<VoiceOutput>,
85}
86
87/// The prompted decision: what a spoken answer applies to.
88#[derive(Debug, Clone)]
89struct Prompt {
90    id: String,
91    version: u64,
92    since: Instant,
93}
94
95/// An utterance from its start: the decision it was bound to, and whether it began over the
96/// model's audio.
97#[derive(Debug, Clone)]
98struct Utterance {
99    bound: Option<(String, u64)>,
100    echo: bool,
101}
102
103/// What [`run`] needs from the hub.
104pub(crate) struct Conversation {
105    pub(crate) engine: SurfaceEngine,
106    pub(crate) surface: Arc<VoiceSurface>,
107    pub(crate) registration: Registration,
108    pub(crate) wake: Arc<Notify>,
109    /// The person, speaking: surface voice, origin voice.
110    pub(crate) speaker: Caller,
111    /// The person, at the view's controls: End.
112    pub(crate) viewer: Caller,
113    pub(crate) session_id: String,
114    pub(crate) input_rate: u32,
115    pub(crate) output_rate: u32,
116    pub(crate) visual: VisualInputs,
117    pub(crate) poll: Duration,
118    /// A spoken answer applies only to the conversation's own decisions: the terminal's
119    /// thread shows those, and no other, in full (spec 3.3 §7.1).
120    pub(crate) own_only: bool,
121    /// The person's screen actions, said aloud: "snooze news digest" (spec 3.3 §5.6).
122    #[cfg(feature = "verb-ui")]
123    pub(crate) verbs: Option<crate::verbs::VerbGate>,
124}
125
126/// Opens the link and runs the conversation on its own task.
127pub(crate) fn start(conversation: Conversation) -> VoiceLink {
128    let (input, input_rx) = mpsc::channel(CHANNEL);
129    let (output_tx, output) = mpsc::channel(CHANNEL);
130    let link = VoiceLink {
131        session_id: conversation.session_id.clone(),
132        input_rate: conversation.input_rate,
133        output_rate: conversation.output_rate,
134        input,
135        output,
136    };
137    tokio::spawn(run(conversation, input_rx, output_tx));
138    link
139}
140
141type Settled = Pin<
142    Box<
143        dyn Future<
144                Output = (
145                    String,
146                    std::result::Result<Result<CommandOutcome>, oneshot::error::RecvError>,
147                ),
148            > + Send,
149    >,
150>;
151
152/// A spoken screen action waiting out its cancel window, then run: its id and how it ended.
153type Acting = Pin<Box<dyn Future<Output = (String, VoiceUpdate)> + Send>>;
154
155struct State {
156    engine: SurfaceEngine,
157    surface: Arc<VoiceSurface>,
158    speaker: Caller,
159    viewer: Caller,
160    session_id: String,
161    input_rate: u32,
162    output_rate: u32,
163    output: mpsc::Sender<VoiceOutput>,
164    visual: VisualInputs,
165    mic_on: bool,
166    speaking: bool,
167    /// Until when the model's audio plays, as far as the server can tell.
168    playing_until: Option<Instant>,
169    /// A barge-in the transport has not yet answered with `playbackEnded`, and until when
170    /// the audio sent since it plays: until the transport flushed, everything sent before
171    /// the barge-in may still play.
172    barge_in: Option<Option<Instant>>,
173    prompt: Option<Prompt>,
174    /// Utterances whose transcript has not arrived, oldest first: a provider that
175    /// transcribes after the next utterance started completes them in order.
176    utterances: VecDeque<Utterance>,
177    own_only: bool,
178    /// The open decisions of this conversation's own session — the calls it held — oldest
179    /// first.
180    own: Vec<String>,
181    /// Spoken answers in their cancel window.
182    pending: HashSet<String>,
183    settled: FuturesUnordered<Settled>,
184    needs_screen: Vec<String>,
185    stopped: bool,
186    ended: bool,
187    /// Resumes of the conversation's held calls, one at a time.
188    resumes: JoinSet<()>,
189    resume_lock: Arc<AsyncMutex<()>>,
190    /// A resume was asked for while two were in flight: one more follows the next to end.
191    resume_again: bool,
192    /// Tells the provider pump a client action may have made the provider speak again.
193    poke: Arc<Notify>,
194    closing: Arc<AtomicBool>,
195    /// Spoken screen actions in their cancel window, by id.
196    actions: HashMap<String, WindowedAction>,
197    /// The same actions, ending.
198    acting: FuturesUnordered<Acting>,
199    #[cfg(feature = "verb-ui")]
200    verbs: Option<crate::verbs::VerbGate>,
201}
202
203async fn run(
204    conversation: Conversation,
205    mut input: mpsc::Receiver<VoiceInput>,
206    output: mpsc::Sender<VoiceOutput>,
207) {
208    let Conversation {
209        engine,
210        surface,
211        registration,
212        wake,
213        speaker,
214        viewer,
215        session_id,
216        input_rate,
217        output_rate,
218        visual,
219        poll,
220        own_only,
221        #[cfg(feature = "verb-ui")]
222        verbs,
223    } = conversation;
224    let closing = Arc::new(AtomicBool::new(false));
225    let poke = Arc::new(Notify::new());
226    let (events_tx, mut events) = mpsc::channel(CHANNEL);
227    // `next_event` observes, screens and persists after it reads the provider, so it is never
228    // dropped half way: it runs on its own task and forwards what it reads.
229    let pump = tokio::spawn(pump(surface.clone(), events_tx, poke.clone(), closing.clone()));
230    let mut state = State {
231        engine,
232        surface,
233        speaker,
234        viewer,
235        session_id,
236        input_rate,
237        output_rate,
238        output,
239        visual,
240        mic_on: true,
241        speaking: false,
242        playing_until: None,
243        barge_in: None,
244        prompt: None,
245        utterances: VecDeque::new(),
246        own_only,
247        own: Vec::new(),
248        pending: HashSet::new(),
249        settled: FuturesUnordered::new(),
250        needs_screen: Vec::new(),
251        stopped: false,
252        ended: false,
253        resumes: JoinSet::new(),
254        resume_lock: Arc::new(AsyncMutex::new(())),
255        resume_again: false,
256        poke,
257        closing,
258        actions: HashMap::new(),
259        acting: FuturesUnordered::new(),
260        #[cfg(feature = "verb-ui")]
261        verbs,
262    };
263    // While every agent is stopped no conversation runs (spec 3.3 S-I10).
264    if state.engine.source().stopped().await.unwrap_or(false) {
265        state.stopped = true;
266    } else {
267        state
268            .send(VoiceUpdate::Ready {
269                session_id: state.session_id.clone(),
270                input_rate: state.input_rate,
271                output_rate: state.output_rate,
272            })
273            .await;
274        state.send(VoiceUpdate::Listening).await;
275        // A call an earlier conversation on this session held may have been decided since.
276        state.resume();
277        state.refresh().await;
278    }
279
280    let source = Arc::clone(state.engine.source());
281    let changes = move || -> Pin<Box<dyn Future<Output = ()> + Send>> {
282        let source = Arc::clone(&source);
283        Box::pin(async move { source.changed(poll).await })
284    };
285    let mut changed = changes();
286    while !state.stopped {
287        tokio::select! {
288            message = input.recv() => match message {
289                Some(message) => {
290                    if state.on_input(message).await.is_break() {
291                        break;
292                    }
293                }
294                None => {
295                    state.end().await;
296                    break;
297                }
298            },
299            event = events.recv() => match event {
300                Some(Ok(event)) => state.on_event(event).await,
301                Some(Err(error)) => {
302                    state
303                        .send(VoiceUpdate::Error {
304                            code: "surface.voice.provider".into(),
305                            message: error.to_string(),
306                        })
307                        .await;
308                }
309                None => {
310                    state.end().await;
311                    break;
312                }
313            },
314            () = wake.notified() => state.resume(),
315            Some((id, settled)) = state.settled.next(), if !state.settled.is_empty() => {
316                state.on_settled(id, settled).await;
317            }
318            Some((id, update)) = state.acting.next(), if !state.acting.is_empty() => {
319                state.actions.remove(&id);
320                state.send(update).await;
321            }
322            () = &mut changed => {
323                changed = changes();
324                // A decision made outside the engine — in Telegram through the kernel, or with
325                // `adk-rust approvals` — reaches no one: look for it while a call is held.
326                let holding = !state.own.is_empty();
327                state.refresh().await;
328                if holding {
329                    state.resume();
330                }
331            }
332            Some(_) = state.resumes.join_next(), if !state.resumes.is_empty() => {
333                if std::mem::take(&mut state.resume_again) {
334                    state.resume();
335                }
336            }
337        }
338        if state.output.is_closed() {
339            state.end().await;
340            break;
341        }
342    }
343    // Stop all ends the conversation: the model stops listening, answering and spending
344    // (spec 3.3 S-I10, §12 phase 5).
345    if state.stopped && !state.ended {
346        state
347            .send(VoiceUpdate::Error {
348                code: "surface.stopped".into(),
349                message: words::ALL_AGENTS_STOPPED.to_string(),
350            })
351            .await;
352        state.end().await;
353    }
354    // A decision recorded from here on goes to the wrapped source. One recorded while the
355    // conversation was ending woke a signal no one listens to any more: resume it here.
356    drop(registration);
357    while state.resumes.join_next().await.is_some() {}
358    if let Err(error) = state.surface.resume_held_calls().await {
359        tracing::debug!(error = %error, "the decided calls could not be resumed at the end");
360    }
361    state.closing.store(true, Ordering::SeqCst);
362    state.poke.notify_one();
363    if let Err(error) = state.surface.runner().close().await {
364        tracing::debug!(error = %error, "closing the realtime session failed");
365    }
366    if tokio::time::timeout(Duration::from_secs(5), pump).await.is_err() {
367        tracing::warn!(session.id = %state.session_id, "the realtime session did not end in time");
368    }
369}
370
371/// Reads the provider until the conversation closes.
372async fn pump(
373    surface: Arc<VoiceSurface>,
374    events: mpsc::Sender<adk_realtime::Result<ServerEvent>>,
375    poke: Arc<Notify>,
376    closing: Arc<AtomicBool>,
377) {
378    loop {
379        match surface.runner().next_event().await {
380            Some(event) => {
381                if events.send(event).await.is_err() {
382                    return;
383                }
384            }
385            // A provider with nothing to say until the person acts again, such as a scripted
386            // one, reports the end of its events; a closed one keeps doing so.
387            None => {
388                if closing.load(Ordering::SeqCst) {
389                    return;
390                }
391                let _ = tokio::time::timeout(Duration::from_secs(1), poke.notified()).await;
392            }
393        }
394    }
395}
396
397enum Flow {
398    Continue,
399    Break,
400}
401
402/// A spoken screen action waiting out its cancel window (spec 3.3 §5.6).
403// Only `verb-ui` takes spoken screen actions; without it the map stays empty.
404#[cfg_attr(not(feature = "verb-ui"), allow(dead_code))]
405struct WindowedAction {
406    /// The task that takes it.
407    task: tokio::task::AbortHandle,
408    /// Claimed by whichever comes first: a cancel, or the task once the window ended. A task
409    /// that claimed it is taking the action and runs to its end, so a late cancel never
410    /// leaves it half done.
411    claimed: Arc<AtomicBool>,
412}
413
414impl WindowedAction {
415    /// Withdraws the action unless it is already being taken; returns whether it was.
416    fn cancel(&self) -> bool {
417        if self.claimed.swap(true, Ordering::SeqCst) {
418            return false;
419        }
420        self.task.abort();
421        true
422    }
423}
424
425impl Flow {
426    fn is_break(&self) -> bool {
427        matches!(self, Self::Break)
428    }
429}
430
431impl State {
432    async fn send(&mut self, update: VoiceUpdate) {
433        let _ = self.output.send(VoiceOutput::Update(update)).await;
434    }
435
436    fn error(&self, error: &SurfaceError) -> VoiceUpdate {
437        VoiceUpdate::Error { code: error.code(), message: error.to_string() }
438    }
439
440    async fn on_input(&mut self, input: VoiceInput) -> Flow {
441        match input {
442            VoiceInput::Audio(pcm) => {
443                if !self.mic_on || pcm.is_empty() {
444                    return Flow::Continue;
445                }
446                let chunk = AudioChunk::new(
447                    pcm,
448                    AudioFormat::new(self.input_rate, 1, 16, AudioEncoding::Pcm16),
449                );
450                if let Err(error) = self.surface.runner().send_audio_chunk(&chunk).await {
451                    self.send(VoiceUpdate::Error {
452                        code: "surface.voice.provider".into(),
453                        message: error.to_string(),
454                    })
455                    .await;
456                    self.end().await;
457                    return Flow::Break;
458                }
459                self.poke.notify_one();
460            }
461            VoiceInput::Frame { source, jpeg } => {
462                if self.visual.offer(source, &jpeg, Instant::now()) {
463                    let data = base64::engine::general_purpose::STANDARD.encode(&jpeg);
464                    if let Err(error) =
465                        self.surface.runner().send_video_frame("image/jpeg", &data).await
466                    {
467                        tracing::debug!(error = %error, "a frame could not be sent");
468                    }
469                }
470                // The voice screen's camera is also a camera of the live camera surface (spec
471                // 3.7 §7.13 `SurfaceCameraSource`): its frames pass that camera's gate too.
472                if source == VisualSource::Camera
473                    && let Some(cameras) = self.engine.camera_hub()
474                    && let Some(camera) = cameras.voice_camera()
475                {
476                    cameras.ingest(&camera, jpeg, chrono::Utc::now()).await;
477                }
478            }
479            VoiceInput::Message(message) => match message {
480                VoiceClientMessage::Switch { source, on } => match source {
481                    InputSource::Mic => self.mic_on = on,
482                    InputSource::Camera => {
483                        self.visual.switch(VisualSource::Camera, on);
484                        // The live camera surface's switch for the same camera follows, recorded
485                        // as the person's.
486                        if let Some(camera) =
487                            self.engine.camera_hub().and_then(|cameras| cameras.voice_camera())
488                            && let Err(error) =
489                                self.engine.switch_camera(&self.viewer, &camera, on).await
490                        {
491                            tracing::debug!(error = %error, camera.id = %camera, "the voice screen's camera switch did not reach its camera");
492                        }
493                    }
494                    InputSource::Screen => self.visual.switch(VisualSource::Screen, on),
495                },
496                VoiceClientMessage::PlaybackEnded => {
497                    let now = Instant::now();
498                    self.playing_until = match self.barge_in.take() {
499                        // The transport flushed what the barge-in interrupted: only audio
500                        // sent since still plays.
501                        Some(since) => Some(since.map_or(now, |until| until.max(now))),
502                        None => Some(self.playing_until.map_or(now, |until| until.max(now))),
503                    };
504                }
505                VoiceClientMessage::End => {
506                    self.end().await;
507                    return Flow::Break;
508                }
509                // Only the first message of a socket is a hello; a later one is ignored.
510                VoiceClientMessage::Hello { .. } => {}
511                VoiceClientMessage::CancelAction { action_id } => {
512                    // Too late once it is being taken: its outcome follows.
513                    if self.actions.get(&action_id).is_some_and(WindowedAction::cancel) {
514                        self.actions.remove(&action_id);
515                    }
516                }
517            },
518        }
519        Flow::Continue
520    }
521
522    /// Whether speech starting now begins over the model's audio.
523    fn over_playback(&self, now: Instant) -> bool {
524        self.playing_until.is_some_and(|until| now < until + ECHO_TAIL)
525    }
526
527    /// Starts an utterance, bound to the decision prompted for at least [`PROMPT_DWELL`].
528    fn begin_utterance(&mut self, now: Instant) {
529        let bound = self
530            .prompt
531            .as_ref()
532            .filter(|prompt| now.saturating_duration_since(prompt.since) >= PROMPT_DWELL)
533            .map(|prompt| (prompt.id.clone(), prompt.version));
534        if self.utterances.len() == UTTERANCES {
535            self.utterances.pop_front();
536        }
537        self.utterances.push_back(Utterance { bound, echo: self.over_playback(now) });
538    }
539
540    async fn on_event(&mut self, event: ServerEvent) {
541        match event {
542            ServerEvent::SpeechStarted { .. } => {
543                let now = Instant::now();
544                if self.over_playback(now) {
545                    self.send(VoiceUpdate::BargeIn).await;
546                    self.barge_in = Some(None);
547                }
548                self.begin_utterance(now);
549            }
550            // A provider that reports no speech onset starts the utterance with its transcript.
551            ServerEvent::InputTranscriptDelta { .. } if self.utterances.is_empty() => {
552                self.begin_utterance(Instant::now());
553            }
554            ServerEvent::InputTranscriptCompleted { transcript, .. } => {
555                let utterance =
556                    self.utterances.pop_front().unwrap_or(Utterance { bound: None, echo: true });
557                self.send(VoiceUpdate::Heard { text: transcript.clone() }).await;
558                self.on_utterance(&transcript, utterance).await;
559            }
560            ServerEvent::AudioDelta { delta, .. } => {
561                let now = Instant::now();
562                let bytes_per_second = u64::from(self.output_rate.max(1)) * 2;
563                let length =
564                    Duration::from_micros(delta.len() as u64 * 1_000_000 / bytes_per_second);
565                let from = self.playing_until.filter(|until| *until > now).unwrap_or(now);
566                self.playing_until = Some(from + length);
567                if let Some(since) = &mut self.barge_in {
568                    let from = since.filter(|until| *until > now).unwrap_or(now);
569                    *since = Some(from + length);
570                }
571                if !self.speaking {
572                    self.speaking = true;
573                    self.send(VoiceUpdate::Speaking).await;
574                }
575                let _ = self.output.send(VoiceOutput::Audio(delta)).await;
576            }
577            ServerEvent::ResponseDone { .. } if self.speaking => {
578                self.speaking = false;
579                self.send(VoiceUpdate::Listening).await;
580            }
581            // The conversation's own call was just held: it is offered first.
582            ServerEvent::ToolConfirmationRequested { call_id, request } => {
583                if let Err(error) = self.surface.record_held(&call_id, &request).await {
584                    tracing::warn!(error = %error, "the hold's audit record failed");
585                }
586                self.refresh().await;
587            }
588            ServerEvent::Error { error, .. } => {
589                self.send(VoiceUpdate::Error {
590                    code: "surface.voice.provider".into(),
591                    message: error.message,
592                })
593                .await;
594            }
595            _ => {}
596        }
597    }
598
599    async fn on_utterance(&mut self, transcript: &str, utterance: Utterance) {
600        let pending = !self.pending.is_empty() || !self.actions.is_empty();
601        let Some(said) = spoken::parse(transcript, pending) else {
602            // Not one of the engine's answers: perhaps a screen action, never from the model's
603            // own audio (spec 3.3 §5.6).
604            if !utterance.echo {
605                self.spoken_action(transcript).await;
606            }
607            return;
608        };
609        // The model's own words, played back into the microphone, never answer.
610        if utterance.echo {
611            return;
612        }
613        match said {
614            Spoken::StopAll => {
615                let stop = Command::StopAll { reason: None };
616                if let Err(error) = self.engine.execute(&self.speaker, stop).await {
617                    let update = match &error {
618                        SurfaceError::OperatorOnly { .. } => VoiceUpdate::Error {
619                            code: error.code(),
620                            message: words::STOPPING_NEEDS_THE_OPERATOR.to_string(),
621                        },
622                        _ => self.error(&error),
623                    };
624                    self.send(update).await;
625                }
626                self.refresh().await;
627            }
628            Spoken::Cancel => {
629                let speaker = self.speaker.clone();
630                self.cancel_pending(&speaker).await;
631                self.cancel_actions();
632            }
633            Spoken::AllowOnce | Spoken::Deny => {
634                let answer =
635                    if said == Spoken::AllowOnce { Answer::AllowOnce } else { Answer::Deny };
636                self.answer(answer, transcript, utterance.bound).await;
637            }
638        }
639    }
640
641    async fn answer(&mut self, answer: Answer, transcript: &str, bound: Option<(String, u64)>) {
642        let Some((id, version)) = bound else {
643            return;
644        };
645        let current = self.prompt.as_ref().map(|prompt| (prompt.id.as_str(), prompt.version));
646        if current != Some((id.as_str(), version)) {
647            self.send(VoiceUpdate::Outcome {
648                decision_id: id,
649                decided: false,
650                text: Some(words::CHANGED_WHILE_YOU_SPOKE.to_string()),
651            })
652            .await;
653            return;
654        }
655        match self.engine.decide_spoken(&self.speaker, &id, version, answer, transcript).await {
656            Ok(SpokenAnswer { outcome, settled }) => {
657                if let CommandOutcome::Pending { decision_id, cancel_until, text } = &outcome {
658                    self.pending.insert(decision_id.clone());
659                    if let Some(settled) = settled {
660                        let id = decision_id.clone();
661                        self.settled.push(Box::pin(async move { (id, settled.await) }));
662                    }
663                    self.send(VoiceUpdate::Pending {
664                        decision_id: decision_id.clone(),
665                        cancel_until: *cancel_until,
666                        text: text.clone(),
667                    })
668                    .await;
669                } else {
670                    self.send(outcome_update(&id, Ok(outcome))).await;
671                }
672            }
673            Err(error) => self.send(outcome_update(&id, Err(error))).await,
674        }
675        self.refresh().await;
676    }
677
678    async fn on_settled(
679        &mut self,
680        id: String,
681        settled: std::result::Result<Result<CommandOutcome>, oneshot::error::RecvError>,
682    ) {
683        self.pending.remove(&id);
684        let update = match settled {
685            Ok(result) => outcome_update(&id, result),
686            // The window's task was aborted: cancelled, ended or stopped.
687            Err(_) => VoiceUpdate::Outcome {
688                decision_id: id,
689                decided: false,
690                text: Some(words::SPOKEN_ANSWER_CANCELLED.to_string()),
691            },
692        };
693        self.send(update).await;
694        self.refresh().await;
695    }
696
697    /// Cancels every spoken answer of this conversation in its cancel window, as `caller`.
698    async fn cancel_pending(&mut self, caller: &Caller) {
699        let pending: Vec<String> = self.pending.iter().cloned().collect();
700        for id in pending {
701            let cancel = Command::CancelAnswer { decision_id: id.clone() };
702            match self.engine.execute(caller, cancel).await {
703                Ok(_) => {}
704                // Its window ended meanwhile; its outcome follows.
705                Err(SurfaceError::NotFound { .. }) => {}
706                Err(error) => self.send(self.error(&error)).await,
707            }
708        }
709    }
710
711    /// Ends the conversation, once: a spoken answer in its cancel window is cancelled.
712    async fn end(&mut self) {
713        if std::mem::replace(&mut self.ended, true) {
714            return;
715        }
716        let viewer = self.viewer.clone();
717        self.cancel_pending(&viewer).await;
718        self.cancel_actions();
719        // The cancelled answers report through their aborted windows.
720        while !self.settled.is_empty() {
721            match tokio::time::timeout(Duration::from_secs(1), self.settled.next()).await {
722                Ok(Some((id, settled))) => self.on_settled(id, settled).await,
723                Ok(None) | Err(_) => break,
724            }
725        }
726        self.send(VoiceUpdate::Ended).await;
727    }
728
729    /// Cancels every spoken screen action of this conversation in its cancel window; one
730    /// already being taken runs to its end.
731    fn cancel_actions(&mut self) {
732        self.actions.retain(|_, action| !action.cancel());
733    }
734
735    /// Reads `transcript` as a screen action on the person's Coming up and, for one, waits out
736    /// the engine's cancel window before taking it (spec 3.3 §5.6, owner question 26).
737    #[cfg(feature = "verb-ui")]
738    async fn spoken_action(&mut self, transcript: &str) {
739        use crate::verbs::spoken::{SpokenAction, parse};
740        use crate::verbs::{ObjectRef, VerbIntent, problem_line, words as verb_words};
741
742        let Some(gate) = self.verbs.clone() else {
743            return;
744        };
745        // An ordinary sentence reads no agenda, inside the conversation's loop.
746        if !crate::verbs::spoken::may_be_action(transcript) {
747            return;
748        }
749        let Ok(items) = gate.coming_up(&self.speaker).await else {
750            return;
751        };
752        let (item, title, tomorrow) = match parse(transcript, &items) {
753            None => return,
754            Some(SpokenAction::Ambiguous { said, matches }) => {
755                let text = format!(
756                    "{} — say the full name or use the screen",
757                    verb_words::things_match(matches.len(), &said)
758                );
759                self.send(VoiceUpdate::ActionOutcome {
760                    action_id: None,
761                    done: false,
762                    text,
763                    heading: None,
764                })
765                .await;
766                return;
767            }
768            Some(SpokenAction::Snooze { item, title, tomorrow }) => (item, title, tomorrow),
769        };
770        let Some(found) = items.iter().find(|found| found.id == item) else {
771            return;
772        };
773        let choice = found.choices.iter().find(|choice| choice.tomorrow == tomorrow);
774        let Some(choice) = choice.filter(|_| found.why_not.is_none()) else {
775            // The choice is gone when the item ends before it, as `/snooze` says.
776            let why = found.why_not.clone().unwrap_or_else(|| match found.ends {
777                Some(ends) => verb_words::ends_at(
778                    &gate.registry().scope(self.speaker.user_id(), None).time_text(ends),
779                ),
780                None => verb_words::NOT_ONE_TIME.to_string(),
781            });
782            let text = verb_words::cant_snooze(&why);
783            self.send(VoiceUpdate::ActionOutcome {
784                action_id: None,
785                done: false,
786                text,
787                heading: None,
788            })
789            .await;
790            return;
791        };
792        let heading = verb_words::move_to(&title, &choice.at_text);
793        let done = verb_words::moved_to(&title, &choice.at_text);
794        let said_done = format!("You snoozed {title} by voice");
795        let window = gate.voice_cancel_window();
796        let id = format!("act-{}", uuid::Uuid::new_v4());
797        let cancel_until = chrono::Utc::now()
798            + chrono::Duration::from_std(window).unwrap_or_else(|_| chrono::Duration::seconds(5));
799        let intent = VerbIntent::new("snooze", serde_json::json!({ "to": choice.to }))
800            .on(ObjectRef::coming_up(&item));
801        let speaker = self.speaker.clone();
802        let said = transcript.to_string();
803        let (task_id, task_heading) = (id.clone(), heading.clone());
804        let cancelled = VoiceUpdate::ActionOutcome {
805            action_id: Some(id.clone()),
806            done: false,
807            text: verb_words::CANCELLED_NOTHING_CHANGED.to_string(),
808            heading: Some(heading.clone()),
809        };
810        let claimed = Arc::new(AtomicBool::new(false));
811        let mine = Arc::clone(&claimed);
812        let withdrawn = cancelled.clone();
813        let handle = tokio::spawn(async move {
814            tokio::time::sleep(window).await;
815            // A cancel that claimed it first withdrew it; from here on it is taken.
816            if mine.swap(true, Ordering::SeqCst) {
817                return withdrawn;
818            }
819            match gate.call_spoken(&speaker, intent, &said).await {
820                Ok(_) => VoiceUpdate::ActionOutcome {
821                    action_id: Some(task_id),
822                    done: true,
823                    text: said_done,
824                    heading: Some(done),
825                },
826                Err(error) => VoiceUpdate::ActionOutcome {
827                    action_id: Some(task_id),
828                    done: false,
829                    text: problem_line(&error),
830                    heading: Some(task_heading),
831                },
832            }
833        });
834        self.actions.insert(id.clone(), WindowedAction { task: handle.abort_handle(), claimed });
835        let ending = id.clone();
836        self.acting.push(Box::pin(async move {
837            match handle.await {
838                Ok(update) => (ending, update),
839                Err(_) => (ending, cancelled),
840            }
841        }));
842        let seconds = window.as_millis().div_ceil(1000) as u64;
843        self.send(VoiceUpdate::PendingAction {
844            action_id: id,
845            cancel_until,
846            text: verb_words::snoozing_in(seconds),
847            heading,
848        })
849        .await;
850    }
851
852    /// Without screen actions, no words take one.
853    #[cfg(not(feature = "verb-ui"))]
854    async fn spoken_action(&mut self, _transcript: &str) {}
855
856    /// Resumes the conversation's held calls that have a decision, on their own task and one
857    /// at a time: a resumed call runs its tool, which can take long.
858    fn resume(&mut self) {
859        while self.resumes.try_join_next().is_some() {}
860        // One running and one waiting cover every decision made meanwhile; a task that ends
861        // unjoined is counted until it is joined, so the ask is kept for the next to end.
862        if self.resumes.len() >= 2 {
863            self.resume_again = true;
864            return;
865        }
866        let surface = Arc::clone(&self.surface);
867        let lock = Arc::clone(&self.resume_lock);
868        let output = self.output.clone();
869        self.resumes.spawn(async move {
870            let _one_at_a_time = lock.lock().await;
871            if let Err(error) = surface.resume_held_calls().await {
872                tracing::warn!(error = %error, "a decided call could not be resumed");
873                let _ = output
874                    .send(VoiceOutput::Update(VoiceUpdate::Error {
875                        code: "surface.voice.provider".into(),
876                        message: error.to_string(),
877                    }))
878                    .await;
879            }
880        });
881    }
882
883    /// Reads the open decisions again and says what is prompted and what needs a screen.
884    async fn refresh(&mut self) {
885        let stopped = self.engine.source().stopped().await.unwrap_or(false);
886        let cards = if stopped {
887            Vec::new()
888        } else {
889            match self.engine.decisions(&self.speaker).await {
890                Ok(cards) if self.own_only => {
891                    cards.into_iter().filter(|card| card.session_id == self.session_id).collect()
892                }
893                Ok(cards) => cards,
894                Err(error) => {
895                    tracing::warn!(error = %error, "the open decisions could not be read");
896                    return;
897                }
898            }
899        };
900        self.stopped = stopped;
901        // Every call of the conversation's own session is one it held: its realtime session
902        // is the only runner of that session.
903        self.own = cards
904            .iter()
905            .filter(|card| card.session_id == self.session_id)
906            .map(|card| card.id.clone())
907            .collect();
908        let choice = choose(&cards, &self.own, &self.pending);
909        let now = Instant::now();
910        let changed = match (&self.prompt, choice) {
911            (Some(prompt), Some(card)) => prompt.id != card.id || prompt.version != card.version,
912            (None, None) => false,
913            _ => true,
914        };
915        if changed {
916            self.prompt = choice.map(|card| Prompt {
917                id: card.id.clone(),
918                version: card.version,
919                since: now,
920            });
921            self.send(VoiceUpdate::Prompted {
922                decision_id: choice.map(|card| card.id.clone()),
923                version: choice.map(|card| card.version),
924            })
925            .await;
926        }
927        // Every decision voice cannot allow once: high risk, money, or a call shown cut short.
928        let needs_screen: Vec<String> = cards
929            .iter()
930            .filter(|card| {
931                card.allowed.option(Answer::AllowOnce).is_none_or(|option| option.needs_expanded)
932            })
933            .map(|card| card.id.clone())
934            .collect();
935        if needs_screen != self.needs_screen {
936            self.needs_screen = needs_screen.clone();
937            self.send(VoiceUpdate::NeedsScreen { decision_ids: needs_screen }).await;
938        }
939    }
940}
941
942/// The decision a spoken answer would apply to: the conversation's own call held last, else
943/// the oldest open decision voice may answer, never one whose spoken answer is pending.
944fn choose<'a>(
945    cards: &'a [DecisionCard],
946    own: &[String],
947    pending: &HashSet<String>,
948) -> Option<&'a DecisionCard> {
949    let answerable = |card: &&DecisionCard| {
950        !pending.contains(&card.id)
951            && card.allowed.options.iter().any(|option| {
952                matches!(option.answer, Answer::AllowOnce | Answer::Deny) && !option.needs_expanded
953            })
954    };
955    own.iter()
956        .rev()
957        .find_map(|id| cards.iter().filter(answerable).find(|card| &card.id == id))
958        .or_else(|| cards.iter().find(answerable))
959}
960
961/// What the view is told once a spoken answer ended.
962fn outcome_update(id: &str, result: Result<CommandOutcome>) -> VoiceUpdate {
963    let (decided, text) = match result {
964        Ok(CommandOutcome::Answered { card }) => (card.decided.is_some(), None),
965        Ok(CommandOutcome::Changed { .. }) => {
966            (false, Some(words::CHANGED_WHILE_YOU_SPOKE.to_string()))
967        }
968        Ok(CommandOutcome::AlreadyDecided { decided, .. }) => (false, Some(decided.text)),
969        Ok(CommandOutcome::AnswerCancelled { .. }) => {
970            (false, Some(words::SPOKEN_ANSWER_CANCELLED.to_string()))
971        }
972        Ok(_) => (false, None),
973        // A high-risk or money call: approving needs the person to confirm it is them.
974        Err(SurfaceError::Rule(_)) => (false, Some(words::VOICE_CANT_APPROVE_THIS.to_string())),
975        Err(error) => (false, Some(error.to_string())),
976    };
977    VoiceUpdate::Outcome { decision_id: id.to_string(), decided, text }
978}