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
//! Configuration system for TUI session UI preferences
//!
//! Contains settings for customizable UI elements, colors, key bindings, and other preferences.

use hashbrown::HashMap;
use serde::{Deserialize, Serialize};
use std::path::Path;
use vtcode_commons::fs::{read_file_with_context_sync, write_file_with_context_sync};

/// Main configuration struct for TUI session preferences
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SessionConfig {
    /// UI appearance settings
    pub appearance: AppearanceConfig,

    /// Key binding preferences
    pub key_bindings: KeyBindingConfig,

    /// Behavior preferences
    pub behavior: BehaviorConfig,

    /// Performance related settings
    pub performance: PerformanceConfig,

    /// Customization settings
    pub customization: CustomizationConfig,
}

// Re-export shared enums from vtcode-commons.
pub use vtcode_commons::ui_protocol::{LayoutModeOverride, ReasoningDisplayMode, UiMode};

/// UI appearance configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppearanceConfig {
    /// Color theme to use
    pub theme: String,

    /// UI mode variant (full, minimal, focused)
    pub ui_mode: UiMode,

    /// Whether to show the right sidebar (queue, context, tools)
    pub show_sidebar: bool,

    /// Minimum width for content area
    pub min_content_width: u16,

    /// Minimum width for navigation area
    pub min_navigation_width: u16,

    /// Percentage of width for navigation area
    pub navigation_width_percent: u8,

    /// Transcript bottom padding
    pub transcript_bottom_padding: u16,

    /// Whether to dim completed todo items (- \[x\] and ~~strikethrough~~)
    pub dim_completed_todos: bool,

    /// Number of blank lines between message blocks (0-2)
    pub message_block_spacing: u8,

    /// Override responsive layout mode
    #[serde(default)]
    pub layout_mode: LayoutModeOverride,

    /// Reasoning visibility mode
    #[serde(default)]
    pub reasoning_display_mode: ReasoningDisplayMode,

    /// Default reasoning visibility when mode is "toggle"
    #[serde(default)]
    pub reasoning_visible_default: bool,

    /// Enable Vim-style input editing for the prompt.
    #[serde(default)]
    pub vim_mode: bool,

    /// Screen reader mode (disables animation-heavy rendering paths)
    #[serde(default)]
    pub screen_reader_mode: bool,

    /// Reduce motion mode (disables shimmer/flashing animations)
    #[serde(default)]
    pub reduce_motion_mode: bool,

    /// Keep progress animation while reduce motion mode is enabled
    #[serde(default)]
    pub reduce_motion_keep_progress_animation: bool,

    /// Customization settings
    pub customization: CustomizationConfig,
}

impl Default for AppearanceConfig {
    fn default() -> Self {
        Self {
            theme: "default".to_owned(),
            ui_mode: UiMode::Full,
            show_sidebar: true,
            min_content_width: 40,
            min_navigation_width: 20,
            navigation_width_percent: 25,
            transcript_bottom_padding: 0,
            dim_completed_todos: true,
            message_block_spacing: 0,
            layout_mode: LayoutModeOverride::Auto,
            reasoning_display_mode: ReasoningDisplayMode::Toggle,
            reasoning_visible_default: crate::config::constants::ui::DEFAULT_REASONING_VISIBLE,
            vim_mode: false,
            screen_reader_mode: false,
            reduce_motion_mode: false,
            reduce_motion_keep_progress_animation: false,
            customization: CustomizationConfig::default(),
        }
    }
}

impl AppearanceConfig {
    /// Check if sidebar should be shown based on ui_mode and show_sidebar
    pub fn should_show_sidebar(&self) -> bool {
        match self.ui_mode {
            UiMode::Full => self.show_sidebar,
            UiMode::Minimal | UiMode::Focused => false,
        }
    }

    pub fn reasoning_visible(&self) -> bool {
        match self.reasoning_display_mode {
            ReasoningDisplayMode::Always => true,
            ReasoningDisplayMode::Hidden => false,
            ReasoningDisplayMode::Toggle => self.reasoning_visible_default,
        }
    }

    pub fn motion_reduced(&self) -> bool {
        self.screen_reader_mode || self.reduce_motion_mode
    }

    pub fn should_animate_progress_status(&self) -> bool {
        !self.screen_reader_mode
            && (!self.reduce_motion_mode || self.reduce_motion_keep_progress_animation)
    }

    /// Check if footer should be shown based on ui_mode
    #[allow(dead_code)]
    pub fn should_show_footer(&self) -> bool {
        match self.ui_mode {
            UiMode::Full => true,
            UiMode::Minimal => false,
            UiMode::Focused => false,
        }
    }
}

/// Key binding configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeyBindingConfig {
    /// Map of action to key sequences
    pub bindings: HashMap<String, Vec<String>>,
}

impl Default for KeyBindingConfig {
    fn default() -> Self {
        let mut bindings = HashMap::new();

        // Navigation
        bindings.insert("scroll_up".to_owned(), vec!["up".to_owned()]);
        bindings.insert("scroll_down".to_owned(), vec!["down".to_owned()]);
        bindings.insert("page_up".to_owned(), vec!["pageup".to_owned()]);
        bindings.insert("page_down".to_owned(), vec!["pagedown".to_owned()]);

        // Input
        bindings.insert("submit".to_owned(), vec!["enter".to_owned()]);
        bindings.insert("submit_queue".to_owned(), vec!["tab".to_owned()]);
        bindings.insert("cancel".to_owned(), vec!["esc".to_owned()]);
        bindings.insert("interrupt".to_owned(), vec!["ctrl+c".to_owned()]);

        Self { bindings }
    }
}

/// Behavior configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BehaviorConfig {
    /// Maximum lines for input area
    pub max_input_lines: usize,

    /// Whether to enable command history
    pub enable_history: bool,

    /// History size limit
    pub history_size: usize,

    /// Whether to enable double-tap escape to clear input
    pub double_tap_escape_clears: bool,

    /// Delay in milliseconds for double-tap detection
    pub double_tap_delay_ms: u64,

    /// Whether to auto-scroll to bottom
    pub auto_scroll_to_bottom: bool,

    /// Whether to show queued inputs
    pub show_queued_inputs: bool,
}

impl Default for BehaviorConfig {
    fn default() -> Self {
        Self {
            max_input_lines: 10,
            enable_history: true,
            history_size: 100,
            double_tap_escape_clears: true,
            double_tap_delay_ms: 300,
            auto_scroll_to_bottom: true,
            show_queued_inputs: true,
        }
    }
}

/// Performance configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceConfig {
    /// Cache size for rendered elements
    pub render_cache_size: usize,

    /// Transcript cache size (number of messages to cache)
    pub transcript_cache_size: usize,

    /// Whether to enable transcript reflow caching
    pub enable_transcript_caching: bool,

    /// Size of LRU cache for expensive operations
    pub lru_cache_size: usize,

    /// Whether to enable smooth scrolling
    pub enable_smooth_scrolling: bool,
}

impl Default for PerformanceConfig {
    fn default() -> Self {
        Self {
            render_cache_size: 1000,
            transcript_cache_size: 500,
            enable_transcript_caching: true,
            lru_cache_size: 128,
            enable_smooth_scrolling: false,
        }
    }
}

/// Customization configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CustomizationConfig {
    /// User-defined UI labels
    pub ui_labels: HashMap<String, String>,

    /// Custom styling options
    pub custom_styles: HashMap<String, String>,

    /// Enabled UI features
    pub enabled_features: Vec<String>,
}

impl Default for CustomizationConfig {
    fn default() -> Self {
        Self {
            ui_labels: HashMap::new(),
            custom_styles: HashMap::new(),
            enabled_features: vec![
                "slash_commands".to_owned(),
                "file_palette".to_owned(),
                "modal_dialogs".to_owned(),
            ],
        }
    }
}

impl SessionConfig {
    /// Creates a new default configuration
    #[allow(dead_code)]
    pub fn new() -> Self {
        Self::default()
    }

    /// Loads configuration from a file
    #[allow(dead_code)]
    pub fn load_from_file(path: &str) -> Result<Self, Box<dyn std::error::Error>> {
        let content = read_file_with_context_sync(Path::new(path), "session config file").map_err(
            |err| -> Box<dyn std::error::Error> { Box::new(std::io::Error::other(err)) },
        )?;
        let config: SessionConfig = toml::from_str(&content)?;
        Ok(config)
    }

    /// Saves configuration to a file
    #[allow(dead_code)]
    pub fn save_to_file(&self, path: &str) -> Result<(), Box<dyn std::error::Error>> {
        let content = toml::to_string_pretty(self)?;
        write_file_with_context_sync(Path::new(path), &content, "session config file").map_err(
            |err| -> Box<dyn std::error::Error> { Box::new(std::io::Error::other(err)) },
        )?;
        Ok(())
    }

    /// Updates a specific configuration value by key
    #[allow(dead_code)]
    pub fn set_value(&mut self, key: &str, value: &str) -> Result<(), String> {
        // This is a simplified version - in a real implementation, we'd have more sophisticated
        // parsing and validation for different configuration types
        match key {
            "behavior.max_input_lines" => {
                self.behavior.max_input_lines = value
                    .parse()
                    .map_err(|_| format!("Cannot parse '{}' as number", value))?;
            }
            "performance.lru_cache_size" => {
                self.performance.lru_cache_size = value
                    .parse()
                    .map_err(|_| format!("Cannot parse '{}' as number", value))?;
            }
            _ => return Err(format!("Unknown configuration key: {}", key)),
        }
        Ok(())
    }

    /// Gets a configuration value by key
    #[allow(dead_code)]
    pub fn get_value(&self, key: &str) -> Option<String> {
        match key {
            "behavior.max_input_lines" => Some(self.behavior.max_input_lines.to_string()),
            "performance.lru_cache_size" => Some(self.performance.lru_cache_size.to_string()),
            _ => None,
        }
    }

    /// Validates the configuration to ensure all values are within acceptable ranges
    #[allow(dead_code)]
    pub fn validate(&self) -> Result<(), Vec<String>> {
        let mut errors = Vec::new();

        if self.behavior.history_size == 0 {
            errors.push("history_size must be greater than 0".to_owned());
        }

        if self.performance.lru_cache_size == 0 {
            errors.push("lru_cache_size must be greater than 0".to_owned());
        }

        if self.appearance.navigation_width_percent > 100 {
            errors.push("navigation_width_percent must be between 0 and 100".to_owned());
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}

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

    #[test]
    fn test_default_config() {
        let config = SessionConfig::new();
        assert_eq!(config.behavior.history_size, 100);
        assert_eq!(
            config.appearance.reasoning_display_mode,
            ReasoningDisplayMode::Toggle
        );
        assert!(config.appearance.reasoning_visible_default);
        assert!(config.appearance.reasoning_visible());
    }

    #[test]
    fn test_config_serialization() {
        let config = SessionConfig::new();
        let serialized = toml::to_string_pretty(&config).unwrap();
        assert!(serialized.contains("theme"));
    }

    #[test]
    fn test_config_value_setting() {
        let mut config = SessionConfig::new();

        config.set_value("behavior.max_input_lines", "15").unwrap();
        assert_eq!(config.behavior.max_input_lines, 15);

        assert!(
            config
                .set_value("behavior.max_input_lines", "not_a_number")
                .is_err()
        );
    }

    #[test]
    fn test_config_value_getting() {
        let config = SessionConfig::new();
        assert_eq!(
            config.get_value("behavior.max_input_lines"),
            Some("10".to_owned())
        );
    }

    #[test]
    fn test_config_validation() {
        let config = SessionConfig::new();
        assert!(config.validate().is_ok());

        // Test invalid history size
        let mut invalid_config = config.clone();
        invalid_config.behavior.history_size = 0;
        assert!(invalid_config.validate().is_err());

        // Test invalid cache size
        let mut invalid_config2 = config.clone();
        invalid_config2.performance.lru_cache_size = 0;
        assert!(invalid_config2.validate().is_err());
    }

    #[test]
    fn test_config_with_custom_values() {
        let mut config = SessionConfig::new();

        // Test setting custom values
        config.behavior.max_input_lines = 20;
        config.performance.lru_cache_size = 256;

        assert_eq!(config.behavior.max_input_lines, 20);
        assert_eq!(config.performance.lru_cache_size, 256);
    }
}