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, AtomicUsize, Ordering};
33 use std::sync::{Arc, Mutex};
34
35 use hashbrown::HashMap;
36 use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};
37 use unicode_width::UnicodeWidthStr;
38
39 use super::{
40 CompactActivityMetadata, InlineListItem, InlineListSearchConfig, InlineListSelection, InlineMessageKind,
41 InlineSegment, InlineTranscriptLine, SecurePromptConfig, ToolOutputId,
42 };
43
44 use crate::ui::theme::ThemeStyles;
45 pub use vtcode_commons::ui_protocol::{ContentPart, SubmittedInput};
46
47 #[derive(Clone, Debug, PartialEq, Eq)]
49 pub enum InlineEvent {
50 Submit(SubmittedInput),
51 WebmcpSubmit(SubmittedInput),
53 QueueSubmit(SubmittedInput),
54 Steer(SubmittedInput),
55 ProcessLatestQueued,
56 EditQueue,
57 Cancel,
58 Exit,
59 Interrupt,
60 Pause,
61 Resume,
62 BackgroundOperation,
63 ScrollLineUp,
64 ScrollLineDown,
65 ScrollPageUp,
66 ScrollPageDown,
67 JumpToLastChange,
68 OpenFileInEditor(String),
69 OpenUrl(String),
70 LaunchEditor,
71 ForceCancelPtySession,
72 RequestInlinePromptSuggestion(String),
73 HistoryPrevious,
74 HistoryNext,
75 }
76
77 #[derive(Clone, Debug)]
79 pub enum InlineCommand {
80 Diagnostic(Box<vtcode_commons::diagnostics::Diagnostic>),
81 AppendLine {
82 kind: InlineMessageKind,
83 segments: Vec<InlineSegment>,
84 },
85 AppendPastedMessage {
86 kind: InlineMessageKind,
87 text: String,
88 line_count: usize,
89 },
90 Inline {
91 kind: InlineMessageKind,
92 segment: InlineSegment,
93 },
94 ReplaceLast {
95 count: usize,
96 kind: InlineMessageKind,
97 lines: Vec<Vec<InlineSegment>>,
98 },
99 AppendLines {
100 lines: Vec<InlineTranscriptLine>,
101 },
102 RecordToolOutput {
103 id: ToolOutputId,
104 lines: Vec<String>,
105 },
106 AppendToolOutputLine {
107 id: ToolOutputId,
108 kind: InlineMessageKind,
109 segments: Vec<InlineSegment>,
110 },
111 AppendCompactActivity(CompactActivityMetadata),
112 RecordDiffReview(vtcode_commons::ui_protocol::DiffReviewAnchor),
113 ReplaceCompactActivity(CompactActivityMetadata),
114 CollapsePtyBlock(CompactActivityMetadata),
115 SetKeyBindings {
116 bindings: HashMap<String, Vec<String>>,
117 },
118 SetImageInputEnabled(bool),
119 RestoreInputDraft(SubmittedInput),
120 ForceRedraw,
121 Shutdown,
122 ClearScreen,
123 CloseModal,
124 SetReasoningStage(Option<String>),
125 }
126
127 #[derive(Clone, Debug)]
129 pub struct InlineHandle {
130 diagnostic_observer: vtcode_commons::diagnostics::DiagnosticObserver,
131 sender: Option<UnboundedSender<InlineCommand>>,
132 deferred_events: Arc<Mutex<VecDeque<InlineEvent>>>,
133 next_tool_output_id: Arc<AtomicU64>,
134 agent_label_frame_width: Arc<AtomicUsize>,
135 }
136
137 const MAX_DEFERRED_EVENTS: usize = 32;
138
139 impl InlineHandle {
140 pub fn new_for_tests(sender: UnboundedSender<InlineCommand>) -> Self {
141 Self {
142 diagnostic_observer: Default::default(),
143 sender: Some(sender),
144 deferred_events: Arc::new(Mutex::new(VecDeque::new())),
145 next_tool_output_id: Arc::new(AtomicU64::new(0)),
146 agent_label_frame_width: Arc::new(AtomicUsize::new(0)),
147 }
148 }
149
150 pub fn defer_event(&self, event: InlineEvent) -> anyhow::Result<()> {
151 let mut deferred_events = self
152 .deferred_events
153 .lock()
154 .map_err(|error| anyhow::anyhow!("deferred input queue poisoned: {error}"))?;
155 if deferred_events.len() >= MAX_DEFERRED_EVENTS {
156 return Err(anyhow::anyhow!("deferred input queue is full"));
157 }
158 deferred_events.push_back(event);
159 Ok(())
160 }
161
162 fn take_deferred_event(&self) -> Option<InlineEvent> {
163 self.deferred_events.lock().ok()?.pop_front()
164 }
165
166 pub fn has_deferred_event(&self) -> bool {
167 self.deferred_events.lock().is_ok_and(|events| !events.is_empty())
168 }
169
170 pub fn set_message_labels(&self, agent: Option<String>, _user: Option<String>) {
176 let width = agent
177 .as_deref()
178 .filter(|label| !label.is_empty())
179 .map(|label| UnicodeWidthStr::width(label) + 1)
180 .unwrap_or_default();
181 self.agent_label_frame_width.store(width, Ordering::Relaxed);
182 }
183
184 pub fn agent_label_frame_width(&self) -> usize {
186 self.agent_label_frame_width.load(Ordering::Relaxed)
187 }
188
189 fn send_command(&self, command: InlineCommand) {
190 if let Some(sender) = &self.sender {
191 let _ = sender.send(command);
192 }
193 }
194
195 pub fn set_diagnostic_sink(&self, sink: vtcode_commons::diagnostics::DiagnosticSink) -> anyhow::Result<()> {
196 self.diagnostic_observer.set_sink(sink)
197 }
198 pub fn diagnostic(&self, diagnostic: vtcode_commons::diagnostics::Diagnostic) {
199 self.present_diagnostic(self.diagnostic_observer.prepare(&diagnostic));
200 }
201 pub fn present_diagnostic(&self, diagnostic: vtcode_commons::diagnostics::Diagnostic) {
202 if self.sender.is_none() {
203 vtcode_commons::diagnostics::stderr_diagnostic(&diagnostic);
204 return;
205 }
206 self.send_command(InlineCommand::Diagnostic(Box::new(vtcode_commons::diagnostics::redact_diagnostic(
207 &diagnostic,
208 ))));
209 }
210
211 #[track_caller]
212 fn try_append_diagnostic(&self, kind: InlineMessageKind, text: &str) -> bool {
213 let severity = match kind {
214 InlineMessageKind::Error => vtcode_commons::diagnostics::DiagnosticSeverity::Error,
215 InlineMessageKind::Warning => vtcode_commons::diagnostics::DiagnosticSeverity::Warning,
216 _ => return false,
217 };
218 if !text.trim().is_empty() {
219 self.diagnostic(vtcode_commons::diagnostics::legacy_ui_diagnostic(severity, text));
220 }
221 true
222 }
223
224 #[track_caller]
225 pub fn append_line(&self, kind: InlineMessageKind, segments: Vec<InlineSegment>) {
226 if matches!(kind, InlineMessageKind::Error | InlineMessageKind::Warning) {
227 let text = segments.iter().map(|segment| segment.text.as_str()).collect::<String>();
228 if self.try_append_diagnostic(kind, &text) {
229 return;
230 }
231 }
232 self.send_command(InlineCommand::AppendLine { kind, segments });
233 }
234 #[track_caller]
235 pub fn append_pasted_message(&self, kind: InlineMessageKind, text: String, line_count: usize) {
236 if self.try_append_diagnostic(kind, &text) {
237 return;
238 }
239 self.send_command(InlineCommand::AppendPastedMessage { kind, text, line_count });
240 }
241 pub fn inline(&self, kind: InlineMessageKind, segment: InlineSegment) {
242 self.send_command(InlineCommand::Inline { kind, segment });
243 }
244 pub fn replace_last(&self, count: usize, kind: InlineMessageKind, lines: Vec<Vec<InlineSegment>>) {
245 self.send_command(InlineCommand::ReplaceLast { count, kind, lines });
246 }
247 #[track_caller]
248 pub fn append_lines(&self, lines: Vec<InlineTranscriptLine>) {
249 if lines.is_empty() {
250 self.send_command(InlineCommand::AppendLines { lines });
251 return;
252 }
253 let mut pending = Vec::new();
254 for line in lines {
255 if matches!(line.kind, InlineMessageKind::Error | InlineMessageKind::Warning) {
256 if !pending.is_empty() {
257 self.send_command(InlineCommand::AppendLines { lines: std::mem::take(&mut pending) });
258 }
259 let text = line.segments.iter().map(|segment| segment.text.as_str()).collect::<String>();
260 self.try_append_diagnostic(line.kind, &text);
261 } else {
262 pending.push(line);
263 }
264 }
265 if !pending.is_empty() {
266 self.send_command(InlineCommand::AppendLines { lines: pending });
267 }
268 }
269 pub fn record_tool_output(&self, lines: Vec<String>) -> ToolOutputId {
270 let id = self.next_tool_output_id.fetch_add(1, Ordering::Relaxed);
271 self.send_command(InlineCommand::RecordToolOutput { id, lines });
272 id
273 }
274 pub fn append_tool_output_line(&self, id: ToolOutputId, kind: InlineMessageKind, segments: Vec<InlineSegment>) {
275 self.send_command(InlineCommand::AppendToolOutputLine { id, kind, segments });
276 }
277 pub fn append_compact_activity(&self, activity: CompactActivityMetadata) {
278 self.send_command(InlineCommand::AppendCompactActivity(activity));
279 }
280 pub fn record_diff_review(&self, anchor: vtcode_commons::ui_protocol::DiffReviewAnchor) {
281 self.send_command(InlineCommand::RecordDiffReview(anchor));
284 }
285 pub fn replace_compact_activity(&self, activity: CompactActivityMetadata) {
286 self.send_command(InlineCommand::ReplaceCompactActivity(activity));
287 }
288 pub fn collapse_pty_block(&self, activity: CompactActivityMetadata) {
289 self.send_command(InlineCommand::CollapsePtyBlock(activity));
290 }
291 pub fn set_key_bindings(&self, bindings: HashMap<String, Vec<String>>) {
292 self.send_command(InlineCommand::SetKeyBindings { bindings });
293 }
294 pub fn force_redraw(&self) {
295 self.send_command(InlineCommand::ForceRedraw);
296 }
297 pub fn shutdown(&self) {
298 self.send_command(InlineCommand::Shutdown);
299 }
300 pub fn clear_screen(&self) {
301 self.send_command(InlineCommand::ClearScreen);
302 }
303 pub fn show_modal(&self, _title: String, _lines: Vec<String>, _secure_prompt: Option<SecurePromptConfig>) {}
304 pub fn show_list_modal(
305 &self,
306 _title: String,
307 _lines: Vec<String>,
308 _items: Vec<InlineListItem>,
309 _selected: Option<InlineListSelection>,
310 _search: Option<InlineListSearchConfig>,
311 ) {
312 }
313 pub fn show_list_modal_with_footer(
314 &self,
315 _title: String,
316 _lines: Vec<String>,
317 _items: Vec<InlineListItem>,
318 _selected: Option<InlineListSelection>,
319 _search: Option<InlineListSearchConfig>,
320 _footer_hint: Option<String>,
321 ) {
322 }
323 pub fn show_list_modal_with_status(
324 &self,
325 _title: String,
326 _lines: Vec<String>,
327 _items: Vec<InlineListItem>,
328 _selected: Option<InlineListSelection>,
329 _search: Option<InlineListSearchConfig>,
330 _footer_hint: Option<String>,
331 _status: Option<vtcode_commons::ui_protocol::InlineStatus>,
332 ) {
333 }
334 pub fn close_modal(&self) {
335 self.send_command(InlineCommand::CloseModal);
336 }
337 pub fn restore_input_draft(&self, input: SubmittedInput) {
338 self.send_command(InlineCommand::RestoreInputDraft(input));
339 }
340 pub fn set_image_input_enabled(&self, enabled: bool) {
341 self.send_command(InlineCommand::SetImageInputEnabled(enabled));
342 }
343 pub fn set_reasoning_stage(&self, stage: Option<String>) {
344 self.send_command(InlineCommand::SetReasoningStage(stage));
345 }
346 }
347
348 pub struct InlineSession {
350 pub handle: InlineHandle,
351 pub events: UnboundedReceiver<InlineEvent>,
352 }
353
354 impl InlineSession {
355 pub async fn next_event(&mut self) -> Option<InlineEvent> {
356 if let Some(event) = self.handle.take_deferred_event() {
357 return Some(event);
358 }
359 self.events.recv().await
360 }
361
362 pub async fn wait_for_exit(&mut self, _timeout: std::time::Duration) -> bool {
365 true
366 }
367
368 pub fn clone_inline_handle(&self) -> InlineHandle {
369 self.handle.clone()
370 }
371 }
372
373 #[derive(Debug, Clone, Default)]
375 pub struct SessionAppearanceConfig {
376 pub theme: String,
377 pub ui_mode: super::UiMode,
378 pub show_sidebar: bool,
379 pub min_content_width: u16,
380 pub min_navigation_width: u16,
381 pub navigation_width_percent: u8,
382 pub transcript_bottom_padding: u16,
388 pub dim_completed_todos: bool,
389 pub show_task_panel: bool,
390 pub message_block_spacing: u8,
391 pub layout_mode: super::LayoutModeOverride,
392 pub reasoning_display_mode: super::ReasoningDisplayMode,
393 pub reasoning_visible_default: bool,
394 pub thinking_display: super::ThinkingBlockState,
395 pub communication_style: vtcode_commons::ui_protocol::CommunicationStyle,
396 pub vim_mode: bool,
397 pub readline_mode: bool,
398 pub busy_enter_behavior: super::BusyEnterBehavior,
399 pub screen_reader_mode: bool,
400 pub reduce_motion_mode: bool,
401 pub reduce_motion_keep_progress_animation: bool,
402 pub hide_header: bool,
403 pub show_transcript_review_hints: bool,
404 pub show_transcript_review_shortcut_guide: bool,
405 pub show_transcript_review_close_button: bool,
406 pub diff_preview_mode: vtcode_commons::ui_protocol::DiffPreviewMode,
407 pub syntax_highlighting: vtcode_config::loader::SyntaxHighlightingConfig,
409 pub customization: (),
410 }
411
412 pub fn theme_from_styles(styles: &ThemeStyles) -> super::InlineTheme {
414 super::theme_from_color_fields(
415 styles.foreground,
416 styles.background,
417 styles.primary,
418 styles.secondary,
419 styles.tool,
420 styles.tool_detail,
421 styles.pty_output,
422 styles.error,
423 styles.warning,
424 )
425 }
426}
427
428#[cfg(not(feature = "tui"))]
429pub use headless::*;