返回 CodeWhale
tests.rs
根目录 / crates / tui / src / tui / transcript / tests.rs
1 use super::*;
2 use crate::tui::history::{
3 CellFoldAction, CellFoldActionTarget, ExecCell, ExecSource, HistoryCell, PlanUpdateCell,
4 ToolCell, ToolStatus, TranscriptActionOwner, TranscriptFold,
5 };
6 use codewhale_engine::tools::plan::PlanSnapshot;
7 use codewhale_localization::Locale;
8 use codewhale_palette as palette;
9
10 impl TranscriptViewCache {
11 pub(crate) fn fold_action_target(&self) -> Option<CellFoldActionTarget> {
12 self.fold_action_target
13 }
14
15 fn streaming_lines_reflattened(&self) -> u64 {
16 self.streaming_lines_reflattened
17 }
18
19 fn streaming_meta_rows_scanned(&self) -> u64 {
20 self.streaming_meta_rows_scanned
21 }
22 }
23
24 fn plain_lines(cache: &TranscriptViewCache) -> Vec<String> {
25 cache
26 .lines()
27 .iter()
28 .map(|line| {
29 line.spans
30 .iter()
31 .map(|span| span.content.as_ref())
32 .collect::<String>()
33 })
34 .collect()
35 }
36
37 fn user_cell(content: &str) -> HistoryCell {
38 HistoryCell::User {
39 content: content.to_string(),
40 }
41 }
42
43 fn assistant_cell(content: &str, streaming: bool) -> HistoryCell {
44 HistoryCell::Assistant {
45 content: content.to_string(),
46 streaming,
47 }
48 }
49
50 fn reasoning_cell(streaming: bool) -> HistoryCell {
51 HistoryCell::Thinking {
52 content: (1..=20)
53 .map(|line| format!("reasoning line {line:02}"))
54 .collect::<Vec<_>>()
55 .join("\n"),
56 streaming,
57 duration_secs: (!streaming).then_some(1.0),
58 }
59 }
60
61 fn reasoning_owner(cell_index: usize) -> TranscriptActionOwner {
62 TranscriptActionOwner {
63 cell_index,
64 identity_epoch: 7,
65 }
66 }
67
68 #[test]
69 fn ordinary_fold_keeps_original_owner_through_filter_and_narrow_resize() {
70 let body = (1..=12)
71 .map(|line| format!("answer line {line:02}"))
72 .collect::<Vec<_>>()
73 .join("\n\n");
74 let cells = [assistant_cell(&body, false)];
75 let folds = HashMap::from([(7, TranscriptFold::Collapsed)]);
76 let owner = reasoning_owner(7);
77 let options = TranscriptRenderOptions {
78 low_motion: true,
79 ..Default::default()
80 };
81 let mut cache = TranscriptViewCache::new();
82 for width in 1..=40 {
83 cache.ensure_split(&[&cells], &[1], width, options, &folds, Some(&[7]), None);
84 let rows = cache.total_lines();
85 assert!(rows > 0);
86 assert!(cache.lines()[0].width() <= usize::from(width));
87 cache.retarget(Some(owner), Some(&[7]));
88 assert_eq!(cache.total_lines(), rows, "hint never changes geometry");
89 assert_eq!(
90 cache.fold_action_target(),
91 Some(CellFoldActionTarget {
92 owner,
93 action: CellFoldAction::Expand
94 })
95 );
96 assert!(cache.lines()[0].width() <= usize::from(width));
97 assert_eq!(
98 cache.line_meta()[0].copy_prefix_width(),
99 cache.lines()[0].width()
100 );
101 cache.retarget(Some(reasoning_owner(0)), Some(&[7]));
102 assert!(
103 cache.fold_action_target().is_none(),
104 "filtered index is not original identity"
105 );
106 }
107 }
108
109 #[test]
110 fn folded_streaming_answer_preserves_links_and_restores_latest_body() {
111 let content = format!(
112 "[reference](https://example.com/reference)\n\n{}",
113 (1..=12)
114 .map(|line| format!("paragraph {line:02}"))
115 .collect::<Vec<_>>()
116 .join("\n\n")
117 );
118 let mut cells = [assistant_cell(&content, true)];
119 let options = TranscriptRenderOptions {
120 low_motion: true,
121 ..Default::default()
122 };
123 let mut cache = TranscriptViewCache::new();
124 let owner = Some(reasoning_owner(0));
125 let mut folds = HashMap::from([(0, TranscriptFold::Collapsed)]);
126 cache.ensure_split(&[&cells], &[1], 80, options, &folds, None, owner);
127 assert!(plain_lines(&cache).join("\n").contains("Space:expand"));
128 assert!(!plain_lines(&cache).join("\n").contains("paragraph 12"));
129 assert!(cache.line_links[0].is_empty());
130 assert!(
131 cache
132 .line_links
133 .iter()
134 .skip(1)
135 .any(|links| !links.is_empty()),
136 "preview body retains its link"
137 );
138 let before = (cache.cells_rendered, cache.streaming_lines_reflattened());
139 cache.ensure_split(&[&cells], &[1], 80, options, &folds, None, owner);
140 assert_eq!(
141 (cache.cells_rendered, cache.streaming_lines_reflattened()),
142 before,
143 "settled folded frame does no work"
144 );
145
146 let HistoryCell::Assistant { content, .. } = &mut cells[0] else {
147 unreachable!()
148 };
149 content.push_str("\n\nlatest streamed paragraph");
150 cache.ensure_split(&[&cells], &[2], 80, options, &folds, None, owner);
151 assert!(
152 !plain_lines(&cache)
153 .join("\n")
154 .contains("latest streamed paragraph")
155 );
156 assert_eq!(
157 cache.fold_action_target().unwrap().action,
158 CellFoldAction::Expand
159 );
160 folds.insert(0, TranscriptFold::Expanded);
161 cache.ensure_split(&[&cells], &[2], 80, options, &folds, None, owner);
162 assert!(
163 plain_lines(&cache)
164 .join("\n")
165 .contains("latest streamed paragraph")
166 );
167 let mut cold = TranscriptViewCache::new();
168 cold.ensure_split(&[&cells], &[2], 80, options, &folds, None, owner);
169 assert_same_flat_output(&cache, &cold);
170
171 let HistoryCell::Assistant { content, .. } = &mut cells[0] else {
172 unreachable!()
173 };
174 content.push_str("\n\ncontinued after unfolding");
175 cache.ensure_split(&[&cells], &[3], 80, options, &folds, None, owner);
176 let mut cold = TranscriptViewCache::new();
177 cold.ensure_split(&[&cells], &[3], 80, options, &folds, None, owner);
178 assert_same_flat_output(&cache, &cold);
179 assert!(
180 plain_lines(&cache)
181 .join("\n")
182 .contains("continued after unfolding")
183 );
184 }
185
186 fn exec_tool_cell_with_output(command: &str, output: String) -> HistoryCell {
187 // A failed shell cell keeps its full output in the live render, so
188 // this fixture proves tool cells do not inherit the prose measure.
189 HistoryCell::Tool(ToolCell::Exec(ExecCell {
190 command: command.to_string(),
191 status: ToolStatus::Failed,
192 output: Some(output),
193 live_output: None,
194 shell_task_id: None,
195 owner_agent_id: None,
196 owner_agent_name: None,
197 started_at: None,
198 duration_ms: None,
199 stale_elapsed_since_output_ms: None,
200 waiting: None,
201 source: ExecSource::Assistant,
202 description: None,
203 interaction: None,
204 output_summary: None,
205 }))
206 }
207
208 fn exec_tool_cell(command: &str) -> HistoryCell {
209 HistoryCell::Tool(ToolCell::Exec(ExecCell {
210 command: command.to_string(),
211 status: ToolStatus::Running,
212 output: None,
213 live_output: None,
214 shell_task_id: None,
215 owner_agent_id: None,
216 owner_agent_name: None,
217 started_at: None,
218 duration_ms: None,
219 stale_elapsed_since_output_ms: None,
220 waiting: None,
221 source: ExecSource::Assistant,
222 description: None,
223 interaction: None,
224 output_summary: None,
225 }))
226 }
227
228 fn durable_work_cell() -> HistoryCell {
229 HistoryCell::Tool(ToolCell::PlanUpdate(PlanUpdateCell {
230 snapshot: PlanSnapshot::default(),
231 status: ToolStatus::Running,
232 }))
233 }
234
235 fn spacer_rows_after_cell(cache: &TranscriptViewCache, target_cell: usize) -> usize {
236 let mut saw_target = false;
237 let mut spacer_rows = 0;
238 for meta in cache.line_meta() {
239 match meta {
240 TranscriptLineMeta::CellLine { cell_index, .. } if *cell_index == target_cell => {
241 saw_target = true;
242 spacer_rows = 0;
243 }
244 TranscriptLineMeta::Spacer { .. } if saw_target => spacer_rows += 1,
245 TranscriptLineMeta::CellLine { .. } if saw_target => break,
246 TranscriptLineMeta::Spacer { .. } | TranscriptLineMeta::CellLine { .. } => {}
247 }
248 }
249 spacer_rows
250 }
251
252 #[test]
253 fn cache_highlights_only_the_newest_user_turn() {
254 let cells = vec![
255 user_cell("first prompt"),
256 assistant_cell("first answer", false),
257 user_cell("second prompt"),
258 ];
259 let revisions = vec![1u64, 1, 1];
260
261 let mut cache = TranscriptViewCache::new();
262 cache.ensure(&cells, &revisions, 40, TranscriptRenderOptions::default());
263
264 let texts = plain_lines(&cache);
265 let first = texts
266 .iter()
267 .position(|line| line.contains("first prompt"))
268 .expect("first prompt renders");
269 let second = texts
270 .iter()
271 .position(|line| line.contains("second prompt"))
272 .expect("second prompt renders");
273 let lines = cache.lines();
274 assert_eq!(
275 lines[first].style.bg, None,
276 "an older prompt renders on the bare ground"
277 );
278 assert!(
279 lines[first]
280 .spans
281 .iter()
282 .all(|span| span.style.bg.is_none()),
283 "an older prompt paints no background block"
284 );
285 assert_eq!(
286 lines[second].style.bg,
287 Some(palette::SURFACE_ELEVATED),
288 "only the newest prompt carries the background"
289 );
290 assert_eq!(lines[second].width(), 40);
291 }
292
293 #[test]
294 fn cache_unhighlights_the_previous_prompt_when_a_new_one_lands() {
295 let first = vec![user_cell("first prompt")];
296 let revisions = vec![1u64];
297
298 let mut cache = TranscriptViewCache::new();
299 cache.ensure(&first, &revisions, 40, TranscriptRenderOptions::default());
300 assert_eq!(
301 cache.lines()[0].style.bg,
302 Some(palette::SURFACE_ELEVATED),
303 "a lone prompt is the newest turn"
304 );
305
306 // The first cell's own revision never moves; supersession alone must
307 // re-render it without the block.
308 let both = vec![user_cell("first prompt"), user_cell("second prompt")];
309 let revisions = vec![1u64, 1];
310 cache.ensure(&both, &revisions, 40, TranscriptRenderOptions::default());
311 let lines = cache.lines();
312 assert_eq!(
313 lines[0].style.bg, None,
314 "the previous newest loses the background"
315 );
316 let texts = plain_lines(&cache);
317 let second = texts
318 .iter()
319 .position(|line| line.contains("second prompt"))
320 .expect("second prompt renders");
321 assert_eq!(lines[second].style.bg, Some(palette::SURFACE_ELEVATED));
322 }
323
324 #[test]
325 fn cache_reuses_cells_when_revision_unchanged() {
326 let cells = vec![
327 user_cell("hello"),
328 assistant_cell("world", false),
329 user_cell("again"),
330 ];
331 let revisions = vec![1u64, 1, 1];
332
333 let mut cache = TranscriptViewCache::new();
334 cache.ensure(&cells, &revisions, 80, TranscriptRenderOptions::default());
335 let first_lines: Vec<String> = cache
336 .lines()
337 .iter()
338 .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
339 .collect();
340 let first_total = cache.total_lines();
341 assert!(first_total > 0, "expected non-empty render");
342
343 // Capture per-cell lines snapshot to verify reuse.
344 let snapshot_per_cell: Vec<Vec<String>> = cache
345 .per_cell
346 .iter()
347 .map(|c| {
348 c.lines
349 .iter()
350 .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
351 .collect()
352 })
353 .collect();
354
355 // Same revisions => everything reused, output identical.
356 cache.ensure(&cells, &revisions, 80, TranscriptRenderOptions::default());
357 let second_lines: Vec<String> = cache
358 .lines()
359 .iter()
360 .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
361 .collect();
362 assert_eq!(first_lines, second_lines);
363 assert_eq!(cache.total_lines(), first_total);
364
365 let snapshot_per_cell_2: Vec<Vec<String>> = cache
366 .per_cell
367 .iter()
368 .map(|c| {
369 c.lines
370 .iter()
371 .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
372 .collect()
373 })
374 .collect();
375 assert_eq!(snapshot_per_cell, snapshot_per_cell_2);
376 }
377
378 #[test]
379 fn bumping_one_cell_revision_only_rerenders_that_cell() {
380 // Track render counts per cell using a custom HistoryCell wrapper
381 // would require trait changes; instead, we detect reuse by inspecting
382 // CachedCell instances. After a bump, only the bumped cell's stored
383 // revision should differ from before; others remain identical.
384
385 let cells_v1 = vec![
386 user_cell("hello"),
387 assistant_cell("hi", true),
388 user_cell("again"),
389 ];
390 let revs_v1 = vec![1u64, 1, 1];
391
392 let mut cache = TranscriptViewCache::new();
393 cache.ensure(&cells_v1, &revs_v1, 80, TranscriptRenderOptions::default());
394
395 // Snapshot the cached lines for cells 0 and 2 (unchanged across the
396 // delta).
397 let cell0_lines_before = cache.per_cell[0]
398 .lines
399 .iter()
400 .map(|l| {
401 l.spans
402 .iter()
403 .map(|s| s.content.to_string())
404 .collect::<String>()
405 })
406 .collect::<Vec<_>>();
407 let cell2_lines_before = cache.per_cell[2]
408 .lines
409 .iter()
410 .map(|l| {
411 l.spans
412 .iter()
413 .map(|s| s.content.to_string())
414 .collect::<String>()
415 })
416 .collect::<Vec<_>>();
417
418 // Mutate cell 1 (assistant streaming delta) and bump only its rev.
419 let cells_v2 = vec![
420 user_cell("hello"),
421 assistant_cell("hi world", true),
422 user_cell("again"),
423 ];
424 let revs_v2 = vec![1u64, 2, 1];
425
426 cache.ensure(&cells_v2, &revs_v2, 80, TranscriptRenderOptions::default());
427
428 // Cells 0 and 2 are byte-identical (proving reuse path didn't corrupt).
429 let cell0_lines_after = cache.per_cell[0]
430 .lines
431 .iter()
432 .map(|l| {
433 l.spans
434 .iter()
435 .map(|s| s.content.to_string())
436 .collect::<String>()
437 })
438 .collect::<Vec<_>>();
439 let cell2_lines_after = cache.per_cell[2]
440 .lines
441 .iter()
442 .map(|l| {
443 l.spans
444 .iter()
445 .map(|s| s.content.to_string())
446 .collect::<String>()
447 })
448 .collect::<Vec<_>>();
449 assert_eq!(cell0_lines_before, cell0_lines_after);
450 assert_eq!(cell2_lines_before, cell2_lines_after);
451
452 // Cell 1 reflects the new content.
453 // The renderer interleaves role/whitespace spans, so the joined
454 // content has internal padding (e.g. "Assistant hi world").
455 // Check for the new tokens individually rather than a literal
456 // "hi world" substring.
457 let cell1_after: String = cache.per_cell[1]
458 .lines
459 .iter()
460 .flat_map(|l| l.spans.iter().map(|s| s.content.to_string()))
461 .collect::<Vec<_>>()
462 .join(" ");
463 assert!(
464 cell1_after.contains("hi") && cell1_after.contains("world"),
465 "cell1 should re-render with new content; got: {cell1_after}"
466 );
467
468 // Revisions in cache reflect the bump.
469 assert_eq!(cache.per_cell[0].revision, 1);
470 assert_eq!(cache.per_cell[1].revision, 2);
471 assert_eq!(cache.per_cell[2].revision, 1);
472 }
473
474 #[test]
475 fn streaming_assistant_keeps_a_persistent_linear_render_prefix() {
476 let mut content = String::new();
477 let mut revision = 1u64;
478 let mut cache = TranscriptViewCache::new();
479 let options = TranscriptRenderOptions {
480 low_motion: true,
481 ..TranscriptRenderOptions::default()
482 };
483
484 content.push_str("start\n```rust\nlet value_0 = 0;\n```\n\n");
485 let mut cells = vec![assistant_cell(&content, true)];
486 cache.ensure(&cells, &[revision], 96, options);
487 let lines_arc = Arc::as_ptr(&cache.per_cell[0].lines);
488
489 for index in 1..120usize {
490 let previous = revision;
491 revision += 1;
492 content.push_str(&format!(
493 "段落 {index} e\u{301} 🚀\n```rust\nlet value_{index} = {index};\n```\n\n"
494 ));
495 cells[0] = assistant_cell(&content, true);
496 cache.set_streaming_source_receipt(Some(StreamingSourceReceipt {
497 cell_index: 0,
498 from_revision: previous,
499 to_revision: revision,
500 content_len: content.len(),
501 }));
502 cache.ensure(&cells, &[revision], 96, options);
503 }
504
505 let previous = revision;
506 revision += 1;
507 cache.set_streaming_source_receipt(Some(StreamingSourceReceipt {
508 cell_index: 0,
509 from_revision: previous,
510 to_revision: revision,
511 content_len: content.len(),
512 }));
513 cache.ensure(&cells, &[revision], 96, options);
514
515 assert_eq!(Arc::as_ptr(&cache.per_cell[0].lines), lines_arc);
516 let work = cache.per_cell[0]
517 .incremental_markdown
518 .as_ref()
519 .expect("streaming markdown cache")
520 .work();
521 assert_eq!(work.invalidations, 1);
522 assert_eq!(work.tail_blocks_rendered, 0);
523 assert_eq!(work.classified_lines as usize, content.lines().count());
524 assert!(
525 cache.streaming_lines_reflattened() <= (cache.total_lines() + 121) as u64,
526 "flatten work must be final output plus at most one hot-tail line per update: work={}, final={}",
527 cache.streaming_lines_reflattened(),
528 cache.total_lines()
529 );
530 assert!(
531 cache.streaming_meta_rows_scanned() <= 121,
532 "reverse lookup must inspect only the replaceable tail: {}",
533 cache.streaming_meta_rows_scanned()
534 );
535
536 let mut cold = TranscriptViewCache::new();
537 cold.ensure(&cells, &[revision], 96, options);
538 assert_eq!(plain_lines(&cache), plain_lines(&cold));
539 }
540
541 #[test]
542 fn tail_update_suffix_rebuild_matches_fresh_flatten() {
543 let mut cells = vec![
544 user_cell("first message"),
545 assistant_cell("stable answer", false),
546 user_cell("tail prompt"),
547 ];
548 let mut revisions = vec![1u64, 1, 1];
549 let mut cache = TranscriptViewCache::new();
550 cache.ensure(&cells, &revisions, 40, TranscriptRenderOptions::default());
551
552 cells.push(assistant_cell("streaming tail", true));
553 revisions.push(1);
554 cache.ensure(&cells, &revisions, 40, TranscriptRenderOptions::default());
555
556 if let HistoryCell::Assistant { content, .. } = cells.last_mut().unwrap() {
557 content.push_str(" plus delta");
558 }
559 *revisions.last_mut().unwrap() += 1;
560 cache.ensure(&cells, &revisions, 40, TranscriptRenderOptions::default());
561 let incremental = plain_lines(&cache);
562
563 let mut fresh = TranscriptViewCache::new();
564 fresh.ensure(&cells, &revisions, 40, TranscriptRenderOptions::default());
565 assert_eq!(incremental, plain_lines(&fresh));
566 }
567
568 #[test]
569 fn width_change_rerenders_all_cells() {
570 let cells = vec![
571 user_cell("a fairly long message that may wrap at narrow widths"),
572 assistant_cell("another long message body content", false),
573 ];
574 let revisions = vec![5u64, 7];
575
576 let mut cache = TranscriptViewCache::new();
577 cache.ensure(&cells, &revisions, 80, TranscriptRenderOptions::default());
578 let wide_total = cache.total_lines();
579
580 // Narrow width should change layout — everything re-renders.
581 cache.ensure(&cells, &revisions, 20, TranscriptRenderOptions::default());
582 let narrow_total = cache.total_lines();
583
584 assert_ne!(
585 wide_total, narrow_total,
586 "narrow width should produce a different number of lines"
587 );
588
589 // Restoring the original width re-renders again.
590 cache.ensure(&cells, &revisions, 80, TranscriptRenderOptions::default());
591 assert_eq!(cache.total_lines(), wide_total);
592 }
593
594 #[test]
595 fn streaming_assistant_only_rebuilds_one_cell_render_count() {
596 // Verify behavior 6: when one Assistant cell streams a delta, only
597 // that one cell is re-rendered. We use a counting wrapper hooked into
598 // a custom History setup. Since `lines_with_options` is on `HistoryCell`
599 // (concrete enum), we can't mock it directly. Instead we verify the
600 // cache's invariant: cells with unchanged revisions retain their
601 // previous CachedCell entries (clone-equal), proving no re-render
602 // happened for them.
603 //
604 // We do this by storing revisions as monotonic u64 and verifying that
605 // a `Vec<u64>` snapshot of `per_cell.revision` only differs at the
606 // index that was bumped.
607
608 let mut cells: Vec<HistoryCell> = (0..50).map(|i| user_cell(&format!("cell {i}"))).collect();
609 cells.push(assistant_cell("streaming", true));
610 let mut revisions: Vec<u64> = vec![1; 51];
611
612 let mut cache = TranscriptViewCache::new();
613 cache.ensure(&cells, &revisions, 80, TranscriptRenderOptions::default());
614
615 // Snapshot total bytes rendered for cells 0..50 (unchanged).
616 let stable_snapshot: Vec<String> = cache.per_cell[..50]
617 .iter()
618 .map(|c| {
619 c.lines
620 .iter()
621 .flat_map(|l| l.spans.iter().map(|s| s.content.to_string()))
622 .collect::<Vec<_>>()
623 .join("|")
624 })
625 .collect();
626
627 // Stream 10 deltas to the assistant cell, bumping only its revision.
628 for i in 0..10 {
629 if let HistoryCell::Assistant { content, .. } = &mut cells[50] {
630 content.push_str(&format!(" delta-{i}"));
631 }
632 revisions[50] += 1;
633 cache.ensure(&cells, &revisions, 80, TranscriptRenderOptions::default());
634
635 // After every delta, cells 0..50 must be byte-identical to the
636 // initial render. If we re-rendered them we'd observe identical
637 // bytes anyway (deterministic), but the test ALSO checks the
638 // CachedCell.revision values stayed at 1 — meaning the cache
639 // never replaced them, only reused them.
640 let stable_now: Vec<String> = cache.per_cell[..50]
641 .iter()
642 .map(|c| {
643 c.lines
644 .iter()
645 .flat_map(|l| l.spans.iter().map(|s| s.content.to_string()))
646 .collect::<Vec<_>>()
647 .join("|")
648 })
649 .collect();
650 assert_eq!(
651 stable_now, stable_snapshot,
652 "stable cells diverged at delta {i}"
653 );
654
655 for (idx, c) in cache.per_cell[..50].iter().enumerate() {
656 assert_eq!(
657 c.revision, 1,
658 "cell {idx} revision changed during streaming delta"
659 );
660 }
661 }
662 }
663
664 #[test]
665 fn missing_revisions_falls_back_to_full_render() {
666 // If callers pass a `cell_revisions` slice with the wrong length
667 // (shouldn't happen, but be defensive), the cache should still
668 // produce correct output rather than panic or skip cells.
669 let cells = vec![user_cell("a"), assistant_cell("b", false)];
670 let bogus_revisions = vec![1u64]; // wrong length
671
672 let mut cache = TranscriptViewCache::new();
673 cache.ensure(
674 &cells,
675 &bogus_revisions,
676 80,
677 TranscriptRenderOptions::default(),
678 );
679
680 // Both cells were rendered (no panic, output non-empty).
681 assert_eq!(cache.per_cell.len(), 2);
682 assert!(!cache.lines().is_empty());
683 }
684
685 #[test]
686 fn adjacent_tool_cells_render_as_one_railed_group() {
687 // Live foreground exec cells collapse to a single header line (copy
688 // dedupe #17), so a third cell is needed for a rail-continuation row.
689 let cells = vec![
690 exec_tool_cell("cargo test"),
691 exec_tool_cell("cargo clippy"),
692 exec_tool_cell("cargo fmt"),
693 ];
694 let revisions = vec![1u64, 1, 1];
695 let mut cache = TranscriptViewCache::new();
696
697 cache.ensure(&cells, &revisions, 80, TranscriptRenderOptions::default());
698 let lines = plain_lines(&cache);
699
700 assert!(
701 lines
702 .first()
703 .is_some_and(|line| line.starts_with("\u{256D} ")),
704 "first tool line should open the shared rail: {lines:?}"
705 );
706 assert!(
707 lines.iter().any(|line| line.starts_with("\u{2502} ")),
708 "middle tool lines should continue the shared rail: {lines:?}"
709 );
710 assert!(
711 lines
712 .last()
713 .is_some_and(|line| line.starts_with("\u{2570} ")),
714 "last tool line should close the shared rail: {lines:?}"
715 );
716 assert!(
717 !lines.iter().any(String::is_empty),
718 "adjacent tool cells must never be separated by a bare blank row — that \
719 would tear the card box open: {lines:?}"
720 );
721 assert!(
722 !lines.iter().any(|line| line.trim_end() == "\u{2502}"),
723 "one tool group must stay compact instead of padding every call: {lines:?}"
724 );
725 assert_eq!(spacer_rows_after_cell(&cache, 0), 0);
726 assert_eq!(spacer_rows_after_cell(&cache, 1), 0);
727 }
728
729 #[test]
730 fn semantic_boundary_matrix_has_four_deliberate_rhythm_levels() {
731 use TranscriptBlockKind::{Answer, DurableWork, Notice, Reasoning, ToolAction, User};
732 use TranscriptBoundary::{Activity, GroupedTool, Joined, Turn};
733
734 let cases = [
735 (User, Answer, false, Turn),
736 (User, ToolAction, false, Turn),
737 (DurableWork, User, false, Turn),
738 // Reasoning handing off to the answer is a phase change the reader
739 // has to see. Running the two together with no blank row is the
740 // density complaint this matrix exists to answer.
741 (Reasoning, Answer, false, Activity),
742 (Answer, Reasoning, false, Activity),
743 // Successive cells of the *same* phase are one block split across
744 // cells; a blank row there would jitter mid-stream.
745 (Answer, Answer, false, Joined),
746 (Reasoning, Reasoning, false, Joined),
747 (Answer, ToolAction, false, Activity),
748 (ToolAction, Reasoning, false, Activity),
749 (Notice, DurableWork, false, Activity),
750 (ToolAction, ToolAction, true, GroupedTool),
751 (DurableWork, DurableWork, true, GroupedTool),
752 (ToolAction, DurableWork, false, Activity),
753 ];
754
755 for (current, next, grouped_tools, expected) in cases {
756 assert_eq!(
757 transcript_boundary(current, next, grouped_tools),
758 expected,
759 "{current:?} -> {next:?}"
760 );
761 }
762
763 assert_eq!(
764 spacer_rows_for_boundary(Turn, TranscriptSpacing::Compact),
765 1
766 );
767 assert_eq!(
768 spacer_rows_for_boundary(Turn, TranscriptSpacing::Spacious),
769 3
770 );
771 assert_eq!(
772 spacer_rows_for_boundary(Activity, TranscriptSpacing::Compact),
773 0
774 );
775 assert_eq!(
776 spacer_rows_for_boundary(Activity, TranscriptSpacing::Spacious),
777 2
778 );
779 assert_eq!(
780 spacer_rows_for_boundary(GroupedTool, TranscriptSpacing::Compact),
781 0,
782 "compact density buys its density by spending no separator rows"
783 );
784 assert_eq!(
785 spacer_rows_for_boundary(GroupedTool, TranscriptSpacing::Spacious),
786 0,
787 "even spacious mode breathes around the group, not inside it"
788 );
789 }
790
791 /// Compact never spends a double blank, because a scrolling terminal cannot
792 /// afford it. Spacious buys its air at turn and activity seams by design.
793 #[test]
794 fn compact_never_spends_more_than_one_row_at_any_boundary() {
795 use TranscriptBoundary::{Activity, GroupedTool, Joined, Turn};
796
797 for boundary in [Joined, GroupedTool, Activity, Turn] {
798 let rows = spacer_rows_for_boundary(boundary, TranscriptSpacing::Compact);
799 assert!(
800 rows <= BLOCK_SEPARATOR_ROWS,
801 "{boundary:?} at compact spent {rows} rows"
802 );
803 }
804 }
805
806 #[test]
807 fn durable_work_tools_have_an_explicit_semantic_role() {
808 let plan = durable_work_cell();
809 let tool = exec_tool_cell("cargo test --locked");
810
811 assert_eq!(
812 TranscriptBlockKind::for_cell(&plan),
813 TranscriptBlockKind::DurableWork
814 );
815 assert_eq!(
816 TranscriptBlockKind::for_cell(&tool),
817 TranscriptBlockKind::ToolAction
818 );
819 }
820
821 #[test]
822 fn durable_work_starts_a_new_activity_rail_without_wasting_compact_rows() {
823 let durable = HistoryCell::Tool(ToolCell::PlanUpdate(PlanUpdateCell {
824 snapshot: PlanSnapshot {
825 objective: Some("Keep the release receipt durable".to_string()),
826 ..PlanSnapshot::default()
827 },
828 status: ToolStatus::Running,
829 }));
830 let cells = vec![
831 exec_tool_cell("cargo test --locked"),
832 exec_tool_cell("cargo clippy --locked"),
833 durable,
834 ];
835 let revisions = vec![1u64; cells.len()];
836
837 let mut compact = TranscriptViewCache::new();
838 compact.ensure(
839 &cells,
840 &revisions,
841 80,
842 TranscriptRenderOptions {
843 spacing: TranscriptSpacing::Compact,
844 low_motion: true,
845 ..TranscriptRenderOptions::default()
846 },
847 );
848
849 assert_eq!(spacer_rows_after_cell(&compact, 0), 0);
850 assert_eq!(spacer_rows_after_cell(&compact, 1), 0);
851 let compact_lines = plain_lines(&compact);
852 assert!(
853 !compact_lines.iter().any(String::is_empty),
854 "compact activity seams must not spend a blank row: {compact_lines:?}"
855 );
856 let lines_for_cell = |target| {
857 compact
858 .lines()
859 .iter()
860 .zip(compact.line_meta())
861 .filter_map(|(line, meta)| match meta {
862 TranscriptLineMeta::CellLine { cell_index, .. } if *cell_index == target => Some(
863 line.spans
864 .iter()
865 .map(|span| span.content.as_ref())
866 .collect::<String>(),
867 ),
868 TranscriptLineMeta::Spacer { .. } | TranscriptLineMeta::CellLine { .. } => None,
869 })
870 .collect::<Vec<_>>()
871 };
872 let second_action = lines_for_cell(1);
873 let durable_work = lines_for_cell(2);
874 assert!(
875 second_action
876 .last()
877 .is_some_and(|line| line.starts_with("\u{2570} ")),
878 "ordinary action rail should close before durable Work: {second_action:?}"
879 );
880 assert!(
881 durable_work
882 .first()
883 .is_some_and(|line| line.starts_with("\u{256D} ")),
884 "durable Work should open its own rail: {durable_work:?}"
885 );
886
887 let mut spacious = TranscriptViewCache::new();
888 spacious.ensure(
889 &cells,
890 &revisions,
891 80,
892 TranscriptRenderOptions {
893 spacing: TranscriptSpacing::Spacious,
894 low_motion: true,
895 ..TranscriptRenderOptions::default()
896 },
897 );
898 assert_eq!(
899 spacer_rows_after_cell(&spacious, 0),
900 0,
901 "two commands inside one activity rail must remain compact"
902 );
903 assert_eq!(
904 spacer_rows_after_cell(&spacious, 1),
905 2,
906 "durable Work needs a semantic activity break outside compact density"
907 );
908 }
909
910 #[test]
911 fn consecutive_system_notes_stay_readable_without_separating_each_event() {
912 let notes = [
913 "Permissions changed to Read only.",
914 "Provider switched to OpenAI.",
915 "Permissions changed to Ask.",
916 ];
917 let mut cells: Vec<_> = notes
918 .iter()
919 .map(|note| HistoryCell::System {
920 content: (*note).into(),
921 })
922 .collect();
923 cells.push(HistoryCell::Error {
924 message: "Approval required to continue.".into(),
925 severity: codewhale_error_taxonomy::ErrorSeverity::Warning,
926 code: None,
927 });
928 cells.push(user_cell("Proceed"));
929 for width in [42, 106] {
930 let mut cache = TranscriptViewCache::new();
931 cache.ensure(
932 &cells,
933 &[1; 5],
934 width,
935 TranscriptRenderOptions {
936 spacing: TranscriptSpacing::Spacious,
937 ..Default::default()
938 },
939 );
940 assert_eq!(spacer_rows_after_cell(&cache, 0), 0);
941 assert_eq!(spacer_rows_after_cell(&cache, 1), 0);
942 assert!(spacer_rows_after_cell(&cache, 2) > 0);
943 assert!(spacer_rows_after_cell(&cache, 3) > 0);
944 for (index, &note) in notes.iter().enumerate() {
945 let row = cache.line_meta().iter().position(|meta| {
946 matches!(meta, TranscriptLineMeta::CellLine { cell_index, .. } if *cell_index == index)
947 }).expect("each note keeps its own source row");
948 let line = &cache.lines()[row];
949 assert!(line.to_string().contains(note));
950 assert!(line.spans.iter().all(|span| {
951 !span
952 .style
953 .add_modifier
954 .contains(ratatui::style::Modifier::ITALIC)
955 }));
956 }
957 let text = plain_lines(&cache).join("\n");
958 assert!(text.contains("Approval required to continue."));
959 assert!(text.contains("Proceed"));
960 }
961 }
962
963 #[test]
964 fn compact_spacing_keeps_conversation_blocks_separate() {
965 let cells = vec![
966 user_cell("Please verify the release."),
967 assistant_cell("I will check the receipts.", false),
968 ];
969 let revisions = vec![1u64, 1];
970 let mut cache = TranscriptViewCache::new();
971 let options = TranscriptRenderOptions {
972 spacing: TranscriptSpacing::Compact,
973 ..TranscriptRenderOptions::default()
974 };
975
976 cache.ensure(&cells, &revisions, 89, options);
977 let lines = plain_lines(&cache);
978
979 assert!(
980 lines.iter().any(String::is_empty),
981 "compact density still needs one user/assistant boundary: {lines:?}"
982 );
983 }
984
985 #[test]
986 fn compact_spacing_keeps_direct_user_tool_turns_separate() {
987 let cells = vec![
988 user_cell("Inspect the repository."),
989 exec_tool_cell("git status --short"),
990 user_cell("Now summarize the result."),
991 ];
992 let revisions = vec![1u64, 1, 1];
993 let options = TranscriptRenderOptions {
994 spacing: TranscriptSpacing::Compact,
995 low_motion: true,
996 ..TranscriptRenderOptions::default()
997 };
998 let mut cache = TranscriptViewCache::new();
999
1000 cache.ensure(&cells, &revisions, 80, options);
1001
1002 assert_eq!(spacer_rows_after_cell(&cache, 0), 1);
1003 assert_eq!(spacer_rows_after_cell(&cache, 1), 1);
1004 }
1005
1006 #[test]
1007 fn compact_spacing_keeps_reasoning_and_answer_in_one_response_block() {
1008 let cells = vec![
1009 HistoryCell::Thinking {
1010 content: "I should verify the release receipts first.".to_string(),
1011 streaming: false,
1012 duration_secs: Some(0.4),
1013 },
1014 assistant_cell("The release receipts are green.", false),
1015 ];
1016 let revisions = vec![1u64, 1];
1017 let mut cache = TranscriptViewCache::new();
1018 let options = TranscriptRenderOptions {
1019 spacing: TranscriptSpacing::Compact,
1020 ..TranscriptRenderOptions::default()
1021 };
1022
1023 cache.ensure(&cells, &revisions, 89, options);
1024 let lines = plain_lines(&cache);
1025
1026 assert!(
1027 !lines.iter().any(String::is_empty),
1028 "reasoning and its answer should read as one response block: {lines:?}"
1029 );
1030 }
1031
1032 #[test]
1033 fn hidden_reasoning_keeps_visible_rhythm_without_phantom_tail_rows() {
1034 let cells = vec![
1035 user_cell("Verify the release."),
1036 HistoryCell::Thinking {
1037 content: "Check the exact receipts.".to_string(),
1038 streaming: false,
1039 duration_secs: Some(0.4),
1040 },
1041 assistant_cell("The receipts are green.", false),
1042 ];
1043 let revisions = vec![1u64, 1, 1];
1044 let hidden = TranscriptRenderOptions {
1045 show_thinking: false,
1046 low_motion: true,
1047 ..TranscriptRenderOptions::default()
1048 };
1049 let mut cache = TranscriptViewCache::new();
1050
1051 cache.ensure(&cells, &revisions, 80, hidden);
1052 let hidden_lines = plain_lines(&cache);
1053 assert_eq!(spacer_rows_after_cell(&cache, 0), 3);
1054 assert!(
1055 hidden_lines.last().is_some_and(|line| !line.is_empty()),
1056 "hidden cells must not leave a trailing blank row: {hidden_lines:?}"
1057 );
1058
1059 let visible = TranscriptRenderOptions {
1060 show_thinking: true,
1061 ..hidden
1062 };
1063 cache.ensure(&cells, &revisions, 80, visible);
1064 cache.ensure(&cells, &revisions, 80, hidden);
1065 assert_eq!(plain_lines(&cache), hidden_lines);
1066
1067 let trailing_hidden = &cells[..2];
1068 let mut tail_cache = TranscriptViewCache::new();
1069 tail_cache.ensure(trailing_hidden, &revisions[..2], 80, hidden);
1070 assert!(
1071 plain_lines(&tail_cache)
1072 .last()
1073 .is_some_and(|line| !line.is_empty()),
1074 "a hidden final cell must not reserve a phantom spacer"
1075 );
1076 }
1077
1078 #[test]
1079 fn hidden_reasoning_cache_never_advertises_or_leaks_content() {
1080 for streaming in [false, true] {
1081 let cells = [reasoning_cell(streaming)];
1082 let mut cache = TranscriptViewCache::new();
1083 cache.ensure_split(
1084 &[&cells],
1085 &[1],
1086 80,
1087 TranscriptRenderOptions {
1088 show_thinking: false,
1089 ..TranscriptRenderOptions::default()
1090 },
1091 &HashMap::new(),
1092 None,
1093 Some(reasoning_owner(0)),
1094 );
1095 let text = plain_lines(&cache).join("\n");
1096 assert_eq!(cache.fold_action_target(), None);
1097 assert!(
1098 !text.contains("reasoning line"),
1099 "hidden body leaked: {text}"
1100 );
1101 assert!(!text.contains("Space:"), "hidden hint leaked: {text}");
1102 assert_eq!(text.contains("Thinking…"), streaming);
1103 }
1104 }
1105
1106 #[test]
1107 fn transcript_rhythm_is_width_and_reduced_motion_invariant() {
1108 let cells = vec![
1109 user_cell("Please inspect the release candidate and verify all receipts."),
1110 HistoryCell::Thinking {
1111 content: "I will inspect the source, run the checks, and compare the receipts."
1112 .to_string(),
1113 streaming: true,
1114 duration_secs: Some(0.8),
1115 },
1116 assistant_cell("I will start with the locked test suite.", false),
1117 exec_tool_cell("cargo test -p codewhale-tui --bins --locked"),
1118 durable_work_cell(),
1119 assistant_cell("The focused checks passed.", false),
1120 user_cell("Proceed to the final verification."),
1121 ];
1122 let revisions = vec![1u64; cells.len()];
1123 // user | reasoning | answer | tool | work | answer | user.
1124 // Turn seams breathe widest; activity seams are the interior of one turn.
1125 let expected_compact = [1, 0, 0, 0, 0, 1, 0];
1126 let expected_spacious = [3, 2, 2, 2, 2, 3, 0];
1127
1128 for width in [40, 80, 100, 140] {
1129 for low_motion in [false, true] {
1130 for (spacing, expected) in [
1131 (TranscriptSpacing::Compact, expected_compact),
1132 (TranscriptSpacing::Spacious, expected_spacious),
1133 ] {
1134 let options = TranscriptRenderOptions {
1135 low_motion,
1136 spacing,
1137 ..TranscriptRenderOptions::default()
1138 };
1139 let mut cache = TranscriptViewCache::new();
1140 cache.ensure(&cells, &revisions, width, options);
1141
1142 let actual =
1143 std::array::from_fn::<_, 7, _>(|index| spacer_rows_after_cell(&cache, index));
1144 assert_eq!(
1145 actual, expected,
1146 "width={width} low_motion={low_motion} spacing={spacing:?}"
1147 );
1148 assert!(
1149 cache
1150 .lines()
1151 .iter()
1152 .all(|line| line.width() <= usize::from(width)),
1153 "render exceeded width={width} low_motion={low_motion}"
1154 );
1155 }
1156 }
1157 }
1158 }
1159
1160 #[test]
1161 fn streaming_state_transitions_do_not_move_neighbor_boundaries() {
1162 let mut cells = vec![
1163 user_cell("Inspect the candidate."),
1164 HistoryCell::Thinking {
1165 content: "Inspecting the candidate now.".to_string(),
1166 streaming: true,
1167 duration_secs: None,
1168 },
1169 exec_tool_cell("git status --short"),
1170 user_cell("Summarize the receipt."),
1171 ];
1172 let mut revisions = vec![1u64; cells.len()];
1173 let options = TranscriptRenderOptions {
1174 low_motion: true,
1175 ..TranscriptRenderOptions::default()
1176 };
1177 let mut cache = TranscriptViewCache::new();
1178
1179 let boundary_rows = |cache: &TranscriptViewCache| {
1180 [
1181 spacer_rows_after_cell(cache, 0),
1182 spacer_rows_after_cell(cache, 1),
1183 spacer_rows_after_cell(cache, 2),
1184 ]
1185 };
1186
1187 cache.ensure(&cells, &revisions, 80, options);
1188 let first = boundary_rows(&cache);
1189 assert_eq!(first, [3, 2, 3]);
1190
1191 cells[1] = assistant_cell("I inspected the candidate.", true);
1192 revisions[1] += 1;
1193 cache.ensure(&cells, &revisions, 80, options);
1194 assert_eq!(boundary_rows(&cache), first);
1195
1196 cells[1] = assistant_cell("I inspected the candidate.", false);
1197 revisions[1] += 1;
1198 cache.ensure(&cells, &revisions, 80, options);
1199 assert_eq!(boundary_rows(&cache), first);
1200
1201 let HistoryCell::Tool(ToolCell::Exec(exec)) = &mut cells[2] else {
1202 unreachable!("fixture is an exec tool")
1203 };
1204 exec.status = ToolStatus::Success;
1205 revisions[2] += 1;
1206 cache.ensure(&cells, &revisions, 80, options);
1207 assert_eq!(boundary_rows(&cache), first);
1208 }
1209
1210 #[test]
1211 fn resize_round_trip_rebuilds_the_same_semantic_rows() {
1212 let cells = vec![
1213 user_cell("A long prompt that wraps when the terminal narrows considerably."),
1214 exec_tool_cell("printf 'a tool receipt with a deliberately long summary'"),
1215 assistant_cell("A stable answer after the tool receipt.", false),
1216 ];
1217 let revisions = vec![1u64; cells.len()];
1218 let options = TranscriptRenderOptions {
1219 low_motion: true,
1220 ..TranscriptRenderOptions::default()
1221 };
1222 let mut cache = TranscriptViewCache::new();
1223
1224 cache.ensure(&cells, &revisions, 140, options);
1225 let wide = plain_lines(&cache);
1226 cache.ensure(&cells, &revisions, 40, options);
1227 cache.ensure(&cells, &revisions, 140, options);
1228
1229 assert_eq!(plain_lines(&cache), wide);
1230 assert_eq!(cache.lines().len(), cache.line_meta().len());
1231 assert_eq!(cache.lines().len(), cache.line_links().len());
1232 }
1233
1234 #[test]
1235 fn palette_mode_change_invalidates_cached_syntax_rendering() {
1236 let cells = vec![assistant_cell(
1237 "```rust\nfn main() { let answer = 42; }\n```",
1238 false,
1239 )];
1240 let revisions = [1u64];
1241 let mut cache = TranscriptViewCache::new();
1242 let dark = TranscriptRenderOptions {
1243 palette_mode: palette::PaletteMode::Dark,
1244 ..TranscriptRenderOptions::default()
1245 };
1246
1247 cache.ensure(&cells, &revisions, 80, dark);
1248 let dark_lines = Arc::clone(&cache.per_cell[0].lines);
1249
1250 cache.ensure(
1251 &cells,
1252 &revisions,
1253 80,
1254 TranscriptRenderOptions {
1255 palette_mode: palette::PaletteMode::Light,
1256 ..dark
1257 },
1258 );
1259
1260 assert!(
1261 !Arc::ptr_eq(&dark_lines, &cache.per_cell[0].lines),
1262 "palette mode is part of TranscriptRenderOptions and must bust cached cells"
1263 );
1264 }
1265
1266 #[test]
1267 fn tool_rails_preserve_rendered_width_budget() {
1268 let cells = vec![exec_tool_cell(
1269 "printf 'this is a command with enough text to wrap in narrow terminals'",
1270 )];
1271 let revisions = vec![1u64];
1272 let mut cache = TranscriptViewCache::new();
1273
1274 cache.ensure(&cells, &revisions, 24, TranscriptRenderOptions::default());
1275
1276 for line in plain_lines(&cache) {
1277 assert!(
1278 unicode_width::UnicodeWidthStr::width(line.as_str()) <= 24,
1279 "tool rail line exceeded narrow width: {line:?}"
1280 );
1281 }
1282 }
1283
1284 /// Simulate a long, complex conversation (thinking + multi-line tool output +
1285 /// tool headers with multiple decorative spans) and report the memory
1286 /// consumed by `rail_prefix_widths`. This is informational — the assertion
1287 /// only fails if the per-line overhead exceeds a generous bound.
1288 // Test prints memory-overhead diagnostics — runs in `cargo test`, never
1289 // inside the TUI alt-screen, so the module-level deny doesn't apply.
1290 #[allow(clippy::print_stderr)]
1291 #[test]
1292 fn rail_prefix_widths_memory_overhead_complex_session() {
1293 let mut cells: Vec<HistoryCell> = Vec::new();
1294 // Build ~60 turns covering the typical deep-reasoning workflow:
1295 // user → thinking (5-15 lines) → assistant → tool → tool output →
1296 // thinking → assistant → ... repeat.
1297 for i in 0..30 {
1298 cells.push(user_cell(&format!("complex query {i} about system design")));
1299 cells.push(HistoryCell::Thinking {
1300 content:
1301 "line A\nline B\nline C\nline D\nline E\nline F\nline G\nline H\nline I\nline J"
1302 .to_string(),
1303 streaming: false,
1304 duration_secs: Some(3.5),
1305 });
1306 cells.push(assistant_cell(
1307 &format!("response {i} with multi-line\ntext content spanning\nseveral lines"),
1308 false,
1309 ));
1310 cells.push(exec_tool_cell(
1311 "cargo test --package my_crate -- --nocapture 2>&1 | head -40",
1312 ));
1313 // Insert a second tool so adjacent tool cells merge into a railed group.
1314 cells.push(exec_tool_cell(&format!("git diff --stat HEAD~{i}")));
1315 }
1316 let revisions: Vec<u64> = (0..cells.len()).map(|i| i as u64 + 1).collect();
1317
1318 let mut cache = TranscriptViewCache::new();
1319 cache.ensure(&cells, &revisions, 80, TranscriptRenderOptions::default());
1320
1321 let total_lines = cache.total_lines();
1322 let pw_len = cache.rail_prefix_widths.len();
1323 let pw_cap = cache.rail_prefix_widths.capacity();
1324 // The Vec's inlined buffer on most platforms is small; capacity
1325 // should be >= len. Both must equal total_lines.
1326 assert_eq!(pw_len, total_lines);
1327 assert!(pw_cap >= pw_len);
1328
1329 let memory_bytes = pw_cap * std::mem::size_of::<usize>();
1330 let memory_kb = memory_bytes as f64 / 1024.0;
1331 // Each usize is 8 bytes on 64-bit. Even with 100k lines this stays
1332 // under 1 MB.
1333 let kbytes_per_1k_lines = (memory_bytes as f64 / total_lines as f64) * 1000.0 / 1024.0;
1334
1335 eprintln!("=== rail_prefix_widths memory (complex session) ===");
1336 eprintln!(" total_lines: {total_lines}");
1337 eprintln!(" vec len: {pw_len}");
1338 eprintln!(" vec capacity: {pw_cap}");
1339 eprintln!(" memory (bytes): {memory_bytes}");
1340 eprintln!(" memory (KB): {memory_kb:.2}");
1341 eprintln!(" KB per 1k lines: {kbytes_per_1k_lines:.2}");
1342 eprintln!(" lines × 8 bytes: {} KB", total_lines * 8 / 1024);
1343
1344 // Sanity: per-line overhead must be reasonable.
1345 assert!(
1346 memory_kb < 1024.0,
1347 "rail_prefix_widths memory unexpectedly large: {memory_kb:.1} KB"
1348 );
1349 eprintln!(" ✓ well under 1 MB even for very long sessions");
1350 }
1351
1352 #[test]
1353 fn ensure_filtered_matches_ensure_split_output() {
1354 let cells = vec![
1355 user_cell("hello"),
1356 assistant_cell("some **markdown** body", false),
1357 exec_tool_cell("cargo test"),
1358 user_cell("again"),
1359 ];
1360 let revisions = vec![1u64, 2, 3, 4];
1361 let index_map: Vec<usize> = vec![0, 1, 2, 3];
1362 // This test compares the two cache traversal paths, not animation.
1363 // Freeze live motion so a spinner tick between the two renders cannot
1364 // turn an equivalent layout into a timing-dependent failure.
1365 let options = TranscriptRenderOptions {
1366 low_motion: true,
1367 motion_mode: crate::tui::motion::MotionMode::Still,
1368 ..TranscriptRenderOptions::default()
1369 };
1370
1371 let mut split_cache = TranscriptViewCache::new();
1372 split_cache.ensure_split(
1373 &[&cells],
1374 &revisions,
1375 40,
1376 options,
1377 &HashMap::new(),
1378 Some(&index_map),
1379 None,
1380 );
1381
1382 let refs: Vec<&HistoryCell> = cells.iter().collect();
1383 let mut filtered_cache = TranscriptViewCache::new();
1384 filtered_cache.ensure_filtered(
1385 &refs,
1386 &revisions,
1387 40,
1388 options,
1389 &HashMap::new(),
1390 Some(&index_map),
1391 None,
1392 );
1393
1394 assert_eq!(plain_lines(&split_cache), plain_lines(&filtered_cache));
1395 assert_eq!(
1396 split_cache.line_meta().len(),
1397 filtered_cache.line_meta().len()
1398 );
1399 }
1400
1401 #[test]
1402 fn ensure_filtered_reuses_unchanged_cells() {
1403 let cells = [
1404 user_cell("hello"),
1405 assistant_cell("streaming", true),
1406 user_cell("again"),
1407 ];
1408 let mut revisions = vec![1u64, 1, 1];
1409 let refs: Vec<&HistoryCell> = cells.iter().collect();
1410
1411 let mut cache = TranscriptViewCache::new();
1412 cache.ensure_filtered(
1413 &refs,
1414 &revisions,
1415 80,
1416 TranscriptRenderOptions::default(),
1417 &HashMap::new(),
1418 None,
1419 None,
1420 );
1421 let first = plain_lines(&cache);
1422
1423 cache.ensure_filtered(
1424 &refs,
1425 &revisions,
1426 80,
1427 TranscriptRenderOptions::default(),
1428 &HashMap::new(),
1429 None,
1430 None,
1431 );
1432 assert_eq!(first, plain_lines(&cache));
1433 for (idx, cached) in cache.per_cell.iter().enumerate() {
1434 assert_eq!(
1435 cached.revision, 1,
1436 "cell {idx} must be reused, not re-rendered"
1437 );
1438 }
1439
1440 // Bump one revision: only that entry re-renders.
1441 revisions[1] = 2;
1442 cache.ensure_filtered(
1443 &refs,
1444 &revisions,
1445 80,
1446 TranscriptRenderOptions::default(),
1447 &HashMap::new(),
1448 None,
1449 None,
1450 );
1451 assert_eq!(cache.per_cell[0].revision, 1);
1452 assert_eq!(cache.per_cell[1].revision, 2);
1453 assert_eq!(cache.per_cell[2].revision, 1);
1454 }
1455
1456 #[test]
1457 fn prose_cells_fill_full_width_on_ultrawide_by_default() {
1458 // #5436: prose (user/assistant/thinking) spends the full content width
1459 // on wide terminals, consistent with tool cells and the #5322
1460 // wide-frame decision. The old 105-column rail is gone unless
1461 // `transcript.prose_measure` opts back into a bounded measure. The
1462 // cache key stays `(CellId, fed_width, revision)` so resize keeps its
1463 // single-feed cost model; the per-cell measure is applied inside the
1464 // render entry points.
1465 const RETIRED_RAIL_MEASURE: usize = 105;
1466 let long = "ultrawide prose paragraph that wraps its words across \
1467 the whole terminal canvas, repeated to guarantee \
1468 several wrapped rows at any column budget, "
1469 .repeat(6);
1470 let cells = [
1471 user_cell(&long),
1472 assistant_cell(&long, false),
1473 HistoryCell::Thinking {
1474 content: long.clone(),
1475 streaming: false,
1476 duration_secs: Some(2.0),
1477 },
1478 exec_tool_cell_with_output(
1479 "cargo test --all",
1480 "long tool output that itself wraps well past the prose measure ".repeat(6),
1481 ),
1482 ];
1483 let refs: Vec<&HistoryCell> = cells.iter().collect();
1484 let revisions = vec![1u64, 2, 3, 4];
1485 let options = TranscriptRenderOptions {
1486 low_motion: true,
1487 motion_mode: crate::tui::motion::MotionMode::Still,
1488 // Expanded thinking so the reasoning body also spends the width.
1489 verbose: true,
1490 thinking_default_expanded: true,
1491 ..TranscriptRenderOptions::default()
1492 };
1493
1494 let mut cache = TranscriptViewCache::new();
1495 cache.ensure_filtered(&refs, &revisions, 220, options, &HashMap::new(), None, None);
1496
1497 for (idx, cell) in cache.per_cell.iter().enumerate().take(3) {
1498 let width = max_line_width(&cell.lines);
1499 assert!(
1500 width > RETIRED_RAIL_MEASURE,
1501 "prose cell {idx} wrapped to {width} columns — still on the retired \
1502 {RETIRED_RAIL_MEASURE}-column rail",
1503 );
1504 assert!(
1505 width <= 220,
1506 "prose cell {idx} wrapped to {width} columns, past the 220-column canvas",
1507 );
1508 }
1509 let tool_width = max_line_width(&cache.per_cell[3].lines);
1510 assert!(
1511 tool_width > RETIRED_RAIL_MEASURE,
1512 "tool cell must keep the full width, got {tool_width}",
1513 );
1514 }
1515
1516 #[test]
1517 fn transcript_prose_measure_caps_prose_but_not_tools() {
1518 // A positive `transcript.prose_measure` restores a bounded reading
1519 // measure for prose only; tool/status cells keep the full content width
1520 // (#5436). The 120-column cap is deliberately above the retired
1521 // 105-column rail so a pass proves the configured cap — not the old
1522 // default — is in effect.
1523 let long = "ultrawide ".repeat(400);
1524 let cells = [
1525 user_cell(&long),
1526 assistant_cell(&long, false),
1527 HistoryCell::Thinking {
1528 content: long.clone(),
1529 streaming: false,
1530 duration_secs: Some(2.0),
1531 },
1532 exec_tool_cell_with_output(
1533 "cargo test --all",
1534 "long tool output that itself wraps well past the prose measure ".repeat(6),
1535 ),
1536 ];
1537 let refs: Vec<&HistoryCell> = cells.iter().collect();
1538 let revisions = vec![1u64, 2, 3, 4];
1539 let options = TranscriptRenderOptions {
1540 low_motion: true,
1541 motion_mode: crate::tui::motion::MotionMode::Still,
1542 verbose: true,
1543 thinking_default_expanded: true,
1544 prose_measure: Some(120),
1545 ..TranscriptRenderOptions::default()
1546 };
1547
1548 let mut cache = TranscriptViewCache::new();
1549 cache.ensure_filtered(&refs, &revisions, 220, options, &HashMap::new(), None, None);
1550
1551 for (idx, cell) in cache.per_cell.iter().enumerate().take(3) {
1552 let width = max_line_width(&cell.lines);
1553 assert!(
1554 width > 105,
1555 "prose cell {idx} wrapped to {width} columns — still on the retired \
1556 105-column rail, so the configured cap is not in effect",
1557 );
1558 assert!(
1559 width <= 120,
1560 "prose cell {idx} wrapped to {width} columns, over the 120-column measure",
1561 );
1562 }
1563 let tool_width = max_line_width(&cache.per_cell[3].lines);
1564 assert!(
1565 tool_width > 120,
1566 "tool cell must keep the full width past the prose measure, got {tool_width}",
1567 );
1568 }
1569
1570 #[test]
1571 fn overlay_and_streaming_entries_share_the_prose_measure() {
1572 // The main cache and the full-screen live-transcript overlay must agree
1573 // on the same effective prose width — the reason the measure rides on
1574 // `TranscriptRenderOptions` instead of being re-derived per cell
1575 // (#5436). Render one streaming assistant message through both
1576 // live-transcript entry points: the copy-metadata path (overlay) and
1577 // the incremental streaming path (active cell).
1578 let long = "ultrawide ".repeat(400);
1579 let cell = assistant_cell(&long, true);
1580 let options = TranscriptRenderOptions {
1581 low_motion: true,
1582 motion_mode: crate::tui::motion::MotionMode::Still,
1583 prose_measure: Some(120),
1584 ..TranscriptRenderOptions::default()
1585 };
1586
1587 let overlay_lines = cell.lines_with_copy_metadata(220, options);
1588 let overlay_width = overlay_lines
1589 .iter()
1590 .map(|line| max_line_width(std::slice::from_ref(&line.line)))
1591 .max()
1592 .unwrap_or(0);
1593
1594 let mut cache = codewhale_tui_kit::markdown_render::IncrementalMarkdownRenderCache::default();
1595 let mut streaming_lines = Vec::new();
1596 let mut links = Vec::new();
1597 let mut separators = Vec::new();
1598 let mut prefix_widths = Vec::new();
1599 cell.update_incremental_streaming_render(
1600 220,
1601 options,
1602 false,
1603 &mut cache,
1604 &mut streaming_lines,
1605 &mut links,
1606 &mut separators,
1607 &mut prefix_widths,
1608 );
1609 let streaming_width = max_line_width(&streaming_lines);
1610
1611 for (name, width) in [("overlay", overlay_width), ("streaming", streaming_width)] {
1612 assert!(
1613 width > 105,
1614 "{name} entry stayed on the retired 105-column rail ({width} columns)",
1615 );
1616 assert!(
1617 width <= 120,
1618 "{name} entry wrapped to {width} columns, over the 120-column measure",
1619 );
1620 }
1621 }
1622
1623 #[test]
1624 fn prose_width_resolves_the_transcript_prose_measure_contract() {
1625 // Absent = full content width (floored at 1); a positive cap clamps
1626 // from above only, so narrow terminals keep their content width
1627 // (#5436: 0/absent means full width).
1628 let full = TranscriptRenderOptions::default();
1629 assert_eq!(full.prose_measure, None);
1630 assert_eq!(full.prose_width(220), 220);
1631 assert_eq!(full.prose_width(96), 96);
1632 assert_eq!(full.prose_width(0), 1);
1633
1634 let capped = TranscriptRenderOptions {
1635 prose_measure: Some(120),
1636 ..TranscriptRenderOptions::default()
1637 };
1638 assert_eq!(capped.prose_width(220), 120);
1639 assert_eq!(capped.prose_width(96), 96);
1640 assert_eq!(capped.prose_width(0), 1);
1641 }
1642
1643 fn max_line_width(lines: &[Line<'static>]) -> usize {
1644 lines
1645 .iter()
1646 .map(|line| {
1647 line.spans
1648 .iter()
1649 .map(|span| unicode_width::UnicodeWidthStr::width(span.content.as_ref()))
1650 .sum()
1651 })
1652 .max()
1653 .unwrap_or(0)
1654 }
1655
1656 #[test]
1657 fn folded_thinking_cache_invalidation() {
1658 let long_content = "reasoning line\n".repeat(50);
1659 let cells = [HistoryCell::Thinking {
1660 content: long_content.clone(),
1661 streaming: false,
1662 duration_secs: Some(1.5),
1663 }];
1664 let revisions = [1u64];
1665 let options = TranscriptRenderOptions {
1666 verbose: true, // expanded by default
1667 ..TranscriptRenderOptions::default()
1668 };
1669 let width = 80u16;
1670
1671 // First render: no folding → full content.
1672 let mut cache = TranscriptViewCache::new();
1673 cache.ensure_split(
1674 &[&cells],
1675 &revisions,
1676 width,
1677 options,
1678 &HashMap::new(),
1679 None,
1680 None,
1681 );
1682 let full_line_count = cache.total_lines();
1683
1684 // Second render: fold the thinking cell → should invalidate and
1685 // produce fewer lines (collapsed summary).
1686 let mut folded = HashMap::new();
1687 folded.insert(0usize, TranscriptFold::Collapsed);
1688 cache.ensure_split(&[&cells], &revisions, width, options, &folded, None, None);
1689 let folded_line_count = cache.total_lines();
1690
1691 assert!(
1692 folded_line_count < full_line_count,
1693 "folded thinking should render fewer lines: folded={folded_line_count} full={full_line_count}"
1694 );
1695
1696 // Third render: unfold → should restore full content.
1697 cache.ensure_split(
1698 &[&cells],
1699 &revisions,
1700 width,
1701 options,
1702 &HashMap::new(),
1703 None,
1704 None,
1705 );
1706 let restored_line_count = cache.total_lines();
1707 assert_eq!(
1708 restored_line_count, full_line_count,
1709 "unfolded thinking should restore full line count"
1710 );
1711 }
1712
1713 #[test]
1714 fn folded_thinking_with_collapsed_cells_uses_original_indices() {
1715 // Two thinking cells: cell 0 and cell 1. Cell 0 is collapsed (hidden).
1716 // Fold cell 1 (original index 1). With the filtered index map,
1717 // the cache should still fold the correct cell.
1718 let cells = [
1719 HistoryCell::Thinking {
1720 content: "first thinking block\n".repeat(20),
1721 streaming: false,
1722 duration_secs: Some(1.0),
1723 },
1724 HistoryCell::Thinking {
1725 content: "second thinking block\n".repeat(20),
1726 streaming: false,
1727 duration_secs: Some(2.0),
1728 },
1729 ];
1730 let revisions = [1u64, 2u64];
1731 let options = TranscriptRenderOptions {
1732 verbose: true,
1733 ..TranscriptRenderOptions::default()
1734 };
1735 let width = 80u16;
1736
1737 // No collapsing, no folding — baseline.
1738 let mut cache = TranscriptViewCache::new();
1739 cache.ensure_split(
1740 &[&cells],
1741 &revisions,
1742 width,
1743 options,
1744 &HashMap::new(),
1745 None,
1746 None,
1747 );
1748 let baseline = cache.total_lines();
1749 assert!(baseline > 0, "baseline render should contain visible lines");
1750
1751 // Collapse cell 0, fold cell 1. The filtered list has only cell 1
1752 // at filtered index 0, but it maps to original index 1.
1753 let filtered_cells = [cells[1].clone()];
1754 let filtered_revs = [2u64];
1755 let index_map: Vec<usize> = vec![1]; // filtered 0 → original 1
1756
1757 let mut folded = HashMap::new();
1758 folded.insert(1usize, TranscriptFold::Collapsed); // fold original index 1
1759
1760 let mut cache2 = TranscriptViewCache::new();
1761 cache2.ensure_split(
1762 &[&filtered_cells],
1763 &filtered_revs,
1764 width,
1765 options,
1766 &folded,
1767 Some(&index_map),
1768 None,
1769 );
1770 let folded_filtered = cache2.total_lines();
1771
1772 // Cell 1 was expanded in baseline; now it should be folded.
1773 // We can't compare directly to baseline because baseline had both
1774 // cells, but folded_filtered should be less than if cell 1 were
1775 // expanded in the filtered view.
1776 let mut cache3 = TranscriptViewCache::new();
1777 cache3.ensure_split(
1778 &[&filtered_cells],
1779 &filtered_revs,
1780 width,
1781 options,
1782 &HashMap::new(),
1783 Some(&index_map),
1784 None,
1785 );
1786 let expanded_filtered = cache3.total_lines();
1787
1788 assert!(
1789 folded_filtered < expanded_filtered,
1790 "folded cell via index map should render fewer lines: folded={folded_filtered} expanded={expanded_filtered}"
1791 );
1792 }
1793
1794 #[test]
1795 fn reasoning_target_transfer_rewrites_same_revision_cells() {
1796 let cells = vec![reasoning_cell(false), reasoning_cell(false)];
1797 let revisions = [1, 2];
1798 let mut cache = TranscriptViewCache::new();
1799 let options = TranscriptRenderOptions::default();
1800 let hint_cells = |cache: &TranscriptViewCache| {
1801 cache
1802 .lines()
1803 .iter()
1804 .zip(cache.line_meta())
1805 .filter(|(line, _)| line.to_string().contains("Space:expand"))
1806 .filter_map(|(_, meta)| meta.cell_line().map(|(cell, _)| cell))
1807 .collect::<Vec<_>>()
1808 };
1809
1810 cache.ensure_split(
1811 &[&cells],
1812 &revisions,
1813 80,
1814 options,
1815 &HashMap::new(),
1816 None,
1817 Some(reasoning_owner(0)),
1818 );
1819 let total = cache.total_lines();
1820 assert_eq!(hint_cells(&cache), vec![0]);
1821 let cached_lines = cache
1822 .per_cell
1823 .iter()
1824 .map(|cell| Arc::as_ptr(&cell.lines))
1825 .collect::<Vec<_>>();
1826 let (hint_line, hint_meta) = cache
1827 .lines()
1828 .iter()
1829 .zip(cache.line_meta())
1830 .find(|(line, _)| line.to_string().contains("Space:expand"))
1831 .expect("hint line");
1832 let hint_index = cache
1833 .lines()
1834 .iter()
1835 .position(|line| line.to_string().contains("Space:expand"))
1836 .expect("hint index");
1837 assert_eq!(
1838 hint_meta.copy_prefix_width(),
1839 hint_line
1840 .width()
1841 .saturating_sub(cache.rail_prefix_width(hint_index))
1842 );
1843 let (neutral_index, neutral_line, neutral_meta) = cache
1844 .lines()
1845 .iter()
1846 .zip(cache.line_meta())
1847 .enumerate()
1848 .find(|(_, (_, meta))| meta.cell_line() == Some((1, 0)))
1849 .map(|(index, (line, meta))| (index, line, meta))
1850 .expect("untargeted neutral affordance");
1851 assert_eq!(
1852 neutral_meta.copy_prefix_width(),
1853 neutral_line
1854 .width()
1855 .saturating_sub(cache.rail_prefix_width(neutral_index))
1856 );
1857 assert!(cache.line_links[neutral_index].is_empty());
1858
1859 cache.retarget(Some(reasoning_owner(1)), None);
1860 assert_eq!(cache.total_lines(), total);
1861 assert_eq!(hint_cells(&cache), vec![1]);
1862 assert_eq!(
1863 cache
1864 .per_cell
1865 .iter()
1866 .map(|cell| Arc::as_ptr(&cell.lines))
1867 .collect::<Vec<_>>(),
1868 cached_lines,
1869 "target transfer must reuse neutral Markdown renders"
1870 );
1871
1872 cache.retarget(None, None);
1873 assert_eq!(cache.total_lines(), total);
1874 assert!(hint_cells(&cache).is_empty());
1875 }
1876
1877 /// Scrolling moves the Space owner to the newest visible cell. On a long
1878 /// transcript that must repaint the two affordance rows, not re-flatten the
1879 /// whole tail below the previous owner (#6652).
1880 fn long_reasoning_transcript(pairs: usize) -> (Vec<HistoryCell>, Vec<u64>) {
1881 let cells = (0..pairs)
1882 .flat_map(|turn| {
1883 [
1884 reasoning_cell(false),
1885 assistant_cell(&format!("answer {turn}\n\nmore prose for {turn}"), false),
1886 ]
1887 })
1888 .collect::<Vec<_>>();
1889 let revisions = vec![1; cells.len()];
1890 (cells, revisions)
1891 }
1892
1893 fn assert_same_flat_output(cache: &TranscriptViewCache, cold: &TranscriptViewCache) {
1894 assert_eq!(cache.lines(), cold.lines());
1895 assert_eq!(cache.line_links(), cold.line_links());
1896 assert_eq!(cache.line_meta(), cold.line_meta());
1897 assert_eq!(cache.rail_prefix_widths, cold.rail_prefix_widths);
1898 assert_eq!(cache.cell_line_starts, cold.cell_line_starts);
1899 }
1900
1901 #[test]
1902 fn retargeting_a_long_transcript_repaints_only_the_hint_rows() {
1903 let (cells, revisions) = long_reasoning_transcript(100);
1904 let options = TranscriptRenderOptions::default();
1905 let ensure = |cache: &mut TranscriptViewCache, owner: usize| {
1906 cache.ensure_split(
1907 &[&cells],
1908 &revisions,
1909 80,
1910 options,
1911 &HashMap::new(),
1912 None,
1913 Some(reasoning_owner(owner)),
1914 );
1915 };
1916 let mut cache = TranscriptViewCache::new();
1917 ensure(&mut cache, 0);
1918 assert!(cache.total_lines() > 600, "{}", cache.total_lines());
1919
1920 // Scroll-frame path: `retarget` after layout.
1921 for owner in [2, 100, 198, 0] {
1922 let before = cache.streaming_lines_reflattened();
1923 cache.retarget(Some(reasoning_owner(owner)), None);
1924 assert!(
1925 cache.streaming_lines_reflattened() - before <= 2,
1926 "retarget to {owner} re-flattened {} rows",
1927 cache.streaming_lines_reflattened() - before
1928 );
1929 let mut cold = TranscriptViewCache::new();
1930 ensure(&mut cold, owner);
1931 assert_same_flat_output(&cache, &cold);
1932 }
1933
1934 // Provisional-owner path: `ensure_split` with only the owner moved.
1935 for owner in [4, 150, 0] {
1936 let before = cache.streaming_lines_reflattened();
1937 ensure(&mut cache, owner);
1938 assert!(
1939 cache.streaming_lines_reflattened() - before <= 2,
1940 "ensure with owner {owner} re-flattened {} rows",
1941 cache.streaming_lines_reflattened() - before
1942 );
1943 let mut cold = TranscriptViewCache::new();
1944 ensure(&mut cold, owner);
1945 assert_same_flat_output(&cache, &cold);
1946 }
1947
1948 // An answer cell owns no hint: moving there only clears the old row.
1949 let before = cache.streaming_lines_reflattened();
1950 cache.retarget(Some(reasoning_owner(1)), None);
1951 assert_eq!(cache.streaming_lines_reflattened() - before, 1);
1952 assert!(!plain_lines(&cache).join("\n").contains("Space:expand"));
1953 }
1954
1955 /// While a reply streams its cell is dirty every frame. Scrolling in that
1956 /// state must still repaint only the hint rows plus the streamed tail, not
1957 /// re-flatten everything below the old owner (#6652).
1958 #[test]
1959 fn retargeting_while_streaming_repaints_only_hint_rows_and_tail() {
1960 let (mut cells, _) = long_reasoning_transcript(100);
1961 // A reasoning cell right above the streaming reply: moving the hint
1962 // there lands inside the rows this frame rebuilds anyway.
1963 cells.push(reasoning_cell(false));
1964 let mut content = String::from("streamed start\n\n");
1965 cells.push(assistant_cell(&content, true));
1966 let streaming = cells.len() - 1;
1967 let mut revisions = vec![1; cells.len()];
1968 let options = TranscriptRenderOptions {
1969 low_motion: true,
1970 ..TranscriptRenderOptions::default()
1971 };
1972 let ensure = |cache: &mut TranscriptViewCache, cells: &[HistoryCell], revs: &[u64], owner| {
1973 cache.ensure_split(
1974 &[cells],
1975 revs,
1976 80,
1977 options,
1978 &HashMap::new(),
1979 None,
1980 Some(reasoning_owner(owner)),
1981 );
1982 };
1983 let mut cache = TranscriptViewCache::new();
1984 ensure(&mut cache, &cells, &revisions, 0);
1985 assert!(cache.total_lines() > 600, "{}", cache.total_lines());
1986
1987 for (frame, owner) in [2, 100, 198, streaming - 1, 0, 4].into_iter().enumerate() {
1988 let previous = revisions[streaming];
1989 revisions[streaming] += 1;
1990 content.push_str(&format!("chunk {frame} of the streamed reply\n\n"));
1991 cells[streaming] = assistant_cell(&content, true);
1992 cache.set_streaming_source_receipt(Some(StreamingSourceReceipt {
1993 cell_index: streaming,
1994 from_revision: previous,
1995 to_revision: revisions[streaming],
1996 content_len: content.len(),
1997 }));
1998 let before = cache.streaming_lines_reflattened();
1999 ensure(&mut cache, &cells, &revisions, owner);
2000 let work = cache.streaming_lines_reflattened() - before;
2001 let tail_rows = (cache.per_cell[streaming - 1].lines.len()
2002 + cache.per_cell[streaming].lines.len()
2003 + 4) as u64;
2004 assert!(
2005 work <= tail_rows,
2006 "streaming frame with owner {owner} re-flattened {work} rows (tail {tail_rows})"
2007 );
2008 let mut cold = TranscriptViewCache::new();
2009 ensure(&mut cold, &cells, &revisions, owner);
2010 assert_same_flat_output(&cache, &cold);
2011 }
2012 }
2013
2014 /// Collapsed transcripts render through an original-index map, and hidden
2015 /// cells record their successor's line start. In-place hint repaint must
2016 /// land on the right rows in both cases (#6652).
2017 #[test]
2018 fn retargeting_a_filtered_transcript_with_hidden_cells_repaints_in_place() {
2019 let original = (0..80)
2020 .flat_map(|turn| {
2021 [
2022 reasoning_cell(false),
2023 // Renders no rows: a hidden cell between reasoning cells.
2024 assistant_cell("", false),
2025 reasoning_cell(false),
2026 assistant_cell(&format!("answer {turn}\n\nmore prose for {turn}"), false),
2027 // Dropped by the filter, so rendered and original indices diverge.
2028 assistant_cell(&format!("collapsed {turn}"), false),
2029 ]
2030 })
2031 .collect::<Vec<_>>();
2032 let map = (0..original.len())
2033 .filter(|index| index % 5 != 4)
2034 .collect::<Vec<_>>();
2035 let refs = map
2036 .iter()
2037 .map(|&index| &original[index])
2038 .collect::<Vec<_>>();
2039 let revisions = vec![1; refs.len()];
2040 let options = TranscriptRenderOptions::default();
2041 let ensure = |cache: &mut TranscriptViewCache, owner: usize| {
2042 cache.ensure_filtered(
2043 &refs,
2044 &revisions,
2045 80,
2046 options,
2047 &HashMap::new(),
2048 Some(&map),
2049 Some(reasoning_owner(owner)),
2050 );
2051 };
2052 let mut cache = TranscriptViewCache::new();
2053 ensure(&mut cache, 0);
2054 assert!(cache.per_cell.iter().any(|cell| cell.is_empty));
2055 assert!(cache.total_lines() > 600, "{}", cache.total_lines());
2056
2057 // Original indices: 2 and 7 sit after a hidden cell, 397 is the last
2058 // reasoning cell, and 1 is the hidden cell itself (no hint).
2059 for owner in [2, 150, 397, 7, 0, 1, 5] {
2060 let before = cache.streaming_lines_reflattened();
2061 cache.retarget(Some(reasoning_owner(owner)), Some(&map));
2062 assert!(
2063 cache.streaming_lines_reflattened() - before <= 2,
2064 "retarget to {owner} re-flattened {} rows",
2065 cache.streaming_lines_reflattened() - before
2066 );
2067 let mut cold = TranscriptViewCache::new();
2068 ensure(&mut cold, owner);
2069 assert_same_flat_output(&cache, &cold);
2070
2071 let next = if owner == 0 { 5 } else { 0 };
2072 let before = cache.streaming_lines_reflattened();
2073 ensure(&mut cache, next);
2074 assert!(
2075 cache.streaming_lines_reflattened() - before <= 2,
2076 "ensure with owner {next} re-flattened {} rows",
2077 cache.streaming_lines_reflattened() - before
2078 );
2079 let mut cold = TranscriptViewCache::new();
2080 ensure(&mut cold, next);
2081 assert_same_flat_output(&cache, &cold);
2082 }
2083 }
2084
2085 /// Synthetic scroll benchmark for #6652; run with `--ignored --nocapture`.
2086 #[test]
2087 #[ignore = "timing benchmark, not a correctness gate"]
2088 #[allow(clippy::print_stderr)]
2089 fn bench_retarget_scroll_over_long_transcript() {
2090 let (cells, revisions) = long_reasoning_transcript(2_000);
2091 let mut cache = TranscriptViewCache::new();
2092 cache.ensure_split(
2093 &[&cells],
2094 &revisions,
2095 120,
2096 TranscriptRenderOptions::default(),
2097 &HashMap::new(),
2098 None,
2099 Some(reasoning_owner(0)),
2100 );
2101 let before = cache.streaming_lines_reflattened();
2102 let started = std::time::Instant::now();
2103 let frames = 400;
2104 for frame in 0..frames {
2105 // Walk the owner between early reasoning cells as a scroll would.
2106 cache.retarget(Some(reasoning_owner((frame % 20) * 2)), None);
2107 }
2108 let elapsed = started.elapsed();
2109 eprintln!(
2110 "#6652 bench: {} lines, {frames} retargets, {:?} total, {:?}/frame, {} rows re-flattened",
2111 cache.total_lines(),
2112 elapsed,
2113 elapsed / frames as u32,
2114 cache.streaming_lines_reflattened() - before
2115 );
2116 }
2117
2118 #[test]
2119 fn filtered_reasoning_owner_keeps_original_identity() {
2120 let cells = [reasoning_cell(false)];
2121 let revisions = [2];
2122 let original_map = [1];
2123 let mut cache = TranscriptViewCache::new();
2124 cache.ensure_split(
2125 &[&cells],
2126 &revisions,
2127 80,
2128 TranscriptRenderOptions::default(),
2129 &HashMap::new(),
2130 Some(&original_map),
2131 Some(reasoning_owner(1)),
2132 );
2133 assert!(plain_lines(&cache).join("\n").contains("Space:expand"));
2134 assert_eq!(
2135 cache.fold_action_target(),
2136 Some(CellFoldActionTarget {
2137 owner: reasoning_owner(1),
2138 action: CellFoldAction::Expand,
2139 })
2140 );
2141 assert!(
2142 cache
2143 .line_meta()
2144 .iter()
2145 .any(|meta| meta.cell_line().is_some_and(|(rendered, _)| rendered == 0))
2146 );
2147
2148 cache.ensure_split(
2149 &[&cells],
2150 &revisions,
2151 80,
2152 TranscriptRenderOptions::default(),
2153 &HashMap::new(),
2154 Some(&original_map),
2155 Some(reasoning_owner(0)),
2156 );
2157 assert!(cache.fold_action_target().is_none());
2158 assert!(!plain_lines(&cache).join("\n").contains("Space:expand"));
2159 }
2160
2161 #[test]
2162 fn streaming_tail_fast_path_cannot_skip_reasoning_retarget() {
2163 let cells = [reasoning_cell(false), assistant_cell("tail", true)];
2164 let mut cache = TranscriptViewCache::new();
2165 cache.ensure_split(
2166 &[&cells],
2167 &[1, 1],
2168 80,
2169 TranscriptRenderOptions::default(),
2170 &HashMap::new(),
2171 None,
2172 Some(reasoning_owner(0)),
2173 );
2174 assert!(plain_lines(&cache).join("\n").contains("Space:expand"));
2175
2176 let updated = [reasoning_cell(false), assistant_cell("tail extended", true)];
2177 cache.ensure_split(
2178 &[&updated],
2179 &[1, 2],
2180 80,
2181 TranscriptRenderOptions::default(),
2182 &HashMap::new(),
2183 None,
2184 None,
2185 );
2186 assert!(cache.fold_action_target().is_none());
2187 assert!(!plain_lines(&cache).join("\n").contains("Space:expand"));
2188 }
2189
2190 #[test]
2191 fn narrow_reasoning_hint_never_changes_cache_geometry() {
2192 let cells = [reasoning_cell(false)];
2193 for width in 1..=40 {
2194 let mut cache = TranscriptViewCache::new();
2195 cache.ensure_split(
2196 &[&cells],
2197 &[1],
2198 width,
2199 TranscriptRenderOptions::default(),
2200 &HashMap::new(),
2201 None,
2202 None,
2203 );
2204 let neutral_lines = cache.total_lines();
2205 cache.ensure_split(
2206 &[&cells],
2207 &[1],
2208 width,
2209 TranscriptRenderOptions::default(),
2210 &HashMap::new(),
2211 None,
2212 Some(reasoning_owner(0)),
2213 );
2214 assert_eq!(cache.total_lines(), neutral_lines, "width {width}");
2215 // The terminal clips an overlong neutral header. Adding a hint must
2216 // never add a row or advertise a chord that cannot fit alongside it.
2217 if width == 40 {
2218 assert!(plain_lines(&cache).join("\n").contains("Space:expand"));
2219 }
2220 if width < 14 {
2221 assert!(!plain_lines(&cache).join("\n").contains("Space:"));
2222 }
2223 }
2224 }
2225
2226 #[test]
2227 fn reasoning_hint_uses_the_render_locale() {
2228 let cells = [reasoning_cell(false)];
2229 let options = TranscriptRenderOptions {
2230 locale: Locale::Ja,
2231 ..TranscriptRenderOptions::default()
2232 };
2233 let mut cache = TranscriptViewCache::new();
2234 cache.ensure_split(
2235 &[&cells],
2236 &[1],
2237 80,
2238 options,
2239 &HashMap::new(),
2240 None,
2241 Some(reasoning_owner(0)),
2242 );
2243 let text = plain_lines(&cache).join("\n");
2244 assert!(text.contains("Space:展開"), "{text}");
2245 assert!(!text.contains("Space:expand"), "{text}");
2246 }
2247
2248 /// Rows-per-element measurement for the calm-UI PR body. Run with
2249 /// `--ignored --nocapture`.
2250 #[test]
2251 #[ignore = "measurement, not a correctness gate"]
2252 #[allow(clippy::print_stderr)]
2253 fn measure_calm_rows_per_turn() {
2254 use crate::tui::history::{GenericToolCell, McpToolCell};
2255 let shipped = TranscriptRenderOptions {
2256 show_tool_details: false,
2257 calm_mode: true,
2258 low_motion: true,
2259 ..TranscriptRenderOptions::default()
2260 };
2261 let body = (1..=40)
2262 .map(|i| format!("reasoning line {i:02}"))
2263 .collect::<Vec<_>>()
2264 .join("\n");
2265 let noisy = (0..30)
2266 .map(|i| format!("row {i:02} output"))
2267 .collect::<Vec<_>>()
2268 .join("\n");
2269 let generic = |name: &str, status: ToolStatus, output: Option<String>| {
2270 HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
2271 name: name.to_string(),
2272 status,
2273 input_summary: Some("path: src/lib.rs".to_string()),
2274 output,
2275 prompts: None,
2276 spillover_path: None,
2277 output_summary: None,
2278 is_diff: false,
2279 }))
2280 };
2281 let mcp = |status: ToolStatus, content: String| {
2282 HistoryCell::Tool(ToolCell::Mcp(McpToolCell {
2283 tool: "mcp_linear_get_issue".to_string(),
2284 status,
2285 content: Some(content),
2286 is_image: false,
2287 }))
2288 };
2289 let turn = vec![
2290 user_cell("fix the bug"),
2291 HistoryCell::Thinking {
2292 content: body.clone(),
2293 streaming: false,
2294 duration_secs: Some(12.0),
2295 },
2296 mcp(
2297 ToolStatus::Success,
2298 "CW-123\nTitle\nState: Todo".to_string(),
2299 ),
2300 mcp(ToolStatus::Failed, noisy.clone()),
2301 generic("read_file", ToolStatus::Failed, Some(noisy.clone())),
2302 exec_tool_cell_with_output("cargo test", noisy.clone()),
2303 assistant_cell("done", false),
2304 ];
2305 for cell in &turn {
2306 let rows = cell.lines_with_options(80, shipped).len();
2307 eprintln!("calm-rows element: {rows}");
2308 }
2309 let revisions = vec![1u64; turn.len()];
2310 let mut cache = TranscriptViewCache::new();
2311 cache.ensure_split(
2312 &[&turn],
2313 &revisions,
2314 80,
2315 shipped,
2316 &HashMap::new(),
2317 None,
2318 None,
2319 );
2320 eprintln!("calm-rows settled turn total: {}", cache.total_lines());
2321
2322 let live = vec![
2323 user_cell("fix the bug"),
2324 HistoryCell::Thinking {
2325 content: body,
2326 streaming: true,
2327 duration_secs: None,
2328 },
2329 ];
2330 let mut cache = TranscriptViewCache::new();
2331 let live_options = shipped;
2332 cache.ensure_split(
2333 &[&live],
2334 &[1, 1],
2335 80,
2336 live_options,
2337 &HashMap::new(),
2338 None,
2339 None,
2340 );
2341 eprintln!(
2342 "calm-rows streaming thinking cell (height-independent): {}",
2343 cache.per_cell[1].lines.len()
2344 );
2345 }
2346
2347 #[test]
2348 fn calm1_reasoning_header_hint_keeps_the_entire_live_tail_copyable() {
2349 let cells = [reasoning_cell(true)];
2350 let mut cache = TranscriptViewCache::new();
2351 let options = TranscriptRenderOptions {
2352 calm_mode: true,
2353 low_motion: true,
2354 ..Default::default()
2355 };
2356 cache.ensure_split(
2357 &[&cells],
2358 &[1],
2359 80,
2360 options,
2361 &HashMap::new(),
2362 None,
2363 Some(reasoning_owner(0)),
2364 );
2365 assert_eq!(cache.total_lines(), 4);
2366 assert!(cache.lines()[0].to_string().contains("Space:expand"));
2367 assert!(cache.lines()[3].to_string().contains("reasoning line 20"));
2368 for index in 1..4 {
2369 assert!(cache.line_meta()[index].copy_prefix_width() < cache.lines()[index].width());
2370 }
2371 }
2372
2373 // ── Steady-state frames do no transcript work (#6652) ───────────────────────
2374
2375 fn settled_transcript(turns: usize) -> (Vec<HistoryCell>, Vec<u64>) {
2376 let cells = (0..turns)
2377 .flat_map(|turn| {
2378 [
2379 user_cell(&format!("question {turn}")),
2380 reasoning_cell(false),
2381 assistant_cell(&format!("answer {turn}\n\n- one\n- two"), false),
2382 ]
2383 })
2384 .collect::<Vec<_>>();
2385 let revisions = (1..=cells.len() as u64).collect();
2386 (cells, revisions)
2387 }
2388
2389 #[test]
2390 fn an_unchanged_frame_renders_and_moves_nothing() {
2391 let (cells, revisions) = settled_transcript(400);
2392 let options = TranscriptRenderOptions::default();
2393 let ensure = |cache: &mut TranscriptViewCache| {
2394 cache.ensure_split(
2395 &[&cells],
2396 &revisions,
2397 80,
2398 options,
2399 &HashMap::new(),
2400 None,
2401 Some(reasoning_owner(1)),
2402 );
2403 };
2404 let mut cache = TranscriptViewCache::new();
2405 ensure(&mut cache);
2406 let rendered = cache.cells_rendered;
2407 let reflattened = cache.streaming_lines_reflattened();
2408 let storage = cache.per_cell.as_ptr();
2409 let line_arcs: Vec<_> = cache
2410 .per_cell
2411 .iter()
2412 .map(|cell| Arc::as_ptr(&cell.lines))
2413 .collect();
2414
2415 for _ in 0..5 {
2416 ensure(&mut cache);
2417 }
2418
2419 assert_eq!(cache.cells_rendered, rendered, "a settled frame rendered");
2420 assert_eq!(cache.streaming_lines_reflattened(), reflattened);
2421 assert_eq!(cache.per_cell.as_ptr(), storage, "cached cells were moved");
2422 for (index, cell) in cache.per_cell.iter().enumerate() {
2423 assert_eq!(Arc::as_ptr(&cell.lines), line_arcs[index], "cell {index}");
2424 }
2425 }
2426
2427 #[test]
2428 fn a_tail_only_change_renders_only_the_tail_in_place() {
2429 let (mut cells, mut revisions) = settled_transcript(400);
2430 cells.push(assistant_cell("streaming", true));
2431 revisions.push(10_000);
2432 let options = TranscriptRenderOptions {
2433 low_motion: true,
2434 ..TranscriptRenderOptions::default()
2435 };
2436 let ensure = |cache: &mut TranscriptViewCache, cells: &[HistoryCell], revisions: &[u64]| {
2437 cache.ensure_split(
2438 &[cells],
2439 revisions,
2440 80,
2441 options,
2442 &HashMap::new(),
2443 None,
2444 None,
2445 );
2446 };
2447 let mut cache = TranscriptViewCache::new();
2448 ensure(&mut cache, &cells, &revisions);
2449 let storage = cache.per_cell.as_ptr();
2450 let line_arcs: Vec<_> = cache
2451 .per_cell
2452 .iter()
2453 .map(|cell| Arc::as_ptr(&cell.lines))
2454 .collect();
2455
2456 for delta in 0..20u64 {
2457 let before = cache.cells_rendered;
2458 if let Some(HistoryCell::Assistant { content, .. }) = cells.last_mut() {
2459 content.push_str(&format!(" delta {delta}"));
2460 }
2461 *revisions.last_mut().unwrap() += 1;
2462 ensure(&mut cache, &cells, &revisions);
2463 assert_eq!(cache.cells_rendered - before, 1, "delta {delta}");
2464 }
2465 assert_eq!(cache.per_cell.as_ptr(), storage, "cached cells were moved");
2466 let settled = line_arcs.len() - 1;
2467 for (index, cell) in cache.per_cell[..settled].iter().enumerate() {
2468 assert_eq!(Arc::as_ptr(&cell.lines), line_arcs[index], "cell {index}");
2469 }
2470 let mut cold = TranscriptViewCache::new();
2471 ensure(&mut cold, &cells, &revisions);
2472 assert_same_flat_output(&cache, &cold);
2473
2474 // A change in the middle renders that cell and nothing after it.
2475 let before = cache.cells_rendered;
2476 cells[600] = assistant_cell("rewritten in place", false);
2477 revisions[600] = 20_000;
2478 ensure(&mut cache, &cells, &revisions);
2479 assert_eq!(cache.cells_rendered - before, 1);
2480 let mut cold = TranscriptViewCache::new();
2481 ensure(&mut cold, &cells, &revisions);
2482 assert_same_flat_output(&cache, &cold);
2483 }
2484
2485 /// A filter can shift rows so that a tool cell's slot is taken by a streaming
2486 /// answer at an unchanged cell count. The answer takes the tail-only update,
2487 /// but the group rail and spacer between it and its neighbour belong to the
2488 /// neighbour's rows and must be rebuilt (found by the cold-render property
2489 /// test below).
2490 #[test]
2491 fn a_tool_slot_taken_by_a_streaming_answer_refreshes_its_neighbour() {
2492 let options = TranscriptRenderOptions {
2493 low_motion: true,
2494 ..TranscriptRenderOptions::default()
2495 };
2496 let mut cells = vec![
2497 user_cell("run it"),
2498 exec_tool_cell("cargo check"),
2499 exec_tool_cell("cargo test"),
2500 ];
2501 let mut revisions = vec![1u64, 2, 3];
2502 let ensure = |cache: &mut TranscriptViewCache, cells: &[HistoryCell], revisions: &[u64]| {
2503 cache.ensure_split(
2504 &[cells],
2505 revisions,
2506 60,
2507 options,
2508 &HashMap::new(),
2509 None,
2510 None,
2511 );
2512 };
2513 let mut cache = TranscriptViewCache::new();
2514 ensure(&mut cache, &cells, &revisions);
2515
2516 cells[2] = assistant_cell("opening", true);
2517 revisions[2] = 4;
2518 ensure(&mut cache, &cells, &revisions);
2519
2520 let mut cold = TranscriptViewCache::new();
2521 ensure(&mut cold, &cells, &revisions);
2522 assert_same_flat_output(&cache, &cold);
2523 assert!(
2524 !plain_lines(&cache)
2525 .iter()
2526 .any(|line| line.starts_with('╭') || line.starts_with('╰')),
2527 "{:?}",
2528 plain_lines(&cache)
2529 );
2530 }
2531
2532 /// xorshift64*: a failing case prints its seed and step, so it replays.
2533 struct Xorshift(u64);
2534
2535 impl Xorshift {
2536 fn next(&mut self) -> u64 {
2537 self.0 ^= self.0 >> 12;
2538 self.0 ^= self.0 << 25;
2539 self.0 ^= self.0 >> 27;
2540 self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
2541 }
2542
2543 fn below(&mut self, bound: usize) -> usize {
2544 (self.next() % bound as u64) as usize
2545 }
2546 }
2547
2548 /// What a live caller hands the cache, advanced the way `App` advances it:
2549 /// every mutation takes a fresh revision from one monotonic counter, active
2550 /// entries share the active revision, and a destructive edit moves the
2551 /// identity epoch.
2552 struct TranscriptModel {
2553 cells: Vec<HistoryCell>,
2554 revisions: Vec<u64>,
2555 next_revision: u64,
2556 active: Vec<HistoryCell>,
2557 active_revision: u64,
2558 folds: HashMap<usize, TranscriptFold>,
2559 hidden: std::collections::HashSet<usize>,
2560 width: u16,
2561 options: TranscriptRenderOptions,
2562 owner: Option<usize>,
2563 epoch: u64,
2564 serial: u64,
2565 }
2566
2567 impl TranscriptModel {
2568 fn new() -> Self {
2569 Self {
2570 cells: Vec::new(),
2571 revisions: Vec::new(),
2572 next_revision: 1,
2573 active: Vec::new(),
2574 active_revision: 0,
2575 folds: HashMap::new(),
2576 hidden: Default::default(),
2577 width: 80,
2578 // Motion is wall-clock driven; the comparison is between two
2579 // renders taken at different instants.
2580 options: TranscriptRenderOptions {
2581 low_motion: true,
2582 ..TranscriptRenderOptions::default()
2583 },
2584 owner: None,
2585 epoch: 0,
2586 serial: 0,
2587 }
2588 }
2589
2590 fn fresh_revision(&mut self) -> u64 {
2591 self.next_revision += 1;
2592 self.next_revision
2593 }
2594
2595 fn random_cell(&mut self, rng: &mut Xorshift) -> HistoryCell {
2596 self.serial += 1;
2597 let serial = self.serial;
2598 let prose = format!(
2599 "{serial} {}",
2600 "words that wrap at narrow widths and keep going ".repeat(1 + rng.below(4))
2601 );
2602 match rng.below(9) {
2603 0 | 1 => user_cell(&prose),
2604 2 => assistant_cell(&format!("{prose}\n\n- item {serial}\n- item"), false),
2605 3 => assistant_cell(&prose, true),
2606 4 => reasoning_cell(false),
2607 5 => reasoning_cell(true),
2608 6 => exec_tool_cell(&format!("cargo test {serial}")),
2609 7 => exec_tool_cell_with_output(&format!("ls {serial}"), prose),
2610 _ => durable_work_cell(),
2611 }
2612 }
2613
2614 fn mutate(&mut self, rng: &mut Xorshift) -> &'static str {
2615 match rng.below(16) {
2616 0..=3 => {
2617 let cell = self.random_cell(rng);
2618 let revision = self.fresh_revision();
2619 self.cells.push(cell);
2620 self.revisions.push(revision);
2621 "append"
2622 }
2623 4 | 5 if !self.cells.is_empty() => {
2624 let index = rng.below(self.cells.len());
2625 self.cells[index] = self.random_cell(rng);
2626 self.revisions[index] = self.fresh_revision();
2627 "replace"
2628 }
2629 6 => {
2630 // Stream into the newest cell the way the reply path does.
2631 let revision = self.fresh_revision();
2632 let streaming_tail = matches!(
2633 self.cells.last(),
2634 Some(HistoryCell::Assistant {
2635 streaming: true,
2636 ..
2637 })
2638 );
2639 if streaming_tail {
2640 if let Some(HistoryCell::Assistant { content, .. }) = self.cells.last_mut() {
2641 content.push_str(" more streamed words\n");
2642 }
2643 *self.revisions.last_mut().unwrap() = revision;
2644 } else {
2645 self.cells.push(assistant_cell("opening ", true));
2646 self.revisions.push(revision);
2647 }
2648 "stream"
2649 }
2650 7 if !self.cells.is_empty() => {
2651 let index = self.cells.len() - 1;
2652 if let HistoryCell::Assistant { streaming, .. } = &mut self.cells[index] {
2653 *streaming = false;
2654 self.revisions[index] = self.fresh_revision();
2655 }
2656 "finish stream"
2657 }
2658 8 => {
2659 self.active = (0..rng.below(4)).map(|_| self.random_cell(rng)).collect();
2660 self.active_revision += 1;
2661 "replace active"
2662 }
2663 9 if !self.cells.is_empty() => {
2664 let index = rng.below(self.cells.len() + self.active.len());
2665 match rng.below(3) {
2666 0 => self.folds.insert(index, TranscriptFold::Expanded),
2667 1 => self.folds.insert(index, TranscriptFold::Collapsed),
2668 _ => self.folds.remove(&index),
2669 };
2670 "fold"
2671 }
2672 10 => {
2673 self.width = [24, 40, 80, 120][rng.below(4)];
2674 "width"
2675 }
2676 11 => {
2677 self.options.spacing =
2678 [TranscriptSpacing::Compact, TranscriptSpacing::Spacious][rng.below(2)];
2679 self.options.show_thinking = rng.below(4) != 0;
2680 "options"
2681 }
2682 12 if rng.below(4) == 0 => {
2683 self.cells.clear();
2684 self.revisions.clear();
2685 self.folds.clear();
2686 self.hidden.clear();
2687 self.epoch += 1;
2688 "clear"
2689 }
2690 13 if !self.cells.is_empty() => {
2691 // Edit/undo: roll back to an earlier prefix.
2692 let keep = rng.below(self.cells.len());
2693 self.cells.truncate(keep);
2694 self.revisions.truncate(keep);
2695 self.folds.retain(|index, _| *index < keep);
2696 self.hidden.retain(|index| *index < keep);
2697 self.epoch += 1;
2698 "truncate"
2699 }
2700 14 => {
2701 let total = self.cells.len() + self.active.len();
2702 if total > 0 {
2703 let index = rng.below(total);
2704 if !self.hidden.remove(&index) {
2705 self.hidden.insert(index);
2706 }
2707 }
2708 "hide"
2709 }
2710 15 => {
2711 let total = self.cells.len() + self.active.len();
2712 self.owner = (total > 0 && rng.below(3) != 0).then(|| rng.below(total));
2713 "owner"
2714 }
2715 _ => "no-op",
2716 }
2717 }
2718
2719 /// One live frame: committed history plus the active tail, filtered when
2720 /// the user has hidden cells, exactly as the chat widget assembles it.
2721 fn frame(&self, cache: &mut TranscriptViewCache, owner: Option<usize>) {
2722 let total = self.cells.len() + self.active.len();
2723 let owner = owner
2724 .filter(|index| *index < total)
2725 .map(|cell_index| TranscriptActionOwner {
2726 cell_index,
2727 identity_epoch: self.epoch,
2728 });
2729 let active_revisions = (0..self.active.len()).map(|i| {
2730 crate::tui::widgets::active_entry_revision(self.active_revision, i as u64 + 1)
2731 });
2732 if self.hidden.is_empty() {
2733 let revisions: Vec<u64> = self
2734 .revisions
2735 .iter()
2736 .copied()
2737 .chain(active_revisions)
2738 .collect();
2739 cache.ensure_split(
2740 &[&self.cells, &self.active],
2741 &revisions,
2742 self.width,
2743 self.options,
2744 &self.folds,
2745 None,
2746 owner,
2747 );
2748 return;
2749 }
2750 let revisions: Vec<u64> = self
2751 .revisions
2752 .iter()
2753 .copied()
2754 .chain(active_revisions)
2755 .collect();
2756 let mut kept = Vec::new();
2757 let mut kept_revisions = Vec::new();
2758 let mut map = Vec::new();
2759 for (index, cell) in self.cells.iter().chain(&self.active).enumerate() {
2760 if !self.hidden.contains(&index) {
2761 kept.push(cell);
2762 kept_revisions.push(revisions[index]);
2763 map.push(index);
2764 }
2765 }
2766 cache.ensure_filtered(
2767 &kept,
2768 &kept_revisions,
2769 self.width,
2770 self.options,
2771 &self.folds,
2772 Some(&map),
2773 owner,
2774 );
2775 }
2776 }
2777
2778 /// After every mutation, the incrementally maintained cache must equal one
2779 /// built from scratch from the same state: the early-out and in-place update
2780 /// may change how much work a frame does, never what it shows.
2781 #[test]
2782 fn cached_transcript_matches_a_cold_render_after_every_mutation() {
2783 for seed in 1..=8u64 {
2784 let mut rng = Xorshift(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1);
2785 let mut model = TranscriptModel::new();
2786 let mut warm = TranscriptViewCache::new();
2787 let mut log = Vec::new();
2788 for step in 0..150 {
2789 let op = model.mutate(&mut rng);
2790 log.push(op);
2791 let context = || format!("seed {seed} step {step}: {}", log.join(", "));
2792
2793 let owner = model.owner;
2794 model.frame(&mut warm, owner);
2795 let mut cold = TranscriptViewCache::new();
2796 model.frame(&mut cold, owner);
2797 assert_eq!(warm.lines(), cold.lines(), "{}", context());
2798 assert_eq!(warm.line_links(), cold.line_links(), "{}", context());
2799 assert_eq!(warm.line_meta(), cold.line_meta(), "{}", context());
2800 assert_eq!(
2801 warm.rail_prefix_widths,
2802 cold.rail_prefix_widths,
2803 "{}",
2804 context()
2805 );
2806 assert_eq!(
2807 warm.cell_line_starts,
2808 cold.cell_line_starts,
2809 "{}",
2810 context()
2811 );
2812 assert_eq!(
2813 warm.fold_action_target(),
2814 cold.fold_action_target(),
2815 "{}",
2816 context()
2817 );
2818
2819 // The same inputs again are a settled frame: no render, no rows
2820 // re-flattened, identical output.
2821 let rendered = warm.cells_rendered;
2822 let reflattened = warm.streaming_lines_reflattened();
2823 model.frame(&mut warm, owner);
2824 assert_eq!(warm.cells_rendered, rendered, "{}", context());
2825 assert_eq!(
2826 warm.streaming_lines_reflattened(),
2827 reflattened,
2828 "{}",
2829 context()
2830 );
2831 assert_eq!(warm.lines(), cold.lines(), "{}", context());
2832
2833 // A scroll frame retargets the hint after layout.
2834 if rng.below(3) == 0 {
2835 let total = model.cells.len() + model.active.len();
2836 let retarget = (total > 0).then(|| rng.below(total));
2837 let map: Vec<usize> = (0..total).filter(|i| !model.hidden.contains(i)).collect();
2838 let index_map = (!model.hidden.is_empty()).then_some(map.as_slice());
2839 let epoch = model.epoch;
2840 warm.retarget(
2841 retarget.map(|cell_index| TranscriptActionOwner {
2842 cell_index,
2843 identity_epoch: epoch,
2844 }),
2845 index_map,
2846 );
2847 let mut cold = TranscriptViewCache::new();
2848 model.frame(&mut cold, retarget);
2849 assert_eq!(warm.lines(), cold.lines(), "retarget; {}", context());
2850 assert_eq!(
2851 warm.line_meta(),
2852 cold.line_meta(),
2853 "retarget; {}",
2854 context()
2855 );
2856 }
2857 }
2858 }
2859 }
2860
2861 #[test]
2862 fn truncate_spans_to_width_preserves_zwj_grapheme_clusters() {
2863 let input = "ab 👨‍👩‍👧‍👦 cd";
2864 let full_width = codewhale_tui_kit::ui_text::text_display_width(input);
2865 for max_width in 4..=full_width {
2866 let out = truncate_spans_to_width(vec![Span::raw(input)], max_width);
2867 let text: String = out.iter().map(|span| span.content.as_ref()).collect();
2868 assert!(
2869 codewhale_tui_kit::ui_text::text_display_width(&text) <= max_width,
2870 "width {max_width} exceeded: {text:?}"
2871 );
2872 assert!(
2873 text.contains("👨‍👩‍👧‍👦") || (!text.contains('👨') && !text.contains('\u{200d}')),
2874 "ZWJ cluster split at width {max_width}: {text:?}"
2875 );
2876 }
2877
2878 let keycap = "ab 1\u{20e3} cd";
2879 let keycap_width = codewhale_tui_kit::ui_text::text_display_width(keycap);
2880 let truncated = truncate_spans_to_width(vec![Span::raw(keycap)], keycap_width - 1);
2881 let text: String = truncated.iter().map(|span| span.content.as_ref()).collect();
2882 assert!(
2883 codewhale_tui_kit::ui_text::text_display_width(&text) < keycap_width,
2884 "keycap span overflowed: {text:?}"
2885 );
2886 assert!(text.ends_with("..."), "expected ellipsis: {text:?}");
2887 }
2888
2889 #[test]
2890 fn transcript_cache_resolves_workspace_inline_code_links_only_when_settled() {
2891 let dir = tempfile::tempdir().unwrap();
2892 let workspace = dir.path().join("ws");
2893 std::fs::create_dir_all(workspace.join("dynamis/build/support-final")).unwrap();
2894 std::fs::write(workspace.join("src_main.rs"), "fn main() {}\n").unwrap();
2895
2896 let mut cache = TranscriptViewCache::new();
2897 cache.set_workspace(Some(&workspace));
2898 let options = TranscriptRenderOptions::default();
2899
2900 let streaming_cells = vec![HistoryCell::Assistant {
2901 content: "see `src_main.rs:12` and `dynamis/build/support-final/`".to_string(),
2902 streaming: true,
2903 }];
2904 cache.ensure(&streaming_cells, &[1], 120, options);
2905 assert!(
2906 cache.line_links().iter().all(Vec::is_empty),
2907 "streaming tail should skip workspace filesystem stat"
2908 );
2909
2910 let settled_cells = vec![HistoryCell::Assistant {
2911 content: "see `src_main.rs:12` and `dynamis/build/support-final/` and `missing.rs`"
2912 .to_string(),
2913 streaming: false,
2914 }];
2915 cache.ensure(&settled_cells, &[2], 120, options);
2916 let links: Vec<_> = cache.line_links().iter().flatten().collect();
2917 assert_eq!(links.len(), 2, "{links:?}");
2918 assert!(links[0].target.ends_with("/src_main.rs"));
2919 assert_eq!(links[0].line, Some(12));
2920 assert!(links[1].target.ends_with("/dynamis/build/support-final"));
2921 assert_eq!(links[1].line, None);
2922 }
2923
2923 lines RUST