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
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
use crate::diff::DiffData;
use crate::grouper::llm::LlmBackend;
use crate::grouper::{GroupingStatus, SemanticGroup};
use crate::highlight::HighlightCache;
use crate::preview::mermaid::{ImageSupport, MermaidCache};
use crate::review::{GroupReview, ReviewCache, ReviewSection, ReviewSource, SectionState};
use crate::theme::Theme;
use crate::ui::file_tree::TreeNodeId;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, HashSet};
use tokio::sync::mpsc;
use tui_tree_widget::TreeState;
/// Hunk-level filter: maps file path → set of hunk indices to show.
/// An empty set means show all hunks for that file.
pub type HunkFilter = HashMap<String, HashSet<usize>>;
/// Input mode for the application.
#[derive(Debug, Clone, PartialEq)]
pub enum InputMode {
Normal,
Search,
Help,
Settings,
}
/// Which panel currently has keyboard focus.
#[derive(Debug, Clone, PartialEq)]
pub enum FocusedPanel {
FileTree,
DiffView,
}
/// Messages processed by the TEA update loop.
#[derive(Debug)]
pub enum Message {
KeyPress(KeyEvent),
Resize(u16, u16),
RefreshSignal,
DebouncedRefresh,
DiffParsed(DiffData, String), // parsed data + raw diff for cache hashing
GroupingComplete(Vec<SemanticGroup>, u64), // groups + diff_hash for cache saving
GroupingFailed(String),
IncrementalGroupingComplete(
Vec<SemanticGroup>,
crate::grouper::DiffDelta,
HashMap<String, u64>,
u64, // diff_hash
String, // head_commit
),
/// A mermaid diagram finished rendering — triggers UI refresh.
MermaidReady,
ReviewSectionReady(u64, ReviewSection, Result<String, String>),
}
/// Commands returned by update() for the main loop to execute.
#[allow(dead_code)]
pub enum Command {
SpawnDiffParse { git_diff_args: Vec<String> },
SpawnGrouping {
backend: LlmBackend,
model: String,
summaries: String,
diff_hash: u64,
head_commit: Option<String>,
file_hashes: HashMap<String, u64>,
},
SpawnIncrementalGrouping {
backend: LlmBackend,
model: String,
summaries: String,
diff_hash: u64,
head_commit: String,
file_hashes: HashMap<String, u64>,
delta: crate::grouper::DiffDelta,
},
SpawnReviewSection {
backend: crate::grouper::llm::LlmBackend,
model: String,
section: ReviewSection,
prompt: String,
group_content_hash: u64,
},
SpawnReviewBatch(Vec<Command>),
CancelReview(u64),
Quit,
}
/// Identifies a collapsible node in the diff tree.
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub enum NodeId {
File(usize),
Hunk(usize, usize),
}
/// UI state for navigation and collapse tracking.
pub struct UiState {
pub selected_index: usize,
pub scroll_offset: u16,
pub collapsed: HashSet<NodeId>,
/// Terminal viewport height, updated each frame.
pub viewport_height: u16,
/// Width of the diff view panel (Cell for interior mutability during render).
pub diff_view_width: Cell<u16>,
/// Scroll offset for preview mode (line-based, not item-based).
pub preview_scroll: usize,
}
/// An item in the flattened visible list.
#[derive(Debug, Clone)]
pub enum VisibleItem {
FileHeader { file_idx: usize },
HunkHeader { file_idx: usize, hunk_idx: usize },
DiffLine { file_idx: usize, hunk_idx: usize, line_idx: usize },
}
/// The main application state (TEA Model).
pub struct App {
pub diff_data: DiffData,
pub ui_state: UiState,
pub highlight_cache: HighlightCache,
#[allow(dead_code)]
pub should_quit: bool,
/// Channel sender for spawning debounce timers that send DebouncedRefresh.
pub event_tx: Option<mpsc::Sender<Message>>,
/// Handle to the current debounce timer task, if any.
pub debounce_handle: Option<tokio::task::JoinHandle<()>>,
/// Current input mode (Normal or Search).
pub input_mode: InputMode,
/// Current search query being typed.
pub search_query: String,
/// The confirmed filter pattern (set on Enter in search mode).
pub active_filter: Option<String>,
/// Semantic groups from LLM, if available. None = ungrouped.
pub semantic_groups: Option<Vec<SemanticGroup>>,
/// Lifecycle state of the current grouping request.
pub grouping_status: GroupingStatus,
/// Handle to the in-flight grouping task, for cancellation (ROB-05).
pub grouping_handle: Option<tokio::task::JoinHandle<()>>,
/// Which LLM backend is available (Claude preferred, Copilot fallback), if any.
pub llm_backend: Option<LlmBackend>,
/// Model string resolved for the active backend.
pub llm_model: String,
/// Which panel currently has keyboard focus.
pub focused_panel: FocusedPanel,
/// Persistent tree state for tui-tree-widget (RefCell for interior mutability in render).
pub tree_state: RefCell<TreeState<TreeNodeId>>,
/// When a group is selected in the sidebar, filter the diff view to those (file, hunk) pairs.
/// Key = file path (stripped), Value = set of hunk indices (empty = all hunks).
pub tree_filter: Option<HunkFilter>,
/// Active theme (colors + syntect theme name), derived from config at startup.
pub theme: Theme,
/// HEAD commit hash when current groups were computed. Used for incremental grouping.
pub previous_head: Option<String>,
/// Per-file content hashes from the last grouping. Used to detect what changed.
pub previous_file_hashes: HashMap<String, u64>,
/// Git diff arguments from the CLI, used for refreshes.
pub git_diff_args: Vec<String>,
/// Whether markdown preview mode is active (toggled with "p").
pub preview_mode: bool,
/// Whether the terminal supports inline image rendering.
pub image_support: ImageSupport,
/// Mermaid diagram cache (only used when image_support == Supported).
pub mermaid_cache: Option<MermaidCache>,
pub review_cache: ReviewCache,
pub review_handles: std::collections::HashMap<(u64, ReviewSection), tokio::task::JoinHandle<()>>,
pub active_review_group: Option<u64>,
pub review_scroll: usize,
pub review_source: ReviewSource,
}
impl App {
/// Create a new App with parsed diff data, user config, and git diff arguments.
pub fn new(diff_data: DiffData, config: &crate::config::Config, git_diff_args: Vec<String>) -> Self {
let theme = Theme::from_mode(config.theme_mode);
let highlight_cache = HighlightCache::new(&diff_data, theme.syntect_theme);
let image_support = crate::preview::mermaid::detect_image_support();
let mermaid_cache = match &image_support {
ImageSupport::Supported(_) => Some(MermaidCache::new()),
_ => None,
};
Self {
diff_data,
ui_state: UiState {
selected_index: 0,
scroll_offset: 0,
collapsed: HashSet::new(),
viewport_height: 24, // will be updated on first draw
diff_view_width: Cell::new(80),
preview_scroll: 0,
},
highlight_cache,
should_quit: false,
event_tx: None,
debounce_handle: None,
input_mode: InputMode::Normal,
search_query: String::new(),
active_filter: None,
semantic_groups: None,
grouping_status: GroupingStatus::Idle,
grouping_handle: None,
llm_backend: config.detect_backend(),
llm_model: config
.detect_backend()
.map(|b| config.model_for_backend(b).to_string())
.unwrap_or_default(),
focused_panel: FocusedPanel::DiffView,
tree_state: RefCell::new(TreeState::default()),
tree_filter: None,
theme,
previous_head: None,
previous_file_hashes: HashMap::new(),
git_diff_args,
preview_mode: false,
image_support,
mermaid_cache,
review_cache: ReviewCache::new(),
review_handles: std::collections::HashMap::new(),
active_review_group: None,
review_scroll: 0,
review_source: crate::review::detect_review_skill(),
}
}
/// TEA update: dispatch message to handler, return optional command.
pub fn update(&mut self, msg: Message) -> Option<Command> {
match msg {
Message::KeyPress(key) => self.handle_key(key),
Message::Resize(_w, h) => {
self.ui_state.viewport_height = h.saturating_sub(1);
None
}
Message::RefreshSignal => {
// Cancel any existing debounce timer
if let Some(handle) = self.debounce_handle.take() {
handle.abort();
}
// Spawn a new debounce timer: 500ms delay before refresh
if let Some(tx) = &self.event_tx {
let tx = tx.clone();
self.debounce_handle = Some(tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
let _ = tx.send(Message::DebouncedRefresh).await;
}));
}
None
}
Message::DebouncedRefresh => {
self.debounce_handle = None;
Some(Command::SpawnDiffParse {
git_diff_args: self.git_diff_args.clone(),
})
}
Message::DiffParsed(new_data, raw_diff) => {
self.apply_new_diff_data(new_data);
let hash = crate::cache::diff_hash(&raw_diff);
let current_head = crate::cache::get_head_commit();
// Check exact diff hash cache first (handles identical re-triggers)
if let Some(cached) = crate::cache::load(hash) {
let mut groups = cached;
crate::grouper::normalize_hunk_indices(&mut groups, &self.diff_data);
self.semantic_groups = Some(groups);
self.grouping_status = GroupingStatus::Done;
self.grouping_handle = None;
// Update incremental state
if let Some(ref head) = current_head {
self.previous_head = Some(head.clone());
}
self.previous_file_hashes =
crate::grouper::compute_all_file_hashes(&self.diff_data);
return None;
}
// Try incremental path: same HEAD + have previous groups
let can_incremental = current_head.is_some()
&& self.previous_head.as_ref() == current_head.as_ref()
&& self.semantic_groups.is_some()
&& !self.previous_file_hashes.is_empty();
if can_incremental {
let new_hashes = crate::grouper::compute_all_file_hashes(&self.diff_data);
let delta =
crate::grouper::compute_diff_delta(&new_hashes, &self.previous_file_hashes);
if !delta.has_changes() {
// Nothing changed — keep existing groups
self.grouping_status = GroupingStatus::Done;
return None;
}
if delta.is_only_removals() {
// Only files removed — prune groups locally, no LLM needed
let mut groups = self.semantic_groups.clone().unwrap_or_default();
crate::grouper::remove_files_from_groups(&mut groups, &delta.removed_files);
crate::grouper::normalize_hunk_indices(&mut groups, &self.diff_data);
self.semantic_groups = Some(groups);
self.grouping_status = GroupingStatus::Done;
self.previous_file_hashes = new_hashes.clone();
// Save updated cache
if let Some(ref head) = current_head {
crate::cache::save_with_state(
hash,
self.semantic_groups.as_ref().unwrap(),
Some(head),
&new_hashes,
);
}
return None;
}
// New or modified files — spawn incremental LLM grouping
if let Some(backend) = self.llm_backend {
if let Some(handle) = self.grouping_handle.take() {
handle.abort();
}
self.grouping_status = GroupingStatus::Loading;
let existing = self.semantic_groups.as_ref().unwrap();
let summaries = crate::grouper::incremental_hunk_summaries(
&self.diff_data,
&delta,
existing,
);
tracing::info!(
new = delta.new_files.len(),
modified = delta.modified_files.len(),
removed = delta.removed_files.len(),
unchanged = delta.unchanged_files.len(),
"Incremental grouping"
);
return Some(Command::SpawnIncrementalGrouping {
backend,
model: self.llm_model.clone(),
summaries,
diff_hash: hash,
head_commit: current_head.unwrap(),
file_hashes: new_hashes,
delta,
});
}
}
// Fallback: full re-group
if let Some(backend) = self.llm_backend {
// Cancel in-flight grouping (ROB-05)
if let Some(handle) = self.grouping_handle.take() {
handle.abort();
}
self.grouping_status = GroupingStatus::Loading;
let summaries = crate::grouper::hunk_summaries(&self.diff_data);
let file_hashes = crate::grouper::compute_all_file_hashes(&self.diff_data);
Some(Command::SpawnGrouping {
backend,
model: self.llm_model.clone(),
summaries,
diff_hash: hash,
head_commit: current_head,
file_hashes,
})
} else {
self.grouping_status = GroupingStatus::Idle;
None
}
}
Message::GroupingComplete(groups, diff_hash) => {
let mut groups = groups;
crate::grouper::normalize_hunk_indices(&mut groups, &self.diff_data);
// Update incremental state for next refresh
let current_head = crate::cache::get_head_commit();
let file_hashes = crate::grouper::compute_all_file_hashes(&self.diff_data);
// Save with full incremental state
crate::cache::save_with_state(
diff_hash,
&groups,
current_head.as_deref(),
&file_hashes,
);
self.previous_head = current_head;
self.previous_file_hashes = file_hashes;
self.semantic_groups = Some(groups);
self.grouping_status = GroupingStatus::Done;
self.grouping_handle = None;
// Reset tree state since structure changed from flat→grouped
let mut ts = self.tree_state.borrow_mut();
*ts = TreeState::default();
ts.select_first();
drop(ts);
// Clear any stale tree filter from the flat view
self.tree_filter = None;
// Spawn reviews for all groups in parallel
self.spawn_all_reviews()
}
Message::IncrementalGroupingComplete(new_assignments, delta, file_hashes, diff_hash, head_commit) => {
let existing = self.semantic_groups.as_ref().cloned().unwrap_or_default();
let mut merged =
crate::grouper::merge_groups(&existing, &new_assignments, &delta);
crate::grouper::normalize_hunk_indices(&mut merged, &self.diff_data);
// Save merged groups to cache with incremental state
crate::cache::save_with_state(
diff_hash,
&merged,
Some(&head_commit),
&file_hashes,
);
self.semantic_groups = Some(merged);
self.grouping_status = GroupingStatus::Done;
self.grouping_handle = None;
self.previous_file_hashes = file_hashes;
self.previous_head = Some(head_commit);
// Reset tree state since structure changed
let mut ts = self.tree_state.borrow_mut();
*ts = TreeState::default();
ts.select_first();
drop(ts);
self.tree_filter = None;
// Spawn reviews for all groups in parallel
self.spawn_all_reviews()
}
Message::GroupingFailed(err) => {
tracing::warn!("Grouping failed: {}", err);
self.grouping_status = GroupingStatus::Error(err);
self.grouping_handle = None;
None // Continue showing ungrouped — graceful degradation (ROB-06)
}
Message::MermaidReady => None, // just triggers UI refresh
Message::ReviewSectionReady(hash, section, result) => {
self.review_handles.remove(&(hash, section));
if let Some(review) = self.review_cache.get_mut(&hash) {
match result {
Ok(content) => {
if section == ReviewSection::How && content.trim() == "SKIP" {
review.sections.insert(section, SectionState::Skipped);
} else {
review.sections.insert(section, SectionState::Ready(content));
}
}
Err(msg) => {
review.sections.insert(section, SectionState::Error(msg));
}
}
let all_complete = review.sections.values().all(|s| s.is_complete());
if all_complete {
let review_clone = review.clone();
crate::review::save_review_to_disk(&review_clone);
}
}
None
}
}
}
/// Apply new diff data while preserving scroll position and collapse state.
fn apply_new_diff_data(&mut self, new_data: DiffData) {
// 1. Record collapsed state by file path (not index)
let mut collapsed_files: HashSet<String> = HashSet::new();
let mut collapsed_hunks: HashSet<(String, usize)> = HashSet::new();
for node in &self.ui_state.collapsed {
match node {
NodeId::File(fi) => {
if let Some(file) = self.diff_data.files.get(*fi) {
collapsed_files.insert(file.target_file.clone());
}
}
NodeId::Hunk(fi, hi) => {
if let Some(file) = self.diff_data.files.get(*fi) {
collapsed_hunks.insert((file.target_file.clone(), *hi));
}
}
}
}
// 2. Record current selected file path for position preservation
let selected_path = self.selected_file_path();
// 3. Replace diff data and rebuild highlight cache
self.diff_data = new_data;
self.highlight_cache = HighlightCache::new(&self.diff_data, self.theme.syntect_theme);
// 4. Rebuild collapsed set with new indices
self.ui_state.collapsed.clear();
for (fi, file) in self.diff_data.files.iter().enumerate() {
if collapsed_files.contains(&file.target_file) {
self.ui_state.collapsed.insert(NodeId::File(fi));
}
for (hi, _) in file.hunks.iter().enumerate() {
if collapsed_hunks.contains(&(file.target_file.clone(), hi)) {
self.ui_state.collapsed.insert(NodeId::Hunk(fi, hi));
}
}
}
// 5. Restore selected position by file path, or clamp
if let Some(path) = selected_path {
let items = self.visible_items();
let restored = items.iter().position(|item| {
if let VisibleItem::FileHeader { file_idx } = item {
self.diff_data.files[*file_idx].target_file == path
} else {
false
}
});
if let Some(idx) = restored {
self.ui_state.selected_index = idx;
} else {
self.ui_state.selected_index = self
.ui_state
.selected_index
.min(items.len().saturating_sub(1));
}
} else {
let items_len = self.visible_items().len();
self.ui_state.selected_index = self
.ui_state
.selected_index
.min(items_len.saturating_sub(1));
}
self.adjust_scroll();
}
/// Get the file path of the currently selected item (for position preservation).
fn selected_file_path(&self) -> Option<String> {
let items = self.visible_items();
let item = items.get(self.ui_state.selected_index)?;
let fi = match item {
VisibleItem::FileHeader { file_idx } => *file_idx,
VisibleItem::HunkHeader { file_idx, .. } => *file_idx,
VisibleItem::DiffLine { file_idx, .. } => *file_idx,
};
self.diff_data.files.get(fi).map(|f| f.target_file.clone())
}
/// Handle a key press event, branching on input mode.
fn handle_key(&mut self, key: KeyEvent) -> Option<Command> {
match self.input_mode {
InputMode::Normal => self.handle_key_normal(key),
InputMode::Search => self.handle_key_search(key),
InputMode::Help => {
// Any key closes help
self.input_mode = InputMode::Normal;
None
}
InputMode::Settings => self.handle_key_settings(key),
}
}
/// Handle keys while the Settings overlay is open.
fn handle_key_settings(&mut self, key: KeyEvent) -> Option<Command> {
match key.code {
KeyCode::Char('d') => {
self.toggle_theme();
None
}
KeyCode::Esc => {
self.input_mode = InputMode::Normal;
None
}
_ => None,
}
}
/// Toggle between dark and light theme, rebuilding the highlight cache.
pub fn toggle_theme(&mut self) {
let new_theme = if self.theme.syntect_theme.contains("dark") {
crate::theme::Theme::light()
} else {
crate::theme::Theme::dark()
};
self.theme = new_theme;
self.highlight_cache = HighlightCache::new(&self.diff_data, self.theme.syntect_theme);
}
/// Handle keys in Normal mode.
fn handle_key_normal(&mut self, key: KeyEvent) -> Option<Command> {
// Global keys that work regardless of focused panel
match key.code {
KeyCode::Char('q') => return Some(Command::Quit),
KeyCode::Char('?') => {
self.input_mode = InputMode::Help;
return None;
}
KeyCode::Char(',') => {
self.input_mode = InputMode::Settings;
return None;
}
KeyCode::Tab => {
self.focused_panel = match self.focused_panel {
FocusedPanel::FileTree => FocusedPanel::DiffView,
FocusedPanel::DiffView => FocusedPanel::FileTree,
};
return None;
}
KeyCode::Esc => {
if self.tree_filter.is_some() || self.active_filter.is_some() {
self.tree_filter = None;
self.active_filter = None;
self.ui_state.selected_index = 0;
self.adjust_scroll();
return None;
} else {
return Some(Command::Quit);
}
}
KeyCode::Char('/') => {
self.input_mode = InputMode::Search;
self.search_query.clear();
return None;
}
KeyCode::Char('p') => {
if crate::ui::preview_view::is_current_file_markdown(self) {
self.preview_mode = !self.preview_mode;
if self.preview_mode {
self.ui_state.preview_scroll = 0;
}
}
return None;
}
_ => {}
}
// Route to panel-specific handler
match self.focused_panel {
FocusedPanel::FileTree => self.handle_key_tree(key),
FocusedPanel::DiffView => self.handle_key_diff(key),
}
}
/// Handle keys when the file tree sidebar is focused.
fn handle_key_tree(&mut self, key: KeyEvent) -> Option<Command> {
let mut ts = self.tree_state.borrow_mut();
match key.code {
KeyCode::Char('j') | KeyCode::Down => {
ts.key_down();
}
KeyCode::Char('k') | KeyCode::Up => {
ts.key_up();
}
KeyCode::Left => {
ts.key_left();
}
KeyCode::Right => {
ts.key_right();
}
KeyCode::Enter => {
ts.toggle_selected();
}
KeyCode::Char('g') => {
ts.select_first();
}
KeyCode::Char('G') => {
ts.select_last();
}
_ => return None,
}
// After any navigation, sync the diff view to the selected tree node
let selected = ts.selected().to_vec();
drop(ts); // release borrow before mutating self
self.apply_tree_selection(&selected)
}
/// Update the diff view filter based on the currently selected tree node.
fn apply_tree_selection(&mut self, selected: &[TreeNodeId]) -> Option<Command> {
match selected.last() {
Some(TreeNodeId::File(group_idx, path)) => {
self.select_tree_file(path, *group_idx);
// Clear review pane display, but let in-flight reviews finish
// in the background so results get cached.
self.active_review_group = None;
self.review_scroll = 0;
None
}
Some(TreeNodeId::Group(gi)) => {
self.select_tree_group(*gi);
// Set this group as active for the review pane display.
// Reviews are pre-spawned for all groups when grouping completes,
// so by the time the user navigates here the review is likely
// already cached or in-flight.
if let Some(groups) = &self.semantic_groups {
if let Some(group) = groups.get(*gi) {
let hash = crate::review::group_content_hash(group);
if self.active_review_group == Some(hash) {
return None; // already showing
}
self.active_review_group = Some(hash);
self.review_scroll = 0;
// If review isn't in memory yet, try disk cache
if self.review_cache.get(&hash).is_none() {
if let Some(cached) = crate::review::load_review_from_disk(hash, &self.review_source) {
self.review_cache.insert(cached);
}
}
// If still not cached (and not in-flight), spawn on demand as fallback
if self.review_cache.get(&hash).is_none() {
return self.spawn_all_reviews();
}
}
}
None
}
None => None,
}
}
/// Spawn reviews for ALL groups. Checks disk cache first, only spawns LLM
/// calls for groups without cached reviews. Returns a SpawnReviewBatch with
/// all needed sections, or None if everything is already cached.
pub fn spawn_all_reviews(&mut self) -> Option<Command> {
let backend = self.llm_backend?;
let groups = self.semantic_groups.as_ref()?.clone();
let mut all_cmds: Vec<Command> = Vec::new();
for group in &groups {
let hash = crate::review::group_content_hash(group);
// Already in memory cache?
if self.review_cache.get(&hash).is_some() {
continue;
}
// Check disk cache
if let Some(cached) = crate::review::load_review_from_disk(hash, &self.review_source) {
self.review_cache.insert(cached);
continue;
}
// Cache miss — prepare LLM calls for this group
let mut sections_map = std::collections::HashMap::new();
for s in ReviewSection::all() {
sections_map.insert(s, SectionState::Loading);
}
self.review_cache.insert(GroupReview {
content_hash: hash,
sections: sections_map,
source: self.review_source.clone(),
});
let model = self.llm_model.clone();
let review_source = self.review_source.clone();
for §ion in &ReviewSection::all() {
let prompt = crate::review::llm::build_review_prompt(
section, group, &self.diff_data, &review_source,
);
all_cmds.push(Command::SpawnReviewSection {
backend,
model: model.clone(),
section,
prompt,
group_content_hash: hash,
});
}
}
if all_cmds.is_empty() {
None
} else {
Some(Command::SpawnReviewBatch(all_cmds))
}
}
/// Handle keys when the diff view is focused (original behavior).
fn handle_key_diff(&mut self, key: KeyEvent) -> Option<Command> {
// Review pane scroll and controls take priority when a review is active
if self.active_review_group.is_some() {
return self.handle_key_review(key);
}
// In preview mode, redirect navigation keys to preview scroll
if self.preview_mode {
return self.handle_key_preview(key);
}
let items_len = self.visible_items().len();
if items_len == 0 {
return None;
}
match key.code {
// Jump to next/previous search match
KeyCode::Char('n') => {
self.jump_to_match(true);
None
}
KeyCode::Char('N') => {
self.jump_to_match(false);
None
}
// Navigation
KeyCode::Char('j') | KeyCode::Down => {
self.move_selection(1, items_len);
None
}
KeyCode::Char('k') | KeyCode::Up => {
self.move_selection(-1, items_len);
None
}
KeyCode::Char('g') => {
self.ui_state.selected_index = 0;
self.adjust_scroll();
None
}
KeyCode::Char('G') => {
self.ui_state.selected_index = items_len.saturating_sub(1);
self.adjust_scroll();
None
}
KeyCode::Char('d') if key.modifiers.contains(KeyModifiers::CONTROL) => {
let half_page = (self.ui_state.viewport_height / 2) as usize;
self.move_selection(half_page as isize, items_len);
None
}
KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
let half_page = (self.ui_state.viewport_height / 2) as usize;
self.move_selection(-(half_page as isize), items_len);
None
}
// Collapse/Expand
KeyCode::Enter => {
self.toggle_collapse();
None
}
_ => None,
}
}
/// Filter the diff view to show only the hunks for the selected file within its group.
/// `group_idx` identifies which group the file was selected from (None = flat/ungrouped).
fn select_tree_file(&mut self, path: &str, group_idx: Option<usize>) {
let filter = self.hunk_filter_for_file(path, group_idx);
// Always apply the filter (don't toggle — that's what group headers are for)
self.tree_filter = Some(filter);
// Rebuild visible items and scroll to the selected file's header
let items = self.visible_items();
let target_idx = items.iter().position(|item| {
if let VisibleItem::FileHeader { file_idx } = item {
self.diff_data.files[*file_idx]
.target_file
.trim_start_matches("b/")
== path
} else {
false
}
});
self.ui_state.selected_index = target_idx.unwrap_or(0);
// Pin scroll so the file header is at the top of the viewport
self.ui_state.scroll_offset = self.ui_state.selected_index as u16;
}
/// Filter the diff view to all changes in the selected group.
fn select_tree_group(&mut self, group_idx: usize) {
let filter = self.hunk_filter_for_group(group_idx);
if filter.is_empty() {
return;
}
self.tree_filter = Some(filter);
self.ui_state.selected_index = 0;
self.ui_state.scroll_offset = 0;
}
/// Build a HunkFilter for a single file's hunks within a specific group.
/// Only shows the hunks relevant to that group, not the entire group's files.
fn hunk_filter_for_file(&self, path: &str, group_idx: Option<usize>) -> HunkFilter {
if let Some(groups) = &self.semantic_groups {
if let Some(gi) = group_idx {
if gi >= groups.len() {
// "Other" group — extract only this file's ungrouped hunks
return self.hunk_filter_for_file_in_other(path);
}
if let Some(group) = groups.get(gi) {
if let Some(filter) = self.hunk_filter_for_file_in_group(path, group) {
return filter;
}
}
}
// Fallback (no group_idx or file not found in specified group):
// search all groups for the first match
for group in groups.iter() {
if let Some(filter) = self.hunk_filter_for_file_in_group(path, group) {
return filter;
}
}
return self.hunk_filter_for_file_in_other(path);
}
// No semantic groups — show all hunks for this file
let mut filter = HunkFilter::new();
filter.insert(path.to_string(), HashSet::new());
filter
}
/// Build a single-file HunkFilter from a specific group's changes.
fn hunk_filter_for_file_in_group(
&self,
path: &str,
group: &crate::grouper::SemanticGroup,
) -> Option<HunkFilter> {
for change in &group.changes() {
if let Some(diff_path) = self.resolve_diff_path(&change.file) {
if diff_path == path {
let mut filter = HunkFilter::new();
let hunk_set: HashSet<usize> = change.hunks.iter().copied().collect();
filter.insert(diff_path, hunk_set);
return Some(filter);
}
}
}
None
}
/// Build a single-file HunkFilter from the "Other" (ungrouped) hunks.
fn hunk_filter_for_file_in_other(&self, path: &str) -> HunkFilter {
let other = self.hunk_filter_for_other();
let mut filter = HunkFilter::new();
if let Some(hunk_set) = other.get(path) {
filter.insert(path.to_string(), hunk_set.clone());
} else {
filter.insert(path.to_string(), HashSet::new());
}
filter
}
/// Build a HunkFilter for group at `group_idx`.
fn hunk_filter_for_group(&self, group_idx: usize) -> HunkFilter {
if let Some(groups) = &self.semantic_groups {
if let Some(group) = groups.get(group_idx) {
let mut filter = HunkFilter::new();
for change in &group.changes() {
// Resolve to actual diff path
if let Some(diff_path) = self.resolve_diff_path(&change.file) {
let hunk_set: HashSet<usize> = change.hunks.iter().copied().collect();
filter
.entry(diff_path)
.or_default()
.extend(hunk_set.iter());
}
}
return filter;
}
// group_idx beyond actual groups = "Other" group
if group_idx >= groups.len() {
return self.hunk_filter_for_other();
}
}
HunkFilter::new()
}
/// Build a HunkFilter for the "Other" group (ungrouped hunks).
fn hunk_filter_for_other(&self) -> HunkFilter {
let groups = match &self.semantic_groups {
Some(g) => g,
None => return HunkFilter::new(),
};
// Collect all grouped (file, hunk) pairs
let mut grouped: HashMap<String, HashSet<usize>> = HashMap::new();
for group in groups {
for change in &group.changes() {
if let Some(dp) = self.resolve_diff_path(&change.file) {
grouped.entry(dp).or_default().extend(change.hunks.iter());
}
}
}
// For each diff file, include hunks NOT covered by any group
let mut filter = HunkFilter::new();
for file in &self.diff_data.files {
let dp = file.target_file.trim_start_matches("b/").to_string();
if let Some(grouped_hunks) = grouped.get(&dp) {
// If grouped_hunks is empty, all hunks are claimed
if grouped_hunks.is_empty() {
continue;
}
let ungrouped: HashSet<usize> = (0..file.hunks.len())
.filter(|hi| !grouped_hunks.contains(hi))
.collect();
if !ungrouped.is_empty() {
filter.insert(dp, ungrouped);
}
} else {
// File not in any group — all hunks are "other"
filter.insert(dp, HashSet::new());
}
}
filter
}
/// Resolve a group file path to the actual diff file path (stripped of b/ prefix).
fn resolve_diff_path(&self, group_path: &str) -> Option<String> {
self.diff_data.files.iter().find_map(|f| {
let dp = f.target_file.trim_start_matches("b/");
if dp == group_path || dp.ends_with(group_path) {
Some(dp.to_string())
} else {
None
}
})
}
/// Handle keys in Search mode.
fn handle_key_search(&mut self, key: KeyEvent) -> Option<Command> {
match key.code {
KeyCode::Esc => {
self.input_mode = InputMode::Normal;
self.search_query.clear();
self.active_filter = None;
None
}
KeyCode::Enter => {
self.input_mode = InputMode::Normal;
self.active_filter = if self.search_query.is_empty() {
None
} else {
Some(self.search_query.clone())
};
self.ui_state.selected_index = 0;
self.adjust_scroll();
None
}
KeyCode::Backspace => {
self.search_query.pop();
None
}
KeyCode::Char(c) => {
self.search_query.push(c);
None
}
_ => None,
}
}
/// Jump to the next or previous file header matching the active filter.
fn jump_to_match(&mut self, forward: bool) {
if self.active_filter.is_none() {
return;
}
let items = self.visible_items();
if items.is_empty() {
return;
}
let pattern = self.active_filter.as_ref().unwrap().to_lowercase();
let len = items.len();
let start = self.ui_state.selected_index;
// Search through all items wrapping around
for offset in 1..=len {
let idx = if forward {
(start + offset) % len
} else {
(start + len - offset) % len
};
if let VisibleItem::FileHeader { file_idx } = &items[idx] {
let path = &self.diff_data.files[*file_idx].target_file;
if path.to_lowercase().contains(&pattern) {
self.ui_state.selected_index = idx;
self.adjust_scroll();
return;
}
}
}
}
/// Move selection by delta, clamping to valid range.
fn move_selection(&mut self, delta: isize, items_len: usize) {
let max_idx = items_len.saturating_sub(1);
let new_idx = if delta > 0 {
(self.ui_state.selected_index + delta as usize).min(max_idx)
} else {
self.ui_state.selected_index.saturating_sub((-delta) as usize)
};
self.ui_state.selected_index = new_idx;
self.adjust_scroll();
}
/// Toggle collapse on the currently selected item.
fn toggle_collapse(&mut self) {
let items = self.visible_items();
if let Some(item) = items.get(self.ui_state.selected_index) {
let node_id = match item {
VisibleItem::FileHeader { file_idx } => Some(NodeId::File(*file_idx)),
VisibleItem::HunkHeader { file_idx, hunk_idx } => {
Some(NodeId::Hunk(*file_idx, *hunk_idx))
}
VisibleItem::DiffLine { .. } => None, // no-op on diff lines
};
if let Some(id) = node_id {
if self.ui_state.collapsed.contains(&id) {
self.ui_state.collapsed.remove(&id);
} else {
self.ui_state.collapsed.insert(id);
}
// Clamp selected_index after collapse/expand changes visible items
let new_items_len = self.visible_items().len();
if self.ui_state.selected_index >= new_items_len {
self.ui_state.selected_index = new_items_len.saturating_sub(1);
}
self.adjust_scroll();
}
}
}
/// Estimate the character width of a visible item's rendered line.
fn item_char_width(&self, item: &VisibleItem) -> usize {
match item {
VisibleItem::FileHeader { file_idx } => {
let file = &self.diff_data.files[*file_idx];
let name = if file.is_rename {
format!(
"renamed: {} -> {}",
file.source_file.trim_start_matches("a/"),
file.target_file.trim_start_matches("b/")
)
} else {
file.target_file.trim_start_matches("b/").to_string()
};
// " v " + name + " " + "+N" + " -N"
3 + name.len()
+ 1
+ format!("+{}", file.added_count).len()
+ format!(" -{}", file.removed_count).len()
}
VisibleItem::HunkHeader { file_idx, hunk_idx } => {
let hunk = &self.diff_data.files[*file_idx].hunks[*hunk_idx];
// " v " + header
5 + hunk.header.len()
}
VisibleItem::DiffLine {
file_idx,
hunk_idx,
line_idx,
} => {
let line =
&self.diff_data.files[*file_idx].hunks[*hunk_idx].lines[*line_idx];
// gutter (10) + prefix (2) + content
12 + line.content.len()
}
}
}
/// Calculate the visual row count for an item given the available width.
pub fn item_visual_rows(&self, item: &VisibleItem, width: u16) -> usize {
if width == 0 {
return 1;
}
let char_width = self.item_char_width(item);
char_width.div_ceil(width as usize).max(1)
}
/// Adjust scroll offset to keep the selected item visible,
/// accounting for line wrapping.
fn adjust_scroll(&mut self) {
let width = self.ui_state.diff_view_width.get();
let viewport = self.ui_state.viewport_height as usize;
let items = self.visible_items();
let selected = self.ui_state.selected_index;
if items.is_empty() || viewport == 0 {
self.ui_state.scroll_offset = 0;
return;
}
let scroll = self.ui_state.scroll_offset as usize;
// Selected is above viewport
if selected < scroll {
self.ui_state.scroll_offset = selected as u16;
return;
}
// Check if selected fits within viewport from current scroll
let mut rows = 0usize;
for (i, item) in items.iter().enumerate().take(selected + 1).skip(scroll) {
rows += self.item_visual_rows(item, width);
if rows > viewport && i < selected {
break;
}
}
if rows <= viewport {
return;
}
// Selected is below viewport — find scroll that shows it at bottom
let selected_height = self.item_visual_rows(&items[selected], width);
if selected_height >= viewport {
self.ui_state.scroll_offset = selected as u16;
return;
}
let mut remaining = viewport - selected_height;
let mut new_scroll = selected;
for i in (0..selected).rev() {
let h = self.item_visual_rows(&items[i], width);
if h > remaining {
break;
}
remaining -= h;
new_scroll = i;
}
self.ui_state.scroll_offset = new_scroll as u16;
}
/// Compute the list of visible items respecting collapsed state, active filter,
/// and hunk-level tree filter.
pub fn visible_items(&self) -> Vec<VisibleItem> {
let filter_lower = self
.active_filter
.as_ref()
.map(|f| f.to_lowercase());
let mut items = Vec::new();
for (fi, file) in self.diff_data.files.iter().enumerate() {
let file_path = file.target_file.trim_start_matches("b/");
// If search filter is active, skip files that don't match
if let Some(ref pattern) = filter_lower {
if !file.target_file.to_lowercase().contains(pattern) {
continue;
}
}
// Determine which hunks are visible based on tree filter
let allowed_hunks: Option<&HashSet<usize>> =
self.tree_filter.as_ref().and_then(|f| f.get(file_path));
// If tree filter is active but this file isn't in it, skip entirely
if self.tree_filter.is_some() && allowed_hunks.is_none() {
continue;
}
items.push(VisibleItem::FileHeader { file_idx: fi });
if !self.ui_state.collapsed.contains(&NodeId::File(fi)) {
for (hi, hunk) in file.hunks.iter().enumerate() {
// If hunk filter is active and this hunk isn't in the set, skip it
// (empty set = show all hunks for this file)
if let Some(hunk_set) = allowed_hunks {
if !hunk_set.is_empty() && !hunk_set.contains(&hi) {
continue;
}
}
items.push(VisibleItem::HunkHeader {
file_idx: fi,
hunk_idx: hi,
});
if !self.ui_state.collapsed.contains(&NodeId::Hunk(fi, hi)) {
for (li, _line) in hunk.lines.iter().enumerate() {
items.push(VisibleItem::DiffLine {
file_idx: fi,
hunk_idx: hi,
line_idx: li,
});
}
}
}
}
}
items
}
/// Handle keys when the review pane is active.
fn handle_key_review(&mut self, key: KeyEvent) -> Option<Command> {
match key.code {
KeyCode::Char('j') | KeyCode::Down => {
self.review_scroll = self.review_scroll.saturating_add(1);
None
}
KeyCode::Char('k') | KeyCode::Up => {
self.review_scroll = self.review_scroll.saturating_sub(1);
None
}
KeyCode::Char('d') if key.modifiers.contains(KeyModifiers::CONTROL) => {
self.review_scroll = self.review_scroll.saturating_add(
(self.ui_state.viewport_height / 2) as usize,
);
None
}
KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
self.review_scroll = self.review_scroll.saturating_sub(
(self.ui_state.viewport_height / 2) as usize,
);
None
}
KeyCode::Char('g') => {
self.review_scroll = 0;
None
}
KeyCode::Char('G') => {
self.review_scroll = 999; // will be clamped by renderer
None
}
KeyCode::Char('R') => {
// Force-refresh review
if let Some(hash) = self.active_review_group {
// Cancel in-flight tasks for this hash
let keys: Vec<_> = self
.review_handles
.keys()
.filter(|(h, _)| *h == hash)
.cloned()
.collect();
for key in keys {
if let Some(handle) = self.review_handles.remove(&key) {
handle.abort();
}
}
// Clear caches
self.review_cache.remove(&hash);
crate::review::delete_review_from_disk(hash);
self.active_review_group = None;
// Re-trigger by re-applying current tree selection
let selected = self.tree_state.borrow().selected().to_vec();
return self.apply_tree_selection(&selected);
}
None
}
KeyCode::Esc => {
// Clear review mode
if let Some(old_hash) = self.active_review_group.take() {
let keys: Vec<_> = self
.review_handles
.keys()
.filter(|(h, _)| *h == old_hash)
.cloned()
.collect();
for key in keys {
if let Some(handle) = self.review_handles.remove(&key) {
handle.abort();
}
}
}
self.review_scroll = 0;
None
}
_ => None,
}
}
/// Handle keys in preview mode (line-based scrolling).
fn handle_key_preview(&mut self, key: KeyEvent) -> Option<Command> {
match key.code {
KeyCode::Char('j') | KeyCode::Down => {
self.ui_state.preview_scroll = self.ui_state.preview_scroll.saturating_add(1);
None
}
KeyCode::Char('k') | KeyCode::Up => {
self.ui_state.preview_scroll = self.ui_state.preview_scroll.saturating_sub(1);
None
}
KeyCode::Char('g') => {
self.ui_state.preview_scroll = 0;
None
}
KeyCode::Char('G') => {
self.ui_state.preview_scroll = usize::MAX; // will be clamped in render
None
}
KeyCode::Char('d') if key.modifiers.contains(KeyModifiers::CONTROL) => {
let half_page = (self.ui_state.viewport_height / 2) as usize;
self.ui_state.preview_scroll = self.ui_state.preview_scroll.saturating_add(half_page);
None
}
KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
let half_page = (self.ui_state.viewport_height / 2) as usize;
self.ui_state.preview_scroll = self.ui_state.preview_scroll.saturating_sub(half_page);
None
}
// Collapse/expand still works in preview mode (no-op but don't block)
KeyCode::Enter => None,
// Search match jumping
KeyCode::Char('n') | KeyCode::Char('N') => None,
_ => None,
}
}
/// TEA view: delegate rendering to the UI module.
/// Returns pending images that must be flushed after terminal.draw().
pub fn view(&self, frame: &mut ratatui::Frame) -> Vec<crate::ui::preview_view::PendingImage> {
crate::ui::draw(self, frame)
}
}