Skip to main content

vtcode_core/utils/ansi/
output.rs

1//! Plain output lines, modals, and screen management.
2
3use super::*;
4
5use crate::utils::transcript;
6
7use crate::ui::markdown::{MarkdownLine, RenderMarkdownOptions, render_markdown_to_lines_with_options};
8use crate::ui::theme;
9use crate::ui::tui::{InlineListItem, InlineListSearchConfig, InlineListSelection, InlineMessageKind};
10use crate::utils::ansi_capabilities::AnsiCapabilities;
11use anstyle::{Reset, Style};
12use anyhow::{Result, anyhow};
13use std::io::Write;
14use unicode_width::UnicodeWidthStr;
15
16const RECENT_DIAGNOSTIC_LIMIT: usize = 128;
17
18impl AnsiRenderer {
19    pub fn set_table_max_width(&mut self, max_width: Option<usize>) {
20        if let Some(sink) = &mut self.sink {
21            sink.table_max_width = max_width;
22            sink.table_max_width_override = max_width;
23        }
24    }
25
26    pub(super) fn should_render_style(&self, style: MessageStyle) -> bool {
27        self.reasoning_visible || !matches!(style, MessageStyle::Reasoning | MessageStyle::ReasoningEmphasis)
28    }
29
30    /// Install the canonical event boundary after a thread sink exists.
31    pub fn set_diagnostic_sink(&mut self, sink: DiagnosticSink) {
32        self.diagnostic_sink = Some(sink);
33        self.diagnostic_history.clear();
34    }
35
36    /// Display an operational diagnostic. Payloads must also be sanitized before event persistence.
37    pub fn diagnostic(&mut self, diagnostic: &vtcode_commons::diagnostics::Diagnostic) -> Result<()> {
38        self.display_diagnostic(diagnostic, true)
39    }
40
41    /// Restore an already-durable incident without emitting another event.
42    pub fn restore_diagnostic(&mut self, diagnostic: &vtcode_commons::diagnostics::Diagnostic) -> Result<()> {
43        self.display_diagnostic(diagnostic, false)
44    }
45
46    fn display_diagnostic(
47        &mut self,
48        diagnostic: &vtcode_commons::diagnostics::Diagnostic,
49        persist: bool,
50    ) -> Result<()> {
51        use vtcode_commons::diagnostics::{DiagnosticSeverity, redact_diagnostic};
52        self.flush_compact_command_group();
53        let mut diagnostic = redact_diagnostic(diagnostic);
54        let already_persisted = self.diagnostic_history.iter().any(|previous| previous == &diagnostic);
55        let persistence_error = if !persist || already_persisted {
56            None
57        } else {
58            self.diagnostic_sink.as_ref().and_then(|sink| sink(&diagnostic).err())
59        };
60        if !already_persisted && persistence_error.is_none() && self.diagnostic_sink.is_some() {
61            self.diagnostic_history
62                .retain(|previous| previous.correlation_id != diagnostic.correlation_id);
63            if self.diagnostic_history.len() == RECENT_DIAGNOSTIC_LIMIT {
64                let _ = self.diagnostic_history.pop_front();
65            }
66            self.diagnostic_history.push_back(diagnostic.clone());
67        }
68        if let Some(error) = &persistence_error {
69            if !diagnostic.agent_details.is_empty() {
70                diagnostic.agent_details.push_str("\n\n");
71            }
72            diagnostic
73                .agent_details
74                .push_str("Diagnostic persistence failed; this message may not be saved.\n");
75            diagnostic
76                .agent_details
77                .push_str(&vtcode_commons::sanitizer::sanitize_provider_diagnostic(error.to_string()));
78        }
79        let style = match diagnostic.severity {
80            DiagnosticSeverity::Info => MessageStyle::Info,
81            DiagnosticSeverity::Warning => MessageStyle::Warning,
82            DiagnosticSeverity::Error => MessageStyle::Error,
83        };
84        if let Some(sink) = &self.sink {
85            if persist && self.diagnostic_sink.is_none() {
86                // Secondary renderers retain their owning handle's canonical observer.
87                sink.handle.diagnostic(diagnostic.clone());
88            } else {
89                sink.handle.present_diagnostic(diagnostic.clone());
90            }
91            transcript::append(&diagnostic.text());
92        } else {
93            self.render_markdown(style, &diagnostic.text())?;
94        }
95        if let Some(error) = persistence_error {
96            return Err(error);
97        }
98        Ok(())
99    }
100
101    #[track_caller]
102    fn legacy_diagnostic(&mut self, style: MessageStyle, text: &str) -> Result<()> {
103        if text.trim().is_empty() {
104            return Ok(());
105        }
106        use vtcode_commons::diagnostics::DiagnosticSeverity;
107        let severity = if matches!(style, MessageStyle::Warning) {
108            DiagnosticSeverity::Warning
109        } else {
110            DiagnosticSeverity::Error
111        };
112        self.diagnostic(&vtcode_commons::diagnostics::legacy_ui_diagnostic(severity, text))
113    }
114
115    pub(super) fn indent_for_style(&self, style: MessageStyle) -> &'static str {
116        if self.screen_reader_mode && matches!(style, MessageStyle::Reasoning | MessageStyle::ReasoningEmphasis) {
117            "  [reasoning] "
118        } else {
119            style.indent()
120        }
121    }
122
123    /// Get the terminal's detected ANSI capabilities
124    pub fn capabilities(&self) -> &AnsiCapabilities {
125        &self.capabilities
126    }
127
128    /// Return the width available to a rendered diff row after the logical
129    /// message indent and, for inline UI output, the transcript frame.
130    ///
131    /// Diff rows use this width only to extend their background with spaces;
132    /// when terminal sizing is unavailable callers retain their bounded
133    /// fallback behavior.
134    pub fn diff_content_width(&self, style: MessageStyle) -> Option<usize> {
135        let indent_width = UnicodeWidthStr::width(self.indent_for_style(style));
136        let kind = Self::message_kind(style);
137        let frame_width = self
138            .sink
139            .as_ref()
140            .map(|sink| transcript_table_frame_width(kind, sink.handle.agent_label_frame_width()))
141            .unwrap_or_default();
142        // An explicit test/configuration width wins. Otherwise prefer a fresh
143        // terminal measurement so a later diff preview follows a resize even
144        // when an earlier Markdown render cached the previous width.
145        let terminal_width = self
146            .sink
147            .as_ref()
148            .and_then(|sink| {
149                sink.table_max_width_override
150                    .or_else(|| crossterm::terminal::size().ok().map(|(width, _)| usize::from(width)))
151                    .or(sink.table_max_width)
152            })
153            .or_else(|| crossterm::terminal::size().ok().map(|(width, _)| usize::from(width)));
154
155        terminal_width.map(|width| width.saturating_sub(indent_width).saturating_sub(frame_width))
156    }
157
158    /// Check if unicode should be used for formatting (tables, boxes, etc.)
159    pub fn should_use_unicode_formatting(&self) -> bool {
160        self.capabilities.should_use_unicode_boxes()
161    }
162
163    /// Check if 256-color output is supported
164    pub fn supports_256_colors(&self) -> bool {
165        self.capabilities.supports_256_colors()
166    }
167
168    /// Check if true color (24-bit) output is supported
169    pub fn supports_true_color(&self) -> bool {
170        self.capabilities.supports_true_color()
171    }
172
173    /// Check if should use unicode characters based on terminal capabilities
174    pub fn should_use_unicode(&self) -> bool {
175        self.capabilities.unicode_support
176    }
177
178    pub fn show_list_modal(
179        &mut self,
180        title: &str,
181        lines: Vec<String>,
182        items: Vec<InlineListItem>,
183        selected: Option<InlineListSelection>,
184        search: Option<InlineListSearchConfig>,
185    ) {
186        if let Some(sink) = &self.sink {
187            sink.show_list_modal(title.into(), lines, items, selected, search);
188        }
189    }
190
191    pub fn show_list_modal_with_footer(
192        &mut self,
193        title: &str,
194        lines: Vec<String>,
195        items: Vec<InlineListItem>,
196        selected: Option<InlineListSelection>,
197        search: Option<InlineListSearchConfig>,
198        footer_hint: Option<String>,
199    ) {
200        self.show_list_modal_with_status(title, lines, items, selected, search, footer_hint, None);
201    }
202
203    /// Show a list modal with an optional status strip (last action feedback).
204    pub fn show_list_modal_with_status(
205        &mut self,
206        title: &str,
207        lines: Vec<String>,
208        items: Vec<InlineListItem>,
209        selected: Option<InlineListSelection>,
210        search: Option<InlineListSearchConfig>,
211        footer_hint: Option<String>,
212        status: Option<vtcode_commons::ui_protocol::InlineStatus>,
213    ) {
214        if let Some(sink) = &self.sink {
215            sink.show_list_modal_with_status(title.into(), lines, items, selected, search, footer_hint, status);
216        }
217    }
218
219    pub fn show_secure_prompt_modal(&mut self, title: &str, lines: Vec<String>, prompt_label: String) {
220        if let Some(sink) = &self.sink {
221            sink.show_secure_prompt_modal(title.into(), lines, prompt_label);
222        }
223    }
224
225    pub fn close_modal(&mut self) {
226        if let Some(sink) = &self.sink {
227            sink.close_modal();
228        }
229    }
230
231    pub fn clear_screen(&mut self) {
232        self.flush_compact_command_group();
233        if let Some(sink) = &self.sink {
234            sink.handle.clear_screen();
235        }
236    }
237
238    /// Push text into the buffer
239    pub fn push(&mut self, text: &str) {
240        self.buffer.push_str(text);
241    }
242
243    /// Flush the buffer with the given style
244    #[track_caller]
245    pub fn flush(&mut self, style: MessageStyle) -> Result<()> {
246        self.flush_compact_command_group();
247        if !self.should_render_style(style) {
248            self.buffer.clear();
249            return Ok(());
250        }
251        if matches!(style, MessageStyle::Error | MessageStyle::ToolError | MessageStyle::Warning) {
252            let text = std::mem::take(&mut self.buffer);
253            return self.legacy_diagnostic(style, &text);
254        }
255        let indent = self.indent_for_style(style);
256        if let Some(sink) = &mut self.sink {
257            // Track if this line is empty
258            self.last_line_was_empty = self.buffer.is_empty() && indent.is_empty();
259            sink.write_line(style.style(), indent, &self.buffer, Self::message_kind(style))?;
260            self.buffer.clear();
261            return Ok(());
262        }
263        let style = style.style();
264        if self.color {
265            writeln!(self.writer, "{style}{}{Reset}", self.buffer)?;
266        } else {
267            writeln!(self.writer, "{}", self.buffer)?;
268        }
269        self.writer.flush()?;
270        transcript::append(&self.buffer);
271        // Track if this line is empty
272        self.last_line_was_empty = self.buffer.is_empty();
273        self.buffer.clear();
274        Ok(())
275    }
276
277    /// Convenience for writing a single line
278    #[track_caller]
279    pub fn line(&mut self, style: MessageStyle, text: &str) -> Result<()> {
280        self.flush_compact_command_group();
281        if !self.should_render_style(style) {
282            return Ok(());
283        }
284        if matches!(style, MessageStyle::Error | MessageStyle::ToolError | MessageStyle::Warning) {
285            return self.legacy_diagnostic(style, text);
286        }
287        if matches!(style, MessageStyle::Response | MessageStyle::Reasoning | MessageStyle::ReasoningEmphasis) {
288            return self.render_markdown(style, text);
289        }
290        if matches!(style, MessageStyle::Output | MessageStyle::ToolOutput) {
291            let stripped = crate::utils::ansi_parser::strip_ansi(text);
292            self.buffer.clear();
293            if looks_like_diff(&stripped) {
294                self.buffer.push_str("```diff\n");
295            } else {
296                self.buffer.push_str("```\n");
297            }
298            self.buffer.push_str(&stripped);
299            self.buffer.push_str("\n```");
300            let fenced = std::mem::take(&mut self.buffer);
301            return self.render_markdown(style, &fenced);
302        }
303        if matches!(style, MessageStyle::ToolDetail) {
304            if contains_markdown_fence(text) {
305                let stripped = crate::utils::ansi_parser::strip_ansi(text);
306                return self.render_markdown(style, &stripped);
307            }
308            if looks_like_diff(text) {
309                let stripped = crate::utils::ansi_parser::strip_ansi(text);
310                self.buffer.clear();
311                self.buffer.push_str("```diff\n");
312                self.buffer.push_str(&stripped);
313                self.buffer.push_str("\n```");
314                let fenced = std::mem::take(&mut self.buffer);
315                return self.render_markdown(style, &fenced);
316            }
317        }
318        let indent = style.indent();
319        let dont_split = matches!(style, MessageStyle::Tool | MessageStyle::ToolDetail);
320
321        if let Some(sink) = &mut self.sink {
322            sink.write_multiline_with_transcript(style.style(), indent, text, Self::message_kind(style), true, None)?;
323            return Ok(());
324        }
325
326        if text.contains('\n') && !dont_split {
327            for line in text.lines() {
328                self.buffer.clear();
329                if !indent.is_empty() && !line.is_empty() {
330                    self.buffer.push_str(indent);
331                }
332                self.buffer.push_str(line);
333                self.flush(style)?;
334            }
335            Ok(())
336        } else {
337            self.buffer.clear();
338            if !indent.is_empty() && !text.is_empty() {
339                self.buffer.push_str(indent);
340            }
341            self.buffer.push_str(text);
342            self.flush(style)
343        }
344    }
345
346    /// Write a continuation line that joins an existing Pty block.
347    ///
348    /// Sends the text as `InlineMessageKind::Pty` through
349    /// `write_multiline_with_transcript` so the TUI reflow renders it
350    /// with the same 2-space block prefix and styling as the PTY output.
351    pub fn pty_continuation_line(&mut self, text: &str) -> Result<()> {
352        self.flush_compact_command_group();
353        let style = MessageStyle::ToolOutput;
354        let indent = style.indent();
355        let kind = Self::message_kind(style);
356        if let Some(sink) = &mut self.sink {
357            sink.write_multiline_with_transcript(style.style(), indent, text, kind, true, None)?;
358            return Ok(());
359        }
360        self.buffer.clear();
361        if !indent.is_empty() && !text.is_empty() {
362            self.buffer.push_str(indent);
363        }
364        self.buffer.push_str(text);
365        self.flush(style)
366    }
367
368    /// Write a URL as a full, clickable line using OSC 8 hyperlinks.
369    ///
370    /// The URL is rendered on its own line so that terminal emulators can
371    /// detect and activate it for click-to-open behaviour.
372    pub fn hyperlink_line(&mut self, style: MessageStyle, url: &str) -> Result<()> {
373        self.flush_compact_command_group();
374        if !self.should_render_style(style) {
375            return Ok(());
376        }
377        let indent = style.indent();
378        if let Some(sink) = &mut self.sink {
379            let linked = format!(
380                "{}{}{}",
381                vtcode_commons::ansi_codes::hyperlink_open(url),
382                url,
383                vtcode_commons::ansi_codes::hyperlink_close(),
384            );
385            sink.write_multiline_with_transcript(
386                style.style(),
387                indent,
388                &linked,
389                Self::message_kind(style),
390                true,
391                None,
392            )?;
393            self.last_line_was_empty = false;
394            return Ok(());
395        }
396        self.buffer.clear();
397        if !indent.is_empty() {
398            self.buffer.push_str(indent);
399        }
400        self.buffer.push_str(&vtcode_commons::ansi_codes::hyperlink_open(url));
401        self.buffer.push_str(url);
402        self.buffer.push_str(&vtcode_commons::ansi_codes::hyperlink_close());
403        let ansi_style = style.style();
404        if self.color {
405            writeln!(self.writer, "{ansi_style}{}{Reset}", self.buffer)?;
406        } else {
407            writeln!(self.writer, "{}", self.buffer)?;
408        }
409        self.writer.flush()?;
410        transcript::append(url);
411        self.last_line_was_empty = false;
412        self.buffer.clear();
413        Ok(())
414    }
415
416    /// Append a large pasted user message as a placeholder in inline UI.
417    pub fn append_paste_placeholder(&mut self, message: &str, line_count: usize) -> Result<()> {
418        self.flush_compact_command_group();
419        if let Some(sink) = &self.sink {
420            sink.handle
421                .append_pasted_message(InlineMessageKind::User, message.to_string(), line_count);
422            transcript::append(message);
423            self.last_line_was_empty = message.trim().is_empty();
424            return Ok(());
425        }
426        self.line(MessageStyle::User, message)
427    }
428
429    /// Write styled text without a trailing newline
430    pub fn inline_with_style(&mut self, style: MessageStyle, text: &str) -> Result<()> {
431        self.flush_compact_command_group();
432        if !self.should_render_style(style) {
433            return Ok(());
434        }
435        if let Some(sink) = &mut self.sink {
436            sink.write_inline(style.style(), text, Self::message_kind(style));
437            return Ok(());
438        }
439        let ansi_style = style.style();
440        if self.color {
441            write!(self.writer, "{ansi_style}{text}{Reset}")?;
442        } else {
443            write!(self.writer, "{text}")?;
444        }
445        self.writer.flush()?;
446        Ok(())
447    }
448
449    /// Write a line with an explicit style
450    pub fn line_with_style(&mut self, style: Style, text: &str) -> Result<()> {
451        self.line_with_override_style(MessageStyle::Info, style, text)
452    }
453
454    /// Write a line with a custom style while preserving the logical message kind.
455    #[track_caller]
456    pub fn line_with_override_style(&mut self, fallback: MessageStyle, style: Style, text: &str) -> Result<()> {
457        self.flush_compact_command_group();
458        let tool_output_id = self.pending_tool_output_anchor.take();
459        if !self.should_render_style(fallback) {
460            return Ok(());
461        }
462        if matches!(fallback, MessageStyle::Error | MessageStyle::ToolError | MessageStyle::Warning) {
463            return self.legacy_diagnostic(fallback, text);
464        }
465        let kind = Self::message_kind(fallback);
466        let indent = self.indent_for_style(fallback);
467        if let Some(sink) = &mut self.sink {
468            sink.write_multiline_with_transcript(style, indent, text, kind, true, tool_output_id)?;
469            self.last_line_was_empty = text.trim().is_empty();
470            return Ok(());
471        }
472        let mut combined;
473        let display = if !indent.is_empty() && !text.is_empty() {
474            combined = String::with_capacity(indent.len() + text.len());
475            combined.push_str(indent);
476            combined.push_str(text);
477            combined.as_str()
478        } else {
479            text
480        };
481        if self.color {
482            writeln!(self.writer, "{style}{display}{Reset}")?;
483        } else {
484            writeln!(self.writer, "{display}")?;
485        }
486        self.writer.flush()?;
487        transcript::append(display);
488        self.last_line_was_empty = text.trim().is_empty();
489        Ok(())
490    }
491
492    /// Write an empty line only if the previous line was not empty
493    pub fn line_if_not_empty(&mut self, style: MessageStyle) -> Result<()> {
494        if !self.was_previous_line_empty() {
495            self.line(style, "")
496        } else {
497            Ok(())
498        }
499    }
500
501    /// Write a raw line without styling
502    pub fn raw_line(&mut self, text: &str) -> Result<()> {
503        self.flush_compact_command_group();
504        writeln!(self.writer, "{text}")?;
505        self.writer.flush()?;
506        transcript::append(text);
507        Ok(())
508    }
509
510    pub fn render_token_delta(&mut self, delta: &str) -> Result<()> {
511        self.inline_with_style(MessageStyle::Response, delta)
512    }
513
514    pub fn stream_markdown_response(&mut self, text: &str, previous_line_count: usize) -> Result<usize> {
515        // Strip ANSI codes from agent response to prevent interference with markdown rendering
516        let text = crate::utils::ansi_parser::strip_ansi(text);
517        let text = &text;
518
519        let styles = theme::active_styles();
520        let style = MessageStyle::Response;
521        let base_style = style.style();
522        let indent = style.indent();
523        if let Some(sink) = &mut self.sink {
524            // Read terminal width fresh so tables adapt to resizes.
525            if sink.table_max_width_override.is_none()
526                && let Ok((w, _)) = crossterm::terminal::size()
527            {
528                sink.table_max_width = Some(w as usize);
529            }
530            let table_max_width = sink.table_content_width(Self::message_kind(style), indent);
531            let (prepared, plain_lines, last_empty) =
532                sink.prepare_markdown_lines_with_table_width(text, indent, base_style, true, true, table_max_width);
533            let line_count = prepared.len();
534            sink.replace_inline_lines(previous_line_count, prepared, &plain_lines, Self::message_kind(style));
535            self.last_line_was_empty = last_empty;
536            return Ok(line_count);
537        }
538
539        let highlight_cfg = if self.highlight_config.enabled {
540            Some(&self.highlight_config)
541        } else {
542            None
543        };
544        let mut lines = render_markdown_to_lines_with_options(
545            text,
546            base_style,
547            &styles,
548            highlight_cfg,
549            RenderMarkdownOptions::default(),
550        );
551        if lines.is_empty() {
552            lines.push(MarkdownLine::default());
553        }
554
555        Err(anyhow!("stream_markdown_response requires an inline sink"))
556    }
557}