vtcode-tui 0.98.1

Reusable TUI primitives and session API for VT Code-style terminal interfaces
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
use std::borrow::Cow;
use std::mem;

use line_clipping::cohen_sutherland::clip_line;
use line_clipping::{LineSegment, Point, Window};
use ratatui::prelude::*;
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
use vtcode_commons::ansi_codes::ESC_CHAR;

use crate::utils::ansi_parser::strip_ansi;

/// Strips ANSI escape codes from text to ensure plain text output
pub fn strip_ansi_codes(text: &str) -> Cow<'_, str> {
    if !text.contains(ESC_CHAR) {
        return Cow::Borrowed(text);
    }
    Cow::Owned(strip_ansi(text))
}

/// Simplify tool call display text for better human readability
#[allow(dead_code)]
pub fn simplify_tool_display(text: &str) -> String {
    // Common patterns to simplify for human readability
    let simplified = if text.starts_with("file ") {
        // Convert "file path/to/file" to "accessing path/to/file"
        text.replacen("file ", "accessing ", 1)
    } else if text.starts_with("path: ") {
        // Convert "path: path/to/file" to "file: path/to/file"
        text.replacen("path: ", "file: ", 1)
    } else if text.contains(" → file ") {
        // Convert complex patterns to simpler ones
        text.replace(" → file ", "")
    } else if text.starts_with("grep ") {
        // Simplify grep patterns for better readability
        text.replacen("grep ", "searching for ", 1)
    } else if text.starts_with("find ") {
        // Simplify find patterns
        text.replacen("find ", "finding ", 1)
    } else if text.starts_with("list ") {
        // Simplify list patterns
        text.replacen("list ", "listing ", 1)
    } else {
        // Return original text if no simplification needed
        text.to_owned()
    };

    // Further simplify parameter displays
    format_tool_parameters(&simplified)
}

/// Format tool parameters for better readability
#[allow(dead_code)]
pub fn format_tool_parameters(text: &str) -> String {
    // Convert common parameter patterns to more readable formats
    let mut formatted = text.to_owned();

    // Convert "pattern: xyz" to "matching 'xyz'"
    if formatted.contains("pattern: ") {
        formatted = formatted.replace("pattern: ", "matching '");
        // Close the quote if there's a parameter separator
        if formatted.contains(" · ") {
            formatted = formatted.replacen(" · ", "' · ", 1);
        } else if formatted.contains("  ") {
            formatted = formatted.replacen("  ", "' ", 1);
        } else {
            formatted.push('\'');
        }
    }

    // Convert "path: xyz" to "in 'xyz'"
    if formatted.contains("path: ") {
        formatted = formatted.replace("path: ", "in '");
        // Close the quote if there's a parameter separator
        if formatted.contains(" · ") {
            formatted = formatted.replacen(" · ", "' · ", 1);
        } else if formatted.contains("  ") {
            formatted = formatted.replacen("  ", "' ", 1);
        } else {
            formatted.push('\'');
        }
    }

    formatted
}

pub(super) fn pty_wrapped_continuation_prefix(base_prefix: &str, line_text: &str) -> String {
    let stripped = strip_ansi_codes(line_text);
    let hang_width = if stripped.starts_with("")
        || stripped.starts_with("")
        || stripped.starts_with("    ")
    {
        4
    } else if stripped.starts_with("• Ran ") {
        "• Ran ".chars().count()
    } else {
        0
    };
    format!("{}{}", base_prefix, " ".repeat(hang_width))
}

/// Wrap a line of text to fit within the specified width.
///
/// This is the standard wrapping function for plain transcript text. It prefers
/// word boundaries for readable prose and falls back to grapheme wrapping for
/// oversized tokens. For URL-aware wrapping that preserves URLs as atomic units,
/// use `super::wrapping::adaptive_wrap_line` instead.
pub fn wrap_line(line: Line<'static>, max_width: usize) -> Vec<Line<'static>> {
    wrap_line_internal(line, max_width, "", true)
}

pub(super) fn wrap_line_with_hanging_prefix(
    line: Line<'static>,
    max_width: usize,
    continuation_prefix: &str,
) -> Vec<Line<'static>> {
    wrap_line_internal(line, max_width, continuation_prefix, false)
}

fn wrap_line_internal(
    mut line: Line<'static>,
    max_width: usize,
    continuation_prefix: &str,
    prefer_word_boundaries: bool,
) -> Vec<Line<'static>> {
    if max_width == 0 {
        return vec![Line::default()];
    }

    line.spans = coalesce_adjacent_spans(line.spans);
    let derived_continuation_prefix = if prefer_word_boundaries && continuation_prefix.is_empty() {
        wrapped_continuation_prefix(&line)
    } else {
        String::new()
    };
    let continuation_prefix = if continuation_prefix.is_empty() {
        derived_continuation_prefix.as_str()
    } else {
        continuation_prefix
    };

    fn push_span(spans: &mut Vec<Span<'static>>, style: &Style, text: &str) {
        if text.is_empty() {
            return;
        }

        if let Some(last) = spans.last_mut().filter(|last| last.style == *style) {
            last.content.to_mut().push_str(text);
            return;
        }

        spans.push(Span::styled(text.to_owned(), *style));
    }

    fn trim_trailing_wrap_whitespace(spans: &mut Vec<Span<'static>>) {
        while let Some(last) = spans.last_mut() {
            let trimmed_len = last.content.trim_end_matches(char::is_whitespace).len();
            if trimmed_len == last.content.len() {
                break;
            }
            if trimmed_len == 0 {
                spans.pop();
                continue;
            }
            last.content.to_mut().truncate(trimmed_len);
            break;
        }
    }

    let continuation_width = UnicodeWidthStr::width(continuation_prefix);
    let use_continuation_prefix =
        !continuation_prefix.is_empty() && continuation_width > 0 && continuation_width < max_width;

    let mut rows = Vec::new();
    let mut current_spans: Vec<Span<'static>> = Vec::new();
    let mut current_width = 0usize;
    let window = Window::new(0.0, max_width as f64, -1.0, 1.0);

    let flush_current = |spans: &mut Vec<Span<'static>>, rows: &mut Vec<Line<'static>>| {
        if spans.is_empty() {
            rows.push(Line::default());
        } else {
            if prefer_word_boundaries {
                trim_trailing_wrap_whitespace(spans);
            }
            rows.push(Line::from(mem::take(spans)));
        }
    };

    let ensure_continuation_prefix =
        |spans: &mut Vec<Span<'static>>, current_width: &mut usize, rows: &[Line<'static>]| {
            if use_continuation_prefix && spans.is_empty() && !rows.is_empty() {
                push_span(spans, &Style::default(), continuation_prefix);
                *current_width = continuation_width;
            }
        };

    let line_start_width = |rows: &[Line<'static>]| -> usize {
        if use_continuation_prefix && !rows.is_empty() {
            continuation_width
        } else {
            0
        }
    };

    let push_wrapped_token = |token: &str,
                              style: &Style,
                              current_spans: &mut Vec<Span<'static>>,
                              current_width: &mut usize,
                              rows: &mut Vec<Line<'static>>| {
        for grapheme in UnicodeSegmentation::graphemes(token, true) {
            if grapheme.is_empty() {
                continue;
            }

            let width = UnicodeWidthStr::width(grapheme);
            if width == 0 {
                ensure_continuation_prefix(current_spans, current_width, rows);
                push_span(current_spans, style, grapheme);
                continue;
            }

            let mut attempts = 0usize;
            loop {
                ensure_continuation_prefix(current_spans, current_width, rows);
                let segment = LineSegment::new(
                    Point::new(*current_width as f64, 0.0),
                    Point::new((*current_width + width) as f64, 0.0),
                );

                match clip_line(segment, window) {
                    Some(clipped) => {
                        let visible = (clipped.p2.x - clipped.p1.x).round() as usize;
                        if visible == width {
                            push_span(current_spans, style, grapheme);
                            *current_width += width;
                            break;
                        }

                        if *current_width == 0 {
                            push_span(current_spans, style, grapheme);
                            *current_width += width;
                            break;
                        }

                        flush_current(current_spans, rows);
                        *current_width = 0;
                    }
                    None => {
                        if *current_width == 0 {
                            push_span(current_spans, style, grapheme);
                            *current_width += width;
                            break;
                        }

                        flush_current(current_spans, rows);
                        *current_width = 0;
                    }
                }

                attempts += 1;
                if attempts > 4 {
                    push_span(current_spans, style, grapheme);
                    *current_width += width;
                    break;
                }
            }

            if *current_width >= max_width {
                flush_current(current_spans, rows);
                *current_width = 0;
            }
        }
    };

    for span in line.spans.into_iter() {
        let style = span.style;
        let content = span.content.into_owned();
        if content.is_empty() {
            continue;
        }

        for piece in content.split_inclusive('\n') {
            let mut text = piece;
            let mut had_newline = false;
            if let Some(stripped) = text.strip_suffix('\n') {
                text = stripped;
                had_newline = true;
                if let Some(without_carriage) = text.strip_suffix('\r') {
                    text = without_carriage;
                }
            }

            if !text.is_empty() {
                if prefer_word_boundaries {
                    for token in UnicodeSegmentation::split_word_bounds(text) {
                        if token.is_empty() {
                            continue;
                        }

                        let token_width = UnicodeWidthStr::width(token);
                        if token_width == 0 {
                            ensure_continuation_prefix(
                                &mut current_spans,
                                &mut current_width,
                                &rows,
                            );
                            push_span(&mut current_spans, &style, token);
                            continue;
                        }

                        let token_is_whitespace = token.chars().all(char::is_whitespace);
                        let line_start = line_start_width(&rows);
                        let has_content = current_width > line_start;

                        if token_is_whitespace && !rows.is_empty() && !has_content {
                            continue;
                        }

                        ensure_continuation_prefix(&mut current_spans, &mut current_width, &rows);
                        if current_width + token_width <= max_width {
                            push_span(&mut current_spans, &style, token);
                            current_width += token_width;
                            continue;
                        }

                        if token_is_whitespace {
                            if has_content {
                                flush_current(&mut current_spans, &mut rows);
                                current_width = 0;
                            }
                            continue;
                        }

                        if token_width <= max_width {
                            if has_content {
                                flush_current(&mut current_spans, &mut rows);
                                current_width = 0;
                                ensure_continuation_prefix(
                                    &mut current_spans,
                                    &mut current_width,
                                    &rows,
                                );
                            }
                            push_span(&mut current_spans, &style, token);
                            current_width += token_width;
                            continue;
                        }

                        push_wrapped_token(
                            token,
                            &style,
                            &mut current_spans,
                            &mut current_width,
                            &mut rows,
                        );
                    }
                } else {
                    push_wrapped_token(
                        text,
                        &style,
                        &mut current_spans,
                        &mut current_width,
                        &mut rows,
                    );
                }
            }

            if had_newline {
                flush_current(&mut current_spans, &mut rows);
                current_width = 0;
            }
        }
    }

    if !current_spans.is_empty() {
        flush_current(&mut current_spans, &mut rows);
    } else if rows.is_empty() {
        rows.push(Line::default());
    }

    rows
}

fn coalesce_adjacent_spans(spans: Vec<Span<'static>>) -> Vec<Span<'static>> {
    let mut merged: Vec<Span<'static>> = Vec::with_capacity(spans.len());
    for span in spans {
        if span.content.is_empty() {
            continue;
        }
        if let Some(last) = merged.last_mut().filter(|last| last.style == span.style) {
            last.content.to_mut().push_str(span.content.as_ref());
        } else {
            merged.push(span);
        }
    }
    merged
}

fn wrapped_continuation_prefix(line: &Line<'static>) -> String {
    let text: String = line
        .spans
        .iter()
        .map(|span| span.content.as_ref())
        .collect();
    structural_continuation_prefix(&text)
}

fn structural_continuation_prefix(text: &str) -> String {
    let stripped = strip_ansi_codes(text);
    let text = stripped.as_ref();
    let bytes = text.as_bytes();
    let mut index = 0usize;
    let mut width = 0usize;

    while index < bytes.len() {
        let Some(ch) = text[index..].chars().next() else {
            break;
        };
        if !ch.is_whitespace() || ch == '\n' || ch == '\r' {
            break;
        }
        width += UnicodeWidthStr::width(ch.encode_utf8(&mut [0u8; 4]) as &str);
        index += ch.len_utf8();
    }

    while text[index..].starts_with("") {
        width += UnicodeWidthStr::width("");
        index += "".len();
    }

    let remaining = &text[index..];
    let marker_width = if remaining.starts_with("- ") {
        Some(UnicodeWidthStr::width("- "))
    } else if remaining.starts_with("* ") {
        Some(UnicodeWidthStr::width("* "))
    } else if remaining.starts_with("+ ") {
        Some(UnicodeWidthStr::width("+ "))
    } else if remaining.starts_with("") {
        Some(UnicodeWidthStr::width(""))
    } else if remaining.starts_with("") {
        Some(UnicodeWidthStr::width(""))
    } else if remaining.starts_with("") {
        Some(UnicodeWidthStr::width(""))
    } else {
        numbered_list_marker_width(remaining)
    };

    if let Some(marker_width) = marker_width {
        return " ".repeat(width + marker_width);
    }

    if width > 0 {
        " ".repeat(width)
    } else {
        String::new()
    }
}

fn numbered_list_marker_width(text: &str) -> Option<usize> {
    let mut chars = text.char_indices().peekable();
    let mut end_after_head = None;

    while let Some((idx, ch)) = chars.peek().copied() {
        if ch.is_ascii_digit() || ch.is_ascii_alphabetic() {
            end_after_head = Some(idx + ch.len_utf8());
            chars.next();
        } else {
            break;
        }
    }

    end_after_head?;

    let (idx, separator) = chars.next()?;
    if separator != '.' && separator != ')' {
        return None;
    }
    let end_after_separator = idx + separator.len_utf8();

    let (idx, space) = chars.next()?;
    if !space.is_whitespace() {
        return None;
    }
    let end = idx + space.len_utf8();

    Some(UnicodeWidthStr::width(
        &text[..end.max(end_after_separator)],
    ))
}

/// Detect if a line is a todo/checkbox item and its state
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TodoState {
    /// Unchecked: `- [ ]`, `* [ ]`, `[ ]`
    Pending,
    /// Checked: `- [x]`, `- [X]`, `* [x]`, `[x]`
    Completed,
    /// Not a todo item
    None,
}

/// Detect if a line contains a todo/checkbox pattern
pub fn detect_todo_state(text: &str) -> TodoState {
    let trimmed = text.trim_start();

    // Common patterns: "- [ ]", "* [ ]", "[ ]", "- [x]", "* [x]", "[x]"
    let patterns_pending = ["- [ ]", "* [ ]", "+ [ ]", "[ ]"];
    let patterns_completed = [
        "- [x]", "- [X]", "* [x]", "* [X]", "+ [x]", "+ [X]", "[x]", "[X]",
    ];

    for pattern in patterns_completed {
        if trimmed.starts_with(pattern) {
            return TodoState::Completed;
        }
    }

    for pattern in patterns_pending {
        if trimmed.starts_with(pattern) {
            return TodoState::Pending;
        }
    }

    // Also check for strikethrough markers (~~text~~)
    if trimmed.starts_with("~~") && trimmed.contains("~~") {
        return TodoState::Completed;
    }

    TodoState::None
}

/// Check if text appears to be a list item (bullet or numbered)
#[allow(dead_code)]
pub fn is_list_item(text: &str) -> bool {
    let trimmed = text.trim_start();

    // Bullet patterns
    if trimmed.starts_with("- ")
        || trimmed.starts_with("* ")
        || trimmed.starts_with("+ ")
        || trimmed.starts_with("")
    {
        return true;
    }

    // Numbered patterns: "1.", "1)", "a.", "a)"
    let mut chars = trimmed.chars();
    if let Some(first) = chars.next()
        && (first.is_ascii_digit() || first.is_ascii_alphabetic())
        && let Some(second) = chars.next()
        && (second == '.' || second == ')')
        && let Some(third) = chars.next()
    {
        return third == ' ';
    }

    false
}

/// Justify plain text by distributing spaces evenly
pub fn justify_plain_text(text: &str, max_width: usize) -> Option<String> {
    let trimmed = text.trim();
    let words: Vec<&str> = trimmed.split_whitespace().collect();
    if words.len() <= 1 {
        return None;
    }

    let total_word_width: usize = words.iter().map(|word| UnicodeWidthStr::width(*word)).sum();
    if total_word_width >= max_width {
        return None;
    }

    let gaps = words.len() - 1;
    let spaces_needed = max_width.saturating_sub(total_word_width);
    if spaces_needed <= gaps {
        return None;
    }

    let base_space = spaces_needed / gaps;
    if base_space == 0 {
        return None;
    }
    let extra = spaces_needed % gaps;

    let mut output = String::with_capacity(max_width + gaps);
    for (index, word) in words.iter().enumerate() {
        output.push_str(word);
        if index < gaps {
            let mut count = base_space;
            if index < extra {
                count += 1;
            }
            for _ in 0..count {
                output.push(' ');
            }
        }
    }

    Some(output)
}

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

    #[test]
    fn test_strip_ansi_codes() {
        assert_eq!(strip_ansi_codes("\x1b[31mRed text\x1b[0m"), "Red text");
        assert_eq!(strip_ansi_codes("No codes here"), "No codes here");
        assert_eq!(
            strip_ansi_codes("\x1b[1;32mBold green\x1b[0m"),
            "Bold green"
        );
    }

    #[test]
    fn test_simplify_tool_display() {
        assert_eq!(
            simplify_tool_display("file path/to/file"),
            "accessing path/to/file"
        );
        assert_eq!(
            simplify_tool_display("path: path/to/file"),
            "file: path/to/file"
        );
        assert_eq!(
            simplify_tool_display("grep pattern"),
            "searching for pattern"
        );
    }

    #[test]
    fn test_justify_plain_text() {
        let result = justify_plain_text("Hello world", 15);
        assert!(result.is_some());
        assert_eq!(result.unwrap().len(), 15);

        assert_eq!(justify_plain_text("Short", 10), None);
        assert_eq!(justify_plain_text("Very long text string", 10), None);
    }

    #[test]
    fn test_detect_todo_state_pending() {
        assert_eq!(detect_todo_state("- [ ] Task"), TodoState::Pending);
        assert_eq!(detect_todo_state("* [ ] Task"), TodoState::Pending);
        assert_eq!(detect_todo_state("+ [ ] Task"), TodoState::Pending);
        assert_eq!(detect_todo_state("[ ] Task"), TodoState::Pending);
        assert_eq!(
            detect_todo_state("  - [ ] Indented task"),
            TodoState::Pending
        );
    }

    #[test]
    fn test_detect_todo_state_completed() {
        assert_eq!(detect_todo_state("- [x] Done"), TodoState::Completed);
        assert_eq!(detect_todo_state("- [X] Done"), TodoState::Completed);
        assert_eq!(detect_todo_state("* [x] Done"), TodoState::Completed);
        assert_eq!(detect_todo_state("[x] Done"), TodoState::Completed);
        assert_eq!(
            detect_todo_state("  - [x] Indented done"),
            TodoState::Completed
        );
        assert_eq!(
            detect_todo_state("~~Strikethrough text~~"),
            TodoState::Completed
        );
    }

    #[test]
    fn test_detect_todo_state_none() {
        assert_eq!(detect_todo_state("Regular text"), TodoState::None);
        assert_eq!(detect_todo_state("- Regular list item"), TodoState::None);
        assert_eq!(detect_todo_state("* Bullet point"), TodoState::None);
        assert_eq!(detect_todo_state("1. Numbered item"), TodoState::None);
    }

    #[test]
    fn test_is_list_item() {
        assert!(is_list_item("- Item"));
        assert!(is_list_item("* Item"));
        assert!(is_list_item("+ Item"));
        assert!(is_list_item("• Item"));
        assert!(is_list_item("1. Item"));
        assert!(is_list_item("a) Item"));
        assert!(is_list_item("  - Indented"));
        assert!(!is_list_item("Regular text"));
        assert!(!is_list_item(""));
    }

    #[test]
    fn test_pty_wrapped_continuation_prefix() {
        assert_eq!(
            pty_wrapped_continuation_prefix("  ", "  └ cargo check"),
            "      "
        );
        assert_eq!(
            pty_wrapped_continuation_prefix("  ", "\u{1b}[32m• Ran cargo check -p vtcode\u{1b}[0m",),
            "        "
        );
        assert_eq!(
            pty_wrapped_continuation_prefix("  ", "• Ran cargo check -p vtcode"),
            "        "
        );
        assert_eq!(pty_wrapped_continuation_prefix("  ", "plain output"), "  ");
    }
}