brain: Refine commit history view

8e126a35062022fae6bb9f1f096a0cbe2fba1f24
Present multi-commit reviews as an aligned, navigable history while keeping
commit diffs lazy until opened.

Assisted-by: Codex:gpt-5.6-sol
Alexis Sellier committed ago 1 parent 5172b0d3
crates/brain/src/backend.rs +77 -14
199 199
    pub hunks: Option<&'a BTreeMap<HunkId, AcceptedHunk>>,
200 200
}
201 201
202 202
/// Review state of one commit projected from the accepted set.
203 203
pub struct Reconciled {
204 -
    /// Whether every hunk in the commit is accepted.
205 -
    pub reviewed: bool,
204 +
    /// Accepted-hunk progress for the commit.
205 +
    pub progress: ReviewProgress,
206 206
    /// Accepted hunks, for commits whose hunk patch ids were supplied.
207 207
    pub accepted: BTreeSet<HunkId>,
208 208
}
209 209
210 210
impl Reconciled {
211 211
    /// Projects exact accepted identities onto commit-local hunk ids.
212 212
    fn for_commits(accepted_state: &Accepted, commits: &[CommitHunks<'_>]) -> Vec<Self> {
213 213
        // Accepted count and total hunk count per commit, so undecoded commits
214 -
        // can be marked reviewed from persisted totals alone.
214 +
        // retain their progress from persisted totals.
215 215
        let mut totals = BTreeMap::<Oid, (usize, u32)>::new();
216 216
        for identity in accepted_state {
217 217
            let entry = totals
218 218
                .entry(identity.commit)
219 219
                .or_insert((0, identity.commit_hunks));
220 220
            entry.0 += 1;
221 221
        }
222 222
223 223
        let mut reconciled = Vec::with_capacity(commits.len());
224 224
        for commit in commits {
225 -
            let (reviewed, accepted) = match commit.hunks {
225 +
            let (progress, accepted) = match commit.hunks {
226 226
                Some(hunks) => {
227 227
                    let accepted = hunks
228 228
                        .iter()
229 229
                        .filter(|(_, identity)| accepted_state.contains(identity))
230 230
                        .map(|(id, _)| *id)
231 231
                        .collect::<BTreeSet<_>>();
232 -
                    (!hunks.is_empty() && accepted.len() == hunks.len(), accepted)
232 +
                    (
233 +
                        ReviewProgress {
234 +
                            accepted: accepted.len(),
235 +
                            total: hunks.len(),
236 +
                        },
237 +
                        accepted,
238 +
                    )
233 239
                }
234 240
                None => {
235 -
                    let reviewed = totals
236 -
                        .get(&commit.commit)
237 -
                        .is_some_and(|(accepted, total)| *accepted == *total as usize);
238 -
                    (reviewed, BTreeSet::new())
241 +
                    let progress = totals.get(&commit.commit).map_or_else(
242 +
                        ReviewProgress::default,
243 +
                        |(accepted, total)| ReviewProgress {
244 +
                            accepted: *accepted,
245 +
                            total: *total as usize,
246 +
                        },
247 +
                    );
248 +
                    (progress, BTreeSet::new())
239 249
                }
240 250
            };
241 -
            reconciled.push(Self { reviewed, accepted });
251 +
            reconciled.push(Self { progress, accepted });
242 252
        }
243 253
        reconciled
244 254
    }
245 255
}
246 256
431 441
/// A revision backend that lists the reviewed commits and their diffs.
432 442
///
433 443
/// The base and target revisions are resolved and stored when the backend is
434 444
/// constructed, so listing commits needs no further arguments.
435 445
pub trait Backend {
446 +
    /// Returns the user-facing revision range under review.
447 +
    fn range_label(&self) -> String;
448 +
    /// Returns the base-to-target diff statistics for the reviewed range.
449 +
    fn range_stats(&self) -> Result<DiffStat, Error>;
450 +
436 451
    /// Returns the reviewed commits in `base..target`, oldest first.
437 452
    fn commits(&self) -> Result<Vec<Commit>, Error>;
438 453
439 454
    /// Returns `commit`'s header.
440 455
    fn commit_header(&self, commit: Oid) -> Result<CommitHeader, Error>;
1147 1162
        })
1148 1163
    }
1149 1164
}
1150 1165
1151 1166
impl Backend for GitBackend {
1167 +
    fn range_label(&self) -> String {
1168 +
        format!(
1169 +
            "{} .. {}",
1170 +
            self.review.base.as_str(),
1171 +
            self.review.target.as_str()
1172 +
        )
1173 +
    }
1174 +
    fn range_stats(&self) -> Result<DiffStat, Error> {
1175 +
        let base = self.repository.commit_id(&self.review.base)?;
1176 +
        let target = self.repository.commit_id(&self.review.target)?;
1177 +
        let document = DiffDocument::decode_str(&self.repository.diff(base, target)?)?;
1178 +
        let stats = document.stats();
1179 +
        Ok(DiffStat {
1180 +
            files_changed: stats.files_changed,
1181 +
            insertions: stats.insertions,
1182 +
            deletions: stats.deletions,
1183 +
        })
1184 +
    }
1185 +
1152 1186
    fn commits(&self) -> Result<Vec<Commit>, Error> {
1153 1187
        let pairs = self
1154 1188
            .repository
1155 1189
            .commits(&self.review.base, &self.review.target)?;
1156 1190
        Commit::with_stats(&self.repository, pairs)
1222 1256
        })
1223 1257
    }
1224 1258
}
1225 1259
1226 1260
impl Backend for JjBackend {
1261 +
    fn range_label(&self) -> String {
1262 +
        format!(
1263 +
            "{} .. {}",
1264 +
            self.review.base.as_str(),
1265 +
            self.review.target.as_str()
1266 +
        )
1267 +
    }
1268 +
    fn range_stats(&self) -> Result<DiffStat, Error> {
1269 +
        let base = self.jj.resolve(&self.review.base)?;
1270 +
        let target = self.jj.resolve(&self.review.target)?;
1271 +
        let document = DiffDocument::decode_str(&self.repository.diff(base, target)?)?;
1272 +
        let stats = document.stats();
1273 +
        Ok(DiffStat {
1274 +
            files_changed: stats.files_changed,
1275 +
            insertions: stats.insertions,
1276 +
            deletions: stats.deletions,
1277 +
        })
1278 +
    }
1279 +
1227 1280
    fn commits(&self) -> Result<Vec<Commit>, Error> {
1228 1281
        let pairs = self.jj.commits(&self.review.base, &self.review.target)?;
1229 1282
        Commit::with_stats(&self.repository, pairs)
1230 1283
    }
1231 1284
1351 1404
            },
1352 1405
        ];
1353 1406
1354 1407
        let fresh = Reconciled::for_commits(&Accepted::new(), &commits);
1355 1408
        assert!(fresh.iter().all(|state| state.accepted.is_empty()));
1356 -
        assert!(fresh.iter().all(|state| !state.reviewed));
1409 +
        assert!(fresh.iter().all(|state| state.progress
1410 +
            == ReviewProgress {
1411 +
                accepted: 0,
1412 +
                total: 1,
1413 +
            }));
1357 1414
1358 1415
        let remaining = Reconciled::for_commits(&Accepted::from([second]), &commits);
1359 1416
        assert!(remaining[0].accepted.is_empty());
1360 1417
        assert_eq!(remaining[1].accepted, BTreeSet::from([HunkId::new(0)]));
1361 -
        assert!(remaining[1].reviewed);
1418 +
        assert!(remaining[1].progress.is_complete());
1362 1419
    }
1363 1420
1364 1421
    #[test]
1365 1422
    fn reconciliation_marks_undecoded_commits_from_persisted_totals() {
1366 1423
        let first = accepted_hunk("1111111111111111111111111111111111111111", "alpha", 0, 2);
1369 1426
            commit: first.commit,
1370 1427
            hunks: None,
1371 1428
        }];
1372 1429
1373 1430
        let partial = Reconciled::for_commits(&Accepted::from([first.clone()]), &commits);
1374 -
        assert!(!partial[0].reviewed);
1431 +
        assert_eq!(
1432 +
            partial[0].progress,
1433 +
            ReviewProgress {
1434 +
                accepted: 1,
1435 +
                total: 2,
1436 +
            }
1437 +
        );
1375 1438
        assert!(partial[0].accepted.is_empty());
1376 1439
1377 1440
        let full = Reconciled::for_commits(&Accepted::from([first, second]), &commits);
1378 -
        assert!(full[0].reviewed);
1441 +
        assert!(full[0].progress.is_complete());
1379 1442
        assert!(full[0].accepted.is_empty());
1380 1443
    }
1381 1444
1382 1445
    #[test]
1383 1446
    fn rebase_remaps_within_a_commit_before_across_commits() {
f +0 -0
crates/brain/src/session.rs +138 -53
9 9
    ContextChange, DiffAction, DiffDocument, DiffFocus, DiffOptions, DiffViewer, FileDiff,
10 10
    FileTreeMode, HighlightOutput, HighlightRequest, Highlighter, ReviewProgress, ViewChange,
11 11
    spawn_highlighter,
12 12
};
13 13
use rustik_repo::DiffStat;
14 -
use rustik_tui::{Control, Event, Key, Line, List, ListState, Mouse, MouseButton, Rect, Terminal};
14 +
use rustik_tui::{
15 +
    Constraint, Control, Event, Key, Line, List, ListState, Mouse, MouseButton, Rect, Size, Style,
16 +
    Table, TableOptions, Terminal,
17 +
};
15 18
use rustik_tui_termion as tui_termion;
16 19
17 20
use crate::backend::{Backend, Brain, Commit, CommitHunks, FilePatches};
18 21
use crate::comments::ReviewComments;
19 22
use crate::error::Error;
25 28
mod status;
26 29
27 30
use commit::{CommitReview, CommitSlot};
28 31
use event::{ContextFetch, Resize, TerminalEvent, Update, context_change};
29 32
use hunk::{CommentEdit, HunkView};
30 -
use status::{ActionContext, Chrome, Status, commit_row, viewer_area};
33 +
use status::{
34 +
    ActionContext, Chrome, SELECTED_COMMIT_BG, Status, StatusContext, commit_row, viewer_area,
35 +
};
31 36
32 37
pub(crate) use status::{BRAIN_BADGE_BG, progress_bar};
33 38
34 39
/// Terminal backend used by the interactive viewer.
35 40
type BrainTerminal = Terminal<tui_termion::TermionBackend<tui_termion::term::TerminalScreen>>;
104 109
    let Events {
105 110
        tx: events_tx,
106 111
        rx: events_rx,
107 112
    } = events;
108 113
114 +
    let (mode, range_stats) = if commits.len() > 1 {
115 +
        (Mode::Commits, Some(backend.range_stats()?))
116 +
    } else {
117 +
        (Mode::Diff, None)
118 +
    };
119 +
120 +
    let range = backend.range_label();
121 +
109 122
    let mut session = Session {
110 123
        terminal,
111 124
        commits: commits
112 125
            .into_iter()
126 +
            .rev()
113 127
            .map(|commit| CommitSlot {
114 128
                commit,
115 -
                reviewed: false,
129 +
                progress: ReviewProgress::default(),
116 130
                loaded: None,
117 131
            })
118 132
            .collect(),
133 +
        range_stats,
134 +
        range,
119 135
        current: 0,
120 136
        visibility: Visibility::default(),
121 -
        mode: Mode::Diff,
137 +
        mode,
122 138
        parked: None,
123 139
        list: ListState::new(),
124 140
        options,
125 141
        backend,
126 142
        brain,
129 145
        generation: 0,
130 146
        highlighter: None,
131 147
        context_fetch: ContextFetch::default(),
132 148
        error: None,
133 149
    };
134 -
    session.current()?;
135 -
    session.reconcile_reviews()?;
136 -
    session.activate()?;
150 +
    if !matches!(session.mode, Mode::Commits) {
151 +
        session.current()?;
152 +
    }
153 +
    session.reconcile_state();
154 +
    if !matches!(session.mode, Mode::Commits) {
155 +
        session.activate()?;
156 +
    }
137 157
    session.redraw()?;
138 158
139 159
    while let Ok(event) = events_rx.recv() {
140 160
        let mut redraw = false;
141 161
        let mut next = Some(event);
162 182
163 183
/// Interactive terminal session state.
164 184
struct Session<'a> {
165 185
    /// Terminal frame target.
166 186
    terminal: &'a mut BrainTerminal,
167 -
    /// Per-commit review slots, oldest first.
187 +
    /// Per-commit review slots, newest first.
168 188
    commits: Vec<CommitSlot>,
189 +
    /// User-facing revision range under review.
190 +
    range: String,
191 +
    /// Lazily cached base-to-target statistics for the reviewed range.
192 +
    range_stats: Option<DiffStat>,
169 193
    /// Index of the commit currently displayed.
170 194
    current: usize,
171 195
    /// Session-wide accepted-hunk visibility.
172 196
    visibility: Visibility,
173 197
    /// Active view: the commit list, the diff, or a hunk's comment box.
346 370
        Ok(Control::Redraw)
347 371
    }
348 372
349 373
    /// Displays the commit at `index`, loading it and respawning workers.
350 374
    fn select_commit(&mut self, index: usize) -> Result<(), Error> {
375 +
        if index != self.current {
376 +
            self.parked = None;
377 +
        }
351 378
        self.current = index;
352 -
        self.parked = None;
353 379
354 380
        let newly_loaded = self.commits[index].loaded.is_none();
355 381
        self.current()?;
356 382
357 383
        if newly_loaded {
358 384
            // Project exact acceptance onto the freshly decoded hunks.
359 -
            self.reconcile_reviews()?;
385 +
            self.reconcile_state();
360 386
        }
387 +
        self.mode = Mode::Diff;
361 388
        self.activate()?;
362 389
363 390
        Ok(())
364 391
    }
365 392
376 403
            | Event::Mouse(Mouse::Press {
377 404
                button: MouseButton::WheelUp,
378 405
                ..
379 406
            }) => -1,
380 407
            Event::Key(Key::Enter) => {
381 -
                let selected = self.list.selected();
382 -
                if selected != self.current {
383 -
                    self.select_commit(selected)?;
384 -
                }
385 -
                self.mode = Mode::Diff;
408 +
                self.select_commit(self.list.selected())?;
386 409
                return Ok(Control::Redraw);
387 410
            }
388 411
            Event::Key(Key::Tab) => {
389 412
                self.next_tab()?;
390 413
                return Ok(Control::Redraw);
546 569
        self.restart_highlighter()?;
547 570
548 571
        Ok(())
549 572
    }
550 573
574 +
    /// Loads and caches the base-to-target statistics used by history.
575 +
    fn ensure_range_stats(&mut self) -> Result<(), Error> {
576 +
        if self.range_stats.is_none() {
577 +
            self.range_stats = Some(self.backend.range_stats()?);
578 +
        }
579 +
        Ok(())
580 +
    }
581 +
551 582
    /// Switches to the next review tab, parking any open hunk view.
552 583
    fn next_tab(&mut self) -> Result<(), Error> {
553 -
        self.mode = match mem::replace(&mut self.mode, Mode::Diff) {
554 -
            Mode::Commits => Mode::Diff,
584 +
        let opens_history = matches!(&self.mode, Mode::Hunk(_))
585 +
            || matches!(&self.mode, Mode::Diff) && self.parked.is_none();
586 +
        if opens_history {
587 +
            self.ensure_range_stats()?;
588 +
            self.stop_highlighter();
589 +
        }
590 +
        match mem::replace(&mut self.mode, Mode::Diff) {
591 +
            Mode::Commits => {
592 +
                self.select_commit(self.list.selected())?;
593 +
            }
555 594
            Mode::Diff => {
556 595
                if let Some(parked) = self.parked.take() {
557 -
                    Mode::Hunk(parked)
596 +
                    self.mode = Mode::Hunk(parked);
597 +
                    self.restart_highlighter()?;
558 598
                } else {
559 599
                    self.list.select(self.current, self.commits.len());
560 -
                    Mode::Commits
600 +
                    self.mode = Mode::Commits;
561 601
                }
562 602
            }
563 603
            Mode::Hunk(view) => {
564 604
                self.parked = Some(view);
565 605
                self.list.select(self.current, self.commits.len());
566 -
                Mode::Commits
606 +
                self.mode = Mode::Commits;
567 607
            }
568 -
        };
569 -
        self.restart_highlighter()?;
608 +
        }
570 609
        Ok(())
571 610
    }
572 611
573 612
    /// Routes one key to the comment editor while the hunk view is open.
574 613
    fn handle_hunk_key(&mut self, event: Event<()>, area: Rect) -> Result<Control, Error> {
577 616
        if let Mode::Hunk(view) = &mut self.mode
578 617
            && !view.is_editing()
579 618
        {
580 619
            match event {
581 620
                Event::Key(Key::Esc) => {
621 +
                    self.stop_highlighter();
582 622
                    self.mode = Mode::Diff;
623 +
                    self.restart_highlighter()?;
583 624
                    return Ok(Control::Redraw);
584 625
                }
585 626
                Event::Key(Key::Tab) => {
586 627
                    self.next_tab()?;
587 628
                    return Ok(Control::Redraw);
810 851
    ///
811 852
    /// This is the only place that replaces `Review` sets and reviewed marks.
812 853
    /// Keeping it as a full recomputation keeps the persisted accepted set,
813 854
    /// current commit list, and per-viewer decorations consistent. Persisted
814 855
    /// hunk totals provide the reviewed mark for commits not yet decoded.
815 -
    fn reconcile_reviews(&mut self) -> Result<(), Error> {
856 +
    fn reconcile_state(&mut self) {
816 857
        let commits = self
817 858
            .commits
818 859
            .iter()
819 860
            .map(|slot| CommitHunks {
820 861
                commit: slot.commit.id,
821 862
                hunks: slot.loaded.as_ref().map(|loaded| &loaded.identities),
822 863
            })
823 864
            .collect::<Vec<_>>();
824 865
        let reconciled = self.brain.reconcile(&commits);
825 866
        for (slot, reconciled) in self.commits.iter_mut().zip(reconciled) {
826 -
            slot.reviewed = reconciled.reviewed;
867 +
            slot.progress = reconciled.progress;
827 868
            if let Some(loaded) = &mut slot.loaded {
828 869
                loaded.review.replace(reconciled.accepted);
829 870
                loaded.refresh_decorations();
830 871
            }
831 872
        }
832 -
        if !self.visibility.show_accepted {
873 +
    }
874 +
875 +
    /// Reconciles review state and refreshes the active viewer when needed.
876 +
    fn reconcile_reviews(&mut self) -> Result<(), Error> {
877 +
        self.reconcile_state();
878 +
        if !self.visibility.show_accepted && !matches!(self.mode, Mode::Commits) {
833 879
            self.refresh_visibility()?;
834 880
        }
835 881
        Ok(())
836 882
    }
837 883
889 935
        {
890 936
            viewer.cancel_highlights(dropped);
891 937
        }
892 938
    }
893 939
940 +
    /// Stops asynchronous work and invalidates results from the active generation.
941 +
    fn stop_highlighter(&mut self) {
942 +
        if let Some(viewer) = self.active_viewer() {
943 +
            viewer.retry_pending_highlights();
944 +
        }
945 +
        self.generation += 1;
946 +
        self.highlighter = None;
947 +
        self.context_fetch = ContextFetch::Idle;
948 +
    }
949 +
894 950
    /// Restarts asynchronous syntax highlighting for the active generation.
895 951
    fn restart_highlighter(&mut self) -> Result<(), Error> {
896 -
        self.generation += 1;
952 +
        self.stop_highlighter();
897 953
898 954
        let generation = self.generation;
899 955
        let tx = self.events_tx.clone();
900 956
        let highlighter = if let Mode::Hunk(view) = &self.mode {
901 957
            spawn_highlighter(view.viewer.document(), None, move |output| {
907 963
            spawn_highlighter(loaded.viewer.document(), repo, move |output| {
908 964
                let _ = tx.send(TerminalEvent::Highlight(generation, output));
909 965
            })
910 966
        };
911 967
        self.highlighter = Some(highlighter);
912 -
        self.context_fetch = ContextFetch::Idle;
913 968
914 969
        Ok(())
915 970
    }
916 971
917 972
    /// Requests context refetch work for one context change.
956 1011
                    frame.render_widget(&mut chrome, chrome_area);
957 1012
                })?;
958 1013
            }
959 1014
            Mode::Commits => {
960 1015
                let palette = self.options.diff_palette;
961 -
                let rows: Vec<Line> = self
962 -
                    .commits
963 -
                    .iter()
964 -
                    .map(|slot| commit_row(slot, palette))
965 -
                    .collect();
1016 +
                let mut table = Table::<8, Line>::new(TableOptions {
1017 +
                    spacing: 2,
1018 +
                    ..TableOptions::default()
1019 +
                });
1020 +
                let last = self.commits.len() - 1;
1021 +
                for (index, slot) in self.commits.iter().enumerate() {
1022 +
                    let graph = match (index, last) {
1023 +
                        (0, 0) => "──●",
1024 +
                        (0, _) => "╭─●",
1025 +
                        (index, last) if index == last => "╰─●",
1026 +
                        _ => "├─●",
1027 +
                    };
1028 +
                    table.push(commit_row(slot, palette, graph));
1029 +
                }
966 1030
                self.terminal.draw(|frame| {
967 1031
                    let (body, chrome_area) = Chrome::areas(frame.area);
968 -
                    frame.render_stateful_widget(List::new(rows), body, &mut self.list);
1032 +
                    let rows = table.lines(Constraint::max(Size::new(body.cols, usize::MAX)));
1033 +
                    let selected = Style::default().bg(SELECTED_COMMIT_BG);
1034 +
                    let list = List::new(rows)
1035 +
                        .selected_styles(selected, selected)
1036 +
                        .scrollbar(DiffViewer::scrollbar_style());
1037 +
                    frame.render_stateful_widget(list, body, &mut self.list);
969 1038
                    frame.render_widget(&mut chrome, chrome_area);
970 1039
                })?;
971 1040
            }
972 1041
            Mode::Diff => {
973 1042
                self.terminal.draw(|frame| {
985 1054
            .set_cursor_visible(matches!(self.mode, Mode::Hunk(ref view) if view.is_editing()))
986 1055
    }
987 1056
988 1057
    /// Returns the footer chrome for the current session mode.
989 1058
    fn chrome(&self) -> Chrome {
990 -
        let slot = &self.commits[self.current];
991 -
        let progress = slot
992 -
            .loaded
993 -
            .as_ref()
994 -
            .map_or_else(ReviewProgress::default, |loaded| ReviewProgress {
995 -
                accepted: loaded.review.accepted().len(),
996 -
                total: loaded.file_hunks.values().map(Vec::len).sum(),
997 -
            });
998 -
        let stats = slot.loaded.as_ref().map_or_else(
999 -
            || {
1000 -
                if slot.reviewed {
1001 -
                    DiffStat::default()
1002 -
                } else {
1003 -
                    slot.commit.stats
1004 -
                }
1005 -
            },
1006 -
            CommitReview::remaining_stats,
1007 -
        );
1059 +
        let (context, progress, stats) = if matches!(self.mode, Mode::Commits) {
1060 +
            let stats = self.range_stats.unwrap_or_default();
1061 +
            (
1062 +
                StatusContext::Range(self.range.clone()),
1063 +
                ReviewProgress::default(),
1064 +
                stats,
1065 +
            )
1066 +
        } else {
1067 +
            let slot = &self.commits[self.current];
1068 +
            let progress = slot
1069 +
                .loaded
1070 +
                .as_ref()
1071 +
                .map_or(slot.progress, |loaded| ReviewProgress {
1072 +
                    accepted: loaded.review.accepted().len(),
1073 +
                    total: loaded.file_hunks.values().map(Vec::len).sum(),
1074 +
                });
1075 +
            let stats = slot.loaded.as_ref().map_or_else(
1076 +
                || {
1077 +
                    if slot.progress.is_complete() {
1078 +
                        DiffStat::default()
1079 +
                    } else {
1080 +
                        slot.commit.stats
1081 +
                    }
1082 +
                },
1083 +
                CommitReview::remaining_stats,
1084 +
            );
1085 +
            (
1086 +
                StatusContext::Commit {
1087 +
                    short: slot.commit.id.short(),
1088 +
                    summary: slot.commit.summary.clone(),
1089 +
                },
1090 +
                progress,
1091 +
                stats,
1092 +
            )
1093 +
        };
1008 1094
        Chrome {
1009 1095
            status: Status {
1010 1096
                mode: self.mode.label(),
1011 -
                short: slot.commit.id.short(),
1012 -
                summary: slot.commit.summary.clone(),
1097 +
                context,
1013 1098
                progress,
1014 1099
                stats,
1015 1100
                palette: self.options.diff_palette,
1016 1101
                visibility: self.visibility,
1017 1102
                error: self.error.clone(),
crates/brain/src/session/commit.rs +4 -5
2 2
3 3
use std::collections::BTreeMap;
4 4
5 5
use rustik_diff::{
6 6
    ContextUpdate, DiffDocument, DiffOptions, DiffViewer, Encode as _, FileDiff, FileId, FileStats,
7 -
    HunkId,
7 +
    HunkId, ReviewProgress,
8 8
};
9 9
use rustik_repo::DiffStat;
10 10
use rustik_tui::Rect;
11 11
12 12
use crate::backend::{AcceptedHunk, Brain, Commit};
17 17
18 18
/// One commit in the reviewed range: header data plus lazily decoded state.
19 19
pub(super) struct CommitSlot {
20 20
    /// Commit under review.
21 21
    pub(super) commit: Commit,
22 -
    /// Whether every hunk in this commit is accepted.
22 +
    /// Accepted-hunk progress for this commit.
23 23
    ///
24 -
    /// Persisted hunk totals let the commit list mark reviewed commits before
25 -
    /// they are decoded.
26 -
    pub(super) reviewed: bool,
24 +
    /// Persisted hunk totals provide progress before the diff is decoded.
25 +
    pub(super) progress: ReviewProgress,
27 26
    /// Decoded diff state, populated when the commit is first displayed.
28 27
    pub(super) loaded: Option<CommitReview>,
29 28
}
30 29
31 30
/// Decoded review state for one commit: its viewer, accepted hunks, and the
a.rs +0 -0
crates/brain/src/session/status.rs +60 -30
36 36
const FOOTER_VALUE_FG: Color = FOOTER_HASH_FG;
37 37
/// Foreground color for the current commit summary.
38 38
const FOOTER_SUMMARY_FG: Color = Color::Fixed(153);
39 39
/// Border color for the selected comment in the hunk view.
40 40
const SELECTED_COMMENT_BORDER: Color = Color::Fixed(239);
41 +
/// Background color for the selected commit, matching the active file row.
42 +
pub(super) const SELECTED_COMMIT_BG: Color = Color::Fixed(235);
41 43
/// Marker shown beside a commit whose hunks have all been accepted: ✔.
42 44
const REVIEWED_MARK: char = '✔';
43 45
/// Marker shown when accepted hunks are visible in the footer: ✔.
44 46
const APPROVED_HUNKS_MODE_ICON: &str = "✔";
45 47
/// Marker shown when full-file mode is visible in the footer: ↕.
103 105
pub(super) const COMMENT_CARD_CHROME_ROWS: usize = 3;
104 106
/// Columns of card chrome on each side of a comment body: the border and its
105 107
/// padding.
106 108
pub(super) const COMMENT_CARD_CHROME_COLS: usize = 2;
107 109
108 -
/// Footer status describing the current commit and review progress.
110 +
/// Context shown on the left side of the footer status.
111 +
#[derive(Debug)]
112 +
pub(super) enum StatusContext {
113 +
    /// Selected commit identity and summary.
114 +
    Commit {
115 +
        /// Abbreviated commit hash.
116 +
        short: String,
117 +
        /// First line of the commit message.
118 +
        summary: String,
119 +
    },
120 +
    /// Reviewed revision range.
121 +
    Range(String),
122 +
}
123 +
124 +
/// Footer status describing the current review context and progress.
109 125
#[derive(Debug)]
110 126
pub(super) struct Status {
111 127
    /// Active review mode name.
112 128
    pub(super) mode: &'static str,
113 -
    /// Abbreviated current commit hash.
114 -
    pub(super) short: String,
115 -
    /// First line of the current commit message.
116 -
    pub(super) summary: String,
117 -
    /// Accepted-hunk progress for the current commit.
129 +
    /// Review context displayed for the active mode.
130 +
    pub(super) context: StatusContext,
131 +
    /// Accepted-hunk progress for the active review context.
118 132
    pub(super) progress: ReviewProgress,
119 -
    /// Aggregated diff size for the current commit.
133 +
    /// Aggregated diff size for the active review context.
120 134
    pub(super) stats: DiffStat,
121 135
    /// Diff palette used for stat and review colors.
122 136
    pub(super) palette: DiffPalette,
123 137
    /// Session-wide accepted-hunk visibility.
124 138
    pub(super) visibility: Visibility,
165 179
            .spacer()
166 180
            .child(right)
167 181
            .child(Line::new(Label::space().bg(FOOTER_BG)).padded(STATUS_RIGHT_PADDING))
168 182
    }
169 183
170 -
    /// Returns the left status section with application, mode, summary, and hash.
184 +
    /// Returns the left status section with application, mode, and review context.
171 185
    fn left_status(&self) -> Line {
186 +
        let context = match &self.context {
187 +
            StatusContext::Commit { short, summary } => Line::blank()
188 +
                .item(Label::new(short).fg(FOOTER_HASH_FG))
189 +
                .item(Label::space())
190 +
                .item(Label::new(summary).fg(FOOTER_SUMMARY_FG)),
191 +
            StatusContext::Range(range) => Line::new(Label::new(range).fg(FOOTER_SUMMARY_FG)),
192 +
        };
172 193
        Line::blank()
173 194
            .item(
174 195
                Label::new(" brain ")
175 196
                    .fg(Color::White)
176 197
                    .bg(BRAIN_BADGE_BG)
181 202
                    .fg(Color::White)
182 203
                    .bg(MODE_BADGE_BG)
183 204
                    .style(Style::default().bold()),
184 205
            )
185 206
            .item(Label::space())
186 -
            .item(Label::new(&self.short).fg(FOOTER_HASH_FG))
187 -
            .item(Label::space())
188 -
            .item(Label::new(&self.summary).fg(FOOTER_SUMMARY_FG))
207 +
            .extend(context)
189 208
            .style(Style::default().bg(FOOTER_BG))
190 209
    }
191 210
192 211
    /// Returns the right status section with review state and diff statistics.
193 212
    fn right_status(&self) -> Line {
199 218
        let full_file_fg = if self.visibility.full_file {
200 219
            FULL_FILE_MODE_FG
201 220
        } else {
202 221
            FOOTER_FG
203 222
        };
204 -
        let files = self.stats.files_changed;
205 -
        let plural = if files == 1 { "" } else { "s" };
223 +
        let files = file_count(self.stats.files_changed);
206 224
207 225
        Line::blank()
208 226
            .extend(progress_bar(self.progress, self.palette, FOOTER_FG))
209 227
            .item(Label::space())
210 228
            .item(Label::new(&format!("+{}", self.stats.insertions)).fg(self.palette.positive_fg))
211 229
            .item(Label::space())
212 230
            .item(Label::new(&format!("-{}", self.stats.deletions)).fg(self.palette.negative_fg))
213 231
            .item(Label::new(FOOTER_SEPARATOR).fg(FOOTER_FG))
214 -
            .item(Label::new(&format!("{files} file{plural}")).fg(FOOTER_VALUE_FG))
232 +
            .item(Label::new(&files).fg(FOOTER_VALUE_FG))
215 233
            .item(Label::new(FOOTER_SEPARATOR).fg(FOOTER_FG))
216 234
            .item(Label::new(APPROVED_HUNKS_MODE_ICON).fg(accepted_fg))
217 235
            .item(Label::space())
218 236
            .item(Label::new(FULL_FILE_MODE_ICON).fg(full_file_fg))
219 237
            .style(Style::default().bg(FOOTER_BG))
246 264
}
247 265
248 266
/// Bottom chrome containing the status bar and contextual action bar.
249 267
#[derive(Debug)]
250 268
pub(super) struct Chrome {
251 -
    /// Current commit status.
269 +
    /// Footer status for the active review context.
252 270
    pub(super) status: Status,
253 271
    /// Active action context.
254 272
    pub(super) actions: ActionContext,
255 273
}
256 274
302 320
            self.action_line(action_area.cols).render(action_area, buf);
303 321
        }
304 322
    }
305 323
}
306 324
325 +
/// Formats a changed-file count with the correct singular or plural noun.
326 +
fn file_count(files: usize) -> String {
327 +
    let plural = if files == 1 { "" } else { "s" };
328 +
    format!("{files} file{plural}")
329 +
}
330 +
307 331
/// Returns a compact commit review progress bar.
308 332
///
309 333
/// The empty segment renders in `empty_fg`, chosen by the caller to fit its
310 334
/// background.
311 335
pub(crate) fn progress_bar(
324 348
/// Returns the viewer area above the footer chrome.
325 349
pub(super) fn viewer_area(area: Rect) -> Rect {
326 350
    Chrome::areas(area).0
327 351
}
328 352
329 -
/// Renders one commit-list row: hash, summary, and diff statistics.
330 -
pub(super) fn commit_row(slot: &CommitSlot, palette: DiffPalette) -> Line {
353 +
/// Returns one commit-table row with its graph lane, metadata, statistics, and progress.
354 +
pub(super) fn commit_row(slot: &CommitSlot, palette: DiffPalette, graph: &str) -> [Line; 8] {
331 355
    let stats = slot.commit.stats;
332 356
    let short = slot.commit.id.short();
333 -
    let status = if slot.reviewed {
357 +
    let status = if slot.progress.is_complete() {
334 358
        Label::from_char(REVIEWED_MARK).fg(palette.positive_fg)
335 359
    } else {
336 360
        Label::space()
337 361
    };
338 -
    Line::spaced([
339 -
        status,
340 -
        Label::new(&short).fg(Color::Yellow),
341 -
        Label::new(&slot.commit.summary),
342 -
        Label::new(&format!("+{}", stats.insertions)).fg(Color::Green),
343 -
        Label::new(&format!("-{}", stats.deletions)).fg(Color::Red),
344 -
        Label::new(&format!("{} files", stats.files_changed)).fg(FOOTER_FG),
345 -
    ])
362 +
    [
363 +
        Line::new(Label::new(graph).fg(colors::fixed::MUTED)),
364 +
        Line::new(Label::new(&short).fg(colors::rgb::ORANGE)),
365 +
        Line::new(slot.commit.summary.as_str()),
366 +
        Line::new(Label::new(&format!("+{}", stats.insertions)).fg(palette.positive_fg)),
367 +
        Line::new(Label::new(&format!("-{}", stats.deletions)).fg(palette.negative_fg)),
368 +
        Line::new(Label::new(&file_count(stats.files_changed)).fg(FOOTER_FG)),
369 +
        Line::new(status),
370 +
        progress_bar(slot.progress, palette, FOOTER_FG),
371 +
    ]
346 372
}
347 373
348 374
/// Renders one stored comment as a bordered card.
349 375
pub(super) fn comment_card_lines(comment: &Comment, selected: bool, cols: usize) -> Vec<Line> {
350 376
    let border = if selected {
478 504
    #[test]
479 505
    fn status_renders_recoverable_error() {
480 506
        let palette = DiffPalette::default();
481 507
        let mut status = Status {
482 508
            mode: "commit",
483 -
            short: "1234567".to_owned(),
484 -
            summary: "summary".to_owned(),
509 +
            context: StatusContext::Commit {
510 +
                short: "1234567".to_owned(),
511 +
                summary: "summary".to_owned(),
512 +
            },
485 513
            progress: ReviewProgress::default(),
486 514
            stats: DiffStat::default(),
487 515
            palette,
488 516
            visibility: Visibility::default(),
489 517
            error: Some("patch does not apply".to_owned()),
505 533
506 534
    #[test]
507 535
    fn status_renders_right_padding() {
508 536
        let mut status = Status {
509 537
            mode: "commit",
510 -
            short: "1234567".to_owned(),
511 -
            summary: "summary".to_owned(),
538 +
            context: StatusContext::Commit {
539 +
                short: "1234567".to_owned(),
540 +
                summary: "summary".to_owned(),
541 +
            },
512 542
            progress: ReviewProgress::default(),
513 543
            stats: DiffStat::default(),
514 544
            palette: DiffPalette::default(),
515 545
            visibility: Visibility::default(),
516 546
            error: None,
crates/diff/src/viewer.rs +8 -3
48 48
/// Width of the review-state gutter before the line numbers.
49 49
const REVIEW_GUTTER_WIDTH: usize = 1;
50 50
/// Foreground color used by old and new line number cells.
51 51
const LINE_NUMBER_FG: Color = colors::fixed::DIM;
52 52
/// Foreground color used by line number cells in the focused hunk.
53 -
const SELECTED_LINE_NUMBER_FG: Color = Color::Fixed(242);
53 +
const SELECTED_LINE_NUMBER_FG: Color = colors::fixed::MUTED;
54 54
/// Width of the hunk marker cell.
55 55
const MARKER_WIDTH: usize = 3;
56 56
/// Scrollbar track glyph (distinct from box-drawing borders so the column reads as a track).
57 57
const SCROLLBAR_TRACK: char = '🮘';
58 58
/// Scrollbar thumb glyph.
1411 1411
        for request in requests {
1412 1412
            self.pending_highlights.remove(&request.key);
1413 1413
        }
1414 1414
    }
1415 1415
1416 +
    /// Makes every pending highlight request eligible to be queued again.
1417 +
    pub fn retry_pending_highlights(&mut self) {
1418 +
        self.pending_highlights.clear();
1419 +
    }
1420 +
1416 1421
    /// Returns the highlight-cache key for one diff row.
1417 1422
    fn key_for(&self, meta: &DiffLineMeta) -> HighlightKey {
1418 1423
        HighlightKey::new(HighlightKeyInput {
1419 1424
            file: meta.file,
1420 1425
            side: meta.side,
2309 2314
        Line::truncate(&mut line, left, "…");
2310 2315
        Line::pad(&mut line, left);
2311 2316
        line.extend(corner.clone())
2312 2317
    }
2313 2318
2314 -
    /// Returns the diff scrollbar style.
2315 -
    fn scrollbar_style() -> ScrollbarStyle {
2319 +
    /// Returns the scrollbar style used by diff views.
2320 +
    pub fn scrollbar_style() -> ScrollbarStyle {
2316 2321
        ScrollbarStyle::new(
2317 2322
            Cell::new(SCROLLBAR_TRACK, Style::default().fg(colors::FAINT)),
2318 2323
            Cell::new(SCROLLBAR_THUMB, Style::default().fg(colors::FAINT)),
2319 2324
        )
2320 2325
    }
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
crates/diff/tests/golden/sticky_header_before_next_file_64x5.txt +0 -0
src/a.rs +0 -0
src/b.rs +0 -0
README.md +0 -0
src/app/a.rs +0 -0
src/lib/b.rs +0 -0
README.md +0 -0
a.rs +0 -0
b.rs +0 -0
assets/css/style.css +0 -0
assets/css/style.css +0 -0
first.rs +0 -0
second.rs +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
a.rs\n", +0 -0
a\n\ +0 -0
crates/tui-core/src/colors.rs +5 -3
75 75
76 76
/// "Fixed" ANSI colors, supported by most terminals.
77 77
pub mod fixed {
78 78
    use super::Color;
79 79
80 -
    /// The faintest color; useful for borders and such.
81 -
    pub const FAINT: Color = Color::Fixed(236);
82 -
    /// Slightly brighter than faint.
80 +
    /// Muted neutral foreground color.
81 +
    pub const MUTED: Color = Color::Fixed(242);
82 +
    /// Dim neutral foreground color.
83 83
    pub const DIM: Color = Color::Fixed(239);
84 +
    /// Faint neutral foreground color.
85 +
    pub const FAINT: Color = Color::Fixed(236);
84 86
85 87
    /// Get a color using the color name.
86 88
    pub fn theme(name: &'static str) -> Option<Color> {
87 89
        match name {
88 90
            "negative" | "red" => Some(Color::Red),