Skip to main content

infr_chat/
stream.rs

1//! Streaming reasoning/content splitter — THE single place model output is separated into
2//! reasoning vs answer (vs tool calls) as it streams. `infr run` (display styling), `infr serve`
3//! (OpenAI deltas) and the history stripper all consume this module, so every thinking model is
4//! exposed the same way on every surface; a new reasoning format (e.g. channel markers) lands
5//! here once and everywhere at once.
6
7/// Does this rendered prompt end with a `<think>` PREFILL (the template opened the reasoning
8/// block itself — Qwen3.5 style — so the model's output starts MID-reasoning with only
9/// the close marker)? Callers inject a synthetic `"<think>"` piece at the head of the stream when
10/// this is true, so the streaming splitter, the display styler and the history stripper all see a
11/// well-formed block through the one shared grammar.
12pub fn prompt_prefills_think(prompt: &str) -> bool {
13    prompt.trim_end().ends_with("<think>")
14}
15
16/// A streamed piece of a response.
17#[derive(Clone, Debug)]
18pub enum Delta {
19    Reasoning(String),
20    Content(String),
21    ToolCall {
22        name: String,
23        arguments: String,
24    },
25    /// One sampled token's log probability, emitted just before the [`Delta::Content`] that
26    /// carries its token's text, so a streaming server can attach it to that chunk. Only answer
27    /// tokens get one: a token whose text is reasoning, a `<think>` marker or a parsed tool call
28    /// is not part of `content`, and its entry is dropped.
29    Logprob(crate::TokenLogprob),
30}
31
32/// Incremental splitter for the streaming server path. Accumulates the raw decoded text and, on each
33/// piece, emits the newly-stable Reasoning (`<think>…</think>`) and Content deltas — holding back a
34/// marker-length tail so a partial `<think>`/`</think>`/`<tool_call>` marker is never emitted. Once a
35/// tool-call opener appears (and tool calls are allowed) it stops streaming content — matching every
36/// dialect `finish()` parses (Hermes `<tool_call>`, the pipe form `<|tool_call>`, and a Llama-3
37/// bare-JSON `{…}` body), so non-Hermes calls can't leak as content while also firing as a ToolCall.
38/// `finish()` flushes the held-back tails and parses the buffered tool call(s) into ToolCall deltas.
39pub struct ChatStream {
40    raw: String,
41    sent_r: usize, // reasoning bytes already emitted (offset within the reasoning region)
42    sent_c: usize, // content bytes already emitted (offset within the content region)
43    // Content before a `<think>` that does not open the reply, fixed once the opener is seen:
44    // `(stop, end)`, where `stop` is a tool-call opener in it (or `end`), and how much of it has
45    // been emitted.
46    lead: Option<(usize, usize)>,
47    sent_lead: usize,
48    // The whitespace the content emitted so far ends in (empty when it ends in a word), or `None`
49    // before any content: what a removed call's leading gap is judged against.
50    shown_gap: Option<String>,
51    allow_tools: bool,
52    // Per-marker cursors so `emit` doesn't re-`find` from offset 0 over the whole buffer on every
53    // pushed piece (that was O(n²) across a response). Each caches the first hit once found and
54    // otherwise resumes scanning from the previously-scanned tail.
55    cur_think_open: Cursor,
56    cur_think_close: Cursor,
57    cur_tool: Cursor,  // Hermes/Qwen `<tool_call>`
58    cur_pipe: Cursor,  // gemma4/E2B/DG `<|tool_call>`
59    cur_final: Cursor, // channel-format `<channel|>`
60    bare: BareJson,
61    /// Token log probabilities waiting for the content delta that carries their text.
62    logprobs: Vec<TokenSpan>,
63}
64
65/// The bytes of [`ChatStream::raw`] one group of sampled tokens produced, with their log
66/// probabilities.
67#[derive(Clone, Debug)]
68struct TokenSpan {
69    start: usize,
70    end: usize,
71    lps: Vec<crate::TokenLogprob>,
72}
73
74/// Incremental scan for a bare-JSON tool call at the head of a content region: skips leading
75/// whitespace, then tracks brace depth outside JSON strings until the first object closes. Each
76/// call scans only the bytes appended since the last, so streaming stays linear in the reply.
77#[derive(Default)]
78struct BareJson {
79    cs: Option<usize>, // the region start this state describes
80    scanned: usize,
81    head: BareHead,
82    depth: usize,
83    in_str: bool,
84    esc: bool,
85}
86
87#[derive(Default, Clone, Copy, PartialEq)]
88enum BareHead {
89    /// Only whitespace so far.
90    #[default]
91    Pending,
92    /// The region opens with `{` at this offset and the object has not closed yet.
93    Open(usize),
94    /// The first object closed and parses as a call; held until `finish` decides.
95    Call(usize),
96    /// Not a bare-JSON call: no leading `{`, or its first object is not a call.
97    No,
98}
99
100impl BareJson {
101    /// Where the region at `cs` opens a possible bare-JSON call, or `None` once it cannot be one.
102    fn open(&mut self, raw: &str, cs: usize) -> Option<usize> {
103        if self.cs != Some(cs) {
104            *self = Self {
105                cs: Some(cs),
106                scanned: cs,
107                ..Self::default()
108            };
109        }
110        let bytes = raw.as_bytes();
111        while self.scanned < bytes.len() {
112            let i = self.scanned;
113            let b = bytes[i];
114            self.scanned += 1;
115            match self.head {
116                BareHead::Pending => match b {
117                    b' ' | b'\n' | b'\t' | b'\r' => {}
118                    b'{' => {
119                        self.head = BareHead::Open(i);
120                        self.depth = 1;
121                    }
122                    _ => self.head = BareHead::No,
123                },
124                BareHead::Open(start) => {
125                    if self.in_str {
126                        match b {
127                            _ if self.esc => self.esc = false,
128                            b'\\' => self.esc = true,
129                            b'"' => self.in_str = false,
130                            _ => {}
131                        }
132                    } else {
133                        match b {
134                            b'"' => self.in_str = true,
135                            b'{' => self.depth += 1,
136                            b'}' => {
137                                self.depth -= 1;
138                                if self.depth == 0 {
139                                    // A call must be the whole region, so the first object
140                                    // decides: one that is not a call means none is coming.
141                                    let call = crate::tools::parse_bare_json_call(&raw[start..=i]);
142                                    self.head = if call.is_some() {
143                                        BareHead::Call(start)
144                                    } else {
145                                        BareHead::No
146                                    };
147                                }
148                            }
149                            _ => {}
150                        }
151                    }
152                }
153                BareHead::Call(_) | BareHead::No => {
154                    self.scanned = bytes.len();
155                }
156            }
157        }
158        match self.head {
159            BareHead::Open(i) | BareHead::Call(i) => Some(i),
160            BareHead::Pending | BareHead::No => None,
161        }
162    }
163}
164
165/// A forward-only search for a fixed `needle` in an append-only buffer: once the needle is found its
166/// byte offset is cached; until then, each call resumes scanning from just before the previously
167/// scanned tail (so a needle straddling the append boundary is still caught).
168#[derive(Default)]
169struct Cursor {
170    off: Option<usize>,
171    scanned: usize,
172}
173
174impl Cursor {
175    fn find(&mut self, raw: &str, needle: &str) -> Option<usize> {
176        self.find_from(raw, needle, 0)
177    }
178
179    /// [`Cursor::find`] for hits at or after `from` only. A cached hit below `from` is dropped and
180    /// the search resumes at `from`: latching it would answer "no hit" forever after, which is how a
181    /// `<tool_call>` quoted in the reasoning hid the real call in the content region.
182    fn find_from(&mut self, raw: &str, needle: &str, from: usize) -> Option<usize> {
183        match self.off {
184            Some(p) if p >= from => return Some(p),
185            Some(_) => {
186                self.off = None;
187                self.scanned = from;
188            }
189            None => {}
190        }
191        let mut start = self
192            .scanned
193            .saturating_sub(needle.len().saturating_sub(1))
194            .max(from);
195        while start > from && !raw.is_char_boundary(start) {
196            start -= 1;
197        }
198        if let Some(p) = raw[start..].find(needle) {
199            self.off = Some(start + p);
200        }
201        self.scanned = raw.len();
202        self.off
203    }
204}
205
206impl ChatStream {
207    pub fn new(allow_tools: bool) -> Self {
208        Self {
209            raw: String::new(),
210            sent_r: 0,
211            sent_c: 0,
212            lead: None,
213            sent_lead: 0,
214            shown_gap: None,
215            allow_tools,
216            cur_think_open: Cursor::default(),
217            cur_think_close: Cursor::default(),
218            cur_tool: Cursor::default(),
219            cur_pipe: Cursor::default(),
220            cur_final: Cursor::default(),
221            bare: BareJson::default(),
222            logprobs: Vec::new(),
223        }
224    }
225
226    /// [`push`](Self::push) with the log probabilities of the tokens that produced `piece`. The
227    /// entries ride, ahead of it, the first content delta that carries any of the piece's text.
228    /// While streaming, a delta does not split the piece — the splitter backs its safe end up to
229    /// the piece's start — so a chunk's `content` and `logprobs.content` describe the same tokens.
230    /// A piece that straddles a region's end (a reasoning or tool-call marker) is split there, and
231    /// its entries ride the part that is content. The piece is the unit because only the decoder
232    /// knows how its tokens' bytes became text.
233    pub fn push_with_logprobs(
234        &mut self,
235        piece: &str,
236        logprobs: Vec<crate::TokenLogprob>,
237        on_delta: &mut dyn FnMut(Delta),
238    ) {
239        let start = self.raw.len();
240        self.raw.push_str(piece);
241        if !logprobs.is_empty() && !piece.is_empty() {
242            self.logprobs.push(TokenSpan {
243                start,
244                end: self.raw.len(),
245                lps: logprobs,
246            });
247        }
248        self.emit(false, on_delta);
249    }
250
251    /// How many token groups are waiting for their content delta.
252    #[cfg(test)]
253    fn queued_logprobs(&self) -> usize {
254        self.logprobs.len()
255    }
256
257    pub fn push(&mut self, piece: &str, on_delta: &mut dyn FnMut(Delta)) {
258        self.raw.push_str(piece);
259        self.emit(false, on_delta);
260    }
261
262    /// Flush the held-back tails (no marker can still be forming) and settle every stretch that
263    /// streaming held back from a tool-call opener: its calls fire, or it is emitted as content
264    /// when it holds none.
265    pub fn finish(&mut self, on_delta: &mut dyn FnMut(Delta)) {
266        self.emit(true, on_delta);
267        // What is left never reached `content` (reasoning, a marker, a parsed-away call).
268        self.logprobs.clear();
269    }
270
271    /// The earliest tool-call opener at/after `cs`, across every dialect `finish()` parses — Hermes
272    /// `<tool_call>`, the pipe form `<|tool_call>`, and (when the content region begins with `{`) a
273    /// Llama-3 bare-JSON call. Returns `None` when tools aren't allowed or no opener is present, so
274    /// the content region runs to the buffer end. Matching `finish()`'s dialect set here is what
275    /// stops non-Hermes calls from leaking as `Delta::Content` while also firing as `Delta::ToolCall`.
276    fn tool_open_at(&mut self, cs: usize, final_flush: bool) -> Option<usize> {
277        if !self.allow_tools {
278            return None;
279        }
280        const TL: &str = "<tool_call>";
281        const PIPE: &str = "<|tool_call>";
282        let hermes = self.cur_tool.find_from(&self.raw, TL, cs);
283        let pipe = self.cur_pipe.find_from(&self.raw, PIPE, cs);
284        let bare = self.bare_json_open(cs, final_flush);
285        [hermes, pipe, bare].into_iter().flatten().min()
286    }
287
288    /// Position of a bare-JSON (`{…}`) tool-call opener in the content region starting at `cs`, or
289    /// `None`. Scoped to the leading `{` of the region (skipping only whitespace) so ordinary prose
290    /// that merely *contains* a brace is never suppressed. During streaming a leading `{` is held
291    /// back until its first object closes ([`BareJson`]): one that is not a call streams as content
292    /// from then on, instead of the whole reply arriving as one chunk at `finish`. On the final
293    /// flush it's confirmed a real call via [`crate::tools::parse_bare_json_call`] so a leading
294    /// brace that isn't a call still streams as content instead of being dropped.
295    fn bare_json_open(&mut self, cs: usize, final_flush: bool) -> Option<usize> {
296        let i = self.bare.open(&self.raw, cs)?;
297        if final_flush && crate::tools::parse_bare_json_call(&self.raw[i..]).is_none() {
298            return None; // leading `{` but not actually a call — let it stream as content
299        }
300        Some(i)
301    }
302
303    fn emit(&mut self, final_flush: bool, on_delta: &mut dyn FnMut(Delta)) {
304        let mut logprobs = std::mem::take(&mut self.logprobs);
305        self.emit_with(final_flush, on_delta, &mut logprobs);
306        self.logprobs = logprobs;
307    }
308
309    fn emit_with(
310        &mut self,
311        final_flush: bool,
312        on_delta: &mut dyn FnMut(Delta),
313        logprobs: &mut Vec<TokenSpan>,
314    ) {
315        const TO: &str = "<think>";
316        const TC: &str = "</think>";
317        // Channel-format head (E2B/gpt-oss: `<|channel>thought…<channel|>answer`): reasoning runs
318        // from after the thought marker to the final-answer marker, content after it. While the
319        // head could still be a forming marker, hold everything back.
320        const FINAL: &str = "<channel|>";
321        if let Some(hm) = channel_thought_head(&self.raw) {
322            let (r_end, hold, c_start) = match self.cur_final.find(&self.raw, FINAL) {
323                Some(f) => (f, false, Some(f + FINAL.len())),
324                None => (self.raw.len(), !final_flush, None),
325            };
326            emit_region(
327                &self.raw,
328                hm,
329                r_end,
330                hold,
331                &mut self.sent_r,
332                true,
333                on_delta,
334                logprobs,
335            );
336            if let Some(cs) = c_start {
337                self.emit_content(cs, final_flush, on_delta, logprobs);
338            }
339            return;
340        }
341        if !final_flush
342            && CHANNEL_THOUGHT.iter().any(|m| {
343                m.as_bytes()
344                    .starts_with(&self.raw.as_bytes()[..self.raw.len().min(m.len())])
345            })
346            && self.raw.len() < CHANNEL_THOUGHT[0].len()
347        {
348            return; // head could still become a channel marker — hold
349        }
350        let think_open = self.cur_think_open.find(&self.raw, TO);
351        // Only a closer after the opener closes the reasoning. One with no opener before it is
352        // text: content already streamed cannot be taken back as reasoning, so reading it any
353        // other way would make the reply depend on how its text was chunked.
354        let think_close =
355            think_open.and_then(|to| self.cur_think_close.find_from(&self.raw, TC, to + TO.len()));
356        // Content before a `<think>` later in the reply. Until the opener arrives it streamed as
357        // the content region at offset 0, so that region's progress carries over; its end is then
358        // fixed, and streaming stops at a tool-call opener in it.
359        let lead = think_open.map(|to| match self.lead {
360            Some(lead) => lead,
361            None => {
362                self.sent_lead = std::mem::take(&mut self.sent_c);
363                // The streaming rule even on the final flush: a held opener is judged by
364                // `settle_held` on the lead-in alone, never with the `<think>` text after it.
365                let stop = match to {
366                    0 => 0,
367                    _ => self.tool_open_at(0, false).map_or(to, |t| t.min(to)),
368                };
369                self.lead = Some((stop, to));
370                (stop, to)
371            }
372        });
373        if let Some((stop, end)) = lead {
374            let unsent = self.sent_lead < end;
375            let from = self.sent_lead;
376            emit_region(
377                &self.raw,
378                0,
379                stop,
380                false,
381                &mut self.sent_lead,
382                false,
383                on_delta,
384                logprobs,
385            );
386            note_shown(&mut self.shown_gap, &self.raw[from..self.sent_lead]);
387            // The lead-in ends at `<think>`, so a stretch held at an opener in it is complete the
388            // moment the opener arrives: settle it now, ahead of the reasoning that follows it.
389            // Content follows after the reasoning, so its end is not the reply's.
390            if unsent && stop < end {
391                settle_held(
392                    &self.raw[stop..end],
393                    &mut self.shown_gap,
394                    false,
395                    on_delta,
396                    logprobs,
397                    stop,
398                );
399                self.sent_lead = end;
400            }
401        }
402        // Reasoning region: between `<think>` and `</think>` (or end, while still thinking).
403        if let Some(to) = think_open {
404            let rs = to + TO.len();
405            let (r_end, hold) = match think_close {
406                Some(tc) => (tc, false),
407                None => (self.raw.len(), !final_flush),
408            };
409            emit_region(
410                &self.raw,
411                rs,
412                r_end,
413                hold,
414                &mut self.sent_r,
415                true,
416                on_delta,
417                logprobs,
418            );
419        }
420        // Content region: after `</think>` (or from the start when there's no `<think>` at all), up to
421        // a tool-call opener (whose block is buffered, not streamed) or the end.
422        let c_start = match think_close {
423            Some(tc) => Some(tc + TC.len()),
424            None if think_open.is_none() => Some(0),
425            None => None,
426        };
427        if let Some(cs) = c_start {
428            self.emit_content(cs, final_flush, on_delta, logprobs);
429        }
430    }
431
432    /// Stream the content region starting at `cs` up to its first tool-call opener. On the final
433    /// flush the stretch from that opener on is settled ([`settle_held`]).
434    fn emit_content(
435        &mut self,
436        cs: usize,
437        final_flush: bool,
438        on_delta: &mut dyn FnMut(Delta),
439        logprobs: &mut Vec<TokenSpan>,
440    ) {
441        let tool_open = self.tool_open_at(cs, final_flush).filter(|&t| t >= cs);
442        let (c_end, hold) = match tool_open {
443            Some(t) => (t, false),
444            None => (self.raw.len(), !final_flush),
445        };
446        let from = cs + self.sent_c;
447        emit_region(
448            &self.raw,
449            cs,
450            c_end,
451            hold,
452            &mut self.sent_c,
453            false,
454            on_delta,
455            logprobs,
456        );
457        note_shown(&mut self.shown_gap, &self.raw[from..cs + self.sent_c]);
458        if let (true, Some(t)) = (final_flush, tool_open) {
459            settle_held(
460                &self.raw[t..],
461                &mut self.shown_gap,
462                true,
463                on_delta,
464                logprobs,
465                t,
466            );
467        }
468    }
469}
470
471/// Settle a stretch streaming held back from a tool-call opener, in textual order. A `<think>`
472/// span in it is reasoning, not content, and goes out as such where it sits. Every call in the
473/// rest fires (after the stretch's text), and what is not a call is emitted as content verbatim:
474/// prose around the calls, and any block that did not parse (see
475/// [`crate::parse_hermes_tool_calls`]) — nothing the model wrote is dropped, and a stretch with no
476/// call is emitted byte for byte.
477///
478/// Whitespace is touched only at an edge a removed call left (between two calls the parser itself
479/// leaves one gap). A call that opens a text span leaves the gap after it judged against what the
480/// reader already has (`shown_gap`, kept up to date here): nothing shown yet, or a gap there
481/// already, and it goes — unless it holds a line break the shown gap lacks. A call that closes the
482/// stretch's last text span at the end of the reply (`at_end`) takes the whitespace after it too.
483fn settle_held(
484    held: &str,
485    shown_gap: &mut Option<String>,
486    at_end: bool,
487    on_delta: &mut dyn FnMut(Delta),
488    logprobs: &mut Vec<TokenSpan>,
489    base: usize,
490) {
491    let mut fired = Vec::new();
492    let spans = reasoning_spans(held);
493    // Only the stretch's last text span can end the reply; an earlier one is followed by more.
494    let last_text = spans.iter().rposition(|s| matches!(s, Span::Text(..)));
495    for (i, span) in spans.into_iter().enumerate() {
496        let (at, text) = match span {
497            Span::Reasoning(r) => {
498                if !r.is_empty() {
499                    on_delta(Delta::Reasoning(r.to_owned()));
500                }
501                continue;
502            }
503            Span::Text(off, t) => (base + off, t),
504        };
505        // Dialect-aware: hermes JSON + qwen3.5/3.6 XML + gemma pipe-marker + llama3 bare JSON
506        // (hermes-only here silently dropped every non-qwen3 model's calls over serve). The
507        // parse records where kept bytes came from only when there are entries to place.
508        let (clean, calls) = if logprobs.is_empty() {
509            let (clean, calls) = crate::tools::parse_any_tool_calls_traced::<()>(text);
510            (
511                crate::tools::Traced {
512                    text: clean.text,
513                    origin: crate::tools::Origins::new(),
514                },
515                calls,
516            )
517        } else {
518            crate::tools::parse_any_tool_calls_traced::<crate::tools::Origins>(text)
519        };
520        let content = if calls.is_empty() {
521            // Emitted verbatim, so the entries of the tokens it holds ride it.
522            if !text.is_empty() {
523                emit_logprobs(
524                    logprobs,
525                    |s| s.start < at + text.len() && s.end > at,
526                    on_delta,
527                );
528            }
529            text
530        } else {
531            let (opens_with_cut, closes_with_cut) = cut_edges(text, &clean.text);
532            let (mut lo, mut hi) = (0, clean.text.len());
533            if opens_with_cut {
534                let rest = clean.text.trim_start();
535                let gap = &clean.text[..clean.text.len() - rest.len()];
536                let keep = match shown_gap.as_deref() {
537                    None => false,
538                    Some("") => true,
539                    Some(shown) => gap.contains('\n') && !shown.contains('\n'),
540                };
541                if !keep {
542                    lo = gap.len();
543                }
544            }
545            if at_end && closes_with_cut && Some(i) == last_text {
546                hi = lo + clean.text[lo..].trim_end().len();
547            }
548            // The parser only removes text and rewrites whitespace at a cut, and it traces where
549            // each byte it kept came from: a token is part of this content when any of its bytes
550            // made it in. A space the parser wrote itself belongs to no token.
551            let kept: Vec<usize> = clean
552                .origin
553                .get(lo..hi)
554                .unwrap_or_default()
555                .iter()
556                .flatten()
557                .map(|&o| at + o)
558                .collect();
559            if !kept.is_empty() {
560                emit_logprobs(
561                    logprobs,
562                    // `kept` ascends: the parser keeps bytes in their order.
563                    |s| {
564                        kept.get(kept.partition_point(|&o| o < s.start))
565                            .is_some_and(|&o| o < s.end)
566                    },
567                    on_delta,
568                );
569            }
570            &clean.text[lo..hi]
571        };
572        if !content.is_empty() {
573            note_shown(shown_gap, content);
574            on_delta(Delta::Content(content.to_owned()));
575        }
576        fired.extend(calls);
577    }
578    // The rest of the stretch is reasoning, markers or calls, none of which is content. A group
579    // that runs on past the stretch's end stays for the content it may still reach.
580    let end = base + held.len();
581    logprobs.retain(|s| s.start < base || s.end > end);
582    for call in fired {
583        on_delta(Delta::ToolCall {
584            name: call.name,
585            arguments: serde_json::to_string(&call.arguments).unwrap_or_else(|_| "{}".to_string()),
586        });
587    }
588}
589
590/// Whether removing calls from `text` (leaving `clean`) cut at its very start and at its very end:
591/// all that precedes the first difference, or follows the last, is whitespace.
592fn cut_edges(text: &str, clean: &str) -> (bool, bool) {
593    let head = text
594        .char_indices()
595        .zip(clean.chars())
596        .find(|((_, a), b)| a != b)
597        .map_or(clean.len().min(text.len()), |((i, _), _)| i);
598    let tail = text
599        .char_indices()
600        .rev()
601        .zip(clean.chars().rev())
602        .find(|((_, a), b)| a != b)
603        .map_or(text.len() - clean.len().min(text.len()), |((i, a), _)| {
604            i + a.len_utf8()
605        });
606    (
607        text[..head].trim().is_empty(),
608        text[tail..].trim().is_empty(),
609    )
610}
611
612/// Record that `text` was emitted as content: the whitespace the shown content now ends in.
613fn note_shown(gap: &mut Option<String>, text: &str) {
614    if text.is_empty() {
615        return;
616    }
617    let word = text.trim_end();
618    if word.is_empty() {
619        gap.get_or_insert_with(String::new).push_str(text);
620    } else {
621        *gap = Some(text[word.len()..].to_owned());
622    }
623}
624
625/// One stretch of a held span: text, with its offset in the span, or the inside of a
626/// `<think>…</think>`.
627enum Span<'a> {
628    Text(usize, &'a str),
629    Reasoning(&'a str),
630}
631
632/// `text` split at its `<think>…</think>` spans (an unclosed one runs to the end), in order.
633fn reasoning_spans(text: &str) -> Vec<Span<'_>> {
634    const TO: &str = "<think>";
635    const TC: &str = "</think>";
636    let mut out = Vec::new();
637    let mut at = 0;
638    while let Some(o) = text[at..].find(TO) {
639        out.push(Span::Text(at, &text[at..at + o]));
640        let inner = at + o + TO.len();
641        let Some(c) = text[inner..].find(TC) else {
642            out.push(Span::Reasoning(&text[inner..]));
643            return out;
644        };
645        out.push(Span::Reasoning(&text[inner..inner + c]));
646        at = inner + c + TC.len();
647    }
648    out.push(Span::Text(at, &text[at..]));
649    out
650}
651
652/// The heads that put a reply in the channel format (E2B/gpt-oss): reasoning after the thought
653/// marker, the answer after `<channel|>`.
654const CHANNEL_THOUGHT: [&str; 2] = ["<|channel|>thought", "<|channel>thought"];
655
656/// The length of the channel-format head `raw` starts with, or `None` for any other reply. THE test
657/// for "this reply is in the channel format": streaming and [`ChatStream::finish`] both use it, so
658/// they cannot disagree about where the content — and so a tool call — can be.
659fn channel_thought_head(raw: &str) -> Option<usize> {
660    CHANNEL_THOUGHT
661        .iter()
662        .find_map(|m| raw.starts_with(m).then_some(m.len()))
663}
664
665/// Emit, in order, the entries of every token group `in_content` picks — those whose text the
666/// content delta about to go out carries — and forget them. Called just before that delta.
667fn emit_logprobs(
668    logprobs: &mut Vec<TokenSpan>,
669    in_content: impl Fn(&TokenSpan) -> bool,
670    on_delta: &mut dyn FnMut(Delta),
671) {
672    logprobs.retain_mut(|s| {
673        if in_content(s) {
674            for lp in s.lps.drain(..) {
675                on_delta(Delta::Logprob(lp));
676            }
677            false
678        } else {
679            true
680        }
681    });
682}
683
684/// Emit the not-yet-sent slice of `raw[region_start .. region_end]` (past `*sent` bytes), holding back
685/// a marker-length tail when `hold` (so a partial marker isn't emitted mid-stream), clamped to a UTF-8
686/// boundary. Advances `*sent`.
687#[allow(clippy::too_many_arguments)]
688fn emit_region(
689    raw: &str,
690    region_start: usize,
691    region_end: usize,
692    hold: bool,
693    sent: &mut usize,
694    reasoning: bool,
695    on_delta: &mut dyn FnMut(Delta),
696    logprobs: &mut Vec<TokenSpan>,
697) {
698    const HOLD: usize = 12; // > the longest marker, so a partial one never streams
699    let abs = region_start + *sent;
700    if abs >= region_end {
701        return;
702    }
703    let mut end = if hold {
704        region_end.saturating_sub(HOLD).max(abs)
705    } else {
706        region_end
707    };
708    // Never split a token group across two content deltas: back the cut up to the start of the
709    // group it falls in. When that is at or before where this delta starts, hold the text until
710    // the next push. A cut at the region's own end is structural and stands. Reasoning carries no
711    // entries, so it is cut anywhere.
712    if !reasoning && !(!hold && end == region_end) {
713        if let Some(s) = logprobs.iter().find(|s| s.start < end && s.end > end) {
714            if s.start <= abs {
715                return;
716            }
717            end = s.start;
718        }
719    }
720    while end > abs && !raw.is_char_boundary(end) {
721        end -= 1;
722    }
723    if end <= abs {
724        return;
725    }
726    if reasoning {
727        // A group wholly inside reasoning that has gone out can never be content: forget it now,
728        // so a long reasoning span does not leave every content delta scanning its tokens.
729        logprobs.retain(|s| s.start < region_start || s.end > end);
730    } else {
731        emit_logprobs(logprobs, |s| s.start < end && s.end > abs, on_delta);
732    }
733    let text = &raw[abs..end];
734    if text.is_empty() {
735        return;
736    }
737    on_delta(if reasoning {
738        Delta::Reasoning(text.to_owned())
739    } else {
740        Delta::Content(text.to_owned())
741    });
742    *sent += text.len();
743}
744
745#[cfg(test)]
746mod chat_stream_tests {
747    use super::*;
748
749    /// Feed `pieces` through a `ChatStream` and collect every emitted delta (streaming + finish).
750    fn run(pieces: &[&str], allow_tools: bool) -> (String, String, Vec<(String, String)>) {
751        let mut out: Vec<Delta> = Vec::new();
752        let mut s = ChatStream::new(allow_tools);
753        {
754            let mut od = |d: Delta| out.push(d);
755            for p in pieces {
756                s.push(p, &mut od);
757            }
758        }
759        s.finish(&mut |d: Delta| out.push(d));
760        let (mut r, mut c, mut t) = (String::new(), String::new(), Vec::new());
761        for d in &out {
762            match d {
763                Delta::Reasoning(x) => r.push_str(x),
764                Delta::Content(x) => c.push_str(x),
765                Delta::ToolCall { name, arguments } => t.push((name.clone(), arguments.clone())),
766                Delta::Logprob(_) => {}
767            }
768        }
769        (r, c, t)
770    }
771
772    #[test]
773    fn logprobs_ride_the_token_aligned_content_chunks() {
774        fn lp(c: char) -> crate::TokenLogprob {
775            crate::TokenLogprob {
776                token: c as u32,
777                text: c.to_string(),
778                bytes: c.to_string().into_bytes(),
779                logprob: -0.5,
780                top: Vec::new(),
781            }
782        }
783        let mut out: Vec<Delta> = Vec::new();
784        let mut s = ChatStream::new(false);
785        for c in "abcdefghijklmnop".chars() {
786            s.push_with_logprobs(&c.to_string(), vec![lp(c)], &mut |d| out.push(d));
787        }
788        s.finish(&mut |d| out.push(d));
789
790        let mut queued: Vec<String> = Vec::new();
791        let mut content = String::new();
792        for d in out {
793            match d {
794                Delta::Logprob(lp) => queued.push(lp.text),
795                Delta::Content(text) => {
796                    assert_eq!(
797                        queued.len(),
798                        text.chars().count(),
799                        "chunk {text:?} has {queued:?}"
800                    );
801                    for (lp, c) in queued.drain(..).zip(text.chars()) {
802                        assert_eq!(lp, c.to_string());
803                    }
804                    content.push_str(&text);
805                }
806                other => panic!("unexpected {other:?}"),
807            }
808        }
809        assert_eq!(content, "abcdefghijklmnop");
810        assert!(queued.is_empty());
811    }
812
813    /// Feed `(piece, token id)` pairs, one token per piece, and pair every content delta with the
814    /// entries emitted just ahead of it, as the server builds its chunks. An entry that is not
815    /// followed by content, or is left over at the end, fails the test.
816    fn content_chunks(pieces: &[(&str, u32)], allow_tools: bool) -> Vec<(String, Vec<u32>)> {
817        let mut out: Vec<Delta> = Vec::new();
818        let mut s = ChatStream::new(allow_tools);
819        for &(piece, id) in pieces {
820            let lp = crate::TokenLogprob {
821                token: id,
822                text: piece.to_owned(),
823                bytes: piece.as_bytes().to_vec(),
824                logprob: -1.0,
825                top: Vec::new(),
826            };
827            s.push_with_logprobs(piece, vec![lp], &mut |d| out.push(d));
828        }
829        s.finish(&mut |d| out.push(d));
830        let mut chunks = Vec::new();
831        let mut queued = Vec::new();
832        for d in out {
833            match d {
834                Delta::Logprob(lp) => queued.push(lp.token),
835                Delta::Content(text) => chunks.push((text, std::mem::take(&mut queued))),
836                other => assert!(queued.is_empty(), "{queued:?} rode {other:?}"),
837            }
838        }
839        assert!(queued.is_empty(), "{queued:?} were left with no content");
840        chunks
841    }
842
843    /// `logprobs.content` describes `content`: the reasoning, and the `<think>` markers around
844    /// it, are not the answer, so their tokens report nothing, and the answer's entries come in
845    /// order on the chunks that carry their text.
846    #[test]
847    fn logprobs_cover_the_answer_and_not_the_reasoning() {
848        let chunks = content_chunks(
849            &[
850                ("<think>", 1),
851                ("\nhmm", 2),
852                ("</think>", 3),
853                ("\n\nYes", 4),
854                (", it", 5),
855                (" is.", 6),
856            ],
857            false,
858        );
859        let ids: Vec<u32> = chunks.iter().flat_map(|c| c.1.clone()).collect();
860        assert_eq!(ids, [4, 5, 6]);
861        let text: String = chunks.iter().map(|c| c.0.as_str()).collect();
862        assert_eq!(text, "\n\nYes, it is.");
863        for (text, ids) in &chunks {
864            assert!(!ids.is_empty(), "{text:?} has no entries");
865        }
866    }
867
868    /// Prose between and after parsed calls is content, and carries its tokens' entries: the
869    /// parser traces each byte it keeps back to the reply. The calls' tokens, and whitespace the
870    /// cut dropped, report nothing.
871    #[test]
872    fn prose_around_parsed_calls_keeps_its_entries() {
873        const CALL: &str = "{\"name\": \"f\", \"arguments\": {}}";
874        let chunks = content_chunks(
875            &[
876                ("A", 1),
877                ("<tool_call>", 2),
878                (CALL, 3),
879                ("</tool_call>", 4),
880                (" then", 5),
881                ("<tool_call>", 6),
882                (CALL, 7),
883                ("</tool_call>", 8),
884                (" done.", 9),
885            ],
886            true,
887        );
888        assert_eq!(
889            chunks,
890            [
891                ("A".to_owned(), vec![1]),
892                (" then done.".to_owned(), vec![5, 9])
893            ]
894        );
895
896        // A call that opens the reply: the line break after it is cut, so its token reports
897        // nothing; the text after it does.
898        let chunks = content_chunks(
899            &[
900                ("<tool_call>", 1),
901                (CALL, 2),
902                ("</tool_call>", 3),
903                ("\n", 4),
904                ("Done", 5),
905                (".", 6),
906            ],
907            true,
908        );
909        assert_eq!(chunks, [("Done.".to_owned(), vec![5, 6])]);
910    }
911
912    /// A group that runs from a held stretch through a whole `<think>…</think>` into later
913    /// content keeps its entry for that content, rather than being dropped with the stretch.
914    #[test]
915    fn a_group_past_a_settled_stretch_keeps_its_entry() {
916        let chunks = content_chunks(
917            &[
918                ("Hi ", 1),
919                ("<tool_call>", 2),
920                ("{\"name\": \"f\", \"arguments\": {}}", 3),
921                ("</tool_call><think>r</think>Done", 4),
922            ],
923            true,
924        );
925        assert_eq!(
926            chunks,
927            [("Hi ".to_owned(), vec![1]), ("Done".to_owned(), vec![4])]
928        );
929    }
930
931    /// The entries of reasoning tokens are dropped as their reasoning goes out, so the queue
932    /// holds only what is still pending however long the reasoning runs.
933    #[test]
934    fn reasoning_entries_do_not_pile_up() {
935        let lp = |id: u32, text: &str| crate::TokenLogprob {
936            token: id,
937            text: text.to_owned(),
938            bytes: text.as_bytes().to_vec(),
939            logprob: -1.0,
940            top: Vec::new(),
941        };
942        let mut s = ChatStream::new(false);
943        let mut out = Vec::new();
944        s.push_with_logprobs("<think>", vec![lp(0, "<think>")], &mut |d| out.push(d));
945        let mut most = 0;
946        for i in 1..=2000 {
947            s.push_with_logprobs("word ", vec![lp(i, "word ")], &mut |d| out.push(d));
948            most = most.max(s.queued_logprobs());
949        }
950        // The opener's group, and the few the reasoning's held-back tail still covers.
951        assert!(most <= 5, "the queue reached {most}");
952        s.push_with_logprobs("</think>", vec![lp(9000, "</think>")], &mut |d| out.push(d));
953        s.push_with_logprobs("Answer", vec![lp(9001, "Answer")], &mut |d| out.push(d));
954        s.finish(&mut |d| out.push(d));
955        let ids: Vec<u32> = out
956            .iter()
957            .filter_map(|d| match d {
958                Delta::Logprob(lp) => Some(lp.token),
959                _ => None,
960            })
961            .collect();
962        assert_eq!(ids, [9001]);
963    }
964
965    /// A `</think>` with no opener before it, after content has streamed: no panic, and the
966    /// closer is text.
967    #[test]
968    fn a_stray_closer_after_streamed_content_does_not_panic() {
969        let (r, c, _) = run(&["abcdefghijklmnopqrstuvwxyz", "</think>"], false);
970        assert_eq!(r, "");
971        assert_eq!(c, "abcdefghijklmnopqrstuvwxyz</think>");
972    }
973
974    /// The same reply pushed whole, a character at a time, and in uneven pieces gives the same
975    /// reasoning, content and calls, with and without logprob entries — stray closers included.
976    #[test]
977    fn output_does_not_depend_on_chunking() {
978        let replies = [
979            "abcdefghijklmnopqrstuvwxyz</think>",
980            "abc</think>def",
981            "x</think>y<think>r</think>z",
982            "</think></think>a",
983            "<think>r</think>a</think>b",
984            "lead</think> <think>think</think>\n\nanswer",
985            "Hi <tool_call>{\"name\": \"f\", \"arguments\": {}}</tool_call></think>done",
986            "<think>why</think>\n\n{\"name\": \"f\", \"arguments\": {}}",
987        ];
988        fn feed(pieces: &[&str], tools: bool, entries: bool) -> (String, String, String) {
989            let mut out = Vec::new();
990            let mut s = ChatStream::new(tools);
991            for (i, p) in pieces.iter().enumerate() {
992                let lps = if entries {
993                    vec![crate::TokenLogprob {
994                        token: i as u32,
995                        text: p.to_string(),
996                        bytes: p.as_bytes().to_vec(),
997                        logprob: -1.0,
998                        top: Vec::new(),
999                    }]
1000                } else {
1001                    Vec::new()
1002                };
1003                s.push_with_logprobs(p, lps, &mut |d| out.push(d));
1004            }
1005            s.finish(&mut |d| out.push(d));
1006            let (mut r, mut c, mut t) = (String::new(), String::new(), String::new());
1007            for d in out {
1008                match d {
1009                    Delta::Reasoning(x) => r.push_str(&x),
1010                    Delta::Content(x) => c.push_str(&x),
1011                    Delta::ToolCall { name, arguments } => {
1012                        t.push_str(&format!("{name}{arguments};"))
1013                    }
1014                    Delta::Logprob(_) => {}
1015                }
1016            }
1017            (r, c, t)
1018        }
1019        let mut state = 0x2545_F491_4F6C_DD1Du64;
1020        for reply in replies {
1021            let chars: Vec<(usize, char)> = reply.char_indices().collect();
1022            let bytewise: Vec<&str> = chars
1023                .iter()
1024                .map(|&(i, ch)| &reply[i..i + ch.len_utf8()])
1025                .collect();
1026            let mut uneven = Vec::new();
1027            let mut at = 0;
1028            while at < reply.len() {
1029                state ^= state << 13;
1030                state ^= state >> 7;
1031                state ^= state << 17;
1032                let mut end = (at + 1 + (state % 7) as usize).min(reply.len());
1033                while !reply.is_char_boundary(end) {
1034                    end += 1;
1035                }
1036                uneven.push(&reply[at..end]);
1037                at = end;
1038            }
1039            for tools in [false, true] {
1040                for entries in [false, true] {
1041                    let whole = feed(&[reply], tools, entries);
1042                    assert_eq!(
1043                        feed(&bytewise, tools, entries),
1044                        whole,
1045                        "{reply:?} char by char, tools {tools}, entries {entries}"
1046                    );
1047                    assert_eq!(
1048                        feed(&uneven, tools, entries),
1049                        whole,
1050                        "{reply:?} in {uneven:?}, tools {tools}, entries {entries}"
1051                    );
1052                }
1053            }
1054        }
1055    }
1056
1057    /// A held stretch that turns out to hold no call goes out verbatim with its tokens' entries;
1058    /// a parsed call's tokens are not content and report nothing.
1059    #[test]
1060    fn logprobs_follow_settled_text_and_skip_parsed_calls() {
1061        let chunks = content_chunks(&[("Hi ", 1), ("<tool_call>", 2), ("oops", 3)], true);
1062        let ids: Vec<u32> = chunks.iter().flat_map(|c| c.1.clone()).collect();
1063        assert_eq!(ids, [1, 2, 3]);
1064        let text: String = chunks.iter().map(|c| c.0.as_str()).collect();
1065        assert_eq!(text, "Hi <tool_call>oops");
1066
1067        let chunks = content_chunks(
1068            &[
1069                ("Sure", 1),
1070                ("<tool_call>", 2),
1071                ("{\"name\": \"f\", \"arguments\": {}}", 3),
1072                ("</tool_call>", 4),
1073            ],
1074            true,
1075        );
1076        assert_eq!(chunks, [("Sure".to_owned(), vec![1])]);
1077    }
1078
1079    #[test]
1080    fn streams_channel_thought_then_final() {
1081        // E2B/gpt-oss channel format: reasoning after the thought marker, content after the
1082        // final-answer marker — streamed as Reasoning/Content like the <think> form.
1083        let (r, c, t) = run(
1084            &[
1085                "<|channel>th",
1086                "ought\nreaso",
1087                "ning<chan",
1088                "nel|>the answer",
1089            ],
1090            false,
1091        );
1092        assert_eq!(r.trim(), "reasoning");
1093        assert_eq!(c.trim(), "the answer");
1094        assert!(t.is_empty());
1095    }
1096
1097    #[test]
1098    fn prefilled_think_via_injected_opener() {
1099        // Template-prefilled thinking (Qwen3.5): the caller injects "<think>" before the model's
1100        // mid-reasoning output; the splitter then treats the head as Reasoning.
1101        let (r, c, t) = run(&["<think>", "reasoning here", "</think>", "answer"], false);
1102        assert_eq!(r.trim(), "reasoning here");
1103        assert_eq!(c.trim(), "answer");
1104        assert!(t.is_empty());
1105    }
1106
1107    #[test]
1108    fn streams_think_then_content() {
1109        let (r, c, t) = run(
1110            &["<think>", "reason", "ing", "</think>", "the ", "answer"],
1111            true,
1112        );
1113        assert_eq!(r.trim(), "reasoning");
1114        assert_eq!(c.trim(), "the answer");
1115        assert!(t.is_empty());
1116    }
1117
1118    #[test]
1119    fn plain_content_no_think() {
1120        let (r, c, _) = run(&["hello ", "world, this is a longer reply"], true);
1121        assert!(r.trim().is_empty());
1122        assert_eq!(c.trim(), "hello world, this is a longer reply");
1123    }
1124
1125    #[test]
1126    fn tool_call_buffered_and_parsed() {
1127        let (r, _c, t) = run(
1128            &[
1129                "<think>plan</think>",
1130                "<tool_call>\n{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}\n</tool_call>",
1131            ],
1132            true,
1133        );
1134        assert_eq!(r.trim(), "plan");
1135        assert_eq!(t.len(), 1);
1136        assert_eq!(t[0].0, "run_bash");
1137        assert!(t[0].1.contains("ls"));
1138    }
1139
1140    #[test]
1141    fn tool_choice_none_keeps_tool_text_as_content() {
1142        // allow_tools=false → a <tool_call> block is NOT extracted; it stays content.
1143        let (_r, c, t) = run(&["<tool_call>{\"name\":\"x\"}</tool_call>"], false);
1144        assert!(t.is_empty());
1145        assert!(c.contains("tool_call"));
1146    }
1147
1148    #[test]
1149    fn pipe_form_tool_call_not_streamed_as_content() {
1150        // gemma4/E2B/DG pipe form has no `<tool_call>` substring — it must still gate content
1151        // and fire exactly once as a ToolCall (not leak as Content AND duplicate).
1152        let (_r, c, t) = run(
1153            &[
1154                "<|tool_",
1155                "call>call:get_weather{city:<|\"|>Par",
1156                "is<|\"|>}",
1157                "<tool_call|>",
1158            ],
1159            true,
1160        );
1161        assert!(
1162            !c.contains("tool_call") && !c.contains("get_weather"),
1163            "pipe markup leaked as content: {c:?}"
1164        );
1165        assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
1166        assert_eq!(t[0].0, "get_weather");
1167    }
1168
1169    #[test]
1170    fn bare_json_tool_call_not_streamed_as_content() {
1171        // Llama-3 bare-JSON form: the whole body is one JSON object — no markers at all.
1172        let (_r, c, t) = run(
1173            &[
1174                "{\"name\": \"get_weather\", ",
1175                "\"parameters\": {\"city\": \"Paris\"}}",
1176            ],
1177            true,
1178        );
1179        assert!(c.trim().is_empty(), "bare json leaked as content: {c:?}");
1180        assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
1181        assert_eq!(t[0].0, "get_weather");
1182    }
1183
1184    #[test]
1185    fn content_with_stray_brace_not_swallowed() {
1186        // Ordinary prose that merely contains a brace mid-text must NOT be treated as a call.
1187        let (_r, c, t) = run(
1188            &[
1189                "The config is {",
1190                "\"a\": 1} and that is the whole story here, nothing more.",
1191            ],
1192            true,
1193        );
1194        assert!(t.is_empty(), "stray brace misparsed as tool call: {t:?}");
1195        assert!(c.contains("The config is"), "content lost: {c:?}");
1196        assert!(c.contains("whole story"), "content truncated: {c:?}");
1197    }
1198
1199    /// A `<tool_call>` mentioned inside the reasoning must not hide the real call that follows in
1200    /// the content: the real one is buffered (not streamed as raw markup) and fires exactly once.
1201    #[test]
1202    fn tool_marker_in_reasoning_does_not_hide_the_real_call() {
1203        let call = "<tool_call>\n{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}\n</tool_call>";
1204        for pipe in [false, true] {
1205            let (mention, real) = if pipe {
1206                (
1207                    "I could emit <|tool_call> here",
1208                    "<|tool_call>call:run_bash{command:<|\"|>ls<|\"|>}<tool_call|>",
1209                )
1210            } else {
1211                ("I could emit <tool_call> here", call)
1212            };
1213            let pieces = ["<think>", mention, "</think>", "Sure. ", real];
1214            let (_r, c, t) = run(&pieces, true);
1215            assert!(
1216                !c.contains("run_bash"),
1217                "the call streamed as content: {c:?}"
1218            );
1219            assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
1220            assert_eq!(t[0].0, "run_bash");
1221        }
1222    }
1223
1224    /// A call quoted inside a channel-format thought block is reasoning, not a call: the stream
1225    /// never treats it as one, and `finish` must not either.
1226    #[test]
1227    fn tool_call_in_channel_reasoning_is_not_a_call() {
1228        let (r, c, t) = run(
1229            &[
1230                "<|channel>thought\nmaybe <|tool_call>call:get_weather{city:<|\"|>Paris<|\"|>}",
1231                "<tool_call|> but no<channel|>It is sunny.",
1232            ],
1233            true,
1234        );
1235        assert!(r.contains("maybe"), "reasoning lost: {r:?}");
1236        assert_eq!(c.trim(), "It is sunny.");
1237        assert!(t.is_empty(), "a call quoted in the reasoning fired: {t:?}");
1238    }
1239
1240    /// A `<think>`-format reply whose content merely mentions a channel marker is still a
1241    /// `<think>`-format reply: the call streaming held back must fire at `finish`, not vanish into
1242    /// an empty channel-format body.
1243    #[test]
1244    fn a_quoted_channel_marker_does_not_switch_formats() {
1245        let (_r, c, t) = run(
1246            &[
1247                "<think>plan</think>",
1248                "The <|channel> marker is how E2B splits. ",
1249                "<tool_call>\n{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}\n</tool_call>",
1250            ],
1251            true,
1252        );
1253        assert!(c.contains("<|channel> marker"), "content lost: {c:?}");
1254        assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
1255        assert_eq!(t[0].0, "run_bash");
1256    }
1257
1258    /// With tools on, a reply opening with a JSON object that is not a call streams once the
1259    /// object closes, instead of arriving as one chunk at `finish`. Braces and an escaped quote
1260    /// inside a string do not end the object early.
1261    #[test]
1262    fn a_leading_json_answer_streams_before_finish() {
1263        let pieces = [
1264            "{\"a\": [1, ",
1265            "2], \"b\": \"x} \\\"q\\\" {\"}",
1266            " and the prose after it keeps coming",
1267            " for a while longer.",
1268        ];
1269        let mut s = ChatStream::new(true);
1270        let mut streamed = String::new();
1271        for p in pieces {
1272            s.push(p, &mut |d| {
1273                if let Delta::Content(x) = d {
1274                    streamed.push_str(&x)
1275                }
1276            });
1277        }
1278        assert!(
1279            streamed.starts_with("{\"a\": [1, 2], \"b\": \"x} \\\"q\\\" {\"}"),
1280            "the object was not streamed before finish: {streamed:?}"
1281        );
1282        let (_r, c, t) = run(&pieces, true);
1283        assert!(t.is_empty(), "a plain object fired as a call: {t:?}");
1284        assert_eq!(c, pieces.concat());
1285    }
1286
1287    /// Content before a `<think>` that does not open the reply streams, in order, and does not
1288    /// shift the content after `</think>`.
1289    #[test]
1290    fn content_before_a_late_think_is_streamed() {
1291        let pieces = [
1292            "Sure, let me check. ",
1293            "<think>",
1294            "plan",
1295            "</think>",
1296            "It is 4.",
1297        ];
1298        let mut out = Vec::new();
1299        let mut s = ChatStream::new(false);
1300        for p in pieces {
1301            s.push(p, &mut |d| out.push(d));
1302        }
1303        s.finish(&mut |d| out.push(d));
1304        let lead = out
1305            .iter()
1306            .position(|d| matches!(d, Delta::Content(x) if x.contains("check.")));
1307        let think = out.iter().position(|d| matches!(d, Delta::Reasoning(_)));
1308        assert!(
1309            lead < think && lead.is_some(),
1310            "lead missing or late: {out:?}"
1311        );
1312        let (r, c, _) = run(&pieces, false);
1313        assert_eq!(r, "plan");
1314        assert_eq!(c, "Sure, let me check. It is 4.");
1315    }
1316
1317    /// A lead-in held at a tool-call opener before a `<think>` (a leading `{`, a `<tool_call>`)
1318    /// that turns out not to be a call is emitted at `finish`, ahead of the content after the
1319    /// reasoning, instead of vanishing.
1320    #[test]
1321    fn a_held_lead_in_that_is_no_call_is_emitted_in_order() {
1322        for (pieces, want) in [
1323            (
1324                &[
1325                    "{not a call} so ",
1326                    "<think>",
1327                    "plan",
1328                    "</think>",
1329                    "an answer long enough to stream",
1330                ][..],
1331                "{not a call} so an answer long enough to stream",
1332            ),
1333            (
1334                &[
1335                    "Hi <tool_call>oops ",
1336                    "<think>",
1337                    "plan",
1338                    "</think>",
1339                    "done, and more after that",
1340                ][..],
1341                "Hi <tool_call>oops done, and more after that",
1342            ),
1343        ] {
1344            let (r, c, t) = run(pieces, true);
1345            assert_eq!(r, "plan");
1346            assert!(t.is_empty(), "no call was made: {t:?}");
1347            assert_eq!(c, want);
1348        }
1349    }
1350
1351    /// A call after the reasoning is judged on the content after `</think>` alone, the region
1352    /// streaming held: the lead-in before `<think>` does not stop it from firing.
1353    #[test]
1354    fn a_call_after_reasoning_fires_despite_a_lead_in() {
1355        let (_r, c, t) = run(
1356            &[
1357                "Sure. ",
1358                "<think>",
1359                "plan",
1360                "</think>",
1361                "{\"name\": \"get_weather\", \"parameters\": {\"city\": \"Paris\"}}",
1362            ],
1363            true,
1364        );
1365        assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
1366        assert_eq!(t[0].0, "get_weather");
1367        assert_eq!(c, "Sure. ");
1368    }
1369
1370    /// A held tool-call marker whose body is not a call is shown as content, not dropped.
1371    #[test]
1372    fn a_marker_that_holds_no_call_is_emitted_as_content() {
1373        let (_r, c, t) = run(&["Here: ", "<tool_call>not json</tool_call>"], true);
1374        assert!(t.is_empty(), "{t:?}");
1375        assert_eq!(c, "Here: <tool_call>not json</tool_call>");
1376    }
1377
1378    /// A `<think>` span after a call in the held stretch is reasoning: it must not reach the
1379    /// content.
1380    #[test]
1381    fn reasoning_after_a_held_call_is_not_content() {
1382        let (r, c, t) = run(
1383            &[
1384                "<think>plan</think>",
1385                "<tool_call>{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}</tool_call>",
1386                "<think>second thoughts</think>",
1387                "Done after the call.",
1388            ],
1389            true,
1390        );
1391        assert_eq!(t.len(), 1, "{t:?}");
1392        assert!(!c.contains("think") && !c.contains("second"), "{c:?}");
1393        assert!(c.contains("Done after the call."), "{c:?}");
1394        assert!(r.contains("second thoughts"), "{r:?}");
1395    }
1396
1397    /// A `<tool_call>` block that does not parse is shown as content whether or not a valid
1398    /// call sits beside it.
1399    #[test]
1400    fn an_unparseable_block_beside_a_call_is_shown() {
1401        let (_r, c, t) = run(
1402            &[
1403                "Here: ",
1404                "<tool_call>not json</tool_call> and ",
1405                "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>",
1406            ],
1407            true,
1408        );
1409        assert_eq!(t.len(), 1, "{t:?}");
1410        assert!(c.contains("<tool_call>not json</tool_call>"), "{c:?}");
1411    }
1412
1413    /// Prose after a removed call keeps the whitespace that separated it from the prose before.
1414    #[test]
1415    fn prose_around_a_removed_call_is_not_glued() {
1416        let (_r, c, t) = run(
1417            &[
1418                "Sure.",
1419                "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>",
1420                " More text after it.",
1421            ],
1422            true,
1423        );
1424        assert_eq!(t.len(), 1, "{t:?}");
1425        assert_eq!(c, "Sure. More text after it.");
1426    }
1427
1428    /// Every delta, in emission order (streaming + finish).
1429    fn deltas(pieces: &[&str]) -> Vec<Delta> {
1430        let mut out = Vec::new();
1431        let mut s = ChatStream::new(true);
1432        for p in pieces {
1433            s.push(p, &mut |d| out.push(d));
1434        }
1435        s.finish(&mut |d| out.push(d));
1436        out
1437    }
1438
1439    fn first_at(out: &[Delta], pred: impl Fn(&Delta) -> bool) -> usize {
1440        out.iter()
1441            .position(pred)
1442            .unwrap_or_else(|| panic!("no such delta in {out:?}"))
1443    }
1444
1445    /// A held stretch is settled in the order it was written: the content before a `<think>` in
1446    /// it, then that reasoning, then the content after it.
1447    #[test]
1448    fn a_held_stretch_settles_in_textual_order() {
1449        let out = deltas(&[
1450            "<think>plan</think>",
1451            "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call> Before.",
1452            "<think>second</think>",
1453            " After.",
1454        ]);
1455        let before = first_at(
1456            &out,
1457            |d| matches!(d, Delta::Content(x) if x.contains("Before")),
1458        );
1459        let mid = first_at(
1460            &out,
1461            |d| matches!(d, Delta::Reasoning(x) if x.contains("second")),
1462        );
1463        let after = first_at(
1464            &out,
1465            |d| matches!(d, Delta::Content(x) if x.contains("After")),
1466        );
1467        assert!(before < mid && mid < after, "{out:?}");
1468    }
1469
1470    /// A lead-in held at an opener before `<think>` reaches the reader before the reasoning that
1471    /// follows it, not at `finish` after it.
1472    #[test]
1473    fn a_held_lead_in_arrives_before_the_reasoning_after_it() {
1474        let out = deltas(&["Hi <tool_call>oops ", "<think>", "plan", "</think>", "done"]);
1475        let lead = first_at(
1476            &out,
1477            |d| matches!(d, Delta::Content(x) if x.contains("oops")),
1478        );
1479        let think = first_at(&out, |d| matches!(d, Delta::Reasoning(_)));
1480        assert!(lead < think, "{out:?}");
1481    }
1482
1483    /// Whitespace that only separated a removed call from its neighbours is not shown, and a gap
1484    /// that keeps two words apart is.
1485    #[test]
1486    fn whitespace_left_by_a_removed_call_is_dropped() {
1487        const CALL: &str = "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>";
1488        for (pieces, want) in [
1489            (vec![CALL, "\n\nI'll check."], "I'll check."),
1490            (vec!["A ", CALL, " B"], "A B"),
1491            (vec!["A ", CALL, " and ", CALL, " B"], "A and B"),
1492            (vec!["I'll check.\n", CALL, "\n"], "I'll check.\n"),
1493        ] {
1494            let (_r, c, t) = run(&pieces, true);
1495            assert!(!t.is_empty(), "{pieces:?}: no call fired");
1496            assert_eq!(c, want, "{pieces:?}");
1497        }
1498    }
1499
1500    const GOOD_CALL: &str = "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>";
1501
1502    /// A removed call's gap is judged against what the reader was actually shown — `"Hi "` here,
1503    /// not the held call markup that followed it in the raw text.
1504    #[test]
1505    fn a_cut_gap_is_judged_against_the_shown_text() {
1506        let lead = format!("Hi {GOOD_CALL}");
1507        let main = format!("{GOOD_CALL} Done.");
1508        let (_r, c, t) = run(&[&lead, "<think>p</think>", &main], true);
1509        assert_eq!(t.len(), 2, "{t:?}");
1510        assert_eq!(c, "Hi Done.");
1511    }
1512
1513    /// Whitespace is trimmed only where a call was cut out: a span after a `</think>` keeps its
1514    /// leading line breaks, though a call later in it was removed.
1515    #[test]
1516    fn a_span_after_reasoning_keeps_its_line_breaks() {
1517        let first = format!("{GOOD_CALL}Before.\n");
1518        let last = format!("\n\nAfter {GOOD_CALL}");
1519        let (_r, c, _t) = run(
1520            &["<think>p</think>", &first, "<think>t</think>", &last],
1521            true,
1522        );
1523        assert_eq!(c, "Before.\n\n\nAfter");
1524    }
1525
1526    /// A lead-in's last words keep the space before the content after the reasoning: only a
1527    /// call's own cut is trimmed, and the lead-in does not end the reply.
1528    #[test]
1529    fn a_lead_in_keeps_the_space_before_later_content() {
1530        let lead = format!("Hi {GOOD_CALL} now ");
1531        let (_r, c, _t) = run(&[&lead, "<think>p</think>", "Done."], true);
1532        assert_eq!(c, "Hi now Done.");
1533    }
1534
1535    /// Only the stretch's LAST text span ends the reply: a span that closes with a call before
1536    /// reasoning keeps its trailing gap, so the text after the reasoning is not glued to it.
1537    #[test]
1538    fn only_the_last_span_of_a_stretch_loses_its_trailing_gap() {
1539        let held = format!("{GOOD_CALL}X {GOOD_CALL}<think>r</think>Y");
1540        let (r, c, t) = run(&["<think>p</think>", &held], true);
1541        assert_eq!(t.len(), 2, "{t:?}");
1542        assert_eq!(r, "pr");
1543        assert_eq!(c, "X Y");
1544    }
1545
1546    /// With tools allowed and no call parsed, the content is the reply's text byte for byte,
1547    /// whitespace included.
1548    #[test]
1549    fn a_reply_with_no_parsed_call_is_byte_identical() {
1550        for pieces in [
1551            &["Here:  ", "<tool_call>not json</tool_call>", "\n\n  "][..],
1552            &["{not a call}  \n", "<think>p</think>", "  ok  "][..],
1553            &["Hi <tool_call>oops\n\n", "<think>p</think>", "\n done"][..],
1554        ] {
1555            let want: String = pieces
1556                .iter()
1557                .map(|p| {
1558                    p.split("<think>").next().unwrap_or_default().to_owned()
1559                        + p.split("</think>").nth(1).unwrap_or_default()
1560                })
1561                .collect();
1562            let (_r, c, t) = run(pieces, true);
1563            assert!(t.is_empty(), "{t:?}");
1564            assert_eq!(c, want, "{pieces:?}");
1565        }
1566    }
1567
1568    /// A Hermes call followed by a pipe-format call: both fire and neither is shown.
1569    #[test]
1570    fn mixed_dialect_calls_all_fire() {
1571        let (_r, c, t) = run(
1572            &[
1573                "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>",
1574                "<|tool_call>call:get_weather{city:<|\"|>Paris<|\"|>}<tool_call|>",
1575            ],
1576            true,
1577        );
1578        let names: Vec<&str> = t.iter().map(|(n, _)| n.as_str()).collect();
1579        assert_eq!(names, ["run_bash", "get_weather"]);
1580        assert!(!c.contains("tool_call"), "{c:?}");
1581    }
1582
1583    #[test]
1584    fn leading_brace_non_call_survives_as_content() {
1585        // A leading `{` that is NOT a valid bare-JSON call must be flushed as content, not dropped.
1586        let (_r, c, t) = run(
1587            &["{not json here, just prose that opens with a brace}"],
1588            true,
1589        );
1590        assert!(t.is_empty(), "non-call misparsed: {t:?}");
1591        assert!(c.contains("not json here"), "content dropped: {c:?}");
1592    }
1593}