brain: Stabilize review progress interactions

a3c96b07dd1b6527ab540413e94a118c613e0967
Preserve comments and accepted hunks across rewritten commits using
range-diff correspondence. Keep navigation responsive during
asynchronous persistence and queue one semantic mutation instead of
dropping input. Include comment progress in commit history.

Assisted-by: Codex:gpt-5.6-sol
Alexis Sellier committed ago 1 parent b44c36f1
crates/brain/src/backend.rs +76 -12
24 24
        refs::{Component, Qualified, RefString},
25 25
    },
26 26
    jj,
27 27
};
28 28
29 +
use crate::comments::ReviewComments;
29 30
use crate::error::Error;
30 31
31 32
/// Directory marking a Jujutsu workspace.
32 33
const JJ_DIR: &str = ".jj";
33 34
/// Number of hexadecimal digits shown for a review target in a state commit summary.
129 130
    /// the identical change are indistinguishable here, so the earlier passes
130 131
    /// exist to claim the unambiguous matches first.
131 132
    fn remap<'a>(
132 133
        stored: &Accepted,
133 134
        current: impl IntoIterator<Item = &'a AcceptedHunk>,
135 +
        commits: &BTreeMap<Oid, Oid>,
134 136
    ) -> Accepted {
137 +
        let stored = stored
138 +
            .iter()
139 +
            .cloned()
140 +
            .map(|mut identity| {
141 +
                if let Some(commit) = commits.get(&identity.commit) {
142 +
                    identity.commit = *commit;
143 +
                }
144 +
                identity
145 +
            })
146 +
            .collect::<Accepted>();
135 147
        let current = current.into_iter().cloned().collect::<Vec<_>>();
136 148
        let live = current.iter().collect::<BTreeSet<_>>();
137 149
        let mut accepted = Accepted::new();
138 150
        let mut remaining = Vec::new();
139 -
        for identity in stored {
151 +
        for identity in &stored {
140 152
            if live.contains(identity) {
141 153
                accepted.insert(identity.clone());
142 154
            } else {
143 155
                remaining.push(identity.clone());
144 156
            }
1242 1254
        commits: &[Commit],
1243 1255
        documents: &[DiffDocument],
1244 1256
    ) -> Result<Self, Error> {
1245 1257
        let state_ref = Brain::ref_for_identity(STATE_REF_NAMESPACE, identity)?;
1246 1258
        let comments_ref = Brain::ref_for_identity(COMMENTS_REF_NAMESPACE, identity)?;
1247 -
        let stored = match repository.optional_ref(&state_ref)? {
1259 +
        let (stored, old_base) = match repository.optional_ref(&state_ref)? {
1248 1260
            Some(existing) => {
1249 1261
                let parent = repository.parent(existing)?;
1250 1262
                let message = repository.commit_message(existing)?;
1251 1263
                let persisted = decode_state(&message).ok_or(Error::InvalidReviewState)?;
1252 1264
                if parent == base && persisted.target == target {
1257 1269
                        base,
1258 1270
                        existing,
1259 1271
                        persisted,
1260 1272
                    ));
1261 1273
                }
1262 -
                persisted
1274 +
                (persisted, parent)
1263 1275
            }
1264 -
            None => PersistedState::empty(target),
1276 +
            None => (PersistedState::empty(target), base),
1265 1277
        };
1278 +
        let commit_map = repository.range_diff(old_base, stored.target, base, target)?;
1266 1279
        let commit = Brain::fresh_state_commit(&repository, base, target)?;
1267 1280
        repository.update_ref(&state_ref, commit)?;
1268 1281
        let mut brain = Self::new(
1269 1282
            repository,
1270 1283
            state_ref,
1277 1290
            commits,
1278 1291
            documents,
1279 1292
            &stored.accepted,
1280 1293
            &stored.rejected,
1281 1294
            &stored.dropped,
1295 +
            &commit_map,
1282 1296
        )?;
1297 +
        if let Some(text) = brain.read_comments()? {
1298 +
            let mut comments = ReviewComments::parse(&text)?;
1299 +
            comments.remap_commits(&commit_map);
1300 +
            brain.write_comments(&comments.encode())?;
1301 +
        }
1283 1302
1284 1303
        Ok(brain)
1285 1304
    }
1286 1305
1287 1306
    /// Creates an empty accepted-state commit for one resolved review range.
1505 1524
            }
1506 1525
        }
1507 1526
        Ok((rejected, dropped))
1508 1527
    }
1509 1528
1510 -
    /// Remaps accepted identities and exact rejected commits onto a moved range.
1529 +
    /// Remaps accepted and commit-level decisions onto a moved range.
1511 1530
    fn remap(
1512 1531
        &mut self,
1513 1532
        commits: &[Commit],
1514 1533
        documents: &[DiffDocument],
1515 1534
        stored: &Accepted,
1516 1535
        stored_rejected: &Rejected,
1517 1536
        stored_dropped: &Dropped,
1537 +
        commit_map: &BTreeMap<Oid, Oid>,
1518 1538
    ) -> Result<(), Error> {
1519 1539
        debug_assert_eq!(commits.len(), documents.len(), "one document per commit");
1520 1540
1521 1541
        // Hunks of the moved range in range order, grouped by file so the
1522 1542
        // projection can apply a whole file at once.
1534 1554
        }
1535 1555
1536 1556
        let identities = current
1537 1557
            .iter()
1538 1558
            .flat_map(|(_, hunks)| hunks.iter().map(|(identity, _)| identity));
1539 -
        let accepted = AcceptedHunk::remap(stored, identities);
1559 +
        let accepted = AcceptedHunk::remap(stored, identities, commit_map);
1540 1560
1541 1561
        let mut tree = self.repository.tree_id(self.base)?;
1542 1562
        for (file, hunks) in current {
1543 1563
            let hunks = hunks
1544 1564
                .into_iter()
1955 1975
        assert_eq!(rebased.read_comments().unwrap().as_deref(), Some(comments));
1956 1976
1957 1977
        let reset = backend.reset_brain().unwrap();
1958 1978
        assert_eq!(reset.read_comments().unwrap(), None);
1959 1979
    }
1980 +
    #[test]
1981 +
    fn rebase_remaps_persisted_comment_commit() {
1982 +
        let repository = TestRepository::new();
1983 +
        fs::write(repository.path.join("reviewed"), "base\n").unwrap();
1984 +
        repository.git(&["add", "reviewed"]);
1985 +
        repository.git(&["commit", "-q", "-m", "base"]);
1986 +
        repository.git(&["switch", "-q", "-c", "topic"]);
1987 +
        fs::write(repository.path.join("reviewed"), "base\nchange\n").unwrap();
1988 +
        repository.git(&["commit", "-q", "-am", "change"]);
1989 +
        let base = Rev::try_from("main").unwrap();
1990 +
        let target = Rev::try_from("topic").unwrap();
1991 +
        let backend = GitBackend::new(repository.path(), base, target).unwrap();
1992 +
        let old_target = backend
1993 +
            .repository
1994 +
            .commit_id(&backend.review.target)
1995 +
            .unwrap();
1996 +
        let brain = backend.reset_brain().unwrap();
1997 +
        brain
1998 +
            .write_comments(&format!(
1999 +
                r#"{{"commit":"{old_target}","id":1,"author":"A","timestamp":1,"heading":"change","path":"reviewed","patch_id":"p","ordinal":0,"body":"retained"}}"#
2000 +
            ))
2001 +
            .unwrap();
2002 +
        repository.git(&["switch", "-q", "main"]);
2003 +
        fs::write(repository.path.join("upstream"), "upstream\n").unwrap();
2004 +
        repository.git(&["add", "upstream"]);
2005 +
        repository.git(&["commit", "-q", "-m", "upstream"]);
2006 +
        repository.git(&["switch", "-q", "topic"]);
2007 +
        repository.git(&["rebase", "main"]);
2008 +
        let new_target = backend
2009 +
            .repository
2010 +
            .commit_id(&backend.review.target)
2011 +
            .unwrap();
2012 +
2013 +
        let rebased = backend.rebase_brain().unwrap();
2014 +
        let comments = rebased.read_comments().unwrap().unwrap();
2015 +
2016 +
        assert!(comments.contains(&new_target.to_string()));
2017 +
        assert!(!comments.contains(&old_target.to_string()));
2018 +
    }
1960 2019
1961 2020
    #[test]
1962 2021
    fn reset_ref_update_is_atomic_when_comment_ref_is_locked() {
1963 2022
        let repository = TestRepository::new();
1964 2023
        repository.git(&["commit", "-q", "--allow-empty", "-m", "base"]);
2587 2646
        let elsewhere = accepted_hunk("3333333333333333333333333333333333333333", "same", 0, 1);
2588 2647
        let same_commit = AcceptedHunk {
2589 2648
            commit_lines: 2,
2590 2649
            ..kept
2591 2650
        };
2592 -
        let current = [elsewhere, same_commit.clone()];
2651 +
        let current = [elsewhere.clone(), same_commit.clone()];
2593 2652
2594 -
        let remapped = AcceptedHunk::remap(&stored, &current);
2653 +
        let remapped = AcceptedHunk::remap(&stored, &current, &BTreeMap::new());
2595 2654
2596 -
        assert_eq!(remapped, Accepted::from([same_commit]));
2655 +
        assert_eq!(remapped, Accepted::from([same_commit.clone()]));
2597 2656
        // With no same-commit candidate, the patch id alone carries acceptance.
2598 -
        let remapped = AcceptedHunk::remap(&stored, [&moved]);
2599 -
        assert_eq!(remapped, Accepted::from([moved]));
2657 +
        let remapped = AcceptedHunk::remap(&stored, [&moved], &BTreeMap::new());
2658 +
        assert_eq!(remapped, Accepted::from([moved.clone()]));
2659 +
2660 +
        let rewritten = accepted_hunk("4444444444444444444444444444444444444444", "same", 0, 1);
2661 +
        let commits = BTreeMap::from([(same_commit.commit, rewritten.commit)]);
2662 +
        let remapped = AcceptedHunk::remap(&stored, [&elsewhere, &rewritten], &commits);
2663 +
        assert_eq!(remapped, Accepted::from([rewritten]));
2600 2664
    }
2601 2665
2602 2666
    #[test]
2603 2667
    fn rebase_remaps_duplicate_patch_ids_by_occurrence() {
2604 2668
        let stored = Accepted::from([
2608 2672
        let first = accepted_hunk("2222222222222222222222222222222222222222", "same", 0, 3);
2609 2673
        let second = accepted_hunk("2222222222222222222222222222222222222222", "same", 1, 3);
2610 2674
        let third = accepted_hunk("2222222222222222222222222222222222222222", "same", 2, 3);
2611 2675
        let current = [first.clone(), second.clone(), third];
2612 2676
2613 -
        let remapped = AcceptedHunk::remap(&stored, &current);
2677 +
        let remapped = AcceptedHunk::remap(&stored, &current, &BTreeMap::new());
2614 2678
2615 2679
        assert_eq!(remapped, Accepted::from([first, second]));
2616 2680
    }
2617 2681
2618 2682
    #[test]
f +0 -0
new.rs +0 -0
image.png +0 -0
new.txt +0 -0
crates/brain/src/comments.rs +113 -5
11 11
use std::io;
12 12
use std::path::PathBuf;
13 13
use std::time::{SystemTime, UNIX_EPOCH};
14 14
15 15
use rustik_diff::HunkId;
16 -
use rustik_repo::PatchId;
16 +
use rustik_repo::{Oid, PatchId};
17 17
use serde::de::{Deserialize as DeserializeTrait, Scalar, Visitor};
18 18
use serde::ser::{Fragment, Serialize as SerializeTrait};
19 19
use serde::{Deserialize, Error, Result, Serialize, json};
20 +
/// Marker drawn beside comment counts: ๐Ÿ—ฉ.
21 +
pub(crate) const COMMENT_MARK: char = '๐Ÿ—ฉ';
20 22
21 23
/// A single review comment authored on a hunk.
22 24
#[derive(Clone, Debug, Eq, PartialEq)]
23 25
pub struct Comment {
24 26
    /// Stable local comment id.
83 85
}
84 86
85 87
/// Target metadata for one commentable hunk.
86 88
#[derive(Clone, Debug, Eq, PartialEq)]
87 89
pub struct CommentTarget {
90 +
    /// Commit containing the reviewed hunk.
91 +
    pub commit: Oid,
88 92
    /// Heading identifying the reviewed item.
89 93
    pub heading: String,
90 94
    /// Optional file path associated with the hunk.
91 95
    pub path: Option<PathBuf>,
92 96
    /// Stable patch id of the hunk the comment is attached to.
105 109
}
106 110
107 111
/// One persisted comment row.
108 112
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
109 113
struct CommentRecord {
114 +
    /// Commit containing the hunk, when recorded by a commit-aware version.
115 +
    commit: Option<Oid>,
110 116
    /// Stable local comment id.
111 117
    id: CommentId,
112 118
    /// Author shown for this comment.
113 119
    author: String,
114 120
    /// Unix timestamp when the comment was authored.
213 219
    /// Returns the number of stored comment rows.
214 220
    pub fn len(&self) -> usize {
215 221
        self.records.len()
216 222
    }
217 223
218 -
    /// Returns comments attached to `target`'s patch occurrence, in storage order.
224 +
    /// Returns the number of comments attached to one patch occurrence.
225 +
    pub fn matching_count(&self, commit: Oid, patch_id: &PatchId, ordinal: u32) -> usize {
226 +
        self.records
227 +
            .iter()
228 +
            .filter(|record| {
229 +
                record.patch_id == *patch_id
230 +
                    && record.ordinal == ordinal
231 +
                    && record.commit.is_none_or(|stored| stored == commit)
232 +
            })
233 +
            .count()
234 +
    }
235 +
236 +
    /// Returns comments attached exactly to `target`, in storage order.
219 237
    fn matching(&self, target: &CommentTarget) -> Vec<Comment> {
220 238
        self.records
221 239
            .iter()
222 -
            .filter(|record| record.patch_id == target.patch_id && record.ordinal == target.ordinal)
240 +
            .filter(|record| {
241 +
                record.patch_id == target.patch_id
242 +
                    && record.ordinal == target.ordinal
243 +
                    && record.commit.is_none_or(|commit| commit == target.commit)
244 +
            })
223 245
            .map(Comment::from)
224 246
            .collect()
225 247
    }
226 248
249 +
    /// Rewrites persisted commit anchors using range-diff correspondence.
250 +
    ///
251 +
    /// Older rows recover their commit from the abbreviated object id at the
252 +
    /// start of the persisted heading when it identifies exactly one pair.
253 +
    pub fn remap_commits(&mut self, commits: &BTreeMap<Oid, Oid>) {
254 +
        for record in &mut self.records {
255 +
            if let Some(commit) = record.commit {
256 +
                if let Some(mapped) = commits.get(&commit) {
257 +
                    record.commit = Some(*mapped);
258 +
                }
259 +
                continue;
260 +
            }
261 +
            let Some(prefix) = record.heading.split_whitespace().next() else {
262 +
                continue;
263 +
            };
264 +
            let mut matches = commits
265 +
                .iter()
266 +
                .filter(|(old, _)| old.to_string().starts_with(prefix));
267 +
            let Some((_, mapped)) = matches.next() else {
268 +
                continue;
269 +
            };
270 +
            if matches.next().is_none() {
271 +
                record.commit = Some(*mapped);
272 +
            }
273 +
        }
274 +
    }
275 +
227 276
    /// Adds one comment row for `target` and returns its view.
228 277
    fn add(&mut self, target: &CommentTarget, body: String) -> Comment {
229 278
        let timestamp = SystemTime::now()
230 279
            .duration_since(UNIX_EPOCH)
231 280
            .unwrap_or_default()
233 282
        let record = CommentRecord {
234 283
            id: self.next_id(),
235 284
            author: self.author.clone(),
236 285
            timestamp,
237 286
            heading: target.heading.clone(),
287 +
            commit: Some(target.commit),
238 288
            path: target.path.clone(),
239 289
            patch_id: target.patch_id.clone(),
240 290
            ordinal: target.ordinal,
241 291
            body,
242 292
        };
289 339
}
290 340
291 341
impl Comments {
292 342
    /// Creates a comment view for a commit's hunk targets.
293 343
    pub fn new(store: &ReviewComments, targets: BTreeMap<HunkId, CommentTarget>) -> Self {
294 -
        let by_hunk = targets
344 +
        let mut by_hunk = targets
295 345
            .iter()
296 346
            .filter_map(|(hunk, target)| {
297 347
                let comments = store.matching(target);
298 348
                (!comments.is_empty()).then_some((*hunk, comments))
299 349
            })
300 -
            .collect();
350 +
            .collect::<BTreeMap<_, _>>();
351 +
        for record in &store.records {
352 +
            let Some(commit) = record.commit else {
353 +
                continue;
354 +
            };
355 +
            let exact = targets.values().any(|target| {
356 +
                target.commit == commit
357 +
                    && target.patch_id == record.patch_id
358 +
                    && target.ordinal == record.ordinal
359 +
            });
360 +
            if exact {
361 +
                continue;
362 +
            }
363 +
            let mut candidates = targets
364 +
                .iter()
365 +
                .filter(|(_, target)| target.commit == commit && target.path == record.path);
366 +
            let Some((hunk, _)) = candidates.next() else {
367 +
                continue;
368 +
            };
369 +
            if candidates.next().is_none() {
370 +
                by_hunk
371 +
                    .entry(*hunk)
372 +
                    .or_default()
373 +
                    .push(Comment::from(record));
374 +
            }
375 +
        }
301 376
302 377
        Self { by_hunk, targets }
303 378
    }
304 379
305 380
    /// Applies one comment mutation and returns the encoded updated store.
375 450
    /// Returns the comments authored on `hunk`.
376 451
    pub fn for_hunk(&self, hunk: HunkId) -> &[Comment] {
377 452
        self.by_hunk.get(&hunk).map_or(&[], Vec::as_slice)
378 453
    }
379 454
455 +
    /// Returns the total number of comments in this commit view.
456 +
    pub fn len(&self) -> usize {
457 +
        self.by_hunk.values().map(Vec::len).sum()
458 +
    }
459 +
380 460
    /// Returns per-hunk comment counts, for decoration snapshots.
381 461
    pub fn counts(&self) -> BTreeMap<HunkId, usize> {
382 462
        self.by_hunk
383 463
            .iter()
384 464
            .map(|(hunk, comments)| (*hunk, comments.len()))
463 543
    const OTHER_HUNK: HunkId = HunkId::new(1);
464 544
465 545
    /// Builds an empty comment store and matching hunk view.
466 546
    fn empty_comments() -> (ReviewComments, Comments) {
467 547
        let target = CommentTarget {
548 +
            commit: "1111111111111111111111111111111111111111".parse().unwrap(),
468 549
            heading: "h".to_owned(),
469 550
            path: None,
470 551
            patch_id: PatchId::from("p".to_owned()),
471 552
            ordinal: 0,
472 553
        };
538 619
    }
539 620
540 621
    #[test]
541 622
    fn identical_patch_occurrences_keep_comments_separate() {
542 623
        let first = CommentTarget {
624 +
            commit: "1111111111111111111111111111111111111111".parse().unwrap(),
543 625
            heading: "h".to_owned(),
544 626
            path: Some(PathBuf::from("file")),
545 627
            patch_id: PatchId::from("same".to_owned()),
546 628
            ordinal: 0,
547 629
        };
572 654
573 655
        let reopened = Comments::new(&store, targets);
574 656
        assert!(reopened.for_hunk(HUNK).is_empty());
575 657
        assert_eq!(reopened.for_hunk(OTHER_HUNK)[0].body, "edited second");
576 658
    }
659 +
660 +
    #[test]
661 +
    fn range_diff_commit_match_recovers_unique_changed_hunk() {
662 +
        let old_commit: Oid = "1111111111111111111111111111111111111111".parse().unwrap();
663 +
        let new_commit: Oid = "2222222222222222222222222222222222222222".parse().unwrap();
664 +
        let mut store = ReviewComments::parse(
665 +
            r#"{"id":1,"author":"A","timestamp":1,"heading":"1111111 old","path":"file","patch_id":"old","ordinal":0,"body":"retained"}"#,
666 +
        )
667 +
        .unwrap();
668 +
        store.remap_commits(&BTreeMap::from([(old_commit, new_commit)]));
669 +
        let targets = BTreeMap::from([(
670 +
            HUNK,
671 +
            CommentTarget {
672 +
                commit: new_commit,
673 +
                heading: "new".to_owned(),
674 +
                path: Some(PathBuf::from("file")),
675 +
                patch_id: PatchId::from("changed".to_owned()),
676 +
                ordinal: 0,
677 +
            },
678 +
        )]);
679 +
680 +
        let comments = Comments::new(&store, targets);
681 +
682 +
        assert_eq!(comments.for_hunk(HUNK)[0].body, "retained");
683 +
        assert!(store.encode().contains(&new_commit.to_string()));
684 +
    }
577 685
}
crates/brain/src/decorate.rs +1 -3
15 15
    ReviewProgress,
16 16
};
17 17
use rustik_tui as tui;
18 18
use tui::{Label, Line, Paint, Style, colors};
19 19
20 -
use crate::comments::Comments;
20 +
use crate::comments::{COMMENT_MARK, Comments};
21 21
use crate::review::Review;
22 22
23 23
/// Check mark drawn beside accepted hunks and fully accepted files: โœ”.
24 24
const ACCEPTED_MARK: char = 'โœ”';
25 25
/// Vertical rule drawn in the gutter beside accepted hunks: โ–.
26 26
const ACCEPTED_GUTTER: char = 'โ–';
27 -
/// Marker drawn beside a hunk that has comments: ๐Ÿ—ฉ.
28 -
const COMMENT_MARK: char = '๐Ÿ—ฉ';
29 27
30 28
/// Immutable decoration snapshot of one commit's review state.
31 29
#[derive(Clone, Debug)]
32 30
pub struct Decorations {
33 31
    /// Hunks accepted at snapshot time.
crates/brain/src/main.rs +9 -2
520 520
    let brain = backend.brain()?;
521 521
    let commits = backend.commits()?;
522 522
    if commits.is_empty() {
523 523
        return Err(Error::Empty);
524 524
    }
525 +
    let comments = ReviewComments::parse(brain.read_comments()?.as_deref().unwrap_or_default())?;
525 526
    let width = status_width();
526 -
    let table =
527 -
        session::history_output_table(commits, &*backend, &brain, DiffPalette::default(), width)?;
527 +
    let table = session::history_output_table(
528 +
        commits,
529 +
        &*backend,
530 +
        &brain,
531 +
        &comments,
532 +
        DiffPalette::default(),
533 +
        width,
534 +
    )?;
528 535
    let mut stdout = io::stdout().lock();
529 536
    for line in table.lines(Constraint::tight(width)) {
530 537
        writeln!(stdout, "{}", line.styled())?;
531 538
    }
532 539
    Ok(())
crates/brain/src/session.rs +224 -15
81 81
            FileVisibility::Full
82 82
        } else {
83 83
            FileVisibility::Context
84 84
        }
85 85
    }
86 +
87 +
    /// Returns the focus-independent mutation represented by `event`.
88 +
    fn deferred_mutation(&self, event: &Event<()>) -> Option<DeferredMutation> {
89 +
        match (self, event) {
90 +
            (Self::Commits | Self::Diff, Event::Key(Key::Char('a'))) => {
91 +
                Some(DeferredMutation::ToggleAcceptance)
92 +
            }
93 +
            (Self::Diff, Event::Key(Key::Char('A'))) => {
94 +
                Some(DeferredMutation::ToggleFileAcceptance)
95 +
            }
96 +
            (Self::Diff, Event::Key(Key::Char('u'))) => Some(DeferredMutation::UndoAcceptance),
97 +
            (Self::Commits, Event::Key(Key::Char('r'))) => Some(DeferredMutation::ToggleRejection),
98 +
            (Self::Commits, Event::Key(Key::Char('d'))) => Some(DeferredMutation::ToggleDrop),
99 +
            _ => None,
100 +
        }
101 +
    }
102 +
103 +
    /// Returns whether `event` is read-only navigation in this view.
104 +
    fn allows_navigation_during_persistence(&self, event: &Event<()>) -> bool {
105 +
        match self {
106 +
            Self::Commits => matches!(
107 +
                event,
108 +
                Event::Key(Key::Char('j' | 'k') | Key::Down | Key::Up)
109 +
                    | Event::Mouse(Mouse::Press {
110 +
                        button: MouseButton::WheelDown | MouseButton::WheelUp,
111 +
                        ..
112 +
                    })
113 +
            ),
114 +
            Self::Diff => matches!(
115 +
                event,
116 +
                Event::Key(
117 +
                    Key::Char('j' | 'k' | 'n' | 'p' | 'g' | 'G' | ' ')
118 +
                        | Key::Down
119 +
                        | Key::Up
120 +
                        | Key::PageDown
121 +
                        | Key::PageUp
122 +
                        | Key::Ctrl('d' | 'u')
123 +
                        | Key::Home
124 +
                        | Key::End
125 +
                ) | Event::Mouse(Mouse::Press {
126 +
                    button: MouseButton::WheelDown | MouseButton::WheelUp,
127 +
                    ..
128 +
                })
129 +
            ),
130 +
            Self::Hunk(_) => false,
131 +
        }
132 +
    }
86 133
}
87 134
88 135
/// Terminal event channel shared by pre-session prompts and the session loop.
89 136
///
90 137
/// Reading terminal input consumes it, so one input worker must feed every
150 197
            remaining_stats: commit.stats,
151 198
            commit,
152 199
            progress: ReviewProgress::default(),
153 200
            accepted_hunks: 0,
154 201
            total_hunks: 0,
202 +
            comment_count: 0,
155 203
            state: CommitReviewState::Pending,
156 204
            document: None,
157 205
            identities: None,
158 206
            loaded: None,
159 207
        })
172 220
        commits: slots,
173 221
        range,
174 222
        history_status: None,
175 223
        accepted: Vec::new(),
176 224
        pending: None,
225 +
        deferred_mutation: None,
177 226
        current: 0,
178 227
        hunk_visibility: HunkVisibility::default(),
179 228
        mode,
180 229
        parked: None,
181 230
        list: ListState::new(),
195 244
196 245
    if let Some(commits) = history_commits {
197 246
        session.loading = Some("loading history");
198 247
        session
199 248
            .repository_worker
200 -
            .send(WorkerCommand::LoadHistory { commits })
249 +
            .send(WorkerCommand::LoadHistory {
250 +
                commits,
251 +
                comments: session.comments.clone(),
252 +
            })
201 253
            .map_err(Error::Git)?;
202 254
    } else {
203 255
        session.request_commit(0)?;
204 256
    }
205 257
    session.redraw()?;
249 301
/// Returns the interactive history table for regular terminal output.
250 302
pub(crate) fn history_output_table(
251 303
    commits: Vec<Commit>,
252 304
    backend: &dyn Backend,
253 305
    brain: &Brain,
306 +
    comments: &ReviewComments,
254 307
    palette: rustik_diff::DiffPalette,
255 308
    width: usize,
256 -
) -> Result<Table<8, Line>, Error> {
257 -
    let (mut slots, _) = reviewed_slots(commits, backend, brain)?;
309 +
) -> Result<Table<9, Line>, Error> {
310 +
    let (mut slots, _) = reviewed_slots(commits, backend, brain, comments)?;
258 311
    slots.reverse();
259 312
    Ok(history_table(&slots, palette, width))
260 313
}
261 314
262 315
/// Builds reviewed commit slots and their aggregate history status.
263 316
fn reviewed_slots(
264 317
    commits: Vec<Commit>,
265 318
    backend: &dyn Backend,
266 319
    brain: &Brain,
320 +
    comments: &ReviewComments,
267 321
) -> Result<(Vec<CommitSlot>, HistoryStatus), Error> {
268 322
    let mut reviewed = Vec::with_capacity(commits.len());
269 323
    for commit in commits {
270 324
        let document = backend.diff_document(commit.id)?.split_hunks();
271 325
        let identities = brain.hunk_identities(&document, commit.id)?;
285 339
            let status = history.commits.entry(commit.id).or_default();
286 340
            CommitSlot {
287 341
                progress: status.progress,
288 342
                accepted_hunks: status.accepted_hunks,
289 343
                total_hunks: status.total_hunks,
344 +
                comment_count: identities
345 +
                    .values()
346 +
                    .map(|identity| {
347 +
                        comments.matching_count(
348 +
                            identity.commit,
349 +
                            &identity.patch_id,
350 +
                            identity.ordinal,
351 +
                        )
352 +
                    })
353 +
                    .sum(),
290 354
                state: status.state,
291 355
                remaining_stats: status.stats,
292 356
                commit,
293 357
                document: Some(document),
294 358
                identities: Some(identities),
302 366
/// Builds the commit table shared by interactive and regular history output.
303 367
fn history_table(
304 368
    commits: &[CommitSlot],
305 369
    palette: rustik_diff::DiffPalette,
306 370
    width: usize,
307 -
) -> Table<8, Line> {
371 +
) -> Table<9, Line> {
308 372
    let now = current_timestamp();
309 373
    let largest_change_count = commits
310 374
        .iter()
311 375
        .map(|slot| {
312 376
            let stats = slot.remaining_stats();
314 378
        })
315 379
        .max()
316 380
        .unwrap_or(0);
317 381
    let diffstat_width = (width / HISTORY_DIFFSTAT_WIDTH_DIVISOR)
318 382
        .clamp(HISTORY_DIFFSTAT_MIN_WIDTH, HISTORY_DIFFSTAT_MAX_WIDTH);
319 -
    let mut table = Table::<8, Line>::new(TableOptions {
383 +
    let mut table = Table::<9, Line>::new(TableOptions {
320 384
        spacing: 2,
321 385
        ..TableOptions::default()
322 386
    })
323 387
    .with_layout([
388 +
        Column::auto(),
324 389
        Column::auto(),
325 390
        Column::auto(),
326 391
        Column::flex(1),
327 392
        Column::collapse(2),
328 393
        Column::collapse(3),
329 394
        Column::collapse(1),
330 -
        Column::collapse(4),
331 395
        Column::auto(),
396 +
        Column::collapse(4),
332 397
    ]);
333 398
    for slot in commits {
334 399
        let [state, id, summary] = commit_row(slot, palette);
335 -
        let [author, age, branches, diffstat, hunks] =
400 +
        let [hunks, author, age, branches, comments, diffstat] =
336 401
            commit_row_suffix(slot, palette, now, largest_change_count, diffstat_width);
337 -
        table.push([state, id, summary, author, age, branches, diffstat, hunks]);
402 +
        table.push([
403 +
            state, hunks, id, summary, author, age, branches, comments, diffstat,
404 +
        ]);
338 405
    }
339 406
    table
340 407
}
341 408
342 409
/// Commit-local hunk location used by acceptance and undo state.
380 447
    Decision,
381 448
    /// Comment mutation currently writing to the repository.
382 449
    Comments(CommentRollback),
383 450
}
384 451
452 +
/// Repository mutation waiting for the active persistence command.
453 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
454 +
enum DeferredMutation {
455 +
    /// Toggle acceptance at the current focus.
456 +
    ToggleAcceptance,
457 +
    /// Toggle acceptance of the focused file.
458 +
    ToggleFileAcceptance,
459 +
    /// Undo the latest accepted hunk.
460 +
    UndoAcceptance,
461 +
    /// Toggle rejection of the selected commit.
462 +
    ToggleRejection,
463 +
    /// Toggle dropping of the selected commit.
464 +
    ToggleDrop,
465 +
    /// Delete the selected hunk comment.
466 +
    DeleteComment,
467 +
}
468 +
385 469
/// Interactive terminal session state.
386 470
struct Session<'a, T: TuiBackend<Error = io::Error>> {
387 471
    /// Terminal frame target.
388 472
    terminal: &'a mut Terminal<T>,
389 473
    /// Per-commit review slots, newest first.
394 478
    history_status: Option<HistoryStatus>,
395 479
    /// Hunk acceptances available to undo, in acceptance order.
396 480
    accepted: Vec<HunkLocation>,
397 481
    /// Optimistic state currently writing to the repository.
398 482
    pending: Option<Pending>,
483 +
    /// Semantic repository mutation waiting for active persistence to finish.
484 +
    deferred_mutation: Option<DeferredMutation>,
399 485
    /// Index of the commit currently displayed.
400 486
    current: usize,
401 487
    /// Set of hunks visible across commit viewers.
402 488
    hunk_visibility: HunkVisibility,
403 489
    /// Active view: the commit list, the diff, or a hunk's comment box.
479 565
                    && matches!(event, Event::Key(Key::Ctrl('c')))
480 566
                {
481 567
                    return self.try_quit();
482 568
                }
483 569
                if self.loading.is_some() && !matches!(event, Event::Resize(_)) {
484 -
                    return Ok(Update::Continue);
570 +
                    if self.pending.is_none() {
571 +
                        return Ok(Update::Continue);
572 +
                    }
573 +
                    if let Some(mutation) = self.deferred_mutation(&event) {
574 +
                        self.deferred_mutation.get_or_insert(mutation);
575 +
                        return Ok(Update::Continue);
576 +
                    }
577 +
                    if !self.allows_navigation_during_persistence(&event) {
578 +
                        return Ok(Update::Continue);
579 +
                    }
485 580
                }
486 581
                let resize = if matches!(event, Event::Resize(_)) {
487 582
                    Resize::Changed
488 583
                } else {
489 584
                    Resize::Stable
593 688
                }
594 689
                Err(message) => self.error = Some(message.replace('\n', " ยท ")),
595 690
            },
596 691
            WorkerOutput::Persisted(result) => {
597 692
                self.finish_persistence(*result)?;
693 +
                if let Some(mutation) = self.deferred_mutation.take() {
694 +
                    self.apply_deferred_mutation(mutation)?;
695 +
                }
598 696
            }
599 697
        }
600 698
        Ok(Update::Redraw)
601 699
    }
602 700
701 +
    /// Returns the repository mutation represented by `event` in the active view.
702 +
    fn deferred_mutation(&self, event: &Event<()>) -> Option<DeferredMutation> {
703 +
        if let Some(mutation) = self.mode.deferred_mutation(event) {
704 +
            return Some(mutation);
705 +
        }
706 +
        match (&self.mode, event) {
707 +
            (Mode::Diff, Event::Key(Key::Char('r' | 'd')))
708 +
                if matches!(
709 +
                    self.commits[self.current]
710 +
                        .loaded
711 +
                        .as_ref()
712 +
                        .and_then(|loaded| loaded.viewer.state().focus),
713 +
                    Some(DiffFocus::Commit)
714 +
                ) =>
715 +
            {
716 +
                Some(if matches!(event, Event::Key(Key::Char('r'))) {
717 +
                    DeferredMutation::ToggleRejection
718 +
                } else {
719 +
                    DeferredMutation::ToggleDrop
720 +
                })
721 +
            }
722 +
            (Mode::Hunk(view), Event::Key(Key::Char('r'))) if !view.is_editing() => {
723 +
                Some(DeferredMutation::ToggleRejection)
724 +
            }
725 +
            (Mode::Hunk(view), Event::Key(Key::Char('d'))) if !view.is_editing() => {
726 +
                Some(DeferredMutation::DeleteComment)
727 +
            }
728 +
            _ => None,
729 +
        }
730 +
    }
731 +
732 +
    /// Returns whether `event` is safe while repository persistence is pending.
733 +
    fn allows_navigation_during_persistence(&self, event: &Event<()>) -> bool {
734 +
        if self.mode.allows_navigation_during_persistence(event) {
735 +
            return true;
736 +
        }
737 +
        match &self.mode {
738 +
            Mode::Hunk(view) if !view.is_editing() => {
739 +
                matches!(event, Event::Key(Key::Char('n' | 'p'))) || Self::hunk_scroll_event(event)
740 +
            }
741 +
            Mode::Commits | Mode::Diff | Mode::Hunk(_) => false,
742 +
        }
743 +
    }
744 +
745 +
    /// Applies one queued mutation against the current semantic focus.
746 +
    fn apply_deferred_mutation(&mut self, mutation: DeferredMutation) -> Result<(), Error> {
747 +
        match mutation {
748 +
            DeferredMutation::ToggleAcceptance => match self.mode {
749 +
                Mode::Commits => self.toggle_commit_accepted(self.list.selected())?,
750 +
                Mode::Diff => {
751 +
                    let area = viewer_area(self.terminal.area());
752 +
                    match self.current()?.viewer.state().focus {
753 +
                        Some(DiffFocus::Commit) => self.toggle_commit_accepted(self.current)?,
754 +
                        Some(DiffFocus::File(_)) => self.toggle_focused_file(area)?,
755 +
                        Some(DiffFocus::Hunk(_)) | None => self.toggle_focused_hunk(area)?,
756 +
                    }
757 +
                }
758 +
                Mode::Hunk(_) => {}
759 +
            },
760 +
            DeferredMutation::ToggleFileAcceptance => {
761 +
                if matches!(self.mode, Mode::Diff) {
762 +
                    let area = viewer_area(self.terminal.area());
763 +
                    self.toggle_focused_file(area)?;
764 +
                }
765 +
            }
766 +
            DeferredMutation::UndoAcceptance => {
767 +
                if matches!(self.mode, Mode::Diff) {
768 +
                    self.undo_last_hunk_accept()?;
769 +
                }
770 +
            }
771 +
            DeferredMutation::ToggleRejection => {
772 +
                let index = if matches!(self.mode, Mode::Commits) {
773 +
                    self.list.selected()
774 +
                } else {
775 +
                    self.current
776 +
                };
777 +
                self.toggle_commit_rejected(index)?;
778 +
                if matches!(self.mode, Mode::Hunk(_)) {
779 +
                    self.next_tab()?;
780 +
                }
781 +
            }
782 +
            DeferredMutation::ToggleDrop => {
783 +
                let index = if matches!(self.mode, Mode::Commits) {
784 +
                    self.list.selected()
785 +
                } else {
786 +
                    self.current
787 +
                };
788 +
                self.toggle_commit_dropped(index)?;
789 +
            }
790 +
            DeferredMutation::DeleteComment => {
791 +
                if matches!(self.mode, Mode::Hunk(_)) {
792 +
                    self.delete_selected_comment()?;
793 +
                }
794 +
            }
795 +
        }
796 +
        Ok(())
797 +
    }
798 +
603 799
    /// Dispatches one input event, handling review keys before the viewer.
604 800
    fn handle_key(&mut self, event: Event<()>, area: Rect) -> Result<Control, Error> {
605 801
        match event {
606 802
            Event::Key(Key::Char('a')) => {
607 803
                match self.current()?.viewer.state().focus {
788 984
    }
789 985
790 986
    /// Toggles acceptance of the focused hunk.
791 987
    fn toggle_focused_hunk(&mut self, area: Rect) -> Result<(), Error> {
792 988
        let current = self.current;
989 +
        let pending_only = matches!(self.hunk_visibility, HunkVisibility::Pending);
793 990
        let before = self.current()?.viewer.state().clone();
794 991
        let loaded = self.current()?;
795 992
        let Some(DiffFocus::Hunk(hunk)) = loaded.viewer.state().focus else {
796 993
            return Ok(());
797 994
        };
798 995
        if !loaded.identities.contains_key(&hunk) {
799 996
            return Ok(());
800 997
        }
801 998
        let accepted = loaded.review.is_accepted(hunk);
999 +
        let next = (!accepted && pending_only)
1000 +
            .then(|| {
1001 +
                loaded
1002 +
                    .document
1003 +
                    .files
1004 +
                    .iter()
1005 +
                    .flat_map(|file| &file.hunks)
1006 +
                    .skip_while(|candidate| candidate.id != hunk)
1007 +
                    .skip(1)
1008 +
                    .find(|candidate| {
1009 +
                        loaded.identities.contains_key(&candidate.id)
1010 +
                            && !loaded.review.is_accepted(candidate.id)
1011 +
                    })
1012 +
                    .map(|candidate| candidate.id)
1013 +
            })
1014 +
            .flatten();
802 1015
        if accepted {
803 1016
            self.reject_hunks(BTreeSet::from([(current, hunk)]))?;
804 1017
        } else {
805 1018
            self.accept_hunks(BTreeSet::from([(current, hunk)]))?;
806 1019
        }
807 -
        if !accepted && matches!(self.hunk_visibility, HunkVisibility::Pending) {
808 -
            let loaded = self.current()?;
809 -
            let has_pending = loaded.review.accepted().len() < loaded.identities.len();
810 -
            if has_pending {
811 -
                loaded.viewer.apply(DiffAction::NextHunk, area);
812 -
            }
1020 +
        if let Some(next) = next {
1021 +
            self.current()?.viewer.focus_hunk(next, area);
813 1022
        }
814 1023
        self.record_navigation_rollback(current, before)?;
815 1024
816 1025
        Ok(())
817 1026
    }
a.rs +0 -0
crates/brain/src/session/commit.rs +3 -0
24 24
    pub(super) progress: ReviewProgress,
25 25
    /// Number of accepted hunks in this commit.
26 26
    pub(super) accepted_hunks: usize,
27 27
    /// Total number of hunks in this commit.
28 28
    pub(super) total_hunks: usize,
29 +
    /// Number of comments attached to hunks in this commit.
30 +
    pub(super) comment_count: usize,
29 31
    /// Final review state of this commit.
30 32
    pub(super) state: CommitReviewState,
31 33
    /// Remaining diff statistics for this commit.
32 34
    pub(super) remaining_stats: DiffStat,
33 35
    /// Split diff document retained from history progress calculation.
148 150
                    .get(&hunk.id)
149 151
                    .ok_or_else(|| Error::Git(format!("hunk {:?} has no identity", hunk.id)))?;
150 152
                targets.insert(
151 153
                    hunk.id,
152 154
                    CommentTarget {
155 +
                        commit: commit.id,
153 156
                        heading: heading.clone(),
154 157
                        path: path.clone(),
155 158
                        patch_id: identity.patch_id.clone(),
156 159
                        ordinal: identity.ordinal,
157 160
                    },
a.rs +0 -0
crates/brain/src/session/status.rs +18 -12
11 11
    Border, Buffer, Color, Constraint, HStack, Label, Line, Rect, Size, Style, Table, TableOptions,
12 12
    Widget, colors,
13 13
};
14 14
15 15
use crate::backend::CommitReviewState;
16 -
use crate::comments::Comment;
16 +
use crate::comments::{COMMENT_MARK, Comment};
17 17
use crate::review::{FileVisibility, HunkVisibility, Visibility};
18 18
19 19
use super::commit::CommitSlot;
20 20
21 21
/// Number of rows used by the status bar.
58 58
const DROPPED_MARK: char = '-';
59 59
/// Marker shown beside a commit that has not been reviewed.
60 60
const PENDING_MARK: char = 'โ—‹';
61 61
/// Marker shown beside a commit whose review is in progress.
62 62
const IN_PROGRESS_MARK: char = 'โ—';
63 -
/// Marker identifying a hunk count in commit history: โ–ค.
64 -
const HUNK_MARK: char = 'โ–ค';
65 63
/// Marker highlighted when all hunks are visible in the footer: โœ”.
66 64
const ALL_HUNKS_MODE_ICON: &str = "โœ”";
67 65
/// Marker shown when full-file mode is visible in the footer: โ†•.
68 66
const FULL_FILE_MODE_ICON: &str = "โ†•";
69 67
/// Separator shown between footer status segments: ยท.
394 392
    ]
395 393
}
396 394
397 395
/// Returns the right-side columns for one commit-table row.
398 396
///
399 -
/// Columns are ordered by their wide-layout position: author, age, branches,
400 -
/// diffstat, and hunk progress.
397 +
/// Columns are ordered by their wide-layout position: hunk progress, author,
398 +
/// age, branches, comment count, and diffstat.
401 399
pub(super) fn commit_row_suffix(
402 400
    slot: &CommitSlot,
403 401
    palette: DiffPalette,
404 402
    now: u64,
405 403
    largest_change_count: usize,
406 404
    max_graph_width: usize,
407 -
) -> [Line; 5] {
405 +
) -> [Line; 6] {
408 406
    let stats = slot.remaining_stats();
409 407
    let diffstat = match slot.state {
410 408
        CommitReviewState::Pending => {
411 409
            history_diffstat(stats, largest_change_count, max_graph_width, palette)
412 410
        }
436 434
        (_, 100) => palette.positive_fg,
437 435
        _ => colors::rgb::ORANGE,
438 436
    };
439 437
    let hunks = Line::new(
440 438
        Label::new(&format!(
441 -
            "{HUNK_MARK} {percent:>3}%/{:<HISTORY_HUNK_COUNT_WIDTH$}",
439 +
            "{percent}%/{:<HISTORY_HUNK_COUNT_WIDTH$}",
442 440
            slot.total_hunks
443 441
        ))
444 442
        .fg(hunk_color),
445 443
    );
444 +
    let comments = slot
445 +
        .loaded
446 +
        .as_ref()
447 +
        .map_or(slot.comment_count, |loaded| loaded.comments.len());
446 448
    [
449 +
        hunks,
447 450
        Line::new(Label::new(slot.commit.author.as_str()).fg(HISTORY_VALUE_FG))
448 451
            .style(identity_style),
449 452
        Line::new(
450 453
            Label::from(relative_time(
451 454
                slot.commit.recency.seconds.into(),
454 457
            .fg(colors::fixed::MUTED),
455 458
        )
456 459
        .style(identity_style),
457 460
        Line::new(Label::new(&slot.commit.branches.join(", ")).fg(colors::rgb::TEAL))
458 461
            .style(row_style),
462 +
        Line::new(Label::new(&format!("{COMMENT_MARK} {comments:>2}")).fg(colors::fixed::MUTED))
463 +
            .style(row_style),
459 464
        diffstat.style(row_style),
460 -
        hunks,
461 465
    ]
462 466
}
463 467
464 468
/// Returns a change count and proportional addition and deletion graph.
465 469
fn history_diffstat(
730 734
                accepted: 0,
731 735
                total: 1,
732 736
            },
733 737
            accepted_hunks: 0,
734 738
            total_hunks: 1,
739 +
            comment_count: 3,
735 740
            state: CommitReviewState::Pending,
736 741
            remaining_stats: stats,
737 742
            document: None,
738 743
            identities: None,
739 744
            loaded: None,
753 758
                    &slot,
754 759
                    DiffPalette::default(),
755 760
                    now as u64,
756 761
                    stats.insertions + stats.deletions,
757 762
                    8,
758 -
                )[3]
763 +
                )[5]
759 764
                .to_string()
760 765
                .is_empty()
761 766
            );
762 767
        }
763 768
764 769
        slot.state = CommitReviewState::Dropped;
765 -
        let [mut author, mut age, _, diffstat, hunks] = commit_row_suffix(
770 +
        let [hunks, mut author, mut age, _, comments, diffstat] = commit_row_suffix(
766 771
            &slot,
767 772
            DiffPalette::default(),
768 773
            now as u64,
769 774
            stats.insertions + stats.deletions,
770 775
            8,
772 777
        assert_eq!(
773 778
            commit_row(&slot, DiffPalette::default())[0].to_string(),
774 779
            DROPPED_MARK.to_string()
775 780
        );
776 781
        assert!(diffstat.to_string().is_empty());
777 -
        assert_eq!(hunks.to_string(), "โ–ค   0%/1   ");
782 +
        assert_eq!(hunks.to_string(), "0%/1   ");
783 +
        assert_eq!(comments.to_string(), "๐Ÿ—ฉ  3");
778 784
779 785
        let mut author_buffer = Buffer::empty(Rect::new(0, 0, slot.commit.author.len(), 1));
780 786
        let mut age_buffer = Buffer::empty(Rect::new(0, 0, 16, 1));
781 787
        author.render(author_buffer.area(), &mut author_buffer);
782 788
        age.render(age_buffer.area(), &mut age_buffer);
819 825
            ),
820 826
        ] {
821 827
            slot.state = state;
822 828
            slot.accepted_hunks = accepted_hunks;
823 829
            slot.total_hunks = 2;
824 -
            let [_, _, _, _, mut hunks] = commit_row_suffix(
830 +
            let [mut hunks, _, _, _, _, _] = commit_row_suffix(
825 831
                &slot,
826 832
                DiffPalette::default(),
827 833
                now as u64,
828 834
                stats.insertions + stats.deletions,
829 835
                8,
crates/brain/src/session/worker.rs +4 -2
68 68
    LoadCommit(Box<LoadCommit>),
69 69
    /// Loads history documents and aggregate status.
70 70
    LoadHistory {
71 71
        /// Commits to load, oldest first.
72 72
        commits: Vec<Commit>,
73 +
        /// Review comments used to count annotations per commit.
74 +
        comments: ReviewComments,
73 75
    },
74 76
    /// Loads file sources into a focused hunk viewer.
75 77
    LoadSources {
76 78
        /// Viewer awaiting file contents.
77 79
        viewer: Box<DiffViewer>,
153 155
                        Output::CommitLoaded {
154 156
                            index,
155 157
                            result: Box::new(result),
156 158
                        }
157 159
                    }
158 -
                    Command::LoadHistory { commits } => {
159 -
                        let result = reviewed_slots(commits, &*backend, &brain)
160 +
                    Command::LoadHistory { commits, comments } => {
161 +
                        let result = reviewed_slots(commits, &*backend, &brain, &comments)
160 162
                            .map_err(|error| error.to_string());
161 163
                        Output::HistoryLoaded(Box::new(result))
162 164
                    }
163 165
                    Command::LoadSources { viewer, hunk } => {
164 166
                        let mut viewer = *viewer;
crates/diff/src/viewer.rs +27 -0
1067 1067
            self.hunk_focus.insert(file.id, hunk);
1068 1068
        }
1069 1069
        self.state.focus = focus;
1070 1070
    }
1071 1071
1072 +
    /// Focuses `hunk` and scrolls it into view.
1073 +
    pub fn focus_hunk(&mut self, hunk: HunkId, area: Rect) -> bool {
1074 +
        let focus = DiffFocus::Hunk(hunk);
1075 +
        if !self.has_focus(focus) {
1076 +
            return false;
1077 +
        }
1078 +
        let before = self.state.clone();
1079 +
        self.set_focus(Some(focus));
1080 +
        let visible_rows = self.layout(area).diff.rows;
1081 +
        if let Some(target) = self
1082 +
            .focus_targets(FocusFilter::HunkNavigation)
1083 +
            .into_iter()
1084 +
            .find(|target| target.focus == focus)
1085 +
        {
1086 +
            let offset =
1087 +
                target.scroll_offset(self.state.scroll.offset, visible_rows, HunkScroll::Preserve);
1088 +
            self.state
1089 +
                .scroll
1090 +
                .set_offset(offset, self.scroll_rows(visible_rows), visible_rows);
1091 +
        }
1092 +
        if self.layout(area).tree.is_some() {
1093 +
            let active = self.active_file();
1094 +
            self.sync_file_tree(active);
1095 +
        }
1096 +
        self.state != before
1097 +
    }
1098 +
1072 1099
    /// Returns the file containing the current focus.
1073 1100
    pub fn focused_file(&self) -> Option<FileId> {
1074 1101
        match self.state.focus? {
1075 1102
            DiffFocus::Commit => None,
1076 1103
            DiffFocus::File(file) => Some(file),
a.rs +0 -0
image.png +0 -0
image.png +0 -0
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
a.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
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
new.rs\n", +0 -0
crates/repo/src/git.rs +58 -0
147 147
            .args(args)
148 148
            .output()
149 149
            .map_err(RepoError::Io)
150 150
    }
151 151
152 +
    /// Pairs corresponding commits between two versions of a review range.
153 +
    ///
154 +
    /// Git's range-diff matching is similarity based, so rewritten commits can
155 +
    /// be paired even when their object ids and exact patch ids changed.
156 +
    pub fn range_diff(
157 +
        &self,
158 +
        old_base: Oid,
159 +
        old_target: Oid,
160 +
        new_base: Oid,
161 +
        new_target: Oid,
162 +
    ) -> Result<BTreeMap<Oid, Oid>, RepoError> {
163 +
        let old_range = format!("{old_base}..{old_target}");
164 +
        let new_range = format!("{new_base}..{new_target}");
165 +
        let abbrev = format!("--abbrev={}", self.object_id_width);
166 +
        let output = self.run(
167 +
            "range-diff",
168 +
            &[
169 +
                "--no-color",
170 +
                "--no-dual-color",
171 +
                &abbrev,
172 +
                &old_range,
173 +
                &new_range,
174 +
            ],
175 +
            Opts::default(),
176 +
        )?;
177 +
        if !output.status.success() {
178 +
            return Err(RepoError::git(&output));
179 +
        }
180 +
        let stdout = utf8(output.stdout)?;
181 +
        let mut pairs = BTreeMap::new();
182 +
        for line in stdout.lines() {
183 +
            let mut fields = line.split_whitespace();
184 +
            let Some(_old_index) = fields.next() else {
185 +
                continue;
186 +
            };
187 +
            let Some(old) = fields.next() else {
188 +
                continue;
189 +
            };
190 +
            let Some(marker) = fields.next() else {
191 +
                continue;
192 +
            };
193 +
            let Some(_new_index) = fields.next() else {
194 +
                continue;
195 +
            };
196 +
            let Some(new) = fields.next() else {
197 +
                continue;
198 +
            };
199 +
            if !matches!(marker, "=" | "!") {
200 +
                continue;
201 +
            }
202 +
            let (Ok(old), Ok(new)) = (old.parse(), new.parse()) else {
203 +
                continue;
204 +
            };
205 +
            pairs.insert(old, new);
206 +
        }
207 +
        Ok(pairs)
208 +
    }
209 +
152 210
    /// Reads the first bytes of a Git blob object.
153 211
    pub fn head_line(&self, oid: Oid) -> Result<Option<String>, RepoError> {
154 212
        let mut child = self
155 213
            .command("show")
156 214
            .arg(oid.to_string())
root\nnew file mode")); +0 -0
file\n")); +0 -0
file\n"), +0 -0
file\n"), +0 -0
a\n--- a/a\n+++ b/a\n@@ -1 +1 @@\n-old\n+new\n".to_owned(), +0 -0
b\n--- a/b\n+++ b/b\n@@ -0,0 +1 @@\n+line\n".to_owned(), +0 -0