bcode_tui 0.0.1-alpha.0

Terminal user interface for bcode
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
//! Cached transcript layout for virtualized TUI rendering.

use bmux_tui::prelude::Line;
use std::collections::BTreeSet;
use std::time::Instant;

use super::indexed_transcript_layout::IndexedTranscriptLayout;

/// Stable identity for a rendered transcript entry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TranscriptLayoutSignature(String);

impl TranscriptLayoutSignature {
    /// Create a layout signature from owned text.
    #[must_use]
    pub const fn new(value: String) -> Self {
        Self(value)
    }

    /// Return the signature text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Retained transcript rows or a sparse span of blank placeholder rows.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TranscriptLayoutRows {
    /// Fully rendered ordinary transcript rows.
    Rendered(Vec<Line>),
    /// Rows and bounded adapter-owned content correspondence accepted together.
    Anchored {
        rows: Vec<Line>,
        anchors: Vec<bcode_plugin_sdk::tui_visual::TuiVisualAnchor>,
    },
    /// Source geometry captured with this exact native visual projection.
    Selected {
        rows: Vec<Line>,
        anchors: Vec<bcode_plugin_sdk::tui_visual::TuiVisualAnchor>,
        selection: std::collections::BTreeMap<usize, bcode_plugin_sdk::tui::PluginTuiSelectionRow>,
    },
    /// Accepted Markdown projection retained for source-aware reflow correspondence.
    Markdown {
        rows: Vec<Line>,
        anchors: Vec<bcode_plugin_sdk::tui_visual::TuiVisualAnchor>,
        projection: std::sync::Arc<bcode_markdown_render::MarkdownRenderResult>,
        body_start: usize,
    },
    /// Logical rows rendered directly by an active terminal interaction.
    BlankSpan(usize),
}

impl Default for TranscriptLayoutRows {
    fn default() -> Self {
        Self::Rendered(Vec::new())
    }
}

impl TranscriptLayoutRows {
    /// Return the logical row count represented by this entry.
    #[must_use]
    pub const fn len(&self) -> usize {
        match self {
            Self::Rendered(rows)
            | Self::Anchored { rows, .. }
            | Self::Selected { rows, .. }
            | Self::Markdown { rows, .. } => rows.len(),
            Self::BlankSpan(len) => *len,
        }
    }

    /// Return whether this entry has no logical rows.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl From<Vec<Line>> for TranscriptLayoutRows {
    fn from(rows: Vec<Line>) -> Self {
        Self::Rendered(rows)
    }
}

/// Fingerprint for inputs used to prepare transcript layout.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TranscriptLayoutFingerprint(String);

impl TranscriptLayoutFingerprint {
    /// Create a layout fingerprint from owned text.
    #[must_use]
    pub const fn new(value: String) -> Self {
        Self(value)
    }

    /// Return the fingerprint text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Reason one transcript layout synchronization performed work.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TranscriptLayoutInvalidation {
    /// The fingerprint already matched, so no entries were scanned or rebuilt.
    CacheHit,
    /// Layout inputs changed without requiring a complete cache reset.
    Incremental,
    /// Terminal width changed and required a complete cache reset.
    Width,
    /// The caller explicitly requested a complete cache reset.
    Explicit,
}

impl TranscriptLayoutInvalidation {
    /// Return the stable low-cardinality metric label.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::CacheHit => "cache_hit",
            Self::Incremental => "incremental",
            Self::Width => "width",
            Self::Explicit => "explicit",
        }
    }
}

/// Work performed by one transcript layout synchronization attempt.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TranscriptLayoutSyncStats {
    /// Invalidation category for this attempt.
    pub invalidation: TranscriptLayoutInvalidation,
    /// Entry signatures inspected by the retained layout.
    pub entries_scanned: usize,
    /// Entry signatures whose rows were regenerated.
    pub signatures_changed: usize,
    /// Entries rebuilt after a signature change.
    pub entries_rebuilt: usize,
    /// Total rows generated for rebuilt entries.
    pub rows_regenerated: usize,
    /// Complete synchronization duration in microseconds.
    pub duration_micros: u64,
}

impl TranscriptLayoutSyncStats {
    /// Construct a cache-hit observation.
    #[must_use]
    pub const fn cache_hit(duration_micros: u64) -> Self {
        Self {
            invalidation: TranscriptLayoutInvalidation::CacheHit,
            entries_scanned: 0,
            signatures_changed: 0,
            entries_rebuilt: 0,
            rows_regenerated: 0,
            duration_micros,
        }
    }
}

/// Cached transcript layout rows.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct TranscriptLayoutCache {
    width: Option<u16>,
    fingerprint: Option<TranscriptLayoutFingerprint>,
    structural_fingerprint: Option<TranscriptLayoutFingerprint>,
    entries: IndexedTranscriptLayout,
    sync_stats: Vec<TranscriptLayoutSyncStats>,
}

/// A rendered line inside the transcript's global row space.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VisibleTranscriptLine {
    /// Global transcript row index from the oldest row.
    pub row_index: usize,
    /// Transcript entry index containing this row.
    pub entry_index: usize,
    /// Row offset within the transcript entry.
    pub row_in_entry: usize,
    /// Logical section that owns this row.
    pub source: VisibleTranscriptSource,
}

/// Cached transcript entry source.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VisibleTranscriptSource {
    /// Older-history status banner.
    HistoryBanner,
    /// Committed entry of the ordered terminal presentation document.
    ///
    /// This covers every committed visible entry regardless of persistence provenance: entries
    /// adapted from canonical session history and process-local ephemeral notices share one
    /// chronological sequence. Entry indexes are visible presentation indexes into that document,
    /// never canonical source indexes, so consumers must not infer durability from this source.
    Transcript,
    /// Pending submission item.
    Pending,
}

impl TranscriptLayoutCache {
    /// Whether newly accepted rows changed below the viewport.
    #[must_use]
    pub fn changed_content_below(&self, bottom: usize) -> bool {
        self.entries.changed_content_below(bottom)
    }

    /// Exclude timer-only visual updates from activity.
    pub fn suppress_visual_content_changes(&mut self, invocations: &BTreeSet<String>) {
        self.entries.suppress_visual_content_changes(invocations);
    }

    /// Acknowledge content changes after successful presentation.
    pub fn clear_content_changes(&mut self) {
        self.entries.clear_content_changes();
    }

    /// Resolve a visible row to its accepted Markdown source position.
    pub fn source_position(&self, index: usize, row: usize) -> Option<usize> {
        self.entries.source_position(index, row)
    }

    /// Resolve an accepted source position after reflow.
    pub fn source_row(&self, index: usize, position: usize) -> Option<usize> {
        self.entries.source_row(index, position)
    }

    /// Find the nearest accepted content key at or before an item row.
    /// Source geometry retained with the exact painted entry projection.
    pub fn selection_row(
        &self,
        index: usize,
        row: usize,
    ) -> Option<&bcode_plugin_sdk::tui::PluginTuiSelectionRow> {
        self.entries.selection_row(index, row)
    }

    pub fn content_anchor(&self, index: usize, row: usize) -> Option<(&str, usize)> {
        self.entries.content_anchor(index, row)
    }

    /// Resolve a region offset without crossing into the next region.
    pub fn resolve_content_anchor(&self, index: usize, key: &str, offset: usize) -> Option<usize> {
        self.entries.resolve_content_anchor(index, key, offset)
    }

    /// Resolve an accepted content key in the current item layout.
    pub fn content_anchor_row(&self, index: usize, key: &str) -> Option<usize> {
        self.entries.content_anchor_row(index, key)
    }

    /// Return whether the cache already represents the given fingerprint.
    #[must_use]
    pub fn is_current(&self, fingerprint: &TranscriptLayoutFingerprint) -> bool {
        self.fingerprint.as_ref() == Some(fingerprint)
    }

    /// Return whether the cache structure matches inputs excluding isolated visual revisions.
    #[must_use]
    pub fn structure_is_current(&self, fingerprint: &TranscriptLayoutFingerprint) -> bool {
        self.structural_fingerprint.as_ref() == Some(fingerprint)
    }

    /// Synchronize only transcript entries owned by dirty visual invocations.
    pub fn sync_visuals<S, R>(
        &mut self,
        fingerprint: TranscriptLayoutFingerprint,
        invocation_ids: &BTreeSet<String>,
        signature: S,
        rows: R,
    ) -> TranscriptLayoutSyncStats
    where
        S: Fn(usize) -> TranscriptLayoutSignature,
        R: FnMut(usize) -> TranscriptLayoutRows,
    {
        let started = Instant::now();
        let (entries_scanned, signatures_changed, rows_regenerated) =
            self.entries.sync_visuals(invocation_ids, signature, rows);
        self.fingerprint = Some(fingerprint);
        let stats = TranscriptLayoutSyncStats {
            invalidation: TranscriptLayoutInvalidation::Incremental,
            entries_scanned,
            signatures_changed,
            entries_rebuilt: signatures_changed,
            rows_regenerated,
            duration_micros: u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX),
        };
        self.sync_stats.push(stats);
        stats
    }

    /// Synchronize only transcript entries identified by stable source damage.
    pub fn sync_transcript_entries<S, R>(
        &mut self,
        fingerprint: TranscriptLayoutFingerprint,
        indexes: &BTreeSet<usize>,
        signature: S,
        rows: R,
    ) -> TranscriptLayoutSyncStats
    where
        S: Fn(usize) -> TranscriptLayoutSignature,
        R: FnMut(usize) -> TranscriptLayoutRows,
    {
        let started = Instant::now();
        let (entries_scanned, signatures_changed, rows_regenerated) = self
            .entries
            .sync_transcript_entries(indexes, signature, rows);
        self.fingerprint = Some(fingerprint);
        let stats = TranscriptLayoutSyncStats {
            invalidation: TranscriptLayoutInvalidation::Incremental,
            entries_scanned,
            signatures_changed,
            entries_rebuilt: signatures_changed,
            rows_regenerated,
            duration_micros: u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX),
        };
        self.sync_stats.push(stats);
        stats
    }

    /// Record one cache-hit synchronization attempt.
    pub fn record_cache_hit(&mut self, duration_micros: u64) {
        self.sync_stats
            .push(TranscriptLayoutSyncStats::cache_hit(duration_micros));
    }

    /// Drain synchronization work observations accumulated since the previous call.
    pub fn drain_sync_stats(&mut self) -> Vec<TranscriptLayoutSyncStats> {
        std::mem::take(&mut self.sync_stats)
    }

    /// Synchronize the cache for a terminal width and current transcript data.
    pub fn sync<TS, TR, TI, PS, PR, HS, HR, R>(
        &mut self,
        spec: TranscriptLayoutSpec<TS, TR, TI, PS, PR, HS, HR, R>,
    ) -> TranscriptLayoutSyncStats
    where
        TS: Fn(usize) -> TranscriptLayoutSignature,
        TR: Fn(usize) -> TranscriptLayoutRows,
        TI: Fn(usize) -> Option<String>,
        PS: Fn(usize) -> TranscriptLayoutSignature,
        PR: Fn(usize) -> TranscriptLayoutRows,
        HS: FnOnce() -> Option<TranscriptLayoutSignature>,
        HR: FnOnce() -> TranscriptLayoutRows,
        R: FnOnce() -> bool,
    {
        let started = Instant::now();
        let width_changed = self.width != Some(spec.width);
        let explicit_reset = (spec.reset)();
        let invalidation = if width_changed {
            TranscriptLayoutInvalidation::Width
        } else if explicit_reset {
            TranscriptLayoutInvalidation::Explicit
        } else {
            TranscriptLayoutInvalidation::Incremental
        };
        if width_changed || explicit_reset {
            self.width = Some(spec.width);
            self.fingerprint = None;
            self.structural_fingerprint = None;
            self.entries.clear();
        }

        let history_signature = (spec.history_banner_signature)();
        let entries_scanned = spec
            .transcript_len
            .saturating_add(spec.pending_len)
            .saturating_add(usize::from(history_signature.is_some()));
        let (history_changed, history_rows) = self
            .entries
            .sync_history(history_signature, spec.history_banner_rows);
        let (transcript_changed, transcript_rows) = self.entries.sync_transcript(
            spec.transcript_len,
            spec.transcript_signature,
            spec.transcript_rows,
            spec.transcript_invocation_id,
        );
        let (pending_changed, pending_rows) =
            self.entries
                .sync_pending(spec.pending_len, spec.pending_signature, spec.pending_rows);
        let signatures_changed = history_changed
            .saturating_add(transcript_changed)
            .saturating_add(pending_changed);
        let rows_regenerated = history_rows
            .saturating_add(transcript_rows)
            .saturating_add(pending_rows);
        if width_changed || explicit_reset {
            self.entries.clear_content_changes();
        }
        self.fingerprint = Some(spec.fingerprint);
        self.structural_fingerprint = Some(spec.structural_fingerprint);
        let stats = TranscriptLayoutSyncStats {
            invalidation,
            entries_scanned,
            signatures_changed,
            entries_rebuilt: signatures_changed,
            rows_regenerated,
            duration_micros: u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX),
        };
        self.sync_stats.push(stats);
        stats
    }

    /// Return total rendered row count for the cached transcript document.
    #[must_use]
    pub fn total_rows(&self) -> usize {
        self.entries.total_rows()
    }

    /// Return visible cached rows for a top-origin start row and viewport height.
    #[must_use]
    pub fn visible_lines_from_top(
        &self,
        start: usize,
        viewport_height: u16,
    ) -> Vec<VisibleTranscriptLine> {
        self.entries.visible_lines_from_top(start, viewport_height)
    }

    /// Return cached line for a visible transcript line.
    #[must_use]
    pub fn line(&self, visible: VisibleTranscriptLine) -> Option<&Line> {
        self.entries.line(visible)
    }

    /// Return visible cached row metadata for one global row index.
    #[must_use]
    pub fn line_at_row(&self, row: usize) -> Option<VisibleTranscriptLine> {
        self.entries.line_at_row(row)
    }

    /// Return the first distinct cached transcript entry start at or after `row`.
    #[must_use]
    pub fn first_entry_start_at_or_after_row(&self, row: usize) -> Option<usize> {
        self.entries.first_entry_start_at_or_after_row(row)
    }

    /// Return the global start row for a cached transcript entry.
    #[must_use]
    pub fn entry_start_row(
        &self,
        source: VisibleTranscriptSource,
        entry_index: usize,
    ) -> Option<usize> {
        self.entries.entry_start_row(source, entry_index)
    }

    pub fn entry_row_count(
        &self,
        source: VisibleTranscriptSource,
        entry_index: usize,
    ) -> Option<usize> {
        self.entries.entry_row_count(source, entry_index)
    }

    /// Return committed transcript entry indexes intersecting a row range.
    #[must_use]
    pub fn visible_transcript_entry_indexes(&self, top_row: usize, height: u16) -> BTreeSet<usize> {
        self.entries
            .visible_lines_from_top(top_row, height)
            .into_iter()
            .filter_map(|line| {
                (line.source == VisibleTranscriptSource::Transcript).then_some(line.entry_index)
            })
            .collect()
    }

    /// Return a stable pointer to the first cached row of a transcript entry for cache-reuse tests.
    #[cfg(test)]
    #[must_use]
    pub fn transcript_entry_row_ptr(&self, entry_index: usize) -> Option<*const Line> {
        let start = self.entry_start_row(VisibleTranscriptSource::Transcript, entry_index)?;
        let line = self.line_at_row(start)?;
        self.line(line).map(std::ptr::from_ref)
    }
}

/// Specification used to synchronize transcript layout cache.
pub struct TranscriptLayoutSpec<TS, TR, TI, PS, PR, HS, HR, R> {
    /// Render width.
    pub width: u16,
    /// Fingerprint for all layout-affecting inputs.
    pub fingerprint: TranscriptLayoutFingerprint,
    /// Structural fingerprint excluding isolated adapter-owned visual revisions.
    pub structural_fingerprint: TranscriptLayoutFingerprint,
    /// Current committed transcript item count.
    pub transcript_len: usize,
    /// Current pending submission count.
    pub pending_len: usize,
    /// Return signature for a committed transcript item.
    pub transcript_signature: TS,
    /// Render rows for a committed transcript item.
    pub transcript_rows: TR,
    /// Return the generic invocation id owning a transcript item, when any.
    pub transcript_invocation_id: TI,
    /// Return signature for a pending submission.
    pub pending_signature: PS,
    /// Render rows for a pending submission.
    pub pending_rows: PR,
    /// Return optional older-history banner signature.
    pub history_banner_signature: HS,
    /// Render older-history banner rows.
    pub history_banner_rows: HR,
    /// Return whether all cached rows must be discarded.
    pub reset: R,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[allow(clippy::type_complexity)]
    fn spec(
        fingerprint: &str,
        transcript_len: usize,
    ) -> TranscriptLayoutSpec<
        impl Fn(usize) -> TranscriptLayoutSignature,
        impl Fn(usize) -> TranscriptLayoutRows,
        impl Fn(usize) -> Option<String>,
        impl Fn(usize) -> TranscriptLayoutSignature,
        impl Fn(usize) -> TranscriptLayoutRows,
        impl FnOnce() -> Option<TranscriptLayoutSignature>,
        impl FnOnce() -> TranscriptLayoutRows,
        impl FnOnce() -> bool,
    > {
        TranscriptLayoutSpec {
            width: 80,
            fingerprint: TranscriptLayoutFingerprint::new(fingerprint.to_owned()),
            structural_fingerprint: TranscriptLayoutFingerprint::new(format!(
                "structural-{fingerprint}"
            )),
            transcript_len,
            pending_len: 0,
            transcript_signature: |index| TranscriptLayoutSignature::new(format!("item-{index}")),
            transcript_rows: |index| vec![Line::from(format!("row-{index}"))].into(),
            transcript_invocation_id: |_| None,
            pending_signature: |index| TranscriptLayoutSignature::new(format!("pending-{index}")),
            pending_rows: |_| Vec::new().into(),
            history_banner_signature: || None,
            history_banner_rows: || Vec::new().into(),
            reset: || false,
        }
    }

    #[test]
    fn width_change_rebuilds_cached_rows_at_new_height() {
        let mut cache = TranscriptLayoutCache::default();
        let rows_for_width = |width: u16| {
            let row_count = if width >= 40 { 1 } else { 3 };
            move |_| {
                (0..row_count)
                    .map(|row| Line::from(format!("row-{row}")))
                    .collect::<Vec<_>>()
                    .into()
            }
        };
        cache.sync(TranscriptLayoutSpec {
            width: 80,
            fingerprint: TranscriptLayoutFingerprint::new("wide".to_owned()),
            structural_fingerprint: TranscriptLayoutFingerprint::new("wide-structure".to_owned()),
            transcript_len: 1,
            pending_len: 0,
            transcript_signature: |_| TranscriptLayoutSignature::new("item-wide".to_owned()),
            transcript_rows: rows_for_width(80),
            transcript_invocation_id: |_| None,
            pending_signature: |_| unreachable!("no pending"),
            pending_rows: |_| unreachable!("no pending"),
            history_banner_signature: || None,
            history_banner_rows: || Vec::new().into(),
            reset: || false,
        });
        assert_eq!(cache.total_rows(), 1);

        let stats = cache.sync(TranscriptLayoutSpec {
            width: 20,
            fingerprint: TranscriptLayoutFingerprint::new("narrow".to_owned()),
            structural_fingerprint: TranscriptLayoutFingerprint::new("narrow-structure".to_owned()),
            transcript_len: 1,
            pending_len: 0,
            transcript_signature: |_| TranscriptLayoutSignature::new("item-narrow".to_owned()),
            transcript_rows: rows_for_width(20),
            transcript_invocation_id: |_| None,
            pending_signature: |_| unreachable!("no pending"),
            pending_rows: |_| unreachable!("no pending"),
            history_banner_signature: || None,
            history_banner_rows: || Vec::new().into(),
            reset: || false,
        });

        assert_eq!(stats.invalidation, TranscriptLayoutInvalidation::Width);
        assert_eq!(stats.rows_regenerated, 3);
        assert_eq!(cache.total_rows(), 3);
    }

    #[test]
    fn sync_stats_report_scans_and_rebuilds() {
        let mut cache = TranscriptLayoutCache::default();

        let initial = cache.sync(spec("one", 10));
        assert_eq!(initial.invalidation, TranscriptLayoutInvalidation::Width);
        assert_eq!(initial.entries_scanned, 10);
        assert_eq!(initial.signatures_changed, 10);
        assert_eq!(initial.entries_rebuilt, 10);
        assert_eq!(initial.rows_regenerated, 10);

        let unchanged = cache.sync(spec("two", 10));
        assert_eq!(
            unchanged.invalidation,
            TranscriptLayoutInvalidation::Incremental
        );
        assert_eq!(unchanged.entries_scanned, 10);
        assert_eq!(unchanged.signatures_changed, 0);
        assert_eq!(unchanged.entries_rebuilt, 0);
        assert_eq!(unchanged.rows_regenerated, 0);
    }

    #[test]
    fn targeted_visual_sync_updates_row_index_without_scanning_siblings() {
        let mut cache = TranscriptLayoutCache::default();
        cache.sync(TranscriptLayoutSpec {
            width: 80,
            fingerprint: TranscriptLayoutFingerprint::new("initial".to_owned()),
            structural_fingerprint: TranscriptLayoutFingerprint::new("structure".to_owned()),
            transcript_len: 3,
            pending_len: 0,
            transcript_signature: |index| TranscriptLayoutSignature::new(format!("item-{index}")),
            transcript_rows: |_| vec![Line::from("row")].into(),
            transcript_invocation_id: |index| Some(format!("call-{index}")),
            pending_signature: |index| TranscriptLayoutSignature::new(format!("pending-{index}")),
            pending_rows: |_| Vec::new().into(),
            history_banner_signature: || None,
            history_banner_rows: || Vec::new().into(),
            reset: || false,
        });
        let stats = cache.sync_visuals(
            TranscriptLayoutFingerprint::new("updated".to_owned()),
            &BTreeSet::from(["call-1".to_owned()]),
            |index| TranscriptLayoutSignature::new(format!("updated-{index}")),
            |_| vec![Line::from("one"), Line::from("two"), Line::from("three")].into(),
        );

        assert_eq!(stats.entries_scanned, 1);
        assert_eq!(stats.entries_rebuilt, 1);
        assert_eq!(stats.rows_regenerated, 3);
        assert_eq!(cache.total_rows(), 5);
        assert_eq!(
            cache.entry_start_row(VisibleTranscriptSource::Transcript, 2),
            Some(4)
        );
        let visible = cache.visible_lines_from_top(3, 2);
        assert_eq!(visible.len(), 2);
        assert_eq!(visible[0].entry_index, 1);
        assert_eq!(visible[0].row_in_entry, 2);
        assert_eq!(visible[1].entry_index, 2);
        assert_eq!(visible[1].row_in_entry, 0);
    }

    #[test]
    fn item_only_update_preserves_row_cache_for_unaffected_entries() {
        let mut cache = TranscriptLayoutCache::default();
        let rebuilds = std::cell::Cell::new(0_usize);
        cache.sync(TranscriptLayoutSpec {
            width: 80,
            fingerprint: TranscriptLayoutFingerprint::new("initial".to_owned()),
            structural_fingerprint: TranscriptLayoutFingerprint::new("structure".to_owned()),
            transcript_len: 4,
            pending_len: 0,
            transcript_signature: |index| TranscriptLayoutSignature::new(format!("item-{index}")),
            transcript_rows: |_| vec![Line::from("row")].into(),
            transcript_invocation_id: |_| None,
            pending_signature: |_| unreachable!("no pending entries"),
            pending_rows: |_| unreachable!("no pending entries"),
            history_banner_signature: || None,
            history_banner_rows: || Vec::new().into(),
            reset: || false,
        });
        assert_eq!(cache.total_rows(), 4);

        // Entry 2 is the only changed entry: entry 1 stands in for an interleaved ephemeral
        // notice that must keep its cached rows while a canonical sibling is regenerated.
        let stats = cache.sync_transcript_entries(
            TranscriptLayoutFingerprint::new("item-updated".to_owned()),
            &BTreeSet::from([2_usize]),
            |index| {
                if index == 2 {
                    TranscriptLayoutSignature::new("item-2-changed".to_owned())
                } else {
                    TranscriptLayoutSignature::new(format!("item-{index}"))
                }
            },
            |index| {
                rebuilds.set(rebuilds.get().saturating_add(1));
                assert_eq!(index, 2, "only the damaged entry may regenerate rows");
                vec![Line::from("changed one"), Line::from("changed two")].into()
            },
        );

        assert_eq!(stats.entries_scanned, 1);
        assert_eq!(stats.entries_rebuilt, 1);
        assert_eq!(stats.rows_regenerated, 2);
        assert_eq!(rebuilds.get(), 1);
        assert_eq!(cache.total_rows(), 5);
        assert_eq!(
            cache.entry_start_row(VisibleTranscriptSource::Transcript, 1),
            Some(1),
            "the entry before the damaged one keeps its cached position"
        );
        assert_eq!(
            cache.entry_start_row(VisibleTranscriptSource::Transcript, 3),
            Some(4),
            "later entries shift by the row delta without being rebuilt"
        );
    }

    #[test]
    fn removing_pending_entry_removes_its_cached_rows() {
        let mut cache = TranscriptLayoutCache::default();
        cache.sync(TranscriptLayoutSpec {
            width: 80,
            fingerprint: TranscriptLayoutFingerprint::new("with-pending".to_owned()),
            structural_fingerprint: TranscriptLayoutFingerprint::new("structure-with".to_owned()),
            transcript_len: 1,
            pending_len: 1,
            transcript_signature: |_| TranscriptLayoutSignature::new("item".to_owned()),
            transcript_rows: |_| vec![Line::from("committed")].into(),
            transcript_invocation_id: |_| None,
            pending_signature: |_| TranscriptLayoutSignature::new("pending".to_owned()),
            pending_rows: |_| vec![Line::from("pending-one"), Line::from("pending-two")].into(),
            history_banner_signature: || None,
            history_banner_rows: || Vec::new().into(),
            reset: || false,
        });
        assert_eq!(cache.total_rows(), 3);

        cache.sync(TranscriptLayoutSpec {
            width: 80,
            fingerprint: TranscriptLayoutFingerprint::new("without-pending".to_owned()),
            structural_fingerprint: TranscriptLayoutFingerprint::new(
                "structure-without".to_owned(),
            ),
            transcript_len: 1,
            pending_len: 0,
            transcript_signature: |_| TranscriptLayoutSignature::new("item".to_owned()),
            transcript_rows: |_| vec![Line::from("committed")].into(),
            transcript_invocation_id: |_| None,
            pending_signature: |_| unreachable!("no pending entries"),
            pending_rows: |_| unreachable!("no pending entries"),
            history_banner_signature: || None,
            history_banner_rows: || Vec::new().into(),
            reset: || false,
        });

        assert_eq!(cache.total_rows(), 1);
        assert_eq!(
            cache
                .visible_lines_from_top(0, 10)
                .into_iter()
                .filter_map(|visible| cache.line(visible))
                .map(|line| line
                    .spans
                    .iter()
                    .map(|span| span.content.as_str())
                    .collect::<String>())
                .collect::<Vec<_>>(),
            ["committed"]
        );
    }

    #[test]
    fn first_entry_navigation_crosses_indexed_sections() {
        let mut cache = TranscriptLayoutCache::default();
        cache.sync(TranscriptLayoutSpec {
            width: 80,
            fingerprint: TranscriptLayoutFingerprint::new("initial".to_owned()),
            structural_fingerprint: TranscriptLayoutFingerprint::new("structure".to_owned()),
            transcript_len: 1,
            pending_len: 1,
            transcript_signature: |_| TranscriptLayoutSignature::new("item".to_owned()),
            transcript_rows: |_| vec![Line::from("a"), Line::from("b")].into(),
            transcript_invocation_id: |_| None,
            pending_signature: |_| TranscriptLayoutSignature::new("pending".to_owned()),
            pending_rows: |_| vec![Line::from("pending")].into(),
            history_banner_signature: || Some(TranscriptLayoutSignature::new("history".to_owned())),
            history_banner_rows: || vec![Line::from("history")].into(),
            reset: || false,
        });

        assert_eq!(cache.first_entry_start_at_or_after_row(0), Some(0));
        assert_eq!(cache.first_entry_start_at_or_after_row(2), Some(3));
        assert_eq!(cache.first_entry_start_at_or_after_row(3), Some(3));
    }

    #[test]
    fn transcript_viewport_reaches_before_through_and_after_logical_interaction_span() {
        let mut cache = TranscriptLayoutCache::default();
        cache.sync(TranscriptLayoutSpec {
            width: 80,
            fingerprint: TranscriptLayoutFingerprint::new("interaction-span".to_owned()),
            structural_fingerprint: TranscriptLayoutFingerprint::new(
                "interaction-span-structure".to_owned(),
            ),
            transcript_len: 3,
            pending_len: 0,
            transcript_signature: |index| TranscriptLayoutSignature::new(format!("item-{index}")),
            transcript_rows: |index| match index {
                0 => vec![Line::from("before")].into(),
                1 => TranscriptLayoutRows::BlankSpan(20),
                2 => vec![Line::from("after")].into(),
                _ => unreachable!("three transcript entries"),
            },
            transcript_invocation_id: |_| None,
            pending_signature: |_| unreachable!("no pending entries"),
            pending_rows: |_| unreachable!("no pending entries"),
            history_banner_signature: || None,
            history_banner_rows: || Vec::new().into(),
            reset: || false,
        });

        let top = cache.visible_lines_from_top(0, 4);
        assert_eq!((top[0].entry_index, top[0].row_in_entry), (0, 0));
        assert_eq!((top[1].entry_index, top[1].row_in_entry), (1, 0));

        let middle = cache.visible_lines_from_top(8, 4);
        assert!(
            middle
                .iter()
                .all(|line| line.entry_index == 1 && (7..11).contains(&line.row_in_entry))
        );

        let bottom = cache.visible_lines_from_top(19, 4);
        assert_eq!(
            bottom
                .iter()
                .map(|line| (line.entry_index, line.row_in_entry))
                .collect::<Vec<_>>(),
            [(1, 18), (1, 19), (2, 0)]
        );
        assert!(cache.visible_lines_from_top(22, 4).is_empty());
    }

    #[test]
    fn cache_hits_are_recorded_without_scanning() {
        let mut cache = TranscriptLayoutCache::default();
        cache.record_cache_hit(7);

        assert_eq!(
            cache.drain_sync_stats(),
            vec![TranscriptLayoutSyncStats::cache_hit(7)]
        );
        assert!(cache.drain_sync_stats().is_empty());
    }
}