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