croft-software 0.2.32

VSCode-style TUI written in Rust
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
//! The Explorer's AGENT LANE section (#345): per coding agent, the files it
//! changed since you last reviewed them. The ledger lives in
//! [`crate::agent_lane`]; the app turns it into [`LaneRow`]s with
//! [`AgentLanePanel::set_rows`], and a click on a file row opens its diff
//! against the reviewed snapshot. An unreviewed file carries a dot; a reviewed
//! one stays listed, dimmed, until the agent touches it again.

use std::path::PathBuf;

use ratatui::{
    buffer::Buffer,
    layout::Rect,
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Paragraph, Widget},
};

use crate::theme::Theme;

const COLOR_HEADER: Color = Color::Rgb(0xE8, 0xEE, 0xF8);
const COLOR_DIM: Color = Color::Rgb(0x60, 0x68, 0x78);
const COLOR_FILE: Color = Color::Rgb(0xCC, 0xCC, 0xCC);
const COLOR_AGENT: Color = Color::Rgb(0x8f, 0xd9, 0xcf);
const COLOR_DOT: Color = Color::Rgb(0xe5, 0xc0, 0x7b);
const COLOR_ADDED: Color = Color::Rgb(0x73, 0xc9, 0x91);
const COLOR_REMOVED: Color = Color::Rgb(0xe0, 0x6c, 0x75);

/// Left indent matching the tree's `Borders::ALL` inset.
const CONTENT_INDENT: u16 = 1;

/// One row of the section: an agent, or a file under the agent above it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LaneRow {
    Agent {
        name: String,
        unreviewed: usize,
    },
    File {
        agent: String,
        path: PathBuf,
        /// What the row shows: the path relative to its workspace root.
        label: String,
        unreviewed: bool,
        /// Lines added and removed since the reviewed snapshot, when the row
        /// has one to count against.
        changes: Option<(usize, usize)>,
    },
}

pub struct AgentLanePanel {
    pub collapsed: bool,
    rows: Vec<LaneRow>,
    /// Agents whose files are folded away under their row (#345).
    collapsed_agents: std::collections::BTreeSet<String>,
    scroll: usize,
    pub theme: Theme,
    pub focused: bool,
    pub hover_pointer: Option<(u16, u16)>,

    pub last_area: Rect,
    last_header_row: u16,
    last_header_x: u16,
    last_header_w: u16,
    first_row_y: u16,
    /// Where rows start horizontally, for the dot's hit test.
    first_row_x: u16,
    visible_rows: u16,
}

impl AgentLanePanel {
    pub fn new() -> Self {
        Self {
            collapsed: true,
            rows: Vec::new(),
            collapsed_agents: std::collections::BTreeSet::new(),
            scroll: 0,
            theme: Theme::default(),
            focused: false,
            hover_pointer: None,
            last_area: Rect::default(),
            last_header_row: 0,
            last_header_x: 0,
            last_header_w: 0,
            first_row_y: 0,
            first_row_x: 0,
            visible_rows: 0,
        }
    }

    /// Replace the rows (the ledger changed), keeping the scroll in range.
    pub fn set_rows(&mut self, rows: Vec<LaneRow>) {
        self.rows = rows;
        self.scroll = self.scroll.min(self.shown().len().saturating_sub(1));
    }

    pub fn rows(&self) -> &[LaneRow] {
        &self.rows
    }

    /// Fold `agent`'s files away under its row, or unfold them.
    pub fn toggle_agent(&mut self, agent: &str) {
        if !self.collapsed_agents.remove(agent) {
            self.collapsed_agents.insert(agent.to_string());
        }
        self.scroll = self.scroll.min(self.shown().len().saturating_sub(1));
    }

    /// The rows on show: every agent, and the files of the unfolded ones.
    fn shown(&self) -> Vec<&LaneRow> {
        self.rows
            .iter()
            .filter(|r| match r {
                LaneRow::Agent { .. } => true,
                LaneRow::File { agent, .. } => !self.collapsed_agents.contains(agent),
            })
            .collect()
    }

    pub fn toggle_collapse(&mut self) {
        self.collapsed = !self.collapsed;
    }

    pub fn scroll_down(&mut self, n: usize) {
        self.scroll = (self.scroll + n).min(self.shown().len().saturating_sub(1));
    }

    pub fn scroll_up(&mut self, n: usize) {
        self.scroll = self.scroll.saturating_sub(n);
    }

    /// Header plus bottom separator when collapsed; one row per item (or a
    /// single empty-state row) when open, capped at half the shared region.
    pub fn desired_height(&self, available: u16) -> u16 {
        const BORDER: u16 = 1;
        if available == 0 {
            return 0;
        }
        let floor = 1 + BORDER;
        if self.collapsed {
            return floor.min(available);
        }
        let content = (self.shown().len() as u16).max(1);
        let half = (available / 2).max(floor);
        (1 + content + BORDER).min(half)
    }

    pub fn hit_header(&self, x: u16, y: u16) -> bool {
        y == self.last_header_row
            && x >= self.last_header_x
            && x < self.last_header_x.saturating_add(self.last_header_w)
    }

    /// Whether a click at (`x`, `y`) lands on an unreviewed file row's dot,
    /// which marks that file reviewed rather than opening its diff.
    pub fn hit_dot(&self, x: u16, y: u16) -> bool {
        let dot = self.first_row_x.saturating_add(2);
        (dot..dot.saturating_add(2)).contains(&x)
            && matches!(
                self.row_at(y),
                Some(LaneRow::File {
                    unreviewed: true,
                    ..
                })
            )
    }

    /// The row a click at `y` lands on.
    pub fn row_at(&self, y: u16) -> Option<&LaneRow> {
        if self.collapsed || self.visible_rows == 0 || y < self.first_row_y {
            return None;
        }
        let offset = (y - self.first_row_y) as usize;
        if offset >= self.visible_rows as usize {
            return None;
        }
        self.shown().get(self.scroll + offset).copied()
    }
}

impl Default for AgentLanePanel {
    fn default() -> Self {
        Self::new()
    }
}

impl Widget for &mut AgentLanePanel {
    fn render(self, area: Rect, buf: &mut Buffer) {
        let block = Block::default()
            .borders(Borders::BOTTOM)
            .border_style(Style::default().fg(self.theme.ui(COLOR_DIM)));
        let inner = block.inner(area);
        block.render(area, buf);
        self.last_area = area;
        self.visible_rows = 0;
        if inner.height == 0 || inner.width == 0 {
            return;
        }
        let inner = Rect {
            x: inner.x + CONTENT_INDENT.min(inner.width),
            width: inner.width.saturating_sub(CONTENT_INDENT),
            ..inner
        };
        let chevron = if self.collapsed {
            crate::icons::CHEVRON_CLOSED
        } else {
            crate::icons::CHEVRON_OPEN
        };
        let total: usize = self
            .rows
            .iter()
            .map(|r| match r {
                LaneRow::Agent { unreviewed, .. } => *unreviewed,
                LaneRow::File { .. } => 0,
            })
            .sum();
        let mut header = vec![
            Span::styled(
                format!("{chevron} "),
                Style::default().fg(self.theme.ui(COLOR_DIM)),
            ),
            Span::styled(
                "AGENT LANE",
                Style::default()
                    .fg(self.theme.ui(COLOR_HEADER))
                    .add_modifier(Modifier::BOLD),
            ),
        ];
        if total > 0 {
            header.push(Span::styled(
                format!("  {total}"),
                Style::default().fg(self.theme.ui(COLOR_DOT)),
            ));
        }
        Paragraph::new(Line::from(header)).render(
            Rect {
                x: inner.x,
                y: inner.y,
                width: inner.width,
                height: 1,
            },
            buf,
        );
        self.last_header_row = inner.y;
        self.last_header_x = inner.x;
        self.last_header_w = inner.width;
        if self.collapsed || inner.height < 2 {
            return;
        }
        let body_y = inner.y + 1;
        let body_h = inner.height - 1;
        self.first_row_y = body_y;
        self.first_row_x = inner.x;
        if self.rows.is_empty() {
            Paragraph::new(Line::from(Span::styled(
                "No agent has changed a file",
                Style::default().fg(self.theme.ui(COLOR_DIM)),
            )))
            .render(
                Rect {
                    x: inner.x,
                    y: body_y,
                    width: inner.width,
                    height: 1,
                },
                buf,
            );
            return;
        }
        let rows: Vec<LaneRow> = self.shown().into_iter().cloned().collect();
        self.scroll = self.scroll.min(rows.len().saturating_sub(body_h as usize));
        let shown = (body_h as usize).min(rows.len() - self.scroll);
        self.visible_rows = shown as u16;
        for i in 0..shown {
            let y = body_y + i as u16;
            let rect = Rect {
                x: inner.x,
                y,
                width: inner.width,
                height: 1,
            };
            if let Some(bg) =
                crate::widgets::hover::row_hover_bg(rect, self.hover_pointer, self.theme)
            {
                buf.set_style(rect, Style::default().bg(bg));
            }
            let line = match &rows[self.scroll + i] {
                LaneRow::Agent { name, unreviewed } => {
                    let fold = if self.collapsed_agents.contains(name) {
                        crate::icons::CHEVRON_CLOSED
                    } else {
                        crate::icons::CHEVRON_OPEN
                    };
                    let mut spans = vec![Span::styled(
                        format!("{fold} \u{25c6} {name}"),
                        Style::default()
                            .fg(self.theme.ui(COLOR_AGENT))
                            .add_modifier(Modifier::BOLD),
                    )];
                    if *unreviewed > 0 {
                        spans.push(Span::styled(
                            format!("  {unreviewed} to review"),
                            Style::default().fg(self.theme.ui(COLOR_DIM)),
                        ));
                    }
                    Line::from(spans)
                }
                LaneRow::File {
                    label,
                    unreviewed,
                    changes,
                    ..
                } => {
                    let (dot, fg) = if *unreviewed {
                        ("\u{25cf} ", COLOR_FILE)
                    } else {
                        ("  ", COLOR_DIM)
                    };
                    let mut spans = vec![
                        Span::raw("  "),
                        Span::styled(dot, Style::default().fg(self.theme.ui(COLOR_DOT))),
                        Span::styled(label.clone(), Style::default().fg(self.theme.ui(fg))),
                    ];
                    // Nothing to say for a row that matches its review.
                    if let Some((added, removed)) = changes.filter(|&(a, r)| a + r > 0) {
                        spans.push(Span::styled(
                            format!("  +{added}"),
                            Style::default().fg(self.theme.ui(COLOR_ADDED)),
                        ));
                        spans.push(Span::styled(
                            format!(" \u{2212}{removed}"),
                            Style::default().fg(self.theme.ui(COLOR_REMOVED)),
                        ));
                    }
                    Line::from(spans)
                }
            };
            Paragraph::new(line).render(rect, buf);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn rows() -> Vec<LaneRow> {
        vec![
            LaneRow::Agent {
                name: "claude".into(),
                unreviewed: 1,
            },
            LaneRow::File {
                agent: "claude".into(),
                path: PathBuf::from("/w/src/a.rs"),
                label: "src/a.rs".into(),
                unreviewed: true,
                changes: Some((3, 1)),
            },
            LaneRow::File {
                agent: "claude".into(),
                path: PathBuf::from("/w/src/b.rs"),
                label: "src/b.rs".into(),
                unreviewed: false,
                changes: Some((0, 0)),
            },
        ]
    }

    fn dump(buf: &Buffer) -> String {
        let a = buf.area;
        (a.y..a.y + a.height)
            .map(|y| {
                (a.x..a.x + a.width)
                    .map(|x| buf[(x, y)].symbol())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    #[test]
    fn open_section_lists_agents_and_files_and_maps_clicks_to_rows() {
        let mut p = AgentLanePanel::new();
        p.collapsed = false;
        p.set_rows(rows());
        let area = Rect::new(0, 0, 40, 8);
        let mut buf = Buffer::empty(area);
        Widget::render(&mut p, area, &mut buf);
        let text = dump(&buf);
        assert!(text.contains("AGENT LANE  1"), "{text}");
        assert!(text.contains("claude  1 to review"), "{text}");
        assert!(
            text.contains("\u{25cf} src/a.rs"),
            "the unreviewed file is marked: {text}"
        );
        assert!(
            text.contains("src/b.rs") && !text.contains("\u{25cf} src/b.rs"),
            "{text}"
        );
        assert!(p.hit_header(3, 0));
        assert!(matches!(p.row_at(2), Some(LaneRow::File { label, .. }) if label == "src/a.rs"));
        assert!(matches!(p.row_at(1), Some(LaneRow::Agent { .. })));
        assert_eq!(p.row_at(6), None, "below the rows");
    }

    #[test]
    fn a_collapsed_section_is_one_row_and_takes_no_row_clicks() {
        let mut p = AgentLanePanel::new();
        p.set_rows(rows());
        assert_eq!(p.desired_height(40), 2);
        let area = Rect::new(0, 0, 40, 2);
        let mut buf = Buffer::empty(area);
        Widget::render(&mut p, area, &mut buf);
        assert_eq!(p.row_at(1), None);
        p.toggle_collapse();
        assert_eq!(p.desired_height(40), 5, "header, three rows, border");
        assert_eq!(p.desired_height(6), 3, "capped at half the region");
    }

    #[test]
    fn an_agents_row_folds_its_files_away_and_back() {
        // #345: one agent folds; the other's rows stay put.
        let mut p = AgentLanePanel::new();
        p.collapsed = false;
        let mut all = rows();
        all.push(LaneRow::Agent {
            name: "codex".into(),
            unreviewed: 1,
        });
        all.push(LaneRow::File {
            agent: "codex".into(),
            path: PathBuf::from("/w/src/c.rs"),
            label: "src/c.rs".into(),
            unreviewed: true,
            changes: None,
        });
        p.set_rows(all);
        let area = Rect::new(0, 0, 40, 12);
        let render = |p: &mut AgentLanePanel| {
            let mut buf = Buffer::empty(area);
            p.render(area, &mut buf);
        };
        render(&mut p);
        let first = p.first_row_y;
        assert_eq!(p.desired_height(40), 1 + 5 + 1);
        p.toggle_agent("claude");
        render(&mut p);
        assert_eq!(
            p.desired_height(40),
            1 + 3 + 1,
            "claude's two files folded away"
        );
        assert!(matches!(p.row_at(first), Some(LaneRow::Agent { name, .. }) if name == "claude"));
        assert!(
            matches!(p.row_at(first + 1), Some(LaneRow::Agent { name, .. }) if name == "codex")
        );
        assert!(
            matches!(p.row_at(first + 2), Some(LaneRow::File { agent, .. }) if agent == "codex")
        );
        p.toggle_agent("claude");
        render(&mut p);
        assert!(
            matches!(p.row_at(first + 1), Some(LaneRow::File { agent, .. }) if agent == "claude")
        );
    }
}