travelagent 1.11.1

Agent-first TUI code review tool
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

use crate::app::InputMode;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Action {
    // Navigation
    CursorDown(usize),
    CursorUp(usize),
    HalfPageDown,
    HalfPageUp,
    PageDown,
    PageUp,
    GoToTop,
    GoToBottom,
    Digit(u8),
    NextFile,
    PrevFile,
    PendingZCommand,
    PendingShiftZCommand,
    /// First-stroke of `]]` chord (advance tour stop).
    PendingRBracketCommand,
    /// First-stroke of `[[` chord (previous tour stop).
    PendingLBracketCommand,
    /// First-stroke of `g`-prefixed chord. `gg` still goes to top (vim
    /// convention); `gf` opens the source file under the cursor in
    /// `$VISUAL`/`$EDITOR`. Any other second key falls through to
    /// `GoToTop` for backwards compatibility with the pre-chord binding.
    PendingGCommand,
    ReviewComment,
    ToggleFileList,
    ShrinkFileList,
    GrowFileList,
    /// Nudge agent to make tour stops coarser (`=` key).
    TourGranularityCoarser,
    /// Nudge agent to make tour stops finer (`-` key).
    TourGranularityFiner,
    ScrollLeft(usize),
    ScrollRight(usize),
    /// `0` — move horizontal scroll to the start of the line (column 0).
    GoToLineStart,
    /// `$` — move horizontal scroll to the end of the longest visible line.
    GoToLineEnd,
    /// `w` — move cursor forward one "word"; in TUI context this is the next hunk.
    WordForward,
    /// `b` — move cursor backward one "word"; in TUI context this is the previous hunk.
    WordBackward,
    /// `H` — move cursor to the top line currently in the viewport.
    CursorToTopOfScreen,
    /// `L` — move cursor to the bottom line of the viewport.
    ///
    /// The vim `M` (middle of screen) binding is intentionally absent because
    /// capital `M` is already bound to `MergePR`.
    CursorToBottomOfScreen,
    /// `zz` — vertically re-center the viewport around the cursor.
    CenterOnCursor,
    /// `Ctrl+Y` — scroll the viewport up one line without moving the cursor.
    ScrollViewUp,
    /// `Ctrl+E` (normal mode only) — scroll the viewport down one line.
    ScrollViewDown,

    // Panel focus
    ToggleFocus,
    ToggleFocusReverse,
    SelectFile,

    // Review actions
    ToggleReviewed,
    AddLineComment,
    EditComment,
    PendingDCommand,
    SearchNext,
    SearchPrev,

    /// Phase I5-2b: Sparring-panel "accept" shortcut (`a`). Firing
    /// outside the Sparring panel is a no-op — the handler ignores
    /// it so other panels aren't accidentally affected.
    SparringAccept,

    /// Toggle resolve/unresolve on the selected thread (Conversation panel only).
    ToggleResolveThread,

    // Visual selection mode
    EnterVisualMode,
    AddRangeComment,

    // Session
    Quit,
    ExportToClipboard,

    /// `Esc` in Normal mode while the Diff panel is focused: return to the
    /// commit list. The handler decides whether this is a no-op based on the
    /// focused panel and whether a commit list is available; emitted
    /// unconditionally from `map_normal_mode`.
    ReturnToCommits,

    // Mode changes
    EnterCommandMode,
    EnterSearchMode,
    ExitMode,
    ToggleHelp,
    /// Toggle the full-file viewer pane on/off (`t` in Normal mode). When on,
    /// the content area shows the whole current file instead of the diff.
    ToggleViewer,
    /// Toggle the viewer's raw↔rendered sub-mode (`T` in Normal mode). No-op
    /// (with a message) for non-markdown files, and only meaningful while the
    /// viewer is active.
    ToggleViewerRender,
    /// Toggle the AI summary popup (Ctrl+A in Normal mode).
    ToggleAiSummary,
    /// Toggle viewport-pin mode (`Ctrl+P`). When pinned, agent MCP
    /// navigation records an `AgentGhost` instead of moving the cursor.
    ToggleViewportPin,
    /// Jump to the agent's ghost position and return to follow mode
    /// (`Ctrl+G`). No-op when there is no ghost.
    JumpToAgentGhost,

    // Text input
    InsertChar(char),
    DeleteChar,
    DeleteWord,
    ClearLine,
    SubmitInput,
    TextCursorLeft,
    TextCursorRight,
    TextCursorLineStart,
    TextCursorLineEnd,
    TextCursorWordLeft,
    TextCursorWordRight,
    /// Insert a GitHub-style ```suggestion block at the cursor in comment mode.
    InsertSuggestion,
    /// Open the current comment buffer in the user's external editor ($VISUAL/$EDITOR).
    OpenExternalEditor,

    // Comment type
    CycleCommentType,
    CycleCommentTypeReverse,

    // Confirm dialog
    ConfirmYes,
    ConfirmNo,

    // Commit selection
    CommitSelectUp,
    CommitSelectDown,
    ToggleCommitSelect,
    ConfirmCommitSelect,
    /// Cycle inline commit selector to next individual commit (`)`)
    CycleCommitNext,
    /// Cycle inline commit selector to previous individual commit (`(`)
    CycleCommitPrev,

    ToggleExpand,
    CollapseAll,
    /// Toggle auto/manual collapse of the current file (the `z` binding).
    /// Flips `FileReview.collapsed`: None → Some(!auto), Some(x) → Some(!x).
    ToggleFileCollapse,
    SelectFileFull,

    // Remote write operations
    SubmitReview,
    MergePR,

    /// L3: re-anchor an orphaned comment at the cursor's current diff line.
    /// Triggered by `A` in Normal mode. See `docs/design/live-review-mode.md`.
    ReanchorOrphan,

    // Remote navigation
    OpenInBrowser,

    /// `gf` — suspend the TUI and open the source file under the cursor in
    /// `$VISUAL`/`$EDITOR` (fallback `vi`) at the cursor's line. Restores
    /// the TUI after the editor exits.
    OpenInEditor,

    // Reaction picker
    OpenReactionPicker,
    ReactionPickerCancel,
    ReactionPickerCursorLeft,
    ReactionPickerCursorRight,
    ReactionPickerSelect,
    ReactionPickerSelectAt(usize),

    // Comment template picker (Ctrl+T in comment mode)
    /// Open the reusable-template picker from comment mode. If no templates
    /// are configured, the handler flashes a pointer to the config file
    /// instead of opening an empty popup.
    OpenCommentTemplatePicker,
    /// Commit the currently selected template into the comment buffer and
    /// return to comment mode.
    CommentTemplatePickerSelect,
    /// Close the picker without inserting anything.
    CommentTemplatePickerCancel,

    // Mental-model modal actions (Phase I2)
    /// Open the mental-model modal from Normal mode. Seeds the draft
    /// from the session's existing model (if any) so the user can edit
    /// rather than re-enter.
    MentalModelOpen,
    /// Persist the draft into `ReviewSession.mental_model`, mark the
    /// session dirty, and return to Normal mode.
    MentalModelSave,
    /// Discard the draft and return to Normal mode without touching
    /// the session's stored model.
    MentalModelCancel,
    /// Cycle focus forward among the four prompts.
    MentalModelNextField,
    /// Cycle focus backward among the four prompts.
    MentalModelPrevField,
    /// Append a character (including `'\n'`) to the focused prompt's
    /// buffer. Bounded at ingress by `App.mental_model_byte_limit`.
    MentalModelInsertChar(char),
    /// Delete the rightmost character from the focused prompt's buffer.
    MentalModelBackspace,

    // No-op
    None,
}

pub fn map_key_to_action(key: KeyEvent, mode: InputMode) -> Action {
    match mode {
        InputMode::Normal => map_normal_mode(key),
        InputMode::Command => map_command_mode(key),
        InputMode::Search => map_search_mode(key),
        InputMode::Comment => map_comment_mode(key),
        InputMode::Help => map_help_mode(key),
        InputMode::Confirm => map_confirm_mode(key),
        InputMode::CommitSelect => map_commit_select_mode(key),
        InputMode::VisualSelect => map_visual_mode(key),
        InputMode::ReviewSubmit => map_review_submit_mode(key),
        InputMode::CommandPalette => map_command_palette_mode(key),
        InputMode::ReactionPicker => map_reaction_picker_mode(key),
        InputMode::CommentTemplatePicker => map_comment_template_picker_mode(key),
        InputMode::MentalModelEdit => map_mental_model_edit_mode(key),
    }
}

/// Mental-model modal keybindings (Phase I2).
///
/// Esc cancels without persisting; Ctrl+S commits the buffer into
/// `ReviewSession.mental_model`; Tab / Shift+Tab cycle which of the
/// four fields has focus; Enter inserts a newline; every other
/// printable key appends to the focused buffer.
fn map_mental_model_edit_mode(key: KeyEvent) -> Action {
    match (key.code, key.modifiers) {
        (KeyCode::Esc, _) => Action::MentalModelCancel,
        (KeyCode::Char('s'), KeyModifiers::CONTROL) => Action::MentalModelSave,
        (KeyCode::Tab, KeyModifiers::NONE) => Action::MentalModelNextField,
        (KeyCode::BackTab, _) => Action::MentalModelPrevField,
        (KeyCode::Enter, KeyModifiers::NONE) => Action::MentalModelInsertChar('\n'),
        (KeyCode::Backspace, _) => Action::MentalModelBackspace,
        (KeyCode::Char(c), m) if !m.contains(KeyModifiers::CONTROL) => {
            Action::MentalModelInsertChar(c)
        }
        _ => Action::None,
    }
}

fn map_normal_mode(key: KeyEvent) -> Action {
    match (key.code, key.modifiers) {
        // Cursor movement (vim-like: cursor moves, scroll follows when needed)
        (KeyCode::Char('j') | KeyCode::Down, KeyModifiers::NONE) => Action::CursorDown(1),
        (KeyCode::Char('k') | KeyCode::Up, KeyModifiers::NONE) => Action::CursorUp(1),
        (KeyCode::Char('d'), KeyModifiers::CONTROL) => Action::HalfPageDown,
        (KeyCode::Char('u'), KeyModifiers::CONTROL) => Action::HalfPageUp,
        (KeyCode::Char('f'), KeyModifiers::CONTROL) => Action::PageDown,
        (KeyCode::Char('b'), KeyModifiers::CONTROL) => Action::PageUp,
        (KeyCode::PageDown, KeyModifiers::NONE) => Action::PageDown,
        (KeyCode::PageUp, KeyModifiers::NONE) => Action::PageUp,
        // `g` is a chord prefix: `gg` → GoToTop, `gf` → OpenInEditor. Any
        // other second key falls through to GoToTop so the pre-chord `g`
        // muscle memory still fires (see main.rs pending_g handling).
        (KeyCode::Char('g'), KeyModifiers::NONE) => Action::PendingGCommand,
        (KeyCode::Char('G'), _) => Action::GoToBottom,
        (KeyCode::Char('z'), KeyModifiers::NONE) => Action::PendingZCommand,
        (KeyCode::Char('Z'), _) => Action::PendingShiftZCommand,

        // File navigation (use _ for modifiers since shift is implicit in the character)
        (KeyCode::Char('}'), _) => Action::NextFile,
        (KeyCode::Char('{'), _) => Action::PrevFile,
        (KeyCode::Char(']'), _) => Action::PendingRBracketCommand,
        (KeyCode::Char('['), _) => Action::PendingLBracketCommand,
        (KeyCode::Char(')'), _) => Action::CycleCommitNext,
        (KeyCode::Char('('), _) => Action::CycleCommitPrev,

        // Panel focus
        (KeyCode::Tab, KeyModifiers::NONE) => Action::ToggleFocus,
        (KeyCode::BackTab, _) => Action::ToggleFocusReverse,
        (KeyCode::Enter, KeyModifiers::NONE) => Action::SelectFile,
        (KeyCode::Enter, KeyModifiers::SHIFT) => Action::SelectFileFull,

        // Horizontal scrolling
        (KeyCode::Char('h') | KeyCode::Left, KeyModifiers::NONE) => Action::ScrollLeft(4),
        (KeyCode::Char('l') | KeyCode::Right, KeyModifiers::NONE) => Action::ScrollRight(4),
        // Vim-style line-position jumps.
        // `0` is handled in main.rs so a leading zero in a count accumulates
        // normally; plain `0` with no pending count becomes GoToLineStart.
        (KeyCode::Char('$'), _) => Action::GoToLineEnd,

        // Vim-style word jumps — at the TUI granularity they step between hunks.
        (KeyCode::Char('w'), KeyModifiers::NONE) => Action::WordForward,
        (KeyCode::Char('b'), KeyModifiers::NONE) => Action::WordBackward,

        // Cursor-vertical operations (vim H/L; M stays bound to MergePR so
        // the existing remote shortcut is unchanged).
        (KeyCode::Char('H'), _) => Action::CursorToTopOfScreen,
        (KeyCode::Char('L'), _) => Action::CursorToBottomOfScreen,

        // Viewport-only scrolling (don't move the cursor).
        (KeyCode::Char('y'), KeyModifiers::CONTROL) => Action::ScrollViewUp,
        (KeyCode::Char('e'), KeyModifiers::CONTROL) => Action::ScrollViewDown,

        // Review actions
        (KeyCode::Char('r'), KeyModifiers::NONE) => Action::ToggleReviewed,
        // Phase I5-2b: `a` accepts the cursored spec in the Sparring
        // panel. No-op elsewhere (the action handler early-returns).
        (KeyCode::Char('a'), KeyModifiers::NONE) => Action::SparringAccept,
        (KeyCode::Char('c'), KeyModifiers::NONE) => Action::AddLineComment,
        (KeyCode::Char('C'), _) => Action::ReviewComment,
        (KeyCode::Char('\\'), _) => Action::ToggleFileList,
        // `t` opens/closes the full-file viewer pane; `T` flips its
        // raw↔rendered sub-mode. Plain `t`/`T` are otherwise unused in Normal
        // mode (only Ctrl+T — the comment-template picker — is bound).
        (KeyCode::Char('t'), KeyModifiers::NONE) => Action::ToggleViewer,
        (KeyCode::Char('T'), _) => Action::ToggleViewerRender,
        (KeyCode::Char('<'), _) => Action::ShrinkFileList,
        (KeyCode::Char('>'), _) => Action::GrowFileList,
        (KeyCode::Char('='), KeyModifiers::NONE) => Action::TourGranularityCoarser,
        (KeyCode::Char('-'), KeyModifiers::NONE) => Action::TourGranularityFiner,
        (KeyCode::Char('i'), KeyModifiers::NONE) => Action::EditComment,
        // Plain `e` opens the reaction picker on the selected thread in the
        // Conversation panel. Ctrl+E is handled separately in comment mode
        // as OpenExternalEditor — that binding is unaffected here.
        (KeyCode::Char('e'), KeyModifiers::NONE) => Action::OpenReactionPicker,
        (KeyCode::Char('d'), KeyModifiers::NONE) => Action::PendingDCommand,
        (KeyCode::Char('v' | 'V'), _) => Action::EnterVisualMode,
        (KeyCode::Char('y'), KeyModifiers::NONE) => Action::ExportToClipboard,
        (KeyCode::Char('n'), KeyModifiers::NONE) => Action::SearchNext,
        (KeyCode::Char('N'), _) => Action::SearchPrev,
        (KeyCode::Char('x'), KeyModifiers::NONE) => Action::ToggleResolveThread,

        // Mode changes (use _ for shifted characters like : and ?)
        (KeyCode::Char(':'), _) => Action::EnterCommandMode,
        (KeyCode::Char('/'), _) => Action::EnterSearchMode,
        (KeyCode::Char('?'), _) => Action::ToggleHelp,
        // Ctrl+A toggles the AI summary panel. Only active in Normal mode; in
        // Comment/text-input modes this is TextCursorLineStart (see map_comment_mode).
        (KeyCode::Char('a'), KeyModifiers::CONTROL) => Action::ToggleAiSummary,
        // Ctrl+P toggles viewport-pin mode (cursor ownership). Pinned = agent
        // navigation records a ghost instead of moving the cursor; Ctrl+G
        // jumps to that ghost and returns to follow mode.
        (KeyCode::Char('p'), KeyModifiers::CONTROL) => Action::ToggleViewportPin,
        (KeyCode::Char('g'), KeyModifiers::CONTROL) => Action::JumpToAgentGhost,
        // `Esc` returns to the commit list when the Diff panel is focused.
        // Previously mapped to `ExitMode`, which was an unhandled no-op in
        // Normal mode. The handler decides whether this fires based on the
        // focused panel + commit availability, so it's emitted unconditionally.
        (KeyCode::Esc, KeyModifiers::NONE) => Action::ReturnToCommits,

        // Quick quit
        (KeyCode::Char('q'), KeyModifiers::NONE) => Action::Quit,

        (KeyCode::Char(' '), KeyModifiers::NONE) => Action::ToggleExpand,
        (KeyCode::Char('o'), KeyModifiers::NONE) => Action::OpenInBrowser,
        (KeyCode::Char('O'), _) => Action::CollapseAll,

        // Remote write operations
        (KeyCode::Char('R'), _) => Action::SubmitReview,
        (KeyCode::Char('M'), _) => Action::MergePR,

        // Phase I2: mental-model modal. Lowercase `m` to not collide
        // with `M` (merge PR) and to echo the pattern of `c` (comment).
        (KeyCode::Char('m'), KeyModifiers::NONE) => Action::MentalModelOpen,

        // L3: re-anchor orphan. `A` is unused elsewhere; design doc calls
        // for `R` but that's SubmitReview, and the chord `Rr` would fight
        // the existing keybinding model more than it's worth. `:reanchor`
        // command works too.
        (KeyCode::Char('A'), _) => Action::ReanchorOrphan,

        (KeyCode::Char(c @ '0'..='9'), KeyModifiers::NONE) => Action::Digit(c as u8 - b'0'),

        _ => Action::None,
    }
}

fn map_command_mode(key: KeyEvent) -> Action {
    match (key.code, key.modifiers) {
        (KeyCode::Esc, KeyModifiers::NONE) => Action::ExitMode,
        (KeyCode::Enter, KeyModifiers::NONE) => Action::SubmitInput,
        (KeyCode::Backspace, KeyModifiers::NONE) => Action::DeleteChar,
        (KeyCode::Char('w'), KeyModifiers::CONTROL) => Action::DeleteWord,
        (KeyCode::Char('u'), KeyModifiers::CONTROL) => Action::ClearLine,
        (KeyCode::Char(c), KeyModifiers::NONE | KeyModifiers::SHIFT) => Action::InsertChar(c),
        _ => Action::None,
    }
}

fn map_search_mode(key: KeyEvent) -> Action {
    match (key.code, key.modifiers) {
        (KeyCode::Esc, KeyModifiers::NONE) => Action::ExitMode,
        (KeyCode::Enter, KeyModifiers::NONE) => Action::SubmitInput,
        (KeyCode::Backspace, KeyModifiers::NONE) => Action::DeleteChar,
        (KeyCode::Char('w'), KeyModifiers::CONTROL) => Action::DeleteWord,
        (KeyCode::Char('u'), KeyModifiers::CONTROL) => Action::ClearLine,
        (KeyCode::Char(c), KeyModifiers::NONE | KeyModifiers::SHIFT) => Action::InsertChar(c),
        _ => Action::None,
    }
}

fn map_comment_mode(key: KeyEvent) -> Action {
    match (key.code, key.modifiers) {
        // Cancel: Esc, Ctrl+C
        (KeyCode::Esc, KeyModifiers::NONE) => Action::ExitMode,
        (KeyCode::Char('c'), KeyModifiers::CONTROL) => Action::ExitMode,
        // Submit: Enter without shift (Ctrl+Enter and Ctrl+S also work)
        (KeyCode::Enter, KeyModifiers::NONE) => Action::SubmitInput,
        (KeyCode::Enter, KeyModifiers::CONTROL) => Action::SubmitInput,
        (KeyCode::Char('s'), KeyModifiers::CONTROL) => Action::SubmitInput,
        // Newline: Shift+Enter (modern terminals) or Ctrl+J (universal fallback)
        (KeyCode::Enter, mods) if mods.contains(KeyModifiers::SHIFT) => Action::InsertChar('\n'),
        (KeyCode::Char('j'), KeyModifiers::CONTROL) => Action::InsertChar('\n'),
        // Suggestion block: Ctrl+G inserts ```suggestion ... ``` template.
        (KeyCode::Char('g'), KeyModifiers::CONTROL) => Action::InsertSuggestion,
        // Comment type: Tab to cycle
        (KeyCode::Tab, KeyModifiers::NONE) => Action::CycleCommentType,
        (KeyCode::BackTab, _) => Action::CycleCommentTypeReverse,
        // External editor: Ctrl+E opens $EDITOR with the current comment buffer.
        (KeyCode::Char('e'), KeyModifiers::CONTROL) => Action::OpenExternalEditor,
        // Template picker: Ctrl+T opens the reusable-snippet picker. No-op
        // (with a helpful warning) when no templates are configured.
        (KeyCode::Char('t'), KeyModifiers::CONTROL) => Action::OpenCommentTemplatePicker,
        // Cursor movement
        (KeyCode::Char('a'), KeyModifiers::CONTROL) => Action::TextCursorLineStart,
        (KeyCode::Left, mods)
            if mods.contains(KeyModifiers::ALT) || mods.contains(KeyModifiers::CONTROL) =>
        {
            Action::TextCursorWordLeft
        }
        (KeyCode::Right, mods)
            if mods.contains(KeyModifiers::ALT) || mods.contains(KeyModifiers::CONTROL) =>
        {
            Action::TextCursorWordRight
        }
        (KeyCode::Home, _) => Action::TextCursorLineStart,
        (KeyCode::End, _) => Action::TextCursorLineEnd,
        (KeyCode::Left, mods)
            if mods.contains(KeyModifiers::SUPER) || mods.contains(KeyModifiers::META) =>
        {
            Action::TextCursorLineStart
        }
        (KeyCode::Right, mods)
            if mods.contains(KeyModifiers::SUPER) || mods.contains(KeyModifiers::META) =>
        {
            Action::TextCursorLineEnd
        }
        (KeyCode::Left, KeyModifiers::NONE) => Action::TextCursorLeft,
        (KeyCode::Right, KeyModifiers::NONE) => Action::TextCursorRight,
        // Editing
        (KeyCode::Backspace, mods)
            if mods.contains(KeyModifiers::SUPER) || mods.contains(KeyModifiers::META) =>
        {
            Action::DeleteWord
        }
        (KeyCode::Backspace, KeyModifiers::NONE) => Action::DeleteChar,
        (KeyCode::Char('w'), KeyModifiers::CONTROL) => Action::DeleteWord,
        (KeyCode::Char('u'), KeyModifiers::CONTROL) => Action::ClearLine,
        (KeyCode::Char(c), _) => Action::InsertChar(c),
        _ => Action::None,
    }
}

fn map_help_mode(key: KeyEvent) -> Action {
    match (key.code, key.modifiers) {
        // Close help
        (KeyCode::Esc | KeyCode::Char('q'), KeyModifiers::NONE) | (KeyCode::Char('?'), _) => {
            Action::ToggleHelp
        }
        // Scroll navigation
        (KeyCode::Char('j') | KeyCode::Down, KeyModifiers::NONE) => Action::CursorDown(1),
        (KeyCode::Char('k') | KeyCode::Up, KeyModifiers::NONE) => Action::CursorUp(1),
        (KeyCode::Char('d'), KeyModifiers::CONTROL) => Action::HalfPageDown,
        (KeyCode::Char('u'), KeyModifiers::CONTROL) => Action::HalfPageUp,
        (KeyCode::Char('f'), KeyModifiers::CONTROL) => Action::PageDown,
        (KeyCode::Char('b'), KeyModifiers::CONTROL) => Action::PageUp,
        (KeyCode::PageDown, KeyModifiers::NONE) => Action::PageDown,
        (KeyCode::PageUp, KeyModifiers::NONE) => Action::PageUp,
        (KeyCode::Char('g'), KeyModifiers::NONE) => Action::GoToTop,
        (KeyCode::Char('G'), _) => Action::GoToBottom,
        _ => Action::None,
    }
}

fn map_confirm_mode(key: KeyEvent) -> Action {
    match key.code {
        KeyCode::Char('y' | 'Y') | KeyCode::Enter => Action::ConfirmYes,
        KeyCode::Char('n' | 'N') | KeyCode::Esc => Action::ConfirmNo,
        _ => Action::None,
    }
}

fn map_commit_select_mode(key: KeyEvent) -> Action {
    match key.code {
        KeyCode::Char('j') | KeyCode::Down => Action::CommitSelectDown,
        KeyCode::Char('k') | KeyCode::Up => Action::CommitSelectUp,
        KeyCode::Char(' ') => Action::ToggleCommitSelect,
        KeyCode::Enter => Action::ConfirmCommitSelect,
        // `:` opens command mode from the picker so `:tour` (gated to the
        // commit picker) is reachable. Command mode remembers it was
        // launched from `CommitSelect` via `nav.command_origin`.
        KeyCode::Char(':') => Action::EnterCommandMode,
        KeyCode::Esc => Action::ExitMode,
        KeyCode::Char('q') => Action::Quit,
        _ => Action::None,
    }
}

fn map_visual_mode(key: KeyEvent) -> Action {
    match (key.code, key.modifiers) {
        // Extend selection
        (KeyCode::Char('j') | KeyCode::Down, KeyModifiers::NONE) => Action::CursorDown(1),
        (KeyCode::Char('k') | KeyCode::Up, KeyModifiers::NONE) => Action::CursorUp(1),
        // Create range comment
        (KeyCode::Char('c'), KeyModifiers::NONE) => Action::AddRangeComment,
        (KeyCode::Enter, KeyModifiers::NONE) => Action::AddRangeComment,
        // Cancel selection
        (KeyCode::Esc, KeyModifiers::NONE) => Action::ExitMode,
        (KeyCode::Char('v' | 'V'), _) => Action::ExitMode,
        // Quick quit
        (KeyCode::Char('q'), KeyModifiers::NONE) => Action::Quit,
        _ => Action::None,
    }
}

fn map_command_palette_mode(key: KeyEvent) -> Action {
    match (key.code, key.modifiers) {
        (KeyCode::Esc, KeyModifiers::NONE) => Action::ExitMode,
        (KeyCode::Enter, KeyModifiers::NONE) => Action::SubmitInput,
        (KeyCode::Char('j') | KeyCode::Down, KeyModifiers::NONE) => Action::CursorDown(1),
        (KeyCode::Char('k') | KeyCode::Up, KeyModifiers::NONE) => Action::CursorUp(1),
        (KeyCode::Backspace, KeyModifiers::NONE) => Action::DeleteChar,
        (KeyCode::Char('w'), KeyModifiers::CONTROL) => Action::DeleteWord,
        (KeyCode::Char('u'), KeyModifiers::CONTROL) => Action::ClearLine,
        (KeyCode::Char('n'), KeyModifiers::CONTROL) => Action::CursorDown(1),
        (KeyCode::Char('p'), KeyModifiers::CONTROL) => Action::CursorUp(1),
        (KeyCode::Char(c), KeyModifiers::NONE | KeyModifiers::SHIFT) => Action::InsertChar(c),
        _ => Action::None,
    }
}

fn map_comment_template_picker_mode(key: KeyEvent) -> Action {
    // Navigation is arrow keys + Ctrl-N/P only. `j`/`k` intentionally fall
    // through to `InsertChar` below so a user filtering by a template name
    // that contains those letters (`json`, `jquery-nit`, `knative-warn`, …)
    // can actually type them. Post-crew review (2026-05-02) fix.
    match (key.code, key.modifiers) {
        (KeyCode::Esc, KeyModifiers::NONE) => Action::CommentTemplatePickerCancel,
        (KeyCode::Char('c'), KeyModifiers::CONTROL) => Action::CommentTemplatePickerCancel,
        (KeyCode::Enter, KeyModifiers::NONE) => Action::CommentTemplatePickerSelect,
        (KeyCode::Down, KeyModifiers::NONE) => Action::CursorDown(1),
        (KeyCode::Up, KeyModifiers::NONE) => Action::CursorUp(1),
        (KeyCode::Char('n'), KeyModifiers::CONTROL) => Action::CursorDown(1),
        (KeyCode::Char('p'), KeyModifiers::CONTROL) => Action::CursorUp(1),
        (KeyCode::Backspace, KeyModifiers::NONE) => Action::DeleteChar,
        (KeyCode::Char('w'), KeyModifiers::CONTROL) => Action::DeleteWord,
        (KeyCode::Char('u'), KeyModifiers::CONTROL) => Action::ClearLine,
        (KeyCode::Char(c), KeyModifiers::NONE | KeyModifiers::SHIFT) => Action::InsertChar(c),
        _ => Action::None,
    }
}

fn map_reaction_picker_mode(key: KeyEvent) -> Action {
    match (key.code, key.modifiers) {
        (KeyCode::Esc, KeyModifiers::NONE) => Action::ReactionPickerCancel,
        (KeyCode::Char('q'), KeyModifiers::NONE) => Action::ReactionPickerCancel,
        (KeyCode::Enter, KeyModifiers::NONE) => Action::ReactionPickerSelect,
        (KeyCode::Char('h') | KeyCode::Left, KeyModifiers::NONE) => {
            Action::ReactionPickerCursorLeft
        }
        (KeyCode::Char('l') | KeyCode::Right, KeyModifiers::NONE) => {
            Action::ReactionPickerCursorRight
        }
        (KeyCode::Char(c @ '1'..='8'), KeyModifiers::NONE) => {
            Action::ReactionPickerSelectAt((c as u8 - b'1') as usize)
        }
        _ => Action::None,
    }
}

fn map_review_submit_mode(key: KeyEvent) -> Action {
    match (key.code, key.modifiers) {
        // Navigate verdict options
        (KeyCode::Char('j') | KeyCode::Down, KeyModifiers::NONE) => Action::CursorDown(1),
        (KeyCode::Char('k') | KeyCode::Up, KeyModifiers::NONE) => Action::CursorUp(1),
        // Enter: toggle to body editing or confirm verdict
        (KeyCode::Enter, KeyModifiers::NONE) => Action::SelectFile,
        // Ctrl+S: submit the review
        (KeyCode::Char('s'), KeyModifiers::CONTROL) => Action::SubmitInput,
        // Cancel
        (KeyCode::Esc, KeyModifiers::NONE) => Action::ExitMode,
        // Text editing (when in body sub-mode)
        (KeyCode::Backspace, KeyModifiers::NONE) => Action::DeleteChar,
        (KeyCode::Char(c), _) => Action::InsertChar(c),
        _ => Action::None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    fn key_shift(c: char) -> KeyEvent {
        KeyEvent::new(KeyCode::Char(c), KeyModifiers::SHIFT)
    }

    #[test]
    fn should_map_digit_keys_to_digit_action_in_normal_mode() {
        for d in 0..=9u8 {
            let c = (b'0' + d) as char;
            let action = map_normal_mode(key(KeyCode::Char(c)));
            assert_eq!(
                action,
                Action::Digit(d),
                "digit key '{c}' should map to Digit({d})"
            );
        }
    }

    #[test]
    fn should_map_uppercase_g_to_go_to_bottom_in_normal_mode() {
        let action = map_normal_mode(key_shift('G'));
        assert_eq!(action, Action::GoToBottom);
    }

    #[test]
    fn should_map_lowercase_g_to_pending_chord_in_normal_mode() {
        // `g` is a chord prefix in normal mode: the second keystroke picks
        // between `gg` (GoToTop) and `gf` (OpenInEditor). Falling back to
        // GoToTop on any other second key is handled in main.rs.
        let action = map_normal_mode(key(KeyCode::Char('g')));
        assert_eq!(action, Action::PendingGCommand);
    }

    #[test]
    fn should_not_map_digits_in_command_mode() {
        for d in 0..=9u8 {
            let c = (b'0' + d) as char;
            let action = map_command_mode(key(KeyCode::Char(c)));
            assert_eq!(
                action,
                Action::InsertChar(c),
                "digit '{c}' in command mode should be InsertChar"
            );
        }
    }

    #[test]
    fn should_not_map_digits_in_search_mode() {
        for d in 0..=9u8 {
            let c = (b'0' + d) as char;
            let action = map_search_mode(key(KeyCode::Char(c)));
            assert_eq!(
                action,
                Action::InsertChar(c),
                "digit '{c}' in search mode should be InsertChar"
            );
        }
    }

    #[test]
    fn should_not_map_shifted_digits_to_digit_action() {
        // Shift+digit produces characters like !, @, #, etc. on most layouts,
        // but if a terminal sends the raw digit with SHIFT modifier it must not
        // be treated as Action::Digit.
        for d in 0..=9u8 {
            let c = (b'0' + d) as char;
            let action = map_normal_mode(key_shift(c));
            assert_ne!(
                action,
                Action::Digit(d),
                "Shift+'{c}' in normal mode must not produce Digit({d})"
            );
        }
    }

    #[test]
    fn should_map_backtab_to_reverse_focus_in_normal_mode() {
        let action = map_normal_mode(KeyEvent::new(KeyCode::BackTab, KeyModifiers::SHIFT));
        assert_eq!(action, Action::ToggleFocusReverse);
    }

    #[test]
    fn should_map_backtab_to_reverse_comment_type_in_comment_mode() {
        let action = map_comment_mode(KeyEvent::new(KeyCode::BackTab, KeyModifiers::SHIFT));
        assert_eq!(action, Action::CycleCommentTypeReverse);
    }

    #[test]
    fn ctrl_e_in_comment_mode_maps_to_open_external_editor() {
        let action = map_comment_mode(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::CONTROL));
        assert_eq!(action, Action::OpenExternalEditor);
    }

    /// Test the paste insertion logic used in main.rs Event::Paste handler.
    /// The handler inserts pasted text at the cursor position and advances the cursor.
    #[test]
    fn paste_inserts_text_at_cursor_position() {
        let mut buffer = String::from("hello world");
        let mut cursor = 5; // between "hello" and " world"
        let paste_text = " beautiful";

        // Simulate: app.comment.buffer.insert_str(app.comment.cursor, &text);
        //           app.comment.cursor += text.len();
        buffer.insert_str(cursor, paste_text);
        cursor += paste_text.len();

        assert_eq!(buffer, "hello beautiful world");
        assert_eq!(cursor, 15); // 5 + 10
    }

    #[test]
    fn paste_at_empty_buffer() {
        let mut buffer = String::new();
        let mut cursor = 0;
        let paste_text = "pasted content";

        buffer.insert_str(cursor, paste_text);
        cursor += paste_text.len();

        assert_eq!(buffer, "pasted content");
        assert_eq!(cursor, 14);
    }

    #[test]
    fn plain_e_maps_to_open_reaction_picker() {
        let action = map_normal_mode(key(KeyCode::Char('e')));
        assert_eq!(action, Action::OpenReactionPicker);
    }

    #[test]
    fn ctrl_e_still_maps_to_external_editor() {
        // Regression: plain `e` must not clobber the Ctrl+E binding in
        // comment mode, which opens the user's external editor.
        let action = map_comment_mode(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::CONTROL));
        assert_eq!(action, Action::OpenExternalEditor);
    }

    #[test]
    fn dollar_key_maps_to_line_end() {
        assert_eq!(map_normal_mode(key_shift('$')), Action::GoToLineEnd);
    }

    #[test]
    fn shift_h_and_l_map_to_cursor_vertical() {
        assert_eq!(map_normal_mode(key_shift('H')), Action::CursorToTopOfScreen);
        assert_eq!(
            map_normal_mode(key_shift('L')),
            Action::CursorToBottomOfScreen
        );
    }

    #[test]
    fn w_and_b_navigate_hunks() {
        assert_eq!(
            map_normal_mode(key(KeyCode::Char('w'))),
            Action::WordForward
        );
        assert_eq!(
            map_normal_mode(key(KeyCode::Char('b'))),
            Action::WordBackward
        );
    }

    #[test]
    fn ctrl_e_and_ctrl_y_scroll_view_without_cursor() {
        assert_eq!(
            map_normal_mode(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::CONTROL)),
            Action::ScrollViewDown
        );
        assert_eq!(
            map_normal_mode(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::CONTROL)),
            Action::ScrollViewUp
        );
    }

    #[test]
    fn reaction_picker_mode_has_expected_bindings() {
        assert_eq!(
            map_reaction_picker_mode(key(KeyCode::Esc)),
            Action::ReactionPickerCancel
        );
        assert_eq!(
            map_reaction_picker_mode(key(KeyCode::Char('q'))),
            Action::ReactionPickerCancel
        );
        assert_eq!(
            map_reaction_picker_mode(key(KeyCode::Enter)),
            Action::ReactionPickerSelect
        );
        assert_eq!(
            map_reaction_picker_mode(key(KeyCode::Char('h'))),
            Action::ReactionPickerCursorLeft
        );
        assert_eq!(
            map_reaction_picker_mode(key(KeyCode::Left)),
            Action::ReactionPickerCursorLeft
        );
        assert_eq!(
            map_reaction_picker_mode(key(KeyCode::Char('l'))),
            Action::ReactionPickerCursorRight
        );
        assert_eq!(
            map_reaction_picker_mode(key(KeyCode::Right)),
            Action::ReactionPickerCursorRight
        );
        // Digits '1'..='8' select the Nth reaction directly (0-indexed).
        for i in 0..8u8 {
            let c = (b'1' + i) as char;
            let action = map_reaction_picker_mode(key(KeyCode::Char(c)));
            assert_eq!(action, Action::ReactionPickerSelectAt(i as usize));
        }
        // Digits outside 1..=8 and other unbound keys are no-ops.
        assert_eq!(
            map_reaction_picker_mode(key(KeyCode::Char('9'))),
            Action::None
        );
        assert_eq!(
            map_reaction_picker_mode(key(KeyCode::Char('0'))),
            Action::None
        );
    }

    // ---- Post-crew review 2026-05-02: `j`/`k` must type, not navigate,
    // in the comment template picker so users can filter by names that
    // contain those letters (`json`, `jquery-nit`, `knative-warn`).

    #[test]
    fn template_picker_j_k_insert_as_filter_chars_not_nav() {
        assert_eq!(
            map_comment_template_picker_mode(key(KeyCode::Char('j'))),
            Action::InsertChar('j'),
            "lowercase j must reach the filter buffer"
        );
        assert_eq!(
            map_comment_template_picker_mode(key(KeyCode::Char('k'))),
            Action::InsertChar('k'),
            "lowercase k must reach the filter buffer"
        );
    }

    #[test]
    fn esc_in_normal_mode_maps_to_return_to_commits() {
        // Esc in Normal mode now returns to the commit list (was an
        // unhandled no-op `ExitMode` before).
        assert_eq!(map_normal_mode(key(KeyCode::Esc)), Action::ReturnToCommits);
    }

    #[test]
    fn colon_in_commit_picker_enters_command_mode() {
        // `:` opens command mode from the full-screen picker so `:tour`
        // is reachable. Additive — does not change the other picker keys.
        assert_eq!(
            map_commit_select_mode(key(KeyCode::Char(':'))),
            Action::EnterCommandMode
        );
        // Existing picker bindings are unchanged.
        assert_eq!(
            map_commit_select_mode(key(KeyCode::Char(' '))),
            Action::ToggleCommitSelect
        );
        assert_eq!(map_commit_select_mode(key(KeyCode::Esc)), Action::ExitMode);
    }

    #[test]
    fn template_picker_arrow_keys_still_navigate() {
        // Arrow keys and Ctrl-N/P remain the nav bindings so the picker
        // is still keyboard-navigable without modifier-free vim keys.
        assert_eq!(
            map_comment_template_picker_mode(key(KeyCode::Down)),
            Action::CursorDown(1)
        );
        assert_eq!(
            map_comment_template_picker_mode(key(KeyCode::Up)),
            Action::CursorUp(1)
        );
        assert_eq!(
            map_comment_template_picker_mode(KeyEvent::new(
                KeyCode::Char('n'),
                KeyModifiers::CONTROL
            )),
            Action::CursorDown(1)
        );
        assert_eq!(
            map_comment_template_picker_mode(KeyEvent::new(
                KeyCode::Char('p'),
                KeyModifiers::CONTROL
            )),
            Action::CursorUp(1)
        );
    }
}