gitpane 0.16.0

Multi-repo Git workspace dashboard TUI
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
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
use super::*;
mod robustness;
use crate::git::status::StashEntry;
use std::path::Path;

mod file_search_input {
    use super::*;
    use crate::git::status::{FileEntry, FileStatus, SubmoduleWarn};
    use crossterm::event::KeyEvent;

    fn file(path: &str) -> FileEntry {
        FileEntry {
            path: path.into(),
            status: FileStatus::Modified,
            staged: false,
            unstaged: true,
            is_submodule: false,
            submodule_state: None,
            submodule_warn: SubmoduleWarn::default(),
            submodule_head: None,
        }
    }

    #[test]
    fn search_consumes_shortcuts_and_escape_in_both_file_panels() {
        for focus in [FocusPanel::Changes, FocusPanel::Graph] {
            let tmp = tempfile::TempDir::new().unwrap();
            let repo = make_repo(tmp.path(), "repo");
            let config = Config {
                root_dirs: vec![tmp.path().to_path_buf()],
                write_target_override: Some(tmp.path().join("config.toml")),
                ..Config::default()
            };
            let mut app = App::new(config);
            app.focus = focus;
            let query = "qprtRasgyo?v";
            app.file_list
                .set_files(vec![file("other"), file(query)], "repo", RepoId(repo));
            assert!(
                app.git_graph
                    .set_commit_files(
                        "abc1234".into(),
                        "subject".into(),
                        vec![("M".into(), "other".into()), ("M".into(), query.into())]
                    )
                    .is_none()
            );
            drain_actions(&mut app);
            app.handle_key_event(KeyCode::Char('/').into()).unwrap();
            for c in query.chars() {
                app.handle_key_event(KeyCode::Char(c).into()).unwrap();
            }
            let actions = drain_actions(&mut app);
            assert!(
                actions
                    .iter()
                    .all(|a| matches!(a, Action::ScheduleCommitDiff { .. })),
                "search dispatched global actions: {actions:?}"
            );
            assert!(!app.show_help);
            if focus == FocusPanel::Changes {
                app.handle_key_event(KeyCode::Enter.into()).unwrap();
                assert!(drain_actions(&mut app).iter().any(|a| matches!(a,
                    Action::ShowDiff(_, path) if path == Path::new(query))));
            }
            app.handle_key_event(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL))
                .unwrap();
            assert!(
                drain_actions(&mut app)
                    .iter()
                    .any(|a| matches!(a, Action::Quit))
            );
            app.handle_key_event(KeyCode::Esc.into()).unwrap();
            assert_eq!(app.focus, focus);
            assert!(app.git_graph.has_detail());
            assert!(!app.file_list.search_active());
            assert!(!app.git_graph.file_search_active());
        }
    }

    #[test]
    fn unmatched_search_rejects_a_late_commit_diff() {
        let tmp = tempfile::TempDir::new().unwrap();
        let mut app = App::new(Config {
            root_dirs: vec![tmp.path().to_path_buf()],
            write_target_override: Some(tmp.path().join("config.toml")),
            ..Config::default()
        });
        app.focus = FocusPanel::Graph;
        assert!(
            app.git_graph
                .set_commit_files(
                    "abc1234".into(),
                    "subject".into(),
                    vec![("M".into(), "main.rs".into())]
                )
                .is_none()
        );
        let generation = app.git_graph.current_detail_generation();
        app.git_graph.set_commit_diff("OLD_PREVIEW".into());
        app.handle_key_event(KeyCode::Char('/').into()).unwrap();
        app.handle_key_event(KeyCode::Char('z').into()).unwrap();
        app.handle_action_rest(Action::CommitDiffLoaded {
            generation,
            content: "LATE_PREVIEW".into(),
        })
        .unwrap();
        let mut terminal =
            ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 40)).unwrap();
        terminal
            .draw(|f| app.git_graph.draw(f, f.area()).unwrap())
            .unwrap();
        let output: String = terminal
            .backend()
            .buffer()
            .content
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(!output.contains("OLD_PREVIEW"));
        assert!(!output.contains("LATE_PREVIEW"));
        assert!(output.contains("No matches"));
    }

    #[test]
    fn search_wheel_rejects_diff_from_previous_matching_file() {
        use crossterm::event::{MouseEvent, MouseEventKind};
        let tmp = tempfile::TempDir::new().unwrap();
        let mut app = App::new(Config {
            root_dirs: vec![tmp.path().to_path_buf()],
            write_target_override: Some(tmp.path().join("config.toml")),
            ..Config::default()
        });
        app.focus = FocusPanel::Graph;
        app.git_graph.horizontal_layout = true;
        assert!(
            app.git_graph
                .set_commit_files(
                    "abc1234".into(),
                    "subject".into(),
                    vec![
                        ("M".into(), "lib.rs".into()),
                        ("M".into(), "library.rs".into())
                    ]
                )
                .is_none()
        );
        app.handle_key_event(KeyCode::Char('/').into()).unwrap();
        app.handle_key_event(KeyCode::Char('l').into()).unwrap();
        let generation = app.git_graph.current_detail_generation();
        app.git_graph.set_commit_diff("OLD_PREVIEW".into());
        let mut terminal =
            ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 60)).unwrap();
        terminal
            .draw(|f| app.git_graph.draw(f, f.area()).unwrap())
            .unwrap();
        let row = (0..60)
            .find(|&row| {
                let text: String = (0..100)
                    .map(|col| terminal.backend().buffer()[(col, row)].symbol())
                    .collect();
                text.contains("Files:")
            })
            .expect("file pane header visible");
        app.git_graph
            .handle_mouse_event(MouseEvent {
                kind: MouseEventKind::ScrollDown,
                column: 1,
                row: row + 1,
                modifiers: KeyModifiers::NONE,
            })
            .unwrap();
        app.handle_action_rest(Action::CommitDiffLoaded {
            generation,
            content: "LATE_PREVIEW".into(),
        })
        .unwrap();
        terminal
            .draw(|f| app.git_graph.draw(f, f.area()).unwrap())
            .unwrap();
        let output: String = terminal
            .backend()
            .buffer()
            .content
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(!output.contains("OLD_PREVIEW"));
        assert!(!output.contains("LATE_PREVIEW"));
    }
}

#[test]
fn refresh_decision_runs_without_previous_refresh() {
    let now = Instant::now();
    assert_eq!(
        refresh_decision(None, now, Duration::from_millis(1000)),
        RefreshDecision::Now
    );
}

#[test]
fn refresh_decision_delays_inside_cooldown() {
    let last = Instant::now();
    let now = last + Duration::from_millis(250);
    assert_eq!(
        refresh_decision(Some(last), now, Duration::from_millis(1000)),
        RefreshDecision::Later(Duration::from_millis(750))
    );
}

#[test]
fn refresh_decision_runs_after_cooldown() {
    let last = Instant::now();
    let now = last + Duration::from_millis(1000);
    assert_eq!(
        refresh_decision(Some(last), now, Duration::from_millis(1000)),
        RefreshDecision::Now
    );
}

#[test]
fn graph_status_changed_ignores_file_only_changes() {
    let previous = test_status("main", Some("aaa"));
    let next = test_status("main", Some("aaa"));

    // Same HEAD and same rendered refs: a working-tree edit must not reload
    // the graph (the no-churn guarantee that keeps CPU down).
    assert!(!graph_status_changed(
        Some(&previous),
        &next,
        BranchFilter::All
    ));
}

#[test]
fn graph_status_changed_detects_head_changes() {
    let previous = test_status("main", Some("aaa"));
    let next = test_status("main", Some("bbb"));

    assert!(graph_status_changed(
        Some(&previous),
        &next,
        BranchFilter::All
    ));
}

#[test]
fn graph_status_changed_detects_stash_changes() {
    let previous = test_status("main", Some("aaa"));
    let mut next = test_status("main", Some("aaa"));
    next.stashes.push(StashEntry {
        index: 0,
        message: "WIP on main".to_string(),
        oid: "stash-oid".to_string(),
    });

    assert!(graph_status_changed(
        Some(&previous),
        &next,
        BranchFilter::All
    ));
}

#[test]
fn graph_status_changed_detects_commit_on_other_branch() {
    // The worktree case: the root's checked-out HEAD is unchanged, but a
    // commit landed on another local branch (its shared `refs/heads/*` tip
    // moved). The graph renders that branch, so it must reload.
    let previous = test_status("main", Some("aaa"));
    let mut next = test_status("main", Some("aaa"));
    next.refs.local = previous.refs.local ^ 0x9e37_79b9;

    assert!(graph_status_changed(
        Some(&previous),
        &next,
        BranchFilter::All
    ));
    // Local-only graphs render local branches too, so they also reload.
    assert!(graph_status_changed(
        Some(&previous),
        &next,
        BranchFilter::Local
    ));
}

#[test]
fn graph_status_changed_local_filter_ignores_remote_only_moves() {
    // A background fetch advances a remote-tracking ref. A local-only graph
    // does not draw it, so it must not reload; an all-branches graph does.
    let previous = test_status("main", Some("aaa"));
    let mut next = test_status("main", Some("aaa"));
    next.refs.remote = previous.refs.remote ^ 0x1234_5678;

    assert!(!graph_status_changed(
        Some(&previous),
        &next,
        BranchFilter::Local
    ));
    assert!(graph_status_changed(
        Some(&previous),
        &next,
        BranchFilter::All
    ));
}

fn test_status(branch: &str, head_oid: Option<&str>) -> RepoStatus {
    RepoStatus {
        branch: branch.to_string(),
        head_oid: head_oid.map(str::to_string),
        files: Vec::new(),
        ahead: 0,
        behind: 0,
        is_dirty: false,
        worktree_info: Vec::new(),
        has_submodules: false,
        submodules: Vec::new(),
        has_dirty_submodules: false,
        has_unpushed_submodules: false,
        fetch_failed: false,
        stashes: Vec::new(),
        refs: crate::git::status::RefsFingerprint::default(),
    }
}

/// Create a minimal repo (a `.git` directory with a `HEAD`) at `<root>/<rel>`
/// and return its path. Matches what `scanner::is_real_git_dir` accepts.
fn make_repo(root: &std::path::Path, rel: &str) -> std::path::PathBuf {
    let repo = root.join(rel);
    let dot_git = repo.join(".git");
    std::fs::create_dir_all(&dot_git).unwrap();
    std::fs::write(dot_git.join("HEAD"), "ref: refs/heads/main\n").unwrap();
    repo
}

/// A submodule-shaped checkout: `.git` is a `gitdir:` pointer file into the
/// parent's module store, the layout `is_repo_root` accepts and the walk
/// never rediscovers.
fn make_submodule_repo(
    root: &std::path::Path,
    parent_rel: &str,
    sub_rel: &str,
) -> std::path::PathBuf {
    let module = root
        .join(parent_rel)
        .join(".git")
        .join("modules")
        .join(sub_rel);
    std::fs::create_dir_all(&module).unwrap();
    std::fs::write(module.join("HEAD"), "ref: refs/heads/main\n").unwrap();
    let sub = root.join(parent_rel).join(sub_rel);
    std::fs::create_dir_all(&sub).unwrap();
    std::fs::write(sub.join(".git"), format!("gitdir: {}\n", module.display())).unwrap();
    sub
}

fn displays(app: &App) -> Vec<String> {
    app.repo_list
        .repos
        .iter()
        .map(|r| r.display.clone())
        .collect()
}

/// The list must open in the order a later rescan reproduces. Discovery
/// orders by basename while rows are labelled and re-sorted by breadcrumb
/// path, so with the two out of step the list silently reshuffled the first
/// time anything triggered a rescan.
#[test]
fn app_opens_with_the_repo_list_already_sorted() {
    let tmp = tempfile::TempDir::new().unwrap();
    // Basename order is (bravo, zulu); breadcrumb order is the reverse.
    make_repo(tmp.path(), "alpha/zulu");
    make_repo(tmp.path(), "zeta/bravo");

    let config = Config {
        write_target_override: Some(tmp.path().join("config.toml")),
        root_dirs: vec![tmp.path().to_path_buf()],
        scan_depth: 3,
        ..Config::default()
    };
    let mut app = App::new(config);

    // Breadcrumb labels carry the platform's native separator.
    let zulu = Path::new("alpha").join("zulu").display().to_string();
    let bravo = Path::new("zeta").join("bravo").display().to_string();
    let at_startup = displays(&app);
    assert_eq!(at_startup, [zulu, bravo]);

    app.sort_repos();
    assert_eq!(
        displays(&app),
        at_startup,
        "first rescan reshuffled the list"
    );
}

/// Sorting is flat: a pinned repo takes its alphabetical place like any other
/// row. Pinning controls persistence (the repo survives rescans), not
/// position — a pinned `zzz` grouped above `aaa` read as "sorting is broken
/// for manually added repos".
#[test]
fn sort_repos_intermixes_pinned_repos() {
    let tmp = tempfile::TempDir::new().unwrap();
    make_repo(tmp.path(), "aaa");
    let pinned = make_repo(tmp.path(), "zzz");

    let config = Config {
        write_target_override: Some(tmp.path().join("config.toml")),
        root_dirs: vec![tmp.path().to_path_buf()],
        pinned_repos: vec![pinned],
        scan_depth: 2,
        ..Config::default()
    };
    let mut app = App::new(config);
    assert_eq!(
        displays(&app),
        ["aaa", "zzz"],
        "pin was grouped, not sorted"
    );

    app.sort_order = SortOrder::ReverseAlphabetical;
    app.sort_repos();
    assert_eq!(displays(&app), ["zzz", "aaa"]);
}

/// The sort key lowercases, so `Presentations` files between `aaa` and `zzz`
/// instead of ASCII-sorting all uppercase names to the top; Z-A is the exact
/// reverse.
#[test]
fn sort_repos_is_case_insensitive_in_both_directions() {
    let tmp = tempfile::TempDir::new().unwrap();
    make_repo(tmp.path(), "zzz");
    make_repo(tmp.path(), "Presentations");
    make_repo(tmp.path(), "aaa");

    let config = Config {
        write_target_override: Some(tmp.path().join("config.toml")),
        root_dirs: vec![tmp.path().to_path_buf()],
        scan_depth: 2,
        ..Config::default()
    };
    let mut app = App::new(config);
    assert_eq!(displays(&app), ["aaa", "Presentations", "zzz"]);

    app.sort_order = SortOrder::ReverseAlphabetical;
    app.sort_repos();
    assert_eq!(displays(&app), ["zzz", "Presentations", "aaa"]);
}

/// `s` must round-trip through every mode and come back to where it started.
#[test]
fn sort_order_cycles_through_all_modes() {
    let mut order = SortOrder::Alphabetical;
    let mut labels = Vec::new();
    for _ in 0..3 {
        labels.push(order.label());
        order = order.next();
    }
    assert_eq!(labels, ["A-Z", "Z-A", "Dirty"]);
    assert_eq!(order, SortOrder::Alphabetical);
}

/// Regression: `s` dumped the selection onto the first row. A sort changes
/// where rows live, never which row the user is on.
#[test]
fn sort_keeps_the_selected_repo() {
    let tmp = tempfile::TempDir::new().unwrap();
    make_repo(tmp.path(), "aaa");
    make_repo(tmp.path(), "zzz");

    let config = Config {
        write_target_override: Some(tmp.path().join("config.toml")),
        root_dirs: vec![tmp.path().to_path_buf()],
        scan_depth: 2,
        ..Config::default()
    };
    let mut app = App::new(config);
    app.repo_list.select_repo_row(1); // zzz

    app.sort_order = SortOrder::ReverseAlphabetical;
    app.sort_repos();

    let selected = app.repo_list.selected_repo().unwrap();
    assert_eq!(selected.display, "zzz");
    assert_eq!(
        app.repo_list.selected_index(),
        Some(0),
        "zzz leads the Z-A order"
    );
}

/// Drain every action queued so far. Events translate to actions
/// synchronously, so this is the full observable outcome of `handle_event`.
fn drain_actions(app: &mut App) -> Vec<Action> {
    let mut actions = Vec::new();
    while let Ok(a) = app.action_rx.try_recv() {
        actions.push(a);
    }
    actions
}

fn power_test_app() -> App {
    let tmp = tempfile::TempDir::new().unwrap();
    let config = Config {
        write_target_override: Some(tmp.path().join("config.toml")),
        root_dirs: vec![tmp.path().to_path_buf()],
        scan_depth: 2,
        ..Config::default()
    };
    App::new(config)
}

#[test]
fn deep_sleep_drops_watcher_refreshes_and_wake_repaints() {
    let mut app = power_test_app();
    drain_actions(&mut app);

    app.handle_event(Event::Power(PowerState::DeepSleep))
        .unwrap();
    app.handle_event(Event::RepoChanged("/some/repo".into()))
        .unwrap();
    assert!(
        drain_actions(&mut app).is_empty(),
        "a hidden pane must not refresh on watcher events"
    );

    app.handle_event(Event::Power(PowerState::Awake)).unwrap();
    assert!(
        drain_actions(&mut app)
            .iter()
            .any(|a| matches!(a, Action::Render)),
        "waking must repaint the stale frame"
    );
}

#[test]
fn doze_still_refreshes_on_real_repo_changes() {
    let mut app = power_test_app();
    drain_actions(&mut app);

    app.handle_event(Event::Power(PowerState::Doze)).unwrap();
    app.handle_event(Event::RepoChanged("/some/repo".into()))
        .unwrap();
    assert!(
        drain_actions(&mut app)
            .iter()
            .any(|a| matches!(a, Action::RefreshRepo(_))),
        "a visible (dozing) pane must keep tracking real changes"
    );
}

#[test]
fn root_change_while_deep_asleep_is_replayed_once_on_wake() {
    let mut app = power_test_app();
    drain_actions(&mut app);

    app.handle_event(Event::Power(PowerState::DeepSleep))
        .unwrap();
    app.handle_event(Event::ReposRootChanged).unwrap();
    app.handle_event(Event::ReposRootChanged).unwrap();
    assert!(
        drain_actions(&mut app).is_empty(),
        "no discovery walk while nobody can see the pane"
    );

    app.handle_event(Event::Power(PowerState::Awake)).unwrap();
    let discoveries = drain_actions(&mut app)
        .iter()
        .filter(|a| matches!(a, Action::DiscoverNewRepos))
        .count();
    assert_eq!(discoveries, 1, "deferred root changes coalesce into one");
}

#[test]
fn doze_to_awake_does_not_replay_or_repaint() {
    let mut app = power_test_app();
    drain_actions(&mut app);

    // Doze never deferred anything, so resuming from it is a no-op.
    app.handle_event(Event::Power(PowerState::Doze)).unwrap();
    app.handle_event(Event::Power(PowerState::Awake)).unwrap();
    assert!(drain_actions(&mut app).is_empty());
}

#[tokio::test]
async fn quit_waits_for_mutating_git_ops_and_force_quits_on_second_request() {
    let mut app = power_test_app();
    assert!(!app.ready_to_exit());

    // Quit with nothing in flight exits immediately.
    app.should_quit = true;
    assert!(app.ready_to_exit());

    // An in-flight mutating op (live GitOpGuard) defers the exit...
    let (tx, _rx) = mpsc::unbounded_channel();
    let guard = GitOpGuard::new(RepoId(std::path::PathBuf::from("/tmp/repo")), tx);
    assert!(!app.ready_to_exit());

    // ...unless the user insists with a second quit request.
    app.force_quit = true;
    assert!(app.ready_to_exit());

    // Completion of the op re-enables the normal exit path.
    app.force_quit = false;
    guard.complete();
    assert!(app.ready_to_exit());
}

/// The live-worktree refresh must drop the worktree's cached graph even
/// when the reload is deferred (commit detail open): a cache hit there would
/// resurrect stale rows for up to a poll interval. Guards the
/// `invalidate_repo(&aw.path)` line in `refresh_active_worktree`.
#[test]
fn worktree_refresh_invalidates_the_cached_graph_for_the_worktree_path() {
    let tmp = tempfile::tempdir().unwrap();
    let config = Config {
        write_target_override: Some(tmp.path().join("config.toml")),
        root_dirs: vec![tmp.path().to_path_buf()],
        ..Config::default()
    };
    let mut app = App::new(config);
    // `spawn_blocking` in the miss path needs a runtime context.
    let runtime = tokio::runtime::Runtime::new().unwrap();
    let _guard = runtime.enter();

    let wt = tmp.path().join("live-wt");
    app.active_worktree = Some(ActiveWorktree {
        path: wt.clone(),
        repo_id: RepoId(wt.clone()),
        display_name: "live-wt".to_string(),
    });

    // Seed the cache the way a completed build would.
    app.git_graph.load_repo(wt.clone(), "live-wt");
    app.git_graph.set_rows(vec![mock_graph_row()]);
    assert!(
        app.git_graph.has_cached_graph_for(&wt),
        "precondition: the worktree graph is cached",
    );

    app.refresh_active_worktree();

    assert!(
        !app.git_graph.has_cached_graph_for(&wt),
        "refresh_active_worktree must invalidate the worktree's cached graph",
    );
}

fn mock_graph_row() -> crate::git::graph::GraphRow {
    crate::git::graph::GraphRow {
        commit_col: 0,
        lanes: vec![crate::git::graph::LaneSegment::Commit],
        horizontal_spans: Vec::new(),
        oid: git2::Oid::from_str("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap(),
        short_id: "abc1234".to_string(),
        message: "m".to_string(),
        author: "a".to_string(),
        time: 0,
        labels: Vec::new(),
        is_merge: false,
        parent_oids: Vec::new(),
        diff_stat: None,
        collapsed: None,
    }
}

/// Removing a pinned submodule must not pollute `excluded_repos`: the walk
/// never rediscovers a repo nested inside another listed repo, and the bare
/// name would substring-match unrelated paths forever after.
#[tokio::test]
async fn removing_a_pinned_submodule_leaves_excluded_repos_untouched() {
    let tmp = tempfile::TempDir::new().unwrap();
    make_repo(tmp.path(), "parent");
    let sub = make_submodule_repo(tmp.path(), "parent", "sub");

    let config = Config {
        write_target_override: Some(tmp.path().join("config.toml")),
        root_dirs: vec![tmp.path().to_path_buf()],
        pinned_repos: vec![sub],
        scan_depth: 2,
        ..Config::default()
    };
    let mut app = App::new(config);
    let id = RepoId(
        app.repo_list
            .repos
            .iter()
            .find(|r| r.name == "sub")
            .expect("pinned submodule listed")
            .path
            .clone(),
    );

    let excluded_before = app.config.excluded_repos.clone();
    app.handle_repo_admin(Action::RemoveRepo(id)).unwrap();

    assert!(app.repo_list.repos.iter().all(|r| r.name != "sub"));
    assert_eq!(
        app.config.excluded_repos, excluded_before,
        "pinned submodule removal must not exclude by name"
    );
}

/// A repo the root walk discovered must still be excluded on removal, or it
/// reappears on the next rescan.
#[test]
fn removing_a_discovered_repo_still_excludes_it() {
    let tmp = tempfile::TempDir::new().unwrap();
    make_repo(tmp.path(), "walker");

    let config = Config {
        write_target_override: Some(tmp.path().join("config.toml")),
        root_dirs: vec![tmp.path().to_path_buf()],
        scan_depth: 2,
        ..Config::default()
    };
    let mut app = App::new(config);
    let id = RepoId(app.repo_list.repos[0].path.clone());

    app.handle_repo_admin(Action::RemoveRepo(id)).unwrap();

    assert!(app.repo_list.repos.is_empty());
    assert!(crate::git::scanner::discover_repos(&app.config).is_empty());
}

/// `ConfirmRemoveRepo` only asks: the repo stays listed until the dialog's
/// accept action fires.
#[test]
fn confirm_remove_repo_asks_before_removing() {
    let tmp = tempfile::TempDir::new().unwrap();
    make_repo(tmp.path(), "keeper");

    let config = Config {
        write_target_override: Some(tmp.path().join("config.toml")),
        root_dirs: vec![tmp.path().to_path_buf()],
        scan_depth: 2,
        ..Config::default()
    };
    let mut app = App::new(config);
    let id = RepoId(app.repo_list.repos[0].path.clone());

    app.handle_repo_admin(Action::ConfirmRemoveRepo(id))
        .unwrap();

    assert_eq!(app.repo_list.repos.len(), 1);
    assert!(app.confirm_dialog.visible);
}

/// Removing the repo whose path is the panels' active context (set by "Open
/// in graph" on a submodule) must drop that context, or the panels keep
/// rendering a repo that is no longer listed.
#[tokio::test]
async fn removing_the_active_context_repo_clears_active_worktree() {
    let tmp = tempfile::TempDir::new().unwrap();
    make_repo(tmp.path(), "parent");
    let sub = make_repo(
        tmp.path(),
        &Path::new("parent").join("sub").display().to_string(),
    );

    let config = Config {
        write_target_override: Some(tmp.path().join("config.toml")),
        root_dirs: vec![tmp.path().to_path_buf()],
        pinned_repos: vec![sub],
        scan_depth: 2,
        ..Config::default()
    };
    let mut app = App::new(config);
    let entry_path = app
        .repo_list
        .repos
        .iter()
        .find(|r| r.name == "sub")
        .expect("pinned submodule listed")
        .path
        .clone();
    app.active_worktree = Some(ActiveWorktree {
        path: entry_path.clone(),
        repo_id: RepoId(entry_path.clone()),
        display_name: "parent/sub".to_string(),
    });

    app.handle_repo_admin(Action::RemoveRepo(RepoId(entry_path)))
        .unwrap();

    assert!(app.active_worktree.is_none());
}

/// Adding a repo must land the user on it: Repos panel focused and the new
/// row selectable immediately (the row model is rebuilt before SelectRepo,
/// not lazily at the next draw).
#[test]
fn add_repo_focuses_the_repo_list_on_the_new_row() {
    let tmp = tempfile::TempDir::new().unwrap();
    make_repo(tmp.path(), "existing");
    let newcomer = make_repo(tmp.path(), "newcomer");

    let config = Config {
        write_target_override: Some(tmp.path().join("config.toml")),
        root_dirs: vec![tmp.path().join("existing-only-root")],
        ..Config::default()
    };
    std::fs::create_dir_all(tmp.path().join("existing-only-root")).unwrap();
    let mut app = App::new(config);
    app.focus = FocusPanel::Changes;

    app.handle_repo_admin(Action::AddRepo(newcomer.clone()))
        .unwrap();

    assert_eq!(app.focus, FocusPanel::Repos);
    let canonical = newcomer.canonicalize().unwrap();
    let idx = app
        .repo_list
        .repos
        .iter()
        .position(|r| r.path == canonical)
        .expect("newcomer listed");
    app.repo_list.select_repo_row(idx);
    assert_eq!(
        app.repo_list.selected_index(),
        Some(idx),
        "display_rows stale: the new row is not selectable before a draw"
    );
}

/// A pinned submodule stays adjacent under its parent in every sort order:
/// alphabetical, reverse (parent still leads its group), and dirty-first
/// (the group follows the parent's dirtiness, not the submodule's own).
#[test]
fn sort_repos_keeps_pinned_submodules_under_their_parent() {
    let tmp = tempfile::TempDir::new().unwrap();
    make_repo(tmp.path(), "aaa");
    make_repo(tmp.path(), "mmm");
    let sub = make_submodule_repo(tmp.path(), "mmm", "sub");

    let config = Config {
        write_target_override: Some(tmp.path().join("config.toml")),
        root_dirs: vec![tmp.path().to_path_buf()],
        pinned_repos: vec![sub],
        scan_depth: 2,
        ..Config::default()
    };
    let mut app = App::new(config);

    let names = |app: &App| {
        app.repo_list
            .repos
            .iter()
            .map(|r| r.name.clone())
            .collect::<Vec<_>>()
    };

    app.sort_order = SortOrder::Alphabetical;
    app.sort_repos();
    assert_eq!(names(&app), ["aaa", "mmm", "sub"]);

    app.sort_order = SortOrder::ReverseAlphabetical;
    app.sort_repos();
    assert_eq!(names(&app), ["mmm", "sub", "aaa"]);

    // Dirty the submodule only: the group must not float above `aaa`
    // (grouping follows the parent), but with the parent dirty it must.
    app.sort_order = SortOrder::DirtyFirst;
    let sub_idx = app
        .repo_list
        .repos
        .iter()
        .position(|r| r.name == "sub")
        .unwrap();
    let mut sub_status = test_status("main", None);
    sub_status.is_dirty = true;
    app.repo_list.repos[sub_idx].status = Some(sub_status);
    app.sort_repos();
    assert_eq!(names(&app), ["aaa", "mmm", "sub"]);

    let mmm_idx = app
        .repo_list
        .repos
        .iter()
        .position(|r| r.name == "mmm")
        .unwrap();
    let mut mmm_status = test_status("main", None);
    mmm_status.is_dirty = true;
    app.repo_list.repos[mmm_idx].status = Some(mmm_status);
    app.sort_repos();
    assert_eq!(names(&app), ["mmm", "sub", "aaa"]);
}

/// A plain repo nested inside another listed repo (real `.git` directory) IS
/// rediscovered by the walk, so removing it must still exclude it — only
/// gitlink checkouts skip the exclusion.
#[tokio::test]
async fn removing_a_nested_plain_repo_still_excludes_it() {
    let tmp = tempfile::TempDir::new().unwrap();
    make_repo(tmp.path(), "parent");
    let plain = make_repo(
        tmp.path(),
        &Path::new("parent")
            .join("tools")
            .join("side")
            .display()
            .to_string(),
    );

    let config = Config {
        write_target_override: Some(tmp.path().join("config.toml")),
        root_dirs: vec![tmp.path().to_path_buf()],
        pinned_repos: vec![plain],
        scan_depth: 2,
        ..Config::default()
    };
    let mut app = App::new(config);
    let id = RepoId(
        app.repo_list
            .repos
            .iter()
            .find(|r| r.name == "side")
            .expect("nested plain repo listed")
            .path
            .clone(),
    );

    app.handle_repo_admin(Action::RemoveRepo(id.clone()))
        .unwrap();

    assert!(!crate::git::scanner::discover_repos(&app.config).contains(&id.0));
}