brain: Simplify session visibility state

a5567d2e557f9ebbe30a899ae13e2b169f3e6910
Model accepted-hunk and file visibility as explicit modes, and derive
file visibility from the active viewer. Remove redundant session tests
that required full session construction.

Assisted-by: Codex:gpt-5.6-sol
Alexis Sellier committed ago 1 parent 3157f067
crates/brain/src/review.rs +34 -4
8 8
9 9
use std::collections::BTreeSet;
10 10
11 11
use rustik_diff::HunkId;
12 12
13 +
/// Visibility of accepted hunks in commit diffs.
14 +
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
15 +
pub enum AcceptedVisibility {
16 +
    /// Hide accepted hunks.
17 +
    #[default]
18 +
    Hidden,
19 +
    /// Show accepted hunks.
20 +
    Shown,
21 +
}
22 +
23 +
impl AcceptedVisibility {
24 +
    /// Switches between hidden and shown accepted hunks.
25 +
    pub fn toggle(&mut self) {
26 +
        *self = match self {
27 +
            Self::Hidden => Self::Shown,
28 +
            Self::Shown => Self::Hidden,
29 +
        };
30 +
    }
31 +
}
32 +
33 +
/// Visibility of the active file outside its diff hunks.
34 +
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
35 +
pub enum FileVisibility {
36 +
    /// Show bounded diff context.
37 +
    #[default]
38 +
    Context,
39 +
    /// Show the full file.
40 +
    Full,
41 +
}
42 +
13 43
/// Visibility modes reported by the active review view.
14 44
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
15 45
pub struct Visibility {
16 -
    /// Show accepted hunks instead of hiding them.
17 -
    pub show_accepted: bool,
18 -
    /// Show the active file's full source instead of bounded hunk context.
19 -
    pub full_file: bool,
46 +
    /// Visibility of accepted hunks.
47 +
    pub accepted: AcceptedVisibility,
48 +
    /// Visibility of the active file.
49 +
    pub file: FileVisibility,
20 50
}
21 51
22 52
/// Per-hunk acceptance state for one commit.
23 53
#[derive(Clone, Debug, Default)]
24 54
pub struct Review {
crates/brain/src/session.rs +26 -275
18 18
use rustik_tui_termion as tui_termion;
19 19
20 20
use crate::backend::{Backend, Brain, Commit, CommitHunks, FilePatches, HistoryStatus};
21 21
use crate::comments::ReviewComments;
22 22
use crate::error::Error;
23 -
use crate::review::Visibility;
23 +
use crate::review::{AcceptedVisibility, FileVisibility, Visibility};
24 24
25 25
mod commit;
26 26
mod event;
27 27
mod hunk;
28 28
mod status;
64 64
            Self::Commits => "history",
65 65
            Self::Diff => "commit",
66 66
            Self::Hunk(_) => "hunk",
67 67
        }
68 68
    }
69 -
}
70 69
71 -
/// Returns a footer visibility snapshot reconciled with the active viewer.
72 -
fn active_visibility(
73 -
    mut visibility: Visibility,
74 -
    mode: &Mode,
75 -
    loaded: Option<&CommitReview>,
76 -
) -> Visibility {
77 -
    visibility.full_file =
78 -
        matches!(mode, Mode::Diff) && loaded.is_some_and(CommitReview::is_full_file);
79 -
    visibility
70 +
    /// Returns the active file's visibility for this view.
71 +
    fn file_visibility(&self, loaded: Option<&CommitReview>) -> FileVisibility {
72 +
        if matches!(self, Self::Diff) && loaded.is_some_and(CommitReview::is_full_file) {
73 +
            FileVisibility::Full
74 +
        } else {
75 +
            FileVisibility::Context
76 +
        }
77 +
    }
80 78
}
81 79
82 80
/// Terminal event channel shared by pre-session prompts and the session loop.
83 81
///
84 82
/// Reading terminal input consumes it, so one input worker must feed every
186 184
        commits: slots,
187 185
        range,
188 186
        history_status,
189 187
        accepted_hunks: Vec::new(),
190 188
        current: 0,
191 -
        show_accepted: false,
189 +
        accepted_visibility: AcceptedVisibility::default(),
192 190
        mode,
193 191
        parked: None,
194 192
        list: ListState::new(),
195 193
        options,
196 194
        backend,
255 253
    history_status: Option<HistoryStatus>,
256 254
    /// Hunk acceptances available to undo, in acceptance order.
257 255
    accepted_hunks: Vec<(usize, rustik_diff::HunkId)>,
258 256
    /// Index of the commit currently displayed.
259 257
    current: usize,
260 -
    /// Whether accepted hunks are visible across commit viewers.
261 -
    show_accepted: bool,
258 +
    /// Visibility of accepted hunks across commit viewers.
259 +
    accepted_visibility: AcceptedVisibility,
262 260
    /// Active view: the commit list, the diff, or a hunk's comment box.
263 261
    mode: Mode,
264 262
    /// Hunk view kept alive while another tab is active, for Tab round-trips.
265 263
    parked: Option<Box<HunkView>>,
266 264
    /// Selection and scroll state for the commit-list tab.
404 402
            Event::Key(Key::Char('A')) => {
405 403
                self.toggle_focused_file(area)?;
406 404
                Ok(Control::Redraw)
407 405
            }
408 406
            Event::Key(Key::Char('v')) => {
409 -
                self.show_accepted = !self.show_accepted;
407 +
                self.accepted_visibility.toggle();
410 408
                self.refresh_visibility()?;
411 409
                Ok(Control::Redraw)
412 410
            }
413 411
            Event::Key(Key::Char('j')) => self.apply(DiffAction::NextHunk, area),
414 412
            Event::Key(Key::Char('k')) => self.apply(DiffAction::PreviousHunk, area),
527 525
        } else {
528 526
            self.accept_hunks(BTreeSet::from([(self.current, hunk)]))?;
529 527
            self.accepted_hunks.push((self.current, hunk));
530 528
        }
531 529
        self.reconcile_reviews()?;
532 -
        if !accepted && !self.show_accepted {
530 +
        if !accepted && matches!(self.accepted_visibility, AcceptedVisibility::Hidden) {
533 531
            self.current()?.viewer.apply(DiffAction::NextHunk, area);
534 532
        }
535 533
536 534
        Ok(())
537 535
    }
999 997
    /// Rebuilds the current commit's files to match accepted-hunk visibility.
1000 998
    ///
1001 999
    /// The original decoded document is kept in `CommitReview::document`; the
1002 1000
    /// viewer receives a filtered copy when accepted hunks are hidden.
1003 1001
    fn refresh_visibility(&mut self) -> Result<(), Error> {
1004 -
        let show_accepted = self.show_accepted;
1002 +
        let accepted_visibility = self.accepted_visibility;
1005 1003
        let area = viewer_area(self.terminal.area());
1006 1004
        let loaded = self.current()?;
1007 1005
1008 -
        let files: Vec<FileDiff> = if show_accepted {
1006 +
        let files: Vec<FileDiff> = if matches!(accepted_visibility, AcceptedVisibility::Shown) {
1009 1007
            loaded.document.files.clone()
1010 1008
        } else {
1011 1009
            loaded
1012 1010
                .document
1013 1011
                .files
1052 1050
1053 1051
    /// Reconciles review state and refreshes the active viewer when needed.
1054 1052
    fn reconcile_reviews(&mut self) -> Result<(), Error> {
1055 1053
        self.reconcile_state();
1056 1054
        self.history_status = None;
1057 -
        if !self.show_accepted && !matches!(self.mode, Mode::Commits) {
1055 +
        if matches!(self.accepted_visibility, AcceptedVisibility::Hidden)
1056 +
            && !matches!(self.mode, Mode::Commits)
1057 +
        {
1058 1058
            self.refresh_visibility()?;
1059 1059
        }
1060 1060
        Ok(())
1061 1061
    }
1062 1062
1277 1277
            .set_cursor_visible(matches!(self.mode, Mode::Hunk(ref view) if view.is_editing()))
1278 1278
    }
1279 1279
1280 1280
    /// Returns the footer chrome for the current session mode.
1281 1281
    fn chrome(&self) -> Chrome {
1282 -
        let loaded = self.commits[self.current].loaded.as_ref();
1283 -
        let visibility = active_visibility(
1284 -
            Visibility {
1285 -
                show_accepted: self.show_accepted,
1286 -
                full_file: false,
1287 -
            },
1288 -
            &self.mode,
1289 -
            loaded,
1290 -
        );
1282 +
        let visibility = Visibility {
1283 +
            accepted: self.accepted_visibility,
1284 +
            file: self
1285 +
                .mode
1286 +
                .file_visibility(self.commits[self.current].loaded.as_ref()),
1287 +
        };
1291 1288
        let (context, progress, stats) = if matches!(self.mode, Mode::Commits) {
1292 1289
            let status = self.history_status.as_ref();
1293 1290
            (
1294 1291
                StatusContext::Range(self.range.clone()),
1295 1292
                status.map_or_else(ReviewProgress::default, |status| status.progress),
1343 1340
}
1344 1341
1345 1342
#[cfg(test)]
1346 1343
mod tests {
1347 1344
    use std::collections::BTreeMap;
1348 -
    use std::fs;
1349 -
    use std::path::{Path, PathBuf};
1350 -
    use std::process::Command;
1351 -
    use std::time::{SystemTime, UNIX_EPOCH};
1352 1345
1353 1346
    use rustik_diff::{ContextChange, Decode as _};
1354 1347
1355 -
    use rustik_repo::Rev;
1356 -
    use rustik_tui::{Point, Size};
1357 -
1358 1348
    use super::*;
1359 1349
    use crate::comments::Comments;
1360 1350
    use crate::review::Review;
1361 1351
1362 -
    /// In-memory terminal backend with the production backend's error type.
1363 -
    struct IoTestBackend {
1364 -
        /// Fixed terminal size.
1365 -
        size: Size,
1366 -
    }
1367 -
1368 -
    impl TuiBackend for IoTestBackend {
1369 -
        type Error = io::Error;
1370 -
1371 -
        fn size(&mut self) -> io::Result<Size> {
1372 -
            Ok(self.size)
1373 -
        }
1374 -
1375 -
        fn draw(&mut self, _: &[rustik_tui::buffer::DirtyRun<'_>]) -> io::Result<()> {
1376 -
            Ok(())
1377 -
        }
1378 -
1379 -
        fn clear(&mut self) -> io::Result<()> {
1380 -
            Ok(())
1381 -
        }
1382 -
1383 -
        fn flush(&mut self) -> io::Result<()> {
1384 -
            Ok(())
1385 -
        }
1386 -
1387 -
        fn set_cursor_position(&mut self, _: Point) -> io::Result<()> {
1388 -
            Ok(())
1389 -
        }
1390 -
1391 -
        fn set_cursor_visible(&mut self, _: bool) -> io::Result<()> {
1392 -
            Ok(())
1393 -
        }
1394 -
    }
1395 -
1396 -
    /// Temporary Git repository containing one commit with two hunks.
1397 -
    struct RepositoryFixture {
1398 -
        /// Repository working tree.
1399 -
        path: PathBuf,
1400 -
    }
1401 -
1402 -
    impl RepositoryFixture {
1403 -
        /// Creates a repository whose tip changes two distant lines.
1404 -
        fn new() -> Self {
1405 -
            let nonce = SystemTime::now()
1406 -
                .duration_since(UNIX_EPOCH)
1407 -
                .unwrap()
1408 -
                .as_nanos();
1409 -
            let path = std::env::temp_dir().join(format!(
1410 -
                "rustik-brain-session-{}-{nonce}",
1411 -
                std::process::id()
1412 -
            ));
1413 -
            fs::create_dir(&path).unwrap();
1414 -
            Self::git(&path, &["init", "-q", "-b", "main", "."]);
1415 -
            fs::write(
1416 -
                path.join("review.txt"),
1417 -
                "\
1418 -
first
1419 -
unchanged 01
1420 -
unchanged 02
1421 -
unchanged 03
1422 -
unchanged 04
1423 -
unchanged 05
1424 -
unchanged 06
1425 -
unchanged 07
1426 -
unchanged 08
1427 -
unchanged 09
1428 -
unchanged 10
1429 -
unchanged 11
1430 -
unchanged 12
1431 -
unchanged 13
1432 -
last
1433 -
",
1434 -
            )
1435 -
            .unwrap();
1436 -
            Self::git(&path, &["add", "review.txt"]);
1437 -
            Self::git(&path, &["commit", "-q", "-m", "base"]);
1438 -
            fs::write(
1439 -
                path.join("review.txt"),
1440 -
                "\
1441 -
changed first
1442 -
unchanged 01
1443 -
unchanged 02
1444 -
unchanged 03
1445 -
unchanged 04
1446 -
unchanged 05
1447 -
unchanged 06
1448 -
unchanged 07
1449 -
unchanged 08
1450 -
unchanged 09
1451 -
unchanged 10
1452 -
unchanged 11
1453 -
unchanged 12
1454 -
unchanged 13
1455 -
changed last
1456 -
",
1457 -
            )
1458 -
            .unwrap();
1459 -
            Self::git(&path, &["add", "review.txt"]);
1460 -
            Self::git(&path, &["commit", "-q", "-m", "change"]);
1461 -
1462 -
            Self { path }
1463 -
        }
1464 -
1465 -
        /// Runs a Git command in the fixture repository.
1466 -
        fn git(path: &Path, args: &[&str]) {
1467 -
            let status = Command::new("git")
1468 -
                .args(["-c", "commit.gpgsign=false"])
1469 -
                .args(args)
1470 -
                .current_dir(path)
1471 -
                .env("GIT_AUTHOR_NAME", "Rustik Test")
1472 -
                .env("GIT_AUTHOR_EMAIL", "rustik@example.com")
1473 -
                .env("GIT_COMMITTER_NAME", "Rustik Test")
1474 -
                .env("GIT_COMMITTER_EMAIL", "rustik@example.com")
1475 -
                .status()
1476 -
                .unwrap();
1477 -
            assert!(status.success());
1478 -
        }
1479 -
    }
1480 -
1481 -
    impl Drop for RepositoryFixture {
1482 -
        fn drop(&mut self) {
1483 -
            fs::remove_dir_all(&self.path).unwrap();
1484 -
        }
1485 -
    }
1486 -
1487 1352
    #[test]
1488 -
    fn undo_rejects_last_hunk_accepted_with_focused_file() {
1489 -
        let repository = RepositoryFixture::new();
1490 -
        let base = Rev::try_from("HEAD^").unwrap();
1491 -
        let target = Rev::try_from("HEAD").unwrap();
1492 -
        let backend = <dyn Backend>::from_path(&repository.path, base, target).unwrap();
1493 -
        let brain = backend.brain().unwrap();
1494 -
        let commit = backend.commits().unwrap().pop().unwrap();
1495 -
        let remaining_stats = commit.stats;
1496 -
        let slot = CommitSlot {
1497 -
            commit,
1498 -
            progress: ReviewProgress::default(),
1499 -
            remaining_stats,
1500 -
            document: None,
1501 -
            identities: None,
1502 -
            loaded: None,
1503 -
        };
1504 -
        let mut terminal = Terminal::new(IoTestBackend {
1505 -
            size: Size::new(80, 24),
1506 -
        })
1507 -
        .unwrap();
1508 -
        let (events_tx, _events_rx) = mpsc::channel();
1509 -
        let mut session = Session {
1510 -
            terminal: &mut terminal,
1511 -
            commits: vec![slot],
1512 -
            range: "HEAD^..HEAD".to_owned(),
1513 -
            history_status: None,
1514 -
            accepted_hunks: Vec::new(),
1515 -
            current: 0,
1516 -
            show_accepted: false,
1517 -
            mode: Mode::Diff,
1518 -
            parked: None,
1519 -
            list: ListState::new(),
1520 -
            options: DiffOptions::default(),
1521 -
            backend,
1522 -
            brain,
1523 -
            comments: ReviewComments::parse("").unwrap(),
1524 -
            events_tx,
1525 -
            generation: 0,
1526 -
            highlighter: None,
1527 -
            context_fetch: ContextFetch::default(),
1528 -
            error: None,
1529 -
        };
1530 -
        let area = Rect::new(0, 0, 80, 23);
1531 -
        let hunk_ids = {
1532 -
            let loaded = session.current().unwrap();
1533 -
            loaded.viewer.apply(DiffAction::NextHunk, area);
1534 -
            loaded.document.files[0]
1535 -
                .hunks
1536 -
                .iter()
1537 -
                .map(|hunk| hunk.id)
1538 -
                .collect::<Vec<_>>()
1539 -
        };
1540 -
        assert_eq!(hunk_ids.len(), 2);
1541 -
1542 -
        session.toggle_focused_file(area).unwrap();
1543 -
        assert_eq!(
1544 -
            session.current().unwrap().review.accepted(),
1545 -
            &BTreeSet::from([hunk_ids[0], hunk_ids[1]])
1546 -
        );
1547 -
1548 -
        session.undo_last_hunk_accept().unwrap();
1549 -
        let loaded = session.current().unwrap();
1550 -
        assert_eq!(loaded.review.accepted(), &BTreeSet::from([hunk_ids[0]]));
1551 -
        assert_eq!(
1552 -
            loaded.viewer.document().files[0]
1553 -
                .hunks
1554 -
                .iter()
1555 -
                .map(|hunk| hunk.id)
1556 -
                .collect::<Vec<_>>(),
1557 -
            vec![hunk_ids[1]]
1558 -
        );
1559 -
    }
1560 -
1561 -
    #[test]
1562 -
    fn control_c_quits_commit_list() {
1563 -
        let event = Event::Key(Key::Ctrl('c'));
1564 -
1565 -
        assert_eq!(
1566 -
            terminal_interrupt(ActionContext::Commits, &event),
1567 -
            Control::Quit
1568 -
        );
1569 -
    }
1570 -
1571 -
    #[test]
1572 -
    fn control_c_quits_commit_diff() {
1573 -
        let event = Event::Key(Key::Ctrl('c'));
1574 -
1575 -
        assert_eq!(
1576 -
            terminal_interrupt(ActionContext::Commit, &event),
1577 -
            Control::Quit
1578 -
        );
1579 -
    }
1580 -
1581 -
    #[test]
1582 -
    fn control_c_quits_hunk_browser() {
1583 -
        let event = Event::Key(Key::Ctrl('c'));
1584 -
1585 -
        assert_eq!(
1586 -
            terminal_interrupt(ActionContext::HunkBrowse, &event),
1587 -
            Control::Quit
1588 -
        );
1589 -
    }
1590 -
1591 -
    #[test]
1592 -
    fn control_c_remains_comment_editor_input() {
1593 -
        let event = Event::Key(Key::Ctrl('c'));
1594 -
1595 -
        assert_eq!(
1596 -
            terminal_interrupt(ActionContext::HunkEdit, &event),
1597 -
            Control::Continue
1598 -
        );
1599 -
    }
1600 -
1601 -
    #[test]
1602 -
    fn footer_full_file_state_follows_the_selected_commit_viewer() {
1353 +
    fn file_visibility_follows_the_selected_commit_viewer() {
1603 1354
        let patch = "\
1604 1355
a.rs +0 -0
crates/brain/src/session/status.rs +8 -10
11 11
    Border, Buffer, Color, Constraint, HStack, Label, Line, Rect, Size, Style, Table, TableOptions,
12 12
    Widget, colors,
13 13
};
14 14
15 15
use crate::comments::Comment;
16 -
use crate::review::Visibility;
16 +
use crate::review::{AcceptedVisibility, FileVisibility, Visibility};
17 17
18 18
use super::commit::CommitSlot;
19 19
20 20
/// Number of rows used by the status bar.
21 21
const STATUS_ROWS: usize = 1;
137 137
    pub(super) progress: ReviewProgress,
138 138
    /// Aggregated diff size for the active review context.
139 139
    pub(super) stats: DiffStat,
140 140
    /// Diff palette used for stat and review colors.
141 141
    pub(super) palette: DiffPalette,
142 -
    /// Session-wide accepted-hunk visibility.
142 +
    /// Visibility modes for the active review view.
143 143
    pub(super) visibility: Visibility,
144 144
    /// Most recent recoverable session error.
145 145
    pub(super) error: Option<String>,
146 146
}
147 147
211 211
            .style(Style::default().bg(FOOTER_BG))
212 212
    }
213 213
214 214
    /// Returns the right status section with review state and diff statistics.
215 215
    fn right_status(&self) -> Line {
216 -
        let accepted_fg = if self.visibility.show_accepted {
217 -
            self.palette.positive_fg
218 -
        } else {
219 -
            FOOTER_FG
216 +
        let accepted_fg = match self.visibility.accepted {
217 +
            AcceptedVisibility::Hidden => FOOTER_FG,
218 +
            AcceptedVisibility::Shown => self.palette.positive_fg,
220 219
        };
221 -
        let full_file_fg = if self.visibility.full_file {
222 -
            FULL_FILE_MODE_FG
223 -
        } else {
224 -
            FOOTER_FG
220 +
        let full_file_fg = match self.visibility.file {
221 +
            FileVisibility::Context => FOOTER_FG,
222 +
            FileVisibility::Full => FULL_FILE_MODE_FG,
225 223
        };
226 224
        let files = file_count(self.stats.files_changed);
227 225
228 226
        Line::blank()
229 227
            .extend(progress_bar(self.progress, self.palette, FOOTER_FG))