Skip to main content

vtcode_config/root/
mod.rs

1use anyhow::{Result, anyhow, bail};
2use hashbrown::HashMap;
3use serde::{Deserialize, Serialize};
4
5use crate::accessibility::reduce_motion_preference;
6use crate::status_line::StatusLineConfig;
7use crate::terminal_title::TerminalTitleConfig;
8use vtcode_commons::ui_protocol::AmbiguousWidthMode;
9use vtcode_commons::ui_protocol::AppIconPreference;
10use vtcode_commons::ui_protocol::BusyEnterBehavior;
11use vtcode_commons::ui_protocol::DiffPreviewMode;
12
13mod modes;
14
15pub use modes::{
16    LayoutModeOverride, NotificationBackend, NotificationDeliveryMode, ReasoningDisplayMode, ToolDisplayMode,
17    ToolOutputMode, UiDisplayMode,
18};
19
20mod notifications;
21
22pub use notifications::UiNotificationsConfig;
23
24#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
25#[derive(Debug, Clone, Deserialize, Serialize)]
26pub struct UiFullscreenConfig {
27    /// Capture mouse events inside the fullscreen UI.
28    /// Can also be controlled via VTCODE_FULLSCREEN_MOUSE_CAPTURE=0/1.
29    #[serde(default = "default_fullscreen_mouse_capture")]
30    pub mouse_capture: bool,
31
32    /// Copy selected transcript text immediately when the mouse selection ends
33    /// (click-drag or double-click word select).
34    /// When disabled, copy manually with Ctrl+C (transcript/input selection)
35    /// or Ctrl+O (last agent response).
36    /// Can also be controlled via VTCODE_FULLSCREEN_COPY_ON_SELECT=0/1.
37    #[serde(default = "default_fullscreen_copy_on_select")]
38    pub copy_on_select: bool,
39
40    /// Multiplier applied to mouse wheel transcript scrolling in fullscreen mode.
41    /// Values are clamped to the range 1..=20.
42    /// Can also be controlled via VTCODE_FULLSCREEN_SCROLL_SPEED.
43    #[serde(default = "default_fullscreen_scroll_speed")]
44    pub scroll_speed: u8,
45}
46
47impl Default for UiFullscreenConfig {
48    fn default() -> Self {
49        Self {
50            mouse_capture: default_fullscreen_mouse_capture(),
51            copy_on_select: default_fullscreen_copy_on_select(),
52            scroll_speed: default_fullscreen_scroll_speed(),
53        }
54    }
55}
56
57/// Presentation controls for the session-local Transcript Review overlay.
58/// These settings affect only the interactive UI; captured transcript content
59/// and exported output remain complete and independent of the controls.
60#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
61#[derive(Debug, Clone, Deserialize, Serialize)]
62pub struct UiTranscriptReviewConfig {
63    /// Show the click/keyboard affordance on compact command rows.
64    #[serde(default = "default_transcript_review_control")]
65    pub show_hints: bool,
66
67    /// Show the keyboard guide footer inside Transcript Review.
68    #[serde(default = "default_transcript_review_control")]
69    pub show_shortcut_guide: bool,
70
71    /// Show the mouse-clickable close control in the Transcript Review title.
72    #[serde(default = "default_transcript_review_control")]
73    pub show_close_button: bool,
74}
75
76impl Default for UiTranscriptReviewConfig {
77    fn default() -> Self {
78        Self {
79            show_hints: default_transcript_review_control(),
80            show_shortcut_guide: default_transcript_review_control(),
81            show_close_button: default_transcript_review_control(),
82        }
83    }
84}
85
86#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
87#[derive(Debug, Clone, Deserialize, Serialize)]
88pub struct UiConfig {
89    /// Tool output display mode ("compact" or "full")
90    #[serde(default = "default_tool_output_mode")]
91    pub tool_output_mode: ToolOutputMode,
92
93    /// Tool transition summary display mode
94    /// Options: "expanded" (expanded summary layout) or "compact" (one compact summary per tool call)
95    #[serde(default = "default_tool_display_mode")]
96    pub tool_display_mode: ToolDisplayMode,
97
98    /// Phrase live tool callouts with the desktop verb headline (`Read
99    /// main.rs`, `Ran cargo check`) instead of the raw tool name (`Running
100    /// tool: read_file`). Enabled by default; disabling restores raw names.
101    #[serde(default = "default_verb_callouts")]
102    pub verb_callouts: bool,
103
104    /// Session action bindings. Each action maps to one or more key specs;
105    /// an empty list explicitly unbinds the built-in action.
106    #[serde(default, alias = "key_bindings")]
107    #[cfg_attr(
108        feature = "schema",
109        schemars(with = "std::collections::BTreeMap<String, Vec<String>>")
110    )]
111    pub keybindings: HashMap<String, Vec<String>>,
112
113    /// Maximum number of lines to display in tool output (prevents transcript flooding)
114    #[serde(default = "default_tool_output_max_lines")]
115    pub tool_output_max_lines: usize,
116
117    /// Maximum bytes of output to display before auto-spooling to disk
118    #[serde(default = "default_tool_output_spool_bytes")]
119    pub tool_output_spool_bytes: usize,
120
121    /// Optional custom directory for spooled tool output logs
122    #[serde(default)]
123    pub tool_output_spool_dir: Option<String>,
124
125    /// Allow ANSI escape sequences in tool output (enables colors but may cause layout issues)
126    #[serde(default = "default_allow_tool_ansi")]
127    pub allow_tool_ansi: bool,
128
129    /// Number of rows to allocate for inline UI viewport
130    #[serde(default = "default_inline_viewport_rows")]
131    pub inline_viewport_rows: u16,
132
133    /// Reasoning display mode for chat UI ("always", "toggle", or "hidden"). Options: "always", "toggle", "hidden".
134    #[serde(default = "default_reasoning_display_mode")]
135    pub reasoning_display_mode: ReasoningDisplayMode,
136
137    /// Default visibility for reasoning when display mode is "toggle"
138    #[serde(default = "default_reasoning_visible_default")]
139    pub reasoning_visible_default: bool,
140
141    /// Default collapse state of agent thinking/reasoning blocks ("collapsed" or "extended")
142    #[serde(default = "default_thinking_display")]
143    pub thinking_display: vtcode_commons::ui_protocol::ThinkingBlockState,
144
145    /// How much routine agent-internal failure chatter reaches the interactive transcript ("balanced", "quiet", or "verbose"). Applies to new sessions; already-running sessions keep the value they started with. Options: "balanced", "quiet", "verbose".
146    #[serde(default = "default_communication_style")]
147    pub communication_style: vtcode_commons::ui_protocol::CommunicationStyle,
148
149    /// Enable Vim-style prompt editing in the interactive terminal UI.
150    #[serde(default = "default_vim_mode")]
151    pub vim_mode: bool,
152
153    /// How plain Enter submits while a turn is running ("queue" or "steer").
154    /// "queue" (default) holds each message for the next turn; "steer" injects
155    /// plain-text input into the live turn via the steering channel. Slash
156    /// commands and attachments always queue. Options: "queue", "steer".
157    #[serde(default = "default_busy_enter_behavior")]
158    pub busy_enter_behavior: BusyEnterBehavior,
159
160    /// Status line configuration settings
161    #[serde(default)]
162    pub status_line: StatusLineConfig,
163
164    /// Terminal title configuration settings
165    #[serde(default)]
166    pub terminal_title: TerminalTitleConfig,
167
168    /// Keyboard protocol enhancements for modern terminals (e.g. Kitty protocol)
169    #[serde(default)]
170    pub keyboard_protocol: KeyboardProtocolConfig,
171
172    /// Override the responsive layout mode
173    #[serde(default)]
174    pub layout_mode: LayoutModeOverride,
175
176    /// UI display mode preset (full, minimal, focused)
177    #[serde(default)]
178    pub display_mode: UiDisplayMode,
179
180    /// Show the right sidebar (queue, context, tools)
181    #[serde(default = "default_show_sidebar")]
182    pub show_sidebar: bool,
183
184    /// Dim completed todo items (- \[x\]) in agent output
185    #[serde(default = "default_dim_completed_todos")]
186    pub dim_completed_todos: bool,
187
188    /// Automatically show the plan-mode TODO task tracking panel when a plan
189    /// is approved or the task tracker is updated. When disabled, the panel
190    /// can still be toggled with the `toggle_task_panel` keybinding.
191    #[serde(default = "default_show_task_panel")]
192    pub show_task_panel: bool,
193
194    /// Add spacing between message blocks
195    #[serde(default = "default_message_block_spacing")]
196    pub message_block_spacing: bool,
197
198    /// Show per-turn elapsed timer line after completed turns
199    #[serde(default = "default_show_turn_timer")]
200    pub show_turn_timer: bool,
201
202    /// Show warning/error/fatal diagnostic lines in the TUI transcript and log panel.
203    /// Also controls whether ERROR-level tracing logs appear in the TUI session log.
204    /// Errors are always captured in the session archive JSON regardless of this setting.
205    #[serde(default = "default_show_diagnostics_in_transcript")]
206    pub show_diagnostics_in_transcript: bool,
207
208    /// Show one wall-clock footer after the final agent message of each turn.
209    #[serde(default = "default_show_message_timestamps")]
210    pub show_message_timestamps: bool,
211
212    // === Color Accessibility Configuration ===
213    // Based on NO_COLOR standard, Ghostty minimum-contrast, and terminal color portability research.
214    /// Minimum contrast ratio for text against background (WCAG 2.1 standard)
215    /// - 4.5: WCAG AA (default, suitable for most users)
216    /// - 7.0: WCAG AAA (enhanced, for low-vision users)
217    /// - 3.0: Large text minimum
218    /// - 1.0: Disable contrast enforcement
219    #[serde(default = "default_minimum_contrast")]
220    pub minimum_contrast: f32,
221
222    /// Raise the effective text contrast floor to WCAG AAA (7.0:1) in the TUI.
223    /// Can also be enabled with VTCODE_HIGH_CONTRAST=1. It wins over
224    /// `minimum_contrast` without rewriting the saved value. The desktop app
225    /// does not read this setting; it has its own independent Accessibility →
226    /// High contrast switch.
227    #[serde(default = "default_high_contrast_mode")]
228    pub high_contrast_mode: bool,
229
230    /// Compatibility mode for legacy terminals that map bold to bright colors.
231    /// When enabled, avoids using bold styling on text that would become bright colors,
232    /// preventing visibility issues in terminals with "bold is bright" behavior.
233    #[serde(default = "default_bold_is_bright")]
234    pub bold_is_bright: bool,
235
236    /// How the terminal renders East-Asian-ambiguous-width glyphs (UAX #11),
237    /// which include every box-drawing character. Terminals set to render the
238    /// set as double width (xterm `cjkWidth`, iTerm2's ambiguous-width
239    /// checkbox, some CJK-locale defaults) draw each glyph as two cells, so
240    /// box-drawing frames and table rules break. Not detectable at runtime.
241    /// Can also be controlled via VTCODE_AMBIGUOUS_WIDTH=wide.
242    /// - "narrow": ambiguous glyphs occupy one cell (default)
243    /// - "wide": ambiguous glyphs occupy two cells; chrome degrades to ASCII
244    ///   and width math counts the glyphs as wide
245    #[serde(default = "default_ambiguous_width")]
246    pub ambiguous_width: AmbiguousWidthMode,
247
248    /// Restrict color palette to the 11 "safe" ANSI colors portable across common themes.
249    /// Safe colors: red, green, yellow, blue, magenta, cyan + brred, brgreen, brmagenta, brcyan
250    /// Problematic colors avoided: brblack (invisible in Solarized Dark), bryellow (light themes),
251    /// white/brwhite (light themes), brblue (Basic Dark).
252    /// See: <https://blog.xoria.org/terminal-colors/>
253    #[serde(default = "default_safe_colors_only")]
254    pub safe_colors_only: bool,
255
256    /// Color scheme mode for automatic light/dark theme switching.
257    /// - "auto": Detect from terminal (via the Contour dark/light query where supported, else OSC 11, or the COLORFGBG env var) and follow live palette changes
258    /// - "light": Force light mode theme selection
259    /// - "dark": Force dark mode theme selection
260    #[serde(default = "default_color_scheme_mode")]
261    pub color_scheme_mode: ColorSchemeMode,
262
263    /// Application icon artwork variant for terminal tab icons and the desktop picker.
264    /// - "dynamic": Follow the active light/dark mode (default)
265    /// - "light": Always use the light-mode artwork
266    /// - "dark": Always use the dark-mode artwork
267    /// - "clear": Always use the clear (glass V on a subtle translucent tile) artwork
268    /// - "tinted": Always use the tinted (monochrome slate) artwork
269    #[serde(default = "default_app_icon")]
270    pub app_icon: AppIconPreference,
271
272    /// Terminal program status reports for the interactive TUI (on by default).
273    #[serde(default)]
274    pub program_status: UiProgramStatusConfig,
275
276    /// Notification preferences for attention events.
277    #[serde(default)]
278    pub notifications: UiNotificationsConfig,
279
280    /// Fullscreen interaction settings for alternate-screen rendering.
281    #[serde(default)]
282    pub fullscreen: UiFullscreenConfig,
283
284    /// Screen reader mode: disables animations, uses plain text thinking indicators,
285    /// and opens Transcript Review in raw mode. Alternate-screen compatibility
286    /// depends on the terminal and assistive technology.
287    /// Can also be enabled via VTCODE_SCREEN_READER=1 environment variable.
288    #[serde(default = "default_screen_reader_mode")]
289    pub screen_reader_mode: bool,
290
291    /// Reduce motion mode: keeps progress labels visible without animated effects.
292    /// If omitted, defaults from VTCODE_REDUCE_MOTION, then a supported OS
293    /// accessibility preference; unknown or unavailable preferences default to false.
294    #[serde(default = "default_reduce_motion_mode")]
295    pub reduce_motion_mode: bool,
296
297    /// Keep animated progress indicators while reduce_motion_mode is enabled.
298    /// Screen reader mode still disables progress animation.
299    #[serde(default = "default_reduce_motion_keep_progress_animation")]
300    pub reduce_motion_keep_progress_animation: bool,
301
302    /// Hide the full TUI header, showing only version info in a compact line.
303    #[serde(default = "default_hide_header")]
304    pub hide_header: bool,
305
306    /// Diff preview layout for file-edit approval overlays.
307    /// Options: "inline" (default) or "side-by-side".
308    #[serde(default = "default_diff_preview_mode")]
309    pub diff_preview_mode: DiffPreviewMode,
310
311    /// Transcript Review presentation controls.
312    #[serde(default)]
313    pub transcript_review: UiTranscriptReviewConfig,
314}
315
316/// Color scheme mode for theme selection
317#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
318#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Default)]
319#[serde(rename_all = "snake_case")]
320pub enum ColorSchemeMode {
321    /// Detect from terminal environment (OSC 11 query or COLORFGBG)
322    #[default]
323    Auto,
324    /// Force light color scheme
325    Light,
326    /// Force dark color scheme
327    Dark,
328    /// Catch-all for unknown modes added by future versions.
329    #[serde(other)]
330    Unknown,
331}
332
333fn default_minimum_contrast() -> f32 {
334    crate::constants::ui::THEME_MIN_CONTRAST_RATIO
335}
336
337fn default_high_contrast_mode() -> bool {
338    env_bool_var("VTCODE_HIGH_CONTRAST").unwrap_or(false)
339}
340
341fn default_bold_is_bright() -> bool {
342    false
343}
344
345fn default_safe_colors_only() -> bool {
346    false
347}
348
349fn default_color_scheme_mode() -> ColorSchemeMode {
350    ColorSchemeMode::Auto
351}
352
353fn default_app_icon() -> AppIconPreference {
354    AppIconPreference::Dynamic
355}
356
357fn default_show_sidebar() -> bool {
358    true
359}
360
361fn default_dim_completed_todos() -> bool {
362    true
363}
364
365fn default_message_block_spacing() -> bool {
366    true
367}
368
369fn default_program_status_enabled() -> bool {
370    true
371}
372
373fn default_show_turn_timer() -> bool {
374    false
375}
376
377fn default_show_diagnostics_in_transcript() -> bool {
378    false
379}
380
381fn default_show_message_timestamps() -> bool {
382    true
383}
384
385fn default_vim_mode() -> bool {
386    false
387}
388
389fn default_busy_enter_behavior() -> BusyEnterBehavior {
390    BusyEnterBehavior::Queue
391}
392
393fn env_bool_var(name: &str) -> Option<bool> {
394    crate::env_helpers::read_env_var(name).and_then(|v| vtcode_commons::utils::parse_bool_env_value(&v))
395}
396
397fn env_u8_var(name: &str) -> Option<u8> {
398    crate::env_helpers::read_env_var(name)
399        .and_then(|value| value.trim().parse::<u8>().ok())
400        .map(clamp_fullscreen_scroll_speed)
401}
402
403fn clamp_fullscreen_scroll_speed(value: u8) -> u8 {
404    value.clamp(1, 20)
405}
406
407fn default_fullscreen_mouse_capture() -> bool {
408    env_bool_var("VTCODE_FULLSCREEN_MOUSE_CAPTURE").unwrap_or(true)
409}
410
411fn default_fullscreen_copy_on_select() -> bool {
412    env_bool_var("VTCODE_FULLSCREEN_COPY_ON_SELECT").unwrap_or(true)
413}
414
415fn default_fullscreen_scroll_speed() -> u8 {
416    env_u8_var("VTCODE_FULLSCREEN_SCROLL_SPEED").unwrap_or(3)
417}
418
419fn default_screen_reader_mode() -> bool {
420    env_bool_var("VTCODE_SCREEN_READER").unwrap_or(false)
421}
422
423fn default_ambiguous_width() -> AmbiguousWidthMode {
424    match crate::env_helpers::read_env_var("VTCODE_AMBIGUOUS_WIDTH")
425        .map(|value| value.trim().to_ascii_lowercase())
426        .as_deref()
427    {
428        Some("wide") => AmbiguousWidthMode::Wide,
429        Some("narrow") => AmbiguousWidthMode::Narrow,
430        _ => AmbiguousWidthMode::default(),
431    }
432}
433
434fn default_reduce_motion_mode() -> bool {
435    env_bool_var("VTCODE_REDUCE_MOTION")
436        .or_else(reduce_motion_preference)
437        .unwrap_or(false)
438}
439
440fn default_reduce_motion_keep_progress_animation() -> bool {
441    false
442}
443
444fn default_hide_header() -> bool {
445    true
446}
447
448fn default_diff_preview_mode() -> DiffPreviewMode {
449    DiffPreviewMode::Inline
450}
451
452fn default_transcript_review_control() -> bool {
453    true
454}
455
456fn default_show_task_panel() -> bool {
457    false
458}
459
460fn default_ask_questions_enabled() -> bool {
461    true
462}
463
464impl Default for UiConfig {
465    fn default() -> Self {
466        Self {
467            tool_output_mode: default_tool_output_mode(),
468            tool_display_mode: default_tool_display_mode(),
469            verb_callouts: default_verb_callouts(),
470            keybindings: HashMap::new(),
471            tool_output_max_lines: default_tool_output_max_lines(),
472            tool_output_spool_bytes: default_tool_output_spool_bytes(),
473            tool_output_spool_dir: None,
474            allow_tool_ansi: default_allow_tool_ansi(),
475            inline_viewport_rows: default_inline_viewport_rows(),
476            reasoning_display_mode: default_reasoning_display_mode(),
477            reasoning_visible_default: default_reasoning_visible_default(),
478            thinking_display: default_thinking_display(),
479            communication_style: default_communication_style(),
480            vim_mode: default_vim_mode(),
481            busy_enter_behavior: default_busy_enter_behavior(),
482            status_line: StatusLineConfig::default(),
483            terminal_title: TerminalTitleConfig::default(),
484            keyboard_protocol: KeyboardProtocolConfig::default(),
485            layout_mode: LayoutModeOverride::default(),
486            display_mode: UiDisplayMode::default(),
487            show_sidebar: default_show_sidebar(),
488            dim_completed_todos: default_dim_completed_todos(),
489            show_task_panel: default_show_task_panel(),
490            message_block_spacing: default_message_block_spacing(),
491            show_turn_timer: default_show_turn_timer(),
492            show_diagnostics_in_transcript: default_show_diagnostics_in_transcript(),
493            show_message_timestamps: default_show_message_timestamps(),
494            // Color accessibility defaults
495            minimum_contrast: default_minimum_contrast(),
496            high_contrast_mode: default_high_contrast_mode(),
497            bold_is_bright: default_bold_is_bright(),
498            ambiguous_width: default_ambiguous_width(),
499            safe_colors_only: default_safe_colors_only(),
500            color_scheme_mode: default_color_scheme_mode(),
501            app_icon: default_app_icon(),
502            program_status: UiProgramStatusConfig::default(),
503            notifications: UiNotificationsConfig::default(),
504            fullscreen: UiFullscreenConfig::default(),
505            screen_reader_mode: default_screen_reader_mode(),
506            reduce_motion_mode: default_reduce_motion_mode(),
507            reduce_motion_keep_progress_animation: default_reduce_motion_keep_progress_animation(),
508            hide_header: default_hide_header(),
509            diff_preview_mode: default_diff_preview_mode(),
510            transcript_review: UiTranscriptReviewConfig::default(),
511        }
512    }
513}
514
515impl UiConfig {
516    /// Contrast floor actually applied to rendered text.
517    ///
518    /// `high_contrast_mode` raises it to the WCAG AAA floor without rewriting
519    /// the user's saved `minimum_contrast`, so toggling it is reversible and
520    /// never loses a custom value.
521    pub fn effective_minimum_contrast(&self) -> f32 {
522        if self.high_contrast_mode {
523            crate::constants::ui::THEME_HIGH_CONTRAST_RATIO.max(self.minimum_contrast)
524        } else {
525            self.minimum_contrast
526        }
527    }
528}
529
530/// Terminal Program Status Protocol preferences.
531#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
532#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
533#[serde(default)]
534pub struct UiProgramStatusConfig {
535    /// Emit terminal status reports (OSC 7501 plus ConEmu OSC 9;4 tab progress on allowlisted terminals) on the interactive TUI terminal stream, plus single-shot exec reports on stderr when it is a terminal.
536    #[serde(default = "default_program_status_enabled")]
537    pub enabled: bool,
538}
539
540impl Default for UiProgramStatusConfig {
541    fn default() -> Self {
542        Self { enabled: default_program_status_enabled() }
543    }
544}
545
546/// Chat configuration
547#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
548#[derive(Debug, Clone, Deserialize, Serialize, Default)]
549pub struct ChatConfig {
550    /// Ask Questions tool configuration (chat.askQuestions.*)
551    #[serde(default, rename = "askQuestions", alias = "ask_questions")]
552    pub ask_questions: AskQuestionsConfig,
553}
554
555/// Ask Questions tool configuration
556#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
557#[derive(Debug, Clone, Deserialize, Serialize)]
558pub struct AskQuestionsConfig {
559    /// Enable the Ask Questions tool in interactive chat
560    #[serde(default = "default_ask_questions_enabled")]
561    pub enabled: bool,
562}
563
564impl Default for AskQuestionsConfig {
565    fn default() -> Self {
566        Self { enabled: default_ask_questions_enabled() }
567    }
568}
569
570/// PTY configuration
571#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
572#[derive(Debug, Clone, Deserialize, Serialize)]
573pub struct PtyConfig {
574    /// Enable PTY support for interactive commands
575    #[serde(default = "default_pty_enabled")]
576    pub enabled: bool,
577
578    /// Default terminal rows for PTY sessions
579    #[serde(default = "default_pty_rows")]
580    pub default_rows: u16,
581
582    /// Default terminal columns for PTY sessions
583    #[serde(default = "default_pty_cols")]
584    pub default_cols: u16,
585
586    /// Maximum number of concurrent PTY sessions
587    #[serde(default = "default_max_pty_sessions")]
588    pub max_sessions: usize,
589
590    /// Deprecated and unused for enforcement.
591    ///
592    /// The authoritative PTY deadline is `[timeouts] pty_ceiling_seconds`.
593    /// This key is retained so existing `vtcode.toml` files keep parsing, but
594    /// changing it has no effect on command execution.
595    #[serde(default = "default_pty_timeout")]
596    pub command_timeout_seconds: u64,
597
598    /// Number of recent PTY output lines to display in the chat transcript
599    #[serde(default = "default_stdout_tail_lines")]
600    pub stdout_tail_lines: usize,
601
602    /// Total scrollback buffer size (lines) retained per PTY session
603    #[serde(default = "default_scrollback_lines")]
604    pub scrollback_lines: usize,
605
606    /// Maximum bytes of output to retain per PTY session (prevents memory explosion)
607    #[serde(default = "default_max_scrollback_bytes")]
608    pub max_scrollback_bytes: usize,
609
610    /// Threshold (KB) at which to auto-spool large outputs to disk instead of memory
611    #[serde(default = "default_large_output_threshold_kb")]
612    pub large_output_threshold_kb: usize,
613
614    /// Preferred shell program for PTY sessions (e.g. "zsh", "bash"); falls back to $SHELL
615    #[serde(default)]
616    pub preferred_shell: Option<String>,
617
618    /// Feature-gated shell runtime path that routes shell execution through zsh EXEC_WRAPPER hooks.
619    #[serde(default = "default_shell_zsh_fork")]
620    pub shell_zsh_fork: bool,
621
622    /// Optional absolute path to patched zsh used when shell_zsh_fork is enabled.
623    #[serde(default)]
624    pub zsh_path: Option<String>,
625}
626
627impl Default for PtyConfig {
628    fn default() -> Self {
629        Self {
630            enabled: default_pty_enabled(),
631            default_rows: default_pty_rows(),
632            default_cols: default_pty_cols(),
633            max_sessions: default_max_pty_sessions(),
634            command_timeout_seconds: default_pty_timeout(),
635            stdout_tail_lines: default_stdout_tail_lines(),
636            scrollback_lines: default_scrollback_lines(),
637            max_scrollback_bytes: default_max_scrollback_bytes(),
638            large_output_threshold_kb: default_large_output_threshold_kb(),
639            preferred_shell: None,
640            shell_zsh_fork: default_shell_zsh_fork(),
641            zsh_path: None,
642        }
643    }
644}
645
646impl PtyConfig {
647    pub fn validate(&self) -> Result<()> {
648        self.zsh_fork_shell_path()?;
649        Ok(())
650    }
651
652    pub fn zsh_fork_shell_path(&self) -> Result<Option<&str>> {
653        if !self.shell_zsh_fork {
654            return Ok(None);
655        }
656
657        let zsh_path = self
658            .zsh_path
659            .as_deref()
660            .map(str::trim)
661            .filter(|path| !path.is_empty())
662            .ok_or_else(|| {
663                anyhow!(
664                    "pty.shell_zsh_fork is enabled, but pty.zsh_path is not configured. \
665                     Set pty.zsh_path to an absolute path to patched zsh."
666                )
667            })?;
668
669        #[cfg(not(unix))]
670        {
671            let _ = zsh_path;
672            bail!("pty.shell_zsh_fork is only supported on Unix platforms");
673        }
674
675        #[cfg(unix)]
676        {
677            let path = std::path::Path::new(zsh_path);
678            if !path.is_absolute() {
679                bail!("pty.zsh_path '{zsh_path}' must be an absolute path when pty.shell_zsh_fork is enabled");
680            }
681            if !path.exists() {
682                bail!("pty.zsh_path '{zsh_path}' does not exist (required when pty.shell_zsh_fork is enabled)");
683            }
684            if !path.is_file() {
685                bail!("pty.zsh_path '{zsh_path}' is not a file (required when pty.shell_zsh_fork is enabled)");
686            }
687
688            Ok(Some(zsh_path))
689        }
690    }
691}
692
693fn default_pty_enabled() -> bool {
694    true
695}
696
697fn default_pty_rows() -> u16 {
698    24
699}
700
701fn default_pty_cols() -> u16 {
702    80
703}
704
705fn default_max_pty_sessions() -> usize {
706    10
707}
708
709fn default_pty_timeout() -> u64 {
710    300
711}
712
713fn default_shell_zsh_fork() -> bool {
714    false
715}
716
717fn default_stdout_tail_lines() -> usize {
718    crate::constants::defaults::DEFAULT_PTY_STDOUT_TAIL_LINES
719}
720
721fn default_scrollback_lines() -> usize {
722    crate::constants::defaults::DEFAULT_PTY_SCROLLBACK_LINES
723}
724
725fn default_max_scrollback_bytes() -> usize {
726    // Reduced from 50MB to 25MB for memory-constrained development environments
727    // Can be overridden in vtcode.toml with: pty.max_scrollback_bytes = 52428800
728    25_000_000 // 25MB max to prevent memory explosion
729}
730
731fn default_large_output_threshold_kb() -> usize {
732    5_000 // 5MB threshold for auto-spooling
733}
734
735fn default_tool_output_mode() -> ToolOutputMode {
736    ToolOutputMode::Compact
737}
738
739fn default_tool_display_mode() -> ToolDisplayMode {
740    ToolDisplayMode::Compact
741}
742
743fn default_verb_callouts() -> bool {
744    true
745}
746
747fn default_tool_output_max_lines() -> usize {
748    30
749}
750
751fn default_tool_output_spool_bytes() -> usize {
752    80_000
753}
754
755fn default_allow_tool_ansi() -> bool {
756    false
757}
758
759fn default_inline_viewport_rows() -> u16 {
760    crate::constants::ui::DEFAULT_INLINE_VIEWPORT_ROWS
761}
762
763fn default_reasoning_display_mode() -> ReasoningDisplayMode {
764    ReasoningDisplayMode::Toggle
765}
766
767fn default_reasoning_visible_default() -> bool {
768    crate::constants::ui::DEFAULT_REASONING_VISIBLE
769}
770
771fn default_thinking_display() -> vtcode_commons::ui_protocol::ThinkingBlockState {
772    vtcode_commons::ui_protocol::ThinkingBlockState::Collapsed
773}
774
775fn default_communication_style() -> vtcode_commons::ui_protocol::CommunicationStyle {
776    vtcode_commons::ui_protocol::CommunicationStyle::Balanced
777}
778
779/// Kitty keyboard protocol configuration
780/// Reference: <https://sw.kovidgoyal.net/kitty/keyboard-protocol/>
781/// Keyboard protocol preset mode
782#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
783#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
784#[serde(rename_all = "snake_case")]
785pub enum KeyboardProtocolMode {
786    /// Standard enhancements (disambiguate + event types + alternate keys)
787    #[default]
788    Default,
789    /// All enhancements including report-all-keys
790    Full,
791    /// Minimal: disambiguate escape codes only
792    Minimal,
793    /// Custom: use individual toggle fields
794    Custom,
795}
796
797impl KeyboardProtocolMode {
798    /// Returns the snake_case string representation.
799    pub fn as_str(&self) -> &'static str {
800        match self {
801            Self::Default => "default",
802            Self::Full => "full",
803            Self::Minimal => "minimal",
804            Self::Custom => "custom",
805        }
806    }
807}
808
809impl std::str::FromStr for KeyboardProtocolMode {
810    type Err = ();
811
812    fn from_str(value: &str) -> Result<Self, Self::Err> {
813        match value.to_ascii_lowercase().as_str() {
814            "default" => Ok(Self::Default),
815            "full" => Ok(Self::Full),
816            "minimal" => Ok(Self::Minimal),
817            "custom" => Ok(Self::Custom),
818            _ => Err(()),
819        }
820    }
821}
822
823#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
824#[derive(Debug, Clone, Deserialize, Serialize)]
825pub struct KeyboardProtocolConfig {
826    /// Enable keyboard protocol enhancements (master toggle)
827    #[serde(default = "default_keyboard_protocol_enabled")]
828    pub enabled: bool,
829
830    /// Preset mode: default, full, minimal, or custom
831    #[serde(default = "default_keyboard_protocol_mode")]
832    pub mode: KeyboardProtocolMode,
833
834    /// Resolve Esc key ambiguity (recommended for performance)
835    #[serde(default = "default_disambiguate_escape_codes")]
836    pub disambiguate_escape_codes: bool,
837
838    /// Report press, release, and repeat events
839    #[serde(default = "default_report_event_types")]
840    pub report_event_types: bool,
841
842    /// Report alternate key layouts (e.g. for non-US keyboards)
843    #[serde(default = "default_report_alternate_keys")]
844    pub report_alternate_keys: bool,
845
846    /// Report all keys, including modifier-only keys (Shift, Ctrl)
847    #[serde(default = "default_report_all_keys")]
848    pub report_all_keys: bool,
849}
850
851impl Default for KeyboardProtocolConfig {
852    fn default() -> Self {
853        Self {
854            enabled: default_keyboard_protocol_enabled(),
855            mode: default_keyboard_protocol_mode(),
856            disambiguate_escape_codes: default_disambiguate_escape_codes(),
857            report_event_types: default_report_event_types(),
858            report_alternate_keys: default_report_alternate_keys(),
859            report_all_keys: default_report_all_keys(),
860        }
861    }
862}
863
864impl KeyboardProtocolConfig {
865    pub fn validate(&self) -> Result<()> {
866        // All enum variants are valid; nothing to validate.
867        let _ = self.mode;
868        Ok(())
869    }
870}
871
872fn default_keyboard_protocol_enabled() -> bool {
873    std::env::var("VTCODE_KEYBOARD_PROTOCOL_ENABLED")
874        .ok()
875        .and_then(|v| v.parse().ok())
876        .unwrap_or(true)
877}
878
879fn default_keyboard_protocol_mode() -> KeyboardProtocolMode {
880    std::env::var("VTCODE_KEYBOARD_PROTOCOL_MODE")
881        .ok()
882        .and_then(|v| v.parse().ok())
883        .unwrap_or_default()
884}
885
886fn default_disambiguate_escape_codes() -> bool {
887    true
888}
889
890fn default_report_event_types() -> bool {
891    true
892}
893
894fn default_report_alternate_keys() -> bool {
895    true
896}
897
898fn default_report_all_keys() -> bool {
899    false
900}
901#[cfg(test)]
902mod tests;