Skip to main content

gemini_adk_rs/live/
transcript.rs

1//! Transcript accumulation buffer for Live sessions.
2//!
3//! Automatically accumulates input/output transcripts per-turn with windowing
4//! support for OOB extraction pipelines.
5
6use std::collections::VecDeque;
7use std::fmt::Write;
8use std::time::Instant;
9
10/// Summary of a tool call within a conversation turn.
11#[derive(Debug, Clone)]
12pub struct ToolCallSummary {
13    /// Name of the tool that was called.
14    pub name: String,
15    /// First 200 chars of JSON args.
16    pub args_summary: String,
17    /// First 200 chars of JSON result.
18    pub result_summary: String,
19}
20
21/// A single completed conversation turn with accumulated transcripts.
22#[derive(Debug, Clone)]
23pub struct TranscriptTurn {
24    /// Sequential turn number (0-based).
25    pub turn_number: u32,
26    /// Accumulated user (input) transcript for this turn.
27    pub user: String,
28    /// Accumulated model (output) transcript for this turn.
29    pub model: String,
30    /// Tool calls that occurred during this turn.
31    pub tool_calls: Vec<ToolCallSummary>,
32    /// When this turn was finalized.
33    pub timestamp: Instant,
34}
35
36/// Default maximum number of completed turns retained in the ring buffer.
37const DEFAULT_MAX_TURNS: usize = 50;
38
39/// Accumulates input/output transcripts and segments them by turn boundaries.
40///
41/// Uses a ring buffer (`VecDeque`) that evicts the oldest turns when
42/// `max_turns` is reached. This prevents unbounded memory growth in
43/// long-running voice sessions.
44///
45/// Thread safety: wrap in `Arc<parking_lot::Mutex<TranscriptBuffer>>` when
46/// sharing between fast lane (push) and control lane (end_turn / window).
47#[derive(Debug)]
48pub struct TranscriptBuffer {
49    turns: VecDeque<TranscriptTurn>,
50    current_user: String,
51    current_model: String,
52    /// Caller words that arrived after the model began speaking this turn.
53    /// A late transcription tail if the turn ends normally; a barge-in that
54    /// starts the next turn if it ends in an interruption.
55    late_user: String,
56    /// The model's turn in progress was interrupted.
57    interrupted: bool,
58    tool_calls_pending: Vec<ToolCallSummary>,
59    turn_count: u32,
60    max_turns: usize,
61}
62
63/// Truncate a string to at most `max_chars` characters, reusing the original when possible.
64fn truncate_string(mut s: String, max_chars: usize) -> String {
65    if s.len() <= max_chars {
66        return s; // fast path: ASCII strings under limit
67    }
68    // Find the byte index of the max_chars-th char boundary
69    if let Some((idx, _)) = s.char_indices().nth(max_chars) {
70        s.truncate(idx);
71    }
72    s
73}
74
75impl TranscriptBuffer {
76    /// Create a new transcript buffer with the default capacity.
77    pub fn new() -> Self {
78        Self::with_capacity(DEFAULT_MAX_TURNS)
79    }
80
81    /// Create a buffer with a custom maximum turn capacity.
82    ///
83    /// When the buffer reaches `max_turns` completed turns, the oldest
84    /// turn is evicted on each new `end_turn()`.
85    pub fn with_capacity(max_turns: usize) -> Self {
86        Self {
87            turns: VecDeque::with_capacity(max_turns.min(64)),
88            current_user: String::new(),
89            current_model: String::new(),
90            late_user: String::new(),
91            interrupted: false,
92            tool_calls_pending: Vec::new(),
93            turn_count: 0,
94            max_turns,
95        }
96    }
97
98    /// Append input (user speech) transcript text.
99    ///
100    /// Words that arrive once the model has started speaking are kept apart
101    /// until the turn ends: see [`mark_interrupted`](Self::mark_interrupted).
102    pub fn push_input(&mut self, text: &str) {
103        if self.current_model.is_empty() {
104            self.current_user.push_str(text);
105        } else {
106            self.late_user.push_str(text);
107        }
108    }
109
110    /// Record that the caller interrupted the model's turn in progress.
111    ///
112    /// The caller words that arrived after the model began speaking are the
113    /// barge-in: when the turn ends they open the next turn instead of being
114    /// filed, before the model's words, under the turn they interrupted.
115    pub fn mark_interrupted(&mut self) {
116        self.interrupted = true;
117    }
118
119    /// Everything the caller has said in the turn in progress.
120    fn pending_user(&self) -> String {
121        format!("{}{}", self.current_user, self.late_user)
122    }
123
124    /// Append output (model speech) transcript text.
125    pub fn push_output(&mut self, text: &str) {
126        self.current_model.push_str(text);
127    }
128
129    /// Record a tool call summary for the current turn.
130    ///
131    /// Args and result are truncated to 200 characters of their JSON representation.
132    pub fn push_tool_call(
133        &mut self,
134        name: String,
135        args: &serde_json::Value,
136        result: &serde_json::Value,
137    ) {
138        let args_str = serde_json::to_string(args).unwrap_or_default();
139        let result_str = serde_json::to_string(result).unwrap_or_default();
140        self.tool_calls_pending.push(ToolCallSummary {
141            name,
142            args_summary: truncate_string(args_str, 200),
143            result_summary: truncate_string(result_str, 200),
144        });
145    }
146
147    /// Finalize the current turn and return it.
148    ///
149    /// Resets the current accumulators for the next turn.
150    /// Only creates a turn if there is any transcript content.
151    pub fn end_turn(&mut self) -> Option<TranscriptTurn> {
152        let barge_in = if std::mem::take(&mut self.interrupted) {
153            std::mem::take(&mut self.late_user)
154        } else {
155            let tail = std::mem::take(&mut self.late_user);
156            self.current_user.push_str(&tail);
157            String::new()
158        };
159        if self.current_user.is_empty()
160            && self.current_model.is_empty()
161            && self.tool_calls_pending.is_empty()
162        {
163            self.current_user = barge_in;
164            return None;
165        }
166
167        let turn = TranscriptTurn {
168            turn_number: self.turn_count,
169            user: std::mem::replace(&mut self.current_user, barge_in),
170            model: std::mem::take(&mut self.current_model),
171            tool_calls: std::mem::take(&mut self.tool_calls_pending),
172            timestamp: Instant::now(),
173        };
174        self.turn_count += 1;
175        // Evict oldest turn if at capacity
176        if self.turns.len() >= self.max_turns {
177            self.turns.pop_front();
178        }
179        let completed = turn.clone();
180        self.turns.push_back(turn);
181        Some(completed)
182    }
183
184    /// Get the last `n` completed turns as a contiguous slice.
185    ///
186    /// Requires `&mut self` to ensure VecDeque contiguity.
187    pub fn window(&mut self, n: usize) -> &[TranscriptTurn] {
188        let slice = self.turns.make_contiguous();
189        let start = slice.len().saturating_sub(n);
190        &slice[start..]
191    }
192
193    /// All completed turns as a contiguous slice.
194    ///
195    /// Requires `&mut self` to ensure VecDeque contiguity.
196    pub fn all_turns(&mut self) -> &[TranscriptTurn] {
197        self.turns.make_contiguous()
198    }
199
200    /// Number of retained turns (may be less than `turn_count` due to eviction).
201    pub fn retained_count(&self) -> usize {
202        self.turns.len()
203    }
204
205    /// Number of completed turns.
206    pub fn turn_count(&self) -> u32 {
207        self.turn_count
208    }
209
210    /// Format the last `n` turns as a human-readable transcript for LLM consumption.
211    pub fn format_window(&mut self, n: usize) -> String {
212        let window = self.window(n);
213        let mut out = String::new();
214        for turn in window {
215            if !turn.user.is_empty() {
216                let _ = writeln!(out, "User: {}", turn.user.trim());
217            }
218            for tc in &turn.tool_calls {
219                let _ = writeln!(
220                    out,
221                    "[Tool: {}({}) \u{2192} {}]",
222                    tc.name, tc.args_summary, tc.result_summary
223                );
224            }
225            if !turn.model.is_empty() {
226                let _ = writeln!(out, "Assistant: {}", turn.model.trim());
227            }
228            let _ = writeln!(out);
229        }
230        out
231    }
232
233    /// Set server-provided input transcription for current turn.
234    /// Overwrites client-accumulated input if server transcription is available.
235    pub fn set_input_transcription(&mut self, text: &str) {
236        self.current_user.clear();
237        self.late_user.clear();
238        self.current_user.push_str(text);
239    }
240
241    /// Set server-provided output transcription for current turn.
242    pub fn set_output_transcription(&mut self, text: &str) {
243        self.current_model.clear();
244        self.current_model.push_str(text);
245    }
246
247    /// Clear the model's text from the turn in progress.
248    pub fn truncate_current_model_turn(&mut self) {
249        self.current_model.clear();
250    }
251
252    /// Cut the model's text in the turn in progress to its first
253    /// `heard_chars` characters, ending at the last whole word. The runtime
254    /// calls this on an interruption with what the listener heard; see
255    /// [`playback`](super::playback).
256    pub fn cut_current_model_turn(&mut self, heard_chars: usize) {
257        let keep = super::playback::heard_prefix(&self.current_model, heard_chars);
258        self.current_model.truncate(keep);
259    }
260
261    /// Whether there is any pending (un-finalized) transcript content.
262    pub fn has_pending(&self) -> bool {
263        !self.current_user.is_empty()
264            || !self.late_user.is_empty()
265            || !self.current_model.is_empty()
266            || !self.tool_calls_pending.is_empty()
267    }
268
269    /// Create a `TranscriptWindow` snapshot of the last `n` completed turns.
270    ///
271    /// This is a cheap clone operation designed for passing to phase callbacks.
272    pub fn snapshot_window(&mut self, n: usize) -> TranscriptWindow {
273        TranscriptWindow::new(self.window(n).to_vec())
274    }
275
276    /// Snapshot including the current in-progress turn (not yet finalized).
277    ///
278    /// Used by `GenerationComplete` extractors to see the model's full output
279    /// before the turn is finalized.
280    pub fn snapshot_window_with_current(&mut self, n: usize) -> TranscriptWindow {
281        let mut turns: Vec<TranscriptTurn> = self.window(n).to_vec();
282        if self.has_pending() {
283            turns.push(TranscriptTurn {
284                turn_number: self.turn_count,
285                user: self.pending_user(),
286                model: self.current_model.clone(),
287                tool_calls: self.tool_calls_pending.clone(),
288                timestamp: std::time::Instant::now(),
289            });
290        }
291        TranscriptWindow::new(turns)
292    }
293}
294
295/// A read-only snapshot of recent transcript turns for context construction.
296///
297/// Cheap to create (clone of ~5 small structs). Used by `on_enter_context`
298/// callbacks to reference recent conversation without holding the buffer lock.
299#[derive(Debug, Clone)]
300pub struct TranscriptWindow {
301    turns: Vec<TranscriptTurn>,
302}
303
304impl TranscriptWindow {
305    /// Create a window from a vec of turns.
306    pub fn new(turns: Vec<TranscriptTurn>) -> Self {
307        Self { turns }
308    }
309
310    /// The turns in this window.
311    pub fn turns(&self) -> &[TranscriptTurn] {
312        &self.turns
313    }
314
315    /// Format all turns as human-readable text for LLM consumption.
316    pub fn formatted(&self) -> String {
317        use std::fmt::Write as _;
318        let mut out = String::new();
319        for turn in &self.turns {
320            if !turn.user.is_empty() {
321                let _ = writeln!(out, "User: {}", turn.user.trim());
322            }
323            for tc in &turn.tool_calls {
324                let _ = writeln!(
325                    out,
326                    "[Tool: {}({}) \u{2192} {}]",
327                    tc.name, tc.args_summary, tc.result_summary
328                );
329            }
330            if !turn.model.is_empty() {
331                let _ = writeln!(out, "Assistant: {}", turn.model.trim());
332            }
333            let _ = writeln!(out);
334        }
335        out
336    }
337
338    /// Last user utterance, if any.
339    pub fn last_user(&self) -> Option<&str> {
340        self.turns
341            .iter()
342            .rev()
343            .find(|t| !t.user.is_empty())
344            .map(|t| t.user.as_str())
345    }
346
347    /// Last model utterance, if any.
348    pub fn last_model(&self) -> Option<&str> {
349        self.turns
350            .iter()
351            .rev()
352            .find(|t| !t.model.is_empty())
353            .map(|t| t.model.as_str())
354    }
355
356    /// Number of turns in this window.
357    pub fn len(&self) -> usize {
358        self.turns.len()
359    }
360
361    /// Whether the window is empty.
362    pub fn is_empty(&self) -> bool {
363        self.turns.is_empty()
364    }
365}
366
367impl Default for TranscriptBuffer {
368    fn default() -> Self {
369        Self::new()
370    }
371}
372
373#[cfg(test)]
374mod tests {
375    use super::*;
376
377    #[test]
378    fn accumulate_and_end_turn() {
379        let mut buf = TranscriptBuffer::new();
380        buf.push_input("Hello ");
381        buf.push_input("there");
382        buf.push_output("Hi! How can I help?");
383        let turn = buf.end_turn().expect("should produce a turn");
384        assert_eq!(turn.turn_number, 0);
385        assert_eq!(turn.user, "Hello there");
386        assert_eq!(turn.model, "Hi! How can I help?");
387        assert_eq!(buf.turn_count(), 1);
388    }
389
390    #[test]
391    fn end_turn_empty_returns_none() {
392        let mut buf = TranscriptBuffer::new();
393        assert!(buf.end_turn().is_none());
394    }
395
396    #[test]
397    fn window_returns_last_n() {
398        let mut buf = TranscriptBuffer::new();
399        for i in 0..5 {
400            buf.push_input(&format!("user-{i}"));
401            buf.push_output(&format!("model-{i}"));
402            buf.end_turn();
403        }
404        let w = buf.window(3);
405        assert_eq!(w.len(), 3);
406        assert_eq!(w[0].turn_number, 2);
407        assert_eq!(w[1].turn_number, 3);
408        assert_eq!(w[2].turn_number, 4);
409    }
410
411    #[test]
412    fn window_larger_than_turns() {
413        let mut buf = TranscriptBuffer::new();
414        buf.push_input("only turn");
415        buf.end_turn();
416        let w = buf.window(10);
417        assert_eq!(w.len(), 1);
418    }
419
420    #[test]
421    fn format_window_produces_readable_text() {
422        let mut buf = TranscriptBuffer::new();
423        buf.push_input("What's the weather?");
424        buf.push_output("It's sunny and 22 degrees.");
425        buf.end_turn();
426        buf.push_input("And tomorrow?");
427        buf.push_output("Rain expected.");
428        buf.end_turn();
429
430        let formatted = buf.format_window(2);
431        assert!(formatted.contains("User: What's the weather?"));
432        assert!(formatted.contains("Assistant: It's sunny and 22 degrees."));
433        assert!(formatted.contains("User: And tomorrow?"));
434        assert!(formatted.contains("Assistant: Rain expected."));
435    }
436
437    #[test]
438    fn has_pending() {
439        let mut buf = TranscriptBuffer::new();
440        assert!(!buf.has_pending());
441        buf.push_input("hello");
442        assert!(buf.has_pending());
443        buf.end_turn();
444        assert!(!buf.has_pending());
445    }
446
447    #[test]
448    fn set_input_transcription_overwrites_accumulated() {
449        let mut buf = TranscriptBuffer::new();
450        buf.push_input("partial ");
451        buf.push_input("input");
452        // Server provides authoritative transcription
453        buf.set_input_transcription("server transcription");
454        let turn = buf.end_turn().expect("should produce a turn");
455        assert_eq!(turn.user, "server transcription");
456    }
457
458    #[test]
459    fn set_output_transcription_overwrites_accumulated() {
460        let mut buf = TranscriptBuffer::new();
461        buf.push_output("partial ");
462        buf.push_output("output");
463        // Server provides authoritative transcription
464        buf.set_output_transcription("server output");
465        let turn = buf.end_turn().expect("should produce a turn");
466        assert_eq!(turn.model, "server output");
467    }
468
469    #[test]
470    fn truncate_current_model_turn_clears_model_text() {
471        let mut buf = TranscriptBuffer::new();
472        buf.push_input("user said something");
473        buf.push_output("model was saying something but got");
474        // Interruption happens
475        buf.truncate_current_model_turn();
476        assert!(buf.has_pending()); // user text is still there
477        let turn = buf.end_turn().expect("should produce a turn");
478        assert_eq!(turn.user, "user said something");
479        assert_eq!(turn.model, ""); // model output was truncated
480    }
481
482    #[test]
483    fn multiple_turns_all_tracked() {
484        let mut buf = TranscriptBuffer::new();
485        buf.push_input("a");
486        buf.end_turn();
487        buf.push_output("b");
488        buf.end_turn();
489        buf.push_input("c");
490        buf.push_output("d");
491        buf.end_turn();
492        assert_eq!(buf.all_turns().len(), 3);
493        assert_eq!(buf.turn_count(), 3);
494    }
495
496    #[test]
497    fn push_tool_call_records_summary() {
498        let mut buf = TranscriptBuffer::new();
499        buf.push_input("check weather");
500        buf.push_tool_call(
501            "get_weather".to_string(),
502            &serde_json::json!({"city": "London"}),
503            &serde_json::json!({"temp": 22, "condition": "sunny"}),
504        );
505        buf.push_output("It's sunny in London.");
506        let turn = buf.end_turn().expect("should produce a turn");
507        assert_eq!(turn.tool_calls.len(), 1);
508        assert_eq!(turn.tool_calls[0].name, "get_weather");
509        assert!(turn.tool_calls[0].args_summary.contains("London"));
510        assert!(turn.tool_calls[0].result_summary.contains("sunny"));
511    }
512
513    #[test]
514    fn push_tool_call_truncates_long_args() {
515        let mut buf = TranscriptBuffer::new();
516        let long_value = "x".repeat(500);
517        buf.push_input("do something");
518        buf.push_tool_call(
519            "big_tool".to_string(),
520            &serde_json::json!({"data": long_value}),
521            &serde_json::json!({"ok": true}),
522        );
523        let turn = buf.end_turn().expect("should produce a turn");
524        assert!(turn.tool_calls[0].args_summary.chars().count() <= 200);
525    }
526
527    #[test]
528    fn multiple_tool_calls_in_one_turn() {
529        let mut buf = TranscriptBuffer::new();
530        buf.push_input("plan my trip");
531        buf.push_tool_call(
532            "get_weather".to_string(),
533            &serde_json::json!({"city": "Paris"}),
534            &serde_json::json!({"temp": 18}),
535        );
536        buf.push_tool_call(
537            "get_flights".to_string(),
538            &serde_json::json!({"from": "NYC", "to": "Paris"}),
539            &serde_json::json!({"price": 450}),
540        );
541        buf.push_output("Here's your trip plan.");
542        let turn = buf.end_turn().expect("should produce a turn");
543        assert_eq!(turn.tool_calls.len(), 2);
544        assert_eq!(turn.tool_calls[0].name, "get_weather");
545        assert_eq!(turn.tool_calls[1].name, "get_flights");
546    }
547
548    #[test]
549    fn tool_calls_appear_in_format_window() {
550        let mut buf = TranscriptBuffer::new();
551        buf.push_input("What's the weather?");
552        buf.push_tool_call(
553            "get_weather".to_string(),
554            &serde_json::json!({"city": "London"}),
555            &serde_json::json!({"temp": 22}),
556        );
557        buf.push_output("It's 22 degrees in London.");
558        buf.end_turn();
559
560        let formatted = buf.format_window(1);
561        assert!(formatted.contains("User: What's the weather?"));
562        assert!(formatted.contains("[Tool: get_weather("));
563        assert!(formatted.contains("London"));
564        assert!(formatted.contains("\u{2192}"));
565        assert!(formatted.contains("22"));
566        assert!(formatted.contains("Assistant: It's 22 degrees in London."));
567    }
568
569    #[test]
570    fn tool_call_only_turn_creates_turn() {
571        let mut buf = TranscriptBuffer::new();
572        // A turn with only a tool call and no user/model text
573        buf.push_tool_call(
574            "ping".to_string(),
575            &serde_json::json!({}),
576            &serde_json::json!({"pong": true}),
577        );
578        assert!(buf.has_pending());
579        let turn = buf
580            .end_turn()
581            .expect("tool-call-only turn should be created");
582        assert_eq!(turn.tool_calls.len(), 1);
583        assert_eq!(turn.user, "");
584        assert_eq!(turn.model, "");
585    }
586
587    #[test]
588    fn snapshot_window_creates_window() {
589        let mut buf = TranscriptBuffer::new();
590        buf.push_input("Hello");
591        buf.push_output("Hi there!");
592        buf.end_turn();
593        buf.push_input("How are you?");
594        buf.push_output("I'm good!");
595        buf.end_turn();
596
597        let window = buf.snapshot_window(5);
598        assert_eq!(window.len(), 2);
599        assert_eq!(window.last_user(), Some("How are you?"));
600        assert_eq!(window.last_model(), Some("I'm good!"));
601        assert!(!window.is_empty());
602    }
603
604    #[test]
605    fn transcript_window_formatted() {
606        let mut buf = TranscriptBuffer::new();
607        buf.push_input("What's the weather?");
608        buf.push_output("It's sunny.");
609        buf.end_turn();
610
611        let window = buf.snapshot_window(1);
612        let formatted = window.formatted();
613        assert!(formatted.contains("User: What's the weather?"));
614        assert!(formatted.contains("Assistant: It's sunny."));
615    }
616
617    #[test]
618    fn transcript_window_empty() {
619        let mut buf = TranscriptBuffer::new();
620        let window = buf.snapshot_window(5);
621        assert!(window.is_empty());
622        assert_eq!(window.len(), 0);
623        assert_eq!(window.last_user(), None);
624        assert_eq!(window.last_model(), None);
625    }
626
627    #[test]
628    fn ring_cap_evicts_oldest() {
629        let mut buf = TranscriptBuffer::with_capacity(3);
630        for i in 0..5 {
631            buf.push_input(&format!("user-{i}"));
632            buf.push_output(&format!("model-{i}"));
633            buf.end_turn();
634        }
635        // Only last 3 retained
636        assert_eq!(buf.retained_count(), 3);
637        assert_eq!(buf.turn_count(), 5);
638        let turns = buf.all_turns();
639        assert_eq!(turns[0].turn_number, 2);
640        assert_eq!(turns[1].turn_number, 3);
641        assert_eq!(turns[2].turn_number, 4);
642    }
643
644    #[test]
645    fn ring_cap_window_within_retained() {
646        let mut buf = TranscriptBuffer::with_capacity(4);
647        for i in 0..10 {
648            buf.push_input(&format!("u{i}"));
649            buf.end_turn();
650        }
651        let w = buf.window(2);
652        assert_eq!(w.len(), 2);
653        assert_eq!(w[0].turn_number, 8);
654        assert_eq!(w[1].turn_number, 9);
655    }
656
657    #[test]
658    fn default_capacity_is_50() {
659        let buf = TranscriptBuffer::new();
660        assert_eq!(buf.max_turns, DEFAULT_MAX_TURNS);
661    }
662
663    #[test]
664    fn tool_calls_reset_after_end_turn() {
665        let mut buf = TranscriptBuffer::new();
666        buf.push_input("turn 1");
667        buf.push_tool_call(
668            "tool_a".to_string(),
669            &serde_json::json!({"x": 1}),
670            &serde_json::json!({"y": 2}),
671        );
672        buf.end_turn();
673
674        buf.push_input("turn 2");
675        buf.push_output("no tools this time");
676        let turn2 = buf.end_turn().expect("should produce turn 2");
677        assert!(turn2.tool_calls.is_empty());
678
679        // Verify turn 1 still has its tool call
680        assert_eq!(buf.all_turns()[0].tool_calls.len(), 1);
681    }
682
683    #[test]
684    fn a_barge_in_opens_the_next_turn() {
685        let mut buf = TranscriptBuffer::new();
686        buf.push_input("Four at seven, under Rossi.");
687        buf.push_output("Four at seven under Rossi. Shall I");
688        buf.push_input("Yes, book it.");
689        buf.mark_interrupted();
690        let interrupted = buf.end_turn().unwrap();
691        assert_eq!(interrupted.user, "Four at seven, under Rossi.");
692
693        // The caller's words are the turn in progress, ahead of the reply.
694        let pending = buf.snapshot_window_with_current(1);
695        assert_eq!(pending.turns().last().unwrap().user, "Yes, book it.");
696        buf.push_output("Booked.");
697        let next = buf.end_turn().unwrap();
698        assert_eq!(next.user, "Yes, book it.");
699        assert_eq!(next.model, "Booked.");
700    }
701
702    #[test]
703    fn a_late_transcription_tail_stays_in_its_turn() {
704        let mut buf = TranscriptBuffer::new();
705        buf.push_input("Table for four");
706        buf.push_output("Sure, ");
707        buf.push_input(" tomorrow.");
708        let turn = buf.end_turn().unwrap();
709        assert_eq!(turn.user, "Table for four tomorrow.");
710        assert!(!buf.has_pending());
711    }
712
713    #[test]
714    fn a_barge_in_over_an_unheard_reply_still_opens_the_next_turn() {
715        let mut buf = TranscriptBuffer::new();
716        buf.push_output("Let me");
717        buf.push_input("Actually, five people.");
718        buf.mark_interrupted();
719        buf.cut_current_model_turn(0);
720        assert!(buf.end_turn().is_none(), "nothing was heard or said before");
721        assert!(buf.has_pending());
722        buf.push_output("Five, got it.");
723        assert_eq!(buf.end_turn().unwrap().user, "Actually, five people.");
724    }
725}