agentty 0.8.11

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
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
use std::io;

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::Terminal;
use ratatui::backend::Backend;
use ratatui::layout::{Constraint, Layout, Rect};
use tracing::warn;

use crate::app::{App, ReviewCacheEntry, diff_content_hash, review_loading_message};
use crate::domain::session::SessionId;
use crate::domain::transcript_notice::TranscriptNotice;
use crate::runtime::mode::confirmation::ConfirmationDecision;
use crate::runtime::{EventResult, backend_err, mode};
use crate::ui::state::app_mode::{AppMode, ConfirmationIntent, ConfirmationViewMode};

/// Routes key events to the active mode handler and returns the next runtime
/// action.
///
/// Successful handlers mark the app dirty so the next loop iteration renders
/// the updated UI state.
pub(crate) async fn handle_key_event<B: Backend>(
    app: &mut App,
    terminal: &mut Terminal<B>,
    key: KeyEvent,
) -> io::Result<EventResult>
where
    B::Error: std::error::Error + Send + Sync + 'static,
{
    let result = if let AppMode::Confirmation {
        selected_confirmation_index,
        ..
    } = &mut app.mode
    {
        let decision = mode::confirmation::handle(selected_confirmation_index, key);

        handle_confirmation_decision(app, decision).await
    } else if matches!(app.mode, AppMode::SessionCreation { .. }) {
        handle_session_creation_key(app, key).await
    } else if matches!(app.mode, AppMode::OpenCommandSelector { .. }) {
        handle_open_command_selector_key(app, key).await
    } else if matches!(app.mode, AppMode::PublishBranchInput { .. }) {
        Ok(handle_publish_branch_input_key(app, key))
    } else {
        match &app.mode {
            AppMode::List => mode::list::handle(app, key).await,
            AppMode::SessionCreation { .. } => {
                unreachable!("session creation mode is handled before dispatch matching")
            }
            AppMode::SyncBlockedPopup { .. } => Ok(mode::sync_blocked::handle(app, key)),
            AppMode::ViewInfoPopup { .. } => Ok(handle_view_info_popup_key(app, key)),
            AppMode::Confirmation { .. } => {
                unreachable!("confirmation mode is handled before dispatch matching")
            }
            AppMode::View { .. } => mode::session_view::handle(app, terminal, key).await,
            AppMode::Prompt { .. } => mode::prompt::handle(app, terminal, key).await,
            AppMode::Question { .. } => {
                let size = terminal.size().map_err(backend_err)?;
                let terminal_rect = Rect::new(0, 0, size.width, size.height);

                Ok(mode::question::handle(app, terminal_rect, key).await)
            }
            AppMode::Diff { .. } => {
                let size = terminal.size().map_err(backend_err)?;
                let terminal_rect = Rect::new(0, 0, size.width, size.height);
                let content_area = content_area_for_terminal(terminal_rect);

                Ok(mode::diff::handle(app, content_area, key))
            }
            AppMode::Help { .. } => Ok(mode::help::handle(app, key)),
            AppMode::OpenCommandSelector { .. } => {
                unreachable!("open-command selector mode is handled before dispatch matching")
            }
            AppMode::PublishBranchInput { .. } => {
                unreachable!("publish-branch input mode is handled before dispatch matching")
            }
        }
    };

    if result.is_ok() {
        app.mark_dirty();
    }

    result
}

/// Returns the central content area after removing the global status and
/// footer bars from the full terminal rectangle.
fn content_area_for_terminal(terminal_rect: Rect) -> Rect {
    let outer_chunks = Layout::default()
        .constraints([
            Constraint::Length(1),
            Constraint::Min(0),
            Constraint::Length(1),
        ])
        .split(terminal_rect);

    outer_chunks[1]
}

/// Handles key input while the session creation selector is visible.
async fn handle_session_creation_key(app: &mut App, key: KeyEvent) -> io::Result<EventResult> {
    match key.code {
        KeyCode::Esc => {
            app.mode = AppMode::List;
        }
        KeyCode::Char(character) if character.eq_ignore_ascii_case(&'q') => {
            app.mode = AppMode::List;
        }
        KeyCode::Up | KeyCode::Char('k') => {
            update_session_creation_selection(app, 0);
        }
        KeyCode::Down | KeyCode::Char('j') => {
            update_session_creation_selection(app, 1);
        }
        KeyCode::Enter => {
            let is_draft = matches!(
                app.mode,
                AppMode::SessionCreation {
                    selected_option_index: 1,
                }
            );
            create_selected_session(app, is_draft).await?;
        }
        _ => {}
    }

    Ok(EventResult::Continue)
}

/// Updates the highlighted option in the session creation selector.
fn update_session_creation_selection(app: &mut App, selected_option_index: usize) {
    if let AppMode::SessionCreation {
        selected_option_index: current_index,
    } = &mut app.mode
    {
        *current_index = selected_option_index.min(1);
    }
}

/// Creates the selected session type and opens its prompt composer.
async fn create_selected_session(app: &mut App, is_draft: bool) -> io::Result<()> {
    let session_id = if is_draft {
        app.create_draft_session().await.map_err(io::Error::other)?
    } else {
        app.create_session().await.map_err(io::Error::other)?
    };
    mode::list::open_session_prompt(app, session_id);

    Ok(())
}

/// Handles key input while a session-scoped informational popup is visible.
fn handle_view_info_popup_key(app: &mut App, key: KeyEvent) -> EventResult {
    let AppMode::ViewInfoPopup {
        is_loading,
        restore_view,
        ..
    } = &app.mode
    else {
        return EventResult::Continue;
    };

    if *is_loading {
        return EventResult::Continue;
    }

    match key.code {
        KeyCode::Enter | KeyCode::Esc => {
            app.mode = restore_view.clone().into_view_mode();
        }
        KeyCode::Char(character) if character.eq_ignore_ascii_case(&'q') => {
            app.mode = restore_view.clone().into_view_mode();
        }
        _ => {}
    }

    EventResult::Continue
}

/// Handles key input while the publish-branch input overlay is visible.
///
/// Only `Esc` cancels the overlay. Plain character keys continue to edit the
/// branch name so session-view shortcuts like `q` and `p` do not leak through
/// while the text field has focus.
fn handle_publish_branch_input_key(app: &mut App, key: KeyEvent) -> EventResult {
    let publish_branch_input =
        PublishBranchInputModeState::from_mode(std::mem::replace(&mut app.mode, AppMode::List));
    let input_locked = publish_branch_input.locked_upstream_ref.is_some();

    match key.code {
        KeyCode::Esc => {
            app.mode = publish_branch_input.restore_view.into_view_mode();
        }
        KeyCode::Enter => {
            let remote_branch_name = if input_locked {
                Some(publish_branch_input.input.text().trim().to_string())
            } else {
                (!publish_branch_input.input.text().trim().is_empty())
                    .then(|| publish_branch_input.input.text().trim().to_string())
            };
            let session_id = publish_branch_input.restore_view.session_id.clone();

            app.start_publish_branch_action(
                publish_branch_input.restore_view,
                &session_id,
                publish_branch_input.publish_branch_action,
                remote_branch_name,
            );
        }
        KeyCode::Left if !input_locked => {
            app.mode =
                publish_branch_input.apply_input_edit(crate::domain::input::InputState::move_left);
        }
        KeyCode::Right if !input_locked => {
            app.mode =
                publish_branch_input.apply_input_edit(crate::domain::input::InputState::move_right);
        }
        KeyCode::Up if !input_locked => {
            app.mode =
                publish_branch_input.apply_input_edit(crate::domain::input::InputState::move_up);
        }
        KeyCode::Down if !input_locked => {
            app.mode =
                publish_branch_input.apply_input_edit(crate::domain::input::InputState::move_down);
        }
        KeyCode::Home if !input_locked => {
            app.mode =
                publish_branch_input.apply_input_edit(crate::domain::input::InputState::move_home);
        }
        KeyCode::End if !input_locked => {
            app.mode =
                publish_branch_input.apply_input_edit(crate::domain::input::InputState::move_end);
        }
        KeyCode::Backspace if !input_locked => {
            app.mode = publish_branch_input
                .apply_input_edit(crate::domain::input::InputState::delete_backward);
        }
        KeyCode::Delete if !input_locked => {
            app.mode = publish_branch_input
                .apply_input_edit(crate::domain::input::InputState::delete_forward);
        }
        KeyCode::Char(character) if !input_locked && is_publish_branch_input_text_key(key) => {
            app.mode = publish_branch_input.apply_input_edit(|input| input.insert_char(character));
        }
        _ => {
            app.mode = publish_branch_input.into_mode();
        }
    }

    EventResult::Continue
}

/// Returns whether one key event should insert text into the publish-branch
/// input field.
///
/// Matches the prompt/question input policy: only plain and shifted
/// characters are treated as text input.
fn is_publish_branch_input_text_key(key: KeyEvent) -> bool {
    key.modifiers == KeyModifiers::NONE || key.modifiers == KeyModifiers::SHIFT
}

/// Captures `AppMode::PublishBranchInput` fields so key handlers can rebuild
/// the overlay consistently after input edits.
struct PublishBranchInputModeState {
    default_branch_name: String,
    input: crate::domain::input::InputState,
    locked_upstream_ref: Option<String>,
    publish_branch_action: crate::domain::session::PublishBranchAction,
    restore_view: ConfirmationViewMode,
}

impl PublishBranchInputModeState {
    /// Extracts publish-branch overlay fields from an app mode value.
    fn from_mode(mode: AppMode) -> Self {
        let AppMode::PublishBranchInput {
            default_branch_name,
            input,
            locked_upstream_ref,
            publish_branch_action,
            restore_view,
        } = mode
        else {
            unreachable!("mode must be publish-branch input in this handler");
        };

        Self {
            default_branch_name,
            input,
            locked_upstream_ref,
            publish_branch_action,
            restore_view,
        }
    }

    /// Applies one input edit and rebuilds the publish-branch overlay mode.
    fn apply_input_edit(
        mut self,
        edit: impl FnOnce(&mut crate::domain::input::InputState),
    ) -> AppMode {
        edit(&mut self.input);

        self.into_mode()
    }

    /// Rebuilds `AppMode::PublishBranchInput` from the stored overlay fields.
    fn into_mode(self) -> AppMode {
        AppMode::PublishBranchInput {
            default_branch_name: self.default_branch_name,
            input: self.input,
            locked_upstream_ref: self.locked_upstream_ref,
            publish_branch_action: self.publish_branch_action,
            restore_view: self.restore_view,
        }
    }
}

/// Handles key input while the app is in open-command selector overlay mode.
async fn handle_open_command_selector_key(app: &mut App, key: KeyEvent) -> io::Result<EventResult> {
    let mode = std::mem::replace(&mut app.mode, AppMode::List);
    let AppMode::OpenCommandSelector {
        commands,
        restore_view,
        selected_command_index,
    } = mode
    else {
        unreachable!("mode must be open-command selector in this handler");
    };

    match key.code {
        KeyCode::Esc | KeyCode::Char('q') => {
            app.mode = restore_view.into_view_mode();
        }
        KeyCode::Char('j') | KeyCode::Down => {
            app.mode = AppMode::OpenCommandSelector {
                selected_command_index: next_open_command_index(selected_command_index, &commands),
                commands,
                restore_view,
            };
        }
        KeyCode::Char('k') | KeyCode::Up => {
            app.mode = AppMode::OpenCommandSelector {
                selected_command_index: previous_open_command_index(
                    selected_command_index,
                    &commands,
                ),
                commands,
                restore_view,
            };
        }
        KeyCode::Enter => {
            let selected_open_command = commands
                .get(selected_command_index)
                .map(std::string::String::as_str);
            app.mode = restore_view.into_view_mode();
            app.open_session_worktree_in_tmux_with_command(selected_open_command)
                .await;
        }
        _ => {
            app.mode = AppMode::OpenCommandSelector {
                commands,
                restore_view,
                selected_command_index,
            };
        }
    }

    Ok(EventResult::Continue)
}

/// Returns the next command index with wrap-around.
fn next_open_command_index(current_index: usize, commands: &[String]) -> usize {
    if commands.is_empty() {
        return 0;
    }

    (current_index + 1) % commands.len()
}

/// Returns the previous command index with wrap-around.
fn previous_open_command_index(current_index: usize, commands: &[String]) -> usize {
    if commands.is_empty() {
        return 0;
    }

    if current_index == 0 {
        commands.len() - 1
    } else {
        current_index - 1
    }
}

/// Applies the semantic result of a generic confirmation interaction.
async fn handle_confirmation_decision(
    app: &mut App,
    decision: ConfirmationDecision,
) -> io::Result<EventResult> {
    match decision {
        ConfirmationDecision::Confirm => handle_confirmation_confirm(app).await,
        ConfirmationDecision::Cancel => {
            app.mode = confirmation_cancel_mode(&app.mode);

            Ok(EventResult::Continue)
        }
        ConfirmationDecision::Continue => Ok(EventResult::Continue),
    }
}

/// Resolves target mode for `Cancel` in confirmation overlays.
fn confirmation_cancel_mode(mode: &AppMode) -> AppMode {
    if let AppMode::Confirmation {
        confirmation_intent:
            ConfirmationIntent::ContinueSession
            | ConfirmationIntent::MergeSession
            | ConfirmationIntent::RegenerateReview,
        restore_view: Some(restore_view),
        ..
    } = mode
    {
        return restore_view.clone().into_view_mode();
    }

    AppMode::List
}

/// Resolves a positive confirmation by dispatching the configured action
/// intent.
async fn handle_confirmation_confirm(app: &mut App) -> io::Result<EventResult> {
    let (confirmation_intent, confirmation_session_id, restore_view) = match &app.mode {
        AppMode::Confirmation {
            confirmation_intent,
            restore_view,
            session_id,
            ..
        } => (
            *confirmation_intent,
            session_id.clone(),
            restore_view.clone(),
        ),
        _ => return Ok(EventResult::Continue),
    };

    match confirmation_intent {
        ConfirmationIntent::Quit => {
            app.mode = AppMode::List;

            Ok(EventResult::Quit)
        }
        ConfirmationIntent::CancelSession => {
            handle_cancel_session_confirmation(app, confirmation_session_id).await
        }
        ConfirmationIntent::ContinueSession => {
            handle_continue_session_confirmation(app, confirmation_session_id, restore_view).await
        }
        ConfirmationIntent::MergeSession => {
            handle_merge_confirmation(app, confirmation_session_id, restore_view).await
        }
        ConfirmationIntent::RegenerateReview => {
            handle_regenerate_review_confirmation(app, confirmation_session_id, restore_view).await
        }
    }
}

/// Cancels the confirmed cancelable session, when still present, and returns
/// to list mode.
async fn handle_cancel_session_confirmation(
    app: &mut App,
    confirmation_session_id: Option<SessionId>,
) -> io::Result<EventResult> {
    app.mode = AppMode::List;

    if let Some(session_id) = confirmation_session_id
        && let Err(error) = app.cancel_session(&session_id).await
    {
        warn!(
            session_id = %session_id,
            error = %error,
            "failed to cancel confirmed session"
        );
    }

    Ok(EventResult::Continue)
}

/// Creates a continuation draft for the confirmed terminal session and opens
/// its prompt composer.
async fn handle_continue_session_confirmation(
    app: &mut App,
    confirmation_session_id: Option<SessionId>,
    restore_view: Option<ConfirmationViewMode>,
) -> io::Result<EventResult> {
    let Some(session_id) = confirmation_session_id else {
        app.mode = restore_view.map_or(AppMode::List, ConfirmationViewMode::into_view_mode);

        return Ok(EventResult::Continue);
    };

    if let Err(error) = app.continue_terminal_session(&session_id).await {
        app.mode = restore_view.map_or(AppMode::List, ConfirmationViewMode::into_view_mode);
        app.append_output_for_session(&session_id, &TranscriptNotice::ContinueError.format(error))
            .await;
    }

    Ok(EventResult::Continue)
}

/// Restores view mode and attempts to add confirmed session to merge queue.
async fn handle_merge_confirmation(
    app: &mut App,
    confirmation_session_id: Option<SessionId>,
    restore_view: Option<ConfirmationViewMode>,
) -> io::Result<EventResult> {
    app.mode = restore_view.map_or(AppMode::List, ConfirmationViewMode::into_view_mode);

    if let Some(session_id) = confirmation_session_id
        && let Err(error) = app.merge_session(&session_id).await
    {
        app.append_output_for_session(&session_id, &TranscriptNotice::MergeError.format(error))
            .await;
    }

    Ok(EventResult::Continue)
}

/// Clears focused review cache state and persisted review text, restarts
/// generation for the confirmed session, then restores session view with the
/// refreshed review state.
async fn handle_regenerate_review_confirmation(
    app: &mut App,
    confirmation_session_id: Option<SessionId>,
    restore_view: Option<ConfirmationViewMode>,
) -> io::Result<EventResult> {
    let Some(session_id) = confirmation_session_id else {
        app.mode = AppMode::List;

        return Ok(EventResult::Continue);
    };

    app.review_cache.remove(session_id.as_str());

    let session = app
        .sessions
        .sessions
        .iter()
        .find(|session| session.id == session_id);
    let Some(session) = session else {
        app.mode = restore_view.map_or(AppMode::List, ConfirmationViewMode::into_view_mode);

        return Ok(EventResult::Continue);
    };

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

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

    if diff.trim().is_empty() || diff.starts_with("Failed to run git diff:") {
        let mut view_mode = restore_view.unwrap_or(ConfirmationViewMode {
            review_status_message: None,
            review_text: None,
            scroll_offset: None,
            session_id: session_id.clone(),
        });
        view_mode.review_status_message = None;
        view_mode.review_text = if diff.trim().is_empty() {
            Some("No diff changes found for review.".to_string())
        } else {
            Some(diff)
        };
        app.mode = view_mode.into_view_mode();

        return Ok(EventResult::Continue);
    }

    let diff_hash = diff_content_hash(&diff);
    let review_model = app.settings.default_review_model;
    app.review_cache
        .insert(session_id.clone(), ReviewCacheEntry::Loading { diff_hash });
    let _ = app
        .services
        .db()
        .update_session_focused_review(session_id.as_str(), None, None)
        .await;
    app.start_review_assist(
        session_id.as_str(),
        &session_folder,
        diff_hash,
        &diff,
        session_summary.as_deref(),
    );

    let mut view_mode = restore_view.unwrap_or(ConfirmationViewMode {
        review_status_message: None,
        review_text: None,
        scroll_offset: None,
        session_id,
    });
    view_mode.review_status_message = Some(review_loading_message(review_model));
    view_mode.review_text = None;
    app.mode = view_mode.into_view_mode();

    Ok(EventResult::Continue)
}

#[cfg(test)]
mod tests {
    use std::path::Path;
    use std::process::Command;
    use std::sync::Arc;

    use crossterm::event::KeyModifiers;
    use mockall::predicate::eq;
    use tempfile::tempdir;

    use super::*;
    use crate::app::AppClients;
    use crate::db::Database;
    use crate::domain::agent::AgentModel;
    use crate::infra::app_server;
    use crate::infra::tmux::{MockTmuxClient, TmuxClient};
    use crate::ui::state::app_mode::ConfirmationViewMode;

    fn setup_test_git_repo(path: &Path) {
        Command::new("git")
            .args(["init"])
            .current_dir(path)
            .output()
            .expect("git init failed");
        Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(path)
            .output()
            .expect("git config failed");
        Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(path)
            .output()
            .expect("git config failed");
        std::fs::write(path.join("README.md"), "test").expect("write failed");
        Command::new("git")
            .args(["add", "."])
            .current_dir(path)
            .output()
            .expect("git add failed");
        Command::new("git")
            .args(["commit", "-m", "Initial commit"])
            .current_dir(path)
            .output()
            .expect("git commit failed");
        Command::new("git")
            .args(["branch", "-M", "main"])
            .current_dir(path)
            .output()
            .expect("git branch failed");
    }

    /// Returns a mock app-server client wrapped in `Arc` for test injection.
    fn mock_app_server() -> std::sync::Arc<dyn app_server::AppServerClient> {
        std::sync::Arc::new(app_server::MockAppServerClient::new())
    }

    /// Builds one client bundle with deterministic agent availability for
    /// test app startup.
    fn test_app_clients() -> AppClients {
        AppClients::new().with_agent_availability_probe(std::sync::Arc::new(
            crate::infra::agent::StaticAgentAvailabilityProbe {
                available_agent_kinds: crate::domain::agent::AgentKind::ALL.to_vec(),
            },
        ))
    }

    /// Builds one test app with an injected tmux boundary.
    async fn new_test_app_with_tmux_client(
        tmux_client: Arc<dyn TmuxClient>,
    ) -> (App, tempfile::TempDir) {
        let base_dir = tempdir().expect("failed to create temp dir");
        let base_path = base_dir.path().to_path_buf();
        let database = Database::open_in_memory()
            .await
            .expect("failed to open in-memory db");
        let clients = test_app_clients()
            .with_app_server_client_override(mock_app_server())
            .with_tmux_client(tmux_client);
        let app = App::new_with_clients(base_path.clone(), base_path, None, database, clients)
            .await
            .expect("failed to build app");

        (app, base_dir)
    }

    /// Builds one test app with a strict mocked tmux boundary.
    async fn new_test_app() -> (App, tempfile::TempDir) {
        new_test_app_with_tmux_client(Arc::new(MockTmuxClient::new())).await
    }

    /// Builds one git-backed test app with an injected tmux boundary.
    async fn new_test_app_with_git_and_tmux_client(
        tmux_client: Arc<dyn TmuxClient>,
    ) -> (App, tempfile::TempDir) {
        let base_dir = tempdir().expect("failed to create temp dir");
        let base_path = base_dir.path().to_path_buf();
        setup_test_git_repo(base_dir.path());
        let database = Database::open_in_memory()
            .await
            .expect("failed to open in-memory db");
        let clients = test_app_clients()
            .with_app_server_client_override(mock_app_server())
            .with_tmux_client(tmux_client);
        let app = App::new_with_clients(
            base_path.clone(),
            base_path,
            Some("main".to_string()),
            database,
            clients,
        )
        .await
        .expect("failed to build app");

        (app, base_dir)
    }

    /// Builds one git-backed test app with a strict mocked tmux boundary.
    async fn new_test_app_with_git() -> (App, tempfile::TempDir) {
        new_test_app_with_git_and_tmux_client(Arc::new(MockTmuxClient::new())).await
    }

    fn set_session_status_for_test(
        app: &mut App,
        session_id: &str,
        status: crate::domain::session::Status,
    ) {
        if let Some(session) = app
            .sessions
            .sessions
            .iter_mut()
            .find(|session| session.id == session_id)
        {
            session.status = status;
        }

        if let Some(handles) = app.sessions.handles.get(session_id)
            && let Ok(mut current_status) = handles.status.lock()
        {
            *current_status = status;
        }
    }

    #[test]
    fn test_content_area_for_terminal_excludes_global_bars() {
        // Arrange
        let terminal_rect = Rect::new(0, 0, 120, 30);

        // Act
        let content_area = content_area_for_terminal(terminal_rect);

        // Assert
        assert_eq!(content_area, Rect::new(0, 1, 120, 28));
    }

    #[tokio::test]
    async fn test_handle_session_creation_key_creates_regular_session() {
        // Arrange
        let (mut app, _base_dir) = new_test_app_with_git().await;
        app.mode = AppMode::SessionCreation {
            selected_option_index: 0,
        };

        // Act
        let result = handle_session_creation_key(
            &mut app,
            KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE),
        )
        .await;

        // Assert
        assert!(matches!(result, Ok(EventResult::Continue)));
        assert_eq!(app.sessions.sessions.len(), 1);
        assert!(!app.sessions.sessions[0].is_draft_session());
        assert!(matches!(
            app.mode,
            AppMode::Prompt {
                ref session_id,
                scroll_offset: None,
                ..
            } if !session_id.is_empty()
        ));
    }

    #[tokio::test]
    async fn test_handle_session_creation_key_creates_draft_session() {
        // Arrange
        let (mut app, _base_dir) = new_test_app_with_git().await;
        app.mode = AppMode::SessionCreation {
            selected_option_index: 0,
        };

        // Act
        handle_session_creation_key(&mut app, KeyEvent::new(KeyCode::Down, KeyModifiers::NONE))
            .await
            .expect("failed to move selection");
        let result = handle_session_creation_key(
            &mut app,
            KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE),
        )
        .await;

        // Assert
        assert!(matches!(result, Ok(EventResult::Continue)));
        assert_eq!(app.sessions.sessions.len(), 1);
        assert!(app.sessions.sessions[0].is_draft_session());
        assert!(matches!(
            app.mode,
            AppMode::Prompt {
                ref session_id,
                scroll_offset: None,
                ..
            } if !session_id.is_empty()
        ));
    }

    #[tokio::test]
    async fn test_handle_session_creation_key_escape_returns_to_list() {
        // Arrange
        let (mut app, _base_dir) = new_test_app_with_git().await;
        app.mode = AppMode::SessionCreation {
            selected_option_index: 0,
        };

        // Act
        let result =
            handle_session_creation_key(&mut app, KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE))
                .await;

        // Assert
        assert!(matches!(result, Ok(EventResult::Continue)));
        assert!(app.sessions.sessions.is_empty());
        assert!(matches!(app.mode, AppMode::List));
    }

    #[tokio::test]
    async fn test_handle_view_info_popup_key_restores_view_mode() {
        // Arrange
        let (mut app, _base_dir) = new_test_app().await;
        app.mode = AppMode::ViewInfoPopup {
            is_loading: false,
            loading_label: "Refreshing review request...".to_string(),
            message: "Review request refreshed.".to_string(),
            restore_view: ConfirmationViewMode {
                review_status_message: None,
                review_text: None,
                scroll_offset: Some(2),
                session_id: "session-id".into(),
            },
            title: "Review request refreshed".to_string(),
        };

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

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

    #[tokio::test]
    async fn test_handle_confirmation_decision_confirm_quits_when_no_session_context() {
        // Arrange
        let (mut app, _base_dir) = new_test_app().await;
        app.mode = AppMode::Confirmation {
            confirmation_intent: ConfirmationIntent::Quit,
            confirmation_message: "Quit agentty?".to_string(),
            confirmation_title: "Confirm Quit".to_string(),
            restore_view: None,
            session_id: None,
            selected_confirmation_index: 0,
        };

        // Act
        let event_result =
            handle_confirmation_decision(&mut app, ConfirmationDecision::Confirm).await;

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

    #[tokio::test]
    async fn test_handle_confirmation_decision_cancel_returns_to_list() {
        // Arrange
        let (mut app, _base_dir) = new_test_app().await;
        app.mode = AppMode::Confirmation {
            confirmation_intent: ConfirmationIntent::Quit,
            confirmation_message: "Quit agentty?".to_string(),
            confirmation_title: "Confirm Quit".to_string(),
            restore_view: None,
            session_id: None,
            selected_confirmation_index: 0,
        };

        // Act
        let event_result =
            handle_confirmation_decision(&mut app, ConfirmationDecision::Cancel).await;

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

    #[tokio::test]
    async fn test_handle_confirmation_decision_confirm_cancels_session_when_context_exists() {
        // Arrange
        let (mut app, _base_dir) = new_test_app_with_git().await;
        let session_id = app
            .create_session()
            .await
            .expect("failed to create session");
        set_session_status_for_test(
            &mut app,
            &session_id,
            crate::domain::session::Status::Review,
        );
        app.mode = AppMode::Confirmation {
            confirmation_intent: ConfirmationIntent::CancelSession,
            confirmation_message: "Cancel session \"test\"?".to_string(),
            confirmation_title: "Confirm Cancel".to_string(),
            restore_view: None,
            session_id: Some(session_id.clone().into()),
            selected_confirmation_index: 0,
        };

        // Act
        let event_result =
            handle_confirmation_decision(&mut app, ConfirmationDecision::Confirm).await;

        // Assert
        assert!(matches!(event_result, Ok(EventResult::Continue)));
        assert!(matches!(app.mode, AppMode::List));
        app.sessions.sync_from_handles();
        assert!(matches!(
            app.sessions.sessions.first(),
            Some(session) if session.id == session_id
                && session.status == crate::domain::session::Status::Canceled
        ));
    }

    #[tokio::test]
    async fn test_handle_key_event_routes_done_session_continue_shortcut() {
        // Arrange
        let (mut app, _base_dir) = new_test_app_with_git().await;
        let source_session_id = app
            .create_session()
            .await
            .expect("failed to create source session");
        app.services
            .db()
            .update_session_merged_commit_hash(&source_session_id, Some("abc1234"))
            .await
            .expect("failed to persist merged commit hash");
        let source_session = app
            .sessions
            .sessions
            .iter_mut()
            .find(|session| session.id == source_session_id)
            .expect("expected source session");
        source_session.status = crate::domain::session::Status::Done;
        source_session.title = Some("Done source".to_string());
        app.mode = AppMode::View {
            review_status_message: None,
            review_text: None,
            session_id: source_session_id.clone().into(),
            scroll_offset: Some(0),
        };
        let backend = ratatui::backend::TestBackend::new(120, 30);
        let mut terminal = ratatui::Terminal::new(backend).expect("failed to create terminal");

        // Act
        let event_result = handle_key_event(
            &mut app,
            &mut terminal,
            KeyEvent::new(KeyCode::Char('c'), KeyModifiers::NONE),
        )
        .await;

        // Assert
        assert!(matches!(event_result, Ok(EventResult::Continue)));
        assert!(matches!(
            app.mode,
            AppMode::Confirmation {
                confirmation_intent: ConfirmationIntent::ContinueSession,
                ref confirmation_title,
                ref restore_view,
                ref session_id,
                ..
            } if confirmation_title == "Confirm Continue"
                && matches!(restore_view, Some(restore_view) if restore_view.session_id == source_session_id)
                && matches!(session_id, Some(session_id) if session_id.as_str() == source_session_id)
        ));
    }

    #[tokio::test]
    async fn test_handle_confirmation_decision_cancel_restores_view_for_merge_confirmation() {
        // Arrange
        let (mut app, _base_dir) = new_test_app_with_git().await;
        let session_id = app
            .create_session()
            .await
            .expect("failed to create session");
        app.mode = AppMode::Confirmation {
            confirmation_intent: ConfirmationIntent::MergeSession,
            confirmation_message: "Add this session to merge queue?".to_string(),
            confirmation_title: "Confirm Merge".to_string(),
            restore_view: Some(ConfirmationViewMode {
                review_status_message: Some(review_loading_message(AgentModel::Gpt54)),
                review_text: Some("Review output".to_string()),
                scroll_offset: Some(6),
                session_id: session_id.clone().into(),
            }),
            session_id: Some(session_id.clone().into()),
            selected_confirmation_index: 0,
        };

        // Act
        let event_result =
            handle_confirmation_decision(&mut app, ConfirmationDecision::Cancel).await;

        // Assert
        assert!(matches!(event_result, Ok(EventResult::Continue)));
        assert!(matches!(
            app.mode,
            AppMode::View {
                review_status_message: Some(ref review_status_message),
                review_text: Some(ref review_text),
                session_id: ref session_id_in_mode,
                scroll_offset: Some(6),
            } if session_id_in_mode == &session_id
                && review_status_message == &review_loading_message(AgentModel::Gpt54)
                && review_text == "Review output"
        ));
    }

    #[tokio::test]
    async fn test_handle_confirmation_decision_cancel_restores_view_for_continue_confirmation() {
        // Arrange
        let (mut app, _base_dir) = new_test_app_with_git().await;
        let session_id = app
            .create_session()
            .await
            .expect("failed to create session");
        app.mode = AppMode::Confirmation {
            confirmation_intent: ConfirmationIntent::ContinueSession,
            confirmation_message: "Create a new draft session with initial context from this \
                                   session?"
                .to_string(),
            confirmation_title: "Confirm Continue".to_string(),
            restore_view: Some(ConfirmationViewMode {
                review_status_message: None,
                review_text: None,
                scroll_offset: Some(4),
                session_id: session_id.clone().into(),
            }),
            session_id: Some(session_id.clone().into()),
            selected_confirmation_index: 1,
        };

        // Act
        let event_result =
            handle_confirmation_decision(&mut app, ConfirmationDecision::Cancel).await;

        // Assert
        assert!(matches!(event_result, Ok(EventResult::Continue)));
        assert!(matches!(
            app.mode,
            AppMode::View {
                session_id: ref session_id_in_mode,
                scroll_offset: Some(4),
                ..
            } if session_id_in_mode == &session_id
        ));
    }

    #[tokio::test]
    async fn test_handle_confirmation_decision_confirm_opens_continuation_draft_prompt() {
        // Arrange
        let (mut app, _base_dir) = new_test_app_with_git().await;
        let merged_commit_hash = "704de31d0f4b5a1234567890abcdef1234567890";
        let source_session_id = app
            .create_session()
            .await
            .expect("failed to create session");
        app.services
            .db()
            .update_session_merged_commit_hash(&source_session_id, Some(merged_commit_hash))
            .await
            .expect("failed to persist merged commit hash");
        set_session_status_for_test(
            &mut app,
            &source_session_id,
            crate::domain::session::Status::Done,
        );
        app.mode = AppMode::Confirmation {
            confirmation_intent: ConfirmationIntent::ContinueSession,
            confirmation_message: "Create a new draft session with initial context from this \
                                   session?"
                .to_string(),
            confirmation_title: "Confirm Continue".to_string(),
            restore_view: Some(ConfirmationViewMode {
                review_status_message: None,
                review_text: None,
                scroll_offset: Some(4),
                session_id: source_session_id.clone().into(),
            }),
            session_id: Some(source_session_id.clone().into()),
            selected_confirmation_index: 0,
        };

        // Act
        let event_result =
            handle_confirmation_decision(&mut app, ConfirmationDecision::Confirm).await;

        // Assert
        assert!(matches!(event_result, Ok(EventResult::Continue)));
        assert!(matches!(
            app.mode,
            AppMode::Prompt {
                ref input,
                ref session_id,
                ..
            } if session_id.as_str() != source_session_id
                && input.text().is_empty()
        ));
        let continued_session_id = match &app.mode {
            AppMode::Prompt { session_id, .. } => session_id.as_str().to_string(),
            _ => unreachable!("expected prompt mode"),
        };
        let continued_session = app
            .sessions
            .sessions
            .iter()
            .find(|session| session.id == continued_session_id)
            .expect("expected created continuation draft");
        assert_eq!(
            continued_session.prompt,
            format!(
                "Summarize changes from {merged_commit_hash} to use it as an initial context for \
                 this session"
            )
        );
    }

    #[tokio::test]
    async fn test_handle_confirmation_decision_confirm_queues_merge_with_view_restore() {
        // Arrange
        let (mut app, _base_dir) = new_test_app_with_git().await;
        let session_id = app
            .create_session()
            .await
            .expect("failed to create session");
        app.mode = AppMode::Confirmation {
            confirmation_intent: ConfirmationIntent::MergeSession,
            confirmation_message: "Add this session to merge queue?".to_string(),
            confirmation_title: "Confirm Merge".to_string(),
            restore_view: Some(ConfirmationViewMode {
                review_status_message: None,
                review_text: None,
                scroll_offset: Some(2),
                session_id: session_id.clone().into(),
            }),
            session_id: Some(session_id.clone().into()),
            selected_confirmation_index: 0,
        };

        // Act
        let event_result =
            handle_confirmation_decision(&mut app, ConfirmationDecision::Confirm).await;

        // Assert
        assert!(matches!(event_result, Ok(EventResult::Continue)));
        assert!(matches!(
            app.mode,
            AppMode::View {
                review_status_message: None,
                review_text: None,
                session_id: ref session_id_in_mode,
                scroll_offset: Some(2),
            } if session_id_in_mode == &session_id
        ));
        app.sessions.sync_from_handles();
        let output = app.sessions.sessions[0].output.clone();
        assert!(output.contains("[Merge Error]"));
    }

    #[tokio::test]
    async fn test_handle_publish_branch_input_key_escape_restores_view_mode() {
        // Arrange
        let (mut app, _base_dir) = new_test_app().await;
        app.mode = AppMode::PublishBranchInput {
            default_branch_name: "wt/session".to_string(),
            input: crate::domain::input::InputState::with_text("review/custom".to_string()),
            locked_upstream_ref: None,
            publish_branch_action: crate::domain::session::PublishBranchAction::Push,
            restore_view: ConfirmationViewMode {
                review_status_message: Some(review_loading_message(AgentModel::Gpt54)),
                review_text: Some("Critical finding".to_string()),
                scroll_offset: Some(7),
                session_id: "session-id".into(),
            },
        };

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

        // Assert
        assert!(matches!(event_result, EventResult::Continue));
        assert!(matches!(
            app.mode,
            AppMode::View {
                review_status_message: Some(ref status_message),
                review_text: Some(ref review_text),
                ref session_id,
                scroll_offset: Some(7),
            } if session_id == "session-id"
                && status_message == &review_loading_message(AgentModel::Gpt54)
                && review_text == "Critical finding"
        ));
    }

    #[tokio::test]
    async fn test_handle_publish_branch_input_key_enter_starts_pull_request_publish() {
        // Arrange
        let (mut app, _base_dir) = new_test_app_with_git().await;
        let session_id = app
            .create_session()
            .await
            .expect("failed to create session");
        set_session_status_for_test(
            &mut app,
            &session_id,
            crate::domain::session::Status::Review,
        );
        app.mode = AppMode::PublishBranchInput {
            default_branch_name: "wt/session".to_string(),
            input: crate::domain::input::InputState::with_text("review/custom".to_string()),
            locked_upstream_ref: None,
            publish_branch_action: crate::domain::session::PublishBranchAction::PublishPullRequest,
            restore_view: ConfirmationViewMode {
                review_status_message: None,
                review_text: None,
                scroll_offset: Some(4),
                session_id: session_id.into(),
            },
        };

        // Act
        let event_result = handle_publish_branch_input_key(
            &mut app,
            KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE),
        );

        // Assert
        assert!(matches!(event_result, EventResult::Continue));
        assert!(matches!(
            app.mode,
            AppMode::ViewInfoPopup {
                is_loading: true,
                ref message,
                ref title,
                ..
            } if title == "Publishing review request"
                && message.contains("`review/custom`")
        ));
    }

    #[tokio::test]
    async fn test_handle_publish_branch_input_key_char_updates_input_state() {
        // Arrange
        let (mut app, _base_dir) = new_test_app().await;
        app.mode = AppMode::PublishBranchInput {
            default_branch_name: "wt/session".to_string(),
            input: crate::domain::input::InputState::default(),
            locked_upstream_ref: None,
            publish_branch_action: crate::domain::session::PublishBranchAction::Push,
            restore_view: ConfirmationViewMode {
                review_status_message: None,
                review_text: None,
                scroll_offset: None,
                session_id: "session-id".into(),
            },
        };

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

        // Assert
        assert!(matches!(event_result, EventResult::Continue));
        assert!(matches!(
            app.mode,
            AppMode::PublishBranchInput {
                input: ref input_state,
                ..
            } if input_state.cursor == 1 && input_state.text() == "r"
        ));
        let AppMode::PublishBranchInput { input, .. } = &app.mode else {
            unreachable!("mode should remain publish-branch input");
        };
        assert_eq!(input.text(), "r");
    }

    #[tokio::test]
    async fn test_handle_publish_branch_input_key_shortcut_chars_are_inserted() {
        // Arrange
        let typed_shortcut_characters = ['q', 'p', 'd', 'f', 'm', 'r', 'j', 'k', 'g', 'G', '?'];

        for character in typed_shortcut_characters {
            let (mut app, _base_dir) = new_test_app().await;
            app.mode = AppMode::PublishBranchInput {
                default_branch_name: "wt/session".to_string(),
                input: crate::domain::input::InputState::default(),
                locked_upstream_ref: None,
                publish_branch_action: crate::domain::session::PublishBranchAction::Push,
                restore_view: ConfirmationViewMode {
                    review_status_message: None,
                    review_text: None,
                    scroll_offset: None,
                    session_id: "session-id".into(),
                },
            };
            let modifiers = if character.is_ascii_uppercase() || character == '?' {
                KeyModifiers::SHIFT
            } else {
                KeyModifiers::NONE
            };

            // Act
            let event_result = handle_publish_branch_input_key(
                &mut app,
                KeyEvent::new(KeyCode::Char(character), modifiers),
            );

            // Assert
            assert!(matches!(event_result, EventResult::Continue));
            assert!(matches!(
                app.mode,
                AppMode::PublishBranchInput {
                    input: ref input_state,
                    ..
                } if input_state.cursor == 1 && input_state.text() == character.to_string()
            ));
        }
    }

    #[tokio::test]
    async fn test_handle_publish_branch_input_key_left_moves_cursor() {
        // Arrange
        let (mut app, _base_dir) = new_test_app().await;
        app.mode = AppMode::PublishBranchInput {
            default_branch_name: "wt/session".to_string(),
            input: crate::domain::input::InputState::with_text("review/custom".to_string()),
            locked_upstream_ref: None,
            publish_branch_action: crate::domain::session::PublishBranchAction::Push,
            restore_view: ConfirmationViewMode {
                review_status_message: None,
                review_text: None,
                scroll_offset: None,
                session_id: "session-id".into(),
            },
        };

        // Act
        let event_result = handle_publish_branch_input_key(
            &mut app,
            KeyEvent::new(KeyCode::Left, KeyModifiers::NONE),
        );

        // Assert
        assert!(matches!(event_result, EventResult::Continue));
        let AppMode::PublishBranchInput { input, .. } = &app.mode else {
            unreachable!("mode should remain publish-branch input");
        };
        assert_eq!(input.text(), "review/custom");
        assert_eq!(input.cursor, "review/custom".chars().count() - 1);
    }

    #[tokio::test]
    async fn test_handle_publish_branch_input_key_char_keeps_locked_branch_name() {
        // Arrange
        let (mut app, _base_dir) = new_test_app().await;
        app.mode = AppMode::PublishBranchInput {
            default_branch_name: "wt/session".to_string(),
            input: crate::domain::input::InputState::with_text("review/custom".to_string()),
            locked_upstream_ref: Some("origin/review/custom".to_string()),
            publish_branch_action: crate::domain::session::PublishBranchAction::Push,
            restore_view: ConfirmationViewMode {
                review_status_message: None,
                review_text: None,
                scroll_offset: None,
                session_id: "session-id".into(),
            },
        };

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

        // Assert
        assert!(matches!(event_result, EventResult::Continue));
        let AppMode::PublishBranchInput {
            input,
            locked_upstream_ref,
            ..
        } = &app.mode
        else {
            unreachable!("mode should remain publish-branch input");
        };
        assert_eq!(locked_upstream_ref.as_deref(), Some("origin/review/custom"));
        assert_eq!(input.text(), "review/custom");
    }

    #[test]
    fn test_next_open_command_index_wraps_to_start() {
        // Arrange
        let commands = vec!["cargo test".to_string(), "npm run dev".to_string()];

        // Act
        let index = next_open_command_index(1, &commands);

        // Assert
        assert_eq!(index, 0);
    }

    #[test]
    fn test_previous_open_command_index_wraps_to_end() {
        // Arrange
        let commands = vec!["cargo test".to_string(), "npm run dev".to_string()];

        // Act
        let index = previous_open_command_index(0, &commands);

        // Assert
        assert_eq!(index, 1);
    }

    #[tokio::test]
    async fn test_handle_open_command_selector_key_escape_restores_view_mode() {
        // Arrange
        let (mut app, _base_dir) = new_test_app().await;
        app.mode = AppMode::OpenCommandSelector {
            commands: vec!["cargo test".to_string(), "npm run dev".to_string()],
            restore_view: ConfirmationViewMode {
                review_status_message: Some(review_loading_message(AgentModel::Gpt54)),
                review_text: Some("Critical finding".to_string()),
                scroll_offset: Some(3),
                session_id: "session-id".into(),
            },
            selected_command_index: 1,
        };

        // Act
        let event_result = handle_open_command_selector_key(
            &mut app,
            KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE),
        )
        .await;

        // Assert
        assert!(matches!(event_result, Ok(EventResult::Continue)));
        assert!(matches!(
            app.mode,
            AppMode::View {
                review_status_message: Some(ref status_message),
                review_text: Some(ref review_text),
                ref session_id,
                scroll_offset: Some(3),
            } if session_id == "session-id"
                && status_message == &review_loading_message(AgentModel::Gpt54)
                && review_text == "Critical finding"
        ));
    }

    #[tokio::test]
    async fn test_handle_open_command_selector_key_j_updates_selected_index() {
        // Arrange
        let (mut app, _base_dir) = new_test_app().await;
        app.mode = AppMode::OpenCommandSelector {
            commands: vec!["cargo test".to_string(), "npm run dev".to_string()],
            restore_view: ConfirmationViewMode {
                review_status_message: None,
                review_text: None,
                scroll_offset: None,
                session_id: "session-id".into(),
            },
            selected_command_index: 0,
        };

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

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

    #[tokio::test]
    async fn test_handle_open_command_selector_key_with_empty_commands_keeps_index_zero() {
        // Arrange
        let (mut app, _base_dir) = new_test_app().await;
        app.mode = AppMode::OpenCommandSelector {
            commands: Vec::new(),
            restore_view: ConfirmationViewMode {
                review_status_message: None,
                review_text: None,
                scroll_offset: None,
                session_id: "session-id".into(),
            },
            selected_command_index: 0,
        };

        // Act
        let event_result = handle_open_command_selector_key(
            &mut app,
            KeyEvent::new(KeyCode::Down, KeyModifiers::NONE),
        )
        .await;

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

    #[tokio::test]
    async fn test_handle_open_command_selector_key_enter_restores_view_without_session() {
        // Arrange
        let (mut app, _base_dir) = new_test_app().await;
        app.mode = AppMode::OpenCommandSelector {
            commands: vec!["cargo test".to_string()],
            restore_view: ConfirmationViewMode {
                review_status_message: None,
                review_text: None,
                scroll_offset: Some(4),
                session_id: "session-id".into(),
            },
            selected_command_index: 0,
        };

        // Act
        let event_result = handle_open_command_selector_key(
            &mut app,
            KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE),
        )
        .await;

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

    #[tokio::test]
    async fn test_handle_open_command_selector_key_enter_runs_selected_command_in_tmux() {
        // Arrange
        let mut mock_tmux_client = MockTmuxClient::new();
        mock_tmux_client
            .expect_open_window_for_folder()
            .times(1)
            .returning(|_| Box::pin(async { Some("@24".to_string()) }));
        mock_tmux_client
            .expect_run_command_in_window()
            .with(eq("@24".to_string()), eq("npm run dev".to_string()))
            .times(1)
            .returning(|_, _| Box::pin(async {}));
        let (mut app, _base_dir) =
            new_test_app_with_git_and_tmux_client(Arc::new(mock_tmux_client)).await;
        let expected_session_id = app
            .create_session()
            .await
            .expect("failed to create session");
        app.mode = AppMode::OpenCommandSelector {
            commands: vec!["cargo test".to_string(), "npm run dev".to_string()],
            restore_view: ConfirmationViewMode {
                review_status_message: None,
                review_text: None,
                scroll_offset: Some(2),
                session_id: expected_session_id.clone().into(),
            },
            selected_command_index: 1,
        };

        // Act
        let event_result = handle_open_command_selector_key(
            &mut app,
            KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE),
        )
        .await;

        // Assert
        assert!(matches!(event_result, Ok(EventResult::Continue)));
        assert!(matches!(
            app.mode,
            AppMode::View {
                review_status_message: None,
                review_text: None,
                ref session_id,
                scroll_offset: Some(2),
            } if session_id == &expected_session_id
        ));
    }

    #[tokio::test]
    async fn test_handle_open_command_selector_key_unknown_key_preserves_state() {
        // Arrange
        let (mut app, _base_dir) = new_test_app().await;
        app.mode = AppMode::OpenCommandSelector {
            commands: vec!["cargo test".to_string(), "npm run dev".to_string()],
            restore_view: ConfirmationViewMode {
                review_status_message: Some(review_loading_message(AgentModel::Gpt54)),
                review_text: Some("Critical finding".to_string()),
                scroll_offset: Some(1),
                session_id: "session-id".into(),
            },
            selected_command_index: 1,
        };

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

        // Assert
        assert!(matches!(event_result, Ok(EventResult::Continue)));
        assert!(matches!(
            app.mode,
            AppMode::OpenCommandSelector {
                selected_command_index: 1,
                ref commands,
                restore_view:
                    ConfirmationViewMode {
                        review_status_message: Some(ref status_message),
                        review_text: Some(ref review_text),
                        scroll_offset: Some(1),
                        ref session_id,
                    },
            } if commands == &vec!["cargo test".to_string(), "npm run dev".to_string()]
                && session_id == "session-id"
                && status_message == &review_loading_message(AgentModel::Gpt54)
                && review_text == "Critical finding"
        ));
    }

    #[tokio::test]
    async fn test_handle_confirmation_decision_cancel_restores_view_for_regenerate_confirmation() {
        // Arrange
        let (mut app, _base_dir) = new_test_app_with_git().await;
        let session_id = app
            .create_session()
            .await
            .expect("failed to create session");
        app.mode = AppMode::Confirmation {
            confirmation_intent: ConfirmationIntent::RegenerateReview,
            confirmation_message: "Regenerate focused review?".to_string(),
            confirmation_title: "Confirm Regenerate".to_string(),
            restore_view: Some(ConfirmationViewMode {
                review_status_message: None,
                review_text: Some("Previous review".to_string()),
                scroll_offset: Some(4),
                session_id: session_id.clone().into(),
            }),
            session_id: Some(session_id.clone().into()),
            selected_confirmation_index: 1,
        };

        // Act
        let event_result =
            handle_confirmation_decision(&mut app, ConfirmationDecision::Cancel).await;

        // Assert
        assert!(matches!(event_result, Ok(EventResult::Continue)));
        assert!(matches!(
            app.mode,
            AppMode::View {
                review_text: Some(ref review_text),
                scroll_offset: Some(4),
                ..
            } if review_text == "Previous review"
        ));
    }

    #[tokio::test]
    async fn test_handle_confirmation_decision_confirm_regenerates_review() {
        // Arrange
        let (mut app, _base_dir) = new_test_app_with_git().await;
        let session_id = app
            .create_session()
            .await
            .expect("failed to create session");
        let session_folder = app.sessions.sessions[0].folder.clone();
        std::fs::write(session_folder.join("README.md"), "regenerate test\n")
            .expect("failed to write");
        app.review_cache.insert(
            session_id.clone().into(),
            ReviewCacheEntry::Ready {
                text: "Old review".to_string(),
                diff_hash: 99,
            },
        );
        app.mode = AppMode::Confirmation {
            confirmation_intent: ConfirmationIntent::RegenerateReview,
            confirmation_message: "Regenerate focused review?".to_string(),
            confirmation_title: "Confirm Regenerate".to_string(),
            restore_view: Some(ConfirmationViewMode {
                review_status_message: None,
                review_text: Some("Old review".to_string()),
                scroll_offset: None,
                session_id: session_id.clone().into(),
            }),
            session_id: Some(session_id.clone().into()),
            selected_confirmation_index: 0,
        };

        // Act
        let event_result =
            handle_confirmation_decision(&mut app, ConfirmationDecision::Confirm).await;

        // Assert — view is restored with loading state, cache shows new Loading entry
        assert!(matches!(event_result, Ok(EventResult::Continue)));
        assert!(matches!(
            app.mode,
            AppMode::View {
                review_status_message: Some(_),
                review_text: None,
                ..
            }
        ));
        assert!(matches!(
            app.review_cache.get(session_id.as_str()),
            Some(ReviewCacheEntry::Loading { .. })
        ));
    }
}