diffler 0.20.0

Standalone magit-style git TUI and code reviewer, on its own or with your coding agent
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
//! Tests for the walkthrough layout, its slides and stop cards.

use super::*;

/// The stop list replaces the file list: one row per stop, in the
/// agent's order, with no group headers between them. A walkthrough with
/// no summary has no leading row at all.
#[test]
fn a_walkthrough_with_no_summary_lists_only_its_stops() {
    let fixture = standard_fixture();
    let app = walkthrough_app(&fixture);
    assert_eq!(
        tree_kinds(&app),
        vec![
            "stop:0".to_owned(),
            "stop:1".to_owned(),
            "stop:2".to_owned()
        ]
    );
}

/// A walkthrough with a summary lists it as the leading row.
#[test]
fn a_walkthrough_with_a_summary_lists_it_as_the_leading_row() {
    let fixture = standard_fixture();
    let app = walkthrough_app_with_summary(&fixture);
    assert_eq!(
        tree_kinds(&app),
        vec![
            "walkthrough_summary".to_owned(),
            "stop:0".to_owned(),
            "stop:1".to_owned(),
            "stop:2".to_owned()
        ]
    );
}

/// Selecting the leading row shows the summary slide.
#[test]
fn the_leading_summary_row_selects_the_summary_slide() {
    let fixture = standard_fixture();
    let mut app = walkthrough_app_with_summary(&fixture);
    assert_eq!(
        tree_cursor(&app),
        1,
        "starts on the first stop, one past the summary"
    );

    app.diff_tree_to(0);

    assert_eq!(
        app.diff.as_ref().expect("diff view").slide,
        Some(Slide::Summary)
    );
    assert_eq!(tree_cursor(&app), 0);
}

/// The summary slide renders one card and no diff rows at all, the way a
/// stop with no anchored line already shows its own card alone.
#[test]
fn the_summary_slide_shows_its_card_and_no_diff_rows() {
    let fixture = standard_fixture();
    let mut app = walkthrough_app_with_summary(&fixture);

    app.diff_tree_to(0);

    assert!(
        rows(&app)
            .iter()
            .all(|row| matches!(row, DiffRow::Summary { .. })),
        "{:?}",
        rows(&app)
    );
    assert!(!rows(&app).is_empty());
}

/// A `mermaid` fence in the summary renders as a figure through the same
/// path a comment's body does.
#[test]
fn a_mermaid_fence_in_the_summary_becomes_a_figure() {
    let fixture = standard_fixture();
    let mut app = walkthrough_app(&fixture);
    crate::test_support::set_walkthrough_summary(
        &mut app,
        "w1",
        "why\n\n```mermaid\nflowchart LR\n  a --> b\n```\n",
    );
    app.diff.as_mut().unwrap().invalidate();
    app.seat_summary();

    let diff = app.diff.as_ref().expect("diff view");
    let key = crate::app::walkthrough::summary_figure_key("w1");
    assert!(
        diff.figures.get(&key).is_some_and(|cached| cached
            .blocks
            .iter()
            .any(|block| matches!(block, crate::app::walkthrough::Block::Figure(_)))),
        "the fence parsed into a figure block"
    );
}

const SUMMARY_WITH_FLOWCHART: &str = r"Under Rosetta 2, `vcmpss` with the NEQ, NLT or NLE predicate writes its mask into a register, and if that register is then reloaded by a full width VEX load, later scalar reads of it still return the old mask. Games then compute NaN from finite inputs (in DOAX3 a bone slerp writes the invalid matrix marker and whole body parts vanish). This PR adds a macOS entry to the existing `Patches` table that upstream's ahead-of-time static patcher applies, and extends the patcher's gap sweep so compares outside EH frame functions are patched too.

```mermaid
flowchart TD
  A[module.cpp static patching on macOS] --> B[PatchSegmentStatically: EH frame functions]
  A --> C[PatchUncoveredCpuInstructions: gaps between them]
  B --> D[FindMatchingPatch / TryPatch over Patches]
  C -->|FindScalarCompareInstructionStart| D
  D -->|VCMPSS + FilterNegatedScalarCompare| E[GenerateNegatedScalarCompare trampoline]
  E --> F[vcmpss with plain predicate, then vxorps lane 0]
```";

/// The summary's flowchart opens full screen like a stop's: the reader
/// walks onto it in the pane and presses `o`, even after the rows were
/// rebuilt under them.
#[test]
fn the_summarys_flowchart_opens_full_screen() {
    let mut terminal =
        ratatui::Terminal::new(ratatui::backend::TestBackend::new(145, 43)).expect("terminal");
    let mut draw = |app: &mut App| {
        terminal
            .draw(|frame| crate::ui::draw(frame, app))
            .expect("draw");
    };
    let fixture = standard_fixture();
    let mut app = App::new(fixture.review(), LoadedConfig::default());
    let crate::mcp::McpResponse::WalkthroughPublished(published) =
        app.handle_mcp(crate::mcp::McpRequestKind::PublishWalkthrough {
            id: None,
            title: "flow".to_owned(),
            stops: vec![crate::mcp::StopParams {
                id: None,
                title: "The answer".to_owned(),
                anchor: Some("src/lib.rs#answer".to_owned()),
                body: "why".to_owned(),
                notes: None,
            }],
            skipped: None,
            summary: Some(SUMMARY_WITH_FLOWCHART.to_owned()),
        })
    else {
        panic!("expected a published walkthrough");
    };
    app.open_walkthrough(&published.id, Slide::Summary);
    draw(&mut app);
    let request = app.pending_walkthrough.take().expect("an anchor read");
    let read = diffler_core::review::Review::compute_walkthrough_files(
        &app.review.repo_root,
        request.read_rev.as_deref(),
        request.read_first,
        &request.files,
    );
    app.handle(AppEvent::WalkthroughAnchors {
        contents: read.contents,
        pin_broken: read.pin_broken,
        token: request.token,
    });
    draw(&mut app);
    app.handle(key('l'));
    app.handle(key('G'));
    for _ in 0..6 {
        app.handle(key('k'));
    }
    // a background result (highlighting, anchors) rebuilds the rows
    // under the reader, which must leave the cursor where it was
    let diff = app.diff.as_mut().expect("diff");
    diff.mark_rows_dirty();
    diff.ensure_rows(&app.review);
    app.handle(key('o'));
    assert_eq!(app.screen(), Screen::Graph, "{:?}", app.message);
}

/// `display_order` drives the file walks, so it has to be the stops' files
/// in stop order with the repeats dropped.
#[test]
fn the_walkthrough_layout_orders_files_by_their_stops() {
    let fixture = standard_fixture();
    let app = walkthrough_app(&fixture);
    let diff = app.diff.as_ref().expect("diff view");
    let model = diff.model(&app.review);
    let session = app.review.session_for(&diff.source);
    let paths: Vec<&str> = diff
        .display_order(model, session)
        .into_iter()
        .filter_map(|index| model.files.get(index))
        .map(|file| file.path.as_str())
        .collect();
    assert_eq!(paths, ["todo.md", "src/lib.rs"]);
}

/// `t` reaches the walkthrough layout only on a walkthrough's own source,
/// even when a walkthrough exists elsewhere.
#[test]
fn t_cycles_into_the_walkthrough_only_on_its_own_source() {
    let fixture = standard_fixture();
    let mut app = diff_app(&fixture);
    seat_walkthrough(&mut app);
    for _ in 0..3 {
        app.handle(key('t'));
    }
    assert_eq!(
        layout_of(&app),
        crate::config::FileLayout::Tree,
        "a walkthrough elsewhere never enters this source's cycle"
    );

    // `open_walkthrough` seats the layout on Walkthrough directly, so the
    // cycle from here runs Tree, Review, Kinds, back to Walkthrough
    app.open_walkthrough("w1", Slide::Stop(0));
    let layouts: Vec<crate::config::FileLayout> = (0..4)
        .map(|_| {
            app.handle(key('t'));
            layout_of(&app)
        })
        .collect();
    assert_eq!(
        layouts,
        [
            crate::config::FileLayout::Tree,
            crate::config::FileLayout::Review,
            crate::config::FileLayout::Kinds,
            crate::config::FileLayout::Walkthrough,
        ]
    );
}

/// A clean tree gives tree/review/kinds nothing to list, so `t` cycles
/// back to the walkthrough.
#[test]
fn t_stays_on_the_walkthrough_when_the_diff_has_no_files_of_its_own() {
    let fixture = Fixture::new();
    fixture.write("README.md", "hello\n");
    fixture.commit_all("initial commit");
    let mut app = App::new(fixture.review(), LoadedConfig::default());
    crate::test_support::seat_walkthrough(
        &mut app,
        "tour",
        &[("Base", Some("README.md:1"), "why hello")],
    );
    app.open_walkthrough("w1", Slide::Stop(0));
    assert_eq!(layout_of(&app), crate::config::FileLayout::Walkthrough);

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

    assert_eq!(
        layout_of(&app),
        crate::config::FileLayout::Walkthrough,
        "tree/review/kinds would list nothing; t stays put"
    );
}

fn layout_of(app: &App) -> crate::config::FileLayout {
    app.diff.as_ref().expect("diff view").layout
}

/// Cycling into the walkthrough must show its stop cards immediately, and
/// cycling back out must drop them and any span band with them.
#[test]
fn cycling_into_and_out_of_the_walkthrough_toggles_its_stop_cards() {
    let fixture = standard_fixture();
    let mut app = App::new(fixture.review(), LoadedConfig::default());
    app.author = "reviewer".to_owned();
    seat_walkthrough(&mut app);
    app.open_walkthrough_diff("w1");
    resolve_walkthrough(&mut app);
    assert_eq!(layout_of(&app), crate::config::FileLayout::Tree);

    for _ in 0..3 {
        app.handle(key('t'));
    }
    assert_eq!(layout_of(&app), crate::config::FileLayout::Walkthrough);
    app.diff.as_mut().unwrap().ensure_rows(&app.review);
    assert!(
        stop_card_rows(&app) > 0,
        "the walkthrough shows its stop card once cycled in"
    );
    let windowed = line_rows(&app);
    assert!(
        shown_line_numbers(&app).iter().all(|no| *no <= 3),
        "and only the current stop's own span"
    );

    app.handle(key('t'));
    assert_eq!(layout_of(&app), crate::config::FileLayout::Tree);
    app.diff.as_mut().unwrap().ensure_rows(&app.review);
    assert!(
        line_rows(&app) > windowed,
        "leaving the walkthrough shows the whole file again"
    );
    assert!(
        app.diff.as_ref().expect("diff view").referenced.is_none(),
        "leaving the walkthrough drops the span band too"
    );
}

/// Diff-line rows on screen, deletions included.
fn line_rows(app: &App) -> usize {
    rows(app)
        .iter()
        .filter(|row| matches!(row, DiffRow::Line { .. }))
        .count()
}

/// Rows of the current stop's own card on screen. Row 0 of the sidebar is
/// the leading all-slides row, so a stop's own row sits one past it.
fn stop_card_rows(app: &App) -> usize {
    let diff = app.diff.as_ref().expect("diff view");
    let session = app.review.session_for(&diff.source);
    let Some(walkthrough) = diff.active_walkthrough(session) else {
        return 0;
    };
    let offset = super::stop_row_offset(walkthrough);
    let Some(current) = diff
        .tree_cursor
        .checked_sub(offset)
        .and_then(|stop| walkthrough.stops.get(stop))
        .and_then(|id| session.comments.iter().position(|c| c.id == *id))
    else {
        return 0;
    };
    rows(app)
        .iter()
        .filter(|row| matches!(row, DiffRow::Comment { comment, .. } if *comment == current))
        .count()
}

/// A stop seats the reader on the first row of the span the agent named,
/// in the file that holds it, and shows that span.
#[test]
fn moving_onto_a_stop_seats_the_cursor_on_its_span() {
    let fixture = standard_fixture();
    let mut app = walkthrough_app(&fixture);
    // stop 2 anchors src/lib.rs#answer, whose definition is lines 1..=3
    app.handle(key('j'));
    app.handle(key('j'));
    assert_eq!(selected_path(&app), "src/lib.rs");
    let diff = app.diff.as_ref().expect("diff view");
    assert_eq!(
        diff.cursor, 1,
        "the cursor lands on the first row of the span"
    );
    let last = diff.rows().len().saturating_sub(1);
    let lines: Vec<u32> = (diff.cursor..=last)
        .filter_map(|row| match diff.rows().get(row) {
            Some(DiffRow::Line { hunk, line, .. }) => diff
                .model(&app.review)
                .files
                .get(diff.selected)
                .and_then(|file| file.hunks.get(*hunk))
                .and_then(|hunk| hunk.lines.get(*line))
                .and_then(|line| line.new_no),
            _ => None,
        })
        .collect();
    assert_eq!(lines, [1, 2, 3], "the slide shows the whole definition");
}

/// A stop with no anchor leaves the pane where the reader had it.
#[test]
fn an_anchorless_stop_leaves_the_pane_alone() {
    let fixture = standard_fixture();
    let mut app = walkthrough_app(&fixture);
    app.handle(key('j'));
    let seated = selected_path(&app);
    assert_eq!(seated, "todo.md");
    app.handle(key('k'));
    assert_eq!(selected_path(&app), seated, "stop 1 anchors nothing");
    assert_eq!(
        app.diff.as_ref().expect("diff view").referenced,
        None,
        "and bands nothing"
    );
}

/// A stop is a comment, so `r` on its card answers it in its own thread.
#[test]
fn r_on_a_stop_card_replies_to_that_stop() {
    let fixture = standard_fixture();
    let mut app = walkthrough_app(&fixture);
    app.handle(key('j'));
    app.handle(key('j'));
    enter_diff_pane(&mut app);
    let card = rows(&app)
        .iter()
        .position(|row| matches!(row, DiffRow::Comment { line: 0, .. }))
        .expect("a stop card");
    app.diff.as_mut().expect("diff view").cursor = card;
    app.handle(key('r'));
    assert!(app.composer_open());
    type_text(&mut app, "why not 43?");
    app.handle(key('\n'));

    let source = app.active_review_source();
    let stop = app
        .review
        .session_for(&source)
        .comment("stop-2")
        .expect("the third stop's comment");
    assert_eq!(stop.replies.len(), 1);
    assert_eq!(stop.replies[0].body, "why not 43?");
    assert_eq!(stop.status, CommentStatus::Replied);
}

/// The stops are comments, so the pane that lists comments lists them
/// with no handling of its own.
#[test]
fn the_comments_pane_lists_the_stops() {
    let fixture = standard_fixture();
    let mut app = walkthrough_app(&fixture);
    app.handle(key('C'));
    assert_eq!(
        app.comment_order(),
        vec![
            "stop-2".to_owned(),
            "stop-0".to_owned(),
            "stop-1".to_owned()
        ],
        "by file as the diff orders them, then by line"
    );
}

/// A comment the reader left, on a line of the open review.
fn add_comment(app: &mut App, file: &str, line: u32, body: &str) -> String {
    let source = app.active_review_source();
    let id = app
        .review
        .session_for_mut(&source)
        .add_comment(
            Anchor {
                file: file.to_owned(),
                line: Some(line),
                line_end: None,
                on_old_side: false,
                line_text: None,
            },
            "reviewer",
            body,
        )
        .id
        .clone();
    let diff = app.diff.as_mut().expect("diff view");
    diff.invalidate();
    diff.ensure_rows(&app.review);
    id
}

/// Comment ids the pane currently shows a card for.
fn shown_comment_ids(app: &App) -> Vec<String> {
    let diff = app.diff.as_ref().expect("diff view");
    let session = app.review.session_for(&diff.source);
    rows(app)
        .iter()
        .filter_map(|row| match row {
            DiffRow::Comment {
                comment, line: 0, ..
            } => session.comments.get(*comment).map(|c| c.id.clone()),
            _ => None,
        })
        .collect()
}

/// Select the comment `id` in the open comments sidebar, the way a motion
/// key in that pane does.
fn select_comment(app: &mut App, id: &str) {
    let at = app
        .comment_order()
        .iter()
        .position(|known| known == id)
        .expect("the comment is listed");
    app.comments_to(at);
}

/// Selecting a comment in the comments pane enters the slide that holds it.
#[test]
fn selecting_a_comment_from_the_pane_enters_the_slide_that_holds_it() {
    let fixture = standard_fixture();
    let mut app = walkthrough_app(&fixture);
    let human = add_comment(&mut app, "src/lib.rs", 2, "why 42?");
    assert_eq!(tree_cursor(&app), 0, "the reader starts on the first stop");

    app.handle(key('C'));
    select_comment(&mut app, &human);

    assert_eq!(tree_cursor(&app), 2, "the sidebar follows to that stop");
    assert_eq!(selected_path(&app), "src/lib.rs");
    assert_eq!(shown_line_numbers(&app), [1, 2, 3], "the stop's own region");
    assert_eq!(
        shown_comment_ids(&app),
        vec![human, "stop-2".to_owned()],
        "cards in line order: line 2's comment before the stop's own card, \
         which sits under line 3, the last line of its span"
    );
}

/// A comment no stop's region holds is a slide of its own.
#[test]
fn a_comment_outside_every_region_opens_as_its_own_slide() {
    let fixture = standard_fixture();
    let mut app = walkthrough_app(&fixture);
    let human = add_comment(&mut app, "ci.yml", 1, "why on push?");

    app.handle(key('C'));
    select_comment(&mut app, &human);

    let diff = app.diff.as_ref().expect("diff view");
    assert_eq!(diff.slide, Some(Slide::AdHoc(human.clone())));
    assert_eq!(selected_path(&app), "ci.yml");
    assert_eq!(shown_line_numbers(&app), [1]);
    assert_eq!(shown_comment_ids(&app), vec![human]);
}

/// A comment on a deleted line anchors old-side, so reaching it through
/// the comments pane windows the deleted row and its hunk header in along
/// with the card.
#[test]
fn a_comment_on_a_deleted_line_bands_the_deleted_row_and_its_hunk() {
    let fixture = two_hunk_fixture();
    let mut app = walkthrough_app_with(
        &fixture,
        &[("Somewhere else", None, "unrelated to the deletion")],
    );
    let source = app.active_review_source();
    let human = app
        .review
        .session_for_mut(&source)
        .add_comment(
            Anchor {
                file: "data.txt".to_owned(),
                line: Some(1),
                line_end: None,
                on_old_side: true,
                line_text: None,
            },
            "reviewer",
            "why drop this line?",
        )
        .id
        .clone();
    app.diff.as_mut().expect("diff view").invalidate();
    app.diff
        .as_mut()
        .expect("diff view")
        .ensure_rows(&app.review);

    app.handle(key('C'));
    select_comment(&mut app, &human);

    let diff = app.diff.as_ref().expect("diff view");
    assert_eq!(diff.slide, Some(Slide::AdHoc(human.clone())));
    let shown = rows(&app);
    assert!(
        shown
            .iter()
            .any(|row| matches!(row, DiffRow::Hunk { hunk: 0, .. })),
        "the deleted row's hunk header must be windowed in: {shown:?}"
    );
    assert!(
        shown.iter().any(|row| matches!(
            row,
            DiffRow::Line {
                hunk: 0,
                line: 0,
                ..
            }
        )),
        "the deleted row itself must be windowed in, not only the card: {shown:?}"
    );
}

/// The comment walk runs over the slides, so stepping past the last
/// comment of one enters the next.
#[test]
fn stepping_past_a_slides_last_comment_enters_the_next_slide() {
    let fixture = standard_fixture();
    let mut app = walkthrough_app(&fixture);
    let human = add_comment(&mut app, "todo.md", 1, "is this list still right?");
    app.handle(key('C'));
    select_comment(&mut app, &human);
    assert_eq!(tree_cursor(&app), 1, "the second stop holds it");
    assert_eq!(
        shown_comment_ids(&app),
        vec!["stop-1".to_owned(), human],
        "that slide holds both"
    );

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

    assert_eq!(tree_cursor(&app), 2, "the walk moved on to the next stop");
    assert_eq!(selected_path(&app), "src/lib.rs");
    assert_eq!(shown_line_numbers(&app), [1, 2, 3]);
    assert_eq!(shown_comment_ids(&app), vec!["stop-2".to_owned()]);
}

/// New-side line numbers of every `DiffRow::Line` the pane currently
/// shows, wherever the file lives in the model.
fn shown_line_numbers(app: &App) -> Vec<u32> {
    let diff = app.diff.as_ref().expect("diff view");
    let model = diff.model(&app.review);
    rows(app)
        .iter()
        .filter_map(|row| {
            let DiffRow::Line { file, hunk, line } = row else {
                return None;
            };
            model
                .files
                .get(*file)?
                .hunks
                .get(*hunk)?
                .lines
                .get(*line)?
                .new_no
        })
        .collect()
}

/// A stop anchored deep in a large file windows the pane to exactly the
/// span the agent pointed at, its hunk header and its card.
#[test]
fn a_stops_window_is_its_anchored_rows_its_hunk_header_and_its_card() {
    let fixture = big_file_fixture();
    let app = walkthrough_app_with(
        &fixture,
        &[("The change", Some("big.txt:100"), "why line 100 changed")],
    );
    assert_eq!(
        shown_line_numbers(&app),
        [100],
        "the anchored line and no context around it"
    );
    assert!(
        rows(&app)
            .iter()
            .any(|row| matches!(row, DiffRow::Hunk { .. })),
        "the hunk header it sits under stays"
    );
    assert!(stop_card_rows(&app) > 0, "the card still draws");
}

/// The window shows a wide span whole, with no row budget.
#[test]
fn a_wide_span_shows_every_row_it_covers() {
    let fixture = huge_span_fixture();
    let app = walkthrough_app_with(
        &fixture,
        &[("The rewrite", Some("big.txt:51-120"), "why 70 lines moved")],
    );
    assert_eq!(shown_line_numbers(&app).len(), 70);
}

/// A stop whose anchor names a file but resolves to no span (here, a bare
/// path) shows only its card.
#[test]
fn an_anchor_with_no_span_shows_only_its_card() {
    let fixture = standard_fixture();
    let app = walkthrough_app_with(
        &fixture,
        &[("Whole file", Some("todo.md"), "look at the whole file")],
    );
    assert!(
        rows(&app)
            .iter()
            .all(|row| matches!(row, DiffRow::Comment { .. })),
        "no hunks at all: {:?}",
        rows(&app)
    );
}

/// Cycling `t` out of the walkthrough drops the window: the file reads
/// whole again, the way any other layout shows it.
#[test]
fn cycling_out_of_the_walkthrough_restores_the_full_file_rows() {
    let fixture = huge_span_fixture();
    let mut app = walkthrough_app_with(
        &fixture,
        &[("The rewrite", Some("big.txt:51-120"), "why 70 lines moved")],
    );
    let windowed = shown_line_numbers(&app).len();
    app.handle(key('t'));
    app.diff.as_mut().unwrap().ensure_rows(&app.review);
    assert_eq!(
        layout_of(&app),
        crate::config::FileLayout::Tree,
        "left the walkthrough"
    );
    assert!(
        shown_line_numbers(&app).len() > windowed,
        "the whole hunk shows again, not just the window"
    );
}

/// `<c-n>` means "the next thing the sidebar lists", which in this layout
/// is the next stop.
#[test]
fn ctrl_n_steps_stops_in_the_walkthrough_layout() {
    let fixture = standard_fixture();
    let mut app = walkthrough_app(&fixture);
    app.handle(ctrl_key('n'));
    assert_eq!(tree_cursor(&app), 1);
    assert_eq!(selected_path(&app), "todo.md");
    app.handle(ctrl_key('n'));
    assert_eq!(tree_cursor(&app), 2);
    assert_eq!(selected_path(&app), "src/lib.rs");
    app.handle(ctrl_key('p'));
    assert_eq!(tree_cursor(&app), 1);
}

/// `m` in the walkthrough layout marks the slide read and moves on, the
/// way `m` on a file advances to the row below it.
#[test]
fn m_marks_the_current_slide_seen_and_advances_to_the_next() {
    let fixture = standard_fixture();
    let mut app = walkthrough_app(&fixture);
    assert_eq!(app.diff.as_ref().unwrap().slide, Some(Slide::Stop(0)));

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

    let source = app.active_review_source();
    assert!(app.review.session_for(&source).is_stop_seen("stop-0"));
    assert_eq!(app.diff.as_ref().unwrap().slide, Some(Slide::Stop(1)));
}

/// `u` skips a slide already marked seen and lands on the next one that
/// isn't.
#[test]
fn u_jumps_to_the_next_unseen_slide_skipping_seen_ones() {
    let fixture = standard_fixture();
    let mut app = walkthrough_app(&fixture);
    let source = app.active_review_source();
    app.review.session_for_mut(&source).mark_stop_seen("stop-1");

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

    assert_eq!(
        app.diff.as_ref().unwrap().slide,
        Some(Slide::Stop(2)),
        "stop-1 is seen, so u skips past it to stop-2"
    );
}

#[test]
fn u_says_every_slide_is_seen_when_none_is_left() {
    let fixture = standard_fixture();
    let mut app = walkthrough_app(&fixture);
    let source = app.active_review_source();
    for id in ["stop-0", "stop-1", "stop-2"] {
        app.review.session_for_mut(&source).mark_stop_seen(id);
    }

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

    assert_eq!(
        app.message.as_ref().map(|m| m.text.as_str()),
        Some("every slide is seen")
    );
}

/// The diff sidebar's own heading counts the walkthrough's stops seen so
/// far.
#[test]
fn seen_progress_shows_in_the_sidebar_heading_not_the_status_header() {
    let fixture = standard_fixture();
    let mut app = walkthrough_app(&fixture);
    let source = app.active_review_source();
    app.review.session_for_mut(&source).mark_stop_seen("stop-0");

    let content = crate::test_support::render(&mut app).backend().to_string();
    assert!(
        content.contains("How the answer moved (1/3)"),
        "sidebar heading: {content}"
    );

    app.handle(key('q'));
    let content = crate::test_support::render(&mut app).backend().to_string();
    assert!(
        content.contains("Walkthroughs (1)"),
        "status header: {content}"
    );
}

/// `d` on the walkthrough layout's leading row asks, then deletes the
/// whole review file, closing the diff with it.
#[test]
fn d_on_the_leading_sidebar_row_asks_then_deletes_the_whole_walkthrough() {
    let fixture = standard_fixture();
    let mut app = walkthrough_app_with_summary(&fixture);
    app.diff.as_mut().unwrap().tree_cursor = 0;

    app.handle(key('d'));
    assert!(matches!(app.modal, Some(crate::app::Modal::Confirm { .. })));
    app.handle(key('y'));

    assert!(app.diff.is_none(), "the diff closes with it");
    let source = diffler_core::source::ReviewSource::walkthrough("w1");
    assert!(
        app.review
            .all_reviews()
            .expect("all reviews")
            .into_iter()
            .all(|(s, _)| s != source),
        "the review file is gone"
    );
}

/// `d` on a stop row asks, then deletes just that stop, keeping the rest
/// of the walkthrough.
#[test]
fn d_on_a_stop_row_asks_then_deletes_just_that_stop() {
    let fixture = standard_fixture();
    let mut app = walkthrough_app(&fixture);
    // no summary, so row 0 is stop 0's own row
    app.diff.as_mut().unwrap().tree_cursor = 0;

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

    let source = app.active_review_source();
    let walkthrough = app
        .review
        .session_for(&source)
        .walkthrough
        .as_ref()
        .expect("the walkthrough is kept");
    assert_eq!(walkthrough.stops.len(), 2);
    assert!(!walkthrough.stops.contains(&"stop-0".to_owned()));
}