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
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
use std::io;

use crossterm::event::{self, KeyCode, KeyEvent};
use ratatui::Terminal;
use ratatui::backend::Backend;
use tracing::warn;

use crate::app::{App, ReviewCacheEntry, SessionStatsUsage, diff_content_hash};
use crate::domain::agent::{AgentKind, AgentModel, ReasoningLevel};
use crate::domain::input::InputState;
use crate::domain::review;
use crate::domain::session::SessionId;
use crate::domain::transcript_notice::TranscriptNotice;
use crate::infra::channel::{TurnPrompt, TurnPromptAttachment, TurnPromptTextSource};
use crate::runtime::mode::{at_mention, input_key};
use crate::runtime::{EventResult, clipboard_image};
use crate::ui::state::app_mode::AppMode;
use crate::ui::state::prompt::{
    PromptAtMentionState, PromptSlashStage, PromptSuggestionSelection,
    apply_prompt_delete_range as apply_prompt_delete_range_components,
    current_line_delete_range as prompt_current_line_delete_range, drain_prompt_submission,
    insert_prompt_character, insert_prompt_local_image, insert_prompt_text,
    prompt_slash_option_count, resolve_prompt_slash_selection,
};
use crate::ui::util::{format_token_count, move_input_cursor_down, move_input_cursor_up};

/// Captures prompt-mode routing flags derived from the current session.
///
/// Draft sessions only stage prompts while they remain in `Status::Draft`.
/// After the first turn starts, follow-up submissions must route through the
/// normal reply path even though the session still records draft origin.
struct PromptContext {
    input_mode: PromptInputMode,
    scroll_offset: Option<u16>,
    session_id: SessionId,
    session_index: usize,
    session_mode: PromptSessionMode,
}

impl PromptContext {
    /// Returns whether `Esc` should delete the blank session backing this
    /// prompt instead of restoring session view.
    fn can_delete_on_cancel(&self) -> bool {
        self.session_mode == PromptSessionMode::NewDeletable
    }

    /// Returns whether the prompt is currently editing an active `@` mention.
    fn is_at_mention(&self) -> bool {
        self.input_mode == PromptInputMode::AtMention
    }

    /// Returns whether the prompt belongs to a draft session that only stages
    /// messages while still in `Status::Draft`.
    fn is_draft_session(&self) -> bool {
        self.session_mode == PromptSessionMode::NewDraft
    }

    /// Returns whether the prompt belongs to a session that has not started
    /// its first turn.
    fn is_new_session(&self) -> bool {
        self.session_mode != PromptSessionMode::Existing
    }

    /// Returns whether the prompt is currently editing a slash command.
    fn is_slash_command(&self) -> bool {
        self.input_mode == PromptInputMode::SlashCommand
    }
}

/// Active prompt input sub-mode used for specialized key routing.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum PromptInputMode {
    /// Prompt text is editing an active file `@` mention.
    AtMention,
    /// Prompt text starts with a slash-command prefix.
    SlashCommand,
    /// Prompt text is normal user input.
    Text,
}

/// Session lifecycle shape that determines prompt submission and cancellation
/// behavior.
#[derive(Clone, Copy, Eq, PartialEq)]
enum PromptSessionMode {
    /// Existing session receiving a follow-up reply.
    Existing,
    /// New non-draft session that can be deleted when prompt composition is
    /// canceled.
    NewDeletable,
    /// Draft-mode session that stages prompt text instead of starting a turn.
    NewDraft,
    /// New non-draft session that should be preserved on cancel because it has
    /// staged drafts.
    NewRegular,
}

/// Handles key input while the app is in `AppMode::Prompt`.
pub(crate) async fn handle<B: Backend>(
    app: &mut App,
    terminal: &mut Terminal<B>,
    key: KeyEvent,
) -> io::Result<EventResult>
where
    B::Error: std::error::Error + Send + Sync + 'static,
{
    let Some(prompt_context) = prompt_context(app) else {
        return Ok(EventResult::Continue);
    };

    if !prompt_context.is_slash_command() {
        reset_prompt_slash_state(app);
    }

    if prompt_context.is_at_mention() && handle_at_mention_key(app, key) {
        return Ok(EventResult::Continue);
    }

    handle_editing_key(app, terminal, key, &prompt_context).await?;

    Ok(EventResult::Continue)
}

/// Handles keys when the at-mention dropdown is active.
///
/// Returns `true` if the key was consumed by at-mention logic.
fn handle_at_mention_key(app: &mut App, key: KeyEvent) -> bool {
    match key.code {
        KeyCode::Esc => dismiss_at_mention(app),
        KeyCode::Enter if !input_key::should_insert_newline(key) => handle_at_mention_select(app),
        KeyCode::Tab => handle_at_mention_select(app),
        KeyCode::Up => handle_at_mention_up(app),
        KeyCode::Down => handle_at_mention_down(app),
        _ => return false,
    }

    true
}

/// Handles all editing, navigation, and submission keys in prompt mode.
async fn handle_editing_key<B: Backend>(
    app: &mut App,
    terminal: &mut Terminal<B>,
    key: KeyEvent,
    prompt_context: &PromptContext,
) -> io::Result<()>
where
    B::Error: std::error::Error + Send + Sync + 'static,
{
    match key.code {
        KeyCode::Enter | KeyCode::Char('\r' | '\n') if input_key::should_insert_newline(key) => {
            reset_prompt_history_navigation(app);
            if let AppMode::Prompt { input, .. } = &mut app.mode {
                input.insert_newline();
            }
        }
        KeyCode::Enter => handle_prompt_submit_key(app, prompt_context).await,
        KeyCode::Esc | KeyCode::Char('c') if is_prompt_cancel_key(key) => {
            handle_prompt_cancel_key(app, prompt_context).await;
        }
        KeyCode::Left => handle_prompt_left(app, key),
        KeyCode::Right => handle_prompt_right(app, key),
        KeyCode::Up => handle_prompt_up_key(app, terminal, prompt_context)?,
        KeyCode::Down => handle_prompt_down_key(app, terminal, prompt_context)?,
        KeyCode::Char('k') if prompt_context.is_slash_command() && is_plain_char_key(key, 'k') => {
            handle_prompt_up_key(app, terminal, prompt_context)?;
        }
        KeyCode::Char('j') if prompt_context.is_slash_command() && is_plain_char_key(key, 'j') => {
            handle_prompt_down_key(app, terminal, prompt_context)?;
        }
        KeyCode::Home => handle_prompt_input(app, InputState::move_home),
        KeyCode::End => handle_prompt_input(app, InputState::move_end),
        KeyCode::Backspace => handle_prompt_backspace(app, key),
        KeyCode::Delete => handle_prompt_delete(app),
        KeyCode::Char(character) if input_key::is_control_newline_key(key, character) => {
            reset_prompt_history_navigation(app);
            if let AppMode::Prompt { input, .. } = &mut app.mode {
                input.insert_newline();
            }
        }
        KeyCode::Char('u') if input_key::is_control_key(key) => handle_prompt_line_delete(app),
        KeyCode::Char('v') if is_prompt_image_paste_key(key) => {
            handle_prompt_image_paste(app, prompt_context).await;
        }
        KeyCode::Char('a') if input_key::is_control_key(key) => {
            handle_prompt_input(app, InputState::move_line_start);
        }
        KeyCode::Char('e') if input_key::is_control_key(key) => {
            handle_prompt_input(app, InputState::move_line_end);
        }
        KeyCode::Char('f') if input_key::is_control_key(key) => {
            handle_prompt_input(app, InputState::move_right);
        }
        KeyCode::Char('b') if input_key::is_control_key(key) => {
            handle_prompt_input(app, InputState::move_left);
        }
        KeyCode::Char('p') if input_key::is_control_key(key) => {
            handle_prompt_up_key(app, terminal, prompt_context)?;
        }
        KeyCode::Char('n') if input_key::is_control_key(key) => {
            handle_prompt_down_key(app, terminal, prompt_context)?;
        }
        KeyCode::Char('d') if input_key::is_control_key(key) => handle_prompt_delete(app),
        KeyCode::Char('k') if input_key::is_control_key(key) => handle_prompt_kill_to_line_end(app),
        KeyCode::Char('w') if input_key::is_control_key(key) => handle_prompt_word_delete(app),
        KeyCode::Char('b') if input_key::is_alt_key(key) => {
            if let AppMode::Prompt { input, .. } = &mut app.mode {
                input_key::move_cursor_word_left(input);
            }

            sync_prompt_at_mention_state(app);
        }
        KeyCode::Char('f') if input_key::is_alt_key(key) => {
            if let AppMode::Prompt { input, .. } = &mut app.mode {
                input_key::move_cursor_word_right(input);
            }

            sync_prompt_at_mention_state(app);
        }
        KeyCode::Char(character) => handle_prompt_char(app, character),
        _ => {}
    }

    Ok(())
}

/// Applies one `InputState` method to the prompt input and keeps `@` mention
/// state aligned with the updated cursor location.
fn handle_prompt_input(app: &mut App, action: fn(&mut InputState)) {
    if let AppMode::Prompt { input, .. } = &mut app.mode {
        action(input);
    }

    sync_prompt_at_mention_state(app);
}

/// Inserts pasted content into the prompt input while normalizing mixed
/// line-endings to `\n`.
pub(crate) fn handle_paste(app: &mut App, pasted_text: &str) {
    let normalized_text = input_key::normalize_pasted_text(pasted_text);
    if normalized_text.is_empty() {
        return;
    }

    if let AppMode::Prompt {
        history_state,
        input,
        slash_state,
        ..
    } = &mut app.mode
    {
        insert_prompt_text(input, history_state, slash_state, &normalized_text);
    }

    sync_prompt_at_mention_state(app);
}

/// Returns the active prompt context for the currently edited session.
fn prompt_context(app: &mut App) -> Option<PromptContext> {
    let (is_at_mention, is_slash_command, scroll_offset, session_id) = match &app.mode {
        AppMode::Prompt {
            at_mention_state,
            input,
            scroll_offset,
            session_id,
            ..
        } => (
            is_active_at_mention(at_mention_state.as_ref(), input),
            input.text().starts_with('/'),
            *scroll_offset,
            session_id.clone(),
        ),
        _ => return None,
    };

    let Some(session_index) = app.session_index_for_id(&session_id) else {
        app.mode = AppMode::List;

        return None;
    };

    let session = app.sessions.sessions.get(session_index);
    let session_mode = session.map_or(PromptSessionMode::Existing, |session| {
        let is_new_session = session.status == crate::domain::session::Status::Draft;

        match (
            is_new_session,
            session.is_draft_session(),
            session.has_staged_drafts(),
        ) {
            (true, true, _) => PromptSessionMode::NewDraft,
            (true, false, false) => PromptSessionMode::NewDeletable,
            (true, false, true) => PromptSessionMode::NewRegular,
            (false, _, _) => PromptSessionMode::Existing,
        }
    });
    // While the session is `InProgress` the composer queues the next chat
    // message instead of dispatching it. Demote a leading `/` to plain text
    // so slash commands cannot run while the active turn is still in flight
    // and so arrow-key navigation behaves as text editing rather than slash
    // menu selection.
    let session_is_in_progress =
        session.is_some_and(|session| session.status == crate::domain::session::Status::InProgress);
    let input_mode = match (is_at_mention, is_slash_command, session_is_in_progress) {
        (true, _, _) => PromptInputMode::AtMention,
        (false, true, false) => PromptInputMode::SlashCommand,
        (false, _, _) => PromptInputMode::Text,
    };

    Some(PromptContext {
        input_mode,
        scroll_offset,
        session_id,
        session_index,
        session_mode,
    })
}

fn is_active_at_mention(
    at_mention_state: Option<&PromptAtMentionState>,
    input: &InputState,
) -> bool {
    at_mention_state.is_some() && input.at_mention_query().is_some()
}

/// Reopens or dismisses the `@` mention dropdown to match the current prompt
/// cursor position.
///
/// This keeps previously inserted `@path` tokens editable after the user types
/// more text elsewhere and later moves the cursor back into the mention.
fn sync_prompt_at_mention_state(app: &mut App) {
    let Some(prompt_context) = prompt_context(app) else {
        return;
    };

    let sync_action = match &app.mode {
        AppMode::Prompt {
            at_mention_state,
            input,
            ..
        } => at_mention::sync_action(input, at_mention_state.as_ref()),
        _ => return,
    };

    match sync_action {
        at_mention::AtMentionSyncAction::Activate if !prompt_context.is_slash_command() => {
            activate_at_mention(app, &prompt_context);
        }
        at_mention::AtMentionSyncAction::Dismiss => dismiss_at_mention(app),
        at_mention::AtMentionSyncAction::KeepOpen => {
            if let AppMode::Prompt {
                at_mention_state: Some(state),
                ..
            } = &mut app.mode
            {
                at_mention::reset_selection(state);
            }
        }
        at_mention::AtMentionSyncAction::Activate => {}
    }
}

fn reset_prompt_slash_state(app: &mut App) {
    if let AppMode::Prompt { slash_state, .. } = &mut app.mode {
        slash_state.reset();
    }
}

fn reset_prompt_history_navigation(app: &mut App) {
    if let AppMode::Prompt { history_state, .. } = &mut app.mode {
        history_state.reset_navigation();
    }
}

fn is_prompt_cancel_key(key: KeyEvent) -> bool {
    key.code == KeyCode::Esc || key.modifiers.contains(event::KeyModifiers::CONTROL)
}

fn is_plain_char_key(key: KeyEvent, character: char) -> bool {
    key.code == KeyCode::Char(character) && key.modifiers == event::KeyModifiers::NONE
}

/// Returns true when the key event should paste one clipboard image into the
/// prompt composer.
fn is_prompt_image_paste_key(key: KeyEvent) -> bool {
    key.code == KeyCode::Char('v')
        && key
            .modifiers
            .intersects(event::KeyModifiers::ALT | event::KeyModifiers::CONTROL)
}

fn handle_prompt_up_key<B: Backend>(
    app: &mut App,
    terminal: &Terminal<B>,
    prompt_context: &PromptContext,
) -> io::Result<()>
where
    B::Error: std::error::Error + Send + Sync + 'static,
{
    if prompt_context.is_slash_command() {
        if let AppMode::Prompt { slash_state, .. } = &mut app.mode {
            slash_state.selected_index = slash_state.selected_index.saturating_sub(1);
        }

        return Ok(());
    }

    let input_width = prompt_input_width(terminal)?;
    if let AppMode::Prompt { input, .. } = &mut app.mode {
        let next_cursor = move_input_cursor_up(input.text(), input_width, input.cursor);
        if next_cursor != input.cursor {
            input.cursor = next_cursor;
            sync_prompt_at_mention_state(app);

            return Ok(());
        }
    }

    navigate_prompt_history_up(app);
    sync_prompt_at_mention_state(app);

    Ok(())
}

fn handle_prompt_down_key<B: Backend>(
    app: &mut App,
    terminal: &Terminal<B>,
    prompt_context: &PromptContext,
) -> io::Result<()>
where
    B::Error: std::error::Error + Send + Sync + 'static,
{
    if prompt_context.is_slash_command() {
        advance_prompt_slash_selection(app);

        return Ok(());
    }

    let input_width = prompt_input_width(terminal)?;
    if let AppMode::Prompt { input, .. } = &mut app.mode {
        let next_cursor = move_input_cursor_down(input.text(), input_width, input.cursor);
        if next_cursor != input.cursor {
            input.cursor = next_cursor;
            sync_prompt_at_mention_state(app);

            return Ok(());
        }
    }

    navigate_prompt_history_down(app);
    sync_prompt_at_mention_state(app);

    Ok(())
}

fn navigate_prompt_history_up(app: &mut App) {
    if let AppMode::Prompt {
        history_state,
        input,
        ..
    } = &mut app.mode
    {
        if history_state.entries.is_empty() {
            return;
        }

        let next_index = if let Some(selected_index) = history_state.selected_index {
            selected_index.saturating_sub(1)
        } else {
            history_state.draft_text = Some(input.text().to_string());

            history_state.entries.len().saturating_sub(1)
        };

        history_state.selected_index = Some(next_index);
        *input = InputState::with_text(history_state.entries[next_index].clone());
    }
}

fn navigate_prompt_history_down(app: &mut App) {
    if let AppMode::Prompt {
        history_state,
        input,
        ..
    } = &mut app.mode
    {
        let Some(selected_index) = history_state.selected_index else {
            return;
        };

        if selected_index + 1 < history_state.entries.len() {
            let next_index = selected_index + 1;

            history_state.selected_index = Some(next_index);
            *input = InputState::with_text(history_state.entries[next_index].clone());

            return;
        }

        history_state.selected_index = None;
        *input = InputState::with_text(history_state.draft_text.take().unwrap_or_default());
    }
}

fn advance_prompt_slash_selection(app: &mut App) {
    let allow_apply_command = prompt_apply_command_is_available(app);
    let (
        available_agent_kinds,
        input_text,
        selected_agent,
        selected_index,
        session_agent_kind,
        stage,
    ) = match &app.mode {
        AppMode::Prompt {
            input, slash_state, ..
        } => (
            slash_state.available_agent_kinds.clone(),
            input.text().to_string(),
            slash_state.selected_agent,
            slash_state.selected_index,
            app.selected_session()
                .map_or(AgentKind::Codex, |session| session.model.kind()),
            slash_state.stage,
        ),
        _ => return,
    };

    let option_count = prompt_slash_option_count(
        &input_text,
        stage,
        selected_agent,
        &available_agent_kinds,
        session_agent_kind,
        allow_apply_command,
    );
    if option_count == 0 {
        return;
    }

    if let AppMode::Prompt { slash_state, .. } = &mut app.mode {
        let max_index = option_count.saturating_sub(1);
        slash_state.selected_index = (selected_index + 1).min(max_index);
    }
}

/// Returns whether the targeted session is currently `InProgress`, used to
/// route non-slash submissions into the in-memory message queue instead of
/// the live reply path.
fn session_is_in_progress(app: &App, session_id: &str) -> bool {
    app.sessions
        .sessions
        .iter()
        .find(|session| session.id == session_id)
        .is_some_and(|session| session.status == crate::domain::session::Status::InProgress)
}

/// Submits the active prompt when it passes prompt-mode validation.
///
/// A submitted prompt clears any cached focused-review output for the session
/// so the next turn starts from the raw transcript again. While the session
/// is `InProgress`, slash command mode is already demoted to text in
/// [`prompt_context`], so any leading `/` falls through to the queue path
/// instead of executing a slash command against the running turn.
async fn handle_prompt_submit_key(app: &mut App, prompt_context: &PromptContext) {
    if prompt_context.is_slash_command() {
        handle_prompt_slash_submit(app, prompt_context).await;

        return;
    }

    let prompt = take_submitted_turn_prompt(app);
    if prompt.is_empty() {
        return;
    }

    if prompt_context.is_draft_session() {
        if let Err(error) = app
            .stage_draft_message(&prompt_context.session_id, prompt)
            .await
        {
            append_output_for_session(
                app,
                &prompt_context.session_id,
                &TranscriptNotice::Error.format(error),
            )
            .await;
        }
    } else if prompt_context.is_new_session() {
        if let Err(error) = app.start_session(&prompt_context.session_id, prompt).await {
            append_output_for_session(
                app,
                &prompt_context.session_id,
                &TranscriptNotice::Error.format(error),
            )
            .await;
        }
    } else if session_is_in_progress(app, &prompt_context.session_id) {
        if let Err(error) = app.enqueue_message(&prompt_context.session_id, prompt) {
            append_output_for_session(
                app,
                &prompt_context.session_id,
                &TranscriptNotice::QueueError.format(error),
            )
            .await;
        }
    } else {
        app.reply(&prompt_context.session_id, prompt).await;
    }

    app.mode = AppMode::View {
        review_status_message: None,
        review_text: None,
        session_id: prompt_context.session_id.clone(),
        scroll_offset: None,
    };
}

/// Pastes one clipboard image into the prompt composer as an inline
/// placeholder token.
async fn handle_prompt_image_paste(app: &mut App, prompt_context: &PromptContext) {
    let attachment_number = match &app.mode {
        AppMode::Prompt {
            attachment_state, ..
        } => attachment_state.next_attachment_number,
        _ => return,
    };

    match clipboard_image::persist_clipboard_image(
        &prompt_context.session_id,
        attachment_number,
        app.services.fs_client().as_ref(),
    )
    .await
    {
        Ok(persisted_image) => {
            insert_pasted_image_placeholder(app, persisted_image.local_image_path);
        }
        Err(error) => {
            append_prompt_status_line(
                app,
                &prompt_context.session_id,
                "Paste Image Error",
                &clipboard_image::normalize_clipboard_image_error(&error),
            )
            .await;
        }
    }
}

/// Inserts one persisted image placeholder into the prompt input and records
/// the attachment metadata in prompt state.
fn insert_pasted_image_placeholder(app: &mut App, local_image_path: std::path::PathBuf) {
    if let AppMode::Prompt {
        attachment_state,
        history_state,
        input,
        slash_state,
        ..
    } = &mut app.mode
    {
        insert_prompt_local_image(
            attachment_state,
            history_state,
            input,
            slash_state,
            local_image_path,
        );
    }

    sync_prompt_at_mention_state(app);
}

/// Drains the prompt composer into the structured turn payload sent to the
/// session workflow.
///
/// Attachments are filtered against the submitted text so manually deleted
/// `[Image #n]` placeholders do not leave orphaned image inputs in the final
/// turn payload.
fn take_submitted_turn_prompt(app: &mut App) -> TurnPrompt {
    match &mut app.mode {
        AppMode::Prompt {
            attachment_state,
            input,
            ..
        } => {
            let submission = drain_prompt_submission(attachment_state, input);
            let attachments = submission
                .attachments
                .into_iter()
                .map(|attachment| TurnPromptAttachment {
                    placeholder: attachment.placeholder,
                    local_image_path: attachment.local_image_path,
                })
                .collect();

            TurnPrompt {
                attachments,
                text: submission.text,
                text_source: TurnPromptTextSource::UserPrompt,
            }
        }
        _ => TurnPrompt::from_text(String::new()),
    }
}

async fn handle_prompt_slash_submit(app: &mut App, prompt_context: &PromptContext) {
    let session_agent_kind = app
        .session_at(prompt_context.session_index)
        .map_or(AgentKind::Codex, |session| session.model.kind());
    let selection = match &app.mode {
        AppMode::Prompt {
            input, slash_state, ..
        } => resolve_prompt_slash_selection(
            input.text(),
            slash_state,
            session_agent_kind,
            apply_command_has_actionable_review_suggestions(app, prompt_context),
        ),
        _ => None,
    };

    match selection {
        Some(PromptSuggestionSelection::Command("/apply")) => {
            reset_prompt_slash_input(app);
            handle_apply_command(app, prompt_context).await;
        }
        Some(PromptSuggestionSelection::Command("/stats")) => {
            reset_prompt_slash_input(app);
            handle_stats_command(app, prompt_context).await;
        }
        Some(PromptSuggestionSelection::Command("/reasoning")) => {
            let selected_reasoning_level = app
                .session_at(prompt_context.session_index)
                .map_or(app.settings.reasoning_level, |session| {
                    session.effective_reasoning_level(app.settings.reasoning_level)
                });
            let selected_index = ReasoningLevel::ALL
                .iter()
                .position(|level| *level == selected_reasoning_level)
                .unwrap_or(0);

            if let AppMode::Prompt { slash_state, .. } = &mut app.mode {
                slash_state.stage = PromptSlashStage::Reasoning;
                slash_state.selected_agent = None;
                slash_state.selected_index = selected_index;
            }
        }
        Some(PromptSuggestionSelection::Command(_)) => {
            if let AppMode::Prompt { slash_state, .. } = &mut app.mode {
                slash_state.stage = PromptSlashStage::Agent;
                slash_state.selected_agent = None;
                slash_state.selected_index = 0;
            }
        }
        Some(PromptSuggestionSelection::Agent(selected_agent)) => {
            if let AppMode::Prompt { slash_state, .. } = &mut app.mode {
                slash_state.selected_agent = Some(selected_agent);
                slash_state.stage = PromptSlashStage::Model;
                slash_state.selected_index = 0;
            }
        }
        Some(PromptSuggestionSelection::Model(selected_model)) => {
            reset_prompt_slash_input(app);
            update_prompt_session_model(app, prompt_context, selected_model).await;
        }
        Some(PromptSuggestionSelection::Reasoning(reasoning_level)) => {
            reset_prompt_slash_input(app);
            update_prompt_session_reasoning_level(app, prompt_context, reasoning_level).await;
        }
        None => {}
    }
}

/// Clears the slash-command buffer after one prompt slash action is accepted.
fn reset_prompt_slash_input(app: &mut App) {
    if let AppMode::Prompt {
        input, slash_state, ..
    } = &mut app.mode
    {
        input.take_text();
        slash_state.reset();
    }
}

/// Persists one slash-selected model change and logs any failure with session
/// context.
async fn update_prompt_session_model(
    app: &mut App,
    prompt_context: &PromptContext,
    selected_model: AgentModel,
) {
    if let Err(error) = app
        .set_session_model(&prompt_context.session_id, selected_model)
        .await
    {
        warn!(
            session_id = %prompt_context.session_id,
            model = %selected_model.as_str(),
            error = %error,
            "failed to switch session model from prompt slash command"
        );
    }
}

/// Persists one slash-selected reasoning override and logs any failure with
/// session context.
async fn update_prompt_session_reasoning_level(
    app: &mut App,
    prompt_context: &PromptContext,
    reasoning_level: ReasoningLevel,
) {
    if let Err(error) = app
        .set_session_reasoning_level(&prompt_context.session_id, Some(reasoning_level))
        .await
    {
        warn!(
            session_id = %prompt_context.session_id,
            reasoning_level = ?reasoning_level,
            error = %error,
            "failed to update session reasoning level from prompt slash command"
        );
    }
}

/// Cancels the active prompt and drops any composer-owned attachment files.
///
/// Existing focused-review output is restored into session view because no new
/// prompt was submitted.
async fn handle_prompt_cancel_key(app: &mut App, prompt_context: &PromptContext) {
    if prompt_context.is_slash_command() {
        if let AppMode::Prompt {
            input, slash_state, ..
        } = &mut app.mode
        {
            input.take_text();
            slash_state.reset();
        }

        return;
    }

    cleanup_prompt_attachment_state(app).await;

    if prompt_context.can_delete_on_cancel() {
        app.delete_selected_session_deferred_cleanup().await;
        app.mode = AppMode::List;

        return;
    }

    app.mode = AppMode::View {
        review_status_message: prompt_review_status_message(app),
        review_text: prompt_review_text(app),
        session_id: prompt_context.session_id.clone(),
        scroll_offset: prompt_context.scroll_offset,
    };
}

/// Returns the preserved focused-review status text stored in prompt mode.
fn prompt_review_status_message(app: &App) -> Option<String> {
    match &app.mode {
        AppMode::Prompt {
            review_status_message,
            ..
        } => review_status_message.clone(),
        _ => None,
    }
}

/// Returns the preserved focused-review output stored in prompt mode.
fn prompt_review_text(app: &App) -> Option<String> {
    match &app.mode {
        AppMode::Prompt { review_text, .. } => review_text.clone(),
        _ => None,
    }
}

/// Drops the preserved focused-review text and status message held in prompt
/// mode so a subsequent cancel cannot restore invalidated review content.
fn clear_prompt_review_state(app: &mut App) {
    if let AppMode::Prompt {
        review_status_message,
        review_text,
        ..
    } = &mut app.mode
    {
        *review_status_message = None;
        *review_text = None;
    }
}

async fn append_output_for_session(app: &App, session_id: &str, output: &str) {
    app.append_output_for_session(session_id, output).await;
}

/// Returns whether the selected session has cached focused-review suggestions
/// that make `/apply` executable from the slash menu.
fn apply_command_has_actionable_review_suggestions(
    app: &App,
    prompt_context: &PromptContext,
) -> bool {
    review_cache_has_actionable_suggestions(app, &prompt_context.session_id)
}

/// Returns whether the active prompt session has cached focused-review
/// suggestions that make `/apply` selectable.
fn prompt_apply_command_is_available(app: &App) -> bool {
    let Some(session_id) = prompt_session_id(app) else {
        return false;
    };

    review_cache_has_actionable_suggestions(app, &session_id)
}

/// Returns the active prompt session id without mutating prompt state.
fn prompt_session_id(app: &App) -> Option<SessionId> {
    match &app.mode {
        AppMode::Prompt { session_id, .. } => Some(session_id.clone()),
        _ => None,
    }
}

/// Returns whether cached focused-review text contains actionable
/// suggestions for one session.
fn review_cache_has_actionable_suggestions(app: &App, session_id: &str) -> bool {
    let Some(ReviewCacheEntry::Ready { text, .. }) = app.review_cache.get(session_id) else {
        return false;
    };

    review::has_actionable_review_suggestions(Some(text))
}

/// Appends one prompt-mode status line to the session transcript shown above
/// the composer.
async fn append_prompt_status_line(app: &App, session_id: &str, label: &str, message: &str) {
    append_output_for_session(app, session_id, &format!("\n[{label}] {message}\n")).await;
}

/// Removes any prompt attachment files still owned by the active composer and
/// resets attachment state before leaving prompt mode.
async fn cleanup_prompt_attachment_state(app: &mut App) {
    let prompt = match &mut app.mode {
        AppMode::Prompt {
            attachment_state, ..
        } => {
            let attachments = attachment_state
                .attachments
                .iter()
                .map(|attachment| TurnPromptAttachment {
                    placeholder: attachment.placeholder.clone(),
                    local_image_path: attachment.local_image_path.clone(),
                })
                .collect::<Vec<_>>();
            attachment_state.reset();

            TurnPrompt {
                attachments,
                text: String::new(),
                text_source: TurnPromptTextSource::UserPrompt,
            }
        }
        _ => return,
    };

    app.cleanup_prompt_attachment_files(&prompt).await;
}

/// Handles `/apply` by extracting suggestions from the focused review and
/// submitting them as a verification-gated prompt to the agent.
///
/// Only runs when the session is in `Status::Review` and a `Ready` review is
/// cached for it so stale or in-flight reviews are not applied. The cached
/// review's diff hash is revalidated against the live worktree diff so a
/// review that no longer matches the current files is rejected instead of
/// submitted as stale instructions.
///
/// Composer attachments are preserved across all early-return validation
/// paths and only cleaned up at the submission boundary, so a rejected
/// attempt leaves the user's pasted images intact for the next action.
///
/// When the cached review fails the stale-hash guard, the preserved
/// `review_text` and `review_status_message` held in `AppMode::Prompt` are
/// cleared so a subsequent cancel cannot restore the invalidated review back
/// into the session view.
async fn handle_apply_command(app: &mut App, prompt_context: &PromptContext) {
    let Some((session_status, session_folder, base_branch)) =
        app.session_at(prompt_context.session_index).map(|session| {
            (
                session.status,
                session.folder.clone(),
                session.base_branch.clone(),
            )
        })
    else {
        return;
    };

    if session_status != crate::domain::session::Status::Review {
        append_prompt_status_line(
            app,
            &prompt_context.session_id,
            "Apply",
            "Apply is only available after a focused review completes (session status must be \
             Review).",
        )
        .await;

        return;
    }

    let (cached_hash, cached_text) = if let Some(ReviewCacheEntry::Ready { diff_hash, text }) =
        app.review_cache.get(prompt_context.session_id.as_str())
    {
        (*diff_hash, text.clone())
    } else {
        append_prompt_status_line(
            app,
            &prompt_context.session_id,
            "Apply",
            "No actionable suggestions available. Run a focused review first (f key).",
        )
        .await;

        return;
    };

    let current_diff = match app
        .services
        .git_client()
        .diff(session_folder, base_branch)
        .await
    {
        Ok(diff) => diff,
        Err(err) => {
            append_prompt_status_line(
                app,
                &prompt_context.session_id,
                "Apply",
                &format!(
                    "Failed to read worktree diff: {err}. Review cache preserved; try /apply \
                     again."
                ),
            )
            .await;

            return;
        }
    };
    let current_hash = diff_content_hash(&current_diff);

    if current_hash != cached_hash {
        app.review_cache.remove(prompt_context.session_id.as_str());
        clear_prompt_review_state(app);
        append_prompt_status_line(
            app,
            &prompt_context.session_id,
            "Apply",
            "Review is stale; the worktree changed since it was generated. Run focused review \
             again (f key).",
        )
        .await;

        return;
    }

    let Some(suggestions) = review::review_suggestions(&cached_text) else {
        append_prompt_status_line(
            app,
            &prompt_context.session_id,
            "Apply",
            "No actionable suggestions found in the current review.",
        )
        .await;

        return;
    };

    let prompt = build_apply_review_prompt(&suggestions);

    cleanup_prompt_attachment_state(app).await;
    app.review_cache.remove(prompt_context.session_id.as_str());
    app.reply(&prompt_context.session_id, prompt).await;

    app.mode = AppMode::View {
        review_status_message: None,
        review_text: None,
        session_id: prompt_context.session_id.clone(),
        scroll_offset: None,
    };
}

/// Builds the agent-facing `/apply` prompt from focused-review suggestions.
///
/// The prompt explicitly asks the agent to verify each suggestion against the
/// current code before making changes, then apply only suggestions that remain
/// correct and relevant.
fn build_apply_review_prompt(suggestions: &str) -> TurnPrompt {
    TurnPrompt::from_text(format!(
        "Verify the following focused-review suggestions against the current code before changing \
         anything. Apply only the suggestions that are still correct and relevant; explain any \
         suggestions you leave unapplied.\n\n{suggestions}"
    ))
}

/// Handles `/stats` by loading stats through the app layer and appending the
/// rendered output to the session transcript.
async fn handle_stats_command(app: &App, prompt_context: &PromptContext) {
    let session_stats = app.stats_for_session(&prompt_context.session_id).await;
    let session_time = session_stats
        .session_duration_seconds
        .map_or_else(|| "Unavailable".to_string(), format_duration);
    let usage_rows_result = build_token_usage_rows(session_stats.usage_rows_result);
    let stats_output =
        build_stats_markdown(&prompt_context.session_id, &session_time, usage_rows_result);

    append_output_for_session(app, &prompt_context.session_id, &stats_output).await;
}

struct TokenUsageRow {
    in_tokens: String,
    model: String,
    out_tokens: String,
}

fn build_token_usage_rows(
    usage_rows_result: Result<Vec<SessionStatsUsage>, String>,
) -> Result<Vec<TokenUsageRow>, String> {
    match usage_rows_result {
        Ok(usage_rows) => {
            let rows = usage_rows
                .into_iter()
                .map(|row| TokenUsageRow {
                    in_tokens: format_token_count(row.input_tokens),
                    model: row.model,
                    out_tokens: format_token_count(row.output_tokens),
                })
                .collect();

            Ok(rows)
        }
        Err(error) => Err(error),
    }
}

fn build_stats_markdown(
    session_id: &str,
    session_time: &str,
    usage_rows_result: Result<Vec<TokenUsageRow>, String>,
) -> String {
    let mut lines = vec![
        format_stats_metric_line("Session ID", session_id),
        format_stats_metric_line("Session Time", session_time),
        String::new(),
        "Tokens Usage".to_string(),
    ];

    lines.extend(build_token_usage_lines(usage_rows_result));

    format!(
        "\n## Session Stats\n\n```stats\n{}\n```\n",
        lines.join("\n")
    )
}

fn format_stats_metric_line(metric: &str, value: &str) -> String {
    format!("{metric}\t{value}")
}

fn build_token_usage_lines(usage_rows_result: Result<Vec<TokenUsageRow>, String>) -> Vec<String> {
    match usage_rows_result {
        Ok(usage_rows) if usage_rows.is_empty() => vec!["No token usage recorded.".to_string()],
        Ok(usage_rows) => render_token_usage_table_lines(&usage_rows),
        Err(error) => vec![
            "Usage unavailable.".to_string(),
            format_stats_metric_line("Error", &error),
        ],
    }
}

fn render_token_usage_table_lines(usage_rows: &[TokenUsageRow]) -> Vec<String> {
    let model_width = usage_rows
        .iter()
        .map(|row| row.model.chars().count())
        .max()
        .unwrap_or_default()
        .max("Model".chars().count());
    let in_width = usage_rows
        .iter()
        .map(|row| row.in_tokens.chars().count())
        .max()
        .unwrap_or_default()
        .max("In".chars().count());
    let out_width = usage_rows
        .iter()
        .map(|row| row.out_tokens.chars().count())
        .max()
        .unwrap_or_default()
        .max("Out".chars().count());

    let mut lines = vec![format!(
        "{:<model_width$}  {:>in_width$}  {:>out_width$}",
        "Model", "In", "Out"
    )];

    lines.extend(usage_rows.iter().map(|row| {
        format!(
            "{:<model_width$}  {:>in_width$}  {:>out_width$}",
            row.model, row.in_tokens, row.out_tokens
        )
    }));

    lines
}

fn format_duration(total_seconds: i64) -> String {
    let hours = total_seconds / 3600;
    let minutes = (total_seconds % 3600) / 60;
    let seconds = total_seconds % 60;

    format!("{hours:02}:{minutes:02}:{seconds:02}")
}

fn prompt_input_width<B: Backend>(terminal: &Terminal<B>) -> io::Result<u16>
where
    B::Error: std::error::Error + Send + Sync + 'static,
{
    let terminal_width = terminal.size().map_err(crate::runtime::backend_err)?.width;

    Ok(terminal_width.saturating_sub(2))
}

/// Moves the prompt cursor left with modifier-aware behavior.
///
/// `Cmd`+`Left` (`SUPER`) moves to the start of the current line,
/// `Option`+`Left` (`ALT`) and `Shift`+`Left` move to the previous word
/// start, and a plain `Left` moves one character. When the move lands inside
/// an existing `@path` token, the file dropdown is reopened.
fn handle_prompt_left(app: &mut App, key: KeyEvent) {
    if let AppMode::Prompt { input, .. } = &mut app.mode {
        if key.modifiers.contains(event::KeyModifiers::SUPER) {
            input.move_line_start();
        } else if key
            .modifiers
            .intersects(event::KeyModifiers::ALT | event::KeyModifiers::SHIFT)
        {
            input_key::move_cursor_word_left(input);
        } else {
            input.move_left();
        }
    }

    sync_prompt_at_mention_state(app);
}

/// Moves the prompt cursor right with modifier-aware behavior.
///
/// `Cmd`+`Right` (`SUPER`) moves to the end of the current line,
/// `Option`+`Right` (`ALT`) and `Shift`+`Right` move to the next word
/// start, and a plain `Right` moves one character. When the move lands inside
/// an existing `@path` token, the file dropdown is reopened.
fn handle_prompt_right(app: &mut App, key: KeyEvent) {
    if let AppMode::Prompt { input, .. } = &mut app.mode {
        if key.modifiers.contains(event::KeyModifiers::SUPER) {
            input.move_line_end();
        } else if key
            .modifiers
            .intersects(event::KeyModifiers::ALT | event::KeyModifiers::SHIFT)
        {
            input_key::move_cursor_word_right(input);
        } else {
            input.move_right();
        }
    }

    sync_prompt_at_mention_state(app);
}

/// Handles `Ctrl+u` line deletion by clearing the current line content.
///
/// This is the standard Unix "kill line" binding and also the sequence macOS
/// terminals send for `Cmd`+`Backspace`.
fn handle_prompt_line_delete(app: &mut App) {
    if let AppMode::Prompt { input, .. } = &app.mode
        && let Some((start, end)) = prompt_current_line_delete_range(input)
    {
        apply_prompt_delete_range(app, start, end);
    }
}

/// Handles `Ctrl+k` kill-to-end-of-line by deleting text from the cursor to
/// the end of the current line (stopping before the newline).
fn handle_prompt_kill_to_line_end(app: &mut App) {
    if let AppMode::Prompt { input, .. } = &mut app.mode {
        input.delete_to_line_end();
    }
}

/// Handles `Ctrl+w` word deletion by deleting the previous word.
fn handle_prompt_word_delete(app: &mut App) {
    if let AppMode::Prompt { input, .. } = &app.mode
        && let Some((start, end)) = input_key::word_delete_range(input.text(), input.cursor)
    {
        apply_prompt_delete_range(app, start, end);
    }
}

/// Handles prompt backspace by deleting one character or one whole word when
/// `Option`/`Alt` (or `Shift` for compatibility) is pressed.
///
/// `Cmd`+`Backspace` takes precedence and clears the current line content.
fn handle_prompt_backspace(app: &mut App, key: KeyEvent) {
    let Some(delete_range) = prompt_backspace_range(app, key) else {
        return;
    };

    apply_prompt_delete_range(app, delete_range.0, delete_range.1);
}

/// Returns the character range deleted by one prompt backspace key press.
fn prompt_backspace_range(app: &App, key: KeyEvent) -> Option<(usize, usize)> {
    let AppMode::Prompt { input, .. } = &app.mode else {
        return None;
    };

    if input_key::is_line_delete_backspace(key) {
        return prompt_current_line_delete_range(input);
    }

    if input_key::is_word_delete_backspace(key) {
        return input_key::word_delete_range(input.text(), input.cursor);
    }

    if input.cursor == 0 {
        return None;
    }

    Some((input.cursor - 1, input.cursor))
}

fn handle_prompt_delete(app: &mut App) {
    let Some(delete_range) = prompt_delete_range(app) else {
        return;
    };

    apply_prompt_delete_range(app, delete_range.0, delete_range.1);
}

/// Returns the character range deleted by one prompt forward-delete key press.
fn prompt_delete_range(app: &App) -> Option<(usize, usize)> {
    let AppMode::Prompt { input, .. } = &app.mode else {
        return None;
    };

    let char_count = input.text().chars().count();
    if input.cursor >= char_count {
        return None;
    }

    Some((input.cursor, input.cursor + 1))
}

/// Applies one prompt deletion range, expanding it to cover full image
/// placeholder tokens and removing orphaned attachments from prompt state.
fn apply_prompt_delete_range(app: &mut App, start: usize, end: usize) {
    if let AppMode::Prompt {
        attachment_state,
        history_state,
        input,
        slash_state,
        ..
    } = &mut app.mode
    {
        apply_prompt_delete_range_components(
            attachment_state,
            history_state,
            input,
            slash_state,
            start,
            end,
        );
    }

    sync_prompt_at_mention_state(app);
}

/// Inserts one typed character into prompt input and keeps at-mention state
/// in sync.
fn handle_prompt_char(app: &mut App, character: char) {
    if let AppMode::Prompt {
        input,
        history_state,
        slash_state,
        ..
    } = &mut app.mode
    {
        insert_prompt_character(input, history_state, slash_state, character);
    }

    sync_prompt_at_mention_state(app);
}

/// Starts asynchronous loading of at-mention file entries for the prompt
/// session.
///
/// Draft sessions in `Draft` state defer worktree creation, so their composer
/// indexes the active project working directory until the session folder is
/// materialized.
fn activate_at_mention(app: &mut App, prompt_context: &PromptContext) {
    let lookup_root = app
        .sessions
        .sessions
        .get(prompt_context.session_index)
        .map_or_else(
            || app.working_dir().to_path_buf(),
            |session| {
                let session_folder = session.folder.clone();
                let has_session_folder = app.services.fs_client().is_dir(session_folder.clone());

                at_mention::lookup_root(
                    app.working_dir().to_path_buf(),
                    Some(session_folder),
                    has_session_folder,
                )
            },
        );
    let session_id = prompt_context.session_id.clone();
    let event_tx = app.services.event_sender();

    at_mention::start_loading_entries(event_tx, lookup_root, session_id, &mut app.sessions);

    if let AppMode::Prompt {
        at_mention_state, ..
    } = &mut app.mode
    {
        *at_mention_state = Some(PromptAtMentionState::new(Vec::new()));
    }
}

/// Clears the at-mention state.
fn dismiss_at_mention(app: &mut App) {
    if let AppMode::Prompt {
        at_mention_state, ..
    } = &mut app.mode
    {
        at_mention::dismiss(at_mention_state);
    }
}

/// Moves the at-mention selection up.
fn handle_at_mention_up(app: &mut App) {
    if let AppMode::Prompt {
        at_mention_state: Some(state),
        ..
    } = &mut app.mode
    {
        at_mention::move_selection_up(state);
    }
}

/// Moves the at-mention selection down.
fn handle_at_mention_down(app: &mut App) {
    if let AppMode::Prompt {
        at_mention_state: Some(state),
        input,
        ..
    } = &mut app.mode
    {
        at_mention::move_selection_down(input, state);
    }
}

/// Selects the currently highlighted file and inserts it into the input.
fn handle_at_mention_select(app: &mut App) {
    let replacement = match &app.mode {
        AppMode::Prompt {
            at_mention_state: Some(state),
            input,
            ..
        } => at_mention::selected_replacement(input, state),
        _ => return,
    };

    if replacement.is_none() {
        dismiss_at_mention(app);

        return;
    }

    if let Some(selection) = replacement
        && let AppMode::Prompt { input, .. } = &mut app.mode
    {
        input.replace_range(selection.at_start, selection.cursor, &selection.text);
    }

    dismiss_at_mention(app);
}

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

    use tempfile::tempdir;

    use super::*;
    use crate::infra::db::Database;
    use crate::infra::file_index::FileEntry;
    use crate::ui::state::prompt::{
        PromptAtMentionState, PromptAttachmentState, PromptHistoryState, PromptSlashState,
    };

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

    /// Replaces the app-level git client with a caller-provided mock by
    /// rebuilding `AppServices` through its public constructor, preserving
    /// the remaining shared dependencies.
    fn install_mock_git_client(app: &mut App, mock_git_client: crate::infra::git::MockGitClient) {
        let mock_git_client: std::sync::Arc<dyn crate::infra::git::GitClient> =
            std::sync::Arc::new(mock_git_client);
        let base_path = app.services.base_path().to_path_buf();
        let db = app.services.db().clone();
        let event_sender = app.services.event_sender();
        let available_agent_kinds = app.services.available_agent_kinds();
        let agent_usage_probe = app.services.agent_usage_probe();
        let app_server_client_override = app.services.app_server_client_override();
        let fs_client = app.services.fs_client();
        let review_request_client = app.services.review_request_client();

        app.services = crate::app::AppServices::new(
            base_path,
            app.services.clock(),
            event_sender,
            crate::app::AppServiceDeps {
                agent_usage_probe,
                app_server_client_override,
                available_agent_kinds,
                fs_client,
                git_client: mock_git_client,
                repositories: db,
                review_request_client,
            },
        );
    }

    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");
    }

    async fn new_test_prompt_app(
        input_text: &str,
        at_mention_state: Option<PromptAtMentionState>,
    ) -> (App, tempfile::TempDir) {
        new_test_prompt_app_with_session_mode(input_text, at_mention_state, false).await
    }

    /// Builds one prompt-mode test app backed by either an immediate-start or
    /// explicit draft session.
    async fn new_test_prompt_app_with_session_mode(
        input_text: &str,
        at_mention_state: Option<PromptAtMentionState>,
        is_draft_session: bool,
    ) -> (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 mut app = App::new_with_clients(
            base_path.clone(),
            base_path,
            Some("main".to_string()),
            database,
            test_app_clients(),
        )
        .await
        .expect("failed to build app");

        let session_id = if is_draft_session {
            app.create_draft_session()
                .await
                .expect("failed to create draft session")
        } else {
            app.create_session()
                .await
                .expect("failed to create session")
        };
        app.mode = AppMode::Prompt {
            at_mention_state,
            attachment_state: PromptAttachmentState::default(),
            history_state: PromptHistoryState::new(Vec::new()),
            review_status_message: None,
            review_text: None,
            slash_state: PromptSlashState::default(),
            session_id: session_id.into(),
            input: InputState::with_text(input_text.to_string()),
            scroll_offset: None,
        };

        (app, base_dir)
    }

    /// Builds one prompt-mode test app whose active session uses the explicit
    /// staged-draft workflow.
    async fn new_test_draft_prompt_app(
        input_text: &str,
        at_mention_state: Option<PromptAtMentionState>,
    ) -> (App, tempfile::TempDir) {
        new_test_prompt_app_with_session_mode(input_text, at_mention_state, true).await
    }

    /// Waits until the app emits an `AtMentionEntriesLoaded` event and skips
    /// unrelated background events produced during startup.
    async fn wait_for_at_mention_entries_event(app: &mut App) -> crate::app::AppEvent {
        let timeout = std::time::Duration::from_secs(1);
        let deadline = tokio::time::Instant::now() + timeout;

        loop {
            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
            let next_event = tokio::time::timeout(remaining, app.next_app_event())
                .await
                .expect("at-mention event should arrive")
                .expect("at-mention event channel closed unexpectedly");

            if matches!(
                next_event,
                crate::app::AppEvent::AtMentionEntriesLoaded { .. }
            ) {
                return next_event;
            }
        }
    }

    #[test]
    fn test_is_plain_char_key_for_plain_character() {
        // Arrange
        let key = KeyEvent::new(KeyCode::Char('j'), event::KeyModifiers::NONE);

        // Act
        let result = is_plain_char_key(key, 'j');

        // Assert
        assert!(result);
    }

    #[test]
    fn test_is_plain_char_key_rejects_modifier_keys() {
        // Arrange
        let key = KeyEvent::new(KeyCode::Char('k'), event::KeyModifiers::SHIFT);

        // Act
        let result = is_plain_char_key(key, 'k');

        // Assert
        assert!(!result);
    }

    #[test]
    fn test_is_plain_char_key_rejects_other_character() {
        // Arrange
        let key = KeyEvent::new(KeyCode::Char('j'), event::KeyModifiers::NONE);

        // Act
        let result = is_plain_char_key(key, 'k');

        // Assert
        assert!(!result);
    }

    #[test]
    fn test_is_prompt_image_paste_key_accepts_alt_v() {
        // Arrange
        let key = KeyEvent::new(KeyCode::Char('v'), event::KeyModifiers::ALT);

        // Act
        let result = is_prompt_image_paste_key(key);

        // Assert
        assert!(result);
    }

    #[test]
    fn test_is_prompt_image_paste_key_accepts_ctrl_v() {
        // Arrange
        let key = KeyEvent::new(KeyCode::Char('v'), event::KeyModifiers::CONTROL);

        // Act
        let result = is_prompt_image_paste_key(key);

        // Assert
        assert!(result);
    }

    #[test]
    fn test_is_prompt_image_paste_key_rejects_plain_v() {
        // Arrange
        let key = KeyEvent::new(KeyCode::Char('v'), event::KeyModifiers::NONE);

        // Act
        let result = is_prompt_image_paste_key(key);

        // Assert
        assert!(!result);
    }

    #[tokio::test]
    async fn test_handle_paste_inserts_multiline_content_with_normalized_newlines() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("prefix ", None).await;

        // Act
        handle_paste(&mut app, "line 1\r\nline 2\rline 3");

        // Assert
        if let AppMode::Prompt { input, .. } = &app.mode {
            assert_eq!(input.text(), "prefix line 1\nline 2\nline 3");
            assert_eq!(
                input.cursor,
                "prefix line 1\nline 2\nline 3".chars().count()
            );
        }
    }

    #[tokio::test]
    async fn test_insert_pasted_image_placeholder_records_attachment_and_resets_prompt_state() {
        // Arrange
        let mut at_mention_state = PromptAtMentionState::new(vec![FileEntry {
            is_dir: false,
            path: "src/main.rs".to_string(),
        }]);
        at_mention_state.selected_index = 4;
        let (mut app, _base_dir) = new_test_prompt_app("Review ", Some(at_mention_state)).await;
        if let AppMode::Prompt {
            history_state,
            slash_state,
            ..
        } = &mut app.mode
        {
            history_state.selected_index = Some(0);
            history_state.draft_text = Some("draft".to_string());
            slash_state.selected_index = 2;
        }

        // Act
        insert_pasted_image_placeholder(&mut app, std::path::PathBuf::from("/tmp/image-1.png"));

        // Assert
        if let AppMode::Prompt {
            at_mention_state,
            attachment_state,
            history_state,
            input,
            slash_state,
            ..
        } = &app.mode
        {
            assert_eq!(input.text(), "Review [Image #1]");
            assert_eq!(attachment_state.attachments.len(), 1);
            assert_eq!(
                attachment_state.attachments[0].local_image_path,
                std::path::PathBuf::from("/tmp/image-1.png")
            );
            assert_eq!(history_state.selected_index, None);
            assert_eq!(history_state.draft_text, None);
            assert_eq!(*slash_state, PromptSlashState::default());
            assert!(at_mention_state.is_none());
        }
    }

    #[tokio::test]
    async fn test_take_submitted_turn_prompt_drains_text_and_attachment_state() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("Review ", None).await;
        insert_pasted_image_placeholder(&mut app, std::path::PathBuf::from("/tmp/image-1.png"));

        // Act
        let prompt = take_submitted_turn_prompt(&mut app);

        // Assert
        assert_eq!(prompt.text, "Review [Image #1]");
        assert_eq!(prompt.attachments.len(), 1);
        assert_eq!(prompt.attachments[0].placeholder, "[Image #1]");
        assert_eq!(
            prompt.attachments[0].local_image_path,
            std::path::PathBuf::from("/tmp/image-1.png")
        );
        if let AppMode::Prompt {
            attachment_state,
            input,
            ..
        } = &app.mode
        {
            assert!(input.text().is_empty());
            assert!(attachment_state.attachments.is_empty());
            assert_eq!(attachment_state.next_attachment_number, 1);
        }
    }

    #[tokio::test]
    async fn test_take_submitted_turn_prompt_filters_deleted_attachment_placeholders() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("Review ", None).await;
        insert_pasted_image_placeholder(&mut app, std::path::PathBuf::from("/tmp/image-1.png"));
        insert_pasted_image_placeholder(&mut app, std::path::PathBuf::from("/tmp/image-2.png"));
        if let AppMode::Prompt { input, .. } = &mut app.mode {
            *input = InputState::with_text("Review [Image #2]".to_string());
        }

        // Act
        let prompt = take_submitted_turn_prompt(&mut app);

        // Assert
        assert_eq!(prompt.text, "Review [Image #2]");
        assert_eq!(prompt.attachments.len(), 1);
        assert_eq!(prompt.attachments[0].placeholder, "[Image #2]");
        assert_eq!(
            prompt.attachments[0].local_image_path,
            std::path::PathBuf::from("/tmp/image-2.png")
        );
        if let AppMode::Prompt {
            attachment_state,
            input,
            ..
        } = &app.mode
        {
            assert!(input.text().is_empty());
            assert!(attachment_state.attachments.is_empty());
            assert_eq!(attachment_state.next_attachment_number, 1);
        }
    }

    #[tokio::test]
    async fn test_take_submitted_turn_prompt_sorts_attachments_by_text_position() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("", None).await;
        insert_pasted_image_placeholder(&mut app, std::path::PathBuf::from("/tmp/image-1.png"));
        insert_pasted_image_placeholder(&mut app, std::path::PathBuf::from("/tmp/image-2.png"));
        if let AppMode::Prompt { input, .. } = &mut app.mode {
            *input = InputState::with_text("[Image #2] then [Image #1]".to_string());
        }

        // Act
        let prompt = take_submitted_turn_prompt(&mut app);

        // Assert
        assert_eq!(prompt.attachments.len(), 2);
        assert_eq!(prompt.attachments[0].placeholder, "[Image #2]");
        assert_eq!(prompt.attachments[1].placeholder, "[Image #1]");
    }

    #[test]
    fn test_prompt_slash_commands_match_model() {
        // Arrange & Act
        let suggestion_list = crate::ui::state::prompt::build_prompt_slash_suggestion_list(
            "/m",
            &PromptSlashState::default(),
            AgentKind::Codex,
            true,
        )
        .expect("expected suggestion list");
        let commands = suggestion_list
            .items
            .into_iter()
            .map(|item| item.label)
            .collect::<Vec<_>>();

        // Assert
        assert_eq!(commands, vec!["/model"]);
    }

    #[test]
    fn test_prompt_slash_commands_lists_all_commands() {
        // Arrange & Act
        let suggestion_list = crate::ui::state::prompt::build_prompt_slash_suggestion_list(
            "/",
            &PromptSlashState::default(),
            AgentKind::Codex,
            true,
        )
        .expect("expected suggestion list");
        let commands = suggestion_list
            .items
            .into_iter()
            .map(|item| item.label)
            .collect::<Vec<_>>();

        // Assert
        assert_eq!(commands, vec!["/apply", "/model", "/reasoning", "/stats"]);
    }

    #[test]
    fn test_prompt_slash_commands_match_stats() {
        // Arrange & Act
        let suggestion_list = crate::ui::state::prompt::build_prompt_slash_suggestion_list(
            "/s",
            &PromptSlashState::default(),
            AgentKind::Codex,
            true,
        )
        .expect("expected suggestion list");
        let commands = suggestion_list
            .items
            .into_iter()
            .map(|item| item.label)
            .collect::<Vec<_>>();

        // Assert
        assert_eq!(commands, vec!["/stats"]);
    }

    #[test]
    fn test_prompt_slash_commands_no_match() {
        // Arrange & Act
        let commands = crate::ui::state::prompt::build_prompt_slash_suggestion_list(
            "/x",
            &PromptSlashState::default(),
            AgentKind::Codex,
            true,
        );

        // Assert
        assert!(commands.is_none());
    }

    #[test]
    fn test_prompt_slash_option_count_for_agent_stage() {
        // Arrange & Act
        let count = prompt_slash_option_count(
            "/model",
            PromptSlashStage::Agent,
            None,
            AgentKind::ALL,
            AgentKind::Codex,
            true,
        );

        // Assert
        assert_eq!(count, AgentKind::ALL.len());
    }

    #[test]
    fn test_prompt_slash_option_count_for_model_stage() {
        // Arrange & Act
        let count = prompt_slash_option_count(
            "/model",
            PromptSlashStage::Model,
            Some(AgentKind::Claude),
            AgentKind::ALL,
            AgentKind::Codex,
            true,
        );

        // Assert
        assert_eq!(count, AgentKind::Claude.models().len());
    }

    #[test]
    fn test_prompt_slash_option_count_for_agent_stage_uses_available_agent_kinds() {
        // Arrange
        let available_agent_kinds = [AgentKind::Codex];

        // Act
        let count = prompt_slash_option_count(
            "/model",
            PromptSlashStage::Agent,
            None,
            &available_agent_kinds,
            AgentKind::Codex,
            true,
        );

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

    #[tokio::test]
    async fn test_navigate_prompt_history_up_stays_on_first_entry() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("draft", None).await;
        if let AppMode::Prompt {
            history_state,
            input,
            ..
        } = &mut app.mode
        {
            history_state.entries = vec!["first".to_string(), "second".to_string()];
            history_state.selected_index = Some(0);
            *input = InputState::with_text("first".to_string());
        }

        // Act
        navigate_prompt_history_up(&mut app);

        // Assert
        if let AppMode::Prompt {
            history_state,
            input,
            ..
        } = &app.mode
        {
            assert_eq!(input.text(), "first");
            assert_eq!(history_state.selected_index, Some(0));
            assert_eq!(history_state.draft_text, None);
        }
    }

    #[tokio::test]
    async fn test_navigate_prompt_history_up_selects_latest_entry_and_saves_draft() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("draft", None).await;
        if let AppMode::Prompt { history_state, .. } = &mut app.mode {
            history_state.entries = vec!["first".to_string(), "second".to_string()];
        }

        // Act
        navigate_prompt_history_up(&mut app);

        // Assert
        if let AppMode::Prompt {
            history_state,
            input,
            ..
        } = &app.mode
        {
            assert_eq!(input.text(), "second");
            assert_eq!(history_state.selected_index, Some(1));
            assert_eq!(history_state.draft_text.as_deref(), Some("draft"));
        }
    }

    #[tokio::test]
    async fn test_navigate_prompt_history_down_restores_draft_after_latest_entry() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("draft", None).await;
        if let AppMode::Prompt { history_state, .. } = &mut app.mode {
            history_state.entries = vec!["first".to_string(), "second".to_string()];
        }
        navigate_prompt_history_up(&mut app);

        // Act
        navigate_prompt_history_down(&mut app);

        // Assert
        if let AppMode::Prompt {
            history_state,
            input,
            ..
        } = &app.mode
        {
            assert_eq!(input.text(), "draft");
            assert_eq!(history_state.selected_index, None);
            assert_eq!(history_state.draft_text, None);
        }
    }

    #[tokio::test]
    async fn test_advance_prompt_slash_selection_stays_on_last_agent() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("/model", None).await;
        if let AppMode::Prompt { slash_state, .. } = &mut app.mode {
            slash_state.stage = PromptSlashStage::Agent;
            slash_state.selected_index = AgentKind::ALL.len().saturating_sub(1);
        }

        // Act
        advance_prompt_slash_selection(&mut app);

        // Assert
        if let AppMode::Prompt { slash_state, .. } = &app.mode {
            assert_eq!(slash_state.stage, PromptSlashStage::Agent);
            assert_eq!(
                slash_state.selected_index,
                AgentKind::ALL.len().saturating_sub(1)
            );
        }
    }

    /// Verifies slash navigation leaves selection unchanged when the current
    /// command text matches no slash-command options.
    #[tokio::test]
    async fn test_advance_prompt_slash_selection_ignores_empty_command_matches() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("/x", None).await;
        if let AppMode::Prompt { slash_state, .. } = &mut app.mode {
            slash_state.selected_index = 2;
        }

        // Act
        advance_prompt_slash_selection(&mut app);

        // Assert
        if let AppMode::Prompt { slash_state, .. } = &app.mode {
            assert_eq!(slash_state.selected_index, 2);
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_slash_submit_advances_model_command_to_agent_stage() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("/model", None).await;
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");

        // Act
        handle_prompt_slash_submit(&mut app, &prompt_context).await;

        // Assert
        if let AppMode::Prompt {
            input, slash_state, ..
        } = &app.mode
        {
            assert_eq!(input.text(), "/model");
            assert_eq!(slash_state.stage, PromptSlashStage::Agent);
            assert_eq!(slash_state.selected_agent, None);
            assert_eq!(slash_state.selected_index, 0);
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_slash_submit_maps_filtered_first_command_to_model() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("/", None).await;
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");

        // Act
        handle_prompt_slash_submit(&mut app, &prompt_context).await;

        // Assert
        if let AppMode::Prompt { slash_state, .. } = &app.mode {
            assert_eq!(slash_state.stage, PromptSlashStage::Agent);
            assert_eq!(slash_state.selected_agent, None);
            assert_eq!(slash_state.selected_index, 0);
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_slash_submit_selects_agent_and_advances_to_model_stage() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("/model", None).await;
        let selected_index = AgentKind::ALL
            .iter()
            .position(|agent_kind| *agent_kind == AgentKind::Claude)
            .expect("expected Claude agent");
        if let AppMode::Prompt { slash_state, .. } = &mut app.mode {
            slash_state.stage = PromptSlashStage::Agent;
            slash_state.selected_index = selected_index;
        }
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");

        // Act
        handle_prompt_slash_submit(&mut app, &prompt_context).await;

        // Assert
        if let AppMode::Prompt { slash_state, .. } = &app.mode {
            assert_eq!(slash_state.stage, PromptSlashStage::Model);
            assert_eq!(slash_state.selected_agent, Some(AgentKind::Claude));
            assert_eq!(slash_state.selected_index, 0);
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_slash_submit_sets_selected_model_and_resets_input() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("/model", None).await;
        let expected_model = AgentKind::Claude.models()[0];
        if let AppMode::Prompt { slash_state, .. } = &mut app.mode {
            slash_state.stage = PromptSlashStage::Model;
            slash_state.selected_agent = Some(AgentKind::Claude);
            slash_state.selected_index = 0;
        }
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");

        // Act
        handle_prompt_slash_submit(&mut app, &prompt_context).await;
        app.process_pending_app_events().await;

        // Assert
        if let AppMode::Prompt {
            input, slash_state, ..
        } = &app.mode
        {
            assert_eq!(input.text(), "");
            assert_eq!(*slash_state, PromptSlashState::default());
        }
        assert_eq!(app.sessions.sessions[0].model, expected_model);
    }

    #[tokio::test]
    async fn test_handle_prompt_slash_submit_runs_stats_command_and_resets_slash_state() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("/stats", None).await;
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");

        // Act
        handle_prompt_slash_submit(&mut app, &prompt_context).await;

        // Assert
        app.sessions.sync_from_handles();
        if let AppMode::Prompt {
            input, slash_state, ..
        } = &app.mode
        {
            assert_eq!(input.text(), "");
            assert_eq!(*slash_state, PromptSlashState::default());
        }
        assert!(app.sessions.sessions[0].output.contains("## Session Stats"));
    }

    #[tokio::test]
    async fn test_handle_prompt_slash_submit_prefills_reasoning_selection_from_default_setting() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("/reasoning", None).await;
        app.settings.reasoning_level = ReasoningLevel::Medium;
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");

        // Act
        handle_prompt_slash_submit(&mut app, &prompt_context).await;

        // Assert
        if let AppMode::Prompt { slash_state, .. } = &app.mode {
            assert_eq!(slash_state.stage, PromptSlashStage::Reasoning);
            assert_eq!(slash_state.selected_agent, None);
            assert_eq!(slash_state.selected_index, 1);
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_slash_submit_prefills_reasoning_selection_from_session_override() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("/reasoning", None).await;
        app.sessions.sessions[0].reasoning_level_override = Some(ReasoningLevel::High);
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");

        // Act
        handle_prompt_slash_submit(&mut app, &prompt_context).await;

        // Assert
        if let AppMode::Prompt { slash_state, .. } = &app.mode {
            assert_eq!(slash_state.stage, PromptSlashStage::Reasoning);
            assert_eq!(slash_state.selected_agent, None);
            assert_eq!(slash_state.selected_index, 2);
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_slash_submit_clamps_stale_command_selection() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("/stats", None).await;
        if let AppMode::Prompt { slash_state, .. } = &mut app.mode {
            slash_state.selected_index = 99;
        }
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");

        // Act
        handle_prompt_slash_submit(&mut app, &prompt_context).await;

        // Assert
        app.sessions.sync_from_handles();
        if let AppMode::Prompt {
            input, slash_state, ..
        } = &app.mode
        {
            assert_eq!(input.text(), "");
            assert_eq!(*slash_state, PromptSlashState::default());
        }
        assert!(app.sessions.sessions[0].output.contains("## Session Stats"));
    }

    /// Verifies slash submit ignores unmatched commands and preserves the
    /// prompt state.
    #[tokio::test]
    async fn test_handle_prompt_slash_submit_ignores_unknown_command() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("/x", None).await;
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");

        // Act
        handle_prompt_slash_submit(&mut app, &prompt_context).await;

        // Assert
        if let AppMode::Prompt {
            input, slash_state, ..
        } = &app.mode
        {
            assert_eq!(input.text(), "/x");
            assert_eq!(*slash_state, PromptSlashState::default());
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_left_with_shift_moves_cursor_to_previous_word_start() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("hello brave world", None).await;
        if let AppMode::Prompt { input, .. } = &mut app.mode {
            input.cursor = "hello brave world".chars().count();
        }

        // Act
        let key = KeyEvent::new(KeyCode::Left, event::KeyModifiers::SHIFT);
        handle_prompt_left(&mut app, key);

        // Assert
        if let AppMode::Prompt { input, .. } = &app.mode {
            assert_eq!(input.cursor, "hello brave ".chars().count());
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_left_with_shift_skips_whitespace_separators() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("hello\t \nworld", None).await;
        if let AppMode::Prompt { input, .. } = &mut app.mode {
            input.cursor = "hello\t \nworld".chars().count();
        }

        // Act
        let key = KeyEvent::new(KeyCode::Left, event::KeyModifiers::SHIFT);
        handle_prompt_left(&mut app, key);

        // Assert
        if let AppMode::Prompt { input, .. } = &app.mode {
            assert_eq!(input.cursor, "hello\t \n".chars().count());
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_right_with_shift_moves_cursor_to_next_word_start() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("hello brave world", None).await;
        if let AppMode::Prompt { input, .. } = &mut app.mode {
            input.cursor = 0;
        }

        // Act
        let key = KeyEvent::new(KeyCode::Right, event::KeyModifiers::SHIFT);
        handle_prompt_right(&mut app, key);

        // Assert
        if let AppMode::Prompt { input, .. } = &app.mode {
            assert_eq!(input.cursor, "hello ".chars().count());
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_left_with_alt_moves_cursor_to_previous_word_start() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("hello brave world", None).await;
        if let AppMode::Prompt { input, .. } = &mut app.mode {
            input.cursor = "hello brave world".chars().count();
        }

        // Act
        let key = KeyEvent::new(KeyCode::Left, event::KeyModifiers::ALT);
        handle_prompt_left(&mut app, key);

        // Assert
        if let AppMode::Prompt { input, .. } = &app.mode {
            assert_eq!(input.cursor, "hello brave ".chars().count());
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_right_with_alt_moves_cursor_to_next_word_start() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("hello brave world", None).await;
        if let AppMode::Prompt { input, .. } = &mut app.mode {
            input.cursor = 0;
        }

        // Act
        let key = KeyEvent::new(KeyCode::Right, event::KeyModifiers::ALT);
        handle_prompt_right(&mut app, key);

        // Assert
        if let AppMode::Prompt { input, .. } = &app.mode {
            assert_eq!(input.cursor, "hello ".chars().count());
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_left_with_super_moves_cursor_to_line_start() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("first\nsecond\nthird", None).await;
        if let AppMode::Prompt { input, .. } = &mut app.mode {
            input.cursor = "first\nseco".chars().count();
        }

        // Act
        let key = KeyEvent::new(KeyCode::Left, event::KeyModifiers::SUPER);
        handle_prompt_left(&mut app, key);

        // Assert
        if let AppMode::Prompt { input, .. } = &app.mode {
            assert_eq!(input.cursor, "first\n".chars().count());
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_right_with_super_moves_cursor_to_line_end() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("first\nsecond\nthird", None).await;
        if let AppMode::Prompt { input, .. } = &mut app.mode {
            input.cursor = "first\nse".chars().count();
        }

        // Act
        let key = KeyEvent::new(KeyCode::Right, event::KeyModifiers::SUPER);
        handle_prompt_right(&mut app, key);

        // Assert
        if let AppMode::Prompt { input, .. } = &app.mode {
            assert_eq!(input.cursor, "first\nsecond".chars().count());
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_backspace_resets_history_navigation() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("second", None).await;
        if let AppMode::Prompt { history_state, .. } = &mut app.mode {
            history_state.draft_text = Some("draft".to_string());
            history_state.entries = vec!["first".to_string(), "second".to_string()];
            history_state.selected_index = Some(1);
        }

        // Act
        let key = KeyEvent::new(KeyCode::Backspace, event::KeyModifiers::NONE);
        handle_prompt_backspace(&mut app, key);

        // Assert
        if let AppMode::Prompt {
            history_state,
            input,
            ..
        } = &app.mode
        {
            assert_eq!(input.text(), "secon");
            assert_eq!(history_state.selected_index, None);
            assert_eq!(history_state.draft_text, None);
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_backspace_removes_whole_image_token_and_attachment() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("Review ", None).await;
        insert_pasted_image_placeholder(&mut app, std::path::PathBuf::from("/tmp/image-1.png"));
        if let AppMode::Prompt {
            history_state,
            input,
            ..
        } = &mut app.mode
        {
            history_state.selected_index = Some(0);
            history_state.draft_text = Some("draft".to_string());
            input.cursor = input.text().chars().count();
        }

        // Act
        let key = KeyEvent::new(KeyCode::Backspace, event::KeyModifiers::NONE);
        handle_prompt_backspace(&mut app, key);

        // Assert
        if let AppMode::Prompt {
            attachment_state,
            history_state,
            input,
            ..
        } = &app.mode
        {
            assert_eq!(input.text(), "Review ");
            assert!(attachment_state.attachments.is_empty());
            assert_eq!(attachment_state.next_attachment_number, 1);
            assert_eq!(history_state.selected_index, None);
            assert_eq!(history_state.draft_text, None);
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_backspace_with_shift_removes_whole_word() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("hello brave world", None).await;
        if let AppMode::Prompt { history_state, .. } = &mut app.mode {
            history_state.draft_text = Some("draft".to_string());
            history_state.entries = vec!["first".to_string(), "second".to_string()];
            history_state.selected_index = Some(1);
        }

        // Act
        let key = KeyEvent::new(KeyCode::Backspace, event::KeyModifiers::SHIFT);
        handle_prompt_backspace(&mut app, key);

        // Assert
        if let AppMode::Prompt {
            history_state,
            input,
            ..
        } = &app.mode
        {
            assert_eq!(input.text(), "hello brave");
            assert_eq!(history_state.selected_index, None);
            assert_eq!(history_state.draft_text, None);
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_delete_removes_whole_image_token_and_attachment() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("Review ", None).await;
        insert_pasted_image_placeholder(&mut app, std::path::PathBuf::from("/tmp/image-1.png"));
        if let AppMode::Prompt {
            history_state,
            input,
            ..
        } = &mut app.mode
        {
            history_state.selected_index = Some(0);
            history_state.draft_text = Some("draft".to_string());
            input.cursor = "Review ".chars().count();
        }

        // Act
        handle_prompt_delete(&mut app);

        // Assert
        if let AppMode::Prompt {
            attachment_state,
            history_state,
            input,
            ..
        } = &app.mode
        {
            assert_eq!(input.text(), "Review ");
            assert!(attachment_state.attachments.is_empty());
            assert_eq!(attachment_state.next_attachment_number, 1);
            assert_eq!(history_state.selected_index, None);
            assert_eq!(history_state.draft_text, None);
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_delete_reuses_deleted_image_number_on_next_paste() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("", None).await;
        insert_pasted_image_placeholder(&mut app, std::path::PathBuf::from("/tmp/image-1.png"));
        insert_pasted_image_placeholder(&mut app, std::path::PathBuf::from("/tmp/image-2.png"));
        insert_pasted_image_placeholder(&mut app, std::path::PathBuf::from("/tmp/image-3.png"));
        if let AppMode::Prompt { input, .. } = &mut app.mode {
            input.cursor = "[Image #1][Image #2]".chars().count();
        }

        // Act
        handle_prompt_delete(&mut app);
        insert_pasted_image_placeholder(&mut app, std::path::PathBuf::from("/tmp/image-4.png"));

        // Assert
        if let AppMode::Prompt {
            attachment_state,
            input,
            ..
        } = &app.mode
        {
            assert_eq!(input.text(), "[Image #1][Image #2][Image #3]");
            assert_eq!(attachment_state.attachments.len(), 3);
            assert_eq!(attachment_state.next_attachment_number, 4);
            assert_eq!(attachment_state.attachments[2].placeholder, "[Image #3]");
            assert_eq!(
                attachment_state.attachments[2].local_image_path,
                std::path::PathBuf::from("/tmp/image-4.png")
            );
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_backspace_with_alt_removes_whole_word() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("hello brave world", None).await;
        if let AppMode::Prompt { history_state, .. } = &mut app.mode {
            history_state.draft_text = Some("draft".to_string());
            history_state.entries = vec!["first".to_string(), "second".to_string()];
            history_state.selected_index = Some(1);
        }

        // Act
        let key = KeyEvent::new(KeyCode::Backspace, event::KeyModifiers::ALT);
        handle_prompt_backspace(&mut app, key);

        // Assert
        if let AppMode::Prompt {
            history_state,
            input,
            ..
        } = &app.mode
        {
            assert_eq!(input.text(), "hello brave");
            assert_eq!(history_state.selected_index, None);
            assert_eq!(history_state.draft_text, None);
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_backspace_with_super_deletes_full_line() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("first line\nsecond line", None).await;
        if let AppMode::Prompt { history_state, .. } = &mut app.mode {
            history_state.draft_text = Some("draft".to_string());
            history_state.entries = vec!["first".to_string(), "second".to_string()];
            history_state.selected_index = Some(1);
        }
        if let AppMode::Prompt { input, .. } = &mut app.mode {
            input.cursor = "first line\nsecond".chars().count();
        }

        // Act
        let key = KeyEvent::new(KeyCode::Backspace, event::KeyModifiers::SUPER);
        handle_prompt_backspace(&mut app, key);

        // Assert
        if let AppMode::Prompt {
            history_state,
            input,
            ..
        } = &app.mode
        {
            assert_eq!(input.text(), "first line");
            assert_eq!(history_state.selected_index, None);
            assert_eq!(history_state.draft_text, None);
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_line_delete_with_ctrl_u_deletes_full_line() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("first line\nsecond line", None).await;
        if let AppMode::Prompt { history_state, .. } = &mut app.mode {
            history_state.draft_text = Some("draft".to_string());
            history_state.entries = vec!["first".to_string(), "second".to_string()];
            history_state.selected_index = Some(1);
        }
        if let AppMode::Prompt { input, .. } = &mut app.mode {
            input.cursor = "first line\nsecond".chars().count();
        }

        // Act
        handle_prompt_line_delete(&mut app);

        // Assert
        if let AppMode::Prompt {
            history_state,
            input,
            ..
        } = &app.mode
        {
            assert_eq!(input.text(), "first line");
            assert_eq!(history_state.selected_index, None);
            assert_eq!(history_state.draft_text, None);
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_backspace_with_shift_removes_whitespace_separators() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("hello\t \nworld", None).await;
        if let AppMode::Prompt { history_state, .. } = &mut app.mode {
            history_state.draft_text = Some("draft".to_string());
            history_state.entries = vec!["first".to_string(), "second".to_string()];
            history_state.selected_index = Some(1);
        }

        // Act
        let key = KeyEvent::new(KeyCode::Backspace, event::KeyModifiers::SHIFT);
        handle_prompt_backspace(&mut app, key);

        // Assert
        if let AppMode::Prompt {
            history_state,
            input,
            ..
        } = &app.mode
        {
            assert_eq!(input.text(), "hello");
            assert_eq!(history_state.selected_index, None);
            assert_eq!(history_state.draft_text, None);
        }
    }

    #[test]
    fn test_is_active_at_mention_true_for_valid_query() {
        // Arrange
        let at_mention_state = Some(PromptAtMentionState::new(Vec::new()));
        let input = InputState::with_text("@read".to_string());

        // Act
        let result = is_active_at_mention(at_mention_state.as_ref(), &input);

        // Assert
        assert!(result);
    }

    #[test]
    fn test_is_active_at_mention_false_for_email_pattern() {
        // Arrange
        let at_mention_state = Some(PromptAtMentionState::new(Vec::new()));
        let input = InputState::with_text("email@test".to_string());

        // Act
        let result = is_active_at_mention(at_mention_state.as_ref(), &input);

        // Assert
        assert!(!result);
    }

    #[test]
    fn test_is_active_at_mention_false_without_state() {
        // Arrange
        let at_mention_state = None;
        let input = InputState::with_text("@read".to_string());

        // Act
        let result = is_active_at_mention(at_mention_state.as_ref(), &input);

        // Assert
        assert!(!result);
    }

    #[tokio::test]
    async fn test_prompt_context_marks_email_pattern_as_inactive_mention() {
        // Arrange
        let state = PromptAtMentionState::new(Vec::new());
        let (mut app, _base_dir) = new_test_prompt_app("email@test", Some(state)).await;

        // Act
        let context = prompt_context(&mut app).expect("expected prompt context");

        // Assert
        assert!(!context.is_at_mention());
    }

    #[tokio::test]
    async fn test_prompt_context_falls_back_to_list_when_session_is_missing() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("follow up", None).await;
        app.mode = AppMode::Prompt {
            at_mention_state: None,
            attachment_state: PromptAttachmentState::default(),
            history_state: PromptHistoryState::new(Vec::new()),
            review_status_message: None,
            review_text: None,
            input: InputState::with_text("follow up".to_string()),
            session_id: "missing-session".into(),
            slash_state: PromptSlashState::default(),
            scroll_offset: Some(2),
        };

        // Act
        let context = prompt_context(&mut app);

        // Assert
        assert!(context.is_none());
        assert!(matches!(app.mode, AppMode::List));
    }

    #[tokio::test]
    async fn test_handle_at_mention_select_dismisses_stale_mention_state() {
        // Arrange
        let state = PromptAtMentionState::new(vec![FileEntry {
            is_dir: false,
            path: "src/main.rs".to_string(),
        }]);
        let (mut app, _base_dir) = new_test_prompt_app("email@test", Some(state)).await;

        // Act
        handle_at_mention_select(&mut app);

        // Assert
        assert!(matches!(app.mode, AppMode::Prompt { .. }));
        if let AppMode::Prompt {
            at_mention_state,
            input,
            ..
        } = &app.mode
        {
            assert!(at_mention_state.is_none());
            assert_eq!(input.text(), "email@test");
        }
    }

    #[tokio::test]
    async fn test_handle_at_mention_select_inserts_directory_with_trailing_slash() {
        // Arrange
        let state = PromptAtMentionState::new(vec![FileEntry {
            is_dir: true,
            path: "src".to_string(),
        }]);
        let (mut app, _base_dir) = new_test_prompt_app("@src", Some(state)).await;

        // Act
        handle_at_mention_select(&mut app);

        // Assert
        assert!(matches!(app.mode, AppMode::Prompt { .. }));
        if let AppMode::Prompt { input, .. } = &app.mode {
            assert_eq!(input.text(), "@src/ ");
        }
    }

    /// Verifies stale at-mention selections are clamped to the filtered entry
    /// list before insertion.
    #[tokio::test]
    async fn test_handle_at_mention_select_clamps_stale_selected_index() {
        // Arrange
        let mut state = PromptAtMentionState::new(vec![
            FileEntry {
                is_dir: false,
                path: "src/main.rs".to_string(),
            },
            FileEntry {
                is_dir: false,
                path: "tests/main.rs".to_string(),
            },
        ]);
        state.selected_index = 9;
        let (mut app, _base_dir) = new_test_prompt_app("@src/ma", Some(state)).await;

        // Act
        handle_at_mention_select(&mut app);

        // Assert
        if let AppMode::Prompt {
            at_mention_state,
            input,
            ..
        } = &app.mode
        {
            assert!(at_mention_state.is_none());
            assert_eq!(input.text(), "@src/main.rs ");
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_char_activates_and_clears_at_mention_state() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("", None).await;

        // Act
        handle_prompt_char(&mut app, '@');

        // Assert
        assert!(matches!(app.mode, AppMode::Prompt { .. }));
        if let AppMode::Prompt {
            at_mention_state, ..
        } = &app.mode
        {
            assert!(at_mention_state.is_some());
        }

        // Act
        handle_prompt_char(&mut app, ' ');

        // Assert
        assert!(matches!(app.mode, AppMode::Prompt { .. }));
        if let AppMode::Prompt {
            at_mention_state, ..
        } = &app.mode
        {
            assert!(at_mention_state.is_none());
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_char_loads_at_mention_entries_from_project_root_for_draft_session()
    {
        // Arrange
        let (mut app, base_dir) = new_test_draft_prompt_app("", None).await;
        let expected_path = "draft_lookup_target.txt";
        std::fs::write(base_dir.path().join(expected_path), "draft")
            .expect("failed to write project file");
        assert!(!app.sessions.sessions[0].folder.exists());

        // Act
        handle_prompt_char(&mut app, '@');
        let next_event = wait_for_at_mention_entries_event(&mut app).await;

        // Assert
        match next_event {
            crate::app::AppEvent::AtMentionEntriesLoaded {
                entries,
                session_id,
            } => {
                assert_eq!(session_id, app.sessions.sessions[0].id.as_str());
                assert!(entries.contains(&FileEntry {
                    is_dir: false,
                    path: expected_path.to_string(),
                }));
            }
            _ => unreachable!("expected at-mention entries event"),
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_left_reactivates_existing_at_mention_without_cached_state() {
        // Arrange
        let input_text = "@src/main.rs more";
        let (mut app, _base_dir) = new_test_prompt_app(input_text, None).await;
        let moves_back_into_mention = " more".chars().count();

        // Act
        for _ in 0..moves_back_into_mention {
            handle_prompt_left(
                &mut app,
                KeyEvent::new(KeyCode::Left, event::KeyModifiers::NONE),
            );
        }

        // Assert
        if let AppMode::Prompt {
            at_mention_state,
            input,
            ..
        } = &app.mode
        {
            assert_eq!(input.cursor, "@src/main.rs".chars().count());
            assert!(at_mention_state.is_some());
        }
    }

    #[tokio::test]
    async fn test_handle_prompt_cancel_key_deletes_blank_session() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("", None).await;
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");
        assert!(prompt_context.is_new_session());
        assert_eq!(app.sessions.sessions.len(), 1);

        // Act
        handle_prompt_cancel_key(&mut app, &prompt_context).await;

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

    #[tokio::test]
    async fn test_handle_prompt_cancel_key_keeps_empty_draft_session() {
        // Arrange
        let (mut app, _base_dir) = new_test_draft_prompt_app("", None).await;
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");
        assert!(prompt_context.is_new_session());
        assert!(!prompt_context.can_delete_on_cancel());
        assert_eq!(app.sessions.sessions.len(), 1);

        // Act
        handle_prompt_cancel_key(&mut app, &prompt_context).await;

        // Assert
        assert!(matches!(app.mode, AppMode::View { .. }));
        assert_eq!(app.sessions.sessions.len(), 1);
        assert_eq!(
            app.sessions.sessions[0].status,
            crate::domain::session::Status::Draft
        );
        assert!(app.sessions.sessions[0].prompt.is_empty());
    }

    #[tokio::test]
    async fn test_handle_prompt_submit_key_ignores_empty_prompt() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("", None).await;
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");

        // Act
        handle_prompt_submit_key(&mut app, &prompt_context).await;

        // Assert
        assert!(matches!(app.mode, AppMode::Prompt { .. }));
        assert_eq!(app.sessions.sessions.len(), 1);
        assert_eq!(app.sessions.sessions[0].prompt, "");
    }

    #[tokio::test]
    async fn test_handle_prompt_submit_key_drains_supported_image_turn() {
        // Arrange
        let (mut app, _base_dir) = new_test_draft_prompt_app("Review ", None).await;
        app.sessions.sessions[0].model = crate::domain::agent::AgentModel::ClaudeSonnet46;
        insert_pasted_image_placeholder(&mut app, std::path::PathBuf::from("/tmp/image-1.png"));
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");

        // Act
        handle_prompt_submit_key(&mut app, &prompt_context).await;

        // Assert
        assert!(matches!(app.mode, AppMode::View { .. }));
        assert_eq!(app.sessions.sessions[0].prompt, "Review [Image #1]");
        assert_eq!(
            app.sessions.sessions[0].status,
            crate::domain::session::Status::Draft
        );
        assert_eq!(app.sessions.sessions[0].draft_attachments.len(), 1);
        assert_eq!(
            app.sessions.sessions[0].draft_attachments[0].placeholder,
            "[Image #1]"
        );
    }

    #[tokio::test]
    async fn test_handle_prompt_submit_key_starts_regular_session_with_image_turn() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("Review ", None).await;
        app.sessions.sessions[0].model = crate::domain::agent::AgentModel::ClaudeSonnet46;
        insert_pasted_image_placeholder(&mut app, std::path::PathBuf::from("/tmp/image-1.png"));
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");

        // Act
        handle_prompt_submit_key(&mut app, &prompt_context).await;

        // Assert
        assert!(matches!(app.mode, AppMode::View { .. }));
        assert_eq!(app.sessions.sessions[0].prompt, "Review [Image #1]");
        assert_eq!(
            app.sessions.sessions[0].title.as_deref(),
            Some("Review [Image #1]")
        );
        assert!(app.sessions.sessions[0].draft_attachments.is_empty());
    }

    #[tokio::test]
    async fn test_handle_prompt_submit_key_clears_cached_review_output() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("follow up", None).await;
        let session_id = app.sessions.sessions[0].id.clone();
        app.review_cache.insert(
            session_id.clone(),
            crate::app::ReviewCacheEntry::Ready {
                diff_hash: 7,
                text: "Focused review".to_string(),
            },
        );
        if let AppMode::Prompt {
            review_status_message,
            review_text,
            ..
        } = &mut app.mode
        {
            *review_status_message = None;
            *review_text = Some("Focused review".to_string());
        }
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");

        // Act
        handle_prompt_submit_key(&mut app, &prompt_context).await;

        // Assert
        assert!(matches!(
            app.mode,
            AppMode::View {
                review_status_message: None,
                review_text: None,
                ..
            }
        ));
        assert!(!app.review_cache.contains_key(session_id.as_str()));
    }

    #[tokio::test]
    async fn test_handle_prompt_submit_key_replies_after_started_draft_session_reaches_review() {
        // Arrange
        let (mut app, _base_dir) = new_test_draft_prompt_app("follow up", None).await;
        app.sessions.sessions[0].status = crate::domain::session::Status::Review;
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");

        // Act
        handle_prompt_submit_key(&mut app, &prompt_context).await;

        // Assert
        assert!(!prompt_context.is_draft_session());
        assert!(matches!(app.mode, AppMode::View { .. }));
        assert!(
            !app.sessions.sessions[0]
                .output
                .contains("Only `Draft` sessions can stage drafts")
        );
    }

    #[tokio::test]
    async fn test_handle_prompt_cancel_key_keeps_new_session_with_staged_drafts() {
        // Arrange
        let (mut app, _base_dir) = new_test_draft_prompt_app("Another draft", None).await;
        app.sessions.sessions[0].prompt = "First draft".to_string();
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");

        // Act
        handle_prompt_cancel_key(&mut app, &prompt_context).await;

        // Assert
        assert!(matches!(app.mode, AppMode::View { .. }));
        assert_eq!(app.sessions.sessions.len(), 1);
    }

    #[tokio::test]
    async fn test_handle_prompt_cancel_key_restores_review_output() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("follow up", None).await;
        app.sessions.sessions[0].status = crate::domain::session::Status::Review;
        if let AppMode::Prompt {
            review_status_message,
            review_text,
            ..
        } = &mut app.mode
        {
            *review_status_message = None;
            *review_text = Some("Focused review".to_string());
        }
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");

        // Act
        handle_prompt_cancel_key(&mut app, &prompt_context).await;

        // Assert
        assert!(matches!(
            app.mode,
            AppMode::View {
                review_status_message: None,
                review_text: Some(ref review_text),
                ..
            } if review_text == "Focused review"
        ));
    }

    #[tokio::test]
    async fn test_handle_prompt_cancel_key_resets_existing_session_draft_attachments() {
        // Arrange
        let (mut app, base_dir) = new_test_prompt_app("Review ", None).await;
        app.sessions.sessions[0].prompt = "Earlier prompt".to_string();
        app.sessions.sessions[0].status = crate::domain::session::Status::Review;
        let image_directory = base_dir.path().join("images");
        std::fs::create_dir_all(&image_directory).expect("image directory should exist");
        let image_path = image_directory.join("image-1.png");
        std::fs::write(&image_path, b"png").expect("image file should be written");
        insert_pasted_image_placeholder(&mut app, image_path.clone());
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");

        // Act
        handle_prompt_cancel_key(&mut app, &prompt_context).await;

        // Assert
        assert!(matches!(app.mode, AppMode::View { .. }));
        assert!(image_path.exists());
        assert!(image_directory.exists());
    }

    #[test]
    fn test_format_duration_zero() {
        // Arrange & Act
        let result = format_duration(0);

        // Assert
        assert_eq!(result, "00:00:00");
    }

    #[test]
    fn test_format_duration_mixed() {
        // Arrange & Act
        let result = format_duration(3661);

        // Assert
        assert_eq!(result, "01:01:01");
    }

    #[test]
    fn test_format_duration_large() {
        // Arrange & Act
        let result = format_duration(86400);

        // Assert
        assert_eq!(result, "24:00:00");
    }

    #[test]
    fn test_format_stats_metric_line_uses_tab_delimiter() {
        // Arrange & Act
        let session_line = format_stats_metric_line("Session ID", "session-id");
        let error_line = format_stats_metric_line("Error", "boom");

        // Assert
        assert_eq!(session_line, "Session ID\tsession-id");
        assert_eq!(error_line, "Error\tboom");
    }

    #[test]
    fn test_build_stats_markdown_renders_aligned_usage_table_without_box() {
        // Arrange
        let usage_rows_result = Ok(vec![TokenUsageRow {
            in_tokens: "1.2k".to_string(),
            model: "gemini-2.5-flash".to_string(),
            out_tokens: "650".to_string(),
        }]);

        // Act
        let result = build_stats_markdown("session-id", "00:20:15", usage_rows_result);

        // Assert
        assert!(result.starts_with("\n## Session Stats\n\n```stats\n"));
        assert!(result.contains("Session ID\tsession-id"));
        assert!(result.contains("Session Time\t00:20:15"));
        assert!(result.contains("Tokens Usage"));
        assert!(result.contains("Model"));
        assert!(result.contains("gemini-2.5-flash"));
        assert!(result.contains("1.2k"));
        assert!(result.contains("650"));
        assert!(!result.contains('+'));
        assert!(!result.contains('|'));

        let session_id_index = result.find("Session ID").expect("expected session id");
        let session_time_index = result.find("Session Time").expect("expected session time");
        let token_usage_index = result
            .find("Tokens Usage")
            .expect("expected token usage title");
        let model_header_index = result.find("Model").expect("expected model header");

        assert!(session_id_index < session_time_index);
        assert!(session_time_index < token_usage_index);
        assert!(token_usage_index < model_header_index);
    }

    #[test]
    fn test_build_stats_markdown_renders_no_usage_message() {
        // Arrange
        let usage_rows_result = Ok(Vec::new());

        // Act
        let result = build_stats_markdown("session-id", "00:20:15", usage_rows_result);

        // Assert
        assert!(result.contains("Tokens Usage"));
        assert!(result.contains("No token usage recorded."));
    }

    #[test]
    fn test_build_apply_review_prompt_requires_verification_before_apply() {
        // Arrange
        let suggestions = "- Fix the typo in `README.md`.";

        // Act
        let prompt = build_apply_review_prompt(suggestions);

        // Assert
        assert!(
            prompt
                .text
                .contains("Verify the following focused-review suggestions"),
        );
        assert!(
            prompt
                .text
                .contains("Apply only the suggestions that are still correct and relevant"),
        );
        assert!(prompt.text.contains(suggestions));
    }

    #[tokio::test]
    async fn test_handle_apply_command_rejects_when_session_not_in_review_status() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("/apply", None).await;
        let session_id = app.sessions.sessions[0].id.clone();
        app.review_cache.insert(
            session_id.clone(),
            crate::app::ReviewCacheEntry::Ready {
                diff_hash: 0,
                text: "## Review\n### Suggestions\n- Fix the typo.".to_string(),
            },
        );
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");

        // Act
        handle_apply_command(&mut app, &prompt_context).await;

        // Assert
        assert!(matches!(app.mode, AppMode::Prompt { .. }));
        assert!(app.review_cache.contains_key(session_id.as_str()));
    }

    #[tokio::test]
    async fn test_handle_apply_command_rejects_without_cached_review() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("/apply", None).await;
        app.sessions.sessions[0].status = crate::domain::session::Status::Review;
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");

        // Act
        handle_apply_command(&mut app, &prompt_context).await;

        // Assert
        assert!(matches!(app.mode, AppMode::Prompt { .. }));
    }

    #[tokio::test]
    async fn test_handle_apply_command_invalidates_cache_when_diff_hash_mismatches() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("/apply", None).await;
        app.sessions.sessions[0].status = crate::domain::session::Status::Review;
        let session_id = app.sessions.sessions[0].id.clone();
        app.review_cache.insert(
            session_id.clone(),
            crate::app::ReviewCacheEntry::Ready {
                diff_hash: u64::MAX,
                text: "## Review\n### Suggestions\n- Fix the typo.".to_string(),
            },
        );
        if let AppMode::Prompt {
            review_status_message,
            review_text,
            ..
        } = &mut app.mode
        {
            *review_status_message = Some("stale status".to_string());
            *review_text = Some("## Review\n### Suggestions\n- Fix the typo.".to_string());
        }
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");

        // Act
        handle_apply_command(&mut app, &prompt_context).await;

        // Assert
        assert!(!app.review_cache.contains_key(session_id.as_str()));
        let AppMode::Prompt {
            review_status_message,
            review_text,
            ..
        } = &app.mode
        else {
            unreachable!("expected AppMode::Prompt after stale-hash bail-out");
        };
        assert!(
            review_status_message.is_none(),
            "stale review status must be cleared so cancel cannot restore it",
        );
        assert!(
            review_text.is_none(),
            "stale review text must be cleared so cancel cannot restore it",
        );
    }

    #[tokio::test]
    async fn test_handle_apply_command_submits_suggestions_when_diff_hash_matches() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("/apply", None).await;
        app.sessions.sessions[0].status = crate::domain::session::Status::Review;
        let session_id = app.sessions.sessions[0].id.clone();
        let folder = app.sessions.sessions[0].folder.clone();
        let base_branch = app.sessions.sessions[0].base_branch.clone();
        let current_diff = app
            .services
            .git_client()
            .diff(folder, base_branch)
            .await
            .unwrap_or_default();
        let current_hash = crate::app::diff_content_hash(&current_diff);
        app.review_cache.insert(
            session_id.clone(),
            crate::app::ReviewCacheEntry::Ready {
                diff_hash: current_hash,
                text: "## Review\n### Suggestions\n- Fix the typo in `README.md`.".to_string(),
            },
        );
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");

        // Act
        handle_apply_command(&mut app, &prompt_context).await;

        // Assert
        assert!(!app.review_cache.contains_key(session_id.as_str()));
        assert!(matches!(app.mode, AppMode::View { .. }));
    }

    #[tokio::test]
    async fn test_handle_apply_command_preserves_cache_on_git_diff_error() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("/apply", None).await;
        app.sessions.sessions[0].status = crate::domain::session::Status::Review;
        let session_id = app.sessions.sessions[0].id.clone();
        app.review_cache.insert(
            session_id.clone(),
            crate::app::ReviewCacheEntry::Ready {
                diff_hash: 42,
                text: "## Review\n### Suggestions\n- Fix the typo in `README.md`.".to_string(),
            },
        );

        let mut mock_git_client = crate::infra::git::MockGitClient::new();
        mock_git_client.expect_diff().returning(|_, _| {
            Box::pin(async {
                Err(crate::infra::git::GitError::OutputParse(
                    "simulated git failure".to_string(),
                ))
            })
        });
        install_mock_git_client(&mut app, mock_git_client);

        let prompt_context = prompt_context(&mut app).expect("expected prompt context");

        // Act
        handle_apply_command(&mut app, &prompt_context).await;

        // Assert
        assert!(matches!(app.mode, AppMode::Prompt { .. }));
        assert!(
            matches!(
                app.review_cache.get(session_id.as_str()),
                Some(crate::app::ReviewCacheEntry::Ready { diff_hash: 42, .. }),
            ),
            "cached review must survive a transient git diff error",
        );
    }

    #[tokio::test]
    /// Verifies that when the active session is `InProgress`, a leading `/`
    /// is demoted from slash-command mode to plain text so submission
    /// queues the prompt instead of executing a slash command against the
    /// running turn.
    async fn test_prompt_context_demotes_slash_command_to_text_when_session_is_in_progress() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("/model", None).await;
        app.sessions.sessions[0].status = crate::domain::session::Status::InProgress;

        // Act
        let context = prompt_context(&mut app).expect("expected prompt context");

        // Assert
        assert!(
            !context.is_slash_command(),
            "slash command mode must be demoted while session is InProgress"
        );
        assert_eq!(context.input_mode, PromptInputMode::Text);
    }

    #[tokio::test]
    /// Verifies that the slash-command gate only fires for `InProgress`
    /// sessions: when status is `Review`, a leading `/` is still recognized
    /// as a slash command so the existing slash submit path keeps working.
    async fn test_prompt_context_keeps_slash_command_when_session_is_review() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("/model", None).await;
        app.sessions.sessions[0].status = crate::domain::session::Status::Review;

        // Act
        let context = prompt_context(&mut app).expect("expected prompt context");

        // Assert
        assert!(
            context.is_slash_command(),
            "slash command mode must remain active when session is not InProgress"
        );
        assert_eq!(context.input_mode, PromptInputMode::SlashCommand);
    }

    #[tokio::test]
    /// Verifies that submitting a `/`-prefixed prompt while the session is
    /// `InProgress` queues the raw text via [`App::enqueue_message`] instead
    /// of invoking the slash command path.
    async fn test_handle_prompt_submit_key_queues_slash_text_when_session_is_in_progress() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("/model gpt-5", None).await;
        let session_id = app.sessions.sessions[0].id.clone();
        app.sessions.handles.insert(
            session_id.clone(),
            crate::domain::session::SessionHandles::new(
                String::new(),
                crate::domain::session::Status::InProgress,
            ),
        );
        app.sessions.sessions[0].status = crate::domain::session::Status::InProgress;
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");

        // Act
        handle_prompt_submit_key(&mut app, &prompt_context).await;

        // Assert
        let queued_len = app
            .sessions
            .handles
            .get(session_id.as_str())
            .expect("handles for in-progress session")
            .queued_messages
            .lock()
            .expect("queue lock")
            .len();
        assert_eq!(
            queued_len, 1,
            "slash-prefixed input must be queued as plain text while turn runs"
        );
        assert_eq!(app.sessions.sessions[0].queued_messages.len(), 1);
        assert_eq!(
            app.sessions.sessions[0].queued_messages[0], "/model gpt-5",
            "queued message preserves the original slash-prefixed text"
        );
    }

    #[tokio::test]
    async fn test_handle_prompt_slash_submit_preserves_attachments_when_apply_bails_out() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("/apply", None).await;
        if let AppMode::Prompt {
            attachment_state, ..
        } = &mut app.mode
        {
            attachment_state
                .attachments
                .push(crate::domain::composer::PromptAttachment::new(
                    1,
                    std::path::PathBuf::from("/tmp/nonexistent-test-attachment.png"),
                ));
        }
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");

        // Act
        handle_prompt_slash_submit(&mut app, &prompt_context).await;

        // Assert
        let AppMode::Prompt {
            attachment_state, ..
        } = &app.mode
        else {
            unreachable!("expected AppMode::Prompt after /apply bail-out");
        };
        assert_eq!(
            attachment_state.attachments.len(),
            1,
            "attachments must survive validation failure so the user keeps their pasted files",
        );
    }

    #[tokio::test]
    async fn test_handle_prompt_slash_submit_ignores_apply_when_suggestions_are_empty() {
        // Arrange
        let (mut app, _base_dir) = new_test_prompt_app("/apply", None).await;
        app.sessions.sessions[0].status = crate::domain::session::Status::Review;
        let session_id = app.sessions.sessions[0].id.clone();
        app.review_cache.insert(
            session_id.clone(),
            crate::app::ReviewCacheEntry::Ready {
                diff_hash: 0,
                text: "## Review\n### Suggestions\n- None".to_string(),
            },
        );
        let prompt_context = prompt_context(&mut app).expect("expected prompt context");

        // Act
        handle_prompt_slash_submit(&mut app, &prompt_context).await;

        // Assert
        let AppMode::Prompt {
            input, slash_state, ..
        } = &app.mode
        else {
            unreachable!("expected AppMode::Prompt after unavailable /apply");
        };
        assert_eq!(input.text(), "/apply");
        assert_eq!(*slash_state, PromptSlashState::default());
        assert!(
            matches!(
                app.review_cache.get(session_id.as_str()),
                Some(crate::app::ReviewCacheEntry::Ready { .. }),
            ),
            "unavailable /apply should not consume the cached review",
        );
    }
}