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