Skip to main content

vtcode_ui/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, MouseEventKind,
8};
9
10use ratatui::{
11    Frame,
12    layout::{Constraint, Layout, Rect},
13    text::{Line, Span, Text},
14    widgets::{Clear, ListState, Widget},
15};
16use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};
17
18use super::{
19    style::{measure_text_width, ratatui_color_from_ansi, ratatui_style_from_inline},
20    types::{
21        ActivityState, InlineCommand, InlineEvent, InlineHeaderContext, InlineListSelection, InlineMessageKind,
22        InlineTextStyle, InlineTheme, OverlayRequest,
23    },
24};
25use crate::tui::config::constants::ui;
26use crate::tui::core_tui::types::LocalAgentEntry;
27use crate::tui::options::FullscreenInteractionSettings;
28use crate::tui::ui::tui::widgets::SessionWidget;
29
30mod diagnostics;
31mod frame_layout;
32mod header;
33mod impl_events;
34mod impl_init;
35mod impl_input;
36mod impl_layout;
37mod impl_logs;
38mod impl_render;
39mod impl_scroll;
40mod impl_style;
41pub(crate) mod inline_list;
42mod input;
43pub(crate) mod input_manager;
44mod layout_state;
45pub(crate) mod list_navigator;
46pub(crate) mod list_panel;
47mod message;
48pub mod modal;
49pub mod mouse_selection;
50mod navigation;
51mod progress;
52mod queue;
53pub(crate) mod render;
54mod render_state;
55mod scroll;
56pub mod styling;
57pub(crate) mod text_utils;
58mod textarea_bridge;
59mod transcript;
60pub(crate) mod utils;
61pub(crate) mod wrapping;
62
63// New modular components (refactored from main session.rs)
64mod command;
65mod editing;
66
67pub mod action;
68pub(crate) mod clipboard_image;
69pub mod config;
70mod driver;
71mod events;
72mod input_render;
73pub(crate) mod message_renderer;
74mod messages;
75pub(crate) mod mode_switch_guard;
76mod overlay_state;
77mod reflow;
78pub(crate) mod reverse_search;
79mod scroll_state;
80mod spinner;
81mod state;
82mod sticky_prompt;
83pub mod terminal_capabilities;
84pub(crate) mod terminal_title;
85#[cfg(test)]
86mod tests;
87mod tool_renderer;
88mod transcript_links;
89mod vim;
90
91use self::input_manager::InputManager;
92use self::layout_state::SessionAreas;
93pub(crate) use self::message::TranscriptLine;
94use self::message::{MessageLabels, MessageLine};
95use self::modal::{ModalState, WizardModalState};
96
97pub use self::action::{Action, BindingStore, parse_key_binding};
98use self::config::AppearanceConfig;
99pub(crate) use self::input::status_requires_shimmer;
100use self::mouse_selection::{DragAutoScroll, DragAutoScrollDirection, MouseSelectionState};
101use self::queue::QueueOverlay;
102use self::render_state::RenderState;
103use self::scroll::ScrollManager;
104pub(crate) use self::spinner::pulse_spinner_frame_for_phase;
105pub(crate) use self::spinner::title_spinner_frame;
106use self::spinner::{ShimmerState, ThinkingSpinner};
107use self::styling::SessionStyles;
108pub use self::terminal_title::{
109    TERMINAL_TITLE_ATTENTION_NEEDLES, TERMINAL_TITLE_UNDOING_NEEDLES, TERMINAL_TITLE_WAITING_NEEDLES,
110};
111use self::transcript::TranscriptReflowCache;
112use self::transcript_links::TranscriptFileLinkTarget;
113pub(crate) use self::transcript_links::TranscriptLinkClickAction;
114use self::vim::VimState;
115#[cfg(test)]
116use super::types::InlineHeaderHighlight;
117// TaskPlan integration intentionally omitted in this UI crate.
118use crate::tui::ui::tui::log::{LogEntry, highlight_log_entry};
119
120const USER_PREFIX: &str = "";
121const PLACEHOLDER_COLOR: RgbColor = RgbColor(ui::PLACEHOLDER_R, ui::PLACEHOLDER_G, ui::PLACEHOLDER_B);
122const MAX_LOG_LINES: usize = 256;
123const MAX_LOG_DRAIN_PER_TICK: usize = 256;
124
125#[derive(Clone, Debug)]
126struct CollapsedPaste {
127    line_index: usize,
128    full_text: String,
129}
130
131#[derive(Clone, Debug, Default)]
132pub(crate) struct SuggestedPromptState {
133    active: bool,
134}
135
136#[derive(Clone, Copy, Debug, PartialEq, Eq)]
137pub(crate) enum InlinePromptSuggestionSource {
138    Llm,
139    Local,
140}
141
142#[derive(Clone, Debug, Default, PartialEq, Eq)]
143pub(crate) struct InlinePromptSuggestionState {
144    suggestion: Option<String>,
145    source: Option<InlinePromptSuggestionSource>,
146}
147
148pub(crate) enum ActiveOverlay {
149    Modal(Box<ModalState>),
150    Wizard(Box<WizardModalState>),
151}
152
153impl ActiveOverlay {
154    fn as_modal(&self) -> Option<&ModalState> {
155        match self {
156            Self::Modal(state) => Some(state),
157            Self::Wizard(_) => None,
158        }
159    }
160
161    fn as_modal_mut(&mut self) -> Option<&mut ModalState> {
162        match self {
163            Self::Modal(state) => Some(state),
164            Self::Wizard(_) => None,
165        }
166    }
167
168    fn as_wizard(&self) -> Option<&WizardModalState> {
169        match self {
170            Self::Wizard(state) => Some(state),
171            Self::Modal(_) => None,
172        }
173    }
174
175    fn as_wizard_mut(&mut self) -> Option<&mut WizardModalState> {
176        match self {
177            Self::Wizard(state) => Some(state),
178            Self::Modal(_) => None,
179        }
180    }
181
182    fn restore_input(&self) -> bool {
183        match self {
184            Self::Modal(state) => state.restore_input,
185            Self::Wizard(_) => true,
186        }
187    }
188
189    fn restore_cursor(&self) -> bool {
190        match self {
191            Self::Modal(state) => state.restore_cursor,
192            Self::Wizard(_) => true,
193        }
194    }
195}
196
197#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
198pub(crate) enum MouseDragTarget {
199    #[default]
200    None,
201    Transcript,
202    ModalText,
203    Input,
204}
205
206#[derive(Clone, Debug, Default, PartialEq, Eq)]
207pub(crate) struct FullscreenSessionState {
208    pub(crate) active: bool,
209    pub(crate) interaction: FullscreenInteractionSettings,
210}
211
212pub struct Session {
213    // --- Managers (Phase 2) ---
214    /// Manages user input, cursor, and command history
215    pub(crate) input_manager: InputManager,
216    /// Manages scroll state and viewport metrics
217    pub(crate) scroll_manager: ScrollManager,
218    user_scrolled: bool,
219
220    // --- Message Management ---
221    pub(crate) lines: Vec<MessageLine>,
222    collapsed_pastes: Vec<CollapsedPaste>,
223    /// Thinking/reasoning run bookkeeping (collapse overrides + the run
224    /// currently streaming), isolated behind a narrow interface so the policy
225    /// can evolve and be tested independently of transcript storage.
226    thinking_runs: ThinkingRunIndex,
227    pub(crate) theme: InlineTheme,
228    pub(crate) styles: SessionStyles,
229    pub(crate) appearance: AppearanceConfig,
230    /// Follow live terminal light/dark reports (Contour `CSI ? 997` DSR) and
231    /// switch themes automatically. Opt-in via `SetColorSchemeAuto`.
232    pub(crate) auto_color_scheme: bool,
233    header_context: InlineHeaderContext,
234    pub(crate) header_rows: u16,
235    pub(crate) labels: MessageLabels,
236
237    // --- Prompt/Input Display ---
238    prompt_prefix: String,
239    prompt_style: InlineTextStyle,
240    placeholder: Option<String>,
241    placeholder_style: Option<InlineTextStyle>,
242    pub(crate) input_status_left: Option<String>,
243    footer_context_status: Option<String>,
244    footer_context_right: Option<String>,
245    footer_context_configured: bool,
246    pub(crate) input_status_right: Option<String>,
247    /// Transient "copied"/"copy failed" confirmation shown in the input status row.
248    copy_notification_until: Option<Instant>,
249    copy_notification_failed: bool,
250    copy_notification_chars: usize,
251    input_compact_mode: bool,
252
253    // --- UI State ---
254    navigation_state: ListState,
255    input_enabled: bool,
256    pub(crate) program_status: super::program_status::ProgramStatus,
257    pub(crate) activity_state: ActivityState,
258    image_input_enabled: bool,
259    cursor_visible: bool,
260    render_state: RenderState,
261    /// Track whether the transcript viewport must be cleared before repainting.
262    pub(crate) transcript_clear_required: bool,
263    /// Total number of message lines removed by transcript eviction.
264    pub(crate) evicted_message_count: usize,
265    /// Number of new transcript lines that arrived while the user was scrolled
266    /// away from the live bottom edge.
267    pub(crate) pending_new_messages: usize,
268    /// Most recent transcript line index that was created or revised.
269    /// Backs the minimal Jump-to-last-change navigation (`Ctrl+End`).
270    pub(crate) last_change_line_idx: Option<usize>,
271    should_exit: bool,
272    /// Timestamp of the last Ctrl+C press for double-press exit detection.
273    pub(crate) last_interrupt_press: Option<Instant>,
274    /// Timestamp of the last Esc press for double-Escape actions.
275    ///
276    /// First Esc arms the timer; a second Esc within
277    /// `DOUBLE_ESCAPE_WINDOW` clears the current line (multiline) or the
278    /// entire input (single-line) when content is present, or opens the
279    /// rewind picker (`/rewind`) when the composer is empty. Any non-Esc key
280    /// resets it so the double press must be consecutive.
281    pub(crate) last_escape_press: Option<Instant>,
282    scroll_cursor_steady_until: Option<Instant>,
283    last_shimmer_active: bool,
284    view_rows: u16,
285    pub(crate) input_height: u16,
286    pub(crate) transcript_rows: u16,
287    pub(crate) transcript_width: u16,
288    pub(crate) transcript_view_top: usize,
289    areas: SessionAreas,
290    sticky_prompt_target: Option<sticky_prompt::StickyPromptTarget>,
291    sticky_prompt_preview_cache: Option<sticky_prompt::StickyPromptPreviewCache>,
292    leading_user_prompt_truncated: bool,
293    transcript_file_link_targets: Vec<TranscriptFileLinkTarget>,
294    modal_link_targets: Vec<TranscriptFileLinkTarget>,
295    hovered_transcript_file_link: Option<usize>,
296    last_mouse_position: Option<(u16, u16)>,
297    last_link_open: Option<(String, Instant)>,
298    pending_link_open: Option<String>,
299    held_key_modifiers: KeyModifiers,
300
301    // --- Logging ---
302    log_receiver: Option<UnboundedReceiver<LogEntry>>,
303    log_lines: VecDeque<Arc<Text<'static>>>,
304    log_cached_text: Option<Arc<Text<'static>>>,
305    log_evicted: bool,
306    pub(crate) show_logs: bool,
307
308    // --- Rendering ---
309    transcript_cache: Option<TranscriptReflowCache>,
310    /// Cache of visible lines by (scroll_offset, width) - shared via Arc for zero-copy reads
311    /// Avoids expensive clone on cache hits
312    visible_lines_cache: Option<(usize, u16, usize, Arc<Vec<TranscriptLine>>)>,
313    pub(crate) queued_inputs: Vec<String>,
314    pub(crate) local_agents: Vec<LocalAgentEntry>,
315    local_agents_drawer_visible: bool,
316    subprocess_entries: Vec<String>,
317    subagent_preview: Option<String>,
318    queue_overlay_cache: Option<QueueOverlay>,
319    queue_overlay_version: u64,
320    active_overlay: Option<ActiveOverlay>,
321    overlay_queue: VecDeque<OverlayRequest>,
322    last_overlay_list_selection: Option<InlineListSelection>,
323    last_overlay_list_was_last: bool,
324    line_revision_counter: u64,
325    pub(crate) transcript_presentation_revision: u64,
326    /// Track the first line that needs reflow/update to avoid O(N) scans
327    first_dirty_line: Option<usize>,
328    in_tool_code_fence: bool,
329
330    // --- Prompt Suggestions ---
331    suggested_prompt_state: SuggestedPromptState,
332    inline_prompt_suggestion: InlinePromptSuggestionState,
333
334    // --- Thinking Indicator ---
335    pub(crate) thinking_spinner: ThinkingSpinner,
336    pub(crate) shimmer_state: ShimmerState,
337    pub(crate) progress: progress::TransientProgress,
338
339    // --- Reverse Search ---
340    pub(crate) reverse_search_state: reverse_search::ReverseSearchState,
341
342    // --- PTY Session Management ---
343    pub(crate) active_pty_sessions: Option<Arc<std::sync::atomic::AtomicUsize>>,
344
345    // --- Background Activity ---
346    /// Number of live background tasks (managed subagents and retained exec
347    /// sessions) surfaced by the most recent local-agents refresh. Drives the
348    /// global loading shimmer so background work is visible without opening
349    /// the drawer; it never feeds the turn-busy guards.
350    pub(crate) background_activity_count: usize,
351    /// Retained finished background rows (completed/failed/stopped/exited).
352    pub(crate) background_finished_count: usize,
353    /// Absolute hit rects for clickable background-indicator spans on the
354    /// input status line (activity text and the `{key} background` hint only).
355    pub(crate) background_indicator_hits: Vec<Rect>,
356
357    // --- Keybinding store ---
358    bindings: BindingStore,
359
360    // --- Clipboard for yank/paste operations ---
361    clipboard: String,
362    vim_state: VimState,
363
364    // --- Mouse Text Selection ---
365    pub(crate) mouse_selection: MouseSelectionState,
366    pub(crate) mouse_drag_target: MouseDragTarget,
367    pub(crate) drag_auto_scroll: Option<DragAutoScroll>,
368    pub(crate) fullscreen: FullscreenSessionState,
369
370    // --- Performance Caching ---
371    header_lines_cache: Option<Arc<Vec<Line<'static>>>>,
372    header_block_title_cache: Option<Line<'static>>,
373    header_height_cache: hashbrown::HashMap<u16, u16>,
374    pub(crate) queued_inputs_preview_cache: Option<Vec<String>>,
375    subprocess_entries_preview_cache: Option<Vec<String>>,
376    /// Fingerprint of the last `build_input_render` inputs (width, height,
377    /// content_hash, cursor, compact, suggested) plus the built result.
378    input_render_cache: Option<(u16, u16, u64, usize, bool, bool, input::InputRender)>,
379
380    // --- Terminal Title ---
381    /// Product/app name used in terminal title branding
382    app_name: String,
383    /// Workspace root path for dynamic title generation
384    workspace_root: Option<std::path::PathBuf>,
385    /// Raw config items for terminal title rendering (`None` means use defaults).
386    terminal_title_items: Option<Vec<String>>,
387    /// Active thread label shown in terminal title when configured.
388    terminal_title_thread_label: Option<String>,
389    /// Active git branch shown in terminal title when configured.
390    terminal_title_git_branch: Option<String>,
391    /// Latest task tracker progress label extracted from the task panel.
392    terminal_title_task_progress: Option<String>,
393    /// Last set terminal title to avoid redundant updates
394    last_terminal_title: Option<String>,
395
396    // --- Streaming State ---
397    /// Track if the assistant is currently streaming a final answer.
398    /// When true, user input should be queued instead of submitted immediately
399    /// to prevent race conditions with turn completion (see GitHub #12569).
400    is_streaming_final_answer: bool,
401}
402
403/// Per-session index of thinking/reasoning (`Policy`) runs.
404///
405/// Owns the collapse overrides and the start of the run currently streaming,
406/// exposing them through a narrow interface. Keeping this state behind guard
407/// rails isolates thinking-run bookkeeping from transcript storage so the
408/// policy can be tested and evolved without coupling to `Session`.
409#[derive(Debug, Default, Clone)]
410pub(crate) struct ThinkingRunIndex {
411    /// Explicit collapse overrides keyed by run-start line index. Absence means
412    /// "use the config default" (`appearance.thinking_collapsed_by_default()`).
413    collapsed: std::collections::HashMap<usize, bool>,
414    /// Start line index of the reasoning run currently being streamed, if any.
415    /// `None` when no reasoning is actively streaming. Because the transcript
416    /// only ever appends lines, this index stays valid until `clear_screen`.
417    active_start: Option<usize>,
418}
419
420impl ThinkingRunIndex {
421    /// Whether the run starting at `start` should render collapsed, falling
422    /// back to `default` when no explicit override exists.
423    fn is_collapsed(&self, start: usize, default: bool) -> bool {
424        self.collapsed.get(&start).copied().unwrap_or(default)
425    }
426
427    /// Set the explicit collapse state for the run starting at `start`.
428    fn set_collapsed(&mut self, start: usize, collapsed: bool) {
429        self.collapsed.insert(start, collapsed);
430    }
431
432    /// Record the start of a newly begun reasoning run.
433    fn begin_run(&mut self, start: usize) {
434        self.active_start = Some(start);
435    }
436
437    /// End the active reasoning run (a non-reasoning line was appended).
438    fn end_run(&mut self) {
439        self.active_start = None;
440    }
441
442    /// Start line index of the reasoning run currently streaming, if any.
443    fn active_start(&self) -> Option<usize> {
444        self.active_start
445    }
446
447    /// Reset all tracked runs (e.g. on `clear_screen`).
448    fn clear(&mut self) {
449        self.collapsed.clear();
450        self.active_start = None;
451    }
452}