Skip to main content

vtcode_core/ui/
tui.rs

1//! TUI protocol types and session interface.
2//!
3//! When the `tui` feature is enabled, this module re-exports the full app-layer
4//! protocol from `vtcode-ui`.  When the feature is disabled (headless build),
5//! it re-exports the shared data types from `vtcode-commons` and provides
6//! lightweight no-op stubs for `InlineHandle`, `InlineSession`, and
7//! `InlineEvent`.
8
9// ── Shared data types (always available from vtcode-commons) ────────────────
10
11pub use vtcode_commons::ui_protocol::{
12    CompactActivityMetadata, InlineHeaderContext, InlineHeaderHighlight, InlineHeaderStatusBadge,
13    InlineHeaderStatusTone, InlineLinkRange, InlineLinkTarget, InlineListItem, InlineListSearchConfig,
14    InlineListSelection, InlineMessageKind, InlineSegment, InlineTextStyle, InlineTheme, InlineTranscriptLine,
15    LayoutModeOverride, PlanContent, PlanPhase, PlanStep, ReasoningDisplayMode, RewindAction, SecurePromptConfig,
16    SessionSurface, SlashCommandItem, ThinkingBlockState, ToolOutputId, UiMode, WizardModalMode, WizardStep,
17    convert_style, theme_from_color_fields,
18};
19
20pub use vtcode_commons::ui_protocol::KeyboardProtocolSettings;
21
22// ── Full TUI re-exports (feature = "tui") ───────────────────────────────────
23
24#[cfg(feature = "tui")]
25pub use vtcode_ui::tui::app::*;
26
27// ── Headless stubs (feature = "tui" disabled) ───────────────────────────────
28
29#[cfg(not(feature = "tui"))]
30mod headless {
31    use std::collections::VecDeque;
32    use std::sync::atomic::{AtomicU64, Ordering};
33    use std::sync::{Arc, Mutex};
34
35    use hashbrown::HashMap;
36    use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};
37
38    use super::{
39        CompactActivityMetadata, InlineListItem, InlineListSearchConfig, InlineListSelection, InlineMessageKind,
40        InlineSegment, InlineTranscriptLine, SecurePromptConfig, ToolOutputId,
41    };
42
43    use crate::ui::theme::ThemeStyles;
44    pub use vtcode_ui::tui::app::{ContentPart, SubmittedInput};
45
46    /// Headless `InlineEvent` — all variants present so match arms compile.
47    #[derive(Clone, Debug, PartialEq, Eq)]
48    pub enum InlineEvent {
49        Submit(SubmittedInput),
50        /// Submit text from the WebMCP bridge without interpreting slash commands.
51        WebmcpSubmit(SubmittedInput),
52        QueueSubmit(SubmittedInput),
53        Steer(SubmittedInput),
54        ProcessLatestQueued,
55        EditQueue,
56        Cancel,
57        Exit,
58        Interrupt,
59        Pause,
60        Resume,
61        BackgroundOperation,
62        ScrollLineUp,
63        ScrollLineDown,
64        ScrollPageUp,
65        ScrollPageDown,
66        JumpToLastChange,
67        OpenFileInEditor(String),
68        OpenUrl(String),
69        LaunchEditor,
70        ForceCancelPtySession,
71        RequestInlinePromptSuggestion(String),
72        HistoryPrevious,
73        HistoryNext,
74    }
75
76    /// Minimal command surface used by tests and headless sinks.
77    #[derive(Clone, Debug)]
78    pub enum InlineCommand {
79        AppendLine {
80            kind: InlineMessageKind,
81            segments: Vec<InlineSegment>,
82        },
83        AppendPastedMessage {
84            kind: InlineMessageKind,
85            text: String,
86            line_count: usize,
87        },
88        Inline {
89            kind: InlineMessageKind,
90            segment: InlineSegment,
91        },
92        ReplaceLast {
93            count: usize,
94            kind: InlineMessageKind,
95            lines: Vec<Vec<InlineSegment>>,
96        },
97        AppendLines {
98            lines: Vec<InlineTranscriptLine>,
99        },
100        RecordToolOutput {
101            id: ToolOutputId,
102            lines: Vec<String>,
103        },
104        AppendToolOutputLine {
105            id: ToolOutputId,
106            kind: InlineMessageKind,
107            segments: Vec<InlineSegment>,
108        },
109        AppendCompactActivity(CompactActivityMetadata),
110        RecordDiffReview(vtcode_commons::ui_protocol::DiffReviewAnchor),
111        ReplaceCompactActivity(CompactActivityMetadata),
112        CollapsePtyBlock(CompactActivityMetadata),
113        SetKeyBindings {
114            bindings: HashMap<String, Vec<String>>,
115        },
116        SetImageInputEnabled(bool),
117        RestoreInputDraft(SubmittedInput),
118        ForceRedraw,
119        Shutdown,
120        ClearScreen,
121        CloseModal,
122        SetReasoningStage(Option<String>),
123    }
124
125    /// Headless handle; commands go to an optional test sink and otherwise discard.
126    #[derive(Clone, Debug)]
127    pub struct InlineHandle {
128        sender: Option<UnboundedSender<InlineCommand>>,
129        deferred_events: Arc<Mutex<VecDeque<InlineEvent>>>,
130        next_tool_output_id: Arc<AtomicU64>,
131    }
132
133    const MAX_DEFERRED_EVENTS: usize = 32;
134
135    impl InlineHandle {
136        pub fn new_for_tests(sender: UnboundedSender<InlineCommand>) -> Self {
137            Self {
138                sender: Some(sender),
139                deferred_events: Arc::new(Mutex::new(VecDeque::new())),
140                next_tool_output_id: Arc::new(AtomicU64::new(0)),
141            }
142        }
143
144        pub fn defer_event(&self, event: InlineEvent) -> anyhow::Result<()> {
145            let mut deferred_events = self
146                .deferred_events
147                .lock()
148                .map_err(|error| anyhow::anyhow!("deferred input queue poisoned: {error}"))?;
149            if deferred_events.len() >= MAX_DEFERRED_EVENTS {
150                return Err(anyhow::anyhow!("deferred input queue is full"));
151            }
152            deferred_events.push_back(event);
153            Ok(())
154        }
155
156        fn take_deferred_event(&self) -> Option<InlineEvent> {
157            self.deferred_events.lock().ok()?.pop_front()
158        }
159
160        pub fn has_deferred_event(&self) -> bool {
161            self.deferred_events.lock().is_ok_and(|events| !events.is_empty())
162        }
163
164        fn send_command(&self, command: InlineCommand) {
165            if let Some(sender) = &self.sender {
166                let _ = sender.send(command);
167            }
168        }
169
170        pub fn append_line(&self, kind: InlineMessageKind, segments: Vec<InlineSegment>) {
171            self.send_command(InlineCommand::AppendLine { kind, segments });
172        }
173        pub fn append_pasted_message(&self, kind: InlineMessageKind, text: String, line_count: usize) {
174            self.send_command(InlineCommand::AppendPastedMessage { kind, text, line_count });
175        }
176        pub fn inline(&self, kind: InlineMessageKind, segment: InlineSegment) {
177            self.send_command(InlineCommand::Inline { kind, segment });
178        }
179        pub fn replace_last(&self, count: usize, kind: InlineMessageKind, lines: Vec<Vec<InlineSegment>>) {
180            self.send_command(InlineCommand::ReplaceLast { count, kind, lines });
181        }
182        pub fn append_lines(&self, lines: Vec<InlineTranscriptLine>) {
183            self.send_command(InlineCommand::AppendLines { lines });
184        }
185        pub fn record_tool_output(&self, lines: Vec<String>) -> ToolOutputId {
186            let id = self.next_tool_output_id.fetch_add(1, Ordering::Relaxed);
187            self.send_command(InlineCommand::RecordToolOutput { id, lines });
188            id
189        }
190        pub fn append_tool_output_line(&self, id: ToolOutputId, kind: InlineMessageKind, segments: Vec<InlineSegment>) {
191            self.send_command(InlineCommand::AppendToolOutputLine { id, kind, segments });
192        }
193        pub fn append_compact_activity(&self, activity: CompactActivityMetadata) {
194            self.send_command(InlineCommand::AppendCompactActivity(activity));
195        }
196        pub fn record_diff_review(&self, anchor: vtcode_commons::ui_protocol::DiffReviewAnchor) {
197            // Headless sinks have no transcript expand affordance, but tests
198            // still need to observe that an anchor was recorded.
199            self.send_command(InlineCommand::RecordDiffReview(anchor));
200        }
201        pub fn replace_compact_activity(&self, activity: CompactActivityMetadata) {
202            self.send_command(InlineCommand::ReplaceCompactActivity(activity));
203        }
204        pub fn collapse_pty_block(&self, activity: CompactActivityMetadata) {
205            self.send_command(InlineCommand::CollapsePtyBlock(activity));
206        }
207        pub fn set_key_bindings(&self, bindings: HashMap<String, Vec<String>>) {
208            self.send_command(InlineCommand::SetKeyBindings { bindings });
209        }
210        pub fn force_redraw(&self) {
211            self.send_command(InlineCommand::ForceRedraw);
212        }
213        pub fn shutdown(&self) {
214            self.send_command(InlineCommand::Shutdown);
215        }
216        pub fn clear_screen(&self) {
217            self.send_command(InlineCommand::ClearScreen);
218        }
219        pub fn show_modal(&self, _title: String, _lines: Vec<String>, _secure_prompt: Option<SecurePromptConfig>) {}
220        pub fn show_list_modal(
221            &self,
222            _title: String,
223            _lines: Vec<String>,
224            _items: Vec<InlineListItem>,
225            _selected: Option<InlineListSelection>,
226            _search: Option<InlineListSearchConfig>,
227        ) {
228        }
229        pub fn show_list_modal_with_footer(
230            &self,
231            _title: String,
232            _lines: Vec<String>,
233            _items: Vec<InlineListItem>,
234            _selected: Option<InlineListSelection>,
235            _search: Option<InlineListSearchConfig>,
236            _footer_hint: Option<String>,
237        ) {
238        }
239        pub fn show_list_modal_with_status(
240            &self,
241            _title: String,
242            _lines: Vec<String>,
243            _items: Vec<InlineListItem>,
244            _selected: Option<InlineListSelection>,
245            _search: Option<InlineListSearchConfig>,
246            _footer_hint: Option<String>,
247            _status: Option<vtcode_commons::ui_protocol::InlineStatus>,
248        ) {
249        }
250        pub fn close_modal(&self) {
251            self.send_command(InlineCommand::CloseModal);
252        }
253        pub fn restore_input_draft(&self, input: SubmittedInput) {
254            self.send_command(InlineCommand::RestoreInputDraft(input));
255        }
256        pub fn set_image_input_enabled(&self, enabled: bool) {
257            self.send_command(InlineCommand::SetImageInputEnabled(enabled));
258        }
259        pub fn set_reasoning_stage(&self, stage: Option<String>) {
260            self.send_command(InlineCommand::SetReasoningStage(stage));
261        }
262    }
263
264    /// Headless session — events never arrive.
265    pub struct InlineSession {
266        pub handle: InlineHandle,
267        pub events: UnboundedReceiver<InlineEvent>,
268    }
269
270    impl InlineSession {
271        pub async fn next_event(&mut self) -> Option<InlineEvent> {
272            if let Some(event) = self.handle.take_deferred_event() {
273                return Some(event);
274            }
275            self.events.recv().await
276        }
277
278        /// Headless stub: there is no TUI task to await, so shutdown is
279        /// always considered complete immediately.
280        pub async fn wait_for_exit(&mut self, _timeout: std::time::Duration) -> bool {
281            true
282        }
283
284        pub fn clone_inline_handle(&self) -> InlineHandle {
285            self.handle.clone()
286        }
287    }
288
289    /// Headless appearance config with sensible defaults.
290    #[derive(Debug, Clone, Default)]
291    pub struct SessionAppearanceConfig {
292        pub theme: String,
293        pub ui_mode: super::UiMode,
294        pub show_sidebar: bool,
295        pub min_content_width: u16,
296        pub min_navigation_width: u16,
297        pub navigation_width_percent: u8,
298        /// Bottom padding rows under the transcript.
299        ///
300        /// Retained for config compatibility only; the live transcript reads
301        /// `vtcode_ui::tui::config::constants::ui::INLINE_TRANSCRIPT_BOTTOM_PADDING`,
302        /// so a non-zero value set here has no render effect.
303        pub transcript_bottom_padding: u16,
304        pub dim_completed_todos: bool,
305        pub message_block_spacing: u8,
306        pub layout_mode: super::LayoutModeOverride,
307        pub reasoning_display_mode: super::ReasoningDisplayMode,
308        pub reasoning_visible_default: bool,
309        pub thinking_display: super::ThinkingBlockState,
310        pub vim_mode: bool,
311        pub screen_reader_mode: bool,
312        pub reduce_motion_mode: bool,
313        pub reduce_motion_keep_progress_animation: bool,
314        pub show_transcript_review_hints: bool,
315        pub show_transcript_review_shortcut_guide: bool,
316        pub show_transcript_review_close_button: bool,
317        pub diff_preview_mode: vtcode_commons::ui_protocol::DiffPreviewMode,
318        pub customization: (),
319    }
320
321    /// Build an [`InlineTheme`](super::InlineTheme) from core theme styles.
322    pub fn theme_from_styles(styles: &ThemeStyles) -> super::InlineTheme {
323        super::theme_from_color_fields(
324            styles.foreground,
325            styles.background,
326            styles.primary,
327            styles.secondary,
328            styles.tool,
329            styles.tool_detail,
330            styles.pty_output,
331            styles.error,
332            styles.warning,
333        )
334    }
335}
336
337#[cfg(not(feature = "tui"))]
338pub use headless::*;