返回 CodeWhale
transcript.rs
根目录 / crates / tui / src / tui / transcript.rs
1 //! Cached transcript rendering for the TUI.
2 //!
3 //! ## Per-cell revision caching
4 //!
5 //! A whole-transcript cache would re-wrap every cell whenever the streaming
6 //! Assistant mutates. Instead each index has a paired revision and unchanged
7 //! cells reuse their wrapped lines. Width, options, fold state, or destructive
8 //! identity changes bust the affected cache. Streaming therefore scales with
9 //! changed cells rather than history; width/option changes still bust all
10 //! cells because wrapping and visibility depend on them.
11
12 use std::collections::HashMap;
13 use std::path::{Path, PathBuf};
14 use std::sync::Arc;
15
16 use ratatui::{
17 style::Style,
18 text::{Line, Span},
19 };
20
21 use crate::tui::app::TranscriptSpacing;
22 use crate::tui::history::{
23 CellFoldAction, CellFoldActionTarget, HistoryCell, TranscriptActionOwner, TranscriptFold,
24 TranscriptRenderOptions,
25 };
26 use codewhale_localization::{MessageId, tr};
27 use codewhale_tui_kit::scrolling::TranscriptLineMeta;
28 use codewhale_tui_kit::ui_text::CopyLineSeparator;
29
30 /// Revision-bound render output. Arcs keep cache enumeration O(cells) instead
31 /// of deep-cloning every rendered line on ambient frames (issue #78); the
32 /// flattened output owns the only per-frame line copy.
33 #[derive(Debug)]
34 struct CachedCell {
35 /// Revision at which lines and metadata were rendered.
36 revision: u64,
37 /// Lines and aligned metadata; no inter-cell spacers. OSC 8 targets never
38 /// enter the ratatui cell buffer. Copy separators preserve source hard
39 /// newlines while allowing copy to remove visual soft-wrap breaks; prefix
40 /// widths strip visual rails. All four vectors remain index-aligned.
41 lines: Arc<Vec<Line<'static>>>,
42 links: Arc<Vec<Vec<codewhale_tui_kit::osc8::LineLink>>>,
43 copy_separators: Arc<Vec<CopyLineSeparator>>,
44 copy_prefix_widths: Arc<Vec<usize>>,
45 /// Empty/blank facts keep spacing decisions independent of rendered text.
46 /// A block ending blank has paid for separation and must not get another.
47 is_empty: bool,
48 ends_blank: bool,
49 /// Semantic role and tool grouping feed the explicit boundary matrix, so
50 /// spacing never depends on strings, palette, terminal depth, or motion.
51 kind: TranscriptBlockKind,
52 is_tool_groupable: bool,
53 fold_action: Option<CellFoldAction>,
54 /// Only the changing Assistant cell carries incremental parser state;
55 /// stable lines stay above its replaceable-tail index.
56 incremental_markdown:
57 Option<Box<codewhale_tui_kit::markdown_render::IncrementalMarkdownRenderCache>>,
58 /// Settled form of the animation-mutated hot tail, restored on append so
59 /// the stable prefix is not reparsed.
60 hot_tail_original: Option<(usize, Line<'static>)>,
61 }
62
63 /// Proof that a live Assistant source only gained appended bytes. Visual-only
64 /// revision bumps can therefore reuse it; revisions are transformed exactly
65 /// as they are for `ensure_*`.
66 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
67 pub(crate) struct StreamingSourceReceipt {
68 pub cell_index: usize,
69 pub from_revision: u64,
70 pub to_revision: u64,
71 pub content_len: usize,
72 }
73
74 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
75 enum TranscriptBlockKind {
76 User,
77 Reasoning,
78 Answer,
79 ToolAction,
80 DurableWork,
81 System,
82 Notice,
83 }
84
85 impl TranscriptBlockKind {
86 fn for_cell(cell: &HistoryCell) -> Self {
87 match cell {
88 HistoryCell::User { .. } => Self::User,
89 HistoryCell::Thinking { .. } => Self::Reasoning,
90 HistoryCell::Assistant { .. } => Self::Answer,
91 HistoryCell::Tool(tool) if tool.is_durable_work_receipt() => Self::DurableWork,
92 HistoryCell::Tool(_) | HistoryCell::SubAgent(_) => Self::ToolAction,
93 HistoryCell::System { .. } => Self::System,
94 HistoryCell::Error { .. }
95 | HistoryCell::Automation(_)
96 | HistoryCell::ApprovalReceipt(_)
97 | HistoryCell::ArchivedContext { .. } => Self::Notice,
98 }
99 }
100 }
101
102 /// A visible boundary costs one row, because terminal separator rows displace
103 /// content and two rows add no extra legibility. Only an opt-in spacious turn
104 /// costs two.
105 const BLOCK_SEPARATOR_ROWS: usize = 1;
106
107 /// Complete transcript spacing vocabulary; no blanket per-cell padding.
108 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
109 enum TranscriptBoundary {
110 Joined,
111 /// Adjacent tool cells share one compact rail with no per-call padding.
112 GroupedTool,
113 /// Transition between response phases, tools, Work, or notices.
114 Activity,
115 /// Human turn boundary; visible even at compact density.
116 Turn,
117 }
118
119 #[derive(Debug)]
120 pub struct TranscriptViewCache {
121 width: u16,
122 options: TranscriptRenderOptions,
123 workspace: Option<PathBuf>,
124 workspace_changed: bool,
125 /// Explicit per-cell fold intent affects rendering without changing cell
126 /// revisions. Keyed by original virtual cell index.
127 cell_folds: HashMap<usize, TranscriptFold>,
128 /// Index of the newest durable Work receipt (checklist / plan snapshot)
129 /// in the last pass. When a new one lands the previous newest must
130 /// re-render collapsed, and its revision alone would not say so.
131 newest_work_receipt: Option<usize>,
132 /// Index of the newest user turn in the last pass. Only it carries the
133 /// elevated-surface background; when a new prompt lands the previous
134 /// newest must re-render on the bare ground, and its revision alone
135 /// would not say so.
136 newest_user_turn: Option<usize>,
137 fold_action_target: Option<CellFoldActionTarget>,
138 transcript_action_owner: Option<TranscriptActionOwner>,
139 identity_epoch: Option<u64>,
140 fold_action_rendered_cell: Option<usize>,
141 /// Per-cell renders plus flattened lines and index-aligned link/selection
142 /// metadata. Rail prefix widths strip decoration without glyph guessing
143 /// (#1163); deterministic counters measure the production cache path.
144 per_cell: Vec<CachedCell>,
145 /// `per_cell[i].revision`, kept contiguous. The steady-state check and the
146 /// first-changed-cell search compare this against the caller's revisions
147 /// without touching a single cached render (#6652).
148 seen_revisions: Vec<u64>,
149 lines: Vec<Line<'static>>,
150 line_links: Vec<Vec<codewhale_tui_kit::osc8::LineLink>>,
151 line_meta: Vec<TranscriptLineMeta>,
152 /// Visual-only prefix widths let selection copy strip rails without glyph guesses.
153 rail_prefix_widths: Vec<usize>,
154 /// Flat line index at which each cell's rendered lines begin (hidden
155 /// cells record where their successor starts). Lets a suffix rebuild
156 /// truncate and an action-hint move repaint without scanning every row.
157 cell_line_starts: Vec<usize>,
158 streaming_source_receipt: Option<StreamingSourceReceipt>,
159 streaming_lines_reflattened: u64,
160 streaming_meta_rows_scanned: u64,
161 /// Cells (re)rendered over the cache's lifetime; proves a settled frame
162 /// renders nothing.
163 #[cfg(test)]
164 cells_rendered: u64,
165 }
166
167 impl TranscriptViewCache {
168 #[must_use]
169 pub fn new() -> Self {
170 Self {
171 width: 0,
172 options: TranscriptRenderOptions::default(),
173 workspace: None,
174 workspace_changed: false,
175 cell_folds: HashMap::new(),
176 newest_work_receipt: None,
177 newest_user_turn: None,
178 fold_action_target: None,
179 transcript_action_owner: None,
180 identity_epoch: None,
181 fold_action_rendered_cell: None,
182 per_cell: Vec::new(),
183 seen_revisions: Vec::new(),
184 lines: Vec::new(),
185 line_links: Vec::new(),
186 line_meta: Vec::new(),
187 rail_prefix_widths: Vec::new(),
188 cell_line_starts: Vec::new(),
189 streaming_source_receipt: None,
190 streaming_lines_reflattened: 0,
191 streaming_meta_rows_scanned: 0,
192 #[cfg(test)]
193 cells_rendered: 0,
194 }
195 }
196
197 pub(crate) fn set_streaming_source_receipt(&mut self, receipt: Option<StreamingSourceReceipt>) {
198 self.streaming_source_receipt = receipt;
199 }
200
201 pub fn set_workspace(&mut self, workspace: Option<&Path>) {
202 if self.workspace.as_deref() != workspace {
203 self.workspace = workspace.map(Path::to_path_buf);
204 self.workspace_changed = true;
205 }
206 }
207
208 #[cfg(test)]
209 pub(crate) fn streaming_render_work(
210 &self,
211 cell_index: usize,
212 ) -> Option<codewhale_tui_kit::markdown_render::MarkdownRenderWork> {
213 self.per_cell
214 .get(cell_index)?
215 .incremental_markdown
216 .as_ref()
217 .map(|cache| cache.work())
218 }
219
220 pub(crate) fn take_transcript_action(
221 &mut self,
222 ) -> Option<(TranscriptActionOwner, Option<CellFoldActionTarget>)> {
223 Some((
224 self.transcript_action_owner.take()?,
225 self.fold_action_target.take(),
226 ))
227 }
228
229 pub(crate) fn retarget(
230 &mut self,
231 owner: Option<TranscriptActionOwner>,
232 original_index_map: Option<&[usize]>,
233 ) {
234 // Scrolling moves the owner to the newest visible cell, so this runs
235 // on scroll frames. The hint only rewrites one line of the previous
236 // and next owner, so repaint those rows in place instead of
237 // re-flattening the transcript tail below them (#6652).
238 if let Some(change) = self.set_action_owner(owner, original_index_map)
239 && !self.repaint_action_hints(change)
240 {
241 self.flatten_from(
242 self.options.spacing,
243 first_hint_cell(change).saturating_sub(1),
244 );
245 }
246 }
247
248 /// Convenience entry point; the live path uses shards to avoid cloning.
249 #[cfg(test)]
250 pub fn ensure(
251 &mut self,
252 cells: &[HistoryCell],
253 cell_revisions: &[u64],
254 width: u16,
255 options: TranscriptRenderOptions,
256 ) {
257 self.ensure_split(
258 &[cells],
259 cell_revisions,
260 width,
261 options,
262 &HashMap::new(),
263 None,
264 None,
265 );
266 }
267
268 /// Ensure logically concatenated shards without cloning history plus the
269 /// active tail each frame. Explicit cache inputs keep identity/fold/map indices
270 /// attached to original virtual cells even when filtering changes positions.
271 #[allow(clippy::too_many_arguments)]
272 pub fn ensure_split(
273 &mut self,
274 cell_shards: &[&[HistoryCell]],
275 cell_revisions: &[u64],
276 width: u16,
277 options: TranscriptRenderOptions,
278 cell_folds: &HashMap<usize, TranscriptFold>,
279 original_index_map: Option<&[usize]>,
280 action_owner: Option<TranscriptActionOwner>,
281 ) {
282 let total_cells: usize = cell_shards.iter().map(|s| s.len()).sum();
283 self.ensure_iter(
284 total_cells,
285 |index| {
286 let mut remaining = index;
287 for shard in cell_shards {
288 if let Some(cell) = shard.get(remaining) {
289 return cell;
290 }
291 remaining -= shard.len();
292 }
293 unreachable!("cell index {index} is below total_cells")
294 },
295 cell_revisions,
296 width,
297 options,
298 cell_folds,
299 original_index_map,
300 action_owner,
301 );
302 }
303
304 /// Ensure an already-filtered list plus its original-index map. Collapse
305 /// may skip cells or substitute tool summaries, so the map is the contract
306 /// that keeps fold/action state attached to original virtual indices
307 /// rather than positional rendered indices (#3896).
308 #[allow(clippy::too_many_arguments)]
309 pub fn ensure_filtered(
310 &mut self,
311 cells: &[&HistoryCell],
312 cell_revisions: &[u64],
313 width: u16,
314 options: TranscriptRenderOptions,
315 cell_folds: &HashMap<usize, TranscriptFold>,
316 original_index_map: Option<&[usize]>,
317 action_owner: Option<TranscriptActionOwner>,
318 ) {
319 self.ensure_iter(
320 cells.len(),
321 |index| cells[index],
322 cell_revisions,
323 width,
324 options,
325 cell_folds,
326 original_index_map,
327 action_owner,
328 );
329 }
330
331 #[allow(clippy::too_many_arguments)]
332 fn ensure_iter<'a>(
333 &mut self,
334 total_cells: usize,
335 cell_at: impl Fn(usize) -> &'a HistoryCell,
336 cell_revisions: &[u64],
337 width: u16,
338 options: TranscriptRenderOptions,
339 cell_folds: &HashMap<usize, TranscriptFold>,
340 original_index_map: Option<&[usize]>,
341 action_owner: Option<TranscriptActionOwner>,
342 ) {
343 let identity_changed = action_owner.is_some_and(|owner| {
344 self.identity_epoch
345 .is_some_and(|epoch| epoch != owner.identity_epoch)
346 });
347 if let Some(owner) = action_owner {
348 self.identity_epoch = Some(owner.identity_epoch);
349 }
350 self.transcript_action_owner = action_owner;
351 // Collapsed reasoning has a fixed preview budget; viewport height
352 // does not participate in wrapping or cached cell identity.
353 self.options.thinking_checkpoints = options.thinking_checkpoints;
354 let workspace_changed = std::mem::take(&mut self.workspace_changed);
355 let layout_changed =
356 self.width != width || self.options != options || identity_changed || workspace_changed;
357 let folded_changed = self.cell_folds != *cell_folds;
358 let revisions_match = cell_revisions.len() == total_cells;
359 // Cells `0..unchanged` were rendered at exactly these revisions, so
360 // their cached output (and what they are: kind, supersession) is
361 // current. Layout, fold, or a mismatched revision vector (never
362 // trusted) leaves no such prefix. In steady state this is all of
363 // them, and the frame ends below without rendering, moving, or even
364 // looking at a cell (#6652).
365 let mut unchanged = if layout_changed || folded_changed || !revisions_match {
366 0
367 } else {
368 self.seen_revisions
369 .iter()
370 .zip(cell_revisions)
371 .position(|(seen, current)| seen != current)
372 .unwrap_or_else(|| self.seen_revisions.len().min(total_cells))
373 };
374 // `todo_write` replaces the whole list on every call, so only the
375 // newest snapshot is worth a full card (#5871). When a new one lands
376 // the previous newest must re-render collapsed; its own revision has
377 // not changed, so supersession has to invalidate the cache itself.
378 let newest_work_receipt = newest_matching_cell(
379 total_cells,
380 unchanged,
381 self.newest_work_receipt,
382 &cell_at,
383 |cell| matches!(cell, HistoryCell::Tool(tool) if tool.is_durable_work_receipt()),
384 );
385 let work_receipt_changed = self.newest_work_receipt != newest_work_receipt;
386 self.newest_work_receipt = newest_work_receipt;
387 // Same supersession shape as the work receipt: the highlight lives on
388 // the newest user turn only, so a newly sent prompt must un-highlight
389 // its predecessor even though that cell's own revision never moved.
390 let newest_user_turn = newest_matching_cell(
391 total_cells,
392 unchanged,
393 self.newest_user_turn,
394 &cell_at,
395 |cell| matches!(cell, HistoryCell::User { .. }),
396 );
397 let user_turn_changed = self.newest_user_turn != newest_user_turn;
398 self.newest_user_turn = newest_user_turn;
399 if layout_changed || folded_changed || work_receipt_changed || user_turn_changed {
400 self.per_cell.clear();
401 self.seen_revisions.clear();
402 unchanged = 0;
403 }
404 self.width = width;
405 self.options = options;
406 // Cloning the map every frame is wasted work for the usual unchanged
407 // case (#6652); `folded_changed` already compared the two.
408 if folded_changed {
409 self.cell_folds.clone_from(cell_folds);
410 }
411 let previous_rendered_target = self.fold_action_rendered_cell;
412
413 // Same-index revision reuse is intentional: insert/remove shifts must
414 // cold-render rather than attach cached lines to another cell. The
415 // destructive identity epoch also prevents revision reuse after an
416 // index is removed and later filled by a different cell.
417 let old_len = self.per_cell.len();
418 let mut any_dirty = layout_changed
419 || folded_changed
420 || work_receipt_changed
421 || user_turn_changed
422 || old_len != total_cells;
423 let mut first_dirty: Option<usize> = if old_len != total_cells {
424 Some(old_len.min(total_cells))
425 } else {
426 None
427 };
428
429 // Update the cache where it stands: a frame that changes only the tail
430 // renders only the tail instead of moving every cached cell out and
431 // back (#6652).
432 self.per_cell.truncate(total_cells);
433 self.seen_revisions.truncate(total_cells);
434 let mut dirty_cells = 0usize;
435 let mut streaming_tail_update = None;
436 let workspace = self.workspace.clone();
437 let mut link_memo: HashMap<
438 String,
439 Option<codewhale_tui_kit::markdown_render::ResolvedLink>,
440 > = HashMap::new();
441 let mut workspace_resolver = workspace.as_deref().map(|ws| {
442 move |candidate: &str| -> Option<codewhale_tui_kit::markdown_render::ResolvedLink> {
443 if let Some(cached) = link_memo.get(candidate) {
444 return cached.clone();
445 }
446 let resolved = crate::tui::history::parse_workspace_link_candidate(candidate, ws)
447 .and_then(|(target, line)| {
448 crate::tui::history::file_uri_for_path(&target.path).map(|uri| {
449 codewhale_tui_kit::markdown_render::ResolvedLink { target: uri, line }
450 })
451 });
452 link_memo.insert(candidate.to_string(), resolved.clone());
453 resolved
454 }
455 });
456
457 for idx in unchanged..total_cells {
458 // A mismatched revision vector is never trusted.
459 let current_rev = cell_revisions
460 .get(idx)
461 .copied()
462 .filter(|_| revisions_match)
463 .unwrap_or(u64::MAX);
464 if revisions_match && self.seen_revisions.get(idx) == Some(&current_rev) {
465 continue;
466 }
467 let cell = cell_at(idx);
468 let original_idx = original_index_map
469 .map(|m| *m.get(idx).unwrap_or(&idx))
470 .unwrap_or(idx);
471 let is_tool_groupable = matches!(cell, HistoryCell::Tool(_));
472 let render_width = if is_tool_groupable {
473 width.saturating_sub(2).max(1)
474 } else {
475 width
476 };
477 let fold = cell_folds.get(&original_idx).copied();
478
479 any_dirty = true;
480 dirty_cells = dirty_cells.saturating_add(1);
481 #[cfg(test)]
482 {
483 self.cells_rendered += 1;
484 }
485 first_dirty = Some(first_dirty.map_or(idx, |current| current.min(idx)));
486
487 if fold != Some(TranscriptFold::Collapsed)
488 && matches!(
489 cell,
490 HistoryCell::Assistant {
491 streaming: true,
492 ..
493 }
494 )
495 {
496 if idx >= self.per_cell.len() {
497 self.per_cell.push(CachedCell {
498 revision: current_rev,
499 lines: Arc::new(Vec::new()),
500 links: Arc::new(Vec::new()),
501 copy_separators: Arc::new(Vec::new()),
502 copy_prefix_widths: Arc::new(Vec::new()),
503 is_empty: true,
504 ends_blank: false,
505 kind: TranscriptBlockKind::Answer,
506 is_tool_groupable: false,
507 fold_action: None,
508 incremental_markdown: Some(Box::default()),
509 hot_tail_original: None,
510 });
511 self.seen_revisions.push(current_rev);
512 }
513 let receipt = self.streaming_source_receipt;
514 let cached = &mut self.per_cell[idx];
515 let shape_before = (cached.kind, cached.is_tool_groupable, cached.is_empty);
516 if let Some((line_index, original)) = cached.hot_tail_original.take()
517 && let Some(line) = Arc::make_mut(&mut cached.lines).get_mut(line_index)
518 {
519 *line = original;
520 }
521 let content_len = match cell {
522 HistoryCell::Assistant { content, .. } => content.len(),
523 _ => 0,
524 };
525 let verified_append = receipt.is_some_and(|receipt| {
526 receipt.cell_index == original_idx
527 && receipt.from_revision == cached.revision
528 && receipt.to_revision == current_rev
529 && receipt.content_len == content_len
530 });
531 let incremental = cached.incremental_markdown.get_or_insert_with(Box::default);
532 let replace_from = cell
533 .update_incremental_streaming_render(
534 render_width,
535 options,
536 verified_append,
537 incremental,
538 Arc::make_mut(&mut cached.lines),
539 Arc::make_mut(&mut cached.links),
540 Arc::make_mut(&mut cached.copy_separators),
541 Arc::make_mut(&mut cached.copy_prefix_widths),
542 )
543 .expect("streaming Assistant matched above");
544 let cached_lines = Arc::make_mut(&mut cached.lines);
545 let last_index = cached_lines.len().checked_sub(1);
546 if let Some((index, last)) = last_index
547 .and_then(|index| cached_lines.get_mut(index).map(|line| (index, line)))
548 {
549 cached.hot_tail_original = Some((index, last.clone()));
550 crate::tui::history::apply_hot_tail_to_line(last, options.low_motion);
551 }
552 cached.revision = current_rev;
553 cached.is_empty = cached.lines.is_empty();
554 cached.ends_blank = last_line_is_blank(&cached.lines);
555 cached.kind = TranscriptBlockKind::Answer;
556 cached.is_tool_groupable = false;
557 cached.fold_action = None;
558 // The spacer and group rail between this cell and its
559 // predecessor depend on what this cell is. A tool, hidden, or
560 // other cell becoming a streaming answer in place (a filter
561 // shifting rows under it) changes them, so only an answer that
562 // stays an answer may take the tail-only shortcut.
563 let same_shape =
564 shape_before == (cached.kind, cached.is_tool_groupable, cached.is_empty);
565 self.seen_revisions[idx] = current_rev;
566 // Hot-tail styling can affect the preceding settled line.
567 streaming_tail_update = same_shape.then_some((idx, replace_from.saturating_sub(1)));
568 continue;
569 }
570
571 let mut cell_options = options;
572 cell_options.superseded_work_receipt = matches!(
573 cell,
574 HistoryCell::Tool(tool) if tool.is_durable_work_receipt()
575 ) && newest_work_receipt
576 .is_some_and(|newest| newest != idx);
577 cell_options.newest_user_turn = matches!(cell, HistoryCell::User { .. })
578 && newest_user_turn.is_some_and(|newest| newest == idx);
579 let rendered = render_cached_cell(
580 cell,
581 current_rev,
582 width,
583 cell_options,
584 fold,
585 workspace_resolver.as_mut().map(|resolver| {
586 resolver as &mut codewhale_tui_kit::markdown_render::WorkspaceLinkResolver<'_>
587 }),
588 );
589 if let Some(slot) = self.per_cell.get_mut(idx) {
590 *slot = rendered;
591 self.seen_revisions[idx] = current_rev;
592 } else {
593 self.per_cell.push(rendered);
594 self.seen_revisions.push(current_rev);
595 }
596 }
597 debug_assert_eq!(self.per_cell.len(), total_cells);
598 debug_assert_eq!(self.seen_revisions.len(), total_cells);
599 // Rows from here down are rebuilt this frame; rows above it are
600 // untouched and still sit at their recorded `cell_line_starts`.
601 let mut rebuild_from = if !any_dirty {
602 usize::MAX
603 } else if layout_changed {
604 0
605 } else {
606 self.visible_rebuild_start(first_dirty.unwrap_or(0).saturating_sub(1))
607 };
608 let mut hint_settled = true;
609 if let Some(change) = self.set_action_owner(action_owner, original_index_map) {
610 // Scrolling moves the owner to the newest visible cell, including
611 // while a reply streams and its cell is dirty every frame. A
612 // hinted cell inside the rebuilt suffix is re-flattened with the
613 // new hint anyway; one above it keeps its geometry, so repaint its
614 // single hint row instead of rebuilding the tail below it (#6652).
615 let above = |cell: Option<usize>| cell.filter(|&cell| cell < rebuild_from);
616 let in_place = HintChange {
617 previous: above(change.previous),
618 next: above(change.next),
619 };
620 let repainted = self.repaint_action_hints(in_place);
621 if !repainted {
622 any_dirty = true;
623 rebuild_from = self.visible_rebuild_start(
624 rebuild_from.min(first_hint_cell(change).saturating_sub(1)),
625 );
626 }
627 hint_settled = repainted && in_place == change;
628 }
629
630 if !any_dirty {
631 return;
632 }
633
634 if !layout_changed
635 && !folded_changed
636 && (hint_settled || previous_rendered_target == self.fold_action_rendered_cell)
637 && old_len == total_cells
638 && dirty_cells == 1
639 && let Some((cell_index, line_from)) = streaming_tail_update
640 && cell_index + 1 == total_cells
641 && self.flatten_streaming_tail(cell_index, line_from)
642 {
643 return;
644 }
645
646 self.flatten_from(options.spacing, rebuild_from);
647 }
648
649 /// A hidden cell has no line boundary at which to truncate. Rebuild from
650 /// a visible predecessor so appearance/disappearance cannot leave its old
651 /// spacer or the following cell's boundary behind.
652 fn visible_rebuild_start(&self, mut from: usize) -> usize {
653 while from > 0 && self.per_cell.get(from).is_some_and(|cell| cell.is_empty) {
654 from -= 1;
655 }
656 from
657 }
658
659 /// Returns the previous and next hinted cells when the hint moved.
660 fn set_action_owner(
661 &mut self,
662 owner: Option<TranscriptActionOwner>,
663 original_index_map: Option<&[usize]>,
664 ) -> Option<HintChange> {
665 self.transcript_action_owner = owner;
666 let rendered = owner.and_then(|owner| match original_index_map {
667 Some(map) => map.iter().position(|&index| index == owner.cell_index),
668 None => (owner.cell_index < self.per_cell.len()).then_some(owner.cell_index),
669 });
670 self.fold_action_target = owner.and_then(|owner| {
671 Some(CellFoldActionTarget {
672 owner,
673 action: self.per_cell.get(rendered?)?.fold_action?,
674 })
675 });
676 let next = self
677 .fold_action_target
678 .filter(|target| target.action == CellFoldAction::Expand)
679 .and(rendered);
680 let previous = self.fold_action_rendered_cell;
681 self.fold_action_rendered_cell = next;
682 (previous != next).then_some(HintChange { previous, next })
683 }
684
685 /// Rewrite the affordance row of the cells whose hint changed. The hint
686 /// only swaps the final span of a cell's header, so geometry, spacers,
687 /// and every other row are unchanged. Returns false when the flat index
688 /// cannot vouch for a cell, and the caller falls back to a rebuild.
689 fn repaint_action_hints(&mut self, change: HintChange) -> bool {
690 let hint = self.action_hint();
691 for cell_index in [change.previous, change.next].into_iter().flatten() {
692 let Some(cached) = self.per_cell.get(cell_index) else {
693 return false;
694 };
695 if cached.lines.is_empty() {
696 continue;
697 }
698 let line_in_cell = 0;
699 let Some(at) = self
700 .cell_line_starts
701 .get(cell_index)
702 .map(|start| start + line_in_cell)
703 else {
704 return false;
705 };
706 if self
707 .line_meta
708 .get(at)
709 .and_then(TranscriptLineMeta::cell_line)
710 != Some((cell_index, line_in_cell))
711 {
712 return false;
713 }
714 let (line, links, rail_prefix_width, meta) =
715 self.flat_cell_line(hint.as_deref(), cell_index, line_in_cell);
716 self.lines[at] = line;
717 self.line_links[at] = links;
718 self.rail_prefix_widths[at] = rail_prefix_width;
719 self.line_meta[at] = meta;
720 self.streaming_lines_reflattened = self.streaming_lines_reflattened.saturating_add(1);
721 }
722 true
723 }
724
725 /// Localized Space affordance, or None when it cannot fit the width.
726 fn action_hint(&self) -> Option<String> {
727 let hint = format!(
728 "Space:{}",
729 tr(self.options.locale, MessageId::TranscriptReasoningExpand)
730 );
731 (unicode_width::UnicodeWidthStr::width(hint.as_str())
732 <= usize::from(self.width).saturating_sub(2))
733 .then_some(hint)
734 }
735
736 /// Final flat form of one cached cell line: hint, group rail, links, and
737 /// copy metadata. Shared by flattening and in-place hint repaint.
738 fn flat_cell_line(
739 &self,
740 hint: Option<&str>,
741 cell_index: usize,
742 line_in_cell: usize,
743 ) -> (
744 Line<'static>,
745 Vec<codewhale_tui_kit::osc8::LineLink>,
746 usize,
747 TranscriptLineMeta,
748 ) {
749 let cached = &self.per_cell[cell_index];
750 let rendered_line_count = cached.lines.len();
751 let line = &cached.lines[line_in_cell];
752 let hint = hint.filter(|hint| {
753 self.fold_action_rendered_cell == Some(cell_index)
754 && line_in_cell == 0
755 && line
756 .width()
757 .saturating_sub(line.spans.last().map_or(0, Span::width))
758 + unicode_width::UnicodeWidthStr::width(*hint)
759 < usize::from(self.width)
760 });
761 let is_hint = hint.is_some();
762 let hinted = hint.map(|hint| {
763 let mut hinted = line.clone();
764 if let Some(span) = hinted.spans.last_mut() {
765 span.content = format!(" {hint}").into();
766 }
767 hinted
768 });
769 let line = hinted.as_ref().unwrap_or(line);
770 let rail = if self.options.calm_cards() && cached.is_tool_groupable {
771 (line_in_cell > 0).then_some(crate::tui::widgets::tool_card::CardRail::Indent)
772 } else {
773 tool_group_rail(
774 self.per_cell.as_slice(),
775 cell_index,
776 line_in_cell,
777 rendered_line_count,
778 )
779 };
780 let final_line = line_with_group_rail(line, rail, usize::from(self.width));
781 let final_links = if is_hint {
782 Vec::new()
783 } else {
784 links_with_group_rail(
785 cached.links.get(line_in_cell).map_or(&[], Vec::as_slice),
786 rail,
787 usize::from(self.width),
788 )
789 };
790 let rail_prefix_width = if rail == Some(crate::tui::widgets::tool_card::CardRail::Indent) {
791 2 + compute_rail_prefix_width(line)
792 } else {
793 compute_rail_prefix_width(&final_line)
794 };
795 let copy_prefix_width = if is_hint {
796 final_line.width().saturating_sub(rail_prefix_width)
797 } else {
798 cached
799 .copy_prefix_widths
800 .get(line_in_cell)
801 .copied()
802 .unwrap_or(0)
803 };
804 let meta = TranscriptLineMeta::CellLine {
805 cell_index,
806 line_in_cell,
807 copy_prefix_width,
808 copy_separator_after: cached
809 .copy_separators
810 .get(line_in_cell)
811 .copied()
812 .unwrap_or(CopyLineSeparator::Newline),
813 };
814 (final_line, final_links, rail_prefix_width, meta)
815 }
816
817 fn flatten(&mut self, spacing: TranscriptSpacing) {
818 self.lines.clear();
819 self.line_links.clear();
820 self.line_meta.clear();
821 self.rail_prefix_widths.clear();
822 self.cell_line_starts.clear();
823 self.append_flattened_cells(spacing, 0);
824 }
825
826 /// Rebuild only a suffix while preserving its predecessor spacer.
827 /// Streaming normally changes only the active tail; rebuilding from the
828 /// previous cell preserves boundary correctness without flattening all
829 /// transcript lines on every token chunk.
830 fn flatten_from(&mut self, spacing: TranscriptSpacing, first_cell: usize) {
831 if first_cell == 0 || self.lines.is_empty() || self.line_meta.is_empty() {
832 self.flatten(spacing);
833 return;
834 }
835
836 let truncate_at = match self.cell_line_starts.get(first_cell) {
837 Some(&start) => start,
838 None => self
839 .line_meta
840 .iter()
841 .position(|meta| match meta {
842 TranscriptLineMeta::CellLine { cell_index, .. } => *cell_index >= first_cell,
843 TranscriptLineMeta::Spacer { .. } => false,
844 })
845 .unwrap_or(self.lines.len()),
846 };
847 self.cell_line_starts
848 .truncate(first_cell.min(self.cell_line_starts.len()));
849 self.lines.truncate(truncate_at);
850 self.line_links.truncate(truncate_at);
851 self.line_meta.truncate(truncate_at);
852 self.rail_prefix_widths.truncate(truncate_at);
853 self.append_flattened_cells(spacing, first_cell);
854 }
855
856 /// Replace only the final streaming cell's changing Markdown tail. Search
857 /// backward from the old hot tail, so append-only updates scan the small
858 /// replaceable suffix; return false when no canonical boundary exists.
859 fn flatten_streaming_tail(&mut self, cell_index: usize, line_from: usize) -> bool {
860 let mut truncate_at = None;
861 for (index, meta) in self.line_meta.iter().enumerate().rev() {
862 self.streaming_meta_rows_scanned = self.streaming_meta_rows_scanned.saturating_add(1);
863 if matches!(
864 meta,
865 TranscriptLineMeta::CellLine {
866 cell_index: candidate,
867 line_in_cell,
868 ..
869 } if *candidate == cell_index && *line_in_cell == line_from
870 ) {
871 truncate_at = Some(index);
872 break;
873 }
874 }
875 let Some(truncate_at) = truncate_at else {
876 return false;
877 };
878 self.lines.truncate(truncate_at);
879 self.line_links.truncate(truncate_at);
880 self.line_meta.truncate(truncate_at);
881 self.rail_prefix_widths.truncate(truncate_at);
882
883 let Some(cached) = self.per_cell.get(cell_index) else {
884 return false;
885 };
886 let rendered_line_count = cached.lines.len();
887 for line_in_cell in line_from..rendered_line_count {
888 let line = &cached.lines[line_in_cell];
889 let rail = tool_group_rail(
890 self.per_cell.as_slice(),
891 cell_index,
892 line_in_cell,
893 rendered_line_count,
894 );
895 let final_line = line_with_group_rail(line, rail, usize::from(self.width));
896 let final_links = links_with_group_rail(
897 cached.links.get(line_in_cell).map_or(&[], Vec::as_slice),
898 rail,
899 usize::from(self.width),
900 );
901 self.rail_prefix_widths
902 .push(compute_rail_prefix_width(&final_line));
903 self.lines.push(final_line);
904 self.line_links.push(final_links);
905 self.line_meta.push(TranscriptLineMeta::CellLine {
906 cell_index,
907 line_in_cell,
908 copy_prefix_width: cached
909 .copy_prefix_widths
910 .get(line_in_cell)
911 .copied()
912 .unwrap_or(0),
913 copy_separator_after: cached
914 .copy_separators
915 .get(line_in_cell)
916 .copied()
917 .unwrap_or(CopyLineSeparator::Newline),
918 });
919 self.streaming_lines_reflattened = self.streaming_lines_reflattened.saturating_add(1);
920 }
921 true
922 }
923
924 fn append_flattened_cells(&mut self, spacing: TranscriptSpacing, start_cell: usize) {
925 let hint = self.action_hint();
926 // A start beyond the recorded prefix is only reachable through the
927 // fallback scan; pad so indices stay aligned with cells.
928 let pad_to = start_cell.min(self.per_cell.len());
929 while self.cell_line_starts.len() < pad_to {
930 self.cell_line_starts.push(self.lines.len());
931 }
932 for cell_index in start_cell..self.per_cell.len() {
933 self.cell_line_starts.push(self.lines.len());
934 let cached = &self.per_cell[cell_index];
935 if cached.is_empty {
936 continue;
937 }
938 for line_in_cell in 0..cached.lines.len() {
939 let (final_line, final_links, rail_prefix_width, meta) =
940 self.flat_cell_line(hint.as_deref(), cell_index, line_in_cell);
941 self.rail_prefix_widths.push(rail_prefix_width);
942 self.lines.push(final_line);
943 self.line_links.push(final_links);
944 self.line_meta.push(meta);
945 self.streaming_lines_reflattened =
946 self.streaming_lines_reflattened.saturating_add(1);
947 }
948
949 let cached = &self.per_cell[cell_index];
950 if let Some(next) = next_visible_cell(&self.per_cell, cell_index) {
951 let separator = separator_between(cached, next, spacing);
952 let rail = (separator.railed && !self.options.calm_cards())
953 .then_some(crate::tui::widgets::tool_card::CardRail::Middle);
954 for _ in 0..separator.rows {
955 let line = line_with_group_rail(&Line::from(""), rail, usize::from(self.width));
956 let copy_prefix_width = compute_rail_prefix_width(&line);
957 self.rail_prefix_widths.push(copy_prefix_width);
958 self.lines.push(line);
959 self.line_links.push(Vec::new());
960 self.line_meta
961 .push(TranscriptLineMeta::Spacer { copy_prefix_width });
962 }
963 }
964 }
965 }
966
967 #[must_use]
968 pub fn lines(&self) -> &[Line<'static>] {
969 &self.lines
970 }
971
972 #[must_use]
973 pub fn line_links(&self) -> &[Vec<codewhale_tui_kit::osc8::LineLink>] {
974 &self.line_links
975 }
976
977 #[must_use]
978 pub fn line_meta(&self) -> &[TranscriptLineMeta] {
979 &self.line_meta
980 }
981
982 #[must_use]
983 pub fn total_lines(&self) -> usize {
984 self.lines.len()
985 }
986
987 #[must_use]
988 pub fn rail_prefix_width(&self, line_index: usize) -> usize {
989 self.rail_prefix_widths
990 .get(line_index)
991 .copied()
992 .unwrap_or(0)
993 }
994 }
995
996 /// Index of the last cell satisfying `is_match`.
997 ///
998 /// The previous pass already classified cells `0..unchanged` (they are
999 /// rendered at the same revisions), so only the changed suffix is searched
1000 /// and a settled transcript costs nothing. A prefix answer is reused only
1001 /// while it still names a cell inside the prefix; otherwise the prefix is
1002 /// searched too (#6652).
1003 fn newest_matching_cell<'a>(
1004 total_cells: usize,
1005 unchanged: usize,
1006 previous: Option<usize>,
1007 cell_at: &impl Fn(usize) -> &'a HistoryCell,
1008 is_match: impl Fn(&HistoryCell) -> bool,
1009 ) -> Option<usize> {
1010 let found = (unchanged..total_cells)
1011 .rev()
1012 .find(|&index| is_match(cell_at(index)))
1013 .or_else(|| match previous {
1014 None => None,
1015 Some(index) if index < unchanged => Some(index),
1016 Some(_) => (0..unchanged).rev().find(|&index| is_match(cell_at(index))),
1017 });
1018 // The shortcut above is only as good as the revision contract. Tests
1019 // prove it against the full scan; production never pays for it.
1020 #[cfg(test)]
1021 assert_eq!(
1022 found,
1023 (0..total_cells)
1024 .rev()
1025 .find(|&index| is_match(cell_at(index))),
1026 "a cell changed without its revision changing"
1027 );
1028 found
1029 }
1030
1031 /// Previous and next cells carrying the Space affordance.
1032 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1033 struct HintChange {
1034 previous: Option<usize>,
1035 next: Option<usize>,
1036 }
1037
1038 /// Earliest cell whose hint changed; rebuilds start one cell earlier.
1039 fn first_hint_cell(change: HintChange) -> usize {
1040 [change.previous, change.next]
1041 .into_iter()
1042 .flatten()
1043 .min()
1044 .unwrap_or(0)
1045 }
1046
1047 fn render_cached_cell(
1048 cell: &HistoryCell,
1049 revision: u64,
1050 width: u16,
1051 options: TranscriptRenderOptions,
1052 fold: Option<TranscriptFold>,
1053 link_resolver: Option<&mut codewhale_tui_kit::markdown_render::WorkspaceLinkResolver<'_>>,
1054 ) -> CachedCell {
1055 let is_tool_groupable = matches!(cell, HistoryCell::Tool(_));
1056 let render_width = if is_tool_groupable {
1057 width.saturating_sub(2).max(1)
1058 } else {
1059 width
1060 };
1061 let (rendered, fold_action) =
1062 cell.lines_with_copy_metadata_folded_and_links(render_width, options, fold, link_resolver);
1063 let mut lines = Vec::with_capacity(rendered.len());
1064 let mut links = Vec::with_capacity(rendered.len());
1065 let mut copy_separators = Vec::with_capacity(rendered.len());
1066 let mut copy_prefix_widths = Vec::with_capacity(rendered.len());
1067 for rendered_line in rendered {
1068 let mut line = rendered_line.line;
1069 if is_tool_groupable {
1070 strip_cell_local_tool_rail(&mut line);
1071 }
1072 lines.push(line);
1073 links.push(rendered_line.links);
1074 copy_prefix_widths.push(rendered_line.copy_prefix_width);
1075 copy_separators.push(rendered_line.copy_separator_after);
1076 }
1077 if fold_action == Some(CellFoldAction::Expand)
1078 && let Some(line) = lines.first()
1079 {
1080 let prefix = line.width().saturating_sub(compute_rail_prefix_width(line));
1081 *copy_prefix_widths
1082 .first_mut()
1083 .expect("fold affordance header") = prefix;
1084 links.first_mut().expect("fold affordance header").clear();
1085 }
1086 let is_empty = lines.is_empty();
1087 let ends_blank = last_line_is_blank(&lines);
1088 CachedCell {
1089 revision,
1090 lines: Arc::new(lines),
1091 links: Arc::new(links),
1092 copy_separators: Arc::new(copy_separators),
1093 copy_prefix_widths: Arc::new(copy_prefix_widths),
1094 is_empty,
1095 ends_blank,
1096 kind: TranscriptBlockKind::for_cell(cell),
1097 is_tool_groupable,
1098 fold_action,
1099 incremental_markdown: None,
1100 hot_tail_original: None,
1101 }
1102 }
1103
1104 /// Strip the cell-local rail because the flat cache owns cross-cell grouping;
1105 /// retaining both produces doubled prefixes such as `╭ ╭`.
1106 fn strip_cell_local_tool_rail(line: &mut Line<'static>) {
1107 if line
1108 .spans
1109 .first()
1110 .is_some_and(|span| matches!(span.content.as_ref(), "─ " | "╭ " | "│ " | "╰ "))
1111 {
1112 line.spans.remove(0);
1113 }
1114 }
1115
1116 fn last_line_is_blank(lines: &[Line<'static>]) -> bool {
1117 lines
1118 .last()
1119 .is_some_and(|line| line.spans.iter().all(|span| span.content.trim().is_empty()))
1120 }
1121
1122 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1123 struct BlockSeparator {
1124 rows: usize,
1125 railed: bool,
1126 }
1127
1128 fn separator_between(
1129 current: &CachedCell,
1130 next: &CachedCell,
1131 spacing: TranscriptSpacing,
1132 ) -> BlockSeparator {
1133 let boundary = transcript_boundary(
1134 current.kind,
1135 next.kind,
1136 same_tool_activity_group(current, next),
1137 );
1138 let mut rows = spacer_rows_for_boundary(boundary, spacing);
1139 // A cell ending blank already paid for separation; a grouped tool rail is
1140 // not blank and must remain continuous.
1141 if !current.ends_blank {
1142 return BlockSeparator {
1143 rows,
1144 railed: boundary == TranscriptBoundary::GroupedTool,
1145 };
1146 }
1147 if boundary == TranscriptBoundary::GroupedTool {
1148 return BlockSeparator { rows, railed: true };
1149 }
1150 rows = rows.saturating_sub(1);
1151 BlockSeparator {
1152 rows,
1153 railed: false,
1154 }
1155 }
1156
1157 fn same_tool_activity_group(current: &CachedCell, next: &CachedCell) -> bool {
1158 // Durable Work receipts are persisted state, not another transient tool
1159 // action; crossing that semantic seam closes the rail even at compact.
1160 current.is_tool_groupable && next.is_tool_groupable && current.kind == next.kind
1161 }
1162
1163 fn transcript_boundary(
1164 current: TranscriptBlockKind,
1165 next: TranscriptBlockKind,
1166 same_tool_group: bool,
1167 ) -> TranscriptBoundary {
1168 if same_tool_group {
1169 debug_assert_eq!(current, next);
1170 // Distinct calls sharing a rail are one compact activity group. The
1171 // rail itself carries the grouping; padding every low-level call would
1172 // recreate the density problem this boundary matrix exists to solve.
1173 return TranscriptBoundary::GroupedTool;
1174 }
1175
1176 // User cells are the only unambiguous turn delimiter. Keep prompt→tool
1177 // distinct too: a model need not emit answer prose before acting.
1178 if current == TranscriptBlockKind::User || next == TranscriptBlockKind::User {
1179 return TranscriptBoundary::Turn;
1180 }
1181
1182 if current == next
1183 && matches!(
1184 current,
1185 TranscriptBlockKind::Reasoning
1186 | TranscriptBlockKind::Answer
1187 | TranscriptBlockKind::System
1188 )
1189 {
1190 return TranscriptBoundary::Joined;
1191 }
1192
1193 // Every other phase transition is reader-visible. In particular,
1194 // reasoning running into final prose was the density bug this matrix
1195 // exists to prevent.
1196 TranscriptBoundary::Activity
1197 }
1198
1199 const fn spacer_rows_for_boundary(
1200 boundary: TranscriptBoundary,
1201 spacing: TranscriptSpacing,
1202 ) -> usize {
1203 match (boundary, spacing) {
1204 (TranscriptBoundary::Joined | TranscriptBoundary::GroupedTool, _) => 0,
1205 (TranscriptBoundary::Activity, TranscriptSpacing::Compact) => 0,
1206 (TranscriptBoundary::Activity, TranscriptSpacing::Spacious) => BLOCK_SEPARATOR_ROWS + 1,
1207 (TranscriptBoundary::Turn, TranscriptSpacing::Compact) => BLOCK_SEPARATOR_ROWS,
1208 (TranscriptBoundary::Turn, TranscriptSpacing::Spacious) => BLOCK_SEPARATOR_ROWS + 2,
1209 }
1210 }
1211
1212 fn previous_visible_cell(cells: &[CachedCell], cell_index: usize) -> Option<&CachedCell> {
1213 cells[..cell_index].iter().rev().find(|cell| !cell.is_empty)
1214 }
1215
1216 fn next_visible_cell(cells: &[CachedCell], cell_index: usize) -> Option<&CachedCell> {
1217 cells
1218 .get(cell_index + 1..)?
1219 .iter()
1220 .find(|cell| !cell.is_empty)
1221 }
1222
1223 fn tool_group_rail(
1224 cells: &[CachedCell],
1225 cell_index: usize,
1226 line_in_cell: usize,
1227 rendered_line_count: usize,
1228 ) -> Option<crate::tui::widgets::tool_card::CardRail> {
1229 let cached = cells.get(cell_index)?;
1230 if !cached.is_tool_groupable || rendered_line_count == 0 {
1231 return None;
1232 }
1233
1234 let previous_shares_group = previous_visible_cell(cells, cell_index)
1235 .is_some_and(|previous| same_tool_activity_group(previous, cached));
1236 let next_shares_group = next_visible_cell(cells, cell_index)
1237 .is_some_and(|next| same_tool_activity_group(cached, next));
1238 let first_line_in_group = !previous_shares_group && line_in_cell == 0;
1239 let last_line_in_group = !next_shares_group && line_in_cell + 1 == rendered_line_count;
1240
1241 let rail = match (first_line_in_group, last_line_in_group) {
1242 (true, true) if rendered_line_count == 1 => {
1243 crate::tui::widgets::tool_card::CardRail::Single
1244 }
1245 (true, _) => crate::tui::widgets::tool_card::CardRail::Top,
1246 (_, true) => crate::tui::widgets::tool_card::CardRail::Bottom,
1247 _ => crate::tui::widgets::tool_card::CardRail::Middle,
1248 };
1249 Some(rail)
1250 }
1251
1252 fn line_with_group_rail(
1253 line: &Line<'static>,
1254 rail: Option<crate::tui::widgets::tool_card::CardRail>,
1255 max_width: usize,
1256 ) -> Line<'static> {
1257 let Some(rail) = rail else {
1258 return line.clone();
1259 };
1260 let glyph = crate::tui::widgets::tool_card::rail_glyph(rail);
1261 if glyph.is_empty() {
1262 let mut rendered = line.clone();
1263 rendered.spans = truncate_spans_to_width(rendered.spans, max_width);
1264 return rendered;
1265 }
1266
1267 let mut rendered = line.clone();
1268 let mut spans = Vec::with_capacity(rendered.spans.len() + 1);
1269 spans.push(Span::styled(
1270 format!("{glyph} "),
1271 Style::default().fg(codewhale_palette::TEXT_DIM),
1272 ));
1273 spans.extend(rendered.spans);
1274 rendered.spans = truncate_spans_to_width(spans, max_width);
1275 rendered
1276 }
1277
1278 fn links_with_group_rail(
1279 links: &[codewhale_tui_kit::osc8::LineLink],
1280 rail: Option<crate::tui::widgets::tool_card::CardRail>,
1281 max_width: usize,
1282 ) -> Vec<codewhale_tui_kit::osc8::LineLink> {
1283 let shift = rail
1284 .map(crate::tui::widgets::tool_card::rail_glyph)
1285 .filter(|glyph| !glyph.is_empty())
1286 .map_or(0, |glyph| unicode_width::UnicodeWidthStr::width(glyph) + 1);
1287 links
1288 .iter()
1289 .map(|link| link.shifted(shift))
1290 .filter(|link| link.col_start < max_width)
1291 .map(|mut link| {
1292 link.col_end = link.col_end.min(max_width.saturating_sub(1));
1293 link
1294 })
1295 .collect()
1296 }
1297
1298 /// Return the display-column count of consecutive visual-only decorative
1299 /// spans at the start of a rendered transcript line. Iterates through
1300 /// leading spans matching either of two patterns:
1301 ///
1302 /// * Pattern A — span is `"<glyph>[<glyph>…]<space>"` where every character
1303 /// except the trailing space is a rail-drawing character (e.g. `▏ `,
1304 /// `▶ `, `⋮⋮ `). The entire span width is accumulated.
1305 /// * Pattern B — span is `"<glyph>"` (1 drawing char) followed by a lone
1306 /// space span `" "` (e.g. `●` then ` `, `▎` then ` `).
1307 ///
1308 /// Stops at the first non-matching span. Every decorated glyph used by the
1309 /// TUI is a single display-column character, so char-count = display width.
1310 ///
1311 /// Returns `0` for lines whose first span is not a decorative prefix.
1312 fn compute_rail_prefix_width(line: &Line<'static>) -> usize {
1313 let spans = line.spans.as_slice();
1314 let mut total = 0;
1315 let mut i = 0;
1316
1317 while i < spans.len() {
1318 let content = spans[i].content.as_ref();
1319 let n_chars = content.chars().count();
1320
1321 // Pattern A — span "<glyph>[<glyph>…]<space>" (≥ 2 chars, trailing
1322 // space, all preceding chars are drawing chars).
1323 if n_chars >= 2
1324 && content.ends_with(' ')
1325 && content
1326 .chars()
1327 .take(n_chars.saturating_sub(1))
1328 .all(is_rail_drawing_char)
1329 {
1330 total += n_chars;
1331 i += 1;
1332 continue;
1333 }
1334
1335 // Pattern B — span "<glyph>" (1 drawing char) + next span " ".
1336 if n_chars == 1
1337 && content.chars().next().is_some_and(is_rail_drawing_char)
1338 && spans.get(i + 1).is_some_and(|s| s.content.as_ref() == " ")
1339 {
1340 total += 2;
1341 i += 2;
1342 continue;
1343 }
1344
1345 break;
1346 }
1347
1348 total
1349 }
1350
1351 /// Characters that serve as decoration glyphs in the TUI left-rail and
1352 /// tool-header prefix system. All are single display-column characters.
1353 fn is_rail_drawing_char(ch: char) -> bool {
1354 matches!(
1355 ch,
1356 '\u{2500}'..='\u{257F}' // Box Drawing (╭ ╮ ╰ ╯ │ ╎ …)
1357 | '\u{2580}'..='\u{259F}' // Block Elements (▏ ▎ ▍ ▌ …)
1358 | '\u{25A0}'..='\u{25FF}' // Geometric Shapes (● ▶ ▷ ◆ ◐ …)
1359 | '\u{2022}' // • bullet (tool status / generic tool)
1360 | '\u{2026}' // … ellipsis (reasoning opener)
1361 | '\u{00B7}' // · middle dot (tool running symbol)
1362 | '\u{2315}' // ⌕ telephone recorder (find/search tool)
1363 | '\u{22EE}' // ⋮ vertical ellipsis (fanout/rlm tool)
1364 )
1365 }
1366
1367 fn truncate_spans_to_width(spans: Vec<Span<'static>>, max_width: usize) -> Vec<Span<'static>> {
1368 if max_width == 0 || spans.is_empty() {
1369 return Vec::new();
1370 }
1371 let current_width: usize = spans
1372 .iter()
1373 .map(|span| codewhale_tui_kit::ui_text::text_display_width(span.content.as_ref()))
1374 .sum();
1375 if current_width <= max_width {
1376 return spans;
1377 }
1378
1379 let ellipsis = if max_width > 3 { "..." } else { "" };
1380 let content_budget = max_width.saturating_sub(ellipsis.len());
1381 let mut used = 0usize;
1382 let mut truncated = Vec::with_capacity(spans.len() + usize::from(!ellipsis.is_empty()));
1383 let mut last_style = Style::default();
1384
1385 'outer: for span in spans {
1386 last_style = span.style;
1387 let mut content = String::new();
1388 for grapheme in
1389 unicode_segmentation::UnicodeSegmentation::graphemes(span.content.as_ref(), true)
1390 {
1391 let width = codewhale_tui_kit::ui_text::text_display_width(grapheme);
1392 if used + width > content_budget {
1393 if !content.is_empty() {
1394 truncated.push(Span::styled(content, span.style));
1395 }
1396 break 'outer;
1397 }
1398 content.push_str(grapheme);
1399 used += width;
1400 }
1401 if !content.is_empty() {
1402 truncated.push(Span::styled(content, span.style));
1403 }
1404 }
1405
1406 if !ellipsis.is_empty() {
1407 truncated.push(Span::styled(ellipsis.to_string(), last_style));
1408 }
1409 truncated
1410 }
1411
1412 #[cfg(test)]
1413 #[path = "transcript/tests.rs"]
1414 mod tests;
1415
1415 lines RUST