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    /// Persist an operational diagnostic to the canonical sink without
37    /// displaying it. Rows the active communication style hides still belong
38    /// to the policy-complete event trail, so producers consult the visibility
39    /// predicate at paint time and call this entry point instead of
40    /// [`Self::diagnostic`] when a row must stay off screen.
41    pub fn persist_diagnostic(&mut self, diagnostic: &vtcode_commons::diagnostics::Diagnostic) -> Result<()> {
42        let (_, persistence_error) = self.persist_diagnostic_impl(diagnostic, true);
43        match persistence_error {
44            Some(error) => Err(error),
45            None => Ok(()),
46        }
47    }
48
49    /// Display an operational diagnostic. Payloads must also be sanitized before event persistence.
50    pub fn diagnostic(&mut self, diagnostic: &vtcode_commons::diagnostics::Diagnostic) -> Result<()> {
51        self.display_diagnostic(diagnostic, true)
52    }
53
54    /// Restore an already-durable incident without emitting another event.
55    pub fn restore_diagnostic(&mut self, diagnostic: &vtcode_commons::diagnostics::Diagnostic) -> Result<()> {
56        self.display_diagnostic(diagnostic, false)
57    }
58
59    fn display_diagnostic(
60        &mut self,
61        diagnostic: &vtcode_commons::diagnostics::Diagnostic,
62        persist: bool,
63    ) -> Result<()> {
64        use vtcode_commons::diagnostics::DiagnosticSeverity;
65        let (diagnostic, persistence_error) = self.persist_diagnostic_impl(diagnostic, persist);
66        let style = match diagnostic.severity {
67            DiagnosticSeverity::Info => MessageStyle::Info,
68            DiagnosticSeverity::Warning => MessageStyle::Warning,
69            DiagnosticSeverity::Error => MessageStyle::Error,
70        };
71        if let Some(sink) = &self.sink {
72            if persist && self.diagnostic_sink.is_none() {
73                // Secondary renderers retain their owning handle's canonical observer.
74                sink.handle.diagnostic(diagnostic.clone());
75            } else {
76                sink.handle.present_diagnostic(diagnostic.clone());
77            }
78            transcript::append(&diagnostic.text());
79        } else {
80            self.render_markdown(style, &diagnostic.text())?;
81        }
82        if let Some(error) = persistence_error {
83            return Err(error);
84        }
85        Ok(())
86    }
87
88    /// Flush, redact, deduplicate, and persist one diagnostic, returning the
89    /// redacted payload annotated with any persistence-failure note and the
90    /// sink error that caused it.
91    fn persist_diagnostic_impl(
92        &mut self,
93        diagnostic: &vtcode_commons::diagnostics::Diagnostic,
94        persist: bool,
95    ) -> (vtcode_commons::diagnostics::Diagnostic, Option<anyhow::Error>) {
96        use vtcode_commons::diagnostics::redact_diagnostic;
97        self.flush_compact_command_group();
98        let mut diagnostic = redact_diagnostic(diagnostic);
99        let already_persisted = self.diagnostic_history.iter().any(|previous| previous == &diagnostic);
100        let persistence_error = if !persist || already_persisted {
101            None
102        } else {
103            self.diagnostic_sink.as_ref().and_then(|sink| sink(&diagnostic).err())
104        };
105        if !already_persisted && persistence_error.is_none() && self.diagnostic_sink.is_some() {
106            self.diagnostic_history
107                .retain(|previous| previous.correlation_id != diagnostic.correlation_id);
108            if self.diagnostic_history.len() == RECENT_DIAGNOSTIC_LIMIT {
109                let _ = self.diagnostic_history.pop_front();
110            }
111            self.diagnostic_history.push_back(diagnostic.clone());
112        }
113        if let Some(error) = &persistence_error {
114            if !diagnostic.agent_details.is_empty() {
115                diagnostic.agent_details.push_str("\n\n");
116            }
117            diagnostic
118                .agent_details
119                .push_str("Diagnostic persistence failed; this message may not be saved.\n");
120            diagnostic
121                .agent_details
122                .push_str(&vtcode_commons::sanitizer::sanitize_provider_diagnostic(error.to_string()));
123        }
124        (diagnostic, persistence_error)
125    }
126
127    #[track_caller]
128    fn legacy_diagnostic(&mut self, style: MessageStyle, text: &str) -> Result<()> {
129        if text.trim().is_empty() {
130            return Ok(());
131        }
132        use vtcode_commons::diagnostics::DiagnosticSeverity;
133        let severity = if matches!(style, MessageStyle::Warning) {
134            DiagnosticSeverity::Warning
135        } else {
136            DiagnosticSeverity::Error
137        };
138        self.diagnostic(&vtcode_commons::diagnostics::legacy_ui_diagnostic(severity, text))
139    }
140
141    pub(super) fn indent_for_style(&self, style: MessageStyle) -> &'static str {
142        if self.screen_reader_mode && matches!(style, MessageStyle::Reasoning | MessageStyle::ReasoningEmphasis) {
143            "  [reasoning] "
144        } else {
145            style.indent()
146        }
147    }
148
149    /// Get the terminal's detected ANSI capabilities
150    pub fn capabilities(&self) -> &AnsiCapabilities {
151        &self.capabilities
152    }
153
154    /// Return the width available to a rendered diff row after the logical
155    /// message indent and, for inline UI output, the transcript frame.
156    ///
157    /// Diff rows use this width only to extend their background with spaces;
158    /// when terminal sizing is unavailable callers retain their bounded
159    /// fallback behavior.
160    pub fn diff_content_width(&self, style: MessageStyle) -> Option<usize> {
161        let indent_width = UnicodeWidthStr::width(self.indent_for_style(style));
162        let kind = Self::message_kind(style);
163        let frame_width = self
164            .sink
165            .as_ref()
166            .map(|sink| transcript_table_frame_width(kind, sink.handle.agent_label_frame_width()))
167            .unwrap_or_default();
168        // An explicit test/configuration width wins. Otherwise prefer a fresh
169        // terminal measurement so a later diff preview follows a resize even
170        // when an earlier Markdown render cached the previous width.
171        let terminal_width = self
172            .sink
173            .as_ref()
174            .and_then(|sink| {
175                sink.table_max_width_override
176                    .or_else(|| crate::utils::tty::terminal_size().map(|(width, _)| usize::from(width)))
177                    .or(sink.table_max_width)
178            })
179            .or_else(|| crate::utils::tty::terminal_size().map(|(width, _)| usize::from(width)));
180
181        terminal_width.map(|width| width.saturating_sub(indent_width).saturating_sub(frame_width))
182    }
183
184    /// Check if unicode should be used for formatting (tables, boxes, etc.)
185    pub fn should_use_unicode_formatting(&self) -> bool {
186        self.capabilities.should_use_unicode_boxes()
187    }
188
189    /// Check if 256-color output is supported
190    pub fn supports_256_colors(&self) -> bool {
191        self.capabilities.supports_256_colors()
192    }
193
194    /// Check if true color (24-bit) output is supported
195    pub fn supports_true_color(&self) -> bool {
196        self.capabilities.supports_true_color()
197    }
198
199    /// Check if should use unicode characters based on terminal capabilities
200    pub fn should_use_unicode(&self) -> bool {
201        self.capabilities.unicode_support
202    }
203
204    pub fn show_list_modal(
205        &mut self,
206        title: &str,
207        lines: Vec<String>,
208        items: Vec<InlineListItem>,
209        selected: Option<InlineListSelection>,
210        search: Option<InlineListSearchConfig>,
211    ) {
212        if let Some(sink) = &self.sink {
213            sink.show_list_modal(title.into(), lines, items, selected, search);
214        }
215    }
216
217    pub fn show_list_modal_with_footer(
218        &mut self,
219        title: &str,
220        lines: Vec<String>,
221        items: Vec<InlineListItem>,
222        selected: Option<InlineListSelection>,
223        search: Option<InlineListSearchConfig>,
224        footer_hint: Option<String>,
225    ) {
226        self.show_list_modal_with_status(title, lines, items, selected, search, footer_hint, None);
227    }
228
229    /// Show a list modal with an optional status strip (last action feedback).
230    pub fn show_list_modal_with_status(
231        &mut self,
232        title: &str,
233        lines: Vec<String>,
234        items: Vec<InlineListItem>,
235        selected: Option<InlineListSelection>,
236        search: Option<InlineListSearchConfig>,
237        footer_hint: Option<String>,
238        status: Option<vtcode_commons::ui_protocol::InlineStatus>,
239    ) {
240        if let Some(sink) = &self.sink {
241            sink.show_list_modal_with_status(title.into(), lines, items, selected, search, footer_hint, status);
242        }
243    }
244
245    pub fn show_secure_prompt_modal(&mut self, title: &str, lines: Vec<String>, prompt_label: String) {
246        if let Some(sink) = &self.sink {
247            sink.show_secure_prompt_modal(title.into(), lines, prompt_label);
248        }
249    }
250
251    pub fn close_modal(&mut self) {
252        if let Some(sink) = &self.sink {
253            sink.close_modal();
254        }
255    }
256
257    pub fn clear_screen(&mut self) {
258        self.flush_compact_command_group();
259        if let Some(sink) = &self.sink {
260            sink.handle.clear_screen();
261        }
262    }
263
264    /// Push text into the buffer
265    pub fn push(&mut self, text: &str) {
266        self.buffer.push_str(text);
267    }
268
269    /// Flush the buffer with the given style
270    #[track_caller]
271    pub fn flush(&mut self, style: MessageStyle) -> Result<()> {
272        self.flush_compact_command_group();
273        if !self.should_render_style(style) {
274            self.buffer.clear();
275            return Ok(());
276        }
277        if matches!(style, MessageStyle::Error | MessageStyle::ToolError | MessageStyle::Warning) {
278            let text = std::mem::take(&mut self.buffer);
279            return self.legacy_diagnostic(style, &text);
280        }
281        let indent = self.indent_for_style(style);
282        if let Some(sink) = &mut self.sink {
283            // Track if this line is empty
284            self.last_line_was_empty = self.buffer.is_empty() && indent.is_empty();
285            sink.write_line(style.style(), indent, &self.buffer, Self::message_kind(style))?;
286            self.buffer.clear();
287            return Ok(());
288        }
289        let style = style.style();
290        if self.color {
291            writeln!(self.writer, "{style}{}{Reset}", self.buffer)?;
292        } else {
293            writeln!(self.writer, "{}", self.buffer)?;
294        }
295        self.writer.flush()?;
296        transcript::append(&self.buffer);
297        // Track if this line is empty
298        self.last_line_was_empty = self.buffer.is_empty();
299        self.buffer.clear();
300        Ok(())
301    }
302
303    /// Convenience for writing a single line
304    #[track_caller]
305    pub fn line(&mut self, style: MessageStyle, text: &str) -> Result<()> {
306        self.flush_compact_command_group();
307        if !self.should_render_style(style) {
308            return Ok(());
309        }
310        if matches!(style, MessageStyle::Error | MessageStyle::ToolError | MessageStyle::Warning) {
311            return self.legacy_diagnostic(style, text);
312        }
313        if matches!(style, MessageStyle::Response | MessageStyle::Reasoning | MessageStyle::ReasoningEmphasis) {
314            return self.render_markdown(style, text);
315        }
316        if matches!(style, MessageStyle::Output | MessageStyle::ToolOutput) {
317            let stripped = crate::utils::ansi_parser::strip_ansi(text);
318            self.buffer.clear();
319            if looks_like_diff(&stripped) {
320                self.buffer.push_str("```diff\n");
321            } else {
322                self.buffer.push_str("```\n");
323            }
324            self.buffer.push_str(&stripped);
325            self.buffer.push_str("\n```");
326            let fenced = std::mem::take(&mut self.buffer);
327            return self.render_markdown(style, &fenced);
328        }
329        if matches!(style, MessageStyle::ToolDetail) {
330            if contains_markdown_fence(text) {
331                let stripped = crate::utils::ansi_parser::strip_ansi(text);
332                return self.render_markdown(style, &stripped);
333            }
334            if looks_like_diff(text) {
335                let stripped = crate::utils::ansi_parser::strip_ansi(text);
336                self.buffer.clear();
337                self.buffer.push_str("```diff\n");
338                self.buffer.push_str(&stripped);
339                self.buffer.push_str("\n```");
340                let fenced = std::mem::take(&mut self.buffer);
341                return self.render_markdown(style, &fenced);
342            }
343        }
344        let indent = style.indent();
345        let dont_split = matches!(style, MessageStyle::Tool | MessageStyle::ToolDetail);
346
347        if let Some(sink) = &mut self.sink {
348            sink.write_multiline_with_transcript(style.style(), indent, text, Self::message_kind(style), true, None)?;
349            return Ok(());
350        }
351
352        if text.contains('\n') && !dont_split {
353            for line in text.lines() {
354                self.buffer.clear();
355                if !indent.is_empty() && !line.is_empty() {
356                    self.buffer.push_str(indent);
357                }
358                self.buffer.push_str(line);
359                self.flush(style)?;
360            }
361            Ok(())
362        } else {
363            self.buffer.clear();
364            if !indent.is_empty() && !text.is_empty() {
365                self.buffer.push_str(indent);
366            }
367            self.buffer.push_str(text);
368            self.flush(style)
369        }
370    }
371
372    /// Write a continuation line that joins an existing Pty block.
373    ///
374    /// Sends the text as `InlineMessageKind::Pty` through
375    /// `write_multiline_with_transcript` so the TUI reflow renders it
376    /// with the same 2-space block prefix and styling as the PTY output.
377    pub fn pty_continuation_line(&mut self, text: &str) -> Result<()> {
378        self.flush_compact_command_group();
379        let style = MessageStyle::ToolOutput;
380        let indent = style.indent();
381        let kind = Self::message_kind(style);
382        if let Some(sink) = &mut self.sink {
383            sink.write_multiline_with_transcript(style.style(), indent, text, kind, true, None)?;
384            return Ok(());
385        }
386        self.buffer.clear();
387        if !indent.is_empty() && !text.is_empty() {
388            self.buffer.push_str(indent);
389        }
390        self.buffer.push_str(text);
391        self.flush(style)
392    }
393
394    /// Write a URL as a full, clickable line using OSC 8 hyperlinks.
395    ///
396    /// The URL is rendered on its own line so that terminal emulators can
397    /// detect and activate it for click-to-open behaviour.
398    pub fn hyperlink_line(&mut self, style: MessageStyle, url: &str) -> Result<()> {
399        self.flush_compact_command_group();
400        if !self.should_render_style(style) {
401            return Ok(());
402        }
403        let indent = style.indent();
404        if let Some(sink) = &mut self.sink {
405            let linked = format!(
406                "{}{}{}",
407                vtcode_commons::ansi_codes::hyperlink_open(url),
408                url,
409                vtcode_commons::ansi_codes::hyperlink_close(),
410            );
411            sink.write_multiline_with_transcript(
412                style.style(),
413                indent,
414                &linked,
415                Self::message_kind(style),
416                true,
417                None,
418            )?;
419            self.last_line_was_empty = false;
420            return Ok(());
421        }
422        self.buffer.clear();
423        if !indent.is_empty() {
424            self.buffer.push_str(indent);
425        }
426        self.buffer.push_str(&vtcode_commons::ansi_codes::hyperlink_open(url));
427        self.buffer.push_str(url);
428        self.buffer.push_str(&vtcode_commons::ansi_codes::hyperlink_close());
429        let ansi_style = style.style();
430        if self.color {
431            writeln!(self.writer, "{ansi_style}{}{Reset}", self.buffer)?;
432        } else {
433            writeln!(self.writer, "{}", self.buffer)?;
434        }
435        self.writer.flush()?;
436        transcript::append(url);
437        self.last_line_was_empty = false;
438        self.buffer.clear();
439        Ok(())
440    }
441
442    /// Append a large pasted user message as a placeholder in inline UI.
443    pub fn append_paste_placeholder(&mut self, message: &str, line_count: usize) -> Result<()> {
444        self.flush_compact_command_group();
445        if let Some(sink) = &self.sink {
446            sink.handle
447                .append_pasted_message(InlineMessageKind::User, message.to_string(), line_count);
448            transcript::append(message);
449            self.last_line_was_empty = message.trim().is_empty();
450            return Ok(());
451        }
452        self.line(MessageStyle::User, message)
453    }
454
455    /// Write styled text without a trailing newline
456    pub fn inline_with_style(&mut self, style: MessageStyle, text: &str) -> Result<()> {
457        self.flush_compact_command_group();
458        if !self.should_render_style(style) {
459            return Ok(());
460        }
461        if let Some(sink) = &mut self.sink {
462            sink.write_inline(style.style(), text, Self::message_kind(style));
463            return Ok(());
464        }
465        let ansi_style = style.style();
466        if self.color {
467            write!(self.writer, "{ansi_style}{text}{Reset}")?;
468        } else {
469            write!(self.writer, "{text}")?;
470        }
471        self.writer.flush()?;
472        Ok(())
473    }
474
475    /// Write a line with an explicit style
476    pub fn line_with_style(&mut self, style: Style, text: &str) -> Result<()> {
477        self.line_with_override_style(MessageStyle::Info, style, text)
478    }
479
480    /// Write a line with a custom style while preserving the logical message kind.
481    #[track_caller]
482    pub fn line_with_override_style(&mut self, fallback: MessageStyle, style: Style, text: &str) -> Result<()> {
483        self.flush_compact_command_group();
484        let tool_output_id = self.pending_tool_output_anchor.take();
485        if !self.should_render_style(fallback) {
486            return Ok(());
487        }
488        if matches!(fallback, MessageStyle::Error | MessageStyle::ToolError | MessageStyle::Warning) {
489            return self.legacy_diagnostic(fallback, text);
490        }
491        let kind = Self::message_kind(fallback);
492        let indent = self.indent_for_style(fallback);
493        if let Some(sink) = &mut self.sink {
494            sink.write_multiline_with_transcript(style, indent, text, kind, true, tool_output_id)?;
495            self.last_line_was_empty = text.trim().is_empty();
496            return Ok(());
497        }
498        let mut combined;
499        let display = if !indent.is_empty() && !text.is_empty() {
500            combined = String::with_capacity(indent.len() + text.len());
501            combined.push_str(indent);
502            combined.push_str(text);
503            combined.as_str()
504        } else {
505            text
506        };
507        if self.color {
508            writeln!(self.writer, "{style}{display}{Reset}")?;
509        } else {
510            writeln!(self.writer, "{display}")?;
511        }
512        self.writer.flush()?;
513        transcript::append(display);
514        self.last_line_was_empty = text.trim().is_empty();
515        Ok(())
516    }
517
518    /// Write an empty line only if the previous line was not empty
519    pub fn line_if_not_empty(&mut self, style: MessageStyle) -> Result<()> {
520        if !self.was_previous_line_empty() {
521            self.line(style, "")
522        } else {
523            Ok(())
524        }
525    }
526
527    /// Write a raw line without styling
528    pub fn raw_line(&mut self, text: &str) -> Result<()> {
529        self.flush_compact_command_group();
530        writeln!(self.writer, "{text}")?;
531        self.writer.flush()?;
532        transcript::append(text);
533        Ok(())
534    }
535
536    pub fn render_token_delta(&mut self, delta: &str) -> Result<()> {
537        self.inline_with_style(MessageStyle::Response, delta)
538    }
539
540    pub fn stream_markdown_response(&mut self, text: &str, previous_line_count: usize) -> Result<usize> {
541        // Strip ANSI codes from agent response to prevent interference with markdown rendering
542        let text = crate::utils::ansi_parser::strip_ansi(text);
543        let text = &text;
544
545        let styles = theme::active_styles();
546        let style = MessageStyle::Response;
547        let base_style = style.style();
548        let indent = style.indent();
549        if let Some(sink) = &mut self.sink {
550            // Read terminal width fresh so tables adapt to resizes.
551            if sink.table_max_width_override.is_none()
552                && let Some((w, _)) = crate::utils::tty::terminal_size()
553            {
554                sink.table_max_width = Some(w as usize);
555            }
556            let table_max_width = sink.table_content_width(Self::message_kind(style), indent);
557            let (prepared, plain_lines, last_empty) =
558                sink.prepare_markdown_lines_with_table_width(text, indent, base_style, true, true, table_max_width);
559            let line_count = prepared.len();
560            sink.replace_inline_lines(previous_line_count, prepared, &plain_lines, Self::message_kind(style));
561            self.last_line_was_empty = last_empty;
562            return Ok(line_count);
563        }
564
565        let highlight_cfg = if self.highlight_config.enabled {
566            Some(&self.highlight_config)
567        } else {
568            None
569        };
570        let mut lines = render_markdown_to_lines_with_options(
571            text,
572            base_style,
573            &styles,
574            highlight_cfg,
575            RenderMarkdownOptions::default(),
576        );
577        if lines.is_empty() {
578            lines.push(MarkdownLine::default());
579        }
580
581        Err(anyhow!("stream_markdown_response requires an inline sink"))
582    }
583
584    /// Finish a streamed response, stamping it when no turn is open.
585    ///
586    /// Streaming replaces the in-progress block per delta, so inside a turn the
587    /// footer is only marked here and emitted by
588    /// [`AnsiRenderer::finish_turn_message_timestamp`] once the turn ends;
589    /// intermediate responses stay unstamped and only the turn's final message
590    /// carries the clock. Outside a turn this stamps immediately. No-op without
591    /// an inline sink, when timestamps are disabled, or during transcript-batch
592    /// replay. The caller owns the "visible content was streamed" condition.
593    pub fn finish_streamed_response(&mut self) -> Result<()> {
594        let Some(sink) = self.sink.as_mut() else {
595            return Ok(());
596        };
597        if !self.show_message_timestamps || sink.in_transcript_batch() {
598            return Ok(());
599        }
600        if self.defer_turn_footer {
601            self.pending_response_footer = true;
602            return Ok(());
603        }
604        let indent = MessageStyle::Response.indent();
605        let status_style = theme::active_styles().status;
606        sink.append_response_timestamp_footer(status_style, indent)?;
607        self.last_line_was_empty = false;
608        Ok(())
609    }
610
611    /// Emit the single wall-clock footer for the turn that just completed.
612    ///
613    /// Called once at the turn boundary after the final agent message has been
614    /// rendered. Disarms deferral so the next out-of-turn response stamps
615    /// immediately again. A no-op when no response body was rendered, when
616    /// timestamps are disabled, or during transcript-batch replay.
617    pub fn finish_turn_message_timestamp(&mut self) -> Result<()> {
618        // Disarm before the early return: the session reuses one renderer, and
619        // a turn that rendered nothing must not leave later output deferring
620        // into a boundary that will never come.
621        self.defer_turn_footer = false;
622        if !self.pending_response_footer {
623            return Ok(());
624        }
625        self.pending_response_footer = false;
626        if !self.show_message_timestamps {
627            return Ok(());
628        }
629        let indent = MessageStyle::Response.indent();
630        if let Some(sink) = self.sink.as_mut() {
631            if sink.in_transcript_batch() {
632                return Ok(());
633            }
634            let status_style = theme::active_styles().status;
635            sink.append_response_timestamp_footer(status_style, indent)?;
636        } else {
637            self.write_response_timestamp_footer(indent)?;
638        }
639        self.last_line_was_empty = false;
640        Ok(())
641    }
642}