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::{Receiver, 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;
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::clipboard_5522::Clipboard5522State;
99use self::config::AppearanceConfig;
100pub(crate) use self::input::status_requires_shimmer;
101use self::mouse_selection::{DragAutoScroll, DragAutoScrollDirection, MouseSelectionState};
102use self::queue::QueueOverlay;
103use self::render_state::RenderState;
104use self::scroll::ScrollManager;
105pub(crate) use self::spinner::pulse_spinner_frame_for_phase;
106pub(crate) use self::spinner::title_spinner_frame;
107use self::spinner::{ShimmerState, ThinkingSpinner};
108use self::styling::SessionStyles;
109pub use self::terminal_title::{
110    TERMINAL_TITLE_ATTENTION_NEEDLES, TERMINAL_TITLE_UNDOING_NEEDLES, TERMINAL_TITLE_WAITING_NEEDLES,
111};
112use self::transcript::TranscriptReflowCache;
113use self::transcript_links::TranscriptFileLinkTarget;
114pub(crate) use self::transcript_links::TranscriptLinkClickAction;
115use self::vim::VimState;
116#[cfg(test)]
117use super::types::InlineHeaderHighlight;
118// TaskPlan integration intentionally omitted in this UI crate.
119use crate::tui::ui::tui::log::{LogEntry, highlight_log_entry};
120
121const USER_PREFIX: &str = "";
122const PLACEHOLDER_COLOR: RgbColor = RgbColor(ui::PLACEHOLDER_R, ui::PLACEHOLDER_G, ui::PLACEHOLDER_B);
123const MAX_LOG_LINES: usize = 256;
124const MAX_LOG_DRAIN_PER_TICK: usize = 256;
125
126#[derive(Clone, Debug)]
127struct CollapsedPaste {
128    line_index: usize,
129    full_text: String,
130}
131
132#[derive(Clone, Debug, Default)]
133pub(crate) struct SuggestedPromptState {
134    active: bool,
135}
136
137#[derive(Clone, Copy, Debug, PartialEq, Eq)]
138pub(crate) enum InlinePromptSuggestionSource {
139    Llm,
140    Local,
141}
142
143#[derive(Clone, Debug, Default, PartialEq, Eq)]
144pub(crate) struct InlinePromptSuggestionState {
145    suggestion: Option<String>,
146    source: Option<InlinePromptSuggestionSource>,
147}
148
149pub(crate) enum ActiveOverlay {
150    Modal(Box<ModalState>),
151    Wizard(Box<WizardModalState>),
152}
153
154impl ActiveOverlay {
155    fn as_modal(&self) -> Option<&ModalState> {
156        match self {
157            Self::Modal(state) => Some(state),
158            Self::Wizard(_) => None,
159        }
160    }
161
162    fn as_modal_mut(&mut self) -> Option<&mut ModalState> {
163        match self {
164            Self::Modal(state) => Some(state),
165            Self::Wizard(_) => None,
166        }
167    }
168
169    fn as_wizard(&self) -> Option<&WizardModalState> {
170        match self {
171            Self::Wizard(state) => Some(state),
172            Self::Modal(_) => None,
173        }
174    }
175
176    fn as_wizard_mut(&mut self) -> Option<&mut WizardModalState> {
177        match self {
178            Self::Wizard(state) => Some(state),
179            Self::Modal(_) => None,
180        }
181    }
182
183    fn restore_input(&self) -> bool {
184        match self {
185            Self::Modal(state) => state.restore_input,
186            Self::Wizard(_) => true,
187        }
188    }
189
190    fn restore_cursor(&self) -> bool {
191        match self {
192            Self::Modal(state) => state.restore_cursor,
193            Self::Wizard(_) => true,
194        }
195    }
196}
197
198#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
199pub(crate) enum MouseDragTarget {
200    #[default]
201    None,
202    Transcript,
203    ModalText,
204    Input,
205}
206
207#[derive(Clone, Debug, Default, PartialEq, Eq)]
208pub(crate) struct FullscreenSessionState {
209    pub(crate) active: bool,
210    pub(crate) interaction: FullscreenInteractionSettings,
211}
212
213/// Transient jump-landing tint: which transcript line index glows and when
214/// the glow ends. Message-index keying keeps the paint reflow-safe; eviction
215/// and clears drop it rather than shifting a 1.5s cosmetic.
216#[derive(Clone, Debug)]
217pub(crate) struct TranscriptFlash {
218    pub(crate) line_idx: usize,
219    pub(crate) expires_at: Instant,
220}
221
222pub struct Session {
223    // --- Managers (Phase 2) ---
224    /// Manages user input, cursor, and command history
225    pub(crate) input_manager: InputManager,
226    /// Manages scroll state and viewport metrics
227    pub(crate) scroll_manager: ScrollManager,
228    user_scrolled: bool,
229
230    // --- Message Management ---
231    pub(crate) lines: Vec<MessageLine>,
232    collapsed_pastes: Vec<CollapsedPaste>,
233    /// Thinking/reasoning run bookkeeping (collapse overrides + the run
234    /// currently streaming), isolated behind a narrow interface so the policy
235    /// can evolve and be tested independently of transcript storage.
236    thinking_runs: ThinkingRunIndex,
237    pub(crate) theme: InlineTheme,
238    pub(crate) styles: SessionStyles,
239    pub(crate) appearance: AppearanceConfig,
240    /// Follow live terminal light/dark reports (Contour `CSI ? 997` DSR) and
241    /// switch themes automatically. Opt-in via `SetColorSchemeAuto`.
242    pub(crate) auto_color_scheme: bool,
243    header_context: InlineHeaderContext,
244    pub(crate) header_rows: u16,
245    pub(crate) labels: MessageLabels,
246
247    // --- Prompt/Input Display ---
248    prompt_prefix: String,
249    prompt_style: InlineTextStyle,
250    placeholder: Option<String>,
251    placeholder_style: Option<InlineTextStyle>,
252    pub(crate) input_status_left: Option<String>,
253    footer_context_status: Option<String>,
254    footer_context_right: Option<String>,
255    footer_context_configured: bool,
256    pub(crate) input_status_right: Option<String>,
257    /// Transient "copied"/"copy failed" confirmation shown in the input status row.
258    copy_notification_until: Option<Instant>,
259    copy_notification_failed: bool,
260    copy_notification_chars: usize,
261    input_compact_mode: bool,
262
263    // --- UI State ---
264    navigation_state: ListState,
265    input_enabled: bool,
266    pub(crate) program_status: super::program_status::ProgramStatus,
267    pub(crate) activity_state: ActivityState,
268    image_input_enabled: bool,
269    cursor_visible: bool,
270    /// Whether the terminal view may currently be observable.
271    ///
272    /// Tracks `CSI ? 999 ; Ps n` visibility reports (mode `2033`). Fail-visible
273    /// default: terminals without support never send a report, so the session
274    /// always paints. While `false` the drive loop skips frame draws and
275    /// animation ticks; input and state updates continue so the session can
276    /// repaint its latest state on return to visible.
277    terminal_visible: bool,
278    /// Kitty OSC 5522 clipboard-read fallback state (image paste over SSH).
279    clipboard_5522: Clipboard5522State,
280    render_state: RenderState,
281    /// Track whether the transcript viewport must be cleared before repainting.
282    pub(crate) transcript_clear_required: bool,
283    /// Total number of message lines removed by transcript eviction.
284    pub(crate) evicted_message_count: usize,
285    /// Number of new transcript lines that arrived while the user was scrolled
286    /// away from the live bottom edge.
287    pub(crate) pending_new_messages: usize,
288    /// Most recent transcript line index that was created or revised.
289    /// Backs the minimal Jump-to-last-change navigation (`Ctrl+End`).
290    pub(crate) last_change_line_idx: Option<usize>,
291    /// Transient tint on the jump-landing message; expires via `handle_tick`.
292    pub(crate) transcript_flash: Option<TranscriptFlash>,
293    should_exit: bool,
294    /// Timestamp of the last Ctrl+C press for double-press exit detection.
295    pub(crate) last_interrupt_press: Option<Instant>,
296    /// Timestamp of the last Esc press for double-Escape actions.
297    ///
298    /// First Esc arms the timer; a second Esc within
299    /// `DOUBLE_ESCAPE_WINDOW` clears the current line (multiline) or the
300    /// entire input (single-line) when content is present, or opens the
301    /// rewind picker (`/rewind`) when the composer is empty. Any non-Esc key
302    /// resets it so the double press must be consecutive.
303    pub(crate) last_escape_press: Option<Instant>,
304    scroll_cursor_steady_until: Option<Instant>,
305    last_shimmer_active: bool,
306    view_rows: u16,
307    pub(crate) input_height: u16,
308    pub(crate) transcript_rows: u16,
309    pub(crate) transcript_width: u16,
310    pub(crate) transcript_view_top: usize,
311    areas: SessionAreas,
312    sticky_prompt_target: Option<sticky_prompt::StickyPromptTarget>,
313    sticky_prompt_preview_cache: Option<sticky_prompt::StickyPromptPreviewCache>,
314    leading_user_prompt_truncated: bool,
315    transcript_file_link_targets: Vec<TranscriptFileLinkTarget>,
316    modal_link_targets: Vec<TranscriptFileLinkTarget>,
317    hovered_transcript_file_link: Option<usize>,
318    last_mouse_position: Option<(u16, u16)>,
319    last_link_open: Option<(String, Instant)>,
320    pending_link_open: Option<String>,
321    held_key_modifiers: KeyModifiers,
322
323    // --- Logging ---
324    log_receiver: Option<Receiver<LogEntry>>,
325    log_lines: VecDeque<Arc<Text<'static>>>,
326    log_cached_text: Option<Arc<Text<'static>>>,
327    log_evicted: bool,
328    pub(crate) show_logs: bool,
329
330    // --- Rendering ---
331    transcript_cache: Option<TranscriptReflowCache>,
332    /// Cache of visible lines by (scroll_offset, width) - shared via Arc for zero-copy reads
333    /// Avoids expensive clone on cache hits
334    visible_lines_cache: Option<(usize, u16, usize, Arc<Vec<TranscriptLine>>)>,
335    pub(crate) queued_inputs: Vec<String>,
336    pub(crate) local_agents: Vec<LocalAgentEntry>,
337    pub(crate) active_plan: Option<ActivePlanEntry>,
338    local_agents_drawer_visible: bool,
339    subprocess_entries: Vec<String>,
340    subagent_preview: Option<String>,
341    queue_overlay_cache: Option<QueueOverlay>,
342    queue_overlay_version: u64,
343    active_overlay: Option<ActiveOverlay>,
344    overlay_queue: VecDeque<OverlayRequest>,
345    last_overlay_list_selection: Option<InlineListSelection>,
346    last_overlay_list_was_last: bool,
347    line_revision_counter: u64,
348    pub(crate) transcript_presentation_revision: u64,
349    /// Track the first line that needs reflow/update to avoid O(N) scans
350    first_dirty_line: Option<usize>,
351    in_tool_code_fence: bool,
352
353    // --- Prompt Suggestions ---
354    suggested_prompt_state: SuggestedPromptState,
355    inline_prompt_suggestion: InlinePromptSuggestionState,
356
357    // --- Thinking Indicator ---
358    pub(crate) thinking_spinner: ThinkingSpinner,
359    pub(crate) shimmer_state: ShimmerState,
360    pub(crate) progress: progress::TransientProgress,
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}