Skip to main content

vtcode_core/utils/ansi/
core.rs

1//! Renderer construction and display-state accessors.
2
3use super::*;
4
5use crate::config::ToolDisplayMode;
6use crate::config::loader::SyntaxHighlightingConfig;
7use crate::ui::tui::{InlineHandle, InlineMessageKind};
8use crate::utils::ansi_capabilities::AnsiCapabilities;
9use anstream::{AutoStream, ColorChoice};
10use std::io;
11use vtcode_commons::color_policy::{self, ColorOutputPolicySource};
12use vtcode_commons::ui_protocol::ToolOutputId;
13
14impl AnsiRenderer {
15    /// Create a new renderer for stdout
16    pub fn stdout() -> Self {
17        let mut capabilities = AnsiCapabilities::detect();
18        let policy = color_policy::current_color_output_policy();
19
20        if !policy.enabled {
21            capabilities.no_color = true;
22            capabilities.force_color = false;
23        } else if matches!(
24            policy.source,
25            ColorOutputPolicySource::CliColorAlways | ColorOutputPolicySource::ConfigOverride
26        ) {
27            capabilities.no_color = false;
28            capabilities.force_color = true;
29        }
30
31        let color = capabilities.supports_color();
32        let choice = if !color {
33            ColorChoice::Never
34        } else if matches!(
35            policy.source,
36            ColorOutputPolicySource::CliColorAlways | ColorOutputPolicySource::ConfigOverride
37        ) {
38            ColorChoice::Always
39        } else {
40            ColorChoice::Auto
41        };
42        Self {
43            writer: AutoStream::new(io::stdout(), choice),
44            buffer: String::with_capacity(1024),
45            color,
46            sink: None,
47            last_line_was_empty: false,
48            highlight_config: SyntaxHighlightingConfig::default(),
49            capabilities,
50            reasoning_visible: true,
51            screen_reader_mode: false,
52            show_diagnostics_in_transcript: false,
53            show_message_timestamps: true,
54            pending_response_footer: false,
55            defer_turn_footer: false,
56            turn_started_at: None,
57            tool_display_mode: ToolDisplayMode::Compact,
58            communication_style: vtcode_commons::ui_protocol::CommunicationStyle::Balanced,
59            diff_preview_mode: vtcode_commons::ui_protocol::DiffPreviewMode::Inline,
60            compact_command_group: None,
61            next_compact_group_id: 0,
62            pending_tool_output_anchor: None,
63            session_expand_anchor: None,
64            session_body: false,
65            diagnostic_sink: None,
66            diagnostic_history: std::collections::VecDeque::new(),
67        }
68    }
69
70    /// Create a renderer that forwards output to the inline UI session handle
71    pub fn with_inline_ui(handle: InlineHandle, highlight_config: SyntaxHighlightingConfig) -> Self {
72        let mut renderer = Self::stdout();
73        renderer.highlight_config = highlight_config.clone();
74        renderer.sink = Some(InlineSink::new(handle, highlight_config));
75        renderer.last_line_was_empty = false;
76        renderer
77    }
78
79    /// Own a presentation-only authentication wait on the interactive terminal.
80    #[cfg(feature = "tui")]
81    pub fn program_status_wait(
82        &self,
83        kind: vtcode_commons::program_status::InteractionKind,
84    ) -> Option<vtcode_ui::tui::core_tui::types::ProgramStatusWaitGuard> {
85        self.sink.as_ref().map(|sink| sink.handle.program_status_wait(kind))
86    }
87
88    /// Override the syntax highlighting configuration.
89    pub fn set_highlight_config(&mut self, config: SyntaxHighlightingConfig) {
90        if let Some(sink) = &mut self.sink {
91            sink.set_highlight_config(config.clone());
92        }
93        self.highlight_config = config;
94    }
95
96    /// Start buffering transcript lines for one batched UI append.
97    ///
98    /// Used by transcript reloads (resume, rewind) so the viewport paints the
99    /// final state once instead of scrolling through intermediate frames.
100    pub fn begin_transcript_batch(&mut self) {
101        if let Some(sink) = &mut self.sink {
102            sink.begin_transcript_batch();
103        }
104    }
105
106    /// Flush buffered transcript lines as a single UI command.
107    pub fn end_transcript_batch(&mut self) {
108        if let Some(sink) = &mut self.sink {
109            sink.end_transcript_batch();
110        }
111    }
112
113    /// Run `render` with transcript batching enabled.
114    ///
115    /// The batch is flushed even when `render` fails, so buffered lines never
116    /// leak into an unrelated later call.
117    pub fn transcript_batch<T>(&mut self, render: impl FnOnce(&mut Self) -> anyhow::Result<T>) -> anyhow::Result<T> {
118        self.begin_transcript_batch();
119        let result = render(self);
120        self.end_transcript_batch();
121        result
122    }
123
124    /// Associate the next summary line with a captured tool output block.
125    ///
126    /// This edge is UI-only. It is carried directly on the summary command so
127    /// repeated commands remain associated with their own captures even when
128    /// completions are interleaved.
129    pub fn set_next_tool_output_anchor(&mut self, id: ToolOutputId) {
130        self.pending_tool_output_anchor = Some(id);
131    }
132
133    /// Remember which capture a forthcoming exec-session expand notice should
134    /// open. Unlike [`Self::set_next_tool_output_anchor`] this survives body
135    /// lines and is consumed only when the notice is emitted.
136    pub fn set_session_expand_anchor(&mut self, id: ToolOutputId) {
137        self.session_expand_anchor = Some(id);
138    }
139
140    /// Take the pending session expand anchor, if any.
141    pub fn take_session_expand_anchor(&mut self) -> Option<ToolOutputId> {
142        self.session_expand_anchor.take()
143    }
144
145    /// Mark the upcoming stream body as an exec-session stdin/stdout capture
146    /// (dim + expand), even when the tool name alone would look like a launch.
147    pub fn set_session_body(&mut self, session_body: bool) {
148        self.session_body = session_body;
149    }
150
151    /// Whether the upcoming stream body should use the exec-session path.
152    pub fn session_body_active(&self) -> bool {
153        self.session_body
154    }
155
156    /// Check if the last line rendered was empty
157    pub fn was_previous_line_empty(&self) -> bool {
158        self.last_line_was_empty
159    }
160
161    pub(super) fn message_kind(style: MessageStyle) -> InlineMessageKind {
162        style.message_kind()
163    }
164
165    pub fn supports_streaming_markdown(&self) -> bool {
166        self.sink.is_some()
167    }
168
169    /// Determine whether the renderer is connected to the inline UI.
170    ///
171    /// Inline rendering uses the terminal session scrollback, so tool output should
172    /// avoid truncation that would otherwise be applied in compact CLI mode.
173    pub fn prefers_untruncated_output(&self) -> bool {
174        self.sink.is_some()
175    }
176
177    pub fn supports_inline_ui(&self) -> bool {
178        self.sink.is_some()
179    }
180
181    pub fn set_reasoning_visible(&mut self, visible: bool) {
182        self.reasoning_visible = visible;
183    }
184
185    pub fn reasoning_visible(&self) -> bool {
186        self.reasoning_visible
187    }
188
189    /// Whether rendered output is streamed into an inline TUI sink (as opposed to
190    /// written directly to a terminal writer).
191    pub fn writes_to_inline_sink(&self) -> bool {
192        self.sink.is_some()
193    }
194
195    pub fn set_screen_reader_mode(&mut self, enabled: bool) {
196        self.screen_reader_mode = enabled;
197    }
198
199    pub fn set_show_diagnostics_in_transcript(&mut self, enabled: bool) {
200        self.show_diagnostics_in_transcript = if cfg!(debug_assertions) { enabled } else { false };
201    }
202
203    /// Start a fresh turn: arm footer deferral and drop any pending footer left
204    /// by aborted output so it cannot leak into this turn's final message.
205    ///
206    /// The arm instant also brackets the turn's duration: the footer pairs the
207    /// wall clock with the elapsed time between this call and
208    /// [`AnsiRenderer::finish_turn_message_timestamp`].
209    pub fn begin_turn_message_timestamp(&mut self) {
210        self.pending_response_footer = false;
211        self.defer_turn_footer = true;
212        self.turn_started_at = Some(std::time::Instant::now());
213    }
214
215    /// Show one wall-clock footer under the turn's final agent response.
216    ///
217    /// Enabled by default so headless and unwired paths stay consistent;
218    /// sessions apply `ui.show_message_timestamps` through this setter.
219    pub fn set_show_message_timestamps(&mut self, enabled: bool) {
220        self.show_message_timestamps = enabled;
221    }
222
223    pub fn show_message_timestamps(&self) -> bool {
224        self.show_message_timestamps
225    }
226
227    pub fn set_tool_display_mode(&mut self, mode: ToolDisplayMode) {
228        self.flush_compact_command_group();
229        self.tool_display_mode = match mode {
230            ToolDisplayMode::Compact => ToolDisplayMode::Compact,
231            ToolDisplayMode::Expanded | ToolDisplayMode::Unknown => ToolDisplayMode::Expanded,
232        };
233    }
234
235    pub fn tool_display_mode(&self) -> ToolDisplayMode {
236        self.tool_display_mode
237    }
238
239    /// How much routine agent-internal failure chatter reaches the transcript.
240    /// Sessions apply `ui.communication_style` through this setter; unknown
241    /// future values resolve to `Balanced` via [`CommunicationStyle::resolve`](vtcode_commons::ui_protocol::CommunicationStyle::resolve).
242    pub fn set_communication_style(&mut self, style: vtcode_commons::ui_protocol::CommunicationStyle) {
243        self.communication_style = style.resolve();
244    }
245
246    pub fn communication_style(&self) -> vtcode_commons::ui_protocol::CommunicationStyle {
247        self.communication_style
248    }
249
250    /// Whether a failed result's evidence rows (inline stderr/critical-note
251    /// lines and the structured error block) paint beyond the owning tool
252    /// row's compact failed marker. Interactive transcripts keep only the
253    /// compact marker outside `Verbose`: hidden evidence stays in the
254    /// canonical tool-output event, the plain-text trail, and Review.
255    /// Headless output is its own surface, so evidence always paints there.
256    pub fn failure_evidence_visible(&self) -> bool {
257        !self.writes_to_inline_sink()
258            || matches!(self.communication_style(), vtcode_commons::ui_protocol::CommunicationStyle::Verbose)
259    }
260
261    /// Whether once-per-turn harness coaching notices (verification
262    /// re-run prompts, repeated-evidence nudges) paint in the interactive
263    /// transcript. These always reach the model as system messages; the
264    /// transcript line is user-informational only, so `Balanced` and `Quiet`
265    /// keep it out while `Verbose` and headless output keep it.
266    pub fn loop_notices_visible(&self) -> bool {
267        use vtcode_commons::ui_protocol::CommunicationStyle;
268        !self.writes_to_inline_sink() || matches!(self.communication_style(), CommunicationStyle::Verbose)
269    }
270
271    /// Whether a tool result's attention rows (inline `⚠ warning` lines) paint
272    /// for this tool call. These are outcome-adjacent signals rather than
273    /// failure evidence, so command tools keep them under the default style;
274    /// failed-result evidence uses [`Self::failure_evidence_visible`] instead.
275    pub fn inline_failure_extras_visible(&self, is_command_tool: bool) -> bool {
276        use vtcode_commons::ui_protocol::CommunicationStyle;
277        match self.communication_style.resolve() {
278            CommunicationStyle::Verbose => true,
279            CommunicationStyle::Balanced => is_command_tool,
280            // `resolve` maps `Unknown` to `Balanced`; the arm below only
281            // keeps the decision total.
282            CommunicationStyle::Quiet | CommunicationStyle::Unknown => false,
283        }
284    }
285
286    /// Whether per-call tool transitions render in compact (grouped) form.
287    ///
288    /// Single source of truth for the compact-vs-expanded decision so every
289    /// call site agrees; the stored mode is already normalized to
290    /// `Compact`/`Expanded` by [`Self::set_tool_display_mode`].
291    pub fn is_compact_display(&self) -> bool {
292        self.tool_display_mode == ToolDisplayMode::Compact
293    }
294
295    pub fn set_diff_preview_mode(&mut self, mode: vtcode_commons::ui_protocol::DiffPreviewMode) {
296        self.diff_preview_mode = mode;
297    }
298
299    /// Attach a completed-edit review payload so the TUI can expand on demand.
300    pub fn record_diff_review(&self, anchor: vtcode_commons::ui_protocol::DiffReviewAnchor) {
301        if let Some(sink) = &self.sink {
302            sink.handle.record_diff_review(anchor);
303        }
304    }
305
306    pub fn diff_preview_mode(&self) -> vtcode_commons::ui_protocol::DiffPreviewMode {
307        self.diff_preview_mode
308    }
309
310    pub fn toggle_tool_display_mode(&mut self) -> ToolDisplayMode {
311        self.flush_compact_command_group();
312        let next = match self.tool_display_mode {
313            ToolDisplayMode::Expanded | ToolDisplayMode::Unknown => ToolDisplayMode::Compact,
314            ToolDisplayMode::Compact => ToolDisplayMode::Expanded,
315        };
316        self.tool_display_mode = next;
317        next
318    }
319}