1use 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#[derive(Debug, Clone)]
19pub enum ReactorEvent {
20 Live(LiveEvent),
22 StateChanged(Vec<StateMutation>),
24 TimerTick {
26 now: Instant,
28 },
29 PlaybackDrained {
31 prompt_pending: bool,
33 },
34 UserSpeechStarted,
36 UserSpeechEnded {
38 prompt_pending: bool,
40 },
41 SoftTurnComplete,
43}
44
45#[derive(Debug, Clone, Default)]
47pub struct VoiceRuntimeState {
48 pub user_speaking: bool,
50 pub playback_active: bool,
52 pub prompt_pending: bool,
54 pub prompt_epoch: u64,
56 pub last_barge_in_at: Option<Instant>,
58 pub last_playback_drained_at: Option<Instant>,
60}
61
62impl VoiceRuntimeState {
63 pub fn apply_event(&mut self, event: &ReactorEvent) {
65 self.apply_event_at(event, Instant::now());
66 }
67
68 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#[derive(Debug, Clone, PartialEq, Eq)]
97pub struct EffectPolicy {
98 pub mode: ExecutionMode,
100 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#[derive(Debug, Clone)]
115pub enum LiveEffect {
116 Noop,
118 SendContext(Vec<Content>),
120 PromptModel,
122 CancelDeferredPrompt,
124 SignalUserActivityStart,
126 SignalUserActivityEnd,
128 UpdateInstruction(String),
130 Emit(LiveEvent),
132}
133
134#[derive(Debug, Clone)]
136pub struct Reaction {
137 pub source: &'static str,
139 pub effect: LiveEffect,
141 pub policy: EffectPolicy,
143}
144
145impl Reaction {
146 pub fn blocking(source: &'static str, effect: LiveEffect) -> Self {
148 Self {
149 source,
150 effect,
151 policy: EffectPolicy::default(),
152 }
153 }
154
155 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
168pub trait ReactorRule: Send + Sync {
170 fn name(&self) -> &str;
172 fn react(&self, event: &ReactorEvent, voice: &VoiceRuntimeState) -> Vec<Reaction>;
174}
175
176pub 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 pub fn new() -> Self {
196 Self::default()
197 }
198
199 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 pub fn with_clock(mut self, clock: crate::clock::SharedClock) -> Self {
209 self.clock = clock;
210 self
211 }
212
213 pub fn add_rule(&mut self, rule: impl ReactorRule + 'static) {
215 self.rules.push(Box::new(rule));
216 }
217
218 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 pub fn voice_state(&self) -> VoiceRuntimeState {
234 self.voice.lock().clone()
235 }
236}
237
238pub 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
262pub 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}