vtcode-ui 0.158.0

Unified UI crate for VT Code: design system, theme registry, and TUI framework
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
//! Shell syntax helpers for `• Ran` tool-call lines.
//!
//! Extracted from `src/agent/runloop/unified/tool_pipeline/pty_stream/segments.rs`
//! so both live PTY rendering and the compact-activity row share one
//! tokenizer + palette. Keeps command/args/option/keyword coloring DRY.

use std::sync::Arc;

use anstyle::{AnsiColor, Color as AnsiColorEnum, Effects, Style as AnsiStyle};
use vtcode_commons::ui_protocol::{InlineSegment, InlineTextStyle, convert_style};

use crate::tui::ui::syntax_highlight;

pub struct ShellLineStyles {
    pub output: Arc<InlineTextStyle>,
    pub bullet: Arc<InlineTextStyle>,
    pub glyph: Arc<InlineTextStyle>,
    pub verb: Arc<InlineTextStyle>,
    pub command: Arc<InlineTextStyle>,
    pub args: Arc<InlineTextStyle>,
    pub keyword: Arc<InlineTextStyle>,
    pub variable: Arc<InlineTextStyle>,
    pub string: Arc<InlineTextStyle>,
    pub option: Arc<InlineTextStyle>,
    pub truncation: Arc<InlineTextStyle>,
    /// Structural tokens (`|`, `;`, `&&`, redirections) — muted so command
    /// words and args carry the color hierarchy.
    pub separator: Arc<InlineTextStyle>,
    /// Grouped `N commands` counts — bold accent matching the verb so the
    /// collapsed row stays prominent instead of washing out.
    pub count: Arc<InlineTextStyle>,
}

impl ShellLineStyles {
    /// Styles derived from the process-global UI theme (used by PTY live view
    /// when no session is available). Mirrors
    /// `PtyLineStyles::new()` in the binary.
    pub fn new() -> Self {
        let theme_styles = crate::theme::active_styles();
        Self::from_ansi_styles(theme_styles.primary, theme_styles.pty_output)
    }

    /// Styles derived from a session's resolved theme — preferred inside
    /// `AppSession`/`Session` where `InlineTheme` is already available.
    pub fn from_session(_session: &crate::tui::core_tui::app::session::AppSession) -> Self {
        let theme_styles = crate::theme::active_styles();
        // Keep verb synced with the session's primary, body with pty_output
        // so compact rows track theme changes (e.g. catppuccin-latte).
        Self::from_ansi_styles(theme_styles.primary, theme_styles.pty_output)
    }

    fn from_ansi_styles(primary: AnsiStyle, pty_output: AnsiStyle) -> Self {
        let output = Arc::new(convert_style(pty_output));
        let magenta_bold = Arc::new(convert_style(
            AnsiStyle::new()
                .fg_color(Some(AnsiColorEnum::Ansi(AnsiColor::Magenta)))
                .effects(Effects::BOLD),
        ));
        let accent_bold = Arc::new(convert_style(primary | Effects::BOLD));
        let yellow = Arc::new(convert_style(AnsiStyle::new().fg_color(Some(AnsiColorEnum::Ansi(AnsiColor::Yellow)))));
        // Args use the themed body color (opaque) instead of hardcoded dimmed
        // white so paths/args stay legible on light themes; separators stay
        // dimmed so command words keep the visual hierarchy.
        let args = Arc::new(convert_style(pty_output));

        Self {
            output: Arc::clone(&output),
            bullet: Arc::new(convert_style(AnsiStyle::new().fg_color(Some(AnsiColorEnum::Ansi(AnsiColor::Green))))),
            glyph: Arc::clone(&output),
            verb: accent_bold,
            command: Arc::new(convert_style(
                AnsiStyle::new()
                    .fg_color(Some(AnsiColorEnum::Ansi(AnsiColor::Green)))
                    .effects(Effects::BOLD),
            )),
            args: Arc::clone(&args),
            keyword: magenta_bold,
            variable: Arc::clone(&yellow),
            string: yellow,
            option: Arc::new(convert_style(AnsiStyle::new().fg_color(Some(AnsiColorEnum::Ansi(AnsiColor::Red))))),
            truncation: Arc::new(convert_style(pty_output | Effects::DIMMED)),
            separator: Arc::new(convert_style(pty_output | Effects::DIMMED)),
            count: Arc::new(convert_style(primary | Effects::BOLD)),
        }
    }
}

impl Default for ShellLineStyles {
    fn default() -> Self {
        Self::new()
    }
}

fn is_bash_keyword(token: &str) -> bool {
    matches!(
        token,
        "if" | "then"
            | "else"
            | "elif"
            | "fi"
            | "for"
            | "in"
            | "do"
            | "done"
            | "while"
            | "until"
            | "case"
            | "esac"
            | "function"
            | "select"
            | "time"
            | "coproc"
            | "{"
            | "}"
            | "[["
            | "]]"
    )
}

fn is_command_separator(token: &str) -> bool {
    matches!(token, "|" | "||" | "&&" | ";" | ";;" | "&")
}

/// Redirection operators, including fd-prefixed and target-attached forms:
/// `>`, `>>`, `2>`, `2>&1`, `2>/dev/null`, `<`, `<<`.
fn is_redirection_token(token: &str) -> bool {
    let body = token.trim_start_matches(|c: char| c.is_ascii_digit());
    body.starts_with('>') || body.starts_with('<')
}

pub fn tokenize_preserve_whitespace(text: &str) -> Vec<&str> {
    let mut parts = Vec::new();
    let mut in_single = false;
    let mut in_double = false;
    let mut escaped = false;
    let mut token_start: Option<usize> = None;
    let mut token_is_whitespace = false;

    for (idx, ch) in text.char_indices() {
        if escaped {
            escaped = false;
        } else if ch == '\\' && !in_single {
            escaped = true;
        } else if ch == '\'' && !in_double {
            in_single = !in_single;
        } else if ch == '"' && !in_single {
            in_double = !in_double;
        }

        let is_whitespace = !in_single && !in_double && ch.is_whitespace();
        match token_start {
            None => {
                token_start = Some(idx);
                token_is_whitespace = is_whitespace;
            }
            Some(start) if token_is_whitespace != is_whitespace => {
                parts.push(&text[start..idx]);
                token_start = Some(idx);
                token_is_whitespace = is_whitespace;
            }
            _ => {}
        }
    }

    if let Some(start) = token_start {
        parts.push(&text[start..]);
    }

    parts
}

fn style_for_token<'a>(token: &'a str, expect_command: &mut bool, styles: &'a ShellLineStyles) -> Arc<InlineTextStyle> {
    if token.trim().is_empty() {
        return Arc::clone(&styles.output);
    }

    if is_command_separator(token) {
        *expect_command = true;
        return Arc::clone(&styles.separator);
    }

    if is_redirection_token(token) {
        *expect_command = false;
        return Arc::clone(&styles.separator);
    }

    if token.starts_with('"') || token.starts_with('\'') || token.ends_with('"') || token.ends_with('\'') {
        *expect_command = false;
        return Arc::clone(&styles.string);
    }

    if token.starts_with('$') || token.contains("=$") || token.starts_with("${") {
        *expect_command = false;
        return Arc::clone(&styles.variable);
    }

    if token.starts_with('-') && token.len() > 1 {
        *expect_command = false;
        return Arc::clone(&styles.option);
    }

    if is_bash_keyword(token) {
        *expect_command = true;
        return Arc::clone(&styles.keyword);
    }

    if *expect_command {
        *expect_command = false;
        return Arc::clone(&styles.command);
    }

    Arc::clone(&styles.args)
}

/// Split trailing `;`/`&`/`|` runs off a whitespace-delimited token so
/// attached separators (`-120;`, `'---';`) color as separators instead of
/// inheriting the word's option/string style. Redirections (`2>/dev/null`,
/// `2>&1`) end in word characters and are left intact.
fn split_trailing_command_operators(token: &str) -> Vec<&str> {
    let bytes = token.as_bytes();
    let mut end = bytes.len();
    while end > 0 && matches!(bytes[end - 1], b';' | b'&' | b'|') {
        end -= 1;
    }
    if end == 0 || end == bytes.len() {
        return vec![token];
    }
    vec![&token[..end], &token[end..]]
}

fn bash_segments(text: &str, styles: &ShellLineStyles, expect_command: bool) -> Vec<InlineSegment> {
    let mut segments = Vec::new();
    let mut command_expected = expect_command;
    for token in tokenize_preserve_whitespace(text) {
        if token.trim().is_empty() {
            segments.push(InlineSegment {
                text: token.to_string(),
                style: Arc::clone(&styles.output),
            });
            continue;
        }
        for part in split_trailing_command_operators(token) {
            segments.push(InlineSegment {
                text: part.to_string(),
                style: style_for_token(part, &mut command_expected, styles),
            });
        }
    }
    segments
}

pub fn shell_syntax_segments(text: &str, styles: &ShellLineStyles, expect_command: bool) -> Vec<InlineSegment> {
    let semantic = bash_segments(text, styles, expect_command);
    let Some(highlighted) = syntax_highlight::highlight_line_to_anstyle_segments(
        text,
        Some("bash"),
        syntax_highlight::get_active_syntax_theme(),
        true,
    ) else {
        return semantic;
    };

    if highlighted.is_empty() {
        return semantic;
    }

    let converted = highlighted
        .into_iter()
        .map(|(style, text)| InlineSegment {
            text,
            style: Arc::new(convert_style(style).merge_color(styles.args.color)),
        })
        .collect::<Vec<_>>();

    let converted_text = converted.iter().map(|segment| segment.text.as_str()).collect::<String>();
    if converted_text != text {
        return semantic;
    }

    let non_ws_count = semantic.iter().filter(|segment| !segment.text.trim().is_empty()).count();
    if non_ws_count > 1 {
        let mut first_colors: Option<(Option<AnsiColorEnum>, Option<AnsiColorEnum>)> = None;
        let mut has_distinct = false;
        for style in converted
            .iter()
            .filter(|segment| !segment.text.trim().is_empty())
            .map(|segment| segment.style.as_ref())
        {
            let colors = (style.color, style.bg_color);
            if let Some(seed) = first_colors {
                if colors != seed {
                    has_distinct = true;
                    break;
                }
            } else {
                first_colors = Some(colors);
            }
        }
        if !has_distinct {
            return semantic;
        }
    }

    converted
}

pub fn line_to_compact_segments(
    metadata: &vtcode_commons::ui_protocol::CompactActivityMetadata,
    styles: &ShellLineStyles,
) -> Vec<InlineSegment> {
    // • Ran <command>  (single) or • Ran N commands (grouped)
    let mut segments = Vec::new();
    segments.push(InlineSegment {
        text: "".to_string(),
        style: Arc::clone(&styles.bullet),
    });
    segments.push(InlineSegment {
        text: "Ran".to_string(),
        style: Arc::clone(&styles.verb),
    });
    segments.push(InlineSegment {
        text: " ".to_string(),
        style: Arc::clone(&styles.output),
    });

    if metadata.command_count > 1 {
        // Grouped: bold accent count matches the verb so `Ran 4 commands`
        // stays prominent instead of washing out.
        segments.push(InlineSegment {
            text: format!("{} commands", metadata.command_count),
            style: Arc::clone(&styles.count),
        });
    } else if let Some(cmd) = metadata.command.as_deref() {
        segments.extend(shell_syntax_segments(cmd, styles, true));
        if metadata.hidden_line_count > 0 {
            segments.push(InlineSegment {
                text: format!(" · … +{} lines", metadata.hidden_line_count),
                style: Arc::clone(&styles.truncation),
            });
        }
    } else {
        segments.push(InlineSegment {
            text: "command".to_string(),
            style: Arc::clone(&styles.args),
        });
    }

    if let Some(suffix) = metadata.suffix.as_deref().filter(|s| !s.is_empty()) {
        segments.push(InlineSegment {
            text: " · ".to_string(),
            style: Arc::clone(&styles.truncation),
        });
        segments.push(InlineSegment {
            text: suffix.to_string(),
            style: Arc::clone(&styles.truncation),
        });
    }

    segments
}

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

    #[test]
    fn command_header_preserves_distinct_semantic_token_colors() {
        let styles = ShellLineStyles::new();
        let segments =
            shell_syntax_segments("find src/agent/runloop -maxdepth 3 -type f -name *.rs | sort", &styles, true);
        let option = segments
            .iter()
            .find(|segment| segment.text.contains("maxdepth"))
            .expect("option token");
        let command = segments
            .iter()
            .find(|segment| segment.text.contains("find"))
            .expect("command token");
        assert_ne!(option.style.color, command.style.color);
    }

    #[test]
    fn grouped_has_no_single_command_highlight() {
        let styles = ShellLineStyles::new();
        let meta = vtcode_commons::ui_protocol::CompactActivityMetadata {
            group_id: 1,
            command_count: 4,
            command: None,
            hidden_line_count: 10,
            suffix: Some("output retained".into()),
            review_anchor: Some(1),
            review_anchors: vec![1],
        };
        let segs = line_to_compact_segments(&meta, &styles);
        let text: String = segs.iter().map(|s| s.text.as_str()).collect();
        assert!(text.contains("4 commands"));
        assert!(text.contains("output retained"));
    }

    #[test]
    fn grouped_count_stays_bold_instead_of_dimmed() {
        let styles = ShellLineStyles::new();
        assert!(styles.count.effects.contains(Effects::BOLD));
        assert!(!styles.count.effects.contains(Effects::DIMMED));
    }

    #[test]
    fn args_use_themed_body_color_for_light_theme_legibility() {
        let styles = ShellLineStyles::new();
        assert_eq!(styles.args.color, styles.output.color);
    }

    #[test]
    fn attached_separator_splits_from_word_style() {
        let styles = ShellLineStyles::new();
        let segments = bash_segments("head -120; echo hi", &styles, true);
        let option = segments.iter().find(|s| s.text == "-120").expect("option part");
        let separator = segments.iter().find(|s| s.text == ";").expect("separator part");
        assert_eq!(option.style.color, styles.option.color);
        assert_eq!(separator.style.color, styles.separator.color);
        assert!(separator.style.effects.contains(Effects::DIMMED));
    }
}