vtcode-ui 0.183.0

Unified UI crate for VT Code: design system, theme registry, and TUI framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
use ratatui::{
    buffer::Buffer,
    layout::{Constraint, Layout, Rect},
    text::{Line, Span},
    widgets::{Clear, Paragraph, StatefulWidget, Widget, Wrap},
};
use tui_widget_list::{ListBuilder, ListState as WidgetListState, ListView};

use super::layout_mode::LayoutMode;
use super::panel::{PanelStyles, new_panel};
use crate::tui::core_tui::types::{ActivePlanEntry, LocalAgentEntry};
use crate::tui::ui::tui::session::styling::SessionStyles;

/// Ellipsis character used to indicate truncated text.
use crate::design::constants::ELLIPSIS;

#[derive(Clone)]
struct SidebarListItem {
    line: Line<'static>,
}

impl Widget for SidebarListItem {
    fn render(self, area: Rect, buf: &mut Buffer) {
        Paragraph::new(self.line).wrap(Wrap { trim: false }).render(area, buf);
    }
}

fn render_static_list(lines: Vec<Line<'static>>, area: Rect, buf: &mut Buffer) {
    if area.width == 0 || area.height == 0 || lines.is_empty() {
        return;
    }

    let rows = lines
        .into_iter()
        .map(|line| (SidebarListItem { line }, 1_u16))
        .collect::<Vec<_>>();
    let count = rows.len();
    let builder = ListBuilder::new(move |context| rows[context.index].clone());
    let widget = ListView::new(builder, count).infinite_scrolling(false);
    let mut state = WidgetListState::default();
    StatefulWidget::render(widget, area, buf, &mut state);
}

/// Sidebar section types for organizing content
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SidebarSection {
    Plan,
    LocalAgents,
    Queue,
    Context,
    Tools,
    Info,
}

/// Widget for rendering the sidebar in wide mode
///
/// The sidebar provides quick access to:
/// - Queued inputs/tasks
/// - Context information
/// - Recent tool calls
/// - Session info
///
/// # Example
/// ```ignore
/// SidebarWidget::new(&styles)
///     .queue_items(&queue)
///     .context_info("12K tokens | 45% context")
///     .active_section(SidebarSection::Queue)
///     .render(sidebar_area, buf);
/// ```
pub struct SidebarWidget<'a> {
    styles: &'a SessionStyles,
    queue_items: Vec<String>,
    local_agents: Vec<LocalAgentEntry>,
    active_plan: Option<ActivePlanEntry>,
    context_info: Option<&'a str>,
    recent_tools: Vec<String>,
    active_section: Option<SidebarSection>,
    mode: LayoutMode,
}

impl<'a> SidebarWidget<'a> {
    /// Create a new sidebar widget
    pub(crate) fn new(styles: &'a SessionStyles) -> Self {
        Self {
            styles,
            queue_items: Vec::new(),
            local_agents: Vec::new(),
            active_plan: None,
            context_info: None,
            recent_tools: Vec::new(),
            active_section: None,
            mode: LayoutMode::Wide,
        }
    }

    /// Set queued items to display
    #[must_use]
    pub(crate) fn queue_items(mut self, items: Vec<String>) -> Self {
        self.queue_items = items;
        self
    }

    #[must_use]
    pub(crate) fn local_agents(mut self, entries: Vec<LocalAgentEntry>) -> Self {
        self.local_agents = entries;
        self
    }

    #[must_use]
    pub(crate) fn plan(mut self, entry: Option<ActivePlanEntry>) -> Self {
        self.active_plan = entry;
        self
    }

    /// Set context info text
    #[must_use]
    pub(crate) fn context_info(mut self, info: &'a str) -> Self {
        self.context_info = Some(info);
        self
    }

    /// Set recent tool calls
    #[must_use]
    pub fn recent_tools(mut self, tools: Vec<String>) -> Self {
        self.recent_tools = tools;
        self
    }

    /// Set the active/focused section
    #[must_use]
    pub fn active_section(mut self, section: SidebarSection) -> Self {
        self.active_section = Some(section);
        self
    }

    /// Set the layout mode
    #[must_use]
    pub(crate) fn mode(mut self, mode: LayoutMode) -> Self {
        self.mode = mode;
        self
    }

    fn render_plan_section(&self, area: Rect, buf: &mut Buffer) {
        let is_active = self.active_section == Some(SidebarSection::Plan);
        let inner = new_panel(self.styles)
            .title("Plan")
            .active(is_active)
            .mode(self.mode)
            .render_and_get_inner(area, buf);

        if inner.height == 0 || inner.width == 0 {
            return;
        }

        let Some(plan) = self.active_plan.as_ref() else {
            let empty_text = Paragraph::new("No active plan").style(self.styles.muted_style());
            empty_text.render(inner, buf);
            return;
        };

        let max_width = inner.width.saturating_sub(2) as usize;
        let mut lines = vec![
            Line::from(Span::styled(truncate_string(&plan.status, max_width), self.styles.accent_style())),
            Line::from(Span::styled(truncate_string(&plan.file_path, max_width), self.styles.muted_style())),
            Line::from(Span::styled(
                if plan.total_steps == 1 {
                    "1 step".to_string()
                } else {
                    format!("{} steps", plan.total_steps)
                },
                self.styles.default_style(),
            )),
        ];
        for (index, title) in plan.step_titles.iter().enumerate() {
            let prefix = format!("{}. ", index + 1);
            lines.push(Line::from(vec![
                Span::styled(prefix, self.styles.accent_style()),
                Span::styled(truncate_string(title, max_width.saturating_sub(3)), self.styles.default_style()),
            ]));
        }
        let remaining = plan.remaining_step_count();
        if remaining > 0 {
            lines.push(Line::from(Span::styled(format!("+{remaining} more"), self.styles.muted_style())));
        }

        render_static_list(lines, inner, buf);
    }

    fn render_queue_section(&self, area: Rect, buf: &mut Buffer) {
        let is_active = self.active_section == Some(SidebarSection::Queue);
        let inner = new_panel(self.styles)
            .title("Queue")
            .active(is_active)
            .mode(self.mode)
            .render_and_get_inner(area, buf);

        if inner.height == 0 || inner.width == 0 {
            return;
        }

        if self.queue_items.is_empty() {
            let empty_text = Paragraph::new("No queued items").style(self.styles.muted_style());
            empty_text.render(inner, buf);
        } else {
            let lines = self
                .queue_items
                .iter()
                .enumerate()
                .map(|(i, item)| {
                    let prefix = format!("{}. ", i + 1);
                    Line::from(vec![
                        Span::styled(prefix, self.styles.accent_style()),
                        Span::styled(
                            truncate_string(item, inner.width.saturating_sub(4) as usize),
                            self.styles.default_style(),
                        ),
                    ])
                })
                .collect();

            render_static_list(lines, inner, buf);
        }
    }

    fn render_local_agents_section(&self, area: Rect, buf: &mut Buffer) {
        let is_active = self.active_section == Some(SidebarSection::LocalAgents);
        let inner = new_panel(self.styles)
            .title("Local Agents")
            .active(is_active)
            .mode(self.mode)
            .render_and_get_inner(area, buf);

        if inner.height == 0 || inner.width == 0 {
            return;
        }

        if self.local_agents.is_empty() {
            let empty_text = Paragraph::new("No local agents").style(self.styles.muted_style());
            empty_text.render(inner, buf);
        } else {
            let mut lines = self
                .local_agents
                .iter()
                .take(4)
                .map(|entry| {
                    Line::from(Span::styled(
                        truncate_string(
                            &format!("{} · {} · {}", entry.display_label, entry.kind.as_str(), entry.status),
                            inner.width.saturating_sub(2) as usize,
                        ),
                        self.styles.default_style(),
                    ))
                })
                .collect::<Vec<_>>();

            if let Some(entry) = self.local_agents.first() {
                lines.push(Line::from(String::new()));
                lines.push(Line::from(Span::styled(
                    truncate_string(&entry.preview, inner.width.saturating_sub(2) as usize),
                    self.styles.muted_style(),
                )));
            }

            render_static_list(lines, inner, buf);
        }
    }

    fn render_context_section(&self, area: Rect, buf: &mut Buffer) {
        let is_active = self.active_section == Some(SidebarSection::Context);
        let inner = new_panel(self.styles)
            .title("Context")
            .active(is_active)
            .mode(self.mode)
            .render_and_get_inner(area, buf);

        if inner.height == 0 || inner.width == 0 {
            return;
        }

        let text = self.context_info.unwrap_or("No context info");
        let paragraph = Paragraph::new(text)
            .style(self.styles.default_style())
            .wrap(Wrap { trim: true });
        paragraph.render(inner, buf);
    }

    fn render_tools_section(&self, area: Rect, buf: &mut Buffer) {
        let is_active = self.active_section == Some(SidebarSection::Tools);
        let inner = new_panel(self.styles)
            .title("Recent Tools")
            .active(is_active)
            .mode(self.mode)
            .render_and_get_inner(area, buf);

        if inner.height == 0 || inner.width == 0 {
            return;
        }

        if self.recent_tools.is_empty() {
            let empty_text = Paragraph::new("No recent tools").style(self.styles.muted_style());
            empty_text.render(inner, buf);
        } else {
            let lines = self
                .recent_tools
                .iter()
                .map(|tool| {
                    Line::from(Span::styled(
                        format!("â–¸ {}", truncate_string(tool, inner.width.saturating_sub(3) as usize)),
                        self.styles.default_style(),
                    ))
                })
                .collect();

            render_static_list(lines, inner, buf);
        }
    }
}

impl Widget for SidebarWidget<'_> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        if area.height == 0 || area.width == 0 {
            return;
        }

        if !self.mode.allow_sidebar() {
            return;
        }

        Clear.render(area, buf);

        // Split sidebar into sections
        let has_local_agents = !self.local_agents.is_empty();
        let has_queue = !self.queue_items.is_empty();
        let has_tools = !self.recent_tools.is_empty();

        let mut sections = Vec::<(SidebarSection, u32)>::new();
        if self.active_plan.is_some() {
            sections.push((SidebarSection::Plan, 4));
        }
        if has_local_agents {
            sections.push((SidebarSection::LocalAgents, 7));
        }
        if has_queue {
            sections.push((SidebarSection::Queue, 3));
        }
        sections.push((SidebarSection::Context, 2));
        if has_tools {
            sections.push((SidebarSection::Tools, 2));
        }

        let total_weight = sections.iter().map(|(_, weight)| *weight).sum::<u32>().max(1);
        let constraints = sections
            .iter()
            .map(|(_, weight)| Constraint::Ratio(*weight, total_weight))
            .collect::<Vec<_>>();
        let chunks = Layout::vertical(constraints).split(area);

        for ((section, _), chunk) in sections.into_iter().zip(chunks.iter()) {
            match section {
                SidebarSection::Plan => self.render_plan_section(*chunk, buf),
                SidebarSection::LocalAgents => self.render_local_agents_section(*chunk, buf),
                SidebarSection::Queue => self.render_queue_section(*chunk, buf),
                SidebarSection::Context => self.render_context_section(*chunk, buf),
                SidebarSection::Tools => self.render_tools_section(*chunk, buf),
                SidebarSection::Info => {}
            }
        }
    }
}

/// Truncate a string to fit within a given display-column width.
fn truncate_string(s: &str, max_width: usize) -> String {
    vtcode_commons::preview::truncate_with_ellipsis(s, max_width, ELLIPSIS)
}

#[cfg(test)]
mod tests {
    use super::SidebarWidget;
    use crate::tui::core_tui::session::styling::SessionStyles;
    use crate::tui::core_tui::types::ActivePlanEntry;
    use crate::tui::core_tui::widgets::LayoutMode;
    use crate::tui::ui::tui::types::InlineTheme;
    use ratatui::buffer::Buffer;
    use ratatui::layout::Rect;
    use ratatui::widgets::Widget;

    fn sample_plan(step_titles: &[&str], total_steps: usize) -> ActivePlanEntry {
        ActivePlanEntry {
            file_path: ".vtcode/plans/task.md".to_string(),
            status: "approved -> build".to_string(),
            step_titles: step_titles.iter().map(|title| title.to_string()).collect(),
            total_steps,
        }
    }

    fn rendered_sidebar_text(buf: &Buffer, area: Rect) -> String {
        (0..area.height)
            .map(|row| (0..area.width).map(|col| buf[(col, row)].symbol()).collect::<String>())
            .collect::<Vec<_>>()
            .join("\n")
    }

    #[test]
    fn sidebar_renders_local_agent_entries() {
        let styles = SessionStyles::new(InlineTheme::default());
        let area = Rect::new(0, 0, 60, 16);
        let mut buf = Buffer::empty(area);

        SidebarWidget::new(&styles)
            .local_agents(vec![
                crate::tui::core_tui::types::LocalAgentEntry {
                    program_status: vtcode_commons::program_status::ProgramState::Idle,
                    updated_at: 0,
                    id: "thread-1".to_string(),
                    display_label: "rust-engineer".to_string(),
                    agent_name: "rust-engineer".to_string(),
                    color: Some("cyan".to_string()),
                    kind: crate::tui::core_tui::types::LocalAgentKind::Delegated,
                    status: crate::tui::core_tui::types::LocalAgentStatus::Running,
                    summary: None,
                    preview: "assistant: reviewing the workspace".to_string(),
                    transcript_path: None,
                },
                crate::tui::core_tui::types::LocalAgentEntry {
                    program_status: vtcode_commons::program_status::ProgramState::Idle,
                    updated_at: 0,
                    id: "bg-1".to_string(),
                    display_label: "reviewer".to_string(),
                    agent_name: "reviewer".to_string(),
                    color: None,
                    kind: crate::tui::core_tui::types::LocalAgentKind::Background,
                    status: crate::tui::core_tui::types::LocalAgentStatus::Starting,
                    summary: None,
                    preview: "waiting for output".to_string(),
                    transcript_path: None,
                },
            ])
            .context_info("Ready")
            .render(area, &mut buf);

        let rendered = (0..area.height)
            .map(|row| (0..area.width).map(|col| buf[(col, row)].symbol()).collect::<String>())
            .collect::<Vec<_>>()
            .join("\n");

        assert!(rendered.contains("Local Agents"));
        assert!(rendered.contains("rust-engineer"));
        assert!(rendered.contains("reviewer"));
    }

    #[test]
    fn sidebar_renders_local_agent_preview() {
        let styles = SessionStyles::new(InlineTheme::default());
        let area = Rect::new(0, 0, 60, 16);
        let mut buf = Buffer::empty(area);

        SidebarWidget::new(&styles)
            .local_agents(vec![crate::tui::core_tui::types::LocalAgentEntry {
                program_status: vtcode_commons::program_status::ProgramState::Idle,
                updated_at: 0,
                id: "thread-1".to_string(),
                display_label: "rust-engineer".to_string(),
                agent_name: "rust-engineer".to_string(),
                color: Some("cyan".to_string()),
                kind: crate::tui::core_tui::types::LocalAgentKind::Delegated,
                status: crate::tui::core_tui::types::LocalAgentStatus::Running,
                summary: None,
                preview: "thinking: Inspecting the diff carefully".to_string(),
                transcript_path: None,
            }])
            .context_info("Ready")
            .render(area, &mut buf);

        let rendered = (0..area.height)
            .map(|row| (0..area.width).map(|col| buf[(col, row)].symbol()).collect::<String>())
            .collect::<Vec<_>>()
            .join("\n");

        assert!(rendered.contains("Local Agents"));
        assert!(rendered.contains("rust-engineer"));
        assert!(rendered.contains("Inspecting the diff carefully"));
    }

    #[test]
    fn sidebar_renders_active_plan_section() {
        let styles = SessionStyles::new(InlineTheme::default());
        let area = Rect::new(0, 0, 60, 20);
        let mut buf = Buffer::empty(area);

        SidebarWidget::new(&styles)
            .plan(Some(sample_plan(&["Add sidebar panel", "Wire approval handoff"], 2)))
            .context_info("Ready")
            .render(area, &mut buf);

        let rendered = rendered_sidebar_text(&buf, area);
        assert!(rendered.contains("Plan"), "missing Plan panel title: {rendered}");
        assert!(rendered.contains("approved -> build"), "missing status badge: {rendered}");
        assert!(rendered.contains(".vtcode/plans/task.md"), "missing plan path: {rendered}");
        assert!(rendered.contains("2 steps"), "missing step total: {rendered}");
        assert!(rendered.contains("Add sidebar panel"), "missing step 1: {rendered}");
        assert!(rendered.contains("Wire approval handoff"), "missing step 2: {rendered}");
        assert!(!rendered.contains("more"), "nothing truncated, no +N row expected: {rendered}");
    }

    #[test]
    fn sidebar_shows_more_row_when_plan_steps_truncated() {
        let styles = SessionStyles::new(InlineTheme::default());
        let area = Rect::new(0, 0, 60, 20);
        let mut buf = Buffer::empty(area);

        SidebarWidget::new(&styles)
            .plan(Some(sample_plan(&["Add sidebar panel", "Wire approval handoff"], 5)))
            .context_info("Ready")
            .render(area, &mut buf);

        let rendered = rendered_sidebar_text(&buf, area);
        assert!(rendered.contains("5 steps"), "missing step total: {rendered}");
        assert!(rendered.contains("+3 more"), "missing truncation row: {rendered}");
    }

    #[test]
    fn sidebar_plan_step_count_uses_singular_for_one_step() {
        let styles = SessionStyles::new(InlineTheme::default());
        let area = Rect::new(0, 0, 60, 20);
        let mut buf = Buffer::empty(area);

        SidebarWidget::new(&styles)
            .plan(Some(sample_plan(&["Only step"], 1)))
            .context_info("Ready")
            .render(area, &mut buf);

        let rendered = rendered_sidebar_text(&buf, area);
        assert!(rendered.contains("1 step"), "missing singular count: {rendered}");
        assert!(!rendered.contains("1 steps"), "must not pluralize one step: {rendered}");
    }

    #[test]
    fn sidebar_omits_plan_section_without_active_plan() {
        let styles = SessionStyles::new(InlineTheme::default());
        let area = Rect::new(0, 0, 60, 20);
        let mut buf = Buffer::empty(area);

        SidebarWidget::new(&styles).context_info("Ready").render(area, &mut buf);

        let rendered = rendered_sidebar_text(&buf, area);
        assert!(!rendered.contains("Plan"), "no plan section expected: {rendered}");
        assert!(rendered.contains("Context"), "other sections must still render: {rendered}");
    }

    #[test]
    fn sidebar_plan_hidden_outside_wide_mode() {
        let styles = SessionStyles::new(InlineTheme::default());
        let area = Rect::new(0, 0, 60, 20);
        let mut buf = Buffer::empty(area);

        SidebarWidget::new(&styles)
            .plan(Some(sample_plan(&["Add sidebar panel"], 1)))
            .context_info("Ready")
            .mode(LayoutMode::Standard)
            .render(area, &mut buf);

        let rendered = rendered_sidebar_text(&buf, area);
        assert!(rendered.trim().is_empty(), "sidebar must not render outside Wide: {rendered}");
    }
}