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 256-color output is supported
185    pub fn supports_256_colors(&self) -> bool {
186        self.capabilities.supports_256_colors()
187    }
188
189    /// Check if true color (24-bit) output is supported
190    pub fn supports_true_color(&self) -> bool {
191        self.capabilities.supports_true_color()
192    }
193
194    pub fn show_list_modal(
195        &mut self,
196        title: &str,
197        lines: Vec<String>,
198        items: Vec<InlineListItem>,
199        selected: Option<InlineListSelection>,
200        search: Option<InlineListSearchConfig>,
201    ) {
202        if let Some(sink) = &self.sink {
203            sink.show_list_modal(title.into(), lines, items, selected, search);
204        }
205    }
206
207    pub fn show_list_modal_with_footer(
208        &mut self,
209        title: &str,
210        lines: Vec<String>,
211        items: Vec<InlineListItem>,
212        selected: Option<InlineListSelection>,
213        search: Option<InlineListSearchConfig>,
214        footer_hint: Option<String>,
215    ) {
216        self.show_list_modal_with_status(title, lines, items, selected, search, footer_hint, None);
217    }
218
219    /// Show a list modal with an optional status strip (last action feedback).
220    pub fn show_list_modal_with_status(
221        &mut self,
222        title: &str,
223        lines: Vec<String>,
224        items: Vec<InlineListItem>,
225        selected: Option<InlineListSelection>,
226        search: Option<InlineListSearchConfig>,
227        footer_hint: Option<String>,
228        status: Option<vtcode_commons::ui_protocol::InlineStatus>,
229    ) {
230        if let Some(sink) = &self.sink {
231            sink.show_list_modal_with_status(title.into(), lines, items, selected, search, footer_hint, status);
232        }
233    }
234
235    pub fn show_secure_prompt_modal(&mut self, title: &str, lines: Vec<String>, prompt_label: String) {
236        if let Some(sink) = &self.sink {
237            sink.show_secure_prompt_modal(title.into(), lines, prompt_label);
238        }
239    }
240
241    pub fn close_modal(&mut self) {
242        if let Some(sink) = &self.sink {
243            sink.close_modal();
244        }
245    }
246
247    pub fn clear_screen(&mut self) {
248        self.flush_compact_command_group();
249        if let Some(sink) = &self.sink {
250            sink.handle.clear_screen();
251        }
252    }
253
254    /// Push text into the buffer
255    pub fn push(&mut self, text: &str) {
256        self.buffer.push_str(text);
257    }
258
259    /// Flush the buffer with the given style
260    #[track_caller]
261    pub fn flush(&mut self, style: MessageStyle) -> Result<()> {
262        self.flush_compact_command_group();
263        if !self.should_render_style(style) {
264            self.buffer.clear();
265            return Ok(());
266        }
267        if matches!(style, MessageStyle::Error | MessageStyle::ToolError | MessageStyle::Warning) {
268            let text = std::mem::take(&mut self.buffer);
269            return self.legacy_diagnostic(style, &text);
270        }
271        let indent = self.indent_for_style(style);
272        if let Some(sink) = &mut self.sink {
273            // Track if this line is empty
274            self.last_line_was_empty = self.buffer.is_empty() && indent.is_empty();
275            sink.write_line(style.style(), indent, &self.buffer, Self::message_kind(style))?;
276            self.buffer.clear();
277            return Ok(());
278        }
279        let style = style.style();
280        if self.color {
281            writeln!(self.writer, "{style}{}{Reset}", self.buffer)?;
282        } else {
283            writeln!(self.writer, "{}", self.buffer)?;
284        }
285        self.writer.flush()?;
286        transcript::append(&self.buffer);
287        // Track if this line is empty
288        self.last_line_was_empty = self.buffer.is_empty();
289        self.buffer.clear();
290        Ok(())
291    }
292
293    /// Convenience for writing a single line
294    #[track_caller]
295    pub fn line(&mut self, style: MessageStyle, text: &str) -> Result<()> {
296        self.flush_compact_command_group();
297        if !self.should_render_style(style) {
298            return Ok(());
299        }
300        if matches!(style, MessageStyle::Error | MessageStyle::ToolError | MessageStyle::Warning) {
301            return self.legacy_diagnostic(style, text);
302        }
303        if matches!(style, MessageStyle::Response | MessageStyle::Reasoning | MessageStyle::ReasoningEmphasis) {
304            return self.render_markdown(style, text);
305        }
306        if matches!(style, MessageStyle::Output | MessageStyle::ToolOutput) {
307            let stripped = crate::utils::ansi_parser::strip_ansi(text);
308            self.buffer.clear();
309            if looks_like_diff(&stripped) {
310                self.buffer.push_str("```diff\n");
311            } else {
312                self.buffer.push_str("```\n");
313            }
314            self.buffer.push_str(&stripped);
315            self.buffer.push_str("\n```");
316            let fenced = std::mem::take(&mut self.buffer);
317            return self.render_markdown(style, &fenced);
318        }
319        if matches!(style, MessageStyle::ToolDetail) {
320            if contains_markdown_fence(text) {
321                let stripped = crate::utils::ansi_parser::strip_ansi(text);
322                return self.render_markdown(style, &stripped);
323            }
324            if looks_like_diff(text) {
325                let stripped = crate::utils::ansi_parser::strip_ansi(text);
326                self.buffer.clear();
327                self.buffer.push_str("```diff\n");
328                self.buffer.push_str(&stripped);
329                self.buffer.push_str("\n```");
330                let fenced = std::mem::take(&mut self.buffer);
331                return self.render_markdown(style, &fenced);
332            }
333        }
334        let indent = style.indent();
335        let dont_split = matches!(style, MessageStyle::Tool | MessageStyle::ToolDetail);
336
337        if let Some(sink) = &mut self.sink {
338            sink.write_multiline_with_transcript(style.style(), indent, text, Self::message_kind(style), true, None)?;
339            return Ok(());
340        }
341
342        if text.contains('\n') && !dont_split {
343            for line in text.lines() {
344                self.buffer.clear();
345                if !indent.is_empty() && !line.is_empty() {
346                    self.buffer.push_str(indent);
347                }
348                self.buffer.push_str(line);
349                self.flush(style)?;
350            }
351            Ok(())
352        } else {
353            self.buffer.clear();
354            if !indent.is_empty() && !text.is_empty() {
355                self.buffer.push_str(indent);
356            }
357            self.buffer.push_str(text);
358            self.flush(style)
359        }
360    }
361
362    /// Write a continuation line that joins an existing Pty block.
363    ///
364    /// Sends the text as `InlineMessageKind::Pty` through
365    /// `write_multiline_with_transcript` so the TUI reflow renders it
366    /// with the same 2-space block prefix and styling as the PTY output.
367    pub fn pty_continuation_line(&mut self, text: &str) -> Result<()> {
368        self.flush_compact_command_group();
369        let style = MessageStyle::ToolOutput;
370        let indent = style.indent();
371        let kind = Self::message_kind(style);
372        if let Some(sink) = &mut self.sink {
373            sink.write_multiline_with_transcript(style.style(), indent, text, kind, true, None)?;
374            return Ok(());
375        }
376        self.buffer.clear();
377        if !indent.is_empty() && !text.is_empty() {
378            self.buffer.push_str(indent);
379        }
380        self.buffer.push_str(text);
381        self.flush(style)
382    }
383
384    /// Write a URL as a full, clickable line using OSC 8 hyperlinks.
385    ///
386    /// The URL is rendered on its own line so that terminal emulators can
387    /// detect and activate it for click-to-open behaviour.
388    pub fn hyperlink_line(&mut self, style: MessageStyle, url: &str) -> Result<()> {
389        self.flush_compact_command_group();
390        if !self.should_render_style(style) {
391            return Ok(());
392        }
393        let indent = style.indent();
394        if let Some(sink) = &mut self.sink {
395            let linked = format!(
396                "{}{}{}",
397                vtcode_commons::ansi_codes::hyperlink_open(url),
398                url,
399                vtcode_commons::ansi_codes::hyperlink_close(),
400            );
401            sink.write_multiline_with_transcript(
402                style.style(),
403                indent,
404                &linked,
405                Self::message_kind(style),
406                true,
407                None,
408            )?;
409            self.last_line_was_empty = false;
410            return Ok(());
411        }
412        self.buffer.clear();
413        if !indent.is_empty() {
414            self.buffer.push_str(indent);
415        }
416        self.buffer.push_str(&vtcode_commons::ansi_codes::hyperlink_open(url));
417        self.buffer.push_str(url);
418        self.buffer.push_str(&vtcode_commons::ansi_codes::hyperlink_close());
419        let ansi_style = style.style();
420        if self.color {
421            writeln!(self.writer, "{ansi_style}{}{Reset}", self.buffer)?;
422        } else {
423            writeln!(self.writer, "{}", self.buffer)?;
424        }
425        self.writer.flush()?;
426        transcript::append(url);
427        self.last_line_was_empty = false;
428        self.buffer.clear();
429        Ok(())
430    }
431
432    /// Append a large pasted user message as a placeholder in inline UI.
433    pub fn append_paste_placeholder(&mut self, message: &str, line_count: usize) -> Result<()> {
434        self.flush_compact_command_group();
435        if let Some(sink) = &self.sink {
436            sink.handle
437                .append_pasted_message(InlineMessageKind::User, message.to_string(), line_count);
438            transcript::append(message);
439            self.last_line_was_empty = message.trim().is_empty();
440            return Ok(());
441        }
442        self.line(MessageStyle::User, message)
443    }
444
445    /// Write styled text without a trailing newline
446    pub fn inline_with_style(&mut self, style: MessageStyle, text: &str) -> Result<()> {
447        self.flush_compact_command_group();
448        if !self.should_render_style(style) {
449            return Ok(());
450        }
451        if let Some(sink) = &mut self.sink {
452            sink.write_inline(style.style(), text, Self::message_kind(style));
453            return Ok(());
454        }
455        let ansi_style = style.style();
456        if self.color {
457            write!(self.writer, "{ansi_style}{text}{Reset}")?;
458        } else {
459            write!(self.writer, "{text}")?;
460        }
461        self.writer.flush()?;
462        Ok(())
463    }
464
465    /// Write a line with an explicit style
466    pub fn line_with_style(&mut self, style: Style, text: &str) -> Result<()> {
467        self.line_with_override_style(MessageStyle::Info, style, text)
468    }
469
470    /// Write a line with a custom style while preserving the logical message kind.
471    #[track_caller]
472    pub fn line_with_override_style(&mut self, fallback: MessageStyle, style: Style, text: &str) -> Result<()> {
473        self.flush_compact_command_group();
474        let tool_output_id = self.pending_tool_output_anchor.take();
475        if !self.should_render_style(fallback) {
476            return Ok(());
477        }
478        if matches!(fallback, MessageStyle::Error | MessageStyle::ToolError | MessageStyle::Warning) {
479            return self.legacy_diagnostic(fallback, text);
480        }
481        let kind = Self::message_kind(fallback);
482        let indent = self.indent_for_style(fallback);
483        if let Some(sink) = &mut self.sink {
484            sink.write_multiline_with_transcript(style, indent, text, kind, true, tool_output_id)?;
485            self.last_line_was_empty = text.trim().is_empty();
486            return Ok(());
487        }
488        let mut combined;
489        let display = if !indent.is_empty() && !text.is_empty() {
490            combined = String::with_capacity(indent.len() + text.len());
491            combined.push_str(indent);
492            combined.push_str(text);
493            combined.as_str()
494        } else {
495            text
496        };
497        if self.color {
498            writeln!(self.writer, "{style}{display}{Reset}")?;
499        } else {
500            writeln!(self.writer, "{display}")?;
501        }
502        self.writer.flush()?;
503        transcript::append(display);
504        self.last_line_was_empty = text.trim().is_empty();
505        Ok(())
506    }
507
508    /// Write an empty line only if the previous line was not empty
509    pub fn line_if_not_empty(&mut self, style: MessageStyle) -> Result<()> {
510        if !self.was_previous_line_empty() {
511            self.line(style, "")
512        } else {
513            Ok(())
514        }
515    }
516
517    /// Write a raw line without styling
518    pub fn raw_line(&mut self, text: &str) -> Result<()> {
519        self.flush_compact_command_group();
520        writeln!(self.writer, "{text}")?;
521        self.writer.flush()?;
522        transcript::append(text);
523        Ok(())
524    }
525
526    pub fn render_token_delta(&mut self, delta: &str) -> Result<()> {
527        self.inline_with_style(MessageStyle::Response, delta)
528    }
529
530    pub fn stream_markdown_response(&mut self, text: &str, previous_line_count: usize) -> Result<usize> {
531        // Strip ANSI codes from agent response to prevent interference with markdown rendering
532        let text = crate::utils::ansi_parser::strip_ansi(text);
533        let text = &text;
534
535        let styles = theme::active_styles();
536        let style = MessageStyle::Response;
537        let base_style = style.style();
538        let indent = style.indent();
539        if let Some(sink) = &mut self.sink {
540            // Read terminal width fresh so tables adapt to resizes.
541            if sink.table_max_width_override.is_none()
542                && let Some((w, _)) = crate::utils::tty::terminal_size()
543            {
544                sink.table_max_width = Some(w as usize);
545            }
546            let table_max_width = sink.table_content_width(Self::message_kind(style), indent);
547            let (prepared, plain_lines, last_empty) =
548                sink.prepare_markdown_lines_with_table_width(text, indent, base_style, true, true, table_max_width);
549            let line_count = prepared.len();
550            sink.replace_inline_lines(previous_line_count, prepared, &plain_lines, Self::message_kind(style));
551            self.last_line_was_empty = last_empty;
552            return Ok(line_count);
553        }
554
555        let highlight_cfg = if self.highlight_config.enabled {
556            Some(&self.highlight_config)
557        } else {
558            None
559        };
560        let mut lines = render_markdown_to_lines_with_options(
561            text,
562            base_style,
563            &styles,
564            highlight_cfg,
565            RenderMarkdownOptions::default(),
566        );
567        if lines.is_empty() {
568            lines.push(MarkdownLine::default());
569        }
570
571        Err(anyhow!("stream_markdown_response requires an inline sink"))
572    }
573
574    /// Finish a streamed response, stamping it when no turn is open.
575    ///
576    /// Streaming replaces the in-progress block per delta, so inside a turn the
577    /// footer is only marked here and emitted by
578    /// [`AnsiRenderer::finish_turn_message_timestamp`] once the turn ends;
579    /// intermediate responses stay unstamped and only the turn's final message
580    /// carries the clock. Outside a turn this stamps immediately. No-op without
581    /// an inline sink, when timestamps are disabled, or during transcript-batch
582    /// replay. The caller owns the "visible content was streamed" condition.
583    pub fn finish_streamed_response(&mut self) -> Result<()> {
584        let Some(sink) = self.sink.as_mut() else {
585            return Ok(());
586        };
587        if !self.show_message_timestamps || sink.in_transcript_batch() {
588            return Ok(());
589        }
590        if self.defer_turn_footer {
591            self.pending_response_footer = true;
592            return Ok(());
593        }
594        let indent = MessageStyle::Response.indent();
595        let status_style = theme::active_styles().status;
596        sink.append_response_timestamp_footer(status_style, indent, None)?;
597        self.last_line_was_empty = false;
598        Ok(())
599    }
600
601    /// Emit the single wall-clock footer for the turn that just completed.
602    ///
603    /// Called once at the turn boundary after the final agent message has been
604    /// rendered. Disarms deferral so the next out-of-turn response stamps
605    /// immediately again. The elapsed half of the footer measures the armed
606    /// turn bracket (`begin_turn_message_timestamp` to here). A no-op when no
607    /// response body was rendered, when timestamps are disabled, or during
608    /// transcript-batch replay.
609    pub fn finish_turn_message_timestamp(&mut self) -> Result<()> {
610        // Disarm before the early return: the session reuses one renderer, and
611        // a turn that rendered nothing must not leave later output deferring
612        // into a boundary that will never come.
613        self.defer_turn_footer = false;
614        let elapsed = self.turn_started_at.take().map(|started| started.elapsed());
615        if !self.pending_response_footer {
616            return Ok(());
617        }
618        self.pending_response_footer = false;
619        if !self.show_message_timestamps {
620            return Ok(());
621        }
622        let indent = MessageStyle::Response.indent();
623        if let Some(sink) = self.sink.as_mut() {
624            if sink.in_transcript_batch() {
625                return Ok(());
626            }
627            let status_style = theme::active_styles().status;
628            sink.append_response_timestamp_footer(status_style, indent, elapsed)?;
629        } else {
630            self.write_response_timestamp_footer(indent, elapsed)?;
631        }
632        self.last_line_was_empty = false;
633        Ok(())
634    }
635}