1pub use vtcode_commons::ui_protocol::{
12 BusyEnterBehavior, 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#[cfg(feature = "tui")]
25pub use vtcode_ui::tui::app::*;
26
27#[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 #[derive(Clone, Debug, PartialEq, Eq)]
48 pub enum InlineEvent {
49 Submit(SubmittedInput),
50 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 #[derive(Clone, Debug)]
78 pub enum InlineCommand {
79 Diagnostic(Box<vtcode_commons::diagnostics::Diagnostic>),
80 AppendLine {
81 kind: InlineMessageKind,
82 segments: Vec<InlineSegment>,
83 },
84 AppendPastedMessage {
85 kind: InlineMessageKind,
86 text: String,
87 line_count: usize,
88 },
89 Inline {
90 kind: InlineMessageKind,
91 segment: InlineSegment,
92 },
93 ReplaceLast {
94 count: usize,
95 kind: InlineMessageKind,
96 lines: Vec<Vec<InlineSegment>>,
97 },
98 AppendLines {
99 lines: Vec<InlineTranscriptLine>,
100 },
101 RecordToolOutput {
102 id: ToolOutputId,
103 lines: Vec<String>,
104 },
105 AppendToolOutputLine {
106 id: ToolOutputId,
107 kind: InlineMessageKind,
108 segments: Vec<InlineSegment>,
109 },
110 AppendCompactActivity(CompactActivityMetadata),
111 RecordDiffReview(vtcode_commons::ui_protocol::DiffReviewAnchor),
112 ReplaceCompactActivity(CompactActivityMetadata),
113 CollapsePtyBlock(CompactActivityMetadata),
114 SetKeyBindings {
115 bindings: HashMap<String, Vec<String>>,
116 },
117 SetImageInputEnabled(bool),
118 RestoreInputDraft(SubmittedInput),
119 ForceRedraw,
120 Shutdown,
121 ClearScreen,
122 CloseModal,
123 SetReasoningStage(Option<String>),
124 }
125
126 #[derive(Clone, Debug)]
128 pub struct InlineHandle {
129 diagnostic_observer: vtcode_commons::diagnostics::DiagnosticObserver,
130 sender: Option<UnboundedSender<InlineCommand>>,
131 deferred_events: Arc<Mutex<VecDeque<InlineEvent>>>,
132 next_tool_output_id: Arc<AtomicU64>,
133 }
134
135 const MAX_DEFERRED_EVENTS: usize = 32;
136
137 impl InlineHandle {
138 pub fn new_for_tests(sender: UnboundedSender<InlineCommand>) -> Self {
139 Self {
140 diagnostic_observer: Default::default(),
141 sender: Some(sender),
142 deferred_events: Arc::new(Mutex::new(VecDeque::new())),
143 next_tool_output_id: Arc::new(AtomicU64::new(0)),
144 }
145 }
146
147 pub fn defer_event(&self, event: InlineEvent) -> anyhow::Result<()> {
148 let mut deferred_events = self
149 .deferred_events
150 .lock()
151 .map_err(|error| anyhow::anyhow!("deferred input queue poisoned: {error}"))?;
152 if deferred_events.len() >= MAX_DEFERRED_EVENTS {
153 return Err(anyhow::anyhow!("deferred input queue is full"));
154 }
155 deferred_events.push_back(event);
156 Ok(())
157 }
158
159 fn take_deferred_event(&self) -> Option<InlineEvent> {
160 self.deferred_events.lock().ok()?.pop_front()
161 }
162
163 pub fn has_deferred_event(&self) -> bool {
164 self.deferred_events.lock().is_ok_and(|events| !events.is_empty())
165 }
166
167 fn send_command(&self, command: InlineCommand) {
168 if let Some(sender) = &self.sender {
169 let _ = sender.send(command);
170 }
171 }
172
173 pub fn set_diagnostic_sink(&self, sink: vtcode_commons::diagnostics::DiagnosticSink) -> anyhow::Result<()> {
174 self.diagnostic_observer.set_sink(sink)
175 }
176 pub fn diagnostic(&self, diagnostic: vtcode_commons::diagnostics::Diagnostic) {
177 self.present_diagnostic(self.diagnostic_observer.prepare(&diagnostic));
178 }
179 pub fn present_diagnostic(&self, diagnostic: vtcode_commons::diagnostics::Diagnostic) {
180 if self.sender.is_none() {
181 vtcode_commons::diagnostics::stderr_diagnostic(&diagnostic);
182 return;
183 }
184 self.send_command(InlineCommand::Diagnostic(Box::new(vtcode_commons::diagnostics::redact_diagnostic(
185 &diagnostic,
186 ))));
187 }
188
189 #[track_caller]
190 fn try_append_diagnostic(&self, kind: InlineMessageKind, text: &str) -> bool {
191 let severity = match kind {
192 InlineMessageKind::Error => vtcode_commons::diagnostics::DiagnosticSeverity::Error,
193 InlineMessageKind::Warning => vtcode_commons::diagnostics::DiagnosticSeverity::Warning,
194 _ => return false,
195 };
196 if !text.trim().is_empty() {
197 self.diagnostic(vtcode_commons::diagnostics::legacy_ui_diagnostic(severity, text));
198 }
199 true
200 }
201
202 #[track_caller]
203 pub fn append_line(&self, kind: InlineMessageKind, segments: Vec<InlineSegment>) {
204 if matches!(kind, InlineMessageKind::Error | InlineMessageKind::Warning) {
205 let text = segments.iter().map(|segment| segment.text.as_str()).collect::<String>();
206 if self.try_append_diagnostic(kind, &text) {
207 return;
208 }
209 }
210 self.send_command(InlineCommand::AppendLine { kind, segments });
211 }
212 #[track_caller]
213 pub fn append_pasted_message(&self, kind: InlineMessageKind, text: String, line_count: usize) {
214 if self.try_append_diagnostic(kind, &text) {
215 return;
216 }
217 self.send_command(InlineCommand::AppendPastedMessage { kind, text, line_count });
218 }
219 pub fn inline(&self, kind: InlineMessageKind, segment: InlineSegment) {
220 self.send_command(InlineCommand::Inline { kind, segment });
221 }
222 pub fn replace_last(&self, count: usize, kind: InlineMessageKind, lines: Vec<Vec<InlineSegment>>) {
223 self.send_command(InlineCommand::ReplaceLast { count, kind, lines });
224 }
225 #[track_caller]
226 pub fn append_lines(&self, lines: Vec<InlineTranscriptLine>) {
227 if lines.is_empty() {
228 self.send_command(InlineCommand::AppendLines { lines });
229 return;
230 }
231 let mut pending = Vec::new();
232 for line in lines {
233 if matches!(line.kind, InlineMessageKind::Error | InlineMessageKind::Warning) {
234 if !pending.is_empty() {
235 self.send_command(InlineCommand::AppendLines { lines: std::mem::take(&mut pending) });
236 }
237 let text = line.segments.iter().map(|segment| segment.text.as_str()).collect::<String>();
238 self.try_append_diagnostic(line.kind, &text);
239 } else {
240 pending.push(line);
241 }
242 }
243 if !pending.is_empty() {
244 self.send_command(InlineCommand::AppendLines { lines: pending });
245 }
246 }
247 pub fn record_tool_output(&self, lines: Vec<String>) -> ToolOutputId {
248 let id = self.next_tool_output_id.fetch_add(1, Ordering::Relaxed);
249 self.send_command(InlineCommand::RecordToolOutput { id, lines });
250 id
251 }
252 pub fn append_tool_output_line(&self, id: ToolOutputId, kind: InlineMessageKind, segments: Vec<InlineSegment>) {
253 self.send_command(InlineCommand::AppendToolOutputLine { id, kind, segments });
254 }
255 pub fn append_compact_activity(&self, activity: CompactActivityMetadata) {
256 self.send_command(InlineCommand::AppendCompactActivity(activity));
257 }
258 pub fn record_diff_review(&self, anchor: vtcode_commons::ui_protocol::DiffReviewAnchor) {
259 self.send_command(InlineCommand::RecordDiffReview(anchor));
262 }
263 pub fn replace_compact_activity(&self, activity: CompactActivityMetadata) {
264 self.send_command(InlineCommand::ReplaceCompactActivity(activity));
265 }
266 pub fn collapse_pty_block(&self, activity: CompactActivityMetadata) {
267 self.send_command(InlineCommand::CollapsePtyBlock(activity));
268 }
269 pub fn set_key_bindings(&self, bindings: HashMap<String, Vec<String>>) {
270 self.send_command(InlineCommand::SetKeyBindings { bindings });
271 }
272 pub fn force_redraw(&self) {
273 self.send_command(InlineCommand::ForceRedraw);
274 }
275 pub fn shutdown(&self) {
276 self.send_command(InlineCommand::Shutdown);
277 }
278 pub fn clear_screen(&self) {
279 self.send_command(InlineCommand::ClearScreen);
280 }
281 pub fn show_modal(&self, _title: String, _lines: Vec<String>, _secure_prompt: Option<SecurePromptConfig>) {}
282 pub fn show_list_modal(
283 &self,
284 _title: String,
285 _lines: Vec<String>,
286 _items: Vec<InlineListItem>,
287 _selected: Option<InlineListSelection>,
288 _search: Option<InlineListSearchConfig>,
289 ) {
290 }
291 pub fn show_list_modal_with_footer(
292 &self,
293 _title: String,
294 _lines: Vec<String>,
295 _items: Vec<InlineListItem>,
296 _selected: Option<InlineListSelection>,
297 _search: Option<InlineListSearchConfig>,
298 _footer_hint: Option<String>,
299 ) {
300 }
301 pub fn show_list_modal_with_status(
302 &self,
303 _title: String,
304 _lines: Vec<String>,
305 _items: Vec<InlineListItem>,
306 _selected: Option<InlineListSelection>,
307 _search: Option<InlineListSearchConfig>,
308 _footer_hint: Option<String>,
309 _status: Option<vtcode_commons::ui_protocol::InlineStatus>,
310 ) {
311 }
312 pub fn close_modal(&self) {
313 self.send_command(InlineCommand::CloseModal);
314 }
315 pub fn restore_input_draft(&self, input: SubmittedInput) {
316 self.send_command(InlineCommand::RestoreInputDraft(input));
317 }
318 pub fn set_image_input_enabled(&self, enabled: bool) {
319 self.send_command(InlineCommand::SetImageInputEnabled(enabled));
320 }
321 pub fn set_reasoning_stage(&self, stage: Option<String>) {
322 self.send_command(InlineCommand::SetReasoningStage(stage));
323 }
324 }
325
326 pub struct InlineSession {
328 pub handle: InlineHandle,
329 pub events: UnboundedReceiver<InlineEvent>,
330 }
331
332 impl InlineSession {
333 pub async fn next_event(&mut self) -> Option<InlineEvent> {
334 if let Some(event) = self.handle.take_deferred_event() {
335 return Some(event);
336 }
337 self.events.recv().await
338 }
339
340 pub async fn wait_for_exit(&mut self, _timeout: std::time::Duration) -> bool {
343 true
344 }
345
346 pub fn clone_inline_handle(&self) -> InlineHandle {
347 self.handle.clone()
348 }
349 }
350
351 #[derive(Debug, Clone, Default)]
353 pub struct SessionAppearanceConfig {
354 pub theme: String,
355 pub ui_mode: super::UiMode,
356 pub show_sidebar: bool,
357 pub min_content_width: u16,
358 pub min_navigation_width: u16,
359 pub navigation_width_percent: u8,
360 pub transcript_bottom_padding: u16,
366 pub dim_completed_todos: bool,
367 pub message_block_spacing: u8,
368 pub layout_mode: super::LayoutModeOverride,
369 pub reasoning_display_mode: super::ReasoningDisplayMode,
370 pub reasoning_visible_default: bool,
371 pub thinking_display: super::ThinkingBlockState,
372 pub vim_mode: bool,
373 pub busy_enter_behavior: super::BusyEnterBehavior,
374 pub screen_reader_mode: bool,
375 pub reduce_motion_mode: bool,
376 pub reduce_motion_keep_progress_animation: bool,
377 pub show_transcript_review_hints: bool,
378 pub show_transcript_review_shortcut_guide: bool,
379 pub show_transcript_review_close_button: bool,
380 pub diff_preview_mode: vtcode_commons::ui_protocol::DiffPreviewMode,
381 pub syntax_highlighting: vtcode_config::loader::SyntaxHighlightingConfig,
383 pub customization: (),
384 }
385
386 pub fn theme_from_styles(styles: &ThemeStyles) -> super::InlineTheme {
388 super::theme_from_color_fields(
389 styles.foreground,
390 styles.background,
391 styles.primary,
392 styles.secondary,
393 styles.tool,
394 styles.tool_detail,
395 styles.pty_output,
396 styles.error,
397 styles.warning,
398 )
399 }
400}
401
402#[cfg(not(feature = "tui"))]
403pub use headless::*;