psmux 3.3.6

Terminal multiplexer for Windows - tmux alternative for PowerShell and Windows Terminal
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
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
pub(crate) mod helpers;
pub(crate) mod options;
pub(crate) mod option_catalog;
mod connection;

use std::io::{self, Write};
use std::sync::mpsc;
use std::thread;
use std::time::{Duration, Instant};
use std::env;
use std::net::TcpListener;

use portable_pty::native_pty_system;
use ratatui::prelude::Rect;

use crate::types::{AppState, CtrlReq, Mode, FocusDir, LayoutKind, PipePaneState, VERSION,
    WaitChannel, WaitForOp, Node, Action, Bind};
use crate::platform::install_console_ctrl_handler;
use crate::pane::{create_window, create_window_raw, split_active_with_command, kill_active_pane, kill_pane_by_id, spawn_warm_pane};
use crate::tree::{self, active_pane, active_pane_mut, resize_all_panes, kill_all_children,
    find_window_index_by_id, focus_pane_by_id, focus_pane_by_id_no_mru, focus_pane_by_index, get_active_pane_id,
    get_split_mut, path_exists};

use helpers::{collect_pane_paths_server, serialize_bindings_json, json_escape_string,
    list_windows_json_with_tabs, combined_data_version, take_pane_clipboard, TMUX_COMMANDS};
use options::{get_option_value, render_window_options, apply_set_option};

use crate::input::{send_text_to_active, send_key_to_active, send_paste_to_active, move_focus, move_focus_preserving_zoom, find_best_pane_in_direction, find_wrap_target};
use crate::copy_mode::{enter_copy_mode, exit_copy_mode, move_copy_cursor, current_prompt_pos,
    yank_selection, scroll_copy_up, scroll_copy_down, switch_with_copy_save,
    capture_active_pane_text, capture_active_pane_range, capture_active_pane_styled};
use crate::layout::{dump_layout_json, dump_layout_json_fast, apply_layout, cycle_layout,
    cycle_layout_reverse};
use crate::window_ops::{toggle_zoom, remote_mouse_down, remote_mouse_drag, remote_mouse_up,
    remote_mouse_button, remote_mouse_motion, remote_scroll_up, remote_scroll_down,
    swap_pane, break_pane_to_window, unzoom_if_zoomed, resize_pane_vertical,
    resize_pane_horizontal, resize_pane_absolute, rotate_panes, respawn_active_pane,
    handle_pane_mouse, handle_pane_scroll, handle_split_set_sizes, handle_split_resize_done};
use crate::config::{load_config, parse_key_string, format_key_binding, normalize_key_for_binding,
    parse_config_content};
use crate::commands::{parse_command_to_action, format_action, parse_menu_definition, execute_command_string};
use crate::util::{list_windows_json, list_tree_json, list_windows_tmux, base64_encode};
use crate::control;
use crate::format::{expand_format, format_list_windows, format_list_panes, set_buffer_idx_override, set_named_buffer_override};
use crate::help;

/// Build a JSON fragment with overlay state (popup, menu, confirm, display_panes).
/// Delegates popup-specific serialization to the popup module.
fn serialize_overlay_json(app: &AppState) -> String {
    use crate::server::helpers::json_escape_string;

    // Popup overlay handles PopupMode, MenuMode, ConfirmMode, PaneChooser, and default
    let mut out = crate::popup::serialize_popup_overlay(app);

    // Include status_message for display-message without -p (#110).
    //
    // tmux(1) display-message: "a delay of zero waits for a key press."
    // So `-d 0` should keep the message visible until any key is pressed;
    // the SendKey / SendText handlers clear status_message, which dismisses
    // it naturally. Treat display_time == 0 as "sticky until keypress" by
    // skipping the time-based expiry check.
    if let Some((ref msg, since, per_msg_duration)) = app.status_message {
        let elapsed = since.elapsed().as_millis() as u64;
        let display_time = per_msg_duration.unwrap_or(app.display_time_ms);
        if display_time == 0 || elapsed < display_time {
            out.push_str(",\"status_message\":\"");
            out.push_str(&json_escape_string(msg));
            out.push('"');
        }
    }
    out
}

fn should_spawn_warm_server(app: &AppState) -> bool {
    app.warm_enabled && app.session_name != "__warm__" && !app.destroy_unattached
}

fn ensure_session_registry_files(home: &str, app: &AppState) {
    let Some(port) = app.control_port else { return; };
    let dir = format!("{}\\.psmux", home);
    let _ = std::fs::create_dir_all(&dir);

    let base = app.port_file_base();
    let port_path = format!("{}\\{}.port", dir, base);
    let key_path = format!("{}\\{}.key", dir, base);
    let sid_path = format!("{}\\{}.sid", dir, base);
    let port_value = port.to_string();
    let sid_value = app.session_id.to_string();

    if std::fs::read_to_string(&port_path)
        .map(|s| s.trim() != port_value)
        .unwrap_or(true)
    {
        let _ = std::fs::write(&port_path, &port_value);
    }

    if std::fs::read_to_string(&key_path)
        .map(|s| s.trim() != app.session_key)
        .unwrap_or(true)
    {
        let _ = std::fs::write(&key_path, &app.session_key);
    }

    if std::fs::read_to_string(&sid_path)
        .map(|s| s.trim() != sid_value)
        .unwrap_or(true)
    {
        let _ = std::fs::write(&sid_path, &sid_value);
    }
}

/// Diagnostic-only logging for warm-server lifecycle races. Gated behind
/// PSMUX_WARM_DEBUG=1 so it is a no-op in normal operation and tests. Writes to
/// %TEMP%\psmux_warm_debug.log (never inside the repo).
fn warm_debug(msg: &str) {
    if std::env::var("PSMUX_WARM_DEBUG").map(|v| v == "1").unwrap_or(false) {
        let tmp = env::var("TEMP")
            .or_else(|_| env::var("TMP"))
            .unwrap_or_else(|_| ".".to_string());
        let path = format!("{}\\psmux_warm_debug.log", tmp);
        let ts = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis())
            .unwrap_or(0);
        if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&path) {
            let _ = std::io::Write::write_all(
                &mut f,
                format!("[{} pid={}] {}\n", ts, std::process::id(), msg).as_bytes(),
            );
        }
    }
}

/// Check if the active pane is currently squelched (hiding injected cd+cls).
/// Uses the non-consuming `squelch_cleared()` so the layout serialiser can
/// still properly consume the sentinel via `take_squelch_cleared()`.
fn is_active_pane_squelched(app: &AppState) -> bool {
    if app.windows.is_empty() { return false; }
    let win = &app.windows[app.active_idx];
    if let Some(p) = active_pane(&win.root, &win.active_path) {
        if let Some(deadline) = p.squelch_until {
            let sentinel = p.term.lock()
                .map(|parser| parser.screen().squelch_cleared())
                .unwrap_or(false);
            !sentinel && Instant::now() < deadline
        } else { false }
    } else { false }
}

/// Spawn a standby "warm server" process that pre-loads config + shell.
/// When `psmux new-session` is run later, the CLI claims this warm server
/// via `claim-session` instead of cold-spawning, making session creation
/// nearly instant.  The warm server uses session name `__warm__`.
fn spawn_warm_server(app: &AppState) {
    // destroy-unattached means the user expects the session to be torn down
    // when the last client leaves; keeping a hidden warm server alive breaks
    // that expectation and makes exit-empty appear ineffective.
    if !should_spawn_warm_server(app) {
        return;
    }
    // Skip if a warm server already exists
    let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
    let warm_base = if let Some(ref sn) = app.socket_name {
        format!("{}____warm__", sn)
    } else {
        "__warm__".to_string()
    };
    let warm_port_path = format!("{}\\.psmux\\{}.port", home, warm_base);
    warm_debug(&format!("spawn_warm_server entry base={} port_exists={}", warm_base, std::path::Path::new(&warm_port_path).exists()));
    if std::path::Path::new(&warm_port_path).exists() {
        // Check if it's actually a live, unclaimed warm server.
        // TCP reachability alone is not sufficient: OS ephemeral-port reuse or
        // duplicated-warm churn can leave __warm__.port pointing at a real
        // claimed session.  That server answers TCP connects but is NOT warm,
        // so returning early here means warm never re-establishes and every
        // subsequent open stays cold (~1-5s) until the pointer is manually removed.
        let mut is_genuine_warm = false;
        if let Ok(port_str) = std::fs::read_to_string(&warm_port_path) {
            if let Ok(port) = port_str.trim().parse::<u16>() {
                let addr = format!("127.0.0.1:{}", port);
                if std::net::TcpStream::connect_timeout(
                    &addr.parse().unwrap(),
                    Duration::from_millis(100),
                ).is_ok() {
                    // TCP is up — verify the session name via AUTH.
                    let warm_key_path = format!("{}\\.psmux\\{}.key", home, warm_base);
                    if let Ok(key) = std::fs::read_to_string(&warm_key_path) {
                        let key = key.trim().to_string();
                        if !key.is_empty() {
                            // Ask the server what its session name is.
                            // Response is the name followed by a newline.
                            // Timeout is capped at 500ms inside send_auth_cmd_response.
                            match crate::session::send_auth_cmd_response(
                                &addr, &key,
                                b"display-message -p '#{session_name}'\n",
                            ) {
                                Ok(resp) if resp.trim() == "__warm__" => {
                                    warm_debug("early-return: existing warm verified alive");
                                    is_genuine_warm = true;
                                }
                                Ok(resp) => {
                                    warm_debug(&format!(
                                        "warm port reachable but session='{}' (not __warm__) — treating as stale",
                                        resp.trim()
                                    ));
                                }
                                Err(_) => {
                                    warm_debug("warm port reachable but auth/query failed — treating as stale");
                                }
                            }
                        }
                    }
                }
            }
        }
        if is_genuine_warm {
            return;
        }
        // Stale or wrong-server port file — remove it (and matching key/sid files)
        warm_debug("removing STALE warm port/key/sid (unreachable or not a warm server)");
        let _ = std::fs::remove_file(&warm_port_path);
        let warm_key_path = format!("{}\\.psmux\\{}.key", home, warm_base);
        let _ = std::fs::remove_file(&warm_key_path);
        let warm_sid_path = format!("{}\\.psmux\\{}.sid", home, warm_base);
        let _ = std::fs::remove_file(&warm_sid_path);
    }
    warm_debug("SPAWNING new warm server");
    let exe = std::env::current_exe().unwrap_or_else(|_| std::path::PathBuf::from("psmux"));
    let mut args: Vec<String> = vec!["server".into(), "-s".into(), "__warm__".into()];
    if let Some(ref sn) = app.socket_name {
        args.push("-L".into());
        args.push(sn.clone());
    }
    // Pass current terminal dimensions so the warm server's first window
    // and warm pane are spawned at the right size.
    let area = app.last_window_area;
    if area.width > 1 && area.height > 1 {
        args.push("-x".into());
        args.push(area.width.to_string());
        args.push("-y".into());
        args.push(area.height.to_string());
    }
    #[cfg(windows)]
    { let _ = crate::platform::spawn_server_hidden(&exe, &args); }
    #[cfg(not(windows))]
    {
        let mut cmd = std::process::Command::new(&exe);
        for a in &args { cmd.arg(a); }
        cmd.stdin(std::process::Stdio::null());
        cmd.stdout(std::process::Stdio::null());
        cmd.stderr(std::process::Stdio::null());
        let _ = cmd.spawn();
    }
}

/// Parse a popup dimension spec: "80" (absolute) or "95%" (percentage of term_dim).
fn parse_popup_dim(spec: &str, term_dim: u16, default: u16) -> u16 {
    if let Some(pct_str) = spec.strip_suffix('%') {
        if let Ok(pct) = pct_str.parse::<u16>() {
            let pct = pct.min(100);
            (term_dim as u32 * pct as u32 / 100) as u16
        } else {
            default
        }
    } else {
        spec.parse().unwrap_or(default)
    }
}

/// Compute the effective display size from all connected clients' terminal sizes.
/// Returns None if no clients have reported sizes.
fn compute_effective_client_size(app: &AppState) -> Option<(u16, u16)> {
    if app.client_sizes.is_empty() { return None; }
    match app.window_size.as_str() {
        "smallest" => Some((
            app.client_sizes.values().map(|s| s.0).min().unwrap(),
            app.client_sizes.values().map(|s| s.1).min().unwrap(),
        )),
        "largest" => Some((
            app.client_sizes.values().map(|s| s.0).max().unwrap(),
            app.client_sizes.values().map(|s| s.1).max().unwrap(),
        )),
        _ => {
            // "latest" — use latest client's size, fall back to smallest
            if let Some(cid) = app.latest_client_id {
                if let Some(&size) = app.client_sizes.get(&cid) {
                    return Some(size);
                }
            }
            Some((
                app.client_sizes.values().map(|s| s.0).min().unwrap(),
                app.client_sizes.values().map(|s| s.1).min().unwrap(),
            ))
        }
    }
}

/// Process a single CtrlReq during the post-config plugin drain loop.
/// Handles the subset of requests that plugin scripts send (set, show, bind,
/// source-file) and silently drops others.
fn drain_plugin_req(
    app: &mut AppState,
    req: CtrlReq,
    shared_aliases: &std::sync::Arc<std::sync::RwLock<std::collections::HashMap<String, String>>>,
) {
    match req {
        CtrlReq::SetOption(option, value) => {
            apply_set_option(app, &option, &value, false);
            app.user_set_options.insert(option.clone());
            if option == "command-alias" {
                if let Ok(mut map) = shared_aliases.write() {
                    *map = app.command_aliases.clone();
                }
            }
            // pane-border-status changes the effective content height (#288)
            if option == "pane-border-status" {
                resize_all_panes(app);
            }
        }
        CtrlReq::SetOptionQuiet(option, value, quiet) => {
            apply_set_option(app, &option, &value, quiet);
            app.user_set_options.insert(option.clone());
            if option == "command-alias" {
                if let Ok(mut map) = shared_aliases.write() {
                    *map = app.command_aliases.clone();
                }
            }
            if option == "pane-border-status" {
                resize_all_panes(app);
            }
        }
        CtrlReq::SetOptionAppend(option, value) => {
            if option.starts_with('@') {
                let existing = app.user_options.get(&option).cloned().unwrap_or_default();
                app.user_options.insert(option, format!("{}{}", existing, value));
            } else {
                match option.as_str() {
                    "status-left" => app.status_left.push_str(&value),
                    "status-right" => app.status_right.push_str(&value),
                    "status-style" => app.status_style.push_str(&value),
                    _ => {}
                }
            }
        }
        CtrlReq::SetOptionUnset(option) => {
            if option.starts_with('@') {
                app.user_options.remove(&option);
            }
        }
        CtrlReq::SetOptionOnlyIfUnset(option, value) => {
            // Only set if the option hasn't been explicitly set by user/config.
            // For @-prefixed user options, check if the key exists.
            // For built-in options, check the user_set_options tracker.
            let already_set = if option.starts_with('@') {
                app.user_options.contains_key(&option)
            } else {
                app.user_set_options.contains(&option)
            };
            if !already_set {
                apply_set_option(app, &option, &value, false);
                app.user_set_options.insert(option.clone());
                if option == "command-alias" {
                    if let Ok(mut map) = shared_aliases.write() {
                        *map = app.command_aliases.clone();
                    }
                }
            }
        }
        CtrlReq::ShowOptionValue(resp, name) => {
            let val = get_option_value(app, &name);
            let _ = resp.send(val);
        }
        CtrlReq::ShowWindowOptionValue(resp, name, target) => {
            let val = crate::server::options::get_window_option_value_for(app, &name, target);
            let _ = resp.send(val);
        }
        CtrlReq::ShowOptions(resp) => {
            // Minimal: just send empty to unblock the caller
            let _ = resp.send(String::new());
        }
        CtrlReq::ShowWindowOptions(resp) => {
            let _ = resp.send(render_window_options(app));
        }
        CtrlReq::BindKey(table_name, key, command, repeat) => {
            if let Some(kc) = parse_key_string(&key) {
                let kc = normalize_key_for_binding(kc);
                let sub_cmds = crate::config::split_chained_commands_pub(&command);
                let action = if sub_cmds.len() > 1 {
                    Some(Action::CommandChain(sub_cmds))
                } else {
                    parse_command_to_action(&command)
                };
                if let Some(act) = action {
                    let table = app.key_tables.entry(table_name).or_default();
                    table.retain(|b| b.key != kc);
                    table.push(Bind { key: kc, action: act, repeat });
                }
            }
        }
        CtrlReq::SourceFile(path) => {
            app.defaults_suppressed = false;
            app.key_tables.clear();
            crate::config::populate_default_bindings(app);
            crate::config::source_file(app, &path);
            // source-file may change pane-border-status (#288)
            resize_all_panes(app);
        }
        CtrlReq::UnbindAll => {
            app.key_tables.clear();
            app.defaults_suppressed = true;
        }
        CtrlReq::UnbindAllInTable(table) => {
            if let Some(binds) = app.key_tables.get_mut(&table) {
                binds.clear();
            }
        }
        CtrlReq::UnbindKey(key, table) => {
            if let Some(kc) = parse_key_string(&key) {
                let kc = normalize_key_for_binding(kc);
                let target = table.unwrap_or_else(|| "prefix".to_string());
                if let Some(binds) = app.key_tables.get_mut(&target) {
                    binds.retain(|b| b.key != kc);
                }
            }
        }
        // Ignore other request types during plugin drain
        _ => {}
    }
}

/// Persist a server-startup failure to `~/.psmux/server-startup.log`.
///
/// The detached server has no visible stderr — when the initial pane spawn
/// fails (e.g. the `CreateProcessW err 87` from psmux issue #167) the user
/// sees only "psmux flashed black and returned to prompt".  This file lets
/// the user (or our docs) point them at concrete evidence:
///
///   - the actual error message (locale-specific GetLastError text),
///   - the build/version of psmux that produced it,
///   - the size of the inherited environment block (a likely culprit on
///     Microsoft-account profiles where OneDrive + WindowsApps inflate
///     the env to near the 32 KB Windows limit),
///   - the path psmux tried to spawn.
///
/// Best-effort: any error writing the log is swallowed (we are already
/// reporting the original failure up the call chain).
pub(crate) fn write_startup_error_log(err: &dyn std::fmt::Display) {
    let home = std::env::var("USERPROFILE")
        .or_else(|_| std::env::var("HOME"))
        .unwrap_or_default();
    if home.is_empty() {
        return;
    }
    let dir = format!("{}\\.psmux", home);
    let _ = std::fs::create_dir_all(&dir);
    let path = format!("{}\\server-startup.log", dir);

    use std::os::windows::ffi::OsStrExt;
    let mut env_count = 0usize;
    let mut env_chars = 0usize;
    let mut env_largest = ("".to_string(), 0usize);
    for (k, v) in std::env::vars_os() {
        env_count += 1;
        let kl = k.encode_wide().count();
        let vl = v.encode_wide().count();
        env_chars += kl + 1 + vl + 1;
        let total = kl + vl + 1;
        if total > env_largest.1 {
            env_largest = (k.to_string_lossy().into_owned(), total);
        }
    }

    let cwd = std::env::current_dir().ok();
    let userprofile = std::env::var("USERPROFILE").ok();
    let onedrive_present = std::env::var("OneDrive").is_ok();
    let comspec = std::env::var("ComSpec").ok();

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let body = format!(
        "psmux server startup error\n\
         ==========================\n\
         psmux version : {version}\n\
         when (epoch s): {now}\n\
         os.family     : windows\n\
         \n\
         error:\n\
           {err}\n\
         \n\
         spawn context:\n\
           CWD                 : {cwd:?}\n\
           USERPROFILE         : {up:?}\n\
           ComSpec             : {cs:?}\n\
           OneDrive present    : {od}\n\
           env vars (count)    : {ec}\n\
           env block size (wch): {eb} (Windows hard limit: 32767)\n\
           largest env entry   : {key} ({sz} chars)\n\
         \n\
         workarounds to try (in order):\n\
           1. PSMUX_NO_PASSTHROUGH=1   (skip ConPTY passthrough mode)\n\
           2. PSMUX_BARE_ENV=1         (spawn with minimal env block)\n\
           3. switch to a local Windows account (Microsoft account\n\
              profiles often inherit a bloated environment)\n\
           4. open an issue at https://github.com/psmux/psmux/issues/167\n\
              and attach this file\n",
        version = env!("CARGO_PKG_VERSION"),
        now = now,
        err = err,
        cwd = cwd,
        up = userprofile,
        cs = comspec,
        od = onedrive_present,
        ec = env_count,
        eb = env_chars,
        key = env_largest.0,
        sz = env_largest.1,
    );
    let _ = std::fs::write(&path, body);
}

/// Absolute path to `~/.psmux/server-startup.log`, or None if no home dir.
pub(crate) fn startup_error_log_path() -> Option<String> {
    let home = std::env::var("USERPROFILE")
        .or_else(|_| std::env::var("HOME"))
        .unwrap_or_default();
    if home.is_empty() {
        return None;
    }
    Some(format!("{}\\.psmux\\server-startup.log", home))
}

/// Read the real failure reason out of a *fresh* `server-startup.log`.
///
/// Issue #370: when the initial pane spawn fails (e.g. a `default-shell`
/// pointing at a non-existent path), the detached server records the concrete
/// error here and exits, but the client the user is actually looking at only
/// printed a generic "failed to create session". This lets the client echo the
/// real cause to the terminal instead of leaving it buried in a log file.
///
/// `since_epoch` is the wall-clock second the current startup attempt began;
/// logs whose `when (epoch s)` predate it are stale (from an earlier run or an
/// adopted warm server) and are ignored. Returns `(error_text, log_path)`.
pub(crate) fn read_fresh_startup_error(since_epoch: u64) -> Option<(String, String)> {
    let path = startup_error_log_path()?;
    read_fresh_startup_error_at(&path, since_epoch)
}

/// Path-injectable core of [`read_fresh_startup_error`] — kept separate so unit
/// tests can exercise the freshness/parsing logic against a temp file without
/// mutating the process-global USERPROFILE/HOME env (which would race the
/// issue-167 log tests sharing this binary).
fn read_fresh_startup_error_at(path: &str, since_epoch: u64) -> Option<(String, String)> {
    let content = std::fs::read_to_string(path).ok()?;

    // Freshness gate: only surface a log written during this attempt.
    let when = content
        .lines()
        .find_map(|l| l.trim().strip_prefix("when (epoch s):"))
        .and_then(|v| v.trim().parse::<u64>().ok())?;
    // Allow 2s of slack so clock granularity / pre-spawn timing never hides a
    // genuinely-current failure.
    if when + 2 < since_epoch {
        return None;
    }

    // Extract the indented error block: the lines after the "error:" marker up
    // to the next blank line.
    let mut lines = content.lines();
    let mut err_lines: Vec<String> = Vec::new();
    while let Some(l) = lines.next() {
        if l.trim() == "error:" {
            for body_line in lines.by_ref() {
                if body_line.trim().is_empty() {
                    break;
                }
                err_lines.push(body_line.trim().to_string());
            }
            break;
        }
    }
    if err_lines.is_empty() {
        return None;
    }
    Some((err_lines.join(" "), path.to_string()))
}

/// Absolute path to `~/.psmux/config-warnings.log`, or None if no home dir.
pub(crate) fn config_warnings_log_path() -> Option<String> {
    let home = std::env::var("USERPROFILE")
        .or_else(|_| std::env::var("HOME"))
        .unwrap_or_default();
    if home.is_empty() {
        return None;
    }
    Some(format!("{}\\.psmux\\config-warnings.log", home))
}

/// Persist non-fatal config parse warnings so the attaching client can echo
/// them to the user's terminal (issue #370 follow-up). The detached server has
/// no visible stderr, so an unknown option / malformed value / unknown command
/// would otherwise be silently dropped. A leading `when (epoch s)` line lets
/// the client ignore a stale file from an earlier run. Writing an empty list
/// removes any prior log so resolved configs don't keep re-reporting.
pub(crate) fn write_config_warnings_log(warnings: &[String]) {
    let Some(path) = config_warnings_log_path() else { return };
    if warnings.is_empty() {
        let _ = std::fs::remove_file(&path);
        return;
    }
    if let Some(parent) = std::path::Path::new(&path).parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let mut body = format!("when (epoch s): {}\n", now);
    for w in warnings {
        body.push_str(w);
        body.push('\n');
    }
    let _ = std::fs::write(&path, body);
}

/// Read fresh config warnings written during the current startup attempt.
/// `since_epoch` is when the attempt began; a log older than that (minus 2s of
/// clock slack) is stale and ignored. Returns the warning lines.
pub(crate) fn read_fresh_config_warnings(since_epoch: u64) -> Vec<String> {
    let Some(path) = config_warnings_log_path() else { return Vec::new() };
    let Ok(content) = std::fs::read_to_string(&path) else { return Vec::new() };
    let mut lines = content.lines();
    let when = lines
        .next()
        .and_then(|l| l.trim().strip_prefix("when (epoch s):").map(|v| v.trim().to_string()))
        .and_then(|v| v.parse::<u64>().ok());
    match when {
        Some(w) if w + 2 >= since_epoch => lines.map(|l| l.to_string()).filter(|l| !l.is_empty()).collect(),
        _ => Vec::new(),
    }
}

pub fn run_server(session_name: String, socket_name: Option<String>, initial_command: Option<String>, raw_command: Option<Vec<String>>, start_dir: Option<String>, window_name: Option<String>, init_size: Option<(u16, u16)>, group_target: Option<String>, env_vars: Vec<(String, String)>) -> io::Result<()> {
    // Write crash info to a log file when stderr is unavailable (detached server)
    // and clean up port/key files so stale entries do not linger (issue #204).
    let panic_session_name = session_name.clone();
    let panic_socket_name = socket_name.clone();
    std::panic::set_hook(Box::new(move |info| {
        let home = std::env::var("USERPROFILE").or_else(|_| std::env::var("HOME")).unwrap_or_default();
        let path = format!("{}\\.psmux\\crash.log", home);
        let bt = std::backtrace::Backtrace::force_capture();
        let _ = std::fs::write(&path, format!("{info}\n\nBacktrace:\n{bt}"));
        // Remove port/key files to prevent stale entries after a panic
        let base = if let Some(ref sn) = panic_socket_name {
            format!("{}__{}", sn, panic_session_name)
        } else {
            panic_session_name.clone()
        };
        let _ = std::fs::remove_file(format!("{}\\.psmux\\{}.port", home, base));
        let _ = std::fs::remove_file(format!("{}\\.psmux\\{}.key", home, base));
        let _ = std::fs::remove_file(format!("{}\\.psmux\\{}.sid", home, base));
    }));
    // Install console control handler to prevent termination on client detach
    install_console_ctrl_handler();

    let pty_system = native_pty_system();

    let mut app = AppState::new(session_name);
    app.socket_name = socket_name;
    app.session_group = group_target;
    // Server starts detached with a reasonable default window size
    app.attached_clients = 0;

    // Bind the control listener BEFORE loading config so that run-shell
    // commands spawned by load_config can connect back to the server.
    let (tx, rx) = mpsc::channel::<CtrlReq>();
    app.control_rx = Some(rx);
    let listener = TcpListener::bind(("127.0.0.1", 0))?;
    let port = listener.local_addr()?.port();
    app.control_port = Some(port);
    warm_debug(&format!("server STARTUP: session='{}' bound port={}", app.session_name, port));

    // Write port and key files IMMEDIATELY after binding, BEFORE loading
    // config or creating windows.  run-shell scripts (e.g. PPM) need the
    // port file to discover the server, and the client polls for it to know
    // the server is ready.
    let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
    let dir = format!("{}\\.psmux", home);
    let _ = std::fs::create_dir_all(&dir);

    // Generate a random session key for security
    let session_key: String = {
        use std::collections::hash_map::RandomState;
        use std::hash::{BuildHasher, Hasher};
        let s = RandomState::new();
        let mut h = s.build_hasher();
        h.write_u64(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos() as u64);
        h.write_u64(std::process::id() as u64);
        format!("{:016x}", h.finish())
    };

    app.session_key = session_key.clone();

    // TEST-ONLY fault injection — compiled out of release builds entirely
    // (gated on debug_assertions); inert in debug unless the env var is set.
    // Delays the .port file write (which happens inside
    // ensure_session_registry_files below) while the server is otherwise
    // healthy, to deterministically reproduce a SLOW server startup under load.
    // The client's readiness gate must wait for the eventually-reachable server
    // rather than give up and orphan it. See tests/test_new_session_no_orphan.ps1.
    #[cfg(debug_assertions)]
    {
        if let Ok(ms) = env::var("PSMUX_TEST_PORTFILE_DELAY_MS") {
            if let Ok(ms) = ms.parse::<u64>() {
                thread::sleep(Duration::from_millis(ms));
            }
        }
    }

    ensure_session_registry_files(&home, &app);

    // TEST-ONLY fault injection — compiled out of release builds entirely.
    // Simulates the server dying AFTER writing its .port file but WITHOUT the
    // panic hook running (a hard exit / kill that leaves a stale .port behind).
    // The client's readiness gate must detect the dead server PID and fail fast
    // instead of blocking until the 15s deadline. See tests/test_new_session_hang.ps1.
    #[cfg(debug_assertions)]
    {
        if env::var("PSMUX_TEST_DIE_AFTER_PORTFILE").is_ok() {
            std::process::exit(3);
        }
    }

    let regpath = format!("{}\\{}.port", dir, app.port_file_base());
    let keypath = format!("{}\\{}.key", dir, app.port_file_base());

    // Expose the server identity via env var so that child processes spawned
    // by run-shell (from hooks, keybindings, etc.) can find this server when
    // they call `psmux set -g ...` or other CLI commands.
    env::set_var("PSMUX_TARGET_SESSION", app.port_file_base());

    // Try to set file permissions to user-only (Windows)
    #[cfg(windows)]
    {
        // Recreate key file with restricted permissions
        let _ = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(&keypath)
            .map(|mut f| std::io::Write::write_all(&mut f, session_key.as_bytes()));
    }

    // Start accept thread BEFORE load_config so that run-shell commands
    // (e.g. PPM plugin manager) spawned during config parsing can connect
    // to the server.  Without this, run-shell scripts fail silently because
    // there is no TCP listener accepting connections yet.
    // Initialize shared aliases empty — will be populated after load_config.
    let shared_aliases: std::sync::Arc<std::sync::RwLock<std::collections::HashMap<String, String>>> =
        std::sync::Arc::new(std::sync::RwLock::new(std::collections::HashMap::new()));
    let shared_aliases_main = shared_aliases.clone();

    thread::spawn(move || {
        for conn in listener.incoming() {
            if let Ok(stream) = conn {
                let tx = tx.clone();
                let session_key_clone = session_key.clone();
                let aliases = shared_aliases.clone();
                thread::spawn(move || {
                    connection::handle_connection(stream, tx, &session_key_clone, aliases);
                }); // end per-connection thread
            }
        }
    });

    // Load config AFTER the TCP listener is bound, port/key files are written,
    // and the accept thread is running.  This ensures that run-shell commands
    // in the config (e.g. `run '~/.psmux/plugins/ppm/ppm.ps1'`) can connect
    // back to the server to apply settings.

    // Apply initial dimensions BEFORE warm pane spawn so spawn_warm_pane()
    // uses the correct terminal size.
    if let Some((w, h)) = init_size {
        app.last_window_area = ratatui::layout::Rect { x: 0, y: 0, width: w, height: h };
    }

    // Apply -e environment variables BEFORE pane spawn so the first pane
    // inherits them via apply_user_environment().
    crate::util::merge_session_env_into_app(&mut app, &env_vars);

    // Pre-spawn a warm pane BEFORE loading config: the shell (pwsh) starts
    // loading immediately and runs in parallel with config parsing / plugin
    // initialization.  By the time create_window() consumes it, the shell
    // has had the full config-load duration (~100-500ms) as a head start.
    // Only when using default shell (no custom command).
    // For detached sessions without -x/-y, last_window_area defaults to
    // 120x30 which is fine for the warm pane (resized later on first attach).
    let early_warm = if initial_command.is_none() && raw_command.is_none() && start_dir.is_none() {
        match spawn_warm_pane(&*pty_system, &mut app) {
            Ok(wp) => Some(wp),
            Err(_) => None,
        }
    } else { None };

    crate::config::populate_default_bindings(&mut app);
    load_config(&mut app);
    // Surface any non-fatal config parse warnings to the attaching client
    // (issue #370 follow-up) instead of silently dropping them.
    write_config_warnings_log(&app.config_warnings);
    // Config may set pane-border-status which changes content height (#288)
    resize_all_panes(&mut app);

    // Execute queued plugin .ps1 scripts (e.g. theme plugins that use
    // PowerShell variables and call back to psmux via CLI).  We spawn
    // them async and then drain the CtrlReq channel in a mini-loop so
    // show-options / set requests from the scripts are handled before
    // the main UI starts.
    if !app.pending_plugin_scripts.is_empty() {
        let scripts: Vec<String> = app.pending_plugin_scripts.drain(..).collect();
        let target_session = app.port_file_base();
        let mut children: Vec<std::process::Child> = Vec::new();
        for ps1 in &scripts {
            // Resolve shell: pwsh (PS7) preferred, fall back to powershell.exe (Windows PS)
            let shell = if which::which("pwsh").is_ok() { "pwsh" } else { "powershell" };
            let mut cmd = std::process::Command::new(shell);
            cmd.args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", ps1]);
            if !target_session.is_empty() {
                cmd.env("PSMUX_TARGET_SESSION", &target_session);
            }
            cmd.stdout(std::process::Stdio::null());
            cmd.stderr(std::process::Stdio::null());
            { use crate::platform::HideWindowCommandExt; cmd.hide_window(); }
            if let Ok(child) = cmd.spawn() {
                children.push(child);
            }
        }

        // Drain CtrlReq messages until all scripts finish (max 5s).
        if !children.is_empty() {
            let deadline = Instant::now() + Duration::from_secs(5);
            // Temporarily take rx out of app to avoid borrow conflict
            if let Some(rx) = app.control_rx.take() {
                loop {
                    let all_done = children.iter_mut().all(|c| {
                        matches!(c.try_wait(), Ok(Some(_)))
                    });
                    let remaining = deadline.saturating_duration_since(Instant::now());
                    if all_done || remaining.is_zero() {
                        while let Ok(req) = rx.try_recv() {
                            drain_plugin_req(&mut app, req, &shared_aliases_main);
                        }
                        break;
                    }
                    match rx.recv_timeout(Duration::from_millis(50).min(remaining)) {
                        Ok(req) => drain_plugin_req(&mut app, req, &shared_aliases_main),
                        Err(mpsc::RecvTimeoutError::Timeout) => {}
                        Err(_) => break,
                    }
                }
                app.control_rx = Some(rx);
            }
        }
    }

    // Reconcile the early warm pane (born with all defaults, before
    // load_config ran) with whatever the config actually established.
    // The decision lives in warm_pane_sync::for_post_config; this site
    // just stages the early pane into `app.warm_pane` so the policy
    // module can act on it uniformly.
    if let Some(wp) = early_warm {
        app.warm_pane = Some(wp);
        let sync = crate::warm_pane_sync::for_post_config(&app);
        crate::warm_pane_sync::apply(&mut app, &*pty_system, sync);
    }

    // Update shared aliases now that config has been loaded
    if let Ok(mut w) = shared_aliases_main.write() {
        *w = app.command_aliases.clone();
    }

    // TEST-ONLY fault injection — compiled out of release builds entirely.
    // Widens the new-session readiness race deterministically: the .port file
    // and accept thread are already up (the client's connect check passes), but
    // the initial window does not yet exist and the main request loop is not yet
    // answering. A large value (e.g. 60000) also simulates a server that is
    // ALIVE but whose create_window hangs forever, exercising the client's
    // bounded 15s deadline (it must return ~15s, never block indefinitely).
    // See tests/test_new_session_readiness.ps1 and tests/test_new_session_hang.ps1.
    #[cfg(debug_assertions)]
    {
        if let Ok(ms) = env::var("PSMUX_TEST_WINDOW_DELAY_MS") {
            if let Ok(ms) = ms.parse::<u64>() {
                thread::sleep(Duration::from_millis(ms));
            }
        }
    }

    // Create initial window — if a warm pane was pre-spawned above,
    // create_window's fast path transplants it instantly.
    //
    // Set the server's working directory to the session start directory (the
    // -c dir if given, otherwise the launch dir) and DO NOT restore it
    // afterwards. This server process hosts exactly one session, so its cwd is
    // that session's start directory for the rest of its life. Every later
    // new-window / split / warm-pane replenish without an explicit -c then
    // inherits it — which is what makes an attached client's new-window/split
    // open in the session start directory, while preserving the warm-pane fast
    // path (warm panes are replenished in this same directory).
    if let Some(ref dir) = start_dir { env::set_current_dir(dir).ok(); }
    let create_result = if let Some(ref raw_args) = raw_command {
        create_window_raw(&*pty_system, &mut app, raw_args)
    } else {
        create_window(&*pty_system, &mut app, initial_command.as_deref(), None)
    };
    if let Err(e) = create_result {
        // Issue #167: when the server fails to spawn its initial pane the
        // detached process exits silently — the user sees only "flashes
        // black and returns to prompt" with no visible error.  Persist the
        // failure to a log file the user can find with their next breath
        // ("look in ~/.psmux/server-startup.log") instead of asking them
        // to rerun `psmux server` interactively to see the error.
        write_startup_error_log(&e);
        // Clean up port and key files so stale entries are not left
        // behind when the pane command fails to spawn (issue #204).
        let _ = std::fs::remove_file(&regpath);
        let _ = std::fs::remove_file(&keypath);
        crate::session::remove_session_id_file(&app.port_file_base());
        // Kill warm pane if one was pre-spawned
        if let Some(mut wp) = app.warm_pane.take() { wp.child.kill().ok(); }
        return Err(e);
    }
    // Resize panes now that the initial window exists and config is loaded.
    // pane-border-status needs 1 row per pane for the border label (#288).
    resize_all_panes(&mut app);
    // Apply window name if specified via -n.  Setting `manual_rename = true`
    // is critical (issue #266) — it implicitly disables automatic-rename for
    // the initial window of a `new-session -n NAME`, matching tmux semantics
    // and the two later `-n` paths in this file (lines ~789, ~812).
    if let Some(n) = window_name {
        app.windows.last_mut().map(|w| { w.name = n; w.manual_rename = true; });
    }
    // Replenish: spawn a warm pane for the NEXT new-window / split.
    // Always replenish when no warm pane is available.
    if app.warm_pane.is_none() {
        match spawn_warm_pane(&*pty_system, &mut app) {
            Ok(wp) => { app.warm_pane = Some(wp); }
            Err(e) => { eprintln!("psmux: warm pane pre-spawn failed: {e}"); }
        }
    }
    // Fire client-attached hooks once at startup so plugins populate initial
    // data (e.g. CPU/battery) even for detached sessions (tppanel previews).
    crate::commands::fire_hooks(&mut app, "client-attached");
    // Fire session-created hook at startup
    crate::commands::fire_hooks(&mut app, "session-created");
    // Spawn a warm server for the NEXT new-session when the current session
    // is allowed to keep background state alive.
    if should_spawn_warm_server(&app) {
        spawn_warm_server(&app);
    }
    let mut state_dirty = true;
    let mut cached_dump_state = String::new();
    let mut cached_data_version: u64 = 0;
    // Cached metadata JSON — windows/tree/prefix change only on structural
    // mutations, so we rebuild them lazily via `meta_dirty`.
    let mut meta_dirty = true;
    let mut cached_windows_json = String::new();
    let mut cached_tree_json = String::new();
    let mut cached_prefix_str = String::new();
    let mut cached_prefix2_str = String::new();
    let mut cached_base_index: usize = 0;
    let mut cached_pred_dim: bool = false;
    let mut cached_status_style = String::new();
    let mut cached_bindings_json = String::from("[]");
    // Reusable buffer for building the combined JSON envelope.
    let mut combined_buf = String::with_capacity(32768);


    // Track when we recently sent keystrokes to the PTY.  While waiting
    // for the echo to appear we use a much shorter recv_timeout (1ms vs 5ms)
    // so that dump-state requests are served with minimal delay.  This is
    // critical for nested-shell latency (e.g. WSL inside pwsh) where the
    // echo path goes through ConPTY → pwsh → WSL → echo → ConPTY and can
    // take 10-30ms.  Without this, each "no-change" polling cycle costs up
    // to 5ms, adding cumulative latency visible as heavy input lag.
    let mut echo_pending_until: Option<Instant> = None;

    // Track when any client last requested a dump or sent input.
    // Used to ramp down the server loop frequency when truly idle.
    let mut last_client_activity = Instant::now();

    let mut last_registry_check = Instant::now();

    // Throttle reap_children: only check for exited processes every 250ms.
    // With hundreds of windows, calling try_wait() on every process each
    // loop iteration wastes CPU.  Exited processes are still reaped promptly
    // (250ms is imperceptible to users).
    let mut last_reap = Instant::now();

    // Persist temp_focus_restore across batch boundaries so that a
    // FocusWindowTemp/FocusPaneByIndexTemp in one batch plus the actual
    // command (e.g. CapturePane) in the next batch still works correctly.
    let mut temp_focus_restore: Option<(usize, usize)> = None;

    loop {
        if last_registry_check.elapsed() >= Duration::from_secs(5) {
            last_registry_check = Instant::now();
            ensure_session_registry_files(&home, &app);
        }

        // Adaptive timeout: ramps from 1ms (active typing/echo) through
        // 5ms (client recently active) up to 50ms (fully idle).  This
        // dramatically reduces CPU usage when the session is idle while
        // keeping responsiveness high during interaction.
        let data_ready = crate::types::PTY_DATA_READY.swap(false, std::sync::atomic::Ordering::AcqRel);
        if data_ready {
            state_dirty = true;
            // Drain output ring buffers and send %output notifications to control clients
            if !app.control_clients.is_empty() {
                // Collect output from all panes first, then dispatch to clients
                let mut pane_outputs: Vec<(usize, String)> = Vec::new();
                for win in &app.windows {
                    crate::tree::for_each_pane(&win.root, &mut |pane: &crate::types::Pane| {
                        if let Ok(mut ring) = pane.output_ring.lock() {
                            if !ring.is_empty() {
                                let bytes: Vec<u8> = ring.drain(..).collect();
                                let data = String::from_utf8_lossy(&bytes).to_string();
                                pane_outputs.push((pane.id, data));
                            }
                        }
                    });
                }
                // Dispatch to each control client with pause-after logic
                let now = std::time::Instant::now();
                for (pane_id, data) in &pane_outputs {
                    for client in app.control_clients.values_mut() {
                        if client.paused_panes.contains(pane_id) {
                            continue;
                        }
                        if client.output_paused_panes.contains(pane_id) {
                            // Pane is paused for this client; drop output
                            continue;
                        }
                        if let Some(pause_secs) = client.pause_after_secs {
                            // Track output timing per pane
                            let last = client.pane_last_output.entry(*pane_id).or_insert(now);
                            let age = now.duration_since(*last);
                            *last = now;
                            if age.as_secs() >= pause_secs {
                                // Client fell behind: pause this pane
                                client.output_paused_panes.insert(*pane_id);
                                let _ = client.notification_tx.try_send(
                                    crate::types::ControlNotification::Pause { pane_id: *pane_id }
                                );
                                continue;
                            }
                            // Send as extended-output with age
                            let age_ms = age.as_millis() as u64;
                            let _ = client.notification_tx.try_send(
                                crate::types::ControlNotification::ExtendedOutput {
                                    pane_id: *pane_id,
                                    age_ms,
                                    data: data.clone(),
                                }
                            );
                        } else {
                            // No pause-after: send normal %output
                            let _ = client.notification_tx.try_send(
                                crate::types::ControlNotification::Output {
                                    pane_id: *pane_id,
                                    data: data.clone(),
                                }
                            );
                        }
                    }
                }
            }
            // Answer any ESC[6n queries — pwsh re-issues this after lock/unlock.
            if crate::types::CPR_DATA_PENDING.swap(false, std::sync::atomic::Ordering::AcqRel) {
                for win in &mut app.windows {
                    helpers::drain_cpr_pending(&mut win.root);
                }
                // Also answer CPR queries for the warm pane — it is not in
                // any window yet, but pwsh / PSReadLine blocks on the ESC[6n
                // response during shell startup.  Without this, the warm
                // pane's shell never finishes loading.
                if let Some(ref mut wp) = app.warm_pane {
                    if wp.cpr_pending.swap(false, std::sync::atomic::Ordering::AcqRel) {
                        let (r, c) = wp.term.lock()
                            .map(|g| g.screen().cursor_position())
                            .unwrap_or((0, 0));
                        let response = format!("\x1b[{};{}R", r + 1, c + 1);
                        use std::io::Write as _;
                        let _ = wp.writer.write_all(response.as_bytes());
                        let _ = wp.writer.flush();
                    }
                }
                // Also answer CPR queries for an active popup PTY pane. Like the
                // warm pane it is not in any window tree, but an interactive popup
                // shell (PSReadLine / fzf) blocks on the ESC[6n response and would
                // otherwise render blank forever (#351).
                if let Mode::PopupMode { popup_pane: Some(ref mut pane), .. } = app.mode {
                    if pane.cpr_pending.swap(false, std::sync::atomic::Ordering::AcqRel) {
                        let (r, c) = pane.term.lock()
                            .map(|g| g.screen().cursor_position())
                            .unwrap_or((0, 0));
                        let response = format!("\x1b[{};{}R", r + 1, c + 1);
                        use std::io::Write as _;
                        let _ = pane.writer.write_all(response.as_bytes());
                        let _ = pane.writer.flush();
                    }
                }
            }
        }
        // When a popup PTY is active, always push frames so interactive
        // content (e.g. fzf, shell prompts) updates in real-time.
        if matches!(app.mode, Mode::PopupMode { .. }) {
            state_dirty = true;
        }
        let echo_active = echo_pending_until.map_or(false, |t| t.elapsed().as_millis() < 50);
        let idle_secs = last_client_activity.elapsed().as_secs();
        let timeout_ms: u64 = if echo_active || data_ready {
            1      // Active echo/data: 1ms for maximum responsiveness
        } else if idle_secs < 2 {
            5      // Recently active: 5ms (200 Hz)
        } else if crate::types::has_frame_receivers() {
            16     // Push clients attached: 16ms (~60 Hz) so PTY data
                   // is detected and pushed within one vsync period.
        } else {
            50     // No clients: 50ms (20 Hz) — saves CPU
        };
        if let Some(rx) = app.control_rx.as_ref() {
            if let Ok(req) = rx.recv_timeout(Duration::from_millis(timeout_ms)) {
                last_client_activity = Instant::now();
                let mut pending = vec![req];
                // Drain any additional queued messages without blocking
                while let Ok(r) = rx.try_recv() {
                    pending.push(r);
                }
                // Also check if fresh PTY output arrived while we were
                // waiting – mark state dirty so DumpState produces a full
                // frame instead of "NC".
                if crate::types::PTY_DATA_READY.swap(false, std::sync::atomic::Ordering::AcqRel) {
                    state_dirty = true;
                }
                // Process key/command inputs BEFORE dump-state requests.
                // This ensures ConPTY receives keystrokes before we serialize
                // the screen, reducing stale-frame responses.
                pending.sort_by_key(|r| match r {
                    CtrlReq::DumpState(..) => 1,
                    CtrlReq::DumpLayout(_) => 1,
                    CtrlReq::WindowDump(..) => 1,
                    _ => 0,
                });
                // Track temporary -t focus: save (active_idx, pane_id) when
                // FocusWindowTemp/FocusPaneTemp is seen, restore after next
                // non-temp command so the user's view doesn't jump.
                // We store the pane ID (not path) because kill-pane
                // restructures the tree, invalidating saved paths (#71).
                // NOTE: temp_focus_restore lives outside the loop so it
                // persists across batch boundaries (prevents race where
                // FocusWindowTemp and the actual command land in different
                // batches).
                for req in pending {
                    let mutates_state = !matches!(&req,
                        CtrlReq::DumpState(..)
                        | CtrlReq::SendText(_)
                        | CtrlReq::SendKey(_)
                        | CtrlReq::SendPaste(_)
                        | CtrlReq::WindowDump(..)
                        | CtrlReq::WindowLayout(..)
                    );
                    let is_temp_focus = matches!(&req,
                        CtrlReq::FocusWindowTemp(_) | CtrlReq::FocusWindowByIdTemp(_) | CtrlReq::FocusWindowByNameTemp(_) | CtrlReq::FocusPaneTemp(_) | CtrlReq::FocusPaneByIndexTemp(_));
                    let mut hook_event: Option<&str> = None;
                    // Track active_idx changes for debugging window-switch issues
                    let _prev_active_idx = app.active_idx;
                    let _req_tag: &str = match &req {
                        CtrlReq::NextWindow => "NextWindow",
                        CtrlReq::PrevWindow => "PrevWindow",
                        CtrlReq::SelectWindow(_) => "SelectWindow",
                        CtrlReq::FocusWindow(_) => "FocusWindow",
                        CtrlReq::FocusWindowById(_) => "FocusWindowById",
                        CtrlReq::FocusWindowByName(_) => "FocusWindowByName",
                        CtrlReq::FocusWindowTemp(_) => "FocusWindowTemp",
                        CtrlReq::FocusWindowByIdTemp(_) => "FocusWindowByIdTemp",
                        CtrlReq::FocusWindowByNameTemp(_) => "FocusWindowByNameTemp",
                        CtrlReq::FocusWindowCmd(_) => "FocusWindowCmd",
                        CtrlReq::LastWindow => "LastWindow",
                        CtrlReq::MouseDown(..) => "MouseDown",
                        CtrlReq::MouseDownRight(..) => "MouseDownRight",
                        CtrlReq::MouseDownMiddle(..) => "MouseDownMiddle",
                        CtrlReq::FocusPane(_) => "FocusPane",
                        CtrlReq::FocusPaneTemp(_) => "FocusPaneTemp",
                        CtrlReq::NewWindow(..) => "NewWindow",
                        CtrlReq::KillWindow => "KillWindow",
                        CtrlReq::KillPane => "KillPane",
                        CtrlReq::KillPaneById(_) => "KillPaneById",
                        CtrlReq::BreakPane => "BreakPane",
                        CtrlReq::JoinPane { .. } => "JoinPane",
                        CtrlReq::MovePane { .. } => "MovePane",
                        CtrlReq::PaneForwardExtract(..) => "PaneForwardExtract",
                        CtrlReq::PaneForwardInject { .. } => "PaneForwardInject",
                        CtrlReq::PaneForwardResize(..) => "PaneForwardResize",
                        CtrlReq::PaneForwardStatus(..) => "PaneForwardStatus",
                        CtrlReq::PaneForwardKill(..) => "PaneForwardKill",
                        CtrlReq::MoveWindow(..) => "MoveWindow",
                        CtrlReq::SwapWindow(_) => "SwapWindow",
                        _ => "",
                    };
                    match req {
                CtrlReq::NewWindow(cmd, name, detached, start_dir) => {
                    if let Some(cmds) = app.hooks.get("before-new-window") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                    let prev_idx = app.active_idx;
                    // Expand format variables like #{pane_current_path} (#111)
                    let start_dir = start_dir.map(|d| expand_format(&d, &app)).filter(|d| !d.is_empty());
                    let saved_dir = if start_dir.is_some() { env::current_dir().ok() } else { None };
                    if let Some(dir) = &start_dir { env::set_current_dir(dir).ok(); }
                    // Hide the warm pane when an explicit start dir is requested
                    // so create_window spawns a fresh shell in the correct CWD.
                    let stashed_warm = if start_dir.is_some() { app.warm_pane.take() } else { None };
                    if let Err(e) = create_window(&*pty_system, &mut app, cmd.as_deref(), start_dir.as_deref()) {
                        eprintln!("psmux: new-window error: {e}");
                    }
                    if let Some(wp) = stashed_warm { app.warm_pane = Some(wp); }
                    if let Some(prev) = saved_dir { env::set_current_dir(prev).ok(); }
                    if let Some(n) = name { app.windows.last_mut().map(|w| { w.name = n; w.manual_rename = true; }); }
                    if detached { app.active_idx = prev_idx; }
                    // Replenish warm pane pool for next new-window
                    if app.warm_pane.is_none() {
                        match spawn_warm_pane(&*pty_system, &mut app) {
                            Ok(wp) => { app.warm_pane = Some(wp); }
                            Err(_) => {}
                        }
                    }
                    resize_all_panes(&mut app); meta_dirty = true; hook_event = Some("after-new-window");
                }
                CtrlReq::NewWindowPrint(cmd, name, detached, start_dir, format_str, resp) => {
                    if let Some(cmds) = app.hooks.get("before-new-window") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                    let prev_idx = app.active_idx;
                    let start_dir = start_dir.map(|d| expand_format(&d, &app)).filter(|d| !d.is_empty());
                    let saved_dir = if start_dir.is_some() { env::current_dir().ok() } else { None };
                    if let Some(dir) = &start_dir { env::set_current_dir(dir).ok(); }
                    let stashed_warm = if start_dir.is_some() { app.warm_pane.take() } else { None };
                    if let Err(e) = create_window(&*pty_system, &mut app, cmd.as_deref(), start_dir.as_deref()) {
                        eprintln!("psmux: new-window error: {e}");
                    }
                    if let Some(wp) = stashed_warm { app.warm_pane = Some(wp); }
                    if let Some(prev) = saved_dir { env::set_current_dir(prev).ok(); }
                    if let Some(n) = name { app.windows.last_mut().map(|w| { w.name = n; w.manual_rename = true; }); }
                    // Use full format engine for -P output (tmux compatible)
                    let new_win_idx = app.windows.len() - 1;
                    let fmt = format_str.as_deref().unwrap_or("#{session_name}:#{window_index}");
                    let pane_info = crate::format::expand_format_for_window(fmt, &app, new_win_idx);
                    if detached { app.active_idx = prev_idx; }
                    let _ = resp.send(pane_info);
                    // Replenish warm pane pool for next new-window
                    if app.warm_pane.is_none() {
                        match spawn_warm_pane(&*pty_system, &mut app) {
                            Ok(wp) => { app.warm_pane = Some(wp); }
                            Err(_) => {}
                        }
                    }
                    resize_all_panes(&mut app); meta_dirty = true; hook_event = Some("after-new-window");
                }
                CtrlReq::SplitWindow(k, cmd, detached, start_dir, split_size, resp) => {
                    if let Some(cmds) = app.hooks.get("before-split-window") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                    // tmux: split-window without -Z permanently unzooms (#82)
                    unzoom_if_zoomed(&mut app);
                    let start_dir = start_dir.map(|d| expand_format(&d, &app)).filter(|d| !d.is_empty());
                    let saved_dir = if start_dir.is_some() { env::current_dir().ok() } else { None };
                    if let Some(dir) = &start_dir { env::set_current_dir(dir).ok(); }
                    let prev_path = app.windows[app.active_idx].active_path.clone();
                    // Hide warm pane when explicit start_dir is given (wrong CWD)
                    let stashed_warm = if start_dir.is_some() { app.warm_pane.take() } else { None };
                    if let Err(e) = split_active_with_command(&mut app, k, cmd.as_deref(), Some(&*pty_system), start_dir.as_deref()) {
                        let msg = format!("split-window: {e}");
                        app.status_message = Some((msg.clone(), std::time::Instant::now(), None));
                        let _ = resp.send(format!("psmux: {msg}"));
                    } else {
                        let _ = resp.send(String::new());
                    }
                    if let Some(wp) = stashed_warm { app.warm_pane = Some(wp); }
                    // Apply size if specified: (value, true) = percentage, (value, false) = cell count
                    if let Some((val, is_pct)) = split_size {
                        let pct = if is_pct {
                            val.clamp(1, 99)
                        } else {
                            // Convert cell count to percentage based on split direction
                            let area = app.last_window_area;
                            let total = if k == LayoutKind::Horizontal { area.width } else { area.height };
                            if total > 0 { ((val as u32 * 100) / total as u32).clamp(1, 99) as u16 } else { 50 }
                        };
                        let win = &mut app.windows[app.active_idx];
                        if let Some(Node::Split { sizes, .. }) = get_split_mut(&mut win.root, &prev_path) {
                            sizes[0] = 100 - pct;
                            sizes[1] = pct;
                        }
                    }
                    if detached {
                        // Capture new pane ID before reverting focus
                        let new_pane_id = crate::tree::get_active_pane_id(
                            &app.windows[app.active_idx].root,
                            &app.windows[app.active_idx].active_path,
                        );
                        // Revert focus to the previously active pane.
                        // After split, prev_path now points to a Split node;
                        // the original pane is child [0] of that Split.
                        let mut revert_path = prev_path;
                        revert_path.push(0);
                        app.windows[app.active_idx].active_path = revert_path;
                        // Detached splits never focus the new pane — remove
                        // from MRU entirely so directional nav tie-breaks by
                        // pane_index among equally-unvisited candidates (#70).
                        if let Some(nid) = new_pane_id {
                            let win = &mut app.windows[app.active_idx];
                            win.pane_mru.retain(|&id| id != nid);
                        }
                    } else {
                        // Non-detached: new pane keeps focus.
                        // Cancel temp_focus_restore so -t doesn't revert (#112).
                        temp_focus_restore = None;
                    }
                    if let Some(prev) = saved_dir { env::set_current_dir(prev).ok(); }
                    // Replenish warm pane for the next new-window/split
                    if app.warm_pane.is_none() {
                        match spawn_warm_pane(&*pty_system, &mut app) {
                            Ok(wp) => { app.warm_pane = Some(wp); }
                            Err(_) => {}
                        }
                    }
                    resize_all_panes(&mut app); meta_dirty = true; hook_event = Some("after-split-window");
                }
                CtrlReq::SplitWindowPrint(k, cmd, detached, start_dir, split_size, format_str, resp) => {
                    if let Some(cmds) = app.hooks.get("before-split-window") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                    unzoom_if_zoomed(&mut app);
                    let start_dir = start_dir.map(|d| expand_format(&d, &app)).filter(|d| !d.is_empty());
                    let saved_dir = if start_dir.is_some() { env::current_dir().ok() } else { None };
                    if let Some(dir) = &start_dir { env::set_current_dir(dir).ok(); }
                    let prev_path = app.windows[app.active_idx].active_path.clone();
                    let stashed_warm = if start_dir.is_some() { app.warm_pane.take() } else { None };
                    if let Err(e) = split_active_with_command(&mut app, k, cmd.as_deref(), Some(&*pty_system), start_dir.as_deref()) {
                        app.status_message = Some((format!("split-window: {e}"), std::time::Instant::now(), None));
                        eprintln!("psmux: split-window error: {e}");
                    }
                    if let Some(wp) = stashed_warm { app.warm_pane = Some(wp); }
                    // Apply size if specified: (value, true) = percentage, (value, false) = cell count
                    if let Some((val, is_pct)) = split_size {
                        let pct = if is_pct {
                            val.clamp(1, 99)
                        } else {
                            let area = app.last_window_area;
                            let total = if k == LayoutKind::Horizontal { area.width } else { area.height };
                            if total > 0 { ((val as u32 * 100) / total as u32).clamp(1, 99) as u16 } else { 50 }
                        };
                        let win = &mut app.windows[app.active_idx];
                        if let Some(Node::Split { sizes, .. }) = get_split_mut(&mut win.root, &prev_path) {
                            sizes[0] = 100 - pct;
                            sizes[1] = pct;
                        }
                    }
                    // Use full format engine for -P output (tmux compatible)
                    let fmt = format_str.as_deref().unwrap_or("#{session_name}:#{window_index}.#{pane_index}");
                    let pane_info = crate::format::expand_format_for_window(fmt, &app, app.active_idx);
                    if detached {
                        // Capture new pane ID before reverting focus
                        let new_pane_id = crate::tree::get_active_pane_id(
                            &app.windows[app.active_idx].root,
                            &app.windows[app.active_idx].active_path,
                        );
                        let mut revert_path = prev_path;
                        revert_path.push(0);
                        app.windows[app.active_idx].active_path = revert_path;
                        // Detached splits: remove from MRU (#70 pane_index tie-break)
                        if let Some(nid) = new_pane_id {
                            let win = &mut app.windows[app.active_idx];
                            win.pane_mru.retain(|&id| id != nid);
                        }
                    } else {
                        temp_focus_restore = None;
                    }
                    let _ = resp.send(pane_info);
                    if let Some(prev) = saved_dir { env::set_current_dir(prev).ok(); }
                    // Replenish warm pane
                    if app.warm_pane.is_none() {
                        match spawn_warm_pane(&*pty_system, &mut app) {
                            Ok(wp) => { app.warm_pane = Some(wp); }
                            Err(_) => {}
                        }
                    }
                    resize_all_panes(&mut app); meta_dirty = true; hook_event = Some("after-split-window");
                }
                CtrlReq::KillPane => {
                    if let Some(cmds) = app.hooks.get("before-kill-pane") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                    unzoom_if_zoomed(&mut app); let _ = kill_active_pane(&mut app); resize_all_panes(&mut app); meta_dirty = true; hook_event = Some("after-kill-pane");
                }
                CtrlReq::KillPaneById(pid) => {
                    if let Some(cmds) = app.hooks.get("before-kill-pane") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                    unzoom_if_zoomed(&mut app); let _ = kill_pane_by_id(&mut app, pid); resize_all_panes(&mut app); meta_dirty = true; hook_event = Some("after-kill-pane");
                }
                CtrlReq::CapturePane(resp) => {
                    // Note: do NOT gate on is_active_pane_squelched here.
                    // Returning empty during the cd+cls squelch window makes
                    // iTerm2's initial attach paint a blank screen, since
                    // capture-pane is only requested once on attach.  Return
                    // current parser screen content; it's just cell text and
                    // any stale frame is harmless (subsequent %output rewrites).
                    if let Some(text) = capture_active_pane_text(&mut app)? { let _ = resp.send(text); } else { let _ = resp.send(String::new()); }
                }
                CtrlReq::CapturePaneStyled(resp, s, e) => {
                    if let Some(text) = capture_active_pane_styled(&mut app, s, e)? { let _ = resp.send(text); } else { let _ = resp.send(String::new()); }
                }
                CtrlReq::CapturePaneRange(resp, s, e) => {
                    if let Some(text) = capture_active_pane_range(&mut app, s, e)? { let _ = resp.send(text); } else { let _ = resp.send(String::new()); }
                }
                CtrlReq::FocusWindow(wid) => {
                    // wid is a display index (same as tmux window number), convert to internal array index
                    if wid >= app.window_base_index {
                        let internal_idx = wid - app.window_base_index;
                        if internal_idx < app.windows.len() && internal_idx != app.active_idx {
                            switch_with_copy_save(&mut app, |app| {
                                app.last_window_idx = app.active_idx;
                                app.active_idx = internal_idx;
                            });
                            // Clear activity/bell/silence flags on the newly-focused window
                            if let Some(win) = app.windows.get_mut(internal_idx) {
                                win.activity_flag = false;
                                win.bell_flag = false;
                                win.silence_flag = false;
                            }
                            // Lazily resize panes in the newly-focused window
                            resize_all_panes(&mut app);
                        }
                    }
                    meta_dirty = true;
                    hook_event = Some("after-select-window");
                }
                CtrlReq::FocusWindowByName(ref name) => {
                    if let Some(internal_idx) = app.windows.iter().position(|w| w.name == *name) {
                        if internal_idx != app.active_idx {
                            switch_with_copy_save(&mut app, |app| {
                                app.last_window_idx = app.active_idx;
                                app.active_idx = internal_idx;
                            });
                            if let Some(win) = app.windows.get_mut(internal_idx) {
                                win.activity_flag = false;
                                win.bell_flag = false;
                                win.silence_flag = false;
                            }
                            resize_all_panes(&mut app);
                        }
                    }
                    meta_dirty = true;
                    hook_event = Some("after-select-window");
                }
                CtrlReq::FocusWindowById(id) => {
                    if let Some(internal_idx) = app.windows.iter().position(|w| w.id == id) {
                        if internal_idx != app.active_idx {
                            switch_with_copy_save(&mut app, |app| {
                                app.last_window_idx = app.active_idx;
                                app.active_idx = internal_idx;
                            });
                            if let Some(win) = app.windows.get_mut(internal_idx) {
                                win.activity_flag = false;
                                win.bell_flag = false;
                                win.silence_flag = false;
                            }
                            resize_all_panes(&mut app);
                        }
                    }
                    meta_dirty = true;
                    hook_event = Some("after-select-window");
                }
                CtrlReq::FocusPane(pid) => {
                    let old_path = app.windows[app.active_idx].active_path.clone();
                    switch_with_copy_save(&mut app, |app| { focus_pane_by_id(app, pid); });
                    if app.windows[app.active_idx].active_path != old_path { unzoom_if_zoomed(&mut app); }
                    meta_dirty = true;
                }
                CtrlReq::FocusPaneByIndex(idx) => {
                    let old_path = app.windows[app.active_idx].active_path.clone();
                    switch_with_copy_save(&mut app, |app| { focus_pane_by_index(app, idx); });
                    if app.windows[app.active_idx].active_path != old_path { unzoom_if_zoomed(&mut app); }
                    // Update MRU so directional navigation remembers this focus change
                    let win = &mut app.windows[app.active_idx];
                    if let Some(pid) = crate::tree::get_active_pane_id(&win.root, &win.active_path) {
                        crate::tree::touch_mru(&mut win.pane_mru, pid);
                    }
                    meta_dirty = true;
                }
                // ── Temporary focus variants for -t targeting ────────────
                // These switch active_idx/active_path so the NEXT command
                // in the batch operates on the correct window/pane.
                // After the entire pending batch is processed, we restore
                // the original focus (see temp_focus_restore below).
                CtrlReq::FocusWindowTemp(wid) => {
                    if temp_focus_restore.is_none() {
                        let pane_id = crate::tree::get_active_pane_id(
                            &app.windows[app.active_idx].root,
                            &app.windows[app.active_idx].active_path,
                        ).unwrap_or(usize::MAX);
                        temp_focus_restore = Some((app.active_idx, pane_id));
                    }
                    if wid >= app.window_base_index {
                        let internal_idx = wid - app.window_base_index;
                        if internal_idx < app.windows.len() {
                            app.active_idx = internal_idx;
                        }
                    }
                }
                CtrlReq::FocusWindowByNameTemp(ref name) => {
                    if temp_focus_restore.is_none() {
                        let pane_id = crate::tree::get_active_pane_id(
                            &app.windows[app.active_idx].root,
                            &app.windows[app.active_idx].active_path,
                        ).unwrap_or(usize::MAX);
                        temp_focus_restore = Some((app.active_idx, pane_id));
                    }
                    if let Some(internal_idx) = app.windows.iter().position(|w| w.name == *name) {
                        app.active_idx = internal_idx;
                    }
                }
                CtrlReq::FocusWindowByIdTemp(id) => {
                    if temp_focus_restore.is_none() {
                        let pane_id = crate::tree::get_active_pane_id(
                            &app.windows[app.active_idx].root,
                            &app.windows[app.active_idx].active_path,
                        ).unwrap_or(usize::MAX);
                        temp_focus_restore = Some((app.active_idx, pane_id));
                    }
                    if let Some(internal_idx) = app.windows.iter().position(|w| w.id == id) {
                        app.active_idx = internal_idx;
                    }
                }
                CtrlReq::FocusPaneTemp(pid) => {
                    if temp_focus_restore.is_none() {
                        let pane_id = crate::tree::get_active_pane_id(
                            &app.windows[app.active_idx].root,
                            &app.windows[app.active_idx].active_path,
                        ).unwrap_or(usize::MAX);
                        temp_focus_restore = Some((app.active_idx, pane_id));
                    }
                    // Use no-MRU variant: temporary -t targeting should not
                    // pollute the recency list (#71 — split-window -t was
                    // incorrectly touching the target pane's MRU rank).
                    focus_pane_by_id_no_mru(&mut app, pid);
                }
                CtrlReq::FocusPaneByIndexTemp(idx) => {
                    if temp_focus_restore.is_none() {
                        let pane_id = crate::tree::get_active_pane_id(
                            &app.windows[app.active_idx].root,
                            &app.windows[app.active_idx].active_path,
                        ).unwrap_or(usize::MAX);
                        temp_focus_restore = Some((app.active_idx, pane_id));
                    }
                    focus_pane_by_index(&mut app, idx);
                }
                CtrlReq::SessionInfo(resp) => {
                    let num_attached = app.client_registry.len();
                    let attached = if num_attached > 0 { " (attached)" } else { "" };
                    let group = if let Some(ref g) = app.session_group {
                        format!(" (group {})", g)
                    } else {
                        String::new()
                    };
                    let windows = app.windows.len();
                    let created = app.created_at.format("%a %b %e %H:%M:%S %Y");
                    let line = format!("{}: {} windows (created {}){}{}\n", app.session_name, windows, created, group, attached);
                    let _ = resp.send(line);
                }
                CtrlReq::SessionInfoFormat(resp, fmt) => {
                    let line = crate::format::format_list_sessions(&app, &fmt);
                    let _ = resp.send(format!("{}\n", line));
                }
                CtrlReq::ClientAttach(cid) => {
                    app.attached_clients = app.attached_clients.saturating_add(1);
                    app.latest_client_id = Some(cid);
                    // Register in client registry if not already present
                    app.client_registry.entry(cid).or_insert_with(|| {
                        let tty = format!("/dev/pts/{}", cid);
                        crate::types::ClientInfo {
                            id: cid,
                            width: app.last_window_area.width,
                            height: app.last_window_area.height,
                            connected_at: std::time::Instant::now(),
                            last_activity: std::time::Instant::now(),
                            tty_name: tty,
                            is_control: false,
                        }
                    });
                    hook_event = Some("client-attached");
                    // update-environment: refresh env vars from the attaching client's environment
                    let update_vars = app.update_environment.clone();
                    for var_spec in &update_vars {
                        let remove = var_spec.starts_with('-');
                        let name = if remove { &var_spec[1..] } else { var_spec.as_str() };
                        if remove {
                            app.environment.remove(name);
                        } else if let Ok(val) = std::env::var(name) {
                            app.environment.insert(name.to_string(), val);
                        } else {
                            app.environment.remove(name);
                        }
                    }
                }
                CtrlReq::ClientDetach(cid) => {
                    app.attached_clients = app.attached_clients.saturating_sub(1);
                    app.client_sizes.remove(&cid);
                    app.client_registry.remove(&cid);
                    app.client_prefix_active = false;
                    if app.latest_client_id == Some(cid) {
                        app.latest_client_id = None;
                    }
                    // Recompute effective size from remaining clients
                    if let Some((w, h)) = compute_effective_client_size(&app) {
                        app.last_window_area = Rect { x: 0, y: 0, width: w, height: h };
                        resize_all_panes(&mut app);
                    }
                    hook_event = Some("client-detached");
                    if app.attached_clients == 0 && app.destroy_unattached {
                        let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
                        let regpath = format!("{}\\.psmux\\{}.port", home, app.port_file_base());
                        let keypath = format!("{}\\.psmux\\{}.key", home, app.port_file_base());
                        let _ = std::fs::remove_file(&regpath);
                        let _ = std::fs::remove_file(&keypath);
                        crate::session::remove_session_id_file(&app.port_file_base());
                        crate::types::shutdown_persistent_streams();
                        tree::kill_all_children_batch(&mut app.windows);
                        if let Some(mut wp) = app.warm_pane.take() {
                            wp.child.kill().ok();
                        }
                        std::thread::sleep(std::time::Duration::from_millis(10));
                        std::process::exit(0);
                    }
                }
                CtrlReq::DumpLayout(resp) => {
                    let json = dump_layout_json(&mut app)?;
                    let _ = resp.send(json);
                }
                CtrlReq::DumpState(resp, allow_nc) => {
                    // ── Activity / bell / silence detection ──
                    let alert_hooks = helpers::check_window_activity(&mut app);
                    for event in &alert_hooks {
                        if let Some(cmds) = app.hooks.get(*event) { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                    }

                    // ── Propagate OSC 0/2 titles to pane.title ──
                    if helpers::propagate_osc_titles(&mut app) {
                        state_dirty = true;
                    }

                    // ── Automatic rename / allow-rename: resolve window names ──
                    {
                        let in_copy = matches!(app.mode, Mode::CopyMode | Mode::CopySearch { .. });
                        let auto_rename = app.automatic_rename;
                        let allow_rename = app.allow_rename;
                        if (auto_rename || allow_rename) && !in_copy {
                            for win in app.windows.iter_mut() {
                                if win.manual_rename { continue; }
                                if let Some(p) = crate::tree::active_pane_mut(&mut win.root, &win.active_path) {
                                    if p.dead { continue; }
                                    if p.last_title_check.elapsed().as_millis() < 1000 { continue; }
                                    p.last_title_check = std::time::Instant::now();
                                    if p.child_pid.is_none() {
                                        p.child_pid = crate::platform::mouse_inject::get_child_pid(&*p.child);
                                    }
                                    let new_name = if auto_rename {
                                        // automatic-rename: use foreground process name
                                        if let Some(pid) = p.child_pid {
                                            match crate::platform::process_info::get_foreground_process_name(pid) {
                                                Some(name) => name,
                                                None => {
                                                    // No foreground child found.  Keep the current
                                                    // window name to avoid flashing to the shell
                                                    // name before a child process spawns (#229).
                                                    // Once a child appears, auto-rename will pick
                                                    // it up on the next tick.
                                                    continue;
                                                }
                                            }
                                        } else if allow_rename && !p.title.is_empty() {
                                            p.title.clone()
                                        } else {
                                            continue;
                                        }
                                    } else if allow_rename {
                                        // allow-rename only: use OSC title from child
                                        if let Ok(parser) = p.term.lock() {
                                            let title = parser.screen().title();
                                            if !title.is_empty() {
                                                title.to_string()
                                            } else {
                                                continue;
                                            }
                                        } else {
                                            continue;
                                        }
                                    } else {
                                        continue;
                                    };
                                    if !new_name.is_empty() && win.name != new_name {
                                        win.name = new_name;
                                        meta_dirty = true;
                                        state_dirty = true;
                                    }
                                }
                            }
                        }
                    }
                    // Fast-path: nothing changed at all → 2-byte "NC" marker
                    // instead of cloning 50-100KB of JSON.
                    // Only allowed for persistent connections that already have
                    // the previous frame; one-shot connections always need full state.
                    let has_squelch = app.windows.get(app.active_idx)
                        .and_then(|w| crate::tree::active_pane(&w.root, &w.active_path))
                        .map_or(false, |p| p.squelch_until.is_some());
                    if allow_nc
                        && !state_dirty
                        && !app.bell_forward
                        && !has_squelch
                        && !cached_dump_state.is_empty()
                        && cached_data_version == combined_data_version(&app)
                    {
                        let _ = resp.send("NC".to_string());
                        continue;
                    }
                    // Rebuild metadata cache if structural changes happened.
                    if meta_dirty {
                        cached_windows_json = list_windows_json_with_tabs(&app)?;
                        cached_tree_json = list_tree_json(&app)?;
                        cached_prefix_str = format_key_binding(&app.prefix_key);
                        cached_prefix2_str = app.prefix2_key.as_ref().map(|k| format_key_binding(k)).unwrap_or_default();
                        cached_base_index = app.window_base_index;
                        cached_pred_dim = app.prediction_dimming;
                        cached_status_style = app.status_style.clone();
                        cached_bindings_json = serialize_bindings_json(&app);
                        meta_dirty = false;
                    }
                    let _t_layout = std::time::Instant::now();
                    let layout_json = dump_layout_json_fast(&mut app)?;
                    let _layout_ms = _t_layout.elapsed().as_micros();
                    combined_buf.clear();
                    // #372: style options must be format-expanded too, so a
                    // #{@var} colour reference resolves before the client's
                    // colour parser sees it (otherwise status-style falls back
                    // to bright green). wsf/wscf stay raw: they are per-window
                    // formats the client expands with each window's own context.
                    let ss_escaped = json_escape_string(&expand_format(&cached_status_style, &app));
                    let sl_expanded = json_escape_string(&expand_format(&app.status_left, &app));
                    let sr_expanded = json_escape_string(&expand_format(&app.status_right, &app));
                    let pbs_escaped = json_escape_string(&expand_format(&app.pane_border_style, &app));
                    let pabs_escaped = json_escape_string(&expand_format(&app.pane_active_border_style, &app));
                    let pbhs_escaped = json_escape_string(&expand_format(&app.pane_border_hover_style, &app));
                    let wsf_escaped = json_escape_string(&app.window_status_format);
                    let wscf_escaped = json_escape_string(&app.window_status_current_format);
                    let wss_escaped = json_escape_string(&expand_format(&app.window_status_separator, &app));
                    let ws_style_escaped = json_escape_string(&expand_format(&app.window_status_style, &app));
                    let wsc_style_escaped = json_escape_string(&expand_format(&app.window_status_current_style, &app));
                    let mode_style_escaped = json_escape_string(&expand_format(&app.mode_style, &app));
                    // #372: message-style was never sent to the client (it
                    // hard-coded bg=yellow,fg=black). Send it, format-expanded.
                    let message_style_escaped = json_escape_string(&expand_format(&app.message_style, &app));
                    let status_position_escaped = json_escape_string(&app.status_position);
                    let status_justify_escaped = json_escape_string(&app.status_justify);
                    // Build status_format JSON array for multi-line status bar
                    let status_format_json = {
                        let mut sf = String::from("[");
                        for (i, fmt_str) in app.status_format.iter().enumerate() {
                            if i > 0 { sf.push(','); }
                            sf.push('"');
                            sf.push_str(&json_escape_string(&expand_format(fmt_str, &app)));
                            sf.push('"');
                        }
                        sf.push(']');
                        sf
                    };
                    let cursor_style_code = crate::rendering::configured_cursor_code();
                    let _ = std::fmt::Write::write_fmt(&mut combined_buf, format_args!(
                        "{{\"layout\":{},\"windows\":{},\"prefix\":\"{}\",\"prefix2\":\"{}\",\"tree\":{},\"base_index\":{},\"pane_base_index\":{},\"prediction_dimming\":{},\"status_style\":\"{}\",\"status_left\":\"{}\",\"status_right\":\"{}\",\"pane_border_style\":\"{}\",\"pane_active_border_style\":\"{}\",\"pane_border_hover_style\":\"{}\",\"wsf\":\"{}\",\"wscf\":\"{}\",\"wss\":\"{}\",\"ws_style\":\"{}\",\"wsc_style\":\"{}\",\"clock_mode\":{},\"bindings\":{},\"status_left_length\":{},\"status_right_length\":{},\"status_lines\":{},\"status_format\":{},\"mode_style\":\"{}\",\"message_style\":\"{}\",\"status_position\":\"{}\",\"status_justify\":\"{}\",\"cursor_style_code\":{},\"status_visible\":{},\"repeat_time\":{},\"zoomed\":{},\"defaults_suppressed\":{},\"pwsh_mouse_selection\":{},\"mouse_selection\":{},\"paste_detection\":{},\"choose_tree_preview\":{},\"scroll_enter_copy_mode\":{}}}",
                        layout_json, cached_windows_json, cached_prefix_str, cached_prefix2_str, cached_tree_json, cached_base_index, app.pane_base_index, cached_pred_dim, ss_escaped, sl_expanded, sr_expanded, pbs_escaped, pabs_escaped, pbhs_escaped, wsf_escaped, wscf_escaped, wss_escaped, ws_style_escaped, wsc_style_escaped,
                        matches!(app.mode, Mode::ClockMode), cached_bindings_json,
                        app.status_left_length, app.status_right_length, app.status_lines, status_format_json,
                        mode_style_escaped, message_style_escaped, status_position_escaped, status_justify_escaped,
                        cursor_style_code, app.status_visible, app.repeat_time_ms,
                        app.windows.get(app.active_idx).map_or(false, |w| w.zoom_saved.is_some()),
                        app.defaults_suppressed,
                        app.pwsh_mouse_selection,
                        app.mouse_selection,
                        app.paste_detection,
                        app.choose_tree_preview,
                        app.scroll_enter_copy_mode,
                    ));
                    // Inject overlay state (popup, menu, confirm, display_panes)
                    {
                        // Inject clock_colour if set
                        if let Some(cc) = app.user_options.get("clock-mode-colour") {
                            if combined_buf.ends_with('}') {
                                combined_buf.pop();
                                combined_buf.push_str(",\"clock_colour\":\"");
                                combined_buf.push_str(&json_escape_string(cc));
                                combined_buf.push_str("\"}");
                            }
                        }
                        // Inject pane-border-status and pane-border-format
                        if let Some(pbs) = app.user_options.get("pane-border-status") {
                            if combined_buf.ends_with('}') {
                                combined_buf.pop();
                                combined_buf.push_str(",\"pane_border_status\":\"");
                                combined_buf.push_str(&json_escape_string(pbs));
                                combined_buf.push('"');
                                if let Some(pbf) = app.user_options.get("pane-border-format") {
                                    combined_buf.push_str(",\"pane_border_format\":\"");
                                    combined_buf.push_str(&json_escape_string(pbf));
                                    combined_buf.push('"');
                                }
                                combined_buf.push('}');
                            }
                        }
                        // set-titles: when on, expand set-titles-string and ship
                        // it so the client emits OSC 0 to its host terminal.
                        if app.set_titles && combined_buf.ends_with('}') {
                            let fmt = if app.set_titles_string.is_empty() {
                                "#S:#I:#W"
                            } else {
                                app.set_titles_string.as_str()
                            };
                            let expanded = expand_format(fmt, &app);
                            combined_buf.pop();
                            combined_buf.push_str(",\"host_title\":\"");
                            combined_buf.push_str(&json_escape_string(&expanded));
                            combined_buf.push_str("\"}");
                        }
                        // Issue #269: forward OSC 9;4 progress from the active
                        // pane so the client emits the same sequence to the
                        // host terminal (Windows Terminal taskbar/tab progress).
                        if combined_buf.ends_with('}') {
                            if let Some((s, v)) = helpers::active_pane_progress(&app) {
                                combined_buf.pop();
                                combined_buf.push_str(",\"host_progress\":\"");
                                combined_buf.push_str(&format!("{};{}", s, v));
                                combined_buf.push_str("\"}");
                            }
                        }
                        let overlay_json = serialize_overlay_json(&app);
                        if !overlay_json.is_empty() && combined_buf.ends_with('}') {
                            combined_buf.pop();
                            combined_buf.push_str(&overlay_json);
                            combined_buf.push('}');
                        }
                    }
                    cached_dump_state.clear();
                    cached_dump_state.push_str(&combined_buf);
                    // Forward OSC 52 from pane child processes (e.g. Claude
                    // Code's `/copy`).  The pane's parser stages incoming
                    // OSC 52 onto its Screen; drain it and decode to plain
                    // text so the existing dump-state injection below
                    // re-emits it as OSC 52 on the client's stdout to the
                    // host terminal.  Gated by `set-clipboard` option.
                    if app.set_clipboard != "off" && app.clipboard_osc52.is_none() {
                        if let Some((_sel, b64)) = take_pane_clipboard(&app) {
                            if let Ok(b64_str) = std::str::from_utf8(&b64) {
                                if let Some(text) = crate::util::base64_decode(b64_str) {
                                    app.clipboard_osc52 = Some(text);
                                }
                            }
                        }
                    }
                    // Inject one-shot clipboard data for OSC 52 delivery to
                    // the client.  Only the *response* includes this field;
                    // the cached copy does not, so subsequent NC frames won't
                    // re-trigger clipboard emission on the client.
                    if let Some(clip_text) = app.clipboard_osc52.take() {
                        let clip_b64 = base64_encode(&clip_text);
                        // Replace trailing '}' with the extra field
                        if combined_buf.ends_with('}') {
                            combined_buf.pop();
                            combined_buf.push_str(",\"clipboard_osc52\":\"");
                            combined_buf.push_str(&clip_b64);
                            combined_buf.push_str("\"}");
                        }
                    }
                    // Forward audible bell to client terminal
                    if app.bell_forward {
                        app.bell_forward = false;
                        if combined_buf.ends_with('}') {
                            combined_buf.pop();
                            combined_buf.push_str(",\"bell\":true}");
                        }
                    }
                    cached_data_version = combined_data_version(&app);
                    state_dirty = false;
                    // Timing log: dump-state build time
                    if std::env::var("PSMUX_LATENCY_LOG").unwrap_or_default() == "1" {
                        let total_us = _t_layout.elapsed().as_micros();
                        use std::io::Write as _;
                        static SRV_LOG: std::sync::OnceLock<std::sync::Mutex<std::fs::File>> = std::sync::OnceLock::new();
                        let log = SRV_LOG.get_or_init(|| {
                            let p = std::path::PathBuf::from(std::env::var("USERPROFILE").unwrap_or_else(|_| "C:\\Users\\gj".into())).join("psmux_server_latency.log");
                            std::sync::Mutex::new(std::fs::File::create(p).expect("create latency log"))
                        });
                        if let Ok(mut f) = log.lock() {
                            let _ = writeln!(f, "[SRV] dump: layout={}us total={}us json_len={}", _layout_ms, total_us, combined_buf.len());
                        }
                    }
                    // Push the newly-built frame to ALL persistent clients so
                    // that other attached sessions see the update immediately,
                    // even if they are idle and not polling dump-state.
                    // Without this, the DumpState handler clears state_dirty,
                    // and the bottom-of-loop push section never fires for frames
                    // already served to the requesting client.
                    // Push combined_buf (not cached_dump_state) so one-shot
                    // fields like bell and clipboard reach all clients.
                    // The cached copy omits them for NC dedup safety.
                    crate::types::push_frame(&combined_buf);
                    let _ = resp.send(combined_buf.clone());
                }
                CtrlReq::SendText(s) => { app.status_message = None; send_text_to_active(&mut app, &s)?; echo_pending_until = Some(Instant::now()); }
                CtrlReq::SendKey(k) => { app.status_message = None; send_key_to_active(&mut app, &k)?; echo_pending_until = Some(Instant::now()); }
                CtrlReq::SendPaste(s) => { send_paste_to_active(&mut app, &s)?; echo_pending_until = Some(Instant::now()); }
                CtrlReq::ZoomPane => { toggle_zoom(&mut app); state_dirty = true; meta_dirty = true; hook_event = Some("after-resize-pane"); }
                CtrlReq::PrefixBegin => { app.client_prefix_active = true; state_dirty = true; }
                CtrlReq::PrefixEnd => { app.client_prefix_active = false; state_dirty = true; }
                CtrlReq::CopyEnter => { enter_copy_mode(&mut app); hook_event = Some("pane-mode-changed"); }
                CtrlReq::CopyEnterPageUp => {
                    if app.scroll_enter_copy_mode {
                        enter_copy_mode(&mut app);
                        let half = app.windows.get(app.active_idx)
                            .and_then(|w| active_pane(&w.root, &w.active_path))
                            .map(|p| p.last_rows as usize).unwrap_or(20);
                        scroll_copy_up(&mut app, half);
                        hook_event = Some("pane-mode-changed");
                    } else {
                        // scroll-enter-copy-mode is off: forward PageUp to the
                        // active pane so apps like less/vim/WSL receive it (#284).
                        send_text_to_active(&mut app, "\x1b[5~")?;
                        echo_pending_until = Some(Instant::now());
                    }
                }
                CtrlReq::ClockMode => { app.mode = Mode::ClockMode; state_dirty = true; hook_event = Some("pane-mode-changed"); }
                CtrlReq::CopyMove(dx, dy) => { move_copy_cursor(&mut app, dx, dy); }
                CtrlReq::CopyAnchor => { if let Some((r,c)) = current_prompt_pos(&mut app) { app.copy_anchor = Some((r,c)); app.copy_anchor_scroll_offset = app.copy_scroll_offset; app.copy_pos = Some((r,c)); } }
                CtrlReq::CopyYank => {
                    let _ = yank_selection(&mut app);
                    if let Some(cmds) = app.hooks.get("pane-set-clipboard") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                    exit_copy_mode(&mut app);
                    hook_event = Some("pane-mode-changed");
                }
                CtrlReq::CopyRectToggle => {
                    app.copy_selection_mode = match app.copy_selection_mode {
                        crate::types::SelectionMode::Rect => crate::types::SelectionMode::Char,
                        _ => crate::types::SelectionMode::Rect,
                    };
                }
                CtrlReq::ClientSize(cid, w, h) => { 
                    app.client_sizes.insert(cid, (w, h));
                    app.latest_client_id = Some(cid);
                    // Update registry with new size and activity timestamp
                    if let Some(info) = app.client_registry.get_mut(&cid) {
                        info.width = w;
                        info.height = h;
                        info.last_activity = std::time::Instant::now();
                    }
                    let (ew, eh) = compute_effective_client_size(&app).unwrap_or((w, h));
                    app.last_window_area = Rect { x: 0, y: 0, width: ew, height: eh };
                    resize_all_panes(&mut app);
                    // Reconcile warm pane dimensions through the central
                    // policy module so resize uses the same code path as
                    // every other warm-pane invalidation (#271).
                    let sync = crate::warm_pane_sync::for_resize(&app, eh, ew);
                    crate::warm_pane_sync::apply(&mut app, &*pty_system, sync);
                    hook_event = Some("client-resized");
                }
                CtrlReq::FocusPaneCmd(pid) => {
                    let old_path = app.windows[app.active_idx].active_path.clone();
                    switch_with_copy_save(&mut app, |app| { focus_pane_by_id(app, pid); });
                    if app.windows[app.active_idx].active_path != old_path { unzoom_if_zoomed(&mut app); }
                    meta_dirty = true;
                }
                CtrlReq::FocusWindowCmd(wid) => { switch_with_copy_save(&mut app, |app| { if let Some(idx) = find_window_index_by_id(app, wid) { app.active_idx = idx; } }); resize_all_panes(&mut app); meta_dirty = true; }
                CtrlReq::MouseDown(cid,x,y) => { if app.mouse_enabled { app.latest_client_id = Some(cid); remote_mouse_down(&mut app, x, y); state_dirty = true; meta_dirty = true; echo_pending_until = Some(Instant::now()); } }
                CtrlReq::MouseDownRight(cid,x,y) => { if app.mouse_enabled { app.latest_client_id = Some(cid); remote_mouse_button(&mut app, x, y, 2, true); state_dirty = true; echo_pending_until = Some(Instant::now()); } }
                CtrlReq::MouseDownMiddle(cid,x,y) => { if app.mouse_enabled { app.latest_client_id = Some(cid); remote_mouse_button(&mut app, x, y, 1, true); state_dirty = true; echo_pending_until = Some(Instant::now()); } }
                CtrlReq::MouseDrag(cid,x,y) => { if app.mouse_enabled { app.latest_client_id = Some(cid); remote_mouse_drag(&mut app, x, y); state_dirty = true; echo_pending_until = Some(Instant::now()); } }
                CtrlReq::MouseUp(cid,x,y) => { if app.mouse_enabled { app.latest_client_id = Some(cid); remote_mouse_up(&mut app, x, y); state_dirty = true; echo_pending_until = Some(Instant::now()); } }
                CtrlReq::MouseUpRight(cid,x,y) => { if app.mouse_enabled { app.latest_client_id = Some(cid); remote_mouse_button(&mut app, x, y, 2, false); state_dirty = true; echo_pending_until = Some(Instant::now()); } }
                CtrlReq::MouseUpMiddle(cid,x,y) => { if app.mouse_enabled { app.latest_client_id = Some(cid); remote_mouse_button(&mut app, x, y, 1, false); state_dirty = true; echo_pending_until = Some(Instant::now()); } }
                CtrlReq::MouseMove(cid,x,y) => { if app.mouse_enabled { app.latest_client_id = Some(cid); remote_mouse_motion(&mut app, x, y); state_dirty = true; echo_pending_until = Some(Instant::now()); } }
                CtrlReq::ScrollUp(cid, x, y) => { if app.mouse_enabled { app.latest_client_id = Some(cid); remote_scroll_up(&mut app, x, y); state_dirty = true; echo_pending_until = Some(Instant::now()); } }
                CtrlReq::ScrollDown(cid, x, y) => { if app.mouse_enabled { app.latest_client_id = Some(cid); remote_scroll_down(&mut app, x, y); state_dirty = true; echo_pending_until = Some(Instant::now()); } }
                CtrlReq::PaneMouse(cid, pane_id, button, col, row, press) => { if app.mouse_enabled { app.latest_client_id = Some(cid); handle_pane_mouse(&mut app, pane_id, button, col, row, press); state_dirty = true; meta_dirty = true; echo_pending_until = Some(Instant::now()); } }
                CtrlReq::PaneScroll(cid, pane_id, up) => { if app.mouse_enabled { app.latest_client_id = Some(cid); handle_pane_scroll(&mut app, pane_id, up); state_dirty = true; meta_dirty = true; echo_pending_until = Some(Instant::now()); } }
                CtrlReq::SplitSetSizes(cid, path, sizes) => { if app.mouse_enabled { app.latest_client_id = Some(cid); handle_split_set_sizes(&mut app, &path, &sizes); state_dirty = true; meta_dirty = true; echo_pending_until = Some(Instant::now()); } }
                CtrlReq::SplitResizeDone(cid) => { if app.mouse_enabled { app.latest_client_id = Some(cid); handle_split_resize_done(&mut app); state_dirty = true; meta_dirty = true; } }
                CtrlReq::NextWindow => {
                    if let Some(cmds) = app.hooks.get("before-select-window") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                    if !app.windows.is_empty() { switch_with_copy_save(&mut app, |app| { app.last_window_idx = app.active_idx; app.active_idx = (app.active_idx + 1) % app.windows.len(); }); resize_all_panes(&mut app); } meta_dirty = true; hook_event = Some("after-select-window");
                }
                CtrlReq::PrevWindow => {
                    if let Some(cmds) = app.hooks.get("before-select-window") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                    if !app.windows.is_empty() { switch_with_copy_save(&mut app, |app| { app.last_window_idx = app.active_idx; app.active_idx = (app.active_idx + app.windows.len() - 1) % app.windows.len(); }); resize_all_panes(&mut app); } meta_dirty = true; hook_event = Some("after-select-window");
                }
                CtrlReq::RenameWindow(name) => {
                    if let Some(cmds) = app.hooks.get("before-rename-window") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                    let win = &mut app.windows[app.active_idx]; win.name = name; win.manual_rename = true; meta_dirty = true; hook_event = Some("after-rename-window");
                }
                CtrlReq::ListWindows(resp) => { helpers::propagate_osc_titles(&mut app); let json = list_windows_json(&app)?; let _ = resp.send(json); }
                CtrlReq::ListWindowsTmux(resp) => { helpers::propagate_osc_titles(&mut app); let text = list_windows_tmux(&app); let _ = resp.send(text); }
                CtrlReq::ListWindowsFormat(resp, fmt) => { helpers::propagate_osc_titles(&mut app); let text = format_list_windows(&app, &fmt); let _ = resp.send(text); }
                CtrlReq::ListTree(resp) => { let json = list_tree_json(&app)?; let _ = resp.send(json); }
                CtrlReq::WindowLayout(wid, resp) => {
                    let json = crate::util::window_layout_json(&app, wid)
                        .unwrap_or_else(|_| "{}".to_string());
                    let _ = resp.send(json);
                }
                CtrlReq::WindowDump(wid, resp) => {
                    let json = crate::layout::dump_window_layout_json(&mut app, wid)
                        .unwrap_or_else(|_| "{}".to_string());
                    let _ = resp.send(json);
                }
                CtrlReq::ToggleSync => { app.sync_input = !app.sync_input; }
                CtrlReq::SetPaneTitle(title) => {
                    let win = &mut app.windows[app.active_idx];
                    if let Some(p) = active_pane_mut(&mut win.root, &win.active_path) {
                        p.title_locked = !title.is_empty();
                        p.title = title;
                    }
                    meta_dirty = true;
                }
                CtrlReq::SetPaneStyle(style) => {
                    // Per-pane styling (e.g. "bg=default,fg=blue") matching
                    // tmux's `-P` flag which sets window-style + window-active-style.
                    // Store on the pane for API compatibility; ConPTY rendering
                    // doesn't support per-pane fg/bg tinting yet.
                    let win = &mut app.windows[app.active_idx];
                    if let Some(p) = active_pane_mut(&mut win.root, &win.active_path) {
                        p.pane_style = Some(style);
                    }
                }
                CtrlReq::SendKeys(keys, literal) => {
                    let in_copy = matches!(app.mode, Mode::CopyMode | Mode::CopySearch { .. });
                    if in_copy {
                        // In copy/search mode — route through mode-aware handlers
                        if literal {
                            send_text_to_active(&mut app, &keys)?;
                        } else {
                            let parts: Vec<&str> = keys.split_whitespace().collect();
                            for key in parts.iter() {
                                let key_upper = key.to_uppercase();
                                let normalized = match key_upper.as_str() {
                                    "ENTER" => "enter",
                                    "TAB" => "tab",
                                    "BTAB" | "BACKTAB" => "btab",
                                    "ESCAPE" | "ESC" => "esc",
                                    "SPACE" => "space",
                                    "BSPACE" | "BACKSPACE" => "backspace",
                                    "UP" => "up",
                                    "DOWN" => "down",
                                    "RIGHT" => "right",
                                    "LEFT" => "left",
                                    "HOME" => "home",
                                    "END" => "end",
                                    "PAGEUP" | "PPAGE" => "pageup",
                                    "PAGEDOWN" | "NPAGE" => "pagedown",
                                    "DELETE" | "DC" => "delete",
                                    "INSERT" | "IC" => "insert",
                                    _ => "",
                                };
                                if !normalized.is_empty() {
                                    send_key_to_active(&mut app, normalized)?;
                                } else if key_upper.starts_with("C-") || key_upper.starts_with("M-") || (key_upper.starts_with("F") && key_upper.len() >= 2 && key_upper[1..].chars().all(|c| c.is_ascii_digit())) {
                                    send_key_to_active(&mut app, &key.to_lowercase())?;
                                } else {
                                    // Plain text char — route through send_text_to_active (handles copy mode chars)
                                    send_text_to_active(&mut app, key)?;
                                }
                            }
                        }
                    } else if literal {
                        send_text_to_active(&mut app, &keys)?;
                    } else {
                        let parts: Vec<&str> = keys.split_whitespace().collect();
                        for (i, key) in parts.iter().enumerate() {
                            let key_upper = key.to_uppercase();
                            let _is_special = matches!(key_upper.as_str(), 
                                "ENTER" | "TAB" | "BTAB" | "BACKTAB" | "ESCAPE" | "ESC" | "SPACE" | "BSPACE" | "BACKSPACE" |
                                "UP" | "DOWN" | "RIGHT" | "LEFT" | "HOME" | "END" |
                                "PAGEUP" | "PPAGE" | "PAGEDOWN" | "NPAGE" | "DELETE" | "DC" | "INSERT" | "IC" |
                                "F1" | "F2" | "F3" | "F4" | "F5" | "F6" | "F7" | "F8" | "F9" | "F10" | "F11" | "F12"
                            ) || key_upper.starts_with("C-") || key_upper.starts_with("M-") || key_upper.starts_with("S-");
                            
                            match key_upper.as_str() {
                                "ENTER" => send_text_to_active(&mut app, "\r")?,
                                "TAB" => send_text_to_active(&mut app, "\t")?,
                                "BTAB" | "BACKTAB" => send_text_to_active(&mut app, "\x1b[Z")?,
                                "ESCAPE" | "ESC" => send_text_to_active(&mut app, "\x1b")?,
                                "SPACE" => send_text_to_active(&mut app, " ")?,
                                "BSPACE" | "BACKSPACE" => send_text_to_active(&mut app, "\x7f")?,
                                "UP" => send_text_to_active(&mut app, "\x1b[A")?,
                                "DOWN" => send_text_to_active(&mut app, "\x1b[B")?,
                                "RIGHT" => send_text_to_active(&mut app, "\x1b[C")?,
                                "LEFT" => send_text_to_active(&mut app, "\x1b[D")?,
                                "HOME" => send_text_to_active(&mut app, "\x1b[H")?,
                                "END" => send_text_to_active(&mut app, "\x1b[F")?,
                                "PAGEUP" | "PPAGE" => send_text_to_active(&mut app, "\x1b[5~")?,
                                "PAGEDOWN" | "NPAGE" => send_text_to_active(&mut app, "\x1b[6~")?,
                                "DELETE" | "DC" => send_text_to_active(&mut app, "\x1b[3~")?,
                                "INSERT" | "IC" => send_text_to_active(&mut app, "\x1b[2~")?,
                                "F1" => send_text_to_active(&mut app, "\x1bOP")?,
                                "F2" => send_text_to_active(&mut app, "\x1bOQ")?,
                                "F3" => send_text_to_active(&mut app, "\x1bOR")?,
                                "F4" => send_text_to_active(&mut app, "\x1bOS")?,
                                "F5" => send_text_to_active(&mut app, "\x1b[15~")?,
                                "F6" => send_text_to_active(&mut app, "\x1b[17~")?,
                                "F7" => send_text_to_active(&mut app, "\x1b[18~")?,
                                "F8" => send_text_to_active(&mut app, "\x1b[19~")?,
                                "F9" => send_text_to_active(&mut app, "\x1b[20~")?,
                                "F10" => send_text_to_active(&mut app, "\x1b[21~")?,
                                "F11" => send_text_to_active(&mut app, "\x1b[23~")?,
                                "F12" => send_text_to_active(&mut app, "\x1b[24~")?,
                                // Modifier + special key combos (C-Left, S-Right, C-M-Up, etc.)
                                // must be checked BEFORE the generic C-x / M-x single-char handlers.
                                s if crate::input::parse_modified_special_key(s).is_some() => {
                                    let seq = crate::input::parse_modified_special_key(s).unwrap();
                                    send_text_to_active(&mut app, &seq)?;
                                }
                                s if s.starts_with("C-M-") || s.starts_with("C-m-") => {
                                    if let Some(c) = key.chars().nth(4) {
                                        if let Some(ctrl) = crate::input::ctrl_char_send_keys_byte(c) {
                                            send_text_to_active(&mut app, &format!("\x1b{}", ctrl as char))?;
                                        }
                                    }
                                }
                                s if s.starts_with("C-") => {
                                    if let Some(c) = s.chars().nth(2) {
                                        let Some(ctrl) = crate::input::ctrl_char_send_keys_byte(c) else { continue };
                                        // On Windows with Win32 input mode, write the key as
                                        // a Win32 input mode escape sequence so ConPTY generates
                                        // a proper KEY_EVENT with VK + LEFT_CTRL_PRESSED (#305).
                                        #[cfg(windows)]
                                        {
                                            if c.is_ascii_alphabetic() {
                                                // Keep Ctrl+C on the legacy interrupt path:
                                                // raw 0x03 + send_ctrl_c_event below.
                                                if ctrl == 0x03 {
                                                    send_text_to_active(&mut app, &String::from(ctrl as char))?;
                                                } else {
                                                    let vk = crate::platform::mouse_inject::char_to_vk(c);
                                                    let scan = crate::platform::mouse_inject::vk_to_scan(vk);
                                                    let u_char = (c.to_ascii_lowercase() as u16) & 0x1F;
                                                    const LEFT_CTRL_PRESSED: u32 = 0x0008;
                                                    let seq = format!(
                                                        "\x1b[{};{};{};1;{};1_\x1b[{};{};{};0;{};1_",
                                                        vk, scan, u_char, LEFT_CTRL_PRESSED,
                                                        vk, scan, u_char, LEFT_CTRL_PRESSED
                                                    );
                                                    send_text_to_active(&mut app, &seq)?;
                                                }
                                            } else {
                                                send_text_to_active(&mut app, &String::from(ctrl as char))?;
                                            }
                                        }
                                        #[cfg(not(windows))]
                                        send_text_to_active(&mut app, &String::from(ctrl as char))?;
                                        // On Windows, writing 0x03 to the PTY pipe doesn't
                                        // generate CTRL_C_EVENT when ENABLE_PROCESSED_INPUT
                                        // is disabled (e.g. after a TUI app).  Fire the real
                                        // signal via the platform helper so detached/headless
                                        // send-keys C-c reliably interrupts processes.
                                        #[cfg(windows)]
                                        if ctrl == 0x03 {
                                            if let Some(win) = app.windows.get_mut(app.active_idx) {
                                                if let Some(p) = active_pane_mut(&mut win.root, &win.active_path) {
                                                    if p.child_pid.is_none() {
                                                        p.child_pid = crate::platform::mouse_inject::get_child_pid(&*p.child);
                                                    }
                                                    if let Some(pid) = p.child_pid {
                                                        crate::platform::mouse_inject::send_ctrl_c_event(pid, false);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                s if s.starts_with("M-") => {
                                    if let Some(c) = key.chars().nth(2) {
                                        send_text_to_active(&mut app, &format!("\x1b{}", c))?;
                                    }
                                }
                                _ => {
                                    send_text_to_active(&mut app, key)?;
                                    if i + 1 < parts.len() {
                                        let next_upper = parts[i + 1].to_uppercase();
                                        let next_is_special = matches!(next_upper.as_str(),
                                            "ENTER" | "TAB" | "BTAB" | "BACKTAB" | "ESCAPE" | "ESC" | "SPACE" | "BSPACE" | "BACKSPACE" |
                                            "UP" | "DOWN" | "RIGHT" | "LEFT" | "HOME" | "END" |
                                            "PAGEUP" | "PPAGE" | "PAGEDOWN" | "NPAGE" | "DELETE" | "DC" | "INSERT" | "IC" |
                                            "F1" | "F2" | "F3" | "F4" | "F5" | "F6" | "F7" | "F8" | "F9" | "F10" | "F11" | "F12"
                                        ) || next_upper.starts_with("C-") || next_upper.starts_with("M-") || next_upper.starts_with("S-");
                                        if !next_is_special {
                                            send_text_to_active(&mut app, " ")?;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    echo_pending_until = Some(Instant::now());
                }
                CtrlReq::SendKeysX(cmd) => {
                    // send-keys -X: dispatch copy-mode commands by name
                    // This is the primary mechanism used by tmux-yank and other plugins
                    let in_copy = matches!(app.mode, Mode::CopyMode | Mode::CopySearch { .. });
                    if !in_copy {
                        // Auto-enter copy mode for commands that require it
                        enter_copy_mode(&mut app);
                    }
                    match cmd.as_str() {
                        "cancel" => {
                            app.mode = Mode::Passthrough;
                            app.copy_anchor = None;
                            app.copy_pos = None;
                            app.copy_scroll_offset = 0;
                            let win = &mut app.windows[app.active_idx];
                            if let Some(p) = active_pane_mut(&mut win.root, &win.active_path) {
                                if let Ok(mut parser) = p.term.lock() {
                                    parser.screen_mut().set_scrollback(0);
                                }
                            }
                            if let Some(cmds) = app.hooks.get("pane-mode-changed") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                        }
                        "begin-selection" => {
                            if let Some((r,c)) = crate::copy_mode::get_copy_pos(&mut app) {
                                app.copy_anchor = Some((r,c));
                                app.copy_anchor_scroll_offset = app.copy_scroll_offset;
                                app.copy_pos = Some((r,c));
                                app.copy_selection_mode = crate::types::SelectionMode::Char;
                            }
                        }
                        "select-line" => {
                            if let Some((r,c)) = crate::copy_mode::get_copy_pos(&mut app) {
                                app.copy_anchor = Some((r,c));
                                app.copy_anchor_scroll_offset = app.copy_scroll_offset;
                                app.copy_pos = Some((r,c));
                                app.copy_selection_mode = crate::types::SelectionMode::Line;
                            }
                        }
                        "rectangle-toggle" => {
                            app.copy_selection_mode = match app.copy_selection_mode {
                                crate::types::SelectionMode::Rect => crate::types::SelectionMode::Char,
                                _ => crate::types::SelectionMode::Rect,
                            };
                        }
                        "copy-selection" => {
                            let _ = yank_selection(&mut app);
                            if let Some(cmds) = app.hooks.get("pane-set-clipboard") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                        }
                        "copy-selection-and-cancel" => {
                            let _ = yank_selection(&mut app);
                            if let Some(cmds) = app.hooks.get("pane-set-clipboard") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                            app.mode = Mode::Passthrough;
                            app.copy_scroll_offset = 0;
                            app.copy_pos = None;
                            if let Some(cmds) = app.hooks.get("pane-mode-changed") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                        }
                        "copy-selection-no-clear" => {
                            let _ = yank_selection(&mut app);
                            if let Some(cmds) = app.hooks.get("pane-set-clipboard") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                        }
                        s if s.starts_with("copy-pipe-and-cancel") || s.starts_with("copy-pipe") => {
                            // copy-pipe[-and-cancel] [command] — yank + pipe to command
                            let _ = yank_selection(&mut app);
                            if let Some(cmds) = app.hooks.get("pane-set-clipboard") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                            // Extract pipe command from argument if present
                            let cancel = s.contains("cancel");
                            let pipe_cmd = cmd.strip_prefix("copy-pipe-and-cancel")
                                .or_else(|| cmd.strip_prefix("copy-pipe"))
                                .unwrap_or("")
                                .trim();
                            if !pipe_cmd.is_empty() {
                                if let Some(text) = app.paste_buffers.first().cloned() {
                                    // Pipe yanked text to the command's stdin
                                    let mut copy_pipe_cmd = std::process::Command::new(if cfg!(windows) { "pwsh" } else { "sh" });
                                    copy_pipe_cmd.args(if cfg!(windows) { vec!["-NoProfile", "-Command", pipe_cmd] } else { vec!["-c", pipe_cmd] })
                                        .stdin(std::process::Stdio::piped())
                                        .stdout(std::process::Stdio::null())
                                        .stderr(std::process::Stdio::null());
                                    { use crate::platform::HideWindowCommandExt; copy_pipe_cmd.hide_window(); }
                                    if let Ok(mut child) = copy_pipe_cmd.spawn() {
                                        if let Some(mut stdin) = child.stdin.take() {
                                            use std::io::Write;
                                            let _ = stdin.write_all(text.as_bytes());
                                        }
                                        let _ = child.wait();
                                    }
                                }
                            }
                            if cancel {
                                app.mode = Mode::Passthrough;
                                app.copy_scroll_offset = 0;
                                app.copy_pos = None;
                                if let Some(cmds) = app.hooks.get("pane-mode-changed") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                            }
                        }
                        "cursor-up" => { move_copy_cursor(&mut app, 0, -1); }
                        "cursor-down" => { move_copy_cursor(&mut app, 0, 1); }
                        "cursor-left" => { move_copy_cursor(&mut app, -1, 0); }
                        "cursor-right" => { move_copy_cursor(&mut app, 1, 0); }
                        "start-of-line" => { crate::copy_mode::move_to_line_start(&mut app); }
                        "end-of-line" => { crate::copy_mode::move_to_line_end(&mut app); }
                        "back-to-indentation" => { crate::copy_mode::move_to_first_nonblank(&mut app); }
                        "next-word" => { crate::copy_mode::move_word_forward(&mut app); }
                        "previous-word" => { crate::copy_mode::move_word_backward(&mut app); }
                        "next-word-end" => { crate::copy_mode::move_word_end(&mut app); }
                        "next-space" => { crate::copy_mode::move_word_forward_big(&mut app); }
                        "previous-space" => { crate::copy_mode::move_word_backward_big(&mut app); }
                        "next-space-end" => { crate::copy_mode::move_word_end_big(&mut app); }
                        "top-line" => { crate::copy_mode::move_to_screen_top(&mut app); }
                        "middle-line" => { crate::copy_mode::move_to_screen_middle(&mut app); }
                        "bottom-line" => { crate::copy_mode::move_to_screen_bottom(&mut app); }
                        "history-top" => { crate::copy_mode::scroll_to_top(&mut app); }
                        "history-bottom" => { crate::copy_mode::scroll_to_bottom(&mut app); }
                        "halfpage-up" => {
                            let half = app.windows.get(app.active_idx)
                                .and_then(|w| active_pane(&w.root, &w.active_path))
                                .map(|p| (p.last_rows / 2) as usize).unwrap_or(10);
                            scroll_copy_up(&mut app, half);
                        }
                        "halfpage-down" => {
                            let half = app.windows.get(app.active_idx)
                                .and_then(|w| active_pane(&w.root, &w.active_path))
                                .map(|p| (p.last_rows / 2) as usize).unwrap_or(10);
                            scroll_copy_down(&mut app, half);
                        }
                        "page-up" => { scroll_copy_up(&mut app, 20); }
                        "page-down" => { scroll_copy_down(&mut app, 20); }
                        "scroll-up" => { scroll_copy_up(&mut app, 1); }
                        "scroll-down" => { scroll_copy_down(&mut app, 1); }
                        "search-forward" | "search-forward-incremental" => {
                            app.mode = Mode::CopySearch { input: String::new(), forward: true };
                            let prompt = "(search down) ".to_string();
                            app.status_message = Some((prompt, std::time::Instant::now(), Some(0)));
                        }
                        "search-backward" | "search-backward-incremental" => {
                            app.mode = Mode::CopySearch { input: String::new(), forward: false };
                            let prompt = "(search up) ".to_string();
                            app.status_message = Some((prompt, std::time::Instant::now(), Some(0)));
                        }
                        "search-again" => { crate::copy_mode::search_next(&mut app); }
                        "search-reverse" => { crate::copy_mode::search_prev(&mut app); }
                        "copy-end-of-line" => { let _ = crate::copy_mode::copy_end_of_line(&mut app); app.mode = Mode::Passthrough; app.copy_scroll_offset = 0; app.copy_pos = None; }
                        "select-word" => {
                            // Select the word under cursor
                            crate::copy_mode::move_word_backward(&mut app);
                            if let Some((r,c)) = crate::copy_mode::get_copy_pos(&mut app) {
                                app.copy_anchor = Some((r,c));
                                app.copy_anchor_scroll_offset = app.copy_scroll_offset;
                                app.copy_selection_mode = crate::types::SelectionMode::Char;
                            }
                            crate::copy_mode::move_word_end(&mut app);
                        }
                        "other-end" => {
                            if let (Some(a), Some(p)) = (app.copy_anchor, app.copy_pos) {
                                app.copy_anchor = Some(p);
                                app.copy_anchor_scroll_offset = app.copy_scroll_offset;
                                app.copy_pos = Some(a);
                            }
                        }
                        "clear-selection" => {
                            app.copy_anchor = None;
                            app.copy_selection_mode = crate::types::SelectionMode::Char;
                        }
                        "append-selection" => {
                            // Append to existing buffer instead of replacing
                            let _ = yank_selection(&mut app);
                            if let Some(cmds) = app.hooks.get("pane-set-clipboard") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                            if app.paste_buffers.len() >= 2 {
                                let appended = format!("{}{}", app.paste_buffers[1], app.paste_buffers[0]);
                                app.paste_buffers[0] = appended;
                            }
                        }
                        "append-selection-and-cancel" => {
                            let _ = yank_selection(&mut app);
                            if let Some(cmds) = app.hooks.get("pane-set-clipboard") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                            if app.paste_buffers.len() >= 2 {
                                let appended = format!("{}{}", app.paste_buffers[1], app.paste_buffers[0]);
                                app.paste_buffers[0] = appended;
                            }
                            app.mode = Mode::Passthrough;
                            app.copy_scroll_offset = 0;
                            app.copy_pos = None;
                            if let Some(cmds) = app.hooks.get("pane-mode-changed") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                        }
                        "copy-line" => {
                            // Select entire current line and yank
                            if let Some((r, _)) = crate::copy_mode::get_copy_pos(&mut app) {
                                app.copy_anchor = Some((r, 0));
                                app.copy_anchor_scroll_offset = app.copy_scroll_offset;
                                app.copy_selection_mode = crate::types::SelectionMode::Line;
                                let cols = app.windows.get(app.active_idx)
                                    .and_then(|w| active_pane(&w.root, &w.active_path))
                                    .map(|p| p.last_cols).unwrap_or(80);
                                app.copy_pos = Some((r, cols.saturating_sub(1)));
                                let _ = yank_selection(&mut app);
                                if let Some(cmds) = app.hooks.get("pane-set-clipboard") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                            }
                            app.mode = Mode::Passthrough;
                            app.copy_scroll_offset = 0;
                            app.copy_pos = None;
                            if let Some(cmds) = app.hooks.get("pane-mode-changed") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                        }
                        s if s.starts_with("goto-line") => {
                            // goto-line <N> — jump to line N in scrollback
                            let n = s.strip_prefix("goto-line").unwrap_or("").trim()
                                .parse::<u16>().unwrap_or(0);
                            app.copy_pos = Some((n, 0));
                        }
                        "jump-forward" => { app.copy_find_char_pending = Some(0); }
                        "jump-backward" => { app.copy_find_char_pending = Some(1); }
                        "jump-to-forward" => { app.copy_find_char_pending = Some(2); }
                        "jump-to-backward" => { app.copy_find_char_pending = Some(3); }
                        "jump-again" => {
                            // Repeat last find-char in same direction
                            // We'd need to store last char; for now emit the pending
                        }
                        "jump-reverse" => {
                            // Repeat last find-char in reverse direction
                        }
                        "next-paragraph" => {
                            crate::copy_mode::move_next_paragraph(&mut app);
                        }
                        "previous-paragraph" => {
                            crate::copy_mode::move_prev_paragraph(&mut app);
                        }
                        "next-matching-bracket" => {
                            crate::copy_mode::move_matching_bracket(&mut app);
                        }
                        "stop-selection" => {
                            // Keep cursor position but stop extending selection
                            app.copy_anchor = None;
                        }
                        _ => {} // ignore unknown copy-mode commands
                    }
                }
                CtrlReq::SelectPane(dir, keep_zoom) => {
                    if let Some(cmds) = app.hooks.get("before-select-pane") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                    // Auto-unzoom when navigating to another pane (tmux behavior).
                    // For directional nav: unzoom first so compute_rects uses
                    // real geometry, then re-zoom only if focus didn't change.
                    // For other cases: only unzoom if focus actually changes.
                    // (fixes #46)
                    match dir.as_str() {
                        "U" | "D" | "L" | "R" => {
                            let focus_dir = match dir.as_str() {
                                "U" => FocusDir::Up, "D" => FocusDir::Down,
                                "L" => FocusDir::Left, _ => FocusDir::Right,
                            };
                            if keep_zoom {
                                let old_path = app.windows[app.active_idx].active_path.clone();
                                switch_with_copy_save(&mut app, |app| {
                                    move_focus_preserving_zoom(app, focus_dir);
                                });
                                if app.windows[app.active_idx].active_path != old_path {
                                    app.last_pane_path = old_path;
                                }
                            } else {
                                let was_zoomed = unzoom_if_zoomed(&mut app);
                                if was_zoomed {
                                // Zoom-aware: check direct neighbor or wrap target (tmux parity: unzoom+wrap).
                                let win = &app.windows[app.active_idx];
                                let mut rects: Vec<(Vec<usize>, ratatui::layout::Rect)> = Vec::new();
                                crate::tree::compute_rects(&win.root, app.last_window_area, &mut rects);
                                let active_idx = rects.iter().position(|(path, _)| *path == win.active_path);
                                let has_target = 
                                    if let Some(ai) = active_idx {
                                        let (_, arect) = &rects[ai];
                                        find_best_pane_in_direction(&rects, ai, arect, focus_dir, &[], &[])
                                            .or_else(|| find_wrap_target(&rects, ai, arect, focus_dir, &[], &[]))
                                            .is_some()
                                    } else { false };
                                    if has_target {
                                        let old_path = app.windows[app.active_idx].active_path.clone();
                                        switch_with_copy_save(&mut app, |app| {
                                            move_focus(app, focus_dir);
                                        });
                                        app.last_pane_path = old_path;
                                    } else {
                                        // No reachable pane (single-pane window) — re-zoom
                                        toggle_zoom(&mut app);
                                    }
                                } else {
                                    let old_path = app.windows[app.active_idx].active_path.clone();
                                    switch_with_copy_save(&mut app, |app| {
                                        move_focus(app, focus_dir);
                                    });
                                    if app.windows[app.active_idx].active_path != old_path {
                                        app.last_pane_path = old_path;
                                    }
                                }
                            }
                        }
                        "last" => {
                            // select-pane -l: switch to last active pane
                            let old_path = app.windows[app.active_idx].active_path.clone();
                            switch_with_copy_save(&mut app, |app| {
                                let win = &mut app.windows[app.active_idx];
                                if !app.last_pane_path.is_empty() {
                                    let tmp = win.active_path.clone();
                                    win.active_path = app.last_pane_path.clone();
                                    app.last_pane_path = tmp;
                                }
                            });
                            if app.windows[app.active_idx].active_path != old_path {
                                // Update MRU for the newly focused pane
                                let win = &mut app.windows[app.active_idx];
                                if let Some(pid) = get_active_pane_id(&win.root, &win.active_path) {
                                    crate::tree::touch_mru(&mut win.pane_mru, pid);
                                }
                                unzoom_if_zoomed(&mut app);
                            }
                        }
                        "mark" => {
                            // select-pane -m: mark the current pane
                            let win = &app.windows[app.active_idx];
                            if let Some(pid) = get_active_pane_id(&win.root, &win.active_path) {
                                app.marked_pane = Some((app.active_idx, pid));
                            }
                        }
                        "next" => {
                            // select-pane next: cycle to next pane (like Prefix+o / tmux -t :.+)
                            let old_path = app.windows[app.active_idx].active_path.clone();
                            switch_with_copy_save(&mut app, |app| {
                                let win = &app.windows[app.active_idx];
                                let mut pane_paths = Vec::new();
                                let mut path = Vec::new();
                                collect_pane_paths_server(&win.root, &mut path, &mut pane_paths);
                                if let Some(cur) = pane_paths.iter().position(|p| *p == win.active_path) {
                                    let next = (cur + 1) % pane_paths.len();
                                    let new_path = pane_paths[next].clone();
                                    let win = &mut app.windows[app.active_idx];
                                    app.last_pane_path = win.active_path.clone();
                                    win.active_path = new_path;
                                }
                            });
                            if app.windows[app.active_idx].active_path != old_path {
                                let win = &mut app.windows[app.active_idx];
                                if let Some(pid) = get_active_pane_id(&win.root, &win.active_path) {
                                    crate::tree::touch_mru(&mut win.pane_mru, pid);
                                }
                                unzoom_if_zoomed(&mut app);
                            }
                        }
                        "prev" => {
                            // select-pane prev: cycle to previous pane (tmux -t :.-)
                            let old_path = app.windows[app.active_idx].active_path.clone();
                            switch_with_copy_save(&mut app, |app| {
                                let win = &app.windows[app.active_idx];
                                let mut pane_paths = Vec::new();
                                let mut path = Vec::new();
                                collect_pane_paths_server(&win.root, &mut path, &mut pane_paths);
                                if let Some(cur) = pane_paths.iter().position(|p| *p == win.active_path) {
                                    let prev = (cur + pane_paths.len() - 1) % pane_paths.len();
                                    let new_path = pane_paths[prev].clone();
                                    let win = &mut app.windows[app.active_idx];
                                    app.last_pane_path = win.active_path.clone();
                                    win.active_path = new_path;
                                }
                            });
                            if app.windows[app.active_idx].active_path != old_path {
                                let win = &mut app.windows[app.active_idx];
                                if let Some(pid) = get_active_pane_id(&win.root, &win.active_path) {
                                    crate::tree::touch_mru(&mut win.pane_mru, pid);
                                }
                                unzoom_if_zoomed(&mut app);
                            }
                        }
                        "unmark" => {
                            // select-pane -M: clear the marked pane
                            app.marked_pane = None;
                        }
                        _ => {}
                    }
                    meta_dirty = true;
                    hook_event = Some("after-select-pane");
                }
                CtrlReq::SelectWindow(idx) => {
                    if let Some(cmds) = app.hooks.get("before-select-window") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                    if idx >= app.window_base_index {
                        let internal_idx = idx - app.window_base_index;
                        if internal_idx < app.windows.len() && internal_idx != app.active_idx {
                            switch_with_copy_save(&mut app, |app| {
                                app.last_window_idx = app.active_idx;
                                app.active_idx = internal_idx;
                            });
                            resize_all_panes(&mut app);
                        }
                    }
                    meta_dirty = true;
                    hook_event = Some("after-select-window");
                }
                CtrlReq::ListPanes(resp) => {
                    helpers::propagate_osc_titles(&mut app);
                    let mut output = String::new();
                    let win = &app.windows[app.active_idx];
                    fn collect_panes(node: &Node, panes: &mut Vec<(usize, u16, u16, vt100::MouseProtocolMode, vt100::MouseProtocolEncoding, bool)>) {
                        match node {
                            Node::Leaf(p) => {
                                let (mode, enc, alt) = match p.term.lock() {
                                    Ok(term) => {
                                        let screen = term.screen();
                                        (screen.mouse_protocol_mode(), screen.mouse_protocol_encoding(), screen.alternate_screen())
                                    }
                                    Err(_) => {
                                        // Mutex poisoned — reader thread panicked.  Use safe defaults.
                                        (vt100::MouseProtocolMode::None, vt100::MouseProtocolEncoding::Default, false)
                                    }
                                };
                                panes.push((p.id, p.last_cols, p.last_rows, mode, enc, alt));
                            }
                            Node::Split { children, .. } => {
                                for c in children { collect_panes(c, panes); }
                            }
                        }
                    }
                    let mut panes = Vec::new();
                    collect_panes(&win.root, &mut panes);
                    let active_pane_id = crate::tree::get_active_pane_id(&win.root, &win.active_path);
                    for (pos, (id, cols, rows, _mode, _enc, _alt)) in panes.iter().enumerate() {
                        let idx = pos + app.pane_base_index;
                        let active_marker = if active_pane_id == Some(*id) { " (active)" } else { "" };
                        output.push_str(&format!("{}: [{}x{}] [history {}/{}, 0 bytes] %{}{}\n", idx, cols, rows, app.history_limit, app.history_limit, id, active_marker));
                    }
                    let _ = resp.send(output);
                }
                CtrlReq::ListPanesFormat(resp, fmt) => {
                    helpers::propagate_osc_titles(&mut app);
                    let text = format_list_panes(&app, &fmt, app.active_idx);
                    let _ = resp.send(text);
                }
                CtrlReq::ListAllPanes(resp) => {
                    let mut output = String::new();
                    fn collect_all_panes(node: &Node, panes: &mut Vec<(usize, u16, u16)>) {
                        match node {
                            Node::Leaf(p) => { panes.push((p.id, p.last_cols, p.last_rows)); }
                            Node::Split { children, .. } => { for c in children { collect_all_panes(c, panes); } }
                        }
                    }
                    for (wi, win) in app.windows.iter().enumerate() {
                        let mut panes = Vec::new();
                        collect_all_panes(&win.root, &mut panes);
                        for (id, cols, rows) in panes {
                            output.push_str(&format!("{}:{}: %{} [{}x{}]\n", app.session_name, wi + app.window_base_index, id, cols, rows));
                        }
                    }
                    let _ = resp.send(output);
                }
                CtrlReq::ListAllPanesFormat(resp, fmt) => {
                    let mut lines = Vec::new();
                    for wi in 0..app.windows.len() {
                        lines.push(format_list_panes(&app, &fmt, wi));
                    }
                    let _ = resp.send(lines.join("\n"));
                }
                CtrlReq::KillWindow => {
                    if app.windows.len() > 1 {
                        let mut win = app.windows.remove(app.active_idx);
                        kill_all_children(&mut win.root);
                        if app.active_idx >= app.windows.len() { app.active_idx = app.windows.len() - 1; }
                    } else {
                        // Last window: kill all children; reaper will detect empty session and exit
                        kill_all_children(&mut app.windows[0].root);
                    }
                    // Killing a window changes the active window and the window
                    // list, so resize the now-active window's panes and force a
                    // status-bar/window-list rebuild + push to attached clients.
                    // Without meta_dirty the cached window tabs stay stale and
                    // without state_dirty the no-change fast path skips the frame,
                    // leaving the bottom bar showing the killed window until the
                    // next input (issue #359). Mirrors every other structural
                    // mutation (new-window, kill-pane, select-window) and tmux's
                    // server_kill_window -> server_redraw_session_group.
                    resize_all_panes(&mut app);
                    meta_dirty = true;
                    state_dirty = true;
                    hook_event = Some("window-closed");
                }
                CtrlReq::KillSession => {
                    // Fire session-closed hook before cleanup
                    if let Some(cmds) = app.hooks.get("session-closed") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                    // Remove port/key/sid files FIRST so clients see the session
                    // as gone immediately, then kill processes.
                    let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
                    let regpath = format!("{}\\.psmux\\{}.port", home, app.port_file_base());
                    let keypath = format!("{}\\.psmux\\{}.key", home, app.port_file_base());
                    let _ = std::fs::remove_file(&regpath);
                    let _ = std::fs::remove_file(&keypath);
                    crate::session::remove_session_id_file(&app.port_file_base());
                    crate::types::send_directive_to_all_clients("DETACH");
                    std::thread::sleep(Duration::from_millis(50));
                    crate::types::shutdown_persistent_streams();
                    // Kill all child processes using a single process snapshot
                    tree::kill_all_children_batch(&mut app.windows);
                    // Kill warm pane's child (process::exit skips Drop)
                    if let Some(mut wp) = app.warm_pane.take() { wp.child.kill().ok(); }
                    // TerminateProcess is synchronous on Windows — processes
                    // are already dead.  Minimal delay for OS handle cleanup.
                    std::thread::sleep(std::time::Duration::from_millis(10));
                    std::process::exit(0);
                }
                CtrlReq::HasSession(resp) => {
                    let _ = resp.send(true);
                }
                CtrlReq::RenameSession(name) => {
                    if let Some(cmds) = app.hooks.get("before-rename-session") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                    let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
                    let old_path = format!("{}\\.psmux\\{}.port", home, app.port_file_base());
                    let old_keypath = format!("{}\\.psmux\\{}.key", home, app.port_file_base());
                    // Compute new port file base with socket_name prefix
                    let new_base = if let Some(ref sn) = app.socket_name {
                        format!("{}__{}" , sn, name)
                    } else {
                        name.clone()
                    };
                    let new_path = format!("{}\\.psmux\\{}.port", home, new_base);
                    let new_keypath = format!("{}\\.psmux\\{}.key", home, new_base);
                    if let Some(port) = app.control_port {
                        let _ = std::fs::remove_file(&old_path);
                        let _ = std::fs::write(&new_path, port.to_string());
                        // Write this server's OWN in-memory key, NOT a copy of the
                        // old .key file. Under warm-server replenish churn the
                        // __warm__.key file may have been overwritten by a LATER warm
                        // server, so copying it would give the renamed/claimed session
                        // a key that does not match this server (seen as "Invalid
                        // session key" on a later command). app.session_key is correct.
                        let _ = std::fs::remove_file(&old_keypath);
                        let _ = std::fs::write(&new_keypath, &app.session_key);
                        // Rename .sid file to match new session name
                        crate::session::remove_session_id_file(&app.port_file_base());
                        crate::session::write_session_id_file(&new_base, app.session_id);
                    }
                    app.session_name = name;
                    // Update env so run-shell/hooks from this server target the new name
                    env::set_var("PSMUX_TARGET_SESSION", app.port_file_base());
                    hook_event = Some("after-rename-session");
                }
                CtrlReq::ClaimSession(name, client_cwd, resp) => {
                    // Guard against clobbering an already-claimed session. Under
                    // rapid `new-session`, a stale __warm__.port (or OS ephemeral
                    // port reuse) can route a claim to a server that has ALREADY
                    // been claimed — its session_name is no longer "__warm__".
                    // Renaming it again would rename the live session away and
                    // destroy it (observed as rapid new-session intermittently
                    // losing 1-4 of N sessions ~2s after creation). Refuse the
                    // claim so the CLI falls back to a cold-spawn, which is the
                    // reliable path. Only a genuine warm server may be claimed.
                    if app.session_name != "__warm__" {
                        warm_debug(&format!("CLAIM REFUSED: this server is '{}' (port={:?}), requested name='{}'", app.session_name, app.control_port, name));
                        let _ = resp.send("ERR: not a warm server (already claimed)\n".to_string());
                    } else {
                    warm_debug(&format!("CLAIM ACCEPT: __warm__ (port={:?}) -> '{}'", app.control_port, name));
                    // Same as RenameSession but with a synchronous response
                    // so the CLI knows the rename completed before attaching.
                    let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
                    let old_path = format!("{}\\.psmux\\{}.port", home, app.port_file_base());
                    let old_keypath = format!("{}\\.psmux\\{}.key", home, app.port_file_base());
                    let new_base = if let Some(ref sn) = app.socket_name {
                        format!("{}__{}" , sn, name)
                    } else {
                        name.clone()
                    };
                    let new_path = format!("{}\\.psmux\\{}.port", home, new_base);
                    let new_keypath = format!("{}\\.psmux\\{}.key", home, new_base);
                    if let Some(port) = app.control_port {
                        let _ = std::fs::remove_file(&old_path);
                        let _ = std::fs::write(&new_path, port.to_string());
                        // Write this server's OWN in-memory key, NOT a copy of the
                        // old .key file. Under warm-server replenish churn the
                        // __warm__.key file may have been overwritten by a LATER warm
                        // server, so copying it would give the renamed/claimed session
                        // a key that does not match this server (seen as "Invalid
                        // session key" on a later command). app.session_key is correct.
                        let _ = std::fs::remove_file(&old_keypath);
                        let _ = std::fs::write(&new_keypath, &app.session_key);
                        // Rename .sid file to match new session name
                        crate::session::remove_session_id_file(&app.port_file_base());
                        crate::session::write_session_id_file(&new_base, app.session_id);
                    }
                    app.session_name = name;
                    // Warm server's created_at is the warm process start time, not the
                    // user's session-creation time — reset on claim or list-sessions /
                    // session_created / uptime would report the warm pool's age.
                    app.created_at = chrono::Local::now();
                    // Update env so run-shell/hooks from this server target the new name
                    env::set_var("PSMUX_TARGET_SESSION", app.port_file_base());
                    // Honour the client's working directory: the warm server
                    // was spawned from a previous session whose CWD may differ
                    // from where the user ran `psmux` now.  Update the
                    // server's CWD (for future pane spawns) and silently
                    // inject `cd` into the active pane so the shell starts
                    // in the right directory.  A clear screen command is
                    // chained after cd so the user never sees the injected
                    // command or its echo.
                    if let Some(ref cwd) = client_cwd {
                        let cwd_path = std::path::Path::new(cwd);
                        if cwd_path.is_dir() {
                            let server_cwd_differs = env::current_dir()
                                .map(|cur| cur != cwd_path)
                                .unwrap_or(true);
                            if server_cwd_differs {
                                env::set_current_dir(cwd_path).ok();
                                // Inject cd + clear into the active pane so
                                // the directory change is invisible to the
                                // user.  Leading space keeps it out of shell
                                // history; the clear wipes visible traces.
                                //
                                // The vt100 parser watches for the CSI 2J
                                // that cls/clear generates, which tells the
                                // layout serialiser the clear finished
                                // (event-driven, no guessing).  A safety
                                // timeout is a fallback for unusual shells.
                                if let Some(win) = app.windows.last_mut() {
                                    if let Some(p) = active_pane_mut(&mut win.root, &win.active_path) {
                                        use std::io::Write as _;
                                        let escaped = cwd.replace('\'', "''");
                                        let clear = if cfg!(windows) { "cls" } else { "clear" };
                                        let cd_cmd = format!(" cd '{}'; {}\r", escaped, clear);
                                        // Tell the vt100 parser to watch for the
                                        // next screen-clear event (CSI 2J/3J).
                                        if let Ok(mut parser) = p.term.lock() {
                                            parser.screen_mut().set_squelch_clear_pending(true);
                                        }
                                        p.squelch_until = Some(Instant::now() + Duration::from_millis(500));
                                        let _ = p.writer.write_all(cd_cmd.as_bytes());
                                        let _ = p.writer.flush();
                                    }
                                }
                            }
                        }
                    }
                    // Update env so run-shell/hooks from this server target the new name
                    env::set_var("PSMUX_TARGET_SESSION", app.port_file_base());
                    // Re-load user config so the claimed session reflects the
                    // current config file.  The warm server loaded config at
                    // its own startup, but the user may have changed their
                    // config since then (or the warm server was spawned by a
                    // different session with a different PSMUX_CONFIG_FILE).
                    app.key_tables.clear();
                    app.defaults_suppressed = false;
                    crate::config::populate_default_bindings(&mut app);
                    load_config(&mut app);
                    // Surface config warnings to the claiming client (#370 follow-up).
                    write_config_warnings_log(&app.config_warnings);
                    // Config may set pane-border-status (#288)
                    resize_all_panes(&mut app);
                    // Update shared aliases after config reload
                    if let Ok(mut w) = shared_aliases_main.write() {
                        *w = app.command_aliases.clone();
                    }
                    // Fire client-session-changed hook (warm server claimed by new session)
                    if let Some(cmds) = app.hooks.get("client-session-changed") { let cmds = cmds.clone(); for cmd in &cmds { let _ = execute_command_string(&mut app, cmd); } }
                    meta_dirty = true;
                    state_dirty = true;
                    let _ = resp.send("OK\n".to_string());
                    // Spawn a replacement warm server for the NEXT new-session
                    spawn_warm_server(&app);
                    hook_event = Some("after-rename-session");
                    }
                }
                CtrlReq::SwapPane(dir) => {
                    // tmux: swap-pane without -Z permanently unzooms (#82)
                    unzoom_if_zoomed(&mut app);
                    match dir.as_str() {
                        "U" => { swap_pane(&mut app, FocusDir::Up); }
                        "D" => { swap_pane(&mut app, FocusDir::Down); }
                        _ => { swap_pane(&mut app, FocusDir::Down); }
                    }
                    hook_event = Some("after-swap-pane");
                }
                CtrlReq::ResizePane(dir, amount) => {
                    unzoom_if_zoomed(&mut app);
                    match dir.as_str() {
                        "U" | "D" => { resize_pane_vertical(&mut app, if dir == "U" { -(amount as i16) } else { amount as i16 }); }
                        "L" | "R" => { resize_pane_horizontal(&mut app, if dir == "L" { -(amount as i16) } else { amount as i16 }); }
                        _ => {}
                    }
                    resize_all_panes(&mut app); meta_dirty = true;
                    hook_event = Some("after-resize-pane");
                }
                CtrlReq::SetBuffer(content) => {
                    app.paste_buffers.insert(0, content);
                    if app.paste_buffers.len() > 10 { app.paste_buffers.pop(); }
                }
                CtrlReq::SetNamedBuffer(name, content) => {
                    app.named_buffers.insert(name, content);
                }
                CtrlReq::ListBuffers(resp) => {
                    let mut output = String::new();
                    // List auto-named buffers (positional stack)
                    for (i, buf) in app.paste_buffers.iter().enumerate() {
                        let preview: String = buf.chars().take(50).collect();
                        output.push_str(&format!("buffer{}: {} bytes: \"{}\"\n", i, buf.len(), preview));
                    }
                    // List named buffers
                    let mut names: Vec<&String> = app.named_buffers.keys().collect();
                    names.sort();
                    for name in names {
                        let buf = &app.named_buffers[name];
                        let preview: String = buf.chars().take(50).collect();
                        output.push_str(&format!("{}: {} bytes: \"{}\"\n", name, buf.len(), preview));
                    }
                    let _ = resp.send(output);
                }
                CtrlReq::ListBuffersFormat(resp, fmt) => {
                    let mut output = Vec::new();
                    for (i, _buf) in app.paste_buffers.iter().enumerate() {
                        set_buffer_idx_override(Some(i));
                        output.push(expand_format(&fmt, &app));
                        set_buffer_idx_override(None);
                    }
                    // Named buffers with format: use name override
                    let mut names: Vec<String> = app.named_buffers.keys().cloned().collect();
                    names.sort();
                    for name in &names {
                        set_named_buffer_override(Some(name.clone()));
                        output.push(expand_format(&fmt, &app));
                        set_named_buffer_override(None);
                    }
                    let _ = resp.send(output.join("\n"));
                }
                CtrlReq::ShowBuffer(resp) => {
                    let content = app.paste_buffers.first().cloned().unwrap_or_default();
                    let _ = resp.send(content);
                }
                CtrlReq::ShowBufferAt(resp, idx) => {
                    let content = app.paste_buffers.get(idx).cloned().unwrap_or_default();
                    let _ = resp.send(content);
                }
                CtrlReq::ShowNamedBuffer(resp, name) => {
                    let content = app.named_buffers.get(&name).cloned().unwrap_or_default();
                    let _ = resp.send(content);
                }
                CtrlReq::DeleteBuffer => {
                    if !app.paste_buffers.is_empty() { app.paste_buffers.remove(0); }
                }
                CtrlReq::DeleteBufferAt(idx) => {
                    if idx < app.paste_buffers.len() { app.paste_buffers.remove(idx); }
                }
                CtrlReq::DeleteNamedBuffer(name) => {
                    app.named_buffers.remove(&name);
                }
                CtrlReq::PasteBufferAt(idx) => {
                    if idx < app.paste_buffers.len() {
                        let text = app.paste_buffers[idx].clone();
                        let win = &mut app.windows[app.active_idx];
                        if let Some(p) = crate::tree::active_pane_mut(&mut win.root, &win.active_path) {
                            let _ = write!(p.writer, "{}", text);
                        }
                    }
                }
                CtrlReq::DisplayMessage(resp, fmt, target_pane_idx, set_status_bar, duration_ms) => {
                    // Propagate OSC titles so #{pane_title} reflects latest state
                    helpers::propagate_osc_titles(&mut app);
                    let result = if let Some(pane_idx) = target_pane_idx {
                        // -t targeting: evaluate format for the specific pane
                        // using PANE_POS_OVERRIDE so #{pane_active} reflects
                        // the REAL active pane, not the target (#113)
                        crate::format::expand_format_for_pane(&fmt, &app, app.active_idx, pane_idx)
                    } else {
                        expand_format(&fmt, &app)
                    };
                    if set_status_bar {
                        app.status_message = Some((result.clone(), Instant::now(), duration_ms));
                        state_dirty = true;
                    }
                    let _ = resp.send(result);
                }
                CtrlReq::DisplayMessageById(resp, fmt, pane_id, set_status_bar, duration_ms) => {
                    // Bare %N pane targeting (#332) — resolve the pane ID
                    // globally across all windows and expand the format with
                    // PANE_POS_OVERRIDE pointing at it.
                    helpers::propagate_osc_titles(&mut app);
                    let result = crate::format::expand_format_for_pane_by_id(&fmt, &app, pane_id);
                    if set_status_bar {
                        app.status_message = Some((result.clone(), Instant::now(), duration_ms));
                        state_dirty = true;
                    }
                    let _ = resp.send(result);
                }
                CtrlReq::LastWindow => {
                    if app.windows.len() > 1 && app.last_window_idx < app.windows.len() {
                        switch_with_copy_save(&mut app, |app| {
                            let tmp = app.active_idx;
                            app.active_idx = app.last_window_idx;
                            app.last_window_idx = tmp;
                        });
                    }
                    meta_dirty = true;
                    hook_event = Some("after-select-window");
                }
                CtrlReq::LastPane => {
                    switch_with_copy_save(&mut app, |app| {
                        let win = &mut app.windows[app.active_idx];
                        if !app.last_pane_path.is_empty() && path_exists(&win.root, &app.last_pane_path) {
                            let tmp = win.active_path.clone();
                            win.active_path = app.last_pane_path.clone();
                            app.last_pane_path = tmp;
                        } else if !win.active_path.is_empty() {
                            let last = win.active_path.last_mut();
                            if let Some(idx) = last {
                                *idx = (*idx + 1) % 2;
                            }
                        }
                    });
                    meta_dirty = true;
                }
                CtrlReq::RotateWindow(reverse) => {
                    rotate_panes(&mut app, reverse);
                    hook_event = Some("after-rotate-window");
                }
                CtrlReq::DisplayPanes => {
                    app.mode = Mode::PaneChooser { opened_at: std::time::Instant::now() };
                    state_dirty = true;
                }
                CtrlReq::DisplayPaneSelect(digit) => {
                    // User pressed a digit during display-panes overlay: select the matching pane
                    let win = &app.windows[app.active_idx];
                    let mut rects: Vec<(Vec<usize>, ratatui::layout::Rect)> = Vec::new();
                    crate::tree::compute_rects(&win.root, app.last_window_area, &mut rects);
                    for (i, (path, _)) in rects.iter().enumerate() {
                        if i >= 10 { break; }
                        let mapped = (i + app.pane_base_index) % 10;
                        if mapped == digit {
                            let new_path = path.clone();
                            let old_path = app.windows[app.active_idx].active_path.clone();
                            app.windows[app.active_idx].active_path = new_path;
                            if app.windows[app.active_idx].active_path != old_path {
                                app.last_pane_path = old_path;
                            }
                            break;
                        }
                    }
                    app.mode = Mode::Passthrough;
                    state_dirty = true;
                    meta_dirty = true;
                }
                CtrlReq::BreakPane => {
                    unzoom_if_zoomed(&mut app);
                    break_pane_to_window(&mut app);
                    hook_event = Some("after-break-pane");
                    meta_dirty = true;
                }
                CtrlReq::JoinPane { src_win, src_pane, target_win, target_pane, horizontal }
                | CtrlReq::MovePane { src_win, src_pane, target_win, target_pane, horizontal } => {
                    unzoom_if_zoomed(&mut app);
                    // Resolve source window index (default: active window)
                    let src_idx = src_win.unwrap_or(app.active_idx);
                    // Resolve target window index (default: active window, but must differ from source)
                    let raw_target_win = target_win.unwrap_or(app.active_idx);
                    if src_idx < app.windows.len() && raw_target_win < app.windows.len() && src_idx != raw_target_win {
                        // Resolve source pane path within source window
                        let src_path = if let Some(pidx) = src_pane {
                            // Get Nth pane path in DFS order
                            let mut leaves = Vec::new();
                            tree::collect_leaf_paths_pub(&app.windows[src_idx].root, &mut Vec::new(), &mut leaves);
                            if let Some((_, p)) = leaves.get(pidx) {
                                p.clone()
                            } else {
                                app.windows[src_idx].active_path.clone()
                            }
                        } else {
                            app.windows[src_idx].active_path.clone()
                        };
                        // Unzoom source window if needed
                        if let Some(saved) = app.windows[src_idx].zoom_saved.take() {
                            let win = &mut app.windows[src_idx];
                            for (p, sz) in saved.into_iter() {
                                if let Some(Node::Split { sizes, .. }) = crate::tree::get_split_mut(&mut win.root, &p) { *sizes = sz; }
                            }
                        }
                        let src_root = std::mem::replace(&mut app.windows[src_idx].root,
                            Node::Split { kind: LayoutKind::Horizontal, sizes: vec![], children: vec![] });
                        let (remaining, extracted) = tree::extract_node(src_root, &src_path);
                        if let Some(pane_node) = extracted {
                            let src_empty = remaining.is_none();
                            if let Some(rem) = remaining {
                                app.windows[src_idx].root = rem;
                                app.windows[src_idx].active_path = tree::first_leaf_path(&app.windows[src_idx].root);
                            }
                            // Adjust target index if source window will be removed and target is after it
                            let tgt = if src_empty && raw_target_win > src_idx { raw_target_win - 1 } else { raw_target_win };
                            if src_empty {
                                app.windows.remove(src_idx);
                                if app.active_idx >= app.windows.len() {
                                    app.active_idx = app.windows.len().saturating_sub(1);
                                }
                            }
                            // Graft pane into target window
                            if tgt < app.windows.len() {
                                // Resolve target pane path
                                let tgt_path = if let Some(tpidx) = target_pane {
                                    let mut leaves = Vec::new();
                                    tree::collect_leaf_paths_pub(&app.windows[tgt].root, &mut Vec::new(), &mut leaves);
                                    if let Some((_, p)) = leaves.get(tpidx) {
                                        p.clone()
                                    } else {
                                        app.windows[tgt].active_path.clone()
                                    }
                                } else {
                                    app.windows[tgt].active_path.clone()
                                };
                                let split_kind = if horizontal { LayoutKind::Horizontal } else { LayoutKind::Vertical };
                                tree::replace_leaf_with_split(&mut app.windows[tgt].root, &tgt_path, split_kind, pane_node);
                                app.active_idx = tgt;
                            }
                            resize_all_panes(&mut app);
                            meta_dirty = true;
                            hook_event = Some("after-join-pane");
                        } else {
                            // Extraction failed — restore
                            if let Some(rem) = remaining {
                                app.windows[src_idx].root = rem;
                            }
                        }
                    }
                }
                // ── Cross-session pane forwarding ───────────────────────
                CtrlReq::PaneForwardExtract(win_idx, pane_idx, resp) => {
                    crate::cross_session_server::handle_pane_forward_extract(&mut app, win_idx, pane_idx, resp);
                    resize_all_panes(&mut app);
                    meta_dirty = true;
                }
                CtrlReq::PaneForwardInject {
                    source_session, source_addr, source_key,
                    forward_id, fwd_port, pid, title, rows, cols,
                    screen_b64, target_win, target_pane, horizontal,
                } => {
                    crate::cross_session_server::handle_pane_forward_inject(
                        &mut app, source_session, source_addr, source_key,
                        forward_id, fwd_port, pid, title, rows, cols,
                        screen_b64, target_win, target_pane, horizontal,
                    );
                    resize_all_panes(&mut app);
                    meta_dirty = true;
                    hook_event = Some("after-join-pane");
                }
                CtrlReq::PaneForwardResize(fwd_id, fwd_rows, fwd_cols) => {
                    if let Some(fp) = app.forwarded_panes.get(&fwd_id) {
                        let _ = fp.master.resize(portable_pty::PtySize {
                            rows: fwd_rows, cols: fwd_cols, pixel_width: 0, pixel_height: 0,
                        });
                    }
                }
                CtrlReq::PaneForwardStatus(fwd_id, resp) => {
                    let status = if let Some(fp) = app.forwarded_panes.get_mut(&fwd_id) {
                        match fp.child.try_wait() {
                            Ok(Some(_)) => "exited".to_string(),
                            Ok(None) => "running".to_string(),
                            Err(_) => "exited".to_string(),
                        }
                    } else {
                        "exited".to_string()
                    };
                    let _ = resp.send(status);
                }
                CtrlReq::PaneForwardKill(fwd_id) => {
                    if let Some(mut fp) = app.forwarded_panes.remove(&fwd_id) {
                        fp.shutdown.store(true, std::sync::atomic::Ordering::Relaxed);
                        let _ = fp.child.kill();
                    }
                }
                CtrlReq::RespawnPane(workdir, kill) => {
                    respawn_active_pane(&mut app, Some(&*pty_system), workdir.as_deref(), kill)?;
                    hook_event = Some("after-respawn-pane");
                }
                CtrlReq::BindKey(table_name, key, command, repeat) => {
                    if let Some(kc) = parse_key_string(&key) {
                        let kc = normalize_key_for_binding(kc);
                        // Support `\;` chaining in server-side bind-key
                        let sub_cmds = crate::config::split_chained_commands_pub(&command);
                        let action = if sub_cmds.len() > 1 {
                            Some(Action::CommandChain(sub_cmds))
                        } else {
                            parse_command_to_action(&command)
                        };
                        if let Some(act) = action {
                            let table = app.key_tables.entry(table_name).or_default();
                            table.retain(|b| b.key != kc);
                            table.push(Bind { key: kc, action: act, repeat });
                        }
                    }
                    meta_dirty = true;
                    state_dirty = true;
                }
                CtrlReq::UnbindKey(key, table) => {
                    if let Some(kc) = parse_key_string(&key) {
                        let kc = normalize_key_for_binding(kc);
                        let target = table.unwrap_or_else(|| "prefix".to_string());
                        if let Some(binds) = app.key_tables.get_mut(&target) {
                            binds.retain(|b| b.key != kc);
                        }
                    }
                    meta_dirty = true;
                    state_dirty = true;
                }
                CtrlReq::UnbindAll => {
                    app.key_tables.clear();
                    app.defaults_suppressed = true;
                    meta_dirty = true;
                    state_dirty = true;
                }
                CtrlReq::UnbindAllInTable(table) => {
                    if let Some(binds) = app.key_tables.get_mut(&table) {
                        binds.clear();
                    }
                    meta_dirty = true;
                    state_dirty = true;
                }
                CtrlReq::ListKeys(resp) => {
                    // Build list-keys output from the canonical help module
                    let user_iter = app.key_tables.iter().flat_map(|(table_name, binds)| {
                        binds.iter().map(move |bind| {
                            let key_str = format_key_binding(&bind.key);
                            let action_str = format_action(&bind.action);
                            (table_name.as_str(), key_str, action_str, bind.repeat)
                        })
                    });
                    let output = help::build_list_keys_output(user_iter, app.defaults_suppressed);
                    let _ = resp.send(output);
                }
                CtrlReq::SetOption(option, value) => {
                    apply_set_option(&mut app, &option, &value, false);
                    app.user_set_options.insert(option.clone());
                    // Reconcile the warm pane with the new option value.
                    // All option-driven warm-pane lifecycle decisions
                    // route through this single module — see #271.
                    let sync = crate::warm_pane_sync::for_option_change(&option, &app);
                    crate::warm_pane_sync::apply(&mut app, &*pty_system, sync);
                    // Update shared aliases if command-alias changed
                    if option == "command-alias" {
                        if let Ok(mut map) = shared_aliases_main.write() {
                            *map = app.command_aliases.clone();
                        }
                    }
                    // pane-border-status changes the effective content height (#288)
                    if option == "pane-border-status" {
                        resize_all_panes(&mut app);
                    }
                    meta_dirty = true;
                    state_dirty = true;
                }
                CtrlReq::SetOptionQuiet(option, value, quiet) => {
                    apply_set_option(&mut app, &option, &value, quiet);
                    app.user_set_options.insert(option.clone());
                    // Reconcile the warm pane with the new option value.
                    // Replaces the prior inline default-shell-only kill
                    // (#99) with a uniform table-driven policy that
                    // also covers history-limit (#271), allow-predictions,
                    // default-terminal, and claude-code-* options.
                    let sync = crate::warm_pane_sync::for_option_change(&option, &app);
                    crate::warm_pane_sync::apply(&mut app, &*pty_system, sync);
                    // Update shared aliases if command-alias changed
                    if option == "command-alias" {
                        if let Ok(mut map) = shared_aliases_main.write() {
                            *map = app.command_aliases.clone();
                        }
                    }
                    // pane-border-status changes the effective content height (#288)
                    if option == "pane-border-status" {
                        resize_all_panes(&mut app);
                    }
                    meta_dirty = true;
                    state_dirty = true;
                }
                CtrlReq::SetOptionUnset(option) => {
                    // Reset option to default or remove @user-option
                    if option.starts_with('@') {
                        app.user_options.remove(&option);
                    } else {
                        match option.as_str() {
                            "status-left" => { app.status_left = "psmux:#I".to_string(); }
                            "status-right" => { app.status_right = "#{?window_bigger,[#{window_offset_x}#,#{window_offset_y}] ,}\"#{=21:pane_title}\" %H:%M %d-%b-%y".to_string(); }
                            "mouse" => { app.mouse_enabled = true; }
                            "scroll-enter-copy-mode" => { app.scroll_enter_copy_mode = true; }
                            "pwsh-mouse-selection" => { app.pwsh_mouse_selection = false; }
                            "mouse-selection" => { app.mouse_selection = true; }
                            "paste-detection" => { app.paste_detection = true; }
                            "choose-tree-preview" => { app.choose_tree_preview = false; }
                            "escape-time" => { app.escape_time_ms = 500; }
                            "history-limit" => { app.history_limit = 2000; }
                            "alternate-screen" => { app.allow_alternate_screen = true; }
                            "display-time" => { app.display_time_ms = 750; }
                            "mode-keys" => { app.mode_keys = "emacs".to_string(); }
                            "status" => { app.status_visible = true; }
                            "status-position" => { app.status_position = "bottom".to_string(); }
                            "status-style" => { app.status_style = String::new(); }
                            "renumber-windows" => { app.renumber_windows = false; }
                            "remain-on-exit" => { app.remain_on_exit = false; }
                            "destroy-unattached" => { app.destroy_unattached = false; }
                            "exit-empty" => { app.exit_empty = true; }
                            "automatic-rename" => { app.automatic_rename = true; }
                            "pane-border-style" => { app.pane_border_style = String::new(); }
                            "pane-active-border-style" => { app.pane_active_border_style = "fg=green".to_string(); }
                            "pane-border-hover-style" => { app.pane_border_hover_style = "fg=yellow".to_string(); }
                            "window-status-format" => { app.window_status_format = "#I:#W#{?window_flags,#{window_flags}, }".to_string(); }
                            "window-status-current-format" => { app.window_status_current_format = "#I:#W#{?window_flags,#{window_flags}, }".to_string(); }
                            "window-status-separator" => { app.window_status_separator = " ".to_string(); }
                            "cursor-style" => { std::env::set_var("PSMUX_CURSOR_STYLE", "bar"); }
                            "cursor-blink" => { std::env::set_var("PSMUX_CURSOR_BLINK", "1"); }
                            _ => {}
                        }
                    }
                }
                CtrlReq::SetOptionAppend(option, value) => {
                    // Append to existing option value
                    if option.starts_with('@') {
                        let existing = app.user_options.get(&option).cloned().unwrap_or_default();
                        app.user_options.insert(option, format!("{}{}", existing, value));
                    } else {
                        match option.as_str() {
                            "status-left" => { app.status_left.push_str(&value); }
                            "status-right" => { app.status_right.push_str(&value); }
                            "status-style" => { app.status_style.push_str(&value); }
                            "pane-border-style" => { app.pane_border_style.push_str(&value); }
                            "pane-active-border-style" => { app.pane_active_border_style.push_str(&value); }
                            "pane-border-hover-style" => { app.pane_border_hover_style.push_str(&value); }
                            "window-status-format" => { app.window_status_format.push_str(&value); }
                            "window-status-current-format" => { app.window_status_current_format.push_str(&value); }
                            _ => {}
                        }
                    }
                }
                CtrlReq::SetOptionOnlyIfUnset(option, value) => {
                    let already_set = if option.starts_with('@') {
                        app.user_options.contains_key(&option)
                    } else {
                        app.user_set_options.contains(&option)
                    };
                    if !already_set {
                        apply_set_option(&mut app, &option, &value, false);
                        app.user_set_options.insert(option.clone());
                        if option == "command-alias" {
                            if let Ok(mut map) = shared_aliases_main.write() {
                                *map = app.command_aliases.clone();
                            }
                        }
                        meta_dirty = true;
                        state_dirty = true;
                    }
                }
                CtrlReq::ShowOptions(resp) => {
                    let mut output = String::new();
                    output.push_str(&format!("prefix {}\n", format_key_binding(&app.prefix_key)));
                    if let Some(ref p2) = app.prefix2_key {
                        output.push_str(&format!("prefix2 {}\n", format_key_binding(p2)));
                    }
                    output.push_str(&format!("base-index {}\n", app.window_base_index));
                    output.push_str(&format!("pane-base-index {}\n", app.pane_base_index));
                    output.push_str(&format!("escape-time {}\n", app.escape_time_ms));
                    output.push_str(&format!("mouse {}\n", if app.mouse_enabled { "on" } else { "off" }));
                    output.push_str(&format!("scroll-enter-copy-mode {}\n", if app.scroll_enter_copy_mode { "on" } else { "off" }));
                    output.push_str(&format!("pwsh-mouse-selection {}\n", if app.pwsh_mouse_selection { "on" } else { "off" }));
                    output.push_str(&format!("mouse-selection {}\n", if app.mouse_selection { "on" } else { "off" }));
                    output.push_str(&format!("paste-detection {}\n", if app.paste_detection { "on" } else { "off" }));
                    output.push_str(&format!("choose-tree-preview {}\n", if app.choose_tree_preview { "on" } else { "off" }));
                    output.push_str(&format!("status {}\n", if app.status_visible { "on" } else { "off" }));
                    output.push_str(&format!("status-position {}\n", app.status_position));
                    output.push_str(&format!("status-left \"{}\"\n", app.status_left));
                    output.push_str(&format!("status-right \"{}\"\n", app.status_right));
                    output.push_str(&format!("history-limit {}\n", app.history_limit));
                    output.push_str(&format!("display-time {}\n", app.display_time_ms));
                    output.push_str(&format!("display-panes-time {}\n", app.display_panes_time_ms));
                    output.push_str(&format!("mode-keys {}\n", app.mode_keys));
                    output.push_str(&format!("focus-events {}\n", if app.focus_events { "on" } else { "off" }));
                    output.push_str(&format!("renumber-windows {}\n", if app.renumber_windows { "on" } else { "off" }));
                    output.push_str(&format!("automatic-rename {}\n", if app.automatic_rename { "on" } else { "off" }));
                    output.push_str(&format!("monitor-activity {}\n", if app.monitor_activity { "on" } else { "off" }));
                    output.push_str(&format!("synchronize-panes {}\n", if app.sync_input { "on" } else { "off" }));
                    output.push_str(&format!("remain-on-exit {}\n", if app.remain_on_exit { "on" } else { "off" }));
                    output.push_str(&format!("destroy-unattached {}\n", if app.destroy_unattached { "on" } else { "off" }));
                    output.push_str(&format!("exit-empty {}\n", if app.exit_empty { "on" } else { "off" }));
                    output.push_str(&format!("set-titles {}\n", if app.set_titles { "on" } else { "off" }));
                    if !app.set_titles_string.is_empty() {
                        output.push_str(&format!("set-titles-string \"{}\"\n", app.set_titles_string));
                    }
                    output.push_str(&format!(
                        "prediction-dimming {}\n",
                        if app.prediction_dimming { "on" } else { "off" }
                    ));
                    output.push_str(&format!("allow-predictions {}\n", if app.allow_predictions { "on" } else { "off" }));
                    output.push_str(&format!("cursor-style {}\n", std::env::var("PSMUX_CURSOR_STYLE").unwrap_or_else(|_| "bar".to_string())));
                    output.push_str(&format!("cursor-blink {}\n", if std::env::var("PSMUX_CURSOR_BLINK").unwrap_or_else(|_| "1".to_string()) != "0" { "on" } else { "off" }));
                    {
                        let shell_val = if app.default_shell.is_empty() {
                            crate::pane::cached_shell().unwrap_or("pwsh.exe").to_string()
                        } else {
                            app.default_shell.clone()
                        };
                        output.push_str(&format!("default-shell {}\n", shell_val));
                    }
                    output.push_str(&format!("word-separators \"{}\"\n", app.word_separators));
                    if !app.pane_border_style.is_empty() {
                        output.push_str(&format!("pane-border-style \"{}\"\n", app.pane_border_style));
                    }
                    if !app.pane_active_border_style.is_empty() {
                        output.push_str(&format!("pane-active-border-style \"{}\"\n", app.pane_active_border_style));
                    }
                    if !app.pane_border_hover_style.is_empty() {
                        output.push_str(&format!("pane-border-hover-style \"{}\"\n", app.pane_border_hover_style));
                    }
                    if !app.status_style.is_empty() {
                        output.push_str(&format!("status-style \"{}\"\n", app.status_style));
                    }
                    if !app.status_left_style.is_empty() {
                        output.push_str(&format!("status-left-style \"{}\"\n", app.status_left_style));
                    }
                    if !app.status_right_style.is_empty() {
                        output.push_str(&format!("status-right-style \"{}\"\n", app.status_right_style));
                    }
                    output.push_str(&format!("status-interval {}\n", app.status_interval));
                    output.push_str(&format!("status-justify {}\n", app.status_justify));
                    output.push_str(&format!("window-status-format \"{}\"\n", app.window_status_format));
                    output.push_str(&format!("window-status-current-format \"{}\"\n", app.window_status_current_format));
                    if !app.window_status_style.is_empty() {
                        output.push_str(&format!("window-status-style \"{}\"\n", app.window_status_style));
                    }
                    if !app.window_status_current_style.is_empty() {
                        output.push_str(&format!("window-status-current-style \"{}\"\n", app.window_status_current_style));
                    }
                    if !app.window_status_activity_style.is_empty() {
                        output.push_str(&format!("window-status-activity-style \"{}\"\n", app.window_status_activity_style));
                    }
                    if !app.message_style.is_empty() {
                        output.push_str(&format!("message-style \"{}\"\n", app.message_style));
                    }
                    if !app.message_command_style.is_empty() {
                        output.push_str(&format!("message-command-style \"{}\"\n", app.message_command_style));
                    }
                    if !app.mode_style.is_empty() {
                        output.push_str(&format!("mode-style \"{}\"\n", app.mode_style));
                    }
                    // Include @user-options (used by plugins)
                    for (key, val) in &app.user_options {
                        output.push_str(&format!("{} \"{}\"\n", key, val));
                    }
                    // New options
                    output.push_str(&format!("main-pane-width {}\n", app.main_pane_width));
                    output.push_str(&format!("main-pane-height {}\n", app.main_pane_height));
                    output.push_str(&format!("status-left-length {}\n", app.status_left_length));
                    output.push_str(&format!("status-right-length {}\n", app.status_right_length));
                    output.push_str(&format!("window-size {}\n", app.window_size));
                    output.push_str(&format!("allow-passthrough {}\n", app.allow_passthrough));
                    output.push_str(&format!("set-clipboard {}\n", app.set_clipboard));
                    if !app.copy_command.is_empty() {
                        output.push_str(&format!("copy-command \"{}\"\n", app.copy_command));
                    }
                    output.push_str(&format!("allow-rename {}\n", if app.allow_rename { "on" } else { "off" }));
                    output.push_str(&format!("allow-set-title {}\n", if app.allow_set_title { "on" } else { "off" }));
                    output.push_str(&format!("bell-action {}\n", app.bell_action));
                    output.push_str(&format!("activity-action {}\n", app.activity_action));
                    output.push_str(&format!("silence-action {}\n", app.silence_action));
                    output.push_str(&format!("update-environment \"{}\"\n", app.update_environment.join(" ")));
                    if let Some(ref group) = app.session_group {
                        output.push_str(&format!("session-group \"{}\"\n", group));
                    }
                    for (alias, expansion) in &app.command_aliases {
                        output.push_str(&format!("command-alias \"{}={}\"\n", alias, expansion));
                    }
                    let _ = resp.send(output);
                }
                CtrlReq::SourceFile(path) => {
                    // Reset binding state so config reload gets a clean slate.
                    // If the config has unbind-key -a, it will re-set the flag.
                    app.defaults_suppressed = false;
                    app.key_tables.clear();
                    crate::config::populate_default_bindings(&mut app);
                    // Use config helper for standard source-file behavior (-F support,
                    // nested parse context). Keep direct glob handling for wildcard sources.
                    let is_format_expand = path.starts_with("-F ") || path.starts_with("-F\t");
                    let path_for_glob = if is_format_expand { path[3..].trim() } else { &path };
                    if !is_format_expand && (path_for_glob.contains('*') || path_for_glob.contains('?')) {
                        let expanded = if path_for_glob.starts_with('~') {
                            let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
                            path_for_glob.replacen('~', &home, 1)
                        } else {
                            path_for_glob.to_string()
                        };
                        if let Ok(entries) = glob::glob(&expanded) {
                            for entry in entries.flatten() {
                                if let Ok(contents) = std::fs::read_to_string(&entry) {
                                    parse_config_content(&mut app, &contents);
                                }
                            }
                        }
                    } else {
                        crate::config::source_file(&mut app, &path);
                    }
                    // source-file may change pane-border-status which
                    // affects pane content height (#288)
                    resize_all_panes(&mut app);
                    // Mark dirty so the client receives updated config
                    // (status bar, bindings, styles, etc.) on the next
                    // dump-state instead of getting an NC fast-path reply.
                    state_dirty = true;
                    meta_dirty = true;
                }
                CtrlReq::MoveWindow(target) => {
                    if let Some(t) = target {
                        if t < app.windows.len() && app.active_idx != t {
                            let win = app.windows.remove(app.active_idx);
                            let insert_idx = if t > app.active_idx { t - 1 } else { t };
                            app.windows.insert(insert_idx.min(app.windows.len()), win);
                            app.active_idx = insert_idx.min(app.windows.len() - 1);
                        }
                    }
                }
                CtrlReq::SwapWindow(target) => {
                    if target < app.windows.len() && app.active_idx != target {
                        app.windows.swap(app.active_idx, target);
                    }
                }
                CtrlReq::LinkWindow(src_idx_opt, dst_idx_opt) => {
                    // link-window: within a single session, create a linked window
                    // referencing the source window. Since PTY handles can't be shared
                    // across windows, this spawns a new shell and marks it as linked.
                    let src = src_idx_opt.unwrap_or(app.active_idx);
                    if src < app.windows.len() {
                        let src_id = app.windows[src].id;
                        let src_name = app.windows[src].name.clone();
                        let dst = dst_idx_opt.unwrap_or(app.windows.len());
                        let pty_system = portable_pty::native_pty_system();
                        match crate::pane::create_window(&*pty_system, &mut app, None, None) {
                            Ok(()) => {
                                let new_idx = app.windows.len() - 1;
                                app.windows[new_idx].linked_from = Some(src_id);
                                app.windows[new_idx].name = src_name;
                                if dst < new_idx {
                                    let win = app.windows.remove(new_idx);
                                    app.windows.insert(dst, win);
                                    if app.active_idx > dst && app.active_idx <= new_idx {
                                        app.active_idx = app.active_idx.saturating_sub(1);
                                    }
                                }
                                resize_all_panes(&mut app);
                                meta_dirty = true;
                                hook_event = Some("window-linked");
                            }
                            Err(_e) => {
                                app.status_message = Some(("link-window: failed to create linked window".to_string(), std::time::Instant::now(), None));
                            }
                        }
                    } else {
                        app.status_message = Some(("link-window: source window not found".to_string(), std::time::Instant::now(), None));
                    }
                    state_dirty = true;
                }
                CtrlReq::UnlinkWindow => {
                    if app.windows.len() > 1 {
                        let mut win = app.windows.remove(app.active_idx);
                        kill_all_children(&mut win.root);
                        if app.active_idx >= app.windows.len() {
                            app.active_idx = app.windows.len() - 1;
                        }
                        resize_all_panes(&mut app);
                        meta_dirty = true;
                        hook_event = Some("window-unlinked");
                    }
                }
                CtrlReq::SetSessionGroup(group_name) => {
                    app.session_group = Some(group_name);
                    state_dirty = true;
                }
                CtrlReq::FindWindow(resp, pattern) => {
                    let mut output = String::new();
                    for (i, win) in app.windows.iter().enumerate() {
                        if win.name.contains(&pattern) {
                            output.push_str(&format!("{}: {} []\n", i + app.window_base_index, win.name));
                        }
                    }
                    let _ = resp.send(output);
                }
                CtrlReq::PipePane(cmd, stdin, stdout, toggle) => {
                    let win = &app.windows[app.active_idx];
                    let pane_id = get_active_pane_id(&win.root, &win.active_path).unwrap_or(0);
                    let has_existing = app.pipe_panes.iter().any(|p| p.pane_id == pane_id);
                    
                    if cmd.is_empty() {
                        // No command: close any existing pipe on this pane
                        if let Some(idx) = app.pipe_panes.iter().position(|p| p.pane_id == pane_id) {
                            if let Some(ref mut proc) = app.pipe_panes[idx].process {
                                let _ = proc.kill();
                            }
                            app.pipe_panes.remove(idx);
                        }
                    } else if toggle && has_existing {
                        // -o flag with existing pipe: close it (toggle off), don't start new
                        if let Some(idx) = app.pipe_panes.iter().position(|p| p.pane_id == pane_id) {
                            if let Some(ref mut proc) = app.pipe_panes[idx].process {
                                let _ = proc.kill();
                            }
                            app.pipe_panes.remove(idx);
                        }
                    } else {
                        // Close any existing pipe first (replace)
                        if let Some(idx) = app.pipe_panes.iter().position(|p| p.pane_id == pane_id) {
                            if let Some(ref mut proc) = app.pipe_panes[idx].process {
                                let _ = proc.kill();
                            }
                            app.pipe_panes.remove(idx);
                        }
                        // Start new pipe
                        let (shell_prog, shell_args) = crate::commands::resolve_run_shell();
                        let process = {
                            let mut c = std::process::Command::new(&shell_prog);
                            for a in &shell_args { c.arg(a); }
                            c.arg(&cmd);
                            c.stdin(if stdout { std::process::Stdio::piped() } else { std::process::Stdio::null() });
                            c.stdout(if stdin { std::process::Stdio::piped() } else { std::process::Stdio::null() });
                            c.stderr(std::process::Stdio::null());
                            { use crate::platform::HideWindowCommandExt; c.hide_window(); }
                            c.spawn().ok()
                        };
                        
                        app.pipe_panes.push(PipePaneState {
                            pane_id,
                            process,
                            stdin,
                            stdout,
                        });
                    }
                }
                CtrlReq::SelectLayout(layout) => {
                    unzoom_if_zoomed(&mut app);
                    apply_layout(&mut app, &layout);
                    resize_all_panes(&mut app);
                    meta_dirty = true;
                    state_dirty = true;
                }
                CtrlReq::NextLayout => {
                    unzoom_if_zoomed(&mut app);
                    cycle_layout(&mut app);
                    resize_all_panes(&mut app);
                    meta_dirty = true;
                    state_dirty = true;
                }
                CtrlReq::ListClients(resp) => {
                    let mut output = String::new();
                    if app.client_registry.is_empty() {
                        // Fallback for backward compat when no clients registered yet
                        output.push_str(&format!("/dev/pts/0: {}: {} [{}x{}] (utf8)\n", 
                            app.session_name, 
                            app.windows[app.active_idx].name,
                            app.last_window_area.width,
                            app.last_window_area.height
                        ));
                    } else {
                        let mut clients: Vec<&crate::types::ClientInfo> = app.client_registry.values().collect();
                        clients.sort_by_key(|c| c.id);
                        for ci in &clients {
                            let activity_secs = ci.last_activity.elapsed().as_secs();
                            let kind = if ci.is_control { " (control mode)" } else { "" };
                            output.push_str(&format!("{}: {}: {} [{}x{}] (utf8){} [activity={}s ago]\n",
                                ci.tty_name,
                                app.session_name,
                                app.windows[app.active_idx].name,
                                ci.width, ci.height,
                                kind,
                                activity_secs,
                            ));
                        }
                    }
                    let _ = resp.send(output);
                }
                CtrlReq::ListClientsFormat(resp, fmt) => {
                    let mut output = String::new();
                    let mut clients: Vec<&crate::types::ClientInfo> = app.client_registry.values().collect();
                    clients.sort_by_key(|c| c.id);
                    for ci in &clients {
                        let activity_secs = ci.last_activity.elapsed().as_secs();
                        let line = fmt
                            .replace("#{client_name}", &ci.tty_name)
                            .replace("#{client_tty}", &ci.tty_name)
                            .replace("#{client_width}", &ci.width.to_string())
                            .replace("#{client_height}", &ci.height.to_string())
                            .replace("#{client_activity}", &activity_secs.to_string())
                            .replace("#{client_session}", &app.session_name)
                            .replace("#{session_name}", &app.session_name)
                            .replace("#{client_control_mode}", if ci.is_control { "1" } else { "0" });
                        output.push_str(&line);
                        output.push('\n');
                    }
                    let _ = resp.send(output);
                }
                CtrlReq::ForceDetachClient(target_cid) => {
                    // Force-detach a specific client by shutting down its TCP stream
                    app.client_sizes.remove(&target_cid);
                    let was_present = app.client_registry.remove(&target_cid).is_some();
                    if was_present {
                        app.attached_clients = app.attached_clients.saturating_sub(1);
                    }
                    if app.latest_client_id == Some(target_cid) {
                        app.latest_client_id = app.client_registry.keys().max().copied();
                    }
                    // Shut down the TCP stream to force disconnect
                    crate::types::shutdown_client_stream(target_cid);
                    // Recompute effective size from remaining clients
                    if let Some((w, h)) = compute_effective_client_size(&app) {
                        app.last_window_area = Rect { x: 0, y: 0, width: w, height: h };
                        resize_all_panes(&mut app);
                    }
                    // Fire detach notification
                    control::emit_notification(&app, crate::types::ControlNotification::ClientDetached {
                        client: format!("/dev/pts/{}", target_cid),
                    });
                    hook_event = Some("client-detached");
                    if app.attached_clients == 0 && app.destroy_unattached {
                        let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
                        let regpath = format!("{}\\.psmux\\{}.port", home, app.port_file_base());
                        let keypath = format!("{}\\.psmux\\{}.key", home, app.port_file_base());
                        let _ = std::fs::remove_file(&regpath);
                        let _ = std::fs::remove_file(&keypath);
                        crate::session::remove_session_id_file(&app.port_file_base());
                        crate::types::shutdown_persistent_streams();
                        tree::kill_all_children_batch(&mut app.windows);
                        if let Some(mut wp) = app.warm_pane.take() {
                            wp.child.kill().ok();
                        }
                        std::thread::sleep(std::time::Duration::from_millis(10));
                        std::process::exit(0);
                    }
                }
                CtrlReq::ForceDetachClientByTty(tty, kill_parent) => {
                    // Look up the client by tty_name (e.g. "/dev/pts/2") and force-detach.
                    let target_cid: Option<u64> = app.client_registry.iter()
                        .find(|(_, ci)| ci.tty_name == tty)
                        .map(|(cid, _)| *cid);
                    if let Some(cid) = target_cid {
                        if kill_parent {
                            crate::types::send_directive_to_client(cid, "DETACH-KILL-PARENT");
                            std::thread::sleep(Duration::from_millis(50));
                        }
                        app.client_sizes.remove(&cid);
                        let was_present = app.client_registry.remove(&cid).is_some();
                        if was_present {
                            app.attached_clients = app.attached_clients.saturating_sub(1);
                        }
                        if app.latest_client_id == Some(cid) {
                            app.latest_client_id = app.client_registry.keys().max().copied();
                        }
                        crate::types::shutdown_client_stream(cid);
                        if let Some((w, h)) = compute_effective_client_size(&app) {
                            app.last_window_area = Rect { x: 0, y: 0, width: w, height: h };
                            resize_all_panes(&mut app);
                        }
                        control::emit_notification(&app, crate::types::ControlNotification::ClientDetached {
                            client: tty.clone(),
                        });
                        hook_event = Some("client-detached");
                    }
                }
                CtrlReq::DetachAllOtherClients(except_cid, kill_parent) => {
                    // Detach all clients except the one with except_cid.
                    // Pass u64::MAX from CLI one-shot path to mean "no current client".
                    let targets: Vec<(u64, String)> = app.client_registry.iter()
                        .filter(|(cid, _)| **cid != except_cid)
                        .map(|(cid, ci)| (*cid, ci.tty_name.clone()))
                        .collect();
                    for (cid, _tty) in &targets {
                        if kill_parent {
                            crate::types::send_directive_to_client(*cid, "DETACH-KILL-PARENT");
                        }
                    }
                    if kill_parent && !targets.is_empty() {
                        std::thread::sleep(Duration::from_millis(50));
                    }
                    for (cid, tty) in &targets {
                        app.client_sizes.remove(cid);
                        if app.client_registry.remove(cid).is_some() {
                            app.attached_clients = app.attached_clients.saturating_sub(1);
                        }
                        crate::types::shutdown_client_stream(*cid);
                        control::emit_notification(&app, crate::types::ControlNotification::ClientDetached {
                            client: tty.clone(),
                        });
                    }
                    if !targets.is_empty() {
                        if app.latest_client_id.map_or(false, |c| !app.client_registry.contains_key(&c)) {
                            app.latest_client_id = app.client_registry.keys().max().copied();
                        }
                        if let Some((w, h)) = compute_effective_client_size(&app) {
                            app.last_window_area = Rect { x: 0, y: 0, width: w, height: h };
                            resize_all_panes(&mut app);
                        }
                        hook_event = Some("client-detached");
                    }
                    if app.attached_clients == 0 && app.destroy_unattached {
                        let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
                        let regpath = format!("{}\\.psmux\\{}.port", home, app.port_file_base());
                        let keypath = format!("{}\\.psmux\\{}.key", home, app.port_file_base());
                        let _ = std::fs::remove_file(&regpath);
                        let _ = std::fs::remove_file(&keypath);
                        crate::session::remove_session_id_file(&app.port_file_base());
                        crate::types::shutdown_persistent_streams();
                        tree::kill_all_children_batch(&mut app.windows);
                        if let Some(mut wp) = app.warm_pane.take() {
                            wp.child.kill().ok();
                        }
                        std::thread::sleep(std::time::Duration::from_millis(10));
                        std::process::exit(0);
                    }
                }
                CtrlReq::DetachAllClients(kill_parent) => {
                    // Detach every attached client of this session.
                    let targets: Vec<(u64, String)> = app.client_registry.iter()
                        .map(|(cid, ci)| (*cid, ci.tty_name.clone()))
                        .collect();
                    for (cid, _) in &targets {
                        if kill_parent {
                            crate::types::send_directive_to_client(*cid, "DETACH-KILL-PARENT");
                        }
                    }
                    if kill_parent && !targets.is_empty() {
                        std::thread::sleep(Duration::from_millis(50));
                    }
                    for (cid, tty) in &targets {
                        app.client_sizes.remove(cid);
                        if app.client_registry.remove(cid).is_some() {
                            app.attached_clients = app.attached_clients.saturating_sub(1);
                        }
                        crate::types::shutdown_client_stream(*cid);
                        control::emit_notification(&app, crate::types::ControlNotification::ClientDetached {
                            client: tty.clone(),
                        });
                    }
                    if !targets.is_empty() {
                        app.latest_client_id = None;
                        app.client_prefix_active = false;
                        if let Some((w, h)) = compute_effective_client_size(&app) {
                            app.last_window_area = Rect { x: 0, y: 0, width: w, height: h };
                            resize_all_panes(&mut app);
                        }
                        hook_event = Some("client-detached");
                    }
                    if app.attached_clients == 0 && app.destroy_unattached {
                        let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
                        let regpath = format!("{}\\.psmux\\{}.port", home, app.port_file_base());
                        let keypath = format!("{}\\.psmux\\{}.key", home, app.port_file_base());
                        let _ = std::fs::remove_file(&regpath);
                        let _ = std::fs::remove_file(&keypath);
                        crate::session::remove_session_id_file(&app.port_file_base());
                        crate::types::shutdown_persistent_streams();
                        tree::kill_all_children_batch(&mut app.windows);
                        if let Some(mut wp) = app.warm_pane.take() {
                            wp.child.kill().ok();
                        }
                        std::thread::sleep(std::time::Duration::from_millis(10));
                        std::process::exit(0);
                    }
                }
                CtrlReq::SwitchClient(target, flag) => {
                    // Resolve the target session name based on the flag
                    let current = app.port_file_base();
                    let all_sessions = crate::session::list_session_names();
                    let resolved = match flag {
                        't' => {
                            // Direct target: validate it exists
                            if target.is_empty() {
                                None
                            } else if all_sessions.contains(&target) {
                                Some(target.clone())
                            } else {
                                // Try partial match (prefix)
                                all_sessions.iter().find(|s| s.starts_with(&target)).cloned()
                            }
                        }
                        'n' => {
                            // Next session (alphabetically after current)
                            let pos = all_sessions.iter().position(|s| s == &current);
                            match pos {
                                Some(i) if i + 1 < all_sessions.len() => Some(all_sessions[i + 1].clone()),
                                Some(_) => all_sessions.first().cloned(), // wrap around
                                None => all_sessions.first().cloned(),
                            }
                        }
                        'p' => {
                            // Previous session (alphabetically before current)
                            let pos = all_sessions.iter().position(|s| s == &current);
                            match pos {
                                Some(0) => all_sessions.last().cloned(), // wrap around
                                Some(i) => Some(all_sessions[i - 1].clone()),
                                None => all_sessions.last().cloned(),
                            }
                        }
                        'l' => {
                            // Last session (read from last_session file)
                            let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
                            let last_path = format!("{}\\.psmux\\last_session", home);
                            std::fs::read_to_string(&last_path).ok()
                                .map(|s| s.trim().to_string())
                                .filter(|s| !s.is_empty() && s != &current && all_sessions.contains(s))
                        }
                        _ => None,
                    };
                    match resolved {
                        Some(ref sess) if sess != &current => {
                            // Signal the attached client to switch by sending a directive
                            if let Some(cid) = app.latest_client_id {
                                crate::types::send_directive_to_client(cid, &format!("SWITCH {}", sess));
                            } else {
                                // No specific client ID, send to all attached clients
                                crate::types::send_directive_to_all_clients(&format!("SWITCH {}", sess));
                            }
                        }
                        Some(_) => {
                            // Target is the same as current session
                            app.status_message = Some(("switch-client: already on that session".to_string(), std::time::Instant::now(), None));
                            state_dirty = true;
                        }
                        None => {
                            if flag == 't' && !target.is_empty() {
                                app.status_message = Some((format!("switch-client: session not found: {}", target), std::time::Instant::now(), None));
                            } else if flag == 'l' {
                                app.status_message = Some(("switch-client: no last session".to_string(), std::time::Instant::now(), None));
                            } else if all_sessions.len() <= 1 {
                                app.status_message = Some(("switch-client: only one session available".to_string(), std::time::Instant::now(), None));
                            } else {
                                app.status_message = Some(("switch-client: no target session".to_string(), std::time::Instant::now(), None));
                            }
                            state_dirty = true;
                        }
                    }
                }
                CtrlReq::SwitchClientTable(table) => {
                    app.current_key_table = Some(table);
                    state_dirty = true;
                }
                CtrlReq::ListCommands(resp) => {
                    let cmds = TMUX_COMMANDS.join("\n");
                    let _ = resp.send(cmds);
                }
                CtrlReq::LockClient => {
                    app.status_message = Some(("lock: not available on Windows".to_string(), std::time::Instant::now(), None));
                    state_dirty = true;
                }
                CtrlReq::RefreshClient => { state_dirty = true; meta_dirty = true; }
                CtrlReq::SuspendClient => {
                    app.status_message = Some(("suspend: not available on Windows".to_string(), std::time::Instant::now(), None));
                    state_dirty = true;
                }
                CtrlReq::CopyModePageUp => {
                    enter_copy_mode(&mut app);
                    move_copy_cursor(&mut app, 0, -20);
                }
                CtrlReq::ClearHistory => {
                    let win = &mut app.windows[app.active_idx];
                    if let Some(p) = active_pane_mut(&mut win.root, &win.active_path) {
                        if let Ok(mut parser) = p.term.lock() {
                            *parser = vt100::Parser::new(p.last_rows, p.last_cols, app.history_limit);
                        }
                    }
                }
                CtrlReq::SaveBuffer(path) => {
                    if let Some(content) = app.paste_buffers.first() {
                        let _ = std::fs::write(&path, content);
                    }
                }
                CtrlReq::LoadBuffer(path) => {
                    if let Ok(content) = std::fs::read_to_string(&path) {
                        app.paste_buffers.insert(0, content);
                        if app.paste_buffers.len() > 10 {
                            app.paste_buffers.pop();
                        }
                    }
                }
                CtrlReq::SetEnvironment(key, value) => {
                    app.environment.insert(key.clone(), value.clone());
                    env::set_var(&key, &value);
                    // Env vars affect the child shell's process state,
                    // which can't be patched in place — must respawn.
                    // Centralised through warm_pane_sync (#137 / #271).
                    let sync = crate::warm_pane_sync::for_env_change();
                    crate::warm_pane_sync::apply(&mut app, &*pty_system, sync);
                }
                CtrlReq::UnsetEnvironment(key) => {
                    app.environment.remove(&key);
                    env::remove_var(&key);
                    let sync = crate::warm_pane_sync::for_env_change();
                    crate::warm_pane_sync::apply(&mut app, &*pty_system, sync);
                }
                CtrlReq::ShowEnvironment(resp) => {
                    let mut output = String::new();
                    // Show psmux/tmux-specific environment vars
                    for (key, value) in &app.environment {
                        output.push_str(&format!("{}={}\n", key, value));
                    }
                    // Also show inherited PSMUX_/TMUX_ vars from process env
                    for (key, value) in env::vars() {
                        if (key.starts_with("PSMUX") || key.starts_with("TMUX")) && !app.environment.contains_key(&key) {
                            output.push_str(&format!("{}={}\n", key, value));
                        }
                    }
                    let _ = resp.send(output);
                }
                CtrlReq::SetHook(hook, cmd) => {
                    // Replace (not append) to match tmux semantics – prevents
                    // duplicate hooks on config reload (issue #133).
                    app.hooks.insert(hook, vec![cmd]);
                }
                CtrlReq::AppendHook(hook, cmd) => {
                    // -a/-ga: append to existing hook list so multiple
                    // plugins can register separate handlers (tmux semantics).
                    app.hooks.entry(hook).or_insert_with(Vec::new).push(cmd);
                }
                CtrlReq::ShowHooks(resp) => {
                    let mut output = String::new();
                    for (name, commands) in &app.hooks {
                        if commands.len() == 1 {
                            output.push_str(&format!("{} -> {}\n", name, commands[0]));
                        } else {
                            for (i, cmd) in commands.iter().enumerate() {
                                output.push_str(&format!("{}[{}] -> {}\n", name, i, cmd));
                            }
                        }
                    }
                    if output.is_empty() {
                        output.push_str("(no hooks)\n");
                    }
                    let _ = resp.send(output);
                }
                CtrlReq::RemoveHook(hook) => {
                    app.hooks.remove(&hook);
                }
                CtrlReq::KillServer => {
                    // Notify control clients that the server is going away,
                    // matching tmux's "%exit" wire notification before close.
                    // Flushes through the writer thread so iTerm2 sees a
                    // proper EOF-with-reason instead of a raw TCP RST.
                    if !app.control_clients.is_empty() {
                        control::emit_notification(
                            &app,
                            crate::types::ControlNotification::Exit {
                                reason: Some("server exited".to_string()),
                            },
                        );
                        // Brief drain window so writer threads can flush
                        // %exit + ST before the process exits.
                        std::thread::sleep(std::time::Duration::from_millis(80));
                    }
                    // Remove port/key files FIRST so clients see the session
                    // as gone immediately, then kill processes.
                    let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
                    let regpath = format!("{}\\.psmux\\{}.port", home, app.port_file_base());
                    let keypath = format!("{}\\.psmux\\{}.key", home, app.port_file_base());
                    let _ = std::fs::remove_file(&regpath);
                    let _ = std::fs::remove_file(&keypath);
                    crate::types::send_directive_to_all_clients("DETACH");
                    std::thread::sleep(Duration::from_millis(50));
                    crate::types::shutdown_persistent_streams();
                    // Kill all child processes using a single process snapshot
                    tree::kill_all_children_batch(&mut app.windows);
                    // Kill warm pane's child (process::exit skips Drop)
                    if let Some(mut wp) = app.warm_pane.take() { wp.child.kill().ok(); }
                    // TerminateProcess is synchronous on Windows — processes
                    // are already dead.  Minimal delay for OS handle cleanup.
                    std::thread::sleep(std::time::Duration::from_millis(10));
                    std::process::exit(0);
                }
                CtrlReq::WaitFor(channel, op) => {
                    match op {
                        WaitForOp::Lock => {
                            let entry = app.wait_channels.entry(channel).or_insert_with(|| WaitChannel {
                                locked: false,
                                waiters: Vec::new(),
                            });
                            entry.locked = true;
                        }
                        WaitForOp::Unlock => {
                            if let Some(ch) = app.wait_channels.get_mut(&channel) {
                                ch.locked = false;
                                for waiter in ch.waiters.drain(..) {
                                    let _ = waiter.send(());
                                }
                            }
                        }
                        WaitForOp::Signal => {
                            if let Some(ch) = app.wait_channels.get_mut(&channel) {
                                for waiter in ch.waiters.drain(..) {
                                    let _ = waiter.send(());
                                }
                            }
                        }
                        WaitForOp::Wait => {
                            app.wait_channels.entry(channel).or_insert_with(|| WaitChannel {
                                locked: false,
                                waiters: Vec::new(),
                            });
                        }
                    }
                }
                CtrlReq::DisplayMenu(menu_def, x, y) => {
                    let menu = parse_menu_definition(&menu_def, x, y);
                    if !menu.items.is_empty() {
                        app.mode = Mode::MenuMode { menu };
                        state_dirty = true;
                    }
                }
                CtrlReq::DisplayMenuDirect(menu) => {
                    if !menu.items.is_empty() {
                        app.mode = Mode::MenuMode { menu };
                        state_dirty = true;
                    }
                }
                CtrlReq::DisplayPopup(command, width_spec, height_spec, close_on_exit, start_dir) => {
                    // Resolve percentage dimensions against terminal area (#154)
                    let term_w = app.last_window_area.width;
                    let term_h = app.last_window_area.height;
                    let width = parse_popup_dim(&width_spec, term_w, 80);
                    let height = parse_popup_dim(&height_spec, term_h, 24);
                    // Expand format variables in start_dir (e.g. #{pane_current_path})
                    let start_dir = start_dir.map(|d| expand_format(&d, &app)).filter(|d| !d.is_empty());
                    let saved_dir = if start_dir.is_some() { env::current_dir().ok() } else { None };
                    if let Some(dir) = &start_dir { let _ = env::set_current_dir(dir); }
                    // Spawn the popup as a real PTY-backed Pane. An EMPTY command
                    // means "run an interactive shell" (tmux parity, issue #351):
                    // create_popup_pane() launches the shell as a REPL in that case.
                    let inner_h = height.saturating_sub(2);
                    let inner_w = width.saturating_sub(2);
                    let pane_result = crate::popup::create_popup_pane(
                        &command,
                        start_dir.as_deref(),
                        inner_h,
                        inner_w,
                        app.next_pane_id,
                        &app.session_name,
                        &app.environment,
                    );
                    if let Some(prev) = saved_dir { let _ = env::set_current_dir(prev); }

                    if pane_result.is_some() {
                        app.mode = Mode::PopupMode {
                            command: command.clone(),
                            output: String::new(),
                            process: None,
                            width,
                            height,
                            close_on_exit,
                            popup_pane: pane_result,
                            scroll_offset: 0,
                        };
                    } else {
                        // PTY spawn failed — fall back to a static, closable popup
                        // so the user is never stuck with a blank, unresponsive box.
                        app.mode = Mode::PopupMode {
                            command: command.clone(),
                            output: "Failed to start popup shell. Press 'q' or Escape to close\n".to_string(),
                            process: None,
                            width,
                            height,
                            close_on_exit: true,
                            popup_pane: None,
                            scroll_offset: 0,
                        };
                    }
                    state_dirty = true;
                }
                CtrlReq::ConfirmBefore(prompt, cmd) => {
                    let prompt_text = if prompt.is_empty() {
                        format!("Confirm: {}? (y/n)", cmd)
                    } else {
                        // Don't append (y/n) if prompt already contains it
                        if prompt.contains("(y/n)") {
                            prompt.clone()
                        } else {
                            let base = prompt.trim_end_matches('?');
                            format!("{}? (y/n)", base)
                        }
                    };
                    app.mode = Mode::ConfirmMode {
                        prompt: prompt_text,
                        command: cmd,
                        input: String::new(),
                    };
                    state_dirty = true;
                }
                CtrlReq::ResizePaneAbsolute(axis, size) => {
                    unzoom_if_zoomed(&mut app);
                    resize_pane_absolute(&mut app, &axis, size);
                    resize_all_panes(&mut app);
                    hook_event = Some("after-resize-pane");
                }
                CtrlReq::ResizePanePercent(axis, pct) => {
                    unzoom_if_zoomed(&mut app);
                    // Convert percentage to absolute size based on current window dimensions
                    let area = app.last_window_area;
                    let total = if axis == "x" { area.width } else { area.height };
                    let abs_size = ((total as u32) * (pct as u32) / 100).max(1) as u16;
                    resize_pane_absolute(&mut app, &axis, abs_size);
                    resize_all_panes(&mut app);
                    hook_event = Some("after-resize-pane");
                }
                CtrlReq::ShowOptionValue(resp, name) => {
                    let val = get_option_value(&app, &name);
                    let _ = resp.send(val);
                }
                CtrlReq::ShowWindowOptionValue(resp, name, target) => {
                    let val = crate::server::options::get_window_option_value_for(&app, &name, target);
                    let _ = resp.send(val);
                }
                CtrlReq::ShowWindowOptions(resp) => {
                    let _ = resp.send(render_window_options(&app));
                }
                CtrlReq::ChooseBuffer(resp) => {
                    let mut output = String::new();
                    for (i, buf) in app.paste_buffers.iter().enumerate() {
                        let preview: String = buf.chars().take(50).collect();
                        let preview = preview.replace('\n', "\\n").replace('\r', "");
                        output.push_str(&format!("buffer{}: {} bytes: \"{}\"\n", i, buf.len(), preview));
                    }
                    let mut names: Vec<&String> = app.named_buffers.keys().collect();
                    names.sort();
                    for name in names {
                        let buf = &app.named_buffers[name];
                        let preview: String = buf.chars().take(50).collect();
                        let preview = preview.replace('\n', "\\n").replace('\r', "");
                        output.push_str(&format!("{}: {} bytes: \"{}\"\n", name, buf.len(), preview));
                    }
                    let _ = resp.send(output);
                }
                CtrlReq::ServerInfo(resp) => {
                    let info = format!(
                        "psmux {} (Windows)\npid: {}\nsession: {}\nwindows: {}\nuptime: {}s\nsocket: {}",
                        VERSION,
                        std::process::id(),
                        app.session_name,
                        app.windows.len(),
                        (chrono::Local::now() - app.created_at).num_seconds(),
                        {
                            let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
                            format!("{}\\.psmux\\{}.port", home, app.port_file_base())
                        }
                    );
                    let _ = resp.send(info);
                }
                CtrlReq::SendPrefix => {
                    // Send the prefix key to the active pane as if typed
                    let prefix = app.prefix_key;
                    let encoded: Vec<u8> = match prefix.0 {
                        crossterm::event::KeyCode::Char(c) if prefix.1.contains(crossterm::event::KeyModifiers::CONTROL) => {
                            vec![(c.to_ascii_lowercase() as u8) & 0x1F]
                        }
                        crossterm::event::KeyCode::Char(c) => format!("{}", c).into_bytes(),
                        _ => vec![],
                    };
                    if !encoded.is_empty() {
                        let win = &mut app.windows[app.active_idx];
                        if let Some(p) = active_pane_mut(&mut win.root, &win.active_path) {
                            let _ = p.writer.write_all(&encoded);
                            let _ = p.writer.flush();
                        }
                    }
                }
                CtrlReq::PrevLayout => {
                    unzoom_if_zoomed(&mut app);
                    cycle_layout_reverse(&mut app);
                    resize_all_panes(&mut app);
                    meta_dirty = true;
                    state_dirty = true;
                }
                CtrlReq::FocusIn => {
                    if app.focus_events {
                        // Forward focus-in escape sequence to all panes in active window
                        let win = &mut app.windows[app.active_idx];
                        fn send_focus_seq(node: &mut Node, seq: &[u8]) {
                            match node {
                                Node::Leaf(p) => { let _ = p.writer.write_all(seq); let _ = p.writer.flush(); }
                                Node::Split { children, .. } => { for c in children { send_focus_seq(c, seq); } }
                            }
                        }
                        send_focus_seq(&mut win.root, b"\x1b[I");
                    }
                    hook_event = Some("pane-focus-in");
                }
                CtrlReq::FocusOut => {
                    if app.focus_events {
                        let win = &mut app.windows[app.active_idx];
                        fn send_focus_seq(node: &mut Node, seq: &[u8]) {
                            match node {
                                Node::Leaf(p) => { let _ = p.writer.write_all(seq); let _ = p.writer.flush(); }
                                Node::Split { children, .. } => { for c in children { send_focus_seq(c, seq); } }
                            }
                        }
                        send_focus_seq(&mut win.root, b"\x1b[O");
                    }
                    hook_event = Some("pane-focus-out");
                }
                CtrlReq::CommandPrompt(initial) => {
                    app.mode = Mode::CommandPrompt { input: initial.clone(), cursor: initial.len() };
                    state_dirty = true;
                }
                CtrlReq::ShowMessages(resp) => {
                    // Return message log (tmux stores recent log messages)
                    let _ = resp.send(String::new());
                }
                CtrlReq::ResizeWindow(_dim, _size) => {
                    // On Windows, window size is controlled by the terminal emulator;
                    // resize-window is a no-op since we adapt to the terminal size.
                }
                CtrlReq::ControlClientResize(w, h) => {
                    // iTerm2 (or another -CC client) is the authoritative
                    // source for window geometry: it sends `refresh-client
                    // -C w,h` on attach and `resize-window -x w -y h -t @N`
                    // whenever the user drag-resizes its window.  Update
                    // last_window_area, resize all panes, and emit
                    // %layout-change so iTerm2 can repaint splits.
                    if w > 0 && h > 0 {
                        let new_area = ratatui::layout::Rect { x: 0, y: 0, width: w, height: h };
                        if app.last_window_area != new_area {
                            app.last_window_area = new_area;
                            resize_all_panes(&mut app);
                            state_dirty = true;
                            meta_dirty = true;
                            if !app.control_clients.is_empty() {
                                for w_ref in &app.windows {
                                    let layout = control::window_layout_string(w_ref, new_area);
                                    control::emit_notification(&app, crate::types::ControlNotification::LayoutChange {
                                        window_id: w_ref.id,
                                        layout,
                                    });
                                }
                            }
                        }
                    }
                }
                CtrlReq::RespawnWindow => {
                    // Kill all panes in the active window and respawn	
                    respawn_active_pane(&mut app, Some(&*pty_system), None, true)?;
                    state_dirty = true;
                }
                CtrlReq::PopupInput(data) => {
                    if let Mode::PopupMode { ref mut popup_pane, .. } = app.mode {
                        if let Some(ref mut pty) = popup_pane {
                            // If child has exited, 'q' closes the popup
                            let child_exited = matches!(pty.child.try_wait(), Ok(Some(_)));
                            if child_exited && data == b"q" {
                                app.mode = Mode::Passthrough;
                            } else if !child_exited {
                                let _ = pty.writer.write_all(&data);
                                let _ = pty.writer.flush();
                            }
                        } else {
                            // No PTY means static popup — 'q' closes it
                            if data == b"q" {
                                app.mode = Mode::Passthrough;
                            }
                        }
                    }
                    state_dirty = true;
                }
                CtrlReq::OverlayClose => {
                    match app.mode {
                        Mode::PopupMode { .. } | Mode::MenuMode { .. } | Mode::ConfirmMode { .. } | Mode::PaneChooser { .. } | Mode::ClockMode | Mode::CustomizeMode { .. } => {
                            app.mode = Mode::Passthrough;
                            state_dirty = true;
                        }
                        _ => {}
                    }
                }
                CtrlReq::ConfirmRespond(yes) => {
                    if let Mode::ConfirmMode { ref command, .. } = app.mode {
                        let cmd = command.clone();
                        app.mode = Mode::Passthrough;
                        if yes {
                            let _ = execute_command_string(&mut app, &cmd);
                        }
                        state_dirty = true;
                    }
                }
                CtrlReq::MenuSelect(idx) => {
                    if let Mode::MenuMode { ref menu } = app.mode {
                        if let Some(item) = menu.items.get(idx) {
                            if !item.is_separator && !item.command.is_empty() {
                                let cmd = item.command.clone();
                                app.mode = Mode::Passthrough;
                                let _ = execute_command_string(&mut app, &cmd);
                                state_dirty = true;
                            }
                        }
                    }
                }
                CtrlReq::MenuNavigate(delta) => {
                    if let Mode::MenuMode { ref mut menu } = app.mode {
                        let len = menu.items.len();
                        if len > 0 {
                            if delta > 0 {
                                // Move down, skipping separators
                                let mut next = (menu.selected + 1) % len;
                                let start = next;
                                while menu.items[next].is_separator {
                                    next = (next + 1) % len;
                                    if next == start { break; }
                                }
                                menu.selected = next;
                            } else {
                                // Move up, skipping separators
                                let mut next = if menu.selected == 0 { len - 1 } else { menu.selected - 1 };
                                let start = next;
                                while menu.items[next].is_separator {
                                    next = if next == 0 { len - 1 } else { next - 1 };
                                    if next == start { break; }
                                }
                                menu.selected = next;
                            }
                            state_dirty = true;
                        }
                    }
                }
                CtrlReq::ShowTextPopup(title, content) => {
                    let lines: Vec<&str> = content.lines().collect();
                    let width = lines.iter().map(|l| l.len()).max().unwrap_or(40).max(20) as u16 + 4;
                    let height = (lines.len() as u16 + 2).max(5);
                    app.mode = Mode::PopupMode {
                        command: title,
                        output: content,
                        process: None,
                        width: width.min(120),
                        height,
                        close_on_exit: false,
                        popup_pane: None,
                        scroll_offset: 0,
                    };
                    state_dirty = true;
                }
                CtrlReq::StatusMessage(msg) => {
                    app.status_message = Some((msg, std::time::Instant::now(), None));
                    state_dirty = true;
                }
                CtrlReq::ClearPromptHistory => {
                    app.command_history.clear();
                    app.command_history_idx = 0;
                }
                CtrlReq::ShowPromptHistory(persistent) => {
                    if persistent {
                        let content = if app.command_history.is_empty() {
                            "(no prompt history)\n".to_string()
                        } else {
                            app.command_history.iter().enumerate()
                                .map(|(i, cmd)| format!("{}: {}", i, cmd))
                                .collect::<Vec<_>>().join("\n")
                        };
                        let lines: Vec<&str> = content.lines().collect();
                        let width = lines.iter().map(|l| l.len()).max().unwrap_or(40).max(20) as u16 + 4;
                        let height = (lines.len() as u16 + 2).max(5);
                        app.mode = Mode::PopupMode {
                            command: "show-prompt-history".to_string(),
                            output: content,
                            process: None,
                            width: width.min(120),
                            height: height.min(40),
                            close_on_exit: false,
                            popup_pane: None,
                            scroll_offset: 0,
                        };
                        state_dirty = true;
                    }
                }
                CtrlReq::ControlRegister { client_id, echo, notif_tx } => {
                    app.control_clients.insert(client_id, crate::types::ControlClient {
                        client_id,
                        cmd_counter: 0,
                        echo_enabled: echo,
                        notification_tx: notif_tx,
                        paused_panes: std::collections::HashSet::new(),
                        subscriptions: std::collections::HashMap::new(),
                        subscription_values: std::collections::HashMap::new(),
                        subscription_last_check: std::collections::HashMap::new(),
                        pause_after_secs: None,
                        output_paused_panes: std::collections::HashSet::new(),
                        pane_last_output: std::collections::HashMap::new(),
                    });
                    // Register control client in the client registry
                    let tty = format!("/dev/pts/{}", client_id);
                    app.client_registry.insert(client_id, crate::types::ClientInfo {
                        id: client_id,
                        width: app.last_window_area.width,
                        height: app.last_window_area.height,
                        connected_at: std::time::Instant::now(),
                        last_activity: std::time::Instant::now(),
                        tty_name: tty,
                        is_control: true,
                    });
                    app.attached_clients = app.attached_clients.saturating_add(1);
                    // Real tmux fires server hooks (session-changed, window-add,
                    // etc.) as side effects of the initial attach-session command.
                    // iTerm2 depends on %session-changed to enable writes
                    // (_canWrite = YES) and flush its command queue. Without
                    // this notification, iTerm2 never sends any commands and
                    // sits idle forever.
                    //
                    // The unsolicited %begin/%end pair (flags=0) is emitted by
                    // connection.rs right after the DCS opener. That triggers
                    // tmuxInitialCommandDidCompleteSuccessfully in iTerm2 which
                    // queues the initialization commands. Then the
                    // %session-changed notification below enables writes so
                    // those queued commands actually get sent.
                    crate::control::emit_initial_state(&app, client_id);
                }
                CtrlReq::ControlSubscribe { client_id, name, target, format } => {
                    if let Some(cc) = app.control_clients.get_mut(&client_id) {
                        cc.subscriptions.insert(name.clone(), (target, format));
                        // Clear cached value so the first check always emits
                        cc.subscription_values.remove(&name);
                        cc.subscription_last_check.remove(&name);
                    }
                }
                CtrlReq::ControlUnsubscribe { client_id, name } => {
                    if let Some(cc) = app.control_clients.get_mut(&client_id) {
                        cc.subscriptions.remove(&name);
                        cc.subscription_values.remove(&name);
                        cc.subscription_last_check.remove(&name);
                    }
                }
                CtrlReq::ControlSetPauseAfter { client_id, pause_after_secs } => {
                    if let Some(cc) = app.control_clients.get_mut(&client_id) {
                        cc.pause_after_secs = pause_after_secs;
                        if pause_after_secs.is_none() {
                            // Clear all pause state when disabling
                            cc.output_paused_panes.clear();
                            cc.pane_last_output.clear();
                        }
                    }
                }
                CtrlReq::ControlContinuePane { client_id, pane_id } => {
                    if let Some(cc) = app.control_clients.get_mut(&client_id) {
                        if cc.output_paused_panes.remove(&pane_id) {
                            let _ = cc.notification_tx.try_send(
                                crate::types::ControlNotification::Continue { pane_id }
                            );
                        }
                    }
                }
                CtrlReq::ControlDeregister { client_id } => {
                    app.control_clients.remove(&client_id);
                    app.client_registry.remove(&client_id);
                    app.attached_clients = app.attached_clients.saturating_sub(1);
                }
                CtrlReq::CustomizeMode => {
                    let options = crate::server::option_catalog::build_option_list(&app);
                    app.mode = Mode::CustomizeMode {
                        options,
                        selected: 0,
                        scroll_offset: 0,
                        editing: false,
                        edit_buffer: String::new(),
                        edit_cursor: 0,
                        filter: String::new(),
                    };
                    state_dirty = true;
                }
                CtrlReq::CustomizeNavigate(delta) => {
                    if let Mode::CustomizeMode { ref options, ref mut selected, ref filter, ref mut scroll_offset, editing, .. } = app.mode {
                        if !editing {
                            let visible: Vec<usize> = options.iter().enumerate()
                                .filter(|(_, (name, _, _))| filter.is_empty() || name.contains(filter.as_str()))
                                .map(|(i, _)| i)
                                .collect();
                            if !visible.is_empty() {
                                let cur_pos = visible.iter().position(|&i| i == *selected).unwrap_or(0);
                                let new_pos = if delta > 0 {
                                    (cur_pos + delta as usize).min(visible.len() - 1)
                                } else {
                                    cur_pos.saturating_sub((-delta) as usize)
                                };
                                *selected = visible[new_pos];
                                // Update scroll offset to keep selection visible
                                if new_pos < *scroll_offset {
                                    *scroll_offset = new_pos;
                                } else if new_pos >= *scroll_offset + 20 {
                                    *scroll_offset = new_pos.saturating_sub(19);
                                }
                            }
                            state_dirty = true;
                        }
                    }
                }
                CtrlReq::CustomizeEdit => {
                    if let Mode::CustomizeMode { ref options, selected, ref mut editing, ref mut edit_buffer, ref mut edit_cursor, .. } = app.mode {
                        if !*editing {
                            if let Some((_, value, _)) = options.get(selected) {
                                *edit_buffer = value.clone();
                                *edit_cursor = edit_buffer.len();
                                *editing = true;
                                state_dirty = true;
                            }
                        }
                    }
                }
                CtrlReq::CustomizeEditUpdate(text) => {
                    if let Mode::CustomizeMode { editing, ref mut edit_buffer, ref mut edit_cursor, .. } = app.mode {
                        if editing {
                            *edit_buffer = text.clone();
                            *edit_cursor = edit_buffer.len();
                            state_dirty = true;
                        }
                    }
                }
                CtrlReq::CustomizeEditConfirm => {
                    if let Mode::CustomizeMode { ref mut options, selected, ref mut editing, ref edit_buffer, .. } = app.mode {
                        if *editing {
                            let name = options[selected].0.clone();
                            let value = edit_buffer.clone();
                            options[selected].1 = value.clone();
                            *editing = false;
                            options::apply_set_option(&mut app, &name, &value, true);
                            state_dirty = true;
                        }
                    }
                }
                CtrlReq::CustomizeEditCancel => {
                    if let Mode::CustomizeMode { ref mut editing, ref mut edit_buffer, .. } = app.mode {
                        if *editing {
                            *editing = false;
                            *edit_buffer = String::new();
                            state_dirty = true;
                        }
                    }
                }
                CtrlReq::CustomizeResetDefault => {
                    if let Mode::CustomizeMode { ref mut options, selected, editing, .. } = app.mode {
                        if !editing {
                            if let Some(def) = option_catalog::default_for(&options[selected].0) {
                                let name = options[selected].0.clone();
                                let value = def.to_string();
                                options[selected].1 = value.clone();
                                options::apply_set_option(&mut app, &name, &value, true);
                                state_dirty = true;
                            }
                        }
                    }
                }
                CtrlReq::CustomizeFilter(text) => {
                    if let Mode::CustomizeMode { ref mut filter, ref mut selected, ref mut scroll_offset, ref options, .. } = app.mode {
                        *filter = text;
                        // Reset selection to first matching option
                        let first_match = options.iter().enumerate()
                            .find(|(_, (name, _, _))| filter.is_empty() || name.contains(filter.as_str()))
                            .map(|(i, _)| i);
                        if let Some(idx) = first_match {
                            *selected = idx;
                        }
                        *scroll_offset = 0;
                        state_dirty = true;
                    }
                }
                CtrlReq::RunCommand(cmd, resp) => {
                    let result = execute_command_string(&mut app, &cmd);
                    match result {
                        Ok(()) => { let _ = resp.send("OK".to_string()); }
                        Err(e) => { let _ = resp.send(format!("error: {}", e)); }
                    }
                }
            }
            // Log any active_idx change for debugging window-switch issues
            if app.active_idx != _prev_active_idx && crate::debug_log::server_log_enabled() {
                crate::debug_log::server_log("switch", &format!(
                    "active_idx changed {} -> {} by req={} hook={:?}",
                    _prev_active_idx, app.active_idx, _req_tag, hook_event));
            }
            // Fire any hooks registered for the event that just occurred
            if let Some(event) = hook_event {
                let _pre_hook_idx = app.active_idx;
                let cmds: Vec<String> = app.hooks.get(event).cloned().unwrap_or_default();
                for cmd in cmds {
                    let _ = execute_command_string(&mut app, &cmd);
                }
                // Emit control mode notifications for hook events
                if !app.control_clients.is_empty() {
                    let active_win = &app.windows[app.active_idx];
                    let win_id = active_win.id;
                    let active_pane_id = get_active_pane_id(&active_win.root, &active_win.active_path).unwrap_or(0);
                    match event {
                        "after-new-window" => {
                            control::emit_notification(&app, crate::types::ControlNotification::WindowAdd { window_id: win_id });
                        }
                        "after-kill-pane" | "window-closed" => {
                            control::emit_notification(&app, crate::types::ControlNotification::WindowClose { window_id: win_id });
                        }
                        "after-rename-window" => {
                            let name = active_win.name.clone();
                            control::emit_notification(&app, crate::types::ControlNotification::WindowRenamed { window_id: win_id, name });
                        }
                        "after-select-window" => {
                            control::emit_notification(&app, crate::types::ControlNotification::SessionWindowChanged {
                                session_id: app.session_id, window_id: win_id,
                            });
                        }
                        "after-select-pane" => {
                            control::emit_notification(&app, crate::types::ControlNotification::WindowPaneChanged {
                                window_id: win_id, pane_id: active_pane_id,
                            });
                        }
                        "after-rename-session" => {
                            let name = app.session_name.clone();
                            control::emit_notification(&app, crate::types::ControlNotification::SessionRenamed { name });
                        }
                        "client-attached" => {
                            let name = app.session_name.clone();
                            control::emit_notification(&app, crate::types::ControlNotification::SessionChanged {
                                session_id: app.session_id, name,
                            });
                        }
                        "client-detached" => {
                            control::emit_notification(&app, crate::types::ControlNotification::ClientDetached {
                                client: "client".to_string(),
                            });
                        }
                        "after-split-window" | "after-resize-pane" | "after-break-pane"
                        | "after-join-pane" | "after-rotate-window" | "after-swap-pane" => {
                            let area = app.last_window_area;
                            let layout = if let Some(w) = app.windows.iter().find(|w| w.id == win_id) {
                                control::window_layout_string(w, area)
                            } else {
                                format!("0000,{}x{},0,0", area.width, area.height)
                            };
                            control::emit_notification(&app, crate::types::ControlNotification::LayoutChange {
                                window_id: win_id,
                                layout,
                            });
                        }
                        "window-linked" => {
                            control::emit_notification(&app, crate::types::ControlNotification::WindowAdd { window_id: win_id });
                        }
                        "window-unlinked" => {
                            control::emit_notification(&app, crate::types::ControlNotification::WindowClose { window_id: win_id });
                        }
                        _ => {}
                    }
                }
                // Check if the hook itself changed active_idx
                if app.active_idx != _pre_hook_idx && crate::debug_log::server_log_enabled() {
                    crate::debug_log::server_log("switch", &format!(
                        "active_idx changed {} -> {} by HOOK event={}",
                        _pre_hook_idx, app.active_idx, event));
                }
            }
            // Restore temporary -t focus after non-temp command completes.
            // Use pane ID (not path) because kill-pane restructures the
            // tree and invalidates saved paths (#71).
            if !is_temp_focus {
                if let Some((restore_idx, restore_pane_id)) = temp_focus_restore.take() {
                    if restore_idx < app.windows.len() {
                        app.active_idx = restore_idx;
                        let win = &mut app.windows[restore_idx];
                        if let Some(path) = crate::tree::find_path_by_id(&win.root, restore_pane_id) {
                            win.active_path = path;
                        }
                        // If the pane was killed, keep whatever active_path
                        // kill_pane_at_path already set (MRU target).
                    }
                }
            }
            if mutates_state {
                state_dirty = true;
            }
        }
                // No trailing cleanup: temp_focus_restore persists across
                // batch boundaries so the actual command that follows in a
                // later batch can still benefit from the temp focus (and
                // will restore when it processes as a non-temp-focus req).
            }
        }
        // Drain async run-shell results (non-blocking).
        if let Some(rx) = app.run_shell_rx.as_ref() {
            while let Ok((title, text)) = rx.try_recv() {
                if !text.is_empty() {
                    let lines: Vec<&str> = text.lines().collect();
                    let width = lines.iter().map(|l| l.len()).max().unwrap_or(40).max(20) as u16 + 4;
                    let height = (lines.len() as u16 + 2).max(5);
                    app.mode = Mode::PopupMode {
                        command: title,
                        output: text,
                        process: None,
                        width: width.min(120),
                        height,
                        close_on_exit: false,
                        popup_pane: None,
                        scroll_offset: 0,
                    };
                    state_dirty = true;
                }
            }
        }
        // ── Server-push: proactively send frames to attached clients ──
        // Instead of waiting for clients to poll dump-state, serialize
        // and push whenever state changed (PTY output, new window, key
        // echo, etc.).  This gives event-driven rendering like wezterm:
        // frames arrive within 1-5ms of ConPTY output instead of waiting
        // for the next client poll cycle (up to 50ms).
        if (state_dirty || meta_dirty) && crate::types::has_frame_receivers() {
            // Check bell/activity state for the pushed frame
            let push_alert_hooks = helpers::check_window_activity(&mut app);
            for event in &push_alert_hooks {
                crate::commands::fire_hooks(&mut app, event);
            }
            // Rebuild metadata cache if structural changes happened.
            if meta_dirty {
                cached_windows_json = list_windows_json_with_tabs(&app)?;
                cached_tree_json = list_tree_json(&app)?;
                cached_prefix_str = format_key_binding(&app.prefix_key);
                cached_prefix2_str = app.prefix2_key.as_ref().map(|k| format_key_binding(k)).unwrap_or_default();
                cached_base_index = app.window_base_index;
                cached_pred_dim = app.prediction_dimming;
                cached_status_style = app.status_style.clone();
                cached_bindings_json = serialize_bindings_json(&app);
                meta_dirty = false;
            }
            let layout_json = dump_layout_json_fast(&mut app)?;
            combined_buf.clear();
            // #372: style options must be format-expanded too (see persistent
            // path above). wsf/wscf stay raw: per-window formats the client
            // expands with each window's own context.
            let ss_escaped = json_escape_string(&expand_format(&cached_status_style, &app));
            let sl_expanded = json_escape_string(&expand_format(&app.status_left, &app));
            let sr_expanded = json_escape_string(&expand_format(&app.status_right, &app));
            let pbs_escaped = json_escape_string(&expand_format(&app.pane_border_style, &app));
            let pabs_escaped = json_escape_string(&expand_format(&app.pane_active_border_style, &app));
            let pbhs_escaped = json_escape_string(&expand_format(&app.pane_border_hover_style, &app));
            let wsf_escaped = json_escape_string(&app.window_status_format);
            let wscf_escaped = json_escape_string(&app.window_status_current_format);
            let wss_escaped = json_escape_string(&expand_format(&app.window_status_separator, &app));
            let ws_style_escaped = json_escape_string(&expand_format(&app.window_status_style, &app));
            let wsc_style_escaped = json_escape_string(&expand_format(&app.window_status_current_style, &app));
            let mode_style_escaped = json_escape_string(&expand_format(&app.mode_style, &app));
            // #372: message-style was never sent to the client (it hard-coded
            // bg=yellow,fg=black). Send it, format-expanded.
            let message_style_escaped = json_escape_string(&expand_format(&app.message_style, &app));
            let status_position_escaped = json_escape_string(&app.status_position);
            let status_justify_escaped = json_escape_string(&app.status_justify);
            let status_format_json = {
                let mut sf = String::from("[");
                for (i, fmt_str) in app.status_format.iter().enumerate() {
                    if i > 0 { sf.push(','); }
                    sf.push('"');
                    sf.push_str(&json_escape_string(&expand_format(fmt_str, &app)));
                    sf.push('"');
                }
                sf.push(']');
                sf
            };
            let cursor_style_code = crate::rendering::configured_cursor_code();
            let _ = std::fmt::Write::write_fmt(&mut combined_buf, format_args!(
                "{{\"layout\":{},\"windows\":{},\"prefix\":\"{}\",\"prefix2\":\"{}\",\"tree\":{},\"base_index\":{},\"pane_base_index\":{},\"prediction_dimming\":{},\"status_style\":\"{}\",\"status_left\":\"{}\",\"status_right\":\"{}\",\"pane_border_style\":\"{}\",\"pane_active_border_style\":\"{}\",\"pane_border_hover_style\":\"{}\",\"wsf\":\"{}\",\"wscf\":\"{}\",\"wss\":\"{}\",\"ws_style\":\"{}\",\"wsc_style\":\"{}\",\"clock_mode\":{},\"bindings\":{},\"status_left_length\":{},\"status_right_length\":{},\"status_lines\":{},\"status_format\":{},\"mode_style\":\"{}\",\"message_style\":\"{}\",\"status_position\":\"{}\",\"status_justify\":\"{}\",\"cursor_style_code\":{},\"status_visible\":{},\"repeat_time\":{},\"zoomed\":{},\"pwsh_mouse_selection\":{},\"mouse_selection\":{},\"paste_detection\":{},\"choose_tree_preview\":{},\"scroll_enter_copy_mode\":{}}}",
                layout_json, cached_windows_json, cached_prefix_str, cached_prefix2_str, cached_tree_json, cached_base_index, app.pane_base_index, cached_pred_dim, ss_escaped, sl_expanded, sr_expanded, pbs_escaped, pabs_escaped, pbhs_escaped, wsf_escaped, wscf_escaped, wss_escaped, ws_style_escaped, wsc_style_escaped,
                matches!(app.mode, Mode::ClockMode), cached_bindings_json,
                app.status_left_length, app.status_right_length, app.status_lines, status_format_json,
                mode_style_escaped, message_style_escaped, status_position_escaped, status_justify_escaped,
                cursor_style_code, app.status_visible, app.repeat_time_ms,
                app.windows.get(app.active_idx).map_or(false, |w| w.zoom_saved.is_some()),
                app.pwsh_mouse_selection,
                app.mouse_selection,
                app.paste_detection,
                app.choose_tree_preview,
                app.scroll_enter_copy_mode,
            ));
            // Inject overlay state (popup, menu, confirm, display_panes)
            {
                // Inject clock_colour if set
                if let Some(cc) = app.user_options.get("clock-mode-colour") {
                    if combined_buf.ends_with('}') {
                        combined_buf.pop();
                        combined_buf.push_str(",\"clock_colour\":\"");
                        combined_buf.push_str(&json_escape_string(cc));
                        combined_buf.push_str("\"}");
                    }
                }
                // Inject pane-border-status and pane-border-format
                if let Some(pbs) = app.user_options.get("pane-border-status") {
                    if combined_buf.ends_with('}') {
                        combined_buf.pop();
                        combined_buf.push_str(",\"pane_border_status\":\"");
                        combined_buf.push_str(&json_escape_string(pbs));
                        combined_buf.push('"');
                        if let Some(pbf) = app.user_options.get("pane-border-format") {
                            combined_buf.push_str(",\"pane_border_format\":\"");
                            combined_buf.push_str(&json_escape_string(pbf));
                            combined_buf.push('"');
                        }
                        combined_buf.push('}');
                    }
                }
                // set-titles: when on, expand set-titles-string and ship
                // it so the client emits OSC 0 to its host terminal.
                if app.set_titles && combined_buf.ends_with('}') {
                    let fmt = if app.set_titles_string.is_empty() {
                        "#S:#I:#W"
                    } else {
                        app.set_titles_string.as_str()
                    };
                    let expanded = expand_format(fmt, &app);
                    combined_buf.pop();
                    combined_buf.push_str(",\"host_title\":\"");
                    combined_buf.push_str(&json_escape_string(&expanded));
                    combined_buf.push_str("\"}");
                }
                // Issue #269: forward OSC 9;4 progress from the active pane.
                if combined_buf.ends_with('}') {
                    if let Some((s, v)) = helpers::active_pane_progress(&app) {
                        combined_buf.pop();
                        combined_buf.push_str(",\"host_progress\":\"");
                        combined_buf.push_str(&format!("{};{}", s, v));
                        combined_buf.push_str("\"}");
                    }
                }
                let overlay_json = serialize_overlay_json(&app);
                if !overlay_json.is_empty() && combined_buf.ends_with('}') {
                    combined_buf.pop();
                    combined_buf.push_str(&overlay_json);
                    combined_buf.push('}');
                }
            }
            // Forward OSC 52 from pane child processes (e.g. Claude Code
            // `/copy`).  See sibling block in the dump-state response path
            // for full context.  Gated by `set-clipboard`.
            if app.set_clipboard != "off" && app.clipboard_osc52.is_none() {
                if let Some((_sel, b64)) = take_pane_clipboard(&app) {
                    if let Ok(b64_str) = std::str::from_utf8(&b64) {
                        if let Some(text) = crate::util::base64_decode(b64_str) {
                            app.clipboard_osc52 = Some(text);
                        }
                    }
                }
            }
            // Inject clipboard data if pending
            if let Some(clip_text) = app.clipboard_osc52.take() {
                let clip_b64 = base64_encode(&clip_text);
                if combined_buf.ends_with('}') {
                    combined_buf.pop();
                    combined_buf.push_str(",\"clipboard_osc52\":\"");
                    combined_buf.push_str(&clip_b64);
                    combined_buf.push_str("\"}");
                }
            }
            cached_dump_state.clear();
            cached_dump_state.push_str(&combined_buf);
            // Inject bell AFTER caching (one-shot: should not persist in cache)
            if app.bell_forward {
                app.bell_forward = false;
                if combined_buf.ends_with('}') {
                    combined_buf.pop();
                    combined_buf.push_str(",\"bell\":true}");
                }
            }
            cached_data_version = combined_data_version(&app);
            state_dirty = false;
            crate::types::push_frame(&combined_buf);
        }
        // ── Status-interval timer: fire hooks periodically ──
        if app.status_interval > 0 {
            let elapsed = app.last_status_interval_fire.elapsed().as_secs();
            if elapsed >= app.status_interval {
                app.last_status_interval_fire = std::time::Instant::now();
                let _pre_status_idx = app.active_idx;
                let cmds: Vec<String> = app.hooks.get("status-interval").cloned().unwrap_or_default();
                for cmd in cmds {
                    let bg_cmd = crate::commands::ensure_background(&cmd);
                    let _ = execute_command_string(&mut app, &bg_cmd);
                }
                if app.active_idx != _pre_status_idx && crate::debug_log::server_log_enabled() {
                    crate::debug_log::server_log("switch", &format!(
                        "active_idx changed {} -> {} by status-interval hook",
                        _pre_status_idx, app.active_idx));
                }
                // Mark state dirty so the next loop iteration pushes a fresh
                // frame with re-expanded strftime codes (%H:%M:%S, %r, etc.)
                // in status-left / status-right.  Without this, the status
                // bar clock never updates for persistent (TUI) clients.
                state_dirty = true;
            }
        }
        // ── Subscription check: expand format strings and emit %subscription-changed ──
        // Zero cost when no clients have subscriptions.
        if !app.control_clients.is_empty() {
            let now_sub = std::time::Instant::now();
            // Phase 1: collect (client_id, sub_name, format) pairs that need checking
            let mut to_check: Vec<(u64, String, String)> = Vec::new();
            for client in app.control_clients.values_mut() {
                if client.subscriptions.is_empty() {
                    continue;
                }
                let sub_names: Vec<String> = client.subscriptions.keys().cloned().collect();
                for name in sub_names {
                    // Rate limit: at most once per second per subscription
                    if let Some(last) = client.subscription_last_check.get(&name) {
                        if now_sub.duration_since(*last).as_secs() < 1 {
                            continue;
                        }
                    }
                    client.subscription_last_check.insert(name.clone(), now_sub);
                    let format = client.subscriptions[&name].1.clone();
                    to_check.push((client.client_id, name, format));
                }
            }
            // Phase 2: expand formats with immutable borrow of app
            let mut sub_results: Vec<(u64, String, String)> = Vec::new();
            for (cid, name, format) in &to_check {
                let expanded = crate::format::expand_format(format, &app);
                sub_results.push((*cid, name.clone(), expanded));
            }
            // Phase 3: compare and emit notifications
            let active_win = &app.windows[app.active_idx];
            let win_id = active_win.id;
            let pane_id = get_active_pane_id(&active_win.root, &active_win.active_path).unwrap_or(0);
            let session_id = app.session_id;
            let win_idx = app.active_idx;
            let mut sub_notifs: Vec<(u64, crate::types::ControlNotification)> = Vec::new();
            for (cid, name, expanded) in sub_results {
                if let Some(cc) = app.control_clients.get(&cid) {
                    let changed = match cc.subscription_values.get(&name) {
                        Some(prev) => prev != &expanded,
                        None => true,
                    };
                    if changed {
                        sub_notifs.push((cid, crate::types::ControlNotification::SubscriptionChanged {
                            name: name.clone(),
                            session_id,
                            window_id: win_id,
                            window_index: win_idx,
                            pane_id,
                            value: expanded.clone(),
                        }));
                    }
                }
            }
            // Phase 4: update cached values and send notifications
            for (cid, ref notif) in &sub_notifs {
                if let Some(cc) = app.control_clients.get_mut(cid) {
                    if let crate::types::ControlNotification::SubscriptionChanged { name, value, .. } = notif {
                        cc.subscription_values.insert(name.clone(), value.clone());
                    }
                }
            }
            for (cid, notif) in sub_notifs {
                if let Some(cc) = app.control_clients.get(&cid) {
                    let _ = cc.notification_tx.try_send(notif);
                }
            }
        }
        // ── PaneChooser timeout ──
        // Auto-close display-panes overlay after display-panes-time (default 1000ms).
        if let Mode::PaneChooser { opened_at } = &app.mode {
            if opened_at.elapsed() > Duration::from_millis(app.display_panes_time_ms) {
                app.mode = Mode::Passthrough;
                state_dirty = true;
            }
        }
        // ── Popup child exit detection ──
        // Check if popup PTY's child process has exited; if so, auto-close.
        if let Mode::PopupMode { ref mut popup_pane, close_on_exit, .. } = app.mode {
            let should_close = if let Some(ref mut pane) = popup_pane {
                matches!(pane.child.try_wait(), Ok(Some(_)))
            } else { false };
            if should_close && close_on_exit {
                app.mode = Mode::Passthrough;
                state_dirty = true;
            }
        }
        // Check if all windows/panes have exited (throttled to every 250ms)
        if last_reap.elapsed() >= Duration::from_millis(100) {
            last_reap = Instant::now();
            // Snapshot per-window state BEFORE reap so we can diff and emit
            // accurate %window-close / %layout-change / %window-pane-changed
            // notifications to control-mode clients (iTerm2 etc.).  Without
            // this, a pane that exits naturally (`exit` in pwsh, child dies)
            // is silently pruned server-side but iTerm2 keeps showing the
            // dead split forever.  Fixes the "exit doesn't kill the pane"
            // report on issue #261.
            let pre_reap: Vec<(usize, Option<usize>, usize)> = if !app.control_clients.is_empty() {
                app.windows.iter().map(|w| (
                    w.id,
                    tree::get_active_pane_id(&w.root, &w.active_path),
                    tree::count_panes(&w.root),
                )).collect()
            } else { Vec::new() };
            let pre_active_win_id: Option<usize> = if !app.control_clients.is_empty() && app.active_idx < app.windows.len() {
                Some(app.windows[app.active_idx].id)
            } else { None };

            let (all_empty, any_pruned, any_newly_dead) = tree::reap_children(&mut app)?;
            if any_pruned {
                // A pane was removed from the tree - resize remaining panes to fill the space
                resize_all_panes(&mut app);
                // Notify any attached control-mode clients about the diff.
                if !app.control_clients.is_empty() {
                    let area = app.last_window_area;
                    for (win_id, prev_active, prev_leaves) in &pre_reap {
                        if let Some(w) = app.windows.iter().find(|w| w.id == *win_id) {
                            let new_leaves = tree::count_panes(&w.root);
                            let new_active = tree::get_active_pane_id(&w.root, &w.active_path);
                            if new_leaves != *prev_leaves {
                                let layout = control::window_layout_string(w, area);
                                control::emit_notification(&app, crate::types::ControlNotification::LayoutChange {
                                    window_id: *win_id,
                                    layout,
                                });
                            }
                            if new_active != *prev_active {
                                if let Some(pid) = new_active {
                                    control::emit_notification(&app, crate::types::ControlNotification::WindowPaneChanged {
                                        window_id: *win_id,
                                        pane_id: pid,
                                    });
                                }
                            }
                        } else {
                            // Window completely removed (last pane died).
                            control::emit_notification(&app, crate::types::ControlNotification::WindowClose {
                                window_id: *win_id,
                            });
                        }
                    }
                    // If the session's active window changed (because the
                    // previous active window was removed), tell iTerm2.
                    if let Some(prev) = pre_active_win_id {
                        if app.active_idx < app.windows.len() {
                            let new_win_id = app.windows[app.active_idx].id;
                            if new_win_id != prev {
                                control::emit_notification(&app, crate::types::ControlNotification::SessionWindowChanged {
                                    session_id: app.session_id,
                                    window_id: new_win_id,
                                });
                            }
                        }
                    }
                }
            }
            if any_pruned || any_newly_dead {
                // A pane exited — fire hooks whether it was removed (remain-on-exit off)
                // or just marked dead (remain-on-exit on).  Fixes #227.
                state_dirty = true;
                meta_dirty = true;
                crate::commands::fire_hooks(&mut app, "pane-died");
                crate::commands::fire_hooks(&mut app, "pane-exited");
            }
            if app.exit_empty && all_empty {
                warm_debug(&format!("EXIT_EMPTY firing for session '{}' (all panes empty/dead) -> removing port file + process::exit", app.session_name));
                // Notify CC clients that the session is ending so iTerm2
                // closes the native window cleanly (same path as KillServer).
                if !app.control_clients.is_empty() {
                    control::emit_notification(
                        &app,
                        crate::types::ControlNotification::Exit { reason: None },
                    );
                    // Give notification threads time to flush %exit through
                    // the DCS stream before we tear down the process.
                    std::thread::sleep(std::time::Duration::from_millis(80));
                }
                let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
                let regpath = format!("{}\\.psmux\\{}.port", home, app.port_file_base());
                let keypath = format!("{}\\.psmux\\{}.key", home, app.port_file_base());
                let _ = std::fs::remove_file(&regpath);
                let _ = std::fs::remove_file(&keypath);
                crate::types::send_directive_to_all_clients("DETACH");
                std::thread::sleep(Duration::from_millis(50));
                crate::types::shutdown_persistent_streams();
                // Kill warm pane's child (process::exit skips Drop)
                if let Some(mut wp) = app.warm_pane.take() { wp.child.kill().ok(); }
                std::thread::sleep(std::time::Duration::from_millis(10));
                std::process::exit(0);
            }
        }
        // recv_timeout already handles the wait; no additional sleep needed.
    }
    #[allow(unreachable_code)]
    Ok(())
}

#[cfg(test)]
#[path = "../../tests-rs/test_server.rs"]
mod tests;

#[cfg(test)]
#[path = "../../tests-rs/test_issue169_manual_rename.rs"]
mod test_issue169;

#[cfg(test)]
#[path = "../../tests-rs/test_pane_title.rs"]
mod test_pane_title;

#[cfg(test)]
#[path = "../../tests-rs/test_issue202_switch_client.rs"]
mod test_issue202;

#[cfg(test)]
#[path = "../../tests-rs/test_new_session_env.rs"]
mod test_new_session_env;

#[cfg(test)]
#[path = "../../tests-rs/test_issue167_startup_log.rs"]
mod test_issue167_startup_log;

#[cfg(test)]
#[path = "../../tests-rs/test_issue370_startup_error_passthrough.rs"]
mod test_issue370_startup_error_passthrough;