tuicr 0.20.0

Review AI-generated diffs like a GitHub pull request, right from your terminal.
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
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
use super::*;

impl App {
    /// Re-enter PR mode after we've already opened a PR via the selector.
    /// Used by the selector → PR open path and by `:reload` in PR mode.
    pub fn enter_pr_diff_mode(
        &mut self,
        backend: Box<dyn ForgeBackend>,
        opened: crate::forge::pr_open::OpenedPullRequest,
    ) -> Result<()> {
        let crate::forge::pr_open::OpenedPullRequest {
            details,
            diff_files,
            session,
            key,
            commits,
            review_metadata,
            pr_info,
        } = opened;

        // Save the current session before transitioning so local-mode work
        // isn't lost.
        self.save_current_session_merging_external()?;

        let pr_source = PullRequestDiffSource::from_details(&details);
        let read_only_reason = pr_source.read_only_reason();
        let virtual_root = session.repo_path.clone();

        self.vcs_info = VcsInfo {
            root_path: virtual_root.clone(),
            head_commit: details.head_sha.clone(),
            branch_name: Some(details.head_ref_name.clone()),
            vcs_type: VcsType::File,
        };
        self.vcs = Box::new(PrNoopVcs::new(self.vcs_info.clone()));
        self.session = session;
        self.diff_files = diff_files;
        self.reset_persisted_session_tracking();
        self.diff_source = DiffSource::PullRequest(Box::new(pr_source));
        self.forge_backend = Some(backend);
        self.forge_repository = Some(key.repository.clone());
        // Reset remote-comment state on every PR mode entry; the new PR's
        // threads will be fetched separately by spawn_pr_threads_fetch.
        self.forge_review_threads = Vec::new();
        self.forge_review_summaries = Vec::new();
        self.forge_review_threads_loading = false;
        self.pr_threads_rx = None;
        // Latest known remote head — equal to the session head at open time;
        // refreshed by future `gh pr view` calls in PR 6.
        self.current_pr_head = Some(details.head_sha.clone());
        self.input_mode = InputMode::Normal;
        self.focused_panel = FocusedPanel::Diff;
        self.clear_expanded_gaps();
        self.commit_list.clear();
        self.commit_selection_range = None;
        self.review_commits.clear();
        self.pr_commits.clear();
        self.pr_last_reviewed_commit_index = None;
        self.show_commit_selector = false;
        self.range_diff_files = None;
        self.saved_inline_selection = None;
        self.diff_state = DiffState::default();
        self.pr_info = Some(pr_info);

        // PR mode populates the inline selector with the PR's commits when
        // there are at least two. Single-commit PRs hide the selector to
        // match the local-mode UX. We mirror `commit_list` and
        // `review_commits` into shared App state so the existing
        // inline_commit_selector renderer Just Works.
        let since_last_review_message = self.apply_pr_commit_selector(commits, review_metadata);

        // Ensure session has all files registered after the swap. A strict
        // selector range is a filtered view, not a new review scope.
        let preserve_hunks =
            Self::is_strict_commit_selection(self.commit_selection_range, self.pr_commits.len());
        Self::register_diff_files(&mut self.session, &self.diff_files, preserve_hunks);

        self.sort_files_by_directory(true);
        self.expand_all_dirs();
        self.rebuild_annotations();

        if let Some(reason) = read_only_reason {
            self.set_warning(format!("This PR is {reason} — review is read-only"));
        } else if let Some(message) = since_last_review_message {
            self.set_message(message);
        }

        // If the restored selection is a strict subset, fire an initial
        // range re-fetch so the diff matches the persisted scope.
        if matches!(&self.diff_source, DiffSource::PullRequest(_))
            && let Some(range) = self.commit_selection_range
            && !self.pr_commits.is_empty()
            && (range.0 > 0 || range.1 + 1 < self.pr_commits.len())
        {
            self.spawn_pr_range_reload();
        }

        Ok(())
    }

    /// Reload the PR's head from the forge. If the head SHA changed, this
    /// switches sessions so old-head draft comments stay with the old
    /// session and the new session starts clean.
    /// Capture the cursor's current file + line numbers so we can try to
    /// land back here after `:e` rebuilds the diff. Returns `None` when
    /// the cursor isn't on a diff line (e.g., it's on a header / comment
    /// / hunk header / expander).
    fn capture_pr_cursor_anchor(&self) -> Option<PrCursorAnchor> {
        let annotation = self.line_annotations.get(self.diff_state.cursor_line)?;
        let (file_idx, old_lineno, new_lineno) = match annotation {
            AnnotatedLine::DiffLine {
                file_idx,
                old_lineno,
                new_lineno,
                ..
            } => (*file_idx, *old_lineno, *new_lineno),
            AnnotatedLine::SideBySideLine {
                file_idx,
                old_lineno,
                new_lineno,
                ..
            } => (*file_idx, *old_lineno, *new_lineno),
            AnnotatedLine::ExpandedContext { gap_id, .. } => {
                // Approximate: drop back to the file index from the gap.
                let file_idx = gap_id.file_idx;
                (file_idx, None, None)
            }
            _ => {
                let file_idx = annotation_file_idx(annotation)?;
                (file_idx, None, None)
            }
        };
        let path = self.diff_files.get(file_idx)?.display_path().clone();
        Some(PrCursorAnchor {
            path,
            new_lineno,
            old_lineno,
        })
    }

    /// Move the cursor to a sensible spot after a reload that may have
    /// shifted file ordering / hunk boundaries. Best-effort: match the
    /// exact `(path, new_lineno)` if it still exists, else the same
    /// `(path, old_lineno)` on the LEFT side, else the file's first
    /// annotation, else stay at line 0.
    fn restore_pr_cursor_to_anchor(&mut self, anchor: &PrCursorAnchor) {
        let mut best: Option<usize> = None;
        let mut file_first: Option<usize> = None;
        for (idx, ann) in self.line_annotations.iter().enumerate() {
            let file_idx = match ann {
                AnnotatedLine::DiffLine { file_idx, .. }
                | AnnotatedLine::SideBySideLine { file_idx, .. }
                | AnnotatedLine::HunkHeader { file_idx, .. }
                | AnnotatedLine::FileHeader { file_idx, .. } => *file_idx,
                _ => continue,
            };
            let Some(file) = self.diff_files.get(file_idx) else {
                continue;
            };
            if file.display_path() != &anchor.path {
                continue;
            }
            file_first.get_or_insert(idx);
            let (line_new, line_old) = match ann {
                AnnotatedLine::DiffLine {
                    old_lineno,
                    new_lineno,
                    ..
                }
                | AnnotatedLine::SideBySideLine {
                    old_lineno,
                    new_lineno,
                    ..
                } => (*new_lineno, *old_lineno),
                _ => (None, None),
            };
            if anchor.new_lineno.is_some() && line_new == anchor.new_lineno {
                best = Some(idx);
                break;
            }
            if anchor.old_lineno.is_some() && line_old == anchor.old_lineno {
                best = Some(idx);
                // Don't break — a later RIGHT-side match may still be better.
            }
        }
        let target = best.or(file_first).unwrap_or(0);
        // `move_cursor_to_annotation` updates cursor_line AND adjusts
        // `scroll_offset` so the cursor stays in the viewport. Without
        // it the viewport snaps back to the top of the diff after the
        // reload.
        self.move_cursor_to_annotation(target);
    }

    /// Persist the active inline selection on the session (PR mode only).
    /// `None` is written when the range covers all commits so re-open
    /// doesn't trigger an unnecessary subset re-fetch.
    pub fn persist_pr_commit_selection_range(&mut self) {
        if !matches!(self.diff_source, DiffSource::PullRequest(_)) {
            return;
        }
        let total = self.pr_commits.len();
        let value = match self.commit_selection_range {
            Some((s, e)) if total > 0 && (s > 0 || e + 1 < total) => Some((s, e)),
            _ => None,
        };
        self.session.commit_selection_range = value;
        self.session.updated_at = chrono::Utc::now();
        let _ = self.save_current_session_merging_external();
    }

    /// Resolve the active inline selection (PR mode) to (start_sha,
    /// end_sha). `start_sha` is the parent of the *oldest* selected
    /// commit; `end_sha` is the *newest*. Because `pr_commits` is stored
    /// newest-first, the oldest selected commit is at `range.1` and the
    /// newest at `range.0`.
    ///
    /// Returns `None` outside PR mode, when the selection is empty, or
    /// when the resolved parent isn't available — in that case the
    /// caller falls back to the cached cumulative PR diff.
    pub fn pr_range_sha_pair(&self) -> Option<(String, String)> {
        let DiffSource::PullRequest(ref pr) = self.diff_source else {
            return None;
        };
        let (start_idx, end_idx) = self.commit_selection_range?;
        if self.pr_commits.is_empty() || start_idx > end_idx || end_idx >= self.pr_commits.len() {
            return None;
        }
        // Newest-first: `end_idx` is the oldest, `start_idx` is the newest.
        let newest = self.pr_commits.get(start_idx)?;
        // Parent of the oldest selected commit. If the oldest selected commit
        // is the PR's first commit (oldest commit overall, at the bottom of
        // the list), its parent is the PR's base SHA.
        let parent_sha = if end_idx + 1 < self.pr_commits.len() {
            self.pr_commits[end_idx + 1].oid.clone()
        } else {
            pr.base_sha.clone()
        };
        Some((parent_sha, newest.oid.clone()))
    }

    /// Reload the PR diff for the currently selected inline commit
    /// subrange. Uses the cached cumulative diff when the selection
    /// covers all commits; spawns a background `compare` fetch otherwise.
    pub fn reload_pr_inline_selection(&mut self) {
        // No-op outside PR mode.
        if !matches!(self.diff_source, DiffSource::PullRequest(_)) {
            return;
        }
        let Some(range) = self.commit_selection_range else {
            return;
        };
        let total = self.pr_commits.len();
        if total == 0 {
            return;
        }

        // Full-range selection: restore the cached cumulative diff
        // without hitting the network.
        if range.0 == 0 && range.1 + 1 == total {
            self.apply_cached_full_pr_diff();
            return;
        }

        // Strict subset → range re-fetch on a background thread.
        self.spawn_pr_range_reload();
    }

    /// Restore the cached cumulative PR diff into the diff view. Used when
    /// the user toggles the selector back to "all commits".
    fn apply_cached_full_pr_diff(&mut self) {
        let Some(files) = self.range_diff_files.clone() else {
            return;
        };
        let anchor = self.capture_pr_cursor_anchor();
        self.diff_files = files;
        self.clear_expanded_gaps();
        for file in &self.diff_files {
            self.session.add_diff_file(file);
        }
        self.sort_files_by_directory(true);
        self.expand_all_dirs();
        self.rebuild_annotations();
        if let Some(anchor) = anchor {
            self.restore_pr_cursor_to_anchor(&anchor);
        }
    }

    /// Kick off a background fetch of `compare/<start>...<end>` and apply
    /// it on the main thread. Cancels any in-flight range reload (a fresh
    /// toggle invalidates the previous request).
    pub fn spawn_pr_range_reload(&mut self) {
        let DiffSource::PullRequest(current) = self.diff_source.clone() else {
            return;
        };
        let Some((start_sha, end_sha)) = self.pr_range_sha_pair() else {
            return;
        };
        let Some(range) = self.commit_selection_range else {
            return;
        };

        let anchor = self.capture_pr_cursor_anchor();
        let request = PrRangeReloadRequest {
            repository: current.key.repository.clone(),
            pr_number: current.key.number,
            head_sha: current.key.head_sha.clone(),
            start_sha: start_sha.clone(),
            end_sha: end_sha.clone(),
            range,
            started_at: Instant::now(),
            anchor,
        };
        // A fresh toggle supersedes any in-flight fetch.
        self.pr_range_reload_state = Some(request.clone());

        let local_checkout = self
            .forge_backend
            .as_deref()
            .and_then(|backend| backend.local_checkout_path());

        let (tx, rx) = std::sync::mpsc::channel();
        self.pr_range_reload_rx = Some(rx);

        let repository = current.key.repository.clone();
        let pr_number = current.key.number;
        let head_sha = current.key.head_sha.clone();
        let base_sha = current.base_sha.clone();
        std::thread::spawn(move || {
            let backend = create_forge_backend(&repository, local_checkout);
            let details = crate::forge::traits::PullRequestDetails {
                repository: repository.clone(),
                number: pr_number,
                title: String::new(),
                url: String::new(),
                state: "OPEN".to_string(),
                is_draft: false,
                author: None,
                head_ref_name: String::new(),
                base_ref_name: String::new(),
                head_sha,
                base_sha,
                body: String::new(),
                updated_at: None,
                closed: false,
                merged_at: None,
                diff_start_sha: None,
            };
            let outcome = backend
                .get_pull_request_commit_range_diff(&details, &start_sha, &end_sha)
                .map_err(|e| e.to_string());
            let _ = tx.send(PrRangeReloadEvent::Done {
                request,
                result: outcome,
            });
        });
    }

    /// Pump any pending range-reload result, parse on the main thread, and
    /// apply. Stale results (the user toggled again, or left PR mode) are
    /// silently dropped.
    pub fn poll_pr_range_reload_events(&mut self) {
        let Some(rx) = self.pr_range_reload_rx.as_ref() else {
            return;
        };
        let event = match rx.try_recv() {
            Ok(e) => e,
            Err(_) => return,
        };
        self.pr_range_reload_rx = None;

        let PrRangeReloadEvent::Done { request, result } = event;
        let in_flight = self.pr_range_reload_state.clone();
        // Only apply if this result still matches the active in-flight
        // request — toggling again, switching PRs, or reloading the head
        // before this lands invalidates it.
        let still_active = in_flight.as_ref().is_some_and(|s| {
            s.start_sha == request.start_sha
                && s.end_sha == request.end_sha
                && s.repository == request.repository
                && s.pr_number == request.pr_number
                && s.head_sha == request.head_sha
                && s.range == request.range
        });
        if !still_active {
            return;
        }
        self.pr_range_reload_state = None;

        match result {
            Ok(patch) => {
                if let Err(e) = self.finish_pr_range_reload(&request, &patch) {
                    self.set_error(format!("Range diff failed: {e}"));
                }
            }
            Err(e) => {
                self.set_error(format!("Range diff failed: {e}"));
            }
        }
    }

    pub(in crate::app) fn finish_pr_range_reload(
        &mut self,
        request: &PrRangeReloadRequest,
        patch: &str,
    ) -> Result<()> {
        use crate::vcs::diff_parser::{DiffFormat, parse_unified_diff};

        let highlighter = self.theme.syntax_highlighter();
        let parsed = match parse_unified_diff(patch, DiffFormat::GitStyle, highlighter) {
            Ok(files) => files,
            Err(TuicrError::NoChanges) => Vec::new(),
            Err(e) => return Err(e),
        };

        let local_checkout = self
            .forge_backend
            .as_deref()
            .and_then(|b| b.local_checkout_path());
        let files = match local_checkout.as_deref() {
            Some(root) => crate::tuicrignore::filter_diff_files(root, parsed),
            None => parsed,
        };

        self.diff_files = files;
        self.clear_expanded_gaps();
        // Range diffs can hide hunks that are still reviewed in the broader
        // PR session, so registration must not prune them.
        Self::register_diff_files(&mut self.session, &self.diff_files, true);
        self.sort_files_by_directory(true);
        self.expand_all_dirs();
        self.rebuild_annotations();

        if let Some(anchor) = &request.anchor {
            self.restore_pr_cursor_to_anchor(anchor);
        }
        Ok(())
    }

    /// Kick off `:e` asynchronously. Captures the cursor anchor, sets
    /// the reload state for the spinner, and spawns the network fetch
    /// on a background thread. Returns immediately. The result is
    /// applied later in `poll_pr_reload_events`.
    pub fn spawn_pr_reload(&mut self) -> Result<()> {
        use crate::forge::pr_open::fetch_pr_data;
        use crate::forge::traits::PullRequestTarget;

        let DiffSource::PullRequest(current) = self.diff_source.clone() else {
            return Err(TuicrError::UnsupportedOperation(
                "Not in PR mode".to_string(),
            ));
        };
        if self.pr_reload_state.is_some() {
            return Ok(()); // already in flight; the existing spinner is enough
        }

        let restore_overview_cursor = (self.diff_state.cursor_line
            < self.review_comments_render_height())
        .then_some(self.diff_state.cursor_line);
        let anchor = if restore_overview_cursor.is_some() {
            None
        } else {
            self.capture_pr_cursor_anchor()
        };
        let request = PrReloadRequest {
            repository: current.key.repository.clone(),
            pr_number: current.key.number,
            head_sha: current.key.head_sha.clone(),
            started_at: Instant::now(),
            anchor,
            restore_overview_cursor,
        };
        self.pr_reload_state = Some(request.clone());

        let local_checkout = self
            .forge_backend
            .as_deref()
            .and_then(|backend| backend.local_checkout_path());

        let (tx, rx) = std::sync::mpsc::channel();
        self.pr_reload_rx = Some(rx);

        let repository = current.key.repository.clone();
        let pr_number = current.key.number;
        std::thread::spawn(move || {
            let backend = create_forge_backend(&repository, local_checkout);
            let target =
                PullRequestTarget::with_repository(repository, pr_number, pr_number.to_string());
            let outcome = fetch_pr_data(backend.as_ref(), target).map_err(|e| e.to_string());
            let _ = tx.send(PrReloadEvent::Done {
                request,
                result: outcome,
            });
        });
        Ok(())
    }

    /// Pump a pending reload result. Parses + applies on the main thread,
    /// then restores the cursor to the remembered anchor.
    pub fn poll_pr_reload_events(&mut self) {
        let Some(rx) = self.pr_reload_rx.as_ref() else {
            return;
        };
        let event = match rx.try_recv() {
            Ok(e) => e,
            Err(_) => return,
        };
        self.pr_reload_rx = None;
        let in_flight = self.pr_reload_state.clone();
        self.pr_reload_state = None;
        let PrReloadEvent::Done { request, result } = event;
        if !in_flight
            .as_ref()
            .is_some_and(|s| s.pr_number == request.pr_number && s.repository == request.repository)
        {
            return;
        }
        match result {
            Ok((details, patch, commits, review_metadata, pr_info)) => {
                if let Err(e) = self.finish_pr_reload(
                    details,
                    patch,
                    commits,
                    review_metadata,
                    pr_info,
                    &request,
                ) {
                    self.set_error(format!("Reload failed: {e}"));
                }
            }
            Err(e) => {
                self.set_error(format!("Reload failed: {e}"));
            }
        }
    }

    pub(in crate::app) fn finish_pr_reload(
        &mut self,
        details: crate::forge::traits::PullRequestDetails,
        patch: String,
        commits: Vec<crate::forge::traits::PullRequestCommit>,
        review_metadata: crate::forge::traits::PullRequestReviewMetadata,
        pr_info: crate::forge::traits::PullRequestInfo,
        request: &PrReloadRequest,
    ) -> Result<()> {
        use crate::forge::pr_open::prepare_open_pr;

        let local_checkout = self
            .forge_backend
            .as_deref()
            .and_then(|backend| backend.local_checkout_path());
        let highlighter = self.theme.syntax_highlighter();
        let opened = prepare_open_pr(
            details,
            &patch,
            commits,
            review_metadata,
            pr_info,
            local_checkout.as_deref(),
            highlighter,
        )?;

        let head_changed = opened.details.head_sha != request.head_sha;
        if head_changed {
            let details_for_threads = opened.details.clone();
            let opened = self.opened_pr_with_new_head_session(opened)?;
            let backend = create_forge_backend(&request.repository, local_checkout.clone());
            let previous_message = self.message.clone();
            self.enter_pr_diff_mode(backend, opened)?;
            self.spawn_pr_threads_fetch(&details_for_threads, local_checkout);
            if self.message == previous_message {
                self.set_message("Reloaded PR at new head".to_string());
            }
        } else {
            self.set_pr_last_reviewed_commit_from_metadata(
                &opened.commits,
                &opened.review_metadata,
            );
            self.diff_files = opened.diff_files;
            self.pr_info = Some(opened.pr_info);
            self.clear_expanded_gaps();
            for file in &self.diff_files {
                self.session.add_diff_file(file);
            }
            self.sort_files_by_directory(true);
            self.expand_all_dirs();
            self.rebuild_annotations();
            self.refetch_pr_threads();
            self.set_message("Reloaded PR (no new commits)".to_string());
        }

        if let Some(line) = request.restore_overview_cursor {
            self.diff_state.cursor_line = line;
            self.ensure_cursor_visible();
        } else if let Some(anchor) = &request.anchor {
            self.restore_pr_cursor_to_anchor(anchor);
        }
        Ok(())
    }

    /// Synchronous reload. Production code uses `spawn_pr_reload` for the
    /// async path; kept as a seam for tests that need to drive a reload
    /// in one call without an mpsc round-trip.
    #[allow(dead_code)]
    pub fn reload_pull_request(&mut self) -> Result<bool> {
        let DiffSource::PullRequest(current) = self.diff_source.clone() else {
            return Err(TuicrError::UnsupportedOperation(
                "Not in PR mode".to_string(),
            ));
        };

        let local_checkout = self
            .forge_backend
            .as_deref()
            .and_then(|backend| backend.local_checkout_path());
        let backend = create_forge_backend(&current.key.repository, local_checkout.clone());
        self.reload_pull_request_with_backend(backend, local_checkout)
    }

    /// Inner reload path. Takes the forge backend as a parameter so tests
    /// can inject a fake without going through `gh`.
    #[allow(dead_code)]
    pub fn reload_pull_request_with_backend(
        &mut self,
        backend: Box<dyn ForgeBackend>,
        local_checkout: Option<std::path::PathBuf>,
    ) -> Result<bool> {
        use crate::forge::pr_open::open_pull_request;

        let DiffSource::PullRequest(current) = self.diff_source.clone() else {
            return Err(TuicrError::UnsupportedOperation(
                "Not in PR mode".to_string(),
            ));
        };

        let target = crate::forge::traits::PullRequestTarget::with_repository(
            current.key.repository.clone(),
            current.key.number,
            current.key.number.to_string(),
        );
        let highlighter = self.theme.syntax_highlighter();
        let opened = open_pull_request(
            backend.as_ref(),
            target,
            local_checkout.as_deref(),
            highlighter,
        )?;

        let head_changed = opened.details.head_sha != current.key.head_sha;
        if head_changed {
            // Save the old-head session before switching so drafts persist.
            let details_for_threads = opened.details.clone();
            let opened = self.opened_pr_with_new_head_session(opened)?;
            self.enter_pr_diff_mode(backend, opened)?;
            // Fetch threads against the new head; old-head threads stay
            // tied to the old session and are dropped here.
            self.spawn_pr_threads_fetch(&details_for_threads, local_checkout.clone());
        } else {
            // Same head: re-parse the diff to pick up any side-channel
            // changes (rare), but keep the session intact.
            self.set_pr_last_reviewed_commit_from_metadata(
                &opened.commits,
                &opened.review_metadata,
            );
            self.diff_files = opened.diff_files;
            self.pr_info = Some(opened.pr_info);
            self.clear_expanded_gaps();
            for file in &self.diff_files {
                self.session.add_diff_file(file);
            }
            self.sort_files_by_directory(true);
            self.expand_all_dirs();
            self.rebuild_annotations();
        }

        Ok(head_changed)
    }

    /// Spawn a background thread that fetches the initial PR list. The
    /// resulting `PrLoadEvent::Initial` is delivered through `pr_load_rx`
    /// and applied in the main loop via `poll_pr_load_events`.
    ///
    /// On the first PR-tab visit (`skip_resolution=false`) the thread first
    /// resolves the detected origin to its canonical (fork-parent) repo via
    /// `gh api`, then lists PRs against that canonical. Subsequent visits
    /// reuse the already-resolved repo and skip the resolver.
    pub(in crate::app) fn spawn_pr_initial_load(
        &mut self,
        origin: ForgeRepository,
        override_repo: Option<ForgeRepository>,
        skip_resolution: bool,
        scope: crate::forge::traits::PullRequestListScope,
    ) {
        use crate::forge::selector::PR_PAGE_SIZE;
        use crate::forge::traits::{ForgeKind, PullRequestListQuery};

        let (tx, rx) = std::sync::mpsc::channel();
        self.pr_load_rx = Some(rx);

        std::thread::spawn(move || {
            // Canonical resolution (fork parent lookup) is GitHub-only.
            let canonical = if skip_resolution || origin.kind != ForgeKind::GitHub {
                override_repo.unwrap_or(origin)
            } else {
                use crate::forge::canonical::resolve_canonical_repository;
                use crate::forge::github::gh::SystemGhRunner;
                let runner = SystemGhRunner;
                resolve_canonical_repository(&origin, override_repo.as_ref(), &runner)
            };
            let backend = create_forge_backend(&canonical, None);
            let query =
                PullRequestListQuery::first_page_with_scope(canonical.clone(), PR_PAGE_SIZE, scope);
            let result = backend
                .list_pull_requests(query)
                .map(|page| (page.pull_requests, page.has_more))
                .map_err(|err| err.to_string());
            let _ = tx.send(PrLoadEvent::Initial { canonical, result });
        });
    }

    /// Spawn a background thread that fetches the next page of PRs.
    fn spawn_pr_load_more(
        &mut self,
        repository: ForgeRepository,
        scope: crate::forge::traits::PullRequestListScope,
        already_loaded: usize,
    ) {
        use crate::forge::selector::PR_PAGE_SIZE;
        use crate::forge::traits::PullRequestListQuery;

        let (tx, rx) = std::sync::mpsc::channel();
        self.pr_load_rx = Some(rx);

        std::thread::spawn(move || {
            let backend = create_forge_backend(&repository, None);
            let query = PullRequestListQuery {
                repository,
                already_loaded,
                page_size: PR_PAGE_SIZE,
                scope,
            };
            let result = backend
                .list_pull_requests(query)
                .map(|page| (page.pull_requests, page.has_more))
                .map_err(|err| err.to_string());
            let _ = tx.send(PrLoadEvent::LoadMore(result));
        });
    }

    /// Pump any pending PR fetch events into the tab state.
    /// Called from the main loop each tick; non-blocking.
    pub fn poll_pr_load_events(&mut self) {
        let Some(rx) = self.pr_load_rx.as_ref() else {
            return;
        };
        let mut events = Vec::new();
        while let Ok(event) = rx.try_recv() {
            events.push(event);
        }
        if events.is_empty() {
            return;
        }
        // The channel is single-use per fetch; drop the receiver once a
        // result has arrived so we don't keep checking it.
        self.pr_load_rx = None;
        for event in events {
            match event {
                PrLoadEvent::Initial { canonical, result } => {
                    // The background thread may have resolved a fork's origin
                    // to its upstream parent. Promote App state to the
                    // resolved repo so every PR-related call (open, threads,
                    // submit, load-more) targets the canonical from here on.
                    self.pr_tab.apply_canonical(canonical.clone());
                    self.forge_repository = Some(canonical);
                    self.canonical_resolved = true;
                    self.pr_tab.apply_initial_load(result);
                }
                PrLoadEvent::LoadMore(result) => self.pr_tab.apply_load_more(result),
            }
        }
        self.pr_tab.clamp_cursor();
    }

    pub fn pr_tab_cursor_up(&mut self) {
        self.pr_tab.cursor_up();
        self.pr_tab
            .ensure_cursor_visible(self.pr_list_viewport_height);
    }

    pub fn pr_tab_cursor_down(&mut self) {
        self.pr_tab.cursor_down();
        self.pr_tab
            .ensure_cursor_visible(self.pr_list_viewport_height);
    }

    pub fn toggle_pr_review_requested_filter(&mut self) {
        let Some((repo, scope)) = self.pr_tab.toggle_scope_and_start_reload() else {
            return;
        };
        self.pr_filter_draft = None;
        let override_repo = self.repo_url_override.clone();
        let skip_resolution = self.canonical_resolved;
        self.spawn_pr_initial_load(repo, override_repo, skip_resolution, scope);
        self.set_message(format!("PR list: {}", scope.label()));
    }

    /// Handle Enter on the PR tab. Returns true when the action was handled
    /// (load more triggered, PR open kicked off, error surfaced, etc).
    pub fn pr_tab_select(&mut self) -> bool {
        // Block re-entry while a previous open is still resolving — the
        // spinner glyph on the row already tells the user something is in
        // flight.
        if self.pr_open_state.is_some() {
            return true;
        }
        if self.pr_tab.cursor_on_load_more() {
            if let Some((repo, scope, already)) = self.pr_tab.start_load_more() {
                self.spawn_pr_load_more(repo, scope, already);
            }
            return true;
        }
        // Clone the summary so we drop the immutable borrow before mutating
        // the app to enter PR mode.
        let Some(summary) = self.pr_tab.cursor_pr().cloned() else {
            return false;
        };
        self.spawn_pr_open(&summary);
        true
    }

    /// Kick off the background fetch for a PR open. The main thread keeps
    /// rendering and pumping events; the resulting `PrOpenEvent::Done` is
    /// drained in `poll_pr_open_events` where parsing happens and PR mode
    /// is entered.
    fn spawn_pr_open(&mut self, summary: &crate::forge::traits::PullRequestSummary) {
        use crate::forge::pr_open::fetch_pr_data;
        use crate::forge::traits::PullRequestTarget;

        let request = PrOpenRequest {
            repository: summary.repository.clone(),
            pr_number: summary.number,
            started_at: Instant::now(),
        };
        self.pr_open_state = Some(request.clone());

        let (tx, rx) = std::sync::mpsc::channel();
        self.pr_open_rx = Some(rx);

        let summary_repo = summary.repository.clone();
        let pr_number = summary.number;
        std::thread::spawn(move || {
            let backend = create_forge_backend(&summary_repo, None);
            let target =
                PullRequestTarget::with_repository(summary_repo, pr_number, pr_number.to_string());
            let outcome = fetch_pr_data(backend.as_ref(), target).map_err(|e| e.to_string());
            let _ = tx.send(PrOpenEvent::Done {
                request,
                result: outcome,
            });
        });
    }

    /// Drain any pending PR-open result and apply it. On success, parses
    /// the diff and enters PR diff mode; on failure, routes the error
    /// into the selector banner. Either way, clears `pr_open_state` and
    /// the receiver so the spinner stops animating.
    pub fn poll_pr_open_events(&mut self) {
        let Some(rx) = self.pr_open_rx.as_ref() else {
            return;
        };
        let event = match rx.try_recv() {
            Ok(e) => e,
            Err(_) => return,
        };
        self.pr_open_rx = None;
        let in_flight = self.pr_open_state.clone();
        self.pr_open_state = None;
        match event {
            PrOpenEvent::Done { request, result } => {
                // If the user cancelled (cleared pr_open_state) but the
                // background thread sent a result before being torn down,
                // ignore the result rather than entering PR mode.
                if !in_flight
                    .as_ref()
                    .map(|s| s.matches(&request.repository, request.pr_number))
                    .unwrap_or(false)
                {
                    return;
                }
                match result {
                    Ok((details, patch, commits, review_metadata, pr_info)) => {
                        if let Err(e) = self.finish_pr_open(
                            details,
                            patch,
                            commits,
                            review_metadata,
                            pr_info,
                            &request,
                        ) {
                            self.set_error(format!(
                                "Failed to open PR #{}: {}",
                                request.pr_number, e
                            ));
                        }
                    }
                    Err(e) => {
                        self.set_error(format!("Failed to open PR #{}: {}", request.pr_number, e));
                    }
                }
            }
        }
    }

    /// Main-thread half of the PR open: parse the patch, build the
    /// session, and enter PR diff mode. Mirrors what the previous synchronous
    /// `open_pr_with_backend` did, but the network fetch has already
    /// happened on the background thread.
    fn finish_pr_open(
        &mut self,
        details: crate::forge::traits::PullRequestDetails,
        patch: String,
        commits: Vec<crate::forge::traits::PullRequestCommit>,
        review_metadata: crate::forge::traits::PullRequestReviewMetadata,
        pr_info: crate::forge::traits::PullRequestInfo,
        request: &PrOpenRequest,
    ) -> Result<()> {
        use crate::forge::pr_open::prepare_open_pr;

        let local_checkout =
            crate::forge::local_checkout_for_repo(&self.vcs_info.root_path, &request.repository);
        let highlighter = self.theme.syntax_highlighter();
        let opened = prepare_open_pr(
            details.clone(),
            &patch,
            commits,
            review_metadata,
            pr_info,
            local_checkout.as_deref(),
            highlighter,
        )?;
        let opened = Self::opened_pr_with_persisted_session(opened)?;
        let backend = create_forge_backend(&request.repository, local_checkout.clone());
        let previous_message = self.message.clone();
        self.enter_pr_diff_mode(backend, opened)?;
        // Kick the remote-thread fetch off on a fresh background thread.
        // The diff view is already up; threads fade in once they land.
        self.spawn_pr_threads_fetch(&details, local_checkout);
        if self.message == previous_message {
            self.set_message(format!(
                "Opened PR {}#{}",
                request.repository.display_name(),
                request.pr_number,
            ));
        }
        Ok(())
    }

    /// Kick off a background fetch of remote review threads for `details`.
    /// Replaces any in-flight fetch — we don't try to merge results across
    /// concurrent fetches because the head SHA scopes everything.
    pub(in crate::app) fn spawn_pr_threads_fetch(
        &mut self,
        details: &crate::forge::traits::PullRequestDetails,
        local_checkout: Option<std::path::PathBuf>,
    ) {
        self.forge_review_threads.clear();
        self.forge_review_threads_loading = true;

        let (tx, rx) = std::sync::mpsc::channel();
        self.pr_threads_rx = Some(rx);

        let details_clone = details.clone();
        let repository = details.repository.clone();
        let pr_number = details.number;
        let head_sha = details.head_sha.clone();

        std::thread::spawn(move || {
            let backend = create_forge_backend(&repository, local_checkout);
            let threads = backend
                .list_review_threads(&details_clone)
                .map_err(|e| e.to_string());
            let summaries = backend
                .list_review_summaries(&details_clone)
                .map_err(|e| e.to_string());
            let _ = tx.send(PrThreadsEvent::Done {
                repository,
                pr_number,
                head_sha,
                threads,
                summaries,
            });
        });
    }

    /// Drain any pending remote-thread fetch result and apply it. Stale
    /// results (a result that arrived after the user switched to a
    /// different PR) are discarded.
    pub fn poll_pr_threads_events(&mut self) {
        let Some(rx) = self.pr_threads_rx.as_ref() else {
            return;
        };
        let event = match rx.try_recv() {
            Ok(e) => e,
            Err(_) => return,
        };
        self.pr_threads_rx = None;
        self.forge_review_threads_loading = false;

        match event {
            PrThreadsEvent::Done {
                repository,
                pr_number,
                head_sha,
                threads,
                summaries,
            } => {
                // Validate against the currently open PR. If the user has
                // opened a different PR (or left PR mode) while the fetch
                // was in flight, drop the result silently.
                let current = match &self.diff_source {
                    DiffSource::PullRequest(pr) => Some((
                        pr.key.repository.clone(),
                        pr.key.number,
                        pr.key.head_sha.clone(),
                    )),
                    _ => None,
                };
                let still_relevant = current
                    .as_ref()
                    .map(|(r, n, sha)| *r == repository && *n == pr_number && *sha == head_sha)
                    .unwrap_or(false);
                if !still_relevant {
                    return;
                }
                let mut had_error = false;
                let mut threads_loaded = false;
                match threads {
                    Ok(t) => {
                        self.forge_review_threads = t;
                        threads_loaded = true;
                    }
                    Err(e) => {
                        self.forge_review_threads = Vec::new();
                        self.set_warning(format!("Failed to load remote comments: {e}"));
                        had_error = true;
                    }
                }
                match summaries {
                    Ok(s) => {
                        self.forge_review_summaries = s;
                    }
                    Err(e) => {
                        self.forge_review_summaries = Vec::new();
                        had_error = true;
                        // Only surface the summary error if the threads call
                        // succeeded — otherwise the user already got a
                        // warning for the broader failure.
                        if threads_loaded {
                            self.set_warning(format!("Failed to load remote reviews: {e}"));
                        }
                    }
                }
                if !had_error {
                    self.prune_locked_comments();
                    let _ = self.save_current_session_merging_external();
                }
                self.rebuild_annotations();
            }
        }
    }

    /// Update the per-session remote comments visibility and repaint.
    /// Returns `true` if the visibility actually changed.
    pub fn set_remote_comments_visibility(
        &mut self,
        visibility: crate::forge::remote_comments::PrCommentsVisibility,
    ) -> bool {
        if self.session.remote_comments_visibility == visibility {
            return false;
        }
        self.session.remote_comments_visibility = visibility;
        self.rebuild_annotations();
        true
    }

    /// Abort an in-flight PR open. Drops the receiver so the eventual
    /// thread send becomes a no-op; clears the spinner state.
    pub fn cancel_pr_open(&mut self) -> bool {
        if self.pr_open_state.is_none() {
            return false;
        }
        self.pr_open_state = None;
        self.pr_open_rx = None;
        self.set_message("PR open cancelled".to_string());
        true
    }

    /// Re-fetch remote review threads for the currently open PR. Called
    /// from `:e` so users can pull the latest discussions without
    /// reopening the PR. No-op outside PR mode.
    pub fn refetch_pr_threads(&mut self) {
        let local_checkout = self
            .forge_backend
            .as_deref()
            .and_then(|b| b.local_checkout_path());
        let details = match &self.diff_source {
            DiffSource::PullRequest(pr) => crate::forge::traits::PullRequestDetails {
                repository: pr.key.repository.clone(),
                number: pr.key.number,
                title: pr.title.clone(),
                url: pr.url.clone(),
                state: pr.state.clone(),
                is_draft: false,
                author: None,
                head_ref_name: pr.head_ref_name.clone(),
                base_ref_name: pr.base_ref_name.clone(),
                head_sha: pr.key.head_sha.clone(),
                base_sha: pr.base_sha.clone(),
                body: String::new(),
                updated_at: None,
                closed: pr.closed,
                merged_at: None,
                diff_start_sha: None,
            },
            _ => return,
        };
        self.spawn_pr_threads_fetch(&details, local_checkout);
    }

    /// Open a PR using the provided forge backend, synchronously. Exists
    /// as a seam for tests that want to drive the open without spinning
    /// up a background thread + mpsc round-trip. Production paths go
    /// through `spawn_pr_open` (selector) or `new_from_pr_target` (CLI).
    ///
    /// Synchronously fetches `list_review_threads` from the same backend
    /// and applies it before returning. This is the convenient seam for
    /// integration tests; the production async path uses
    /// `spawn_pr_threads_fetch` instead.
    #[allow(dead_code)]
    pub fn open_pr_with_backend(
        &mut self,
        summary: &crate::forge::traits::PullRequestSummary,
        backend: Box<dyn ForgeBackend>,
        local_checkout: Option<std::path::PathBuf>,
    ) -> Result<()> {
        use crate::forge::pr_open::open_pull_request;
        use crate::forge::traits::PullRequestTarget;

        let target = PullRequestTarget::with_repository(
            summary.repository.clone(),
            summary.number,
            summary.number.to_string(),
        );
        let highlighter = self.theme.syntax_highlighter();
        let opened = open_pull_request(
            backend.as_ref(),
            target,
            local_checkout.as_deref(),
            highlighter,
        )?;
        let opened = Self::opened_pr_with_persisted_session(opened)?;
        // Sync thread + summary fetch — tests assert on
        // `app.forge_review_threads`/`forge_review_summaries` immediately
        // after this returns.
        let threads = backend
            .list_review_threads(&opened.details)
            .unwrap_or_default();
        let summaries = backend
            .list_review_summaries(&opened.details)
            .unwrap_or_default();
        self.enter_pr_diff_mode(backend, opened)?;
        self.forge_review_threads = threads;
        self.forge_review_summaries = summaries;
        self.prune_locked_comments();
        self.rebuild_annotations();
        Ok(())
    }

    pub fn begin_pr_filter(&mut self) {
        if !self.pr_tab.is_loaded() {
            return;
        }
        // Seed the draft from the current applied filter so the user can
        // refine it. Starting from empty is also reasonable; preserving the
        // current filter feels less surprising when re-opening.
        let current = match &self.pr_tab {
            PullRequestsTab::Loaded { filter, .. } => filter.clone(),
            _ => String::new(),
        };
        self.pr_filter_draft = Some(current);
    }

    pub fn commit_pr_filter(&mut self) {
        if let Some(draft) = self.pr_filter_draft.take() {
            self.pr_tab.set_filter(draft);
        }
    }

    pub fn cancel_pr_filter(&mut self) {
        self.pr_filter_draft = None;
    }

    pub fn pr_filter_insert_char(&mut self, ch: char) {
        if let Some(draft) = self.pr_filter_draft.as_mut() {
            draft.push(ch);
        }
    }

    pub fn pr_filter_delete_char(&mut self) {
        if let Some(draft) = self.pr_filter_draft.as_mut() {
            draft.pop();
        }
    }

    pub fn pr_filter_clear(&mut self) {
        if let Some(draft) = self.pr_filter_draft.as_mut() {
            draft.clear();
        }
    }

    pub fn pr_filter_editing(&self) -> bool {
        self.pr_filter_draft.is_some()
    }
}