Skip to main content

vtcode_ui/tui/core_tui/session/
header.rs

1use std::fmt::Write;
2use std::sync::Arc;
3
4use ratatui::{
5    style::{Color, Modifier, Style},
6    text::{Line, Span},
7    widgets::{Block, Paragraph, Wrap},
8};
9use unicode_segmentation::UnicodeSegmentation;
10
11use crate::tui::config::constants::ui;
12use crate::tui::core_tui::blocked_status;
13use crate::tui::core_tui::style::convert_style;
14
15use super::super::types::{InlineHeaderContext, InlineHeaderHighlight};
16use super::terminal_capabilities;
17use super::utils::line_truncation::truncate_line_with_ellipsis_if_overflow;
18use super::{Session, ratatui_color_from_ansi, ratatui_style_from_inline};
19
20pub(crate) fn ultrafast_badge_style(colors_enabled: bool, safe_colors_only: bool, bold_is_bright: bool) -> Style {
21    let mut style = Style::default().remove_modifier(Modifier::DIM | Modifier::REVERSED);
22    style = if !colors_enabled {
23        style.fg(Color::Reset).bg(Color::Reset).add_modifier(Modifier::REVERSED)
24    } else if safe_colors_only {
25        style.fg(Color::Black).bg(Color::Yellow)
26    } else {
27        // Black text on the premium #D99A4E fill exceeds WCAG AAA (7:1).
28        style.fg(Color::Rgb(0, 0, 0)).bg(Color::Rgb(0xD9, 0x9A, 0x4E))
29    };
30    if bold_is_bright {
31        style.remove_modifier(Modifier::BOLD)
32    } else {
33        style.add_modifier(Modifier::BOLD)
34    }
35}
36
37fn clean_reasoning_text(text: &str) -> String {
38    vtcode_commons::formatting::clean_reasoning_text(text)
39}
40
41fn capitalize_first_letter(s: &str) -> String {
42    let mut chars = s.chars();
43    match chars.next() {
44        None => String::new(),
45        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
46    }
47}
48
49fn format_model_summary_label(model: &str) -> String {
50    model.split('-').map(capitalize_first_letter).collect::<Vec<_>>().join("-")
51}
52
53pub(crate) fn primary_agent_header_label(name: Option<&str>) -> String {
54    let Some(name) = name.map(str::trim).filter(|name| !name.is_empty()) else {
55        return "Build".to_string();
56    };
57    format_model_summary_label(name)
58}
59
60fn compact_context_window_label(context_window_size: usize) -> String {
61    if context_window_size >= 1_000_000 {
62        format!("{}M", context_window_size / 1_000_000)
63    } else if context_window_size >= 1_000 {
64        format!("{}K", context_window_size / 1_000)
65    } else {
66        context_window_size.to_string()
67    }
68}
69
70fn line_is_empty(spans: &[Span<'static>]) -> bool {
71    spans.len() == 1 && spans.first().is_some_and(|span| span.content.is_empty())
72}
73
74impl Session {
75    pub(crate) fn header_lines(&mut self) -> Arc<Vec<Line<'static>>> {
76        if let Some(cached) = &self.header_lines_cache {
77            return Arc::clone(cached);
78        }
79
80        let lines = if self.appearance.hide_header {
81            vec![self.header_block_title_for_width(self.transcript_width)]
82        } else {
83            vec![self.header_compact_line()]
84        };
85        let arc = Arc::new(lines);
86        self.header_lines_cache = Some(Arc::clone(&arc));
87        arc
88    }
89
90    /// Cached border-block title (rebuilt only when the header cache drops).
91    pub(crate) fn header_block_title_cached(&mut self) -> Line<'static> {
92        if let Some(title) = &self.header_block_title_cache {
93            return title.clone();
94        }
95        let title = self.header_block_title();
96        self.header_block_title_cache = Some(title.clone());
97        title
98    }
99
100    pub(crate) fn header_height_from_lines(&mut self, width: u16, lines: &[Line<'static>]) -> u16 {
101        if self.appearance.hide_header {
102            return 1;
103        }
104
105        if width == 0 {
106            return self.header_rows.max(ui::INLINE_HEADER_HEIGHT);
107        }
108
109        if let Some(&height) = self.header_height_cache.get(&width) {
110            return height;
111        }
112
113        let paragraph = self.build_header_paragraph(lines);
114        let measured = paragraph.line_count(width);
115        let resolved = u16::try_from(measured).unwrap_or(u16::MAX);
116        // Limit to max 3 lines to accommodate suggestions
117        let resolved = resolved.clamp(ui::INLINE_HEADER_HEIGHT, 3);
118        self.header_height_cache.insert(width, resolved);
119        resolved
120    }
121
122    pub(crate) fn build_header_paragraph(&self, lines: &[Line<'static>]) -> Paragraph<'static> {
123        let text_style = self.header_primary_style().add_modifier(Modifier::DIM);
124
125        if self.appearance.hide_header {
126            return Paragraph::new(lines.to_vec()).style(text_style).wrap(Wrap { trim: true });
127        }
128
129        let mut border_style = Style::default();
130        if let Some(accent) = self.theme.tool_accent.or(self.theme.primary).or(self.theme.foreground) {
131            border_style = border_style.fg(ratatui_color_from_ansi(accent));
132        }
133        let text_style = self.header_primary_style().add_modifier(Modifier::DIM);
134        let block = Block::bordered()
135            .title(self.header_block_title())
136            .border_set(terminal_capabilities::get_border_set())
137            .border_style(border_style)
138            .style(self.styles.default_style());
139
140        Paragraph::new(lines.to_vec())
141            .style(text_style)
142            .wrap(Wrap { trim: true })
143            .block(block)
144    }
145
146    #[cfg(test)]
147    pub(crate) fn header_height_for_width(&mut self, width: u16) -> u16 {
148        let lines = self.header_lines();
149        self.header_height_from_lines(width, lines.as_slice())
150    }
151
152    fn header_block_title(&self) -> Line<'static> {
153        self.header_block_title_for_width(0)
154    }
155
156    fn header_block_title_for_width(&self, width: u16) -> Line<'static> {
157        let fallback = InlineHeaderContext::default();
158        let version = if self.header_context.version.trim().is_empty() {
159            fallback.version
160        } else {
161            self.header_context.version.clone()
162        };
163
164        let app_name = if self.header_context.app_name.trim().is_empty() {
165            ui::HEADER_VERSION_PREFIX
166        } else {
167            self.header_context.app_name.trim()
168        };
169        let prompt = format!("{}{}", ui::HEADER_VERSION_PROMPT, app_name);
170        let version_text =
171            format!(" {}{}{}", ui::HEADER_VERSION_LEFT_DELIMITER, version.trim(), ui::HEADER_VERSION_RIGHT_DELIMITER);
172
173        let prompt_style = self.section_title_style();
174        let version_style = self.header_secondary_style().add_modifier(Modifier::DIM);
175
176        let mut spans = vec![
177            Span::styled(prompt, prompt_style),
178            Span::styled(version_text, version_style),
179        ];
180
181        if self.appearance.hide_header && width > 0 {
182            let right_spans = self.header_compact_right_spans();
183            if right_spans.is_empty() {
184                return Line::from(spans);
185            }
186
187            let left_width = spans.iter().map(Span::width).sum::<usize>();
188            let summary_width = right_spans.iter().map(Span::width).sum::<usize>();
189            let available_width = usize::from(width);
190            let spacer_width = available_width.saturating_sub(left_width.saturating_add(summary_width)).max(1);
191            spans.push(Span::raw(" ".repeat(spacer_width)));
192            spans.extend(right_spans);
193        }
194
195        let line = Line::from(spans);
196        if width > 0 {
197            truncate_line_with_ellipsis_if_overflow(line, usize::from(width))
198        } else {
199            line
200        }
201    }
202
203    fn header_compact_right_spans(&self) -> Vec<Span<'static>> {
204        let mut spans = Vec::new();
205        let agent_label = primary_agent_header_label(self.header_context.primary_agent.as_deref());
206        let model_summary_spans = self.header_compact_model_summary_spans();
207        if !agent_label.trim().is_empty() {
208            let fallback = self.theme.primary.map(ratatui_color_from_ansi).unwrap_or(Color::LightMagenta);
209            let agent_style =
210                super::super::style::agent_color_style(self.header_context.primary_agent_color.as_deref(), fallback);
211            spans.push(Span::styled(agent_label, agent_style));
212        }
213
214        if !spans.is_empty() && !model_summary_spans.is_empty() {
215            spans.push(Span::styled(" · ".to_owned(), self.header_secondary_style()));
216        }
217        spans.extend(model_summary_spans);
218
219        spans
220    }
221
222    fn header_compact_model_summary_spans(&self) -> Vec<Span<'static>> {
223        let provider = self.header_provider_short_value();
224        let model = self.header_model_short_value();
225        let reasoning = self.header_reasoning_short_value();
226        let mut spans = Vec::new();
227        let mut provider_model_parts = Vec::new();
228
229        match (
230            !provider.is_empty() && !provider.eq_ignore_ascii_case(ui::HEADER_UNKNOWN_PLACEHOLDER),
231            !model.is_empty() && !model.eq_ignore_ascii_case(ui::HEADER_UNKNOWN_PLACEHOLDER),
232        ) {
233            (true, true) => provider_model_parts.push(format!(
234                "{} {}",
235                capitalize_first_letter(&provider),
236                format_model_summary_label(&model)
237            )),
238            (true, false) => provider_model_parts.push(capitalize_first_letter(&provider)),
239            (false, true) => provider_model_parts.push(format_model_summary_label(&model)),
240            (false, false) => {}
241        }
242
243        if let Some(summary) = (!provider_model_parts.is_empty()).then(|| provider_model_parts.join(" ")) {
244            spans.push(Span::styled(summary, self.header_secondary_style().add_modifier(Modifier::DIM)));
245        }
246
247        if !reasoning.is_empty() && !reasoning.eq_ignore_ascii_case(ui::HEADER_UNKNOWN_PLACEHOLDER) {
248            if !spans.is_empty() {
249                spans.push(Span::styled(" · ".to_owned(), self.header_secondary_style()));
250            }
251            let value_style = self.header_secondary_style().add_modifier(Modifier::ITALIC);
252            spans.push(Span::styled(reasoning, value_style));
253        }
254
255        if let Some(tier) = self.header_service_tier_short_value() {
256            if !spans.is_empty() {
257                spans.push(Span::styled(" · ".to_owned(), self.header_secondary_style()));
258            }
259            spans.push(self.header_service_tier_span(&tier));
260        }
261
262        if self.header_computer_use_short_value().is_some() {
263            if !spans.is_empty() {
264                spans.push(Span::styled(" · ".to_owned(), self.header_secondary_style()));
265            }
266            spans.push(self.header_computer_use_span());
267        }
268
269        spans
270    }
271
272    pub(crate) fn header_title_line(&self) -> Line<'static> {
273        // First line: badge-style provider + model + reasoning summary
274        let mut spans = Vec::new();
275
276        let provider = self.header_provider_short_value();
277        let model = self.header_model_short_value();
278        let reasoning = self.header_reasoning_short_value();
279
280        if !provider.is_empty() {
281            let capitalized_provider = capitalize_first_letter(&provider);
282            let mut style = self.header_primary_style();
283            style = style.add_modifier(Modifier::BOLD);
284            spans.push(Span::styled(capitalized_provider, style));
285        }
286
287        if !model.is_empty() {
288            if !spans.is_empty() {
289                spans.push(Span::raw(" "));
290            }
291            let mut style = self.header_primary_style();
292            style = style.add_modifier(Modifier::ITALIC);
293            spans.push(Span::styled(model, style));
294        }
295
296        if !reasoning.is_empty() {
297            if !spans.is_empty() {
298                spans.push(Span::raw(" "));
299            }
300            let mut style = self.header_secondary_style();
301            style = style.add_modifier(Modifier::ITALIC | Modifier::DIM);
302
303            if let Some(stage) = &self.header_context.reasoning_stage {
304                let mut stage_style = style;
305                stage_style = stage_style.remove_modifier(Modifier::DIM).add_modifier(Modifier::BOLD);
306                spans.push(Span::styled(format!("[{stage}]"), stage_style));
307                spans.push(Span::raw(" "));
308            }
309
310            spans.push(Span::styled(reasoning.to_string(), style));
311        }
312
313        if let Some(tier) = self.header_service_tier_short_value() {
314            if !spans.is_empty() {
315                spans.push(Span::raw(" "));
316            }
317            spans.push(self.header_service_tier_span(&tier));
318        }
319
320        if self.header_computer_use_short_value().is_some() {
321            if !spans.is_empty() {
322                spans.push(Span::raw(" "));
323            }
324            spans.push(self.header_computer_use_span());
325        }
326
327        if spans.is_empty() {
328            spans.push(Span::raw(String::new()));
329        }
330
331        Line::from(spans)
332    }
333
334    fn header_compact_line(&self) -> Line<'static> {
335        let mut spans = self.header_title_line().spans;
336        if line_is_empty(&spans) {
337            spans.clear();
338        }
339
340        let mut meta_spans = self.header_meta_line().spans;
341        if line_is_empty(&meta_spans) {
342            meta_spans.clear();
343        }
344
345        let mut tail_spans = if self.should_show_suggestions() {
346            self.header_suggestions_line()
347        } else {
348            self.header_highlights_line()
349        }
350        .map(|line| line.spans)
351        .unwrap_or_default();
352
353        if line_is_empty(&tail_spans) {
354            tail_spans.clear();
355        }
356
357        let separator_style = self.header_secondary_style();
358        let separator = Span::styled(ui::HEADER_PRIMARY_SEPARATOR.to_owned(), separator_style);
359
360        let mut append_section = |section: &mut Vec<Span<'static>>| {
361            if section.is_empty() {
362                return;
363            }
364            if !spans.is_empty() {
365                spans.push(separator.clone());
366            }
367            spans.append(section);
368        };
369
370        append_section(&mut meta_spans);
371        append_section(&mut tail_spans);
372
373        if spans.is_empty() {
374            spans.push(Span::raw(String::new()));
375        }
376
377        Line::from(spans)
378    }
379
380    fn header_provider_value(&self) -> String {
381        let trimmed = self.header_context.provider.trim();
382        if trimmed.is_empty() {
383            InlineHeaderContext::default().provider
384        } else {
385            self.header_context.provider.clone()
386        }
387    }
388
389    fn header_model_value(&self) -> String {
390        let trimmed = self.header_context.model.trim();
391        if trimmed.is_empty() {
392            InlineHeaderContext::default().model
393        } else {
394            self.header_context.model.clone()
395        }
396    }
397
398    fn header_reasoning_value(&self) -> Option<String> {
399        let raw_reasoning = &self.header_context.reasoning;
400        let cleaned = clean_reasoning_text(raw_reasoning);
401        let trimmed = cleaned.trim();
402        let value = if trimmed.is_empty() {
403            InlineHeaderContext::default().reasoning
404        } else {
405            cleaned
406        };
407        if value.trim().is_empty() { None } else { Some(value) }
408    }
409
410    fn header_provider_short_value(&self) -> String {
411        let value = self.header_provider_value();
412        Self::strip_prefix(&value, ui::HEADER_PROVIDER_PREFIX).trim().to_owned()
413    }
414
415    fn header_model_short_value(&self) -> String {
416        let value = self.header_model_value();
417        let model = Self::strip_prefix(&value, ui::HEADER_MODEL_PREFIX).trim().to_owned();
418
419        match self.header_context.context_window_size {
420            Some(context_window_size) if context_window_size > 0 => {
421                format!("{} ({})", model, compact_context_window_label(context_window_size))
422            }
423            _ => model,
424        }
425    }
426
427    fn header_reasoning_short_value(&self) -> String {
428        let value = self.header_reasoning_value().unwrap_or_default();
429        Self::strip_prefix(&value, ui::HEADER_REASONING_PREFIX).trim().to_owned()
430    }
431
432    fn header_service_tier_short_value(&self) -> Option<String> {
433        let raw = self.header_context.service_tier.as_deref()?;
434        let tier = Self::strip_prefix(raw, ui::HEADER_SERVICE_TIER_PREFIX).trim();
435        (!tier.is_empty() && !tier.eq_ignore_ascii_case(ui::HEADER_UNKNOWN_PLACEHOLDER)).then(|| tier.to_owned())
436    }
437
438    pub(super) fn header_computer_use_short_value(&self) -> Option<String> {
439        let raw = self.header_context.computer_use.as_deref()?;
440        let state = Self::strip_prefix(raw, ui::HEADER_COMPUTER_USE_PREFIX).trim();
441        (!state.is_empty() && !state.eq_ignore_ascii_case(ui::HEADER_UNKNOWN_PLACEHOLDER)).then(|| state.to_owned())
442    }
443
444    /// Premium badge for the computer-use master switch. Presence means the
445    /// switch is on; the header has exactly one badge idiom, so an enabled
446    /// runtime borrows the same gold treatment as the premium speed tiers.
447    fn header_computer_use_span(&self) -> Span<'static> {
448        Span::styled(
449            " COMPUTER USE ",
450            ultrafast_badge_style(
451                vtcode_commons::color_policy::current_color_output_policy().enabled,
452                crate::theme::is_safe_colors_only(),
453                crate::theme::is_bold_bright_mode(),
454            ),
455        )
456    }
457
458    fn header_service_tier_span(&self, tier: &str) -> Span<'static> {
459        if tier.eq_ignore_ascii_case("ultrafast") || tier.eq_ignore_ascii_case("fast") {
460            Span::styled(
461                if tier.eq_ignore_ascii_case("fast") {
462                    " FAST "
463                } else {
464                    " ULTRAFAST "
465                },
466                ultrafast_badge_style(
467                    vtcode_commons::color_policy::current_color_output_policy().enabled,
468                    crate::theme::is_safe_colors_only(),
469                    crate::theme::is_bold_bright_mode(),
470                ),
471            )
472        } else {
473            Span::styled(capitalize_first_letter(tier), self.header_secondary_style())
474        }
475    }
476
477    pub fn header_chain_values(&self) -> Vec<String> {
478        let mut values = Vec::new();
479
480        for value in [
481            &self.header_context.tools,
482            &self.header_context.git,
483            &self.header_context.mcp,
484        ] {
485            let trimmed = value.trim();
486            if trimmed.is_empty() {
487                continue;
488            }
489
490            if trimmed.starts_with(ui::HEADER_TOOLS_PREFIX) || trimmed.starts_with(ui::HEADER_GIT_PREFIX) {
491                continue;
492            }
493
494            if let Some(body) = trimmed.strip_prefix(ui::HEADER_MCP_PREFIX) {
495                let body = body.trim();
496                if body.is_empty() || body.eq_ignore_ascii_case(ui::HEADER_UNKNOWN_PLACEHOLDER) {
497                    continue;
498                }
499                values.push(format!("MCP: {body}"));
500                continue;
501            }
502
503            values.push(trimmed.to_owned());
504        }
505
506        values
507    }
508
509    pub(crate) fn header_meta_line(&self) -> Line<'static> {
510        let mut spans = Vec::new();
511
512        let mut first_section = true;
513        let separator_style = self.header_secondary_style();
514
515        let push_badge = |spans: &mut Vec<Span<'static>>, text: String, style: Style, first: &mut bool| {
516            if !*first {
517                spans.push(Span::styled(ui::HEADER_SECONDARY_SEPARATOR.to_owned(), separator_style));
518            }
519            spans.push(Span::styled(text, style));
520            *first = false;
521        };
522
523        let agent_badge_color = self
524            .theme
525            .primary
526            .or(self.theme.foreground)
527            .map(ratatui_color_from_ansi)
528            .unwrap_or(Color::LightMagenta);
529        let agent_style = Style::default().fg(agent_badge_color).add_modifier(Modifier::BOLD);
530        push_badge(
531            &mut spans,
532            primary_agent_header_label(self.header_context.primary_agent.as_deref()),
533            agent_style,
534            &mut first_section,
535        );
536
537        // Show trust level badge
538        let trust_value = self.header_context.workspace_trust.to_lowercase();
539        if trust_value.contains("full auto") || trust_value.contains("full_auto") {
540            let auto_badge_color = self
541                .theme
542                .tool_accent
543                .or(self.theme.primary)
544                .or(self.theme.foreground)
545                .map(ratatui_color_from_ansi)
546                .unwrap_or(Color::LightCyan);
547            let badge_style = Style::default().fg(auto_badge_color).add_modifier(Modifier::BOLD);
548            push_badge(&mut spans, "Full-auto".to_string(), badge_style, &mut first_section);
549        } else if trust_value.contains("tools policy") || trust_value.contains("tools_policy") {
550            let safe_badge_color = self
551                .theme
552                .primary
553                .or(self.theme.foreground)
554                .map(ratatui_color_from_ansi)
555                .unwrap_or(Color::LightGreen);
556            let badge_style = Style::default().fg(safe_badge_color).add_modifier(Modifier::BOLD);
557            push_badge(&mut spans, "Safe".to_string(), badge_style, &mut first_section);
558        }
559
560        // Show active subagent badge (first one, matching input block behavior)
561        if let Some(badge) = self.header_context.subagent_badges.first() {
562            let mut badge_style = ratatui_style_from_inline(&badge.style, self.theme.foreground);
563            if badge.full_background {
564                badge_style = badge_style.add_modifier(Modifier::BOLD);
565            }
566            let hidden = self.header_context.subagent_badges.len().saturating_sub(1);
567            let label = if hidden == 0 {
568                badge.text.clone()
569            } else {
570                format!("{} +{}", badge.text, hidden)
571            };
572            push_badge(&mut spans, format!(" {label} "), badge_style, &mut first_section);
573        }
574
575        // Persistent background-work badge. The bottom-line background copy is
576        // idle-only (loading moves to the transcript progress row), so the
577        // header carries the always-visible count with short static text that
578        // never shimmers or changes width per-second.
579        if let Some(badge) = self.background_header_badge_text() {
580            let style = if self.has_background_activity() {
581                // Live work stays prominent: undimmed primary bold, unlike the
582                // dimmed secondary used for retained history below.
583                self.header_primary_style()
584                    .remove_modifier(Modifier::DIM)
585                    .add_modifier(Modifier::BOLD)
586            } else {
587                self.header_secondary_style().add_modifier(Modifier::DIM)
588            };
589            push_badge(&mut spans, badge, style, &mut first_section);
590        }
591
592        // Show blocked/recovery badge so a stalled turn is visible in the header,
593        // not only in the footer hint. Uses ActivityState plus the blocked
594        // status needles shared with the footer hint (see blocked_status): the
595        // runloop flags blocked turns through status text, not a dedicated flag.
596        let is_blocked_header = matches!(
597            self.activity_state,
598            vtcode_commons::ui_protocol::ActivityState::Blocked | vtcode_commons::ui_protocol::ActivityState::Recovery
599        ) || self
600            .input_status_right
601            .as_deref()
602            .is_some_and(blocked_status::right_status_is_blocked)
603            || self
604                .input_status_left
605                .as_deref()
606                .is_some_and(blocked_status::left_status_is_blocked);
607        if is_blocked_header {
608            // Use the active theme's contrast-validated alert token instead of a
609            // hardcoded color so the badge adapts to the selected theme. The
610            // token carries bold unless the bold-is-bright accessibility mode
611            // suppresses it.
612            let blocked_inline = convert_style(crate::theme::active_styles().error);
613            let blocked_style = ratatui_style_from_inline(&blocked_inline, self.theme.foreground);
614            push_badge(&mut spans, "Blocked".to_string(), blocked_style, &mut first_section);
615        }
616
617        if spans.is_empty() {
618            spans.push(Span::raw(String::new()));
619        }
620
621        Line::from(spans)
622    }
623
624    fn header_highlights_line(&self) -> Option<Line<'static>> {
625        let mut spans = Vec::new();
626        let mut first_section = true;
627
628        for highlight in &self.header_context.highlights {
629            let title = highlight.title.trim();
630            let summary = self.header_highlight_summary(highlight);
631
632            if title.is_empty() && summary.is_none() {
633                continue;
634            }
635
636            if !first_section {
637                spans.push(Span::styled(ui::HEADER_META_SEPARATOR.to_owned(), self.header_secondary_style()));
638            }
639
640            if !title.is_empty() {
641                let mut title_style = self.header_secondary_style();
642                title_style = title_style.add_modifier(Modifier::BOLD);
643                let mut title_text = title.to_owned();
644                if summary.is_some() {
645                    title_text.push(':');
646                }
647                spans.push(Span::styled(title_text, title_style));
648                if summary.is_some() {
649                    spans.push(Span::styled(" ".to_owned(), self.header_secondary_style()));
650                }
651            }
652
653            if let Some(body) = summary {
654                spans.push(Span::styled(body, self.header_primary_style()));
655            }
656
657            first_section = false;
658        }
659
660        if spans.is_empty() {
661            None
662        } else {
663            Some(Line::from(spans))
664        }
665    }
666
667    fn header_highlight_summary(&self, highlight: &InlineHeaderHighlight) -> Option<String> {
668        let entries: Vec<String> = highlight
669            .lines
670            .iter()
671            .map(|line| line.trim())
672            .filter(|line| !line.is_empty())
673            .map(|line| {
674                let stripped = line.strip_prefix("- ").or_else(|| line.strip_prefix("• ")).unwrap_or(line);
675                stripped.trim().to_owned()
676            })
677            .collect();
678
679        if entries.is_empty() {
680            return None;
681        }
682
683        Some(self.compact_highlight_entries(&entries))
684    }
685
686    fn compact_highlight_entries(&self, entries: &[String]) -> String {
687        let mut summary = self.truncate_highlight_preview(entries.first().map(String::as_str).unwrap_or(""));
688        if entries.len() > 1 {
689            let remaining = entries.len() - 1;
690            if !summary.is_empty() {
691                let _ = write!(summary, " (+{remaining} more)");
692            } else {
693                summary = format!("(+{remaining} more)");
694            }
695        }
696        summary
697    }
698
699    fn truncate_highlight_preview(&self, text: &str) -> String {
700        let max = ui::HEADER_HIGHLIGHT_PREVIEW_MAX_CHARS;
701        if max == 0 {
702            return String::new();
703        }
704
705        let grapheme_count = text.graphemes(true).count();
706        if grapheme_count <= max {
707            return text.to_owned();
708        }
709
710        // Optimization: return early if string is short (already checked above with grapheme count)
711        // This is safe because count() <= max means it doesn't need truncation.
712
713        let mut truncated = String::new();
714        // pre-allocate capacity
715        truncated.reserve(text.len().min(max * 4));
716        for grapheme in text.graphemes(true).take(max.saturating_sub(1)) {
717            truncated.push_str(grapheme);
718        }
719        truncated.push_str(ui::INLINE_PREVIEW_ELLIPSIS);
720        truncated
721    }
722
723    /// Determine if suggestions should be shown in the header
724    fn should_show_suggestions(&self) -> bool {
725        // Show suggestions when input is empty or starts with /
726        self.input_manager.content().is_empty() || self.input_manager.content().starts_with('/')
727    }
728
729    /// Generate header line with slash command and keyboard shortcut suggestions
730    pub(crate) fn header_suggestions_line(&self) -> Option<Line<'static>> {
731        let dim = self.header_secondary_style().add_modifier(Modifier::DIM);
732        let key = self.header_primary_style().add_modifier(Modifier::BOLD);
733        let label = self.header_secondary_style();
734        let dot = Span::styled(" · ", dim);
735
736        let mut spans = vec![
737            Span::styled("/help", key),
738            dot.clone(),
739            Span::styled("/model", key),
740            dot.clone(),
741            Span::styled("/effort", key),
742            dot.clone(),
743            Span::styled("/config", key),
744            dot.clone(),
745            Span::styled("/clear", key),
746            Span::styled("  │  ", dim),
747            Span::styled("↑↓", key),
748            Span::styled(" nav", label),
749            dot.clone(),
750            Span::styled("Tab", key),
751            Span::styled(" complete", label),
752        ];
753
754        if self.has_local_agents() {
755            spans.push(Span::styled("  │  ", dim));
756            spans.push(Span::styled("Alt+S", key));
757            spans.push(Span::styled(" agents", label));
758            spans.push(dot.clone());
759            spans.push(Span::styled(self.background_shortcut_label().to_owned(), key));
760            spans.push(Span::styled(" background", label));
761        } else if self.has_active_foreground_pty() {
762            spans.push(Span::styled("  │  ", dim));
763            spans.push(Span::styled(self.background_shortcut_label().to_owned(), key));
764            spans.push(Span::styled(" background", label));
765        }
766
767        Some(Line::from(spans))
768    }
769
770    pub(crate) fn section_title_style(&self) -> Style {
771        let mut style = self.styles.default_style().add_modifier(Modifier::BOLD | Modifier::DIM);
772        if let Some(primary) = self.theme.primary.or(self.theme.foreground) {
773            style = style.fg(ratatui_color_from_ansi(primary));
774        }
775        style
776    }
777
778    pub(crate) fn header_primary_style(&self) -> Style {
779        let mut style = self.styles.default_style().add_modifier(Modifier::DIM);
780        if let Some(primary) = self.theme.primary.or(self.theme.foreground) {
781            style = style.fg(ratatui_color_from_ansi(primary));
782        }
783        style
784    }
785
786    pub(crate) fn header_secondary_style(&self) -> Style {
787        let mut style = self.styles.default_style().add_modifier(Modifier::DIM);
788        if let Some(secondary) = self.theme.secondary.or(self.theme.foreground) {
789            style = style.fg(ratatui_color_from_ansi(secondary));
790        }
791        style
792    }
793
794    fn strip_prefix<'a>(value: &'a str, prefix: &str) -> &'a str {
795        value.trim_prefix(prefix)
796    }
797}
798
799#[cfg(test)]
800mod badge_tests;