Skip to main content

gemini_adk_rs/live/
reactor.rs

1//! First-class reactor vocabulary for Live sessions.
2//!
3//! This module is intentionally small: it defines the normalized events,
4//! reactions, and typed effects that existing mechanisms can migrate onto
5//! incrementally without rewriting the current control plane in one step.
6
7use parking_lot::Mutex;
8use std::time::{Duration, Instant};
9
10use gemini_genai_rs::prelude::Content;
11
12use crate::state::StateMutation;
13
14use super::ExecutionMode;
15use super::events::LiveEvent;
16
17/// A normalized event that can drive ADK-level reactions.
18#[derive(Debug, Clone)]
19pub enum ReactorEvent {
20    /// Existing semantic Live event.
21    Live(LiveEvent),
22    /// State changed since the last reactor cursor.
23    StateChanged(Vec<StateMutation>),
24    /// Periodic tick for timers and sustained conditions.
25    TimerTick {
26        /// Time observed by the control lane for this tick.
27        now: Instant,
28    },
29    /// Client-side playback drained after model audio was generated.
30    PlaybackDrained {
31        /// Whether the control plane has armed a deferred model prompt.
32        prompt_pending: bool,
33    },
34    /// Client detected that the user started speaking.
35    UserSpeechStarted,
36    /// Client detected that the user stopped speaking.
37    UserSpeechEnded {
38        /// Whether the control plane has armed a deferred model prompt.
39        prompt_pending: bool,
40    },
41    /// User speech ended, but the model may or may not produce a turn.
42    SoftTurnComplete,
43}
44
45/// Voice-flow state owned by the reactor.
46#[derive(Debug, Clone, Default)]
47pub struct VoiceRuntimeState {
48    /// Whether the client believes the user is currently speaking.
49    pub user_speaking: bool,
50    /// Whether browser playback is believed to be active.
51    pub playback_active: bool,
52    /// Whether a deferred model prompt is armed.
53    pub prompt_pending: bool,
54    /// Monotonic epoch bumped whenever a prompt is cancelled or armed state changes.
55    pub prompt_epoch: u64,
56    /// Last time the client reported barge-in/user speech start.
57    pub last_barge_in_at: Option<Instant>,
58    /// Last time browser playback reported drained.
59    pub last_playback_drained_at: Option<Instant>,
60}
61
62impl VoiceRuntimeState {
63    /// Apply an incoming event to the voice runtime state before rules run.
64    pub fn apply_event(&mut self, event: &ReactorEvent) {
65        self.apply_event_at(event, Instant::now());
66    }
67
68    /// [`apply_event`](Self::apply_event) with an explicit `now`, for callers
69    /// that read time from a [`Clock`](crate::clock::Clock).
70    pub fn apply_event_at(&mut self, event: &ReactorEvent, now: Instant) {
71        match event {
72            ReactorEvent::PlaybackDrained { prompt_pending } => {
73                self.playback_active = false;
74                self.prompt_pending = *prompt_pending;
75                self.last_playback_drained_at = Some(now);
76            }
77            ReactorEvent::UserSpeechStarted => {
78                self.user_speaking = true;
79                self.playback_active = false;
80                if self.prompt_pending {
81                    self.prompt_epoch = self.prompt_epoch.saturating_add(1);
82                }
83                self.prompt_pending = false;
84                self.last_barge_in_at = Some(now);
85            }
86            ReactorEvent::UserSpeechEnded { prompt_pending } => {
87                self.user_speaking = false;
88                self.prompt_pending = *prompt_pending && !self.playback_active;
89            }
90            _ => {}
91        }
92    }
93}
94
95/// Execution policy for an effect.
96#[derive(Debug, Clone, PartialEq, Eq)]
97pub struct EffectPolicy {
98    /// Whether this effect blocks later effects from running.
99    pub mode: ExecutionMode,
100    /// Optional maximum time budget for the effect.
101    pub timeout: Option<Duration>,
102}
103
104impl Default for EffectPolicy {
105    fn default() -> Self {
106        Self {
107            mode: ExecutionMode::Blocking,
108            timeout: None,
109        }
110    }
111}
112
113/// A typed runtime effect emitted by a reaction.
114#[derive(Debug, Clone)]
115pub enum LiveEffect {
116    /// No operation; useful for conditional reaction builders.
117    Noop,
118    /// Add state/context turns to the session.
119    SendContext(Vec<Content>),
120    /// Ask the model to generate from accumulated context.
121    PromptModel,
122    /// Cancel a deferred model prompt while leaving queued context intact.
123    CancelDeferredPrompt,
124    /// Tell the Live API that user speech activity started.
125    SignalUserActivityStart,
126    /// Tell the Live API that user speech activity ended.
127    SignalUserActivityEnd,
128    /// Replace or amend the active instruction.
129    UpdateInstruction(String),
130    /// Emit a semantic event for observers.
131    Emit(LiveEvent),
132}
133
134/// A policy-wrapped effect.
135#[derive(Debug, Clone)]
136pub struct Reaction {
137    /// Rule or subsystem that produced the reaction.
138    pub source: &'static str,
139    /// Runtime effect requested by the rule.
140    pub effect: LiveEffect,
141    /// Execution policy for the effect.
142    pub policy: EffectPolicy,
143}
144
145impl Reaction {
146    /// Create a blocking reaction.
147    pub fn blocking(source: &'static str, effect: LiveEffect) -> Self {
148        Self {
149            source,
150            effect,
151            policy: EffectPolicy::default(),
152        }
153    }
154
155    /// Create a concurrent reaction.
156    pub fn concurrent(source: &'static str, effect: LiveEffect) -> Self {
157        Self {
158            source,
159            effect,
160            policy: EffectPolicy {
161                mode: ExecutionMode::Concurrent,
162                ..EffectPolicy::default()
163            },
164        }
165    }
166}
167
168/// A rule that reacts to normalized events and emits typed effects.
169pub trait ReactorRule: Send + Sync {
170    /// Stable rule name for diagnostics and reaction provenance.
171    fn name(&self) -> &str;
172    /// Produce reactions for a normalized event.
173    fn react(&self, event: &ReactorEvent, voice: &VoiceRuntimeState) -> Vec<Reaction>;
174}
175
176/// Ordered collection of reactor rules.
177pub struct LiveReactor {
178    rules: Vec<Box<dyn ReactorRule>>,
179    voice: Mutex<VoiceRuntimeState>,
180    clock: crate::clock::SharedClock,
181}
182
183impl Default for LiveReactor {
184    fn default() -> Self {
185        Self {
186            rules: Vec::new(),
187            voice: Mutex::new(VoiceRuntimeState::default()),
188            clock: crate::clock::system_clock(),
189        }
190    }
191}
192
193impl LiveReactor {
194    /// Create an empty reactor.
195    pub fn new() -> Self {
196        Self::default()
197    }
198
199    /// Create a reactor with the default voice-flow rules.
200    pub fn voice_defaults() -> Self {
201        let mut reactor = Self::new();
202        reactor.add_rule(PromptOnPlaybackDrained);
203        reactor.add_rule(UserSpeechActivityRule);
204        reactor
205    }
206
207    /// Timestamp voice events with `clock` instead of the system clock.
208    pub fn with_clock(mut self, clock: crate::clock::SharedClock) -> Self {
209        self.clock = clock;
210        self
211    }
212
213    /// Add a rule to the end of the ordered rule list.
214    pub fn add_rule(&mut self, rule: impl ReactorRule + 'static) {
215        self.rules.push(Box::new(rule));
216    }
217
218    /// Run all rules against an event and collect reactions in rule order.
219    pub fn react(&self, event: &ReactorEvent) -> Vec<Reaction> {
220        let voice = {
221            let mut voice = self.voice.lock();
222            voice.apply_event_at(event, self.clock.now());
223            voice.clone()
224        };
225
226        self.rules
227            .iter()
228            .flat_map(|rule| rule.react(event, &voice))
229            .collect()
230    }
231
232    /// Return a snapshot of the current voice runtime state.
233    pub fn voice_state(&self) -> VoiceRuntimeState {
234        self.voice.lock().clone()
235    }
236}
237
238/// Prompt the model when browser playback is fully drained and a prompt is armed.
239pub struct PromptOnPlaybackDrained;
240
241impl ReactorRule for PromptOnPlaybackDrained {
242    fn name(&self) -> &str {
243        "prompt_on_playback_drained"
244    }
245
246    fn react(&self, event: &ReactorEvent, voice: &VoiceRuntimeState) -> Vec<Reaction> {
247        if matches!(event, ReactorEvent::PlaybackDrained { .. })
248            && voice.prompt_pending
249            && !voice.user_speaking
250            && !voice.playback_active
251        {
252            vec![Reaction::blocking(
253                "prompt_on_playback_drained",
254                LiveEffect::PromptModel,
255            )]
256        } else {
257            Vec::new()
258        }
259    }
260}
261
262/// Cancel pending model prompts and signal activity around user speech.
263pub struct UserSpeechActivityRule;
264
265impl ReactorRule for UserSpeechActivityRule {
266    fn name(&self) -> &str {
267        "user_speech_activity"
268    }
269
270    fn react(&self, event: &ReactorEvent, voice: &VoiceRuntimeState) -> Vec<Reaction> {
271        match event {
272            ReactorEvent::UserSpeechStarted => vec![
273                Reaction::blocking("user_speech_activity", LiveEffect::CancelDeferredPrompt),
274                Reaction::blocking("user_speech_activity", LiveEffect::SignalUserActivityStart),
275            ],
276            ReactorEvent::UserSpeechEnded { .. } => {
277                let mut reactions = vec![Reaction::blocking(
278                    "user_speech_activity",
279                    LiveEffect::SignalUserActivityEnd,
280                )];
281                if voice.prompt_pending && !voice.playback_active {
282                    reactions.push(Reaction::blocking(
283                        "user_speech_activity",
284                        LiveEffect::PromptModel,
285                    ));
286                }
287                reactions
288            }
289            _ => Vec::new(),
290        }
291    }
292}
293
294#[cfg(test)]
295mod tests {
296    use super::*;
297
298    #[test]
299    fn reactor_collects_reactions_in_rule_order() {
300        let mut reactor = LiveReactor::new();
301        reactor.add_rule(PromptOnPlaybackDrained);
302
303        let reactions = reactor.react(&ReactorEvent::PlaybackDrained {
304            prompt_pending: true,
305        });
306        assert_eq!(reactions.len(), 1);
307        assert_eq!(reactions[0].source, "prompt_on_playback_drained");
308        assert_eq!(reactions[0].policy.mode, ExecutionMode::Blocking);
309        assert!(matches!(reactions[0].effect, LiveEffect::PromptModel));
310    }
311
312    #[test]
313    fn playback_drained_without_pending_prompt_is_noop() {
314        let reactor = LiveReactor::voice_defaults();
315
316        let reactions = reactor.react(&ReactorEvent::PlaybackDrained {
317            prompt_pending: false,
318        });
319
320        assert!(reactions.is_empty());
321    }
322
323    #[test]
324    fn user_speech_started_cancels_prompt_and_signals_activity() {
325        let reactor = LiveReactor::voice_defaults();
326
327        let prompt_reactions = reactor.react(&ReactorEvent::PlaybackDrained {
328            prompt_pending: true,
329        });
330        assert_eq!(prompt_reactions.len(), 1);
331
332        let reactions = reactor.react(&ReactorEvent::UserSpeechStarted);
333
334        assert_eq!(reactions.len(), 2);
335        assert!(matches!(
336            reactions[0].effect,
337            LiveEffect::CancelDeferredPrompt
338        ));
339        assert!(matches!(
340            reactions[1].effect,
341            LiveEffect::SignalUserActivityStart
342        ));
343        let voice = reactor.voice_state();
344        assert!(voice.user_speaking);
345        assert!(!voice.prompt_pending);
346        assert_eq!(voice.prompt_epoch, 1);
347    }
348
349    #[test]
350    fn user_speech_ended_signals_activity_end() {
351        let reactor = LiveReactor::voice_defaults();
352
353        let reactions = reactor.react(&ReactorEvent::UserSpeechEnded {
354            prompt_pending: false,
355        });
356
357        assert_eq!(reactions.len(), 1);
358        assert!(matches!(
359            reactions[0].effect,
360            LiveEffect::SignalUserActivityEnd
361        ));
362        assert!(!reactor.voice_state().user_speaking);
363    }
364
365    #[test]
366    fn speech_end_prompts_when_playback_already_drained_and_prompt_pending() {
367        let reactor = LiveReactor::voice_defaults();
368
369        reactor.react(&ReactorEvent::UserSpeechStarted);
370        let drain_reactions = reactor.react(&ReactorEvent::PlaybackDrained {
371            prompt_pending: true,
372        });
373        assert!(drain_reactions.is_empty());
374
375        let reactions = reactor.react(&ReactorEvent::UserSpeechEnded {
376            prompt_pending: true,
377        });
378
379        assert_eq!(reactions.len(), 2);
380        assert!(matches!(
381            reactions[0].effect,
382            LiveEffect::SignalUserActivityEnd
383        ));
384        assert!(matches!(reactions[1].effect, LiveEffect::PromptModel));
385    }
386
387    #[test]
388    fn playback_drained_does_not_prompt_while_user_is_speaking() {
389        let reactor = LiveReactor::voice_defaults();
390
391        reactor.react(&ReactorEvent::UserSpeechStarted);
392        let reactions = reactor.react(&ReactorEvent::PlaybackDrained {
393            prompt_pending: true,
394        });
395
396        assert!(reactions.is_empty());
397        let voice = reactor.voice_state();
398        assert!(voice.user_speaking);
399        assert!(voice.prompt_pending);
400    }
401
402    #[test]
403    fn speech_start_wins_after_pending_prompt_snapshot() {
404        let reactor = LiveReactor::voice_defaults();
405
406        reactor.react(&ReactorEvent::PlaybackDrained {
407            prompt_pending: true,
408        });
409        reactor.react(&ReactorEvent::UserSpeechStarted);
410        let reactions = reactor.react(&ReactorEvent::PlaybackDrained {
411            prompt_pending: false,
412        });
413
414        assert!(reactions.is_empty());
415        let voice = reactor.voice_state();
416        assert!(voice.user_speaking);
417        assert!(!voice.prompt_pending);
418        assert_eq!(voice.prompt_epoch, 1);
419    }
420}