aether-wisp 0.4.35

A terminal UI for AI coding agents via the Agent Client Protocol (ACP)
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
use crate::components::common::VerticalCursor;
use crate::components::file_tree::{FileTree, FileTreeEntry, FileTreeEntryKind};
use crate::components::git_diff::{file_status_color, header_rule, push_diff_stats};
use crate::git_diff::{DiffScope, FileDiff, FileStatus, StageState};
use tui::{Component, Event, Frame, KeyCode, Line, MouseEventKind, Style, ViewContext, truncate_line, truncate_text};

const CHROME_HEIGHT: usize = 2;

pub struct FileListPanel {
    tree: FileTree,
    cursor: VerticalCursor,
    queued_comment_count: usize,
    file_count: usize,
    additions: usize,
    deletions: usize,
    focused: bool,
    file_comment_counts: Vec<usize>,
    diff_scope: DiffScope,
    scroll_consumed_this_frame: bool,
}

pub enum FileListMessage {
    Selected(usize),
    FileOpened(usize),
}

impl Default for FileListPanel {
    fn default() -> Self {
        Self {
            tree: FileTree::empty(),
            cursor: VerticalCursor::new(),
            queued_comment_count: 0,
            file_count: 0,
            additions: 0,
            deletions: 0,
            focused: false,
            file_comment_counts: Vec::new(),
            diff_scope: DiffScope::default(),
            scroll_consumed_this_frame: false,
        }
    }
}

impl FileListPanel {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn rebuild_from_files(&mut self, files: &[FileDiff]) {
        self.file_count = files.len();
        self.additions = files.iter().map(FileDiff::additions).sum();
        self.deletions = files.iter().map(FileDiff::deletions).sum();
        self.tree.rebuild_from_files(files);
        self.file_comment_counts = vec![0; files.len()];
    }

    pub fn selected_file_index(&self) -> Option<usize> {
        self.tree.selected_file_index()
    }

    pub fn selected_file_indices(&self) -> Vec<usize> {
        self.tree.selected_file_indices()
    }

    pub fn select_file_index(&mut self, file_index: usize) {
        self.tree.select_file_index(file_index);
    }

    pub fn sync_view_state(&mut self, queued_comment_count: usize, file_comment_counts: Vec<usize>) {
        self.queued_comment_count = queued_comment_count;
        self.file_comment_counts = file_comment_counts;
    }

    pub fn set_diff_scope(&mut self, diff_scope: DiffScope) {
        self.diff_scope = diff_scope;
    }

    pub fn set_focused(&mut self, focused: bool) {
        self.focused = focused;
    }

    pub(crate) fn select_relative(&mut self, delta: isize) -> Option<usize> {
        let prev_file = self.tree.selected_file_index();
        self.tree.navigate(delta);
        let new_file = self.tree.selected_file_index();
        if let Some(idx) = new_file
            && Some(idx) != prev_file
        {
            return Some(idx);
        }
        None
    }

    pub(crate) fn tree_collapse_or_parent(&mut self) {
        self.tree.collapse_or_parent();
    }

    pub(crate) fn tree_expand_or_enter(&mut self) -> Option<usize> {
        let is_file = self.tree.expand_or_enter();
        if is_file { self.tree.selected_file_index() } else { None }
    }

    fn header_row(&self, width: usize, theme: &tui::Theme) -> Line {
        let title_fg = if self.focused { theme.accent() } else { theme.text_primary() };
        let mut row = Line::default();
        row.push_text(" ");
        row.push_with_style(format!("Git Diff · {}", self.diff_scope.label()), Style::fg(title_fg).bold());
        row.push_text("  ");
        row.push_with_style(
            format!("{} file{}", self.file_count, if self.file_count == 1 { "" } else { "s" }),
            Style::fg(theme.text_primary()),
        );
        row.push_text("  ");
        push_diff_stats(&mut row, self.additions, self.deletions, theme);
        if self.queued_comment_count > 0 {
            row.push_text("  ");
            row.push_with_style(format!("{}", self.queued_comment_count), Style::fg(theme.accent()));
        }
        row.extend_bg_to_width(width);
        truncate_line(&row, width)
    }

    fn ensure_visible(&mut self, viewport_height: usize) {
        self.cursor.ensure_visible(self.tree.selected_visible(), viewport_height);
    }
}

impl Component for FileListPanel {
    type Message = FileListMessage;

    async fn on_event(&mut self, event: &Event) -> Option<Vec<Self::Message>> {
        if let Event::Mouse(mouse) = event {
            return match mouse.kind {
                MouseEventKind::ScrollUp => {
                    if self.scroll_consumed_this_frame {
                        return Some(vec![]);
                    }
                    self.scroll_consumed_this_frame = true;
                    Some(self.select_relative(-1).map(|idx| vec![FileListMessage::Selected(idx)]).unwrap_or_default())
                }
                MouseEventKind::ScrollDown => {
                    if self.scroll_consumed_this_frame {
                        return Some(vec![]);
                    }
                    self.scroll_consumed_this_frame = true;
                    Some(self.select_relative(1).map(|idx| vec![FileListMessage::Selected(idx)]).unwrap_or_default())
                }
                _ => None,
            };
        }

        let Event::Key(key) = event else {
            return None;
        };
        match key.code {
            KeyCode::Char('j') | KeyCode::Down => {
                Some(self.select_relative(1).map(|idx| vec![FileListMessage::Selected(idx)]).unwrap_or_default())
            }
            KeyCode::Char('k') | KeyCode::Up => {
                Some(self.select_relative(-1).map(|idx| vec![FileListMessage::Selected(idx)]).unwrap_or_default())
            }
            KeyCode::Char('h') | KeyCode::Left => {
                self.tree_collapse_or_parent();
                Some(vec![])
            }
            KeyCode::Enter | KeyCode::Char('l') | KeyCode::Right => {
                if let Some(idx) = self.tree_expand_or_enter() {
                    Some(vec![FileListMessage::FileOpened(idx)])
                } else {
                    Some(vec![])
                }
            }
            _ => None,
        }
    }

    fn render(&mut self, ctx: &ViewContext) -> Frame {
        let theme = &ctx.theme;
        self.scroll_consumed_this_frame = false;
        let width = ctx.size.width as usize;
        let height = ctx.size.height as usize;
        if width < 2 {
            return Frame::new((0..height).map(|_| Line::new(" ".repeat(width))).collect());
        }

        let tree_height = height.saturating_sub(CHROME_HEIGHT);
        self.ensure_visible(tree_height);

        let mut lines = Vec::with_capacity(height);
        lines.push(self.header_row(width, theme));
        lines.push(header_rule(width, theme));

        let visible_entries = self.tree.visible_entries();
        let tree_selected = self.tree.selected_visible();
        for row in 0..tree_height {
            let entry_index = row + self.cursor.scroll;
            let mut content = Line::default();
            if let Some(entry) = visible_entries.get(entry_index) {
                let is_selected = entry_index == tree_selected;
                let comments =
                    entry_file_index(entry).and_then(|index| self.file_comment_counts.get(index).copied()).unwrap_or(0);
                let indent = tree_indent(&visible_entries, entry_index);
                let flags = EntryFlags { is_selected, indent: &indent, width, comments };
                match &entry.kind {
                    FileTreeEntryKind::Directory { name, expanded, staged, .. } => {
                        render_directory_entry(&mut content, name, *expanded, *staged, entry.depth, flags, theme);
                    }
                    FileTreeEntryKind::File { name, status, staged, additions, deletions, .. } => {
                        let row = FileRow {
                            name,
                            status: *status,
                            staged: *staged,
                            additions: *additions,
                            deletions: *deletions,
                        };
                        render_file_entry(&mut content, row, flags, theme);
                    }
                }
            } else {
                content.push_text(" ".repeat(width));
            }
            lines.push(content);
        }

        lines.truncate(height);
        Frame::new(lines)
    }
}

fn entry_file_index(entry: &FileTreeEntry) -> Option<usize> {
    match &entry.kind {
        FileTreeEntryKind::File { file_index, .. } => Some(*file_index),
        FileTreeEntryKind::Directory { .. } => None,
    }
}

#[derive(Clone, Copy)]
struct EntryFlags<'a> {
    is_selected: bool,
    indent: &'a str,
    width: usize,
    comments: usize,
}

fn render_directory_entry(
    line: &mut Line,
    name: &str,
    expanded: bool,
    staged: StageState,
    depth: usize,
    flags: EntryFlags<'_>,
    theme: &tui::Theme,
) {
    let EntryFlags { is_selected, indent, width, .. } = flags;
    let icon = if expanded { "" } else { "" };
    let connector = if depth == 0 { "" } else { "" };
    let icon_gap = if depth == 0 { "  " } else { " " };
    let dir_style = row_fg_style(theme.info(), is_selected, theme);
    let indicator = if is_selected { "" } else { " " };
    let (checkbox, checkbox_color) = stage_checkbox(staged, theme);
    let prefix_width = format!("{indicator}{indent}{connector}{icon}{icon_gap}").chars().count();

    line.push_with_style(indicator, row_fg_style(theme.accent(), is_selected, theme));
    line.push_with_style(format!("{indent}{connector}"), row_fg_style(theme.muted(), is_selected, theme));
    line.push_with_style(format!("{icon}{icon_gap}"), dir_style);
    push_name_padded_to_suffix(
        line,
        &format!("{name}/"),
        dir_style.bold(),
        dir_style,
        prefix_width,
        vec![(format!(" {checkbox}"), row_fg_style(checkbox_color, is_selected, theme))],
        width,
    );
}

#[derive(Clone, Copy)]
struct FileRow<'a> {
    name: &'a str,
    status: FileStatus,
    staged: StageState,
    additions: usize,
    deletions: usize,
}

fn render_file_entry(line: &mut Line, row: FileRow<'_>, flags: EntryFlags<'_>, theme: &tui::Theme) {
    let FileRow { name, status, staged, additions, deletions } = row;
    let EntryFlags { is_selected, indent, width, comments } = flags;
    let style = row_style(is_selected, theme);
    let guide_style = row_fg_style(theme.muted(), is_selected, theme);
    let indicator = if is_selected { "" } else { " " };
    let (checkbox, checkbox_color) = stage_checkbox(staged, theme);

    let mut suffix = vec![(" ".to_string(), style)];
    if comments > 0 {
        suffix.push((format!("{comments} "), row_fg_style(theme.accent(), is_selected, theme)));
    }
    suffix.push((format!("+{additions}"), row_fg_style(theme.diff_added_fg(), is_selected, theme)));
    suffix.push((format!(" -{deletions}"), row_fg_style(theme.diff_removed_fg(), is_selected, theme)));
    suffix.push((format!(" {}", status.marker()), row_fg_style(file_status_color(status, theme), is_selected, theme)));
    suffix.push((format!(" {checkbox}"), row_fg_style(checkbox_color, is_selected, theme)));
    let prefix_width = format!("{indicator}{indent}── ").chars().count();

    line.push_with_style(indicator, row_fg_style(theme.accent(), is_selected, theme));
    line.push_with_style(format!("{indent}── "), guide_style);
    push_name_padded_to_suffix(line, name, style, style, prefix_width, suffix, width);
}

fn push_name_padded_to_suffix(
    line: &mut Line,
    name: &str,
    name_style: Style,
    pad_style: Style,
    prefix_width: usize,
    suffix: Vec<(String, Style)>,
    width: usize,
) {
    let suffix_width: usize = suffix.iter().map(|(text, _)| text.chars().count()).sum();
    let truncated = truncate_text(name, width.saturating_sub(prefix_width + suffix_width));
    line.push_with_style(truncated.as_ref(), name_style);
    let padding = width.saturating_sub(prefix_width + truncated.chars().count() + suffix_width);
    if padding > 0 {
        line.push_with_style(" ".repeat(padding), pad_style);
    }
    for (text, style) in suffix {
        line.push_with_style(text, style);
    }
    line.extend_bg_to_width(width);
}

fn stage_checkbox(staged: StageState, theme: &tui::Theme) -> (&'static str, tui::Color) {
    match staged {
        StageState::Staged => ("", theme.diff_added_fg()),
        StageState::PartiallyStaged => ("", theme.warning()),
        StageState::Unstaged => ("", theme.muted()),
    }
}

fn row_style(is_selected: bool, theme: &tui::Theme) -> Style {
    if is_selected { theme.selected_row_style() } else { Style::default() }
}

fn row_fg_style(fg: tui::Color, is_selected: bool, theme: &tui::Theme) -> Style {
    if is_selected { theme.selected_row_style_with_fg(fg) } else { Style::fg(fg) }
}

fn tree_indent(entries: &[&FileTreeEntry], index: usize) -> String {
    let Some(entry) = entries.get(index) else {
        return String::new();
    };
    if entry.depth == 0 {
        return String::new();
    }
    let mut indent = String::new();
    for level in 1..entry.depth {
        indent.push_str(if level_continues(entries, index, level) { "" } else { "  " });
    }
    indent.push(if level_continues(entries, index, entry.depth) { '' } else { '' });
    indent
}

fn level_continues(entries: &[&FileTreeEntry], index: usize, level: usize) -> bool {
    for next in &entries[index + 1..] {
        if next.depth < level {
            return false;
        }
        if next.depth == level {
            return true;
        }
    }
    false
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::git_diff::Hunk;
    use tui::{KeyEvent, KeyModifiers};

    fn modified(path: &str) -> FileDiff {
        FileDiff {
            old_path: None,
            path: path.to_string(),
            status: FileStatus::Modified,
            staged: StageState::Unstaged,
            hunks: vec![Hunk {
                header: "@@ -1 +1 @@".to_string(),
                old_start: 1,
                old_count: 1,
                new_start: 1,
                new_count: 1,
                lines: Vec::new(),
            }],
            binary: false,
        }
    }

    #[tokio::test]
    async fn active_indicator_follows_selected_directory() {
        let mut panel = FileListPanel::new();
        panel.rebuild_from_files(&[modified("lib/c.rs"), modified("src/a.rs")]);
        panel.select_file_index(0);
        panel.on_event(&Event::Key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE))).await;

        let frame = panel.render(&ViewContext::new((32, 8)));
        let lines = frame.lines();

        assert!(!lines[3].plain_text().starts_with(''), "previous file row should not keep the active indicator");
        assert!(lines[4].plain_text().starts_with(''), "selected directory row should have the active indicator");
    }
}