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