vtcode-ui 0.183.2

Unified UI crate for VT Code: design system, theme registry, and TUI framework
Documentation
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
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
use super::{
    Action, PLACEHOLDER_COLOR, Session, measure_text_width, ratatui_color_from_ansi, ratatui_style_from_inline,
};
use crate::tui::config::constants::ui;
use crate::tui::ui::tui::types::InlineTextStyle;
use anstyle::{Color as AnsiColorEnum, Effects};
use ratatui::{
    buffer::Buffer,
    prelude::*,
    widgets::{Block, Padding, Paragraph, Wrap},
};

mod helpers;
mod tokenizer;

pub(crate) use helpers::{InputWidgetData, should_track_compact_paste, status_requires_shimmer};
use helpers::{
    byte_index_to_char_index, char_index_to_byte_index, compact_image_label, compact_image_placeholders,
    compact_paste_range_preview, display_width_for_char_range, generic_large_input_preview,
    inline_prompt_suggestion_suffix, render_fake_cursor,
};

pub(super) use tokenizer::{InputToken, InputTokenKind, tokenize_input};

/// Paint pre-wrapped lines into `area` without Paragraph wrapping.
/// `base` is the Paragraph base style; span styles patch on top.
fn paint_pre_wrapped_text(text: &Text<'static>, area: Rect, buf: &mut Buffer, base: Style) {
    for (row, line) in text.lines.iter().take(usize::from(area.height)).enumerate() {
        let y = area.y + row as u16;
        let mut x = area.x;
        for span in &line.spans {
            if x >= area.right() {
                break;
            }
            let merged = base.patch(span.style);
            let (end_x, _) =
                buf.set_stringn(x, y, span.content.as_ref(), area.right().saturating_sub(x) as usize, merged);
            x = end_x;
        }
    }
}

fn paint_pre_wrapped_line(line: &Line<'static>, area: Rect, buf: &mut Buffer, base: Style) {
    if area.width == 0 || area.height == 0 {
        return;
    }
    let mut x = area.x;
    let y = area.y;
    for span in &line.spans {
        if x >= area.right() {
            break;
        }
        let merged = base.patch(span.style);
        let (end_x, _) = buf.set_stringn(x, y, span.content.as_ref(), area.right().saturating_sub(x) as usize, merged);
        x = end_x;
    }
}
use tui_shimmer::shimmer_spans_with_style_at_phase;
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

use super::utils::line_truncation::truncate_line_with_ellipsis_if_overflow;

pub(super) struct InputRender {
    pub(super) text: Text<'static>,
    pub(super) cursor_x: u16,
    pub(super) cursor_y: u16,
}

#[derive(Default)]
pub(super) struct InputStatusLine {
    pub(super) line: Line<'static>,
    pub(super) background_hits: Vec<(u16, u16)>,
    pub(super) progress_start: u16,
    pub(super) progress_columns: u16,
}

pub(super) struct CompactInputPreview {
    pub(super) before: String,
    pub(super) placeholder: String,
    pub(super) after_lines: Vec<String>,
}

impl CompactInputPreview {
    fn line_count(&self) -> usize {
        self.after_lines.len().max(1)
    }
}

#[derive(Default)]
pub(super) struct InputLineBuffer {
    pub(super) prefix: String,
    pub(super) text: String,
    pub(super) prefix_width: u16,
    pub(super) text_width: u16,
    /// Character index in the original input where this buffer's text starts.
    pub(super) char_start: usize,
}

impl InputLineBuffer {
    fn new(prefix: String, prefix_width: u16, char_start: usize) -> Self {
        Self {
            prefix,
            text: String::new(),
            prefix_width,
            text_width: 0,
            char_start,
        }
    }
}

pub(super) struct InputLayout {
    pub(super) buffers: Vec<InputLineBuffer>,
    pub(super) cursor_line_idx: usize,
    pub(super) cursor_column: u16,
}

/// Visual-row geometry of the composer input.
///
/// Dimension key: `total_rows` is the soft-wrapped row count (at least 1);
/// `cursor_row` is the 0-based row holding the cursor.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct InputVisualGeometry {
    pub(crate) total_rows: usize,
    pub(crate) cursor_row: usize,
}

const SHELL_MODE_BORDER_TITLE: &str = " ! Shell mode ";
const SHELL_MODE_STATUS_HINT: &str = "Shell mode (!): direct command execution";

impl Session {
    /// Composer-area acknowledgement for queued follow-ups while a turn runs.
    ///
    /// The transcript queue overlay can be scrolled away (or covered by a live
    /// progress row) while the agent is working, so the composer's own status
    /// line also reports the pending count. Hidden while idle (the overlay
    /// already shows an idle queue); superseded by a copy notification or the
    /// active turn's own live phase status, and placed ahead of configured
    /// context and the generic "Thinking" label because a queued entry is the
    /// freshest user action.
    pub(super) fn queued_input_status_text(&self) -> Option<String> {
        let pending = self.queued_inputs.len();
        if pending == 0 || !self.is_running_activity() || self.copy_notification_text().is_some() {
            return None;
        }
        // One queued item renders the truncated text so the user gets direct
        // confirmation of what was captured; several fall back to a count.
        if pending == 1 {
            const PREVIEW_CHARS: usize = 40;
            let entry = &self.queued_inputs[0];
            let flattened = entry.replace(['\r', '\n'], " ");
            let trimmed = flattened.trim();
            let preview: String = trimmed.chars().take(PREVIEW_CHARS).collect();
            let ellipsis = if trimmed.chars().count() > PREVIEW_CHARS {
                "…"
            } else {
                ""
            };
            return Some(format!("Queued: {preview}{ellipsis} — runs after this turn"));
        }
        Some(format!("{pending} turns queued — running after this turn"))
    }

    #[cfg_attr(feature = "profiling", hotpath::measure)]
    pub(crate) fn render_input(&mut self, frame: &mut Frame<'_>, area: Rect) {
        if area.height == 0 {
            self.set_input_area(None);
            self.set_background_indicator_hits(Vec::new());
            return;
        }

        let mut input_area = area;
        let mut status_area = None;
        if area.height > ui::INLINE_INPUT_STATUS_HEIGHT {
            let block_height = area.height.saturating_sub(ui::INLINE_INPUT_STATUS_HEIGHT);
            input_area.height = block_height.max(1);
            status_area = Some(Rect::new(area.x, area.y + block_height, area.width, ui::INLINE_INPUT_STATUS_HEIGHT));
        }

        let background_style = self.styles.input_background_style();
        let shell_mode_title = self.shell_mode_border_title();
        let active_subagent_title = self.active_subagent_input_title();
        let active_subagent_border_style = self.active_subagent_input_border_style();
        let mut block = if shell_mode_title.is_some() || active_subagent_title.is_some() {
            Block::bordered()
        } else {
            Block::new()
        };
        block = block.style(background_style).padding(self.input_block_padding());
        if shell_mode_title.is_some() || active_subagent_title.is_some() {
            block = block.border_set(super::terminal_capabilities::get_border_set()).border_style(
                active_subagent_border_style.unwrap_or_else(|| self.styles.accent_style().add_modifier(Modifier::BOLD)),
            );
        }
        if let Some(title) = shell_mode_title {
            block = block.title_top(Line::from(title).left_aligned());
        }
        if let Some(title) = active_subagent_title {
            block = block.title_top(title);
        }
        let inner = block.inner(input_area);
        self.set_input_area(Some(inner));
        let input_render = self.build_input_render(inner.width, inner.height);
        // Input rows are already soft-wrapped to `inner.width` by `input_layout`.
        // Paint via set_span — avoid Paragraph wrap every frame (hotpath ~5KB).
        frame.render_widget(block, input_area);
        {
            let buf = frame.buffer_mut();
            buf.set_style(inner, background_style);
            paint_pre_wrapped_text(&input_render.text, inner, buf, background_style);
        }
        self.apply_input_selection_highlight(frame.buffer_mut(), inner);
        // Auto-copy on select only when enabled; otherwise the selection stays
        // until the user copies manually with Ctrl+C (or Cmd+C).
        if self.fullscreen.interaction.copy_on_select && self.input_manager.selection_needs_copy() {
            let _ = self.copy_input_selection_to_clipboard();
        }

        if self.cursor_should_be_visible() && inner.width > 0 && inner.height > 0 {
            let cursor_x = input_render.cursor_x.min(inner.width.saturating_sub(1)).saturating_add(inner.x);
            let cursor_y = input_render
                .cursor_y
                .min(inner.height.saturating_sub(1))
                .saturating_add(inner.y);
            if self.use_fake_cursor() {
                render_fake_cursor(frame.buffer_mut(), cursor_x, cursor_y);
            } else {
                frame.set_cursor_position(Position::new(cursor_x, cursor_y));
            }
        }

        if let Some(status_area) = status_area {
            let status = self.build_input_status_line(status_area.width).unwrap_or_default();
            {
                let buf = frame.buffer_mut();
                buf.set_style(status_area, self.styles.default_style());
                paint_pre_wrapped_line(&status.line, status_area, buf, self.styles.default_style());
            }
            if status.progress_columns > 0 {
                let feedback_area =
                    Rect::new(status_area.x + status.progress_start, status_area.y, status.progress_columns, 1);
                self.set_progress_feedback_area(feedback_area.intersection(frame.area()));
            }
            let hits = status
                .background_hits
                .into_iter()
                .map(|(start, end)| {
                    Rect::new(status_area.x.saturating_add(start), status_area.y, end.saturating_sub(start), 1)
                })
                .collect();
            self.set_background_indicator_hits(hits);
        } else {
            self.set_background_indicator_hits(Vec::new());
        }
    }

    pub(crate) fn desired_input_lines(&self, inner_width: u16) -> u16 {
        if inner_width == 0 {
            return 1;
        }

        if self.input_compact_mode && self.input_manager.cursor() == self.input_manager.content().len() {
            if let Some(preview) = self.input_compact_preview() {
                return preview.line_count().min(ui::INLINE_INPUT_MAX_LINES.max(1)) as u16;
            }
            if self.input_compact_placeholder().is_some() {
                return 1;
            }
        }

        if self.input_manager.content().is_empty() {
            return 1;
        }

        let prompt_width = UnicodeWidthStr::width(self.prompt_prefix.as_str()) as u16;
        let prompt_display_width = prompt_width.min(inner_width);
        let layout = self.input_layout(inner_width, prompt_display_width);
        let line_count = layout.buffers.len().max(1);
        let capped = line_count.min(ui::INLINE_INPUT_MAX_LINES.max(1));
        capped as u16
    }

    pub(crate) fn apply_input_height(&mut self, height: u16) {
        let resolved = height.max(Self::input_block_height_for_lines(1));
        if self.input_height != resolved {
            self.input_height = resolved;
            self.recalculate_transcript_rows();
        }
    }

    pub(crate) fn input_block_height_for_lines(lines: u16) -> u16 {
        lines.max(1).saturating_add(ui::INLINE_INPUT_PADDING_VERTICAL.saturating_mul(2))
    }

    pub(crate) fn input_block_extra_height(&self) -> u16 {
        if self.active_subagent_input_title().is_some() && !self.input_uses_shell_prefix() {
            2
        } else {
            0
        }
    }

    fn input_layout(&self, width: u16, prompt_display_width: u16) -> InputLayout {
        let indent_prefix = " ".repeat(prompt_display_width as usize);
        let mut buffers = vec![InputLineBuffer::new(
            self.prompt_prefix.clone(),
            prompt_display_width,
            0,
        )];
        let secure_prompt_active = self.secure_prompt_active();
        let mut cursor_line_idx = 0usize;
        let mut cursor_column = prompt_display_width;
        let input_content = self.input_manager.content();
        let cursor_pos = self.input_manager.cursor();
        let mut cursor_set = cursor_pos == 0;
        let mut char_idx: usize = 0;

        for (idx, ch) in input_content.char_indices() {
            if !cursor_set
                && cursor_pos == idx
                && let Some(current) = buffers.last()
            {
                cursor_line_idx = buffers.len() - 1;
                cursor_column = current.prefix_width + current.text_width;
                cursor_set = true;
            }

            if ch == '\n' {
                let end = idx + ch.len_utf8();
                char_idx += 1;
                buffers.push(InputLineBuffer::new(indent_prefix.clone(), prompt_display_width, char_idx));
                if !cursor_set && cursor_pos == end {
                    cursor_line_idx = buffers.len() - 1;
                    cursor_column = prompt_display_width;
                    cursor_set = true;
                }
                continue;
            }

            let display_ch = if secure_prompt_active { '•' } else { ch };
            let char_width = UnicodeWidthChar::width(display_ch).unwrap_or(0) as u16;

            if let Some(current) = buffers.last_mut() {
                let capacity = width.saturating_sub(current.prefix_width);
                if capacity > 0 && current.text_width + char_width > capacity && !current.text.is_empty() {
                    buffers.push(InputLineBuffer::new(indent_prefix.clone(), prompt_display_width, char_idx));
                }
            }

            if let Some(current) = buffers.last_mut() {
                current.text.push(display_ch);
                current.text_width = current.text_width.saturating_add(char_width);
            }

            char_idx += 1;

            let end = idx + ch.len_utf8();
            if !cursor_set
                && cursor_pos == end
                && let Some(current) = buffers.last()
            {
                cursor_line_idx = buffers.len() - 1;
                cursor_column = current.prefix_width + current.text_width;
                cursor_set = true;
            }
        }

        if !cursor_set && let Some(current) = buffers.last() {
            cursor_line_idx = buffers.len() - 1;
            cursor_column = current.prefix_width + current.text_width;
        }

        InputLayout { buffers, cursor_line_idx, cursor_column }
    }

    pub(super) fn visible_input_window(&self, width: u16, height: u16) -> (InputLayout, usize, usize) {
        let prompt_width = UnicodeWidthStr::width(self.prompt_prefix.as_str()) as u16;
        let prompt_display_width = prompt_width.min(width);
        let layout = self.input_layout(width, prompt_display_width);
        let total_lines = layout.buffers.len();
        let visible_limit = height.max(1).min(ui::INLINE_INPUT_MAX_LINES as u16) as usize;
        let mut start = total_lines.saturating_sub(visible_limit);
        if layout.cursor_line_idx < start {
            start = layout.cursor_line_idx.saturating_sub(visible_limit - 1);
        }
        let end = (start + visible_limit).min(total_lines);
        (layout, start, end)
    }

    /// Visual-row geometry of the composer.
    ///
    /// Rows are soft-wrapped visual rows from [`Session::input_layout`], not
    /// logical `\n` lines: a long single-line draft that wraps on screen
    /// spans multiple visual rows. Returns `None` before the first render
    /// (no input area yet) or for a zero-width area.
    pub(crate) fn input_visual_geometry(&self) -> Option<InputVisualGeometry> {
        let area = self.input_area()?;
        if area.width == 0 {
            return None;
        }
        let prompt_width = UnicodeWidthStr::width(self.prompt_prefix.as_str()) as u16;
        let layout = self.input_layout(area.width, prompt_width.min(area.width));
        Some(InputVisualGeometry {
            total_rows: layout.buffers.len().max(1),
            cursor_row: layout.cursor_line_idx,
        })
    }

    /// Whether the composer spans more than one visual row.
    ///
    /// Falls back to logical lines before the first render (no input area).
    pub(crate) fn is_multi_row_composer(&self) -> bool {
        match self.input_visual_geometry() {
            Some(geometry) => geometry.total_rows > 1,
            None => !self.input_manager.is_single_line(),
        }
    }

    /// Move the cursor up one visual (soft-wrapped) row.
    ///
    /// Returns `true` when the cursor moved, `false` at the first row or
    /// when the input area is unknown.
    pub(crate) fn move_cursor_up_within_visual(&mut self) -> bool {
        self.move_cursor_visual_rows(-1)
    }

    /// Move the cursor down one visual (soft-wrapped) row.
    ///
    /// Returns `true` when the cursor moved, `false` at the last row or
    /// when the input area is unknown.
    pub(crate) fn move_cursor_down_within_visual(&mut self) -> bool {
        self.move_cursor_visual_rows(1)
    }

    fn move_cursor_visual_rows(&mut self, delta: isize) -> bool {
        let area = match self.input_area() {
            Some(area) if area.width > 0 => area,
            _ => return false,
        };
        let prompt_width = UnicodeWidthStr::width(self.prompt_prefix.as_str()) as u16;
        let layout = self.input_layout(area.width, prompt_width.min(area.width));
        let total = layout.buffers.len();
        if total == 0 {
            return false;
        }
        let current = layout.cursor_line_idx.min(total - 1);
        let Some(target_idx) = current.checked_add_signed(delta) else {
            return false;
        };
        if target_idx >= total || target_idx == current {
            return false;
        }
        let desired = layout.cursor_column.saturating_sub(layout.buffers[current].prefix_width);
        let target = &layout.buffers[target_idx];
        let mut acc = 0u16;
        let mut offset = 0usize;
        for ch in target.text.chars() {
            if acc >= desired {
                break;
            }
            acc = acc.saturating_add(UnicodeWidthChar::width(ch).unwrap_or(0) as u16);
            offset += 1;
        }
        let char_index = target.char_start.saturating_add(offset);
        self.input_manager
            .set_cursor(char_index_to_byte_index(self.input_manager.content(), char_index));
        true
    }

    /// Test-only entry that exercises the fingerprint cache.
    #[cfg(test)]
    pub(super) fn build_input_render_for_test(&mut self, width: u16, height: u16) -> InputRender {
        self.build_input_render(width, height)
    }

    fn apply_input_selection_highlight(&self, buf: &mut Buffer, area: Rect) {
        let Some((selection_start, selection_end)) = self.input_manager.selection_range() else {
            return;
        };
        if area.width == 0 || area.height == 0 || selection_start == selection_end {
            return;
        }

        let (layout, start, end) = self.visible_input_window(area.width, area.height);
        let selection_start_char = byte_index_to_char_index(self.input_manager.content(), selection_start);
        let selection_end_char = byte_index_to_char_index(self.input_manager.content(), selection_end);

        for (row_offset, buffer) in layout.buffers[start..end].iter().enumerate() {
            let line_char_start = buffer.char_start;
            let line_char_end = buffer.char_start + buffer.text.chars().count();
            let highlight_start = selection_start_char.max(line_char_start);
            let highlight_end = selection_end_char.min(line_char_end);
            if highlight_start >= highlight_end {
                continue;
            }

            let local_start = highlight_start.saturating_sub(line_char_start);
            let local_end = highlight_end.saturating_sub(line_char_start);
            let start_x = area
                .x
                .saturating_add(buffer.prefix_width)
                .saturating_add(display_width_for_char_range(&buffer.text, local_start));
            let end_x = area
                .x
                .saturating_add(buffer.prefix_width)
                .saturating_add(display_width_for_char_range(&buffer.text, local_end));
            let y = area.y.saturating_add(row_offset as u16);

            for x in start_x..end_x.min(area.x.saturating_add(area.width)) {
                if let Some(cell) = buf.cell_mut((x, y)) {
                    let mut style = cell.style();
                    style = style.add_modifier(Modifier::REVERSED);
                    cell.set_style(style);
                    if cell.symbol().is_empty() {
                        cell.set_symbol(" ");
                    }
                }
            }
        }
    }

    pub(crate) fn cursor_index_for_input_point(&self, column: u16, row: u16) -> Option<usize> {
        let area = self.input_area()?;
        if row < area.y
            || row >= area.y.saturating_add(area.height)
            || column < area.x
            || column >= area.x.saturating_add(area.width)
        {
            return None;
        }

        if self.input_compact_mode
            && self.input_manager.cursor() == self.input_manager.content().len()
            && self.input_compact_placeholder().is_some()
        {
            return Some(self.input_manager.content().len());
        }

        let relative_row = row.saturating_sub(area.y);
        let relative_column = column.saturating_sub(area.x);
        let (layout, start, end) = self.visible_input_window(area.width, area.height);
        if start >= end {
            return Some(0);
        }

        let line_index = (start + usize::from(relative_row)).min(end.saturating_sub(1));
        let buffer = layout.buffers.get(line_index)?;
        if relative_column <= buffer.prefix_width {
            return Some(char_index_to_byte_index(self.input_manager.content(), buffer.char_start));
        }

        let target_width = relative_column.saturating_sub(buffer.prefix_width);
        let mut consumed_width = 0u16;
        let mut char_offset = 0usize;
        for ch in buffer.text.chars() {
            let ch_width = UnicodeWidthChar::width(ch).unwrap_or(0) as u16;
            let next_width = consumed_width.saturating_add(ch_width);
            if target_width < next_width {
                break;
            }
            consumed_width = next_width;
            char_offset += 1;
        }

        let char_index = buffer.char_start.saturating_add(char_offset);
        Some(char_index_to_byte_index(self.input_manager.content(), char_index))
    }

    pub(crate) fn input_compact_placeholder(&self) -> Option<String> {
        let content = self.input_manager.content();
        let trimmed = content.trim();
        if trimmed.is_empty() {
            return None;
        }

        if let Some(label) = compact_image_label(trimmed) {
            return Some(format!("[Image: {label}]"));
        }

        if let Some(preview) = self.input_compact_preview() {
            return Some(preview.placeholder);
        }

        if let Some(compact) = compact_image_placeholders(content) {
            // `compact_image_placeholders` returns the full content with image
            // paths substituted. Never render it unbounded: large inputs are
            // already collapsed by `input_compact_preview` above, so this is
            // only a safety net for small embeds.
            if compact.chars().count() >= ui::INLINE_INPUT_COMPACT_CHAR_THRESHOLD {
                let char_count = content.chars().count();
                return Some(format!("[Pasted Content {char_count} chars]"));
            }
            return Some(compact);
        }

        None
    }

    pub(super) fn input_compact_preview(&self) -> Option<CompactInputPreview> {
        let content = self.input_manager.content();
        if let Some(preview) = compact_paste_range_preview(content, self.input_manager.compact_paste_range()) {
            return Some(preview);
        }

        generic_large_input_preview(content, self.input_manager.attachments().len())
    }

    pub(crate) fn visible_inline_prompt_suggestion_suffix(&self) -> Option<String> {
        if !self.input_enabled
            || self.has_active_overlay()
            || self.input_compact_mode
            || self.input_manager.cursor() != self.input_manager.content().len()
        {
            return None;
        }

        let suggestion = self.inline_prompt_suggestion.suggestion.as_deref()?;
        inline_prompt_suggestion_suffix(self.input_manager.content(), suggestion)
    }

    pub(crate) fn render_input_status_line(&self, width: u16) -> Option<Line<'static>> {
        self.render_input_status_line_with_hit(width).map(|(line, _hits)| line)
    }

    /// Status line plus column ranges (relative to the status area) of the
    /// clickable background indicator spans: the activity text and the
    /// `{key} background` hint only.
    pub(crate) fn render_input_status_line_with_hit(&self, width: u16) -> Option<(Line<'static>, Vec<(u16, u16)>)> {
        self.build_input_status_line(width)
            .map(|status| (status.line, status.background_hits))
    }

    fn input_uses_shell_prefix(&self) -> bool {
        self.input_manager.content().trim_start().starts_with('!')
    }

    pub(crate) fn input_block_padding(&self) -> Padding {
        if self.input_uses_shell_prefix() {
            Padding::new(0, 0, 0, 0)
        } else {
            Padding::new(
                ui::INLINE_INPUT_PADDING_HORIZONTAL,
                ui::INLINE_INPUT_PADDING_HORIZONTAL,
                ui::INLINE_INPUT_PADDING_VERTICAL,
                ui::INLINE_INPUT_PADDING_VERTICAL,
            )
        }
    }

    pub(crate) fn shell_mode_border_title(&self) -> Option<&'static str> {
        self.input_uses_shell_prefix().then_some(SHELL_MODE_BORDER_TITLE)
    }

    pub(crate) fn active_subagent_input_title(&self) -> Option<Line<'static>> {
        let badge = self.header_context.subagent_badges.first()?;
        let hidden = self.header_context.subagent_badges.len().saturating_sub(1);
        let label = if hidden == 0 {
            badge.text.clone()
        } else {
            format!("{} +{}", badge.text, hidden)
        };

        let mut style = ratatui_style_from_inline(&badge.style, self.theme.foreground);
        if badge.full_background {
            style = style.add_modifier(Modifier::BOLD);
        }

        Some(Line::from(Span::styled(format!(" {label} "), style)).right_aligned())
    }

    fn active_subagent_input_border_style(&self) -> Option<Style> {
        // Use the primary agent color if available, otherwise fall back to badge color.
        if let Some(color_style) =
            super::super::style::agent_color_style(self.header_context.primary_agent_color.as_deref(), Color::Magenta)
                .fg
        {
            return Some(self.styles.accent_style().fg(color_style).add_modifier(Modifier::BOLD));
        }

        let badge = self.header_context.subagent_badges.first()?;
        let mut title_style = ratatui_style_from_inline(&badge.style, self.theme.foreground);
        if badge.full_background {
            title_style = title_style.add_modifier(Modifier::BOLD);
        }

        let color = if badge.full_background {
            title_style.bg.or(title_style.fg)
        } else {
            title_style.fg.or(title_style.bg)
        }?;

        Some(self.styles.accent_style().fg(color).add_modifier(Modifier::BOLD))
    }

    /// Trimmed primary agent mode name, driving the persistent mode border/pill.
    fn primary_mode_name(&self) -> Option<&str> {
        self.header_context
            .primary_agent
            .as_deref()
            .map(str::trim)
            .filter(|name| !name.is_empty())
    }

    /// Mode pill for the input status line, reusing the header badge color.
    ///
    /// Returns `None` when no primary agent name is set so the default
    /// (modeless) status line is unchanged. The style resolves through the
    /// shared design-system `agent_color_style`, keeping the four mode hues
    /// distinct on both dark and light terminals.
    /// Resolved primary-agent mode color, sharing the header badge source.
    ///
    /// Returns `None` when no mode name is set so modeless chrome is unchanged.
    fn primary_mode_color(&self) -> Option<Color> {
        self.primary_mode_name()?;
        let fallback = self.theme.primary.map(ratatui_color_from_ansi).unwrap_or(Color::LightMagenta);
        super::super::style::agent_color_style(self.header_context.primary_agent_color.as_deref(), fallback).fg
    }

    pub(super) fn primary_mode_pill(&self) -> Option<(String, Style)> {
        let name = self.primary_mode_name()?;
        let color = self.primary_mode_color()?;
        let label = super::header::primary_agent_header_label(Some(name));
        let style = Style::default().fg(color).add_modifier(Modifier::BOLD);
        Some((format!("• {label}"), style))
    }

    pub(super) fn shell_mode_status_hint(&self) -> Option<&'static str> {
        self.input_uses_shell_prefix().then_some(SHELL_MODE_STATUS_HINT)
    }

    pub(super) fn local_agents_input_status_hint(&self) -> Option<String> {
        if self.input_uses_shell_prefix() || !self.input_manager.content().trim().is_empty() {
            // A foreground PTY keeps its background hint visible even with a
            // non-empty composer so users can discover the background
            // shortcut mid-command.
            return self.foreground_pty_background_hint();
        }

        if !self.has_local_agents() {
            return self.foreground_pty_background_hint();
        }

        Some(format!("↓ or Alt+S local agents · {} background", self.background_shortcut_label()))
    }

    /// Appends the local-agents hint spans. Returns the column range of the
    /// `{key} background` span only (relative to the start of the appended
    /// content) so click hit-testing ignores `Alt+S local agents` and separators.
    pub(super) fn append_background_hint_spans(
        spans: &mut Vec<Span<'static>>,
        hint: &str,
        key_label: &str,
        dim_style: Style,
        key_style: Style,
        label_style: Style,
    ) -> Option<(u16, u16)> {
        let mut appended_width = 0_u16;
        let mut key_hit: Option<(u16, u16)> = None;
        let mut push = |spans: &mut Vec<Span<'static>>, text: &str, style: Style, mark: bool| {
            let width = measure_text_width(text);
            let start = appended_width;
            let end = appended_width.saturating_add(width);
            if mark {
                key_hit = Some(match key_hit {
                    Some((s, e)) => (s.min(start), e.max(end)),
                    None => (start, end),
                });
            }
            appended_width = end;
            spans.push(Span::styled(text.to_owned(), style));
        };

        // PTY-only hint has the exact shape "{key} background".
        if let Some(prefix) = hint.strip_suffix(" background")
            && prefix == key_label
        {
            if !spans.is_empty() {
                push(spans, " · ", dim_style, false);
            }
            push(spans, key_label, key_style, true);
            push(spans, " background", label_style, true);
            return key_hit;
        }
        // Combined drawer hint has the exact shape
        // "↓ or Alt+S local agents · {key} background".
        if let Some(rest) = hint.strip_prefix("↓ or Alt+S local agents · ")
            && let Some(prefix) = rest.strip_suffix(" background")
            && prefix == key_label
        {
            if !spans.is_empty() {
                push(spans, " · ", dim_style, false);
            }
            push(spans, "↓ or ", label_style, false);
            push(spans, "Alt+S", key_style, false);
            push(spans, " local agents", label_style, false);
            push(spans, " · ", dim_style, false);
            push(spans, key_label, key_style, true);
            push(spans, " background", label_style, true);
            return key_hit;
        }
        if !spans.is_empty() {
            push(spans, " · ", dim_style, false);
        }
        // Unrecognized hint shape: render it dim but do not make it a hit
        // target. Only the known `{key} background` shapes are clickable.
        push(spans, hint, dim_style, false);
        key_hit
    }

    /// Builds the footer scroll indicator.
    ///
    /// Uses the inverted scroll model documented on `ScrollManager`:
    /// offset 0 is the bottom (live) edge and increasing offsets move toward
    /// older content at the top of the transcript.
    ///
    /// - At the bottom: no indicator at all.
    /// - While scrolled: `↑ {visible_top}/{total}` shows the top row position.
    /// - When new lines arrived while scrolled: `↓ {N} new` highlights the
    ///   pending content until the user returns to the bottom.
    /// - When scrolled up with a tracked change: appends
    ///   `⤓ Jump to last change [key]` hint.
    pub(super) fn build_scroll_indicator(&self) -> Option<String> {
        if !self.user_scrolled {
            return None;
        }

        // Defensive cap: passive clamps (resize, eviction) can shrink the
        // viewport without owning follow state, so unseen arrivals never
        // exceed the rows still below the view.
        let pending = self.pending_new_messages.min(self.scroll_manager.offset());
        let total = self.transcript_rows.max(1) as usize;
        let top = self.scroll_manager.offset().saturating_add(1).min(total);

        let mut label = if pending > 0 {
            format!("↓ {} new", pending)
        } else {
            format!("↑ {}/{}", top, total)
        };
        if self.should_show_jump_to_last_change() {
            let key_label = self.primary_binding_label(Action::JumpToLastChange).unwrap_or("Ctrl+End");
            label.push_str(&format!(" · ⤓ Jump to last change [{key_label}]"));
        }
        Some(label)
    }

    pub(super) fn create_git_status_spans(&self, text: &str, default_style: Style) -> Vec<Span<'static>> {
        let text = text.trim_prefix(ui::HEADER_GIT_PREFIX).trim_start();
        if let Some((branch_part, indicator_part)) = text.rsplit_once(" | ") {
            let mut spans = Vec::new();
            let branch_trim = branch_part.trim_end();
            if !branch_trim.is_empty() {
                // Status values may already include the header's `git: `
                // label. The footer is the compact view, so omit that label.
                spans.push(Span::styled(branch_trim.to_owned(), default_style));
            }
            spans.push(Span::raw(" "));

            let indicator_trim = indicator_part.trim();
            let indicator_style = if indicator_trim == ui::HEADER_GIT_DIRTY_SUFFIX {
                Style::default().fg(Color::Red).add_modifier(Modifier::BOLD)
            } else if indicator_trim == ui::HEADER_GIT_CLEAN_SUFFIX {
                Style::default().fg(Color::Green).add_modifier(Modifier::BOLD)
            } else {
                self.styles.accent_style().add_modifier(Modifier::BOLD)
            };

            spans.push(Span::styled(indicator_trim.to_owned(), indicator_style));
            spans
        } else {
            vec![Span::styled(text.to_owned(), default_style)]
        }
    }

    fn cursor_should_be_visible(&self) -> bool {
        let loading_state = self.is_running_activity() || self.has_status_spinner();
        self.cursor_visible && (self.input_enabled || loading_state)
    }

    fn use_fake_cursor(&self) -> bool {
        self.has_status_spinner()
    }

    fn secure_prompt_active(&self) -> bool {
        self.modal_state().and_then(|modal| modal.secure_prompt.as_ref()).is_some()
    }

    /// Build input render data for external widgets
    pub(crate) fn build_input_widget_data(&self, width: u16, height: u16) -> InputWidgetData {
        let input_render = self.build_input_render_uncached(width, height);
        let background_style = self.styles.input_background_style();

        InputWidgetData {
            text: input_render.text,
            cursor_x: input_render.cursor_x,
            cursor_y: input_render.cursor_y,
            cursor_should_be_visible: self.cursor_should_be_visible(),
            use_fake_cursor: self.use_fake_cursor(),
            background_style,
            default_style: self.styles.default_style(),
        }
    }

    /// Build input status line for external widgets
    pub(crate) fn build_input_status_widget_data(&self, width: u16) -> Option<Vec<Span<'static>>> {
        self.render_input_status_line(width).map(|line| line.spans)
    }
}

#[cfg(test)]
mod input_highlight_tests;