brain: Fix review correctness and diff inspection

a6cb1f95226bf37643294ebf8b8af22b132c1504
Make review mutations atomic across concurrent sessions and keep
resolved range identities stable.

Represent every supported Git change kind and render repository content
safely. Preserve comment drafts and expose valid actions in constrained
layouts.

Assisted-by: Codex:gpt-5.6-sol
Alexis Sellier committed ago 1 parent cea31f63
crates/brain/src/backend.rs +257 -48
254 254
        }
255 255
    }
256 256
}
257 257
258 258
/// Accepted hunks of one file, ready to apply to the projected tree.
259 -
pub struct FilePatches {
259 +
struct FilePatches {
260 260
    /// Every hunk of the file in one patch.
261 -
    pub combined: String,
261 +
    combined: String,
262 262
    /// The same hunks as individual patches, used when `combined` fails.
263 -
    pub hunks: Vec<String>,
263 +
    hunks: Vec<String>,
264 264
}
265 265
266 266
impl FilePatches {
267 267
    /// Builds combined and per-hunk patches for `hunks` of `file`.
268 -
    pub fn new(file: &FileDiff, hunks: Vec<Hunk>) -> Result<Self, Error> {
269 -
        if file.header.kind == FileKind::Binary {
268 +
    fn new(file: &FileDiff, hunks: Vec<Hunk>) -> Result<Self, Error> {
269 +
        if matches!(file.header.kind, FileKind::Binary | FileKind::ModeChanged) {
270 270
            let patch = DiffDocument::for_hunks(file, []).to_unified_string()?;
271 271
            return Ok(Self {
272 272
                combined: patch.clone(),
273 273
                hunks: vec![patch],
274 274
            });
765 765
}
766 766
767 767
/// Returns the branch point for the branch containing `target`.
768 768
pub fn branch_base(cwd: &Path, target: &Rev) -> Result<Rev, Error> {
769 769
    if is_jj_workspace(cwd) {
770 -
        let base = jj::Repository::new(cwd).branch_base(target)?;
770 +
        let repository = jj::Repository::new(cwd);
771 +
        let base = repository.branch_base(target)?;
772 +
        if let Some((_, bookmark)) = repository
773 +
            .bookmarks()?
774 +
            .into_iter()
775 +
            .find(|(head, _)| *head == base)
776 +
        {
777 +
            return Rev::try_from(bookmark.as_str())
778 +
                .map_err(|message| Error::Git(format!("invalid base bookmark: {message}")));
779 +
        }
771 780
        return Ok(Rev::from(base));
772 781
    }
773 782
    let repository = open_repository(cwd)?;
774 783
    let base = repository.branch_base(target)?.ok_or_else(|| {
775 784
        Error::Git(
776 785
            "could not infer a base for the target; supply an explicit base revision".to_owned(),
777 786
        )
778 787
    })?;
788 +
    let branches = repository.branches()?;
789 +
    if let Some(trunk) = repository.trunk(&branches)?
790 +
        && trunk.head == base
791 +
    {
792 +
        return Rev::try_from(trunk.name.as_str())
793 +
            .map_err(|message| Error::Git(format!("invalid trunk branch: {message}")));
794 +
    }
795 +
    if let Some(branch) = branches.into_iter().find(|branch| branch.head == base) {
796 +
        return Rev::try_from(branch.name.as_str())
797 +
            .map_err(|message| Error::Git(format!("invalid base branch: {message}")));
798 +
    }
779 799
    Ok(Rev::from(base))
780 800
}
781 801
782 802
/// Returns stored review statuses for the repository containing `cwd`.
783 803
pub fn statuses(cwd: &Path) -> Result<Vec<BrainStatus>, Error> {
1149 1169
        let mut commit_lines = 0u32;
1150 1170
        for file in &document.files {
1151 1171
            for hunk in &file.hunks {
1152 1172
                let stats = hunk.stats();
1153 1173
                let changed = stats.additions + stats.deletions;
1154 -
                let changed = usize::from(file.header.kind == FileKind::Binary).max(changed);
1174 +
                let changed = usize::from(matches!(
1175 +
                    file.header.kind,
1176 +
                    FileKind::Binary | FileKind::ModeChanged
1177 +
                ))
1178 +
                .max(changed);
1155 1179
                let lines = u32::try_from(changed)
1156 1180
                    .map_err(|_| Error::Git("hunk contains too many changed lines".to_owned()))?;
1157 1181
                commit_lines = commit_lines.checked_add(lines).ok_or_else(|| {
1158 1182
                    Error::Git("commit contains too many changed lines".to_owned())
1159 1183
                })?;
1191 1215
        target: Oid,
1192 1216
        identity: &ReviewIdentity,
1193 1217
    ) -> Result<Self, Error> {
1194 1218
        let state_ref = Brain::ref_for_identity(STATE_REF_NAMESPACE, identity)?;
1195 1219
        let comments_ref = Brain::ref_for_identity(COMMENTS_REF_NAMESPACE, identity)?;
1196 -
        let (commit, persisted) = match repository.optional_ref(&state_ref)? {
1197 -
            Some(existing) => {
1198 -
                let parent = repository.parent(existing)?;
1199 -
                if parent != base {
1200 -
                    return Err(Error::StaleReviewState);
1220 +
        let (commit, persisted) = loop {
1221 +
            match repository.optional_ref(&state_ref)? {
1222 +
                Some(existing) => {
1223 +
                    let parent = repository.parent(existing)?;
1224 +
                    if parent != base {
1225 +
                        return Err(Error::StaleReviewState);
1226 +
                    }
1227 +
                    let message = repository.commit_message(existing)?;
1228 +
                    let persisted = decode_state(&message).ok_or(Error::InvalidReviewState)?;
1229 +
                    if persisted.target != target {
1230 +
                        return Err(Error::StaleReviewState);
1231 +
                    }
1232 +
                    break (existing, persisted);
1201 1233
                }
1202 -
                let message = repository.commit_message(existing)?;
1203 -
                let persisted = decode_state(&message).ok_or(Error::InvalidReviewState)?;
1204 -
                if persisted.target != target {
1205 -
                    return Err(Error::StaleReviewState);
1234 +
                None => {
1235 +
                    let commit = Brain::fresh_state_commit(&repository, base, target)?;
1236 +
                    if repository.compare_and_update_ref(&state_ref, commit, None)? {
1237 +
                        break (commit, PersistedState::empty(target));
1238 +
                    }
1206 1239
                }
1207 -
                (existing, persisted)
1208 -
            }
1209 -
            None => {
1210 -
                let commit = Brain::fresh_state_commit(&repository, base, target)?;
1211 -
                repository.update_ref(&state_ref, commit)?;
1212 -
                let persisted = PersistedState::empty(target);
1213 -
                (commit, persisted)
1214 1240
            }
1215 1241
        };
1216 1242
        Ok(Self::new(
1217 1243
            repository,
1218 1244
            state_ref,
1337 1363
    /// Reads one source blob for file metadata derived from complete contents.
1338 1364
    pub fn read_blob(&self, oid: Oid) -> Result<Vec<u8>, Error> {
1339 1365
        Ok(self.repository.cat_blob(oid)?)
1340 1366
    }
1341 1367
1368 +
    /// Returns the repository-configured comment author.
1369 +
    pub fn comment_author(&self) -> Result<Option<String>, Error> {
1370 +
        Ok(self.repository.config("user.name")?)
1371 +
    }
1372 +
1342 1373
    /// Reads the review's persisted comments blob, if any.
1343 1374
    pub fn read_comments(&self) -> Result<Option<String>, Error> {
1344 1375
        let Some(blob) = self.repository.optional_ref(&self.comments_ref)? else {
1345 1376
            return Ok(None);
1346 1377
        };
1353 1384
        let blob = self.repository.write_blob(text.as_bytes())?;
1354 1385
        self.repository.update_ref(&self.comments_ref, blob)?;
1355 1386
        Ok(())
1356 1387
    }
1357 1388
1389 +
    /// Persists one comment-store delta without replacing concurrent updates.
1390 +
    pub fn merge_comments(
1391 +
        &self,
1392 +
        previous: &ReviewComments,
1393 +
        updated: &ReviewComments,
1394 +
    ) -> Result<ReviewComments, Error> {
1395 +
        loop {
1396 +
            let expected = self.repository.optional_ref(&self.comments_ref)?;
1397 +
            let mut current = if let Some(blob) = expected {
1398 +
                let bytes = self.repository.cat_blob(blob)?;
1399 +
                ReviewComments::parse(&String::from_utf8_lossy(&bytes))?
1400 +
            } else {
1401 +
                ReviewComments::parse("")?
1402 +
            };
1403 +
            current.merge(previous, updated);
1404 +
            let blob = self.repository.write_blob(current.encode().as_bytes())?;
1405 +
            if self
1406 +
                .repository
1407 +
                .compare_and_update_ref(&self.comments_ref, blob, expected)?
1408 +
            {
1409 +
                return Ok(current);
1410 +
            }
1411 +
        }
1412 +
    }
1413 +
1414 +
    /// Reloads review decisions written by another process.
1415 +
    fn refresh(&mut self) -> Result<(), Error> {
1416 +
        let Some(commit) = self.repository.optional_ref(&self.state_ref)? else {
1417 +
            return Err(Error::InvalidReviewState);
1418 +
        };
1419 +
        if commit == self.commit {
1420 +
            return Ok(());
1421 +
        }
1422 +
        let base = self.repository.parent(commit)?;
1423 +
        let message = self.repository.commit_message(commit)?;
1424 +
        let state = decode_state(&message).ok_or(Error::InvalidReviewState)?;
1425 +
        if base != self.base || state.target != self.target {
1426 +
            return Err(Error::StaleReviewState);
1427 +
        }
1428 +
        self.commit = commit;
1429 +
        self.accepted = state.accepted;
1430 +
        self.rejected = state.rejected;
1431 +
        self.dropped = state.dropped;
1432 +
        Ok(())
1433 +
    }
1434 +
1358 1435
    /// Rolls back accepted-hunk state without writing it to the repository.
1359 1436
    pub(crate) fn rollback(&mut self, accepted: Accepted) {
1360 1437
        self.accepted = accepted;
1361 1438
    }
1362 1439
1363 1440
    /// Marks hunks accepted and updates the derived tree.
1364 -
    pub fn accept(
1365 -
        &mut self,
1366 -
        hunks: impl IntoIterator<Item = AcceptedHunk>,
1367 -
        files: impl IntoIterator<Item = FilePatches>,
1368 -
    ) -> Result<(), Error> {
1441 +
    pub fn accept(&mut self, hunks: impl IntoIterator<Item = AcceptedHunk>) -> Result<(), Error> {
1442 +
        self.refresh()?;
1369 1443
        let mut accepted = self.accepted.clone();
1370 1444
        let mut rejected = self.rejected.clone();
1371 1445
        let mut dropped = self.dropped.clone();
1372 1446
        for hunk in hunks {
1373 1447
            rejected.remove(&hunk.commit);
1374 1448
            dropped.remove(&hunk.commit);
1375 1449
            accepted.insert(hunk);
1376 1450
        }
1377 -
        let mut tree = self.repository.tree_id(self.base)?;
1378 -
        for file in files {
1379 -
            tree = self.project_file(tree, &file)?;
1380 -
        }
1451 +
        let tree = self.project_accepted(&accepted)?;
1381 1452
        self.persist(tree, accepted, rejected, dropped)
1382 1453
    }
1383 1454
1384 1455
    /// Marks exact hunks unaccepted and rebuilds the derived tree.
1385 -
    pub fn reject(
1386 -
        &mut self,
1387 -
        rejected: &BTreeSet<AcceptedHunk>,
1388 -
        files: impl IntoIterator<Item = FilePatches>,
1389 -
    ) -> Result<(), Error> {
1456 +
    pub fn reject(&mut self, rejected: &BTreeSet<AcceptedHunk>) -> Result<(), Error> {
1457 +
        self.refresh()?;
1390 1458
        let mut accepted = self.accepted.clone();
1391 1459
        accepted.retain(|hunk| !rejected.contains(hunk));
1392 -
        let mut tree = self.repository.tree_id(self.base)?;
1393 -
        for file in files {
1394 -
            tree = self.project_file(tree, &file)?;
1395 -
        }
1460 +
        let tree = self.project_accepted(&accepted)?;
1396 1461
        self.persist(tree, accepted, self.rejected.clone(), self.dropped.clone())
1397 1462
    }
1398 1463
1399 1464
    /// Toggles the rejected state of one commit.
1400 1465
    pub fn toggle_commit_rejected(&mut self, commit: Oid) -> Result<(), Error> {
1466 +
        self.refresh()?;
1401 1467
        let mut rejected = self.rejected.clone();
1402 1468
        let mut dropped = self.dropped.clone();
1403 1469
        if rejected.remove(&commit).is_none() {
1404 1470
            let decision = self.commit_decision(commit)?;
1405 1471
            rejected.insert(commit, decision);
1409 1475
        self.persist(tree, self.accepted.clone(), rejected, dropped)
1410 1476
    }
1411 1477
1412 1478
    /// Toggles the dropped state of one commit.
1413 1479
    pub fn toggle_commit_dropped(&mut self, commit: Oid) -> Result<(), Error> {
1480 +
        self.refresh()?;
1414 1481
        let mut rejected = self.rejected.clone();
1415 1482
        let mut dropped = self.dropped.clone();
1416 1483
        if dropped.remove(&commit).is_none() {
1417 1484
            let decision = self.commit_decision(commit)?;
1418 1485
            dropped.insert(commit, decision);
1480 1547
            tree = self.project(tree, patch)?;
1481 1548
        }
1482 1549
        Ok(tree)
1483 1550
    }
1484 1551
1552 +
    /// Rebuilds the projected tree from the complete accepted set.
1553 +
    fn project_accepted(&self, accepted: &Accepted) -> Result<Oid, Error> {
1554 +
        let commits = self
1555 +
            .repository
1556 +
            .commits(&Rev::from(self.base), &Rev::from(self.target))?;
1557 +
        let mut tree = self.repository.tree_id(self.base)?;
1558 +
        for (commit, _) in commits {
1559 +
            let diff = self.repository.commit_diff(commit)?;
1560 +
            let document = DiffDocument::decode_bytes(&diff)?.split_hunks();
1561 +
            let identities = self.hunk_identities(&document, commit)?;
1562 +
            for file in &document.files {
1563 +
                let hunks = file
1564 +
                    .hunks
1565 +
                    .iter()
1566 +
                    .filter(|hunk| {
1567 +
                        identities
1568 +
                            .get(&hunk.id)
1569 +
                            .is_some_and(|identity| accepted.contains(identity))
1570 +
                    })
1571 +
                    .cloned()
1572 +
                    .collect::<Vec<_>>();
1573 +
                if hunks.is_empty() {
1574 +
                    continue;
1575 +
                }
1576 +
                tree = self.project_file(tree, &FilePatches::new(file, hunks)?)?;
1577 +
            }
1578 +
        }
1579 +
        Ok(tree)
1580 +
    }
1581 +
1485 1582
    /// Remaps commit-level decisions by exact id, then stable decision identity.
1486 1583
    fn remap_commit_decisions(
1487 1584
        &self,
1488 1585
        commits: &[Commit],
1489 1586
        documents: &[DiffDocument],
1591 1688
        };
1592 1689
        let message = encode_state(&state);
1593 1690
        let commit =
1594 1691
            self.repository
1595 1692
                .commit(tree, self.base, "brain", "brain@example.invalid", &message)?;
1596 -
        self.repository.update_ref(&self.state_ref, commit)?;
1693 +
        if !self
1694 +
            .repository
1695 +
            .compare_and_update_ref(&self.state_ref, commit, Some(self.commit))?
1696 +
        {
1697 +
            return Err(Error::Git(
1698 +
                "review state changed while it was being saved".to_owned(),
1699 +
            ));
1700 +
        }
1597 1701
        self.commit = commit;
1598 1702
        self.accepted = state.accepted;
1599 1703
        self.rejected = state.rejected;
1600 1704
        self.dropped = state.dropped;
1601 1705
1627 1731
    stats
1628 1732
}
1629 1733
1630 1734
/// Returns the patch text used to identify `hunk` across base movement.
1631 1735
fn hunk_identity_patch(file: &FileDiff, hunk: &Hunk) -> Result<String, Error> {
1632 -
    let hunks = (file.header.kind != FileKind::Binary).then(|| hunk.identity());
1736 +
    let hunks = (!matches!(file.header.kind, FileKind::Binary | FileKind::ModeChanged))
1737 +
        .then(|| hunk.identity());
1633 1738
    Ok(DiffDocument::for_hunks(file, hunks).to_unified_string()?)
1634 1739
}
1635 1740
1636 1741
/// Returns each hunk's id and identity patch text, in document order.
1637 1742
fn hunk_identity_patches(document: &DiffDocument) -> Result<Vec<(HunkId, String)>, Error> {
2100 2205
        assert!(backend.brain().unwrap().dropped.is_empty());
2101 2206
2102 2207
        brain.toggle_commit_rejected(commit).unwrap();
2103 2208
        let document = backend.diff_document(commit).unwrap().split_hunks();
2104 2209
        let identities = brain.hunk_identities(&document, commit).unwrap();
2105 -
        let file = &document.files[0];
2106 -
        let patches = FilePatches::new(file, file.hunks.clone()).unwrap();
2107 -
        brain.accept(identities.into_values(), [patches]).unwrap();
2210 +
        brain.accept(identities.into_values()).unwrap();
2108 2211
        let stored = backend.brain().unwrap();
2109 2212
2110 2213
        assert!(stored.rejected.is_empty());
2111 2214
        assert!(stored.dropped.is_empty());
2112 2215
2114 2217
        let history = HistoryStatus::for_commits(&brain, &[(commit, &document, &identities)]);
2115 2218
        assert!(history.progress.is_complete());
2116 2219
        assert_eq!(history.stats, DiffStat::default());
2117 2220
    }
2118 2221
2222 +
    #[test]
2223 +
    fn concurrent_acceptance_rebuilds_tree_from_merged_state() {
2224 +
        let repository = TestRepository::new();
2225 +
        let first_path = repository.path.join("first.txt");
2226 +
        let second_path = repository.path.join("second.txt");
2227 +
        fs::write(&first_path, "base\n").unwrap();
2228 +
        fs::write(&second_path, "base\n").unwrap();
2229 +
        repository.git(&["add", "first.txt", "second.txt"]);
2230 +
        repository.git(&["commit", "-q", "-m", "base"]);
2231 +
        repository.git(&["switch", "-q", "-c", "topic"]);
2232 +
        fs::write(&first_path, "accepted first\n").unwrap();
2233 +
        repository.git(&["commit", "-q", "-am", "first"]);
2234 +
        fs::write(&second_path, "accepted second\n").unwrap();
2235 +
        repository.git(&["commit", "-q", "-am", "second"]);
2236 +
2237 +
        let backend = GitBackend::new(
2238 +
            &repository.path,
2239 +
            Rev::try_from("main").unwrap(),
2240 +
            Rev::try_from("topic").unwrap(),
2241 +
        )
2242 +
        .unwrap();
2243 +
        let commits = backend.commits().unwrap();
2244 +
        let documents = commits
2245 +
            .iter()
2246 +
            .map(|commit| backend.diff_document(commit.id).unwrap().split_hunks())
2247 +
            .collect::<Vec<_>>();
2248 +
        let mut first = backend.reset_brain().unwrap();
2249 +
        let mut second = backend.brain().unwrap();
2250 +
        let first_identity = first
2251 +
            .hunk_identities(&documents[0], commits[0].id)
2252 +
            .unwrap()
2253 +
            .into_values()
2254 +
            .next()
2255 +
            .unwrap();
2256 +
        let second_identity = second
2257 +
            .hunk_identities(&documents[1], commits[1].id)
2258 +
            .unwrap()
2259 +
            .into_values()
2260 +
            .next()
2261 +
            .unwrap();
2262 +
2263 +
        first.accept([first_identity]).unwrap();
2264 +
        second.accept([second_identity]).unwrap();
2265 +
2266 +
        let stored = backend.brain().unwrap();
2267 +
        let first_object = format!("{}:first.txt", stored.commit);
2268 +
        let second_object = format!("{}:second.txt", stored.commit);
2269 +
        assert_eq!(
2270 +
            repository.git_output(&["show", &first_object]),
2271 +
            b"accepted first\n"
2272 +
        );
2273 +
        assert_eq!(
2274 +
            repository.git_output(&["show", &second_object]),
2275 +
            b"accepted second\n"
2276 +
        );
2277 +
    }
2278 +
2279 +
    #[test]
2280 +
    fn projected_tree_matches_split_review_hunk_identities() {
2281 +
        let repository = TestRepository::new();
2282 +
        let path = repository.path.join("reviewed.txt");
2283 +
        fs::write(&path, "one\ntwo\nthree\nfour\nfive\nsix\nseven\n").unwrap();
2284 +
        repository.git(&["add", "reviewed.txt"]);
2285 +
        repository.git(&["commit", "-q", "-m", "base"]);
2286 +
        repository.git(&["switch", "-q", "-c", "topic"]);
2287 +
        fs::write(&path, "one\nTWO\nthree\nfour\nfive\nSIX\nseven\n").unwrap();
2288 +
        repository.git(&["commit", "-q", "-am", "two changes"]);
2289 +
2290 +
        let backend = GitBackend::new(
2291 +
            &repository.path,
2292 +
            Rev::try_from("main").unwrap(),
2293 +
            Rev::try_from("topic").unwrap(),
2294 +
        )
2295 +
        .unwrap();
2296 +
        let commit = backend.commits().unwrap().pop().unwrap();
2297 +
        let document = backend.diff_document(commit.id).unwrap().split_hunks();
2298 +
        assert_eq!(document.files[0].hunks.len(), 2);
2299 +
        let mut brain = backend.reset_brain().unwrap();
2300 +
        let identities = brain.hunk_identities(&document, commit.id).unwrap();
2301 +
        let accepted = identities[&document.files[0].hunks[1].id].clone();
2302 +
2303 +
        brain.accept([accepted]).unwrap();
2304 +
2305 +
        let object = format!("{}:reviewed.txt", brain.commit);
2306 +
        assert_eq!(
2307 +
            repository.git_output(&["show", &object]),
2308 +
            b"one\ntwo\nthree\nfour\nfive\nSIX\nseven\n"
2309 +
        );
2310 +
    }
2311 +
2312 +
    #[test]
2313 +
    fn implicit_base_uses_trunk_branch_identity() {
2314 +
        let repository = TestRepository::new();
2315 +
        let reviewed = repository.path.join("reviewed.txt");
2316 +
        fs::write(&reviewed, "base\n").unwrap();
2317 +
        repository.git(&["add", "reviewed.txt"]);
2318 +
        repository.git(&["commit", "-q", "-m", "base"]);
2319 +
        repository.git(&["switch", "-q", "-c", "topic"]);
2320 +
        fs::write(&reviewed, "change\n").unwrap();
2321 +
        repository.git(&["commit", "-q", "-am", "change"]);
2322 +
2323 +
        assert_eq!(
2324 +
            branch_base(&repository.path, &Rev::try_from("topic").unwrap()).unwrap(),
2325 +
            Rev::try_from("main").unwrap()
2326 +
        );
2327 +
    }
2328 +
2119 2329
    #[test]
2120 2330
    fn rebase_keeps_unchanged_hunk_acceptance_after_amend() {
2121 2331
        let repository = TestRepository::new();
2122 2332
        let reviewed = repository.path.join("reviewed.txt");
2123 2333
        let amended = repository.path.join("amended.txt");
2145 2355
                    .display_path()
2146 2356
                    .is_some_and(|path| path == Path::new("reviewed.txt"))
2147 2357
            })
2148 2358
            .unwrap();
2149 2359
        let first_identity = first_identities[&first_file.hunks[0].id].clone();
2150 -
        let first_patches = FilePatches::new(first_file, first_file.hunks.clone()).unwrap();
2151 -
        brain.accept([first_identity], [first_patches]).unwrap();
2360 +
        brain.accept([first_identity]).unwrap();
2152 2361
2153 2362
        fs::write(&amended, "second\n").unwrap();
2154 2363
        repository.git(&["commit", "-q", "-am", "T2", "--amend"]);
2155 2364
        let second = backend.commits().unwrap().pop().unwrap();
2156 2365
        let second_document = backend.diff_document(second.id).unwrap().split_hunks();
f +0 -0
new.rs +0 -0
image.png +0 -0
new.txt +0 -0
crates/brain/src/comments.rs +48 -0
214 214
    /// Returns the author name used for newly authored comments.
215 215
    pub fn author(&self) -> &str {
216 216
        &self.author
217 217
    }
218 218
219 +
    /// Selects the author name used for newly authored comments.
220 +
    pub(crate) fn set_author(&mut self, author: String) {
221 +
        if !author.trim().is_empty() {
222 +
            self.author = author;
223 +
        }
224 +
    }
225 +
219 226
    /// Returns the number of stored comment rows.
220 227
    pub fn len(&self) -> usize {
221 228
        self.records.len()
222 229
    }
223 230
323 330
            .max()
324 331
            .unwrap_or_default()
325 332
            .saturating_add(1);
326 333
        CommentId::from(next)
327 334
    }
335 +
336 +
    /// Applies the difference between two snapshots without replacing unrelated rows.
337 +
    pub(crate) fn merge(&mut self, previous: &Self, updated: &Self) {
338 +
        for record in &previous.records {
339 +
            if !updated
340 +
                .records
341 +
                .iter()
342 +
                .any(|candidate| candidate.id == record.id)
343 +
            {
344 +
                self.delete(&record.id);
345 +
            }
346 +
        }
347 +
        for record in &updated.records {
348 +
            match previous
349 +
                .records
350 +
                .iter()
351 +
                .find(|candidate| candidate.id == record.id)
352 +
            {
353 +
                Some(previous) if previous != record => {
354 +
                    if let Some(current) = self
355 +
                        .records
356 +
                        .iter_mut()
357 +
                        .find(|candidate| candidate.id == record.id)
358 +
                    {
359 +
                        *current = record.clone();
360 +
                    }
361 +
                }
362 +
                None => {
363 +
                    let mut added = record.clone();
364 +
                    added.id = self.next_id();
365 +
                    self.records.push(added);
366 +
                }
367 +
                _ => {}
368 +
            }
369 +
        }
370 +
    }
328 371
}
329 372
330 373
impl From<&CommentRecord> for Comment {
331 374
    fn from(record: &CommentRecord) -> Self {
332 375
        Self {
462 505
        self.by_hunk
463 506
            .iter()
464 507
            .map(|(hunk, comments)| (*hunk, comments.len()))
465 508
            .collect()
466 509
    }
510 +
511 +
    /// Rebuilds this per-hunk view from an updated review-wide store.
512 +
    pub fn refresh(&mut self, store: &ReviewComments) {
513 +
        *self = Self::new(store, self.targets.clone());
514 +
    }
467 515
}
468 516
469 517
/// Encodes arbitrary review identity text as one path or refname component.
470 518
pub(crate) fn encode_component(input: &str) -> String {
471 519
    let mut encoded = String::new();
crates/brain/src/main.rs +15 -8
273 273
    Loaded(Box<LoadedReview>),
274 274
}
275 275
276 276
/// Executes one blocking startup command on a worker thread.
277 277
fn execute_startup(command: StartupCommand) -> Result<StartupOutput, Error> {
278 -
    let (backend, brain) = match command {
278 +
    let (backend, brain, commits) = match command {
279 279
        StartupCommand::Open {
280 280
            cwd,
281 281
            base,
282 282
            target,
283 283
            state,
285 285
            let base = match base {
286 286
                Some(base) => base,
287 287
                None => backend::branch_base(&cwd, &target)?,
288 288
            };
289 289
            let backend = <dyn backend::Backend>::from_path(&cwd, base, target)?;
290 +
            let commits = backend.commits()?;
291 +
            if commits.is_empty() {
292 +
                return Err(Error::Empty);
293 +
            }
290 294
            let brain = match state {
291 295
                ReviewStateLoad::Existing => match backend.brain() {
292 296
                    Ok(brain) => brain,
293 297
                    Err(Error::StaleReviewState) => return Ok(StartupOutput::Stale(backend)),
294 298
                    Err(error) => return Err(error),
295 299
                },
296 300
                ReviewStateLoad::Fresh => backend.reset_brain()?,
297 301
                ReviewStateLoad::Rebase => backend.rebase_brain()?,
298 302
            };
299 -
            (backend, brain)
303 +
            (backend, brain, commits)
300 304
        }
301 305
        StartupCommand::Resolve { backend, action } => {
306 +
            let commits = backend.commits()?;
307 +
            if commits.is_empty() {
308 +
                return Err(Error::Empty);
309 +
            }
302 310
            let brain = match action {
303 311
                StaleReviewStateAction::Rebase => backend.rebase_brain()?,
304 312
                StaleReviewStateAction::Reset => backend.reset_brain()?,
305 313
                StaleReviewStateAction::Quit => return Ok(StartupOutput::Stale(backend)),
306 314
            };
307 -
            (backend, brain)
315 +
            (backend, brain, commits)
308 316
        }
309 317
    };
310 318
    let persisted = brain.read_comments()?;
311 -
    let comments = ReviewComments::parse(persisted.as_deref().unwrap_or_default())?;
312 -
    let commits = backend.commits()?;
313 -
    if commits.is_empty() {
314 -
        return Err(Error::Empty);
319 +
    let mut comments = ReviewComments::parse(persisted.as_deref().unwrap_or_default())?;
320 +
    if let Some(author) = brain.comment_author()? {
321 +
        comments.set_author(author);
315 322
    }
316 323
    Ok(StartupOutput::Loaded(Box::new(LoadedReview {
317 324
        backend,
318 325
        brain,
319 326
        comments,
515 522
516 523
/// Prints the history view for the commits in `base..target`.
517 524
fn run_range_status(base: Rev, target: Rev) -> Result<(), Error> {
518 525
    let cwd = env::current_dir()?;
519 526
    let backend = <dyn backend::Backend>::from_path(&cwd, base, target)?;
520 -
    let brain = backend.brain()?;
521 527
    let commits = backend.commits()?;
522 528
    if commits.is_empty() {
523 529
        return Err(Error::Empty);
524 530
    }
531 +
    let brain = backend.brain()?;
525 532
    let comments = ReviewComments::parse(brain.read_comments()?.as_deref().unwrap_or_default())?;
526 533
    let width = status_width();
527 534
    let table = session::history_output_table(
528 535
        commits,
529 536
        &*backend,
crates/brain/src/session.rs +114 -88
17 17
    MouseButton, Rect, ScrollView, Style, Table, TableOptions, Terminal,
18 18
};
19 19
use rustik_tui_termion as tui_termion;
20 20
21 21
use crate::backend::{
22 -
    Accepted, Backend, Brain, Commit, CommitHunks, CommitReviewState, FilePatches, HistoryStatus,
22 +
    Accepted, Backend, Brain, Commit, CommitHunks, CommitReviewState, HistoryStatus,
23 23
};
24 24
use crate::comments::{Comments, ReviewComments};
25 25
use crate::error::Error;
26 26
use crate::review::{FileVisibility, HunkVisibility, Visibility};
27 27
38 38
use status::{
39 39
    ActionContext, Chrome, HISTORY_DIFFSTAT_MAX_WIDTH, SELECTED_COMMIT_BG, Status, StatusContext,
40 40
    commit_row, commit_row_suffix, current_timestamp, viewer_area,
41 41
};
42 42
use worker::{
43 -
    Command as WorkerCommand, LoadCommit, Output as WorkerOutput, ReviewMutation, Worker,
43 +
    Command as WorkerCommand, LoadCommit, Output as WorkerOutput, Persisted, ReviewMutation, Worker,
44 44
};
45 45
46 46
/// Terminal backend used by the interactive viewer.
47 47
type BrainTerminal = Terminal<tui_termion::TermionBackend<tui_termion::term::TerminalScreen>>;
48 48
462 462
    ToggleDrop,
463 463
    /// Delete the selected hunk comment.
464 464
    DeleteComment,
465 465
}
466 466
467 +
/// Hunk editor retained with the commit that owns it.
468 +
struct ParkedHunk {
469 +
    /// Index of the owning commit.
470 +
    commit: usize,
471 +
    /// Retained hunk view and draft.
472 +
    view: Box<HunkView>,
473 +
}
467 474
/// Interactive terminal session state.
468 475
struct Session<'a, T: TuiBackend<Error = io::Error>> {
469 476
    /// Terminal frame target.
470 477
    terminal: &'a mut Terminal<T>,
471 478
    /// Per-commit review slots, newest first.
484 491
    current: usize,
485 492
    /// Set of hunks visible across commit viewers.
486 493
    hunk_visibility: HunkVisibility,
487 494
    /// Active view: the commit list, the diff, or a hunk's comment box.
488 495
    mode: Mode,
489 -
    /// Hunk view kept alive while another tab is active, for Tab round-trips.
490 -
    parked: Option<Box<HunkView>>,
496 +
    /// Hunk view kept alive while another tab or commit is active.
497 +
    parked: Option<ParkedHunk>,
491 498
    /// Selection and scroll state for the commit-list tab.
492 499
    list: ListState,
493 500
    /// Viewer options used to build commit and per-hunk viewers.
494 501
    options: DiffOptions,
495 502
    /// Git contexts used only by background highlighters.
880 887
        Ok(Control::Redraw)
881 888
    }
882 889
883 890
    /// Displays the commit at `index`, loading it and respawning workers.
884 891
    fn select_commit(&mut self, index: usize) -> Result<(), Error> {
885 -
        if index != self.current {
886 -
            self.parked = None;
887 -
        }
888 892
        self.current = index;
889 893
        self.mode = Mode::Diff;
890 894
        if self.commits[index].loaded.is_some() {
891 895
            self.activate()?;
892 896
        } else {
983 987
984 988
    /// Toggles acceptance of the focused hunk.
985 989
    fn toggle_focused_hunk(&mut self, area: Rect) -> Result<(), Error> {
986 990
        let current = self.current;
987 991
        let pending_only = matches!(self.hunk_visibility, HunkVisibility::Pending);
992 +
        if !self.current()?.viewer.focused_hunk_visible(area) {
993 +
            self.error = Some("focused hunk is not visible".to_owned());
994 +
            return Ok(());
995 +
        }
988 996
        let before = self.current()?.viewer.state().clone();
989 997
        let loaded = self.current()?;
990 998
        let Some(DiffFocus::Hunk(hunk)) = loaded.viewer.state().focus else {
991 999
            return Ok(());
992 1000
        };
1096 1104
        accepted.extend(identities.iter().cloned());
1097 1105
1098 1106
        let mut undo = self.accepted.clone();
1099 1107
        undo.extend(hunks);
1100 1108
1101 -
        self.persist_acceptance(accepted, undo, move |patches| ReviewMutation::Accept {
1102 -
            identities,
1103 -
            patches,
1104 -
        })
1109 +
        self.persist_acceptance(accepted, undo, ReviewMutation::Accept { identities })
1105 1110
    }
1106 1111
1107 1112
    /// Optimistically rejects the selected hunks and starts persistence.
1108 1113
    fn reject_hunks(&mut self, hunks: BTreeSet<HunkLocation>) -> Result<(), Error> {
1109 1114
        let identities = hunks
1121 1126
        accepted.retain(|identity| !identities.contains(identity));
1122 1127
1123 1128
        let mut undo = self.accepted.clone();
1124 1129
        undo.retain(|hunk| !hunks.contains(hunk));
1125 1130
1126 -
        self.persist_acceptance(accepted, undo, move |patches| ReviewMutation::Reject {
1127 -
            identities,
1128 -
            patches,
1129 -
        })
1131 +
        self.persist_acceptance(accepted, undo, ReviewMutation::Reject { identities })
1130 1132
    }
1131 1133
1132 1134
    /// Records automatic navigation for the pending rollback.
1133 1135
    fn record_navigation_rollback(
1134 1136
        &mut self,
1144 1146
            });
1145 1147
        }
1146 1148
        Ok(())
1147 1149
    }
1148 1150
1149 -
    /// Shows optimistic state, prepares its projection, and starts persistence.
1151 +
    /// Shows optimistic state and starts persistence.
1150 1152
    fn persist_acceptance(
1151 1153
        &mut self,
1152 1154
        accepted: Accepted,
1153 1155
        undo: Vec<HunkLocation>,
1154 -
        mutation: impl FnOnce(Vec<FilePatches>) -> ReviewMutation,
1156 +
        mutation: ReviewMutation,
1155 1157
    ) -> Result<(), Error> {
1156 1158
        debug_assert!(self.pending.is_none());
1157 1159
1158 1160
        let rollback = self.brain.clone();
1159 1161
        self.brain.rollback(accepted);
1161 1163
            self.brain = rollback;
1162 1164
            self.reconcile_state();
1163 1165
            return Err(error);
1164 1166
        }
1165 1167
1166 -
        let result = (|| -> Result<(), Error> {
1167 -
            let mut patches = Vec::new();
1168 -
            for slot in &self.commits {
1169 -
                let identities = slot.identities()?;
1170 -
                let document = slot.document()?;
1171 -
                for file in &document.files {
1172 -
                    let hunks = file
1173 -
                        .hunks
1174 -
                        .iter()
1175 -
                        .filter(|hunk| {
1176 -
                            identities
1177 -
                                .get(&hunk.id)
1178 -
                                .is_some_and(|identity| self.brain.accepted.contains(identity))
1179 -
                        })
1180 -
                        .cloned()
1181 -
                        .collect::<Vec<_>>();
1182 -
                    if !hunks.is_empty() {
1183 -
                        let patch = FilePatches::new(file, hunks)?;
1184 -
                        patches.push(patch);
1185 -
                    }
1186 -
                }
1187 -
            }
1188 -
1189 -
            self.repository_worker
1190 -
                .send(WorkerCommand::Mutate(mutation(patches)))
1191 -
                .map_err(Error::Git)
1192 -
        })();
1168 +
        let result = self
1169 +
            .repository_worker
1170 +
            .send(WorkerCommand::Mutate(mutation))
1171 +
            .map_err(Error::Git);
1193 1172
        if let Err(error) = result {
1194 1173
            self.brain = rollback;
1195 1174
            self.reconcile_reviews()?;
1196 1175
            return Err(error);
1197 1176
        }
1203 1182
        }));
1204 1183
        Ok(())
1205 1184
    }
1206 1185
1207 1186
    /// Finalizes one persisted state mutation or restores its optimistic state.
1208 -
    fn finish_persistence(&mut self, result: Result<Option<Brain>, String>) -> Result<(), Error> {
1187 +
    fn finish_persistence(&mut self, result: Result<Persisted, String>) -> Result<(), Error> {
1209 1188
        let Some(pending) = self.pending.take() else {
1210 1189
            return Err(Error::Git(
1211 1190
                "persistence completed without pending state".to_owned(),
1212 1191
            ));
1213 1192
        };
1214 -
        let committed = match result {
1215 -
            Ok(committed) => committed,
1193 +
        let persisted = match result {
1194 +
            Ok(persisted) => persisted,
1216 1195
            Err(message) => {
1217 1196
                match pending {
1218 1197
                    Pending::Acceptance(pending) => {
1219 1198
                        let navigation = pending.navigation.and_then(|navigation| {
1220 1199
                            let loaded = self.commits.get(navigation.commit)?.loaded.as_ref()?;
1240 1219
                return Ok(());
1241 1220
            }
1242 1221
        };
1243 1222
        match pending {
1244 1223
            Pending::Acceptance(pending) => {
1245 -
                let Some(brain) = committed else {
1224 +
                let Persisted::Review(brain) = persisted else {
1246 1225
                    return Err(Error::Git(
1247 -
                        "review persistence completed without review state".to_owned(),
1226 +
                        "review persistence returned comment state".to_owned(),
1248 1227
                    ));
1249 1228
                };
1250 -
                self.brain = brain;
1229 +
                self.brain = *brain;
1251 1230
                self.accepted = pending.undo;
1252 1231
            }
1253 1232
            Pending::Decision => {
1254 -
                let Some(brain) = committed else {
1233 +
                let Persisted::Review(brain) = persisted else {
1255 1234
                    return Err(Error::Git(
1256 -
                        "decision persistence completed without review state".to_owned(),
1235 +
                        "decision persistence returned comment state".to_owned(),
1257 1236
                    ));
1258 1237
                };
1259 -
                self.brain = brain;
1238 +
                self.brain = *brain;
1260 1239
                self.reconcile_reviews()?;
1261 1240
            }
1262 1241
            Pending::Comments(_) => {
1263 -
                debug_assert!(committed.is_none());
1242 +
                let Persisted::Comments(comments) = persisted else {
1243 +
                    return Err(Error::Git(
1244 +
                        "comment persistence returned review state".to_owned(),
1245 +
                    ));
1246 +
                };
1247 +
                self.comments = comments;
1248 +
                for slot in &mut self.commits {
1249 +
                    if let Some(loaded) = &mut slot.loaded {
1250 +
                        loaded.comments.refresh(&self.comments);
1251 +
                        loaded.refresh_decorations();
1252 +
                    }
1253 +
                }
1264 1254
            }
1265 1255
        }
1266 1256
        Ok(())
1267 1257
    }
1268 1258
1275 1265
            self.current()?.viewer.apply(DiffAction::NextHunk, area);
1276 1266
        }
1277 1267
        let Some(DiffFocus::Hunk(hunk)) = self.current()?.viewer.state().focus else {
1278 1268
            return Ok(());
1279 1269
        };
1280 -
        // Resume a parked draft on the same hunk instead of discarding it.
1281 -
        if let Some(mut parked) = self.parked.take_if(|parked| parked.hunk == hunk) {
1282 -
            if !parked.is_editing() {
1283 -
                parked.enter();
1270 +
        // Resume a parked draft on the same commit and hunk.
1271 +
        if let Some(parked) = self
1272 +
            .parked
1273 +
            .take_if(|parked| parked.commit == self.current && parked.view.hunk == hunk)
1274 +
        {
1275 +
            let mut view = parked.view;
1276 +
            if !view.is_editing() {
1277 +
                view.enter();
1284 1278
            }
1285 -
            self.mode = Mode::Hunk(parked);
1279 +
            self.mode = Mode::Hunk(view);
1286 1280
            self.restart_highlighter()?;
1287 1281
            return Ok(());
1288 1282
        }
1289 -
        self.parked = None;
1290 1283
        let mut options = self.options.clone();
1291 1284
        options.file_tree = FileTreeMode::Hidden;
1292 1285
        options.hunk_focus = HunkFocus::Plain;
1293 1286
1294 1287
        let loaded = self.current()?;
1338 1331
        Ok(())
1339 1332
    }
1340 1333
1341 1334
    /// Switches to the next review tab, parking any open hunk view.
1342 1335
    fn next_tab(&mut self) -> Result<(), Error> {
1343 -
        let opens_history = matches!(&self.mode, Mode::Hunk(_))
1344 -
            || matches!(&self.mode, Mode::Diff) && self.parked.is_none();
1336 +
        let parked_here = self
1337 +
            .parked
1338 +
            .as_ref()
1339 +
            .is_some_and(|parked| parked.commit == self.current);
1340 +
        let opens_history =
1341 +
            matches!(&self.mode, Mode::Hunk(_)) || matches!(&self.mode, Mode::Diff) && !parked_here;
1345 1342
        if opens_history {
1346 1343
            self.ensure_history_status()?;
1347 1344
            self.stop_highlighter();
1348 1345
        }
1349 1346
        match mem::replace(&mut self.mode, Mode::Diff) {
1350 1347
            Mode::Commits => {
1351 1348
                self.select_commit(self.list.selected())?;
1352 1349
            }
1353 1350
            Mode::Diff => {
1354 -
                if let Some(parked) = self.parked.take() {
1355 -
                    self.mode = Mode::Hunk(parked);
1351 +
                if parked_here {
1352 +
                    let Some(parked) = self.parked.take() else {
1353 +
                        return Err(Error::Git("parked hunk view is missing".to_owned()));
1354 +
                    };
1355 +
                    self.mode = Mode::Hunk(parked.view);
1356 1356
                    self.restart_highlighter()?;
1357 1357
                } else {
1358 1358
                    self.list.select(self.current, self.commits.len());
1359 1359
                    self.mode = Mode::Commits;
1360 1360
                }
1361 1361
            }
1362 1362
            Mode::Hunk(view) => {
1363 -
                self.parked = Some(view);
1363 +
                self.parked = Some(ParkedHunk {
1364 +
                    commit: self.current,
1365 +
                    view,
1366 +
                });
1364 1367
                self.list.select(self.current, self.commits.len());
1365 1368
                self.mode = Mode::Commits;
1366 1369
            }
1367 1370
        }
1368 1371
        Ok(())
1462 1465
            return Ok(());
1463 1466
        };
1464 1467
        let hunk = view.hunk;
1465 1468
        let Some((target, body)) = view.pending_edit() else {
1466 1469
            view.cancel_edit();
1470 +
            if self.hunk_comment_count() == 0 {
1471 +
                self.mode = Mode::Diff;
1472 +
            }
1467 1473
            return Ok(());
1468 1474
        };
1469 1475
        let Some(loaded) = &mut self.commits[self.current].loaded else {
1470 1476
            return Ok(());
1471 1477
        };
1473 1479
        let rollback = CommentRollback {
1474 1480
            commit: self.current,
1475 1481
            store: self.comments.clone(),
1476 1482
            comments: loaded.comments.clone(),
1477 1483
        };
1478 -
        let encoded =
1479 -
            loaded
1480 -
                .comments
1481 -
                .transact(&mut self.comments, |comments, store| match target {
1482 -
                    CommentEdit::Add => comments.author(store, hunk, body),
1483 -
                    CommentEdit::Edit(id) => comments.edit(store, hunk, &id, body),
1484 -
                });
1485 -
        if let Some(encoded) = encoded {
1486 -
            if let Err(message) = self
1487 -
                .repository_worker
1488 -
                .send(WorkerCommand::WriteComments { encoded })
1489 -
            {
1484 +
        let changed = loaded
1485 +
            .comments
1486 +
            .transact(&mut self.comments, |comments, store| match target {
1487 +
                CommentEdit::Add => comments.author(store, hunk, body),
1488 +
                CommentEdit::Edit(id) => comments.edit(store, hunk, &id, body),
1489 +
            })
1490 +
            .is_some();
1491 +
        if changed {
1492 +
            if let Err(message) = self.repository_worker.send(WorkerCommand::WriteComments {
1493 +
                previous: rollback.store.clone(),
1494 +
                updated: self.comments.clone(),
1495 +
            }) {
1490 1496
                self.comments = rollback.store;
1491 1497
                loaded.comments = rollback.comments;
1492 1498
                loaded.refresh_decorations();
1493 1499
                return Err(Error::Git(message));
1494 1500
            }
1518 1524
    /// Returns rendered comment rows for the active hunk view.
1519 1525
    fn hunk_comment_rows(&self) -> usize {
1520 1526
        let Mode::Hunk(view) = &self.mode else {
1521 1527
            return 0;
1522 1528
        };
1523 -
        view.comment_rows(self.hunk_comment_count())
1529 +
        let comments = self.commits[self.current]
1530 +
            .loaded
1531 +
            .as_ref()
1532 +
            .map_or(&[][..], |loaded| loaded.comments.for_hunk(view.hunk));
1533 +
        view.comment_rows(comments)
1524 1534
    }
1525 1535
1526 1536
    /// Returns whether an event should scroll the nested hunk diff viewer.
1527 1537
    fn hunk_scroll_event(event: &Event<()>) -> bool {
1528 1538
        if Self::non_text_hunk_scroll_event(event) {
1584 1594
        let rollback = CommentRollback {
1585 1595
            commit: self.current,
1586 1596
            store: self.comments.clone(),
1587 1597
            comments: loaded.comments.clone(),
1588 1598
        };
1589 -
        let encoded = loaded
1599 +
        let changed = loaded
1590 1600
            .comments
1591 1601
            .transact(&mut self.comments, |comments, store| {
1592 1602
                comments.delete(store, hunk, &id)
1593 -
            });
1594 -
        if let Some(encoded) = encoded {
1595 -
            if let Err(message) = self
1596 -
                .repository_worker
1597 -
                .send(WorkerCommand::WriteComments { encoded })
1598 -
            {
1603 +
            })
1604 +
            .is_some();
1605 +
        if changed {
1606 +
            if let Err(message) = self.repository_worker.send(WorkerCommand::WriteComments {
1607 +
                previous: rollback.store.clone(),
1608 +
                updated: self.comments.clone(),
1609 +
            }) {
1599 1610
                self.comments = rollback.store;
1600 1611
                loaded.comments = rollback.comments;
1601 1612
                loaded.refresh_decorations();
1602 1613
                return Err(Error::Git(message));
1603 1614
            }
1890 1901
            );
1891 1902
            (
1892 1903
                StatusContext::Commit {
1893 1904
                    short: slot.commit.id.short(),
1894 1905
                    summary: slot.commit.summary.clone(),
1906 +
                    state: slot.state,
1895 1907
                },
1896 1908
                progress,
1897 1909
                stats,
1898 1910
            )
1899 1911
        };
1909 1921
                loading: self.loading.map(|operation| (operation, self.spinner)),
1910 1922
            },
1911 1923
            actions: self.action_context(),
1912 1924
        }
1913 1925
    }
1914 -
1915 1926
    /// Returns the action-bar context for the current session mode.
1916 1927
    fn action_context(&self) -> ActionContext {
1928 +
        let rejected = matches!(
1929 +
            self.commits[self.current].state,
1930 +
            CommitReviewState::Rejected
1931 +
        );
1917 1932
        match &self.mode {
1918 1933
            Mode::Commits => ActionContext::Commits,
1919 -
            Mode::Diff => ActionContext::Commit,
1934 +
            Mode::Diff => {
1935 +
                let area = viewer_area(self.terminal.area());
1936 +
                let loaded = self.commits[self.current].loaded.as_ref();
1937 +
                let can_accept_hunk = loaded.is_none_or(|loaded| {
1938 +
                    !matches!(loaded.viewer.state().focus, Some(DiffFocus::Hunk(_)))
1939 +
                        || loaded.viewer.focused_hunk_visible(area)
1940 +
                });
1941 +
                ActionContext::Commit {
1942 +
                    rejected,
1943 +
                    can_accept_hunk,
1944 +
                }
1945 +
            }
1920 1946
            Mode::Hunk(view) if view.is_editing() => ActionContext::HunkEdit,
1921 -
            Mode::Hunk(_) => ActionContext::HunkBrowse,
1947 +
            Mode::Hunk(_) => ActionContext::HunkBrowse { rejected },
1922 1948
        }
1923 1949
    }
1924 1950
}
1925 1951
1926 1952
#[cfg(test)]
a.rs +0 -0
crates/brain/src/session/hunk.rs +15 -10
5 5
    Buffer, Color, Constraint, Line, Rect, RenderResult, Scroll, Size, StatefulWidget, Style,
6 6
    TextField, TextInput, Widget,
7 7
};
8 8
9 9
use super::status::{
10 -
    COMMENT_CARD_CHROME_COLS, COMMENT_CARD_CHROME_ROWS, COMMENT_CARD_ROWS, comment_age,
11 -
    comment_card_lines, comment_editor_lines,
10 +
    COMMENT_CARD_CHROME_COLS, COMMENT_CARD_CHROME_ROWS, comment_age, comment_card_lines,
11 +
    comment_editor_lines,
12 12
};
13 13
use crate::comments::{Comment, CommentId};
14 14
15 15
/// Maximum rows the comment input grows to.
16 16
const MAX_INPUT_ROWS: usize = 6;
172 172
    /// Returns the area occupied by the isolated hunk viewer.
173 173
    pub(super) fn viewer_area(&self, area: Rect, comment_rows: usize) -> Rect {
174 174
        self.areas(area, comment_rows).0
175 175
    }
176 176
177 -
    /// Returns rendered rows needed for `comments` stored cards and the editor.
177 +
    /// Returns rendered rows needed for stored cards and the editor.
178 178
    ///
179 179
    /// A comment being edited is rendered as the editor card in its place, so
180 180
    /// it does not count towards the stored cards.
181 -
    pub(super) fn comment_rows(&self, comments: usize) -> usize {
182 -
        let stored = match &self.mode {
181 +
    pub(super) fn comment_rows(&self, comments: &[Comment]) -> usize {
182 +
        let edited = match &self.mode {
183 183
            HunkMode::Editing {
184 -
                target: CommentEdit::Edit(_),
184 +
                target: CommentEdit::Edit(id),
185 185
                ..
186 -
            } => comments.saturating_sub(1),
187 -
            _ => comments,
186 +
            } => Some(id),
187 +
            _ => None,
188 188
        };
189 -
        (stored * COMMENT_CARD_ROWS).min(MAX_COMMENT_ROWS) + self.editor_rows()
189 +
        let stored = comments
190 +
            .iter()
191 +
            .filter(|comment| edited != Some(&comment.id))
192 +
            .map(|comment| COMMENT_CARD_CHROME_ROWS + comment.body.lines().count().max(1))
193 +
            .sum::<usize>();
194 +
        stored.min(MAX_COMMENT_ROWS) + self.editor_rows()
190 195
    }
191 196
192 197
    /// Returns the number of table-body rows needed by the active editor.
193 198
    fn editor_body_rows(&self) -> usize {
194 199
        match &self.mode {
296 301
    ) -> RenderResult {
297 302
        if area.is_empty() {
298 303
            return RenderResult::default();
299 304
        }
300 305
        self.clamp_selection(comments.len());
301 -
        let (hunk_area, comments_area) = self.areas(area, self.comment_rows(comments.len()));
306 +
        let (hunk_area, comments_area) = self.areas(area, self.comment_rows(comments));
302 307
        let mut result = RenderResult::default();
303 308
        if self.scroll_to_bottom {
304 309
            self.viewer
305 310
                .apply(DiffAction::Scroll(Scroll::Bottom), hunk_area);
306 311
            self.scroll_to_bottom = false;
a.txt +0 -0
crates/brain/src/session/status.rs +88 -21
94 94
    ("q", "quit"),
95 95
];
96 96
/// Action hints shown in commit diff mode.
97 97
const COMMIT_ACTIONS: &[(&str, &str)] = &[
98 98
    (TAB_KEY, "history"),
99 +
    ("q", "quit"),
99 100
    ("j/k", "hunk"),
100 101
    ("n/p", "file"),
101 102
    ("a", "accept hunk"),
102 103
    ("r", "reject commit"),
103 104
    ("d", "drop commit"),
119 120
    (RETURN_KEY, "newline"),
120 121
    (CTRL_RETURN_KEY, "save"),
121 122
    ("esc", "cancel"),
122 123
    (TAB_KEY, "history"),
123 124
];
124 -
/// Rendered rows in one stored comment card.
125 -
pub(super) const COMMENT_CARD_ROWS: usize = 4;
126 125
/// Rows of card chrome around a comment body: the top border, the header row,
127 126
/// and the bottom border.
128 127
pub(super) const COMMENT_CARD_CHROME_ROWS: usize = 3;
129 128
/// Columns of card chrome on each side of a comment body: the border and its
130 129
/// padding.
137 136
    Commit {
138 137
        /// Abbreviated commit hash.
139 138
        short: String,
140 139
        /// First line of the commit message.
141 140
        summary: String,
141 +
        /// Final review decision for this commit.
142 +
        state: CommitReviewState,
142 143
    },
143 144
    /// Reviewed revision range.
144 145
    Range(String),
145 146
}
146 147
214 215
            Line::new(Label::from_char(spinner).fg(FOOTER_VALUE_FG))
215 216
                .item(Label::space())
216 217
                .item(Label::new(operation).fg(FOOTER_VALUE_FG))
217 218
        } else {
218 219
            match &self.context {
219 -
                StatusContext::Commit { short, summary } => Line::blank()
220 -
                    .item(Label::new(short).fg(FOOTER_HASH_FG))
221 -
                    .item(Label::space())
222 -
                    .item(Label::new(summary).fg(FOOTER_SUMMARY_FG)),
220 +
                StatusContext::Commit {
221 +
                    short,
222 +
                    summary,
223 +
                    state,
224 +
                } => {
225 +
                    let (marker, color) = match state {
226 +
                        CommitReviewState::Accepted => (REVIEWED_MARK, self.palette.positive_fg),
227 +
                        CommitReviewState::Rejected => (REJECTED_MARK, self.palette.negative_fg),
228 +
                        CommitReviewState::Dropped => (DROPPED_MARK, colors::fixed::MUTED),
229 +
                        CommitReviewState::Pending => (PENDING_MARK, colors::fixed::MUTED),
230 +
                    };
231 +
                    Line::new(Label::from_char(marker).fg(color))
232 +
                        .item(Label::space())
233 +
                        .item(Label::new(short).fg(FOOTER_HASH_FG))
234 +
                        .item(Label::space())
235 +
                        .item(Label::new(summary).fg(FOOTER_SUMMARY_FG))
236 +
                }
223 237
                StatusContext::Range(range) => Line::new(Label::new(range).fg(FOOTER_SUMMARY_FG)),
224 238
            }
225 239
        };
226 240
        Line::blank()
227 241
            .item(
273 287
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
274 288
pub(super) enum ActionContext {
275 289
    /// Commit-list mode.
276 290
    Commits,
277 291
    /// Commit diff mode.
278 -
    Commit,
292 +
    Commit {
293 +
        /// Whether the open commit is rejected.
294 +
        rejected: bool,
295 +
        /// Whether the focused hunk can be accepted from this viewport.
296 +
        can_accept_hunk: bool,
297 +
    },
279 298
    /// Hunk comments are being browsed.
280 -
    HunkBrowse,
299 +
    HunkBrowse {
300 +
        /// Whether the owning commit is rejected.
301 +
        rejected: bool,
302 +
    },
281 303
    /// A hunk comment is being edited.
282 304
    HunkEdit,
283 305
}
284 306
285 307
impl ActionContext {
286 308
    /// Returns the action hints for this context.
287 309
    fn actions(self) -> &'static [(&'static str, &'static str)] {
288 310
        match self {
289 311
            Self::Commits => COMMITS_ACTIONS,
290 -
            Self::Commit => COMMIT_ACTIONS,
291 -
            Self::HunkBrowse => HUNK_BROWSE_ACTIONS,
312 +
            Self::Commit { .. } => COMMIT_ACTIONS,
313 +
            Self::HunkBrowse { .. } => HUNK_BROWSE_ACTIONS,
292 314
            Self::HunkEdit => HUNK_EDIT_ACTIONS,
293 315
        }
294 316
    }
317 +
318 +
    /// Returns whether the reject key restores the current commit.
319 +
    fn restores(self) -> bool {
320 +
        match self {
321 +
            Self::Commit { rejected, .. } | Self::HunkBrowse { rejected } => rejected,
322 +
            Self::Commits | Self::HunkEdit => false,
323 +
        }
324 +
    }
325 +
326 +
    /// Returns whether an action should be shown.
327 +
    fn shows(self, key: &str) -> bool {
328 +
        !matches!(
329 +
            self,
330 +
            Self::Commit {
331 +
                can_accept_hunk: false,
332 +
                ..
333 +
            }
334 +
        ) || key != "a"
335 +
    }
295 336
}
296 337
297 338
/// Bottom chrome containing the status bar and contextual action bar.
298 339
#[derive(Debug)]
299 340
pub(super) struct Chrome {
317 358
    /// Returns the rendered action row.
318 359
    fn action_line(&self, cols: usize) -> Line {
319 360
        let mut line = Line::blank();
320 361
        let mut first = true;
321 362
        for (key, label) in self.actions.actions() {
363 +
            if !self.actions.shows(key) {
364 +
                continue;
365 +
            }
366 +
            let label = if *key == "r" && self.actions.restores() {
367 +
                "restore commit"
368 +
            } else {
369 +
                label
370 +
            };
322 371
            if !first {
323 372
                line = line.item(Label::new(ACTION_SEPARATOR).fg(FOOTER_FG));
324 373
            }
325 374
            first = false;
326 375
            line = line
512 561
    let border = if selected {
513 562
        SELECTED_COMMENT_BORDER
514 563
    } else {
515 564
        colors::FAINT
516 565
    };
517 -
    let body = Line::new(Label::new(&comment.body.replace('\n', " ")).fg(Color::White));
566 +
    let bodies = comment
567 +
        .body
568 +
        .lines()
569 +
        .map(|line| Line::new(Label::new(line).fg(Color::White)))
570 +
        .collect::<Vec<_>>();
571 +
    let width = bodies.iter().map(Line::width).max().unwrap_or_default();
518 572
    let header = comment_header(
519 573
        &comment.author,
520 574
        &comment_age(comment),
521 -
        comment_table_content_width(cols).max(body.width()),
575 +
        comment_table_content_width(cols).max(width),
522 576
    );
523 577
    let mut table = Table::<1, Line>::new(TableOptions {
524 578
        border: Some(Border::new(border)),
525 579
        ..TableOptions::bordered()
526 580
    });
527 581
    table.header([header]);
528 -
    table.push([body]);
582 +
    for body in bodies {
583 +
        table.push([body]);
584 +
    }
529 585
    table.lines(Constraint::tight(cols))
530 586
}
531 587
532 588
/// Renders an editable comment card with a blank body of `rows` lines.
533 589
pub(super) fn comment_editor_lines(author: &str, age: &str, rows: usize, cols: usize) -> Vec<Line> {
633 689
    }
634 690
635 691
    #[test]
636 692
    fn action_context_changes_action_hints() {
637 693
        assert!(
638 -
            ActionContext::Commit
639 -
                .actions()
640 -
                .iter()
641 -
                .any(|(_, label)| *label == "accept hunk")
694 +
            ActionContext::Commit {
695 +
                rejected: false,
696 +
                can_accept_hunk: true,
697 +
            }
698 +
            .actions()
699 +
            .iter()
700 +
            .any(|(_, label)| *label == "accept hunk")
642 701
        );
643 702
        assert!(
644 703
            ActionContext::Commits
645 704
                .actions()
646 705
                .iter()
647 706
                .any(|(_, label)| *label == "reject commit")
648 707
        );
649 708
        assert!(
650 -
            ActionContext::HunkBrowse
709 +
            ActionContext::HunkBrowse { rejected: false }
651 710
                .actions()
652 711
                .iter()
653 712
                .any(|(_, label)| *label == "reject commit")
654 713
        );
655 714
        assert!(
666 725
            status: Status {
667 726
                mode: "commit",
668 727
                context: StatusContext::Commit {
669 728
                    short: "1234567".to_owned(),
670 729
                    summary: "summary".to_owned(),
730 +
                    state: CommitReviewState::Pending,
671 731
                },
672 732
                progress: ReviewProgress::default(),
673 733
                stats: DiffStat::default(),
674 734
                palette: DiffPalette::default(),
675 735
                visibility: Visibility::default(),
676 736
                error: Some("patch does not apply".to_owned()),
677 737
                loading: None,
678 738
            },
679 -
            actions: ActionContext::Commit,
739 +
            actions: ActionContext::Commit {
740 +
                rejected: false,
741 +
                can_accept_hunk: true,
742 +
            },
680 743
        };
744 +
        assert!(chrome.action_line(80).to_string().contains("q quit"));
681 745
        let mut buffer = Buffer::empty(Rect::new(0, 0, 40, 2));
682 746
683 747
        chrome.render(buffer.area(), &mut buffer);
684 748
685 749
        let status = buffer.line(0);
692 756
        let mut status = Status {
693 757
            mode: "commit",
694 758
            context: StatusContext::Commit {
695 759
                short: "1234567".to_owned(),
696 760
                summary: "summary".to_owned(),
761 +
                state: CommitReviewState::Pending,
697 762
            },
698 763
            progress: ReviewProgress::default(),
699 764
            stats: DiffStat::default(),
700 765
            palette: DiffPalette::default(),
701 766
            visibility: Visibility::default(),
719 784
        let mut status = Status {
720 785
            mode: "commit",
721 786
            context: StatusContext::Commit {
722 787
                short: "1234567".to_owned(),
723 788
                summary: "summary".to_owned(),
789 +
                state: CommitReviewState::Accepted,
724 790
            },
725 791
            progress: ReviewProgress {
726 792
                accepted: 5,
727 793
                total: 5,
728 794
            },
971 1037
            .iter()
972 1038
            .map(ToString::to_string)
973 1039
            .collect::<Vec<_>>()
974 1040
            .join("\n");
975 1041
976 -
        assert_eq!(lines.len(), COMMENT_CARD_ROWS);
1042 +
        assert_eq!(lines.len(), COMMENT_CARD_CHROME_ROWS + 2);
977 1043
        assert!(text.contains("alice"), "text: {text:?}");
978 1044
        assert!(text.contains("just now"), "text: {text:?}");
979 -
        assert!(text.contains("first second"), "text: {text:?}");
1045 +
        assert!(lines.iter().any(|line| line.to_string().contains("first")));
1046 +
        assert!(lines.iter().any(|line| line.to_string().contains("second")));
980 1047
        assert!(!text.contains('๐Ÿ—จ'), "text: {text:?}");
981 1048
    }
982 1049
983 1050
    #[test]
984 1051
    fn relative_time_uses_largest_whole_unit() {
crates/brain/src/session/worker.rs +23 -23
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, FilePatches};
14 +
use crate::backend::{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 and projects their patches.
23 +
    /// Accepts exact hunk identities.
24 24
    Accept {
25 25
        /// Identities being accepted.
26 26
        identities: Vec<AcceptedHunk>,
27 -
        /// File patches used to update the projected tree.
28 -
        patches: Vec<FilePatches>,
29 27
    },
30 -
    /// Rejects exact hunk identities and rebuilds their projected files.
28 +
    /// Rejects exact hunk identities.
31 29
    Reject {
32 30
        /// Identities being rejected.
33 31
        identities: BTreeSet<AcceptedHunk>,
34 -
        /// File patches used to update the projected tree.
35 -
        patches: Vec<FilePatches>,
36 32
    },
37 33
    /// Toggles one commit's rejected decision.
38 34
    ToggleRejected {
39 35
        /// Commit whose decision changes.
40 36
        commit: Oid,
80 76
        /// Hunk that owns the viewer.
81 77
        hunk: HunkId,
82 78
    },
83 79
    /// Persists one review-state mutation.
84 80
    Mutate(ReviewMutation),
85 -
    /// Persists the complete encoded comment store.
81 +
    /// Persists one comment-store delta.
86 82
    WriteComments {
87 -
        /// Encoded JSONL comment data.
88 -
        encoded: String,
83 +
        /// Review-wide store before the local mutation.
84 +
        previous: ReviewComments,
85 +
        /// Review-wide store after the local mutation.
86 +
        updated: ReviewComments,
89 87
    },
90 88
    /// Stops the worker after all preceding commands.
91 89
    Shutdown,
92 90
}
93 91
92 +
/// State returned after one repository mutation.
93 +
pub(super) enum Persisted {
94 +
    /// Updated review decisions.
95 +
    Review(Box<Brain>),
96 +
    /// Updated review comments.
97 +
    Comments(ReviewComments),
98 +
}
99 +
94 100
/// Typed result returned to the terminal event loop.
95 101
pub(super) enum Output {
96 102
    /// One commit viewer finished loading.
97 103
    CommitLoaded {
98 104
        /// Session commit index.
108 114
        hunk: HunkId,
109 115
        /// Populated viewer or its user-facing failure.
110 116
        result: Box<Result<DiffViewer, String>>,
111 117
    },
112 118
    /// A state mutation finished persisting.
113 -
    Persisted(Box<Result<Option<Brain>, String>>),
119 +
    Persisted(Box<Result<Persisted, String>>),
114 120
}
115 121
116 122
/// Handle used by the UI to enqueue repository commands.
117 123
pub(super) struct Worker {
118 124
    /// Command sender owned by the terminal session.
173 179
                            result: Box::new(result),
174 180
                        }
175 181
                    }
176 182
                    Command::Mutate(mutation) => {
177 183
                        let result = match mutation {
178 -
                            ReviewMutation::Accept {
179 -
                                identities,
180 -
                                patches,
181 -
                            } => brain.accept(identities, patches),
182 -
                            ReviewMutation::Reject {
183 -
                                identities,
184 -
                                patches,
185 -
                            } => brain.reject(&identities, patches),
184 +
                            ReviewMutation::Accept { identities } => brain.accept(identities),
185 +
                            ReviewMutation::Reject { identities } => brain.reject(&identities),
186 186
                            ReviewMutation::ToggleRejected { commit } => {
187 187
                                brain.toggle_commit_rejected(commit)
188 188
                            }
189 189
                            ReviewMutation::ToggleDropped { commit } => {
190 190
                                brain.toggle_commit_dropped(commit)
191 191
                            }
192 192
                        }
193 -
                        .map(|()| Some(brain.clone()))
193 +
                        .map(|()| Persisted::Review(Box::new(brain.clone())))
194 194
                        .map_err(|error| error.to_string());
195 195
                        Output::Persisted(Box::new(result))
196 196
                    }
197 -
                    Command::WriteComments { encoded } => {
197 +
                    Command::WriteComments { previous, updated } => {
198 198
                        let result = brain
199 -
                            .write_comments(&encoded)
200 -
                            .map(|()| None)
199 +
                            .merge_comments(&previous, &updated)
200 +
                            .map(Persisted::Comments)
201 201
                            .map_err(|error| error.to_string());
202 202
                        Output::Persisted(Box::new(result))
203 203
                    }
204 204
                    Command::Shutdown => break,
205 205
                };
crates/diff/src/decode.rs +3 -12
98 98
        Stream::new(input).decode_document()
99 99
    }
100 100
101 101
    /// Decodes a diff document from raw bytes.
102 102
    ///
103 -
    /// Non-UTF-8 bytes are replaced with U+FFFD and ANSI escape sequences are
104 -
    /// stripped before parsing, so output from colored Git pipes round-trips
105 -
    /// without caller-side preprocessing.
103 +
    /// Non-UTF-8 bytes are replaced with U+FFFD. All valid UTF-8 content is
104 +
    /// preserved exactly.
106 105
    fn decode_bytes(input: &[u8]) -> Result<Self, DecodeError> {
107 -
        if !input.contains(&b'\x1b')
108 -
            && let Ok(text) = std::str::from_utf8(input)
109 -
        {
110 -
            let mut reader = io::BufReader::new(text.as_bytes());
111 -
            return Self::decode(&mut reader);
112 -
        }
113 -
114 106
        let text = String::from_utf8_lossy(input);
115 -
        let stripped = rustik_tui::ansi::strip(&text);
116 -
        let mut reader = io::BufReader::new(stripped.as_bytes());
107 +
        let mut reader = io::BufReader::new(text.as_bytes());
117 108
        Self::decode(&mut reader)
118 109
    }
119 110
}
120 111
121 112
/// Streaming decoder over a buffered input stream.
{ +0 -0
+0 -0
=> break, +0 -0
a.rs +0 -0
new.rs +0 -0
old.rs +0 -0
to.rs +0 -0
copy2.rs +0 -0
mode.sh +0 -0
image.png +0 -0
caf\303\251\t\"slash\\.rs" "b/modified caf\303\251\t\"slash\\.rs" +0 -0
ordinary.rs +0 -0
from caf\303\251\t\"slash\\.rs" "b/rename to caf\303\251\t\"slash\\.rs" +0 -0
"b/non-utf8-\377.rs" +0 -0
a +0 -0
a +0 -0
a +0 -0
a +0 -0
a.rs +0 -0
b.rs +0 -0
a.rs\x1b[m +0 -0
a.rs +0 -0
crates/diff/src/encode.rs +1 -1
37 37
impl Encode for FileDiff {
38 38
    fn encode(&self, out: &mut impl Write) -> io::Result<()> {
39 39
        for line in &self.header.raw {
40 40
            writeln!(out, "{line}")?;
41 41
        }
42 -
        if self.header.kind != FileKind::Binary {
42 +
        if !matches!(self.header.kind, FileKind::Binary | FileKind::ModeChanged) {
43 43
            for hunk in &self.hunks {
44 44
                hunk.encode(out)?;
45 45
            }
46 46
        }
47 47
        Ok(())
a.txt +0 -0
b.txt +0 -0
image.png +0 -0
crates/diff/src/viewer.rs +68 -15
1 1
//! Read-only diff viewer state and buffer rendering.
2 2
3 3
mod tree;
4 4
5 +
use std::borrow::Cow;
5 6
use std::collections::btree_map::Entry;
6 7
use std::collections::{BTreeMap, BTreeSet};
7 8
use std::convert::Infallible;
8 9
use std::io::Read as _;
9 10
use std::ops::Range;
87 88
const DEFAULT_THEME: &str = "auto";
88 89
/// Number of rows in a sticky file header.
89 90
const STICKY_HEADER_ROWS: usize = 3;
90 91
/// Number of body rows moved by keyboard line-scroll inputs.
91 92
const LINE_SCROLL_ROWS: isize = 1;
93 +
/// Number of source columns moved by horizontal-scroll inputs.
94 +
const HORIZONTAL_SCROLL_COLS: usize = 8;
92 95
/// Number of body rows moved by mouse-wheel inputs.
93 96
const WHEEL_SCROLL_ROWS: isize = 3;
94 97
/// Central viewport percentage where hunk navigation preserves the scroll offset.
95 98
const HUNK_SCROLL_COMFORT_PERCENT: usize = 80;
96 99
/// Local row of a file card's top border.
102 105
/// Local row of the first hunk body line after the fixed file-card chrome.
103 106
const HUNK_BODY_START: usize = FILE_DIVIDER_ROW + 1;
104 107
/// Total card height when the file has no visible body.
105 108
const EMPTY_CARD_ROWS: usize = FILE_DIVIDER_ROW + 1;
106 109
110 +
/// Escapes path control characters while preserving printable Unicode.
111 +
fn escape_path(input: &str) -> Cow<'_, str> {
112 +
    if !input.chars().any(char::is_control) {
113 +
        return Cow::Borrowed(input);
114 +
    }
115 +
    let mut escaped = String::with_capacity(input.len());
116 +
    for ch in input.chars() {
117 +
        if ch.is_control() {
118 +
            escaped.extend(ch.escape_default());
119 +
        } else {
120 +
            escaped.push(ch);
121 +
        }
122 +
    }
123 +
    Cow::Owned(escaped)
124 +
}
125 +
107 126
/// Mutable read-only diff viewport state.
108 127
#[derive(Clone, Debug, Default, Eq, PartialEq)]
109 128
pub struct DiffState {
110 129
    /// Vertical viewport over the rendered document.
111 130
    pub scroll: Viewport,
131 +
    /// Horizontal source-text offset in terminal columns.
132 +
    pub horizontal: usize,
112 133
    /// Currently focused commit, file, or hunk.
113 134
    pub focus: Option<DiffFocus>,
114 135
}
115 136
116 137
/// Focus target inside a diff document.
127 148
/// Viewer action accepted by [`DiffViewer::apply`].
128 149
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
129 150
pub enum DiffAction {
130 151
    /// Scroll the viewport.
131 152
    Scroll(Scroll),
153 +
    /// Scroll source text horizontally by signed steps.
154 +
    ScrollHorizontal(isize),
132 155
    /// Clamp scroll after a terminal resize.
133 156
    Resize,
134 157
    /// Focus the next file or hunk target.
135 158
    FocusNext,
136 159
    /// Focus the previous file or hunk target.
752 775
        mut read_blob: impl FnMut(Oid) -> Result<Vec<u8>, E>,
753 776
    ) -> Result<(), E> {
754 777
        let mut blobs: BTreeMap<Oid, usize> = BTreeMap::new();
755 778
756 779
        for file in &self.document.files {
757 -
            if file.header.kind == FileKind::Binary {
780 +
            if file.header.kind == FileKind::Binary
781 +
                || matches!(
782 +
                    (file.header.old_mode, file.header.new_mode),
783 +
                    (Some(FileMode::Commit | FileMode::Tree), _)
784 +
                        | (_, Some(FileMode::Commit | FileMode::Tree))
785 +
                )
786 +
            {
758 787
                continue;
759 788
            }
760 789
            for oid in [file.header.old_oid, file.header.new_oid]
761 790
                .into_iter()
762 791
                .flatten()
1108 1137
                .find(|file| file.hunks.iter().any(|candidate| candidate.id == hunk))
1109 1138
                .map(|file| file.id),
1110 1139
        }
1111 1140
    }
1112 1141
1142 +
    /// Returns whether the focused hunk has a visible row in `area`.
1143 +
    pub fn focused_hunk_visible(&self, area: Rect) -> bool {
1144 +
        let Some(focus @ DiffFocus::Hunk(_)) = self.state.focus else {
1145 +
            return false;
1146 +
        };
1147 +
        self.focus_anchor(self.layout(area).diff.rows)
1148 +
            .is_some_and(|(visible, _)| visible == focus)
1149 +
    }
1150 +
1113 1151
    /// Returns the focused file, or the first visible file when focus is unset.
1114 1152
    fn active_file(&self) -> Option<FileId> {
1115 1153
        self.focused_file().or_else(|| self.visible_file())
1116 1154
    }
1117 1155
1323 1361
                    && !matches!(self.state.focus, Some(DiffFocus::Hunk(_)))
1324 1362
                {
1325 1363
                    self.set_focus(Some(DiffFocus::File(file)));
1326 1364
                }
1327 1365
            }
1366 +
            DiffAction::ScrollHorizontal(steps) => {
1367 +
                let columns = steps.saturating_mul(HORIZONTAL_SCROLL_COLS as isize);
1368 +
                self.state.horizontal = self.state.horizontal.saturating_add_signed(columns);
1369 +
            }
1328 1370
            DiffAction::Resize => {
1329 1371
                self.state
1330 1372
                    .scroll
1331 1373
                    .clamp(self.scroll_rows(diff.rows), diff.rows);
1332 1374
            }
1382 1424
            }
1383 1425
        }
1384 1426
1385 1427
        let sync_after_action = match action {
1386 1428
            DiffAction::Scroll(_) => self.state.scroll != before.scroll,
1429 +
            DiffAction::ScrollHorizontal(_) => false,
1387 1430
            DiffAction::NextHunk | DiffAction::PreviousHunk => self.state.focus != before.focus,
1388 1431
            DiffAction::MoveFileTree(_)
1389 1432
            | DiffAction::ShowFileTreeTarget
1390 1433
            | DiffAction::ActivateFileTreeTarget
1391 1434
            | DiffAction::CollapseFileTreeFolder
1448 1491
                return Control::Redraw;
1449 1492
            }
1450 1493
            Event::Key(Key::Esc) => return Control::Quit,
1451 1494
            Event::Key(Key::Char('n')) => DiffAction::FocusNext,
1452 1495
            Event::Key(Key::Char('p')) => DiffAction::FocusPrevious,
1496 +
            Event::Key(Key::Left) => DiffAction::ScrollHorizontal(-1),
1497 +
            Event::Key(Key::Right) => DiffAction::ScrollHorizontal(1),
1453 1498
            Event::Key(Key::Char('j') | Key::Down) => {
1454 1499
                DiffAction::Scroll(Scroll::Lines(LINE_SCROLL_ROWS))
1455 1500
            }
1456 1501
            Event::Key(Key::Char('k') | Key::Up) => {
1457 1502
                DiffAction::Scroll(Scroll::Lines(-LINE_SCROLL_ROWS))
2208 2253
                    file_start: indexed.start,
2209 2254
                });
2210 2255
            }
2211 2256
            if filter == FocusFilter::HunkNavigation && file.has_body() {
2212 2257
                for (hunk, local) in file.hunk_body_rows(self.hunk_gaps(file.id)) {
2213 -
                    let leading = hunk
2214 -
                        .lines
2215 -
                        .iter()
2216 -
                        .take_while(|line| self.expanded_context.contains(&line.id))
2217 -
                        .count();
2258 +
                    let leading = self.leading_expanded_rows(hunk);
2218 2259
                    let trailing = hunk
2219 2260
                        .lines
2220 2261
                        .iter()
2221 2262
                        .rev()
2222 2263
                        .take_while(|line| self.expanded_context.contains(&line.id))
2231 2272
            }
2232 2273
        }
2233 2274
        targets
2234 2275
    }
2235 2276
2277 +
    /// Returns leading expanded-context rows before a hunk's review target.
2278 +
    fn leading_expanded_rows(&self, hunk: &crate::Hunk) -> usize {
2279 +
        hunk.lines
2280 +
            .iter()
2281 +
            .take_while(|line| self.expanded_context.contains(&line.id))
2282 +
            .count()
2283 +
    }
2284 +
2236 2285
    /// Returns one rendered row inside a hunk.
2237 2286
    fn hunk_row_at(
2238 2287
        &self,
2239 2288
        file: &FileDiff,
2240 2289
        hunk: &crate::Hunk,
2243 2292
        decoration: &HunkDecoration,
2244 2293
    ) -> RenderRow {
2245 2294
        let (old_line, new_line) = Self::hunk_line_numbers(hunk, line_index);
2246 2295
        let line = &hunk.lines[line_index];
2247 2296
        let meta = DiffLineMeta::new(file, hunk.id, line, old_line, new_line);
2248 -
2249 -
        self.hunk_row(meta, line, old_line, inner, decoration)
2297 +
        let focus_row = line_index == self.leading_expanded_rows(hunk);
2298 +
        self.hunk_row(meta, line, old_line, inner, decoration, focus_row)
2250 2299
    }
2251 2300
2252 2301
    /// Returns source metadata for one rendered hunk body row.
2253 2302
    fn hunk_meta_at(&self, file: &FileDiff, hunk: &crate::Hunk, line_index: usize) -> DiffLineMeta {
2254 2303
        let (old_line, new_line) = Self::hunk_line_numbers(hunk, line_index);
2272 2321
        meta: DiffLineMeta,
2273 2322
        line: &DiffLine,
2274 2323
        old_line: u32,
2275 2324
        row_cols: usize,
2276 2325
        decoration: &HunkDecoration,
2326 +
        focus_row: bool,
2277 2327
    ) -> RenderRow {
2278 2328
        let line_number_fg = if matches!(self.state.focus, Some(DiffFocus::Hunk(focused)) if focused == meta.hunk)
2279 2329
        {
2280 2330
            SELECTED_LINE_NUMBER_FG
2281 2331
        } else {
2331 2381
                Line::new(NO_NEWLINE_MARKER).style(Style::default().fg(colors::rgb::DIM)),
2332 2382
                Style::default(),
2333 2383
                Style::default(),
2334 2384
            ),
2335 2385
        };
2386 +
        let focused = focus_row
2387 +
            && matches!(self.state.focus, Some(DiffFocus::Hunk(hunk)) if hunk == meta.hunk);
2336 2388
        let decoration = HunkRowDecoration {
2337 2389
            gutter: if matches!(line.kind, DiffLineKind::Addition | DiffLineKind::Deletion) {
2338 2390
                decoration.gutter
2339 2391
            } else {
2340 2392
                None
2341 2393
            },
2342 -
            style: if matches!(self.state.focus, Some(DiffFocus::Hunk(hunk)) if hunk == meta.hunk) {
2343 -
                None
2344 -
            } else {
2345 -
                decoration.style
2346 -
            },
2394 +
            style: if focused { None } else { decoration.style },
2347 2395
        };
2348 2396
        let rendered = self.hunk_line(cells, source, row_cols, row_style, source_style, decoration);
2349 2397
2350 2398
        RenderRow {
2351 2399
            line: rendered,
2365 2413
    ) -> Line {
2366 2414
        let source_cols =
2367 2415
            row_cols.saturating_sub(REVIEW_GUTTER_WIDTH + LINE_NUMBER_WIDTH * 2 + MARKER_WIDTH);
2368 2416
2369 2417
        if source_cols > 0 {
2418 +
            source.skip(self.state.horizontal);
2370 2419
            Line::truncate(&mut source, source_cols, "โ€ฆ");
2371 2420
            let source_width = source.width();
2372 2421
            if source_width < source_cols {
2373 2422
                let padding = " ".repeat(source_cols - source_width);
2374 2423
                source.push(Label::new(&padding));
2633 2682
}
2634 2683
2635 2684
impl FileDiff {
2636 2685
    /// Returns whether this file card should render hunk rows.
2637 2686
    fn has_body(&self) -> bool {
2638 -
        self.header.kind != FileKind::Binary && !self.hunks.is_empty()
2687 +
        !matches!(self.header.kind, FileKind::Binary | FileKind::ModeChanged)
2688 +
            && !self.hunks.is_empty()
2639 2689
    }
2640 2690
2641 2691
    /// Returns the rendered row count for this file's card.
2642 2692
    fn rendered_rows(&self, gaps: HunkGaps) -> usize {
2643 2693
        if !self.has_body() {
2846 2896
            .style(style)
2847 2897
    }
2848 2898
2849 2899
    /// Returns a display path or placeholder.
2850 2900
    fn display_path(path: Option<&PathBuf>) -> String {
2851 -
        path.map_or_else(|| "<unknown>".to_owned(), |path| path.display().to_string())
2901 +
        path.map_or_else(
2902 +
            || "<unknown>".to_owned(),
2903 +
            |path| escape_path(&path.display().to_string()).into_owned(),
2904 +
        )
2852 2905
    }
2853 2906
}
2854 2907
2855 2908
impl DiffLineMeta {
2856 2909
    /// Creates metadata for a source row.
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/diff/src/viewer/tree.rs +7 -6
7 7
use tui::{
8 8
    Buffer, Cell, Color, Constraint, Label, Placement, Point, Rect, Size, Style, Tree, TreeHitZone,
9 9
    TreeModel, TreeNodeKind, TreeRow, TreeState, TreeStyle, Widget,
10 10
};
11 11
12 -
use super::{DiffPalette, FILE_KIND_BADGE_FG, MIN_RENDER_COLS};
12 +
use super::{DiffPalette, FILE_KIND_BADGE_FG, MIN_RENDER_COLS, escape_path};
13 13
use crate::{DiffDecorator, DiffDocument, FileId, FileKind};
14 14
15 15
/// Blank rows above the file tree list.
16 16
const TOP_PADDING_ROWS: usize = 1;
17 17
/// Background color for the selected or active file row.
494 494
    }
495 495
496 496
    /// Returns a folder row (used by both structural and styled tree views).
497 497
    fn folder_row(&self, id: usize, fg: Color, style: Style) -> TreeRow {
498 498
        let node = &self.nodes[id];
499 -
        let label = if node.name == "/" {
500 -
            node.name.to_owned()
499 +
        let name = escape_path(&node.name);
500 +
        let label = if name == "/" {
501 +
            name.into_owned()
501 502
        } else {
502 -
            format!("{}/", node.name)
503 +
            format!("{name}/")
503 504
        };
504 505
        TreeRow::new(Label::from(label).fg(fg))
505 506
            .marker_style(Style::new(fg))
506 507
            .style(style)
507 508
    }
529 530
    fn row(&self, id: Self::Id) -> TreeRow {
530 531
        let node = &self.nodes[id];
531 532
        let Some(file) = node.file else {
532 533
            return self.folder_row(id, FOLDER_FG, Style::default());
533 534
        };
534 -
        TreeRow::new(Label::new(&node.name).fg(Color::White))
535 +
        TreeRow::new(Label::from(escape_path(&node.name).into_owned()).fg(Color::White))
535 536
            .marker(file.kind.marker())
536 537
            .marker_style(Style::new(Color::Unset))
537 538
    }
538 539
}
539 540
630 631
            .decorator
631 632
            .and_then(|decorator| decorator.file(file.id).status);
632 633
        let marker = status.map_or_else(|| file.kind.marker(), |status| status.item);
633 634
        let marker_style = status.map_or_else(|| Style::new(kind_fg), |status| status.style);
634 635
635 -
        TreeRow::new(Label::new(&node.name).fg(fg))
636 +
        TreeRow::new(Label::from(escape_path(&node.name).into_owned()).fg(fg))
636 637
            .marker(marker)
637 638
            .marker_style(marker_style)
638 639
            .style(self.row_style(id))
639 640
    }
640 641
}
a.rs +0 -0
b.rs +0 -0
crates/diff/tests/golden/focused_second_file_64x6.txt +1 -1
1 1
โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ๐Ÿฎ˜
2 2
โ”‚ โŠ™ b.rs 2 LOC                                          +1 -1 โ”‚๐Ÿฎ˜
3 3
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค๐Ÿฎ˜
4 -
โ”‚  1    1       keep                                          โ”‚โ–—
4 +
โ”‚ >1    1       keep                                          โ”‚โ–—
5 5
โ”‚  2          - before                                        โ”‚โ–
6 6
โ”‚       2     + after                                         โ”‚โ–
crates/repo/src/git.rs +33 -15
591 591
        Ok(AheadBehind { ahead, behind })
592 592
    }
593 593
594 594
    /// Returns whether `target` would merge into `base` with conflicts.
595 595
    fn merge_status(&self, base: &Rev, target: &Rev) -> Result<MergeStatus, RepoError> {
596 -
        let merge_base = self.git("merge-base", &[base.as_str(), target.as_str()])?;
597 -
        let merge_base = utf8(merge_base)?;
598 -
        let merge_base = merge_base.trim();
599 -
        let bytes = self.git(
596 +
        let output = self.run(
600 597
            "merge-tree",
601 -
            &[
602 -
                "--trivial-merge",
603 -
                merge_base,
604 -
                base.as_str(),
605 -
                target.as_str(),
606 -
            ],
598 +
            &["--write-tree", base.as_str(), target.as_str()],
599 +
            Opts::default(),
607 600
        )?;
608 -
        let text = utf8(bytes)?;
609 -
        if text.trim().is_empty() {
610 -
            Ok(MergeStatus::Clean)
611 -
        } else {
612 -
            Ok(MergeStatus::Conflicts)
601 +
        if output.status.success() {
602 +
            return Ok(MergeStatus::Clean);
613 603
        }
604 +
        if output.status.code() == Some(1) {
605 +
            return Ok(MergeStatus::Conflicts);
606 +
        }
607 +
        Err(RepoError::git(&output))
614 608
    }
615 609
616 610
    /// Returns the single parent of `commit`, or an error if it has more or fewer.
617 611
    fn parent(&self, commit: Oid) -> Result<Oid, RepoError> {
618 612
        let commit = commit.to_string();
848 842
            "diff",
849 843
            &[
850 844
                "--no-ext-diff",
851 845
                "--no-textconv",
852 846
                "--full-index",
847 +
                "--find-copies-harder",
853 848
                parent,
854 849
                &commit,
855 850
            ],
856 851
        )
857 852
    }
999 994
        if !output.status.success() {
1000 995
            return Err(RepoError::git(&output));
1001 996
        }
1002 997
        Ok(())
1003 998
    }
999 +
1000 +
    /// Moves `reference` to `commit` only when it still points to `expected`.
1001 +
    fn compare_and_update_ref(
1002 +
        &self,
1003 +
        reference: &Qualified<'_>,
1004 +
        commit: Oid,
1005 +
        expected: Option<Oid>,
1006 +
    ) -> Result<bool, RepoError> {
1007 +
        let commit = commit.to_string();
1008 +
        let expected_arg = expected.map_or_else(|| "0".repeat(40), |oid| oid.to_string());
1009 +
        let output = self.run(
1010 +
            "update-ref",
1011 +
            &[reference.as_str(), &commit, &expected_arg],
1012 +
            Opts::default(),
1013 +
        )?;
1014 +
        if output.status.success() {
1015 +
            return Ok(true);
1016 +
        }
1017 +
        if self.optional_ref(reference)? != expected {
1018 +
            return Ok(false);
1019 +
        }
1020 +
        Err(RepoError::git(&output))
1021 +
    }
1004 1022
}
1005 1023
1006 1024
impl Repository {
1007 1025
    /// Returns the default branch reported by `origin/HEAD`, if present.
1008 1026
    fn remote_default_branch(&self) -> Result<Option<String>, RepoError> {
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
f{index}\n--- a/f{index}\n+++ b/f{index}\n\ +0 -0
crates/repo/src/lib.rs +10 -0
267 267
        deleted: &Qualified<'_>,
268 268
    ) -> Result<(), RepoError>;
269 269
270 270
    /// Moves `reference` to point at `commit`.
271 271
    fn update_ref(&self, reference: &Qualified<'_>, commit: Oid) -> Result<(), RepoError>;
272 +
273 +
    /// Moves `reference` to `commit` only when it still points to `expected`.
274 +
    ///
275 +
    /// Returns `false` when another writer changed the reference first.
276 +
    fn compare_and_update_ref(
277 +
        &self,
278 +
        reference: &Qualified<'_>,
279 +
        commit: Oid,
280 +
        expected: Option<Oid>,
281 +
    ) -> Result<bool, RepoError>;
272 282
}
273 283
274 284
/// A diff backend a viewer can re-query for wider hunk context.
275 285
pub trait DiffRepository {
276 286
    /// Refetches `paths` with `context_lines` of unified context per hunk.
crates/tui-core/src/label.rs +21 -11
42 42
        Self::raw(clean(s.to_owned()), Style::default())
43 43
    }
44 44
45 45
    /// Creates a new label from one character.
46 46
    pub fn from_char(ch: char) -> Self {
47 -
        let content = if matches!(ch, '\n' | '\r') {
48 -
            String::new()
49 -
        } else {
50 -
            ch.to_string()
51 -
        };
52 -
        Self::raw(content, Style::default())
47 +
        Self::from(ch.to_string())
53 48
    }
54 49
55 50
    /// Creates a blank label.
56 51
    pub fn blank() -> Self {
57 52
        Self::raw(String::new(), Style::default())
182 177
/// Creates a new label from a [`Paint`] object.
183 178
pub fn label(s: impl Into<Paint<String>>) -> Label {
184 179
    Label::from(s.into())
185 180
}
186 181
187 -
/// Removes unsupported label line breaks.
188 -
fn clean(mut input: String) -> String {
189 -
    if input.as_bytes().contains(&b'\n') || input.as_bytes().contains(&b'\r') {
190 -
        input.retain(|c| c != '\n' && c != '\r');
182 +
/// Escapes control characters that a terminal could interpret.
183 +
fn clean(input: String) -> String {
184 +
    if !input.chars().any(|ch| ch.is_control() && ch != '\t') {
185 +
        return input;
186 +
    }
187 +
    let mut cleaned = String::with_capacity(input.len());
188 +
    for ch in input.chars() {
189 +
        if ch.is_control() && ch != '\t' {
190 +
            cleaned.extend(ch.escape_default());
191 +
        } else {
192 +
            cleaned.push(ch);
193 +
        }
191 194
    }
192 -
    input
195 +
    cleaned
193 196
}
194 197
195 198
#[cfg(test)]
196 199
mod tests {
197 200
    use super::*;
204 207
            .style(Style::default().bold());
205 208
206 209
        assert_eq!(label.paint.style().fg_color(), Color::White);
207 210
        assert_eq!(label.paint.style().bg_color(), Color::Blue);
208 211
    }
212 +
213 +
    #[test]
214 +
    fn control_characters_are_visible() {
215 +
        let label = Label::new("tab\tline\nescape\x1b");
216 +
217 +
        assert_eq!(label.content(), "tab\tline\\nescape\\u{1b}");
218 +
    }
209 219
}
crates/tui-core/src/primitive.rs +36 -1
6 6
7 7
use std::fmt;
8 8
use std::ops::Range;
9 9
use std::vec;
10 10
11 -
use super::cell::Text;
11 +
use super::cell::{Text, char_width};
12 12
use crate::widget::Widget;
13 13
14 14
use super::{Buffer, Color, Filled, Label, Rect, Style};
15 15
16 16
/// Rendering constraint.
261 261
    pub fn truncated(mut self, width: usize, delim: &str) -> Self {
262 262
        Line::truncate(&mut self, width, delim);
263 263
        self
264 264
    }
265 265
266 +
    /// Removes the first `width` terminal columns from this line.
267 +
    pub fn skip(&mut self, width: usize) {
268 +
        if width == 0 {
269 +
            return;
270 +
        }
271 +
        let mut remaining = width;
272 +
        let mut items = Vec::with_capacity(self.items.len());
273 +
        for label in std::mem::take(&mut self.items) {
274 +
            if remaining == 0 {
275 +
                items.push(label);
276 +
                continue;
277 +
            }
278 +
            let label_width = label.width();
279 +
            if label_width <= remaining {
280 +
                remaining -= label_width;
281 +
                continue;
282 +
            }
283 +
            let mut cols = 0;
284 +
            let mut boundary = 0;
285 +
            for (index, ch) in label.content().char_indices() {
286 +
                cols += char_width(ch);
287 +
                boundary = index + ch.len_utf8();
288 +
                if cols >= remaining {
289 +
                    break;
290 +
                }
291 +
            }
292 +
            items.push(Label::raw(
293 +
                label.content()[boundary..].to_owned(),
294 +
                label.paint.style,
295 +
            ));
296 +
            remaining = 0;
297 +
        }
298 +
        self.items = items;
299 +
    }
300 +
266 301
    /// Returns this line with one leading space and padding to the given width.
267 302
    pub fn inset(self, width: usize) -> Self {
268 303
        if width <= 2 {
269 304
            return self;
270 305
        }
crates/tui-widgets/src/dialog.rs +106 -16
171 171
    pub const fn margin(mut self, margin: Size) -> Self {
172 172
        self.margin = margin;
173 173
        self
174 174
    }
175 175
176 -
    /// Returns the largest panel size available inside `area`.
177 -
    fn available_max(&self, area: Rect) -> Size {
176 +
    /// Returns the effective margin, dropping it when compact content needs the space.
177 +
    fn effective_margin(&self, area: Rect) -> Size {
178 +
        Size::new(
179 +
            if area.cols >= self.margin.cols.saturating_mul(2).saturating_add(2) {
180 +
                self.margin.cols
181 +
            } else {
182 +
                0
183 +
            },
184 +
            if area.rows >= self.margin.rows.saturating_mul(2).saturating_add(5) {
185 +
                self.margin.rows
186 +
            } else {
187 +
                0
188 +
            },
189 +
        )
190 +
    }
191 +
192 +
    /// Returns the largest panel size available inside `area` and `margin`.
193 +
    fn available_max(&self, area: Rect, margin: Size) -> Size {
178 194
        Size::new(
179 195
            self.max_size
180 196
                .cols
181 -
                .min(area.cols.saturating_sub(self.margin.cols.saturating_mul(2))),
197 +
                .min(area.cols.saturating_sub(margin.cols.saturating_mul(2))),
182 198
            self.max_size
183 199
                .rows
184 -
                .min(area.rows.saturating_sub(self.margin.rows.saturating_mul(2))),
200 +
                .min(area.rows.saturating_sub(margin.rows.saturating_mul(2))),
185 201
        )
186 202
    }
187 203
188 -
    /// Returns the dialog size under `max`.
189 -
    fn panel_size(&self, max: Size) -> Size {
190 -
        let action = self.action_line();
191 -
        let body_width = self.body.iter().map(Line::width).max().unwrap_or_default();
192 -
        let content_width = self.heading.width().max(body_width).max(action.width());
193 -
        let content_rows = 1
194 -
            + usize::from(!self.body.is_empty() || !self.actions.items().is_empty())
204 +
    /// Returns the dialog's natural content height.
205 +
    fn content_rows(&self) -> usize {
206 +
        1 + usize::from(!self.body.is_empty() || !self.actions.items().is_empty())
195 207
            + self.body.len()
196 208
            + if self.actions.items().is_empty() {
197 209
                0
198 210
            } else {
199 211
                2
200 -
            };
212 +
            }
213 +
    }
214 +
215 +
    /// Returns the dialog size under `max`.
216 +
    fn panel_size(&self, max: Size) -> Size {
217 +
        let action = self.action_line();
218 +
        let body_width = self.body.iter().map(Line::width).max().unwrap_or_default();
219 +
        let content_width = self.heading.width().max(body_width).max(action.width());
220 +
        let content_rows = self.content_rows();
201 221
        let size = Size::new(
202 222
            content_width
203 223
                .saturating_add(DIALOG_PADDING.saturating_mul(2))
204 224
                .saturating_add(2),
205 225
            content_rows.saturating_add(2),
238 258
    fn size(&self, parent: Constraint) -> Size {
239 259
        parent.bounded_size()
240 260
    }
241 261
242 262
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
243 -
        let max = self.available_max(area);
263 +
        let margin = self.effective_margin(area);
264 +
        let max = self.available_max(area, margin);
244 265
        let size = self.panel_size(max);
245 -
        let area = overlay_area(area, size, self.margin);
266 +
        let area = overlay_area(area, size, margin);
246 267
247 268
        if area.is_empty() {
248 269
            return;
249 270
        }
250 271
257 278
            .saturating_sub(DIALOG_PADDING.saturating_mul(2));
258 279
        let content_x = content.x + DIALOG_PADDING.min(content.cols);
259 280
        let heading_area = Rect::new(content_x, content.y, content_cols, 1);
260 281
        self.render_heading(heading_area, buf);
261 282
283 +
        let compact = content.rows < self.content_rows();
262 284
        let action_area = if self.actions.items().is_empty() || content.rows < 2 {
263 285
            Rect::ZERO
264 286
        } else {
265 287
            Rect::new(
266 288
                content_x,
267 289
                content.bottom().saturating_sub(1),
268 290
                content_cols,
269 291
                1,
270 292
            )
271 293
        };
272 -
        let body_y = content.y.saturating_add(2);
294 +
        let body_y = content.y.saturating_add(if compact { 1 } else { 2 });
273 295
        let body_bottom = if action_area.is_empty() {
274 296
            content.bottom()
275 297
        } else {
276 -
            action_area.y.saturating_sub(1)
298 +
            action_area.y.saturating_sub(usize::from(!compact))
277 299
        };
278 300
        let body_area = Rect::new(
279 301
            content_x,
280 302
            body_y,
281 303
            content_cols,
324 346
        dialog.render(buffer.area(), &mut buffer);
325 347
326 348
        assert!(first_position_with_background(&buffer, Color::Fixed(250)).is_some());
327 349
    }
328 350
351 +
    #[test]
352 +
    fn compact_dialog_keeps_body_and_actions_visible() {
353 +
        let mut dialog = Dialog::error()
354 +
            .body_line("The existing review is stale.")
355 +
            .actions(
356 +
                ActionList::new()
357 +
                    .action("enter", "rebase")
358 +
                    .action("x", "reset")
359 +
                    .action("esc", "quit"),
360 +
            );
361 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 80, 5));
362 +
363 +
        dialog.render(buffer.area(), &mut buffer);
364 +
365 +
        let text = buffer_text(&buffer);
366 +
        assert!(
367 +
            text.contains("The existing review is stale."),
368 +
            "text: {text:?}"
369 +
        );
370 +
        assert!(text.contains("rebase"), "text: {text:?}");
371 +
        assert!(text.contains("reset"), "text: {text:?}");
372 +
        assert!(text.contains("quit"), "text: {text:?}");
373 +
    }
374 +
375 +
    #[test]
376 +
    fn capped_dialog_keeps_complete_body_visible() {
377 +
        let mut dialog = Dialog::error()
378 +
            .body([
379 +
                Line::new("The existing review is stale."),
380 +
                Line::new("Its resolved commits no longer match this branch."),
381 +
                Line::blank(),
382 +
                Line::new("Rebasing carries matching accepted hunks forward."),
383 +
                Line::new("Changed or new hunks are left for review."),
384 +
            ])
385 +
            .actions(
386 +
                ActionList::new()
387 +
                    .action("enter", "rebase")
388 +
                    .action("x", "reset")
389 +
                    .action("esc", "quit"),
390 +
            )
391 +
            .max_size(Size::new(78, 10));
392 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 80, 12));
393 +
394 +
        dialog.render(buffer.area(), &mut buffer);
395 +
396 +
        let text = buffer_text(&buffer);
397 +
        assert!(
398 +
            text.contains("Changed or new hunks are left for review."),
399 +
            "text: {text:?}"
400 +
        );
401 +
        assert!(text.contains("rebase"), "text: {text:?}");
402 +
        assert!(text.contains("reset"), "text: {text:?}");
403 +
        assert!(text.contains("quit"), "text: {text:?}");
404 +
    }
329 405
    #[test]
330 406
    fn tiny_dialog_drops_actions_instead_of_overwriting_the_heading() {
331 407
        let mut dialog = Dialog::error()
332 408
            .actions(ActionList::new().action("q", "quit"))
333 409
            .max_size(Size::new(24, 3))
354 430
355 431
        assert_eq!(key, Some(Color::Black));
356 432
        assert!(label.is_some());
357 433
    }
358 434
435 +
    /// Returns all visible buffer cells as newline-separated text.
436 +
    fn buffer_text(buffer: &Buffer) -> String {
437 +
        let mut text = String::new();
438 +
        for y in 0..buffer.area().rows {
439 +
            for x in 0..buffer.area().cols {
440 +
                if let Some(cell) = buffer.get(x, y) {
441 +
                    text.push_str(&cell.glyph());
442 +
                }
443 +
            }
444 +
            text.push('\n');
445 +
        }
446 +
        text
447 +
    }
448 +
359 449
    /// Returns the first position whose foreground color is `foreground`.
360 450
    fn first_position_with_foreground(
361 451
        buffer: &Buffer,
362 452
        foreground: Color,
363 453
    ) -> Option<(usize, usize)> {