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) on both the
223    /// TUI and desktop. Can also be enabled with VTCODE_HIGH_CONTRAST=1. It
224    /// wins over `minimum_contrast` without rewriting the saved value.
225    #[serde(default = "default_high_contrast_mode")]
226    pub high_contrast_mode: bool,
227
228    /// Compatibility mode for legacy terminals that map bold to bright colors.
229    /// When enabled, avoids using bold styling on text that would become bright colors,
230    /// preventing visibility issues in terminals with "bold is bright" behavior.
231    #[serde(default = "default_bold_is_bright")]
232    pub bold_is_bright: bool,
233
234    /// How the terminal renders East-Asian-ambiguous-width glyphs (UAX #11),
235    /// which include every box-drawing character. Terminals set to render the
236    /// set as double width (xterm `cjkWidth`, iTerm2's ambiguous-width
237    /// checkbox, some CJK-locale defaults) draw each glyph as two cells, so
238    /// box-drawing frames and table rules break. Not detectable at runtime.
239    /// Can also be controlled via VTCODE_AMBIGUOUS_WIDTH=wide.
240    /// - "narrow": ambiguous glyphs occupy one cell (default)
241    /// - "wide": ambiguous glyphs occupy two cells; chrome degrades to ASCII
242    ///   and width math counts the glyphs as wide
243    #[serde(default = "default_ambiguous_width")]
244    pub ambiguous_width: AmbiguousWidthMode,
245
246    /// Restrict color palette to the 11 "safe" ANSI colors portable across common themes.
247    /// Safe colors: red, green, yellow, blue, magenta, cyan + brred, brgreen, brmagenta, brcyan
248    /// Problematic colors avoided: brblack (invisible in Solarized Dark), bryellow (light themes),
249    /// white/brwhite (light themes), brblue (Basic Dark).
250    /// See: <https://blog.xoria.org/terminal-colors/>
251    #[serde(default = "default_safe_colors_only")]
252    pub safe_colors_only: bool,
253
254    /// Color scheme mode for automatic light/dark theme switching.
255    /// - "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
256    /// - "light": Force light mode theme selection
257    /// - "dark": Force dark mode theme selection
258    #[serde(default = "default_color_scheme_mode")]
259    pub color_scheme_mode: ColorSchemeMode,
260
261    /// Application icon artwork variant for terminal tab icons and the desktop picker.
262    /// - "dynamic": Follow the active light/dark mode (default)
263    /// - "light": Always use the light-mode artwork
264    /// - "dark": Always use the dark-mode artwork
265    /// - "clear": Always use the clear (glass V on a subtle translucent tile) artwork
266    /// - "tinted": Always use the tinted (monochrome slate) artwork
267    #[serde(default = "default_app_icon")]
268    pub app_icon: AppIconPreference,
269
270    /// Terminal program status reports for the interactive TUI (on by default).
271    #[serde(default)]
272    pub program_status: UiProgramStatusConfig,
273
274    /// Notification preferences for attention events.
275    #[serde(default)]
276    pub notifications: UiNotificationsConfig,
277
278    /// Fullscreen interaction settings for alternate-screen rendering.
279    #[serde(default)]
280    pub fullscreen: UiFullscreenConfig,
281
282    /// Screen reader mode: disables animations, uses plain text thinking indicators,
283    /// and opens Transcript Review in raw mode. Alternate-screen compatibility
284    /// depends on the terminal and assistive technology.
285    /// Can also be enabled via VTCODE_SCREEN_READER=1 environment variable.
286    #[serde(default = "default_screen_reader_mode")]
287    pub screen_reader_mode: bool,
288
289    /// Reduce motion mode: keeps progress labels visible without animated effects.
290    /// If omitted, defaults from VTCODE_REDUCE_MOTION, then a supported OS
291    /// accessibility preference; unknown or unavailable preferences default to false.
292    #[serde(default = "default_reduce_motion_mode")]
293    pub reduce_motion_mode: bool,
294
295    /// Keep animated progress indicators while reduce_motion_mode is enabled.
296    /// Screen reader mode still disables progress animation.
297    #[serde(default = "default_reduce_motion_keep_progress_animation")]
298    pub reduce_motion_keep_progress_animation: bool,
299
300    /// Hide the full TUI header, showing only version info in a compact line.
301    #[serde(default = "default_hide_header")]
302    pub hide_header: bool,
303
304    /// Diff preview layout for file-edit approval overlays.
305    /// Options: "inline" (default) or "side-by-side".
306    #[serde(default = "default_diff_preview_mode")]
307    pub diff_preview_mode: DiffPreviewMode,
308
309    /// Transcript Review presentation controls.
310    #[serde(default)]
311    pub transcript_review: UiTranscriptReviewConfig,
312}
313
314/// Color scheme mode for theme selection
315#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
316#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Default)]
317#[serde(rename_all = "snake_case")]
318pub enum ColorSchemeMode {
319    /// Detect from terminal environment (OSC 11 query or COLORFGBG)
320    #[default]
321    Auto,
322    /// Force light color scheme
323    Light,
324    /// Force dark color scheme
325    Dark,
326    /// Catch-all for unknown modes added by future versions.
327    #[serde(other)]
328    Unknown,
329}
330
331fn default_minimum_contrast() -> f32 {
332    crate::constants::ui::THEME_MIN_CONTRAST_RATIO
333}
334
335fn default_high_contrast_mode() -> bool {
336    env_bool_var("VTCODE_HIGH_CONTRAST").unwrap_or(false)
337}
338
339fn default_bold_is_bright() -> bool {
340    false
341}
342
343fn default_safe_colors_only() -> bool {
344    false
345}
346
347fn default_color_scheme_mode() -> ColorSchemeMode {
348    ColorSchemeMode::Auto
349}
350
351fn default_app_icon() -> AppIconPreference {
352    AppIconPreference::Dynamic
353}
354
355fn default_show_sidebar() -> bool {
356    true
357}
358
359fn default_dim_completed_todos() -> bool {
360    true
361}
362
363fn default_message_block_spacing() -> bool {
364    true
365}
366
367fn default_program_status_enabled() -> bool {
368    true
369}
370
371fn default_show_turn_timer() -> bool {
372    false
373}
374
375fn default_show_diagnostics_in_transcript() -> bool {
376    false
377}
378
379fn default_show_message_timestamps() -> bool {
380    true
381}
382
383fn default_vim_mode() -> bool {
384    false
385}
386
387fn default_busy_enter_behavior() -> BusyEnterBehavior {
388    BusyEnterBehavior::Queue
389}
390
391fn env_bool_var(name: &str) -> Option<bool> {
392    crate::env_helpers::read_env_var(name).and_then(|v| vtcode_commons::utils::parse_bool_env_value(&v))
393}
394
395fn env_u8_var(name: &str) -> Option<u8> {
396    crate::env_helpers::read_env_var(name)
397        .and_then(|value| value.trim().parse::<u8>().ok())
398        .map(clamp_fullscreen_scroll_speed)
399}
400
401fn clamp_fullscreen_scroll_speed(value: u8) -> u8 {
402    value.clamp(1, 20)
403}
404
405fn default_fullscreen_mouse_capture() -> bool {
406    env_bool_var("VTCODE_FULLSCREEN_MOUSE_CAPTURE").unwrap_or(true)
407}
408
409fn default_fullscreen_copy_on_select() -> bool {
410    env_bool_var("VTCODE_FULLSCREEN_COPY_ON_SELECT").unwrap_or(true)
411}
412
413fn default_fullscreen_scroll_speed() -> u8 {
414    env_u8_var("VTCODE_FULLSCREEN_SCROLL_SPEED").unwrap_or(3)
415}
416
417fn default_screen_reader_mode() -> bool {
418    env_bool_var("VTCODE_SCREEN_READER").unwrap_or(false)
419}
420
421fn default_ambiguous_width() -> AmbiguousWidthMode {
422    match crate::env_helpers::read_env_var("VTCODE_AMBIGUOUS_WIDTH")
423        .map(|value| value.trim().to_ascii_lowercase())
424        .as_deref()
425    {
426        Some("wide") => AmbiguousWidthMode::Wide,
427        Some("narrow") => AmbiguousWidthMode::Narrow,
428        _ => AmbiguousWidthMode::default(),
429    }
430}
431
432fn default_reduce_motion_mode() -> bool {
433    env_bool_var("VTCODE_REDUCE_MOTION")
434        .or_else(reduce_motion_preference)
435        .unwrap_or(false)
436}
437
438fn default_reduce_motion_keep_progress_animation() -> bool {
439    false
440}
441
442fn default_hide_header() -> bool {
443    true
444}
445
446fn default_diff_preview_mode() -> DiffPreviewMode {
447    DiffPreviewMode::Inline
448}
449
450fn default_transcript_review_control() -> bool {
451    true
452}
453
454fn default_show_task_panel() -> bool {
455    false
456}
457
458fn default_ask_questions_enabled() -> bool {
459    true
460}
461
462impl Default for UiConfig {
463    fn default() -> Self {
464        Self {
465            tool_output_mode: default_tool_output_mode(),
466            tool_display_mode: default_tool_display_mode(),
467            verb_callouts: default_verb_callouts(),
468            keybindings: HashMap::new(),
469            tool_output_max_lines: default_tool_output_max_lines(),
470            tool_output_spool_bytes: default_tool_output_spool_bytes(),
471            tool_output_spool_dir: None,
472            allow_tool_ansi: default_allow_tool_ansi(),
473            inline_viewport_rows: default_inline_viewport_rows(),
474            reasoning_display_mode: default_reasoning_display_mode(),
475            reasoning_visible_default: default_reasoning_visible_default(),
476            thinking_display: default_thinking_display(),
477            communication_style: default_communication_style(),
478            vim_mode: default_vim_mode(),
479            busy_enter_behavior: default_busy_enter_behavior(),
480            status_line: StatusLineConfig::default(),
481            terminal_title: TerminalTitleConfig::default(),
482            keyboard_protocol: KeyboardProtocolConfig::default(),
483            layout_mode: LayoutModeOverride::default(),
484            display_mode: UiDisplayMode::default(),
485            show_sidebar: default_show_sidebar(),
486            dim_completed_todos: default_dim_completed_todos(),
487            show_task_panel: default_show_task_panel(),
488            message_block_spacing: default_message_block_spacing(),
489            show_turn_timer: default_show_turn_timer(),
490            show_diagnostics_in_transcript: default_show_diagnostics_in_transcript(),
491            show_message_timestamps: default_show_message_timestamps(),
492            // Color accessibility defaults
493            minimum_contrast: default_minimum_contrast(),
494            high_contrast_mode: default_high_contrast_mode(),
495            bold_is_bright: default_bold_is_bright(),
496            ambiguous_width: default_ambiguous_width(),
497            safe_colors_only: default_safe_colors_only(),
498            color_scheme_mode: default_color_scheme_mode(),
499            app_icon: default_app_icon(),
500            program_status: UiProgramStatusConfig::default(),
501            notifications: UiNotificationsConfig::default(),
502            fullscreen: UiFullscreenConfig::default(),
503            screen_reader_mode: default_screen_reader_mode(),
504            reduce_motion_mode: default_reduce_motion_mode(),
505            reduce_motion_keep_progress_animation: default_reduce_motion_keep_progress_animation(),
506            hide_header: default_hide_header(),
507            diff_preview_mode: default_diff_preview_mode(),
508            transcript_review: UiTranscriptReviewConfig::default(),
509        }
510    }
511}
512
513impl UiConfig {
514    /// Contrast floor actually applied to rendered text.
515    ///
516    /// `high_contrast_mode` raises it to the WCAG AAA floor without rewriting
517    /// the user's saved `minimum_contrast`, so toggling it is reversible and
518    /// never loses a custom value.
519    pub fn effective_minimum_contrast(&self) -> f32 {
520        if self.high_contrast_mode {
521            crate::constants::ui::THEME_HIGH_CONTRAST_RATIO.max(self.minimum_contrast)
522        } else {
523            self.minimum_contrast
524        }
525    }
526}
527
528/// Terminal Program Status Protocol preferences.
529#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
530#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
531#[serde(default)]
532pub struct UiProgramStatusConfig {
533    /// 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.
534    #[serde(default = "default_program_status_enabled")]
535    pub enabled: bool,
536}
537
538impl Default for UiProgramStatusConfig {
539    fn default() -> Self {
540        Self { enabled: default_program_status_enabled() }
541    }
542}
543
544/// Chat configuration
545#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
546#[derive(Debug, Clone, Deserialize, Serialize, Default)]
547pub struct ChatConfig {
548    /// Ask Questions tool configuration (chat.askQuestions.*)
549    #[serde(default, rename = "askQuestions", alias = "ask_questions")]
550    pub ask_questions: AskQuestionsConfig,
551}
552
553/// Ask Questions tool configuration
554#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
555#[derive(Debug, Clone, Deserialize, Serialize)]
556pub struct AskQuestionsConfig {
557    /// Enable the Ask Questions tool in interactive chat
558    #[serde(default = "default_ask_questions_enabled")]
559    pub enabled: bool,
560}
561
562impl Default for AskQuestionsConfig {
563    fn default() -> Self {
564        Self { enabled: default_ask_questions_enabled() }
565    }
566}
567
568/// PTY configuration
569#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
570#[derive(Debug, Clone, Deserialize, Serialize)]
571pub struct PtyConfig {
572    /// Enable PTY support for interactive commands
573    #[serde(default = "default_pty_enabled")]
574    pub enabled: bool,
575
576    /// Default terminal rows for PTY sessions
577    #[serde(default = "default_pty_rows")]
578    pub default_rows: u16,
579
580    /// Default terminal columns for PTY sessions
581    #[serde(default = "default_pty_cols")]
582    pub default_cols: u16,
583
584    /// Maximum number of concurrent PTY sessions
585    #[serde(default = "default_max_pty_sessions")]
586    pub max_sessions: usize,
587
588    /// Deprecated and unused for enforcement.
589    ///
590    /// The authoritative PTY deadline is `[timeouts] pty_ceiling_seconds`.
591    /// This key is retained so existing `vtcode.toml` files keep parsing, but
592    /// changing it has no effect on command execution.
593    #[serde(default = "default_pty_timeout")]
594    pub command_timeout_seconds: u64,
595
596    /// Number of recent PTY output lines to display in the chat transcript
597    #[serde(default = "default_stdout_tail_lines")]
598    pub stdout_tail_lines: usize,
599
600    /// Total scrollback buffer size (lines) retained per PTY session
601    #[serde(default = "default_scrollback_lines")]
602    pub scrollback_lines: usize,
603
604    /// Maximum bytes of output to retain per PTY session (prevents memory explosion)
605    #[serde(default = "default_max_scrollback_bytes")]
606    pub max_scrollback_bytes: usize,
607
608    /// Threshold (KB) at which to auto-spool large outputs to disk instead of memory
609    #[serde(default = "default_large_output_threshold_kb")]
610    pub large_output_threshold_kb: usize,
611
612    /// Preferred shell program for PTY sessions (e.g. "zsh", "bash"); falls back to $SHELL
613    #[serde(default)]
614    pub preferred_shell: Option<String>,
615
616    /// Feature-gated shell runtime path that routes shell execution through zsh EXEC_WRAPPER hooks.
617    #[serde(default = "default_shell_zsh_fork")]
618    pub shell_zsh_fork: bool,
619
620    /// Optional absolute path to patched zsh used when shell_zsh_fork is enabled.
621    #[serde(default)]
622    pub zsh_path: Option<String>,
623}
624
625impl Default for PtyConfig {
626    fn default() -> Self {
627        Self {
628            enabled: default_pty_enabled(),
629            default_rows: default_pty_rows(),
630            default_cols: default_pty_cols(),
631            max_sessions: default_max_pty_sessions(),
632            command_timeout_seconds: default_pty_timeout(),
633            stdout_tail_lines: default_stdout_tail_lines(),
634            scrollback_lines: default_scrollback_lines(),
635            max_scrollback_bytes: default_max_scrollback_bytes(),
636            large_output_threshold_kb: default_large_output_threshold_kb(),
637            preferred_shell: None,
638            shell_zsh_fork: default_shell_zsh_fork(),
639            zsh_path: None,
640        }
641    }
642}
643
644impl PtyConfig {
645    pub fn validate(&self) -> Result<()> {
646        self.zsh_fork_shell_path()?;
647        Ok(())
648    }
649
650    pub fn zsh_fork_shell_path(&self) -> Result<Option<&str>> {
651        if !self.shell_zsh_fork {
652            return Ok(None);
653        }
654
655        let zsh_path = self
656            .zsh_path
657            .as_deref()
658            .map(str::trim)
659            .filter(|path| !path.is_empty())
660            .ok_or_else(|| {
661                anyhow!(
662                    "pty.shell_zsh_fork is enabled, but pty.zsh_path is not configured. \
663                     Set pty.zsh_path to an absolute path to patched zsh."
664                )
665            })?;
666
667        #[cfg(not(unix))]
668        {
669            let _ = zsh_path;
670            bail!("pty.shell_zsh_fork is only supported on Unix platforms");
671        }
672
673        #[cfg(unix)]
674        {
675            let path = std::path::Path::new(zsh_path);
676            if !path.is_absolute() {
677                bail!("pty.zsh_path '{zsh_path}' must be an absolute path when pty.shell_zsh_fork is enabled");
678            }
679            if !path.exists() {
680                bail!("pty.zsh_path '{zsh_path}' does not exist (required when pty.shell_zsh_fork is enabled)");
681            }
682            if !path.is_file() {
683                bail!("pty.zsh_path '{zsh_path}' is not a file (required when pty.shell_zsh_fork is enabled)");
684            }
685
686            Ok(Some(zsh_path))
687        }
688    }
689}
690
691fn default_pty_enabled() -> bool {
692    true
693}
694
695fn default_pty_rows() -> u16 {
696    24
697}
698
699fn default_pty_cols() -> u16 {
700    80
701}
702
703fn default_max_pty_sessions() -> usize {
704    10
705}
706
707fn default_pty_timeout() -> u64 {
708    300
709}
710
711fn default_shell_zsh_fork() -> bool {
712    false
713}
714
715fn default_stdout_tail_lines() -> usize {
716    crate::constants::defaults::DEFAULT_PTY_STDOUT_TAIL_LINES
717}
718
719fn default_scrollback_lines() -> usize {
720    crate::constants::defaults::DEFAULT_PTY_SCROLLBACK_LINES
721}
722
723fn default_max_scrollback_bytes() -> usize {
724    // Reduced from 50MB to 25MB for memory-constrained development environments
725    // Can be overridden in vtcode.toml with: pty.max_scrollback_bytes = 52428800
726    25_000_000 // 25MB max to prevent memory explosion
727}
728
729fn default_large_output_threshold_kb() -> usize {
730    5_000 // 5MB threshold for auto-spooling
731}
732
733fn default_tool_output_mode() -> ToolOutputMode {
734    ToolOutputMode::Compact
735}
736
737fn default_tool_display_mode() -> ToolDisplayMode {
738    ToolDisplayMode::Compact
739}
740
741fn default_verb_callouts() -> bool {
742    true
743}
744
745fn default_tool_output_max_lines() -> usize {
746    30
747}
748
749fn default_tool_output_spool_bytes() -> usize {
750    80_000
751}
752
753fn default_allow_tool_ansi() -> bool {
754    false
755}
756
757fn default_inline_viewport_rows() -> u16 {
758    crate::constants::ui::DEFAULT_INLINE_VIEWPORT_ROWS
759}
760
761fn default_reasoning_display_mode() -> ReasoningDisplayMode {
762    ReasoningDisplayMode::Toggle
763}
764
765fn default_reasoning_visible_default() -> bool {
766    crate::constants::ui::DEFAULT_REASONING_VISIBLE
767}
768
769fn default_thinking_display() -> vtcode_commons::ui_protocol::ThinkingBlockState {
770    vtcode_commons::ui_protocol::ThinkingBlockState::Collapsed
771}
772
773fn default_communication_style() -> vtcode_commons::ui_protocol::CommunicationStyle {
774    vtcode_commons::ui_protocol::CommunicationStyle::Balanced
775}
776
777/// Kitty keyboard protocol configuration
778/// Reference: <https://sw.kovidgoyal.net/kitty/keyboard-protocol/>
779/// Keyboard protocol preset mode
780#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
781#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
782#[serde(rename_all = "snake_case")]
783pub enum KeyboardProtocolMode {
784    /// Standard enhancements (disambiguate + event types + alternate keys)
785    #[default]
786    Default,
787    /// All enhancements including report-all-keys
788    Full,
789    /// Minimal: disambiguate escape codes only
790    Minimal,
791    /// Custom: use individual toggle fields
792    Custom,
793}
794
795impl KeyboardProtocolMode {
796    /// Returns the snake_case string representation.
797    pub fn as_str(&self) -> &'static str {
798        match self {
799            Self::Default => "default",
800            Self::Full => "full",
801            Self::Minimal => "minimal",
802            Self::Custom => "custom",
803        }
804    }
805}
806
807#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
808#[derive(Debug, Clone, Deserialize, Serialize)]
809pub struct KeyboardProtocolConfig {
810    /// Enable keyboard protocol enhancements (master toggle)
811    #[serde(default = "default_keyboard_protocol_enabled")]
812    pub enabled: bool,
813
814    /// Preset mode: default, full, minimal, or custom
815    #[serde(default = "default_keyboard_protocol_mode")]
816    pub mode: KeyboardProtocolMode,
817
818    /// Resolve Esc key ambiguity (recommended for performance)
819    #[serde(default = "default_disambiguate_escape_codes")]
820    pub disambiguate_escape_codes: bool,
821
822    /// Report press, release, and repeat events
823    #[serde(default = "default_report_event_types")]
824    pub report_event_types: bool,
825
826    /// Report alternate key layouts (e.g. for non-US keyboards)
827    #[serde(default = "default_report_alternate_keys")]
828    pub report_alternate_keys: bool,
829
830    /// Report all keys, including modifier-only keys (Shift, Ctrl)
831    #[serde(default = "default_report_all_keys")]
832    pub report_all_keys: bool,
833}
834
835impl Default for KeyboardProtocolConfig {
836    fn default() -> Self {
837        Self {
838            enabled: default_keyboard_protocol_enabled(),
839            mode: default_keyboard_protocol_mode(),
840            disambiguate_escape_codes: default_disambiguate_escape_codes(),
841            report_event_types: default_report_event_types(),
842            report_alternate_keys: default_report_alternate_keys(),
843            report_all_keys: default_report_all_keys(),
844        }
845    }
846}
847
848impl KeyboardProtocolConfig {
849    pub fn validate(&self) -> Result<()> {
850        // All enum variants are valid; nothing to validate.
851        let _ = self.mode;
852        Ok(())
853    }
854}
855
856fn default_keyboard_protocol_enabled() -> bool {
857    std::env::var("VTCODE_KEYBOARD_PROTOCOL_ENABLED")
858        .ok()
859        .and_then(|v| v.parse().ok())
860        .unwrap_or(true)
861}
862
863fn default_keyboard_protocol_mode() -> KeyboardProtocolMode {
864    std::env::var("VTCODE_KEYBOARD_PROTOCOL_MODE")
865        .ok()
866        .and_then(|v| match v.to_ascii_lowercase().as_str() {
867            "default" => Some(KeyboardProtocolMode::Default),
868            "full" => Some(KeyboardProtocolMode::Full),
869            "minimal" => Some(KeyboardProtocolMode::Minimal),
870            "custom" => Some(KeyboardProtocolMode::Custom),
871            _ => None,
872        })
873        .unwrap_or_default()
874}
875
876fn default_disambiguate_escape_codes() -> bool {
877    true
878}
879
880fn default_report_event_types() -> bool {
881    true
882}
883
884fn default_report_alternate_keys() -> bool {
885    true
886}
887
888fn default_report_all_keys() -> bool {
889    false
890}
891#[cfg(test)]
892mod tests;