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::{ActivePlanEntry, 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    /// Whether the terminal view may currently be observable.
270    ///
271    /// Tracks `CSI ? 999 ; Ps n` visibility reports (mode `2033`). Fail-visible
272    /// default: terminals without support never send a report, so the session
273    /// always paints. While `false` the drive loop skips frame draws and
274    /// animation ticks; input and state updates continue so the session can
275    /// repaint its latest state on return to visible.
276    terminal_visible: bool,
277    render_state: RenderState,
278    /// Track whether the transcript viewport must be cleared before repainting.
279    pub(crate) transcript_clear_required: bool,
280    /// Total number of message lines removed by transcript eviction.
281    pub(crate) evicted_message_count: usize,
282    /// Number of new transcript lines that arrived while the user was scrolled
283    /// away from the live bottom edge.
284    pub(crate) pending_new_messages: usize,
285    /// Most recent transcript line index that was created or revised.
286    /// Backs the minimal Jump-to-last-change navigation (`Ctrl+End`).
287    pub(crate) last_change_line_idx: Option<usize>,
288    /// Transient tint on the jump-landing message; expires via `handle_tick`.
289    pub(crate) transcript_flash: Option<TranscriptFlash>,
290    should_exit: bool,
291    /// Timestamp of the last Ctrl+C press for double-press exit detection.
292    pub(crate) last_interrupt_press: Option<Instant>,
293    /// Timestamp of the last Esc press for double-Escape actions.
294    ///
295    /// First Esc arms the timer; a second Esc within
296    /// `DOUBLE_ESCAPE_WINDOW` clears the current line (multiline) or the
297    /// entire input (single-line) when content is present, or opens the
298    /// rewind picker (`/rewind`) when the composer is empty. Any non-Esc key
299    /// resets it so the double press must be consecutive.
300    pub(crate) last_escape_press: Option<Instant>,
301    scroll_cursor_steady_until: Option<Instant>,
302    last_shimmer_active: bool,
303    view_rows: u16,
304    pub(crate) input_height: u16,
305    pub(crate) transcript_rows: u16,
306    pub(crate) transcript_width: u16,
307    pub(crate) transcript_view_top: usize,
308    areas: SessionAreas,
309    sticky_prompt_target: Option<sticky_prompt::StickyPromptTarget>,
310    sticky_prompt_preview_cache: Option<sticky_prompt::StickyPromptPreviewCache>,
311    leading_user_prompt_truncated: bool,
312    transcript_file_link_targets: Vec<TranscriptFileLinkTarget>,
313    modal_link_targets: Vec<TranscriptFileLinkTarget>,
314    hovered_transcript_file_link: Option<usize>,
315    last_mouse_position: Option<(u16, u16)>,
316    last_link_open: Option<(String, Instant)>,
317    pending_link_open: Option<String>,
318    held_key_modifiers: KeyModifiers,
319
320    // --- Logging ---
321    log_receiver: Option<UnboundedReceiver<LogEntry>>,
322    log_lines: VecDeque<Arc<Text<'static>>>,
323    log_cached_text: Option<Arc<Text<'static>>>,
324    log_evicted: bool,
325    pub(crate) show_logs: bool,
326
327    // --- Rendering ---
328    transcript_cache: Option<TranscriptReflowCache>,
329    /// Cache of visible lines by (scroll_offset, width) - shared via Arc for zero-copy reads
330    /// Avoids expensive clone on cache hits
331    visible_lines_cache: Option<(usize, u16, usize, Arc<Vec<TranscriptLine>>)>,
332    pub(crate) queued_inputs: Vec<String>,
333    pub(crate) local_agents: Vec<LocalAgentEntry>,
334    pub(crate) active_plan: Option<ActivePlanEntry>,
335    local_agents_drawer_visible: bool,
336    subprocess_entries: Vec<String>,
337    subagent_preview: Option<String>,
338    queue_overlay_cache: Option<QueueOverlay>,
339    queue_overlay_version: u64,
340    active_overlay: Option<ActiveOverlay>,
341    overlay_queue: VecDeque<OverlayRequest>,
342    last_overlay_list_selection: Option<InlineListSelection>,
343    last_overlay_list_was_last: bool,
344    line_revision_counter: u64,
345    pub(crate) transcript_presentation_revision: u64,
346    /// Track the first line that needs reflow/update to avoid O(N) scans
347    first_dirty_line: Option<usize>,
348    in_tool_code_fence: bool,
349
350    // --- Prompt Suggestions ---
351    suggested_prompt_state: SuggestedPromptState,
352    inline_prompt_suggestion: InlinePromptSuggestionState,
353
354    // --- Thinking Indicator ---
355    pub(crate) thinking_spinner: ThinkingSpinner,
356    pub(crate) shimmer_state: ShimmerState,
357    pub(crate) progress: progress::TransientProgress,
358
359    // --- Reverse Search ---
360    pub(crate) reverse_search_state: reverse_search::ReverseSearchState,
361
362    // --- PTY Session Management ---
363    pub(crate) active_pty_sessions: Option<Arc<std::sync::atomic::AtomicUsize>>,
364
365    // --- Background Activity ---
366    /// Number of live background tasks (managed subagents and retained exec
367    /// sessions) surfaced by the most recent local-agents refresh. Drives the
368    /// global loading shimmer so background work is visible without opening
369    /// the drawer; it never feeds the turn-busy guards.
370    pub(crate) background_activity_count: usize,
371    /// Retained finished background rows (completed/failed/stopped/exited).
372    pub(crate) background_finished_count: usize,
373    /// Absolute hit rects for clickable background-indicator spans on the
374    /// input status line (activity text and the `{key} background` hint only).
375    pub(crate) background_indicator_hits: Vec<Rect>,
376
377    // --- Keybinding store ---
378    bindings: BindingStore,
379
380    // --- Clipboard for yank/paste operations ---
381    clipboard: String,
382    vim_state: VimState,
383
384    // --- Mouse Text Selection ---
385    pub(crate) mouse_selection: MouseSelectionState,
386    pub(crate) mouse_drag_target: MouseDragTarget,
387    pub(crate) drag_auto_scroll: Option<DragAutoScroll>,
388    pub(crate) fullscreen: FullscreenSessionState,
389
390    // --- Performance Caching ---
391    header_lines_cache: Option<Arc<Vec<Line<'static>>>>,
392    header_block_title_cache: Option<Line<'static>>,
393    header_height_cache: hashbrown::HashMap<u16, u16>,
394    pub(crate) queued_inputs_preview_cache: Option<Vec<String>>,
395    subprocess_entries_preview_cache: Option<Vec<String>>,
396    /// Fingerprint of the last `build_input_render` inputs (width, height,
397    /// content_hash, cursor, compact, suggested) plus the built result.
398    input_render_cache: Option<(u16, u16, u64, usize, bool, bool, input::InputRender)>,
399
400    // --- Terminal Title ---
401    /// Product/app name used in terminal title branding
402    app_name: String,
403    /// Workspace root path for dynamic title generation
404    workspace_root: Option<std::path::PathBuf>,
405    /// Raw config items for terminal title rendering (`None` means use defaults).
406    terminal_title_items: Option<Vec<String>>,
407    /// Active thread label shown in terminal title when configured.
408    terminal_title_thread_label: Option<String>,
409    /// Active git branch shown in terminal title when configured.
410    terminal_title_git_branch: Option<String>,
411    /// Latest task tracker progress label extracted from the task panel.
412    terminal_title_task_progress: Option<String>,
413    /// Last set terminal title to avoid redundant updates
414    last_terminal_title: Option<String>,
415
416    // --- Streaming State ---
417    /// Track if the assistant is currently streaming a final answer.
418    /// When true, user input should be queued instead of submitted immediately
419    /// to prevent race conditions with turn completion (see GitHub #12569).
420    is_streaming_final_answer: bool,
421}
422
423/// Per-session index of thinking/reasoning (`Policy`) runs.
424///
425/// Owns the collapse overrides and the start of the run currently streaming,
426/// exposing them through a narrow interface. Keeping this state behind guard
427/// rails isolates thinking-run bookkeeping from transcript storage so the
428/// policy can be tested and evolved without coupling to `Session`.
429#[derive(Debug, Default, Clone)]
430pub(crate) struct ThinkingRunIndex {
431    /// Explicit collapse overrides keyed by run-start line index. Absence means
432    /// "use the config default" (`appearance.thinking_collapsed_by_default()`).
433    collapsed: std::collections::HashMap<usize, bool>,
434    /// Start line index of the reasoning run currently being streamed, if any.
435    /// `None` when no reasoning is actively streaming. Because the transcript
436    /// only ever appends lines, this index stays valid until `clear_screen`.
437    active_start: Option<usize>,
438}
439
440impl ThinkingRunIndex {
441    /// Whether the run starting at `start` should render collapsed, falling
442    /// back to `default` when no explicit override exists.
443    fn is_collapsed(&self, start: usize, default: bool) -> bool {
444        self.collapsed.get(&start).copied().unwrap_or(default)
445    }
446
447    /// Set the explicit collapse state for the run starting at `start`.
448    fn set_collapsed(&mut self, start: usize, collapsed: bool) {
449        self.collapsed.insert(start, collapsed);
450    }
451
452    /// Record the start of a newly begun reasoning run.
453    fn begin_run(&mut self, start: usize) {
454        self.active_start = Some(start);
455    }
456
457    /// End the active reasoning run (a non-reasoning line was appended).
458    fn end_run(&mut self) {
459        self.active_start = None;
460    }
461
462    /// Start line index of the reasoning run currently streaming, if any.
463    fn active_start(&self) -> Option<usize> {
464        self.active_start
465    }
466
467    /// Reset all tracked runs (e.g. on `clear_screen`).
468    fn clear(&mut self) {
469        self.collapsed.clear();
470        self.active_start = None;
471    }
472}