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