返回 CodeWhale
mod.rs
根目录 / crates / tui-kit / src / streaming / mod.rs
1 //! Provider-delta ingest for display-clock rendering.
2 //!
3 //! Provider deltas arrive as dozens of tiny SSE chunks. This module buffers
4 //! them without mutating the visible transcript ([`StreamBuffer`]) and bounds
5 //! both how often that buffer is flushed ([`StreamDisplayClock`]) and how much
6 //! each beat may uncover ([`reveal_budget`]), so the pace a reader sees is set
7 //! by the clock rather than by how the provider happened to chunk its output.
8 //!
9 //! Deltas are *input*, never animation timing. A commit beat reveals a bounded
10 //! slice at [`REVEAL_PER_SECOND`], so the pace a reader sees is the same
11 //! whatever shape the provider's chunks arrive in. There is still no
12 //! per-grapheme typewriter and no adaptive drain policy. A two-gear "adaptive
13 //! chunking" policy lived here until v0.9.4; it could never emit anything other
14 //! than "drain everything available", so it was deleted rather than wired up.
15 //! What replaced it is not that policy: it takes a measured slice per beat
16 //! instead of deciding between two gears.
17 //!
18 //! Buffering never changes what the model emitted: a delta reaches a cell only
19 //! when a commit beat takes it, but the bytes are never dropped. The
20 //! `accumulated_text` / `accumulated_thinking` counters on [`StreamingState`]
21 //! are diagnostic only — nothing in the product reads them — and
22 //! [`StreamingState::reset`] clears them at a block boundary, so they describe
23 //! the current block rather than the whole response.
24 //!
25 //! # Known limitations
26 //!
27 //! - **Latency is backlog over rate, not a fixed window.** The ceiling caps how
28 //! fast bytes become visible, so a receipt larger than one beat's slice takes
29 //! `backlog / REVEAL_PER_SECOND` to finish. A 4 KiB burst takes about 1.7 s to
30 //! uncover. That is the deliberate trade (even pace over minimum latency) and
31 //! it is not configurable.
32 //! - **A receipt that lands after a long pause is shown whole.** A pause
33 //! longer than the beat interval leaves the next beat due immediately, and
34 //! finalization takes a [`StreamDisplayClock::flush_now`] forced beat that
35 //! drains everything buffered, bypassing pacing entirely — so very large
36 //! receipts still land in one step.
37 //! - **Tool output does not pass through here.** It is unbuffered and has no
38 //! pacing of its own.
39 //! - **Catch-up is staged, not wired.** [`CATCH_UP_QUEUE_DEPTH`] and
40 //! [`CATCH_UP_OLDEST_AGE`] exist and are tested, but every production drain
41 //! site calls `note_delta` with a queue depth of 1, so catch-up never fires.
42 //! See the honesty note in `docs/MOTION_CONTRACT.md`.
43 //! - **Nothing measures this.** There is no benchmark and no budget for reveal
44 //! throughput or visible latency; the numbers in the commit that introduced
45 //! paced reveal came from a throwaway harness. See the runtime-perf-gate gap.
46 //!
47 //! Newline-boundary safety (never showing a half-written code fence) is owned
48 //! by the incremental markdown parser downstream — see
49 //! `ParseState::commit_complete_lines` in `tui/markdown_render.rs`, which
50 //! leaves the trailing partial line uncommitted and re-parses it each tick.
51 //! A separate `LineBuffer` gate used to sit here, but both constructors
52 //! bypassed it, so it protected nothing and was removed with the policy.
53
54 use std::time::Duration;
55 use std::time::Instant;
56
57 /// Default cadence for moving queued provider deltas into visible transcript
58 /// text. This intentionally tracks animation frames rather than upstream SSE
59 /// cadence, so tiny bursty deltas coalesce into one history/cache mutation.
60 ///
61 /// ~60 FPS (16ms). Full motion may catch up sooner when backlog crosses
62 /// [`CATCH_UP_QUEUE_DEPTH`] / [`CATCH_UP_OLDEST_AGE`]; reduced motion never
63 /// accelerates — it stays on this steady clock (not a slow typewriter).
64 pub const DEFAULT_STREAM_COMMIT_INTERVAL: Duration = Duration::from_millis(16);
65
66 /// Queue-depth threshold that pulls the display clock forward (catch-up).
67 ///
68 /// Staged, not live: every production drain site calls
69 /// [`StreamDisplayClock::note_delta`] (queued = 1), so catch-up never fires
70 /// today. See the honesty note in `docs/MOTION_CONTRACT.md`.
71 pub const CATCH_UP_QUEUE_DEPTH: usize = 160;
72
73 /// Oldest-chunk age that pulls the display clock forward (catch-up).
74 /// Staged alongside [`CATCH_UP_QUEUE_DEPTH`].
75 pub const CATCH_UP_OLDEST_AGE: Duration = Duration::from_millis(1_200);
76
77 /// Ceiling on how fast received text may become visible, in bytes per second.
78 ///
79 /// This is the pace the reader sees. At the display clock's beat it is also the
80 /// size of one step, so the visible text advances by roughly the same amount
81 /// every beat instead of in provider-sized chunks.
82 ///
83 /// Set several times a fast model's own output rate (a brisk stream is a few
84 /// hundred bytes per second): ordinary streaming is then limited by when the
85 /// bytes arrive, not by this ceiling, and receives no artificial delay. The
86 /// ceiling only spreads a burst that lands ahead of that rate.
87 pub const REVEAL_PER_SECOND: usize = 2_400;
88
89 /// How many bytes may become visible on a beat that is `interval` long, given
90 /// `backlog` bytes waiting.
91 #[must_use]
92 pub fn reveal_budget(interval: Duration, backlog: usize) -> usize {
93 if backlog == 0 {
94 return 0;
95 }
96 let per_beat = (REVEAL_PER_SECOND as u128 * interval.as_nanos() / 1_000_000_000) as usize;
97 per_beat.max(1).min(backlog)
98 }
99
100 /// Frame-clock gate for stream display commits.
101 ///
102 /// Provider deltas may arrive in dozens of tiny chunks inside one event-loop
103 /// drain. This clock lets the TUI ingest those bytes cheaply, then mutate the
104 /// visible transcript at most once per display beat unless the stream is being
105 /// finalized or measured backlog demands catch-up.
106 #[derive(Debug, Clone)]
107 pub struct StreamDisplayClock {
108 interval: Duration,
109 pending: bool,
110 next_due_at: Option<Instant>,
111 last_commit_at: Option<Instant>,
112 commit_count: u64,
113 catch_up_count: u64,
114 /// When true, backlog may pull `next_due_at` forward to `now`.
115 allow_catch_up: bool,
116 }
117
118 impl Default for StreamDisplayClock {
119 fn default() -> Self {
120 Self::new(DEFAULT_STREAM_COMMIT_INTERVAL)
121 }
122 }
123
124 impl StreamDisplayClock {
125 pub fn new(interval: Duration) -> Self {
126 Self {
127 interval,
128 pending: false,
129 next_due_at: None,
130 last_commit_at: None,
131 commit_count: 0,
132 catch_up_count: 0,
133 allow_catch_up: true,
134 }
135 }
136
137 /// Enable/disable catch-up acceleration. Reduced motion keeps the steady
138 /// clock and never pulls beats forward.
139 pub fn set_allow_catch_up(&mut self, allow: bool) {
140 self.allow_catch_up = allow;
141 }
142
143 /// Note that at least one stream delta is waiting to become visible.
144 pub fn note_delta(&mut self, now: Instant) {
145 self.note_delta_with_backlog(now, 1, None);
146 }
147
148 /// Note a delta together with measured queue pressure.
149 ///
150 /// Normal motion coalesces onto the steady interval unless backlog crosses
151 /// the catch-up thresholds, in which case the next beat is due immediately.
152 pub fn note_delta_with_backlog(
153 &mut self,
154 now: Instant,
155 queued: usize,
156 oldest_age: Option<Duration>,
157 ) {
158 self.pending = true;
159 let catch_up = self.allow_catch_up
160 && (queued >= CATCH_UP_QUEUE_DEPTH
161 || oldest_age.is_some_and(|age| age >= CATCH_UP_OLDEST_AGE));
162
163 if catch_up {
164 self.next_due_at = Some(now);
165 self.catch_up_count = self.catch_up_count.saturating_add(1);
166 return;
167 }
168
169 if self.next_due_at.is_some() {
170 return;
171 }
172 self.next_due_at = Some(match self.last_commit_at {
173 Some(last) => last.checked_add(self.interval).unwrap_or(now).max(now),
174 None => now,
175 });
176 }
177
178 /// Returns the time until the pending commit is due, if any.
179 pub fn due_in(&self, now: Instant) -> Option<Duration> {
180 let due = self.next_due_at?;
181 Some(due.saturating_duration_since(now))
182 }
183
184 /// Consume a due commit beat.
185 pub fn take_due(&mut self, now: Instant) -> bool {
186 if !self.pending {
187 self.next_due_at = None;
188 return false;
189 }
190 let Some(due) = self.next_due_at else {
191 return false;
192 };
193 if now < due {
194 return false;
195 }
196 self.pending = false;
197 self.next_due_at = None;
198 self.last_commit_at = Some(now);
199 self.commit_count = self.commit_count.saturating_add(1);
200 true
201 }
202
203 /// Force a commit beat, used when the stream is being finalized.
204 pub fn flush_now(&mut self, now: Instant) -> bool {
205 let had_pending = self.pending;
206 self.pending = false;
207 self.next_due_at = None;
208 if had_pending {
209 self.last_commit_at = Some(now);
210 self.commit_count = self.commit_count.saturating_add(1);
211 }
212 had_pending
213 }
214
215 pub fn reset(&mut self) {
216 self.pending = false;
217 self.next_due_at = None;
218 self.last_commit_at = None;
219 self.commit_count = 0;
220 self.catch_up_count = 0;
221 }
222
223 /// The configured beat length, so a caller can size work per beat.
224 #[must_use]
225 pub fn interval(&self) -> Duration {
226 self.interval
227 }
228
229 /// Number of commit beats consumed since the last reset (observability).
230 #[cfg(test)]
231 pub fn commit_count(&self) -> u64 {
232 self.commit_count
233 }
234
235 /// Number of beats pulled forward by backlog since the last reset
236 /// (observability; see the staged-catch-up note on
237 /// [`CATCH_UP_QUEUE_DEPTH`]).
238 #[cfg(test)]
239 pub fn catch_up_count(&self) -> u64 {
240 self.catch_up_count
241 }
242 }
243
244 /// Buffers raw provider deltas between display-clock beats.
245 ///
246 /// One buffer per active block (assistant / thinking). Tool output is
247 /// unbuffered and bypasses this path entirely. Each commit beat takes a
248 /// bounded slice ([`StreamBuffer::take_up_to`]) so the visible text advances
249 /// at a steady rate rather than in provider-sized steps.
250 #[derive(Debug, Default, Clone)]
251 pub struct StreamBuffer {
252 pending: String,
253 }
254
255 impl StreamBuffer {
256 pub fn new() -> Self {
257 Self::default()
258 }
259
260 /// Append a raw model delta.
261 pub fn push_delta(&mut self, delta: &str) {
262 self.pending.push_str(delta);
263 }
264
265 /// Whether any text is waiting for the next commit beat.
266 pub fn has_pending(&self) -> bool {
267 !self.pending.is_empty()
268 }
269
270 /// Take at most `budget` bytes, leaving the rest for a later beat.
271 ///
272 /// The cut lands on a grapheme boundary: slicing through a cluster would
273 /// flash a broken glyph for one beat. A budget too small to hold the next
274 /// cluster still takes that cluster whole, so a drain can never stall.
275 pub fn take_up_to(&mut self, budget: usize) -> String {
276 use unicode_segmentation::UnicodeSegmentation;
277 if budget >= self.pending.len() {
278 return std::mem::take(&mut self.pending);
279 }
280 let mut end = budget.min(self.pending.len());
281 while end > 0 && !self.pending.is_char_boundary(end) {
282 end -= 1;
283 }
284 if end > 0 {
285 end = self
286 .pending
287 .grapheme_indices(true)
288 .map(|(index, _)| index)
289 .take_while(|index| *index <= end)
290 .last()
291 .unwrap_or(0);
292 }
293 if end == 0 {
294 end = self.pending.graphemes(true).next().map_or(0, str::len);
295 }
296 let rest = self.pending.split_off(end);
297 std::mem::replace(&mut self.pending, rest)
298 }
299
300 /// Bytes waiting for a later beat.
301 pub fn pending_len(&self) -> usize {
302 self.pending.len()
303 }
304
305 /// Take everything buffered since the previous beat.
306 pub fn take(&mut self) -> String {
307 std::mem::take(&mut self.pending)
308 }
309 }
310
311 /// Per-block streaming substate.
312 ///
313 /// ```text
314 /// raw delta -> StreamBuffer.push_delta -> commit beat -> take -> transcript
315 /// ```
316 #[derive(Debug, Default)]
317 struct BlockState {
318 /// Thinking blocks route to `accumulated_thinking`; text blocks to
319 /// `accumulated_text`.
320 is_thinking: bool,
321 /// Cleared once the block has been finalized.
322 is_streaming: bool,
323 /// Deltas received but not yet flushed to the transcript.
324 buffer: StreamBuffer,
325 }
326
327 /// State for managing multiple stream buffers (one per content block)
328 #[derive(Debug, Default)]
329 pub struct StreamingState {
330 /// Per-block state by index.
331 blocks: Vec<Option<BlockState>>,
332 /// Whether any stream is currently active
333 pub is_active: bool,
334 /// Per-kind byte totals for the current block. Diagnostic only: replay
335 /// reads `App::last_reasoning` and `current_streaming_text`, not these, and
336 /// `reset` clears them at every block boundary. A relabel leaves the bytes
337 /// already collected under the old kind, so after one they no longer match
338 /// the block's current kind.
339 pub accumulated_text: String,
340 /// See [`StreamingState::accumulated_text`].
341 pub accumulated_thinking: String,
342 }
343
344 impl StreamingState {
345 /// Create a new streaming state
346 pub fn new() -> Self {
347 Self::default()
348 }
349
350 /// Start a new text block. Assistant prose is buffered until the next
351 /// display-clock beat so provider bursts produce one visible mutation.
352 pub fn start_text(&mut self, index: usize) {
353 self.start_block(index, false);
354 }
355
356 /// Start a new thinking block. Thinking deltas are buffered exactly like
357 /// assistant prose — long reasoning often arrives as one paragraph with no
358 /// intermediate newlines, so nothing here waits on a line boundary.
359 pub fn start_thinking(&mut self, index: usize) {
360 self.start_block(index, true);
361 }
362
363 fn start_block(&mut self, index: usize, is_thinking: bool) {
364 self.ensure_capacity(index);
365 self.blocks[index] = Some(BlockState {
366 is_thinking,
367 is_streaming: true,
368 buffer: StreamBuffer::new(),
369 });
370 self.is_active = true;
371 }
372
373 /// Push content to a block.
374 ///
375 /// The bytes land in the display buffer and in the block's own accumulated
376 /// counter, which follows the routed kind. The counters are diagnostic —
377 /// replay reads `App::last_reasoning` and `current_streaming_text` — and
378 /// [`StreamingState::reset`] clears them at every block boundary.
379 pub fn push_content(&mut self, index: usize, content: &str) {
380 if let Some(Some(block)) = self.blocks.get_mut(index) {
381 if block.is_thinking {
382 self.accumulated_thinking.push_str(content);
383 } else {
384 self.accumulated_text.push_str(content);
385 }
386 block.buffer.push_delta(content);
387 }
388 }
389
390 /// Run one commit beat and return the text to flush to the transcript,
391 /// taking at most `budget` bytes. Empty when nothing arrived since the
392 /// previous beat or the budget admits none.
393 pub fn commit_text(&mut self, index: usize, budget: usize) -> String {
394 match self.blocks.get_mut(index) {
395 Some(Some(block)) => block.buffer.take_up_to(budget),
396 _ => String::new(),
397 }
398 }
399
400 /// Re-label the block at `index` without disturbing anything else.
401 ///
402 /// A block's kind is normally decided by its start event, but a gateway
403 /// can open a text block inside a thinking stream (or the reverse) and
404 /// keep sending deltas of the first kind. `reset` clears every block and
405 /// both accumulated counters; a relabel touches one block's routed kind and
406 /// replaces its pending buffer. The caller must deliver that pending tail
407 /// to the cell the old kind owned first: it is discarded here.
408 pub fn set_block_kind(&mut self, index: usize, is_thinking: bool) {
409 self.ensure_capacity(index);
410 match self.blocks.get_mut(index) {
411 Some(Some(block)) => {
412 block.is_thinking = is_thinking;
413 block.is_streaming = true;
414 block.buffer = StreamBuffer::new();
415 self.is_active = true;
416 }
417 _ => self.start_block(index, is_thinking),
418 }
419 }
420
421 /// Whether the block at `index` carries reasoning text.
422 ///
423 /// Display beats must route a committed delta by the block's own kind.
424 /// An assistant cell can already be live when a later thinking block
425 /// starts inside the same response, so the mere presence of a streaming
426 /// message index does not say which cell the delta belongs to (#7123).
427 pub fn block_is_thinking(&self, index: usize) -> bool {
428 matches!(self.blocks.get(index), Some(Some(block)) if block.is_thinking)
429 }
430
431 /// Bytes waiting in a block's buffer.
432 pub fn pending_len(&self, index: usize) -> usize {
433 self.blocks
434 .get(index)
435 .and_then(|b| b.as_ref())
436 .map_or(0, |b| b.buffer.pending_len())
437 }
438
439 /// Whether a block holds text waiting to be flushed by the next commit
440 /// beat. Callers use this to keep the display clock ticking while a
441 /// buffer drains.
442 pub fn has_pending_stream_text(&self, index: usize) -> bool {
443 self.blocks
444 .get(index)
445 .and_then(|b| b.as_ref())
446 .is_some_and(|b| b.buffer.has_pending())
447 }
448
449 /// Finalize a block and return whatever text it still holds.
450 pub fn finalize_block_text(&mut self, index: usize) -> String {
451 let out = match self.blocks.get_mut(index) {
452 Some(Some(block)) => {
453 block.is_streaming = false;
454 block.buffer.take()
455 }
456 _ => return String::new(),
457 };
458 self.check_active();
459 out
460 }
461
462 /// Check if any stream is still active
463 fn check_active(&mut self) {
464 self.is_active = self.blocks.iter().flatten().any(|b| b.is_streaming);
465 }
466
467 /// Ensure capacity for the given index
468 fn ensure_capacity(&mut self, index: usize) {
469 while self.blocks.len() <= index {
470 self.blocks.push(None);
471 }
472 }
473
474 /// Reset the streaming state
475 pub fn reset(&mut self) {
476 self.blocks.clear();
477 self.is_active = false;
478 self.accumulated_text.clear();
479 self.accumulated_thinking.clear();
480 }
481 }
482
483 #[cfg(test)]
484 mod tests {
485 use super::*;
486
487 #[test]
488 fn set_block_kind_reroutes_the_next_delta() {
489 let mut state = StreamingState::new();
490 state.start_text(0);
491 state.push_content(0, "prose ");
492 assert!(!state.block_is_thinking(0));
493
494 // The caller delivers the pending tail to the cell the old kind owned
495 // before relabeling; the relabel installs a fresh buffer and routes the
496 // next delta to the other kind.
497 assert_eq!(state.finalize_block_text(0), "prose ");
498 state.set_block_kind(0, true);
499 assert!(state.block_is_thinking(0));
500
501 state.push_content(0, "reasoning");
502 assert_eq!(state.commit_text(0, usize::MAX), "reasoning");
503
504 // And back again: prose after an interposed thinking block.
505 assert_eq!(state.finalize_block_text(0), "");
506 state.set_block_kind(0, false);
507 assert!(!state.block_is_thinking(0));
508 state.push_content(0, "tail");
509 assert_eq!(state.commit_text(0, usize::MAX), "tail");
510 }
511
512 /// A second beat must be taken on one time base. `note_delta` schedules the
513 /// next beat at `last_commit_at + interval`, so a caller that re-reads the
514 /// wall clock between beats and ticks at `now + 50ms` can land before the
515 /// beat is due and commit nothing — the delta then sits in the buffer until
516 /// some later beat.
517 #[test]
518 fn a_second_beat_needs_one_time_base_not_a_fresh_wall_clock() {
519 let interval = Duration::from_millis(33);
520 let t0 = Instant::now();
521
522 let mut clock = StreamDisplayClock::new(interval);
523 clock.note_delta(t0);
524 assert!(clock.take_due(t0 + Duration::from_millis(50)));
525
526 // The wrong shape: schedule from a moment inside the interval, then tick
527 // before `last_commit + interval` has passed.
528 clock.note_delta(t0 + Duration::from_millis(55));
529 assert!(
530 !clock.take_due(t0 + Duration::from_millis(60)),
531 "a tick inside the interval must not commit"
532 );
533
534 // The right shape: one base, and a tick past `last_commit + interval`.
535 let mut clock = StreamDisplayClock::new(interval);
536 let mut state = StreamingState::new();
537 state.start_thinking(0);
538 state.push_content(0, "first half. ");
539 clock.note_delta(t0);
540 assert!(clock.take_due(t0 + Duration::from_millis(50)));
541 let first = state.commit_text(0, reveal_budget(interval, state.pending_len(0)));
542 assert_eq!(first, "first half. ");
543
544 state.push_content(0, "second half.");
545 clock.note_delta(t0 + Duration::from_millis(60));
546 assert!(
547 clock.take_due(t0 + Duration::from_millis(200)),
548 "a tick past the interval must be due"
549 );
550 let second = state.commit_text(0, reveal_budget(interval, state.pending_len(0)));
551 assert_eq!(second, "second half.");
552 }
553
554 #[test]
555 fn assistant_text_streams_before_newline() {
556 let mut state = StreamingState::new();
557 state.start_text(0);
558 state.push_content(0, "hello world");
559
560 assert_eq!(state.commit_text(0, usize::MAX), "hello world");
561 assert!(!state.has_pending_stream_text(0));
562 }
563
564 #[test]
565 fn thinking_text_streams_before_newline() {
566 let mut state = StreamingState::new();
567 state.start_thinking(0);
568 state.push_content(0, "thinking deeply");
569
570 assert_eq!(state.commit_text(0, usize::MAX), "thinking deeply");
571 assert!(!state.has_pending_stream_text(0));
572 }
573
574 #[test]
575 fn commit_beat_drains_everything_received_since_the_previous_beat() {
576 // A burst arriving "at once" is displayed at the same cadence instead
577 // of being synthetically dripped and flushed at end of turn.
578 let mut state = StreamingState::new();
579 state.start_text(0);
580
581 let burst = "abcdefghijklmnopqrstuvwxyz".repeat(8);
582 state.push_content(0, &burst);
583 assert_eq!(state.commit_text(0, usize::MAX), burst);
584 // Second beat with nothing new is empty, not a replay.
585 assert_eq!(state.commit_text(0, usize::MAX), "");
586 }
587
588 #[test]
589 fn combining_marks_stay_with_their_base_letter() {
590 let mut state = StreamingState::new();
591 state.start_text(0);
592 state.push_content(0, "e\u{301}x");
593 assert_eq!(state.commit_text(0, usize::MAX), "e\u{301}x");
594 }
595
596 #[test]
597 fn finalize_drains_partial_tail() {
598 // The final, possibly-unterminated line must survive finalization.
599 let mut state = StreamingState::new();
600 state.start_text(0);
601 state.push_content(0, "done\nno-newline-here");
602 assert_eq!(state.finalize_block_text(0), "done\nno-newline-here");
603 assert!(!state.is_active);
604 }
605
606 #[test]
607 fn finalize_after_commit_has_nothing_left() {
608 let mut state = StreamingState::new();
609 state.start_text(0);
610 state.push_content(0, "abc");
611 assert_eq!(state.commit_text(0, usize::MAX), "abc");
612 assert_eq!(state.finalize_block_text(0), "");
613 }
614
615 #[test]
616 fn accumulators_track_raw_stream_by_block_kind() {
617 let mut state = StreamingState::new();
618 state.start_thinking(0);
619 state.push_content(0, "reasoning");
620 state.start_text(1);
621 state.push_content(1, "answer");
622
623 assert_eq!(state.accumulated_thinking, "reasoning");
624 assert_eq!(state.accumulated_text, "answer");
625 }
626
627 #[test]
628 fn bursty_stream_state_has_no_text_loss_after_coalesced_flushes() {
629 let mut state = StreamingState::new();
630 state.start_text(0);
631 let mut expected = String::new();
632
633 for idx in 0..250 {
634 let chunk = format!("{idx}.");
635 expected.push_str(&chunk);
636 state.push_content(0, &chunk);
637 }
638
639 let first_flush = state.commit_text(0, usize::MAX);
640 assert_eq!(first_flush, expected);
641 assert_eq!(state.finalize_block_text(0), "");
642 }
643
644 #[test]
645 fn stream_display_clock_coalesces_bursty_tiny_deltas() {
646 let interval = Duration::from_millis(33);
647 let mut clock = StreamDisplayClock::new(interval);
648 let t0 = Instant::now();
649
650 for _ in 0..100 {
651 clock.note_delta(t0);
652 }
653
654 assert_eq!(clock.due_in(t0), Some(Duration::ZERO));
655 assert!(clock.take_due(t0));
656 assert_eq!(clock.commit_count(), 1);
657
658 for _ in 0..25 {
659 clock.note_delta(t0 + Duration::from_millis(5));
660 }
661 assert!(!clock.take_due(t0 + Duration::from_millis(5)));
662 assert_eq!(
663 clock.due_in(t0 + Duration::from_millis(5)),
664 Some(Duration::from_millis(28))
665 );
666 assert!(clock.take_due(t0 + interval));
667 assert_eq!(clock.commit_count(), 2);
668 }
669
670 #[test]
671 fn stream_display_clock_bounds_long_reasoning_commit_count() {
672 let interval = Duration::from_millis(33);
673 let mut clock = StreamDisplayClock::new(interval);
674 let t0 = Instant::now();
675 let mut commits = 0u64;
676
677 for millis in 0..300 {
678 let now = t0 + Duration::from_millis(millis);
679 clock.note_delta(now);
680 if clock.take_due(now) {
681 commits += 1;
682 }
683 }
684
685 assert!(commits > 1, "long streams should keep advancing visibly");
686 assert!(
687 commits <= 11,
688 "300 one-ms deltas should not commit on provider cadence: {commits}"
689 );
690 assert_eq!(commits, clock.commit_count());
691 }
692
693 #[test]
694 fn stream_display_clock_final_flush_consumes_pending_delta() {
695 let mut clock = StreamDisplayClock::new(Duration::from_millis(33));
696 let t0 = Instant::now();
697
698 clock.note_delta(t0);
699 assert!(clock.take_due(t0));
700 clock.note_delta(t0 + Duration::from_millis(4));
701
702 assert!(!clock.take_due(t0 + Duration::from_millis(4)));
703 assert!(clock.flush_now(t0 + Duration::from_millis(5)));
704 assert_eq!(clock.due_in(t0 + Duration::from_millis(5)), None);
705 assert!(!clock.take_due(t0 + Duration::from_millis(33)));
706 assert_eq!(clock.commit_count(), 2);
707 }
708
709 #[test]
710 fn normal_clock_catch_up_only_when_backlog_crosses_threshold() {
711 let interval = Duration::from_millis(33);
712 let mut clock = StreamDisplayClock::new(interval);
713 let t0 = Instant::now();
714
715 clock.note_delta(t0);
716 assert!(clock.take_due(t0));
717 // Small backlog after a commit stays on the steady interval.
718 clock.note_delta_with_backlog(
719 t0 + Duration::from_millis(1),
720 3,
721 Some(Duration::from_millis(5)),
722 );
723 assert!(!clock.take_due(t0 + Duration::from_millis(1)));
724 assert_eq!(clock.catch_up_count(), 0);
725
726 // Measured backlog crosses the catch-up threshold → due immediately.
727 clock.note_delta_with_backlog(
728 t0 + Duration::from_millis(2),
729 CATCH_UP_QUEUE_DEPTH,
730 Some(Duration::from_millis(10)),
731 );
732 assert!(clock.take_due(t0 + Duration::from_millis(2)));
733 assert!(clock.catch_up_count() >= 1);
734 }
735
736 #[test]
737 fn reduced_motion_keeps_steady_clock_without_catch_up_or_typewriter() {
738 let interval = Duration::from_millis(33);
739 let mut clock = StreamDisplayClock::new(interval);
740 clock.set_allow_catch_up(false);
741 let t0 = Instant::now();
742
743 clock.note_delta(t0);
744 assert!(clock.take_due(t0));
745 clock.note_delta_with_backlog(
746 t0 + Duration::from_millis(1),
747 CATCH_UP_QUEUE_DEPTH * 2,
748 Some(CATCH_UP_OLDEST_AGE),
749 );
750 // Reduced motion must not pull the beat forward.
751 assert!(!clock.take_due(t0 + Duration::from_millis(1)));
752 assert_eq!(clock.catch_up_count(), 0);
753 assert_eq!(
754 clock.due_in(t0 + Duration::from_millis(1)),
755 Some(Duration::from_millis(32))
756 );
757 assert!(clock.take_due(t0 + interval));
758 // Same interval as full motion — not a slower artificial typewriter.
759 assert_eq!(clock.commit_count(), 2);
760 }
761
762 #[test]
763 fn reveal_budget_is_a_steady_step_and_always_progresses() {
764 let interval = DEFAULT_STREAM_COMMIT_INTERVAL;
765 let full = reveal_budget(interval, usize::MAX);
766 assert_eq!(full, REVEAL_PER_SECOND * 16 / 1000);
767 // A backlog smaller than one step is taken whole, so a small receipt
768 // is never slowed down by the ceiling.
769 assert_eq!(reveal_budget(interval, 3), 3);
770 // Nothing waiting means nothing to reveal.
771 assert_eq!(reveal_budget(interval, 0), 0);
772 // A budget too small to hold a character still admits progress.
773 assert!(reveal_budget(Duration::from_nanos(1), 10_000) >= 1);
774 }
775
776 #[test]
777 fn a_burst_is_spread_across_beats_instead_of_landing_at_once() {
778 // The defect this guards: the whole buffer used to move to the
779 // transcript on the first beat, so the reader saw provider-sized jumps.
780 let interval = DEFAULT_STREAM_COMMIT_INTERVAL;
781 let burst = "x".repeat(2_000);
782 let mut state = StreamingState::default();
783 state.start_text(0);
784 state.push_content(0, &burst);
785
786 let step = reveal_budget(interval, state.pending_len(0));
787 assert!(
788 step < burst.len() / 4,
789 "one beat took {step} of {} bytes",
790 burst.len()
791 );
792
793 let mut revealed = String::new();
794 for beat in 0..200 {
795 let budget = reveal_budget(interval, state.pending_len(0));
796 let taken = state.commit_text(0, budget);
797 assert!(taken.len() <= budget, "beat {beat} overspent its budget");
798 revealed.push_str(&taken);
799 if !state.has_pending_stream_text(0) {
800 break;
801 }
802 }
803 assert_eq!(revealed, burst, "every byte must arrive, in order");
804 }
805
806 #[test]
807 fn take_up_to_never_splits_a_character_and_always_progresses() {
808 let mut buffer = StreamBuffer::new();
809 buffer.push_delta("a👩🏽‍💻b");
810 // A budget that cannot hold the emoji still yields it whole rather
811 // than stalling the drain forever.
812 assert_eq!(buffer.take_up_to(1), "a");
813 assert_eq!(buffer.take_up_to(1), "👩🏽‍💻");
814 assert!(buffer.has_pending());
815 assert_eq!(buffer.take_up_to(usize::MAX), "b");
816 assert!(!buffer.has_pending());
817 }
818 }
819
820 /// Runtime performance gate for the reveal path (#6193 first slice).
821 #[cfg(test)]
822 #[path = "tests/perf_gate.rs"]
823 mod perf_gate;
824
824 lines RUST