agentty 0.13.3

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
Documentation
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
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::layout::Rect;

use crate::app::App;
use crate::presentation::app_mode::{
    AppMode, DiffRestoreTarget, DiffScrollCache, HelpContext, ViewportRect,
};
use crate::runtime::EventResult;
use crate::ui::component::file_explorer::FileExplorer;
use crate::ui::{RenderCacheStore, page};

/// Handles key input while the app is in `AppMode::Diff`.
///
/// File selection via `j`/`k` wraps around between the first and last file
/// explorer entries. Leaving diff mode restores the prior composer or question
/// snapshot when present; otherwise it rebuilds session view with any cached
/// focused review output for the same session.
pub(crate) fn handle_with_cache(
    app: &mut App,
    render_cache_store: &RenderCacheStore,
    content_area: Rect,
    key: KeyEvent,
) -> EventResult {
    if handle_help_key(app, key) {
        return EventResult::Continue;
    }

    if handle_exit_key(app, key) {
        return EventResult::Continue;
    }

    handle_navigation_key(app, render_cache_store, content_area, key);

    EventResult::Continue
}

#[cfg(test)]
fn handle(app: &mut App, content_area: Rect, key: KeyEvent) -> EventResult {
    handle_with_cache(app, &RenderCacheStore::default(), content_area, key)
}

/// Runs `git diff` for the session with `session_id`, returning the diff text.
///
/// Returns `None` when the session is not loaded or the worktree diff is empty,
/// so callers can treat the diff shortcut as unavailable for unchanged
/// sessions. Git failures surface as a `Failed to run git diff:` message rather
/// than `None`, so the diff view still opens to report the error.
pub(crate) async fn session_diff(app: &App, session_id: &str) -> Option<String> {
    let session = app
        .sessions
        .sessions()
        .iter()
        .find(|session| session.id == session_id)?;

    let session_folder = session.folder.clone();
    let base_branch = session.base_branch.clone();

    let diff = app
        .services
        .git_client()
        .diff(session_folder, base_branch)
        .await
        .unwrap_or_else(|error| format!("Failed to run git diff: {error}"));

    if diff.trim().is_empty() {
        return None;
    }

    Some(diff)
}

/// Enters `AppMode::Diff` for `session_id` with a preloaded `diff`.
///
/// `restore` records the originating page so leaving the diff returns there;
/// `None` falls back to session view.
pub(crate) fn enter_diff_mode(
    app: &mut App,
    session_id: &str,
    diff: String,
    restore: Option<DiffRestoreTarget>,
) {
    app.mode = AppMode::Diff {
        diff,
        file_explorer_selected_index: 0,
        restore: restore.map(Box::new),
        scroll_cache: None,
        session_id: session_id.into(),
        scroll_offset: 0,
    };
}

/// Opens diff help while preserving the current diff-mode snapshot.
fn handle_help_key(app: &mut App, key: KeyEvent) -> bool {
    if key.code != KeyCode::Char('?') {
        return false;
    }

    let mode = std::mem::replace(&mut app.mode, AppMode::List);
    if let AppMode::Diff {
        diff,
        file_explorer_selected_index,
        restore,
        session_id,
        scroll_offset,
        ..
    } = mode
    {
        app.mode = AppMode::Help {
            context: HelpContext::Diff {
                diff,
                file_explorer_selected_index,
                restore,
                session_id,
                scroll_offset,
            },
            scroll_offset: 0,
        };
    } else {
        app.mode = mode;
    }

    true
}

/// Leaves diff mode and restores the originating view or question state.
fn handle_exit_key(app: &mut App, key: KeyEvent) -> bool {
    if !matches!(key.code, KeyCode::Char('q') | KeyCode::Esc) {
        return false;
    }

    let mode = std::mem::replace(&mut app.mode, AppMode::List);
    if let AppMode::Diff {
        restore,
        session_id,
        ..
    } = mode
    {
        app.mode = if let Some(restore) = restore {
            restore.into_mode()
        } else {
            AppMode::View {
                session_id,
                scroll_offset: None,
            }
        };
    } else {
        app.mode = mode;
    }

    true
}

/// Applies file-selection and scroll navigation keys in diff mode.
fn handle_navigation_key(
    app: &mut App,
    render_cache_store: &RenderCacheStore,
    content_area: Rect,
    key: KeyEvent,
) {
    let mode = std::mem::replace(&mut app.mode, AppMode::List);
    let AppMode::Diff {
        diff,
        mut file_explorer_selected_index,
        restore,
        mut scroll_cache,
        mut scroll_offset,
        session_id,
    } = mode
    else {
        app.mode = mode;

        return;
    };

    match key.code {
        KeyCode::Char('j') if is_plain_char_key(key, 'j') => {
            let content = render_cache_store.diff_layout_cache().content(&diff);
            let new_index = FileExplorer::next_selected_index(
                file_explorer_selected_index,
                content.item_count(),
            );

            if file_explorer_selected_index != new_index {
                file_explorer_selected_index = new_index;
                scroll_cache = None;
                scroll_offset = 0;
            }
        }
        KeyCode::Char('k') if is_plain_char_key(key, 'k') => {
            let content = render_cache_store.diff_layout_cache().content(&diff);
            let new_index = FileExplorer::previous_selected_index(
                file_explorer_selected_index,
                content.item_count(),
            );

            if file_explorer_selected_index != new_index {
                file_explorer_selected_index = new_index;
                scroll_cache = None;
                scroll_offset = 0;
            }
        }
        KeyCode::Down | KeyCode::Char('J' | 'j')
            if key.code == KeyCode::Down || is_shift_char_key(key, 'j') =>
        {
            let max_scroll_offset = diff_max_scroll_offset(
                &diff,
                content_area,
                file_explorer_selected_index,
                &mut scroll_cache,
                render_cache_store.diff_layout_cache(),
            );
            let clamped_scroll_offset = scroll_offset.min(max_scroll_offset);

            scroll_offset = clamped_scroll_offset
                .saturating_add(1)
                .min(max_scroll_offset);
        }
        KeyCode::Up | KeyCode::Char('K' | 'k')
            if key.code == KeyCode::Up || is_shift_char_key(key, 'k') =>
        {
            let max_scroll_offset = diff_max_scroll_offset(
                &diff,
                content_area,
                file_explorer_selected_index,
                &mut scroll_cache,
                render_cache_store.diff_layout_cache(),
            );
            let clamped_scroll_offset = scroll_offset.min(max_scroll_offset);

            scroll_offset = clamped_scroll_offset.saturating_sub(1);
        }
        _ => {}
    }

    app.mode = AppMode::Diff {
        diff,
        file_explorer_selected_index,
        restore,
        scroll_cache,
        scroll_offset,
        session_id,
    };
}

/// Returns true when the key event is a plain character key with no
/// modifiers.
fn is_plain_char_key(key: KeyEvent, character: char) -> bool {
    key.code == KeyCode::Char(character) && key.modifiers == KeyModifiers::NONE
}

/// Returns true when the key event is a shifted character key, accepting both
/// uppercase and lowercase char payloads emitted by terminals.
fn is_shift_char_key(key: KeyEvent, character: char) -> bool {
    let lowercase_character = character.to_ascii_lowercase();
    let uppercase_character = character.to_ascii_uppercase();

    key.modifiers == KeyModifiers::SHIFT
        && matches!(
            key.code,
            KeyCode::Char(pressed)
                if pressed == lowercase_character || pressed == uppercase_character
        )
}

/// Returns the max valid scroll offset for the active diff selection.
fn diff_max_scroll_offset(
    diff: &str,
    content_area: Rect,
    selected_index: usize,
    scroll_cache: &mut Option<DiffScrollCache>,
    diff_layout_cache: &page::diff::DiffLayoutCache,
) -> u16 {
    if let Some(cached_scroll_limit) = scroll_cache
        && cached_scroll_limit.content_area == viewport_rect(content_area)
        && cached_scroll_limit.file_explorer_selected_index == selected_index
    {
        return cached_scroll_limit.max_scroll_offset;
    }

    let max_scroll_offset = page::diff::diff_view_max_scroll_offset(
        diff,
        selected_index,
        content_area,
        diff_layout_cache,
    );

    *scroll_cache = Some(DiffScrollCache {
        content_area: viewport_rect(content_area),
        file_explorer_selected_index: selected_index,
        max_scroll_offset,
    });

    max_scroll_offset
}

/// Converts terminal geometry into the frontend-neutral cached viewport key.
fn viewport_rect(content_area: Rect) -> ViewportRect {
    ViewportRect {
        height: content_area.height,
        width: content_area.width,
        x: content_area.x,
        y: content_area.y,
    }
}

#[cfg(test)]
mod tests {
    use crossterm::event::KeyModifiers;
    use ratatui::layout::Rect;

    use super::*;

    const TEST_TERMINAL_SIZE: Rect = Rect::new(0, 0, 80, 12);

    /// Returns a diff long enough to keep the diff pane scrollable in tests.
    fn scrollable_diff_fixture() -> String {
        (0..40)
            .map(|index| format!("+line {index}"))
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// Draft text carried by [`non_default_prompt_snapshot`].
    const RESTORE_DRAFT_TEXT: &str = "draft body";

    /// The single at-mention entry carried by [`non_default_prompt_snapshot`].
    fn prompt_mention_entry() -> crate::domain::file_entry::FileEntry {
        crate::domain::file_entry::FileEntry {
            is_dir: false,
            path: "src/main.rs".to_string(),
        }
    }

    /// Builds a prompt snapshot with non-default attachment, history, slash,
    /// and at-mention state so restore tests prove no composer field is
    /// dropped when leaving diff.
    fn non_default_prompt_snapshot() -> crate::presentation::app_mode::PromptModeSnapshot {
        use crate::domain::agent::AgentKind;
        use crate::domain::input::InputState;
        use crate::presentation::app_mode::PromptModeSnapshot;
        use crate::presentation::prompt::{
            PromptAtMentionState, PromptAttachmentState, PromptHistoryState, PromptSlashStage,
            PromptSlashState,
        };

        let mut attachment_state = PromptAttachmentState::default();
        attachment_state.register_local_image(std::path::PathBuf::from("/tmp/pic.png"), 0);

        let mut history_state =
            PromptHistoryState::new(vec!["prev one".to_string(), "prev two".to_string()]);
        history_state.draft_text = Some("saved draft".to_string());
        history_state.selected_index = Some(1);

        let mut slash_state = PromptSlashState::with_available_agent_kinds(vec![AgentKind::Codex]);
        slash_state.stage = PromptSlashStage::Model;
        slash_state.selected_index = 2;

        PromptModeSnapshot {
            at_mention_state: Some(PromptAtMentionState {
                all_entries: vec![prompt_mention_entry()],
                selected_index: 1,
            }),
            attachment_state,
            history_state,
            input: InputState::with_text(RESTORE_DRAFT_TEXT.to_string()),
            scroll_offset: Some(4),
            session_id: "session-p".into(),
            slash_state,
        }
    }

    /// Asserts `mode` is a prompt composer restored losslessly from
    /// [`non_default_prompt_snapshot`], with input focus.
    fn assert_restored_prompt_composer(mode: &AppMode) {
        use crate::domain::agent::AgentKind;
        use crate::presentation::prompt::PromptSlashStage;

        let AppMode::Prompt {
            at_mention_state,
            attachment_state,
            focus,
            history_state,
            input,
            scroll_offset,
            slash_state,
            ..
        } = mode
        else {
            unreachable!("expected AppMode::Prompt after leaving diff");
        };

        assert_eq!(*focus, crate::presentation::app_mode::ChatFocus::Input);
        assert_eq!(input.text(), RESTORE_DRAFT_TEXT);
        assert_eq!(*scroll_offset, Some(4));

        assert_eq!(attachment_state.attachments.len(), 1);
        assert_eq!(attachment_state.next_attachment_number, 2);

        assert_eq!(
            history_state.entries,
            vec!["prev one".to_string(), "prev two".to_string()]
        );
        assert_eq!(history_state.draft_text, Some("saved draft".to_string()));
        assert_eq!(history_state.selected_index, Some(1));

        assert_eq!(slash_state.available_agent_kinds, vec![AgentKind::Codex]);
        assert_eq!(slash_state.stage, PromptSlashStage::Model);
        assert_eq!(slash_state.selected_index, 2);

        let at_mention_state = at_mention_state
            .as_ref()
            .expect("at-mention state must survive leaving diff");
        assert_eq!(at_mention_state.selected_index, 1);
        assert_eq!(at_mention_state.all_entries, vec![prompt_mention_entry()]);
    }

    #[tokio::test]
    async fn test_handle_quit_key_returns_to_view_mode() {
        // Arrange
        let (mut app, _base_dir) = crate::test_support::new_test_app().await;
        app.mode = AppMode::Diff {
            session_id: "session-id".into(),
            diff: "diff output".to_string(),
            scroll_offset: 7,
            file_explorer_selected_index: 0,
            restore: None,
            scroll_cache: None,
        };

        // Act
        let event_result = handle(
            &mut app,
            TEST_TERMINAL_SIZE,
            KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE),
        );

        // Assert
        assert!(matches!(event_result, EventResult::Continue));
        assert!(matches!(
            app.mode,
            AppMode::View {
                ref session_id,
                scroll_offset: None,
                ..
            } if session_id == "session-id"
        ));
    }

    #[tokio::test]
    async fn test_handle_quit_key_restores_cached_review_output() {
        // Arrange
        let (mut app, _base_dir) = crate::test_support::new_test_app().await;
        app.review_cache.insert(
            "session-id".into(),
            crate::app::ReviewCacheEntry::Ready {
                text: "Focused review".to_string(),
                diff_hash: 7,
            },
        );
        app.mode = AppMode::Diff {
            session_id: "session-id".into(),
            diff: "diff output".to_string(),
            scroll_offset: 7,
            file_explorer_selected_index: 0,
            restore: None,
            scroll_cache: None,
        };

        // Act
        let event_result = handle(
            &mut app,
            TEST_TERMINAL_SIZE,
            KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE),
        );

        // Assert
        assert!(matches!(event_result, EventResult::Continue));
        assert!(matches!(
            app.mode,
            AppMode::View {
                ref session_id,
                scroll_offset: None,
                ..
            } if session_id == "session-id"
        ));
    }

    #[tokio::test]
    async fn test_handle_down_key_increments_scroll_offset() {
        // Arrange
        let (mut app, _base_dir) = crate::test_support::new_test_app().await;
        app.mode = AppMode::Diff {
            session_id: "session-id".into(),
            diff: scrollable_diff_fixture(),
            scroll_offset: 0,
            file_explorer_selected_index: 0,
            restore: None,
            scroll_cache: None,
        };

        // Act
        let event_result = handle(
            &mut app,
            TEST_TERMINAL_SIZE,
            KeyEvent::new(KeyCode::Down, KeyModifiers::NONE),
        );

        // Assert
        assert!(matches!(event_result, EventResult::Continue));
        assert!(matches!(
            app.mode,
            AppMode::Diff {
                scroll_offset: 1,
                ..
            }
        ));
    }

    #[tokio::test]
    async fn test_handle_shift_j_increments_scroll_offset() {
        // Arrange
        let (mut app, _base_dir) = crate::test_support::new_test_app().await;
        app.mode = AppMode::Diff {
            session_id: "session-id".into(),
            diff: scrollable_diff_fixture(),
            scroll_offset: 3,
            file_explorer_selected_index: 2,
            restore: None,
            scroll_cache: None,
        };

        // Act
        let event_result = handle(
            &mut app,
            TEST_TERMINAL_SIZE,
            KeyEvent::new(KeyCode::Char('J'), KeyModifiers::SHIFT),
        );

        // Assert
        assert!(matches!(event_result, EventResult::Continue));
        assert!(matches!(
            app.mode,
            AppMode::Diff {
                scroll_offset: 4,
                file_explorer_selected_index: 2,
                ..
            }
        ));
    }

    #[tokio::test]
    async fn test_handle_up_key_saturates_scroll_offset_at_zero() {
        // Arrange
        let (mut app, _base_dir) = crate::test_support::new_test_app().await;
        app.mode = AppMode::Diff {
            session_id: "session-id".into(),
            diff: "diff output".to_string(),
            scroll_offset: 0,
            file_explorer_selected_index: 0,
            restore: None,
            scroll_cache: None,
        };

        // Act
        let event_result = handle(
            &mut app,
            TEST_TERMINAL_SIZE,
            KeyEvent::new(KeyCode::Up, KeyModifiers::NONE),
        );

        // Assert
        assert!(matches!(event_result, EventResult::Continue));
        assert!(matches!(
            app.mode,
            AppMode::Diff {
                scroll_offset: 0,
                ..
            }
        ));
    }

    #[tokio::test]
    async fn test_handle_shift_k_saturates_scroll_offset_at_zero() {
        // Arrange
        let (mut app, _base_dir) = crate::test_support::new_test_app().await;
        app.mode = AppMode::Diff {
            session_id: "session-id".into(),
            diff: "diff output".to_string(),
            scroll_offset: 0,
            file_explorer_selected_index: 2,
            restore: None,
            scroll_cache: None,
        };

        // Act
        let event_result = handle(
            &mut app,
            TEST_TERMINAL_SIZE,
            KeyEvent::new(KeyCode::Char('K'), KeyModifiers::SHIFT),
        );

        // Assert
        assert!(matches!(event_result, EventResult::Continue));
        assert!(matches!(
            app.mode,
            AppMode::Diff {
                scroll_offset: 0,
                file_explorer_selected_index: 2,
                ..
            }
        ));
    }

    #[tokio::test]
    async fn test_handle_non_diff_mode_leaves_mode_unchanged() {
        // Arrange
        let (mut app, _base_dir) = crate::test_support::new_test_app().await;
        app.mode = AppMode::List;

        // Act
        let event_result = handle(
            &mut app,
            TEST_TERMINAL_SIZE,
            KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE),
        );

        // Assert
        assert!(matches!(event_result, EventResult::Continue));
        assert!(matches!(app.mode, AppMode::List));
    }

    #[tokio::test]
    async fn test_handle_j_resets_scroll_offset() {
        // Arrange
        let (mut app, _base_dir) = crate::test_support::new_test_app().await;
        app.mode = AppMode::Diff {
            session_id: "session-id".into(),
            diff: "diff --git a/src/main.rs b/src/main.rs\n+added".to_string(),
            scroll_offset: 10,
            file_explorer_selected_index: 0,
            restore: None,
            scroll_cache: None,
        };

        // Act
        handle(
            &mut app,
            TEST_TERMINAL_SIZE,
            KeyEvent::new(KeyCode::Char('j'), KeyModifiers::NONE),
        );

        // Assert
        assert!(matches!(
            app.mode,
            AppMode::Diff {
                scroll_offset: 0,
                file_explorer_selected_index: 1,
                ..
            }
        ));
    }

    #[tokio::test]
    async fn test_handle_j_wraps_file_selection_from_last_to_first() {
        // Arrange
        let (mut app, _base_dir) = crate::test_support::new_test_app().await;
        app.mode = AppMode::Diff {
            session_id: "session-id".into(),
            diff: "diff --git a/src/main.rs b/src/main.rs\n+added".to_string(),
            scroll_offset: 10,
            file_explorer_selected_index: 1,
            restore: None,
            scroll_cache: None,
        };

        // Act
        handle(
            &mut app,
            TEST_TERMINAL_SIZE,
            KeyEvent::new(KeyCode::Char('j'), KeyModifiers::NONE),
        );

        // Assert
        assert!(matches!(
            app.mode,
            AppMode::Diff {
                scroll_offset: 0,
                file_explorer_selected_index: 0,
                ..
            }
        ));
    }

    #[tokio::test]
    async fn test_handle_k_resets_scroll_offset() {
        // Arrange
        let (mut app, _base_dir) = crate::test_support::new_test_app().await;
        app.mode = AppMode::Diff {
            session_id: "session-id".into(),
            diff: "diff --git a/src/main.rs b/src/main.rs\n+added".to_string(),
            scroll_offset: 10,
            file_explorer_selected_index: 1,
            restore: None,
            scroll_cache: None,
        };

        // Act
        handle(
            &mut app,
            TEST_TERMINAL_SIZE,
            KeyEvent::new(KeyCode::Char('k'), KeyModifiers::NONE),
        );

        // Assert
        assert!(matches!(
            app.mode,
            AppMode::Diff {
                scroll_offset: 0,
                file_explorer_selected_index: 0,
                ..
            }
        ));
    }

    #[tokio::test]
    async fn test_handle_k_wraps_file_selection_from_first_to_last() {
        // Arrange
        let (mut app, _base_dir) = crate::test_support::new_test_app().await;
        app.mode = AppMode::Diff {
            session_id: "session-id".into(),
            diff: "diff --git a/src/main.rs b/src/main.rs\n+added".to_string(),
            scroll_offset: 10,
            file_explorer_selected_index: 0,
            restore: None,
            scroll_cache: None,
        };

        // Act
        handle(
            &mut app,
            TEST_TERMINAL_SIZE,
            KeyEvent::new(KeyCode::Char('k'), KeyModifiers::NONE),
        );

        // Assert
        assert!(matches!(
            app.mode,
            AppMode::Diff {
                scroll_offset: 0,
                file_explorer_selected_index: 1,
                ..
            }
        ));
    }

    #[tokio::test]
    async fn test_handle_question_mark_opens_help_overlay() {
        // Arrange
        let (mut app, _base_dir) = crate::test_support::new_test_app().await;
        app.mode = AppMode::Diff {
            session_id: "session-id".into(),
            diff: "diff output".to_string(),
            scroll_offset: 5,
            file_explorer_selected_index: 3,
            restore: None,
            scroll_cache: None,
        };

        // Act
        let event_result = handle(
            &mut app,
            TEST_TERMINAL_SIZE,
            KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE),
        );

        // Assert
        assert!(matches!(event_result, EventResult::Continue));
        assert!(matches!(
            app.mode,
            AppMode::Help {
                context: HelpContext::Diff {
                    ref session_id,
                    ref diff,
                    scroll_offset: 5,
                    file_explorer_selected_index: 3,
                    ..
                },
                scroll_offset: 0,
            } if session_id == "session-id" && diff == "diff output"
        ));
    }

    #[tokio::test]
    async fn test_handle_down_key_clamps_scroll_offset_at_bottom() {
        // Arrange
        let (mut app, _base_dir) = crate::test_support::new_test_app().await;
        let diff = scrollable_diff_fixture();
        let diff_layout_cache = page::diff::DiffLayoutCache::default();
        let max_scroll_offset =
            diff_max_scroll_offset(&diff, TEST_TERMINAL_SIZE, 0, &mut None, &diff_layout_cache);
        app.mode = AppMode::Diff {
            session_id: "session-id".into(),
            diff,
            scroll_offset: max_scroll_offset,
            file_explorer_selected_index: 0,
            restore: None,
            scroll_cache: None,
        };

        // Act
        let event_result = handle(
            &mut app,
            TEST_TERMINAL_SIZE,
            KeyEvent::new(KeyCode::Down, KeyModifiers::NONE),
        );

        // Assert
        assert!(matches!(event_result, EventResult::Continue));
        assert!(matches!(
            app.mode,
            AppMode::Diff {
                scroll_offset,
                ..
            } if scroll_offset == max_scroll_offset
        ));
    }

    #[tokio::test]
    async fn test_handle_up_key_recovers_immediately_from_overscrolled_state() {
        // Arrange
        let (mut app, _base_dir) = crate::test_support::new_test_app().await;
        let diff = scrollable_diff_fixture();
        let diff_layout_cache = page::diff::DiffLayoutCache::default();
        let max_scroll_offset =
            diff_max_scroll_offset(&diff, TEST_TERMINAL_SIZE, 0, &mut None, &diff_layout_cache);
        app.mode = AppMode::Diff {
            session_id: "session-id".into(),
            diff,
            scroll_offset: u16::MAX,
            file_explorer_selected_index: 0,
            restore: None,
            scroll_cache: None,
        };

        // Act
        let event_result = handle(
            &mut app,
            TEST_TERMINAL_SIZE,
            KeyEvent::new(KeyCode::Up, KeyModifiers::NONE),
        );

        // Assert
        assert!(matches!(event_result, EventResult::Continue));
        assert!(matches!(
            app.mode,
            AppMode::Diff {
                scroll_offset,
                ..
            } if scroll_offset == max_scroll_offset.saturating_sub(1)
        ));
    }

    #[tokio::test]
    async fn test_handle_quit_with_question_snapshot_restores_question_mode() {
        // Arrange — diff opened from question mode carries a snapshot.
        use crate::domain::input::InputState;
        use crate::domain::question::QuestionItem;
        use crate::presentation::app_mode::QuestionModeSnapshot;

        let (mut app, _base_dir) = crate::test_support::new_test_app().await;
        app.mode = AppMode::Diff {
            session_id: "session-q".into(),
            diff: "diff output".to_string(),
            scroll_offset: 0,
            file_explorer_selected_index: 0,
            restore: Some(Box::new(DiffRestoreTarget::Question(
                QuestionModeSnapshot {
                    at_mention_state: None,
                    current_index: 0,
                    input: InputState::default(),
                    questions: vec![QuestionItem {
                        options: Vec::new(),
                        text: "Q?".to_string(),
                    }],
                    responses: Vec::new(),
                    scroll_offset: None,
                    selected_option_index: None,
                    session_id: "session-q".into(),
                },
            ))),
            scroll_cache: None,
        };

        // Act
        let event_result = handle(
            &mut app,
            TEST_TERMINAL_SIZE,
            KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE),
        );

        // Assert — restored to Question mode, not View.
        assert!(matches!(event_result, EventResult::Continue));
        assert!(matches!(
            app.mode,
            AppMode::Question {
                ref session_id,
                focus: crate::presentation::app_mode::ChatFocus::Input,
                ..
            } if session_id == "session-q"
        ));
    }

    #[tokio::test]
    async fn test_handle_quit_with_prompt_snapshot_restores_prompt_mode() {
        // Arrange — diff opened from prompt mode carries a composer snapshot.
        use crate::domain::input::InputState;
        use crate::presentation::app_mode::PromptModeSnapshot;
        use crate::presentation::prompt::{
            PromptAttachmentState, PromptHistoryState, PromptSlashState,
        };

        let (mut app, _base_dir) = crate::test_support::new_test_app().await;
        app.mode = AppMode::Diff {
            session_id: "session-p".into(),
            diff: "diff output".to_string(),
            scroll_offset: 0,
            file_explorer_selected_index: 0,
            restore: Some(Box::new(DiffRestoreTarget::Prompt(PromptModeSnapshot {
                at_mention_state: None,
                attachment_state: PromptAttachmentState::default(),
                history_state: PromptHistoryState::new(Vec::new()),
                input: InputState::with_text("draft text".to_string()),
                scroll_offset: None,
                session_id: "session-p".into(),
                slash_state: PromptSlashState::default(),
            }))),
            scroll_cache: None,
        };

        // Act
        let event_result = handle(
            &mut app,
            TEST_TERMINAL_SIZE,
            KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE),
        );

        // Assert — restored to prompt mode with the draft intact and input focus.
        assert!(matches!(event_result, EventResult::Continue));
        assert!(matches!(
            &app.mode,
            AppMode::Prompt {
                focus: crate::presentation::app_mode::ChatFocus::Input,
                input,
                session_id,
                ..
            } if input.text() == "draft text" && session_id == "session-p"
        ));
    }

    #[tokio::test]
    async fn test_handle_quit_with_prompt_snapshot_preserves_composer_context() {
        // Arrange — a prompt snapshot carrying non-default attachment, history,
        // slash, and at-mention state so leaving diff cannot silently drop it.
        let (mut app, _base_dir) = crate::test_support::new_test_app().await;
        app.mode = AppMode::Diff {
            session_id: "session-p".into(),
            diff: "diff output".to_string(),
            scroll_offset: 0,
            file_explorer_selected_index: 0,
            restore: Some(Box::new(DiffRestoreTarget::Prompt(
                non_default_prompt_snapshot(),
            ))),
            scroll_cache: None,
        };

        // Act
        handle(
            &mut app,
            TEST_TERMINAL_SIZE,
            KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE),
        );

        // Assert — every composer field survives the diff round-trip.
        assert_restored_prompt_composer(&app.mode);
    }

    #[tokio::test]
    async fn test_handle_prompt_then_help_then_exit_preserves_composer_context() {
        // Arrange — diff opened from prompt mode, then the user opens help with `?`.
        let (mut app, _base_dir) = crate::test_support::new_test_app().await;
        app.mode = AppMode::Diff {
            session_id: "session-p".into(),
            diff: "diff output".to_string(),
            scroll_offset: 3,
            file_explorer_selected_index: 1,
            restore: Some(Box::new(DiffRestoreTarget::Prompt(
                non_default_prompt_snapshot(),
            ))),
            scroll_cache: None,
        };

        // Act — open help overlay.
        handle(
            &mut app,
            TEST_TERMINAL_SIZE,
            KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE),
        );

        // Intermediate assert — help carries the prompt restore target.
        assert!(matches!(
            app.mode,
            AppMode::Help {
                context: HelpContext::Diff {
                    restore: Some(_),
                    ..
                },
                ..
            }
        ));

        // Act — close help overlay, returning to diff.
        crate::runtime::mode::help::handle(
            &mut app,
            KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE),
        );

        // Intermediate assert — diff still carries the prompt restore target.
        assert!(matches!(
            app.mode,
            AppMode::Diff {
                restore: Some(_),
                ..
            }
        ));

        // Act — exit diff.
        handle(
            &mut app,
            TEST_TERMINAL_SIZE,
            KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE),
        );

        // Assert — restored to the prompt composer with all context intact.
        assert_restored_prompt_composer(&app.mode);
    }

    #[tokio::test]
    async fn test_handle_question_then_help_then_exit_preserves_restore_question() {
        // Arrange — diff opened from question mode, then user opens help with `?`.
        use crate::domain::input::InputState;
        use crate::domain::question::QuestionItem;
        use crate::presentation::app_mode::QuestionModeSnapshot;

        let (mut app, _base_dir) = crate::test_support::new_test_app().await;
        let snapshot = QuestionModeSnapshot {
            at_mention_state: None,
            current_index: 1,
            input: InputState::default(),
            questions: vec![
                QuestionItem {
                    options: Vec::new(),
                    text: "Q1?".to_string(),
                },
                QuestionItem {
                    options: Vec::new(),
                    text: "Q2?".to_string(),
                },
            ],
            responses: vec!["answer-1".to_string()],
            scroll_offset: None,
            selected_option_index: None,
            session_id: "session-q".into(),
        };

        app.mode = AppMode::Diff {
            session_id: "session-q".into(),
            diff: "diff output".to_string(),
            scroll_offset: 3,
            file_explorer_selected_index: 1,
            restore: Some(Box::new(DiffRestoreTarget::Question(snapshot))),
            scroll_cache: None,
        };

        // Act — open help overlay.
        handle(
            &mut app,
            TEST_TERMINAL_SIZE,
            KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE),
        );

        // Intermediate assert — help carries the snapshot.
        assert!(matches!(
            app.mode,
            AppMode::Help {
                context: HelpContext::Diff {
                    restore: Some(_),
                    ..
                },
                ..
            }
        ));

        // Act — close help overlay, returning to diff.
        crate::runtime::mode::help::handle(
            &mut app,
            KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE),
        );

        // Intermediate assert — diff still carries the snapshot.
        assert!(matches!(
            app.mode,
            AppMode::Diff {
                restore: Some(_),
                ..
            }
        ));

        // Act — exit diff.
        handle(
            &mut app,
            TEST_TERMINAL_SIZE,
            KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE),
        );

        // Assert — restored to Question mode, not View.
        assert!(matches!(
            app.mode,
            AppMode::Question {
                ref session_id,
                current_index: 1,
                focus: crate::presentation::app_mode::ChatFocus::Input,
                ..
            } if session_id == "session-q"
        ));
    }

    #[tokio::test]
    async fn test_handle_question_mark_in_non_diff_mode_leaves_mode_unchanged() {
        // Arrange
        let (mut app, _base_dir) = crate::test_support::new_test_app().await;
        app.mode = AppMode::List;

        // Act
        let event_result = handle(
            &mut app,
            TEST_TERMINAL_SIZE,
            KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE),
        );

        // Assert — the help key is a no-op outside diff mode.
        assert!(matches!(event_result, EventResult::Continue));
        assert!(matches!(app.mode, AppMode::List));
    }

    #[tokio::test]
    async fn test_handle_navigation_key_in_non_diff_mode_leaves_mode_unchanged() {
        // Arrange
        let (mut app, _base_dir) = crate::test_support::new_test_app().await;
        app.mode = AppMode::List;

        // Act
        let event_result = handle(
            &mut app,
            TEST_TERMINAL_SIZE,
            KeyEvent::new(KeyCode::Char('j'), KeyModifiers::NONE),
        );

        // Assert — navigation keys are a no-op outside diff mode.
        assert!(matches!(event_result, EventResult::Continue));
        assert!(matches!(app.mode, AppMode::List));
    }

    #[tokio::test]
    async fn test_handle_unhandled_key_keeps_diff_mode_unchanged() {
        // Arrange
        let (mut app, _base_dir) = crate::test_support::new_test_app().await;
        app.mode = AppMode::Diff {
            session_id: "session-id".into(),
            diff: "diff output".to_string(),
            scroll_offset: 4,
            file_explorer_selected_index: 2,
            restore: None,
            scroll_cache: None,
        };

        // Act
        let event_result = handle(
            &mut app,
            TEST_TERMINAL_SIZE,
            KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE),
        );

        // Assert — an unhandled key leaves the diff selection and scroll intact.
        assert!(matches!(event_result, EventResult::Continue));
        assert!(matches!(
            app.mode,
            AppMode::Diff {
                scroll_offset: 4,
                file_explorer_selected_index: 2,
                ..
            }
        ));
    }

    #[test]
    fn test_diff_max_scroll_offset_returns_cached_value_on_matching_key() {
        // Arrange — a cache entry whose key matches the requested viewport and
        // selection.
        let diff = scrollable_diff_fixture();
        let diff_layout_cache = page::diff::DiffLayoutCache::default();
        let mut scroll_cache = Some(DiffScrollCache {
            content_area: viewport_rect(TEST_TERMINAL_SIZE),
            file_explorer_selected_index: 0,
            max_scroll_offset: 4242,
        });

        // Act
        let max_scroll_offset = diff_max_scroll_offset(
            &diff,
            TEST_TERMINAL_SIZE,
            0,
            &mut scroll_cache,
            &diff_layout_cache,
        );

        // Assert — the cached limit is returned verbatim without recomputing.
        assert_eq!(max_scroll_offset, 4242);
    }

    #[test]
    #[should_panic(expected = "expected AppMode::Prompt after leaving diff")]
    fn test_assert_restored_prompt_composer_rejects_non_prompt_mode() {
        // Arrange, Act & Assert — the helper rejects modes that are not a restored
        // composer.
        assert_restored_prompt_composer(&AppMode::List);
    }
}