Skip to main content

vtcode_ui/tui/core_tui/session/
config.rs

1//! Configuration system for TUI session UI preferences
2//!
3//! Contains settings for customizable UI elements, colors, key bindings, and other preferences.
4
5use hashbrown::HashMap;
6use serde::{Deserialize, Serialize};
7use std::path::Path;
8use vtcode_commons::fs::{read_file_with_context_sync, write_file_with_context_sync};
9
10/// Main configuration struct for TUI session preferences
11#[derive(Debug, Clone, Serialize, Deserialize, Default)]
12pub struct SessionConfig {
13    /// UI appearance settings
14    appearance: AppearanceConfig,
15
16    /// Key binding preferences
17    key_bindings: KeyBindingConfig,
18
19    /// Behavior preferences
20    behavior: BehaviorConfig,
21
22    /// Performance related settings
23    performance: PerformanceConfig,
24
25    /// Customization settings
26    customization: CustomizationConfig,
27}
28
29// Re-export shared enums from vtcode-commons.
30pub use vtcode_commons::ui_protocol::{
31    BusyEnterBehavior, DiffPreviewMode, LayoutModeOverride, ReasoningDisplayMode, ThinkingBlockState, UiMode,
32};
33
34/// UI appearance configuration
35#[derive(Debug, Clone, Serialize, Deserialize)]
36pub struct AppearanceConfig {
37    /// Color theme to use
38    pub theme: String,
39
40    /// UI mode variant (full, minimal, focused)
41    pub ui_mode: UiMode,
42
43    /// Whether to show the right sidebar (queue, context, tools)
44    pub show_sidebar: bool,
45
46    /// Minimum width for content area
47    pub min_content_width: u16,
48
49    /// Minimum width for navigation area
50    pub min_navigation_width: u16,
51
52    /// Percentage of width for navigation area
53    pub navigation_width_percent: u8,
54
55    /// Transcript bottom padding.
56    ///
57    /// Deprecated: retained for serialized-config compatibility only (including
58    /// the `vtcode-core` mirror field, which carries the same note). The live
59    /// transcript uses `INLINE_TRANSCRIPT_BOTTOM_PADDING`
60    /// via `effective_transcript_bottom_padding()`;
61    /// this field is never read at render time.
62    pub transcript_bottom_padding: u16,
63
64    /// Whether to dim completed todo items (- \[x\] and ~~strikethrough~~)
65    pub dim_completed_todos: bool,
66
67    /// Automatically show the plan-mode TODO task tracking panel when a plan
68    /// is approved or the task tracker is updated.
69    #[serde(default)]
70    pub show_task_panel: bool,
71
72    /// Number of blank lines between message blocks (0-2)
73    pub message_block_spacing: u8,
74
75    /// Override responsive layout mode
76    #[serde(default)]
77    pub layout_mode: LayoutModeOverride,
78
79    /// Reasoning visibility mode
80    #[serde(default)]
81    pub reasoning_display_mode: ReasoningDisplayMode,
82
83    /// Default reasoning visibility when mode is "toggle"
84    #[serde(default)]
85    pub reasoning_visible_default: bool,
86
87    /// Default collapse state of agent thinking/reasoning blocks
88    #[serde(default)]
89    pub thinking_display: ThinkingBlockState,
90
91    /// Enable Vim-style input editing for the prompt.
92    #[serde(default)]
93    pub vim_mode: bool,
94
95    /// Enable Readline-style input editing for the prompt.
96    /// This adds Emacs-style keybindings like Ctrl+F/B for navigation,
97    /// Ctrl+P/N for history, Alt+D for kill word forward, etc.
98    #[serde(default)]
99    pub readline_mode: bool,
100
101    /// How plain Enter submits while a turn is running (queue or steer).
102    #[serde(default)]
103    pub busy_enter_behavior: BusyEnterBehavior,
104
105    /// Screen reader mode (disables animation-heavy rendering paths)
106    #[serde(default)]
107    pub screen_reader_mode: bool,
108
109    /// Reduce motion mode (keeps progress labels visible without animated effects)
110    #[serde(default)]
111    pub reduce_motion_mode: bool,
112
113    /// Keep progress animation while reduce motion mode is enabled.
114    /// Screen reader mode still disables progress animation.
115    #[serde(default)]
116    pub reduce_motion_keep_progress_animation: bool,
117
118    /// Hide the full TUI header, showing only version info in a compact line
119    #[serde(default)]
120    pub hide_header: bool,
121
122    /// Show the clickable/keyboard affordance on compact command rows.
123    #[serde(default = "default_transcript_review_control")]
124    pub show_transcript_review_hints: bool,
125
126    /// Show the keyboard guide footer inside Transcript Review.
127    #[serde(default = "default_transcript_review_control")]
128    pub show_transcript_review_shortcut_guide: bool,
129
130    /// Show the mouse-clickable close control in the Transcript Review title.
131    #[serde(default = "default_transcript_review_control")]
132    pub show_transcript_review_close_button: bool,
133
134    /// Diff preview layout for file-edit approval overlays.
135    #[serde(default)]
136    pub diff_preview_mode: DiffPreviewMode,
137
138    /// Syntax highlighting for the code surfaces the TUI renders itself
139    /// (diagnostic evidence bodies). The code palette follows the active UI
140    /// theme; this decides whether highlighting happens and which languages
141    /// are eligible.
142    #[serde(default)]
143    pub syntax_highlighting: vtcode_config::loader::SyntaxHighlightingConfig,
144
145    /// Customization settings
146    pub customization: CustomizationConfig,
147}
148
149impl Default for AppearanceConfig {
150    fn default() -> Self {
151        Self {
152            theme: "default".to_owned(),
153            ui_mode: UiMode::Full,
154            show_sidebar: true,
155            min_content_width: 40,
156            min_navigation_width: 20,
157            navigation_width_percent: 25,
158            transcript_bottom_padding: 0,
159            dim_completed_todos: true,
160            show_task_panel: false,
161            // Default 1 provides a single blank line between blocks (unified vertical rhythm).
162            // `tool_block_spacing` clamps 1..2, so tool blocks remain visually grouped even when
163            // this is 0. Previously 0 produced a cramped transcript; 1 matches the approved UX.
164            message_block_spacing: 1,
165            layout_mode: LayoutModeOverride::Auto,
166            reasoning_display_mode: ReasoningDisplayMode::Toggle,
167            reasoning_visible_default: crate::tui::config::constants::ui::DEFAULT_REASONING_VISIBLE,
168            thinking_display: ThinkingBlockState::Collapsed,
169            vim_mode: false,
170            readline_mode: false,
171            busy_enter_behavior: BusyEnterBehavior::Queue,
172            screen_reader_mode: false,
173            reduce_motion_mode: false,
174            reduce_motion_keep_progress_animation: false,
175            hide_header: true,
176            show_transcript_review_hints: default_transcript_review_control(),
177            show_transcript_review_shortcut_guide: default_transcript_review_control(),
178            show_transcript_review_close_button: default_transcript_review_control(),
179            diff_preview_mode: DiffPreviewMode::Inline,
180            syntax_highlighting: vtcode_config::loader::SyntaxHighlightingConfig::default(),
181            customization: CustomizationConfig::default(),
182        }
183    }
184}
185
186fn default_transcript_review_control() -> bool {
187    true
188}
189
190impl AppearanceConfig {
191    /// Check if sidebar should be shown based on ui_mode and show_sidebar
192    pub(crate) fn should_show_sidebar(&self) -> bool {
193        match self.ui_mode {
194            UiMode::Full => self.show_sidebar,
195            UiMode::Minimal | UiMode::Focused => false,
196        }
197    }
198
199    /// Whether the plan-mode TODO task tracking panel may auto-show.
200    pub(crate) fn should_show_task_panel(&self) -> bool {
201        self.show_task_panel
202    }
203
204    fn reasoning_visible(&self) -> bool {
205        match self.reasoning_display_mode {
206            ReasoningDisplayMode::Always => true,
207            ReasoningDisplayMode::Hidden => false,
208            ReasoningDisplayMode::Toggle => self.reasoning_visible_default,
209        }
210    }
211
212    /// Whether thinking/reasoning blocks should render collapsed by default.
213    pub(crate) fn thinking_collapsed_by_default(&self) -> bool {
214        self.thinking_display == ThinkingBlockState::Collapsed
215    }
216
217    /// Whether progress effects animate; screen reader mode always suppresses them.
218    pub(crate) fn should_animate_progress_status(&self) -> bool {
219        !self.screen_reader_mode && (!self.reduce_motion_mode || self.reduce_motion_keep_progress_animation)
220    }
221
222    /// Check if footer should be shown based on ui_mode
223    pub fn should_show_footer(&self) -> bool {
224        match self.ui_mode {
225            UiMode::Full => true,
226            UiMode::Minimal => false,
227            UiMode::Focused => false,
228        }
229    }
230}
231
232/// Key binding configuration
233#[derive(Debug, Clone, Serialize, Deserialize)]
234pub struct KeyBindingConfig {
235    /// Map of action to key sequences
236    bindings: HashMap<String, Vec<String>>,
237}
238
239impl Default for KeyBindingConfig {
240    fn default() -> Self {
241        let mut bindings = HashMap::new();
242
243        // Navigation
244        bindings.insert("scroll_up".to_owned(), vec!["up".to_owned()]);
245        bindings.insert("scroll_down".to_owned(), vec!["down".to_owned()]);
246        bindings.insert("page_up".to_owned(), vec!["pageup".to_owned()]);
247        bindings.insert("page_down".to_owned(), vec!["pagedown".to_owned()]);
248
249        // Input
250        bindings.insert("submit".to_owned(), vec!["enter".to_owned()]);
251        bindings.insert("submit_queue".to_owned(), vec!["tab".to_owned()]);
252        bindings.insert("cancel".to_owned(), vec!["esc".to_owned()]);
253        bindings.insert("interrupt".to_owned(), vec!["ctrl+c".to_owned()]);
254
255        Self { bindings }
256    }
257}
258
259/// Behavior configuration
260#[derive(Debug, Clone, Serialize, Deserialize)]
261pub struct BehaviorConfig {
262    /// Maximum lines for input area
263    max_input_lines: usize,
264
265    /// Whether to enable command history
266    enable_history: bool,
267
268    /// History size limit
269    history_size: usize,
270
271    /// Whether to show queued inputs
272    show_queued_inputs: bool,
273}
274
275impl Default for BehaviorConfig {
276    fn default() -> Self {
277        Self {
278            max_input_lines: 10,
279            enable_history: true,
280            history_size: 100,
281            show_queued_inputs: true,
282        }
283    }
284}
285
286/// Performance configuration
287#[derive(Debug, Clone, Serialize, Deserialize)]
288pub struct PerformanceConfig {
289    /// Cache size for rendered elements
290    render_cache_size: usize,
291
292    /// Transcript cache size (number of messages to cache)
293    transcript_cache_size: usize,
294
295    /// Whether to enable transcript reflow caching
296    enable_transcript_caching: bool,
297
298    /// Size of LRU cache for expensive operations
299    lru_cache_size: usize,
300
301    /// Whether to enable smooth scrolling
302    enable_smooth_scrolling: bool,
303}
304
305impl Default for PerformanceConfig {
306    fn default() -> Self {
307        Self {
308            render_cache_size: 1000,
309            transcript_cache_size: 500,
310            enable_transcript_caching: true,
311            lru_cache_size: 128,
312            enable_smooth_scrolling: false,
313        }
314    }
315}
316
317/// Customization configuration
318#[derive(Debug, Clone, Serialize, Deserialize)]
319pub struct CustomizationConfig {
320    /// User-defined UI labels
321    ui_labels: HashMap<String, String>,
322
323    /// Custom styling options
324    custom_styles: HashMap<String, String>,
325
326    /// Enabled UI features
327    enabled_features: Vec<String>,
328}
329
330impl Default for CustomizationConfig {
331    fn default() -> Self {
332        Self {
333            ui_labels: HashMap::new(),
334            custom_styles: HashMap::new(),
335            enabled_features: vec![
336                "slash_commands".to_owned(),
337                "file_palette".to_owned(),
338                "modal_dialogs".to_owned(),
339            ],
340        }
341    }
342}
343
344impl SessionConfig {
345    /// Creates a new default configuration
346    fn new() -> Self {
347        Self::default()
348    }
349
350    /// Loads configuration from a file
351    pub fn load_from_file(path: &str) -> Result<Self, Box<dyn std::error::Error>> {
352        let content = read_file_with_context_sync(Path::new(path), "session config file")
353            .map_err(|err| -> Box<dyn std::error::Error> { Box::new(std::io::Error::other(err)) })?;
354        let config: SessionConfig = toml::from_str(&content)?;
355        Ok(config)
356    }
357
358    /// Saves configuration to a file
359    pub fn save_to_file(&self, path: &str) -> Result<(), Box<dyn std::error::Error>> {
360        let content = toml::to_string_pretty(self)?;
361        write_file_with_context_sync(Path::new(path), &content, "session config file")
362            .map_err(|err| -> Box<dyn std::error::Error> { Box::new(std::io::Error::other(err)) })?;
363        Ok(())
364    }
365
366    /// Updates a specific configuration value by key
367    fn set_value(&mut self, key: &str, value: &str) -> Result<(), String> {
368        // This is a simplified version - in a real implementation, we'd have more sophisticated
369        // parsing and validation for different configuration types
370        match key {
371            "behavior.max_input_lines" => {
372                self.behavior.max_input_lines =
373                    value.parse().map_err(|_| format!("Cannot parse '{value}' as number"))?;
374            }
375            "performance.lru_cache_size" => {
376                self.performance.lru_cache_size =
377                    value.parse().map_err(|_| format!("Cannot parse '{value}' as number"))?;
378            }
379            _ => return Err(format!("Unknown configuration key: {key}")),
380        }
381        Ok(())
382    }
383
384    /// Gets a configuration value by key
385    fn get_value(&self, key: &str) -> Option<String> {
386        match key {
387            "behavior.max_input_lines" => Some(self.behavior.max_input_lines.to_string()),
388            "performance.lru_cache_size" => Some(self.performance.lru_cache_size.to_string()),
389            _ => None,
390        }
391    }
392
393    /// Validates the configuration to ensure all values are within acceptable ranges
394    fn validate(&self) -> Result<(), Vec<String>> {
395        let mut errors = Vec::new();
396
397        if self.behavior.history_size == 0 {
398            errors.push("history_size must be greater than 0".to_owned());
399        }
400
401        if self.performance.lru_cache_size == 0 {
402            errors.push("lru_cache_size must be greater than 0".to_owned());
403        }
404
405        if self.appearance.navigation_width_percent > 100 {
406            errors.push("navigation_width_percent must be between 0 and 100".to_owned());
407        }
408
409        if errors.is_empty() { Ok(()) } else { Err(errors) }
410    }
411}
412
413#[cfg(test)]
414mod tests {
415    use super::*;
416
417    #[test]
418    fn test_default_config() {
419        let config = SessionConfig::new();
420        assert_eq!(config.behavior.history_size, 100);
421        assert_eq!(config.appearance.reasoning_display_mode, ReasoningDisplayMode::Toggle);
422        assert!(config.appearance.reasoning_visible_default);
423        assert!(config.appearance.reasoning_visible());
424        assert_eq!(config.appearance.thinking_display, ThinkingBlockState::Collapsed);
425        assert!(config.appearance.thinking_collapsed_by_default());
426    }
427
428    #[test]
429    fn test_task_panel_default_hidden() {
430        let mut config = SessionConfig::new();
431        assert!(!config.appearance.show_task_panel);
432        assert!(!config.appearance.should_show_task_panel());
433
434        config.appearance.show_task_panel = true;
435        assert!(config.appearance.should_show_task_panel());
436    }
437
438    #[test]
439    fn test_thinking_display_default_collapsed() {
440        let config = SessionConfig::new();
441        assert_eq!(config.appearance.thinking_display, ThinkingBlockState::Collapsed);
442        assert!(config.appearance.thinking_collapsed_by_default());
443    }
444
445    #[test]
446    fn test_thinking_display_override_extended() {
447        let mut config = SessionConfig::new();
448        config.appearance.thinking_display = ThinkingBlockState::Extended;
449        assert!(!config.appearance.thinking_collapsed_by_default());
450    }
451
452    #[test]
453    fn test_config_serialization() {
454        let config = SessionConfig::new();
455        let serialized = toml::to_string_pretty(&config).unwrap();
456        assert!(serialized.contains("theme"));
457    }
458
459    #[test]
460    fn test_config_value_setting() {
461        let mut config = SessionConfig::new();
462
463        config.set_value("behavior.max_input_lines", "15").unwrap();
464        assert_eq!(config.behavior.max_input_lines, 15);
465
466        assert!(config.set_value("behavior.max_input_lines", "not_a_number").is_err());
467    }
468
469    #[test]
470    fn test_config_value_getting() {
471        let config = SessionConfig::new();
472        assert_eq!(config.get_value("behavior.max_input_lines"), Some("10".to_owned()));
473    }
474
475    #[test]
476    fn test_config_validation() {
477        let config = SessionConfig::new();
478        config.validate().unwrap();
479
480        // Test invalid history size
481        let mut invalid_config = config.clone();
482        invalid_config.behavior.history_size = 0;
483        assert!(invalid_config.validate().is_err());
484
485        // Test invalid cache size
486        let mut invalid_config2 = config.clone();
487        invalid_config2.performance.lru_cache_size = 0;
488        assert!(invalid_config2.validate().is_err());
489    }
490
491    #[test]
492    fn test_config_with_custom_values() {
493        let mut config = SessionConfig::new();
494
495        // Test setting custom values
496        config.behavior.max_input_lines = 20;
497        config.performance.lru_cache_size = 256;
498
499        assert_eq!(config.behavior.max_input_lines, 20);
500        assert_eq!(config.performance.lru_cache_size, 256);
501    }
502}