Skip to main content

gemini_adk_rs/live/
handle.rs

1//! LiveHandle — runtime interaction with a Live session.
2
3use std::sync::Arc;
4
5use gemini_genai_rs::prelude::{FunctionResponse, SessionEvent, SessionPhase, VadEvent};
6use gemini_genai_rs::protocol::ContextUpdate;
7use gemini_genai_rs::session::{SessionError, SessionHandle, SessionWriter};
8use parking_lot::Mutex;
9use serde::de::DeserializeOwned;
10use tokio::sync::{broadcast, mpsc};
11use tokio::task::JoinHandle;
12use tokio_util::sync::CancellationToken;
13
14use crate::flow::{FlowExplanation, FlowSnapshot, SharedFlowStack};
15use crate::state::State;
16
17use super::background_tool::BackgroundToolTracker;
18use super::context_writer::PendingContext;
19use super::effect_executor::LiveEffectExecutor;
20use super::input_vad::{
21    ActivityAuthority, BackendInputVad, BackendVadSnapshot, InputAudioProcessor,
22};
23use super::processor::ControlEvent;
24use super::reactor::{LiveReactor, ReactorEvent, VoiceRuntimeState};
25use super::telemetry::SessionTelemetry;
26use super::turn_commit::TurnSignal;
27
28/// Handle for interacting with a running Live session.
29///
30/// Provides send methods for audio/text/video, system instruction updates,
31/// event subscription, state access, telemetry, and graceful shutdown.
32///
33/// When [`ContextDelivery::Deferred`](super::steering::ContextDelivery::Deferred) is
34/// enabled, `send_audio`, `send_text`, and `send_video` automatically flush
35/// any pending context turns before forwarding the user content.
36#[derive(Clone)]
37pub struct LiveHandle {
38    session: SessionHandle,
39    /// Writer used for user-facing sends.  When deferred context delivery is
40    /// enabled, this is a `DeferredWriter` that flushes pending context.
41    /// Otherwise it's the raw `SessionHandle`.
42    writer: Arc<dyn SessionWriter>,
43    /// Fast-lane task. Held in `Arc<Mutex<Option<..>>>` so `LiveHandle` stays
44    /// `Clone` while [`disconnect`](Self::disconnect) can take ownership to
45    /// grace-await and then abort the lane.
46    fast_task: Arc<Mutex<Option<JoinHandle<()>>>>,
47    /// Control-lane task (same ownership scheme as `fast_task`).
48    ctrl_task: Arc<Mutex<Option<JoinHandle<()>>>>,
49    /// Cancellation token for the telemetry lane, cancelled on disconnect.
50    telem_cancel: CancellationToken,
51    state: State,
52    telemetry: Arc<SessionTelemetry>,
53    event_tx: broadcast::Sender<super::events::LiveEvent>,
54    pending_context: Option<Arc<PendingContext>>,
55    reactor: Arc<LiveReactor>,
56    effect_executor: LiveEffectExecutor,
57    input_vad: Arc<Mutex<BackendInputVad>>,
58    /// Mic-chain processors run over outgoing audio inside `send_audio`.
59    input_processors: Arc<Mutex<Vec<Box<dyn InputAudioProcessor>>>>,
60    /// Whether this client's VAD sends activityStart/activityEnd marks.
61    client_activity_authority: Arc<std::sync::atomic::AtomicBool>,
62    /// Turn-commit policy between VAD edges and activity marks (None = raw
63    /// edge forwarding). See [`set_turn_commit`](Self::set_turn_commit).
64    turn_commit: Arc<Mutex<Option<super::turn_commit::TurnCommitPolicy>>>,
65    /// Monotonic audio clock in milliseconds, advanced by each chunk's
66    /// duration — the policy's time base (deterministic, not wall time).
67    audio_clock_ms: Arc<std::sync::atomic::AtomicU64>,
68    /// Governed-flow monitor shared with the control lane (None when the
69    /// session is not governed by a flow).
70    flow: Option<SharedFlowStack>,
71    task_status: Option<Arc<Mutex<crate::tasks::TaskSessionSnapshot>>>,
72    /// Tracker for in-flight background tool tasks. Shared with the control
73    /// lane (which spawns/cancels per-call tasks) so [`disconnect`](Self::disconnect)
74    /// can cancel every outstanding background tool — otherwise orphaned tasks
75    /// could keep running and post stale `ToolCompleted` events after shutdown.
76    background_tracker: Arc<BackgroundToolTracker>,
77    /// Control-lane sender used by [`send_text`](Self::send_text) to record the
78    /// typed turn on the transcript, so a text-driven session is visible to
79    /// extractors exactly as a spoken one is.
80    ///
81    /// Deliberately a [`WeakSender`](mpsc::WeakSender): the control channel must
82    /// still close once the router drops its strong sender, or the lane would
83    /// never drain and shut down.
84    ctrl_tx: Option<mpsc::WeakSender<ControlEvent>>,
85    /// Where the listener's playback is reported; shared with the router.
86    playback: super::playback::PlaybackClock,
87}
88
89impl LiveHandle {
90    #[allow(
91        clippy::too_many_arguments,
92        reason = "crate-internal constructor called once from spawn_lanes; the runtime parts are deliberately enumerated rather than re-bundled"
93    )]
94    pub(crate) fn new(
95        session: SessionHandle,
96        writer: Arc<dyn SessionWriter>,
97        fast_task: JoinHandle<()>,
98        ctrl_task: JoinHandle<()>,
99        state: State,
100        telemetry: Arc<SessionTelemetry>,
101        event_tx: broadcast::Sender<super::events::LiveEvent>,
102        pending_context: Option<Arc<PendingContext>>,
103        flow: Option<SharedFlowStack>,
104        background_tracker: Arc<BackgroundToolTracker>,
105        telem_cancel: CancellationToken,
106    ) -> Self {
107        let reactor = Arc::new(LiveReactor::voice_defaults().with_clock(state.clock()));
108        let state_clock = state.clock();
109        let effect_executor = LiveEffectExecutor::new(
110            Arc::new(session.clone()),
111            pending_context.clone(),
112            event_tx.clone(),
113        );
114
115        Self {
116            session,
117            writer,
118            fast_task: Arc::new(Mutex::new(Some(fast_task))),
119            ctrl_task: Arc::new(Mutex::new(Some(ctrl_task))),
120            telem_cancel,
121            state,
122            telemetry,
123            event_tx,
124            pending_context,
125            reactor,
126            effect_executor,
127            input_vad: Arc::new(Mutex::new(BackendInputVad::default())),
128            input_processors: Arc::new(Mutex::new(Vec::new())),
129            client_activity_authority: Arc::new(std::sync::atomic::AtomicBool::new(false)),
130            turn_commit: Arc::new(Mutex::new(None)),
131            audio_clock_ms: Arc::new(std::sync::atomic::AtomicU64::new(0)),
132            flow,
133            task_status: None,
134            background_tracker,
135            ctrl_tx: None,
136            playback: super::playback::PlaybackClock::new(state_clock),
137        }
138    }
139
140    pub(crate) fn with_task_status(
141        mut self,
142        status: Option<Arc<Mutex<crate::tasks::TaskSessionSnapshot>>>,
143    ) -> Self {
144        self.task_status = status;
145        self
146    }
147
148    /// Observe the installed skill catalog and task lifecycle.
149    pub fn task_snapshot(&self) -> Option<crate::tasks::TaskSessionSnapshot> {
150        self.task_status
151            .as_ref()
152            .map(|status| status.lock().clone())
153    }
154
155    /// Apply a trusted task command on the control lane.
156    ///
157    /// Approval decisions belong here or in an authenticated application UI;
158    /// they are never exposed as model-callable tools.
159    pub async fn task_command(
160        &self,
161        command: crate::tasks::TaskCommand,
162    ) -> Result<crate::tasks::TaskSessionSnapshot, String> {
163        if self.task_status.is_none() {
164            return Err("this session has no installed skills".into());
165        }
166        let sender = self
167            .ctrl_tx
168            .as_ref()
169            .and_then(mpsc::WeakSender::upgrade)
170            .ok_or_else(|| "the session control lane has stopped".to_string())?;
171        let (reply, result) = tokio::sync::oneshot::channel();
172        sender
173            .send(ControlEvent::TaskCommand { command, reply })
174            .await
175            .map_err(|_| "the session control lane has stopped".to_string())?;
176        result
177            .await
178            .map_err(|_| "the session ended before the command completed".to_string())?
179    }
180
181    /// Attach the control-lane sender used to record typed turns on the
182    /// transcript. Called once from the builder's `spawn_lanes`.
183    pub(crate) fn with_control_sender(mut self, ctrl_tx: mpsc::WeakSender<ControlEvent>) -> Self {
184        self.ctrl_tx = Some(ctrl_tx);
185        self
186    }
187
188    /// Share the router's playback clock. Called once from `spawn_lanes`.
189    pub(crate) fn with_playback(mut self, playback: super::playback::PlaybackClock) -> Self {
190        self.playback = playback;
191        self
192    }
193
194    /// The session's playback clock. Whatever plays the model's audio to the
195    /// listener reports to it, so an interruption cuts the model's transcript
196    /// to what was heard. The voice pump and the telephony bridges report on
197    /// their own; a custom player calls
198    /// [`queued`](super::PlaybackClock::queued) as it plays audio and
199    /// [`flushed`](super::PlaybackClock::flushed) when it drops audio on
200    /// barge-in. See [`playback`](super::playback).
201    pub fn playback(&self) -> &super::playback::PlaybackClock {
202        &self.playback
203    }
204
205    /// Send audio data (raw PCM16 16kHz bytes).
206    ///
207    /// Configured input processors (see [`configure_input_audio`](Self::configure_input_audio))
208    /// run over the frame first; the backend input VAD then sees the
209    /// processed stream, and under client activity authority its speech
210    /// edges are forwarded to the server as activityStart/activityEnd.
211    /// When deferred context delivery is enabled, any pending model-role
212    /// context turns are flushed to the wire before the audio frame.
213    pub async fn send_audio(&self, data: impl Into<bytes::Bytes>) -> Result<(), SessionError> {
214        let data: bytes::Bytes = data.into();
215        // The active stage's voice timing (see `flow::timing`).
216        let timing = self
217            .state
218            .get::<crate::flow::VoiceTiming>(crate::flow::VOICE_TIMING_KEY);
219        // A stage that holds the floor (a statutory readout) replaces the
220        // mic with silence while the model speaks, so neither the server's
221        // VAD nor ours can cut the model off. The stream keeps its cadence.
222        let data = if timing
223            .as_ref()
224            .is_some_and(crate::flow::VoiceTiming::holds_floor)
225            && self
226                .state
227                .session()
228                .get::<bool>("is_model_speaking")
229                .unwrap_or(false)
230        {
231            bytes::Bytes::from(vec![0u8; data.len()])
232        } else {
233            data
234        };
235        let data = {
236            let mut processors = self.input_processors.lock();
237            if processors.is_empty() {
238                data
239            } else {
240                let mut frame: Vec<i16> =
241                    gemini_genai_rs::buffer::convert::pcm16_le_samples(&data).collect();
242                for processor in processors.iter_mut() {
243                    processor.process_frame(&mut frame);
244                }
245                gemini_genai_rs::buffer::convert::i16_to_pcm16_le(&frame).into()
246            }
247        };
248        let (vad_events, sample_rate) = {
249            let mut input_vad = self.input_vad.lock();
250            (input_vad.process_pcm_bytes(&data), input_vad.sample_rate())
251        };
252        let client_authority = self
253            .client_activity_authority
254            .load(std::sync::atomic::Ordering::Relaxed);
255
256        // Advance the audio clock by this chunk's duration and run the
257        // turn-commit policy (if configured) over the observed edges. The
258        // policy decides which activity marks reach the wire; raw-edge
259        // callbacks below stay untouched so watchers and transcript
260        // bookkeeping see VAD truth either way.
261        let commit_signals = {
262            let samples = (data.len() / 2) as u64;
263            let chunk_ms = samples * 1000 / u64::from(sample_rate.max(1));
264            let now_ms = chunk_ms
265                + self
266                    .audio_clock_ms
267                    .fetch_add(chunk_ms, std::sync::atomic::Ordering::Relaxed);
268            let mut policy = self.turn_commit.lock();
269            // A stage's endpointing sets the end-of-turn hold. It needs a
270            // turn-commit policy, so one is installed (otherwise edges pass
271            // through unchanged) under client authority.
272            if let Some(hold) = timing
273                .as_ref()
274                .and_then(|t| t.end_of_speech_ms)
275                .map(std::time::Duration::from_millis)
276                && client_authority
277            {
278                let policy = policy.get_or_insert_with(|| {
279                    super::turn_commit::TurnCommitPolicy::new(
280                        super::turn_commit::TurnCommitConfig::immediate(),
281                    )
282                });
283                if policy.config().eot_hold != hold {
284                    policy.set_eot_hold(hold);
285                }
286            }
287            policy.as_mut().map(|p| {
288                let model_speaking = self
289                    .state
290                    .session()
291                    .get::<bool>("is_model_speaking")
292                    .unwrap_or(false);
293                p.advance(now_ms, &vad_events, model_speaking)
294            })
295        };
296
297        if vad_events.contains(&VadEvent::SpeechStart) {
298            if client_authority && commit_signals.is_none() {
299                self.writer.signal_activity_start().await?;
300            }
301            self.user_speech_started().await?;
302        }
303        if let Some(signals) = &commit_signals {
304            // Start-type commits go out before the audio, like raw marks.
305            for signal in signals {
306                if client_authority
307                    && matches!(
308                        signal,
309                        TurnSignal::ActivityStart | TurnSignal::InterruptionStart
310                    )
311                {
312                    self.writer.signal_activity_start().await?;
313                }
314            }
315        }
316
317        self.writer.send_audio(data).await?;
318
319        if vad_events.contains(&VadEvent::SpeechEnd) {
320            if client_authority && commit_signals.is_none() {
321                self.writer.signal_activity_end().await?;
322            }
323            self.user_speech_ended().await?;
324        }
325        if let Some(signals) = &commit_signals {
326            for signal in signals {
327                if client_authority && matches!(signal, TurnSignal::ActivityEnd) {
328                    self.writer.signal_activity_end().await?;
329                }
330            }
331        }
332
333        Ok(())
334    }
335
336    /// Install a turn-commit policy between the input VAD's speech edges and
337    /// the activity marks sent under client activity authority.
338    ///
339    /// Raw edges make two measured mistakes as turn signals (TurnBench dev
340    /// set): committing end-of-turn during mid-turn pauses, and treating
341    /// backchannels ("mm-hm") over model speech as barge-ins. The policy's
342    /// end-hold and interruption-sustain rules suppress both — see
343    /// [`TurnCommitConfig`](super::turn_commit::TurnCommitConfig) for the
344    /// measured operating points. Without a
345    /// policy, edges forward to the wire unchanged.
346    pub fn set_turn_commit(&self, config: super::turn_commit::TurnCommitConfig) {
347        *self.turn_commit.lock() = Some(super::turn_commit::TurnCommitPolicy::new(config));
348    }
349
350    /// Configure the input audio path: mic-chain processors applied inside
351    /// [`send_audio`](Self::send_audio), an optional replacement input-VAD
352    /// configuration, and the interruption authority. Call once after
353    /// connect, before streaming audio; a mid-stream call resets the VAD's
354    /// adaptive state.
355    pub fn configure_input_audio(
356        &self,
357        processors: Vec<Box<dyn InputAudioProcessor>>,
358        vad: Option<gemini_genai_rs::vad::VadConfig>,
359        authority: ActivityAuthority,
360    ) {
361        *self.input_processors.lock() = processors;
362        if let Some(config) = vad {
363            *self.input_vad.lock() = BackendInputVad::new(config);
364        }
365        self.client_activity_authority.store(
366            authority == ActivityAuthority::Client,
367            std::sync::atomic::Ordering::Relaxed,
368        );
369    }
370
371    /// Send a text message.
372    ///
373    /// When deferred context delivery is enabled, any pending model-role
374    /// context turns are flushed to the wire before the text message.
375    ///
376    /// The text is also recorded on the session transcript as the user side of
377    /// the current turn, through the same internal control event that ASR of
378    /// audio produces. Without this a text-driven session would hand every
379    /// [`TurnExtractor`](super::extractor::TurnExtractor) an empty user turn,
380    /// since the transcript's user side is otherwise written only by ASR.
381    /// Routing through the control event rather than poking the buffer keeps a
382    /// typed turn and a spoken one the *same* event downstream.
383    pub async fn send_text(&self, text: impl Into<String>) -> Result<(), SessionError> {
384        let text = text.into();
385        self.telemetry.record_text_send();
386        self.writer.send_text(text.clone()).await?;
387
388        // Record only after a *successful* send: a turn the model never
389        // received is not part of the conversation.
390        if let Some(tx) = self.ctrl_tx.as_ref().and_then(mpsc::WeakSender::upgrade) {
391            let _ = tx.send(ControlEvent::InputTranscript(text)).await;
392        }
393
394        Ok(())
395    }
396
397    /// Send a video/image frame (raw JPEG bytes).
398    ///
399    /// When deferred context delivery is enabled, any pending model-role
400    /// context turns are flushed to the wire before the video frame.
401    pub async fn send_video(&self, jpeg_data: impl Into<bytes::Bytes>) -> Result<(), SessionError> {
402        self.writer.send_video(jpeg_data.into()).await
403    }
404
405    /// Update the system instruction mid-session.
406    pub async fn update_instruction(
407        &self,
408        instruction: impl Into<String>,
409    ) -> Result<(), SessionError> {
410        SessionWriter::update_instruction(&self.session, instruction.into()).await
411    }
412
413    /// Replace the declared tools and/or the system instruction mid-session
414    /// with a `contextUpdate` message (Gemini 3.8 Live). See
415    /// [`SessionHandle::update_context`](gemini_genai_rs::session::SessionHandle::update_context).
416    ///
417    /// With [`SteeringMode::ContextUpdate`](crate::live::SteeringMode::ContextUpdate)
418    /// the runtime sends these itself at phase and step changes; call this
419    /// only for changes the runtime does not know about.
420    pub async fn update_context(&self, update: ContextUpdate) -> Result<(), SessionError> {
421        SessionWriter::update_context(&self.session, update).await
422    }
423
424    /// Send tool responses manually (if not using auto-dispatch).
425    pub async fn send_tool_response(
426        &self,
427        responses: Vec<FunctionResponse>,
428    ) -> Result<(), SessionError> {
429        self.session.send_tool_response(responses).await
430    }
431
432    /// Notify the runtime that client-side playback has drained.
433    ///
434    /// Voice UIs should call this only when it is safe for the model to speak,
435    /// for example after browser speaker playback has drained and the user is
436    /// not actively speaking. User audio/text sends intentionally flush context
437    /// only and leave the prompt armed.
438    pub async fn playback_drained(&self) -> Result<(), SessionError> {
439        let prompt_pending = self
440            .pending_context
441            .as_ref()
442            .is_some_and(|pending| pending.has_prompt());
443        let reactions = self
444            .reactor
445            .react(&ReactorEvent::PlaybackDrained { prompt_pending });
446        self.effect_executor.execute_reactions(reactions).await
447    }
448
449    /// Notify the runtime that client-side user speech has started.
450    ///
451    /// This is the barge-in edge for voice clients: pending model prompts are
452    /// cancelled before they can race with user audio, while queued context is
453    /// kept so the next user send can still carry it.
454    pub async fn user_speech_started(&self) -> Result<(), SessionError> {
455        let reactions = self.reactor.react(&ReactorEvent::UserSpeechStarted);
456        self.effect_executor.execute_reactions(reactions).await
457    }
458
459    /// Notify the runtime that client-side user speech has ended.
460    pub async fn user_speech_ended(&self) -> Result<(), SessionError> {
461        let prompt_pending = self
462            .pending_context
463            .as_ref()
464            .is_some_and(|pending| pending.has_prompt());
465        let reactions = self
466            .reactor
467            .react(&ReactorEvent::UserSpeechEnded { prompt_pending });
468        self.effect_executor.execute_reactions(reactions).await
469    }
470
471    /// Snapshot the reactor-owned voice runtime state.
472    pub fn voice_state(&self) -> VoiceRuntimeState {
473        self.reactor.voice_state()
474    }
475
476    /// Snapshot backend input VAD state.
477    pub fn input_vad_state(&self) -> BackendVadSnapshot {
478        self.input_vad.lock().snapshot()
479    }
480
481    /// Flush deferred context and any pending model prompt.
482    ///
483    /// Prefer [`Self::playback_drained`] for voice clients. This compatibility
484    /// method routes through the same reactor/effect executor path.
485    pub async fn flush_deferred_prompt(&self) -> Result<(), SessionError> {
486        self.playback_drained().await
487    }
488
489    /// Get the user-facing session writer.
490    ///
491    /// When deferred context delivery is enabled, this returns the
492    /// `DeferredWriter` that flushes pending context before sends.
493    pub fn writer(&self) -> Arc<dyn SessionWriter> {
494        self.writer.clone()
495    }
496
497    /// Subscribe to raw session events (for custom processing).
498    pub fn subscribe(&self) -> broadcast::Receiver<SessionEvent> {
499        self.session.subscribe()
500    }
501
502    /// Get the current session phase.
503    pub fn phase(&self) -> SessionPhase {
504        self.session.phase()
505    }
506
507    /// Gracefully disconnect the session.
508    ///
509    /// Shutdown sequence:
510    /// 1. Cancel all in-flight background tool tasks (they are aborted at an
511    ///    await point; tool futures must therefore be drop-safe).
512    /// 2. Close the L0 session. The terminal `Disconnected` event makes the
513    ///    event router exit, which closes the lane channels.
514    /// 3. Grace-await the fast and control lanes (~250 ms each) so they can
515    ///    drain queued events and run their final persistence drain, then
516    ///    abort whatever is still stuck (e.g. a lane blocked in a slow tool).
517    /// 4. Cancel the telemetry lane.
518    pub async fn disconnect(&self) -> Result<(), SessionError> {
519        if self.task_status.is_some()
520            && let Some(sender) = self.ctrl_tx.as_ref().and_then(mpsc::WeakSender::upgrade)
521        {
522            let (reply, result) = tokio::sync::oneshot::channel();
523            let _ = tokio::time::timeout(Self::LANE_SHUTDOWN_GRACE, async {
524                if sender
525                    .send(ControlEvent::ShutdownTasks(reply))
526                    .await
527                    .is_ok()
528                {
529                    let _ = result.await;
530                }
531            })
532            .await;
533        }
534        // Cancel background tool tasks FIRST: once the session is closing,
535        // their results can no longer be delivered, and leaving them running
536        // would let them post stale ToolCompleted events to a dead lane.
537        self.background_tracker.cancel_all();
538        let result = SessionWriter::disconnect(&self.session).await;
539
540        // Grace-await the lanes, then abort. Taking the JoinHandles out of
541        // their mutexes gives us the ownership `await` requires; a second
542        // disconnect (or a clone's disconnect) simply finds them gone.
543        for lane in [&self.fast_task, &self.ctrl_task] {
544            let task = lane.lock().take();
545            if let Some(mut task) = task
546                && tokio::time::timeout(Self::LANE_SHUTDOWN_GRACE, &mut task)
547                    .await
548                    .is_err()
549            {
550                task.abort();
551            }
552        }
553
554        // Stop the telemetry lane now rather than when the router exits; until
555        // then it would keep running its debounce timer.
556        self.telem_cancel.cancel();
557        result
558    }
559
560    /// How long [`disconnect`](Self::disconnect) waits for each lane to drain
561    /// before aborting it.
562    const LANE_SHUTDOWN_GRACE: std::time::Duration = std::time::Duration::from_millis(250);
563
564    /// Wait for the session to end (disconnect, GoAway, or error).
565    pub async fn done(&self) -> Result<(), SessionError> {
566        self.session
567            .join()
568            .await
569            .map_err(|_| SessionError::ChannelClosed)
570    }
571
572    /// Get the underlying SessionHandle for advanced usage.
573    pub fn session(&self) -> &SessionHandle {
574        &self.session
575    }
576
577    /// Latest session-resumption handle issued by the server, if any.
578    ///
579    /// While session resumption is enabled
580    /// ([`SessionConfig::session_resumption`](gemini_genai_rs::prelude::SessionConfig::session_resumption);
581    /// L2: `Live::builder().session_resume(true)`), the Gemini server
582    /// periodically sends `SessionResumptionUpdate` messages; this returns the
583    /// most recent handle (also captured in persistence snapshots as
584    /// [`SessionSnapshot::resume_handle`](crate::live::persistence::SessionSnapshot::resume_handle)).
585    ///
586    /// To survive a server-initiated `GoAway` or a planned restart, read this
587    /// handle (e.g. from the `on_go_away` callback) and pass it to
588    /// `resume_from(handle)` on the next connect's
589    /// [`SessionConfig`](gemini_genai_rs::prelude::SessionConfig). No
590    /// automatic reconnect is performed — resumption is an explicit caller
591    /// decision.
592    ///
593    /// Returns `None` when resumption is disabled or no update has arrived yet.
594    pub fn resume_handle(&self) -> Option<String> {
595        self.session.resume_handle()
596    }
597
598    /// Access the shared State container.
599    ///
600    /// Extraction results from `TurnExtractor`s are stored here under the
601    /// extractor's name. Use `state().get::<T>(name)` to read typed values.
602    pub fn state(&self) -> &State {
603        &self.state
604    }
605
606    /// Access the session telemetry (auto-collected by the telemetry lane).
607    ///
608    /// Use `telemetry().snapshot()` to get a JSON snapshot of all metrics.
609    pub fn telemetry(&self) -> &Arc<SessionTelemetry> {
610        &self.telemetry
611    }
612
613    /// Subscribe to semantic events from the processor.
614    ///
615    /// Returns a broadcast receiver. Call multiple times for independent
616    /// subscribers. A subscriber that falls more than
617    /// [`LiveSessionBuilder::event_capacity`](super::builder::LiveSessionBuilder::event_capacity)
618    /// events behind receives `RecvError::Lagged` and skips the oldest.
619    pub fn events(&self) -> broadcast::Receiver<super::events::LiveEvent> {
620        self.event_tx.subscribe()
621    }
622
623    /// Subscribe to semantic events as a [`futures_util::Stream`].
624    ///
625    /// Stream-flavored sibling of [`events`](Self::events): each call creates
626    /// an independent subscriber starting from the current point in the event
627    /// flow. If the subscriber falls behind the broadcast buffer, the missed
628    /// events are skipped and the stream continues; the stream ends when the
629    /// session's event channel closes. See
630    /// [`LiveEventStream`](super::events::LiveEventStream).
631    ///
632    /// # Example
633    ///
634    /// ```rust,ignore
635    /// use futures_util::StreamExt;
636    ///
637    /// let mut stream = handle.stream();
638    /// while let Some(ev) = stream.next().await {
639    ///     match ev {
640    ///         LiveEvent::TextDelta(t) => print!("{t}"),
641    ///         LiveEvent::TurnComplete => println!(),
642    ///         _ => {}
643    ///     }
644    /// }
645    /// ```
646    pub fn stream(&self) -> super::events::LiveEventStream {
647        super::events::LiveEventStream::new(self.event_tx.subscribe())
648    }
649
650    /// Convenience: get the latest extraction result by extractor name.
651    pub fn extracted<T: DeserializeOwned>(&self, name: &str) -> Option<T> {
652        self.state.get(name)
653    }
654
655    /// Snapshot the governed flow's control-plane state: active steps, which
656    /// tools are admitted vs blocked (with reasons), and unmet requirements.
657    ///
658    /// The deterministic answer to "why did the assistant ask that?" — computed
659    /// against the live [`State`] and the marking the control lane maintains.
660    /// Returns `None` when the session is not governed by a flow
661    /// (`Live::govern`/`observe` was not used).
662    ///
663    /// When a digression is active the snapshot describes that layer; the
664    /// `flow:overlay` state key names it.
665    ///
666    /// This is a synchronous snapshot: it briefly locks the shared
667    /// [`FlowStack`](crate::flow::FlowStack) and never blocks on session
668    /// I/O.
669    pub fn explain(&self) -> Option<FlowExplanation> {
670        self.flow
671            .as_ref()
672            .map(|mon| mon.lock().explain(&self.state))
673    }
674
675    /// Observe governed steps, digressions, and whole-stack completion.
676    ///
677    /// Returns `None` for an ungoverned session. Reads the stack under one
678    /// short lock without session I/O; shared business state can still change
679    /// independently. The result is not a resumable session checkpoint.
680    pub fn flow_snapshot(&self) -> Option<FlowSnapshot> {
681        self.flow
682            .as_ref()
683            .map(|stack| stack.lock().snapshot(&self.state))
684    }
685
686    /// Replace a governed step's posture mid-session. Returns `true` when the
687    /// session is governed and the step exists.
688    ///
689    /// Postures are re-projected at every turn boundary, so the edit steers
690    /// the very next turn. This is the *safe* subset of live spec editing:
691    /// the DAG, guards, and tool gates stay fixed (tool declarations cannot
692    /// change mid-session at the wire level anyway).
693    pub fn update_step_posture(&self, step_id: &str, posture: Option<String>) -> bool {
694        self.flow
695            .as_ref()
696            .map(|mon| mon.lock().set_posture(step_id, posture))
697            .unwrap_or(false)
698    }
699
700    /// Replace a governed step's grounding template mid-session. Same
701    /// semantics as [`update_step_posture`](Self::update_step_posture).
702    pub fn update_step_ground(&self, step_id: &str, ground: Option<String>) -> bool {
703        self.flow
704            .as_ref()
705            .map(|mon| mon.lock().set_ground(step_id, ground))
706            .unwrap_or(false)
707    }
708}
709
710#[cfg(test)]
711mod tests {
712    use super::*;
713    use crate::live::telemetry::SessionTelemetry;
714    use gemini_genai_rs::session::{SessionCommand, SessionState};
715    use tokio_util::sync::CancellationToken;
716
717    /// Build a LiveHandle wired to an in-memory SessionHandle (no transport).
718    /// The command receiver is returned so `disconnect()` sends succeed.
719    fn make_handle_with_lanes(
720        fast: JoinHandle<()>,
721        ctrl: JoinHandle<()>,
722    ) -> (LiveHandle, tokio::sync::mpsc::Receiver<SessionCommand>) {
723        let (command_tx, command_rx) = tokio::sync::mpsc::channel(8);
724        let (event_tx, _) = broadcast::channel(16);
725        let (phase_tx, phase_rx) = tokio::sync::watch::channel(SessionPhase::Active);
726        let state = Arc::new(SessionState::with_events(phase_tx, event_tx.clone()));
727        let session = SessionHandle::new(command_tx, event_tx, state, phase_rx);
728        let writer: Arc<dyn SessionWriter> = Arc::new(session.clone());
729        let (live_tx, _) = broadcast::channel(16);
730        let handle = LiveHandle::new(
731            session,
732            writer,
733            fast,
734            ctrl,
735            State::new(),
736            Arc::new(SessionTelemetry::new()),
737            live_tx,
738            None,
739            None,
740            Arc::new(BackgroundToolTracker::new()),
741            CancellationToken::new(),
742        );
743        (handle, command_rx)
744    }
745
746    fn make_handle() -> (LiveHandle, tokio::sync::mpsc::Receiver<SessionCommand>) {
747        make_handle_with_lanes(tokio::spawn(async {}), tokio::spawn(async {}))
748    }
749
750    /// Like [`make_handle`] but also hands back the L0 session state, for
751    /// tests that simulate what the transport writes there.
752    fn make_handle_and_state() -> (
753        LiveHandle,
754        tokio::sync::mpsc::Receiver<SessionCommand>,
755        Arc<SessionState>,
756    ) {
757        let (command_tx, command_rx) = tokio::sync::mpsc::channel(8);
758        let (event_tx, _) = broadcast::channel(16);
759        let (phase_tx, phase_rx) = tokio::sync::watch::channel(SessionPhase::Active);
760        let state = Arc::new(SessionState::with_events(phase_tx, event_tx.clone()));
761        let session = SessionHandle::new(command_tx, event_tx, state.clone(), phase_rx);
762        let writer: Arc<dyn SessionWriter> = Arc::new(session.clone());
763        let (live_tx, _) = broadcast::channel(16);
764        let handle = LiveHandle::new(
765            session,
766            writer,
767            tokio::spawn(async {}),
768            tokio::spawn(async {}),
769            State::new(),
770            Arc::new(SessionTelemetry::new()),
771            live_tx,
772            None,
773            None,
774            Arc::new(BackgroundToolTracker::new()),
775            CancellationToken::new(),
776        );
777        (handle, command_rx, state)
778    }
779
780    /// Sets a flag when dropped — observes that an aborted task's future was
781    /// actually torn down.
782    struct SetOnDrop(Arc<std::sync::atomic::AtomicBool>);
783    impl Drop for SetOnDrop {
784        fn drop(&mut self) {
785            self.0.store(true, std::sync::atomic::Ordering::SeqCst);
786        }
787    }
788
789    #[tokio::test]
790    async fn disconnect_cancels_background_tool_tasks() {
791        let (handle, _cmd_rx) = make_handle();
792        let tracker = handle.background_tracker.clone();
793
794        // Register a never-finishing background tool task.
795        let token = CancellationToken::new();
796        let t = token.clone();
797        let task = tokio::spawn(async move {
798            t.cancelled().await;
799            std::future::pending::<()>().await;
800        });
801        tracker.spawn("call-1".into(), task, token.clone());
802        assert_eq!(tracker.active_count(), 1);
803
804        handle.disconnect().await.expect("disconnect");
805
806        assert_eq!(
807            tracker.active_count(),
808            0,
809            "disconnect must cancel all tracked background tool tasks"
810        );
811        assert!(token.is_cancelled(), "cooperative token must be cancelled");
812    }
813
814    #[tokio::test]
815    async fn disconnect_aborts_stuck_lanes_within_grace_period() {
816        use std::sync::atomic::{AtomicBool, Ordering};
817
818        // Lanes that never finish on their own (simulating a lane blocked in a
819        // slow tool); drop guards record that abort tore the futures down.
820        let fast_dropped = Arc::new(AtomicBool::new(false));
821        let ctrl_dropped = Arc::new(AtomicBool::new(false));
822        let f = fast_dropped.clone();
823        let c = ctrl_dropped.clone();
824        let fast = tokio::spawn(async move {
825            let _guard = SetOnDrop(f);
826            std::future::pending::<()>().await;
827        });
828        let ctrl = tokio::spawn(async move {
829            let _guard = SetOnDrop(c);
830            std::future::pending::<()>().await;
831        });
832
833        let (handle, _cmd_rx) = make_handle_with_lanes(fast, ctrl);
834        let telem_cancel = handle.telem_cancel.clone();
835
836        // disconnect() must return in bounded time even with stuck lanes.
837        tokio::time::timeout(std::time::Duration::from_secs(2), handle.disconnect())
838            .await
839            .expect("disconnect must not hang on stuck lanes")
840            .expect("disconnect");
841
842        // Give the aborts a beat to take effect, then verify teardown.
843        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
844        assert!(
845            fast_dropped.load(Ordering::SeqCst),
846            "fast lane must be aborted after the grace period"
847        );
848        assert!(
849            ctrl_dropped.load(Ordering::SeqCst),
850            "control lane must be aborted after the grace period"
851        );
852        assert!(
853            telem_cancel.is_cancelled(),
854            "telemetry lane must be cancelled on disconnect"
855        );
856    }
857
858    #[tokio::test]
859    async fn resume_handle_surfaces_latest_server_handle() {
860        let (handle, _cmd_rx, state) = make_handle_and_state();
861        assert_eq!(handle.resume_handle(), None, "no update yet");
862
863        // Simulate the L0 transport storing a SessionResumptionUpdate.
864        *state.resume_handle.lock() = Some("rh-42".into());
865        assert_eq!(handle.resume_handle(), Some("rh-42".to_string()));
866    }
867
868    #[tokio::test]
869    async fn disconnect_is_idempotent_across_clones() {
870        let (handle, _cmd_rx) = make_handle();
871        let clone = handle.clone();
872        handle.disconnect().await.expect("first disconnect");
873        // The clone's disconnect finds the lane handles already taken.
874        clone.disconnect().await.expect("second disconnect");
875    }
876}