brain: Keep hunk acceptance responsive

5e9d3fd66b3d141c03f18d1938569b99321b91e8
Accept several hunks quickly or accept a large hunk after scrolling
inside it. Each action now updates immediately, persists the latest
accepted state, and remains available while any part of the focused
hunk is visible.

Keep line-based review progress consistent with optimistic state. Show
a recoverable error in the status row without blanking the action row.

Assisted-by: Codex:gpt-5.6
Alexis Sellier committed ago 1 parent 6ebf50bf
crates/brain/src/backend.rs +17 -13
432 432
    pub progress: ReviewProgress,
433 433
    /// Final review state of the commit.
434 434
    pub state: CommitReviewState,
435 435
    /// Diff statistics from hunks that remain unaccepted.
436 436
    pub stats: DiffStat,
437 -
    /// Number of accepted hunks in the commit.
438 -
    pub accepted_hunks: usize,
439 437
    /// Total number of hunks in the commit.
440 438
    pub total_hunks: usize,
441 439
}
442 440
443 441
impl HistoryStatus {
1145 1143
                    *commit,
1146 1144
                    CommitStatus {
1147 1145
                        progress: reconciled.progress,
1148 1146
                        state: reconciled.state,
1149 1147
                        stats: commit_remaining_stats(document, &reconciled.accepted),
1150 -
                        accepted_hunks: reconciled.accepted.len(),
1151 1148
                        total_hunks: identities.len(),
1152 1149
                    },
1153 1150
                )
1154 1151
            })
1155 1152
            .collect()
1435 1432
    /// Rolls back accepted-hunk state without writing it to the repository.
1436 1433
    pub(crate) fn rollback(&mut self, accepted: Accepted) {
1437 1434
        self.accepted = accepted;
1438 1435
    }
1439 1436
1440 -
    /// Marks hunks accepted and updates the derived tree.
1441 -
    pub fn accept(&mut self, hunks: impl IntoIterator<Item = AcceptedHunk>) -> Result<(), Error> {
1437 +
    /// Replaces accepted-hunk state and updates the derived tree.
1438 +
    pub(crate) fn set_accepted(&mut self, accepted: Accepted) -> Result<(), Error> {
1442 1439
        self.refresh()?;
1443 -
        let mut accepted = self.accepted.clone();
1444 1440
        let mut rejected = self.rejected.clone();
1445 1441
        let mut dropped = self.dropped.clone();
1446 -
        for hunk in hunks {
1442 +
        for hunk in &accepted {
1447 1443
            rejected.remove(&hunk.commit);
1448 1444
            dropped.remove(&hunk.commit);
1449 -
            accepted.insert(hunk);
1450 1445
        }
1451 1446
        let tree = self.project_accepted(&accepted)?;
1452 1447
        self.persist(tree, accepted, rejected, dropped)
1453 1448
    }
1454 1449
1455 -
    /// Marks exact hunks unaccepted and rebuilds the derived tree.
1456 -
    pub fn reject(&mut self, rejected: &BTreeSet<AcceptedHunk>) -> Result<(), Error> {
1450 +
    /// Marks hunks accepted and updates the derived tree in tests.
1451 +
    #[cfg(test)]
1452 +
    fn accept(&mut self, hunks: impl IntoIterator<Item = AcceptedHunk>) -> Result<(), Error> {
1457 1453
        self.refresh()?;
1458 1454
        let mut accepted = self.accepted.clone();
1459 -
        accepted.retain(|hunk| !rejected.contains(hunk));
1455 +
        let mut rejected = self.rejected.clone();
1456 +
        let mut dropped = self.dropped.clone();
1457 +
        for hunk in hunks {
1458 +
            rejected.remove(&hunk.commit);
1459 +
            dropped.remove(&hunk.commit);
1460 +
            accepted.insert(hunk);
1461 +
        }
1460 1462
        let tree = self.project_accepted(&accepted)?;
1461 -
        self.persist(tree, accepted, self.rejected.clone(), self.dropped.clone())
1463 +
        self.persist(tree, accepted, rejected, dropped)
1462 1464
    }
1463 1465
1464 1466
    /// Toggles the rejected state of one commit.
1465 1467
    pub fn toggle_commit_rejected(&mut self, commit: Oid) -> Result<(), Error> {
1466 1468
        self.refresh()?;
2205 2207
        assert!(backend.brain().unwrap().dropped.is_empty());
2206 2208
2207 2209
        brain.toggle_commit_rejected(commit).unwrap();
2208 2210
        let document = backend.diff_document(commit).unwrap().split_hunks();
2209 2211
        let identities = brain.hunk_identities(&document, commit).unwrap();
2210 -
        brain.accept(identities.into_values()).unwrap();
2212 +
        brain
2213 +
            .set_accepted(identities.into_values().collect())
2214 +
            .unwrap();
2211 2215
        let stored = backend.brain().unwrap();
2212 2216
2213 2217
        assert!(stored.rejected.is_empty());
2214 2218
        assert!(stored.dropped.is_empty());
2215 2219
f +0 -0
new.rs +0 -0
image.png +0 -0
new.txt +0 -0
crates/brain/src/session.rs +119 -25
195 195
        .into_iter()
196 196
        .map(|commit| CommitSlot {
197 197
            remaining_stats: commit.stats,
198 198
            commit,
199 199
            progress: ReviewProgress::default(),
200 -
            accepted_hunks: 0,
201 200
            total_hunks: 0,
202 201
            comment_count: 0,
203 202
            state: CommitReviewState::Pending,
204 203
            document: None,
205 204
            identities: None,
221 220
        range,
222 221
        history_status: None,
223 222
        accepted: Vec::new(),
224 223
        pending: None,
225 224
        deferred_mutation: None,
225 +
        queued_acceptance: None,
226 226
        current: 0,
227 227
        hunk_visibility: HunkVisibility::default(),
228 228
        mode,
229 229
        parked: None,
230 230
        list: ListState::new(),
337 337
        .into_iter()
338 338
        .map(|(commit, document, identities)| {
339 339
            let status = history.commits.entry(commit.id).or_default();
340 340
            CommitSlot {
341 341
                progress: status.progress,
342 -
                accepted_hunks: status.accepted_hunks,
343 342
                total_hunks: status.total_hunks,
344 343
                comment_count: identities
345 344
                    .values()
346 345
                    .map(|identity| {
347 346
                        comments.matching_count(
424 423
    /// Undo stack installed after successful persistence.
425 424
    undo: Vec<HunkLocation>,
426 425
    /// Navigation restored if the user has not moved again.
427 426
    navigation: Option<NavigationRollback>,
428 427
}
428 +
/// Latest optimistic acceptance waiting for active persistence.
429 +
struct QueuedAcceptance {
430 +
    /// Exact accepted-hunk state to persist.
431 +
    accepted: Accepted,
432 +
    /// Undo stack installed after successful persistence.
433 +
    undo: Vec<HunkLocation>,
434 +
    /// Navigation restored if persistence fails without later movement.
435 +
    navigation: Option<NavigationRollback>,
436 +
}
429 437
430 438
/// Comment state restored if persistence fails.
431 439
struct CommentRollback {
432 440
    /// Commit whose comment view changed.
433 441
    commit: usize,
462 470
    ToggleDrop,
463 471
    /// Delete the selected hunk comment.
464 472
    DeleteComment,
465 473
}
466 474
475 +
impl DeferredMutation {
476 +
    /// Returns whether this mutation can update optimistic acceptance state.
477 +
    fn updates_optimistic_acceptance(self) -> bool {
478 +
        matches!(
479 +
            self,
480 +
            Self::ToggleAcceptance | Self::ToggleFileAcceptance | Self::UndoAcceptance
481 +
        )
482 +
    }
483 +
}
484 +
467 485
/// Hunk editor retained with the commit that owns it.
468 486
struct ParkedHunk {
469 487
    /// Index of the owning commit.
470 488
    commit: usize,
471 489
    /// Retained hunk view and draft.
485 503
    accepted: Vec<HunkLocation>,
486 504
    /// Optimistic state currently writing to the repository.
487 505
    pending: Option<Pending>,
488 506
    /// Semantic repository mutation waiting for active persistence to finish.
489 507
    deferred_mutation: Option<DeferredMutation>,
508 +
    /// Latest optimistic acceptance waiting for active persistence.
509 +
    queued_acceptance: Option<QueuedAcceptance>,
490 510
    /// Index of the commit currently displayed.
491 511
    current: usize,
492 512
    /// Set of hunks visible across commit viewers.
493 513
    hunk_visibility: HunkVisibility,
494 514
    /// Active view: the commit list, the diff, or a hunk's comment box.
574 594
                if self.loading.is_some() && !matches!(event, Event::Resize(_)) {
575 595
                    if self.pending.is_none() {
576 596
                        return Ok(Update::Continue);
577 597
                    }
578 598
                    if let Some(mutation) = self.deferred_mutation(&event) {
599 +
                        if mutation.updates_optimistic_acceptance()
600 +
                            && matches!(self.pending, Some(Pending::Acceptance(_)))
601 +
                        {
602 +
                            self.apply_deferred_mutation(mutation)?;
603 +
                            return Ok(Update::Redraw);
604 +
                        }
579 605
                        self.deferred_mutation.get_or_insert(mutation);
580 606
                        return Ok(Update::Continue);
581 607
                    }
582 608
                    if !self.allows_navigation_during_persistence(&event) {
583 609
                        return Ok(Update::Continue);
693 719
                }
694 720
                Err(message) => self.error = Some(message.replace('\n', " ยท ")),
695 721
            },
696 722
            WorkerOutput::Persisted(result) => {
697 723
                self.finish_persistence(*result)?;
698 -
                if let Some(mutation) = self.deferred_mutation.take() {
724 +
                if self.pending.is_none()
725 +
                    && let Some(mutation) = self.deferred_mutation.take()
726 +
                {
699 727
                    self.apply_deferred_mutation(mutation)?;
700 728
                }
701 729
            }
702 730
        }
703 731
        Ok(Update::Redraw)
1031 1059
        Ok(())
1032 1060
    }
1033 1061
1034 1062
    /// Rejects the most recently accepted hunk that remains accepted.
1035 1063
    fn undo_last_hunk_accept(&mut self) -> Result<(), Error> {
1036 -
        while let Some(&(index, hunk)) = self.accepted.last() {
1064 +
        let mut undo = self.optimistic_undo();
1065 +
        while let Some((index, hunk)) = undo.pop() {
1037 1066
            let accepted = self.load(index)?.review.is_accepted(hunk);
1038 1067
            if accepted {
1039 1068
                let before = self.load(index)?.viewer.state().clone();
1040 1069
                self.reject_hunks(BTreeSet::from([(index, hunk)]))?;
1041 1070
                self.record_navigation_rollback(index, before)?;
1042 1071
                break;
1043 1072
            }
1044 -
            self.accepted.pop();
1045 1073
        }
1046 1074
        Ok(())
1047 1075
    }
1048 1076
1049 1077
    /// Persists acceptance or rejection of every hunk in the focused file.
1101 1129
            .collect::<Result<Vec<_>, Error>>()?;
1102 1130
1103 1131
        let mut accepted = self.brain.accepted.clone();
1104 1132
        accepted.extend(identities.iter().cloned());
1105 1133
1106 -
        let mut undo = self.accepted.clone();
1134 +
        let mut undo = self.optimistic_undo();
1107 1135
        undo.extend(hunks);
1108 1136
1109 -
        self.persist_acceptance(accepted, undo, ReviewMutation::Accept { identities })
1137 +
        self.persist_acceptance(accepted, undo)
1110 1138
    }
1111 1139
1112 1140
    /// Optimistically rejects the selected hunks and starts persistence.
1113 1141
    fn reject_hunks(&mut self, hunks: BTreeSet<HunkLocation>) -> Result<(), Error> {
1114 1142
        let identities = hunks
1123 1151
            .collect::<Result<BTreeSet<_>, Error>>()?;
1124 1152
1125 1153
        let mut accepted = self.brain.accepted.clone();
1126 1154
        accepted.retain(|identity| !identities.contains(identity));
1127 1155
1128 -
        let mut undo = self.accepted.clone();
1156 +
        let mut undo = self.optimistic_undo();
1129 1157
        undo.retain(|hunk| !hunks.contains(hunk));
1130 1158
1131 -
        self.persist_acceptance(accepted, undo, ReviewMutation::Reject { identities })
1159 +
        self.persist_acceptance(accepted, undo)
1160 +
    }
1161 +
1162 +
    /// Returns the undo stack including acceptance that is still persisting.
1163 +
    fn optimistic_undo(&self) -> Vec<HunkLocation> {
1164 +
        if let Some(queued) = &self.queued_acceptance {
1165 +
            queued.undo.clone()
1166 +
        } else if let Some(Pending::Acceptance(pending)) = &self.pending {
1167 +
            pending.undo.clone()
1168 +
        } else {
1169 +
            self.accepted.clone()
1170 +
        }
1132 1171
    }
1133 1172
1134 1173
    /// Records automatic navigation for the pending rollback.
1135 1174
    fn record_navigation_rollback(
1136 1175
        &mut self,
1137 1176
        commit: usize,
1138 1177
        before: DiffState,
1139 1178
    ) -> Result<(), Error> {
1140 1179
        let after = self.load(commit)?.viewer.state().clone();
1141 -
        if let Some(Pending::Acceptance(pending)) = &mut self.pending {
1142 -
            pending.navigation = Some(NavigationRollback {
1143 -
                commit,
1144 -
                before,
1145 -
                after,
1180 +
        let navigation = NavigationRollback {
1181 +
            commit,
1182 +
            before,
1183 +
            after,
1184 +
        };
1185 +
        if let Some(queued) = &mut self.queued_acceptance {
1186 +
            queued.navigation = Some(match queued.navigation.take() {
1187 +
                Some(previous)
1188 +
                    if previous.commit == navigation.commit
1189 +
                        && previous.after == navigation.before =>
1190 +
                {
1191 +
                    NavigationRollback {
1192 +
                        before: previous.before,
1193 +
                        ..navigation
1194 +
                    }
1195 +
                }
1196 +
                _ => navigation,
1146 1197
            });
1198 +
        } else if let Some(Pending::Acceptance(pending)) = &mut self.pending {
1199 +
            pending.navigation = Some(navigation);
1147 1200
        }
1148 1201
        Ok(())
1149 1202
    }
1150 1203
1151 -
    /// Shows optimistic state and starts persistence.
1204 +
    /// Shows optimistic state and starts or updates persistence.
1152 1205
    fn persist_acceptance(
1153 1206
        &mut self,
1154 1207
        accepted: Accepted,
1155 1208
        undo: Vec<HunkLocation>,
1156 -
        mutation: ReviewMutation,
1157 1209
    ) -> Result<(), Error> {
1158 -
        debug_assert!(self.pending.is_none());
1159 -
1160 1210
        let rollback = self.brain.clone();
1161 -
        self.brain.rollback(accepted);
1211 +
        self.brain.rollback(accepted.clone());
1162 1212
        if let Err(error) = self.reconcile_reviews() {
1163 1213
            self.brain = rollback;
1164 1214
            self.reconcile_state();
1165 1215
            return Err(error);
1166 1216
        }
1167 1217
1218 +
        if matches!(self.pending, Some(Pending::Acceptance(_))) {
1219 +
            let navigation = self
1220 +
                .queued_acceptance
1221 +
                .take()
1222 +
                .and_then(|queued| queued.navigation);
1223 +
            self.queued_acceptance = Some(QueuedAcceptance {
1224 +
                accepted,
1225 +
                undo,
1226 +
                navigation,
1227 +
            });
1228 +
            return Ok(());
1229 +
        }
1230 +
1168 1231
        let result = self
1169 1232
            .repository_worker
1170 -
            .send(WorkerCommand::Mutate(mutation))
1233 +
            .send(WorkerCommand::Mutate(ReviewMutation::SetAccepted(accepted)))
1171 1234
            .map_err(Error::Git);
1172 1235
        if let Err(error) = result {
1173 1236
            self.brain = rollback;
1174 1237
            self.reconcile_reviews()?;
1175 1238
            return Err(error);
1193 1256
        let persisted = match result {
1194 1257
            Ok(persisted) => persisted,
1195 1258
            Err(message) => {
1196 1259
                match pending {
1197 1260
                    Pending::Acceptance(pending) => {
1198 -
                        let navigation = pending.navigation.and_then(|navigation| {
1261 +
                        let queued_navigation = self
1262 +
                            .queued_acceptance
1263 +
                            .take()
1264 +
                            .and_then(|queued| queued.navigation);
1265 +
                        let navigation = match (pending.navigation, queued_navigation) {
1266 +
                            (Some(first), Some(last))
1267 +
                                if first.commit == last.commit && first.after == last.before =>
1268 +
                            {
1269 +
                                Some(NavigationRollback {
1270 +
                                    after: last.after,
1271 +
                                    ..first
1272 +
                                })
1273 +
                            }
1274 +
                            (first, last) => last.or(first),
1275 +
                        }
1276 +
                        .and_then(|navigation| {
1199 1277
                            let loaded = self.commits.get(navigation.commit)?.loaded.as_ref()?;
1200 1278
                            (loaded.viewer.state() == &navigation.after)
1201 1279
                                .then_some((navigation.commit, navigation.before))
1202 1280
                        });
1203 1281
                        self.brain = *pending.rollback;
1224 1302
                let Persisted::Review(brain) = persisted else {
1225 1303
                    return Err(Error::Git(
1226 1304
                        "review persistence returned comment state".to_owned(),
1227 1305
                    ));
1228 1306
                };
1229 -
                self.brain = *brain;
1230 -
                self.accepted = pending.undo;
1307 +
                if let Some(queued) = self.queued_acceptance.take() {
1308 +
                    let accepted = queued.accepted.clone();
1309 +
                    if let Err(message) = self
1310 +
                        .repository_worker
1311 +
                        .send(WorkerCommand::Mutate(ReviewMutation::SetAccepted(accepted)))
1312 +
                    {
1313 +
                        self.brain = *brain;
1314 +
                        self.reconcile_reviews()?;
1315 +
                        return Err(Error::Git(message));
1316 +
                    }
1317 +
                    self.pending = Some(Pending::Acceptance(AcceptancePending {
1318 +
                        rollback: brain,
1319 +
                        undo: queued.undo,
1320 +
                        navigation: queued.navigation,
1321 +
                    }));
1322 +
                    self.loading = Some("saving review");
1323 +
                } else {
1324 +
                    self.brain = *brain;
1325 +
                    self.accepted = pending.undo;
1326 +
                }
1231 1327
            }
1232 1328
            Pending::Decision => {
1233 1329
                let Persisted::Review(brain) = persisted else {
1234 1330
                    return Err(Error::Git(
1235 1331
                        "decision persistence returned comment state".to_owned(),
1318 1414
                .collect::<Result<Vec<_>, Error>>()?;
1319 1415
            let status = HistoryStatus::for_commits(&self.brain, &status_inputs);
1320 1416
            for slot in &mut self.commits {
1321 1417
                if let Some(commit) = status.commits.get(&slot.commit.id) {
1322 1418
                    slot.progress = commit.progress;
1323 -
                    slot.accepted_hunks = commit.accepted_hunks;
1324 1419
                    slot.total_hunks = commit.total_hunks;
1325 1420
                    slot.state = commit.state;
1326 1421
                    slot.remaining_stats = commit.stats;
1327 1422
                }
1328 1423
            }
1686 1781
            })
1687 1782
            .collect::<Vec<_>>();
1688 1783
        let reconciled = self.brain.reconcile(&commits);
1689 1784
        for (slot, reconciled) in self.commits.iter_mut().zip(reconciled) {
1690 1785
            slot.progress = reconciled.progress;
1691 -
            slot.accepted_hunks = reconciled.accepted.len();
1692 1786
            slot.total_hunks = slot.hunk_count();
1693 1787
            slot.state = reconciled.state;
1694 1788
            if let Some(loaded) = &mut slot.loaded {
1695 1789
                loaded.review.replace(reconciled.accepted);
1696 1790
                loaded.refresh_decorations();
a.rs +0 -0
crates/brain/src/session/commit.rs +0 -2
20 20
    pub(super) commit: Commit,
21 21
    /// Accepted-line progress for this commit.
22 22
    ///
23 23
    /// Persisted line totals provide progress before the diff is decoded.
24 24
    pub(super) progress: ReviewProgress,
25 -
    /// Number of accepted hunks in this commit.
26 -
    pub(super) accepted_hunks: usize,
27 25
    /// Total number of hunks in this commit.
28 26
    pub(super) total_hunks: usize,
29 27
    /// Number of comments attached to hunks in this commit.
30 28
    pub(super) comment_count: usize,
31 29
    /// Final review state of this commit.
a.rs +0 -0
crates/brain/src/session/status.rs +15 -20
395 395
            return;
396 396
        }
397 397
        let (status_area, action_area) = Self::rows(area);
398 398
        self.status.render(status_area, buf);
399 399
        if !action_area.is_empty() {
400 -
            let mut line = if self.status.error.is_some() {
401 -
                Status::background(action_area.cols)
402 -
            } else {
403 -
                self.action_line(action_area.cols)
404 -
            };
405 -
            line.render(action_area, buf);
400 +
            self.action_line(action_area.cols).render(action_area, buf);
406 401
        }
407 402
    }
408 403
}
409 404
410 405
/// Returns the viewer area above the footer chrome.
463 458
    let identity_style = if matches!(slot.state, CommitReviewState::Dropped) {
464 459
        Style::default().dim().strikethrough()
465 460
    } else {
466 461
        Style::default()
467 462
    };
468 -
    let percent = slot
469 -
        .accepted_hunks
470 -
        .saturating_mul(100)
471 -
        .checked_div(slot.total_hunks)
472 -
        .unwrap_or(0);
463 +
    let percent = slot.progress.filled(100);
473 464
    let hunk_color = match (slot.state, percent) {
474 465
        (CommitReviewState::Rejected, _) => palette.negative_fg,
475 466
        (_, 0) => colors::fixed::MUTED,
476 467
        (_, 100) => palette.positive_fg,
477 468
        _ => colors::rgb::BLUE,
478 469
    };
479 470
    let state = match slot.state {
480 471
        CommitReviewState::Accepted => Label::from_char(REVIEWED_MARK).fg(palette.positive_fg),
481 472
        CommitReviewState::Rejected => Label::from_char(REJECTED_MARK).fg(palette.negative_fg),
482 473
        CommitReviewState::Dropped => Label::from_char(DROPPED_MARK).fg(colors::fixed::MUTED),
483 -
        CommitReviewState::Pending if slot.accepted_hunks > 0 => {
474 +
        CommitReviewState::Pending if slot.progress.accepted > 0 => {
484 475
            Label::from_char(IN_PROGRESS_MARK).fg(colors::rgb::BLUE)
485 476
        }
486 477
        CommitReviewState::Pending => Label::from_char(PENDING_MARK).fg(colors::fixed::MUTED),
487 478
    };
488 479
    let progress = Line::new(state)
747 738
        chrome.render(buffer.area(), &mut buffer);
748 739
749 740
        let status = buffer.line(0);
750 741
        assert!(status.contains("patch does not apply"));
751 742
        assert!(!status.contains("brain"));
743 +
        assert!(buffer.line(1).contains("q quit"));
752 744
    }
753 745
754 746
    #[test]
755 747
    fn loading_status_preserves_application_and_mode() {
756 748
        let mut status = Status {
829 821
            },
830 822
            progress: ReviewProgress {
831 823
                accepted: 0,
832 824
                total: 1,
833 825
            },
834 -
            accepted_hunks: 0,
835 826
            total_hunks: 1,
836 827
            comment_count: 3,
837 828
            state: CommitReviewState::Pending,
838 829
            remaining_stats: stats,
839 830
            document: None,
907 898
                8,
908 899
            )[4]
909 900
            .to_string()
910 901
            .starts_with(PENDING_MARK)
911 902
        );
912 -
        slot.accepted_hunks = 1;
903 +
        slot.progress.accepted = 1;
913 904
        assert!(
914 905
            commit_row_suffix(
915 906
                &slot,
916 907
                DiffPalette::default(),
917 908
                now as u64,
920 911
            )[4]
921 912
            .to_string()
922 913
            .starts_with(IN_PROGRESS_MARK)
923 914
        );
924 915
925 -
        for (state, accepted_hunks, expected_color) in [
916 +
        for (state, accepted_lines, expected_color) in [
926 917
            (CommitReviewState::Pending, 0, colors::fixed::MUTED),
927 918
            (CommitReviewState::Pending, 1, colors::rgb::BLUE),
928 919
            (
929 920
                CommitReviewState::Pending,
930 -
                2,
921 +
                4,
931 922
                DiffPalette::default().positive_fg,
932 923
            ),
933 924
            (
934 925
                CommitReviewState::Rejected,
935 926
                0,
936 927
                DiffPalette::default().negative_fg,
937 928
            ),
938 929
        ] {
939 930
            slot.state = state;
940 -
            slot.accepted_hunks = accepted_hunks;
931 +
            slot.progress = ReviewProgress {
932 +
                accepted: accepted_lines,
933 +
                total: 4,
934 +
            };
941 935
            slot.total_hunks = 2;
942 936
            let [_, _, _, _, mut progress, _] = commit_row_suffix(
943 937
                &slot,
944 938
                DiffPalette::default(),
945 939
                now as u64,
946 940
                stats.insertions + stats.deletions,
947 941
                8,
948 942
            );
943 +
            let percent = slot.progress.filled(100);
944 +
            assert!(progress.to_string().contains(&format!("{percent}%/2")));
949 945
            let mut buffer = Buffer::empty(Rect::new(0, 0, 16, 1));
950 946
            progress.render(buffer.area(), &mut buffer);
951 -
            let slash_col =
952 -
                2 + format!("{}", accepted_hunks.saturating_mul(100) / slot.total_hunks).len() + 1;
947 +
            let slash_col = 2 + percent.to_string().len() + 1;
953 948
954 -
            let icon_color = match (state, accepted_hunks) {
949 +
            let icon_color = match (state, accepted_lines) {
955 950
                (CommitReviewState::Rejected, _) => DiffPalette::default().negative_fg,
956 951
                (CommitReviewState::Pending, 0) => colors::fixed::MUTED,
957 952
                (CommitReviewState::Pending, _) => colors::rgb::BLUE,
958 953
                _ => unreachable!(),
959 954
            };
crates/brain/src/session/worker.rs +5 -14
2 2
//!
3 3
//! All repository and filesystem I/O initiated by the UI must be represented by
4 4
//! a [`Command`] and executed here. Keeping the backend and writable review state
5 5
//! in this worker makes blocking the terminal event loop difficult by construction.
6 6
7 -
use std::collections::{BTreeMap, BTreeSet};
7 +
use std::collections::BTreeMap;
8 8
use std::sync::mpsc::{self, Sender};
9 9
use std::thread;
10 10
11 11
use rustik_diff::{DiffDocument, DiffOptions, DiffViewer, HunkId};
12 12
use rustik_repo::Oid;
13 13
14 -
use crate::backend::{AcceptedHunk, Backend, Brain, Commit};
14 +
use crate::backend::{Accepted, AcceptedHunk, Backend, Brain, Commit};
15 15
use crate::comments::ReviewComments;
16 16
17 17
use super::commit::{CommitReview, CommitSlot};
18 18
use super::event::TerminalEvent;
19 19
use super::{HistoryStatus, reviewed_slots};
20 20
21 21
/// One review-state mutation executed by the repository worker.
22 22
pub(super) enum ReviewMutation {
23 -
    /// Accepts exact hunk identities.
24 -
    Accept {
25 -
        /// Identities being accepted.
26 -
        identities: Vec<AcceptedHunk>,
27 -
    },
28 -
    /// Rejects exact hunk identities.
29 -
    Reject {
30 -
        /// Identities being rejected.
31 -
        identities: BTreeSet<AcceptedHunk>,
32 -
    },
23 +
    /// Replaces the exact accepted-hunk state.
24 +
    SetAccepted(Accepted),
33 25
    /// Toggles one commit's rejected decision.
34 26
    ToggleRejected {
35 27
        /// Commit whose decision changes.
36 28
        commit: Oid,
37 29
    },
179 171
                            result: Box::new(result),
180 172
                        }
181 173
                    }
182 174
                    Command::Mutate(mutation) => {
183 175
                        let result = match mutation {
184 -
                            ReviewMutation::Accept { identities } => brain.accept(identities),
185 -
                            ReviewMutation::Reject { identities } => brain.reject(&identities),
176 +
                            ReviewMutation::SetAccepted(accepted) => brain.set_accepted(accepted),
186 177
                            ReviewMutation::ToggleRejected { commit } => {
187 178
                                brain.toggle_commit_rejected(commit)
188 179
                            }
189 180
                            ReviewMutation::ToggleDropped { commit } => {
190 181
                                brain.toggle_commit_dropped(commit)
crates/diff/src/viewer.rs +13 -2
1142 1142
    /// Returns whether the focused hunk has a visible row in `area`.
1143 1143
    pub fn focused_hunk_visible(&self, area: Rect) -> bool {
1144 1144
        let Some(focus @ DiffFocus::Hunk(_)) = self.state.focus else {
1145 1145
            return false;
1146 1146
        };
1147 -
        self.focus_anchor(self.layout(area).diff.rows)
1148 -
            .is_some_and(|(visible, _)| visible == focus)
1147 +
        let visible_rows = self.layout(area).diff.rows;
1148 +
        let scroll = self.state.scroll.offset;
1149 +
        self.focus_targets(FocusFilter::HunkNavigation)
1150 +
            .into_iter()
1151 +
            .find(|target| target.focus == focus)
1152 +
            .is_some_and(|target| target.visible(scroll, visible_rows))
1149 1153
    }
1150 1154
1151 1155
    /// Returns the focused file, or the first visible file when focus is unset.
1152 1156
    fn active_file(&self) -> Option<FileId> {
1153 1157
        self.focused_file().or_else(|| self.visible_file())
2623 2627
        } else {
2624 2628
            0
2625 2629
        }
2626 2630
    }
2627 2631
2632 +
    /// Returns whether any target row is visible in the viewport.
2633 +
    fn visible(self, scroll: usize, visible_rows: usize) -> bool {
2634 +
        let top = scroll.saturating_add(self.sticky_rows(scroll));
2635 +
        let bottom = scroll.saturating_add(visible_rows);
2636 +
        self.row < bottom && self.row.saturating_add(self.height.max(1)) > top
2637 +
    }
2638 +
2628 2639
    /// Returns the scroll offset for placing this target in a viewport.
2629 2640
    fn scroll_offset(self, current: usize, visible_rows: usize, placement: HunkScroll) -> usize {
2630 2641
        if visible_rows == 0 {
2631 2642
            return current;
2632 2643
        }
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