bcode_tui 0.0.1-alpha.0

Terminal user interface for bcode
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
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
//! Background effect runner for TUI work that may touch daemon/client services.

use std::collections::{BTreeMap, VecDeque};

use bcode_client::{BcodeClient, ClientError, MessageAcceptance};
use bcode_ipc::{ComposerDraftScope, PermissionSummary, PromptPlacement};
use bcode_session_models::{
    ProjectionWindowAnchor, ProjectionWindowDirection, ProjectionWindowLimits,
    ProjectionWindowRequest, ProjectionWindowTarget, SessionHistoryCursor, SessionHistoryPage,
    SessionId, SessionProjectionKind, SessionSummary, WorkId,
};
use bcode_session_view::execute_session_view_action;
use bcode_session_view_models::{SessionViewAction, SessionViewActionOutcome};
use bcode_skill_models::SkillId;
use bcode_worktree_models::WorktreeCreateRequest;

use tokio::sync::{mpsc, oneshot};
use tokio::task::JoinHandle;

use super::{
    TuiError, clipboard_image, history_flow,
    session_flow::{self, AgentCatalog},
    slash_palette,
};

const TRANSCRIPT_PAGE_TARGET_ITEMS: usize = 4;
const TRANSCRIPT_PAGE_MAX_ITEMS: usize = 16;
const TRANSCRIPT_PAGE_TARGET_ROWS: usize = 24;
const TRANSCRIPT_PAGE_MAX_EVENTS_SCANNED: usize = 512;
const TRANSCRIPT_PAGE_MAX_BYTES: usize = 512 * 1024;

async fn load_transcript_history_page(
    client: &BcodeClient,
    session_id: SessionId,
    cursor: SessionHistoryCursor,
    width_columns: u16,
    older: bool,
) -> Result<
    (
        SessionHistoryPage,
        Vec<bcode_session_models::SubmissionRecord>,
    ),
    ClientError,
> {
    let (anchor, direction) = if older {
        (
            ProjectionWindowAnchor::BeforeSequence(cursor.sequence.saturating_add(1)),
            ProjectionWindowDirection::Backward,
        )
    } else {
        (
            ProjectionWindowAnchor::AfterSequence(cursor.sequence.saturating_sub(1)),
            ProjectionWindowDirection::Forward,
        )
    };
    let page = client
        .session_projection_history_page(
            session_id,
            ProjectionWindowRequest {
                projection: SessionProjectionKind::Transcript,
                anchor,
                direction,
                target: ProjectionWindowTarget {
                    min_items: Some(TRANSCRIPT_PAGE_TARGET_ITEMS),
                    min_estimated_rows: Some(TRANSCRIPT_PAGE_TARGET_ROWS),
                    min_bytes: None,
                    width_columns: Some(width_columns.max(1)),
                },
                limits: ProjectionWindowLimits {
                    max_items: TRANSCRIPT_PAGE_MAX_ITEMS,
                    max_events_scanned: TRANSCRIPT_PAGE_MAX_EVENTS_SCANNED,
                    max_bytes: TRANSCRIPT_PAGE_MAX_BYTES,
                },
            },
        )
        .await?;
    let page = projection_page_as_history_page(session_id, cursor, older, page)?;
    let records = client
        .submissions_for_history(session_id, &page.events)
        .await?;
    Ok((page, records))
}

fn projection_page_as_history_page(
    session_id: SessionId,
    cursor: SessionHistoryCursor,
    older: bool,
    page: bcode_session_models::ProjectionHistoryPage,
) -> Result<SessionHistoryPage, ClientError> {
    let has_more = if older {
        page.window.has_older
    } else {
        page.window.has_newer
    };
    let expected_boundary = page.window.source_range.map(|range| {
        if older {
            // The request anchors at cursor + 1, so a canonical contiguous
            // page ends at cursor itself (not cursor - 1).
            range.end_sequence == cursor.sequence
        } else {
            range.start_sequence == cursor.sequence
        }
    });
    if page.session_id != session_id
        || page.window.projection != SessionProjectionKind::Transcript
        || page.events.is_empty() && has_more
        || page.window.source_range.is_some() == page.events.is_empty()
        || expected_boundary == Some(false)
        || page.window.source_range.is_some_and(|range| {
            page.events.first().map(|event| event.sequence) != Some(range.start_sequence)
                || page.events.last().map(|event| event.sequence) != Some(range.end_sequence)
                || page
                    .events
                    .iter()
                    .any(|event| event.session_id != session_id)
                || page
                    .events
                    .windows(2)
                    .any(|pair| pair[0].sequence >= pair[1].sequence)
        })
    {
        return Err(ClientError::Protocol(
            "inconsistent projection history page boundary".to_owned(),
        ));
    }
    Ok(SessionHistoryPage {
        session_id,
        events: page.events,
        compatibility_issues: Vec::new(),
        next_cursor: None,
        has_more,
    })
}

/// Submit-message effect request payload.
pub struct SubmitMessageRequest {
    /// Stable identity allocated with the optimistic composer item.
    pub submission_id: bcode_session_models::SubmissionId,
    /// Existing session, if already attached.
    pub session_id: Option<SessionId>,
    /// Working directory to use when creating a draft session.
    pub launch_working_directory: std::path::PathBuf,
    /// Message text to submit.
    pub message: String,
    /// Prompt placement semantics.
    pub placement: PromptPlacement,
    /// Provider to apply before sending, if any.
    pub provider_plugin_id: Option<String>,
    /// Model to apply before sending, if any.
    pub model_id: Option<String>,
    /// Agent to apply before sending, if any.
    pub agent_id: Option<String>,
    /// Reasoning effort to apply before sending.
    pub reasoning_effort: Option<String>,
    /// Reasoning summary to apply before sending.
    pub reasoning_summary: Option<String>,
    /// Reasoning effort generation captured by this submission, if locally pending.
    pub reasoning_effort_generation: Option<u64>,
    /// Launch-scoped execution defaults for this exact turn.
    pub execution: bcode_session_models::TurnExecutionOptions,
    /// Event sender for a newly-created session stream.
    pub event_sender: mpsc::Sender<super::history_flow::SessionStreamUpdate>,
}

/// Skill action kind requested by the TUI.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SkillActionKind {
    /// Activate the skill for the session.
    Activate,
    /// Deactivate the skill for the session.
    Deactivate,
    /// Invoke the skill for one turn.
    Invoke,
}

/// Skill action effect request payload.
pub struct SkillActionRequest {
    /// Existing session, if already attached.
    pub session_id: Option<SessionId>,
    /// Working directory to use when creating a draft session.
    pub launch_working_directory: std::path::PathBuf,
    /// Skill to act on.
    pub skill_id: SkillId,
    /// Skill action kind.
    pub action: SkillActionKind,
    /// Arguments for invocation.
    pub arguments: String,
    /// Provider to apply before invoking a skill, if any.
    pub provider_plugin_id: Option<String>,
    /// Model to apply before invoking a skill, if any.
    pub model_id: Option<String>,
    /// Agent to apply before invoking a skill, if any.
    pub agent_id: Option<String>,
    /// Reasoning effort captured for the invocation.
    pub reasoning_effort: Option<String>,
    /// Reasoning summary captured for the invocation.
    pub reasoning_summary: Option<String>,
    /// Pending reasoning effort generation captured by the invocation.
    pub reasoning_effort_generation: Option<u64>,
    /// Launch-scoped execution defaults for an invoked turn.
    pub execution: bcode_session_models::TurnExecutionOptions,
    /// Event sender for a newly-created session stream.
    pub event_sender: mpsc::Sender<super::history_flow::SessionStreamUpdate>,
}

/// Background work requested by local TUI event handling.
pub enum TuiEffect {
    /// Attach to a session and start its event stream.
    OpenSession {
        /// Session to open.
        session_id: SessionId,
        /// Initial projection window request.
        initial_window_request: ProjectionWindowRequest,
        /// Event sender for the live session stream.
        event_sender: mpsc::Sender<super::history_flow::SessionStreamUpdate>,
        /// Whether this explicit open may start the daemon.
        allow_daemon_start: bool,
    },
    /// Load declarative configuration and global interactive TUI state.
    LoadConfig,
    /// Persist one interactive TUI theme selection to user state.
    PersistThemeSelection {
        /// Stable base theme id.
        name: String,
    },
    /// Clear the interactive theme selection and restore the configured default.
    ClearThemeSelection,
    /// Persist one interactive streaming-presentation policy to user state.
    PersistStreamingPresentation {
        /// Normalized renderer-neutral presentation policy.
        policy: bcode_session_view_models::StreamingPresentationPolicy,
    },
    /// Clear the interactive streaming-presentation override.
    ClearStreamingPresentation,
    /// Reconcile auth security status for a loaded config.
    ReconcileAuthSecurity {
        /// Loaded configuration.
        config: Box<bcode_config::BcodeConfig>,
    },
    /// Load draft-session status.
    LoadDraftStatus {
        /// Directory for draft-session draft scope.
        launch_working_directory: std::path::PathBuf,
    },
    /// Execute one typed targeted recovery action through the shared application boundary.
    QueueRecovery {
        session_id: SessionId,
        generation: u64,
        action: Box<SessionViewAction>,
    },
    /// Load non-critical status for an attached session.
    LoadSessionStatus {
        /// Session to hydrate.
        session_id: SessionId,
    },
    /// Refresh resolved model metadata after a model event.
    LoadSessionModelStatus { session_id: SessionId },
    /// Refresh plugin-owned status after a plugin lifecycle event.
    LoadPluginStatus { session_id: SessionId },
    /// Load agent metadata.
    LoadAgentCatalog,
    /// Load an older history page before the currently displayed timeline.
    LoadOlderHistory {
        /// Session to load.
        session_id: SessionId,
        /// Pagination cursor.
        cursor: SessionHistoryCursor,
        /// Resident window generation at request time.
        generation: u64,
        /// Width used for semantic row estimation (not terminal layout).
        width_columns: u16,
    },
    /// Load a newer history page after the currently displayed timeline.
    LoadNewerHistory {
        /// Session to load.
        session_id: SessionId,
        /// Pagination cursor.
        cursor: SessionHistoryCursor,
        /// Resident window generation at request time.
        generation: u64,
        /// Width used for semantic row estimation (not terminal layout).
        width_columns: u16,
    },
    /// Load the bounded pending-permission snapshot during attach/reconnect.
    ListPermissions,
    /// Save composer draft text for a scope.
    SaveDraft {
        /// Draft scope to save.
        scope: ComposerDraftScope,
        /// Draft text.
        text: String,
    },
    /// Load slash command completions for a composer query.
    LoadSlashPalette {
        /// Active provider scope for model discovery.
        provider_plugin_id: Option<String>,
        /// Composer discovery generation.
        generation: u64,
        /// Current slash query.
        query: String,
        /// Active session, if any.
        session_id: Option<SessionId>,
    },
    /// Load host and plugin command-palette contributions.
    LoadCommandPalette,
    /// Load one bounded direct-child page; no recursive daemon traversal.
    LoadSessionChildren {
        parent_id: SessionId,
        after: Option<SessionId>,
        generation: u64,
    },
    /// Observe normalized activity without appending transcript events.
    LoadChildActivity {
        session_id: SessionId,
        after: Option<SessionId>,
        generation: u64,
    },
    /// Load the bounded session catalog for the root session picker.
    LoadSessionPicker {
        generation: u64,
        scope: bcode_session_models::SessionDiscoveryScope,
        query: bcode_session_models::SessionCatalogQuery,
        cursor: Option<bcode_session_models::SessionCatalogCursor>,
    },
    /// Import one external session selected by the root picker.
    ImportSession {
        source_id: String,
        external_session_id: String,
    },
    /// Rename one session selected by the root picker.
    RenameSession {
        session_id: SessionId,
        name: Option<String>,
    },
    /// Delete one session selected by the root picker.
    DeleteSession { session_id: SessionId },
    /// Run one bounded transcript search from the root session picker.
    SearchSessions {
        request: Box<bcode_session_search::SessionSearchRequest>,
        policy: bcode_session_search::SessionSearchPlanPolicy,
    },
    /// Start compatibility inventory or confirmed canonical migration.
    StartBulkMigration {
        request: bcode_ipc::SessionBulkMigrationStartRequest,
    },
    /// Cooperatively cancel transient aggregate canonical migration.
    CancelBulkMigration { operation_id: String },
    /// Wait for the next transient aggregate canonical migration revision.
    WaitBulkMigration {
        operation_id: String,
        after_revision: u64,
    },
    /// Start explicit all-enabled-provider historical backfill.
    StartSearchIndexing {
        request: bcode_session_search::CompleteSessionSearchBackfillRequest,
    },
    /// Cancel transient aggregate derived-search backfill.
    CancelSearchIndexing { operation_id: String },
    /// Wait for the next transient aggregate derived-search backfill revision.
    WaitSearchIndexing {
        operation_id: String,
        after_revision: u64,
    },
    /// Execute a resolved slash command without terminal navigation.
    ExecuteSlashCommand {
        /// Current session.
        session_id: Option<SessionId>,
        /// Working directory context.
        working_directory: std::path::PathBuf,
        /// Current agent identity.
        current_agent_id: String,
        /// Current reasoning display mode.
        reasoning_display_mode: bcode_config::TuiThinkingMode,
        /// Whether reasoning is displayed.
        reasoning_visible: bool,
        /// Complete command text.
        message: String,
    },
    /// Execute one non-interactive Ralph action through the root runtime.
    RalphAction {
        /// Repository root for the Ralph lifecycle operation.
        repo_root: std::path::PathBuf,
        /// Action to execute.
        action: super::ralph_flow::RalphRootAction,
    },
    /// Create a Ralph loop from root-owned dialog input.
    RalphStart {
        /// Validated root dialog request.
        request: super::ralph_flow::RalphStartRequest,
    },
    /// Open a plugin-owned native surface for root-runtime presentation.
    OpenPluginSurface {
        /// Plugin owner.
        plugin_id: String,
        /// Surface kind.
        surface_kind: String,
        /// Instance identity.
        instance_id: String,
        /// Plugin-owned options.
        options: serde_json::Value,
        /// Working directory context.
        working_directory: std::path::PathBuf,
        /// Active session context.
        session_id: Option<SessionId>,
    },
    /// Load model providers before opening the root model picker.
    LoadModelProviders,
    /// Load portable auth-pool status before opening the subscription picker.
    LoadAuthPoolPicker,
    /// Persist or clear an auth-pool preference.
    SetAuthPoolPreference {
        pool: String,
        profile: Option<String>,
    },
    /// Explicitly consented, bounded check for exactly one selected model.
    CheckSelectedModel {
        session_id: Option<SessionId>,
        provider_plugin_id: Option<String>,
        model_id: String,
        generation: u64,
    },
    /// Load models for the selected provider.
    LoadModelPicker {
        /// Selected provider plugin, or the default provider.
        provider_plugin_id: Option<String>,
    },
    /// Load skills before opening the root skill picker.
    LoadSkillPicker,
    /// Load one skill manifest for root picker help.
    DescribeSkill {
        /// Skill to describe.
        skill_id: SkillId,
    },
    /// Load reasoning status before opening the root thinking dialog.
    LoadThinkingDialog {
        /// Current session, if any.
        session_id: Option<SessionId>,
        /// Initially focused setting.
        focus: super::thinking_dialog::ThinkingDialogFocus,
    },
    /// Load one bounded canonical milestone page for timeline navigation.
    LoadMilestones {
        request: super::timeline_dialog::MilestonePageRequest,
    },
    /// Load a bounded history window around a timeline entry.
    LoadTimelineJump {
        /// Active session.
        session_id: SessionId,
        /// Resident window generation when the jump was requested.
        generation: u64,
        /// Selected event sequence.
        sequence: u64,
    },
    /// Invoke a plugin-owned command without terminal navigation effects.
    InvokePluginCommand {
        /// Plugin owner.
        plugin_id: String,
        /// Command identifier.
        command_id: String,
        /// Optional command arguments.
        arguments: Option<String>,
        /// Working directory context.
        working_directory: std::path::PathBuf,
        /// Active session context.
        session_id: Option<SessionId>,
    },
    /// Submit a user message through the daemon-backed session pipeline.
    SubmitMessage {
        /// Submit request.
        request: Box<SubmitMessageRequest>,
    },
    /// Perform a skill action for a session.
    SkillAction {
        /// Skill action request.
        request: Box<SkillActionRequest>,
    },
    /// Set the active model for a session.
    SetSessionModel {
        /// Session to update.
        session_id: SessionId,
        /// Provider plugin id, when explicitly selected.
        provider_plugin_id: Option<String>,
        /// Model id to set.
        model_id: String,
    },
    /// Set session reasoning preferences.
    SetSessionReasoning {
        /// Session to update.
        session_id: SessionId,
        /// Optional reasoning effort.
        effort: Option<String>,
        /// Optional reasoning summary.
        summary: Option<String>,
        /// Pending effort generation staged for this update.
        effort_generation: Option<u64>,
        /// Success status text.
        status: String,
    },
    /// Append one durable presentation-only transcript note.
    AppendPresentationNote {
        /// Session that owns the note.
        session_id: SessionId,
        /// Stable producer identity.
        source_id: String,
        /// Unique note identity within the producer.
        note_id: String,
        /// Complete bounded note text.
        text: String,
        /// Renderer-neutral text format.
        format: bcode_command::CommandTextFormat,
    },
    /// Cancel runtime work for a session.
    CancelRuntimeWork {
        /// Session that owns the work.
        session_id: SessionId,
        /// Runtime work id.
        work_id: WorkId,
    },
    /// Request context compaction for the current session.
    CompactContext {
        /// Session to compact.
        session_id: SessionId,
    },
    /// Attach current session to a worktree path.
    AttachWorktree {
        /// Session to attach.
        session_id: SessionId,
        /// Selected worktree path.
        path: std::path::PathBuf,
    },
    /// Create a worktree.
    CreateWorktree {
        /// Stable idempotency identity retained across bounded waits.
        operation_id: String,
        /// Request payload.
        request: WorktreeCreateRequest,
    },
    /// Wait for worktree creation progress.
    WaitWorktreeCreate {
        operation_id: String,
        after_revision: u64,
    },
    /// Request cancellation of the active turn for a session.
    CancelTurn { session_id: SessionId },
    /// Resolve one pending permission request.
    ResolvePermission {
        /// Permission request id.
        permission_id: String,
        /// Whether to approve the request.
        approved: bool,
        /// Whether to remember the decision.
        remember: bool,
        /// Whether the action targets every request in the authorization batch.
        apply_to_batch: bool,
        /// Authorization batch id when `apply_to_batch` is true.
        batch_id: Option<String>,
    },
}

/// Daemon connectivity observation reported by completed effects.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DaemonObservation {
    /// The effect does not say anything about daemon connectivity.
    None,
    /// A daemon-backed request completed successfully.
    Success,
    /// The daemon was unavailable or unreachable.
    Unavailable(String),
    /// A daemon-backed request failed after reaching the daemon or for an unknown reason.
    Failed(String),
}

impl DaemonObservation {
    fn from_client_error(error: &ClientError) -> Self {
        if error.is_daemon_unavailable() {
            Self::Unavailable(error.to_string())
        } else {
            Self::Failed(error.to_string())
        }
    }

    fn from_client_result<T>(result: &Result<T, ClientError>) -> Self {
        match result {
            Ok(_) => Self::Success,
            Err(error) => Self::from_client_error(error),
        }
    }

    fn from_tui_result<T>(result: &Result<T, TuiError>) -> Self {
        match result {
            Ok(_) => Self::Success,
            Err(TuiError::Client(error)) => Self::from_client_error(error),
            Err(_) => Self::None,
        }
    }

    fn from_optional_error(connected: bool, error: Option<&str>) -> Self {
        if connected {
            Self::Success
        } else if let Some(error) = error {
            Self::Unavailable(error.to_owned())
        } else {
            Self::None
        }
    }
}

/// Completed TUI background work.
pub enum TuiEffectResult {
    /// Targeted recovery action and fresh bounded status.
    QueueRecovery {
        session_id: SessionId,
        generation: u64,
        result: Box<
            Result<
                (
                    SessionViewActionOutcome,
                    bcode_session_models::SubmissionQueueStatus,
                ),
                ClientError,
            >,
        >,
    },
    SessionChildrenLoaded {
        parent_id: SessionId,
        generation: u64,
        result: Result<bcode_session_models::SessionChildPage, ClientError>,
    },
    ChildActivityLoaded {
        session_id: SessionId,
        generation: u64,
        result: Result<bcode_session_models::SessionActivityPage, ClientError>,
    },
    /// Session-open preparation progress emitted while the open effect is running.
    SessionOpenProgress {
        snapshot: bcode_session_models::SessionOpenOperationSnapshot,
    },
    /// Session open completed.
    SessionOpened {
        /// Session that was opened.
        session_id: SessionId,
        /// Whether older history exists before the attached window.
        has_older_history: bool,
        /// Attach result and event-stream task.
        result: Box<Result<(bcode_client::AttachedSessionHistory, JoinHandle<()>), TuiError>>,
    },
    /// User configuration load completed.
    ConfigLoaded {
        /// Config load result.
        config: Box<Result<bcode_config::BcodeConfig, String>>,
        /// Global interactive theme selection load result.
        theme_selection: Result<Option<String>, String>,
        /// Global interactive streaming-presentation override load result.
        streaming_presentation:
            Result<Option<bcode_session_view_models::StreamingPresentationPolicy>, String>,
    },
    /// Durable TUI theme state update completed.
    ThemeSelectionPersisted {
        /// Stable base theme id requested by the user, or none when cleared.
        name: Option<String>,
        /// State write result.
        result: Result<std::path::PathBuf, String>,
    },
    /// Durable streaming-presentation state update completed.
    StreamingPresentationPersisted {
        /// Policy requested by the user, or none when cleared.
        policy: Option<bcode_session_view_models::StreamingPresentationPolicy>,
        /// State write result.
        result: Result<std::path::PathBuf, String>,
    },
    /// Auth security reconciliation completed.
    AuthSecurityReconciled {
        /// Status to display, if any.
        status: Option<String>,
    },
    /// Draft-session status hydration completed.
    DraftStatusLoaded {
        /// Whether at least one daemon-backed request completed successfully.
        daemon_connected: bool,
        /// Default model status, if available.
        model: Option<bcode_model::SessionModelStatus>,
        /// Restored composer draft, if available.
        composer_draft: Option<String>,
        /// First non-critical error encountered.
        error: Option<String>,
    },
    /// Attached session status hydration completed.
    SessionStatusLoaded {
        /// Whether at least one daemon-backed request completed successfully.
        daemon_connected: bool,
        /// Session that was hydrated.
        session_id: SessionId,
        /// Hydrated semantic/runtime status.
        hydration: Box<SessionStatusHydration>,
    },
    /// Targeted model projection refresh completed.
    SessionModelStatusLoaded {
        session_id: SessionId,
        result: Result<bcode_model::SessionModelStatus, ClientError>,
    },
    /// Targeted plugin status projection refresh completed.
    PluginStatusLoaded {
        session_id: SessionId,
        plugin_status: Vec<bcode_session_view_models::PluginStatusView>,
        error: Option<String>,
    },
    /// Agent metadata load completed.
    AgentCatalogLoaded {
        /// Agent catalog result.
        agents: Result<AgentCatalog, String>,
    },
    /// Older history page load completed.
    OlderHistoryLoaded {
        /// Session that was requested.
        session_id: SessionId,
        /// Requested boundary cursor.
        cursor: SessionHistoryCursor,
        /// Resident window generation at request time.
        generation: u64,
        /// History page result.
        result: Result<
            (
                SessionHistoryPage,
                Vec<bcode_session_models::SubmissionRecord>,
            ),
            ClientError,
        >,
    },
    /// Newer history page load completed.
    NewerHistoryLoaded {
        /// Session that was requested.
        session_id: SessionId,
        /// Requested boundary cursor.
        cursor: SessionHistoryCursor,
        /// Resident window generation at request time.
        generation: u64,
        /// History page result.
        result: Result<
            (
                SessionHistoryPage,
                Vec<bcode_session_models::SubmissionRecord>,
            ),
            ClientError,
        >,
    },
    /// Permission poll completed.
    PermissionList {
        /// Permission list result.
        result: Result<Vec<PermissionSummary>, ClientError>,
    },
    /// Composer draft save completed.
    SaveDraft {
        /// Saved draft text.
        text: String,
        /// Save result.
        result: Result<(), ClientError>,
    },
    /// Slash palette load completed.
    SlashPaletteLoaded {
        /// Composer discovery generation.
        generation: u64,
        /// Query used to build completions.
        query: String,
        /// Loaded palette state.
        palette: slash_palette::SlashPalette,
    },
    /// Command palette contributions load completed.
    CommandPaletteLoaded {
        /// Contributions result from the application client boundary.
        result: Result<Vec<bcode_command::CommandContribution>, ClientError>,
    },
    /// Root session-picker catalog load completed.
    SessionPickerLoaded {
        /// Subscription generation that produced the result.
        generation: u64,
        /// Bounded catalog result from the application client boundary.
        result: Result<bcode_session_models::SessionCatalogPage, ClientError>,
        /// Catalog invalidation restarts navigation rather than reusing a stale cursor.
        restart: bool,
    },
    /// External session import completed.
    SessionImported {
        result: Result<(SessionSummary, Vec<bcode_ipc::SessionImportWarning>), ClientError>,
    },
    /// Session rename completed.
    SessionRenamed {
        result: Result<SessionSummary, ClientError>,
    },
    /// Session deletion completed.
    SessionDeleted {
        result: Result<SessionSummary, ClientError>,
    },
    /// Root picker transcript search completed.
    SessionsSearched {
        result: Result<
            (
                bcode_session_search::FederatedSessionSearchResponse,
                Vec<bcode_session_search::HydratedSessionSearchHit>,
            ),
            ClientError,
        >,
    },
    BulkMigrationUpdated {
        result: Result<bcode_ipc::SessionBulkMigrationOperationStatus, ClientError>,
    },
    BulkMigrationWaited {
        result: Result<bcode_ipc::SessionBulkMigrationOperationStatus, ClientError>,
    },
    SearchIndexingStarted {
        result: Result<bcode_session_search::StartSessionSearchBackfillResponse, ClientError>,
    },
    SearchIndexingUpdated {
        result: Result<bcode_session_search::SessionSearchBackfillOperationStatus, ClientError>,
    },
    SearchIndexingWaited {
        result: Result<bcode_session_search::SessionSearchBackfillOperationStatus, ClientError>,
    },
    /// Resolved slash command execution completed.
    SlashCommandExecuted {
        /// Submitted command text.
        message: String,
        /// Command outcome.
        result: Result<super::slash_commands::SlashCommandOutcome, ClientError>,
    },
    /// Root Ralph action completed.
    RalphAction {
        /// Completed action.
        action: super::ralph_flow::RalphRootAction,
        /// Presentation result.
        result: Result<super::ralph_flow::RalphRootOutput, TuiError>,
    },
    /// Root Ralph loop creation completed.
    RalphStarted {
        /// Creation result.
        result: Result<super::ralph_flow::RalphStartOutput, TuiError>,
    },
    /// Plugin-owned native surface opened.
    PluginSurfaceOpened {
        /// Plugin owner.
        plugin_id: String,
        /// Opened surface or error.
        result: Result<bcode_plugin_sdk::tui::BoxedPluginTuiSurface, TuiError>,
    },
    /// Model providers for the root picker loaded.
    ModelProvidersLoaded {
        /// Loaded plugin service summaries.
        result: Result<Vec<bcode_ipc::PluginServiceSummary>, ClientError>,
    },
    /// Portable auth-pool status loaded.
    AuthPoolPickerLoaded {
        /// Loaded secret-free pool summaries.
        result: Result<Vec<bcode_provider_auth_models::AuthPoolSummary>, ClientError>,
    },
    /// Interactive auth-pool preference mutation completed.
    AuthPoolPreferenceSet {
        /// Updated pool.
        pool: String,
        /// New preferred profile, or `None` when clearing the override.
        profile: Option<String>,
        /// Daemon response.
        result: Result<(), ClientError>,
    },
    /// Completed selected check and post-persistence model-list refresh.
    SelectedModelChecked {
        session_id: Option<SessionId>,
        provider_plugin_id: Option<String>,
        generation: u64,
        result: Result<bcode_model::ModelCheckReport, ClientError>,
        models: Result<bcode_model::ModelList, ClientError>,
    },
    /// Models for the root picker loaded.
    ModelPickerLoaded {
        /// Provider used for the model query.
        provider_plugin_id: Option<String>,
        /// Loaded normalized model list.
        result: Result<bcode_model::ModelList, ClientError>,
    },
    /// Skills for the root skill picker loaded.
    SkillPickerLoaded {
        /// Loaded skill summaries.
        result: Result<bcode_skill_models::SkillList, ClientError>,
    },
    /// Skill details for root picker help loaded.
    SkillDescribed {
        /// Requested skill.
        skill_id: SkillId,
        /// Loaded manifest.
        result: Result<bcode_skill_models::SkillManifest, ClientError>,
    },
    /// Reasoning status for the root thinking dialog loaded.
    ThinkingDialogLoaded {
        /// Initially focused setting.
        focus: super::thinking_dialog::ThinkingDialogFocus,
        /// Loaded model status.
        result: Result<bcode_model::SessionModelStatus, ClientError>,
    },
    /// Canonical milestones loaded without generation.
    MilestonesLoaded {
        /// Exact terminal-only request identity.
        request: super::timeline_dialog::MilestonePageRequest,
        /// Bounded canonical page.
        result: Result<bcode_session_models::SessionMilestonePage, ClientError>,
    },
    /// Bounded timeline jump history loaded.
    TimelineJumpLoaded {
        /// Session for which the jump was requested.
        session_id: SessionId,
        /// Resident window generation when the jump was requested.
        generation: u64,
        /// Selected source sequence.
        sequence: u64,
        /// Loaded events and bounded-window flags.
        result: Result<
            (
                Vec<bcode_session_models::SessionEvent>,
                bool,
                bool,
                Vec<bcode_session_models::SubmissionRecord>,
            ),
            TuiError,
        >,
    },
    /// Plugin command invocation completed.
    PluginCommandInvoked {
        /// Plugin owner.
        plugin_id: String,
        /// Typed command response.
        result: Result<bcode_command::InvokeCommandResponse, TuiError>,
    },
    /// Submit message completed.
    SubmitMessage {
        /// Identity retained even when transport outcome is ambiguous.
        submission_id: bcode_session_models::SubmissionId,
        /// Message text originally submitted.
        message: String,
        /// Submit result.
        result: Box<Result<SubmitMessageResult, ClientError>>,
    },
    /// Skill action completed.
    SkillAction {
        /// Skill action kind.
        action: SkillActionKind,
        /// Skill acted on.
        skill_id: SkillId,
        /// Skill action result.
        result: Box<Result<SkillActionResult, ClientError>>,
    },
    /// Session model selection completed.
    SetSessionModel {
        /// Session that was updated.
        session_id: SessionId,
        /// Provider plugin id, when explicitly selected.
        provider_plugin_id: Option<String>,
        /// Model id that was requested.
        model_id: String,
        /// Daemon response.
        result: Result<(), ClientError>,
    },
    /// Session reasoning update completed.
    SetSessionReasoning {
        /// Session that was updated.
        session_id: SessionId,
        /// Effort value requested by the update.
        effort: Option<String>,
        /// Pending effort generation staged for the update.
        effort_generation: Option<u64>,
        /// Success status text.
        status: String,
        /// Daemon response.
        result: Result<(), ClientError>,
    },
    /// Durable presentation note append completed.
    AppendPresentationNote {
        /// Session whose ordered note append completed.
        session_id: SessionId,
        /// Daemon response.
        result: Result<(), ClientError>,
    },
    /// Runtime work cancellation completed.
    CancelRuntimeWork {
        /// Cancelled work id.
        work_id: WorkId,
        /// Daemon response.
        result: Result<bool, ClientError>,
    },
    /// Context compaction completed.
    CompactContext {
        /// Session the request targeted.
        session_id: SessionId,
        /// Daemon response.
        result: Result<String, ClientError>,
    },
    /// Worktree attach completed.
    AttachWorktree {
        /// Selected worktree path.
        path: std::path::PathBuf,
        /// Attach result.
        result: Result<SessionSummary, ClientError>,
    },
    /// Worktree creation completed.
    CreateWorktree {
        /// Worktree operation snapshot.
        result: Result<bcode_worktree_models::WorktreeCreateOperationStatus, ClientError>,
    },
    /// Result for active turn cancellation.
    CancelTurn {
        /// Session the request targeted.
        session_id: SessionId,
        /// Daemon response.
        result: Result<bool, ClientError>,
    },
    /// Result for a permission resolution.
    PermissionResolved {
        /// Permission request id.
        permission_id: String,
        /// Whether the request was approved.
        approved: bool,
        /// Whether the decision was remembered.
        remember: bool,
        /// Whether the action targeted the authorization batch.
        apply_to_batch: bool,
        /// Daemon response indicating whether any request was resolved.
        result: Result<bool, ClientError>,
    },
}

#[allow(clippy::match_same_arms)]
impl TuiEffectResult {
    /// Return the daemon connectivity observation implied by this effect result.
    #[must_use]
    pub fn daemon_observation(&self) -> DaemonObservation {
        match self {
            Self::QueueRecovery { result, .. } => DaemonObservation::from_client_result(result),
            Self::SessionChildrenLoaded { result, .. } => {
                DaemonObservation::from_client_result(result)
            }
            Self::ChildActivityLoaded { result, .. } => {
                DaemonObservation::from_client_result(result)
            }
            Self::SessionOpenProgress { .. } => DaemonObservation::Success,
            Self::SessionOpened { result, .. } => DaemonObservation::from_tui_result(result),
            Self::DraftStatusLoaded {
                daemon_connected,
                error,
                ..
            } => DaemonObservation::from_optional_error(*daemon_connected, error.as_deref()),
            Self::SessionStatusLoaded {
                daemon_connected,
                hydration,
                ..
            } => DaemonObservation::from_optional_error(
                *daemon_connected,
                hydration.error.as_deref(),
            ),
            Self::SessionModelStatusLoaded { result, .. } => {
                DaemonObservation::from_client_result(result)
            }
            Self::PluginStatusLoaded { error, .. } => {
                error.as_ref().map_or(DaemonObservation::Success, |error| {
                    DaemonObservation::Failed(error.clone())
                })
            }
            Self::AgentCatalogLoaded { agents } => match agents {
                Ok(_) => DaemonObservation::Success,
                Err(error) => DaemonObservation::Unavailable(error.clone()),
            },
            Self::OlderHistoryLoaded { result, .. } | Self::NewerHistoryLoaded { result, .. } => {
                DaemonObservation::from_client_result(result)
            }
            Self::PermissionList { result } => DaemonObservation::from_client_result(result),
            Self::SaveDraft { result, .. } => DaemonObservation::from_client_result(result),
            Self::SkillAction { result, .. } => DaemonObservation::from_client_result(result),
            Self::SetSessionModel { result, .. } => DaemonObservation::from_client_result(result),
            Self::SetSessionReasoning { result, .. } => {
                DaemonObservation::from_client_result(result)
            }
            Self::AppendPresentationNote { result, .. } => {
                DaemonObservation::from_client_result(result)
            }
            Self::SubmitMessage { result, .. } => DaemonObservation::from_client_result(result),
            Self::CompactContext { result, .. } => DaemonObservation::from_client_result(result),
            Self::CancelRuntimeWork { result, .. } => DaemonObservation::from_client_result(result),
            Self::AttachWorktree { result, .. } => DaemonObservation::from_client_result(result),
            Self::CreateWorktree { result } => DaemonObservation::from_client_result(result),
            Self::CancelTurn { result, .. } | Self::PermissionResolved { result, .. } => {
                DaemonObservation::from_client_result(result)
            }
            Self::ConfigLoaded { .. }
            | Self::ThemeSelectionPersisted { .. }
            | Self::StreamingPresentationPersisted { .. }
            | Self::AuthSecurityReconciled { .. }
            | Self::SlashPaletteLoaded { .. }
            | Self::CommandPaletteLoaded { .. }
            | Self::SessionPickerLoaded { .. }
            | Self::SessionImported { .. }
            | Self::SessionRenamed { .. }
            | Self::SessionDeleted { .. }
            | Self::SessionsSearched { .. }
            | Self::BulkMigrationUpdated { .. }
            | Self::BulkMigrationWaited { .. }
            | Self::SearchIndexingStarted { .. }
            | Self::SearchIndexingUpdated { .. }
            | Self::SearchIndexingWaited { .. }
            | Self::SlashCommandExecuted { .. }
            | Self::ThinkingDialogLoaded { .. }
            | Self::MilestonesLoaded { .. }
            | Self::TimelineJumpLoaded { .. }
            | Self::PluginCommandInvoked { .. } => DaemonObservation::None,
            Self::RalphAction { result, .. } => DaemonObservation::from_tui_result(result),
            Self::RalphStarted { result } => DaemonObservation::from_tui_result(result),
            Self::PluginSurfaceOpened { result, .. } => DaemonObservation::from_tui_result(result),
            Self::ModelProvidersLoaded { result } => DaemonObservation::from_client_result(result),
            Self::AuthPoolPickerLoaded { result } => DaemonObservation::from_client_result(result),
            Self::AuthPoolPreferenceSet { result, .. } => {
                DaemonObservation::from_client_result(result)
            }
            Self::SelectedModelChecked { result, .. } => {
                DaemonObservation::from_client_result(result)
            }
            Self::ModelPickerLoaded { result, .. } => DaemonObservation::from_client_result(result),
            Self::SkillPickerLoaded { result } => DaemonObservation::from_client_result(result),
            Self::SkillDescribed { result, .. } => DaemonObservation::from_client_result(result),
        }
    }
}

/// Skill action effect success payload.
#[derive(Debug)]
pub struct SkillActionResult {
    /// Session that received the skill action.
    pub session_id: SessionId,
    /// Newly-created/attached session summary, if the action created a session.
    pub created_session: Option<SessionSummary>,
    /// Event stream task for a newly-created session.
    pub event_task: Option<JoinHandle<()>>,
    /// Invocation acceptance when invoking a skill.
    pub acceptance: Option<MessageAcceptance>,
    /// Agent committed during invocation.
    pub committed_agent_id: Option<String>,
    /// Pending reasoning effort generation committed during invocation.
    pub committed_reasoning_effort_generation: Option<u64>,
    /// Releases a newly-created session stream after the TUI installs the session id.
    pub event_stream_release: Option<oneshot::Sender<()>>,
}

/// Attached session status hydration payload.
#[derive(Debug)]
pub struct SessionStatusHydration {
    /// Model status, if available.
    pub model: Option<bcode_model::SessionModelStatus>,
    /// Active skills captured during bounded attach hydration.
    pub active_skills: Option<Vec<bcode_skill_models::SkillContextResponse>>,
    /// Runtime work snapshots, if available.
    pub runtime_work: Option<Vec<bcode_session_models::RuntimeWorkSnapshot>>,
    /// Pending interactive requests, if available.
    pub interactions: Option<Vec<bcode_session_view_models::InteractionViewSummary>>,
    /// Active plugin-owned status contributions.
    pub plugin_status: Vec<bcode_session_view_models::PluginStatusView>,
    /// First non-critical error encountered.
    pub error: Option<String>,
}

#[derive(Debug)]
pub struct SubmitMessageResult {
    /// Session that received the message.
    pub session_id: SessionId,
    /// Newly-created/attached session summary, if the submit created a session.
    pub created_session: Option<SessionSummary>,
    /// Bounded lifecycle read following acceptance, when available.
    pub submission: Result<Option<bcode_session_models::SubmissionRecord>, ClientError>,
    /// Server acceptance for the submitted message.
    pub receipt: bcode_session_models::SubmissionReceipt,
    /// Agent committed during submission.
    pub committed_agent_id: Option<String>,
    /// Pending reasoning effort generation committed during submission.
    pub committed_reasoning_effort_generation: Option<u64>,
    /// Event stream task for a newly-created session.
    pub event_task: Option<JoinHandle<()>>,
    /// Releases a newly-created session stream after the TUI installs the session id.
    pub event_stream_release: Option<oneshot::Sender<()>>,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum EffectKey {
    QueueRecovery,
    SessionOpen,
    Config,
    ThemeSelection,
    StreamingPresentation,
    AuthSecurity,
    DraftStatus,
    SessionStatus,
    SessionModelStatus,
    PluginStatus,
    AgentCatalog,
    OlderHistory,
    NewerHistory,
    PermissionList,
    DraftSave,
    SlashPalette,
    CommandPalette,
    SessionChildren(SessionId),
    ChildActivity(SessionId),
    SessionPicker,
    ImportSession,
    RenameSession(SessionId),
    DeleteSession(SessionId),
    SearchSessions,
    BulkMigration,
    SearchIndexing,
    SlashCommand,
    RalphAction,
    RalphStart,
    PluginSurface,
    ModelProviders,
    ModelCheck,
    ModelPicker,
    AuthPoolPicker,
    AuthPoolPreference,
    SkillPicker,
    SkillDescription,
    ThinkingDialog,
    TimelineJump,
    PluginCommand(String, String),
    SubmitMessage(bcode_session_models::SubmissionId),
    SkillAction(SkillId),
    SetSessionModel(SessionId),
    SetSessionReasoning(SessionId),
    AppendPresentationNote(SessionId, String),
    CancelRuntimeWork(SessionId),
    CompactContext(SessionId),
    AttachWorktree(SessionId),
    CreateWorktree,
    CancelTurn(SessionId),
    ResolvePermission(String),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EffectSchedule {
    StartIfIdle,
    Replace,
    QueueLatest,
    Cancel,
}

/// Daemon-backed effect scheduling class.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EffectDaemonIntent {
    /// Use the background client clone for non-foreground work.
    Background,
    /// Use the foreground client clone for explicit user actions.
    Foreground,
}

impl TuiEffect {
    #[allow(clippy::too_many_lines, dead_code)]
    fn daemon_start_failed(self, client_error: ClientError) -> TuiEffectResult {
        match self {
            Self::QueueRecovery {
                session_id,
                generation,
                ..
            } => TuiEffectResult::QueueRecovery {
                generation,
                session_id,
                result: Box::new(Err(client_error)),
            },
            Self::LoadSessionChildren {
                parent_id,
                generation,
                ..
            } => TuiEffectResult::SessionChildrenLoaded {
                parent_id,
                generation,
                result: Err(client_error),
            },
            Self::LoadChildActivity {
                session_id,
                generation,
                ..
            } => TuiEffectResult::ChildActivityLoaded {
                session_id,
                generation,
                result: Err(client_error),
            },
            Self::OpenSession { session_id, .. } => TuiEffectResult::SessionOpened {
                session_id,
                has_older_history: true,
                result: Box::new(Err(TuiError::Client(client_error))),
            },
            Self::LoadDraftStatus { .. } => TuiEffectResult::DraftStatusLoaded {
                daemon_connected: false,
                model: None,
                composer_draft: None,
                error: Some(client_error.to_string()),
            },
            Self::LoadSessionStatus { session_id } => TuiEffectResult::SessionStatusLoaded {
                daemon_connected: false,
                session_id,
                hydration: Box::new(SessionStatusHydration {
                    model: None,
                    active_skills: None,
                    runtime_work: None,
                    interactions: None,
                    plugin_status: Vec::new(),
                    error: Some(client_error.to_string()),
                }),
            },
            Self::LoadSessionModelStatus { session_id } => {
                TuiEffectResult::SessionModelStatusLoaded {
                    session_id,
                    result: Err(client_error),
                }
            }
            Self::LoadPluginStatus { session_id } => TuiEffectResult::PluginStatusLoaded {
                session_id,
                plugin_status: Vec::new(),
                error: Some(client_error.to_string()),
            },
            Self::LoadAgentCatalog => TuiEffectResult::AgentCatalogLoaded {
                agents: Err(client_error.to_string()),
            },
            Self::SubmitMessage { request } => TuiEffectResult::SubmitMessage {
                submission_id: request.submission_id,
                message: request.message,
                result: Box::new(Err(client_error)),
            },
            Self::SkillAction { request } => TuiEffectResult::SkillAction {
                action: request.action,
                skill_id: request.skill_id,
                result: Box::new(Err(client_error)),
            },
            Self::SetSessionModel {
                session_id,
                provider_plugin_id,
                model_id,
            } => TuiEffectResult::SetSessionModel {
                session_id,
                provider_plugin_id,
                model_id,
                result: Err(client_error),
            },
            Self::SetSessionReasoning {
                session_id,
                effort,
                effort_generation,
                status,
                ..
            } => TuiEffectResult::SetSessionReasoning {
                session_id,
                effort,
                effort_generation,
                status,
                result: Err(client_error),
            },
            Self::AppendPresentationNote { session_id, .. } => {
                TuiEffectResult::AppendPresentationNote {
                    session_id,
                    result: Err(client_error),
                }
            }
            Self::CancelRuntimeWork { work_id, .. } => TuiEffectResult::CancelRuntimeWork {
                work_id,
                result: Err(client_error),
            },
            Self::CompactContext { session_id } => TuiEffectResult::CompactContext {
                session_id,
                result: Err(client_error),
            },
            Self::AttachWorktree { path, .. } => TuiEffectResult::AttachWorktree {
                path,
                result: Err(client_error),
            },
            Self::CreateWorktree { .. } | Self::WaitWorktreeCreate { .. } => {
                TuiEffectResult::CreateWorktree {
                    result: Err(client_error),
                }
            }
            Self::CancelTurn { session_id } => TuiEffectResult::CancelTurn {
                session_id,
                result: Err(client_error),
            },
            Self::ResolvePermission {
                permission_id,
                approved,
                remember,
                apply_to_batch,
                ..
            } => TuiEffectResult::PermissionResolved {
                permission_id,
                approved,
                remember,
                apply_to_batch,
                result: Err(client_error),
            },
            Self::LoadConfig
            | Self::PersistThemeSelection { .. }
            | Self::ClearThemeSelection
            | Self::PersistStreamingPresentation { .. }
            | Self::ClearStreamingPresentation
            | Self::ReconcileAuthSecurity { .. }
            | Self::LoadOlderHistory { .. }
            | Self::LoadNewerHistory { .. }
            | Self::ListPermissions
            | Self::SaveDraft { .. }
            | Self::LoadSlashPalette { .. }
            | Self::LoadCommandPalette
            | Self::LoadSessionPicker { .. }
            | Self::ImportSession { .. }
            | Self::RenameSession { .. }
            | Self::DeleteSession { .. }
            | Self::SearchSessions { .. }
            | Self::StartBulkMigration { .. }
            | Self::CancelBulkMigration { .. }
            | Self::WaitBulkMigration { .. }
            | Self::StartSearchIndexing { .. }
            | Self::CancelSearchIndexing { .. }
            | Self::WaitSearchIndexing { .. }
            | Self::ExecuteSlashCommand { .. }
            | Self::RalphAction { .. }
            | Self::RalphStart { .. }
            | Self::OpenPluginSurface { .. }
            | Self::LoadModelProviders
            | Self::LoadAuthPoolPicker
            | Self::SetAuthPoolPreference { .. }
            | Self::CheckSelectedModel { .. }
            | Self::LoadModelPicker { .. }
            | Self::LoadSkillPicker
            | Self::DescribeSkill { .. }
            | Self::LoadThinkingDialog { .. }
            | Self::LoadMilestones { .. }
            | Self::LoadTimelineJump { .. }
            | Self::InvokePluginCommand { .. } => {
                unreachable!("daemon start failure for non-foreground effect")
            }
        }
    }

    const fn daemon_intent(&self) -> EffectDaemonIntent {
        match self {
            Self::OpenSession {
                allow_daemon_start: true,
                ..
            }
            | Self::QueueRecovery { .. }
            | Self::LoadDraftStatus { .. }
            | Self::LoadSessionStatus { .. }
            | Self::LoadAgentCatalog
            | Self::SubmitMessage { .. }
            | Self::SkillAction { .. }
            | Self::SetSessionModel { .. }
            | Self::SetSessionReasoning { .. }
            | Self::AppendPresentationNote { .. }
            | Self::CancelRuntimeWork { .. }
            | Self::CompactContext { .. }
            | Self::AttachWorktree { .. }
            | Self::CreateWorktree { .. }
            | Self::WaitWorktreeCreate { .. }
            | Self::CancelTurn { .. }
            | Self::ResolvePermission { .. }
            | Self::InvokePluginCommand { .. } => EffectDaemonIntent::Foreground,
            Self::OpenSession {
                allow_daemon_start: false,
                ..
            }
            | Self::LoadSessionChildren { .. }
            | Self::LoadChildActivity { .. }
            | Self::LoadConfig
            | Self::PersistThemeSelection { .. }
            | Self::ClearThemeSelection
            | Self::PersistStreamingPresentation { .. }
            | Self::ClearStreamingPresentation
            | Self::ReconcileAuthSecurity { .. }
            | Self::LoadSessionModelStatus { .. }
            | Self::LoadPluginStatus { .. }
            | Self::LoadOlderHistory { .. }
            | Self::LoadNewerHistory { .. }
            | Self::ListPermissions
            | Self::SaveDraft { .. }
            | Self::LoadSlashPalette { .. }
            | Self::LoadCommandPalette
            | Self::LoadSessionPicker { .. }
            | Self::ImportSession { .. }
            | Self::RenameSession { .. }
            | Self::DeleteSession { .. }
            | Self::SearchSessions { .. }
            | Self::StartBulkMigration { .. }
            | Self::CancelBulkMigration { .. }
            | Self::WaitBulkMigration { .. }
            | Self::StartSearchIndexing { .. }
            | Self::CancelSearchIndexing { .. }
            | Self::WaitSearchIndexing { .. }
            | Self::ExecuteSlashCommand { .. }
            | Self::RalphAction { .. }
            | Self::RalphStart { .. }
            | Self::OpenPluginSurface { .. }
            | Self::LoadModelProviders
            | Self::LoadAuthPoolPicker
            | Self::SetAuthPoolPreference { .. }
            | Self::CheckSelectedModel { .. }
            | Self::LoadModelPicker { .. }
            | Self::LoadSkillPicker
            | Self::DescribeSkill { .. }
            | Self::LoadThinkingDialog { .. }
            | Self::LoadMilestones { .. }
            | Self::LoadTimelineJump { .. } => EffectDaemonIntent::Background,
        }
    }
}

type OrderedPresentationEffects = BTreeMap<SessionId, VecDeque<TuiEffect>>;
type ScheduledEffects = Vec<(EffectSchedule, TuiEffect)>;

/// Queue of effects requested before the chat loop runner can start them.
///
/// The queue keeps only the latest pending request for each effect key. This
/// mirrors runner semantics and avoids spawning then immediately aborting stale
/// work when multiple state transitions request the same background effect
/// before the loop has a chance to drain the queue.
#[derive(Default)]
pub struct TuiEffectQueue {
    effects: BTreeMap<EffectKey, (EffectSchedule, TuiEffect)>,
}

impl TuiEffectQueue {
    /// Queue an effect using normal start-if-idle scheduling.
    pub fn start(&mut self, effect: TuiEffect) {
        self.push(effect, EffectSchedule::StartIfIdle);
    }

    /// Queue an effect that should replace any in-flight effect with the same key.
    pub fn replace(&mut self, effect: TuiEffect) {
        self.push(effect, EffectSchedule::Replace);
    }

    /// Queue the latest effect with this key to run after the current one finishes.
    pub fn queue_latest(&mut self, effect: TuiEffect) {
        self.push(effect, EffectSchedule::QueueLatest);
    }

    /// Queue an ordered presentation note without collapsing another note for the same session.
    pub fn start_ordered(&mut self, effect: TuiEffect) {
        let key = effect.key();
        debug_assert!(matches!(key, EffectKey::AppendPresentationNote(_, _)));
        self.effects
            .insert(key, (EffectSchedule::QueueLatest, effect));
    }

    /// Cancel active and pending work matching this effect key.
    pub fn cancel(&mut self, effect: TuiEffect) {
        self.push(effect, EffectSchedule::Cancel);
    }

    fn push(&mut self, effect: TuiEffect, schedule: EffectSchedule) {
        self.effects.insert(effect.key(), (schedule, effect));
    }

    #[cfg(test)]
    pub fn queued_effect_count(&self) -> usize {
        self.effects.len()
    }

    /// Return whether an open-session effect is queued for the given session.
    #[cfg(test)]
    pub fn has_open_session(&self, session_id: SessionId) -> bool {
        self.effects.values().any(|(_, effect)| {
            matches!(
                effect,
                TuiEffect::OpenSession {
                    session_id: queued,
                    ..
                } if *queued == session_id
            )
        })
    }

    #[cfg(test)]
    pub fn queued_agent_id(&self) -> Option<&str> {
        self.effects.values().find_map(|(_, effect)| match effect {
            TuiEffect::SubmitMessage { request } => request.agent_id.as_deref(),
            TuiEffect::SkillAction { request } => request.agent_id.as_deref(),
            _ => None,
        })
    }

    #[cfg(test)]
    pub fn queued_execution_options(&self) -> Option<&bcode_session_models::TurnExecutionOptions> {
        self.effects.values().find_map(|(_, effect)| match effect {
            TuiEffect::SubmitMessage { request } => Some(&request.execution),
            TuiEffect::SkillAction { request } => Some(&request.execution),
            _ => None,
        })
    }

    /// Return whether a plugin surface-open effect is queued for the given plugin and kind.
    /// Return the projection request queued for one open session.
    #[cfg(test)]
    pub fn open_session_request(&self, session_id: SessionId) -> Option<&ProjectionWindowRequest> {
        self.effects.values().find_map(|(_, effect)| match effect {
            TuiEffect::OpenSession {
                session_id: queued,
                initial_window_request,
                ..
            } if *queued == session_id => Some(initial_window_request),
            _ => None,
        })
    }

    /// Return whether work with the same scheduling key is already queued.
    pub(super) fn contains_effect(&self, effect: &TuiEffect) -> bool {
        self.effects.contains_key(&effect.key())
    }

    /// Drain non-note effects while retaining ordered presentation notes for serialized release.
    pub(super) fn drain_runtime(&mut self) -> (ScheduledEffects, OrderedPresentationEffects) {
        let mut effects = Vec::new();
        let mut notes = BTreeMap::<SessionId, VecDeque<TuiEffect>>::new();
        for (schedule, effect) in std::mem::take(&mut self.effects).into_values() {
            if let TuiEffect::AppendPresentationNote { session_id, .. } = &effect {
                notes.entry(*session_id).or_default().push_back(effect);
            } else {
                effects.push((schedule, effect));
            }
        }
        (effects, notes)
    }
}

const TUI_EFFECT_STREAM_CAPACITY: usize = 64;

impl TuiEffect {
    #[cfg(test)]
    pub(super) async fn run_for_test(self, client: BcodeClient) -> TuiEffectResult {
        let (streaming_sender, _streaming_receiver) = mpsc::channel(1);
        self.run(client, streaming_sender).await
    }

    pub(super) fn command_key(&self) -> bmux_tui_runtime::CommandKey {
        let key = match self {
            Self::AppendPresentationNote { session_id, .. } => {
                return bmux_tui_runtime::CommandKey::new(format!(
                    "bcode.effect.AppendPresentationNote({session_id})"
                ));
            }
            _ => self.key(),
        };
        bmux_tui_runtime::CommandKey::new(format!("bcode.effect.{key:?}"))
    }

    pub(super) fn command(
        self,
        schedule: EffectSchedule,
        foreground_client: &BcodeClient,
        passive_client: &BcodeClient,
        handle: bmux_tui_runtime::RuntimeHandle<super::root_program::BcodeRuntimeMessage>,
    ) -> bmux_tui_runtime::Command<super::root_program::BcodeRuntimeMessage> {
        let key = self.command_key();
        let client = match self.daemon_intent() {
            EffectDaemonIntent::Background => passive_client.clone(),
            EffectDaemonIntent::Foreground => foreground_client.clone(),
        };
        let future = async move {
            let (streaming_sender, mut streaming_receiver) =
                mpsc::channel(TUI_EFFECT_STREAM_CAPACITY);
            let effect = Box::pin(self.run(client, streaming_sender));
            tokio::pin!(effect);
            loop {
                tokio::select! {
                    result = &mut effect => {
                        break Some(super::root_program::BcodeRuntimeMessage::EffectCompleted(
                            Box::new(result),
                        ));
                    }
                    progress = streaming_receiver.recv() => {
                        let Some(progress) = progress else {
                            continue;
                        };
                        if handle
                            .send(super::root_program::BcodeRuntimeMessage::EffectCompleted(
                                Box::new(progress),
                            ))
                            .await
                            .is_err()
                        {
                            break None;
                        }
                    }
                }
            }
        };
        match schedule {
            EffectSchedule::StartIfIdle => bmux_tui_runtime::Command::start_if_idle(key, future),
            EffectSchedule::Replace => bmux_tui_runtime::Command::replace(key, future),
            EffectSchedule::QueueLatest => bmux_tui_runtime::Command::queue_latest(key, future),
            EffectSchedule::Cancel => bmux_tui_runtime::Command::cancel(key),
        }
    }

    fn key(&self) -> EffectKey {
        match self {
            Self::QueueRecovery { .. } => EffectKey::QueueRecovery,
            Self::OpenSession { .. } => EffectKey::SessionOpen,
            Self::LoadConfig => EffectKey::Config,
            Self::PersistThemeSelection { .. } | Self::ClearThemeSelection => {
                EffectKey::ThemeSelection
            }
            Self::PersistStreamingPresentation { .. } | Self::ClearStreamingPresentation => {
                EffectKey::StreamingPresentation
            }
            Self::ReconcileAuthSecurity { .. } => EffectKey::AuthSecurity,
            Self::LoadDraftStatus { .. } => EffectKey::DraftStatus,
            Self::LoadSessionStatus { .. } => EffectKey::SessionStatus,
            Self::LoadSessionModelStatus { .. } => EffectKey::SessionModelStatus,
            Self::LoadPluginStatus { .. } => EffectKey::PluginStatus,
            Self::LoadAgentCatalog => EffectKey::AgentCatalog,
            Self::LoadOlderHistory { .. } => EffectKey::OlderHistory,
            Self::LoadNewerHistory { .. } => EffectKey::NewerHistory,
            Self::ListPermissions => EffectKey::PermissionList,
            Self::SaveDraft { .. } => EffectKey::DraftSave,
            Self::LoadSlashPalette { .. } => EffectKey::SlashPalette,
            Self::LoadCommandPalette => EffectKey::CommandPalette,
            Self::LoadSessionChildren { parent_id, .. } => EffectKey::SessionChildren(*parent_id),
            Self::LoadChildActivity { session_id, .. } => EffectKey::ChildActivity(*session_id),
            Self::LoadSessionPicker { .. } => EffectKey::SessionPicker,
            Self::ImportSession { .. } => EffectKey::ImportSession,
            Self::RenameSession { session_id, .. } => EffectKey::RenameSession(*session_id),
            Self::DeleteSession { session_id } => EffectKey::DeleteSession(*session_id),
            Self::SearchSessions { .. } => EffectKey::SearchSessions,
            Self::StartBulkMigration { .. }
            | Self::CancelBulkMigration { .. }
            | Self::WaitBulkMigration { .. } => EffectKey::BulkMigration,
            Self::StartSearchIndexing { .. }
            | Self::CancelSearchIndexing { .. }
            | Self::WaitSearchIndexing { .. } => EffectKey::SearchIndexing,
            Self::ExecuteSlashCommand { .. } => EffectKey::SlashCommand,
            Self::RalphAction { .. } => EffectKey::RalphAction,
            Self::RalphStart { .. } => EffectKey::RalphStart,
            Self::OpenPluginSurface { .. } => EffectKey::PluginSurface,
            Self::LoadModelProviders => EffectKey::ModelProviders,
            Self::LoadAuthPoolPicker => EffectKey::AuthPoolPicker,
            Self::SetAuthPoolPreference { .. } => EffectKey::AuthPoolPreference,
            Self::CheckSelectedModel { .. } => EffectKey::ModelCheck,
            Self::LoadModelPicker { .. } => EffectKey::ModelPicker,
            Self::LoadSkillPicker => EffectKey::SkillPicker,
            Self::DescribeSkill { .. } => EffectKey::SkillDescription,
            Self::LoadThinkingDialog { .. } => EffectKey::ThinkingDialog,
            Self::LoadMilestones { .. } | Self::LoadTimelineJump { .. } => EffectKey::TimelineJump,
            Self::InvokePluginCommand {
                plugin_id,
                command_id,
                ..
            } => EffectKey::PluginCommand(plugin_id.clone(), command_id.clone()),
            Self::SubmitMessage { request } => {
                EffectKey::SubmitMessage(request.submission_id.clone())
            }
            Self::SkillAction { request } => EffectKey::SkillAction(request.skill_id.clone()),
            Self::SetSessionModel { session_id, .. } => EffectKey::SetSessionModel(*session_id),
            Self::SetSessionReasoning { session_id, .. } => {
                EffectKey::SetSessionReasoning(*session_id)
            }
            Self::AppendPresentationNote {
                session_id,
                note_id,
                ..
            } => EffectKey::AppendPresentationNote(*session_id, note_id.clone()),
            Self::CancelRuntimeWork { session_id, .. } => EffectKey::CancelRuntimeWork(*session_id),
            Self::CompactContext { session_id } => EffectKey::CompactContext(*session_id),
            Self::AttachWorktree { session_id, .. } => EffectKey::AttachWorktree(*session_id),
            Self::CreateWorktree { .. } | Self::WaitWorktreeCreate { .. } => {
                EffectKey::CreateWorktree
            }
            Self::CancelTurn { session_id } => EffectKey::CancelTurn(*session_id),
            Self::ResolvePermission { permission_id, .. } => {
                EffectKey::ResolvePermission(permission_id.clone())
            }
        }
    }

    async fn run_session_status_effect(
        client: &BcodeClient,
        session_id: SessionId,
    ) -> TuiEffectResult {
        Box::pin(load_session_status(client, session_id)).await
    }

    #[allow(clippy::too_many_lines, clippy::large_stack_frames)]
    async fn run(
        self,
        client: BcodeClient,
        streaming_sender: mpsc::Sender<TuiEffectResult>,
    ) -> TuiEffectResult {
        match self {
            Self::QueueRecovery {
                session_id,
                generation,
                action,
            } => {
                let result = async {
                    let outcome = execute_session_view_action(&client, *action).await?;
                    let status = client.queue_status(session_id).await?;
                    Ok((outcome, status))
                }
                .await;
                TuiEffectResult::QueueRecovery {
                    session_id,
                    generation,
                    result: Box::new(result),
                }
            }
            Self::LoadSessionChildren {
                parent_id,
                after,
                generation,
            } => TuiEffectResult::SessionChildrenLoaded {
                parent_id,
                generation,
                result: client
                    .query_child_sessions(bcode_session_models::SessionChildQuery {
                        parent_id,
                        after,
                        limit: 64,
                    })
                    .await,
            },
            Self::LoadChildActivity {
                session_id,
                after,
                generation,
            } => TuiEffectResult::ChildActivityLoaded {
                session_id,
                generation,
                result: client
                    .session_activity(
                        session_id,
                        bcode_session_models::SessionActivityQuery {
                            scope: bcode_session_models::SessionActivityScope::DirectChildren,
                            after,
                            limit: 64,
                        },
                    )
                    .await
                    .map(|mut page| {
                        // A terminal continuation is complete for its query, not for the
                        // currently displayed window of the whole direct-child scope.
                        if after.is_some()
                            && page.coverage
                                == bcode_session_models::SessionActivityCoverage::Complete
                        {
                            page.coverage = bcode_session_models::SessionActivityCoverage::Partial;
                        }
                        page
                    }),
            },
            Self::OpenSession {
                session_id,
                initial_window_request,
                event_sender,
                allow_daemon_start: _,
            } => TuiEffectResult::SessionOpened {
                session_id,
                has_older_history: true,
                result: Box::new(
                    history_flow::attach_session_event_stream_with_window_request(
                        &client,
                        session_id,
                        event_sender,
                        initial_window_request,
                        |snapshot| {
                            let _result =
                                streaming_sender.try_send(TuiEffectResult::SessionOpenProgress {
                                    snapshot: snapshot.clone(),
                                });
                        },
                    )
                    .await,
                ),
            },
            Self::LoadConfig => TuiEffectResult::ConfigLoaded {
                config: Box::new(bcode_config::load_config().map_err(|error| error.to_string())),
                theme_selection: bcode_config::load_tui_theme_selection()
                    .map_err(|error| error.to_string()),
                streaming_presentation: bcode_config::load_tui_streaming_presentation_override()
                    .map_err(|error| error.to_string()),
            },
            Self::PersistThemeSelection { name } => TuiEffectResult::ThemeSelectionPersisted {
                result: bcode_config::set_tui_theme_selection(&name)
                    .map_err(|error| error.to_string()),
                name: Some(name),
            },
            Self::ClearThemeSelection => TuiEffectResult::ThemeSelectionPersisted {
                result: bcode_config::clear_tui_theme_selection()
                    .map_err(|error| error.to_string()),
                name: None,
            },
            Self::PersistStreamingPresentation { policy } => {
                TuiEffectResult::StreamingPresentationPersisted {
                    result: bcode_config::set_tui_streaming_presentation_override(policy)
                        .map_err(|error| error.to_string()),
                    policy: Some(policy.normalized()),
                }
            }
            Self::ClearStreamingPresentation => TuiEffectResult::StreamingPresentationPersisted {
                result: bcode_config::clear_tui_streaming_presentation_override()
                    .map_err(|error| error.to_string()),
                policy: None,
            },
            Self::ReconcileAuthSecurity { config } => TuiEffectResult::AuthSecurityReconciled {
                status: session_flow::auth_security_status(&config),
            },
            Self::LoadDraftStatus {
                launch_working_directory,
            } => Box::pin(load_draft_status(&client, launch_working_directory)).await,
            Self::LoadSessionStatus { session_id } => {
                Box::pin(Self::run_session_status_effect(&client, session_id)).await
            }
            Self::LoadSessionModelStatus { session_id } => {
                TuiEffectResult::SessionModelStatusLoaded {
                    session_id,
                    result: client.session_model_status(session_id).await,
                }
            }
            Self::LoadPluginStatus { session_id } => {
                let (plugin_status, error) = load_plugin_session_status(&client, session_id).await;
                TuiEffectResult::PluginStatusLoaded {
                    session_id,
                    plugin_status,
                    error,
                }
            }
            Self::LoadAgentCatalog => TuiEffectResult::AgentCatalogLoaded {
                agents: AgentCatalog::load(&client)
                    .await
                    .map_err(|error| error.to_string()),
            },
            Self::LoadOlderHistory {
                session_id,
                cursor,
                generation,
                width_columns,
            } => TuiEffectResult::OlderHistoryLoaded {
                session_id,
                cursor,
                generation,
                result: load_transcript_history_page(
                    &client,
                    session_id,
                    cursor,
                    width_columns,
                    true,
                )
                .await,
            },
            Self::LoadNewerHistory {
                session_id,
                cursor,
                generation,
                width_columns,
            } => TuiEffectResult::NewerHistoryLoaded {
                session_id,
                cursor,
                generation,
                result: load_transcript_history_page(
                    &client,
                    session_id,
                    cursor,
                    width_columns,
                    false,
                )
                .await,
            },
            Self::ListPermissions => TuiEffectResult::PermissionList {
                result: client.list_permissions().await,
            },
            Self::SaveDraft { scope, text } => {
                let scope = match scope {
                    ComposerDraftScope::Session { session_id } => {
                        bcode_session_view_models::ComposerDraftViewScope::Session { session_id }
                    }
                    ComposerDraftScope::DraftSession {
                        launch_working_directory,
                    } => bcode_session_view_models::ComposerDraftViewScope::DraftSession {
                        launch_working_directory,
                    },
                };
                let result = execute_session_view_action(
                    &client,
                    SessionViewAction::UpdateDraft {
                        scope,
                        text: text.clone(),
                    },
                )
                .await
                .map(|_| ());
                TuiEffectResult::SaveDraft { text, result }
            }
            Self::LoadSlashPalette {
                query,
                session_id,
                generation,
                provider_plugin_id,
            } => {
                let palette = slash_palette::SlashPalette::discover(
                    &client,
                    session_id,
                    provider_plugin_id,
                    &query,
                )
                .await;
                TuiEffectResult::SlashPaletteLoaded {
                    query,
                    palette,
                    generation,
                }
            }
            Self::LoadCommandPalette => TuiEffectResult::CommandPaletteLoaded {
                result: client
                    .plugin_contributions()
                    .await
                    .map(|contributions| contributions.command_contributions),
            },
            Self::LoadSessionPicker {
                generation,
                scope,
                query,
                cursor,
            } => {
                let result = async {
                    if let bcode_session_models::SessionDiscoveryScope::WorkingDirectory(_) = &scope
                    {
                        let mut watcher = client.watch_session_catalog_with_scope(scope).await?;
                        let mut snapshot = watcher.initial_snapshot().await?;
                        loop {
                            let page = bcode_session_models::SessionCatalogPage {
                                sessions: snapshot.sessions,
                                catalog_status: snapshot.catalog_status,
                                catalog_sources: snapshot.catalog_sources,
                                catalog_revision: snapshot.catalog_revision,
                                next_cursor: None,
                            };
                            if streaming_sender
                                .send(TuiEffectResult::SessionPickerLoaded {
                                    result: Ok(page),
                                    generation,
                                    restart: false,
                                })
                                .await
                                .is_err()
                            {
                                return Err(ClientError::Protocol(
                                    "session picker receiver closed".into(),
                                ));
                            }
                            snapshot = watcher.next_snapshot().await?;
                        }
                    }
                    let mut watcher = client
                        .watch_session_catalog_with_scope(scope.clone())
                        .await?;
                    let initial = client
                        .list_sessions_page_with_scope(
                            scope.clone(),
                            query.clone(),
                            cursor.clone(),
                            100,
                        )
                        .await?;
                    if streaming_sender
                        .send(TuiEffectResult::SessionPickerLoaded {
                            result: Ok(initial),
                            generation,
                            restart: false,
                        })
                        .await
                        .is_err()
                    {
                        return Err(ClientError::Protocol(
                            "session picker receiver closed".into(),
                        ));
                    }
                    loop {
                        watcher.next_revision().await?;
                        let snapshot = client
                            .list_sessions_page_with_scope(scope.clone(), query.clone(), None, 100)
                            .await?;
                        if streaming_sender
                            .send(TuiEffectResult::SessionPickerLoaded {
                                result: Ok(snapshot),
                                generation,
                                restart: true,
                            })
                            .await
                            .is_err()
                        {
                            return Err(ClientError::Protocol(
                                "session picker receiver closed".into(),
                            ));
                        }
                    }
                }
                .await;
                TuiEffectResult::SessionPickerLoaded {
                    result,
                    generation,
                    restart: false,
                }
            }
            Self::ImportSession {
                source_id,
                external_session_id,
            } => TuiEffectResult::SessionImported {
                result: client
                    .import_external_session(source_id, external_session_id)
                    .await,
            },
            Self::RenameSession { session_id, name } => TuiEffectResult::SessionRenamed {
                result: execute_session_view_action(
                    &client,
                    SessionViewAction::RenameSession { session_id, name },
                )
                .await
                .and_then(|outcome| match outcome {
                    SessionViewActionOutcome::SessionRenamed { session } => Ok(*session),
                    _ => Err(ClientError::UnexpectedResponse),
                }),
            },
            Self::DeleteSession { session_id } => TuiEffectResult::SessionDeleted {
                result: execute_session_view_action(
                    &client,
                    SessionViewAction::DeleteSession { session_id },
                )
                .await
                .and_then(|outcome| match outcome {
                    SessionViewActionOutcome::SessionDeleted { session } => Ok(*session),
                    _ => Err(ClientError::UnexpectedResponse),
                }),
            },
            Self::SearchSessions { request, policy } => TuiEffectResult::SessionsSearched {
                result: client
                    .session_search(*request, policy, Vec::new(), true)
                    .await,
            },
            Self::StartBulkMigration { request } => TuiEffectResult::BulkMigrationUpdated {
                result: client.start_session_bulk_migration(request).await,
            },
            Self::CancelBulkMigration { operation_id } => TuiEffectResult::BulkMigrationUpdated {
                result: client.cancel_session_bulk_migration(operation_id).await,
            },
            Self::WaitBulkMigration {
                operation_id,
                after_revision,
            } => TuiEffectResult::BulkMigrationWaited {
                result: client
                    .wait_session_bulk_migration(operation_id, after_revision, 30_000)
                    .await,
            },
            Self::StartSearchIndexing { request } => TuiEffectResult::SearchIndexingStarted {
                result: client.session_search_index_all_start(request).await,
            },
            Self::CancelSearchIndexing { operation_id } => TuiEffectResult::SearchIndexingUpdated {
                result: client.session_search_backfill_cancel(operation_id).await,
            },
            Self::WaitSearchIndexing {
                operation_id,
                after_revision,
            } => TuiEffectResult::SearchIndexingWaited {
                result: client
                    .session_search_backfill_wait(operation_id, after_revision, 30_000)
                    .await,
            },
            Self::ExecuteSlashCommand {
                session_id,
                working_directory,
                current_agent_id,
                reasoning_display_mode,
                reasoning_visible,
                message,
            } => {
                let result = match super::slash_registry::resolve(&client, &message).await {
                    Ok(resolution) => {
                        super::slash_commands::execute_resolved(
                            &client,
                            session_id,
                            super::slash_commands::SlashExecutionContext {
                                working_directory: &working_directory,
                                current_agent_id: &current_agent_id,
                                reasoning_display_mode,
                                reasoning_visible,
                            },
                            &message,
                            resolution,
                        )
                        .await
                    }
                    Err(error) => Err(error),
                };
                TuiEffectResult::SlashCommandExecuted { message, result }
            }
            Self::RalphAction { repo_root, action } => TuiEffectResult::RalphAction {
                action,
                result: super::ralph_flow::execute_root_action(&client, repo_root, action).await,
            },
            Self::RalphStart { request } => TuiEffectResult::RalphStarted {
                result: super::ralph_flow::execute_root_start(&client, request).await,
            },
            Self::OpenPluginSurface {
                plugin_id,
                surface_kind,
                instance_id,
                options,
                working_directory,
                session_id,
            } => {
                let result = async {
                    let options = super::palette_flow::hydrate_root_plugin_surface_options(
                        &client, session_id, options,
                    )
                    .await;
                    let runtime =
                        bcode_plugin::PluginRuntimeHost::load_defaults_with_static_bundled(
                            &bcode_plugin::PluginSelection::all_enabled(),
                            &crate::static_bundled_plugins(),
                        )
                        .map_err(|error| TuiError::PluginService {
                            code: "plugin_runtime_load_failed".to_owned(),
                            message: error.to_string(),
                        })?;
                    crate::plugin_tui::open_plugin_tui_surface(
                        &runtime,
                        &plugin_id,
                        &surface_kind,
                        bcode_plugin_sdk::tui::PluginTuiSurfaceOpenRequest {
                            instance_id,
                            repo_path: Some(working_directory),
                            session_id,
                            target: None,
                            options,
                        },
                    )
                    .await
                    .map_err(|error| TuiError::PluginService {
                        code: "tui_surface_open_failed".to_owned(),
                        message: error.to_string(),
                    })
                }
                .await;
                TuiEffectResult::PluginSurfaceOpened { plugin_id, result }
            }
            Self::LoadModelProviders => TuiEffectResult::ModelProvidersLoaded {
                result: client.plugin_services().await.map(|services| {
                    services
                        .into_iter()
                        .filter(|service| {
                            service.interface_id == bcode_model::MODEL_PROVIDER_INTERFACE_ID
                        })
                        .collect()
                }),
            },
            Self::LoadAuthPoolPicker => TuiEffectResult::AuthPoolPickerLoaded {
                result: client.auth_pool_list().await,
            },
            Self::SetAuthPoolPreference { pool, profile } => {
                TuiEffectResult::AuthPoolPreferenceSet {
                    pool: pool.clone(),
                    profile: profile.clone(),
                    result: client.set_auth_pool_preference(pool, profile).await,
                }
            }
            Self::CheckSelectedModel {
                session_id,
                provider_plugin_id,
                model_id,
                generation,
            } => {
                let result = client
                    .check_models(
                        session_id,
                        provider_plugin_id.clone(),
                        vec![model_id],
                        20,
                        true,
                    )
                    .await;
                let models = match session_id {
                    Some(id) => {
                        client
                            .session_model_list_for_session(id, provider_plugin_id.clone())
                            .await
                    }
                    None => client.session_model_list(provider_plugin_id.clone()).await,
                };
                TuiEffectResult::SelectedModelChecked {
                    session_id,
                    provider_plugin_id,
                    generation,
                    result,
                    models,
                }
            }
            Self::LoadModelPicker { provider_plugin_id } => TuiEffectResult::ModelPickerLoaded {
                result: client.session_model_list(provider_plugin_id.clone()).await,
                provider_plugin_id,
            },
            Self::LoadSkillPicker => TuiEffectResult::SkillPickerLoaded {
                result: client.list_skills().await,
            },
            Self::DescribeSkill { skill_id } => TuiEffectResult::SkillDescribed {
                skill_id: skill_id.clone(),
                result: client.describe_skill(skill_id).await,
            },
            Self::LoadMilestones { request } => TuiEffectResult::MilestonesLoaded {
                request,
                result: client
                    .session_milestones(
                        request.session_id,
                        bcode_session_models::SessionMilestoneQuery {
                            after_sequence: request.after_sequence,
                            limit: 200,
                        },
                    )
                    .await,
            },
            Self::LoadThinkingDialog { session_id, focus } => {
                let result = match session_id {
                    Some(session_id) => client.session_model_status(session_id).await,
                    None => client.default_model_status().await,
                };
                TuiEffectResult::ThinkingDialogLoaded { focus, result }
            }
            Self::LoadTimelineJump {
                session_id,
                generation,
                sequence,
            } => TuiEffectResult::TimelineJumpLoaded {
                session_id,
                generation,
                sequence,
                result: super::history_flow::load_timeline_jump_events(
                    &client, session_id, sequence,
                )
                .await,
            },
            Self::InvokePluginCommand {
                plugin_id,
                command_id,
                arguments,
                working_directory,
                session_id,
            } => {
                let mut args = BTreeMap::new();
                if let Some(arguments) = arguments.filter(|value| !value.is_empty()) {
                    args.insert("arguments".to_owned(), arguments);
                }
                let result = async {
                    let payload = serde_json::to_vec(&bcode_command::InvokeCommandRequest {
                        command_id,
                        args,
                        context: Some(bcode_command::CommandInvocationContext {
                            session_id,
                            working_directory,
                        }),
                    })?;
                    let response = client
                        .invoke_plugin_service(
                            plugin_id.clone(),
                            bcode_command::COMMAND_INTERFACE_ID.to_owned(),
                            bcode_command::OP_INVOKE_COMMAND.to_owned(),
                            payload,
                        )
                        .await?;
                    if let Some(error) = response.error {
                        return Err(TuiError::PluginService {
                            code: error.code,
                            message: error.message,
                        });
                    }
                    Ok(serde_json::from_slice::<
                        bcode_command::InvokeCommandResponse,
                    >(&response.payload)?)
                }
                .await;
                TuiEffectResult::PluginCommandInvoked { plugin_id, result }
            }
            Self::SubmitMessage { request } => run_submit_message(&client, *request).await,
            Self::SkillAction { request } => run_skill_action(&client, *request).await,
            Self::SetSessionModel {
                session_id,
                provider_plugin_id,
                model_id,
            } => TuiEffectResult::SetSessionModel {
                session_id,
                provider_plugin_id: provider_plugin_id.clone(),
                model_id: model_id.clone(),
                result: execute_session_view_action(
                    &client,
                    SessionViewAction::SetModel {
                        session_id,
                        provider_plugin_id,
                        model_id,
                    },
                )
                .await
                .map(|_| ()),
            },
            Self::SetSessionReasoning {
                session_id,
                effort,
                summary,
                effort_generation,
                status,
            } => TuiEffectResult::SetSessionReasoning {
                session_id,
                effort: effort.clone(),
                effort_generation,
                status,
                result: execute_session_view_action(
                    &client,
                    SessionViewAction::SetReasoning {
                        session_id,
                        effort,
                        summary,
                    },
                )
                .await
                .map(|_| ()),
            },
            Self::AppendPresentationNote {
                session_id,
                source_id,
                note_id,
                text,
                format,
            } => TuiEffectResult::AppendPresentationNote {
                session_id,
                result: client
                    .append_presentation_note(session_id, source_id, note_id, text, format)
                    .await,
            },
            Self::CancelRuntimeWork {
                session_id,
                work_id,
            } => TuiEffectResult::CancelRuntimeWork {
                work_id: work_id.clone(),
                result: match execute_session_view_action(
                    &client,
                    SessionViewAction::CancelRuntimeWork {
                        session_id,
                        work_id,
                    },
                )
                .await
                {
                    Ok(SessionViewActionOutcome::RuntimeWorkCancellationRequested {
                        cancelled,
                    }) => Ok(cancelled),
                    Ok(_) => Err(ClientError::UnexpectedResponse),
                    Err(error) => Err(error),
                },
            },
            Self::CompactContext { session_id } => TuiEffectResult::CompactContext {
                session_id,
                result: match execute_session_view_action(
                    &client,
                    SessionViewAction::CompactContext { session_id },
                )
                .await
                {
                    Ok(SessionViewActionOutcome::ContextCompacted { message }) => Ok(message),
                    Ok(_) => Err(ClientError::UnexpectedResponse),
                    Err(error) => Err(error),
                },
            },
            Self::AttachWorktree { session_id, path } => TuiEffectResult::AttachWorktree {
                path: path.clone(),
                result: match execute_session_view_action(
                    &client,
                    SessionViewAction::ChangeWorkingDirectory { session_id, path },
                )
                .await
                {
                    Ok(SessionViewActionOutcome::WorkingDirectoryChanged { session }) => {
                        Ok(*session)
                    }
                    Ok(_) => Err(ClientError::UnexpectedResponse),
                    Err(error) => Err(error),
                },
            },
            Self::CreateWorktree {
                operation_id,
                request,
            } => TuiEffectResult::CreateWorktree {
                result: client.start_worktree_create(operation_id, request).await,
            },
            Self::WaitWorktreeCreate {
                operation_id,
                after_revision,
            } => TuiEffectResult::CreateWorktree {
                result: client
                    .wait_worktree_create(operation_id, after_revision, 30_000)
                    .await,
            },
            Self::CancelTurn { session_id } => TuiEffectResult::CancelTurn {
                session_id,
                result: match execute_session_view_action(
                    &client,
                    active_turn_cancel_action(session_id),
                )
                .await
                {
                    Ok(SessionViewActionOutcome::Cancelled { cancelled }) => Ok(cancelled),
                    Ok(_) => Err(ClientError::UnexpectedResponse),
                    Err(error) => Err(error),
                },
            },
            Self::ResolvePermission {
                permission_id,
                approved,
                remember,
                apply_to_batch,
                batch_id,
            } => {
                let result = if apply_to_batch {
                    let Some(batch_id) = batch_id else {
                        return TuiEffectResult::PermissionResolved {
                            permission_id,
                            approved,
                            remember,
                            apply_to_batch,
                            result: Err(ClientError::UnexpectedResponse),
                        };
                    };
                    match execute_session_view_action(
                        &client,
                        SessionViewAction::ResolvePermissionBatch { batch_id, approved },
                    )
                    .await
                    {
                        Ok(SessionViewActionOutcome::PermissionBatchResolved {
                            resolved_count,
                        }) => Ok(resolved_count > 0),
                        Ok(_) => Err(ClientError::UnexpectedResponse),
                        Err(error) => Err(error),
                    }
                } else {
                    match execute_session_view_action(
                        &client,
                        SessionViewAction::ResolvePermission {
                            permission_id: permission_id.clone(),
                            approved,
                            remember,
                        },
                    )
                    .await
                    {
                        Ok(SessionViewActionOutcome::PermissionResolved { resolved }) => {
                            Ok(resolved)
                        }
                        Ok(_) => Err(ClientError::UnexpectedResponse),
                        Err(error) => Err(error),
                    }
                };
                TuiEffectResult::PermissionResolved {
                    permission_id,
                    approved,
                    remember,
                    apply_to_batch,
                    result,
                }
            }
        }
    }
}

async fn ensure_session_for_foreground_action(
    client: &BcodeClient,
    session_id: Option<SessionId>,
    launch_working_directory: std::path::PathBuf,
    event_sender: mpsc::Sender<super::history_flow::SessionStreamUpdate>,
) -> Result<
    (
        SessionId,
        Option<SessionSummary>,
        Option<JoinHandle<()>>,
        Option<oneshot::Sender<()>>,
    ),
    ClientError,
> {
    if let Some(session_id) = session_id {
        return Ok((session_id, None, None, None));
    }
    let session = client
        .create_session_in_working_directory(None, launch_working_directory.clone())
        .await?;
    let _ = execute_session_view_action(
        client,
        SessionViewAction::UpdateDraft {
            scope: bcode_session_view_models::ComposerDraftViewScope::DraftSession {
                launch_working_directory,
            },
            text: String::new(),
        },
    )
    .await;
    let (attached, task, release) =
        history_flow::attach_paused_session_event_stream(client, session.id, event_sender)
            .await
            .map_err(|error| match error {
                TuiError::Client(error) => error,
                other => ClientError::Server {
                    code: "tui_session_attach_failed".to_owned(),
                    message: other.to_string(),
                },
            })?;
    Ok((
        session.id,
        Some(attached.session),
        Some(task),
        Some(release),
    ))
}

async fn run_skill_action(client: &BcodeClient, request: SkillActionRequest) -> TuiEffectResult {
    let action = request.action;
    let skill_id = request.skill_id.clone();
    TuiEffectResult::SkillAction {
        action,
        skill_id,
        result: Box::new(skill_action(client, request).await),
    }
}

async fn skill_action(
    client: &BcodeClient,
    request: SkillActionRequest,
) -> Result<SkillActionResult, ClientError> {
    let SkillActionRequest {
        session_id,
        launch_working_directory,
        skill_id,
        action,
        arguments,
        provider_plugin_id,
        model_id,
        agent_id,
        reasoning_effort,
        reasoning_summary,
        reasoning_effort_generation,
        mut execution,
        event_sender,
    } = request;
    execution.reasoning = Some(Box::new(bcode_session_models::TurnReasoningOptions {
        effort: reasoning_effort.clone(),
        summary: reasoning_summary.clone(),
    }));
    execution.agent_profile.clone_from(&agent_id);
    let (session_id, created_session, event_task, event_stream_release) =
        ensure_session_for_foreground_action(
            client,
            session_id,
            launch_working_directory,
            event_sender,
        )
        .await?;
    let acceptance = match action {
        SkillActionKind::Activate => {
            execute_session_view_action(
                client,
                SessionViewAction::ActivateSkill {
                    session_id,
                    skill_id: skill_id.to_string(),
                },
            )
            .await?;
            None
        }
        SkillActionKind::Deactivate => {
            execute_session_view_action(
                client,
                SessionViewAction::DeactivateSkill {
                    session_id,
                    skill_id: skill_id.to_string(),
                },
            )
            .await?;
            None
        }
        SkillActionKind::Invoke => {
            apply_submit_runtime_selections(
                client,
                session_id,
                provider_plugin_id,
                model_id,
                None,
                reasoning_effort.clone(),
                reasoning_summary.clone(),
            )
            .await?;
            let display_text = if arguments.trim().is_empty() {
                format!("Invoke skill {skill_id}")
            } else {
                format!("Invoke skill {skill_id}: {arguments}")
            };
            let outcome = execute_session_view_action(
                client,
                SessionViewAction::InvokeSkill {
                    session_id,
                    skill_id: skill_id.to_string(),
                    arguments,
                    display_text,
                    execution: Box::new(execution),
                },
            )
            .await?;
            Some(message_acceptance_from_action_outcome(&outcome)?)
        }
    };
    Ok(SkillActionResult {
        session_id,
        created_session,
        event_task,
        acceptance,
        committed_agent_id: (action == SkillActionKind::Invoke)
            .then_some(agent_id)
            .flatten(),
        committed_reasoning_effort_generation: (action == SkillActionKind::Invoke)
            .then_some(reasoning_effort_generation)
            .flatten(),
        event_stream_release,
    })
}

async fn run_submit_message(
    client: &BcodeClient,
    request: SubmitMessageRequest,
) -> TuiEffectResult {
    let message = request.message.clone();
    TuiEffectResult::SubmitMessage {
        submission_id: request.submission_id.clone(),
        message,
        result: Box::new(submit_message(client, request).await),
    }
}

pub async fn apply_submit_runtime_selections(
    client: &BcodeClient,
    session_id: SessionId,
    provider_plugin_id: Option<String>,
    model_id: Option<String>,
    agent_id: Option<String>,
    reasoning_effort: Option<String>,
    reasoning_summary: Option<String>,
) -> Result<(), ClientError> {
    if let Some(model_id) = model_id {
        execute_session_view_action(
            client,
            SessionViewAction::SetModel {
                session_id,
                provider_plugin_id,
                model_id,
            },
        )
        .await?;
    }
    if let Some(agent_id) = agent_id {
        execute_session_view_action(
            client,
            SessionViewAction::SetAgent {
                session_id,
                agent_id,
            },
        )
        .await?;
    }
    execute_session_view_action(
        client,
        SessionViewAction::SetReasoning {
            session_id,
            effort: reasoning_effort,
            summary: reasoning_summary,
        },
    )
    .await?;
    Ok(())
}

fn message_acceptance_from_action_outcome(
    outcome: &SessionViewActionOutcome,
) -> Result<MessageAcceptance, ClientError> {
    let SessionViewActionOutcome::MessageAccepted {
        queued,
        queue_position,
        disposition,
        ..
    } = outcome
    else {
        return Err(ClientError::UnexpectedResponse);
    };
    Ok(MessageAcceptance {
        queued: *queued,
        queue_position: queue_position.and_then(|position| u32::try_from(position).ok()),
        disposition: match disposition {
            bcode_session_view_models::MessageAcceptanceDispositionView::AppliedSteering => {
                bcode_ipc::MessageAcceptanceDisposition::AppliedSteering
            }
            bcode_session_view_models::MessageAcceptanceDispositionView::QueuedFollowUp => {
                bcode_ipc::MessageAcceptanceDisposition::QueuedFollowUp
            }
            bcode_session_view_models::MessageAcceptanceDispositionView::QueuedTurn => {
                bcode_ipc::MessageAcceptanceDisposition::QueuedTurn
            }
            bcode_session_view_models::MessageAcceptanceDispositionView::StartedTurn => {
                bcode_ipc::MessageAcceptanceDisposition::StartedTurn
            }
        },
    })
}

#[allow(clippy::too_many_lines)]
fn submission_stage_error(stage: &'static str, error: ClientError) -> ClientError {
    match error {
        ClientError::RequestTimeout { timeout } => ClientError::Server {
            code: "tui_submission_request_timeout".into(),
            message: format!(
                "Message submission timed out while {stage} after {timeout:?}. Acceptance is not confirmed; check session history before retrying."
            ),
        },
        other => other,
    }
}

#[cfg(test)]
mod submission_error_tests {
    use super::*;

    #[test]
    fn timeout_reports_stage_without_claiming_rejection_or_restart() {
        let error = submission_stage_error(
            "waiting for message acceptance",
            ClientError::RequestTimeout {
                timeout: std::time::Duration::from_secs(30),
            },
        );
        let ClientError::Server { code, message } = error else {
            panic!("stage diagnostic");
        };
        assert_eq!(code, "tui_submission_request_timeout");
        assert!(message.contains("waiting for message acceptance"));
        assert!(message.contains("Acceptance is not confirmed"));
        let startup = submission_stage_error(
            "creating the session",
            ClientError::DaemonStartupTimeout {
                timeout: std::time::Duration::from_secs(10),
            },
        );
        assert!(matches!(startup, ClientError::DaemonStartupTimeout { .. }));
    }
}

fn submission_attach_error(error: TuiError) -> ClientError {
    match error {
        TuiError::Client(error) => {
            submission_stage_error("attaching the session event stream", error)
        }
        other => ClientError::Server {
            code: "tui_session_attach_failed".into(),
            message: other.to_string(),
        },
    }
}

async fn submit_message(
    client: &BcodeClient,
    request: SubmitMessageRequest,
) -> Result<SubmitMessageResult, ClientError> {
    let SubmitMessageRequest {
        submission_id,
        session_id,
        launch_working_directory,
        message,
        placement,
        provider_plugin_id,
        model_id,
        agent_id,
        reasoning_effort,
        reasoning_summary,
        reasoning_effort_generation,
        mut execution,
        event_sender,
    } = request;
    execution.reasoning = Some(Box::new(bcode_session_models::TurnReasoningOptions {
        effort: reasoning_effort.clone(),
        summary: reasoning_summary.clone(),
    }));
    execution.agent_profile.clone_from(&agent_id);
    let mut message = message;
    let mut created_session = None;
    let mut event_task = None;
    let mut event_stream_release = None;
    let session_id = if let Some(session_id) = session_id {
        session_id
    } else {
        let session = client
            .create_session_in_working_directory(None, launch_working_directory.clone())
            .await
            .map_err(|error| submission_stage_error("creating the session", error))?;
        let _ = execute_session_view_action(
            client,
            SessionViewAction::UpdateDraft {
                scope: bcode_session_view_models::ComposerDraftViewScope::DraftSession {
                    launch_working_directory: launch_working_directory.clone(),
                },
                text: String::new(),
            },
        )
        .await;
        let (attached, task, release) =
            history_flow::attach_paused_session_event_stream(client, session.id, event_sender)
                .await
                .map_err(submission_attach_error)?;
        let session_id = session.id;
        message = clipboard_image::promote_draft_clipboard_images(
            &message,
            &launch_working_directory,
            session_id,
        )
        .map_err(|error| ClientError::Server {
            code: "tui_clipboard_image_promotion_failed".to_owned(),
            message: error.to_string(),
        })?;
        created_session = Some(attached.session);
        event_task = Some(task);
        event_stream_release = Some(release);
        session_id
    };
    apply_submit_runtime_selections(
        client,
        session_id,
        provider_plugin_id,
        model_id,
        None,
        reasoning_effort.clone(),
        reasoning_summary.clone(),
    )
    .await
    .map_err(|error| submission_stage_error("applying model/agent/reasoning selections", error))?;
    let outcome = execute_session_view_action(
        client,
        SessionViewAction::SubmitMessage {
            submission_id,
            session_id: Some(session_id),
            launch_working_directory: None,
            text: message,
            placement,
            execution: Box::new(execution),
        },
    )
    .await
    .map_err(|error| submission_stage_error("waiting for message acceptance", error))?;
    let receipt = submission_receipt_from_action(outcome)?;
    Ok(SubmitMessageResult {
        session_id,
        created_session,
        submission: client
            .get_submission(session_id, receipt.submission_id.clone())
            .await,
        receipt,
        committed_agent_id: agent_id,
        committed_reasoning_effort_generation: reasoning_effort_generation,
        event_task,
        event_stream_release,
    })
}

fn submission_receipt_from_action(
    outcome: SessionViewActionOutcome,
) -> Result<bcode_session_models::SubmissionReceipt, ClientError> {
    match outcome {
        SessionViewActionOutcome::SubmissionAccepted { receipt, .. } => Ok(receipt),
        _ => Err(ClientError::UnexpectedResponse),
    }
}

async fn optional_client_result<T>(
    future: impl std::future::Future<Output = Result<T, ClientError>>,
) -> (Option<T>, Option<String>) {
    match future.await {
        Ok(value) => (Some(value), None),
        Err(error) => (None, Some(error.to_string())),
    }
}

async fn load_draft_status(
    client: &BcodeClient,
    launch_working_directory: std::path::PathBuf,
) -> TuiEffectResult {
    let (model, model_error) =
        Box::pin(optional_client_result(client.default_model_status())).await;
    let draft_scope = ComposerDraftScope::DraftSession {
        launch_working_directory,
    };
    let (composer_draft, draft_error) =
        Box::pin(optional_client_result(client.composer_draft(draft_scope))).await;
    TuiEffectResult::DraftStatusLoaded {
        daemon_connected: model.is_some() || composer_draft.is_some(),
        model,
        composer_draft: composer_draft.flatten(),
        error: model_error.or(draft_error),
    }
}

async fn load_plugin_session_status(
    client: &BcodeClient,
    session_id: SessionId,
) -> (
    Vec<bcode_session_view_models::PluginStatusView>,
    Option<String>,
) {
    let services = match client.plugin_services().await {
        Ok(services) => services,
        Err(error) => return (Vec::new(), Some(error.to_string())),
    };
    let mut contributions = Vec::new();
    let mut first_error = None;
    for service in services
        .into_iter()
        .filter(|service| service.interface_id == bcode_plugin_sdk::SESSION_STATUS_INTERFACE_ID)
    {
        let plugin_id = service.plugin_id.clone();
        let payload =
            match serde_json::to_vec(&bcode_plugin_sdk::SessionStatusRequest { session_id }) {
                Ok(payload) => payload,
                Err(error) => {
                    first_error.get_or_insert_with(|| error.to_string());
                    continue;
                }
            };
        match client
            .invoke_plugin_service(
                service.plugin_id,
                bcode_plugin_sdk::SESSION_STATUS_INTERFACE_ID.to_owned(),
                bcode_plugin_sdk::OP_SESSION_STATUS.to_owned(),
                payload,
            )
            .await
        {
            Ok(response) if response.error.is_none() => {
                match serde_json::from_slice::<bcode_plugin_sdk::SessionStatusResponse>(
                    &response.payload,
                ) {
                    Ok(response) => {
                        contributions.extend(response.contribution.map(|contribution| {
                            bcode_session_view_models::PluginStatusView {
                                plugin_id: plugin_id.clone(),
                                note_id: contribution.contribution_id,
                                text: contribution.text,
                                priority: contribution.priority,
                                metadata: contribution.metadata,
                            }
                        }));
                    }
                    Err(error) => {
                        first_error.get_or_insert_with(|| error.to_string());
                    }
                }
            }
            Ok(response) => {
                if let Some(error) = response.error {
                    first_error.get_or_insert(error.message);
                }
            }
            Err(error) if error.is_optional_domain_unavailable() => {}
            Err(error) => {
                first_error.get_or_insert_with(|| error.to_string());
            }
        }
    }
    contributions.sort_by_key(|contribution| contribution.priority);
    (contributions, first_error)
}

#[cfg(any(
    feature = "static-bundled-code-review-plugin",
    feature = "static-bundled-filesystem-plugin",
    feature = "static-bundled-plugins",
    feature = "static-bundled-workflow-plugin"
))]
fn interaction_adapter_for_exchange(
    producer_id: &str,
    schema: &str,
    schema_version: u32,
    platform_id: &str,
) -> Option<bcode_plugin_sdk::interaction::PluginInteractionAdapterCapability> {
    bcode_bundled_plugins::interaction_adapter(producer_id, schema, schema_version, platform_id)
}

#[cfg(not(any(
    feature = "static-bundled-code-review-plugin",
    feature = "static-bundled-filesystem-plugin",
    feature = "static-bundled-plugins",
    feature = "static-bundled-workflow-plugin"
)))]
const fn interaction_adapter_for_exchange(
    _producer_id: &str,
    _schema: &str,
    _schema_version: u32,
    _platform_id: &str,
) -> Option<bcode_plugin_sdk::interaction::PluginInteractionAdapterCapability> {
    None
}

pub async fn load_pending_interactions(
    client: &BcodeClient,
    session_id: SessionId,
) -> Result<Vec<bcode_session_view_models::InteractionViewSummary>, ClientError> {
    let mut interactions = Vec::new();
    for request in client
        .list_pending_tool_exchanges()
        .await?
        .into_iter()
        .filter(|request| request.is_addressed_to(session_id))
    {
        let exchange = request.request;
        let interaction_id = exchange.exchange_id.clone();
        let producer_id = exchange.producer_id.clone();
        let exchange_schema = exchange.schema.clone();
        let exchange_schema_version = exchange.schema_version;
        let snapshot = exchange.payload;
        let adapter = interaction_adapter_for_exchange(
            &exchange.producer_id,
            &exchange.schema,
            exchange.schema_version,
            "tui",
        );
        let kind = adapter.as_ref().map_or_else(
            || exchange.schema.clone(),
            |adapter| adapter.interaction_kind.clone(),
        );
        interactions.push(bcode_session_view_models::InteractionViewSummary {
            interaction_id,
            producer_id: Some(producer_id),
            exchange_schema: Some(exchange_schema),
            exchange_schema_version: Some(exchange_schema_version),
            kind,
            tool_call_id: Some(exchange.invocation_id),
            title: Some(exchange.producer_id),
            required: exchange.response_policy
                == bcode_session_models::ToolExchangeResponsePolicy::Required,
            snapshot: Some(snapshot),
            state: bcode_session_view_models::InteractionViewState::Pending,
            status_detail: None,
            resolved: false,
            resolution: None,
        });
    }
    Ok(interactions)
}

const fn active_turn_cancel_action(session_id: SessionId) -> SessionViewAction {
    SessionViewAction::CancelTurn {
        session_id,
        clear_queue: false,
    }
}

async fn load_session_status(client: &BcodeClient, session_id: SessionId) -> TuiEffectResult {
    let (model, model_error) = Box::pin(optional_client_result(
        client.session_model_status(session_id),
    ))
    .await;
    let (
        (active_skills, skills_error),
        (runtime_work, runtime_work_error),
        (interactions, interactions_error),
        (plugin_status, plugin_error),
    ) = tokio::join!(
        optional_client_result(client.active_skills(session_id)),
        optional_client_result(client.list_runtime_work(session_id)),
        optional_client_result(load_pending_interactions(client, session_id)),
        load_plugin_session_status(client, session_id),
    );
    TuiEffectResult::SessionStatusLoaded {
        daemon_connected: model.is_some() || active_skills.is_some() || runtime_work.is_some(),
        session_id,
        hydration: Box::new(SessionStatusHydration {
            model,
            active_skills,
            runtime_work,
            interactions,
            plugin_status,
            error: model_error
                .or(skills_error)
                .or(runtime_work_error)
                .or(interactions_error)
                .or(plugin_error),
        }),
    }
}

#[cfg(test)]
mod projection_paging_tests {
    #[test]
    fn active_turn_cancel_preserves_all_pending_queue_items() {
        let session_id = SessionId::new();
        assert_eq!(
            active_turn_cancel_action(session_id),
            SessionViewAction::CancelTurn {
                session_id,
                clear_queue: false
            }
        );
    }

    use super::*;
    use bcode_session_models::{
        CURRENT_SESSION_EVENT_SCHEMA_VERSION, ClientId, ProjectionSourceRange, ProjectionWindow,
        SessionEvent, SessionEventKind,
    };

    fn projection_page(
        session_id: SessionId,
        start: u64,
        end: u64,
        has_more: bool,
    ) -> bcode_session_models::ProjectionHistoryPage {
        bcode_session_models::ProjectionHistoryPage {
            session_id,
            window: ProjectionWindow {
                projection: SessionProjectionKind::Transcript,
                transcript_items: Vec::new(),
                source_range: Some(ProjectionSourceRange {
                    start_sequence: start,
                    end_sequence: end,
                }),
                has_older: has_more,
                has_newer: has_more,
                scanned_events: usize::try_from(end - start + 1).expect("small test page"),
            },
            events: (start..=end)
                .map(|sequence| SessionEvent {
                    schema_version: CURRENT_SESSION_EVENT_SCHEMA_VERSION,
                    sequence,
                    timestamp_ms: sequence,
                    session_id,
                    provenance: None,
                    kind: SessionEventKind::ClientAttached {
                        client_id: ClientId::new(),
                    },
                })
                .collect(),
        }
    }

    fn queue_test_hello() -> bcode_ipc::ResponsePayload {
        bcode_ipc::ResponsePayload::Hello {
            protocol_version: bcode_ipc::ProtocolVersion::current(),
            client_id: ClientId::new(),
            daemon: bcode_ipc::DaemonStatus {
                namespace: bcode_ipc::daemon_namespace(),
                protocol_version: u32::from(bcode_ipc::ProtocolVersion::current().0),
                artifact_id: Some(bcode_ipc::ArtifactId::current()),
                executable_digest: Some(
                    bcode_daemon_lifecycle::current_executable_identity()
                        .unwrap()
                        .1,
                ),
                build_fingerprint: bcode_ipc::BUILD_FINGERPRINT.to_owned(),
                storage_writer_epoch: Some(
                    bcode_session_models::CURRENT_SESSION_STORAGE_WRITER_EPOCH,
                ),
                session_event_schema_version: Some(CURRENT_SESSION_EVENT_SCHEMA_VERSION),
                state_location_id: Some(bcode_ipc::state_location_id()),
                ..bcode_ipc::DaemonStatus::default()
            },
        }
    }
    async fn respond_to_prepare(
        listener: bcode_ipc::LocalIpcListener,
        session_id: SessionId,
        submission_id: bcode_session_models::SubmissionId,
        confirmation: bcode_session_models::SubmissionResumeConfirmation,
    ) {
        let mut prepared = false;
        let mut finished = false;
        while !finished {
            let mut stream = listener.accept().await.unwrap();
            loop {
                let Ok(envelope) = bcode_ipc::recv_envelope(&mut stream).await else {
                    break;
                };
                let request = bcode_ipc::decode_request(&envelope.payload).unwrap();
                let response = match request {
                    bcode_ipc::Request::Hello { .. } => queue_test_hello(),
                    bcode_ipc::Request::PrepareSubmissionResume {
                        session_id: requested,
                        submission_id: requested_id,
                        expected_accepted_sequence,
                    } => {
                        assert_eq!(requested, session_id);
                        assert_eq!(requested_id, submission_id);
                        assert_eq!(expected_accepted_sequence, 17);
                        assert!(!prepared);
                        prepared = true;
                        bcode_ipc::ResponsePayload::SubmissionResumePrepared {
                            confirmation: confirmation.clone(),
                        }
                    }
                    bcode_ipc::Request::SubmissionQueueStatus {
                        session_id: requested,
                    } => {
                        assert!(prepared);
                        assert_eq!(requested, session_id);
                        finished = true;
                        bcode_ipc::ResponsePayload::SubmissionQueueStatus {
                            status: bcode_session_models::SubmissionQueueStatus {
                                oldest: None,
                                blocker: None,
                            },
                        }
                    }
                    other => panic!("prepare must not mutate or scan history: {other:?}"),
                };
                let reply = bcode_ipc::response_envelope(
                    envelope.request_id,
                    &bcode_ipc::Response::Ok(response),
                )
                .unwrap();
                bcode_ipc::send_envelope(&mut stream, &reply).await.unwrap();
                if finished {
                    break;
                }
            }
        }
    }

    #[tokio::test]
    async fn targeted_prepare_dispatches_read_only_identity_then_bounded_status() {
        use bcode_session_models::*;
        let session_id = SessionId::new();
        let submission_id = SubmissionId("exact-pending".to_owned());
        let confirmation = SubmissionResumeConfirmation {
            version: 1,
            submission_id: submission_id.clone(),
            expected_accepted_sequence: 17,
            descriptor: SubmissionExecutionDescriptor {
                version: 2,
                provider: "provider".to_owned(),
                model: "model".to_owned(),
                reasoning: None,
                model_profile: Some("selected-profile".to_owned()),
                auth_profile: None,
                config_identity: "digest".to_owned(),
                recovery_recipe: None,
            },
        };
        let expected = confirmation.clone();
        let socket_dir = tempfile::tempdir().unwrap();
        let endpoint = bcode_ipc::IpcEndpoint::unix_socket(socket_dir.path().join("queue.sock"));
        let listener = bcode_ipc::LocalIpcListener::bind(&endpoint).unwrap();
        let responder = tokio::spawn(respond_to_prepare(
            listener,
            session_id,
            submission_id,
            confirmation,
        ));
        let effect = TuiEffect::QueueRecovery {
            session_id,
            generation: 0,
            action: Box::new(SessionViewAction::PrepareSubmissionResume {
                session_id,
                submission_id: expected.submission_id.clone(),
                expected_accepted_sequence: 17,
            }),
        };
        let (sender, _receiver) = tokio::sync::mpsc::channel(1);
        let result = tokio::time::timeout(
            std::time::Duration::from_secs(5),
            effect.run(BcodeClient::new(endpoint), sender),
        )
        .await
        .unwrap();
        responder.await.unwrap();
        let TuiEffectResult::QueueRecovery { result, .. } = result else {
            panic!("expected recovery result");
        };
        let Ok((SessionViewActionOutcome::SubmissionResumePrepared { confirmation }, status)) =
            *result
        else {
            panic!("expected read-only prepared confirmation");
        };
        assert_eq!(confirmation, expected);
        assert!(status.oldest.is_none());
    }

    #[tokio::test]
    #[allow(clippy::too_many_lines)]
    async fn scheduled_history_effect_fetches_bounded_page_over_ipc() {
        use bcode_session_models::{ProjectionHistoryPage, ProjectionWindow};

        let session_id = SessionId::new();
        let socket_dir = tempfile::tempdir().expect("socket directory");
        let endpoint = bcode_ipc::IpcEndpoint::unix_socket(socket_dir.path().join("history.sock"));
        let listener = bcode_ipc::LocalIpcListener::bind(&endpoint).expect("IPC listener");
        let responder = tokio::spawn(async move {
            let mut stream = listener.accept().await.expect("history client");
            let mut observed_request = None;
            loop {
                let envelope = bcode_ipc::recv_envelope(&mut stream)
                    .await
                    .expect("client request");
                let request = bcode_ipc::decode_request(&envelope.payload).expect("decode request");
                let response = match request {
                    bcode_ipc::Request::Hello { .. } => {
                        bcode_ipc::Response::Ok(bcode_ipc::ResponsePayload::Hello {
                            protocol_version: bcode_ipc::ProtocolVersion::current(),
                            client_id: ClientId::new(),
                            daemon: bcode_ipc::DaemonStatus {
                                namespace: bcode_ipc::daemon_namespace(),
                                protocol_version: u32::from(
                                    bcode_ipc::ProtocolVersion::current().0,
                                ),
                                artifact_id: Some(bcode_ipc::ArtifactId::current()),
                                executable_digest: Some(
                                    bcode_daemon_lifecycle::current_executable_identity()
                                        .expect("test executable identity")
                                        .1,
                                ),
                                build_fingerprint: bcode_ipc::BUILD_FINGERPRINT.to_owned(),
                                storage_writer_epoch: Some(
                                    bcode_ipc::CURRENT_SESSION_STORAGE_WRITER_EPOCH,
                                ),
                                session_event_schema_version: Some(
                                    CURRENT_SESSION_EVENT_SCHEMA_VERSION,
                                ),
                                state_location_id: Some(bcode_ipc::state_location_id()),
                                ..bcode_ipc::DaemonStatus::default()
                            },
                        })
                    }
                    bcode_ipc::Request::SessionProjectionHistoryPage {
                        session_id: requested,
                        request,
                    } => {
                        assert_eq!(requested, session_id);
                        assert_eq!(request.anchor, ProjectionWindowAnchor::BeforeSequence(11));
                        assert_eq!(request.direction, ProjectionWindowDirection::Backward);
                        assert_eq!(request.projection, SessionProjectionKind::Transcript);
                        assert!(
                            request.limits.max_events_scanned <= TRANSCRIPT_PAGE_MAX_EVENTS_SCANNED
                        );
                        observed_request = Some(request);
                        bcode_ipc::Response::Ok(
                            bcode_ipc::ResponsePayload::SessionProjectionHistoryPage {
                                page: ProjectionHistoryPage {
                                    session_id,
                                    window: ProjectionWindow {
                                        projection: SessionProjectionKind::Transcript,
                                        transcript_items: Vec::new(),
                                        source_range: Some(ProjectionSourceRange {
                                            start_sequence: 7,
                                            end_sequence: 10,
                                        }),
                                        has_older: true,
                                        has_newer: true,
                                        scanned_events: 4,
                                    },
                                    events: projection_page(session_id, 7, 10, true).events,
                                },
                            },
                        )
                    }
                    other => panic!("unexpected history request: {other:?}"),
                };
                let reply = bcode_ipc::response_envelope(envelope.request_id, &response)
                    .expect("encode response");
                bcode_ipc::send_envelope(&mut stream, &reply)
                    .await
                    .expect("send response");
                if observed_request.is_some() {
                    break;
                }
            }
            observed_request.expect("projection request")
        });
        let effect = TuiEffect::LoadOlderHistory {
            session_id,
            cursor: SessionHistoryCursor { sequence: 10 },
            generation: 42,
            width_columns: 80,
        };
        let (sender, _receiver) = tokio::sync::mpsc::channel(1);
        let result = tokio::time::timeout(
            std::time::Duration::from_secs(5),
            effect.run(BcodeClient::new(endpoint), sender),
        )
        .await
        .expect("history fetch timeout");
        let request = responder.await.expect("IPC responder");
        assert_eq!(request.target.min_items, Some(TRANSCRIPT_PAGE_TARGET_ITEMS));
        match result {
            TuiEffectResult::OlderHistoryLoaded {
                session_id: returned,
                cursor,
                generation,
                result,
            } => {
                assert_eq!(returned, session_id);
                assert_eq!(cursor.sequence, 10);
                assert_eq!(generation, 42);
                let (page, _) = result.expect("bounded history page");
                assert_eq!(page.events.len(), 4);
                assert_eq!(page.events.first().map(|event| event.sequence), Some(7));
                assert!(page.has_more);
            }
            _ => panic!("unexpected effect result"),
        }
    }

    #[test]
    fn projection_pages_preserve_non_presenting_source_progress_in_both_directions() {
        let session_id = SessionId::new();
        let older = projection_page_as_history_page(
            session_id,
            SessionHistoryCursor { sequence: 10 },
            true,
            projection_page(session_id, 7, 10, true),
        )
        .expect("older non-presenting page");
        assert_eq!(older.events.len(), 4);
        assert!(older.has_more);
        let newer = projection_page_as_history_page(
            session_id,
            SessionHistoryCursor { sequence: 12 },
            false,
            projection_page(session_id, 12, 15, false),
        )
        .expect("newer non-presenting page");
        assert_eq!(newer.events.len(), 4);
        assert!(!newer.has_more);
    }

    #[test]
    fn projection_pages_reject_wrong_boundary_or_stale_session() {
        let session_id = SessionId::new();
        let page = projection_page(session_id, 7, 10, true);
        assert!(
            projection_page_as_history_page(
                session_id,
                SessionHistoryCursor { sequence: 11 },
                true,
                page.clone(),
            )
            .is_err()
        );
        assert!(
            projection_page_as_history_page(
                SessionId::new(),
                SessionHistoryCursor { sequence: 10 },
                true,
                page,
            )
            .is_err()
        );
    }
}

#[cfg(test)]
mod progress_routing_tests {
    use super::*;

    fn picker_effect() -> TuiEffect {
        TuiEffect::LoadSessionPicker {
            generation: 1,
            scope: bcode_session_models::SessionDiscoveryScope::AllWorkingDirectories,
            query: bcode_session_models::SessionCatalogQuery::default(),
            cursor: None,
        }
    }

    #[test]
    fn session_picker_subscription_replacement_and_cancellation_are_coalesced() {
        let mut queue = TuiEffectQueue::default();
        queue.replace(picker_effect());
        queue.replace(picker_effect());
        let (effects, _) = queue.drain_runtime();
        assert_eq!(effects.len(), 1);
        assert!(matches!(effects[0].0, EffectSchedule::Replace));
        queue.replace(picker_effect());
        queue.cancel(picker_effect());
        let (effects, _) = queue.drain_runtime();
        assert_eq!(effects.len(), 1);
        assert!(matches!(effects[0].0, EffectSchedule::Cancel));
    }

    #[test]
    fn application_failures_do_not_claim_the_daemon_is_offline() {
        let server_error = ClientError::Server {
            code: "permission_denied".to_owned(),
            message: "request rejected".to_owned(),
        };
        assert!(matches!(
            DaemonObservation::from_client_result::<()>(&Err(server_error)),
            DaemonObservation::Failed(_)
        ));
        let optional_domain = ClientError::Server {
            code: "workflow_capability_unavailable".to_owned(),
            message: "maintenance required".to_owned(),
        };
        assert!(optional_domain.is_optional_domain_unavailable());
        assert_eq!(
            DaemonObservation::from_tui_result::<()>(&Err(TuiError::SessionUnavailable {
                session_id: SessionId::new(),
                reason: "owned elsewhere".to_owned(),
            })),
            DaemonObservation::None
        );
    }

    #[test]
    fn transport_unavailability_remains_connectivity_evidence() {
        let error = ClientError::Transport(bcode_ipc::IpcTransportError::Io(std::io::Error::new(
            std::io::ErrorKind::ConnectionRefused,
            "offline",
        )));
        assert!(matches!(
            DaemonObservation::from_client_result::<()>(&Err(error)),
            DaemonObservation::Unavailable(_)
        ));
    }

    #[test]
    fn runtime_effect_drain_preserves_every_ordered_note_per_session() {
        let session_id = SessionId::new();
        let mut queue = TuiEffectQueue::default();
        for note_id in ["0001", "0002", "0003"] {
            queue.start_ordered(TuiEffect::AppendPresentationNote {
                session_id,
                source_id: "test".to_owned(),
                note_id: note_id.to_owned(),
                text: note_id.to_owned(),
                format: bcode_command::CommandTextFormat::PlainText,
            });
        }

        let (effects, notes) = queue.drain_runtime();

        assert!(effects.is_empty());
        let queued = notes
            .get(&session_id)
            .expect("ordered session queue")
            .iter()
            .map(TuiEffect::key)
            .collect::<Vec<_>>();
        assert_eq!(
            queued,
            vec![
                EffectKey::AppendPresentationNote(session_id, "0001".to_owned()),
                EffectKey::AppendPresentationNote(session_id, "0002".to_owned()),
                EffectKey::AppendPresentationNote(session_id, "0003".to_owned()),
            ]
        );
    }
}