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