diffler 0.14.1

Terminal code review for AI coding agents
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! The comments sidebar: a navigator down the review's comments that drives
//! the diff cursor. Selecting a comment seats the cursor on it, so the pane's
//! own verbs (reply, resolve, delete, yank) act on the right one with no
//! separate handling.

use super::{DiffRow, Pane};
use crate::app::App;

impl super::DiffView {
    pub fn comments_open(&self) -> bool {
        self.comments_open
    }

    pub fn comments_cursor(&self) -> usize {
        self.comments_cursor
    }
}

impl App {
    /// Where a comment's file sits in the diff, `usize::MAX` when the diff no
    /// longer carries it. Sorting the sidebar and asking whether a comment is
    /// orphaned are the same question.
    fn file_rank(&self, path: &str) -> usize {
        self.diff.as_ref().map_or(usize::MAX, |diff| {
            diff.model_for_rows(&self.review)
                .files
                .iter()
                .position(|file| file.path == path)
                .unwrap_or(usize::MAX)
        })
    }

    /// Comment ids of the active review, in the order the sidebar lists them:
    /// by file as the diff orders them, then by line.
    pub(crate) fn comment_order(&self) -> Vec<String> {
        let Some(diff) = self.diff.as_ref() else {
            return Vec::new();
        };
        let session = self.review.session_for(&diff.source);
        let mut ordered: Vec<&diffler_core::session::Comment> = session.comments.iter().collect();
        ordered.sort_by_key(|comment| {
            (
                self.file_rank(&comment.anchor.file),
                comment.anchor.line.unwrap_or(0),
            )
        });
        ordered.iter().map(|comment| comment.id.clone()).collect()
    }

    /// The sidebar is a pane of the diff screen, so it opens over a review
    /// that is already on screen.
    pub(crate) fn toggle_comments_sidebar(&mut self) {
        let Some(diff) = self.diff.as_mut() else {
            return;
        };
        diff.comments_open = !diff.comments_open;
        if !diff.comments_open {
            if diff.focus == Pane::Comments {
                diff.focus = Pane::Diff;
            }
            return;
        }
        let count = self.comment_order().len();
        // an empty sidebar is an answer, so it opens with nothing to focus
        if count == 0 {
            return;
        }
        if let Some(diff) = self.diff.as_mut() {
            diff.comments_cursor = diff.comments_cursor.min(count - 1);
            diff.focus = Pane::Comments;
        }
        self.seat_cursor_on_selected_comment();
    }

    pub(crate) fn comments_step(&mut self, delta: isize) {
        let count = self.comment_order().len();
        let Some(diff) = self.diff.as_mut() else {
            return;
        };
        if count == 0 {
            return;
        }
        diff.comments_cursor = diff
            .comments_cursor
            .saturating_add_signed(delta)
            .min(count - 1);
        self.seat_cursor_on_selected_comment();
    }

    pub(crate) fn comments_to(&mut self, index: usize) {
        let count = self.comment_order().len();
        let Some(diff) = self.diff.as_mut() else {
            return;
        };
        if count == 0 {
            return;
        }
        diff.comments_cursor = index.min(count - 1);
        self.seat_cursor_on_selected_comment();
    }

    /// Pull the sidebar selection back into range after the comment list
    /// shrank under it, and re-seat the diff cursor the verbs read.
    pub(crate) fn resettle_comments_cursor(&mut self) {
        let Some(diff) = self.diff.as_ref() else {
            return;
        };
        if !diff.comments_open {
            return;
        }
        self.comments_to(diff.comments_cursor);
    }

    /// The comment the sidebar has selected.
    pub(crate) fn selected_comment_id(&self) -> Option<String> {
        let index = self.diff.as_ref()?.comments_cursor;
        self.comment_order().get(index).cloned()
    }

    /// Whether the selected comment is anchored to a file this diff no longer
    /// carries, so it has no row in the pane.
    pub(crate) fn selected_comment_is_orphan(&self) -> bool {
        self.selected_comment_id()
            .is_some_and(|id| self.comment_is_orphan(&id))
    }

    /// Whether `id` is anchored to a file outside this diff. The comment
    /// survives, since the file can come back on the next edit.
    pub(crate) fn comment_is_orphan(&self, id: &str) -> bool {
        let Some(diff) = self.diff.as_ref() else {
            return false;
        };
        self.review
            .session_for(&diff.source)
            .comment(id)
            .is_some_and(|comment| self.file_rank(&comment.anchor.file) == usize::MAX)
    }

    /// Delete the comment the sidebar has selected, by id: an orphan has no
    /// row for the cursor, and the cursor-driven delete would take whichever
    /// comment it was last left on.
    pub(crate) fn delete_selected_comment(&mut self) {
        let Some(id) = self.selected_comment_id() else {
            self.info("no comment selected");
            return;
        };
        self.confirm_delete_comment(&id);
    }

    /// Whether a column falls in the open comments sidebar.
    pub(crate) fn comments_col(&self, col: u16) -> bool {
        self.diff
            .as_ref()
            .is_some_and(|diff| diff.comments_open && col >= diff.comments_rect.x)
    }

    /// The comment a click lands on, through the last render's line table so
    /// a wrapped body line picks the comment it belongs to.
    pub(crate) fn comments_row_at(&self, col: u16, row: u16) -> Option<usize> {
        let diff = self.diff.as_ref()?;
        if !diff.comments_open {
            return None;
        }
        let rect = diff.comments_rect;
        if col < rect.x || row < rect.y || row >= rect.y.saturating_add(rect.height) {
            return None;
        }
        let line = (row - rect.y) as usize + diff.comments_scroll;
        diff.comment_lines.get(line).copied().flatten()
    }

    /// Move the diff cursor onto the selected comment, switching files when it
    /// lives in another one. This is what makes the pane's verbs apply.
    pub(crate) fn seat_cursor_on_selected_comment(&mut self) {
        let order = self.comment_order();
        let Some(diff) = self.diff.as_ref() else {
            return;
        };
        let Some(id) = order.get(diff.comments_cursor).cloned() else {
            return;
        };
        self.focus_comment(&id);
    }

    /// Enter the slide that holds `id`, so the walkthrough layout never shows
    /// a comment outside the slide on screen: the stop it is the primary of,
    /// else the stop whose region covers it, else a slide of its own. A
    /// comment reached this way always belongs to the open source's own
    /// walkthrough, since that source carries no other. Every route into a
    /// comment calls this; in any other layout it does nothing.
    pub(crate) fn enter_slide_for_comment(&mut self, id: &str) {
        let Some(diff) = self.diff.as_ref() else {
            return;
        };
        if diff.layout != crate::config::FileLayout::Walkthrough || self.comment_is_orphan(id) {
            return;
        }
        let session = self.review.session_for(&diff.source);
        let Some(walkthrough) = diff.active_walkthrough(session) else {
            return;
        };
        let holds = |stop: &String| {
            session
                .comments
                .iter()
                .position(|comment| comment.id == *stop)
                .is_some_and(|primary| {
                    crate::app::walkthrough::slide_comments(session, primary)
                        .into_iter()
                        .filter_map(|index| session.comments.get(index))
                        .any(|comment| comment.id == id)
                })
        };
        let slide = walkthrough
            .stops
            .iter()
            .position(|stop| stop == id)
            .or_else(|| walkthrough.stops.iter().position(holds));
        // the stop's own seating bands its region and opens its file, the
        // same arrival the sidebar gives
        if let Some(index) = slide {
            self.seat_stop(index);
            return;
        }
        let Some(diff) = self.diff.as_mut() else {
            return;
        };
        diff.slide = Some(super::Slide::AdHoc(id.to_owned()));
        diff.referenced = None;
        diff.mark_rows_dirty();
    }

    /// Seat the diff cursor on the comment with `id`. Reports whether the
    /// comment's file is part of this diff at all.
    pub(crate) fn focus_comment(&mut self, id: &str) -> bool {
        self.enter_slide_for_comment(id);
        let Some(diff) = self.diff.as_ref() else {
            return false;
        };
        let session = self.review.session_for(&diff.source);
        let Some(comment_index) = session.comments.iter().position(|comment| comment.id == id)
        else {
            return false;
        };
        let Some(file) = session
            .comments
            .get(comment_index)
            .map(|c| c.anchor.file.clone())
        else {
            return false;
        };
        let model = diff.model_for_rows(&self.review);
        let Some(file_index) = model.files.iter().position(|entry| entry.path == file) else {
            self.info("comment file is not in this diff");
            return false;
        };
        let span = session
            .comments
            .get(comment_index)
            .and_then(|comment| comment.anchor.span());
        let review = &self.review;
        let Some(diff) = self.diff.as_mut() else {
            return false;
        };
        let seated = diff
            .seat_on(review, file_index, |row| {
                matches!(row, DiffRow::Comment { comment, line: 0, .. } if *comment == comment_index)
            })
            .is_some();
        // a jump lands on the card, so the lines it speaks about are banded to
        // say which of the code around it the reader was sent to
        diff.referenced =
            span.and_then(|(line, end)| diff.span_rows(review, file_index, line, end));
        seated
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::Pane;
    use crate::config::LoadedConfig;
    use crate::keymap::Action;
    use crate::test_support::{Fixture, key, standard_fixture};
    use diffler_core::session::Anchor;

    fn anchor(file: &str, line: u32) -> Anchor {
        Anchor {
            file: file.to_owned(),
            line: Some(line),
            line_end: None,
            on_old_side: false,
            line_text: None,
        }
    }

    /// Two comments in different files, so stepping has to switch files.
    fn app_with_comments() -> (Fixture, App) {
        let fixture = standard_fixture();
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        app.author = "reviewer".to_owned();
        app.review
            .session
            .add_comment(anchor("src/lib.rs", 2), "reviewer", "why 42?");
        app.review
            .session
            .add_comment(anchor("todo.md", 1), "reviewer", "stale note");
        app.open_working_tree_diff(None);
        (fixture, app)
    }

    fn tree_cursor_on_selected(app: &App) -> bool {
        let diff = app.diff.as_ref().expect("diff");
        let rows = super::super::sidebar_rows(diff, &app.review);
        matches!(
            rows.get(diff.tree_cursor).map(|row| &row.node),
            Some(crate::tree::TreeNode::File { index, .. }) if *index == diff.selected
        )
    }

    #[test]
    fn jumping_unfolds_the_directory_holding_the_comment() {
        let (_fixture, mut app) = app_with_comments();
        app.diff
            .as_mut()
            .expect("diff")
            .folded_dirs
            .insert("src".to_owned());

        app.handle(key('C'));

        let diff = app.diff.as_ref().expect("diff");
        assert!(!diff.folded_dirs.contains("src"), "the folder opened");
        assert!(tree_cursor_on_selected(&app));
    }

    #[test]
    fn jumping_unfolds_the_review_bucket_holding_the_comment() {
        let (_fixture, mut app) = app_with_comments();
        let diff = app.diff.as_mut().expect("diff");
        diff.layout = crate::config::FileLayout::Review;
        diff.bucket_folds.toggle_fold(crate::tree::Bucket::ToReview);

        app.handle(key('C'));

        assert!(
            !app.diff
                .as_ref()
                .expect("diff")
                .bucket_folds
                .is_folded(crate::tree::Bucket::ToReview),
            "the bucket opened"
        );
        assert!(tree_cursor_on_selected(&app));
    }

    #[test]
    fn jumping_leaves_the_other_layout_folds_alone() {
        let (_fixture, mut app) = app_with_comments();
        let diff = app.diff.as_mut().expect("diff");
        diff.folded_dirs.insert("src".to_owned());

        app.handle(key('C'));

        let diff = app.diff.as_ref().expect("diff");
        assert!(
            diff.bucket_folds.is_folded(crate::tree::Bucket::Viewed),
            "the review layout keeps its collapsed viewed pile"
        );
    }

    /// A file can leave the diff under an open review (the agent reverts it),
    /// stranding its comments with no row in the pane.
    #[test]
    fn deleting_an_orphaned_comment_takes_that_one_and_no_other() {
        let (_fixture, mut app) = app_with_comments();
        app.review
            .session
            .add_comment(anchor("gone.rs", 1), "reviewer", "orphan");
        app.handle(key('C'));
        app.handle(key('G'));
        assert!(app.selected_comment_is_orphan(), "the orphan sorts last");

        app.handle(key('d'));
        app.handle(key('y'));

        let left: Vec<&str> = app
            .review
            .session
            .comments
            .iter()
            .map(|comment| comment.body.as_str())
            .collect();
        assert_eq!(left, vec!["why 42?", "stale note"], "only the orphan went");
    }

    /// A verb that reads the diff cursor or the selected file finds neither on
    /// an orphan: `v` would mark a file the reader never opened as viewed, and
    /// `y`/`e` would take a third, unrelated file.
    #[test]
    fn an_orphaned_comment_declines_the_verbs_that_need_a_row() {
        for verb in ['r', 'R', 'c', 'V', 'v', 'y', 'e'] {
            let (_fixture, mut app) = app_with_comments();
            app.review
                .session
                .add_comment(anchor("gone.rs", 1), "reviewer", "orphan");
            app.handle(key('C'));
            app.handle(key('G'));
            assert!(app.selected_comment_is_orphan());

            app.handle(key(verb));

            assert!(!app.composer_open(), "{verb}: no composer opened");
            assert!(
                app.review.session.viewed.is_empty(),
                "{verb}: nothing was marked viewed"
            );
            assert!(
                app.pending_clipboard.is_none(),
                "{verb}: nothing was yanked"
            );
            assert!(app.pending_editor.is_none(), "{verb}: no editor was opened");
            assert!(
                app.message
                    .as_ref()
                    .is_some_and(|m| m.text.contains("not in this diff")),
                "{verb}: {:?}",
                app.message
            );
        }
    }

    /// The review-wide verbs address the whole review, so an orphan sitting
    /// under the cursor is no reason to refuse them.
    #[test]
    fn an_orphaned_selection_still_allows_the_verbs_that_need_no_row() {
        let (_fixture, mut app) = app_with_comments();
        app.review
            .session
            .add_comment(anchor("gone.rs", 1), "reviewer", "orphan");
        app.handle(key('C'));
        app.handle(key('G'));
        assert!(app.selected_comment_is_orphan());

        app.handle(key('D'));

        assert!(
            matches!(app.modal, Some(crate::app::Modal::Confirm { .. })),
            "D starts the review wipe: {:?}",
            app.message
        );
    }

    #[test]
    fn wiping_the_review_pulls_the_sidebar_selection_back_into_range() {
        let (_fixture, mut app) = app_with_comments();
        app.review
            .session
            .add_comment(anchor("todo.md", 2), "reviewer", "from the forge");
        let last = app.review.session.comments.len() - 1;
        app.review.session.comments[last].remote_id = Some("9".into());
        app.handle(key('C'));
        app.handle(key('j'));
        app.handle(key('j'));

        app.handle(key('D'));
        app.handle(key('y'));

        let diff = app.diff.as_ref().expect("diff");
        assert_eq!(app.review.session.comments.len(), 1, "the forge one stays");
        assert_eq!(diff.comments_cursor(), 0, "the selection follows it");
    }

    #[test]
    fn shift_d_from_the_sidebar_clears_the_whole_review_after_a_confirm() {
        let (_fixture, mut app) = app_with_comments();
        app.handle(key('C'));

        app.handle(key('D'));
        assert!(
            matches!(app.modal, Some(crate::app::Modal::Confirm { .. })),
            "delete-all asks first"
        );
        app.handle(key('y'));

        assert!(app.review.session.comments.is_empty());
    }

    #[test]
    fn c_on_the_status_screen_opens_no_review() {
        let fixture = standard_fixture();
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        app.handle(key('C'));
        assert!(
            app.diff.is_none(),
            "the comments sidebar is a pane of a review, not a way into one"
        );
    }

    #[test]
    fn c_opens_the_sidebar_and_seats_the_diff_cursor_on_the_first_comment() {
        let (_fixture, mut app) = app_with_comments();
        app.handle(key('C'));
        let diff = app.diff.as_ref().expect("diff");
        assert!(diff.comments_open());
        assert_eq!(diff.focus, Pane::Comments);
        assert!(matches!(
            diff.rows().get(diff.cursor),
            Some(DiffRow::Comment { line: 0, .. })
        ));
    }

    #[test]
    fn stepping_the_sidebar_follows_a_comment_into_another_file() {
        let (_fixture, mut app) = app_with_comments();
        app.handle(key('C'));
        let first = app.diff.as_ref().expect("diff").selected;
        app.handle(key('j'));
        let diff = app.diff.as_ref().expect("diff");
        assert_eq!(diff.comments_cursor(), 1);
        assert_ne!(diff.selected, first, "the pane switched to the other file");
        assert!(
            matches!(
                diff.rows().get(diff.cursor),
                Some(DiffRow::Comment { line: 0, .. })
            ),
            "the cursor lands on the comment in its own file"
        );
    }

    #[test]
    fn a_comment_verb_from_the_sidebar_acts_on_the_selected_comment() {
        let (_fixture, mut app) = app_with_comments();
        app.handle(key('C'));
        app.handle(key('j'));
        // `d` is the diff pane's own delete and reaches the selection untouched
        app.handle(key('d'));
        app.handle(key('y'));
        let bodies: Vec<&str> = app
            .review
            .session
            .comments
            .iter()
            .map(|c| c.body.as_str())
            .collect();
        assert_eq!(bodies, vec!["why 42?"], "the selected one went");
    }

    #[test]
    fn enter_leaves_the_sidebar_for_the_diff_and_c_closes_it() {
        let (_fixture, mut app) = app_with_comments();
        app.handle(key('C'));
        app.dispatch(Action::Open);
        assert_eq!(app.diff.as_ref().expect("diff").focus, Pane::Diff);
        assert!(app.diff.as_ref().expect("diff").comments_open());
        app.handle(key('C'));
        assert!(!app.diff.as_ref().expect("diff").comments_open());
    }

    #[test]
    fn h_and_l_walk_files_diff_comments_and_stop_at_the_ends() {
        let (_fixture, mut app) = app_with_comments();
        app.handle(key('C'));
        app.handle(key('h'));
        assert_eq!(app.diff.as_ref().expect("diff").focus, Pane::Diff);
        app.handle(key('h'));
        assert_eq!(app.diff.as_ref().expect("diff").focus, Pane::List);
        app.handle(key('h'));
        assert_eq!(app.diff.as_ref().expect("diff").focus, Pane::List);
        app.handle(key('l'));
        assert_eq!(app.diff.as_ref().expect("diff").focus, Pane::Diff);
        app.handle(key('l'));
        assert_eq!(app.diff.as_ref().expect("diff").focus, Pane::Comments);
    }

    #[test]
    fn opening_with_no_comments_shows_the_empty_sidebar() {
        let fixture = standard_fixture();
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        app.open_working_tree_diff(None);
        let before = app.diff.as_ref().expect("diff").focus;

        app.handle(key('C'));

        let diff = app.diff.as_ref().expect("diff");
        assert!(diff.comments_open(), "the empty sidebar still opens");
        assert_eq!(diff.focus, before, "nothing to select, so focus holds");
    }
}