返回 CodeWhale
live_transcript.rs
根目录 / crates / tui / src / tui / live_transcript.rs
1 //! Full-screen live transcript overlay with sticky-bottom auto-scroll (#94).
2 //!
3 //! Toggled with `Ctrl+Shift+T` while the engine is streaming (`Ctrl+T` now
4 //! cycles reasoning effort). Behaviour:
5 //!
6 //! - At-bottom (`sticky_to_bottom = true`) — every refresh re-pins scroll to
7 //! the new tail, so streaming output appears to flow off the bottom edge.
8 //! - Scroll up — `sticky_to_bottom` flips to `false`; subsequent refreshes
9 //! leave scroll position alone so the user can read history without being
10 //! yanked back down.
11 //! - Scroll back to bottom (End / G / paging past the tail) — `sticky` flips
12 //! to `true` again; auto-tail resumes.
13 //! - Esc / `q` — close, returning to the normal view. The engine never
14 //! pauses while the overlay is open; new chunks accumulate in the cells
15 //! exactly as they would on the normal screen.
16 //!
17 //! Cache strategy: the overlay holds its own `TranscriptCache` keyed by
18 //! `(CellId, width, revision)`. Revisions come from the same per-cell
19 //! counters the main transcript already maintains (`App.history_revisions`
20 //! and `App.active_cell_revision`). Resize invalidates the cells whose width
21 //! key just changed; revision bumps invalidate only the cells that mutated;
22 //! cells that didn't change reuse their existing wrap.
23
24 use std::cell::{Cell, RefCell};
25
26 use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
27 use ratatui::{
28 buffer::Buffer,
29 layout::Rect,
30 style::{Modifier, Style},
31 text::{Line, Span},
32 widgets::{Block, Borders, Clear, Padding, Widget},
33 };
34
35 use crate::tui::app::App;
36 use crate::tui::backtrack::Direction;
37 use crate::tui::history::{HistoryCell, TranscriptRenderOptions};
38 use crate::tui::transcript_cache::{CachedTranscriptLine, CellId, TranscriptCache};
39 use crate::tui::views::{
40 ActionHint, ModalKind, ModalView, ViewAction, ViewEvent, render_modal_footer,
41 };
42 use codewhale_palette as palette;
43
44 /// Render mode for the overlay. `Tail` is the original sticky-tail
45 /// behaviour (#94). `BacktrackPreview` (#133) highlights the Nth-from-tail
46 /// `HistoryCell::User` so the user can see which turn Esc-Esc-Enter will
47 /// roll back to. The mode also disables sticky-tail (we want the user to
48 /// scan history, not be yanked to live output) and pins scroll near the
49 /// highlighted cell on transitions.
50 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
51 pub enum Mode {
52 #[default]
53 Tail,
54 BacktrackPreview {
55 selected_idx: usize,
56 },
57 }
58
59 /// Snapshot of one cell, refreshed every frame from `App`. Owns the cell so
60 /// the overlay's `render(&self)` can wrap without re-borrowing `App`.
61 #[derive(Debug, Clone)]
62 struct CellSnapshot {
63 id: CellId,
64 revision: u64,
65 cell: HistoryCell,
66 }
67
68 struct FlattenedTranscript {
69 lines: Vec<Line<'static>>,
70 line_links: Vec<Vec<codewhale_tui_kit::osc8::LineLink>>,
71 highlighted_range: Option<(usize, usize)>,
72 }
73
74 pub struct LiveTranscriptOverlay {
75 /// Latest cell snapshots (history + active). Refreshed via
76 /// `refresh_from_app` immediately before each render so streaming
77 /// mutations show up on the next paint.
78 snapshots: Vec<CellSnapshot>,
79 /// Render options sampled from `App` at refresh time so toggles like
80 /// `show_thinking` propagate into the overlay live.
81 options: TranscriptRenderOptions,
82 /// Wrapped-line cache. `RefCell` so `render(&self)` can write through.
83 cache: RefCell<TranscriptCache>,
84 /// Sticky-tail flag: when `true`, refresh re-pins scroll to the bottom.
85 /// Flipped to `false` when the user scrolls up; flipped back to `true`
86 /// when they scroll past the last visible line.
87 sticky_to_bottom: Cell<bool>,
88 /// Current top-of-viewport line offset into the flattened line list.
89 scroll: Cell<usize>,
90 /// Visible content height from the last render. Used by paging keys
91 /// before the next render frame populates a fresh value.
92 last_visible_height: Cell<usize>,
93 /// Last total line count after wrapping; cached so `handle_key` can
94 /// clamp scroll without re-wrapping. Updated by `render`.
95 last_total_lines: Cell<usize>,
96 /// Pending `gg` second keystroke for Vim-style jump-to-top.
97 pending_g: bool,
98 /// Render mode — `Tail` is the live-stream mode; `BacktrackPreview`
99 /// highlights the selected user message (#133).
100 mode: Mode,
101 /// Set when a backtrack selection changes. The next render pins the
102 /// selected cell into view once we know the wrapped line range.
103 preview_pin_pending: Cell<bool>,
104 /// Bumped by `refresh_from_app` whenever any snapshot actually changed.
105 /// Lets the flatten cache below be keyed in O(1) (#3904).
106 snapshots_generation: Cell<u64>,
107 /// Cached flattened line vector. `flatten` used to re-clone every cell's
108 /// cached wrapped lines into a fresh `Vec` on every frame; now it is
109 /// rebuilt only when the snapshots, width, mode, or render options change.
110 flat_cache: RefCell<Option<FlatCache>>,
111 /// How many `HistoryCell` deep clones `refresh_from_app` has performed.
112 /// Diagnostics + the #3904 regression tests.
113 cell_clones: Cell<u64>,
114 undo_selection: bool,
115 /// How many times `flatten` actually rebuilt the flat line vector.
116 flattens: Cell<u64>,
117 }
118
119 /// Key that fully determines the output of `flatten`.
120 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
121 struct FlatKey {
122 generation: u64,
123 width: u16,
124 mode: Mode,
125 options: TranscriptRenderOptions,
126 }
127
128 struct FlatCache {
129 key: FlatKey,
130 flat: FlattenedTranscript,
131 }
132
133 impl LiveTranscriptOverlay {
134 #[must_use]
135 pub fn new() -> Self {
136 Self {
137 snapshots: Vec::new(),
138 options: TranscriptRenderOptions::default(),
139 cache: RefCell::new(TranscriptCache::new()),
140 sticky_to_bottom: Cell::new(true),
141 scroll: Cell::new(0),
142 last_visible_height: Cell::new(0),
143 last_total_lines: Cell::new(0),
144 pending_g: false,
145 mode: Mode::Tail,
146 preview_pin_pending: Cell::new(false),
147 snapshots_generation: Cell::new(0),
148 flat_cache: RefCell::new(None),
149 cell_clones: Cell::new(0),
150 undo_selection: false,
151 flattens: Cell::new(0),
152 }
153 }
154
155 /// Switch the overlay into backtrack-preview mode. Sticky-tail is
156 /// turned off so the highlighted cell stays in view while the user
157 /// steps through prior turns. The wrap cache stays valid because the
158 /// underlying snapshot data hasn't changed — only the post-wrap
159 /// highlight overlay does.
160 pub fn set_backtrack_preview(&mut self, selected_idx: usize) {
161 self.mode = Mode::BacktrackPreview { selected_idx };
162 self.sticky_to_bottom.set(false);
163 self.preview_pin_pending.set(true);
164 }
165
166 pub fn set_undo_selection(&mut self) {
167 self.undo_selection = true;
168 }
169
170 /// Return the overlay to live-tail mode (used when backtrack is
171 /// confirmed or canceled). Re-arms sticky-tail so streaming resumes.
172 #[cfg(test)]
173 pub fn set_tail_mode(&mut self) {
174 self.mode = Mode::Tail;
175 self.sticky_to_bottom.set(true);
176 self.preview_pin_pending.set(false);
177 }
178
179 /// For tests + UI: current mode.
180 #[cfg(test)]
181 #[must_use]
182 pub fn mode(&self) -> Mode {
183 self.mode
184 }
185
186 /// Pull the latest cells + revisions from `App` so the next `render` shows
187 /// streaming mutations. Must be called before `view_stack.render` while
188 /// this overlay is on top; otherwise the cells stay frozen at whatever
189 /// state they were in when the overlay was first opened.
190 pub fn refresh_from_app(&mut self, app: &mut App) {
191 app.resync_history_revisions();
192 let mut slot = 0usize;
193 let mut changed = false;
194 for (idx, cell) in app.history.iter().enumerate() {
195 let rev = app.history_revisions.get(idx).copied().unwrap_or(0);
196 changed |= self.store_snapshot(slot, CellId::History(idx), rev, cell);
197 slot += 1;
198 }
199 if let Some(active) = app.active_cell.as_ref() {
200 let active_rev = app.active_cell_revision;
201 for (idx, cell) in active.entries().iter().enumerate() {
202 let salt = (idx as u64).wrapping_add(1);
203 // Share the main transcript's revision derivation instead of
204 // keeping an inline copy of the same mixing constant (#3904).
205 let revision = crate::tui::widgets::active_entry_revision(active_rev, salt);
206 changed |= self.store_snapshot(slot, CellId::Active(idx), revision, cell);
207 slot += 1;
208 }
209 }
210 if self.snapshots.len() != slot {
211 self.snapshots.truncate(slot);
212 changed = true;
213 }
214 let options = app.transcript_render_options();
215 self.options.thinking_checkpoints = options.thinking_checkpoints;
216 if self.options != options {
217 self.options = options;
218 // Per-cell wraps are keyed by (cell, width, revision) only, so a
219 // theme, locale or thinking toggle would otherwise reuse lines
220 // rendered under the old options (U04-m1).
221 self.cache.get_mut().clear();
222 changed = true;
223 }
224 if changed {
225 self.snapshots_generation
226 .set(self.snapshots_generation.get().wrapping_add(1));
227 }
228 }
229
230 /// Write the snapshot for `slot`, cloning the cell **only** when its
231 /// `(CellId, revision)` differs from what is already stored (#3904).
232 ///
233 /// Returns whether anything changed. The overlay tails a live stream, so
234 /// this runs at streaming cadence; the old code deep-cloned every history
235 /// cell every frame even though revisions were already available.
236 fn store_snapshot(
237 &mut self,
238 slot: usize,
239 id: CellId,
240 revision: u64,
241 cell: &HistoryCell,
242 ) -> bool {
243 match self.snapshots.get_mut(slot) {
244 Some(existing) if existing.id == id && existing.revision == revision => false,
245 Some(existing) => {
246 existing.id = id;
247 existing.revision = revision;
248 existing.cell = cell.clone();
249 self.cell_clones.set(self.cell_clones.get() + 1);
250 true
251 }
252 None => {
253 self.snapshots.push(CellSnapshot {
254 id,
255 revision,
256 cell: cell.clone(),
257 });
258 self.cell_clones.set(self.cell_clones.get() + 1);
259 true
260 }
261 }
262 }
263
264 /// Wrap each cell (using the cache) and return the flat line vector.
265 /// In `BacktrackPreview` mode the lines belonging to the selected
266 /// `HistoryCell::User` are decorated with a leading `▶` marker on the
267 /// first line and reverse-video styling on every line so the eye
268 /// snaps to them at a glance. The decoration is applied *after* the
269 /// cache lookup so toggling preview mode never invalidates wraps.
270 /// Cached wrapper around [`Self::flatten`] (#3904).
271 ///
272 /// The overlay renders at streaming cadence while the main transcript
273 /// renders underneath in the same frame, so re-flattening the whole
274 /// transcript per frame roughly doubled per-frame allocations. The flat
275 /// vector only depends on the snapshots, the width, the mode, and the
276 /// render options — all of which are in `FlatKey`.
277 fn flattened(&self, width: u16) -> std::cell::Ref<'_, FlattenedTranscript> {
278 let key = FlatKey {
279 generation: self.snapshots_generation.get(),
280 width: width.max(1),
281 mode: self.mode,
282 options: self.options,
283 };
284 {
285 let mut cache = self.flat_cache.borrow_mut();
286 let stale = cache.as_ref().is_none_or(|cached| cached.key != key);
287 if stale {
288 let flat = self.flatten(key.width);
289 self.flattens.set(self.flattens.get() + 1);
290 *cache = Some(FlatCache { key, flat });
291 }
292 }
293 std::cell::Ref::map(self.flat_cache.borrow(), |cache| {
294 &cache.as_ref().expect("flat cache populated above").flat
295 })
296 }
297
298 fn flatten(&self, width: u16) -> FlattenedTranscript {
299 let width = width.max(1);
300 let mut out: Vec<Line<'static>> = Vec::new();
301 let mut out_links: Vec<Vec<codewhale_tui_kit::osc8::LineLink>> = Vec::new();
302 let mut highlighted_range = None;
303
304 // Pre-compute which cell index (in `self.snapshots`) is the one
305 // the user has selected via Esc-Esc. We walk snapshots backwards
306 // counting User cells; the snapshot index whose count matches
307 // `selected_idx + 1` is the highlighted one.
308 let highlighted_cell_idx: Option<usize> = match self.mode {
309 Mode::BacktrackPreview { selected_idx } => {
310 let mut count = 0usize;
311 let mut hit = None;
312 for (idx, snap) in self.snapshots.iter().enumerate().rev() {
313 if matches!(snap.cell, HistoryCell::User { .. }) {
314 if count == selected_idx {
315 hit = Some(idx);
316 break;
317 }
318 count += 1;
319 }
320 }
321 hit
322 }
323 Mode::Tail => None,
324 };
325
326 let mut cache = self.cache.borrow_mut();
327 // Room for every cell plus a new revision of each, so the sweep
328 // below never evicts entries it is about to read (a 1,000-cell
329 // transcript against the old fixed 512 cap missed every lookup).
330 cache.ensure_capacity(self.snapshots.len().saturating_mul(2));
331 for (cell_idx, snap) in self.snapshots.iter().enumerate() {
332 // Borrow the cached slice and clone each line (and its links)
333 // exactly once into the flattened output.
334 let split = |cached: &[CachedTranscriptLine]| -> (Vec<Line<'static>>, Vec<_>) {
335 cached
336 .iter()
337 .map(|rendered| (rendered.line.clone(), rendered.links.clone()))
338 .unzip()
339 };
340 let (lines, mut line_links) = match cache.get(snap.id, width, snap.revision) {
341 Some(cached) => split(cached),
342 None => {
343 let rendered = snap
344 .cell
345 .lines_with_copy_metadata(width, self.options)
346 .into_iter()
347 .map(|rendered| CachedTranscriptLine {
348 line: rendered.line,
349 links: rendered.links,
350 })
351 .collect::<Vec<_>>();
352 let split_lines = split(&rendered);
353 cache.insert(snap.id, width, snap.revision, rendered);
354 split_lines
355 }
356 };
357
358 if Some(cell_idx) == highlighted_cell_idx {
359 let start = out.len();
360 let lines = decorate_highlight(lines);
361 if let Some(first_links) = line_links.first_mut() {
362 *first_links = first_links.iter().map(|link| link.shifted(2)).collect();
363 }
364 out.extend(lines);
365 out_links.extend(line_links);
366 let end = out.len();
367 if end > start {
368 highlighted_range = Some((start, end));
369 }
370 } else {
371 out.extend(lines);
372 out_links.extend(line_links);
373 }
374 }
375 FlattenedTranscript {
376 lines: out,
377 line_links: out_links,
378 highlighted_range,
379 }
380 }
381
382 fn page_height(&self) -> usize {
383 let cached = self.last_visible_height.get();
384 if cached == 0 { 10 } else { cached }
385 }
386
387 fn half_page_height(&self) -> usize {
388 self.page_height().div_ceil(2).max(1)
389 }
390
391 fn max_scroll(&self) -> usize {
392 let total = self.last_total_lines.get();
393 let visible = self.page_height();
394 total.saturating_sub(visible)
395 }
396
397 fn scroll_up(&mut self, amount: usize) {
398 self.scroll.set(self.scroll.get().saturating_sub(amount));
399 // Any upward motion exits sticky-tail; explicit user intent.
400 self.sticky_to_bottom.set(false);
401 self.preview_pin_pending.set(false);
402 }
403
404 fn scroll_down(&mut self, amount: usize) {
405 let max = self.max_scroll();
406 let scroll = self.scroll.get().saturating_add(amount).min(max);
407 self.scroll.set(scroll);
408 self.preview_pin_pending.set(false);
409 if scroll >= max && matches!(self.mode, Mode::Tail) {
410 self.sticky_to_bottom.set(true);
411 }
412 }
413
414 fn jump_to_top(&mut self) {
415 self.scroll.set(0);
416 self.sticky_to_bottom.set(false);
417 self.preview_pin_pending.set(false);
418 }
419
420 fn jump_to_bottom(&mut self) {
421 self.scroll.set(self.max_scroll());
422 self.sticky_to_bottom.set(matches!(self.mode, Mode::Tail));
423 self.preview_pin_pending.set(false);
424 }
425
426 /// For tests: snapshot count.
427 #[cfg(test)]
428 fn snapshot_count(&self) -> usize {
429 self.snapshots.len()
430 }
431
432 /// For tests: whether sticky-tail is currently armed.
433 #[cfg(test)]
434 pub fn is_sticky(&self) -> bool {
435 self.sticky_to_bottom.get()
436 }
437
438 /// For tests: current scroll offset.
439 #[cfg(test)]
440 pub fn scroll_offset(&self) -> usize {
441 self.scroll.get()
442 }
443 }
444
445 impl Default for LiveTranscriptOverlay {
446 fn default() -> Self {
447 Self::new()
448 }
449 }
450
451 /// Apply a backtrack-preview highlight to the lines belonging to a single
452 /// `HistoryCell::User`. The first line gets a `▶ ` prefix in accent color
453 /// (so the marker remains visible even on terminals where reverse-video
454 /// is washed out); every line in the cell gets `Modifier::REVERSED` so
455 /// the cell visually pops out of the surrounding transcript. Internal
456 /// span structure is preserved so syntax/role coloring underneath the
457 /// reverse stays readable.
458 fn decorate_highlight(mut lines: Vec<Line<'static>>) -> Vec<Line<'static>> {
459 if lines.is_empty() {
460 return lines;
461 }
462 for line in &mut lines {
463 for span in &mut line.spans {
464 span.style = span.style.add_modifier(Modifier::REVERSED);
465 }
466 }
467 let marker = Span::styled(
468 "\u{25B6} ",
469 Style::default()
470 .fg(palette::TEXT_ACCENT)
471 .add_modifier(Modifier::BOLD),
472 );
473 if let Some(first) = lines.first_mut() {
474 first.spans.insert(0, marker);
475 }
476 lines
477 }
478
479 fn scroll_to_show_range(
480 current: usize,
481 start: usize,
482 end: usize,
483 visible_height: usize,
484 max_scroll: usize,
485 ) -> usize {
486 if visible_height == 0 {
487 return 0;
488 }
489 let end = end.max(start.saturating_add(1));
490 if start < current {
491 start.min(max_scroll)
492 } else if end > current.saturating_add(visible_height) {
493 end.saturating_sub(visible_height).min(max_scroll)
494 } else {
495 current.min(max_scroll)
496 }
497 }
498
499 impl ModalView for LiveTranscriptOverlay {
500 fn kind(&self) -> ModalKind {
501 ModalKind::LiveTranscript
502 }
503
504 fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
505 self
506 }
507
508 fn handle_key(&mut self, key: KeyEvent) -> ViewAction {
509 let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
510 let shift = key.modifiers.contains(KeyModifiers::SHIFT);
511
512 // Backtrack-preview mode (#133) intercepts Left/Right/Enter/Esc
513 // before the normal scroll handlers so the user can step through
514 // prior user messages without their input being interpreted as
515 // pager navigation. Other keys (page up/down, gg/G, etc.) still
516 // fall through so the user can scroll the transcript while
517 // previewing.
518 if matches!(self.mode, Mode::BacktrackPreview { .. }) {
519 match key.code {
520 KeyCode::Left | KeyCode::Char('h') if !ctrl => {
521 return ViewAction::Emit(ViewEvent::BacktrackStep {
522 direction: Direction::Left,
523 });
524 }
525 KeyCode::Right | KeyCode::Char('l') if !ctrl => {
526 return ViewAction::Emit(ViewEvent::BacktrackStep {
527 direction: Direction::Right,
528 });
529 }
530 KeyCode::Enter => {
531 return ViewAction::EmitAndClose(ViewEvent::BacktrackConfirm);
532 }
533 KeyCode::Esc | KeyCode::Char('q') => {
534 return ViewAction::EmitAndClose(ViewEvent::BacktrackCancel);
535 }
536 _ => {}
537 }
538 }
539
540 if ctrl {
541 match key.code {
542 KeyCode::Char('d') | KeyCode::Char('D') => {
543 self.scroll_down(self.half_page_height());
544 self.pending_g = false;
545 return ViewAction::None;
546 }
547 KeyCode::Char('u') | KeyCode::Char('U') => {
548 self.scroll_up(self.half_page_height());
549 self.pending_g = false;
550 return ViewAction::None;
551 }
552 KeyCode::Char('f') | KeyCode::Char('F') => {
553 self.scroll_down(self.page_height());
554 self.pending_g = false;
555 return ViewAction::None;
556 }
557 KeyCode::Char('b') | KeyCode::Char('B') => {
558 self.scroll_up(self.page_height());
559 self.pending_g = false;
560 return ViewAction::None;
561 }
562 // Ctrl+Shift+T toggles the overlay closed when already open.
563 KeyCode::Char('t') | KeyCode::Char('T')
564 if key.modifiers.contains(KeyModifiers::CONTROL)
565 && key.modifiers.contains(KeyModifiers::SHIFT) =>
566 {
567 return ViewAction::Close;
568 }
569 _ => {}
570 }
571 }
572
573 match key.code {
574 KeyCode::Esc | KeyCode::Char('q') => ViewAction::Close,
575 KeyCode::Up | KeyCode::Char('k') => {
576 self.scroll_up(1);
577 self.pending_g = false;
578 ViewAction::None
579 }
580 KeyCode::Down | KeyCode::Char('j') => {
581 self.scroll_down(1);
582 self.pending_g = false;
583 ViewAction::None
584 }
585 KeyCode::PageUp => {
586 self.scroll_up(self.page_height());
587 self.pending_g = false;
588 ViewAction::None
589 }
590 KeyCode::PageDown => {
591 self.scroll_down(self.page_height());
592 self.pending_g = false;
593 ViewAction::None
594 }
595 KeyCode::Char(' ') if shift => {
596 self.scroll_up(self.page_height());
597 self.pending_g = false;
598 ViewAction::None
599 }
600 KeyCode::Char(' ') => {
601 self.scroll_down(self.page_height());
602 self.pending_g = false;
603 ViewAction::None
604 }
605 KeyCode::Home => {
606 self.jump_to_top();
607 self.pending_g = false;
608 ViewAction::None
609 }
610 KeyCode::End => {
611 self.jump_to_bottom();
612 self.pending_g = false;
613 ViewAction::None
614 }
615 KeyCode::Char('g') => {
616 if self.pending_g {
617 self.jump_to_top();
618 self.pending_g = false;
619 } else {
620 self.pending_g = true;
621 }
622 ViewAction::None
623 }
624 KeyCode::Char('G') => {
625 self.jump_to_bottom();
626 self.pending_g = false;
627 ViewAction::None
628 }
629 _ => ViewAction::None,
630 }
631 }
632
633 fn render(&self, area: Rect, buf: &mut Buffer) {
634 let popup_width = area.width.saturating_sub(2).max(1);
635 let popup_height = area.height.saturating_sub(2).max(1);
636 let popup_area = Rect {
637 x: 1,
638 y: 1,
639 width: popup_width,
640 height: popup_height,
641 };
642
643 Clear.render(popup_area, buf);
644
645 let title: String = match self.mode {
646 Mode::BacktrackPreview { selected_idx } if self.undo_selection => format!(
647 " Undo {} request(s) and their file changes (←/→ select, Enter undo, Esc cancel) ",
648 selected_idx + 1
649 ),
650 Mode::BacktrackPreview { selected_idx } => format!(
651 " Backtrack preview — turn {} (\u{2190}/\u{2192} step, Enter rewind, Esc cancel) ",
652 selected_idx + 1
653 ),
654 Mode::Tail => {
655 if self.sticky_to_bottom.get() {
656 " Live transcript (tailing) ".to_string()
657 } else {
658 " Live transcript (paused) ".to_string()
659 }
660 }
661 };
662
663 let block = Block::default()
664 .title(title)
665 .borders(Borders::ALL)
666 .border_style(Style::default().fg(palette::BORDER_COLOR))
667 .style(Style::default().bg(palette::WHALE_BG))
668 .padding(Padding::uniform(1));
669 let inner = block.inner(popup_area);
670 block.render(popup_area, buf);
671
672 // Wrapping action footer along the bottom of the inner area; the body
673 // fills the rows above it.
674 let content = render_modal_footer(
675 inner,
676 buf,
677 &[
678 ActionHint::new("j/k", "scroll"),
679 ActionHint::new("Space/C-b", "page"),
680 ActionHint::new("g/G", "top/bottom"),
681 ActionHint::new("End", "resume tail"),
682 ActionHint::new("q/Esc", "close"),
683 ],
684 );
685
686 // `content` already excludes the border, padding, and footer rows.
687 let visible_height = content.height as usize;
688 self.last_visible_height.set(visible_height);
689
690 // Wrap content using the per-cell cache at the body width.
691 let content_width = content.width;
692 let flat = self.flattened(content_width);
693 let FlattenedTranscript {
694 lines,
695 line_links,
696 highlighted_range,
697 } = &*flat;
698 let highlighted_range = *highlighted_range;
699 self.last_total_lines.set(lines.len());
700
701 let max_scroll = lines.len().saturating_sub(visible_height);
702 // Sticky-tail: every render re-pins scroll to the bottom unless the
703 // user has explicitly scrolled away. Without this, streaming new
704 // content would push the visible window backwards as `scroll` stays
705 // fixed against a growing total.
706 let scroll = if self.sticky_to_bottom.get() {
707 self.scroll.set(max_scroll);
708 max_scroll
709 } else if self.preview_pin_pending.replace(false) {
710 let next = highlighted_range
711 .map(|(start, end)| {
712 scroll_to_show_range(self.scroll.get(), start, end, visible_height, max_scroll)
713 })
714 .unwrap_or_else(|| self.scroll.get().min(max_scroll));
715 self.scroll.set(next);
716 next
717 } else {
718 let next = self.scroll.get().min(max_scroll);
719 self.scroll.set(next);
720 next
721 };
722 let end = (scroll + visible_height).min(lines.len());
723 let visible_lines: Vec<Line<'static>> = if lines.is_empty() {
724 vec![Line::from(Span::styled(
725 "(no transcript yet)",
726 Style::default().fg(palette::TEXT_DIM),
727 ))]
728 } else {
729 lines[scroll..end].to_vec()
730 };
731 let visible_line_links = if lines.is_empty() {
732 vec![Vec::new()]
733 } else {
734 line_links[scroll..end].to_vec()
735 };
736
737 let mut viewport = codewhale_ratatui::TranscriptViewport::new(&visible_lines);
738 viewport.wrap = true;
739 let plan = viewport.render(content, buf);
740
741 // Targets stay beside the visible lines, so the popup never writes an
742 // escape payload into the buffer. Replace the opaque popup's portion
743 // of the frame map so links in the obscured transcript cannot leak
744 // through unrelated modal text.
745 let regions = codewhale_tui_kit::osc8::link_regions_for_plan(&plan, &visible_line_links);
746 codewhale_tui_kit::osc8::overlay_frame_links(popup_area, regions);
747 }
748 }
749
750 #[cfg(test)]
751 mod tests {
752 use super::*;
753 use crate::tui::history::HistoryCell;
754
755 fn user(s: &str) -> HistoryCell {
756 HistoryCell::User {
757 content: s.to_string(),
758 }
759 }
760
761 fn assistant(s: &str, streaming: bool) -> HistoryCell {
762 HistoryCell::Assistant {
763 content: s.to_string(),
764 streaming,
765 }
766 }
767
768 /// Force a render so `last_visible_height` and `last_total_lines` are
769 /// populated; otherwise paging keys use the constant fallback.
770 fn prime_layout(view: &mut LiveTranscriptOverlay, height: u16) {
771 let area = Rect::new(0, 0, 60, height);
772 let mut buf = Buffer::empty(area);
773 view.render(area, &mut buf);
774 }
775
776 fn install_snapshots(view: &mut LiveTranscriptOverlay, cells: Vec<HistoryCell>) {
777 view.snapshots = cells
778 .into_iter()
779 .enumerate()
780 .map(|(idx, cell)| CellSnapshot {
781 id: CellId::History(idx),
782 revision: 1,
783 cell,
784 })
785 .collect();
786 view.snapshots_generation
787 .set(view.snapshots_generation.get().wrapping_add(1));
788 }
789
790 fn mark_snapshots_changed(view: &LiveTranscriptOverlay) {
791 view.snapshots_generation
792 .set(view.snapshots_generation.get().wrapping_add(1));
793 }
794
795 fn buffer_text(buf: &Buffer) -> String {
796 let mut out = String::new();
797 for y in 0..buf.area.height {
798 for x in 0..buf.area.width {
799 out.push_str(buf[(x, y)].symbol());
800 }
801 out.push('\n');
802 }
803 out
804 }
805
806 #[test]
807 fn new_overlay_starts_sticky() {
808 let v = LiveTranscriptOverlay::new();
809 assert!(v.is_sticky());
810 assert_eq!(v.scroll_offset(), 0);
811 assert_eq!(v.snapshot_count(), 0);
812 }
813
814 #[test]
815 fn overlay_publishes_scrolled_url_metadata_without_escape_cells() {
816 let target = "https://example.test/a/very/long/path/that/wraps/in/the/live/view";
817 let mut view = LiveTranscriptOverlay::new();
818 let mut cells = (0..12)
819 .map(|index| user(&format!("older row {index}")))
820 .collect::<Vec<_>>();
821 cells.push(assistant(target, false));
822 install_snapshots(&mut view, cells);
823
824 let area = Rect::new(0, 0, 32, 16);
825 let mut buf = Buffer::empty(area);
826 let _ = codewhale_tui_kit::osc8::take_frame_links();
827 view.render(area, &mut buf);
828 let regions = codewhale_tui_kit::osc8::take_frame_links();
829
830 assert!(view.scroll_offset() > 0, "fixture must render a tail slice");
831 assert!(regions.len() > 1, "narrow overlay should wrap: {regions:?}");
832 assert!(regions.iter().all(|region| region.target == target));
833 assert!(regions.iter().all(|region| {
834 area.contains(ratatui::layout::Position {
835 x: region.col_start,
836 y: region.row,
837 }) && area.contains(ratatui::layout::Position {
838 x: region.col_end,
839 y: region.row,
840 })
841 }));
842 assert!((area.y..area.bottom()).all(|y| {
843 (area.x..area.right()).all(|x| {
844 let symbol = buf[(x, y)].symbol();
845 !symbol.contains('\x1b') && !symbol.contains("]8;;")
846 })
847 }));
848 }
849
850 #[test]
851 fn scroll_up_breaks_sticky() {
852 let mut v = LiveTranscriptOverlay::new();
853 install_snapshots(
854 &mut v,
855 (0..50).map(|i| user(&format!("line {i}"))).collect(),
856 );
857 prime_layout(&mut v, 10);
858 // Force scroll non-zero so scroll_up actually moves.
859 v.scroll.set(5);
860 v.sticky_to_bottom.set(true);
861 let _ = v.handle_key(KeyEvent::new(KeyCode::Char('k'), KeyModifiers::NONE));
862 assert!(!v.is_sticky(), "scrolling up must release the sticky tail");
863 }
864
865 #[test]
866 fn end_resumes_sticky_tail() {
867 let mut v = LiveTranscriptOverlay::new();
868 install_snapshots(
869 &mut v,
870 (0..50).map(|i| user(&format!("line {i}"))).collect(),
871 );
872 prime_layout(&mut v, 10);
873 // Drop out of sticky mode by scrolling up.
874 v.scroll.set(10);
875 v.sticky_to_bottom.set(false);
876 let _ = v.handle_key(KeyEvent::new(KeyCode::End, KeyModifiers::NONE));
877 assert!(
878 v.is_sticky(),
879 "End must re-arm the sticky tail so streaming continues to follow"
880 );
881 }
882
883 #[test]
884 fn scrolling_to_max_re_arms_sticky() {
885 let mut v = LiveTranscriptOverlay::new();
886 install_snapshots(
887 &mut v,
888 (0..50).map(|i| user(&format!("line {i}"))).collect(),
889 );
890 prime_layout(&mut v, 10);
891 v.sticky_to_bottom.set(false);
892 // PageDown once should not re-arm since we're not yet at the tail.
893 let _ = v.handle_key(KeyEvent::new(KeyCode::PageDown, KeyModifiers::NONE));
894 // Now jump explicitly to bottom and verify re-arm.
895 v.scroll.set(0);
896 v.sticky_to_bottom.set(false);
897 let _ = v.handle_key(KeyEvent::new(KeyCode::Char('G'), KeyModifiers::NONE));
898 assert!(v.is_sticky());
899 }
900
901 #[test]
902 fn esc_closes() {
903 let mut v = LiveTranscriptOverlay::new();
904 let action = v.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
905 assert!(matches!(action, ViewAction::Close));
906 }
907
908 #[test]
909 fn ctrl_shift_t_closes_when_already_open() {
910 // The overlay toggle moved to Ctrl+Shift+T (Wave 7 M3: plain Ctrl+T
911 // now cycles reasoning effort).
912 let mut v = LiveTranscriptOverlay::new();
913 let action = v.handle_key(KeyEvent::new(
914 KeyCode::Char('t'),
915 KeyModifiers::CONTROL | KeyModifiers::SHIFT,
916 ));
917 assert!(matches!(action, ViewAction::Close));
918 }
919
920 #[test]
921 fn render_does_not_panic_on_empty() {
922 let v = LiveTranscriptOverlay::new();
923 let area = Rect::new(0, 0, 40, 12);
924 let mut buf = Buffer::empty(area);
925 v.render(area, &mut buf);
926 }
927
928 #[test]
929 fn cache_reuses_unchanged_cells_across_renders() {
930 // Same revisions across two renders should reuse cache entries; only
931 // a "modified" cell (different revision) forces a new wrap. Verify by
932 // counting cache size — it grows by 1 per unique (cell, width, rev).
933 let mut v = LiveTranscriptOverlay::new();
934 install_snapshots(&mut v, vec![user("a"), user("b"), assistant("c", false)]);
935 let area = Rect::new(0, 0, 60, 16);
936 let mut buf = Buffer::empty(area);
937 v.render(area, &mut buf);
938 let after_first = v.cache.borrow().len();
939 v.render(area, &mut buf);
940 let after_second = v.cache.borrow().len();
941 assert_eq!(
942 after_first, after_second,
943 "second render should reuse every cell — no new cache entries"
944 );
945 }
946
947 #[test]
948 fn streaming_render_stays_within_per_frame_cell_diff_budget() {
949 let mut view = LiveTranscriptOverlay::new();
950 let mut cells = (0..30)
951 .map(|index| user(&format!("stable transcript row {index}")))
952 .collect::<Vec<_>>();
953 cells.push(assistant("streaming answer", true));
954 install_snapshots(&mut view, cells);
955
956 let area = Rect::new(0, 0, 89, 24);
957 let mut before = Buffer::empty(area);
958 view.render(area, &mut before);
959
960 let tail = view.snapshots.last_mut().expect("streaming tail");
961 let HistoryCell::Assistant { content, .. } = &mut tail.cell else {
962 panic!("fixture tail must be an assistant cell");
963 };
964 content.push_str(" + one delta");
965 tail.revision = tail.revision.saturating_add(1);
966 mark_snapshots_changed(&view);
967
968 let mut after = Buffer::empty(area);
969 view.render(area, &mut after);
970 let changed_cells = before
971 .content()
972 .iter()
973 .zip(after.content())
974 .filter(|(left, right)| left != right)
975 .count();
976
977 // A short stream delta may change its text row and a wrap boundary,
978 // but it must not invalidate the viewport. Four rows is a generous
979 // ceiling that still catches a full-frame repaint regression.
980 let max_changed_cells = area.width as usize * 4;
981 assert!(changed_cells > 0, "stream delta did not reach the frame");
982 assert!(
983 changed_cells <= max_changed_cells,
984 "stream delta changed {changed_cells} cells; budget is {max_changed_cells}"
985 );
986 }
987
988 /// A transcript longer than the default cache cap must still hit the
989 /// wrap cache on the next sweep instead of re-wrapping every cell.
990 #[test]
991 fn thousand_cell_sweep_hits_the_cache_on_the_second_pass() {
992 let mut v = LiveTranscriptOverlay::new();
993 let cells = (0..1_000)
994 .map(|index| user(&format!("cell {index}")))
995 .collect::<Vec<_>>();
996 install_snapshots(&mut v, cells);
997 let area = Rect::new(0, 0, 60, 16);
998 let mut buf = Buffer::empty(area);
999 v.render(area, &mut buf);
1000 assert_eq!(
1001 v.cache.borrow().len(),
1002 1_000,
1003 "the first sweep must keep every cell's wrap"
1004 );
1005 mark_snapshots_changed(&v);
1006 v.render(area, &mut buf);
1007 assert_eq!(
1008 v.cache.borrow().len(),
1009 1_000,
1010 "the second sweep must reuse every wrap, not re-insert any"
1011 );
1012 }
1013
1014 #[test]
1015 fn cache_invalidates_on_revision_bump() {
1016 let mut v = LiveTranscriptOverlay::new();
1017 install_snapshots(&mut v, vec![user("a"), assistant("b", true)]);
1018 let area = Rect::new(0, 0, 60, 16);
1019 let mut buf = Buffer::empty(area);
1020 v.render(area, &mut buf);
1021 let before = v.cache.borrow().len();
1022 // Bump the streaming assistant's revision (simulating a delta) and
1023 // re-render. We expect the cache to grow by one new entry — the new
1024 // (cell, width, new_rev) — while the user cell entry is reused.
1025 v.snapshots[1].revision = 2;
1026 mark_snapshots_changed(&v);
1027 v.render(area, &mut buf);
1028 let after = v.cache.borrow().len();
1029 assert!(
1030 after > before,
1031 "bumping a revision must add a new cache entry"
1032 );
1033 }
1034
1035 #[test]
1036 fn resize_does_not_evict_unchanged_width_entries() {
1037 // Render at width=60, then again at width=80. Both wraps must
1038 // co-exist in the cache so flipping back to width=60 hits cache.
1039 let mut v = LiveTranscriptOverlay::new();
1040 install_snapshots(&mut v, vec![user("a"), user("b")]);
1041 let small = Rect::new(0, 0, 60, 16);
1042 let large = Rect::new(0, 0, 80, 16);
1043 let mut buf_s = Buffer::empty(small);
1044 let mut buf_l = Buffer::empty(large);
1045 v.render(small, &mut buf_s);
1046 let after_small = v.cache.borrow().len();
1047 v.render(large, &mut buf_l);
1048 let after_both = v.cache.borrow().len();
1049 assert!(
1050 after_both > after_small,
1051 "rendering at a new width must add new cache entries"
1052 );
1053 // Flip back to small — should NOT add any new entries (cache hits).
1054 v.render(small, &mut buf_s);
1055 let after_replay = v.cache.borrow().len();
1056 assert_eq!(
1057 after_replay, after_both,
1058 "replay at old width must hit cache"
1059 );
1060 }
1061
1062 #[test]
1063 fn backtrack_preview_disables_sticky() {
1064 let mut v = LiveTranscriptOverlay::new();
1065 assert!(v.is_sticky());
1066 v.set_backtrack_preview(0);
1067 assert!(!v.is_sticky());
1068 assert!(matches!(
1069 v.mode(),
1070 Mode::BacktrackPreview { selected_idx: 0 }
1071 ));
1072 }
1073
1074 #[test]
1075 fn set_tail_mode_re_arms_sticky() {
1076 let mut v = LiveTranscriptOverlay::new();
1077 v.set_backtrack_preview(2);
1078 v.set_tail_mode();
1079 assert!(v.is_sticky());
1080 assert!(matches!(v.mode(), Mode::Tail));
1081 }
1082
1083 #[test]
1084 fn backtrack_preview_does_not_panic_with_no_user_cells() {
1085 // Render in preview mode against a transcript that has zero User
1086 // cells — the highlight scan should miss gracefully.
1087 let mut v = LiveTranscriptOverlay::new();
1088 install_snapshots(&mut v, vec![assistant("hi", false)]);
1089 v.set_backtrack_preview(0);
1090 let area = Rect::new(0, 0, 40, 10);
1091 let mut buf = Buffer::empty(area);
1092 v.render(area, &mut buf);
1093 }
1094
1095 #[test]
1096 fn backtrack_preview_highlights_selected_user_cell() {
1097 // With 3 user cells (oldest → newest: u0, u1, u2), `selected_idx
1098 // = 0` should highlight u2 (newest), `= 1` u1, `= 2` u0. We can
1099 // detect the highlight by scanning the rendered buffer for the
1100 // marker glyph.
1101 let mut v = LiveTranscriptOverlay::new();
1102 install_snapshots(
1103 &mut v,
1104 vec![
1105 user("u0"),
1106 assistant("a0", false),
1107 user("u1"),
1108 assistant("a1", false),
1109 user("u2"),
1110 assistant("a2", false),
1111 ],
1112 );
1113 for sel in [0usize, 1, 2] {
1114 v.set_backtrack_preview(sel);
1115 // Force Tail re-render between iterations to confirm marker
1116 // really moves rather than smearing.
1117 let area = Rect::new(0, 0, 40, 24);
1118 let mut buf = Buffer::empty(area);
1119 v.render(area, &mut buf);
1120 // Just verify the cell index resolved without panicking and
1121 // the buffer is non-empty. Detailed marker placement is
1122 // visual, hence not asserted here.
1123 let mut any_content = false;
1124 for y in 0..buf.area.height {
1125 for x in 0..buf.area.width {
1126 if !buf[(x, y)].symbol().is_empty() && buf[(x, y)].symbol() != " " {
1127 any_content = true;
1128 break;
1129 }
1130 }
1131 if any_content {
1132 break;
1133 }
1134 }
1135 assert!(any_content, "preview render must produce visible content");
1136 }
1137 }
1138
1139 #[test]
1140 fn backtrack_preview_opens_near_latest_user_not_transcript_start() {
1141 let mut v = LiveTranscriptOverlay::new();
1142 let mut cells = Vec::new();
1143 for i in 0..12 {
1144 cells.push(user(&format!("user {i}")));
1145 cells.push(assistant(&format!("assistant {i}"), false));
1146 }
1147 install_snapshots(&mut v, cells);
1148
1149 v.set_backtrack_preview(0);
1150 let area = Rect::new(0, 0, 48, 10);
1151 let mut buf = Buffer::empty(area);
1152 v.render(area, &mut buf);
1153 let rendered = buffer_text(&buf);
1154
1155 assert!(
1156 v.scroll_offset() > 0,
1157 "preview should pin near the selected recent turn, got top offset 0"
1158 );
1159 assert!(
1160 rendered.contains("user 11"),
1161 "latest user turn should be visible after opening preview: {rendered}"
1162 );
1163 assert!(
1164 !rendered.contains("user 0"),
1165 "preview must not open at the oldest transcript line: {rendered}"
1166 );
1167 }
1168
1169 #[test]
1170 fn live_transcript_is_usable_and_opaque_at_blocker_sizes() {
1171 use crate::tui::views::ViewStack;
1172 use unicode_width::UnicodeWidthStr;
1173
1174 const BLOCKER_SIZES: [(u16, u16); 4] = [(80, 24), (100, 30), (120, 32), (160, 40)];
1175 for (w, h) in BLOCKER_SIZES {
1176 // Construct an empty overlay: transcript cells paint their own
1177 // backgrounds, so an empty body keeps the interior as the modal ink
1178 // and lets us assert opacity at the center cell directly.
1179 let overlay = LiveTranscriptOverlay::new();
1180
1181 let area = Rect::new(0, 0, w, h);
1182 let mut buf = Buffer::empty(area);
1183 for y in 0..h {
1184 for x in 0..w {
1185 buf[(x, y)].set_symbol("X");
1186 }
1187 }
1188 let mut stack = ViewStack::new();
1189 stack.push(overlay);
1190 stack.render(area, &mut buf);
1191
1192 let rows: Vec<String> = (0..h)
1193 .map(|y| (0..w).map(|x| buf[(x, y)].symbol().to_string()).collect())
1194 .collect();
1195 let text = rows.join("\n");
1196
1197 // Footer keeps every action.
1198 for label in ["scroll", "page", "top/bottom", "resume tail", "close"] {
1199 assert!(text.contains(label), "{w}x{h}: footer missing '{label}'");
1200 }
1201
1202 // Composited frame is fully opaque.
1203 assert!(!text.contains('X'), "{w}x{h}: background bleed-through");
1204 assert_eq!(
1205 buf[(w / 2, h / 2)].bg,
1206 palette::WHALE_BG,
1207 "{w}x{h}: modal interior must be opaque"
1208 );
1209
1210 // No horizontal overflow.
1211 for (y, row) in rows.iter().enumerate() {
1212 assert!(
1213 UnicodeWidthStr::width(row.trim_end()) <= w as usize,
1214 "{w}x{h}: row {y} overflows width: {row:?}"
1215 );
1216 }
1217 }
1218 }
1219
1220 #[test]
1221 fn backtrack_preview_out_of_range_does_not_panic() {
1222 // Selecting beyond the user-cell count should simply not
1223 // highlight anything — no panic, no marker.
1224 let mut v = LiveTranscriptOverlay::new();
1225 install_snapshots(&mut v, vec![user("only")]);
1226 v.set_backtrack_preview(99);
1227 let area = Rect::new(0, 0, 40, 10);
1228 let mut buf = Buffer::empty(area);
1229 v.render(area, &mut buf);
1230 }
1231 }
1232
1232 lines RUST