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
63mod 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;
117use 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#[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 pub(crate) input_manager: InputManager,
225 pub(crate) scroll_manager: ScrollManager,
227 user_scrolled: bool,
228
229 pub(crate) lines: Vec<MessageLine>,
231 collapsed_pastes: Vec<CollapsedPaste>,
232 thinking_runs: ThinkingRunIndex,
236 pub(crate) theme: InlineTheme,
237 pub(crate) styles: SessionStyles,
238 pub(crate) appearance: AppearanceConfig,
239 pub(crate) auto_color_scheme: bool,
242 header_context: InlineHeaderContext,
243 pub(crate) header_rows: u16,
244 pub(crate) labels: MessageLabels,
245
246 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 copy_notification_until: Option<Instant>,
258 copy_notification_failed: bool,
259 copy_notification_chars: usize,
260 input_compact_mode: bool,
261
262 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 terminal_visible: bool,
277 render_state: RenderState,
278 pub(crate) transcript_clear_required: bool,
280 pub(crate) evicted_message_count: usize,
282 pub(crate) pending_new_messages: usize,
285 pub(crate) last_change_line_idx: Option<usize>,
288 pub(crate) transcript_flash: Option<TranscriptFlash>,
290 should_exit: bool,
291 pub(crate) last_interrupt_press: Option<Instant>,
293 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 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 transcript_cache: Option<TranscriptReflowCache>,
329 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 first_dirty_line: Option<usize>,
348 in_tool_code_fence: bool,
349
350 suggested_prompt_state: SuggestedPromptState,
352 inline_prompt_suggestion: InlinePromptSuggestionState,
353
354 pub(crate) thinking_spinner: ThinkingSpinner,
356 pub(crate) shimmer_state: ShimmerState,
357 pub(crate) progress: progress::TransientProgress,
358
359 pub(crate) reverse_search_state: reverse_search::ReverseSearchState,
361
362 pub(crate) active_pty_sessions: Option<Arc<std::sync::atomic::AtomicUsize>>,
364
365 pub(crate) background_activity_count: usize,
371 pub(crate) background_finished_count: usize,
373 pub(crate) background_indicator_hits: Vec<Rect>,
376
377 bindings: BindingStore,
379
380 clipboard: String,
382 vim_state: VimState,
383
384 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 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 input_render_cache: Option<(u16, u16, u64, usize, bool, bool, input::InputRender)>,
399
400 app_name: String,
403 workspace_root: Option<std::path::PathBuf>,
405 terminal_title_items: Option<Vec<String>>,
407 terminal_title_thread_label: Option<String>,
409 terminal_title_git_branch: Option<String>,
411 terminal_title_task_progress: Option<String>,
413 last_terminal_title: Option<String>,
415
416 is_streaming_final_answer: bool,
421}
422
423#[derive(Debug, Default, Clone)]
430pub(crate) struct ThinkingRunIndex {
431 collapsed: std::collections::HashMap<usize, bool>,
434 active_start: Option<usize>,
438}
439
440impl ThinkingRunIndex {
441 fn is_collapsed(&self, start: usize, default: bool) -> bool {
444 self.collapsed.get(&start).copied().unwrap_or(default)
445 }
446
447 fn set_collapsed(&mut self, start: usize, collapsed: bool) {
449 self.collapsed.insert(start, collapsed);
450 }
451
452 fn begin_run(&mut self, start: usize) {
454 self.active_start = Some(start);
455 }
456
457 fn end_run(&mut self) {
459 self.active_start = None;
460 }
461
462 fn active_start(&self) -> Option<usize> {
464 self.active_start
465 }
466
467 fn clear(&mut self) {
469 self.collapsed.clear();
470 self.active_start = None;
471 }
472}