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