Skip to main content

vtcode_tui/core_tui/
session.rs

1use std::{collections::VecDeque, sync::Arc, time::Instant};
2
3#[cfg(test)]
4use anstyle::Color as AnsiColorEnum;
5use anstyle::RgbColor;
6use ratatui::crossterm::event::{
7    Event as CrosstermEvent, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseEvent,
8    MouseEventKind,
9};
10
11use ratatui::{
12    Frame,
13    layout::{Constraint, Layout, Rect},
14    text::{Line, Span, Text},
15    widgets::{Clear, ListState, Widget},
16};
17use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};
18
19use super::{
20    style::{measure_text_width, ratatui_color_from_ansi, ratatui_style_from_inline},
21    types::{
22        InlineCommand, InlineEvent, InlineHeaderContext, InlineListSelection, InlineMessageKind,
23        InlineTextStyle, InlineTheme, OverlayRequest,
24    },
25};
26use crate::config::constants::ui;
27use crate::ui::tui::widgets::SessionWidget;
28
29mod frame_layout;
30mod header;
31mod impl_events;
32mod impl_init;
33mod impl_input;
34mod impl_layout;
35mod impl_logs;
36mod impl_render;
37mod impl_scroll;
38mod impl_style;
39pub(crate) mod inline_list;
40mod input;
41pub(crate) mod input_manager;
42pub(crate) mod list_navigator;
43pub(crate) mod list_panel;
44mod message;
45pub mod modal;
46pub mod mouse_selection;
47mod navigation;
48mod queue;
49pub mod render;
50mod scroll;
51pub mod styling;
52mod text_utils;
53mod transcript;
54pub mod utils;
55pub mod wrapping;
56
57// New modular components (refactored from main session.rs)
58mod command;
59mod editing;
60
61pub mod config;
62mod driver;
63mod events;
64pub(crate) mod message_renderer;
65mod messages;
66mod reflow;
67pub(crate) mod reverse_search;
68mod spinner;
69mod state;
70pub mod terminal_capabilities;
71mod terminal_title;
72#[cfg(test)]
73mod tests;
74mod tool_renderer;
75mod transcript_links;
76mod vim;
77
78use self::input_manager::InputManager;
79pub(crate) use self::message::TranscriptLine;
80use self::message::{MessageLabels, MessageLine};
81use self::modal::{ModalState, WizardModalState};
82
83use self::config::AppearanceConfig;
84pub(crate) use self::input::status_requires_shimmer;
85use self::mouse_selection::MouseSelectionState;
86use self::queue::QueueOverlay;
87use self::scroll::ScrollManager;
88use self::spinner::{ShimmerState, ThinkingSpinner};
89use self::styling::SessionStyles;
90use self::transcript::TranscriptReflowCache;
91use self::transcript_links::TranscriptFileLinkTarget;
92pub(crate) use self::transcript_links::TranscriptLinkClickAction;
93use self::vim::VimState;
94#[cfg(test)]
95use super::types::InlineHeaderHighlight;
96// TaskPlan integration intentionally omitted in this UI crate.
97use crate::ui::tui::log::{LogEntry, highlight_log_entry};
98
99const USER_PREFIX: &str = "";
100const PLACEHOLDER_COLOR: RgbColor =
101    RgbColor(ui::PLACEHOLDER_R, ui::PLACEHOLDER_G, ui::PLACEHOLDER_B);
102const MAX_LOG_LINES: usize = 256;
103const MAX_LOG_DRAIN_PER_TICK: usize = 256;
104
105#[derive(Clone, Debug)]
106struct CollapsedPaste {
107    line_index: usize,
108    full_text: String,
109}
110
111#[derive(Clone, Debug, Default)]
112pub(crate) struct SuggestedPromptState {
113    pub(crate) active: bool,
114}
115
116pub(crate) enum ActiveOverlay {
117    Modal(Box<ModalState>),
118    Wizard(Box<WizardModalState>),
119}
120
121impl ActiveOverlay {
122    fn as_modal(&self) -> Option<&ModalState> {
123        match self {
124            Self::Modal(state) => Some(state),
125            Self::Wizard(_) => None,
126        }
127    }
128
129    fn as_modal_mut(&mut self) -> Option<&mut ModalState> {
130        match self {
131            Self::Modal(state) => Some(state),
132            Self::Wizard(_) => None,
133        }
134    }
135
136    fn as_wizard(&self) -> Option<&WizardModalState> {
137        match self {
138            Self::Wizard(state) => Some(state),
139            Self::Modal(_) => None,
140        }
141    }
142
143    fn as_wizard_mut(&mut self) -> Option<&mut WizardModalState> {
144        match self {
145            Self::Wizard(state) => Some(state),
146            Self::Modal(_) => None,
147        }
148    }
149
150    fn restore_input(&self) -> bool {
151        match self {
152            Self::Modal(state) => state.restore_input,
153            Self::Wizard(_) => true,
154        }
155    }
156
157    fn restore_cursor(&self) -> bool {
158        match self {
159            Self::Modal(state) => state.restore_cursor,
160            Self::Wizard(_) => true,
161        }
162    }
163}
164
165#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
166pub(crate) enum MouseDragTarget {
167    #[default]
168    None,
169    Transcript,
170    Input,
171}
172
173pub struct Session {
174    // --- Managers (Phase 2) ---
175    /// Manages user input, cursor, and command history
176    pub(crate) input_manager: InputManager,
177    /// Manages scroll state and viewport metrics
178    pub(crate) scroll_manager: ScrollManager,
179    user_scrolled: bool,
180
181    // --- Message Management ---
182    pub(crate) lines: Vec<MessageLine>,
183    collapsed_pastes: Vec<CollapsedPaste>,
184    pub(crate) theme: InlineTheme,
185    pub(crate) styles: SessionStyles,
186    pub(crate) appearance: AppearanceConfig,
187    pub(crate) header_context: InlineHeaderContext,
188    pub(crate) header_rows: u16,
189    pub(crate) labels: MessageLabels,
190
191    // --- Prompt/Input Display ---
192    prompt_prefix: String,
193    prompt_style: InlineTextStyle,
194    placeholder: Option<String>,
195    placeholder_style: Option<InlineTextStyle>,
196    pub(crate) input_status_left: Option<String>,
197    pub(crate) input_status_right: Option<String>,
198    input_compact_mode: bool,
199
200    // --- UI State ---
201    #[allow(dead_code)]
202    navigation_state: ListState,
203    input_enabled: bool,
204    cursor_visible: bool,
205    pub(crate) needs_redraw: bool,
206    pub(crate) needs_full_clear: bool,
207    /// Track if transcript content changed (not just scroll position)
208    pub(crate) transcript_content_changed: bool,
209    should_exit: bool,
210    scroll_cursor_steady_until: Option<Instant>,
211    last_shimmer_active: bool,
212    pub(crate) view_rows: u16,
213    pub(crate) input_height: u16,
214    pub(crate) transcript_rows: u16,
215    pub(crate) transcript_width: u16,
216    pub(crate) transcript_view_top: usize,
217    transcript_area: Option<Rect>,
218    input_area: Option<Rect>,
219    bottom_panel_area: Option<Rect>,
220    modal_list_area: Option<Rect>,
221    transcript_file_link_targets: Vec<TranscriptFileLinkTarget>,
222    hovered_transcript_file_link: Option<usize>,
223    last_mouse_position: Option<(u16, u16)>,
224    held_key_modifiers: KeyModifiers,
225
226    // --- Logging ---
227    log_receiver: Option<UnboundedReceiver<LogEntry>>,
228    log_lines: VecDeque<Arc<Text<'static>>>,
229    log_cached_text: Option<Arc<Text<'static>>>,
230    log_evicted: bool,
231    pub(crate) show_logs: bool,
232
233    // --- Rendering ---
234    transcript_cache: Option<TranscriptReflowCache>,
235    /// Cache of visible lines by (scroll_offset, width) - shared via Arc for zero-copy reads
236    /// Avoids expensive clone on cache hits
237    pub(crate) visible_lines_cache: Option<(usize, u16, Arc<Vec<TranscriptLine>>)>,
238    pub(crate) queued_inputs: Vec<String>,
239    queue_overlay_cache: Option<QueueOverlay>,
240    queue_overlay_version: u64,
241    active_overlay: Option<ActiveOverlay>,
242    overlay_queue: VecDeque<OverlayRequest>,
243    last_overlay_list_selection: Option<InlineListSelection>,
244    last_overlay_list_was_last: bool,
245    line_revision_counter: u64,
246    /// Track the first line that needs reflow/update to avoid O(N) scans
247    first_dirty_line: Option<usize>,
248    in_tool_code_fence: bool,
249
250    // --- Prompt Suggestions ---
251    pub(crate) suggested_prompt_state: SuggestedPromptState,
252
253    // --- Thinking Indicator ---
254    pub(crate) thinking_spinner: ThinkingSpinner,
255    pub(crate) shimmer_state: ShimmerState,
256
257    // --- Reverse Search ---
258    pub(crate) reverse_search_state: reverse_search::ReverseSearchState,
259
260    // --- PTY Session Management ---
261    pub(crate) active_pty_sessions: Option<Arc<std::sync::atomic::AtomicUsize>>,
262
263    // --- Clipboard for yank/paste operations ---
264    #[allow(dead_code)]
265    pub(crate) clipboard: String,
266    pub(crate) vim_state: VimState,
267
268    // --- Mouse Text Selection ---
269    pub(crate) mouse_selection: MouseSelectionState,
270    pub(crate) mouse_drag_target: MouseDragTarget,
271
272    pub(crate) skip_confirmations: bool,
273
274    // --- Performance Caching ---
275    pub(crate) header_lines_cache: Option<Vec<Line<'static>>>,
276    pub(crate) header_height_cache: hashbrown::HashMap<u16, u16>,
277    pub(crate) queued_inputs_preview_cache: Option<Vec<String>>,
278
279    // --- Terminal Title ---
280    /// Product/app name used in terminal title branding
281    pub(crate) app_name: String,
282    /// Workspace root path for dynamic title generation
283    pub(crate) workspace_root: Option<std::path::PathBuf>,
284    /// Last set terminal title to avoid redundant updates
285    last_terminal_title: Option<String>,
286
287    // --- Streaming State ---
288    /// Track if the assistant is currently streaming a final answer.
289    /// When true, user input should be queued instead of submitted immediately
290    /// to prevent race conditions with turn completion (see GitHub #12569).
291    pub(crate) is_streaming_final_answer: bool,
292}