返回 CodeWhale
streaming_thinking.rs
根目录 / crates / tui / src / tui / streaming_thinking.rs
1 //! Streaming-thinking lifecycle for the active cell.
2 //!
3 //! DeepSeek V4 emits `reasoning_content` chunks before final answers.
4 //! These get rendered as a "Thinking" entry inside the per-turn active
5 //! cell. This module is the single source of truth for:
6 //!
7 //! - creating a streaming thinking entry on first chunk
8 //! - appending chunks to the live entry
9 //! - showing a localized placeholder while a translation is in-flight
10 //! (and animating its elapsed/spinner suffix)
11 //! - replacing the placeholder when the translation arrives
12 //! - finalizing the entry (stopping the spinner, stamping duration)
13 //! when a thinking block ends
14 //! - stashing the reasoning buffer onto `app.last_reasoning` so the
15 //! summary survives compaction
16
17 use std::time::Duration;
18 use std::time::Instant;
19
20 use crate::tui::active_cell::ActiveCell;
21 use crate::tui::app::App;
22 use crate::tui::history::HistoryCell;
23
24 /// Debounce window for active-cell revision bumps while a thinking block is
25 /// streaming (#1620). Reasoning deltas arrive far faster than the eye can
26 /// follow, and each revision bump invalidates the active cell's wrap cache,
27 /// forcing a full re-wrap of the live tail. Coalescing intermediate bumps to
28 /// one per window keeps the perceived stream smooth without re-wrapping per
29 /// character. ~100ms ≈ 10 intermediate repaints/sec, well below the 120 FPS
30 /// frame cap (see `frame_rate_limiter`) yet imperceptible as lag.
31 ///
32 /// Correctness: this only skips *intermediate* repaints. Appended content is
33 /// never dropped — it lands in the cell immediately — the display beat renders
34 /// a skipped bump once the window has passed, and finalize always forces a
35 /// bump so the final reasoning text is fully rendered.
36 const THINKING_REVISION_THROTTLE: Duration = Duration::from_millis(100);
37
38 /// Bump the active-cell revision for a streaming thinking mutation, but at
39 /// most once per [`THINKING_REVISION_THROTTLE`] window. Returns whether a bump
40 /// was actually emitted. Skipped bumps coalesce into the next one, into
41 /// [`render_owed_revision`] on a later display beat, or into the forced
42 /// finalize bump, so no content is ever lost — only redundant intermediate
43 /// re-wraps are dropped.
44 fn bump_thinking_revision_throttled(app: &mut App, now: Instant) -> bool {
45 let due = app
46 .thinking_revision_last_bump_at
47 .is_none_or(|last| now.saturating_duration_since(last) >= THINKING_REVISION_THROTTLE);
48 if due {
49 app.thinking_revision_last_bump_at = Some(now);
50 app.bump_active_cell_revision();
51 }
52 app.thinking_revision_owed = !due;
53 due
54 }
55
56 pub(super) fn render_owed_revision(app: &mut App, now: Instant) -> bool {
57 if app.streaming_thinking_active_entry.is_none() {
58 app.thinking_revision_owed = false;
59 }
60 app.thinking_revision_owed && bump_thinking_revision_throttled(app, now)
61 }
62
63 /// Ensure an in-flight Thinking entry exists in `active_cell` and return its
64 /// entry index. If no thinking entry is currently streaming, push a fresh one.
65 /// P2.3: thinking shares the active cell with subsequent tool calls so the
66 /// pair render as one logical "Working…" block.
67 ///
68 /// A card that has had a sibling appended after it is no longer the live tail.
69 /// A gateway that keeps sending `thinking_delta` after a tool block would
70 /// otherwise grow that card, putting new reasoning above the tool card the
71 /// reader already saw (#7454). Such a card is finalized and a new one opens
72 /// below the sibling instead.
73 pub(super) fn ensure_active_entry(app: &mut App) -> usize {
74 if let Some(idx) = app.streaming_thinking_active_entry {
75 if card_is_the_live_tail(app, idx) {
76 return idx;
77 }
78 // Translation shows a placeholder on the card and fills it only when
79 // `ThinkingComplete` names that card, which it now cannot: the pointer
80 // is about to move to the new card. Hand the settled card the text it
81 // already received so it stops re-framing a placeholder nothing will
82 // replace. `ThinkingDelta` splits before it records a delta, so the
83 // buffer holds only this card's text here.
84 if app.translation_enabled {
85 let original = app.reasoning_buffer.clone();
86 if !original.is_empty() {
87 if let Some(active) = app.active_cell.as_mut()
88 && let Some(HistoryCell::Thinking { content, .. }) = active.entry_mut(idx)
89 {
90 *content = original;
91 }
92 app.bump_active_cell_revision();
93 stash_reasoning_buffer_into_last_reasoning(app);
94 }
95 }
96 finalize_current(app);
97 }
98 if app.active_cell.is_none() {
99 app.active_cell = Some(ActiveCell::new());
100 }
101 let active = app.active_cell.as_mut().expect("active_cell just ensured");
102 let entry_idx = active.push_thinking(HistoryCell::Thinking {
103 content: String::new(),
104 streaming: true,
105 duration_secs: None,
106 });
107 app.streaming_thinking_active_entry = Some(entry_idx);
108 app.thinking_read_window = Default::default();
109 // A card that opens after a tool still needs a start time, or its duration
110 // reads as unknown. `start_block` sets one before calling here, so this only
111 // fills the gap a resumed card would otherwise leave.
112 if app.thinking_started_at.is_none() {
113 app.thinking_started_at = Some(Instant::now());
114 }
115 app.bump_active_cell_revision();
116 entry_idx
117 }
118
119 /// Whether `index` still names a thinking card with nothing appended after it.
120 ///
121 /// Anything else means the card is settled: a tool or notice was appended below
122 /// it, or it is gone. Growing it would draw new reasoning above a card the
123 /// reader already saw (#7454).
124 fn card_is_the_live_tail(app: &App, index: usize) -> bool {
125 app.active_cell.as_ref().is_some_and(|active| {
126 active.entry_count() == index + 1
127 && matches!(
128 active.entries().get(index),
129 Some(HistoryCell::Thinking { .. })
130 )
131 })
132 }
133
134 /// Append text to a streaming Thinking entry inside `active_cell`. The text is
135 /// committed to the cell immediately; the active-cell revision bump that
136 /// triggers a re-wrap of the live tail is debounced to at most one per
137 /// [`THINKING_REVISION_THROTTLE`] window (#1620). Skipped bumps coalesce into
138 /// the next append, a later display beat or the forced finalize bump, so no
139 /// content is ever lost.
140 pub(super) fn append(app: &mut App, entry_idx: usize, text: &str) {
141 append_at(app, entry_idx, text, Instant::now());
142 }
143
144 /// `append` with an injectable clock so the debounce can be tested
145 /// deterministically.
146 pub(super) fn append_at(app: &mut App, entry_idx: usize, text: &str, now: Instant) {
147 if text.is_empty() {
148 return;
149 }
150 let following = app.viewport.transcript_scroll.is_at_tail();
151 let animate = following && !app.effective_low_motion_for_status();
152 let mutated = if let Some(active) = app.active_cell.as_mut()
153 && let Some(HistoryCell::Thinking { content, .. }) = active.entry_mut(entry_idx)
154 {
155 let start = content.len();
156 content.push_str(text);
157 if app.show_thinking
158 && !app.translation_enabled
159 && let Some(area) = app.viewport.last_transcript_area
160 {
161 let width = app
162 .prose_measure
163 .map_or(area.width, |limit| area.width.min(limit))
164 .saturating_sub(4);
165 let previous = app.thinking_read_window.projection().excerpts[1];
166 app.thinking_read_window.append(
167 content,
168 start,
169 now,
170 usize::from(width),
171 usize::from(area.height),
172 following,
173 );
174 let newest = app.thinking_read_window.projection().excerpts[1];
175 if animate && newest.is_some() && newest != previous {
176 app.thinking_read_window.start_settling(now);
177 }
178 } else {
179 app.thinking_read_window.skip_to(content.len());
180 }
181 true
182 } else {
183 false
184 };
185 if mutated {
186 bump_thinking_revision_throttled(app, now);
187 }
188 }
189
190 /// Build the spinner-decorated placeholder shown in the thinking entry
191 /// while a translation is in flight (`Thinking… (1.2s |)`).
192 fn translation_placeholder_spinner_frame(app: &App, elapsed: f32) -> &'static str {
193 let elapsed = std::time::Duration::try_from_secs_f32(elapsed.max(0.0))
194 .unwrap_or(std::time::Duration::MAX);
195 let animated_frame =
196 codewhale_ratatui::spin::frame(elapsed, codewhale_ratatui::MotionMode::Full, true);
197 app.motion_policy().spinner_glyph(animated_frame, true)
198 }
199
200 pub(super) fn translation_placeholder_frame(app: &App) -> String {
201 let base = codewhale_localization::thinking_translation_placeholder(app.ui_locale);
202 let elapsed = app
203 .thinking_started_at
204 .or(app.turn_started_at)
205 .map(|started| started.elapsed().as_secs_f32())
206 .unwrap_or_default();
207 let frame = translation_placeholder_spinner_frame(app, elapsed);
208 format!("{base} ({elapsed:.1}s {frame})")
209 }
210
211 /// If the given entry is empty or still showing the translation
212 /// placeholder prefix, replace it with the latest animated frame.
213 pub(super) fn set_placeholder(app: &mut App, entry_idx: usize) {
214 app.thinking_read_window = Default::default();
215 let base = codewhale_localization::thinking_translation_placeholder(app.ui_locale);
216 let next = translation_placeholder_frame(app);
217 let mutated = if let Some(active) = app.active_cell.as_mut()
218 && let Some(HistoryCell::Thinking { content, .. }) = active.entry_mut(entry_idx)
219 && (content.is_empty() || content.starts_with(base))
220 {
221 if *content != next {
222 *content = next;
223 true
224 } else {
225 false
226 }
227 } else {
228 false
229 };
230 if mutated {
231 app.bump_active_cell_revision();
232 }
233 }
234
235 /// Advance the spinner suffix on every existing translation placeholder
236 /// in `active_cell`. Returns true when at least one cell was updated so
237 /// the dispatch loop can schedule another tick.
238 pub(super) fn animate_pending_translation(app: &mut App, translation_pending: bool) -> bool {
239 if !app.translation_enabled {
240 return false;
241 }
242 let thinking_streaming = app.streaming_thinking_active_entry.is_some();
243 if !translation_pending && !thinking_streaming {
244 return false;
245 }
246 let base = codewhale_localization::thinking_translation_placeholder(app.ui_locale);
247 let next = translation_placeholder_frame(app);
248
249 if let Some(active) = app.active_cell.as_mut() {
250 for idx in (0..active.entry_count()).rev() {
251 if let Some(HistoryCell::Thinking { content, .. }) = active.entry_mut(idx)
252 && content.starts_with(base)
253 && *content != next
254 {
255 *content = next.clone();
256 app.bump_active_cell_revision();
257 return true;
258 }
259 }
260 }
261 false
262 }
263
264 /// Replace a translation placeholder with the finished translated text.
265 pub(super) fn replace_pending_translation(
266 app: &mut App,
267 cell_index: usize,
268 translated_text: String,
269 ) {
270 if let Some(HistoryCell::Thinking { content, .. }) = app.cell_at_virtual_index_mut(cell_index) {
271 *content = translated_text;
272 app.needs_redraw = true;
273 }
274 }
275
276 /// Start a new streaming thinking block. If another thinking block is still
277 /// active, first drain its pending UI tail so a late block boundary cannot
278 /// discard content buffered inside `StreamingState`.
279 pub(super) fn start_block(app: &mut App) -> bool {
280 let finalized_previous = if app.streaming_thinking_active_entry.is_some() {
281 let finalized = finalize_current(app);
282 stash_reasoning_buffer_into_last_reasoning(app);
283 finalized
284 } else {
285 false
286 };
287
288 // #7123: a text block can still hold an uncommitted tail when a reasoning
289 // block opens — the display beat commits once per interval, so the
290 // boundary lands between beats. `reset` below discards whatever is left.
291 flush_pending_text_tail(app);
292 app.reasoning_buffer.clear();
293 app.reasoning_header = None;
294 app.thinking_started_at = Some(Instant::now());
295 app.streaming_state.reset();
296 app.streaming_state.start_thinking(0);
297 let _ = ensure_active_entry(app);
298 finalized_previous
299 }
300
301 /// Flush a text block's uncommitted tail into the assistant cell.
302 ///
303 /// The display beat commits at most once per interval, so a block boundary
304 /// that arrives between beats leaves the last slice of prose sitting in
305 /// `StreamingState`. Both `start_block` and the finalize paths reset that
306 /// state; without this drain the tail before a reasoning card never reaches
307 /// the transcript (#7123).
308 fn flush_pending_text_tail(app: &mut App) {
309 if app.streaming_state.block_is_thinking(0) {
310 return;
311 }
312 // Nothing buffered: do not create an assistant cell just to write nothing
313 // into it.
314 if app.streaming_state.pending_len(0) == 0 {
315 return;
316 }
317 // Resolve the destination before taking the buffer. Draining first and
318 // then discovering there is nowhere to put the text discarded it (#7123).
319 let index = app
320 .streaming_message_index
321 .unwrap_or_else(|| crate::tui::ui::frame::ensure_streaming_assistant_history_cell(app));
322 let remaining = app.streaming_state.finalize_block_text(0);
323 if remaining.is_empty() {
324 return;
325 }
326 crate::tui::ui::frame::append_streaming_text(app, index, &remaining);
327 crate::tui::ui::frame::accrue_streaming_token_estimate(app, &remaining);
328 }
329
330 /// Re-establish the block kind the arriving delta actually carries.
331 ///
332 /// A block's kind is set by its start event alone, so a gateway that opens a
333 /// text block inside a thinking stream leaves block 0 marked text. The
334 /// reasoning that follows would then be committed into the prose body, and one
335 /// sentence would be split across the thinking card and the answer that
336 /// follows it — the #7123 split with the opposite ordering. The pending tail
337 /// goes to the cell its old kind owned first, then the block takes the new
338 /// kind.
339 ///
340 /// A flip closes the reasoning card and starts a fresh one on the way back, so
341 /// a gateway that flips twice renders one passage as two cards, the second
342 /// without a duration stamp. That is the honest reading of a stream that
343 /// really did interleave, not a display defect.
344 ///
345 /// Returns whether the kind changed.
346 pub(super) fn resync_block_kind(app: &mut App, is_thinking: bool) -> bool {
347 if app.streaming_state.block_is_thinking(0) == is_thinking {
348 return false;
349 }
350 if is_thinking {
351 flush_pending_text_tail(app);
352 } else if !app.translation_enabled && app.streaming_thinking_active_entry.is_some() {
353 // The prose that interrupted the reasoning closes its card. Leaving
354 // the entry streaming would keep the spinner turning and stamp a
355 // duration that grows until the next finalize; stashing the buffer
356 // matches what `MessageStarted` does, so replay still has the text.
357 //
358 // Skipped under translation so this branch does not clear the entry or
359 // the buffer before `ThinkingComplete` reads them. It cannot make the
360 // card fill in: `MessageDelta` calls `flush_active_cell` immediately
361 // after the resync, which takes the entry regardless. What the guard
362 // buys is that the reasoning text stays in `reasoning_buffer` for
363 // replay, and that fixing the index is left to `ThinkingComplete`.
364 finalize_current(app);
365 stash_reasoning_buffer_into_last_reasoning(app);
366 } else {
367 drain_thinking_tail_into_entry(app);
368 }
369 app.streaming_state.set_block_kind(0, is_thinking);
370 true
371 }
372
373 /// Deliver a live reasoning block's uncommitted tail into its own card.
374 ///
375 /// The mirror of `flush_pending_text_tail`. Only reached when the entry was
376 /// already finalized, so there is usually nothing buffered; when there is, the
377 /// bytes also live in `reasoning_buffer` and `set_block_kind` discards this
378 /// copy on the next line.
379 fn drain_thinking_tail_into_entry(app: &mut App) {
380 if app.translation_enabled
381 || !app.streaming_state.block_is_thinking(0)
382 || app.streaming_state.pending_len(0) == 0
383 {
384 return;
385 }
386 let entry_idx = ensure_active_entry(app);
387 let tail = app.streaming_state.finalize_block_text(0);
388 if !tail.is_empty() {
389 append(app, entry_idx, &tail);
390 }
391 }
392
393 /// Finalize the currently-streaming thinking entry: drain the pending
394 /// state buffer, compute elapsed duration, stop the spinner.
395 pub(super) fn finalize_current(app: &mut App) -> bool {
396 if app.streaming_thinking_active_entry.is_none() {
397 app.thinking_started_at = None;
398 return false;
399 }
400 let duration = app
401 .thinking_started_at
402 .take()
403 .map(|t| t.elapsed().as_secs_f32());
404 // #7123: drain only the reasoning block. If a text block owns index 0 at
405 // this point (a boundary lost an event), taking its buffer here would
406 // append prose to the thinking card and drop it from the answer.
407 let remaining = if app.streaming_state.block_is_thinking(0) {
408 app.streaming_state.finalize_block_text(0)
409 } else {
410 String::new()
411 };
412 finalize_active_entry(app, duration, &remaining)
413 }
414
415 /// Move the in-flight reasoning buffer onto `app.last_reasoning` so the
416 /// summary survives compaction or transcript trimming.
417 pub(super) fn stash_reasoning_buffer_into_last_reasoning(app: &mut App) {
418 if app.reasoning_buffer.is_empty() {
419 return;
420 }
421
422 if let Some(existing) = app.last_reasoning.as_mut()
423 && !existing.is_empty()
424 {
425 if !existing.ends_with('\n') {
426 existing.push('\n');
427 }
428 existing.push_str(&app.reasoning_buffer);
429 } else {
430 app.last_reasoning = Some(app.reasoning_buffer.clone());
431 }
432 app.reasoning_buffer.clear();
433 }
434
435 /// Finalize the in-flight thinking entry in `active_cell`: append the
436 /// collector's remaining buffered text, stop the spinner, and stamp the
437 /// duration. Returns `true` when a thinking entry was finalized (so the
438 /// dispatch loop knows the transcript was touched). No-op if no thinking
439 /// entry is currently streaming.
440 pub(super) fn finalize_active_entry(app: &mut App, duration: Option<f32>, remaining: &str) -> bool {
441 let Some(entry_idx) = app.streaming_thinking_active_entry.take() else {
442 return false;
443 };
444 if !remaining.is_empty() && !app.translation_enabled {
445 append(app, entry_idx, remaining);
446 }
447 if let Some(active) = app.active_cell.as_mut()
448 && let Some(HistoryCell::Thinking {
449 streaming,
450 duration_secs,
451 ..
452 }) = active.entry_mut(entry_idx)
453 {
454 *streaming = false;
455 *duration_secs = duration;
456 }
457 // Red line (#1620): finalize must force a bump so the final reasoning text
458 // is fully rendered even if the last appended chunk was throttled. Reset
459 // the debounce window so the next thinking block's first chunk renders
460 // immediately rather than being coalesced into a stale window.
461 app.thinking_read_window = Default::default();
462 app.thinking_revision_last_bump_at = None;
463 app.thinking_revision_owed = false;
464 app.bump_active_cell_revision();
465 true
466 }
467
468 #[cfg(test)]
469 mod tests {
470 use super::*;
471 use crate::tui::app::{App, TuiOptions};
472 use codewhale_runtime::config::Config;
473 use std::path::PathBuf;
474
475 fn test_app() -> App {
476 let options = TuiOptions {
477 start_in_agent_mode: true,
478 skip_onboarding: false,
479 ..crate::tui::test_support::test_tui_options(PathBuf::from("."))
480 };
481 App::new(options, &Config::default())
482 }
483
484 fn thinking_content(app: &App, entry_idx: usize) -> String {
485 match app
486 .active_cell
487 .as_ref()
488 .and_then(|active| active.entries().get(entry_idx))
489 {
490 Some(HistoryCell::Thinking { content, .. }) => content.clone(),
491 other => panic!("expected a Thinking entry at {entry_idx}, got {other:?}"),
492 }
493 }
494
495 #[test]
496 fn burst_frame_keeps_checkpoints_live_tail_and_expanded_source() {
497 use crate::tui::history::{CellFoldAction, TranscriptFold};
498 use crate::tui::ui::frame::commit_streaming_display_tick;
499 use codewhale_tui_kit::streaming::StreamDisplayClock;
500
501 let mut app = test_app();
502 app.show_thinking = true;
503 app.low_motion = true;
504 app.thinking_default_expanded = false;
505 app.verbose_transcript = false;
506 app.viewport.last_transcript_area = Some(ratatui::layout::Rect::new(0, 0, 60, 12));
507 let mut clock = StreamDisplayClock::new(Duration::from_millis(16));
508 let now = Instant::now();
509 let entry = ensure_active_entry(&mut app);
510 app.streaming_state.start_thinking(0);
511 let trace = format!(
512 "Lookup starts in config.rs. Read the path.\n{}\nThe fallback is relative. Keep its original path.\n\nChecking spaces",
513 "source detail\n".repeat(30)
514 );
515 app.streaming_state.push_content(0, &trace);
516 clock.note_delta(now);
517 assert!(commit_streaming_display_tick(&mut app, &mut clock, now));
518 assert_eq!(app.streaming_state.pending_len(0), 0);
519 assert_eq!(thinking_content(&app, entry), trace);
520 assert!(!app.thinking_read_window.is_settling());
521
522 let cell = &app.active_cell.as_ref().unwrap().entries()[entry];
523 let options = app.transcript_render_options();
524 let (lines, action) = cell.lines_with_options_folded(60, options, None);
525 let rows: Vec<_> = lines.iter().map(ToString::to_string).collect();
526 assert_eq!(action, Some(CellFoldAction::Expand));
527 assert!(
528 rows.iter()
529 .any(|row| row.contains("› Lookup starts in config.rs."))
530 );
531 assert!(
532 rows.iter()
533 .any(|row| row.contains("› The fallback is relative."))
534 );
535 assert!(rows.last().unwrap().contains("Checking spaces"));
536 assert!(rows.iter().all(|row| !row.contains("source detail")));
537
538 let (expanded, action) =
539 cell.lines_with_options_folded(60, options, Some(TranscriptFold::Expanded));
540 assert_eq!(action, Some(CellFoldAction::Collapse));
541 assert_eq!(
542 expanded
543 .iter()
544 .filter(|row| row.to_string().contains("source detail"))
545 .count(),
546 30
547 );
548 let (hidden, _) = cell.lines_with_options_folded(
549 60,
550 crate::tui::history::TranscriptRenderOptions {
551 show_thinking: false,
552 ..options
553 },
554 None,
555 );
556 assert!(
557 hidden
558 .iter()
559 .all(|row| !row.to_string().contains("config.rs"))
560 );
561 }
562
563 #[test]
564 fn translation_placeholder_spinner_uses_full_motion_only() {
565 let mut app = test_app();
566 app.low_motion = false;
567 app.fancy_animations = true;
568 assert_eq!(translation_placeholder_spinner_frame(&app, 0.0), ">");
569 assert_eq!(translation_placeholder_spinner_frame(&app, 0.6), "\\");
570
571 app.low_motion = true;
572 assert_eq!(translation_placeholder_spinner_frame(&app, 0.0), "●");
573 assert_eq!(translation_placeholder_spinner_frame(&app, 0.6), "●");
574
575 app.low_motion = false;
576 app.fancy_animations = false;
577 assert_eq!(translation_placeholder_spinner_frame(&app, 0.0), "›");
578 assert_eq!(translation_placeholder_spinner_frame(&app, 0.6), "›");
579 }
580
581 /// #1620: a burst of reasoning chunks inside one throttle window must
582 /// coalesce to a single active-cell revision bump (so the renderer
583 /// re-wraps the live tail ~10x/sec instead of once per character), while
584 /// every byte of content is preserved and finalize forces a final bump.
585 #[test]
586 fn issue_1620_throttles_thinking_bumps_without_losing_content() {
587 let mut app = test_app();
588 let entry = ensure_active_entry(&mut app);
589 // `ensure_active_entry` bumped once on creation; start the measurement
590 // from a clean throttle window so the first append renders immediately.
591 app.thinking_revision_last_bump_at = None;
592 let rev_before = app.active_cell_revision;
593
594 let t0 = Instant::now();
595 let chunks = [
596 "Hel", "lo, ", "this", " is", " a", " lo", "ng", " re", "ason", "ing",
597 ];
598 // All ten chunks land within a single 100ms window (5ms apart).
599 for (i, chunk) in chunks.iter().enumerate() {
600 append_at(
601 &mut app,
602 entry,
603 chunk,
604 t0 + Duration::from_millis(i as u64 * 5),
605 );
606 }
607 assert_eq!(
608 app.active_cell_revision.wrapping_sub(rev_before),
609 1,
610 "rapid chunks within one throttle window must coalesce to one bump"
611 );
612
613 // A chunk after the window expires is allowed to bump again.
614 append_at(
615 &mut app,
616 entry,
617 " stream",
618 t0 + THINKING_REVISION_THROTTLE + Duration::from_millis(10),
619 );
620 assert_eq!(
621 app.active_cell_revision.wrapping_sub(rev_before),
622 2,
623 "a chunk past the throttle window should bump once more"
624 );
625
626 // No content was dropped despite the skipped intermediate bumps.
627 let expected = format!("{} stream", chunks.concat());
628 assert_eq!(thinking_content(&app, entry), expected);
629
630 // Red line: finalize forces exactly one bump and flushes the tail.
631 let rev_pre_final = app.active_cell_revision;
632 let finalized = finalize_active_entry(&mut app, Some(1.5), " [end]");
633 assert!(finalized, "finalize should report it finalized an entry");
634 assert_eq!(
635 app.active_cell_revision,
636 rev_pre_final.wrapping_add(1),
637 "finalize must always force exactly one revision bump"
638 );
639 assert_eq!(
640 thinking_content(&app, entry),
641 format!("{expected} [end]"),
642 "finalize must not drop the trailing reasoning text"
643 );
644 assert!(
645 app.thinking_revision_last_bump_at.is_none(),
646 "finalize should reset the throttle window for the next block"
647 );
648 }
649
650 #[test]
651 fn a_paused_stream_renders_the_reasoning_it_already_received() {
652 let mut app = test_app();
653 let entry = ensure_active_entry(&mut app);
654 app.thinking_revision_last_bump_at = None;
655 let t0 = Instant::now();
656 append_at(&mut app, entry, "first slice ", t0);
657 let shown = app.active_cell_revision;
658 append_at(&mut app, entry, "held back", t0 + Duration::from_millis(16));
659 assert_eq!(app.active_cell_revision, shown);
660
661 assert!(!render_owed_revision(
662 &mut app,
663 t0 + Duration::from_millis(32)
664 ));
665 assert_eq!(app.active_cell_revision, shown);
666 assert!(render_owed_revision(
667 &mut app,
668 t0 + THINKING_REVISION_THROTTLE
669 ));
670 assert_eq!(app.active_cell_revision, shown.wrapping_add(1));
671 assert!(!render_owed_revision(
672 &mut app,
673 t0 + THINKING_REVISION_THROTTLE * 3
674 ));
675 assert_eq!(app.active_cell_revision, shown.wrapping_add(1));
676 }
677
678 /// #7123: a reasoning block that opens while the display beat still holds
679 /// an uncommitted slice of prose must not drop that slice. `start_block`
680 /// resets `StreamingState`, so the tail has to be delivered first.
681 #[test]
682 fn issue_7123_reasoning_block_keeps_the_prose_tail_it_interrupts() {
683 let mut app = test_app();
684
685 // Prose streams, and the beat has not committed the last slice yet.
686 app.streaming_state.reset();
687 app.streaming_state.start_text(0);
688 app.streaming_state.push_content(0, "answer tail");
689 app.add_message(HistoryCell::Assistant {
690 content: "answer head ".to_string(),
691 streaming: true,
692 });
693 app.streaming_message_index = Some(app.history.len() - 1);
694
695 start_block(&mut app);
696
697 let prose = match app.history.last() {
698 Some(HistoryCell::Assistant { content, .. }) => content.clone(),
699 other => panic!("expected the assistant cell: {other:?}"),
700 };
701 assert_eq!(
702 prose, "answer head answer tail",
703 "the prose tail must reach the transcript before the reasoning block"
704 );
705 assert!(
706 app.streaming_state.block_is_thinking(0),
707 "the new block must be the reasoning block"
708 );
709 }
710
711 /// #7123: `MessageStarted` must deliver a live reasoning tail *before*
712 /// `flush_active_cell`, because that flush clears
713 /// `streaming_thinking_active_entry` on every path and only marks the cell
714 /// finished. Draining afterwards is dead code and the tail is lost.
715 #[test]
716 fn issue_7123_message_started_order_keeps_the_reasoning_tail() {
717 let mut app = test_app();
718 let entry = ensure_active_entry(&mut app);
719 app.thinking_started_at = Some(Instant::now());
720 app.streaming_state.reset();
721 app.streaming_state.start_thinking(0);
722 app.streaming_state.push_content(0, "reasoning tail");
723
724 // The real handler order.
725 assert!(finalize_current(&mut app));
726 stash_reasoning_buffer_into_last_reasoning(&mut app);
727 let before_flush = thinking_content(&app, entry);
728 app.flush_active_cell();
729
730 let flushed = app
731 .history
732 .iter()
733 .find_map(|cell| match cell {
734 HistoryCell::Thinking { content, .. } => Some(content.clone()),
735 _ => None,
736 })
737 .unwrap_or_default();
738 assert_eq!(
739 before_flush, "reasoning tail",
740 "finalize must deliver the tail into the entry while it is still live"
741 );
742 assert_eq!(
743 flushed, "reasoning tail",
744 "the flush must carry that tail into the transcript"
745 );
746 assert!(
747 app.streaming_thinking_active_entry.is_none(),
748 "flush_active_cell clears the pointer"
749 );
750
751 let mut translated = test_app();
752 translated.translation_enabled = true;
753 translated.thinking_started_at = Some(Instant::now());
754 let entry = ensure_active_entry(&mut translated);
755 set_placeholder(&mut translated, entry);
756 let placeholder = thinking_content(&translated, entry);
757 translated.streaming_state.start_thinking(0);
758 translated
759 .streaming_state
760 .push_content(0, "untranslated tail");
761 translated.reasoning_buffer.push_str("untranslated tail");
762 assert!(finalize_current(&mut translated));
763 assert_eq!(thinking_content(&translated, entry), placeholder);
764 stash_reasoning_buffer_into_last_reasoning(&mut translated);
765 assert_eq!(
766 translated.last_reasoning.as_deref(),
767 Some("untranslated tail")
768 );
769 }
770
771 /// #7123: with no live entry there is no cell to deliver into, so the
772 /// buffer must be left alone rather than drained and discarded.
773 #[test]
774 fn issue_7123_finalize_current_keeps_the_buffer_without_an_entry() {
775 let mut app = test_app();
776 app.streaming_thinking_active_entry = None;
777 app.streaming_state.reset();
778 app.streaming_state.start_thinking(0);
779 app.streaming_state.push_content(0, "orphan reasoning");
780
781 assert!(!finalize_current(&mut app));
782 assert_eq!(
783 app.streaming_state.pending_len(0),
784 "orphan reasoning".len(),
785 "text with nowhere to go must stay buffered"
786 );
787 }
788
789 /// #7123: `finalize_current` must take a reasoning tail but never consume a
790 /// text block that lost its boundary event.
791 #[test]
792 fn issue_7123_finalize_current_leaves_a_text_block_alone() {
793 let mut app = test_app();
794 let entry = ensure_active_entry(&mut app);
795 app.thinking_started_at = Some(Instant::now());
796
797 // A text block owns index 0 while a reasoning entry is live: a lost
798 // `ContentBlockStop` leaves the state in exactly this shape.
799 app.streaming_state.reset();
800 app.streaming_state.start_text(0);
801 app.streaming_state.push_content(0, "stray prose");
802
803 let _ = finalize_current(&mut app);
804
805 assert_eq!(
806 thinking_content(&app, entry),
807 "",
808 "prose must not be appended to the reasoning card"
809 );
810 }
811
812 /// #7454: a tool card appended after a live reasoning card makes that card
813 /// settled. More reasoning must open a new card below the tool, not grow
814 /// the card that now sits above it.
815 #[test]
816 fn issue_7454_reasoning_after_a_tool_opens_a_card_below_it() {
817 let mut app = test_app();
818
819 let first = ensure_active_entry(&mut app);
820 assert_eq!(first, 0);
821 append(&mut app, first, "plan the command");
822
823 // A tool lands in the same active cell, after the reasoning card.
824 let active = app.active_cell.as_mut().expect("active cell");
825 let tool = active.push_tool(
826 "t1",
827 HistoryCell::System {
828 content: "running".to_string(),
829 },
830 );
831 assert_eq!(tool, 1);
832
833 // The next delta must not grow the card above the tool.
834 let second = ensure_active_entry(&mut app);
835 assert_eq!(second, 2, "a fresh card opens below the tool");
836 assert_ne!(second, first, "the settled card must not be reused");
837
838 append(&mut app, second, "read the output");
839 assert_eq!(thinking_content(&app, first), "plan the command");
840 assert_eq!(thinking_content(&app, second), "read the output");
841 }
842
843 /// The guard must not churn when nothing was appended: a plain reasoning
844 /// stream keeps one card.
845 #[test]
846 fn issue_7454_a_stream_with_no_sibling_keeps_one_card() {
847 let mut app = test_app();
848
849 let first = ensure_active_entry(&mut app);
850 append(&mut app, first, "a");
851 assert_eq!(ensure_active_entry(&mut app), first);
852 append(&mut app, first, "b");
853 assert_eq!(ensure_active_entry(&mut app), first);
854 assert_eq!(thinking_content(&app, first), "ab");
855 }
856
857 /// A card whose entry is gone must not be reused either: the pointer would
858 /// name an index that no longer exists.
859 #[test]
860 fn issue_7454_a_stale_pointer_opens_a_new_card() {
861 let mut app = test_app();
862
863 let first = ensure_active_entry(&mut app);
864 append(&mut app, first, "gone");
865 app.flush_active_cell();
866 // `flush_active_cell` clears the pointer; pin the defensive path by
867 // restoring a stale one.
868 app.active_cell = Some(ActiveCell::new());
869 app.streaming_thinking_active_entry = Some(first);
870
871 let fresh = ensure_active_entry(&mut app);
872 assert_eq!(
873 app.active_cell
874 .as_ref()
875 .map_or(0, |active| active.entry_count()),
876 1,
877 "a stale pointer must open exactly one card, not reuse the dead index"
878 );
879 assert_eq!(thinking_content(&app, fresh), "");
880 }
881
882 /// The bytes a beat has not revealed yet were all received before the
883 /// sibling, so the split must land them in the card above it. Only the
884 /// delta that triggers the split belongs to the new card.
885 #[test]
886 fn issue_7454_unrevealed_bytes_stay_in_the_card_above_the_tool() {
887 let mut app = test_app();
888
889 let first = ensure_active_entry(&mut app);
890 app.streaming_state.reset();
891 app.streaming_state.start_thinking(0);
892 app.streaming_state.push_content(0, "above the tool");
893
894 let active = app.active_cell.as_mut().expect("active cell");
895 let _ = active.push_tool(
896 "t1",
897 HistoryCell::System {
898 content: "running".to_string(),
899 },
900 );
901
902 // The handler's order: split, and the split drains what was pending.
903 let second = ensure_active_entry(&mut app);
904 assert_ne!(second, first);
905 assert_eq!(
906 thinking_content(&app, first),
907 "above the tool",
908 "bytes received before the sibling stay above it"
909 );
910 assert_eq!(
911 thinking_content(&app, second),
912 "",
913 "the new card starts with nothing"
914 );
915 assert_eq!(
916 app.streaming_state.pending_len(0),
917 0,
918 "the split leaves no pending bytes behind"
919 );
920 }
921
922 /// #7454, translation: the settled card cannot be the translation target any
923 /// more, so it must show its own text instead of re-framing a placeholder
924 /// nothing will ever replace. The delta that triggers the split belongs to
925 /// the new card: `ThinkingDelta` splits before it records the text.
926 #[test]
927 fn issue_7454_a_split_card_shows_its_text_instead_of_a_placeholder() {
928 let mut app = test_app();
929 app.translation_enabled = true;
930
931 let first = ensure_active_entry(&mut app);
932 set_placeholder(&mut app, first);
933
934 // Delta 1, in handler order: split (a no-op here), then record.
935 app.reasoning_buffer.push_str("first段");
936 app.streaming_state.push_content(0, "first段");
937
938 let active = app.active_cell.as_mut().expect("active cell");
939 let _ = active.push_tool(
940 "t1",
941 HistoryCell::System {
942 content: "running".to_string(),
943 },
944 );
945
946 // Delta 2, in handler order: split first, then record.
947 let second = ensure_active_entry(&mut app);
948 app.reasoning_buffer.push_str("second段");
949
950 assert_ne!(second, first, "the split must open a new card");
951 assert_eq!(
952 thinking_content(&app, first),
953 "first段",
954 "the settled card keeps its own text, not a spinning placeholder"
955 );
956 assert_eq!(
957 app.last_reasoning.as_deref(),
958 Some("first段"),
959 "the settled card's text moves to last_reasoning"
960 );
961 assert_eq!(
962 app.reasoning_buffer, "second段",
963 "the delta that triggered the split belongs to the new card"
964 );
965 assert_eq!(
966 thinking_content(&app, second),
967 "",
968 "the new card starts empty so its own translation lands there"
969 );
970 }
971 }
972
972 lines RUST