vtcode 0.99.1

A Rust-based terminal coding agent with modular architecture supporting multiple LLM providers
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
use crate::agent::runloop::unified::shell::{
    detect_explicit_run_command, strip_run_command_prefixes,
};
use anstyle::{AnsiColor, Color as AnsiColorEnum, Effects, Reset, Style as AnsiStyle};
use anyhow::{Context, Result};
use std::path::Path;
use vtcode_core::command_safety::shell_parser::parse_shell_commands_tree_sitter;
use vtcode_core::config::loader::{ConfigManager, VTCodeConfig};
use vtcode_core::config::types::AgentConfig as CoreAgentConfig;
use vtcode_core::utils::ansi::{AnsiRenderer, MessageStyle};
use vtcode_core::utils::dot_config::update_theme_preference;

pub(crate) async fn persist_theme_preference(
    renderer: &mut AnsiRenderer,
    workspace: &Path,
    theme_id: &str,
) -> Result<()> {
    if let Err(err) = update_theme_preference(theme_id).await {
        renderer.line(
            MessageStyle::Error,
            &format!("Failed to persist theme preference: {}", err),
        )?;
    }
    if let Err(err) = persist_theme_config(workspace, theme_id) {
        renderer.line(
            MessageStyle::Error,
            &format!("Failed to persist theme in vtcode.toml: {}", err),
        )?;
    }
    Ok(())
}

pub(crate) fn sync_runtime_theme_selection(
    config: &mut CoreAgentConfig,
    vt_cfg: Option<&mut VTCodeConfig>,
    theme_id: &str,
) {
    config.theme = theme_id.to_string();
    if let Some(vt_cfg) = vt_cfg {
        vt_cfg.agent.theme = theme_id.to_string();
    }
}

fn persist_theme_config(workspace: &Path, theme_id: &str) -> Result<()> {
    let mut manager = ConfigManager::load_from_workspace(workspace)
        .context("Failed to load configuration for theme update")?;
    let mut config = manager.config().clone();
    if config.agent.theme != theme_id {
        config.agent.theme = theme_id.to_string();
        manager
            .save_config(&config)
            .context("Failed to save theme to configuration")?;
    }
    Ok(())
}

/// Display a user message using the active user styling
pub(crate) fn display_user_message(renderer: &mut AnsiRenderer, message: &str) -> Result<()> {
    let rendered = highlight_shell_user_input(message).unwrap_or_else(|| message.to_string());
    renderer.line(MessageStyle::User, &rendered)
}

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, "|" | "||" | "&&" | ";" | ";;" | "&")
}

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(token: &str, expect_command: &mut bool) -> Option<AnsiStyle> {
    if token.trim().is_empty() {
        return None;
    }
    if is_command_separator(token) {
        *expect_command = true;
        return None;
    }
    if token.starts_with('"')
        || token.starts_with('\'')
        || token.ends_with('"')
        || token.ends_with('\'')
    {
        *expect_command = false;
        return Some(AnsiStyle::new().fg_color(Some(AnsiColorEnum::Ansi(AnsiColor::Yellow))));
    }
    if token.starts_with('$') || token.contains("=$") || token.starts_with("${") {
        *expect_command = false;
        return Some(AnsiStyle::new().fg_color(Some(AnsiColorEnum::Ansi(AnsiColor::Yellow))));
    }
    if token.starts_with('-') && token.len() > 1 {
        *expect_command = false;
        return Some(AnsiStyle::new().fg_color(Some(AnsiColorEnum::Ansi(AnsiColor::Red))));
    }
    if is_bash_keyword(token) {
        *expect_command = true;
        return Some(
            AnsiStyle::new()
                .fg_color(Some(AnsiColorEnum::Ansi(AnsiColor::Blue)))
                .effects(Effects::BOLD),
        );
    }
    if *expect_command {
        *expect_command = false;
        return Some(
            AnsiStyle::new()
                .fg_color(Some(AnsiColorEnum::Ansi(AnsiColor::Green)))
                .effects(Effects::BOLD),
        );
    }
    Some(
        AnsiStyle::new()
            .fg_color(Some(AnsiColorEnum::Ansi(AnsiColor::White)))
            .effects(Effects::DIMMED),
    )
}

fn strip_matching_backticks(input: &str) -> &str {
    let trimmed = input.trim();
    if trimmed.len() >= 2 && trimmed.starts_with('`') && trimmed.ends_with('`') {
        &trimmed[1..trimmed.len() - 1]
    } else {
        input
    }
}

fn highlight_shell_command(command: &str) -> String {
    let command = strip_matching_backticks(command);
    if !is_valid_bash_grammar(command) {
        return command.to_string();
    }
    let mut rendered = String::with_capacity(command.len() + 32);
    let mut expect_command = true;
    for token in tokenize_preserve_whitespace(command) {
        if let Some(style) = style_for_token(token, &mut expect_command) {
            rendered.push_str(&style.to_string());
            rendered.push_str(token);
            rendered.push_str(&Reset.to_string());
        } else {
            rendered.push_str(token);
        }
    }
    rendered
}

fn is_valid_bash_grammar(command: &str) -> bool {
    parse_shell_commands_tree_sitter(command)
        .map(|commands| !commands.is_empty())
        .unwrap_or(false)
}

fn highlight_shell_user_input(message: &str) -> Option<String> {
    let leading_ws_len = message.chars().take_while(|ch| ch.is_whitespace()).count();
    let leading_ws_bytes = message
        .char_indices()
        .nth(leading_ws_len)
        .map(|(idx, _)| idx)
        .unwrap_or(message.len());
    let trimmed = &message[leading_ws_bytes..];

    if let Some(rest) = trimmed.strip_prefix('!') {
        let command = rest.trim();
        if command.is_empty() || !is_valid_bash_grammar(strip_matching_backticks(command)) {
            return None;
        }
        let prefix_len = rest.len() - rest.trim_start().len();
        let prefix_style = AnsiStyle::new()
            .fg_color(Some(AnsiColorEnum::Ansi(AnsiColor::White)))
            .effects(Effects::DIMMED);
        let prefix = format!(
            "{}{}!{}{}",
            prefix_style,
            &message[..leading_ws_bytes],
            &rest[..prefix_len],
            Reset
        );
        return Some(format!("{}{}", prefix, highlight_shell_command(command)));
    }

    if let Some((prefix_end, command)) = extract_run_command_for_highlight(trimmed) {
        detect_explicit_run_command(trimmed)?;
        if !is_valid_bash_grammar(strip_matching_backticks(command)) {
            return None;
        }
        let prefix = &trimmed[..prefix_end];
        let prefix_style = AnsiStyle::new()
            .fg_color(Some(AnsiColorEnum::Ansi(AnsiColor::White)))
            .effects(Effects::DIMMED);
        let prefix_rendered = format!(
            "{}{}{}{}",
            prefix_style,
            &message[..leading_ws_bytes],
            prefix,
            Reset
        );
        return Some(format!(
            "{}{}",
            prefix_rendered,
            highlight_shell_command_preserve_text(command)
        ));
    }

    None
}

#[cfg(test)]
mod theme_sync_tests {
    use super::sync_runtime_theme_selection;
    use std::collections::BTreeMap;
    use vtcode_core::config::core::PromptCachingConfig;
    use vtcode_core::config::loader::VTCodeConfig;
    use vtcode_core::config::types::{
        AgentConfig as CoreAgentConfig, ModelSelectionSource, UiSurfacePreference,
    };
    use vtcode_core::core::agent::snapshots::{
        DEFAULT_CHECKPOINTS_ENABLED, DEFAULT_MAX_AGE_DAYS, DEFAULT_MAX_SNAPSHOTS,
    };

    fn runtime_config(theme: &str) -> CoreAgentConfig {
        CoreAgentConfig {
            model: "gpt-5.4".to_string(),
            api_key: String::new(),
            provider: "openai".to_string(),
            api_key_env: "OPENAI_API_KEY".to_string(),
            workspace: std::env::temp_dir(),
            verbose: false,
            quiet: false,
            theme: theme.to_string(),
            reasoning_effort: Default::default(),
            ui_surface: UiSurfacePreference::default(),
            prompt_cache: PromptCachingConfig::default(),
            model_source: ModelSelectionSource::WorkspaceConfig,
            custom_api_keys: BTreeMap::new(),
            checkpointing_enabled: DEFAULT_CHECKPOINTS_ENABLED,
            checkpointing_storage_dir: None,
            checkpointing_max_snapshots: DEFAULT_MAX_SNAPSHOTS,
            checkpointing_max_age_days: Some(DEFAULT_MAX_AGE_DAYS),
            max_conversation_turns: 1000,
            model_behavior: None,
            openai_chatgpt_auth: None,
        }
    }

    #[test]
    fn sync_runtime_theme_selection_updates_runtime_and_loaded_config() {
        let mut runtime = runtime_config("ansi");
        let mut vt_cfg = VTCodeConfig::default();
        vt_cfg.agent.theme = "ansi".to_string();

        sync_runtime_theme_selection(&mut runtime, Some(&mut vt_cfg), "vitesse-light");

        assert_eq!(runtime.theme, "vitesse-light");
        assert_eq!(vt_cfg.agent.theme, "vitesse-light");
    }
}

fn highlight_shell_command_preserve_text(command: &str) -> String {
    let trimmed = command.trim();
    if trimmed.len() >= 2 && trimmed.starts_with('`') && trimmed.ends_with('`') {
        let leading_len = command.len() - command.trim_start().len();
        let trailing_len = command.len() - command.trim_end().len();
        let leading = &command[..leading_len];
        let trailing = &command[command.len() - trailing_len..];
        let inner = &trimmed[1..trimmed.len() - 1];
        return format!(
            "{}`{}`{}",
            leading,
            highlight_shell_command(inner),
            trailing
        );
    }
    highlight_shell_command(command)
}

fn extract_run_command_for_highlight(input: &str) -> Option<(usize, &str)> {
    if !input.to_ascii_lowercase().starts_with("run ") {
        return None;
    }

    let mut index = 3usize;
    while let Some(ch) = input[index..].chars().next() {
        if !ch.is_whitespace() {
            break;
        }
        index += ch.len_utf8();
    }
    if index >= input.len() {
        return None;
    }

    let command = strip_run_command_prefixes(&input[index..]);
    if command.is_empty() {
        return None;
    }

    let command_start = input.len().saturating_sub(command.len());
    Some((command_start, command))
}

#[cfg(test)]
mod tests {
    use super::*;
    use vtcode_core::utils::ansi_parser::strip_ansi;

    #[test]
    fn highlights_run_prefix_user_input() {
        let highlighted = highlight_shell_user_input("run cargo fmt").expect("should highlight");
        assert_eq!(strip_ansi(&highlighted), "run cargo fmt");
        assert!(highlighted.contains("cargo"));
        assert!(highlighted.contains("fmt"));
    }

    #[test]
    fn highlights_bang_prefix_user_input() {
        let highlighted = highlight_shell_user_input("!echo $HOME").expect("should highlight");
        assert!(highlighted.contains("!"));
        assert!(highlighted.contains("echo"));
        assert!(highlighted.contains("$HOME"));
    }

    #[test]
    fn skips_natural_language_run_input() {
        assert!(highlight_shell_user_input("run the tests").is_none());
    }

    #[test]
    fn strips_backticks_from_explicit_run_command() {
        let highlighted = highlight_shell_user_input("run `cargo fmt`").expect("should highlight");
        assert_eq!(strip_ansi(&highlighted), "run `cargo fmt`");
        assert!(highlighted.contains("cargo"));
        assert!(highlighted.contains("fmt"));
    }

    #[test]
    fn preserves_text_with_unix_command_wrapper() {
        let highlighted =
            highlight_shell_user_input("run unix command ls -la").expect("should highlight");
        assert_eq!(strip_ansi(&highlighted), "run unix command ls -la");
    }

    #[test]
    fn preserves_text_with_mixed_wrappers() {
        let highlighted =
            highlight_shell_user_input("run command please cargo check").expect("should highlight");
        assert_eq!(strip_ansi(&highlighted), "run command please cargo check");
    }

    #[test]
    fn skips_highlighting_for_invalid_bash_grammar() {
        assert!(highlight_shell_user_input("run )(").is_none());
        assert!(highlight_shell_user_input("! )(").is_none());
    }
}