Skip to main content

vtcode_ui/tui/core_tui/session/
impl_input.rs

1use super::*;
2#[cfg_attr(not(vendored_crossterm), allow(unused_imports))]
3use vtcode_commons::ansi_capabilities::ColorScheme;
4
5impl Session {
6    pub(crate) fn cursor(&self) -> usize {
7        self.input_manager.cursor()
8    }
9
10    pub(crate) fn set_input(&mut self, text: impl Into<String>) {
11        self.input_manager.set_content(text.into());
12        self.input_compact_mode = self.input_compact_placeholder().is_some();
13        self.mark_dirty();
14    }
15
16    pub(crate) fn set_cursor(&mut self, pos: usize) {
17        self.input_manager.set_cursor(pos);
18        self.mark_dirty();
19    }
20
21    #[cfg_attr(feature = "profiling", hotpath::measure)]
22    pub(crate) fn process_key(&mut self, key: KeyEvent) -> Option<InlineEvent> {
23        events::process_key(self, key)
24    }
25
26    pub fn handle_command(&mut self, command: InlineCommand) {
27        let mut command_needs_redraw = true;
28
29        // Track streaming state: set when agent starts responding
30        if matches!(
31            &command,
32            InlineCommand::AppendLine { kind: InlineMessageKind::Agent, segments }
33                if !segments.is_empty()
34        ) || matches!(
35            &command,
36            InlineCommand::AppendLines { lines }
37                if lines
38                    .iter()
39                    .any(|line| line.kind == InlineMessageKind::Agent && !line.segments.is_empty())
40        ) || matches!(
41            &command,
42            InlineCommand::AppendPastedMessage { kind: InlineMessageKind::Agent, text, .. }
43                if !text.is_empty()
44        ) || matches!(
45            &command,
46            InlineCommand::Inline { kind: InlineMessageKind::Agent, segment }
47                if !segment.text.is_empty()
48        ) {
49            self.is_streaming_final_answer = true;
50        }
51
52        // Clear streaming state on turn completion (status cleared)
53        if let InlineCommand::SetInputStatus { left, right } | InlineCommand::SetConfiguredInputStatus { left, right } =
54            &command
55            && self.is_streaming_final_answer
56            && left.is_none()
57            && right.is_none()
58        {
59            self.is_streaming_final_answer = false;
60        }
61
62        match command {
63            InlineCommand::Diagnostic(diagnostic) => self.upsert_diagnostic(*diagnostic),
64            InlineCommand::AppendLine { kind, segments } => {
65                let previous_max_offset = self.current_max_scroll_offset();
66                self.clear_thinking_spinner_if_active(kind);
67                self.push_line(kind, segments);
68                self.adjust_scroll_after_change(previous_max_offset);
69                self.request_transcript_clear();
70            }
71            InlineCommand::AppendLines { lines } => {
72                let previous_max_offset = self.current_max_scroll_offset();
73                for line in lines {
74                    self.clear_thinking_spinner_if_active(line.kind);
75                    self.push_line(line.kind, line.segments);
76                }
77                self.adjust_scroll_after_change(previous_max_offset);
78                self.request_transcript_clear();
79            }
80            InlineCommand::AppendPastedMessage { kind, text, line_count } => {
81                let previous_max_offset = self.current_max_scroll_offset();
82                self.clear_thinking_spinner_if_active(kind);
83                self.append_pasted_message(kind, text, line_count);
84                self.adjust_scroll_after_change(previous_max_offset);
85                self.request_transcript_clear();
86            }
87            InlineCommand::Inline { kind, segment } => {
88                self.clear_thinking_spinner_if_active(kind);
89                self.append_inline(kind, segment);
90                self.request_transcript_clear();
91            }
92            InlineCommand::ReplaceLast { count, kind, lines, link_ranges } => {
93                self.clear_thinking_spinner_if_active(kind);
94                self.replace_last(count, kind, lines, link_ranges);
95                self.request_transcript_clear();
96            }
97            InlineCommand::SetPrompt { prefix, style } => {
98                self.prompt_prefix = prefix;
99                self.prompt_style = style;
100                self.ensure_prompt_style_color();
101                self.input_render_cache = None;
102            }
103            InlineCommand::SetPlaceholder { hint, style } => {
104                self.placeholder = hint;
105                self.placeholder_style = style;
106                self.input_render_cache = None;
107            }
108            InlineCommand::SetMessageLabels { agent, user } => {
109                self.labels.agent = agent.filter(|label| !label.is_empty());
110                self.labels.user = user.filter(|label| !label.is_empty());
111                self.invalidate_transcript_cache();
112                self.invalidate_scroll_metrics();
113            }
114            InlineCommand::SetHeaderContext { context } => {
115                let mut next_context = *context;
116                next_context.reasoning_stage = self.header_context.reasoning_stage.clone();
117                next_context.primary_agent = self.header_context.primary_agent.clone();
118                next_context.primary_agent_color = self.header_context.primary_agent_color.clone();
119                self.header_context = next_context;
120                self.invalidate_header_cache();
121            }
122            InlineCommand::SetInputStatus { left, right } => {
123                self.apply_input_status(left, right);
124            }
125            InlineCommand::SetConfiguredInputStatus { left, right } => {
126                self.footer_context_configured = true;
127                self.footer_context_right = right.clone();
128                self.footer_context_status = left
129                    .as_deref()
130                    .map(str::trim)
131                    .filter(|value| !value.is_empty())
132                    .map(str::to_owned);
133                self.apply_input_status(left, right);
134            }
135            InlineCommand::ProgramStatus(update) => {
136                self.program_status.apply(update);
137                if matches!(update, vtcode_commons::program_status::ProgramStatusUpdate::Configure { enabled: true }) {
138                    self.program_status.children(&self.local_agents);
139                }
140                command_needs_redraw = false;
141            }
142            InlineCommand::UpdateProgress(update) => {
143                self.program_status.progress(update);
144                if self.progress.apply(update) {
145                    self.request_transcript_clear();
146                } else {
147                    command_needs_redraw = false;
148                }
149            }
150            InlineCommand::SetActivityState(state) => {
151                self.program_status.activity(state);
152                self.activity_state = state;
153                self.input_status_left = state.status().map(ToOwned::to_owned);
154                let enabled = !state.is_busy();
155                self.set_input_enabled(enabled);
156                if let Some(ActiveOverlay::Modal(overlay)) = self.active_overlay.as_mut() {
157                    overlay.restore_cursor = enabled;
158                }
159                self.cursor_visible = enabled && !self.has_active_overlay();
160                // ActivityState contributes the cached header badge as well as
161                // the uncached footer/status presentation.
162                self.invalidate_header_cache();
163            }
164            InlineCommand::SetTerminalTitleItems { items } => {
165                if self.terminal_title_items != items {
166                    self.terminal_title_items = items;
167                    self.mark_visual_dirty();
168                } else {
169                    command_needs_redraw = false;
170                }
171            }
172            InlineCommand::SetTerminalTitleThreadLabel { label } => {
173                let label = label.filter(|value| !value.trim().is_empty());
174                if self.terminal_title_thread_label != label {
175                    self.terminal_title_thread_label = label;
176                    self.mark_visual_dirty();
177                } else {
178                    command_needs_redraw = false;
179                }
180            }
181            InlineCommand::SetTerminalTitleGitBranch { branch } => {
182                let branch = branch.filter(|value| !value.trim().is_empty());
183                if self.terminal_title_git_branch != branch {
184                    self.terminal_title_git_branch = branch;
185                    self.mark_visual_dirty();
186                } else {
187                    command_needs_redraw = false;
188                }
189            }
190            InlineCommand::SetTheme { theme } => {
191                let previous_theme = self.theme.clone();
192                self.theme = theme.clone();
193                self.styles.set_theme(theme);
194                self.retint_lines_for_theme_change(&previous_theme);
195                self.ensure_prompt_style_color();
196                self.invalidate_header_cache();
197                self.invalidate_transcript_cache();
198            }
199            InlineCommand::SetColorSchemeAuto { enabled } => {
200                self.auto_color_scheme = enabled;
201                command_needs_redraw = false;
202            }
203            InlineCommand::SetAppearance { appearance } => {
204                self.appearance = appearance;
205                self.invalidate_header_cache();
206                self.invalidate_transcript_cache();
207                self.invalidate_scroll_metrics();
208            }
209            InlineCommand::SetFullscreenInteraction { interaction } => {
210                self.fullscreen.interaction = interaction;
211                self.mark_visual_dirty();
212            }
213            InlineCommand::SetVimModeEnabled(enabled) => {
214                self.vim_state.set_enabled(enabled);
215                self.mark_visual_dirty();
216            }
217            InlineCommand::SetQueuedInputs { entries } => {
218                self.set_queued_inputs_entries(entries);
219                self.mark_visual_dirty();
220            }
221            InlineCommand::SetSubprocessEntries { entries } => {
222                self.subprocess_entries = entries;
223                self.invalidate_sidebar_cache();
224            }
225            InlineCommand::SetSubagentPreview { text } => {
226                self.subagent_preview = text.filter(|value| !value.trim().is_empty());
227                self.invalidate_sidebar_cache();
228            }
229            InlineCommand::SetPrimaryAgent { name, color } => {
230                self.header_context.primary_agent = name.filter(|value| !value.trim().is_empty());
231                self.header_context.primary_agent_color = color.filter(|value| !value.trim().is_empty());
232                self.invalidate_header_cache();
233            }
234            InlineCommand::SetCursorVisible(value) => {
235                self.cursor_visible = value;
236            }
237            InlineCommand::SetInputEnabled(value) => {
238                self.set_input_enabled(value);
239            }
240            InlineCommand::SetImageInputEnabled(value) => {
241                self.image_input_enabled = value;
242            }
243            InlineCommand::SetInput(content) => {
244                // Check if the content appears to be an error message
245                // If it looks like an error, redirect to transcript instead
246                if Self::is_error_content(&content) {
247                    // Add error to transcript instead of input field
248                    crate::tui::utils::transcript::display_error(&content);
249                } else {
250                    self.clear_suggested_prompt_state();
251                    self.clear_inline_prompt_suggestion();
252                    self.input_manager.set_content(content);
253                    self.input_compact_mode = self.input_compact_placeholder().is_some();
254                    self.scroll_manager.set_offset(0);
255                    self.sync_follow_state();
256                }
257            }
258            InlineCommand::RestoreInputDraft(input) => {
259                self.clear_suggested_prompt_state();
260                self.clear_inline_prompt_suggestion();
261                self.input_manager.set_content(input.text);
262                self.input_manager.set_attachments(input.attachments);
263                self.input_compact_mode = self.input_compact_placeholder().is_some();
264                self.scroll_manager.set_offset(0);
265                self.sync_follow_state();
266            }
267            InlineCommand::ApplySuggestedPrompt(content) => {
268                self.apply_suggested_prompt(content);
269                self.scroll_manager.set_offset(0);
270                self.sync_follow_state();
271            }
272            InlineCommand::SetInlinePromptSuggestion { suggestion, llm_generated } => {
273                self.set_inline_prompt_suggestion(suggestion, llm_generated);
274            }
275            InlineCommand::ClearInlinePromptSuggestion => {
276                self.clear_inline_prompt_suggestion();
277            }
278            InlineCommand::ClearInput => {
279                command::clear_input(self);
280            }
281            InlineCommand::ForceRedraw => {
282                self.mark_dirty();
283            }
284            InlineCommand::ShowOverlay { request } => {
285                self.clear_inline_prompt_suggestion();
286                self.show_overlay(*request);
287            }
288            InlineCommand::CloseOverlay => {
289                self.close_overlay();
290            }
291            InlineCommand::ClearScreen => {
292                self.clear_screen();
293            }
294            InlineCommand::SuspendEventLoop
295            | InlineCommand::ResumeEventLoop
296            | InlineCommand::ClearInputQueue
297            | InlineCommand::StopEventStream
298            | InlineCommand::StartEventStream => {
299                // Handled by drive_terminal
300            }
301            InlineCommand::SetSkipConfirmations(skip) => {
302                if skip {
303                    // Permission bypass is handled by the runtime. Close only
304                    // an approval overlay that was already open; user-started
305                    // selection modals must remain interactive after this.
306                    self.close_overlay();
307                }
308            }
309            InlineCommand::Shutdown => {
310                self.request_exit();
311            }
312            InlineCommand::SetReasoningStage(stage) => {
313                self.header_context.reasoning_stage = stage;
314                self.invalidate_header_cache();
315            }
316        }
317        if command_needs_redraw {
318            self.mark_visual_dirty();
319        }
320    }
321
322    fn apply_input_status(&mut self, left: Option<String>, right: Option<String>) {
323        self.input_status_left = left;
324        self.input_status_right = right;
325        if self.thinking_spinner.is_active {
326            self.thinking_spinner.stop();
327        }
328        // The blocked/recovery badge can be derived from either status field.
329        self.invalidate_header_cache();
330    }
331
332    /// Apply an unsolicited terminal color-scheme report (Contour VT extension,
333    /// `CSI ? 997 ; Ps n`). No-op unless automatic color-scheme following is
334    /// enabled via `SetColorSchemeAuto`, which the host wires from
335    /// `ui.color_scheme_mode = "auto"`.
336    ///
337    /// The shared scheme override is updated first so theme matching and
338    /// suggestions agree with the reported scheme; the switch itself goes
339    /// through the regular `SetTheme` path so retinting and caches stay
340    /// consistent. The user's persisted theme preference is never touched.
341    #[cfg_attr(not(vendored_crossterm), allow(dead_code))]
342    pub(crate) fn apply_terminal_color_scheme_report(&mut self, dark: bool) {
343        if !self.auto_color_scheme {
344            return;
345        }
346        let scheme = if dark { ColorScheme::Dark } else { ColorScheme::Light };
347        vtcode_commons::ansi_capabilities::set_color_scheme_override(Some(scheme));
348        let active = crate::theme::active_theme_id();
349        if crate::theme::theme_matches_terminal_scheme(&active) {
350            return;
351        }
352        let next = crate::theme::theme_for_terminal_scheme_change(&active, dark);
353        if crate::theme::set_active_theme(next).is_err() {
354            return;
355        }
356        let theme = crate::tui::core_tui::style::theme_from_styles(&crate::theme::active_styles());
357        self.handle_command(InlineCommand::SetTheme { theme });
358    }
359}