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