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
use crate::config::AppConfig;
use crate::gitlab::{spawn_mr_fetch, CachedMrData, FetchContext};
use crate::models::{
AppEvent, GitLabMilestone, GitlabMrState, MergeabilityStatus, MrStatus, SavedMr, TrackedMr,
};
use gitlab_tracker_core::{
collect_all_columns, collect_all_filters, ColumnDef, FilterDef, MrSnapshot,
};
use gitlab_tracker_notify as notify;
use ratatui::widgets::TableState;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use tokio::sync::mpsc::UnboundedSender;
use tokio::sync::Semaphore;
/// Shared handle to the active tracker provider (Redmine, Jira, Trello, …).
///
/// Wrapped in `Arc` so it can be cloned cheaply into spawned async tasks.
/// `None` when no provider is configured or the user skipped the token prompt.
pub type TrackerHandle = Arc<dyn gitlab_tracker_core::TrackerProvider>;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SortColumn {
UpdatedAt,
Id,
Milestone,
Title,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SortOrder {
Ascending,
Descending,
}
/// Controls whether keyboard input is routed to the text field or to shortcut bindings.
///
/// - `Normal`: shortcut keys (S, O, P, R, …) are active; the input field is passive.
/// - `Editing`: every printable key feeds the input field; shortcuts are suspended.
/// Enter `/` or `i` to enter Editing mode; press `Esc` to leave it.
/// - `ColumnPicker`: the column visibility popup is open; arrow keys and Space navigate/toggle.
/// - `FilterPicker`: the filter picker popup is open — arrow keys navigate, Enter confirms,
/// typing feeds the text input for Milestone/Assignee entries.
/// - `LogTime`: the Log Time popup is open — Tab navigates fields, Enter submits.
/// Only reachable when a tracker provider is configured (`app.tracker.is_some()`).
/// - `Help`: the help popup is open — any key closes it.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum InputMode {
/// Shortcut keys are active; the input field is passive.
#[default]
Normal,
/// The input field has exclusive focus; shortcuts are suspended.
Editing,
/// The column-picker popup is open — arrow keys and Space toggle columns.
ColumnPicker,
/// The filter picker popup is open — arrow keys navigate, Enter confirms.
/// Typing feeds the text input for Milestone / Assignee entries.
FilterPicker,
/// The Log Time popup is open — Tab cycles fields, Enter submits.
/// Only reachable when `app.tracker.is_some()`.
LogTime,
/// The help popup is open — lists all registered shortcuts by section.
/// Any key press closes it and returns to Normal mode.
Help,
}
/// Which field is focused inside the Log Time popup.
///
/// Cycling order: Duration → Activity → Comment → (submit on Enter).
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum LogTimeField {
#[default]
Duration,
Activity,
Comment,
}
/// State held by the Log Time popup while it is open.
///
/// Reset every time the popup is opened so the user starts with a clean form.
#[derive(Debug, Clone, Default)]
pub struct LogTimeForm {
/// Raw text typed by the user in the Duration field.
pub duration_input: String,
/// Index of the currently highlighted activity in the selector list.
pub selected_activity_idx: usize,
/// Raw text typed by the user in the Comment field.
pub comment_input: String,
/// Which field currently has focus inside the popup.
pub focused_field: LogTimeField,
/// Inline validation / submission error shown beneath the Duration field.
/// `None` when no error is present.
pub error: Option<String>,
/// Whether a submission is in flight (disables the Submit button).
pub submitting: bool,
}
/// Represents the currently focused pane in the TUI layout.
///
/// Adding a new pane only requires adding a variant here and handling it
/// in the relevant input/render logic — no structural change needed.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum ActivePane {
/// The main MR list table (left pane).
#[default]
Dashboard,
/// The MR detail side viewer — upper-right pane.
Inspector,
/// The tracker ticket pane — lower-right pane.
/// Only reachable when a tracker provider is configured and a ticket is linked.
Tracker,
}
impl ActivePane {
/// Cycles to the next pane.
/// When a tracker ticket is available the cycle is: Dashboard → Inspector → Tracker → Dashboard.
/// Otherwise: Dashboard ↔ Inspector.
pub fn next(self, has_tracker_ticket: bool) -> Self {
match self {
ActivePane::Dashboard => ActivePane::Inspector,
ActivePane::Inspector => {
if has_tracker_ticket {
ActivePane::Tracker
} else {
ActivePane::Dashboard
}
}
ActivePane::Tracker => ActivePane::Dashboard,
}
}
}
/// Controls which view is rendered inside the Inspector side panel.
///
/// Cycled with [P] — rotates between MrInfo and Pipelines only.
/// The TimeLog has moved to the dedicated Tracker pane.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum InspectorView {
/// Default: MR metadata, description, labels.
#[default]
MrInfo,
/// Pipeline list for the selected MR.
Pipelines,
}
impl InspectorView {
/// Cycles between MrInfo and Pipelines.
pub fn next(self) -> Self {
match self {
InspectorView::MrInfo => InspectorView::Pipelines,
InspectorView::Pipelines => InspectorView::MrInfo,
}
}
}
/// Controls which view is rendered inside the Tracker pane (lower-right).
///
/// Cycled with [P] when the Tracker pane is focused.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum TrackerView {
/// Ticket details: type, priority, status, version, progress, time tracking.
#[default]
TicketInfo,
/// Time entries logged on the linked ticket.
TimeLog,
}
impl TrackerView {
/// Cycles between TicketInfo and TimeLog.
pub fn next(self) -> Self {
match self {
TrackerView::TicketInfo => TrackerView::TimeLog,
TrackerView::TimeLog => TrackerView::TicketInfo,
}
}
}
/// Active filter state: which `FilterDef` is selected and the optional query string.
///
/// Replaces the old `FilterMode` enum — the predicate now lives inside `FilterDef::apply`
/// collected via `inventory`. The orchestrator only stores the index + query here.
#[derive(Debug, Clone, Default)]
pub struct ActiveFilter {
/// Index into `App::filter_defs` of the currently active filter.
/// Index 0 is always the "All" filter (priority 0, registered in `filters_core.rs`).
pub index: usize,
/// Free-text query for parametric filters (Milestone, Assignee).
/// Empty string for non-parametric filters.
pub query: String,
}
impl ActiveFilter {
/// Returns the display label shown in the table header for the active filter.
pub fn label(&self, filter_defs: &[&'static FilterDef]) -> String {
let Some(def) = filter_defs.get(self.index) else {
return "All".to_string();
};
if def.needs_text_input && !self.query.is_empty() {
format!("{} {}", def.active_label, self.query)
} else {
def.active_label.to_string()
}
}
}
/// State held by the filter picker popup while it is open.
#[derive(Debug, Clone, Default)]
pub struct FilterPickerState {
/// Index of the currently highlighted row (0-based).
pub cursor: usize,
/// Free-text input used for parametric filters (Milestone, Assignee, …).
pub input: String,
}
pub struct App {
pub mrs: Vec<TrackedMr>,
pub branches: Vec<String>,
pub input: String,
/// Whether the input field has exclusive keyboard focus.
/// In `Editing` mode all printable keys feed the field; shortcuts are suspended.
pub input_mode: InputMode,
pub token: String,
pub project_id: String,
pub base_url: String,
pub time_left: u64,
pub refresh_interval_secs: u64,
pub table_state: TableState,
pub config: AppConfig,
pub sort_column: SortColumn,
pub sort_order: SortOrder,
/// Which pane currently holds focus (drives keyboard & scroll routing).
pub active_pane: ActivePane,
/// Which view is rendered inside the Inspector panel ([P] toggles).
pub inspector_view: InspectorView,
/// Vertical scroll offset for the Inspector pane (in lines).
pub inspector_scroll: u16,
/// Total number of lines in the currently rendered Inspector content.
/// Updated at each render frame — used to clamp scroll and avoid blank space.
pub inspector_content_lines: u16,
/// Height (in rows) of the Inspector pane area, updated at each render frame.
pub inspector_pane_height: u16,
/// Which view is rendered inside the Tracker pane ([P] toggles when focused).
pub tracker_view: TrackerView,
/// Vertical scroll offset for the Tracker pane (in lines).
pub tracker_scroll: u16,
/// Total number of lines in the currently rendered Tracker pane content.
pub tracker_content_lines: u16,
/// Height (in rows) of the Tracker pane area, updated at each render frame.
pub tracker_pane_height: u16,
/// Index of the currently highlighted row in the column-picker popup (0-based).
pub column_picker_cursor: usize,
/// Countdown (in ticks ~= seconds) during which recently-updated rows stay highlighted.
/// Reset to `RECENT_UPDATE_FADE_TICKS` each time a MR update is detected.
/// Decremented on every Tick; rows are highlighted while this is > 0.
pub update_highlight_ticks: u64,
/// List of active/upcoming milestones fetched from GitLab on startup.
/// Used to power the milestone autocomplete in the input field.
pub milestones: Vec<GitLabMilestone>,
/// When the user types `@` followed by text in Editing mode, this holds the
/// filtered list of milestone titles matching the current query.
/// Empty when autocomplete is not active.
pub milestone_suggestions: Vec<String>,
/// Index of the currently highlighted suggestion in the autocomplete popup.
pub milestone_suggestion_cursor: usize,
/// Active filter applied to the MR table — selected via the [F] picker popup.
pub active_filter: ActiveFilter,
/// State of the filter picker popup (cursor position + text input).
/// Reset each time the popup is opened.
pub filter_picker: FilterPickerState,
/// All registered filter definitions, collected at startup via `inventory`.
/// Sorted by priority — index 0 is always "All".
pub filter_defs: Vec<&'static FilterDef>,
/// All registered column definitions, collected at startup via `inventory`.
/// Sorted by priority — used by the column picker popup and `VisibleColumns`.
pub column_defs: Vec<&'static ColumnDef>,
/// Number of MR fetches still pending from the initial startup load.
/// Change notifications (updated_at, mergeability, milestone) are suppressed
/// until this reaches zero, preventing spurious toasts on first launch.
pub pending_initial_fetches: usize,
/// Number of MR fetches still pending from the current auto-refresh cycle.
/// Drives the spinner in the table title; reset to 0 when all fetches complete.
pub pending_refresh_fetches: usize,
/// Active tracker provider (Redmine, Jira, Trello, …), shared across async tasks via Arc.
/// `None` when no provider is configured or the user skipped the token prompt.
pub tracker: Option<TrackerHandle>,
/// Colour maps for tracker badge labels (type and priority).
/// Populated from the active tracker's config at startup and forwarded to the Tracker pane renderer.
/// Defaults to empty maps (dark_gray / white fallback) when no provider is configured.
pub tracker_colors: crate::ui::tracker::TrackerLabelColors,
/// Activity categories fetched from the tracker at startup.
/// Populated by `AppEvent::ActivitiesLoaded` and used to fill the Log Time popup.
pub activities: Vec<gitlab_tracker_core::Activity>,
/// Time entries for the currently selected ticket, fetched when the TimeLog view opens.
pub time_entries: Vec<gitlab_tracker_core::TimeEntry>,
/// State of the Log Time popup form. Reset each time the popup is opened.
pub log_time_form: LogTimeForm,
/// When `true`, the user has pressed Esc once and is being asked to confirm quitting.
/// A second Esc (or `y`) confirms; any other key cancels.
pub quit_confirm: bool,
/// Monotonically incrementing counter bumped on every render frame (~20 fps).
/// Used to animate the spinner independently of the 1-second tick timer.
pub spinner_frame: usize,
/// Shortcut blocks collected at startup via `inventory` from every linked crate.
///
/// Populated once by `gitlab_tracker_core::collect_all_blocks()` — no explicit
/// provider registration needed in `main.rs`. The help popup iterates this list
/// in collection order (link order: Core first, optional plugins after).
pub shortcut_providers: Vec<gitlab_tracker_core::ShortcutBlock>,
}
/// Duration (in seconds) of the green highlight fade after a MR is updated.
pub const RECENT_UPDATE_FADE_TICKS: u64 = 10;
impl App {
pub fn new(
token: String,
project_id: String,
base_url: String,
refresh_interval_secs: u64,
mut config: AppConfig,
) -> Self {
let mut table_state = TableState::default();
table_state.select(None);
// Collect columns first so we can seed `visible_columns` defaults before
// moving `config` into the struct — avoids a borrow-after-move.
let column_defs = collect_all_columns();
config.visible_columns.apply_defaults(&column_defs);
Self {
mrs: Vec::new(),
branches: Vec::new(),
input: String::new(),
input_mode: InputMode::default(),
token,
project_id,
base_url,
refresh_interval_secs,
time_left: refresh_interval_secs,
table_state,
config,
sort_column: SortColumn::UpdatedAt,
sort_order: SortOrder::Descending,
active_pane: ActivePane::default(),
inspector_view: InspectorView::default(),
inspector_scroll: 0,
inspector_content_lines: 0,
inspector_pane_height: 0,
tracker_view: TrackerView::default(),
tracker_scroll: 0,
tracker_content_lines: 0,
tracker_pane_height: 0,
column_picker_cursor: 0,
update_highlight_ticks: 0,
milestones: Vec::new(),
milestone_suggestions: Vec::new(),
milestone_suggestion_cursor: 0,
active_filter: ActiveFilter::default(),
filter_picker: FilterPickerState::default(),
filter_defs: collect_all_filters(),
column_defs,
// Initialised to 0 — main.rs sets this to the number of MRs loaded from state
// before the first fetch cycle begins, then decrements it on each MrLoaded event.
pending_initial_fetches: 0,
pending_refresh_fetches: 0,
// Initialised to None — main.rs injects the provider after keyring lookup.
tracker: None,
tracker_colors: crate::ui::tracker::TrackerLabelColors::default(),
activities: Vec::new(),
time_entries: Vec::new(),
log_time_form: LogTimeForm::default(),
quit_confirm: false,
spinner_frame: 0,
// Populated at startup by main.rs — at least CoreShortcutProvider is always pushed.
shortcut_providers: Vec::new(),
}
}
/// Toggles the flagged state of the currently selected MR.
///
/// Returns the MR id if a MR was toggled, `None` if no MR is selected.
pub fn toggle_flag_selected(&mut self) -> Option<String> {
let selected = self.table_state.selected()?;
// When a filter is active the visible index differs from `self.mrs` index.
let mr = self.visible_mrs_mut().nth(selected)?;
mr.flagged = !mr.flagged;
Some(mr.id.clone())
}
/// Opens the filter picker popup, pre-selecting the currently active filter row.
pub fn open_filter_picker(&mut self) {
self.filter_picker = FilterPickerState {
cursor: self.active_filter.index,
input: self.active_filter.query.clone(),
};
self.input_mode = InputMode::FilterPicker;
}
/// Applies the filter picker selection and closes the popup.
///
/// When the selected filter requires a text input and the input is empty,
/// falls back to index 0 ("All") to avoid an empty parametric filter.
pub fn apply_filter_picker(&mut self) {
let input = self.filter_picker.input.trim().to_string();
let idx = self.filter_picker.cursor;
// If the chosen filter needs text but the input is empty, reset to "All".
let (final_idx, final_query) = if let Some(def) = self.filter_defs.get(idx) {
if def.needs_text_input && input.is_empty() {
(0, String::new())
} else {
(idx, input)
}
} else {
(0, String::new())
};
self.active_filter = ActiveFilter {
index: final_idx,
query: final_query,
};
self.input_mode = InputMode::Normal;
// Reset selection so we never point past the end of the filtered list.
if self.visible_mrs().next().is_some() {
self.table_state.select(Some(0));
} else {
self.table_state.select(None);
}
self.reset_inspector_scroll();
}
/// Returns an iterator over the MRs that pass the current filter.
pub fn visible_mrs(&self) -> impl Iterator<Item = &TrackedMr> {
self.mrs.iter().filter(move |mr| self.filter_passes(mr))
}
/// Returns a mutable iterator over the MRs that pass the current filter.
fn visible_mrs_mut(&mut self) -> impl Iterator<Item = &mut TrackedMr> {
let filter_defs = self.filter_defs.clone();
let active = self.active_filter.clone();
self.mrs
.iter_mut()
.filter(move |mr| Self::apply_filter(&filter_defs, &active, mr))
}
/// Returns `true` when `mr` passes the currently active filter.
fn filter_passes(&self, mr: &TrackedMr) -> bool {
Self::apply_filter(&self.filter_defs, &self.active_filter, mr)
}
/// Pure predicate — does not borrow `self`, usable inside `iter_mut` closures.
///
/// Builds a [`MrSnapshot`] from the tracked MR and delegates to the registered
/// `FilterDef::apply` function — no match arm needed when a new filter is added.
fn apply_filter(
filter_defs: &[&'static FilterDef],
active: &ActiveFilter,
mr: &TrackedMr,
) -> bool {
let Some(def) = filter_defs.get(active.index) else {
return true; // Unknown index → show all.
};
let snapshot = MrSnapshot {
flagged: mr.flagged,
state: match &mr.state {
crate::models::GitlabMrState::Opened => "opened",
crate::models::GitlabMrState::Merged => "merged",
crate::models::GitlabMrState::Closed => "closed",
},
mergeability: match &mr.mergeability {
crate::models::MergeabilityStatus::Mergeable => "Mergeable",
crate::models::MergeabilityStatus::Conflict => "Conflict",
crate::models::MergeabilityStatus::NeedsRebase => "NeedsRebase",
crate::models::MergeabilityStatus::NotApproved => "NotApproved",
crate::models::MergeabilityStatus::RequestedChanges => "RequestedChanges",
crate::models::MergeabilityStatus::Draft => "Draft",
crate::models::MergeabilityStatus::DiscussionsNotResolved => {
"DiscussionsNotResolved"
}
crate::models::MergeabilityStatus::CiMustPass => "CiMustPass",
crate::models::MergeabilityStatus::CiStillRunning => "CiStillRunning",
crate::models::MergeabilityStatus::NotOpen => "NotOpen",
crate::models::MergeabilityStatus::Unknown => "Unknown",
},
user_notes_count: mr.user_notes_count,
milestone: &mr.milestone,
assignee: &mr.assignee,
linked_ticket: mr.linked_ticket.as_ref(),
pipeline_status: mr.pipelines.first().map(|p| match &p.status {
crate::models::PipelineState::Failed => "Failed",
crate::models::PipelineState::Success => "Success",
crate::models::PipelineState::Running => "Running",
crate::models::PipelineState::Pending => "Pending",
crate::models::PipelineState::Canceled => "Canceled",
crate::models::PipelineState::Skipped => "Skipped",
crate::models::PipelineState::Created => "Created",
crate::models::PipelineState::Unknown => "Unknown",
}),
};
(def.apply)(snapshot, &active.query)
}
/// Updates `milestone_suggestions` based on the current input query after `@`.
///
/// Call this whenever the input changes in Editing mode. If the input does not
/// contain `@`, suggestions are cleared. The query is case-insensitive.
pub fn update_milestone_suggestions(&mut self) {
if let Some(query) = self.input.strip_prefix('@') {
let query_lower = query.to_lowercase();
self.milestone_suggestions = self
.milestones
.iter()
.map(|m| m.title.clone())
.filter(|title| title.to_lowercase().contains(&query_lower))
.collect();
// Reset cursor to avoid out-of-bounds after list changes.
self.milestone_suggestion_cursor = 0;
} else {
self.milestone_suggestions.clear();
self.milestone_suggestion_cursor = 0;
}
}
/// Moves the autocomplete cursor down (wraps around).
pub fn milestone_suggestion_next(&mut self) {
if !self.milestone_suggestions.is_empty() {
self.milestone_suggestion_cursor =
(self.milestone_suggestion_cursor + 1) % self.milestone_suggestions.len();
}
}
/// Moves the autocomplete cursor up (wraps around).
pub fn milestone_suggestion_prev(&mut self) {
if !self.milestone_suggestions.is_empty() {
let len = self.milestone_suggestions.len();
self.milestone_suggestion_cursor = (self.milestone_suggestion_cursor + len - 1) % len;
}
}
/// Confirms the currently highlighted suggestion, replacing the `@query` in the input.
///
/// Returns the selected milestone title so the caller can trigger the bulk-add fetch.
pub fn confirm_milestone_suggestion(&mut self) -> Option<String> {
let selected = self
.milestone_suggestions
.get(self.milestone_suggestion_cursor)
.cloned()?;
// Replace the `@...` prefix with the confirmed milestone title (prefixed with `@`).
self.input = format!("@{}", selected);
self.milestone_suggestions.clear();
Some(selected)
}
/// Scrolls the Inspector pane down by the given number of lines.
///
/// Clamps the scroll so the user cannot scroll past the last line of content,
/// preventing blank space from appearing at the bottom of the Inspector pane.
pub fn inspector_scroll_down(&mut self, amount: u16) {
let max_scroll = self
.inspector_content_lines
.saturating_sub(self.inspector_pane_height);
self.inspector_scroll = self.inspector_scroll.saturating_add(amount).min(max_scroll);
}
/// Scrolls the Inspector pane up by the given number of lines.
pub fn inspector_scroll_up(&mut self, amount: u16) {
self.inspector_scroll = self.inspector_scroll.saturating_sub(amount);
}
/// Resets the Inspector scroll to the top (e.g. when selecting a new MR).
pub fn reset_inspector_scroll(&mut self) {
self.inspector_scroll = 0;
}
pub fn tracker_scroll_down(&mut self, amount: u16) {
let max_scroll = self
.tracker_content_lines
.saturating_sub(self.tracker_pane_height);
self.tracker_scroll = self.tracker_scroll.saturating_add(amount).min(max_scroll);
}
pub fn tracker_scroll_up(&mut self, amount: u16) {
self.tracker_scroll = self.tracker_scroll.saturating_sub(amount);
}
pub fn reset_tracker_scroll(&mut self) {
self.tracker_scroll = 0;
}
/// Returns true when the selected MR has a linked tracker ticket.
pub fn has_tracker_ticket(&self) -> bool {
self.table_state
.selected()
.and_then(|i| self.visible_mrs().nth(i))
.and_then(|mr| mr.linked_ticket.as_ref())
.is_some()
}
pub fn next_row(&mut self) {
let count = self.visible_mrs().count();
if count == 0 {
return;
}
let i = match self.table_state.selected() {
Some(i) => {
if i >= count - 1 {
0
} else {
i + 1
}
}
None => 0,
};
self.table_state.select(Some(i));
// Reset inspector scroll when the selected MR changes.
self.reset_inspector_scroll();
}
pub fn prev_row(&mut self) {
let count = self.visible_mrs().count();
if count == 0 {
return;
}
let i = match self.table_state.selected() {
Some(i) => {
if i == 0 {
count - 1
} else {
i - 1
}
}
None => 0,
};
self.table_state.select(Some(i));
// Reset inspector scroll when the selected MR changes.
self.reset_inspector_scroll();
}
pub fn cycle_sort_column(&mut self) {
self.sort_column = match self.sort_column {
SortColumn::UpdatedAt => SortColumn::Id,
SortColumn::Id => SortColumn::Milestone,
SortColumn::Milestone => SortColumn::Title,
SortColumn::Title => SortColumn::UpdatedAt,
};
// Reset to a sensible default order when switching columns.
self.sort_order = match self.sort_column {
SortColumn::UpdatedAt => SortOrder::Descending,
_ => SortOrder::Ascending,
};
self.sort_mrs();
}
pub fn toggle_sort_order(&mut self) {
self.sort_order = match self.sort_order {
SortOrder::Ascending => SortOrder::Descending,
SortOrder::Descending => SortOrder::Ascending,
};
self.sort_mrs();
}
pub fn sort_mrs(&mut self) {
let order = self.sort_order;
let col = self.sort_column;
// Preserve the currently selected MR id so the cursor can be restored
// after the sort reorders the underlying vector.
let selected_id: Option<String> = self
.table_state
.selected()
.and_then(|i| self.visible_mrs().nth(i))
.map(|mr| mr.id.clone());
self.mrs.sort_by(|a, b| {
let cmp = match col {
SortColumn::UpdatedAt => {
// MRs without a timestamp are pushed to the bottom.
match (&a.updated_at, &b.updated_at) {
(Some(ta), Some(tb)) => ta.cmp(tb),
(None, Some(_)) => std::cmp::Ordering::Less,
(Some(_), None) => std::cmp::Ordering::Greater,
(None, None) => std::cmp::Ordering::Equal,
}
}
SortColumn::Id => {
let id_a = a.id.parse::<u64>().unwrap_or(0);
let id_b = b.id.parse::<u64>().unwrap_or(0);
id_a.cmp(&id_b)
}
SortColumn::Milestone => {
if a.milestone == "None" && b.milestone != "None" {
std::cmp::Ordering::Greater
} else if a.milestone != "None" && b.milestone == "None" {
std::cmp::Ordering::Less
} else {
a.milestone.to_lowercase().cmp(&b.milestone.to_lowercase())
}
}
SortColumn::Title => a.title.to_lowercase().cmp(&b.title.to_lowercase()),
};
if order == SortOrder::Ascending {
cmp
} else {
cmp.reverse()
}
});
// Restore the cursor on the same MR after the sort. If the previously
// selected MR is no longer visible (e.g. filtered out), fall back to
// position 0 so the selection is never left dangling.
if let Some(id) = selected_id {
let new_idx = self.visible_mrs().position(|mr| mr.id == id).unwrap_or(0);
self.table_state.select(Some(new_idx));
}
}
}
pub trait TrackedMrExt {
fn find_mut(&mut self, id: &str) -> Option<&mut TrackedMr>;
}
impl TrackedMrExt for Vec<TrackedMr> {
fn find_mut(&mut self, id: &str) -> Option<&mut TrackedMr> {
self.iter_mut().find(|m| m.id == id)
}
}
impl App {
/// Builds a `FetchContext` from the current application state.
///
/// Centralises the repeated construction of `FetchContext` that was
/// previously scattered across `main.rs` and `events.rs`.
pub fn fetch_context(&self) -> FetchContext {
FetchContext {
base_url: self.base_url.clone(),
token: self.token.clone(),
project_id: self.project_id.clone(),
branches: self.branches.clone(),
}
}
/// Restores tracked MRs from persisted state on startup.
///
/// For each saved MR:
/// - Reconstructs a `TrackedMr` with cached data (mergeability reset to Unknown).
/// - If the MR is not already fully merged into all branches, spawns a background
/// fetch and increments `pending_initial_fetches` to suppress spurious notifications.
pub fn restore_from_saved(
&mut self,
saved_mrs: Vec<SavedMr>,
semaphore: Arc<Semaphore>,
tx: UnboundedSender<AppEvent>,
) {
let ctx = self.fetch_context();
for saved in saved_mrs {
let initial_status = if !saved.found_branches.is_empty()
&& self
.branches
.iter()
.all(|b| saved.found_branches.contains(b))
{
MrStatus::MergedIn(saved.found_branches.clone())
} else {
MrStatus::Loading
};
self.mrs.push(TrackedMr {
id: saved.id.clone(),
title: saved.title.clone(),
status: initial_status.clone(),
sha: saved.sha.clone(),
description: saved
.description
.clone()
.unwrap_or_else(|| "No description cached.".to_string()),
author: saved
.author
.clone()
.unwrap_or_else(|| "Unknown".to_string()),
assignee: saved.assignee.clone().unwrap_or_else(|| "None".to_string()),
reviewers: saved.reviewers.clone(),
milestone: saved
.milestone
.clone()
.unwrap_or_else(|| "None".to_string()),
milestone_due_date: saved.milestone_due_date.clone(),
web_url: saved.web_url.clone().unwrap_or_default(),
labels: saved.labels.clone().unwrap_or_default(),
updated_at: saved.updated_at.clone(),
source_branch: saved
.source_branch
.clone()
.unwrap_or_else(|| "unknown".to_string()),
target_branch: saved
.target_branch
.clone()
.unwrap_or_else(|| "unknown".to_string()),
state: saved.state.clone(),
merged_by: saved.merged_by.clone(),
merged_at: saved.merged_at.clone(),
// Mergeability is not persisted — reset to Unknown on restart and re-fetched live.
mergeability: MergeabilityStatus::Unknown,
// Restore persisted pipelines — refreshed on each MR fetch.
pipelines: saved.pipelines.clone(),
// On startup, no MR is considered recently updated.
recently_updated: false,
// Restore persisted notes count — refreshed on each MR fetch.
user_notes_count: saved.user_notes_count,
// Restore persisted flagged state.
flagged: saved.flagged,
// Restore persisted ticket — avoids a tracker request on every restart.
linked_ticket: saved.linked_ticket,
// Restore persisted diff stats — refreshed only when updated_at changes.
diff_stats: saved.diff_stats.clone(),
});
if initial_status == MrStatus::Loading {
let cached = CachedMrData {
title: Some(saved.title),
sha: saved.sha,
description: saved.description,
author: saved.author,
assignee: saved.assignee,
web_url: saved.web_url,
labels: saved.labels,
updated_at: saved.updated_at,
pipelines: saved.pipelines,
diff_stats: saved.diff_stats,
};
// Count each pending fetch so we can suppress change notifications
// until the initial sync is complete (avoids spurious toasts on launch).
self.pending_initial_fetches += 1;
spawn_mr_fetch(ctx.clone(), saved.id, cached, semaphore.clone(), tx.clone());
}
}
if !self.mrs.is_empty() {
self.table_state.select(Some(0));
}
}
/// Applies a single `AppEvent` to the application state.
///
/// This is the central event dispatch extracted from `main.rs` to keep the
/// event loop thin. Returns `true` if the state was mutated in a way that
/// requires persisting (caller must then call `save_state_async`).
pub async fn apply_event(
&mut self,
event: AppEvent,
semaphore: Arc<Semaphore>,
tx: &UnboundedSender<AppEvent>,
last_known_branches: &mut HashMap<String, HashSet<String>>,
) -> bool {
match event {
// ── Tracker ticket resolved ───────────────────────────────────────
AppEvent::TrackerTicketLoaded { mr_id, ticket } => {
if let Some(mr) = self.mrs.find_mut(&mr_id) {
// Compute the diff between the cached ticket and the freshly fetched one.
// The diff logic lives entirely in `core` (LinkedTicket::diff) — this site
// only dispatches the resulting changes to the notification layer.
// Adding a new tracked field only requires touching `core::TicketChange`
// and `core::LinkedTicket::diff`; this match arm stays unchanged.
if let Some(old) = &mr.linked_ticket {
let mr_title = mr.title.clone();
let ticket_url = ticket.url.clone();
let ticket_id = ticket.id.clone();
for change in old.diff(&ticket) {
let (old_val, new_val) = change.before_after();
tracing::info!(
ticket_id = %ticket_id,
field = %change.field_label(),
old = %old_val,
new = %new_val,
"Tracker ticket field changed",
);
notify::ticket_field_changed(
&ticket_id,
&mr_title,
change.field_label(),
old_val,
new_val,
&ticket_url,
);
}
}
mr.linked_ticket = Some(*ticket);
}
// Ticket data is display-only — no state persist needed.
false
}
// ── Activity categories loaded ────────────────────────────────────
AppEvent::ActivitiesLoaded(activities) => {
self.activities = activities;
false
}
// ── Time entries loaded for a ticket ─────────────────────────────
AppEvent::TimeEntriesLoaded { entries } => {
self.time_entries = entries;
false
}
// ── Time log submitted successfully ───────────────────────────────
AppEvent::TimeLogSubmitted { mr_id, ticket_id } => {
// Re-fetch both time entries (for the TimeLog view) and the full ticket
// (so that spent_hours updates in the Inspector header and table column).
// We now carry the mr_id so TrackerTicketLoaded routes to the right MR.
if let Some(provider) = &self.tracker {
let provider = Arc::clone(provider);
let tx2 = tx.clone();
let tid = ticket_id.clone();
tokio::spawn(async move {
// Run both requests concurrently.
let (entries, ticket) = tokio::join!(
provider.fetch_time_entries(&tid),
provider.fetch_ticket(&tid),
);
let _ = tx2.send(AppEvent::TimeEntriesLoaded { entries });
if let Some(ticket) = ticket {
let _ = tx2.send(AppEvent::TrackerTicketLoaded {
mr_id,
ticket: Box::new(ticket),
});
}
});
}
// Close the popup and reset the form.
self.input_mode = InputMode::Normal;
self.log_time_form = LogTimeForm::default();
false
}
// ── Time log submission failed ────────────────────────────────────
AppEvent::TimeLogFailed { error } => {
self.log_time_form.submitting = false;
self.log_time_form.error = Some(error);
false
}
AppEvent::MrLoaded(data) => {
let Some(mr) = self.mrs.find_mut(&data.id) else {
return false;
};
// Compare new branches against the last persisted state to avoid
// re-notifying on restart or in-memory state that hasn't changed on disk.
let previously_known = last_known_branches
.get(&data.id)
.cloned()
.unwrap_or_default();
for b in &data.branches {
if !previously_known.contains(b) {
notify::mr_on_new_branch(&data.id, &data.title, b, &data.web_url);
}
}
// Update the persisted reference so subsequent refreshes won't re-notify.
last_known_branches.insert(data.id.clone(), data.branches.clone());
// Decrement the startup fence: notifications are suppressed until
// all MRs from the saved state have received their first API response.
let notify_allowed = self.pending_initial_fetches == 0;
if self.pending_initial_fetches > 0 {
self.pending_initial_fetches -= 1;
}
// Decrement the auto-refresh counter (drives the spinner in the table title).
if self.pending_refresh_fetches > 0 {
self.pending_refresh_fetches -= 1;
}
// Detect whether this MR was actually updated since the last refresh.
// We compare the old `updated_at` before overwriting it.
let was_updated = mr.updated_at.is_some() && mr.updated_at != data.updated_at;
// Trace field-level changes so they are visible in the log file.
// All comparisons happen before the fields are overwritten below.
if was_updated {
tracing::info!(
mr_id = %data.id,
old = %mr.updated_at.as_deref().unwrap_or("none"),
new = %data.updated_at.as_deref().unwrap_or("none"),
"MR updated_at changed",
);
if notify_allowed {
notify::mr_updated(
&data.id,
&data.title,
data.updated_at.as_deref(),
&data.web_url,
);
}
}
if mr.mergeability != data.mergeability {
tracing::info!(
mr_id = %data.id,
old = ?mr.mergeability,
new = ?data.mergeability,
"MR mergeability changed",
);
if notify_allowed {
notify::mr_mergeability_changed(
&data.id,
&data.title,
&format!("{:?}", mr.mergeability),
&format!("{:?}", data.mergeability),
&data.web_url,
);
}
}
if mr.milestone != data.milestone {
tracing::info!(
mr_id = %data.id,
old = %mr.milestone,
new = %data.milestone,
"MR milestone changed",
);
if notify_allowed {
notify::mr_milestone_changed(
&data.id,
&data.title,
&mr.milestone,
&data.milestone,
&data.web_url,
);
}
}
mr.title = data.title;
mr.sha = data.sha;
mr.status = MrStatus::MergedIn(data.branches);
mr.description = data.description;
mr.author = data.author;
mr.assignee = data.assignee;
mr.reviewers = data.reviewers;
mr.milestone = data.milestone;
mr.milestone_due_date = data.milestone_due_date;
mr.web_url = data.web_url;
mr.labels = data.labels;
mr.updated_at = data.updated_at;
mr.source_branch = data.source_branch;
mr.target_branch = data.target_branch;
mr.state = data.state;
mr.merged_by = data.merged_by;
mr.merged_at = data.merged_at;
mr.mergeability = data.mergeability;
mr.pipelines = data.pipelines;
mr.recently_updated = was_updated;
mr.user_notes_count = data.user_notes_count;
mr.diff_stats = data.diff_stats;
// Arm (or re-arm) the global fade countdown.
if was_updated {
self.update_highlight_ticks = RECENT_UPDATE_FADE_TICKS;
}
// If a tracker provider is active, re-fetch the linked ticket when:
// • the detected ticket ID is new or has changed (ID mismatch), OR
// • the MR was updated since the last refresh (was_updated), which
// implies that time entries or status may have changed on the
// tracker side (e.g. after a manual [R] refresh).
if let Some(provider) = &self.tracker {
let detected_id = provider.detect_ticket_id(&mr.title, &mr.description);
let cached_id = mr.linked_ticket.as_ref().map(|t| t.id.clone());
// Determine the ticket id to fetch:
// - If the detected id differs from the cache → use the new id.
// - If they match but we want a forced refresh → reuse the cached id.
// - If the cached ticket's schema is outdated → invalidate and re-fetch.
// - If nothing is detected and nothing cached → nothing to do.
let cache_is_stale = mr.linked_ticket.as_ref().is_some_and(|t| {
t.schema_version < gitlab_tracker_core::LINKED_TICKET_SCHEMA_VERSION
});
let fetch_id: Option<String> = if detected_id != cached_id {
// ID changed (or newly detected): always re-fetch.
detected_id.clone()
} else if detected_id.is_some() && was_updated {
// Same ID but the MR was updated: refresh to pick up new spent hours.
detected_id.clone()
} else if detected_id.is_some() && cache_is_stale {
// Same ID but the cached struct is from an older schema version:
// re-fetch silently to populate the new fields.
detected_id.clone()
} else {
// No change needed.
None
};
if let Some(raw_id) = fetch_id {
let provider = Arc::clone(provider);
let mr_id = mr.id.clone();
let tx2 = tx.clone();
tokio::spawn(async move {
if let Some(ticket) = provider.fetch_ticket(&raw_id).await {
let _ = tx2.send(AppEvent::TrackerTicketLoaded {
mr_id,
ticket: Box::new(ticket),
});
}
});
} else if detected_id.is_none() && cached_id.is_some() {
// Ticket reference was removed from the MR — clear the cache.
mr.linked_ticket = None;
}
}
self.sort_mrs();
true
}
AppEvent::MrFailed { id, error } => {
let Some(mr) = self.mrs.find_mut(&id) else {
return false;
};
mr.title = format!("⚠️ ERROR: {}", error);
mr.status = MrStatus::Error;
true
}
AppEvent::GitlabLabelsLoaded(labels) => {
// Store into config so it flows through everywhere config is passed.
self.config.gitlab_label_colors = labels
.into_iter()
.map(|l| (l.name.to_lowercase(), l.color))
.collect();
false
}
AppEvent::MilestonesLoaded(milestones) => {
self.milestones = milestones;
false
}
AppEvent::MilestoneMrsLoaded {
milestone_title,
mr_ids,
} => {
let ctx = self.fetch_context();
let mut added = 0u32;
for mr_id in mr_ids {
// Skip MRs already tracked to avoid duplicates.
if self.mrs.iter().any(|m| m.id == mr_id) {
continue;
}
self.mrs.push(TrackedMr {
id: mr_id.clone(),
title: format!("Loading… ({})", milestone_title),
status: MrStatus::Loading,
state: GitlabMrState::Opened,
mergeability: MergeabilityStatus::Unknown,
sha: None,
description: String::new(),
author: "Loading".to_string(),
assignee: "Loading".to_string(),
reviewers: vec![],
milestone: milestone_title.clone(),
milestone_due_date: None,
web_url: String::new(),
labels: vec![],
updated_at: None,
source_branch: "unknown".to_string(),
target_branch: "unknown".to_string(),
merged_by: None,
merged_at: None,
pipelines: vec![],
recently_updated: false,
user_notes_count: 0,
// New MRs start unflagged.
flagged: false,
diff_stats: None,
// Ticket resolved live after each MR fetch — never pre-populated.
linked_ticket: None,
});
spawn_mr_fetch(
ctx.clone(),
mr_id,
CachedMrData::default(),
semaphore.clone(),
tx.clone(),
);
added += 1;
}
if added > 0 {
self.table_state.select(Some(0));
true
} else {
false
}
}
AppEvent::Tick => {
// Decrement the highlight fade countdown and clear flags when expired.
if self.update_highlight_ticks > 0 {
self.update_highlight_ticks -= 1;
if self.update_highlight_ticks == 0 {
for mr in &mut self.mrs {
mr.recently_updated = false;
}
}
}
if self.time_left > 0 {
self.time_left -= 1;
return false;
}
// Timer elapsed — trigger a full refresh of all MRs.
self.time_left = self.refresh_interval_secs;
let ctx = self.fetch_context();
for mr in &mut self.mrs {
if let MrStatus::MergedIn(ref found) = mr.status {
// Skip refresh for MRs that are fully merged into all branches —
// state != Opened ensures we don't skip still-open MRs.
if self.branches.iter().all(|b| found.contains(b))
&& mr.sha.is_some()
&& mr.state != GitlabMrState::Opened
{
continue;
}
}
mr.status = MrStatus::Loading;
let cached = CachedMrData {
title: Some(mr.title.clone()),
sha: mr.sha.clone(),
description: Some(mr.description.clone()),
author: Some(mr.author.clone()),
assignee: Some(mr.assignee.clone()),
web_url: Some(mr.web_url.clone()),
labels: Some(mr.labels.clone()),
updated_at: mr.updated_at.clone(),
pipelines: mr.pipelines.clone(),
diff_stats: mr.diff_stats.clone(),
};
spawn_mr_fetch(
ctx.clone(),
mr.id.clone(),
cached,
semaphore.clone(),
tx.clone(),
);
// Track pending auto-refresh fetches to drive the spinner.
self.pending_refresh_fetches += 1;
// Re-fetch the tracker ticket unconditionally on each auto-refresh cycle,
// mirroring the manual [R] refresh behaviour. The GitLab MR may not have
// changed (was_updated = false) while the tracker ticket status, spent time,
// or priority did — the conditional re-fetch inside MrLoaded would miss this.
if let Some(provider) = self.tracker.as_ref().map(Arc::clone) {
if let Some(ticket_id) = mr.linked_ticket.as_ref().map(|t| t.id.clone()) {
let mr_id = mr.id.clone();
let tx2 = tx.clone();
tokio::spawn(async move {
if let Some(ticket) = provider.fetch_ticket(&ticket_id).await {
let _ = tx2.send(AppEvent::TrackerTicketLoaded {
mr_id,
ticket: Box::new(ticket),
});
}
});
}
}
}
false
}
}
}
}