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 render_state: RenderState,
270 pub(crate) transcript_clear_required: bool,
272 pub(crate) evicted_message_count: usize,
274 pub(crate) pending_new_messages: usize,
277 pub(crate) last_change_line_idx: Option<usize>,
280 pub(crate) transcript_flash: Option<TranscriptFlash>,
282 should_exit: bool,
283 pub(crate) last_interrupt_press: Option<Instant>,
285 pub(crate) last_escape_press: Option<Instant>,
293 scroll_cursor_steady_until: Option<Instant>,
294 last_shimmer_active: bool,
295 view_rows: u16,
296 pub(crate) input_height: u16,
297 pub(crate) transcript_rows: u16,
298 pub(crate) transcript_width: u16,
299 pub(crate) transcript_view_top: usize,
300 areas: SessionAreas,
301 sticky_prompt_target: Option<sticky_prompt::StickyPromptTarget>,
302 sticky_prompt_preview_cache: Option<sticky_prompt::StickyPromptPreviewCache>,
303 leading_user_prompt_truncated: bool,
304 transcript_file_link_targets: Vec<TranscriptFileLinkTarget>,
305 modal_link_targets: Vec<TranscriptFileLinkTarget>,
306 hovered_transcript_file_link: Option<usize>,
307 last_mouse_position: Option<(u16, u16)>,
308 last_link_open: Option<(String, Instant)>,
309 pending_link_open: Option<String>,
310 held_key_modifiers: KeyModifiers,
311
312 log_receiver: Option<UnboundedReceiver<LogEntry>>,
314 log_lines: VecDeque<Arc<Text<'static>>>,
315 log_cached_text: Option<Arc<Text<'static>>>,
316 log_evicted: bool,
317 pub(crate) show_logs: bool,
318
319 transcript_cache: Option<TranscriptReflowCache>,
321 visible_lines_cache: Option<(usize, u16, usize, Arc<Vec<TranscriptLine>>)>,
324 pub(crate) queued_inputs: Vec<String>,
325 pub(crate) local_agents: Vec<LocalAgentEntry>,
326 pub(crate) active_plan: Option<ActivePlanEntry>,
327 local_agents_drawer_visible: bool,
328 subprocess_entries: Vec<String>,
329 subagent_preview: Option<String>,
330 queue_overlay_cache: Option<QueueOverlay>,
331 queue_overlay_version: u64,
332 active_overlay: Option<ActiveOverlay>,
333 overlay_queue: VecDeque<OverlayRequest>,
334 last_overlay_list_selection: Option<InlineListSelection>,
335 last_overlay_list_was_last: bool,
336 line_revision_counter: u64,
337 pub(crate) transcript_presentation_revision: u64,
338 first_dirty_line: Option<usize>,
340 in_tool_code_fence: bool,
341
342 suggested_prompt_state: SuggestedPromptState,
344 inline_prompt_suggestion: InlinePromptSuggestionState,
345
346 pub(crate) thinking_spinner: ThinkingSpinner,
348 pub(crate) shimmer_state: ShimmerState,
349 pub(crate) progress: progress::TransientProgress,
350
351 pub(crate) reverse_search_state: reverse_search::ReverseSearchState,
353
354 pub(crate) active_pty_sessions: Option<Arc<std::sync::atomic::AtomicUsize>>,
356
357 pub(crate) background_activity_count: usize,
363 pub(crate) background_finished_count: usize,
365 pub(crate) background_indicator_hits: Vec<Rect>,
368
369 bindings: BindingStore,
371
372 clipboard: String,
374 vim_state: VimState,
375
376 pub(crate) mouse_selection: MouseSelectionState,
378 pub(crate) mouse_drag_target: MouseDragTarget,
379 pub(crate) drag_auto_scroll: Option<DragAutoScroll>,
380 pub(crate) fullscreen: FullscreenSessionState,
381
382 header_lines_cache: Option<Arc<Vec<Line<'static>>>>,
384 header_block_title_cache: Option<Line<'static>>,
385 header_height_cache: hashbrown::HashMap<u16, u16>,
386 pub(crate) queued_inputs_preview_cache: Option<Vec<String>>,
387 subprocess_entries_preview_cache: Option<Vec<String>>,
388 input_render_cache: Option<(u16, u16, u64, usize, bool, bool, input::InputRender)>,
391
392 app_name: String,
395 workspace_root: Option<std::path::PathBuf>,
397 terminal_title_items: Option<Vec<String>>,
399 terminal_title_thread_label: Option<String>,
401 terminal_title_git_branch: Option<String>,
403 terminal_title_task_progress: Option<String>,
405 last_terminal_title: Option<String>,
407
408 is_streaming_final_answer: bool,
413}
414
415#[derive(Debug, Default, Clone)]
422pub(crate) struct ThinkingRunIndex {
423 collapsed: std::collections::HashMap<usize, bool>,
426 active_start: Option<usize>,
430}
431
432impl ThinkingRunIndex {
433 fn is_collapsed(&self, start: usize, default: bool) -> bool {
436 self.collapsed.get(&start).copied().unwrap_or(default)
437 }
438
439 fn set_collapsed(&mut self, start: usize, collapsed: bool) {
441 self.collapsed.insert(start, collapsed);
442 }
443
444 fn begin_run(&mut self, start: usize) {
446 self.active_start = Some(start);
447 }
448
449 fn end_run(&mut self) {
451 self.active_start = None;
452 }
453
454 fn active_start(&self) -> Option<usize> {
456 self.active_start
457 }
458
459 fn clear(&mut self) {
461 self.collapsed.clear();
462 self.active_start = None;
463 }
464}