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
212/// Transient jump-landing tint: which transcript line index glows and when
213/// the glow ends. Message-index keying keeps the paint reflow-safe; eviction
214/// and clears drop it rather than shifting a 1.5s cosmetic.
215#[derive(Clone, Debug)]
216pub(crate) struct TranscriptFlash {
217    pub(crate) line_idx: usize,
218    pub(crate) expires_at: Instant,
219}
220
221pub struct Session {
222    // --- Managers (Phase 2) ---
223    /// Manages user input, cursor, and command history
224    pub(crate) input_manager: InputManager,
225    /// Manages scroll state and viewport metrics
226    pub(crate) scroll_manager: ScrollManager,
227    user_scrolled: bool,
228
229    // --- Message Management ---
230    pub(crate) lines: Vec<MessageLine>,
231    collapsed_pastes: Vec<CollapsedPaste>,
232    /// Thinking/reasoning run bookkeeping (collapse overrides + the run
233    /// currently streaming), isolated behind a narrow interface so the policy
234    /// can evolve and be tested independently of transcript storage.
235    thinking_runs: ThinkingRunIndex,
236    pub(crate) theme: InlineTheme,
237    pub(crate) styles: SessionStyles,
238    pub(crate) appearance: AppearanceConfig,
239    /// Follow live terminal light/dark reports (Contour `CSI ? 997` DSR) and
240    /// switch themes automatically. Opt-in via `SetColorSchemeAuto`.
241    pub(crate) auto_color_scheme: bool,
242    header_context: InlineHeaderContext,
243    pub(crate) header_rows: u16,
244    pub(crate) labels: MessageLabels,
245
246    // --- Prompt/Input Display ---
247    prompt_prefix: String,
248    prompt_style: InlineTextStyle,
249    placeholder: Option<String>,
250    placeholder_style: Option<InlineTextStyle>,
251    pub(crate) input_status_left: Option<String>,
252    footer_context_status: Option<String>,
253    footer_context_right: Option<String>,
254    footer_context_configured: bool,
255    pub(crate) input_status_right: Option<String>,
256    /// Transient "copied"/"copy failed" confirmation shown in the input status row.
257    copy_notification_until: Option<Instant>,
258    copy_notification_failed: bool,
259    copy_notification_chars: usize,
260    input_compact_mode: bool,
261
262    // --- UI State ---
263    navigation_state: ListState,
264    input_enabled: bool,
265    pub(crate) program_status: super::program_status::ProgramStatus,
266    pub(crate) activity_state: ActivityState,
267    image_input_enabled: bool,
268    cursor_visible: bool,
269    render_state: RenderState,
270    /// Track whether the transcript viewport must be cleared before repainting.
271    pub(crate) transcript_clear_required: bool,
272    /// Total number of message lines removed by transcript eviction.
273    pub(crate) evicted_message_count: usize,
274    /// Number of new transcript lines that arrived while the user was scrolled
275    /// away from the live bottom edge.
276    pub(crate) pending_new_messages: usize,
277    /// Most recent transcript line index that was created or revised.
278    /// Backs the minimal Jump-to-last-change navigation (`Ctrl+End`).
279    pub(crate) last_change_line_idx: Option<usize>,
280    /// Transient tint on the jump-landing message; expires via `handle_tick`.
281    pub(crate) transcript_flash: Option<TranscriptFlash>,
282    should_exit: bool,
283    /// Timestamp of the last Ctrl+C press for double-press exit detection.
284    pub(crate) last_interrupt_press: Option<Instant>,
285    /// Timestamp of the last Esc press for double-Escape actions.
286    ///
287    /// First Esc arms the timer; a second Esc within
288    /// `DOUBLE_ESCAPE_WINDOW` clears the current line (multiline) or the
289    /// entire input (single-line) when content is present, or opens the
290    /// rewind picker (`/rewind`) when the composer is empty. Any non-Esc key
291    /// resets it so the double press must be consecutive.
292    pub(crate) last_escape_press: Option<Instant>,
293    scroll_cursor_steady_until: Option<Instant>,
294    last_shimmer_active: bool,
295    view_rows: u16,
296    pub(crate) input_height: u16,
297    pub(crate) transcript_rows: u16,
298    pub(crate) transcript_width: u16,
299    pub(crate) transcript_view_top: usize,
300    areas: SessionAreas,
301    sticky_prompt_target: Option<sticky_prompt::StickyPromptTarget>,
302    sticky_prompt_preview_cache: Option<sticky_prompt::StickyPromptPreviewCache>,
303    leading_user_prompt_truncated: bool,
304    transcript_file_link_targets: Vec<TranscriptFileLinkTarget>,
305    modal_link_targets: Vec<TranscriptFileLinkTarget>,
306    hovered_transcript_file_link: Option<usize>,
307    last_mouse_position: Option<(u16, u16)>,
308    last_link_open: Option<(String, Instant)>,
309    pending_link_open: Option<String>,
310    held_key_modifiers: KeyModifiers,
311
312    // --- Logging ---
313    log_receiver: Option<UnboundedReceiver<LogEntry>>,
314    log_lines: VecDeque<Arc<Text<'static>>>,
315    log_cached_text: Option<Arc<Text<'static>>>,
316    log_evicted: bool,
317    pub(crate) show_logs: bool,
318
319    // --- Rendering ---
320    transcript_cache: Option<TranscriptReflowCache>,
321    /// Cache of visible lines by (scroll_offset, width) - shared via Arc for zero-copy reads
322    /// Avoids expensive clone on cache hits
323    visible_lines_cache: Option<(usize, u16, usize, Arc<Vec<TranscriptLine>>)>,
324    pub(crate) queued_inputs: Vec<String>,
325    pub(crate) local_agents: Vec<LocalAgentEntry>,
326    local_agents_drawer_visible: bool,
327    subprocess_entries: Vec<String>,
328    subagent_preview: Option<String>,
329    queue_overlay_cache: Option<QueueOverlay>,
330    queue_overlay_version: u64,
331    active_overlay: Option<ActiveOverlay>,
332    overlay_queue: VecDeque<OverlayRequest>,
333    last_overlay_list_selection: Option<InlineListSelection>,
334    last_overlay_list_was_last: bool,
335    line_revision_counter: u64,
336    pub(crate) transcript_presentation_revision: u64,
337    /// Track the first line that needs reflow/update to avoid O(N) scans
338    first_dirty_line: Option<usize>,
339    in_tool_code_fence: bool,
340
341    // --- Prompt Suggestions ---
342    suggested_prompt_state: SuggestedPromptState,
343    inline_prompt_suggestion: InlinePromptSuggestionState,
344
345    // --- Thinking Indicator ---
346    pub(crate) thinking_spinner: ThinkingSpinner,
347    pub(crate) shimmer_state: ShimmerState,
348    pub(crate) progress: progress::TransientProgress,
349
350    // --- Reverse Search ---
351    pub(crate) reverse_search_state: reverse_search::ReverseSearchState,
352
353    // --- PTY Session Management ---
354    pub(crate) active_pty_sessions: Option<Arc<std::sync::atomic::AtomicUsize>>,
355
356    // --- Background Activity ---
357    /// Number of live background tasks (managed subagents and retained exec
358    /// sessions) surfaced by the most recent local-agents refresh. Drives the
359    /// global loading shimmer so background work is visible without opening
360    /// the drawer; it never feeds the turn-busy guards.
361    pub(crate) background_activity_count: usize,
362    /// Retained finished background rows (completed/failed/stopped/exited).
363    pub(crate) background_finished_count: usize,
364    /// Absolute hit rects for clickable background-indicator spans on the
365    /// input status line (activity text and the `{key} background` hint only).
366    pub(crate) background_indicator_hits: Vec<Rect>,
367
368    // --- Keybinding store ---
369    bindings: BindingStore,
370
371    // --- Clipboard for yank/paste operations ---
372    clipboard: String,
373    vim_state: VimState,
374
375    // --- Mouse Text Selection ---
376    pub(crate) mouse_selection: MouseSelectionState,
377    pub(crate) mouse_drag_target: MouseDragTarget,
378    pub(crate) drag_auto_scroll: Option<DragAutoScroll>,
379    pub(crate) fullscreen: FullscreenSessionState,
380
381    // --- Performance Caching ---
382    header_lines_cache: Option<Arc<Vec<Line<'static>>>>,
383    header_block_title_cache: Option<Line<'static>>,
384    header_height_cache: hashbrown::HashMap<u16, u16>,
385    pub(crate) queued_inputs_preview_cache: Option<Vec<String>>,
386    subprocess_entries_preview_cache: Option<Vec<String>>,
387    /// Fingerprint of the last `build_input_render` inputs (width, height,
388    /// content_hash, cursor, compact, suggested) plus the built result.
389    input_render_cache: Option<(u16, u16, u64, usize, bool, bool, input::InputRender)>,
390
391    // --- Terminal Title ---
392    /// Product/app name used in terminal title branding
393    app_name: String,
394    /// Workspace root path for dynamic title generation
395    workspace_root: Option<std::path::PathBuf>,
396    /// Raw config items for terminal title rendering (`None` means use defaults).
397    terminal_title_items: Option<Vec<String>>,
398    /// Active thread label shown in terminal title when configured.
399    terminal_title_thread_label: Option<String>,
400    /// Active git branch shown in terminal title when configured.
401    terminal_title_git_branch: Option<String>,
402    /// Latest task tracker progress label extracted from the task panel.
403    terminal_title_task_progress: Option<String>,
404    /// Last set terminal title to avoid redundant updates
405    last_terminal_title: Option<String>,
406
407    // --- Streaming State ---
408    /// Track if the assistant is currently streaming a final answer.
409    /// When true, user input should be queued instead of submitted immediately
410    /// to prevent race conditions with turn completion (see GitHub #12569).
411    is_streaming_final_answer: bool,
412}
413
414/// Per-session index of thinking/reasoning (`Policy`) runs.
415///
416/// Owns the collapse overrides and the start of the run currently streaming,
417/// exposing them through a narrow interface. Keeping this state behind guard
418/// rails isolates thinking-run bookkeeping from transcript storage so the
419/// policy can be tested and evolved without coupling to `Session`.
420#[derive(Debug, Default, Clone)]
421pub(crate) struct ThinkingRunIndex {
422    /// Explicit collapse overrides keyed by run-start line index. Absence means
423    /// "use the config default" (`appearance.thinking_collapsed_by_default()`).
424    collapsed: std::collections::HashMap<usize, bool>,
425    /// Start line index of the reasoning run currently being streamed, if any.
426    /// `None` when no reasoning is actively streaming. Because the transcript
427    /// only ever appends lines, this index stays valid until `clear_screen`.
428    active_start: Option<usize>,
429}
430
431impl ThinkingRunIndex {
432    /// Whether the run starting at `start` should render collapsed, falling
433    /// back to `default` when no explicit override exists.
434    fn is_collapsed(&self, start: usize, default: bool) -> bool {
435        self.collapsed.get(&start).copied().unwrap_or(default)
436    }
437
438    /// Set the explicit collapse state for the run starting at `start`.
439    fn set_collapsed(&mut self, start: usize, collapsed: bool) {
440        self.collapsed.insert(start, collapsed);
441    }
442
443    /// Record the start of a newly begun reasoning run.
444    fn begin_run(&mut self, start: usize) {
445        self.active_start = Some(start);
446    }
447
448    /// End the active reasoning run (a non-reasoning line was appended).
449    fn end_run(&mut self) {
450        self.active_start = None;
451    }
452
453    /// Start line index of the reasoning run currently streaming, if any.
454    fn active_start(&self) -> Option<usize> {
455        self.active_start
456    }
457
458    /// Reset all tracked runs (e.g. on `clear_screen`).
459    fn clear(&mut self) {
460        self.collapsed.clear();
461        self.active_start = None;
462    }
463}