Skip to main content

vtcode_ui/tui/core_tui/widgets/
sidebar.rs

1use ratatui::{
2    buffer::Buffer,
3    layout::{Constraint, Layout, Rect},
4    text::{Line, Span},
5    widgets::{Clear, Paragraph, StatefulWidget, Widget, Wrap},
6};
7use tui_widget_list::{ListBuilder, ListState as WidgetListState, ListView};
8
9use super::layout_mode::LayoutMode;
10use super::panel::{PanelStyles, new_panel};
11use crate::tui::core_tui::types::{ActivePlanEntry, LocalAgentEntry};
12use crate::tui::ui::tui::session::styling::SessionStyles;
13
14/// Ellipsis character used to indicate truncated text.
15use crate::design::constants::ELLIPSIS;
16
17#[derive(Clone)]
18struct SidebarListItem {
19    line: Line<'static>,
20}
21
22impl Widget for SidebarListItem {
23    fn render(self, area: Rect, buf: &mut Buffer) {
24        Paragraph::new(self.line).wrap(Wrap { trim: false }).render(area, buf);
25    }
26}
27
28fn render_static_list(lines: Vec<Line<'static>>, area: Rect, buf: &mut Buffer) {
29    if area.width == 0 || area.height == 0 || lines.is_empty() {
30        return;
31    }
32
33    let rows = lines
34        .into_iter()
35        .map(|line| (SidebarListItem { line }, 1_u16))
36        .collect::<Vec<_>>();
37    let count = rows.len();
38    let builder = ListBuilder::new(move |context| rows[context.index].clone());
39    let widget = ListView::new(builder, count).infinite_scrolling(false);
40    let mut state = WidgetListState::default();
41    StatefulWidget::render(widget, area, buf, &mut state);
42}
43
44/// Sidebar section types for organizing content
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub enum SidebarSection {
47    Plan,
48    LocalAgents,
49    Queue,
50    Context,
51    Tools,
52    Info,
53}
54
55/// Widget for rendering the sidebar in wide mode
56///
57/// The sidebar provides quick access to:
58/// - Queued inputs/tasks
59/// - Context information
60/// - Recent tool calls
61/// - Session info
62///
63/// # Example
64/// ```ignore
65/// SidebarWidget::new(&styles)
66///     .queue_items(&queue)
67///     .context_info("12K tokens | 45% context")
68///     .active_section(SidebarSection::Queue)
69///     .render(sidebar_area, buf);
70/// ```
71pub struct SidebarWidget<'a> {
72    styles: &'a SessionStyles,
73    queue_items: Vec<String>,
74    local_agents: Vec<LocalAgentEntry>,
75    active_plan: Option<ActivePlanEntry>,
76    context_info: Option<&'a str>,
77    recent_tools: Vec<String>,
78    active_section: Option<SidebarSection>,
79    mode: LayoutMode,
80}
81
82impl<'a> SidebarWidget<'a> {
83    /// Create a new sidebar widget
84    pub(crate) fn new(styles: &'a SessionStyles) -> Self {
85        Self {
86            styles,
87            queue_items: Vec::new(),
88            local_agents: Vec::new(),
89            active_plan: None,
90            context_info: None,
91            recent_tools: Vec::new(),
92            active_section: None,
93            mode: LayoutMode::Wide,
94        }
95    }
96
97    /// Set queued items to display
98    #[must_use]
99    pub(crate) fn queue_items(mut self, items: Vec<String>) -> Self {
100        self.queue_items = items;
101        self
102    }
103
104    #[must_use]
105    pub(crate) fn local_agents(mut self, entries: Vec<LocalAgentEntry>) -> Self {
106        self.local_agents = entries;
107        self
108    }
109
110    #[must_use]
111    pub(crate) fn plan(mut self, entry: Option<ActivePlanEntry>) -> Self {
112        self.active_plan = entry;
113        self
114    }
115
116    /// Set context info text
117    #[must_use]
118    pub(crate) fn context_info(mut self, info: &'a str) -> Self {
119        self.context_info = Some(info);
120        self
121    }
122
123    /// Set recent tool calls
124    #[must_use]
125    pub fn recent_tools(mut self, tools: Vec<String>) -> Self {
126        self.recent_tools = tools;
127        self
128    }
129
130    /// Set the active/focused section
131    #[must_use]
132    pub fn active_section(mut self, section: SidebarSection) -> Self {
133        self.active_section = Some(section);
134        self
135    }
136
137    /// Set the layout mode
138    #[must_use]
139    pub(crate) fn mode(mut self, mode: LayoutMode) -> Self {
140        self.mode = mode;
141        self
142    }
143
144    fn render_plan_section(&self, area: Rect, buf: &mut Buffer) {
145        let is_active = self.active_section == Some(SidebarSection::Plan);
146        let inner = new_panel(self.styles)
147            .title("Plan")
148            .active(is_active)
149            .mode(self.mode)
150            .render_and_get_inner(area, buf);
151
152        if inner.height == 0 || inner.width == 0 {
153            return;
154        }
155
156        let Some(plan) = self.active_plan.as_ref() else {
157            let empty_text = Paragraph::new("No active plan").style(self.styles.muted_style());
158            empty_text.render(inner, buf);
159            return;
160        };
161
162        let max_width = inner.width.saturating_sub(2) as usize;
163        let mut lines = vec![
164            Line::from(Span::styled(truncate_string(&plan.status, max_width), self.styles.accent_style())),
165            Line::from(Span::styled(truncate_string(&plan.file_path, max_width), self.styles.muted_style())),
166            Line::from(Span::styled(
167                if plan.total_steps == 1 {
168                    "1 step".to_string()
169                } else {
170                    format!("{} steps", plan.total_steps)
171                },
172                self.styles.default_style(),
173            )),
174        ];
175        for (index, title) in plan.step_titles.iter().enumerate() {
176            let prefix = format!("{}. ", index + 1);
177            lines.push(Line::from(vec![
178                Span::styled(prefix, self.styles.accent_style()),
179                Span::styled(truncate_string(title, max_width.saturating_sub(3)), self.styles.default_style()),
180            ]));
181        }
182        let remaining = plan.remaining_step_count();
183        if remaining > 0 {
184            lines.push(Line::from(Span::styled(format!("+{remaining} more"), self.styles.muted_style())));
185        }
186
187        render_static_list(lines, inner, buf);
188    }
189
190    fn render_queue_section(&self, area: Rect, buf: &mut Buffer) {
191        let is_active = self.active_section == Some(SidebarSection::Queue);
192        let inner = new_panel(self.styles)
193            .title("Queue")
194            .active(is_active)
195            .mode(self.mode)
196            .render_and_get_inner(area, buf);
197
198        if inner.height == 0 || inner.width == 0 {
199            return;
200        }
201
202        if self.queue_items.is_empty() {
203            let empty_text = Paragraph::new("No queued items").style(self.styles.muted_style());
204            empty_text.render(inner, buf);
205        } else {
206            let lines = self
207                .queue_items
208                .iter()
209                .enumerate()
210                .map(|(i, item)| {
211                    let prefix = format!("{}. ", i + 1);
212                    Line::from(vec![
213                        Span::styled(prefix, self.styles.accent_style()),
214                        Span::styled(
215                            truncate_string(item, inner.width.saturating_sub(4) as usize),
216                            self.styles.default_style(),
217                        ),
218                    ])
219                })
220                .collect();
221
222            render_static_list(lines, inner, buf);
223        }
224    }
225
226    fn render_local_agents_section(&self, area: Rect, buf: &mut Buffer) {
227        let is_active = self.active_section == Some(SidebarSection::LocalAgents);
228        let inner = new_panel(self.styles)
229            .title("Local Agents")
230            .active(is_active)
231            .mode(self.mode)
232            .render_and_get_inner(area, buf);
233
234        if inner.height == 0 || inner.width == 0 {
235            return;
236        }
237
238        if self.local_agents.is_empty() {
239            let empty_text = Paragraph::new("No local agents").style(self.styles.muted_style());
240            empty_text.render(inner, buf);
241        } else {
242            let mut lines = self
243                .local_agents
244                .iter()
245                .take(4)
246                .map(|entry| {
247                    Line::from(Span::styled(
248                        truncate_string(
249                            &format!("{} · {} · {}", entry.display_label, entry.kind.as_str(), entry.status),
250                            inner.width.saturating_sub(2) as usize,
251                        ),
252                        self.styles.default_style(),
253                    ))
254                })
255                .collect::<Vec<_>>();
256
257            if let Some(entry) = self.local_agents.first() {
258                lines.push(Line::from(String::new()));
259                lines.push(Line::from(Span::styled(
260                    truncate_string(&entry.preview, inner.width.saturating_sub(2) as usize),
261                    self.styles.muted_style(),
262                )));
263            }
264
265            render_static_list(lines, inner, buf);
266        }
267    }
268
269    fn render_context_section(&self, area: Rect, buf: &mut Buffer) {
270        let is_active = self.active_section == Some(SidebarSection::Context);
271        let inner = new_panel(self.styles)
272            .title("Context")
273            .active(is_active)
274            .mode(self.mode)
275            .render_and_get_inner(area, buf);
276
277        if inner.height == 0 || inner.width == 0 {
278            return;
279        }
280
281        let text = self.context_info.unwrap_or("No context info");
282        let paragraph = Paragraph::new(text)
283            .style(self.styles.default_style())
284            .wrap(Wrap { trim: true });
285        paragraph.render(inner, buf);
286    }
287
288    fn render_tools_section(&self, area: Rect, buf: &mut Buffer) {
289        let is_active = self.active_section == Some(SidebarSection::Tools);
290        let inner = new_panel(self.styles)
291            .title("Recent Tools")
292            .active(is_active)
293            .mode(self.mode)
294            .render_and_get_inner(area, buf);
295
296        if inner.height == 0 || inner.width == 0 {
297            return;
298        }
299
300        if self.recent_tools.is_empty() {
301            let empty_text = Paragraph::new("No recent tools").style(self.styles.muted_style());
302            empty_text.render(inner, buf);
303        } else {
304            let lines = self
305                .recent_tools
306                .iter()
307                .map(|tool| {
308                    Line::from(Span::styled(
309                        format!("▸ {}", truncate_string(tool, inner.width.saturating_sub(3) as usize)),
310                        self.styles.default_style(),
311                    ))
312                })
313                .collect();
314
315            render_static_list(lines, inner, buf);
316        }
317    }
318}
319
320impl Widget for SidebarWidget<'_> {
321    fn render(self, area: Rect, buf: &mut Buffer) {
322        if area.height == 0 || area.width == 0 {
323            return;
324        }
325
326        if !self.mode.allow_sidebar() {
327            return;
328        }
329
330        Clear.render(area, buf);
331
332        // Split sidebar into sections
333        let has_local_agents = !self.local_agents.is_empty();
334        let has_queue = !self.queue_items.is_empty();
335        let has_tools = !self.recent_tools.is_empty();
336
337        let mut sections = Vec::<(SidebarSection, u32)>::new();
338        if self.active_plan.is_some() {
339            sections.push((SidebarSection::Plan, 4));
340        }
341        if has_local_agents {
342            sections.push((SidebarSection::LocalAgents, 7));
343        }
344        if has_queue {
345            sections.push((SidebarSection::Queue, 3));
346        }
347        sections.push((SidebarSection::Context, 2));
348        if has_tools {
349            sections.push((SidebarSection::Tools, 2));
350        }
351
352        let total_weight = sections.iter().map(|(_, weight)| *weight).sum::<u32>().max(1);
353        let constraints = sections
354            .iter()
355            .map(|(_, weight)| Constraint::Ratio(*weight, total_weight))
356            .collect::<Vec<_>>();
357        let chunks = Layout::vertical(constraints).split(area);
358
359        for ((section, _), chunk) in sections.into_iter().zip(chunks.iter()) {
360            match section {
361                SidebarSection::Plan => self.render_plan_section(*chunk, buf),
362                SidebarSection::LocalAgents => self.render_local_agents_section(*chunk, buf),
363                SidebarSection::Queue => self.render_queue_section(*chunk, buf),
364                SidebarSection::Context => self.render_context_section(*chunk, buf),
365                SidebarSection::Tools => self.render_tools_section(*chunk, buf),
366                SidebarSection::Info => {}
367            }
368        }
369    }
370}
371
372/// Truncate a string to fit within a given display-column width.
373fn truncate_string(s: &str, max_width: usize) -> String {
374    vtcode_commons::preview::truncate_with_ellipsis(s, max_width, ELLIPSIS)
375}
376
377#[cfg(test)]
378mod tests {
379    use super::SidebarWidget;
380    use crate::tui::core_tui::session::styling::SessionStyles;
381    use crate::tui::core_tui::types::ActivePlanEntry;
382    use crate::tui::core_tui::widgets::LayoutMode;
383    use crate::tui::ui::tui::types::InlineTheme;
384    use ratatui::buffer::Buffer;
385    use ratatui::layout::Rect;
386    use ratatui::widgets::Widget;
387
388    fn sample_plan(step_titles: &[&str], total_steps: usize) -> ActivePlanEntry {
389        ActivePlanEntry {
390            file_path: ".vtcode/plans/task.md".to_string(),
391            status: "approved -> build".to_string(),
392            step_titles: step_titles.iter().map(|title| title.to_string()).collect(),
393            total_steps,
394        }
395    }
396
397    fn rendered_sidebar_text(buf: &Buffer, area: Rect) -> String {
398        (0..area.height)
399            .map(|row| (0..area.width).map(|col| buf[(col, row)].symbol()).collect::<String>())
400            .collect::<Vec<_>>()
401            .join("\n")
402    }
403
404    #[test]
405    fn sidebar_renders_local_agent_entries() {
406        let styles = SessionStyles::new(InlineTheme::default());
407        let area = Rect::new(0, 0, 60, 16);
408        let mut buf = Buffer::empty(area);
409
410        SidebarWidget::new(&styles)
411            .local_agents(vec![
412                crate::tui::core_tui::types::LocalAgentEntry {
413                    program_status: vtcode_commons::program_status::ProgramState::Idle,
414                    updated_at: 0,
415                    id: "thread-1".to_string(),
416                    display_label: "rust-engineer".to_string(),
417                    agent_name: "rust-engineer".to_string(),
418                    color: Some("cyan".to_string()),
419                    kind: crate::tui::core_tui::types::LocalAgentKind::Delegated,
420                    status: crate::tui::core_tui::types::LocalAgentStatus::Running,
421                    summary: None,
422                    preview: "assistant: reviewing the workspace".to_string(),
423                    transcript_path: None,
424                },
425                crate::tui::core_tui::types::LocalAgentEntry {
426                    program_status: vtcode_commons::program_status::ProgramState::Idle,
427                    updated_at: 0,
428                    id: "bg-1".to_string(),
429                    display_label: "reviewer".to_string(),
430                    agent_name: "reviewer".to_string(),
431                    color: None,
432                    kind: crate::tui::core_tui::types::LocalAgentKind::Background,
433                    status: crate::tui::core_tui::types::LocalAgentStatus::Starting,
434                    summary: None,
435                    preview: "waiting for output".to_string(),
436                    transcript_path: None,
437                },
438            ])
439            .context_info("Ready")
440            .render(area, &mut buf);
441
442        let rendered = (0..area.height)
443            .map(|row| (0..area.width).map(|col| buf[(col, row)].symbol()).collect::<String>())
444            .collect::<Vec<_>>()
445            .join("\n");
446
447        assert!(rendered.contains("Local Agents"));
448        assert!(rendered.contains("rust-engineer"));
449        assert!(rendered.contains("reviewer"));
450    }
451
452    #[test]
453    fn sidebar_renders_local_agent_preview() {
454        let styles = SessionStyles::new(InlineTheme::default());
455        let area = Rect::new(0, 0, 60, 16);
456        let mut buf = Buffer::empty(area);
457
458        SidebarWidget::new(&styles)
459            .local_agents(vec![crate::tui::core_tui::types::LocalAgentEntry {
460                program_status: vtcode_commons::program_status::ProgramState::Idle,
461                updated_at: 0,
462                id: "thread-1".to_string(),
463                display_label: "rust-engineer".to_string(),
464                agent_name: "rust-engineer".to_string(),
465                color: Some("cyan".to_string()),
466                kind: crate::tui::core_tui::types::LocalAgentKind::Delegated,
467                status: crate::tui::core_tui::types::LocalAgentStatus::Running,
468                summary: None,
469                preview: "thinking: Inspecting the diff carefully".to_string(),
470                transcript_path: None,
471            }])
472            .context_info("Ready")
473            .render(area, &mut buf);
474
475        let rendered = (0..area.height)
476            .map(|row| (0..area.width).map(|col| buf[(col, row)].symbol()).collect::<String>())
477            .collect::<Vec<_>>()
478            .join("\n");
479
480        assert!(rendered.contains("Local Agents"));
481        assert!(rendered.contains("rust-engineer"));
482        assert!(rendered.contains("Inspecting the diff carefully"));
483    }
484
485    #[test]
486    fn sidebar_renders_active_plan_section() {
487        let styles = SessionStyles::new(InlineTheme::default());
488        let area = Rect::new(0, 0, 60, 20);
489        let mut buf = Buffer::empty(area);
490
491        SidebarWidget::new(&styles)
492            .plan(Some(sample_plan(&["Add sidebar panel", "Wire approval handoff"], 2)))
493            .context_info("Ready")
494            .render(area, &mut buf);
495
496        let rendered = rendered_sidebar_text(&buf, area);
497        assert!(rendered.contains("Plan"), "missing Plan panel title: {rendered}");
498        assert!(rendered.contains("approved -> build"), "missing status badge: {rendered}");
499        assert!(rendered.contains(".vtcode/plans/task.md"), "missing plan path: {rendered}");
500        assert!(rendered.contains("2 steps"), "missing step total: {rendered}");
501        assert!(rendered.contains("Add sidebar panel"), "missing step 1: {rendered}");
502        assert!(rendered.contains("Wire approval handoff"), "missing step 2: {rendered}");
503        assert!(!rendered.contains("more"), "nothing truncated, no +N row expected: {rendered}");
504    }
505
506    #[test]
507    fn sidebar_shows_more_row_when_plan_steps_truncated() {
508        let styles = SessionStyles::new(InlineTheme::default());
509        let area = Rect::new(0, 0, 60, 20);
510        let mut buf = Buffer::empty(area);
511
512        SidebarWidget::new(&styles)
513            .plan(Some(sample_plan(&["Add sidebar panel", "Wire approval handoff"], 5)))
514            .context_info("Ready")
515            .render(area, &mut buf);
516
517        let rendered = rendered_sidebar_text(&buf, area);
518        assert!(rendered.contains("5 steps"), "missing step total: {rendered}");
519        assert!(rendered.contains("+3 more"), "missing truncation row: {rendered}");
520    }
521
522    #[test]
523    fn sidebar_plan_step_count_uses_singular_for_one_step() {
524        let styles = SessionStyles::new(InlineTheme::default());
525        let area = Rect::new(0, 0, 60, 20);
526        let mut buf = Buffer::empty(area);
527
528        SidebarWidget::new(&styles)
529            .plan(Some(sample_plan(&["Only step"], 1)))
530            .context_info("Ready")
531            .render(area, &mut buf);
532
533        let rendered = rendered_sidebar_text(&buf, area);
534        assert!(rendered.contains("1 step"), "missing singular count: {rendered}");
535        assert!(!rendered.contains("1 steps"), "must not pluralize one step: {rendered}");
536    }
537
538    #[test]
539    fn sidebar_omits_plan_section_without_active_plan() {
540        let styles = SessionStyles::new(InlineTheme::default());
541        let area = Rect::new(0, 0, 60, 20);
542        let mut buf = Buffer::empty(area);
543
544        SidebarWidget::new(&styles).context_info("Ready").render(area, &mut buf);
545
546        let rendered = rendered_sidebar_text(&buf, area);
547        assert!(!rendered.contains("Plan"), "no plan section expected: {rendered}");
548        assert!(rendered.contains("Context"), "other sections must still render: {rendered}");
549    }
550
551    #[test]
552    fn sidebar_plan_hidden_outside_wide_mode() {
553        let styles = SessionStyles::new(InlineTheme::default());
554        let area = Rect::new(0, 0, 60, 20);
555        let mut buf = Buffer::empty(area);
556
557        SidebarWidget::new(&styles)
558            .plan(Some(sample_plan(&["Add sidebar panel"], 1)))
559            .context_info("Ready")
560            .mode(LayoutMode::Standard)
561            .render(area, &mut buf);
562
563        let rendered = rendered_sidebar_text(&buf, area);
564        assert!(rendered.trim().is_empty(), "sidebar must not render outside Wide: {rendered}");
565    }
566}