brain: Improve review controls

21cddbe167d5cfd568bbf5d162861c438f305d94
Add hunk comment browsing, editing, and deletion to the review TUI, and
let reviewers toggle accepted hunks or whole files without leaving the
session.

Teach the repository layer to reverse-apply patches so unaccepting
content updates the hidden review tree consistently.

Assisted-by: Codex:gpt-5.5
Alexis Sellier committed ago 1 parent 50331058
crates/brain/src/backend.rs +11 -0
222 222
    /// accepted hunk produces a new synthetic commit whose parent remains the
223 223
    /// exact review base, so later loads can reject state from a different base
224 224
    /// instead of trying to reinterpret it.
225 225
    pub fn apply_patch(&mut self, patch: &str) -> Result<(), Error> {
226 226
        let tree = self.repository.apply_patch_to_tree(self.commit, patch)?;
227 +
        self.advance_to_tree(tree)
228 +
    }
229 +
230 +
    /// Applies the reverse of one selected hunk patch to the hidden tree.
231 +
    pub fn reverse_patch(&mut self, patch: &str) -> Result<(), Error> {
232 +
        let tree = self.repository.reverse_patch_to_tree(self.commit, patch)?;
233 +
        self.advance_to_tree(tree)
234 +
    }
235 +
236 +
    /// Persists `tree` as the current accepted review state.
237 +
    fn advance_to_tree(&mut self, tree: Oid) -> Result<(), Error> {
227 238
        let commit = self.repository.commit(
228 239
            tree,
229 240
            self.base,
230 241
            "brain",
231 242
            "brain@example.invalid",
crates/brain/src/comments.rs +98 -0
193 193
        self.records.push(record);
194 194
195 195
        comment
196 196
    }
197 197
198 +
    /// Replaces the body of the comment with `id`.
199 +
    fn edit(&mut self, id: &CommentId, body: String) -> bool {
200 +
        let Some(record) = self.records.iter_mut().find(|record| record.id == *id) else {
201 +
            return false;
202 +
        };
203 +
        record.body = body;
204 +
        true
205 +
    }
206 +
207 +
    /// Deletes the comment with `id`.
208 +
    fn delete(&mut self, id: &CommentId) -> bool {
209 +
        let Some(index) = self.records.iter().position(|record| record.id == *id) else {
210 +
            return false;
211 +
        };
212 +
        self.records.remove(index);
213 +
        true
214 +
    }
215 +
198 216
    /// Returns the next stable local comment id.
199 217
    fn next_id(&self) -> CommentId {
200 218
        let next = self
201 219
            .records
202 220
            .iter()
241 259
        let comment = store.add(target, body);
242 260
        self.by_hunk.entry(hunk).or_default().push(comment);
243 261
        true
244 262
    }
245 263
264 +
    /// Edits one comment on `hunk`.
265 +
    pub fn edit(
266 +
        &mut self,
267 +
        store: &mut ReviewComments,
268 +
        hunk: HunkId,
269 +
        id: &CommentId,
270 +
        body: String,
271 +
    ) -> bool {
272 +
        let Some(comments) = self.by_hunk.get_mut(&hunk) else {
273 +
            return false;
274 +
        };
275 +
        let Some(comment) = comments.iter_mut().find(|comment| comment.id == *id) else {
276 +
            return false;
277 +
        };
278 +
        if !store.edit(id, body.clone()) {
279 +
            return false;
280 +
        }
281 +
        comment.body = body;
282 +
        true
283 +
    }
284 +
285 +
    /// Deletes one comment from `hunk`.
286 +
    pub fn delete(&mut self, store: &mut ReviewComments, hunk: HunkId, id: &CommentId) -> bool {
287 +
        let Some(comments) = self.by_hunk.get_mut(&hunk) else {
288 +
            return false;
289 +
        };
290 +
        let Some(index) = comments.iter().position(|comment| comment.id == *id) else {
291 +
            return false;
292 +
        };
293 +
        if !store.delete(id) {
294 +
            return false;
295 +
        }
296 +
        comments.remove(index);
297 +
        if comments.is_empty() {
298 +
            self.by_hunk.remove(&hunk);
299 +
        }
300 +
        true
301 +
    }
302 +
246 303
    /// Returns the comments authored on `hunk`.
247 304
    pub fn for_hunk(&self, hunk: HunkId) -> &[Comment] {
248 305
        self.by_hunk.get(&hunk).map_or(&[], Vec::as_slice)
249 306
    }
250 307
288 345
289 346
#[cfg(test)]
290 347
mod tests {
291 348
    use super::*;
292 349
350 +
    /// Hunk used by comment view tests.
351 +
    const HUNK: HunkId = HunkId::new(0);
352 +
353 +
    /// Builds an empty comment store and matching hunk view.
354 +
    fn empty_comments() -> (ReviewComments, Comments) {
355 +
        let target = CommentTarget {
356 +
            heading: "h".to_owned(),
357 +
            path: None,
358 +
            patch_id: PatchId::from("p".to_owned()),
359 +
        };
360 +
        let mut targets = BTreeMap::new();
361 +
        targets.insert(HUNK, target);
362 +
        let store = ReviewComments::parse("").unwrap();
363 +
        let comments = Comments::new(&store, targets);
364 +
        (store, comments)
365 +
    }
366 +
293 367
    #[test]
294 368
    fn comment_id_serializes_as_number() {
295 369
        let id = CommentId::from(7);
296 370
297 371
        assert_eq!(json::to_string(&id), "7");
305 379
        )
306 380
        .unwrap();
307 381
308 382
        assert_eq!(store.next_id(), CommentId::from(8));
309 383
    }
384 +
385 +
    #[test]
386 +
    fn comments_edit_updates_store_and_view() {
387 +
        let (mut store, mut comments) = empty_comments();
388 +
389 +
        assert!(comments.author(&mut store, HUNK, "old".to_owned()));
390 +
        let id = comments.for_hunk(HUNK)[0].id.clone();
391 +
        assert!(comments.edit(&mut store, HUNK, &id, "new".to_owned()));
392 +
393 +
        assert_eq!(comments.for_hunk(HUNK)[0].body, "new");
394 +
        assert!(store.encode().contains(r#""body":"new""#));
395 +
    }
396 +
397 +
    #[test]
398 +
    fn comments_delete_updates_store_and_view() {
399 +
        let (mut store, mut comments) = empty_comments();
400 +
401 +
        assert!(comments.author(&mut store, HUNK, "body".to_owned()));
402 +
        let id = comments.for_hunk(HUNK)[0].id.clone();
403 +
        assert!(comments.delete(&mut store, HUNK, &id));
404 +
405 +
        assert!(comments.for_hunk(HUNK).is_empty());
406 +
        assert!(store.encode().is_empty());
407 +
    }
310 408
}
crates/brain/src/session.rs +152 -25
6 6
7 7
use rustik_diff::{
8 8
    ContextChange, DiffAction, DiffDocument, DiffFocus, DiffOptions, DiffViewer, FileDiff,
9 9
    FileTreeMode, HighlightOutput, HighlightRequest, Highlighter, ViewChange, spawn_highlighter,
10 10
};
11 -
use rustik_tui::{
12 -
    Control, Event, Key, Line, List, ListState, Mouse, MouseButton, Rect, Terminal, TextInput,
13 -
};
11 +
use rustik_tui::{Control, Event, Key, Line, List, ListState, Mouse, MouseButton, Rect, Terminal};
14 12
use rustik_tui_termion as tui_termion;
15 13
16 14
use crate::backend::{Backend, Brain, Commit, CommitHunks};
17 15
use crate::comments::ReviewComments;
18 16
use crate::error::Error;
23 21
mod hunk;
24 22
mod status;
25 23
26 24
use commit::{CommitReview, CommitSlot};
27 25
use event::{ContextFetch, Resize, TerminalEvent, Update, context_change};
28 -
use hunk::HunkView;
26 +
use hunk::{CommentEdit, HunkView};
29 27
use status::{Status, comment_block_lines, commit_row, viewer_area};
30 28
31 29
/// Terminal backend used by the interactive viewer.
32 30
type BrainTerminal = Terminal<tui_termion::TermionBackend<tui_termion::term::TerminalScreen>>;
33 31
185 183
                    Mode::Diff => {
186 184
                        if let Some(change) = context_change(&event) {
187 185
                            // Context expansion is asynchronous and may not
188 186
                            // redraw immediately, so it bypasses the ordinary
189 187
                            // diff input path.
188 +
                            if change == ContextChange::ToggleFile {
189 +
                                self.visibility.full_file = !self.visibility.full_file;
190 +
                            }
190 191
                            self.request_context(change);
191 192
                            return Ok(Update::Continue);
192 193
                        }
193 194
                        let area = viewer_area(self.terminal.area());
194 195
                        self.handle_key(event, area)?
230 231
231 232
    /// Dispatches one input event, handling review keys before the viewer.
232 233
    fn handle_key(&mut self, event: Event<()>, area: Rect) -> Result<Control, Error> {
233 234
        match event {
234 235
            Event::Key(Key::Char('a')) => {
235 -
                self.accept_focused(area)?;
236 +
                self.toggle_focused_hunk(area)?;
237 +
                Ok(Control::Redraw)
238 +
            }
239 +
            Event::Key(Key::Char('A')) => {
240 +
                self.toggle_focused_file(area)?;
236 241
                Ok(Control::Redraw)
237 242
            }
238 243
            Event::Key(Key::Char('v')) => {
239 244
                self.visibility.show_accepted = !self.visibility.show_accepted;
240 245
                self.refresh_visibility()?;
333 338
    /// Persists acceptance of the focused hunk, or focuses one when none is.
334 339
    ///
335 340
    /// Accepting updates the hidden tree first, then rebuilds all per-commit
336 341
    /// accepted hunk sets from that tree. The visible commit state is derived
337 342
    /// rather than patched locally so overlapping commits stay consistent.
338 -
    fn accept_focused(&mut self, area: Rect) -> Result<(), Error> {
343 +
    fn toggle_focused_hunk(&mut self, area: Rect) -> Result<(), Error> {
339 344
        let loaded = self.current()?;
340 345
        let Some(DiffFocus::Hunk(hunk)) = loaded.viewer.state().focus else {
341 346
            // No hunk is focused yet: move focus to the first hunk so the next
342 -
            // accept has an unambiguous target.
347 +
            // toggle has an unambiguous target.
343 348
            loaded.viewer.apply(DiffAction::NextHunk, area);
344 349
            return Ok(());
345 350
        };
346 -
        if loaded.review.is_accepted(hunk) {
347 -
            return Ok(());
348 -
        }
349 351
        let Some(patch) = loaded.hunk_patches.get(&hunk).cloned() else {
350 352
            return Ok(());
351 353
        };
352 -
        self.brain.apply_patch(&patch)?;
354 +
        if loaded.review.is_accepted(hunk) {
355 +
            self.brain.reverse_patch(&patch)?;
356 +
        } else {
357 +
            self.brain.apply_patch(&patch)?;
358 +
        }
353 359
        self.reconcile_reviews()?;
354 360
355 361
        Ok(())
356 362
    }
357 363
364 +
    /// Persists acceptance or rejection of every hunk in the focused file.
365 +
    fn toggle_focused_file(&mut self, area: Rect) -> Result<(), Error> {
366 +
        let loaded = self.current()?;
367 +
        let Some(file) = loaded.viewer.focused_file() else {
368 +
            loaded.viewer.apply(DiffAction::NextHunk, area);
369 +
            return Ok(());
370 +
        };
371 +
        let Some(file) = loaded.files.iter().find(|candidate| candidate.id == file) else {
372 +
            return Ok(());
373 +
        };
374 +
        let hunk_ids = file.hunks.iter().map(|hunk| hunk.id).collect::<Vec<_>>();
375 +
        let accepted = loaded.review.accepts_all(hunk_ids.iter().copied());
376 +
        let mut patches = hunk_ids
377 +
            .into_iter()
378 +
            .filter(|hunk| loaded.review.is_accepted(*hunk) == accepted)
379 +
            .filter_map(|hunk| loaded.hunk_patches.get(&hunk).cloned())
380 +
            .collect::<Vec<_>>();
381 +
        if accepted {
382 +
            patches.reverse();
383 +
            for patch in patches {
384 +
                self.brain.reverse_patch(&patch)?;
385 +
            }
386 +
        } else {
387 +
            for patch in patches {
388 +
                self.brain.apply_patch(&patch)?;
389 +
            }
390 +
        }
391 +
        self.reconcile_reviews()?;
392 +
        Ok(())
393 +
    }
394 +
358 395
    /// Opens the hunk view for the focused hunk to author a comment.
359 396
    fn enter_hunk_view(&mut self, area: Rect) -> Result<(), Error> {
360 397
        let focus = self.current()?.viewer.state().focus;
361 398
        let Some(DiffFocus::Hunk(hunk)) = focus else {
362 399
            // Focus the first hunk so a later press has a target to comment on.
380 417
            return Ok(());
381 418
        };
382 419
        let document = DiffDocument::for_hunks(file, [focused.clone()]);
383 420
        let viewer = DiffViewer::new(document, options);
384 421
385 -
        self.mode = Mode::Hunk(Box::new(HunkView {
386 -
            hunk,
387 -
            viewer,
388 -
            input: TextInput::new(),
389 -
        }));
422 +
        self.mode = Mode::Hunk(Box::new(HunkView::new(hunk, viewer)));
390 423
391 424
        Ok(())
392 425
    }
393 426
394 427
    /// Switches to the next review tab, parking any open hunk view.
411 444
        };
412 445
    }
413 446
414 447
    /// Routes one key to the comment editor while the hunk view is open.
415 448
    fn handle_hunk_key(&mut self, event: Event<()>) -> Result<Control, Error> {
449 +
        let comment_count = self.hunk_comment_count();
450 +
        if let Mode::Hunk(view) = &mut self.mode
451 +
            && !view.is_editing()
452 +
        {
453 +
            match event {
454 +
                Event::Key(Key::Esc) => {
455 +
                    self.mode = Mode::Diff;
456 +
                    return Ok(Control::Redraw);
457 +
                }
458 +
                Event::Key(Key::Tab) => {
459 +
                    self.next_tab();
460 +
                    return Ok(Control::Redraw);
461 +
                }
462 +
                Event::Key(Key::Char('c') | Key::Enter) => {
463 +
                    view.start_new();
464 +
                    return Ok(Control::Redraw);
465 +
                }
466 +
                Event::Key(Key::Char('n')) => {
467 +
                    view.select_next(comment_count);
468 +
                    return Ok(Control::Redraw);
469 +
                }
470 +
                Event::Key(Key::Char('p')) => {
471 +
                    view.select_previous();
472 +
                    return Ok(Control::Redraw);
473 +
                }
474 +
                Event::Key(Key::Char('e')) => {
475 +
                    self.edit_selected_comment();
476 +
                    return Ok(Control::Redraw);
477 +
                }
478 +
                Event::Key(Key::Char('d')) => {
479 +
                    self.delete_selected_comment()?;
480 +
                    return Ok(Control::Redraw);
481 +
                }
482 +
                Event::Resize(_) => return Ok(Control::Redraw),
483 +
                _ => return Ok(Control::Continue),
484 +
            }
485 +
        }
416 486
        match event {
417 487
            Event::Key(Key::Esc) => {
418 -
                self.mode = Mode::Diff;
488 +
                if let Mode::Hunk(view) = &mut self.mode {
489 +
                    view.cancel_edit();
490 +
                }
419 491
                return Ok(Control::Redraw);
420 492
            }
421 493
            Event::Key(Key::Tab) => {
422 494
                self.next_tab();
423 495
                return Ok(Control::Redraw);
432 504
        }
433 505
        let Mode::Hunk(view) = &mut self.mode else {
434 506
            return Ok(Control::Continue);
435 507
        };
436 508
        let changed = match event {
437 -
            Event::Key(Key::Enter) => view.input.newline(),
438 -
            Event::Key(key) => view.input.input(key),
509 +
            Event::Key(Key::Enter) => view.newline(),
510 +
            Event::Key(key) => view.input(key),
439 511
            Event::Resize(_) => true,
440 512
            _ => false,
441 513
        };
442 514
        Ok(if changed {
443 515
            Control::Redraw
449 521
    /// Stores the authored comment, if any, and clears the input box.
450 522
    fn save_comment(&mut self) -> Result<(), Error> {
451 523
        let Mode::Hunk(view) = &mut self.mode else {
452 524
            return Ok(());
453 525
        };
454 -
        if view.input.is_empty() {
526 +
        let hunk = view.hunk;
527 +
        let Some((target, body)) = view.finish_edit() else {
455 528
            return Ok(());
529 +
        };
530 +
        let Some(loaded) = &mut self.commits[self.current].loaded else {
531 +
            return Ok(());
532 +
        };
533 +
        let changed = match target {
534 +
            CommentEdit::Add => loaded.comments.author(&mut self.comments, hunk, body),
535 +
            CommentEdit::Edit(id) => loaded.comments.edit(&mut self.comments, hunk, &id, body),
536 +
        };
537 +
        if changed {
538 +
            self.brain.write_comments(&self.comments.encode())?;
539 +
            loaded.refresh_decorations();
456 540
        }
541 +
        Ok(())
542 +
    }
543 +
544 +
    /// Returns the number of comments on the active hunk.
545 +
    fn hunk_comment_count(&self) -> usize {
546 +
        let Mode::Hunk(view) = &self.mode else {
547 +
            return 0;
548 +
        };
549 +
        self.commits[self.current]
550 +
            .loaded
551 +
            .as_ref()
552 +
            .map_or(0, |loaded| loaded.comments.for_hunk(view.hunk).len())
553 +
    }
554 +
555 +
    /// Starts editing the selected hunk comment.
556 +
    fn edit_selected_comment(&mut self) {
557 +
        let Mode::Hunk(view) = &mut self.mode else {
558 +
            return;
559 +
        };
560 +
        let Some(loaded) = &self.commits[self.current].loaded else {
561 +
            return;
562 +
        };
563 +
        let comments = loaded.comments.for_hunk(view.hunk);
564 +
        view.clamp_selection(comments.len());
565 +
        let Some(comment) = comments.get(view.selected()) else {
566 +
            return;
567 +
        };
568 +
        view.start_edit(comment);
569 +
    }
570 +
571 +
    /// Deletes the selected hunk comment.
572 +
    fn delete_selected_comment(&mut self) -> Result<(), Error> {
573 +
        let Mode::Hunk(view) = &mut self.mode else {
574 +
            return Ok(());
575 +
        };
457 576
        let Some(loaded) = &mut self.commits[self.current].loaded else {
458 577
            return Ok(());
459 578
        };
460 -
        let body = view.input.value().to_owned();
461 -
        if loaded.comments.author(&mut self.comments, view.hunk, body) {
579 +
        let comments = loaded.comments.for_hunk(view.hunk);
580 +
        view.clamp_selection(comments.len());
581 +
        let Some(comment) = comments.get(view.selected()) else {
582 +
            return Ok(());
583 +
        };
584 +
        let id = comment.id.clone();
585 +
        if loaded.comments.delete(&mut self.comments, view.hunk, &id) {
462 586
            self.brain.write_comments(&self.comments.encode())?;
463 587
            loaded.refresh_decorations();
464 -
            view.input = TextInput::new();
588 +
            let comments = loaded.comments.for_hunk(view.hunk).len();
589 +
            view.clamp_selection(comments);
465 590
        }
466 591
        Ok(())
467 592
    }
468 593
469 594
    /// Applies current visibility and starts workers for the active commit.
616 741
            Mode::Hunk(view) => {
617 742
                let comments = self.commits[current]
618 743
                    .loaded
619 744
                    .as_ref()
620 745
                    .map_or(&[][..], |loaded| loaded.comments.for_hunk(view.hunk));
621 -
                let mut comment_lines = comment_block_lines(comments);
746 +
                view.clamp_selection(comments.len());
747 +
                let selected = view.selected();
748 +
                let mut comment_lines = comment_block_lines(comments, selected);
622 749
                self.terminal.draw(|frame| {
623 750
                    let (body, footer_area) = Status::areas(frame.area);
624 751
                    frame.render_stateful_widget(&mut **view, body, &mut comment_lines);
625 752
                    frame.render_widget(&mut footer, footer_area);
626 753
                })?;
644 771
            }
645 772
        }
646 773
        // The terminal caret is a pure function of the active view: only the
647 774
        // hunk view's comment editor shows it.
648 775
        self.terminal
649 -
            .set_cursor_visible(matches!(self.mode, Mode::Hunk(_)))
776 +
            .set_cursor_visible(matches!(self.mode, Mode::Hunk(ref view) if view.is_editing()))
650 777
    }
651 778
652 779
    /// Returns the footer status line for the current commit.
653 780
    fn footer(&self) -> Status {
654 781
        let slot = &self.commits[self.current];
crates/brain/src/session/hunk.rs +160 -17
6 6
    Buffer, Constraint, Direction, Length, Line, RenderResult, Size, StatefulWidget, TextField,
7 7
    TextInput,
8 8
};
9 9
10 10
use super::status::heading;
11 +
use crate::comments::{Comment, CommentId};
11 12
12 13
/// Maximum rows the comment input grows to.
13 14
const MAX_INPUT_ROWS: usize = 6;
14 15
/// Maximum rows used to list a hunk's existing comments.
15 16
const MAX_COMMENT_ROWS: usize = 8;
16 17
/// Hint shown above the comment input box.
17 -
const COMMENT_HINT: &str =
18 +
const BROWSE_HINT: &str = "comments \u{00b7} c new \u{00b7} e edit \u{00b7} d delete \u{00b7} n/p select \u{00b7} Esc back";
19 +
/// Hint shown above the comment input box.
20 +
const EDIT_HINT: &str =
18 21
    "comment \u{00b7} Enter newline \u{00b7} Ctrl-Enter save \u{00b7} Esc cancel";
19 22
23 +
/// Comment editor target.
24 +
#[derive(Clone, Debug, Eq, PartialEq)]
25 +
pub(super) enum CommentEdit {
26 +
    /// Add a new comment.
27 +
    Add,
28 +
    /// Edit an existing comment.
29 +
    Edit(CommentId),
30 +
}
31 +
32 +
/// Active hunk comment mode.
33 +
#[derive(Clone, Debug)]
34 +
enum HunkMode {
35 +
    /// Browse existing comments and hunk content.
36 +
    Browsing {
37 +
        /// Selected comment row.
38 +
        selected: usize,
39 +
    },
40 +
    /// Edit a new or existing comment.
41 +
    Editing {
42 +
        /// Selected comment row before entering edit mode.
43 +
        selected: usize,
44 +
        /// Comment being edited.
45 +
        target: CommentEdit,
46 +
        /// Comment text being authored.
47 +
        input: TextInput,
48 +
    },
49 +
}
50 +
20 51
/// State for the hunk view: the hunk, its isolated viewer, and the in-progress
21 52
/// comment.
22 53
#[derive(Debug)]
23 54
pub(super) struct HunkView {
24 55
    /// Hunk being commented on.
25 56
    pub(super) hunk: HunkId,
26 57
    /// Viewer rendering the single hunk in isolation.
27 58
    pub(super) viewer: DiffViewer,
28 -
    /// Comment text being authored.
29 -
    pub(super) input: TextInput,
59 +
    /// Current comment mode.
60 +
    mode: HunkMode,
61 +
}
62 +
63 +
impl HunkView {
64 +
    /// Creates a hunk comment view.
65 +
    pub(super) fn new(hunk: HunkId, viewer: DiffViewer) -> Self {
66 +
        Self {
67 +
            hunk,
68 +
            viewer,
69 +
            mode: HunkMode::Browsing { selected: 0 },
70 +
        }
71 +
    }
72 +
73 +
    /// Returns whether the view is editing a comment.
74 +
    pub(super) fn is_editing(&self) -> bool {
75 +
        matches!(self.mode, HunkMode::Editing { .. })
76 +
    }
77 +
78 +
    /// Starts a new comment draft.
79 +
    pub(super) fn start_new(&mut self) {
80 +
        self.mode = HunkMode::Editing {
81 +
            selected: self.selected(),
82 +
            target: CommentEdit::Add,
83 +
            input: TextInput::new(),
84 +
        };
85 +
    }
86 +
87 +
    /// Starts editing `comment`.
88 +
    pub(super) fn start_edit(&mut self, comment: &Comment) {
89 +
        self.mode = HunkMode::Editing {
90 +
            selected: self.selected(),
91 +
            target: CommentEdit::Edit(comment.id.clone()),
92 +
            input: TextInput::with_value(comment.body.clone()),
93 +
        };
94 +
    }
95 +
96 +
    /// Cancels the active draft.
97 +
    pub(super) fn cancel_edit(&mut self) {
98 +
        self.mode = HunkMode::Browsing {
99 +
            selected: self.selected(),
100 +
        };
101 +
    }
102 +
103 +
    /// Finishes the active draft, returning the target and body.
104 +
    pub(super) fn finish_edit(&mut self) -> Option<(CommentEdit, String)> {
105 +
        let HunkMode::Editing { target, input, .. } = &self.mode else {
106 +
            return None;
107 +
        };
108 +
        if input.is_empty() {
109 +
            self.cancel_edit();
110 +
            return None;
111 +
        }
112 +
        let target = target.clone();
113 +
        let body = input.value().to_owned();
114 +
        self.cancel_edit();
115 +
116 +
        Some((target, body))
117 +
    }
118 +
119 +
    /// Applies an edit key to the draft comment.
120 +
    pub(super) fn input(&mut self, key: rustik_tui::Key) -> bool {
121 +
        let HunkMode::Editing { input, .. } = &mut self.mode else {
122 +
            return false;
123 +
        };
124 +
        input.input(key)
125 +
    }
126 +
127 +
    /// Inserts a newline into the draft comment.
128 +
    pub(super) fn newline(&mut self) -> bool {
129 +
        let HunkMode::Editing { input, .. } = &mut self.mode else {
130 +
            return false;
131 +
        };
132 +
        input.newline()
133 +
    }
134 +
135 +
    /// Returns the currently selected comment row.
136 +
    pub(super) fn selected(&self) -> usize {
137 +
        match &self.mode {
138 +
            HunkMode::Browsing { selected } => *selected,
139 +
            HunkMode::Editing { selected, .. } => *selected,
140 +
        }
141 +
    }
142 +
143 +
    /// Selects the next comment.
144 +
    pub(super) fn select_next(&mut self, comments: usize) {
145 +
        let HunkMode::Browsing { selected } = &mut self.mode else {
146 +
            return;
147 +
        };
148 +
        *selected = selected.saturating_add(1).min(comments.saturating_sub(1));
149 +
    }
150 +
151 +
    /// Selects the previous comment.
152 +
    pub(super) fn select_previous(&mut self) {
153 +
        let HunkMode::Browsing { selected } = &mut self.mode else {
154 +
            return;
155 +
        };
156 +
        *selected = selected.saturating_sub(1);
157 +
    }
158 +
159 +
    /// Clamps the selected comment after comment list changes.
160 +
    pub(super) fn clamp_selection(&mut self, comments: usize) {
161 +
        let HunkMode::Browsing { selected } = &mut self.mode else {
162 +
            return;
163 +
        };
164 +
        *selected = (*selected).min(comments.saturating_sub(1));
165 +
    }
30 166
}
31 167
32 168
impl StatefulWidget for HunkView {
33 169
    type State = Vec<Line>;
34 170
43 179
        comments: &mut Self::State,
44 180
    ) -> RenderResult {
45 181
        if area.is_empty() {
46 182
            return RenderResult::default();
47 183
        }
48 -
        let input_rows = self
49 -
            .input
50 -
            .value()
51 -
            .split('\n')
52 -
            .count()
53 -
            .clamp(1, MAX_INPUT_ROWS);
54 -
        let input_h = (input_rows + 1).min(area.rows);
184 +
        let input_rows = match &self.mode {
185 +
            HunkMode::Editing { input, .. } => {
186 +
                input.value().split('\n').count().clamp(1, MAX_INPUT_ROWS)
187 +
            }
188 +
            HunkMode::Browsing { .. } => 0,
189 +
        };
190 +
        let input_h = if self.is_editing() {
191 +
            (input_rows + 1).min(area.rows)
192 +
        } else {
193 +
            1.min(area.rows)
194 +
        };
55 195
        let comments_h = if comments.is_empty() {
56 196
            0
57 197
        } else {
58 198
            (comments.len().min(MAX_COMMENT_ROWS) + 1).min(area.rows.saturating_sub(input_h))
59 199
        };
79 219
                buf,
80 220
            );
81 221
        }
82 222
        let (heading_area, input_area) = input_area.split_top(1);
83 223
84 -
        buf.set_line(
85 -
            heading_area.x,
86 -
            heading_area.y,
87 -
            &heading(COMMENT_HINT, area.cols),
88 -
        );
224 +
        let hint = if self.is_editing() {
225 +
            EDIT_HINT
226 +
        } else {
227 +
            BROWSE_HINT
228 +
        };
229 +
        buf.set_line(heading_area.x, heading_area.y, &heading(hint, area.cols));
89 230
90 -
        if !input_area.is_empty() {
231 +
        if let HunkMode::Editing { input, .. } = &mut self.mode
232 +
            && !input_area.is_empty()
233 +
        {
91 234
            return TextField::new()
92 235
                .placeholder("Write a comment...")
93 -
                .render_with_state(input_area, buf, &mut self.input);
236 +
                .render_with_state(input_area, buf, input);
94 237
        }
95 238
        RenderResult::default()
96 239
    }
97 240
}
crates/brain/src/session/status.rs +7 -2
126 126
        Label::new(&format!("{} files", stats.files_changed)).fg(FOOTER_FG),
127 127
    ])
128 128
}
129 129
130 130
/// Renders a hunk's stored comments as styled lines for the hunk view.
131 -
pub(super) fn comment_block_lines(comments: &[Comment]) -> Vec<Line> {
131 +
pub(super) fn comment_block_lines(comments: &[Comment], selected: usize) -> Vec<Line> {
132 132
    let mut lines = Vec::new();
133 133
    for (index, comment) in comments.iter().enumerate() {
134 134
        if index > 0 {
135 135
            lines.push(Line::blank());
136 136
        }
137 +
        let style = (index == selected).then(|| Style::default().bg(Color::Fixed(236)));
137 138
        for (row, body) in comment.body.split('\n').enumerate() {
138 139
            let prefix = if row == 0 { COMMENT_PREFIX } else { " " };
139 -
            lines.push(Line::new(Label::new(&format!("{prefix} {body}"))));
140 +
            let mut line = Line::new(Label::new(&format!("{prefix} {body}")));
141 +
            if let Some(style) = style {
142 +
                line = line.style(style);
143 +
            }
144 +
            lines.push(line);
140 145
        }
141 146
    }
142 147
    lines
143 148
}
144 149
crates/repo/src/git.rs +76 -46
26 26
/// Maximum bytes read from a file head for shebang-style inference.
27 27
const HEAD_BYTES: usize = 64;
28 28
/// Pathspec separator that ends Git's option list.
29 29
const PATHSPEC_SEPARATOR: &str = "--";
30 30
31 +
/// Direction used when applying a patch to an isolated tree.
32 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
33 +
enum PatchDirection {
34 +
    /// Apply the patch as written.
35 +
    Forward,
36 +
    /// Apply the patch in reverse.
37 +
    Reverse,
38 +
}
39 +
31 40
/// Git repository command context.
32 41
#[derive(Clone, Debug)]
33 42
pub struct Repository {
34 43
    /// Working directory for worktree-aware invocations.
35 44
    cwd: PathBuf,
411 420
    ///
412 421
    /// The temporary index is seeded from `base`, patched with
413 422
    /// `git apply --cached`, then written with `git write-tree`. This keeps
414 423
    /// acceptance updates isolated from the user's working tree and real index.
415 424
    fn apply_patch_to_tree(&self, base: Oid, patch: &str) -> Result<Oid, RepoError> {
416 -
        if patch.trim().is_empty() {
417 -
            return self.tree_id(base);
418 -
        }
419 -
        let index = TempIndex::new()?;
420 -
        let index_path = index.path();
421 -
        let base = base.to_string();
425 +
        self.apply_patch_to_tree_with_direction(base, patch, PatchDirection::Forward)
426 +
    }
422 427
423 -
        // `read-tree` initializes the temporary index to the exact tree being
424 -
        // updated; subsequent Git commands use only `GIT_INDEX_FILE`.
425 -
        let output = self.run(
426 -
            "read-tree",
427 -
            &[&base],
428 -
            Opts {
429 -
                index: Some(index_path),
430 -
                ..Opts::default()
431 -
            },
432 -
        )?;
433 -
        if !output.status.success() {
434 -
            return Err(RepoError::git(&output));
435 -
        }
436 -
        // `--recount` lets single-hunk patches keep working after context
437 -
        // filtering changes hunk line counts.
438 -
        let output = self.run(
439 -
            "apply",
440 -
            &["--cached", "--recount", "--whitespace=nowarn", "--binary"],
441 -
            Opts {
442 -
                index: Some(index_path),
443 -
                stdin: Some(patch.as_bytes()),
444 -
                ..Opts::default()
445 -
            },
446 -
        )?;
447 -
        if !output.status.success() {
448 -
            return Err(RepoError::git(&output));
449 -
        }
450 -
        let output = self.run(
451 -
            "write-tree",
452 -
            &[],
453 -
            Opts {
454 -
                index: Some(index_path),
455 -
                ..Opts::default()
456 -
            },
457 -
        )?;
458 -
        if !output.status.success() {
459 -
            return Err(RepoError::git(&output));
460 -
        }
461 -
        Oid::try_from(output.stdout.as_slice())
462 -
            .map_err(|_| RepoError::Git("invalid oid from write-tree".to_owned()))
428 +
    /// Applies the reverse of a Git-format patch to a temporary index.
429 +
    fn reverse_patch_to_tree(&self, base: Oid, patch: &str) -> Result<Oid, RepoError> {
430 +
        self.apply_patch_to_tree_with_direction(base, patch, PatchDirection::Reverse)
463 431
    }
464 432
465 433
    /// Creates a commit with `tree` and `parent`.
466 434
    fn commit(
467 435
        &self,
506 474
        }
507 475
        Ok(())
508 476
    }
509 477
}
510 478
479 +
impl Repository {
480 +
    /// Applies or reverses a Git-format patch against an isolated tree.
481 +
    fn apply_patch_to_tree_with_direction(
482 +
        &self,
483 +
        base: Oid,
484 +
        patch: &str,
485 +
        direction: PatchDirection,
486 +
    ) -> Result<Oid, RepoError> {
487 +
        if patch.trim().is_empty() {
488 +
            return self.tree_id(base);
489 +
        }
490 +
        let index = TempIndex::new()?;
491 +
        let index_path = index.path();
492 +
        let base = base.to_string();
493 +
494 +
        // `read-tree` initializes the temporary index to the exact tree being
495 +
        // updated; subsequent Git commands use only `GIT_INDEX_FILE`.
496 +
        let output = self.run(
497 +
            "read-tree",
498 +
            &[&base],
499 +
            Opts {
500 +
                index: Some(index_path),
501 +
                ..Opts::default()
502 +
            },
503 +
        )?;
504 +
        if !output.status.success() {
505 +
            return Err(RepoError::git(&output));
506 +
        }
507 +
        // `--recount` lets single-hunk patches keep working after context
508 +
        // filtering changes hunk line counts.
509 +
        let mut args = vec!["--cached", "--recount", "--whitespace=nowarn", "--binary"];
510 +
        if direction == PatchDirection::Reverse {
511 +
            args.push("--reverse");
512 +
        }
513 +
        let output = self.run(
514 +
            "apply",
515 +
            &args,
516 +
            Opts {
517 +
                index: Some(index_path),
518 +
                stdin: Some(patch.as_bytes()),
519 +
                ..Opts::default()
520 +
            },
521 +
        )?;
522 +
        if !output.status.success() {
523 +
            return Err(RepoError::git(&output));
524 +
        }
525 +
        let output = self.run(
526 +
            "write-tree",
527 +
            &[],
528 +
            Opts {
529 +
                index: Some(index_path),
530 +
                ..Opts::default()
531 +
            },
532 +
        )?;
533 +
        if !output.status.success() {
534 +
            return Err(RepoError::git(&output));
535 +
        }
536 +
        Oid::try_from(output.stdout.as_slice())
537 +
            .map_err(|_| RepoError::Git("invalid oid from write-tree".to_owned()))
538 +
    }
539 +
}
540 +
511 541
impl DiffRepository for Repository {
512 542
    fn diff(&self, context_lines: usize, paths: &[&Path]) -> Result<Vec<u8>, RepoError> {
513 543
        let context = OsString::from(format!("-U{context_lines}"));
514 544
        let output = self
515 545
            .command("diff")
crates/repo/src/lib.rs +3 -0
167 167
    fn write_blob(&self, bytes: &[u8]) -> Result<Oid, RepoError>;
168 168
169 169
    /// Applies a Git-format patch to a temporary index and returns its tree id.
170 170
    fn apply_patch_to_tree(&self, base: Oid, patch: &str) -> Result<Oid, RepoError>;
171 171
172 +
    /// Applies the reverse of a Git-format patch to a temporary index.
173 +
    fn reverse_patch_to_tree(&self, base: Oid, patch: &str) -> Result<Oid, RepoError>;
174 +
172 175
    /// Creates a commit with `tree` and `parent`.
173 176
    fn commit(
174 177
        &self,
175 178
        tree: Oid,
176 179
        parent: Oid,
crates/tui-widgets/src/input.rs +23 -0
42 42
    /// Creates an empty input with the caret at the start.
43 43
    pub fn new() -> Self {
44 44
        Self::default()
45 45
    }
46 46
47 +
    /// Creates an input initialized with `value`.
48 +
    pub fn with_value(value: String) -> Self {
49 +
        let cursor = value.len();
50 +
        Self {
51 +
            value,
52 +
            cursor,
53 +
            scroll: 0,
54 +
            hscroll: 0,
55 +
            caret: Point::new(0, 0),
56 +
        }
57 +
    }
58 +
47 59
    /// Returns the edited text.
48 60
    pub fn value(&self) -> &str {
49 61
        &self.value
50 62
    }
51 63
401 413
        // The caret is on the third line; a two-row area scrolls to show it.
402 414
        assert_eq!(buffer.lines(), vec!["two   ", "three "]);
403 415
        assert_eq!(input.caret(), Point::new(5, 1));
404 416
    }
405 417
418 +
    #[test]
419 +
    fn with_value_places_caret_after_initial_text() {
420 +
        let mut input = TextInput::with_value("abc".to_owned());
421 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 8, 1));
422 +
423 +
        TextField::new().render_with_state(buffer.area(), &mut buffer, &mut input);
424 +
425 +
        assert_eq!(input.value(), "abc");
426 +
        assert_eq!(input.caret(), Point::new(3, 0));
427 +
    }
428 +
406 429
    #[test]
407 430
    fn empty_input_renders_placeholder() {
408 431
        let mut field = TextField::new().placeholder("type here");
409 432
        let mut input = TextInput::new();
410 433
        let mut buffer = Buffer::empty(Rect::new(0, 0, 9, 1));